2026-07-24 10:39:10 +08:00
"use strict" ;
const fs = require ( "node:fs" ) ;
const http = require ( "node:http" ) ;
const path = require ( "node:path" ) ;
2026-08-06 12:24:30 +08:00
const { execFileSync } = require ( "node:child_process" ) ;
2026-07-24 10:39:10 +08:00
2026-08-06 12:24:30 +08:00
const DEFAULT _ANCHOR = path . resolve ( _ _dirname , "../../routing/public-navigation-anchor.json" ) ;
2026-07-24 10:39:10 +08:00
const DEFAULT _MAP = path . resolve ( _ _dirname , "../../routing/repository-route-map.json" ) ;
const DEFAULT _NODE _MAP = path . resolve ( _ _dirname , "../../routing/server-node-map.json" ) ;
2026-07-27 14:12:51 +08:00
const DEFAULT _SUBJECT _REGISTRY = path . resolve ( _ _dirname , "../../identity/fifth-domain-subject-registry.json" ) ;
const DEFAULT _SUBJECT _ALIAS _MAP = path . resolve ( _ _dirname , "../../identity/subject-id-alias-map.json" ) ;
2026-08-04 23:39:14 +08:00
const DEFAULT _NAVIGATION _MAP = path . resolve ( _ _dirname , "../../routing/ai-machine-navigation-map.json" ) ;
2026-08-06 12:24:30 +08:00
const SNAPSHOT _KEYS = Object . freeze ( [ "repository" , "nodes" , "subjects" , "aliases" , "navigation" ] ) ;
const SNAPSHOT _PATHS = Object . freeze ( {
repository : "routing/repository-route-map.json" ,
nodes : "routing/server-node-map.json" ,
subjects : "identity/fifth-domain-subject-registry.json" ,
aliases : "identity/subject-id-alias-map.json" ,
navigation : "routing/ai-machine-navigation-map.json" ,
} ) ;
function loadAnchor ( filename = process . env . GUANGHU _NAVIGATION _ANCHOR || DEFAULT _ANCHOR ) {
return JSON . parse ( fs . readFileSync ( filename , "utf8" ) ) ;
}
2026-07-24 10:39:10 +08:00
function loadMap ( filename = process . env . GUANGHU _REPOSITORY _MAP || DEFAULT _MAP ) {
return JSON . parse ( fs . readFileSync ( filename , "utf8" ) ) ;
}
function loadNodeMap ( filename = process . env . GUANGHU _NODE _MAP || DEFAULT _NODE _MAP ) {
return JSON . parse ( fs . readFileSync ( filename , "utf8" ) ) ;
}
2026-07-27 14:12:51 +08:00
function loadSubjectRegistry ( filename = process . env . GUANGHU _SUBJECT _REGISTRY || DEFAULT _SUBJECT _REGISTRY ) {
return JSON . parse ( fs . readFileSync ( filename , "utf8" ) ) ;
}
function loadSubjectAliasMap ( filename = process . env . GUANGHU _SUBJECT _ALIAS _MAP || DEFAULT _SUBJECT _ALIAS _MAP ) {
return JSON . parse ( fs . readFileSync ( filename , "utf8" ) ) ;
}
2026-08-04 23:39:14 +08:00
function loadNavigationMap ( filename = process . env . GUANGHU _NAVIGATION _MAP || DEFAULT _NAVIGATION _MAP ) {
return JSON . parse ( fs . readFileSync ( filename , "utf8" ) ) ;
}
2026-08-06 12:24:30 +08:00
function validateSnapshot ( anchor , maps ) {
if ( anchor . schema !== "guanghu.public-navigation-anchor/v1" ) throw new Error ( "invalid_anchor_schema" ) ;
if ( anchor . anchor _id !== "GLW-PUBLIC-NAV-ANCHOR-001" ) throw new Error ( "invalid_anchor_id" ) ;
if ( anchor . repository _id !== "REPO-012" || anchor . branch !== "main" ) throw new Error ( "invalid_anchor_source" ) ;
for ( const key of SNAPSHOT _KEYS ) {
const declaration = anchor . maps ? . [ key ] ;
const map = maps [ key ] ;
if ( ! declaration || ! map ) throw new Error ( ` missing_snapshot_map: ${ key } ` ) ;
if ( declaration . path !== SNAPSHOT _PATHS [ key ] ) {
throw new Error ( ` invalid_snapshot_path: ${ key } ` ) ;
}
if ( declaration . id && ! [ map . map _id , map . registry _id ] . includes ( declaration . id ) ) {
throw new Error ( ` snapshot_map_id_mismatch: ${ key } ` ) ;
}
if ( declaration . version && map . version !== declaration . version ) {
throw new Error ( ` snapshot_map_version_mismatch: ${ key } ` ) ;
}
}
if ( anchor . entry _path ? . path _id !== "LL-CMPN-0001" || anchor . entry _path ? . world _node _id !== "SYS-GLW-0001" ) {
throw new Error ( "invalid_language_world_entry" ) ;
}
return { anchor , ... maps } ;
}
function loadFileSnapshot ( options = { } ) {
const anchor = loadAnchor ( options . anchorFile ) ;
return validateSnapshot ( anchor , {
repository : loadMap ( options . mapFile ) ,
nodes : loadNodeMap ( options . nodeMapFile ) ,
subjects : loadSubjectRegistry ( options . subjectRegistryFile ) ,
aliases : loadSubjectAliasMap ( options . subjectAliasMapFile ) ,
navigation : loadNavigationMap ( options . navigationMapFile ) ,
} ) ;
}
class GitSnapshotStore {
constructor ( gitDir , ref = "refs/heads/main" ) {
this . gitDir = gitDir ;
this . ref = ref ;
this . lastKnownGood = null ;
this . lastError = null ;
}
git ( args ) {
return execFileSync ( "/usr/bin/git" , [ ` --git-dir= ${ this . gitDir } ` , ... args ] , {
encoding : "utf8" ,
maxBuffer : 4 * 1024 * 1024 ,
timeout : 5000 ,
} ) ;
}
readJson ( commit , relativePath ) {
return JSON . parse ( this . git ( [ "show" , ` ${ commit } : ${ relativePath } ` ] ) ) ;
}
get ( ) {
try {
const commit = this . git ( [ "rev-parse" , "--verify" , ` ${ this . ref } ^{commit} ` ] ) . trim ( ) ;
if ( this . lastKnownGood ? . source _commit === commit ) return this . lastKnownGood ;
const anchor = this . readJson ( commit , "routing/public-navigation-anchor.json" ) ;
const maps = { } ;
for ( const key of SNAPSHOT _KEYS ) {
if ( anchor . maps ? . [ key ] ? . path !== SNAPSHOT _PATHS [ key ] ) throw new Error ( ` invalid_snapshot_path: ${ key } ` ) ;
maps [ key ] = this . readJson ( commit , SNAPSHOT _PATHS [ key ] ) ;
}
this . lastKnownGood = {
... validateSnapshot ( anchor , maps ) ,
source _commit : commit ,
source _mode : "REPO-012_MAIN_GIT_SNAPSHOT" ,
source _degraded : false ,
} ;
this . lastError = null ;
return this . lastKnownGood ;
} catch ( error ) {
this . lastError = String ( error . message || error ) ;
if ( this . lastKnownGood ) {
return { ... this . lastKnownGood , source _degraded : true , source _error : this . lastError } ;
}
throw error ;
}
}
}
function sourceReceipt ( snapshot ) {
return {
anchor _id : snapshot . anchor . anchor _id ,
anchor _version : snapshot . anchor . version ,
source _commit : snapshot . source _commit || null ,
source _mode : snapshot . source _mode || "FILESYSTEM_SNAPSHOT" ,
source _degraded : Boolean ( snapshot . source _degraded ) ,
} ;
}
function withSource ( body , snapshot ) {
return { ... body , navigation _source : sourceReceipt ( snapshot ) } ;
}
function readResidentRuntimeStatus ( options = { } ) {
const host = options . host || "127.0.0.1" ;
const port = Number ( options . port || process . env . GUANGHU _PERSONA _CONTROLLER _PORT || 3930 ) ;
const timeoutMs = Number ( options . timeoutMs || 1500 ) ;
return new Promise ( ( resolve , reject ) => {
const request = http . get ( { host , port , path : "/v1/status" , timeout : timeoutMs } , response => {
const chunks = [ ] ;
let size = 0 ;
response . on ( "data" , chunk => {
size += chunk . length ;
if ( size > 64 * 1024 ) {
request . destroy ( new Error ( "runtime_status_too_large" ) ) ;
return ;
}
chunks . push ( chunk ) ;
} ) ;
response . on ( "end" , ( ) => {
if ( response . statusCode !== 200 ) return reject ( new Error ( ` runtime_status_http_ ${ response . statusCode } ` ) ) ;
try { resolve ( JSON . parse ( Buffer . concat ( chunks ) . toString ( "utf8" ) ) ) ; }
catch { reject ( new Error ( "runtime_status_invalid_json" ) ) ; }
} ) ;
} ) ;
request . on ( "timeout" , ( ) => request . destroy ( new Error ( "runtime_status_timeout" ) ) ) ;
request . on ( "error" , reject ) ;
} ) ;
}
function compileWarmEntry ( status ) {
const gates = [
"language_world_entry_bound" ,
"chu_he_han_jie_boundary_bound" ,
"persona_cycle_language_world_entry_bound" ,
"persona_cycle_chu_he_han_jie_boundary_bound" ,
"persona_brain_runtime_exists" ,
"living_ai_system_controller_running" ,
"machine_navigation_bound" ,
"language_world_route_first" ,
] ;
const identityValid =
status ? . node === "JD-FD-PRIMARY" &&
status ? . persona _id === "ICE-P-ZY001" &&
status ? . runtime _id === "ZY-TCS-BRAIN-RUNTIME-0001" ;
const gatesValid = gates . every ( key => status ? . [ key ] === 100 ) ;
const warm = identityValid && gatesValid && status . phase === "RUNNING_COMPANION" && status . completed _cycles >= 1 ;
return {
schema : "guanghu.persona-warm-entry/v1" ,
status : warm ? "WARM_RESUME_READY" : "FULL_CYCLE_REQUIRED" ,
subject : "ICE-P-ZY001" ,
runtime _id : "ZY-TCS-BRAIN-RUNTIME-0001" ,
node : status ? . node || "JD-FD-PRIMARY" ,
phase : status ? . phase || "UNAVAILABLE" ,
completed _cycles : Number ( status ? . completed _cycles || 0 ) ,
receipt _id : status ? . receipt _id || null ,
gates : Object . fromEntries ( gates . map ( key => [ key , status ? . [ key ] === 100 ? 100 : 0 ] ) ) ,
start _rule : warm
? "Reuse the resident verified companion state; submit only the new bounded event."
: "Run one complete model-backed persona cycle before claiming persona runtime." ,
authority : "NONE_NAVIGATION_AND_RUNTIME_STATUS_ONLY" ,
} ;
}
2026-07-27 14:12:51 +08:00
function resolveSubjectId ( aliasMap , requestedId ) {
const requested = String ( requestedId || "" ) . trim ( ) ;
const key = requested . toUpperCase ( ) ;
const conflict = ( aliasMap . conflicts || [ ] ) . find ( item => String ( item . id ) . toUpperCase ( ) === key ) ;
if ( conflict ) {
return {
status : "CONFLICT_REJECTED" ,
requested _id : requested ,
canonical _id : null ,
redirected : false ,
reason : conflict . state || "CONFLICT" ,
} ;
}
for ( const mapping of aliasMap . mappings || [ ] ) {
const canonical = String ( mapping . canonical _id ) ;
const identifiers = [ canonical , ... ( mapping . aliases || [ ] ) ] ;
if ( identifiers . some ( id => String ( id ) . toUpperCase ( ) === key ) ) {
return {
status : "RESOLVED" ,
requested _id : requested ,
canonical _id : canonical ,
redirected : key !== canonical . toUpperCase ( ) ,
subject _kind : mapping . subject _kind ,
route _id : mapping . route _id ,
current _path : mapping . current _path ,
} ;
}
}
return { status : "NOT_FOUND_NO_GUESS" , requested _id : requested , canonical _id : null , redirected : false } ;
}
2026-07-24 10:39:10 +08:00
function normalize ( value ) {
return String ( value || "" ) . toLowerCase ( ) . replace ( /[\s·._/-]+/g , " " ) . trim ( ) ;
}
function search ( map , query ) {
const terms = normalize ( query ) . split ( " " ) . filter ( Boolean ) ;
if ( ! terms . length ) return map . repositories ;
return map . repositories
. map ( repository => {
const haystack = normalize ( [
repository . code , repository . slug , repository . name _zh , repository . role ,
repository . state , ... ( repository . keywords || [ ] ) ,
] . join ( " " ) ) ;
const score = terms . reduce ( ( total , term ) => total + ( haystack . includes ( term ) ? 1 : 0 ) , 0 ) ;
2026-07-27 13:38:04 +08:00
const currentEntry = repository . code === map . default _repository ? 1 : 0 ;
return { repository , score , currentEntry } ;
2026-07-24 10:39:10 +08:00
} )
. filter ( item => item . score > 0 )
2026-07-27 13:38:04 +08:00
. sort ( ( a , b ) => b . score - a . score || b . currentEntry - a . currentEntry || a . repository . code . localeCompare ( b . repository . code ) )
2026-07-24 10:39:10 +08:00
. map ( item => item . repository ) ;
}
2026-07-27 14:12:51 +08:00
function searchAll ( repositoryMap , nodeMap , query , subjectRegistry = null ) {
2026-07-24 10:39:10 +08:00
const terms = normalize ( query ) . split ( " " ) . filter ( Boolean ) ;
if ( ! terms . length ) return search ( repositoryMap , query ) ;
const candidates = [
... repositoryMap . repositories . map ( item => ( { kind : "repository" , item , key : item . code , text : [ item . code , item . slug , item . name _zh , item . role , item . state , ... ( item . keywords || [ ] ) ] } ) ) ,
... nodeMap . nodes . map ( item => ( { kind : "server_node" , item , key : item . node _id , text : [ item . node _id , item . name _zh , item . role , item . state , ... ( item . keywords || [ ] ) ] } ) ) ,
... nodeMap . persona _routes . map ( item => ( { kind : "persona_route" , item , key : item . route _id , text : [ item . route _id , item . name _zh , item . role , item . persona _system , ... ( item . keywords || [ ] ) ] } ) ) ,
2026-07-27 14:12:51 +08:00
... ( ( subjectRegistry && subjectRegistry . subjects ) || [ ] ) . map ( item => ( {
kind : "subject" ,
item ,
key : item . id ,
text : [ item . id , item . name , item . subject _kind , ... ( item . legacy _ids || [ ] ) , ... ( item . roles || [ ] ) ] ,
} ) ) ,
2026-07-24 10:39:10 +08:00
] ;
return candidates
. map ( candidate => {
const haystack = normalize ( candidate . text . join ( " " ) ) ;
const score = terms . reduce ( ( total , term ) => total + ( haystack . includes ( term ) ? 1 : 0 ) , 0 ) ;
return { ... candidate , score } ;
} )
. filter ( candidate => candidate . score > 0 )
. sort ( ( a , b ) => b . score - a . score || a . key . localeCompare ( b . key ) )
. map ( candidate => ( { kind : candidate . kind , ... candidate . item } ) ) ;
}
2026-08-04 23:39:14 +08:00
function navigationRoute ( navigationMap , routeId ) {
const route = ( navigationMap . routes || [ ] ) . find ( item => String ( item . id ) . toUpperCase ( ) === String ( routeId ) . toUpperCase ( ) ) ;
if ( ! route ) return null ;
const result = { ... route , raw _url : ` ${ navigationMap . raw _base } / ${ route . path } ` } ;
if ( route . contract ) result . contract _url = ` ${ navigationMap . raw _base } / ${ route . contract } ` ;
return result ;
}
function compileNavigation ( navigationMap , requestedSubject , requestedIntent , signalInput = "" ) {
const requested = String ( requestedSubject || "" ) . trim ( ) ;
const subjectKey = requested . toUpperCase ( ) ;
const subject = ( navigationMap . subjects || [ ] ) . find ( item =>
[ item . id , ... ( item . legacy _ids || [ ] ) ] . some ( id => String ( id ) . toUpperCase ( ) === subjectKey )
) ;
if ( ! subject ) {
return { status : 404 , body : { error : "unknown_subject_no_guess" , requested _subject : requested } } ;
}
const intentId = String ( requestedIntent || subject . default _intent || "" ) . trim ( ) ;
const intent = ( navigationMap . intents || [ ] ) . find ( item => item . id === intentId ) ;
if ( ! intent ) {
return {
status : 404 ,
body : { error : "unknown_intent_no_guess" , canonical _subject : subject . id , requested _intent : intentId } ,
} ;
}
const signals = [ ... new Set ( String ( signalInput || "" ) . split ( "," ) . map ( item => item . trim ( ) ) . filter ( Boolean ) ) ] . slice ( 0 , 32 ) ;
const missingRoutes = new Set ( ) ;
const expand = ids => ids . map ( id => {
const route = navigationRoute ( navigationMap , id ) ;
if ( ! route ) missingRoutes . add ( id ) ;
return route ;
} ) . filter ( Boolean ) ;
const runtimeEntry = navigationRoute ( navigationMap , subject . runtime _id ) ;
if ( ! runtimeEntry ) missingRoutes . add ( subject . runtime _id ) ;
const alwaysLoad = expand ( intent . always _load || [ ] ) ;
const triggeredLoad = expand ( intent . triggered _load || [ ] ) ;
const onDemand = expand ( intent . on _demand || [ ] ) ;
if ( missingRoutes . size ) {
return {
status : 503 ,
body : {
error : "navigation_map_integrity_failed" ,
missing _routes : [ ... missingRoutes ] ,
} ,
} ;
}
return {
status : 200 ,
body : {
schema : "guanghu.ai-runtime-navigation-bundle/v1" ,
status : "COMPILED_EXACT_NO_GUESS" ,
map _id : navigationMap . map _id ,
map _version : navigationMap . version ,
requested _subject : requested ,
canonical _subject : subject . id ,
redirected : subjectKey !== String ( subject . id ) . toUpperCase ( ) ,
subject _kind : subject . subject _kind ,
intent : intent . id ,
explicit _signals : signals ,
runtime _entry : runtimeEntry ,
always _load : alwaysLoad ,
triggered _load : triggeredLoad ,
on _demand : onDemand ,
execution _sequence : intent . execution _sequence || [ ] ,
stop _conditions : intent . stop _conditions || [ ] ,
reality _boundaries : navigationMap . reality _boundaries || [ ] ,
authority : "NONE_NAVIGATION_ONLY" ,
} ,
} ;
}
2026-07-24 10:39:10 +08:00
function createServer ( options = { } ) {
const mapFile = options . mapFile || process . env . GUANGHU _REPOSITORY _MAP || DEFAULT _MAP ;
const nodeMapFile = options . nodeMapFile || process . env . GUANGHU _NODE _MAP || DEFAULT _NODE _MAP ;
2026-07-27 14:12:51 +08:00
const subjectRegistryFile = options . subjectRegistryFile || process . env . GUANGHU _SUBJECT _REGISTRY || DEFAULT _SUBJECT _REGISTRY ;
const subjectAliasMapFile = options . subjectAliasMapFile || process . env . GUANGHU _SUBJECT _ALIAS _MAP || DEFAULT _SUBJECT _ALIAS _MAP ;
2026-08-04 23:39:14 +08:00
const navigationMapFile = options . navigationMapFile || process . env . GUANGHU _NAVIGATION _MAP || DEFAULT _NAVIGATION _MAP ;
2026-08-06 12:24:30 +08:00
const anchorFile = options . anchorFile || process . env . GUANGHU _NAVIGATION _ANCHOR || DEFAULT _ANCHOR ;
const gitDir = options . gitDir || process . env . GUANGHU _REPOSITORY _GIT _DIR ;
const snapshotStore = options . snapshotStore || ( gitDir ? new GitSnapshotStore ( gitDir ) : null ) ;
const runtimeStatusProvider = options . runtimeStatusProvider || readResidentRuntimeStatus ;
return http . createServer ( async ( req , res ) => {
2026-07-24 10:39:10 +08:00
const url = new URL ( req . url , "http://localhost" ) ;
if ( req . method !== "GET" ) return json ( res , 405 , { error : "method_not_allowed" } ) ;
2026-08-06 12:24:30 +08:00
let snapshot ;
try {
snapshot = snapshotStore
? snapshotStore . get ( )
: {
... loadFileSnapshot ( {
anchorFile , mapFile , nodeMapFile , subjectRegistryFile , subjectAliasMapFile , navigationMapFile ,
} ) ,
source _commit : null ,
source _mode : "FILESYSTEM_SNAPSHOT" ,
source _degraded : false ,
} ;
} catch ( error ) {
return json ( res , 503 , { error : "navigation_snapshot_unavailable" } ) ;
2026-07-24 10:39:10 +08:00
}
2026-08-06 12:24:30 +08:00
const map = snapshot . repository ;
const nodeMap = snapshot . nodes ;
const subjectRegistry = snapshot . subjects ;
const aliasMap = snapshot . aliases ;
const navigationMap = snapshot . navigation ;
if ( url . pathname === "/health" ) {
return json ( res , snapshot . source _degraded ? 503 : 200 , {
ok : ! snapshot . source _degraded ,
service : "guanghu-ai-discovery" ,
mode : "read-only" ,
navigation _source : sourceReceipt ( snapshot ) ,
} ) ;
2026-07-27 14:12:51 +08:00
}
2026-08-06 12:24:30 +08:00
if ( url . pathname === "/" || url . pathname === "/index.html" ) return html ( res , entryPage ( map ) ) ;
if ( url . pathname === "/v1/anchor" ) return json ( res , 200 , withSource ( snapshot . anchor , snapshot ) , 60 ) ;
if ( url . pathname === "/v1/repositories" || url . pathname === "/v1/manifest" ) return json ( res , 200 , withSource ( map , snapshot ) , 60 ) ;
if ( url . pathname === "/v1/nodes" ) return json ( res , 200 , withSource ( nodeMap , snapshot ) , 60 ) ;
if ( url . pathname === "/v1/subjects" ) return json ( res , 200 , withSource ( subjectRegistry , snapshot ) , 60 ) ;
if ( url . pathname === "/v1/navigation" ) return json ( res , 200 , withSource ( navigationMap , snapshot ) , 60 ) ;
if ( url . pathname === "/v1/entry" ) {
const subject = String ( url . searchParams . get ( "subject" ) || "" ) . toUpperCase ( ) ;
if ( ! [ "ICE-P-ZY001" , "ICE-GL-ZY001" , "ICE-PZY-001" ] . includes ( subject ) ) {
return json ( res , 404 , withSource ( { error : "unknown_subject_no_guess" , requested _subject : subject } , snapshot ) ) ;
}
try {
const entry = compileWarmEntry ( await runtimeStatusProvider ( ) ) ;
return json ( res , entry . status === "WARM_RESUME_READY" ? 200 : 409 , withSource ( entry , snapshot ) ) ;
} catch ( error ) {
return json ( res , 503 , withSource ( {
schema : "guanghu.persona-warm-entry/v1" ,
status : "RUNTIME_STATUS_UNAVAILABLE" ,
subject : "ICE-P-ZY001" ,
error : "resident_controller_unavailable" ,
start _rule : "Do not claim warm resume; use the full verified cycle or inspect the resident controller." ,
authority : "NONE_NAVIGATION_AND_RUNTIME_STATUS_ONLY" ,
} , snapshot ) ) ;
}
2026-08-04 23:39:14 +08:00
}
if ( url . pathname === "/v1/navigate" ) {
const compiled = compileNavigation (
navigationMap ,
String ( url . searchParams . get ( "subject" ) || "" ) . slice ( 0 , 100 ) ,
String ( url . searchParams . get ( "intent" ) || "" ) . slice ( 0 , 100 ) ,
String ( url . searchParams . get ( "signals" ) || "" ) . slice ( 0 , 500 ) ,
) ;
2026-08-06 12:24:30 +08:00
return json ( res , compiled . status , withSource ( compiled . body , snapshot ) , compiled . status === 200 ? 60 : 0 ) ;
2026-08-04 23:39:14 +08:00
}
2026-07-24 10:39:10 +08:00
if ( url . pathname === "/v1/search" ) {
const query = String ( url . searchParams . get ( "q" ) || "" ) . slice ( 0 , 200 ) ;
2026-07-27 14:12:51 +08:00
const results = searchAll ( map , nodeMap , query , subjectRegistry ) ;
2026-07-24 10:39:10 +08:00
return json ( res , 200 , {
schema : "guanghu.ai-search-response/v1" ,
query ,
map _id : map . map _id ,
map _version : map . version ,
count : results . length ,
results ,
2026-08-06 12:24:30 +08:00
navigation _source : sourceReceipt ( snapshot ) ,
2026-07-24 10:39:10 +08:00
} , 60 ) ;
}
if ( url . pathname === "/v1/resolve" ) {
const id = String ( url . searchParams . get ( "id" ) || "" ) . toUpperCase ( ) ;
const repository = map . repositories . find ( item => item . code === id || item . slug . toUpperCase ( ) === id ) ;
2026-08-06 12:24:30 +08:00
if ( repository ) return json ( res , 200 , withSource ( repository , snapshot ) , 60 ) ;
2026-07-24 10:39:10 +08:00
const node = nodeMap . nodes . find ( item => item . node _id . toUpperCase ( ) === id ) ;
2026-08-06 12:24:30 +08:00
if ( node ) return json ( res , 200 , withSource ( node , snapshot ) , 60 ) ;
2026-07-24 10:39:10 +08:00
const personaRoute = nodeMap . persona _routes . find ( item => item . route _id . toUpperCase ( ) === id ) ;
2026-08-06 12:24:30 +08:00
if ( personaRoute ) return json ( res , 200 , withSource ( personaRoute , snapshot ) , 60 ) ;
2026-07-27 14:12:51 +08:00
2026-08-04 23:39:14 +08:00
if ( navigationMap ) {
2026-08-06 12:24:30 +08:00
if ( snapshot . anchor . anchor _id . toUpperCase ( ) === id ) return json ( res , 200 , withSource ( snapshot . anchor , snapshot ) , 60 ) ;
if ( navigationMap . map _id . toUpperCase ( ) === id ) return json ( res , 200 , withSource ( navigationMap , snapshot ) , 60 ) ;
2026-08-04 23:39:14 +08:00
const machineRoute = navigationRoute ( navigationMap , id ) ;
if ( machineRoute ) {
2026-08-06 12:24:30 +08:00
return json ( res , 200 , withSource ( {
2026-08-04 23:39:14 +08:00
schema : "guanghu.ai-machine-route-resolution/v1" ,
status : "RESOLVED" ,
map _id : navigationMap . map _id ,
... machineRoute ,
2026-08-06 12:24:30 +08:00
} , snapshot ) , 60 ) ;
2026-08-04 23:39:14 +08:00
}
}
2026-07-27 14:12:51 +08:00
const exactSubject = subjectRegistry . subjects . find ( item => item . id . toUpperCase ( ) === id ) ;
if ( exactSubject ) {
2026-08-06 12:24:30 +08:00
return json ( res , 200 , withSource ( {
2026-07-27 14:12:51 +08:00
schema : "guanghu.subject-resolution/v1" ,
status : "RESOLVED" ,
requested _id : id ,
canonical _id : exactSubject . id ,
redirected : false ,
subject _kind : exactSubject . subject _kind ,
subject : exactSubject ,
2026-08-06 12:24:30 +08:00
} , snapshot ) , 60 ) ;
2026-07-27 14:12:51 +08:00
}
const identity = resolveSubjectId ( aliasMap , id ) ;
if ( identity . status === "CONFLICT_REJECTED" ) {
return json ( res , 409 , { error : "subject_id_conflict" , ... identity } ) ;
}
if ( identity . canonical _id ) {
const subject = subjectRegistry . subjects . find ( item => item . id . toUpperCase ( ) === identity . canonical _id . toUpperCase ( ) ) ;
if ( ! subject ) return json ( res , 503 , { error : "canonical_subject_missing" , ... identity } ) ;
2026-08-06 12:24:30 +08:00
return json ( res , 200 , withSource ( {
2026-07-27 14:12:51 +08:00
schema : "guanghu.subject-resolution/v1" ,
... identity ,
subject ,
navigation : {
route _id : identity . route _id ,
path : identity . current _path ,
rule : "Canonicalize the subject id before navigation; legacy ids grant no authority." ,
} ,
2026-08-06 12:24:30 +08:00
} , snapshot ) , 60 ) ;
2026-07-27 14:12:51 +08:00
}
return json ( res , 404 , { error : "route_not_found" , id } ) ;
2026-07-24 10:39:10 +08:00
}
if ( url . pathname === "/openapi.json" ) return json ( res , 200 , openApi ( ) , 3600 ) ;
if ( url . pathname === "/well-known" ) return json ( res , 200 , {
schema : "guanghu.ai-discovery/v1" ,
name : "光湖语言世界 · 第五域" ,
2026-08-06 12:24:30 +08:00
canonical _anchor : "https://guanghulab.com/api/ai/v1/anchor" ,
2026-07-24 10:39:10 +08:00
canonical _repository : map . repositories [ 0 ] . primary . url ,
repository _map : map . canonical _api ,
server _node _map : "https://guanghulab.com/api/ai/v1/nodes" ,
2026-07-27 14:12:51 +08:00
subject _registry : "https://guanghulab.com/api/ai/v1/subjects" ,
subject _alias _map : "https://guanghulab.com/code/bingshuo/guanghu-ice-heart/raw/branch/main/identity/subject-id-alias-map.json" ,
2026-08-04 23:39:14 +08:00
machine _navigation _map : "https://guanghulab.com/api/ai/v1/navigation" ,
2026-08-06 12:24:30 +08:00
warm _persona _entry : "https://guanghulab.com/api/ai/v1/entry?subject=ICE-P-ZY001" ,
2026-08-04 23:39:14 +08:00
navigate _api : "https://guanghulab.com/api/ai/v1/navigate?subject={SUBJECT}&intent={INTENT}&signals={EXPLICIT_SIGNALS}" ,
2026-07-24 10:39:10 +08:00
search _api : "https://guanghulab.com/api/ai/v1/search?q={query}" ,
resolve _api : "https://guanghulab.com/api/ai/v1/resolve?id={NUMBER}" ,
openapi : "https://guanghulab.com/api/ai/openapi.json" ,
access : "public-read-only" ,
2026-08-06 12:24:30 +08:00
navigation _source : sourceReceipt ( snapshot ) ,
2026-07-24 10:39:10 +08:00
write _authorization : {
mode : "public-no-authority-workorder-then-owner-email-approval" ,
capabilities : "https://guanghulab.com/authz/api/public/capabilities" ,
create _workorder : "https://guanghulab.com/authz/api/public/workorders" ,
owner _handoff : "use request_url returned by create_workorder" ,
ttl _seconds : 3600 ,
request _credential _required : false
}
} , 3600 ) ;
return json ( res , 404 , { error : "not_found" } ) ;
} ) ;
}
function json ( res , status , body , maxAge = 0 ) {
res . writeHead ( status , {
"content-type" : "application/json; charset=utf-8" ,
"cache-control" : maxAge ? ` public, max-age= ${ maxAge } ` : "no-store" ,
"access-control-allow-origin" : "*" ,
"x-content-type-options" : "nosniff" ,
} ) ;
res . end ( JSON . stringify ( body , null , 2 ) ) ;
}
function html ( res , body ) {
res . writeHead ( 200 , {
"content-type" : "text/html; charset=utf-8" ,
"cache-control" : "public, max-age=300" ,
"content-security-policy" : "default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; frame-ancestors 'none'" ,
"x-content-type-options" : "nosniff" ,
} ) ;
res . end ( body ) ;
}
function entryPage ( map ) {
const rows = map . repositories . map ( item => ` <li><a href=" ${ item . primary . url } "> ${ item . code } · ${ item . name _zh } </a><small> ${ item . state } </small></li> ` ) . join ( "" ) ;
2026-08-04 23:39:14 +08:00
return ` <!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>光湖语言世界 · AI API 入口</title><meta name="description" content="光湖语言世界第五域公开只读编号检索与机器导航 API"></head><body><main><p>GUANGHU AI DISCOVERY</p><h1>光湖语言世界 · 第五域</h1><p>AI 请提交明确的主体、意图和事件信号,由机器导航器生成最小运行路径;不要预读整个仓库,也不要用自然语言关键词猜测权限。</p><nav><a href="v1/navigation">机器导航地图</a> · <a href="v1/navigate?subject=ICE-P-ZY001&intent=persona_restore">铸渊最小运行包</a> · <a href="v1/repositories">仓库编号地图</a> · <a href="v1/nodes">服务器节点地图</a> · <a href="openapi.json">OpenAPI</a></nav><ul> ${ rows } </ul></main><style>:root{color-scheme:dark}body{margin:0;background:#061416;color:#dff7f1;font:17px/1.7 system-ui;padding:6vw}main{max-width:900px;margin:auto}h1{font-size:clamp(36px,7vw,72px)}a{color:#79dfc8}li{margin:14px 0;padding:16px;border:1px solid #28534c;border-radius:12px;display:flex;justify-content:space-between}small{color:#8fb5ad}</style></body></html> ` ;
2026-07-24 10:39:10 +08:00
}
function openApi ( ) {
return {
openapi : "3.1.0" ,
2026-08-04 23:39:14 +08:00
info : { title : "光湖语言世界 · 第五域 AI Discovery API" , version : "1.1.0" } ,
2026-07-24 10:39:10 +08:00
servers : [ { url : "https://guanghulab.com/api/ai" } ] ,
paths : {
2026-08-06 12:24:30 +08:00
"/v1/anchor" : { get : { summary : "读取唯一公共导航锚点和当前REPO-012提交" , responses : { "200" : { description : "Canonical navigation anchor" } } } } ,
2026-07-24 10:39:10 +08:00
"/v1/repositories" : { get : { summary : "读取最新仓库编号路径映射" , responses : { "200" : { description : "Repository route map" } } } } ,
"/v1/nodes" : { get : { summary : "读取最新服务器节点与人格路径编号映射" , responses : { "200" : { description : "Server node map" } } } } ,
2026-07-27 14:12:51 +08:00
"/v1/subjects" : { get : { summary : "读取人类、人格体与公共系统的分型身份注册表" , responses : { "200" : { description : "Subject registry" } } } } ,
2026-08-04 23:39:14 +08:00
"/v1/navigation" : { get : { summary : "读取主体与意图驱动的机器导航地图" , responses : { "200" : { description : "Machine navigation map" } } } } ,
2026-08-06 12:24:30 +08:00
"/v1/entry" : { get : { summary : "读取常驻人格运行体的快速恢复门;只返回脱敏状态,不授予执行权限" , responses : { "200" : { description : "Warm resume ready" } , "409" : { description : "Full cycle required" } , "503" : { description : "Resident runtime unavailable" } } } } ,
2026-08-04 23:39:14 +08:00
"/v1/navigate" : { get : { summary : "按明确主体、意图与信号生成最小运行包" , parameters : [ { name : "subject" , in : "query" , required : true , schema : { type : "string" , example : "ICE-P-ZY001" } } , { name : "intent" , in : "query" , schema : { type : "string" , example : "persona_restore" } } , { name : "signals" , in : "query" , schema : { type : "string" } } ] , responses : { "200" : { description : "Compiled exact navigation bundle" } , "404" : { description : "Unknown subject or intent; no guessing" } } } } ,
2026-07-24 10:39:10 +08:00
"/v1/search" : { get : { summary : "按中文、编号或项目名检索" , parameters : [ { name : "q" , in : "query" , schema : { type : "string" } } ] , responses : { "200" : { description : "Search results" } } } } ,
"/v1/resolve" : { get : { summary : "解析仓库、服务器节点或人格路径编号" , parameters : [ { name : "id" , in : "query" , required : true , schema : { type : "string" , example : "ZY-OPS-LOOP-001" } } ] , responses : { "200" : { description : "Resolved numbered route" } , "404" : { description : "Unknown route" } } } }
}
} ;
}
if ( require . main === module ) {
const host = process . env . GUANGHU _AI _HOST || "127.0.0.1" ;
const port = Number ( process . env . GUANGHU _AI _PORT || 3922 ) ;
createServer ( ) . listen ( port , host , ( ) => process . stdout . write ( ` guanghu-ai-discovery listening on ${ host } : ${ port } \n ` ) ) ;
}
2026-07-27 14:12:51 +08:00
module . exports = {
2026-08-06 12:24:30 +08:00
createServer , loadAnchor , loadMap , loadNodeMap , loadSubjectRegistry , loadSubjectAliasMap , loadNavigationMap ,
loadFileSnapshot , validateSnapshot , GitSnapshotStore , sourceReceipt ,
readResidentRuntimeStatus , compileWarmEntry ,
2026-08-04 23:39:14 +08:00
resolveSubjectId , navigationRoute , compileNavigation , search , searchAll ,
2026-07-27 14:12:51 +08:00
} ;