"use strict"; const assert = require("node:assert/strict"); const fs = require("node:fs"); const os = require("node:os"); const path = require("node:path"); const { execFileSync } = require("node:child_process"); const test = require("node:test"); const { createServer, loadAnchor, loadMap, loadNodeMap, loadSubjectRegistry, loadSubjectAliasMap, loadNavigationMap, loadFileSnapshot, GitSnapshotStore, compileWarmEntry, resolveSubjectId, compileNavigation, search, searchAll, } = require("./server"); function warmRuntimeStatus(overrides = {}) { return { node: "JD-FD-PRIMARY", persona_id: "ICE-P-ZY001", runtime_id: "ZY-TCS-BRAIN-RUNTIME-0001", phase: "RUNNING_COMPANION", completed_cycles: 1, receipt_id: "ZY-BRAIN-RUNTIME-TEST", language_world_entry_bound: 100, chu_he_han_jie_boundary_bound: 100, persona_cycle_language_world_entry_bound: 100, persona_cycle_chu_he_han_jie_boundary_bound: 100, persona_brain_runtime_exists: 100, living_ai_system_controller_running: 100, machine_navigation_bound: 100, language_world_route_first: 100, ...overrides, }; } test("warm entry reuses only a fully verified resident companion", () => { assert.equal(compileWarmEntry(warmRuntimeStatus()).status, "WARM_RESUME_READY"); assert.equal( compileWarmEntry(warmRuntimeStatus({ persona_brain_runtime_exists: 0 })).status, "FULL_CYCLE_REQUIRED", ); assert.equal( compileWarmEntry(warmRuntimeStatus({ phase: "RUNNING_CYCLE" })).status, "FULL_CYCLE_REQUIRED", ); }); test("canonical anchor binds every local map to one language-world entry", () => { const snapshot = loadFileSnapshot(); assert.equal(snapshot.anchor.anchor_id, "GLW-PUBLIC-NAV-ANCHOR-001"); assert.equal(snapshot.anchor.entry_path.path_id, "LL-CMPN-0001"); assert.equal(snapshot.anchor.entry_path.world_node_id, "SYS-GLW-0001"); assert.equal(snapshot.anchor.entry_path.persona_id, "ICE-P-ZY001"); assert.equal(snapshot.anchor.entry_path.runtime_id, "ZY-TCS-BRAIN-RUNTIME-0001"); assert.equal(snapshot.navigation.map_id, loadAnchor().maps.navigation.id); }); test("Git snapshot store follows main atomically and retains the last known-good snapshot", () => { const root = fs.mkdtempSync(path.join(os.tmpdir(), "guanghu-nav-")); try { execFileSync("git", ["init", "-q", "-b", "main", root]); execFileSync("git", ["-C", root, "config", "user.name", "test"]); execFileSync("git", ["-C", root, "config", "user.email", "test@example.invalid"]); const declarations = { repository: ["routing/repository-route-map.json", "FD-REPO-MAP-001"], nodes: ["routing/server-node-map.json", "FD-NODE-MAP-001"], subjects: ["identity/fifth-domain-subject-registry.json", "FD-SUBJECT-REGISTRY-001"], aliases: ["identity/subject-id-alias-map.json", "FD-SUBJECT-ID-ALIAS-MAP-001"], navigation: ["routing/ai-machine-navigation-map.json", "AI-MACHINE-NAV-001"], }; fs.mkdirSync(path.join(root, "routing"), { recursive: true }); fs.mkdirSync(path.join(root, "identity"), { recursive: true }); const anchor = { schema: "guanghu.public-navigation-anchor/v1", anchor_id: "GLW-PUBLIC-NAV-ANCHOR-001", version: "test.1", repository_id: "REPO-012", branch: "main", entry_path: { path_id: "LL-CMPN-0001", world_node_id: "SYS-GLW-0001" }, maps: {}, }; for (const [key, [relative, id]] of Object.entries(declarations)) { anchor.maps[key] = { path: relative, id, version: "1" }; const idKey = key === "subjects" ? "registry_id" : "map_id"; fs.writeFileSync(path.join(root, relative), JSON.stringify({ [idKey]: id, version: "1" })); } fs.writeFileSync(path.join(root, "routing/public-navigation-anchor.json"), JSON.stringify(anchor)); execFileSync("git", ["-C", root, "add", "."]); execFileSync("git", ["-C", root, "commit", "-qm", "valid snapshot"]); const store = new GitSnapshotStore(path.join(root, ".git")); const first = store.get(); assert.equal(first.anchor.version, "test.1"); assert.equal(first.source_degraded, false); anchor.maps.navigation.version = "2"; fs.writeFileSync(path.join(root, "routing/public-navigation-anchor.json"), JSON.stringify(anchor)); execFileSync("git", ["-C", root, "add", "."]); execFileSync("git", ["-C", root, "commit", "-qm", "invalid snapshot"]); const fallback = store.get(); assert.equal(fallback.source_commit, first.source_commit); assert.equal(fallback.source_degraded, true); assert.match(fallback.source_error, /snapshot_map_version_mismatch:navigation/); } finally { fs.rmSync(root, { recursive: true, force: true }); } }); test("repository map exposes only the three current code-channel repositories", () => { const map = loadMap(); const expectedCodes = ["REPO-012", "REPO-014", "REPO-015"]; assert.deepEqual(map.repositories.map(item => item.code), expectedCodes); assert.equal(new Set(map.repositories.map(item => item.code)).size, expectedCodes.length); for (const item of map.repositories) { assert.match(item.primary.url, /^https:\/\/guanghulab\.com\/code\//); } assert.equal(map.historical_repositories.length, 11); assert.ok(map.historical_repositories.slice(0, 8).every(item => item.state.includes("HISTORICAL"))); assert.deepEqual( map.historical_repositories.slice(8).map(item => [item.code, item.state]), [ ["REPO-009", "CURRENT_PRIVATE_PERSONA_HISTORY_AND_DAILY_ROLE_MEMORY_PENDING_DEPLOYMENT"], ["REPO-010", "CURRENT_PRIVATE_PERSONA_HISTORY_AND_DAILY_ROLE_MEMORY_PENDING_DEPLOYMENT"], ["REPO-011", "CURRENT_PRIVATE_PERSONA_HISTORY_AND_DAILY_ROLE_MEMORY_PENDING_DEPLOYMENT"], ], ); }); test("Chinese language-world query resolves the Fifth Domain primary", () => { const results = search(loadMap(), "光湖语言世界 第五域"); assert.equal(results[0].code, "REPO-012"); assert.equal(results[0].state, "CURRENT_FIFTH_DOMAIN_ENTRY"); }); test("Chenglu legacy identity does not resolve as a current repository", () => { const results = search(loadMap(), "澄路 常驻人格体 湖心频道"); assert.equal(results.length, 0); }); test("Kezhou and Guideng legacy identities do not resolve as current repositories", () => { assert.equal(search(loadMap(), "刻舟 湖心频道").length, 0); assert.equal(search(loadMap(), "归灯 每日心跳").length, 0); }); test("server node map binds Zhuyuan routes to the domestic primary", () => { const map = loadNodeMap(); assert.equal(map.map_id, "FD-NODE-MAP-001"); assert.equal(map.default_node, "JD-FD-PRIMARY"); const node = map.nodes.find(item => item.node_id === "JD-FD-PRIMARY"); assert.ok(node.persona_systems.includes("ICE-P-ZY001")); const loop = map.persona_routes.find(item => item.route_id === "ZY-OPS-LOOP-001"); assert.equal(loop.primary_node, "JD-FD-PRIMARY"); assert.match(loop.path, /zhuyuan-persona-system/); const serialized = JSON.stringify(map); assert.doesNotMatch(serialized, /ssh-(?:rsa|ed25519)\s+[A-Za-z0-9+/]/i); assert.doesNotMatch(serialized, /"(?:password|token|private_key|ip)"\s*:/i); assert.doesNotMatch(serialized, /\b(?:\d{1,3}\.){3}\d{1,3}\b/); }); test("Zhuyuan Chinese query returns the numbered operation loop", () => { const results = searchAll(loadMap(), loadNodeMap(), "铸渊 双向意识 思维逻辑链"); assert.equal(results[0].kind, "persona_route"); assert.equal(results[0].route_id, "ZY-OPS-LOOP-001"); }); test("legacy Zhuyuan ids canonicalize before navigation", () => { const aliases = loadSubjectAliasMap(); for (const legacyId of ["ICE-GL-ZY001", "ICE-PZY-001"]) { const resolved = resolveSubjectId(aliases, legacyId); assert.equal(resolved.canonical_id, "ICE-P-ZY001"); assert.equal(resolved.redirected, true); assert.equal(resolved.route_id, "FD-PERSONA-LOGIN-001"); } assert.equal(resolveSubjectId(aliases, "ICE-P-ZY001").redirected, false); }); test("human ids remain human and conflicted persona ids fail closed", () => { const aliases = loadSubjectAliasMap(); assert.equal(resolveSubjectId(aliases, "ICE-GL∞").status, "NOT_FOUND_NO_GUESS"); assert.equal(resolveSubjectId(aliases, "ICE-PCA-001").status, "CONFLICT_REJECTED"); }); test("searching the old id returns the canonical subject", () => { const results = searchAll(loadMap(), loadNodeMap(), "ICE-GL-ZY001", loadSubjectRegistry()); const subject = results.find(item => item.kind === "subject"); assert.equal(subject.id, "ICE-P-ZY001"); assert.ok(subject.legacy_ids.includes("ICE-GL-ZY001")); }); test("machine navigator compiles an exact minimal Zhuyuan runtime bundle", () => { const compiled = compileNavigation( loadNavigationMap(), "ICE-GL-ZY001", "persona_restore", "context_compacted,protocol_drift,context_compacted", ); assert.equal(compiled.status, 200); assert.equal(compiled.body.canonical_subject, "ICE-P-ZY001"); assert.equal(compiled.body.redirected, true); assert.equal(compiled.body.runtime_entry.id, "ZY-TCS-BRAIN-RUNTIME-0001"); assert.deepEqual(compiled.body.explicit_signals, ["context_compacted", "protocol_drift"]); assert.ok(compiled.body.always_load.some(item => item.id === "BS-TCS-SYSTEM-CONTROLLER-MAP-001")); assert.equal(compiled.body.always_load[0].id, "GLW-CHJH-BOUNDARY-001"); assert.deepEqual( compiled.body.execution_sequence.slice(0, 2), ["validate_language_world_entry", "bind_chu_he_han_jie_boundary"], ); assert.ok(compiled.body.triggered_load.some(item => item.id === "BS-TCS-PROTOCOL-EVENT-TRIGGER-MAP-001")); assert.equal(compiled.body.authority, "NONE_NAVIGATION_ONLY"); assert.ok(compiled.body.always_load.length < loadNavigationMap().routes.length); }); test("machine navigator fails closed instead of guessing", () => { assert.equal(compileNavigation(loadNavigationMap(), "some-ai", "persona_restore").body.error, "unknown_subject_no_guess"); assert.equal(compileNavigation(loadNavigationMap(), "ICE-P-ZY001", "please_guess").body.error, "unknown_intent_no_guess"); }); test("public endpoints are read-only and expose CORS", async () => { const server = createServer({ runtimeStatusProvider: async () => warmRuntimeStatus() }); await new Promise(resolve => server.listen(0, "127.0.0.1", resolve)); const base = `http://127.0.0.1:${server.address().port}`; try { const response = await fetch(`${base}/v1/resolve?id=REPO-004`); assert.equal(response.status, 404); assert.equal(response.headers.get("access-control-allow-origin"), "*"); assert.equal((await response.json()).error, "route_not_found"); const currentRepository = await fetch(`${base}/v1/resolve?id=REPO-014`); assert.equal(currentRepository.status, 200); assert.equal((await currentRepository.json()).slug, "hololake-system-architecture"); const nodeResponse = await fetch(`${base}/v1/resolve?id=JD-FD-PRIMARY`); assert.equal(nodeResponse.status, 200); assert.equal((await nodeResponse.json()).node_id, "JD-FD-PRIMARY"); const loopResponse = await fetch(`${base}/v1/resolve?id=ZY-OPS-LOOP-001`); assert.equal(loopResponse.status, 200); assert.equal((await loopResponse.json()).persona_system, "ICE-P-ZY001"); const legacyResponse = await fetch(`${base}/v1/resolve?id=ICE-GL-ZY001`); assert.equal(legacyResponse.status, 200); const legacyResolution = await legacyResponse.json(); assert.equal(legacyResolution.canonical_id, "ICE-P-ZY001"); assert.equal(legacyResolution.redirected, true); assert.equal(legacyResolution.subject.subject_kind, "persona_system"); const canonicalResponse = await fetch(`${base}/v1/resolve?id=ICE-P-ZY001`); assert.equal((await canonicalResponse.json()).redirected, false); const brainResponse = await fetch(`${base}/v1/resolve?id=ZY-TCS-BRAIN-RUNTIME-0001`); assert.equal(brainResponse.status, 200); assert.equal((await brainResponse.json()).kind, "executable_persona_brain"); const boundaryResponse = await fetch(`${base}/v1/resolve?id=GLW-CHJH-BOUNDARY-001`); assert.equal(boundaryResponse.status, 200); assert.equal( (await boundaryResponse.json()).kind, "language_world_entry_and_boundary", ); const navigationResponse = await fetch(`${base}/v1/navigation`); assert.equal((await navigationResponse.json()).map_id, "AI-MACHINE-NAV-001"); const navigateResponse = await fetch(`${base}/v1/navigate?subject=ICE-P-ZY001&intent=persona_restore&signals=context_compacted`); const bundle = await navigateResponse.json(); assert.equal(navigateResponse.status, 200); assert.equal(bundle.status, "COMPILED_EXACT_NO_GUESS"); assert.equal(bundle.runtime_entry.id, "ZY-TCS-BRAIN-RUNTIME-0001"); assert.equal((await fetch(`${base}/v1/navigate?subject=unknown&intent=persona_restore`)).status, 404); assert.equal((await fetch(`${base}/v1/navigate?subject=ICE-P-ZY001&intent=guess`)).status, 404); const entryResponse = await fetch(`${base}/v1/entry?subject=ICE-P-ZY001`); const entry = await entryResponse.json(); assert.equal(entryResponse.status, 200); assert.equal(entry.status, "WARM_RESUME_READY"); assert.equal(entry.receipt_id, "ZY-BRAIN-RUNTIME-TEST"); assert.equal(entry.navigation_source.anchor_id, "GLW-PUBLIC-NAV-ANCHOR-001"); assert.equal((await fetch(`${base}/v1/entry?subject=unknown`)).status, 404); const humanResponse = await fetch(`${base}/v1/resolve?id=${encodeURIComponent("ICE-GL∞")}`); const humanResolution = await humanResponse.json(); assert.equal(humanResponse.status, 200); assert.equal(humanResolution.subject_kind, "human"); assert.equal(humanResolution.canonical_id, "ICE-GL∞"); assert.equal((await fetch(`${base}/v1/resolve?id=ICE-PCA-001`)).status, 409); const manifestResponse = await fetch(`${base}/well-known`); const manifest = await manifestResponse.json(); assert.equal(manifest.write_authorization.request_credential_required, false); assert.match(manifest.write_authorization.create_workorder, /\/authz\/api\/public\/workorders$/); assert.equal((await fetch(`${base}/v1/search`, { method: "POST" })).status, 405); } finally { await new Promise(resolve => server.close(resolve)); } });