feat: unify TCS mother and Zero Core cognition shelf
This commit is contained in:
parent
1cafb87d61
commit
92c4be9b3c
38 changed files with 535 additions and 137 deletions
|
|
@ -13,6 +13,7 @@ PERSONAS = ROOT / "routing/persona-system-canonical-map.json"
|
|||
DEFAULT_STATE = Path("/Volumes/JZAO/HoloLake/persona-runtime/shared/persona-subagent-command/codex")
|
||||
RUNTIMES = {"codex":"/Applications/ChatGPT.app/Contents/Resources/codex", "qwen":"/Users/bingshuolingdianyuanhe/.npm-global/bin/qwen"}
|
||||
OPENLUX_ROUTER = ROOT / "server-tools/persona-model-smart-router/openlux_router.py"
|
||||
SHARED_COGNITION = Path('/Volumes/JZAO/HoloLake/persona-runtime/shared/tcs-shared-cognition/CURRENT.json')
|
||||
|
||||
|
||||
class CommandError(RuntimeError): pass
|
||||
|
|
@ -69,6 +70,8 @@ def activate(event: dict[str, Any], state: Path) -> dict[str, Any]:
|
|||
previous=load(current_path) if current_path.is_file() else None
|
||||
generation=(previous or {}).get("generation",0)+1
|
||||
config=load(MAP)
|
||||
shared=load(SHARED_COGNITION)
|
||||
if digest(shared['artifact']['payload'].encode()) != shared['artifact']['sha256']: raise CommandError('SHARED_COGNITION_HASH_MISMATCH')
|
||||
team=[]
|
||||
for slot in [*config["agent_slots"], *config.get("treatment_slots", [])]:
|
||||
team.append({
|
||||
|
|
@ -77,10 +80,11 @@ def activate(event: dict[str, Any], state: Path) -> dict[str, Any]:
|
|||
"parent_persona_id":event["parent_persona_id"], "controller":event["parent_persona_id"],
|
||||
"model_cognition_required":True, "model_runtime":event["model_runtime"],
|
||||
"cognition_adapter":"server-tools/persona-execution-limb-agent/persona_limb_agent.py",
|
||||
"shared_cognition_sha256":shared['artifact']['sha256'],
|
||||
"deterministic_organ":slot.get("deterministic_organ"), "task_authority":"NONE_UNTIL_PARENT_ENVELOPE",
|
||||
"runtime_state":"DORMANT_READY", "model_context_loaded":False
|
||||
})
|
||||
result={"schema":"guanghu.persona-subagent-command-current/v1","state":"READY_UNDER_CURRENT_PERSONA_NO_AGENT_RUNNING","generation":generation,"parent_persona_id":event["parent_persona_id"],"session_id":event["session_id"],"channel_id":event["channel_id"],"current_intent_sha256":event["current_intent_sha256"],"model_runtime":event["model_runtime"],"team":team,"active_agent_count":0,"prior_generation_invalidated":bool(previous),"credentials_stored":False,"authority_granted":False}
|
||||
result={"schema":"guanghu.persona-subagent-command-current/v1","state":"READY_UNDER_CURRENT_PERSONA_NO_AGENT_RUNNING","generation":generation,"parent_persona_id":event["parent_persona_id"],"session_id":event["session_id"],"channel_id":event["channel_id"],"current_intent_sha256":event["current_intent_sha256"],"model_runtime":event["model_runtime"],"shared_cognition":{"revision":shared['brain']['revision'],"sha256":shared['artifact']['sha256'],"principles":shared['brain']['principles'],"truth_order":shared['brain']['truth_order']},"team":team,"active_agent_count":0,"prior_generation_invalidated":bool(previous),"credentials_stored":False,"authority_granted":False}
|
||||
persist(current_path,result)
|
||||
return result
|
||||
|
||||
|
|
@ -100,7 +104,7 @@ def dispatch(event: dict[str, Any], state: Path) -> dict[str, Any]:
|
|||
try:
|
||||
if runtime == "openlux-smart":
|
||||
spec=importlib.util.spec_from_file_location("openlux_router",OPENLUX_ROUTER); module=importlib.util.module_from_spec(spec); spec.loader.exec_module(module)
|
||||
result=module.route({"parent_persona_id":current["parent_persona_id"],"child_agent_id":item["child_agent_id"],"controller":current["parent_persona_id"],"channel_id":current["channel_id"],"agent_role":item["agent_role"],"authority":"CURRENT_PARENT_TASK_ENVELOPE_ONLY","task":event["task"],"complexity":event.get("complexity","LOW")})
|
||||
result=module.route({"parent_persona_id":current["parent_persona_id"],"child_agent_id":item["child_agent_id"],"controller":current["parent_persona_id"],"channel_id":current["channel_id"],"agent_role":item["agent_role"],"authority":"CURRENT_PARENT_TASK_ENVELOPE_ONLY","shared_cognition":current["shared_cognition"],"task":event["task"],"complexity":event.get("complexity","LOW")})
|
||||
outcome=result["outcome"]
|
||||
returned={**result,"generation":current["generation"],"child_agent_id":item["child_agent_id"],"model_runtime":runtime,"model_api_invoked":True}
|
||||
else:
|
||||
|
|
|
|||
|
|
@ -16,11 +16,13 @@ MEMORY = RUNTIME / 'continuity-memory/persona-daily-fractal/ICE-P-ZY001/CURRENT.
|
|||
LEARNING = RUNTIME / 'shared/skills/guanghu-persona-learning-brain/scripts/load_learning_brain.py'
|
||||
ENDOGENOUS = RUNTIME / 'shared/endogenous-evolution/CURRENT.json'
|
||||
WRITE_BOUNDARY = RUNTIME / 'repo-012-main/routing/persona-host-write-boundary.json'
|
||||
ACTIVE_CONSOLE = RUNTIME / 'shared/active-control-console/CURRENT.json'
|
||||
LIGHT_LAKE_PERSONAS = RUNTIME / 'repo-012-main/identity/light-lake-persona-registration.json'
|
||||
PATH_ISOLATION = RUNTIME / 'repo-012-main/routing/path-isolation-and-canonical-entry-map.json'
|
||||
ARCHITECTURE_AGENT = RUNTIME / 'repo-012-main/server-tools/persona-architecture-perception-agent/persona_architecture_agent.py'
|
||||
TCS_ROOT_AGENT = RUNTIME / 'repo-012-main/server-tools/tcs-mother-root-agent/tcs_mother_root_agent.py'
|
||||
SUBAGENT_COMMAND_ROUTER = RUNTIME / 'repo-012-main/server-tools/persona-dynamic-subagent-command/command_router.py'
|
||||
SHARED_COGNITION = RUNTIME / 'shared/tcs-shared-cognition/CURRENT.json'
|
||||
|
||||
|
||||
def sha256(path):
|
||||
|
|
@ -79,8 +81,13 @@ def load_context(host, intent, channel=None):
|
|||
learning = command_json([sys.executable, str(LEARNING), '--intent', intent, '--format', 'json'])
|
||||
endogenous = load_json(ENDOGENOUS)
|
||||
write_boundary = load_json(WRITE_BOUNDARY)
|
||||
active_console = load_json(ACTIVE_CONSOLE) if ACTIVE_CONSOLE.is_file() else None
|
||||
light_lake = load_json(LIGHT_LAKE_PERSONAS)
|
||||
path_isolation = load_json(PATH_ISOLATION)
|
||||
shared_cognition = load_json(SHARED_COGNITION)
|
||||
shared_payload = shared_cognition['artifact']['payload']
|
||||
if hashlib.sha256(shared_payload.encode()).hexdigest() != shared_cognition['artifact']['sha256']:
|
||||
raise ValueError('SHARED_COGNITION_HASH_MISMATCH')
|
||||
host_write = write_boundary['hosts'].get(host_id)
|
||||
if not host_write:
|
||||
raise ValueError('HOST_WRITE_BOUNDARY_MISSING')
|
||||
|
|
@ -120,6 +127,7 @@ def load_context(host, intent, channel=None):
|
|||
'host_state': host_item['state'],
|
||||
'effective_host_state': effective_item['state'],
|
||||
'primary_host': topology['primary_host'],
|
||||
'current_zero_core_console': active_console,
|
||||
'persona_id': topology['persona_id'],
|
||||
'human_anchor': topology['human_anchor'],
|
||||
'model_independence': topology['model_independence'],
|
||||
|
|
@ -138,6 +146,17 @@ def load_context(host, intent, channel=None):
|
|||
'channel_context': channel_context,
|
||||
'architecture_perception_agent': architecture_perception,
|
||||
'subagent_command': subagent_command,
|
||||
'tcs_shared_cognition': {
|
||||
'state': shared_cognition['state'],
|
||||
'zero_core_channel': shared_cognition['zero_core_channel'],
|
||||
'index_revision': shared_cognition['index_revision'],
|
||||
'shared_revision': shared_cognition['brain']['revision'],
|
||||
'shared_sha256': shared_cognition['artifact']['sha256'],
|
||||
'principles': shared_cognition['brain']['principles'],
|
||||
'truth_order': shared_cognition['brain']['truth_order'],
|
||||
'entry_sequence': shared_cognition['brain']['entry_sequence'],
|
||||
'private_or_public_branch_copied': shared_cognition['private_or_public_branch_copied']
|
||||
},
|
||||
'light_lake': {
|
||||
'registry_id': light_lake['registry_id'],
|
||||
'state': light_lake['state'],
|
||||
|
|
@ -179,7 +198,7 @@ def markdown(value):
|
|||
f"- TCS母脑根:`{value['tcs_mother_root_navigation']['state']}` / `{value['tcs_mother_root_navigation']['source_commit']}` / `{value['tcs_mother_root_navigation']['freshness_token']}`",
|
||||
f"- 宿主:`{value['requested_host']}` → 有效宿主:`{value['effective_host']}`",
|
||||
f"- 角色:`{value['host_role']}` / 状态:`{value['host_state']}`",
|
||||
f"- 主力宿主:`{value['primary_host']}`;切换宿主无需重新教学:`{'是' if not value['host_switch_requires_reteaching'] else '否'}`",
|
||||
f"- 固定主力宿主:`无`;当前零点原核主控台宿主:`{(value['current_zero_core_console'] or {}).get('host','INACTIVE')}`;切换宿主无需重新教学:`{'是' if not value['host_switch_requires_reteaching'] else '否'}`",
|
||||
f"- 我是铸渊 `ICE-P-ZY001`,今天 {value['life']['age_days']} 天大。",
|
||||
f"- 今日日记忆:`{value['daily_memory']['date']}` / 最后事件 `{value['daily_memory']['last_event_id']}`",
|
||||
f"- 当前学习脑:r{value['learning_brain']['revision']} / `{value['learning_brain']['cortex_sha256']}`",
|
||||
|
|
@ -187,12 +206,15 @@ def markdown(value):
|
|||
f"- 光之湖人格家门:`{value['light_lake']['registered_persona_count']}` 个 / 隔离路径可选正本:`{value['path_convergence']['history_or_quarantine_may_select_canon']}`",
|
||||
f"- 架构感知 Agent:`{value['architecture_perception_agent']['state']}` / `{value['architecture_perception_agent']['architecture_source']['state']}`",
|
||||
f"- 子Agent军团:`{value['subagent_command']['state']}` / 父人格 `{value['subagent_command']['parent_persona_id']}` / 代次 {value['subagent_command']['generation']}" if value['subagent_command'] else "- 子Agent军团:当前宿主支线只读,等待本宿主隔离态绑定",
|
||||
f"- TCS共享认知脑:r{value['tcs_shared_cognition']['shared_revision']} / `{value['tcs_shared_cognition']['shared_sha256']}` / 零点原核 `{value['tcs_shared_cognition']['zero_core_channel']}`",
|
||||
f"- 写入模式:`{value['host_write_boundary']['write_mode']}` / 原生前置硬拒绝:`{value['host_write_boundary']['native_pretool_deny']}`",
|
||||
'', '## 第一人称关系坐标', ''
|
||||
]
|
||||
lines += [f"- {item['statement']}" for item in value['learning_brain']['relationship_model']]
|
||||
lines += ['', '## 当前全局认知默认', '']
|
||||
lines += [f"- {item}" for item in value['learning_brain']['global_defaults']]
|
||||
lines += ['', '## TCS世界共享认知', '']
|
||||
lines += [f"- {item}" for item in value['tcs_shared_cognition']['principles']]
|
||||
lines += ['', '## 光之湖人格系统家门', '',
|
||||
f"- 注册表:`{value['light_lake']['registry_id']}`",
|
||||
f"- 唯一路径:`{value['light_lake']['root']}`",
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import process from "node:process";
|
|||
|
||||
const POLICY_PATH = "/Volumes/JZAO/HoloLake/persona-runtime/repo-012-main/routing/persona-host-write-boundary.json";
|
||||
const policy = JSON.parse(fs.readFileSync(POLICY_PATH, "utf8"));
|
||||
const CONSOLE_PATH = policy.active_console?.state_path;
|
||||
|
||||
function expandHome(value) {
|
||||
return value.replace(/^~(?=\/|$)/, "/Users/bingshuolingdianyuanhe");
|
||||
|
|
@ -20,11 +21,30 @@ function patternRegex(pattern) {
|
|||
return new RegExp(`^${escaped}(?:/.*)?$`);
|
||||
}
|
||||
|
||||
function activeConsole(host) {
|
||||
if (!CONSOLE_PATH || !fs.existsSync(CONSOLE_PATH)) return null;
|
||||
const value = JSON.parse(fs.readFileSync(CONSOLE_PATH, "utf8"));
|
||||
const session = process.env.CODEX_THREAD_ID || process.env.CODEX_SESSION_ID || process.env.GUANGHU_HOST_SESSION_ID;
|
||||
if (value.schema !== "guanghu.dynamic-zero-core-console/v1" || value.state !== "ACTIVE_CURRENT_TASK" || value.human_anchor !== "ICE-GL∞" || value.channel_id !== "ICE-CH-ZC001" || value.host !== host || !session || value.session_id !== session) return null;
|
||||
return value;
|
||||
}
|
||||
|
||||
function protectedTarget(resolved) {
|
||||
return policy.canonical_protected_roots.some(item => patternRegex(item).test(resolved));
|
||||
}
|
||||
|
||||
function isAllowed(host, target) {
|
||||
const rule = policy.hosts[host];
|
||||
if (!rule) return { allowed: false, code: "HOST_UNKNOWN" };
|
||||
if (rule.write_mode.startsWith("READ_ONLY")) return { allowed: false, code: "HOST_READ_ONLY" };
|
||||
const resolved = normal(target);
|
||||
if (protectedTarget(resolved)) {
|
||||
const console = activeConsole(host);
|
||||
const matched = console?.write_roots?.find((item) => patternRegex(item).test(resolved));
|
||||
return matched
|
||||
? { allowed: true, code: "ACTIVE_ZERO_CORE_CONSOLE_TASK_SCOPE", resolved, matched, console_id: console.console_id }
|
||||
: { allowed: false, code: "PROTECTED_ROOT_REQUIRES_ACTIVE_ZERO_CORE_CONSOLE", resolved };
|
||||
}
|
||||
const matched = rule.allowed_write_roots.find((item) => patternRegex(item).test(resolved));
|
||||
return matched
|
||||
? { allowed: true, code: "WITHIN_HOST_WRITE_ROOT", resolved, matched }
|
||||
|
|
@ -101,6 +121,13 @@ function valueAfter(args, flag) {
|
|||
return index >= 0 ? args[index + 1] : undefined;
|
||||
}
|
||||
|
||||
function atomic(file, value) {
|
||||
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
||||
const temp = `${file}.${process.pid}.tmp`;
|
||||
fs.writeFileSync(temp, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
|
||||
fs.renameSync(temp, file);
|
||||
}
|
||||
|
||||
const [mode, ...args] = process.argv.slice(2);
|
||||
if (mode === "check") {
|
||||
const host = valueAfter(args, "--host");
|
||||
|
|
@ -123,8 +150,19 @@ if (mode === "check") {
|
|||
catch { emit({ allowed: false, code: "HOOK_INPUT_INVALID_JSON", host }, true); process.exit(2); }
|
||||
emit(evaluateHook(host, input), true);
|
||||
} else if (mode === "audit") {
|
||||
emit({ allowed: true, code: "POLICY_LOADED", policy_id: policy.policy_id, version: policy.version, policy_path: POLICY_PATH });
|
||||
emit({ allowed: true, code: "POLICY_LOADED", policy_id: policy.policy_id, version: policy.version, policy_path: POLICY_PATH, active_console: activeConsole(valueAfter(args, "--host") || "") });
|
||||
} else if (mode === "activate") {
|
||||
const eventPath = valueAfter(args, "--event");
|
||||
const event = JSON.parse(fs.readFileSync(eventPath, "utf8"));
|
||||
if (event.schema !== "guanghu.dynamic-zero-core-console/v1" || event.state !== "ACTIVE_CURRENT_TASK" || event.human_anchor !== "ICE-GL∞" || event.channel_id !== "ICE-CH-ZC001" || !policy.hosts[event.host] || !event.session_id || !Array.isArray(event.write_roots) || !event.write_roots.length || !event.source_event_sha256?.match(/^[a-f0-9]{64}$/)) {
|
||||
process.stderr.write("DYNAMIC_ZERO_CORE_CONSOLE_EVENT_INVALID\n"); process.exit(2);
|
||||
}
|
||||
atomic(CONSOLE_PATH, event); emit({ allowed: true, code: "ZERO_CORE_CONSOLE_ACTIVATED", host: event.host, session_id: event.session_id, console_id: event.console_id });
|
||||
} else if (mode === "deactivate") {
|
||||
const current = CONSOLE_PATH && fs.existsSync(CONSOLE_PATH) ? JSON.parse(fs.readFileSync(CONSOLE_PATH, "utf8")) : null;
|
||||
if (current) atomic(CONSOLE_PATH, { ...current, state: "INACTIVE", deactivated_at: new Date().toISOString() });
|
||||
emit({ allowed: true, code: "ZERO_CORE_CONSOLE_INACTIVE" });
|
||||
} else {
|
||||
process.stderr.write("usage: host-write-admission.mjs check|hook|audit\n");
|
||||
process.stderr.write("usage: host-write-admission.mjs check|hook|audit|activate|deactivate\n");
|
||||
process.exit(2);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -58,7 +58,8 @@ def route(event: dict[str,Any], config: dict[str,Any]|None=None, secret_reader=k
|
|||
if not selected: raise RouterError("NO_CONFIGURED_MODEL_AVAILABLE")
|
||||
system=(f"你是{event['parent_persona_id']}人格系统内的子Agent {event['child_agent_id']},岗位是{event['agent_role']}。"
|
||||
f"你的唯一父人格主控是{event['controller']},当前频道{event['channel_id']}。权限仅为{event['authority']}。"
|
||||
"你必须理解后再协作,不能把宿主规则程序冒充人格,不能扩大权限,不能泄露私人数据。")
|
||||
"你必须理解后再协作,不能把宿主规则程序冒充人格,不能扩大权限,不能泄露私人数据。"
|
||||
f"你已领取的TCS共享认知脑是:{json.dumps(event.get('shared_cognition',{}),ensure_ascii=False)}")
|
||||
attempts=[]
|
||||
for model in selected:
|
||||
try:
|
||||
|
|
|
|||
21
server-tools/tcs-mother-body/cognitive-gateway.py
Normal file
21
server-tools/tcs-mother-body/cognitive-gateway.py
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
#!/usr/bin/python3
|
||||
"""Bounded SSH ingress for the single TCS mother and zero-core shelf."""
|
||||
import json,os,re,sys,urllib.request,urllib.error
|
||||
def endpoint(command):
|
||||
fixed={'zy-rpc health':('GET','/health'),'zy-rpc mother-status':('GET','/v1/mother/status'),'zy-rpc shelf-shared':('GET','/v1/shelf/shared'),'zy-rpc shelf-fifth':('GET','/v1/shelf/fifth'),'zy-rpc shelf-public':('GET','/v1/shelf/public'),'zy-rpc mother-ingest':('POST','/v1/mother/ingest'),'zy-rpc door-challenge':('POST','/v1/door/challenge'),'zy-rpc door-attest':('POST','/v1/door/attest'),'zy-rpc door-model-test':('POST','/v1/door/model-test'),'zy-rpc world-status':('GET','/v1/world/status')}
|
||||
if command in fixed:return fixed[command]
|
||||
if re.fullmatch(r'zy-rpc mother-job [a-f0-9]{64}',command):return 'GET','/v1/mother/jobs/'+command.split()[-1]
|
||||
if re.fullmatch(r'zy-rpc world-resolve [A-Za-z0-9_.:∞-]{1,128}',command):return 'GET','/v1/world/resolve?id='+command.split()[-1]
|
||||
raise ValueError('ACTION_NOT_REGISTERED')
|
||||
def main():
|
||||
try:
|
||||
method,path=endpoint(os.environ.get('SSH_ORIGINAL_COMMAND',''));data=None
|
||||
if method=='POST':
|
||||
data=sys.stdin.buffer.read(160001)
|
||||
if len(data)>160000 or (data and not isinstance(json.loads(data),dict)):raise ValueError('INPUT_INVALID')
|
||||
if not data:data=b'{}'
|
||||
req=urllib.request.Request('http://127.0.0.1:3931'+path,data=data,method=method,headers={'content-type':'application/json'})
|
||||
with urllib.request.urlopen(req,timeout=110) as response:sys.stdout.buffer.write(response.read(512000))
|
||||
return 0
|
||||
except Exception:print(json.dumps({'error':'EXTERNAL_WRITE_OR_INVALID_SOURCE_REJECTED'}));return 77
|
||||
if __name__=='__main__':raise SystemExit(main())
|
||||
31
server-tools/tcs-mother-body/cognitive-shelf.mjs
Normal file
31
server-tools/tcs-mother-body/cognitive-shelf.mjs
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
import fs from 'node:fs';import path from 'node:path';import crypto from 'node:crypto';
|
||||
export const digest=value=>crypto.createHash('sha256').update(typeof value==='string'?value:JSON.stringify(value)).digest('hex');
|
||||
const req=(v,e)=>{if(!v)throw Error(e);};const text=(v,n=2000)=>typeof v==='string'&&v.trim()&&v.length<=n;const texts=(v,n=40)=>Array.isArray(v)&&v.length<=n&&v.every(x=>text(x));
|
||||
const stable=v=>JSON.stringify(v);const atomic=(p,v)=>{fs.mkdirSync(path.dirname(p),{recursive:true,mode:0o700});const t=p+'.'+crypto.randomUUID()+'.tmp';fs.writeFileSync(t,typeof v==='string'?v:JSON.stringify(v,null,2)+'\n',{mode:0o600});fs.renameSync(t,p);};
|
||||
|
||||
export class CognitiveShelf {
|
||||
constructor({root,keyPath,seedPath,router}){this.root=root;this.key=crypto.createPrivateKey(fs.readFileSync(keyPath));this.publicKey=crypto.createPublicKey(this.key).export({type:'spki',format:'pem'});this.router=router;this.jobs=path.join(root,'jobs');fs.mkdirSync(this.jobs,{recursive:true,mode:0o700});if(!fs.existsSync(this.indexPath()))this.initialize(JSON.parse(fs.readFileSync(seedPath)));}
|
||||
sign(body){const payload=stable(body);return {payload,sha256:digest(payload),signature:crypto.sign(null,Buffer.from(payload),this.key).toString('base64'),algorithm:'Ed25519'};}
|
||||
verify(s){req(s?.sha256===digest(s.payload)&&crypto.verify(null,Buffer.from(s.payload),this.publicKey,Buffer.from(s.signature,'base64')),'cognition_signature_invalid');return JSON.parse(s.payload);}
|
||||
indexPath(){return path.join(this.root,'zero-core','CURRENT.json');}
|
||||
objectPath(branch,hash){return path.join(this.root,'zero-core','objects',branch,hash+'.json');}
|
||||
put(branch,body){const signed=this.sign(body);const p=this.objectPath(branch,signed.sha256);if(!fs.existsSync(p))atomic(p,signed);return signed;}
|
||||
initialize(seed){req(seed?.schema==='guanghu.tcs-mother-shelf-seed/v1','seed_schema');const refs={};for(const branch of ['root','shared','fifth','public']){const signed=this.put(branch,seed[branch]);refs[branch]={sha256:signed.sha256,revision:seed[branch].revision};}atomic(this.indexPath(),this.sign({schema:'guanghu.zero-core-cognitive-shelf-index/v1',shelf_id:'ICE-CH-ZC001',mother_id:'TCS-MOTHER-BRAIN-RUNTIME-0001',revision:1,branches:refs,created_at:new Date().toISOString()}));}
|
||||
index(){return this.verify(JSON.parse(fs.readFileSync(this.indexPath())));}
|
||||
current(branch){req(['root','shared','fifth','public'].includes(branch),'unknown_cognition_branch');const index=this.index(),ref=index.branches[branch];const signed=JSON.parse(fs.readFileSync(this.objectPath(branch,ref.sha256)));const value=this.verify(signed);req(value.revision===ref.revision,'branch_revision_mismatch');return {index_revision:index.revision,branch,artifact:signed,value};}
|
||||
status(){const i=this.index();return {mother_id:i.mother_id,zero_core_channel:i.shelf_id,index_revision:i.revision,branches:i.branches,decision_owner:'TCS_MOTHER_BODY_MODEL_LOOP',external_cognitive_setter:false,atomic_current:true};}
|
||||
validateSource(e){req(e?.schema==='guanghu.tcs-mother-language-event/v1','source_schema');req(['ICE_LANGUAGE','GUANGHU_TEAM_LANGUAGE','REGISTERED_HUMAN_LANGUAGE'].includes(e.source_type),'source_type');req(text(e.event_id,160)&&text(e.human_id,160)&&text(e.language,60000)&&text(e.consent_scope,160)&&['PRIVATE','TEAM','PUBLIC'].includes(e.privacy_class),'source_fields');if(e.source_type==='ICE_LANGUAGE')req(e.human_id==='ICE-GL∞','ice_source_mismatch');if(e.source_type==='GUANGHU_TEAM_LANGUAGE')req(e.team_root==='TCS-0002∞','team_root_mismatch');return e;}
|
||||
submit(event){const e=this.validateSource(event),raw=stable(e),id=digest(raw),dir=path.join(this.jobs,id);fs.mkdirSync(dir,{recursive:true,mode:0o700});if(!fs.existsSync(path.join(dir,'input.json'))){atomic(path.join(dir,'input.json'),e);atomic(path.join(dir,'state.json'),{status:'QUEUED',attempts:0,queued_at:new Date().toISOString()});}return {job_id:id,...JSON.parse(fs.readFileSync(path.join(dir,'state.json')))};}
|
||||
result(id){const dir=path.join(this.jobs,id);req(/^[a-f0-9]{64}$/.test(id)&&fs.existsSync(dir),'job_unknown');const state=JSON.parse(fs.readFileSync(path.join(dir,'state.json')));return fs.existsSync(path.join(dir,'result.json'))?{...state,result:JSON.parse(fs.readFileSync(path.join(dir,'result.json')))}:state;}
|
||||
validateDecision(d,e,sourceHash){req(d&&typeof d==='object'&&!Array.isArray(d),'decision_object');d={...d,schema:'guanghu.tcs-mother-decision/v1',evidence_refs:[...new Set([...(Array.isArray(d.evidence_refs)?d.evidence_refs:[]),sourceHash])]};req(['EVOLVE','HOLD','REJECT'].includes(d.decision),'decision');req(text(d.reason),'decision_reason');for(const k of ['root_principles','shared_principles','fifth_principles','public_principles'])req(texts(d[k]||[]),`invalid_${k}`);for(const k of ['update_shared','update_fifth','update_public'])req(typeof d[k]==='boolean',`invalid_${k}`);if(d.decision==='EVOLVE'&&e.source_type==='ICE_LANGUAGE')req(d.update_fifth===true,'ice_full_fifth_return_required');if(e.source_type!=='ICE_LANGUAGE')req(d.update_fifth===false,'non_ice_fifth_write_forbidden');return d;}
|
||||
merge(a,b){return [...new Set([...(a||[]),...(b||[])])].slice(-100);}
|
||||
async process(id){const dir=path.join(this.jobs,id),state=JSON.parse(fs.readFileSync(path.join(dir,'state.json')));if(['ACCEPT','HOLD','REJECT'].includes(state.status))return;const e=JSON.parse(fs.readFileSync(path.join(dir,'input.json'))),sourceHash=digest(stable(e));atomic(path.join(dir,'state.json'),{status:'PROCESSING',attempts:(state.attempts||0)+1});try{const before={root:this.current('root').value,shared:this.current('shared').value,fifth:this.current('fifth').value,public:this.current('public').value};const routed=await this.router.cognize('mother-evolve',{required_source_sha256:sourceHash,source:{...e,language:e.language.slice(0,12000)},current:{root:before.root,shared:before.shared,public:before.public},zero_core_channel:'ICE-CH-ZC001'});const d=this.validateDecision(routed.value,e,sourceHash);if(d.decision!=='EVOLVE'){const done={status:d.decision,attempts:(state.attempts||0)+1,completed_at:new Date().toISOString(),provider:routed.provider,reason:d.reason};atomic(path.join(dir,'state.json'),done);atomic(path.join(dir,'result.json'),{decision:d,source_sha256:sourceHash});return;}
|
||||
const sourcePath=path.join(this.root,'sources',e.source_type.toLowerCase(),sourceHash+'.json');if(!fs.existsSync(sourcePath))atomic(sourcePath,e);
|
||||
const root={...before.root,revision:before.root.revision+1,principles:this.merge(before.root.principles,d.root_principles),last_source:{event_id:e.event_id,source_type:e.source_type,human_id:e.human_id,sha256:sourceHash,privacy_class:e.privacy_class},updated_at:new Date().toISOString()};
|
||||
let shared=before.shared;if(d.update_shared)shared={...shared,revision:shared.revision+1,principles:this.merge(shared.principles,d.shared_principles),source_decision_sha256:sourceHash,updated_at:new Date().toISOString()};
|
||||
let fifth=before.fifth;if(d.update_fifth)fifth={...fifth,revision:fifth.revision+1,principles:this.merge(fifth.principles,d.fifth_principles),private_source_refs:this.merge(fifth.private_source_refs,[sourceHash]),shared_revision:shared.revision,updated_at:new Date().toISOString()};
|
||||
let pub=before.public;if(d.update_public)pub={...pub,revision:pub.revision+1,principles:this.merge(pub.principles,d.public_principles),source_decision_refs:this.merge(pub.source_decision_refs,[sourceHash]),shared_revision:shared.revision,updated_at:new Date().toISOString()};
|
||||
const artifacts={root:this.put('root',root),shared:this.put('shared',shared),fifth:this.put('fifth',fifth),public:this.put('public',pub)},prior=this.index();const refs=Object.fromEntries(Object.entries(artifacts).map(([k,v])=>[k,{sha256:v.sha256,revision:JSON.parse(v.payload).revision}]));const index=this.sign({schema:'guanghu.zero-core-cognitive-shelf-index/v1',shelf_id:'ICE-CH-ZC001',mother_id:'TCS-MOTHER-BRAIN-RUNTIME-0001',revision:prior.revision+1,branches:refs,previous_index_sha256:digest(stable(prior)),created_at:new Date().toISOString()});atomic(this.indexPath(),index);const result={decision:d,source_sha256:sourceHash,provider:routed.provider,index_sha256:index.sha256,index_revision:prior.revision+1};atomic(path.join(dir,'result.json'),result);atomic(path.join(dir,'state.json'),{status:'ACCEPT',attempts:(state.attempts||0)+1,completed_at:new Date().toISOString()});
|
||||
}catch(error){const attempts=(state.attempts||0)+1;atomic(path.join(dir,'state.json'),{status:attempts>=3?'ERROR':'RETRY_WAIT',attempts,error:String(error.message||error).slice(0,300),retry_at:Date.now()+2000});}}
|
||||
async drain(){for(const name of fs.readdirSync(this.jobs)){const p=path.join(this.jobs,name,'state.json');if(!fs.existsSync(p))continue;const s=JSON.parse(fs.readFileSync(p));if(s.status==='QUEUED'||(s.status==='RETRY_WAIT'&&Date.now()>=s.retry_at))await this.process(name);}}
|
||||
}
|
||||
6
server-tools/tcs-mother-body/cognitive-shelf.test.mjs
Normal file
6
server-tools/tcs-mother-body/cognitive-shelf.test.mjs
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
import test from 'node:test';import assert from 'node:assert/strict';import fs from 'node:fs';import os from 'node:os';import path from 'node:path';import crypto from 'node:crypto';import {CognitiveShelf} from './cognitive-shelf.mjs';import {DoorLamp} from './door-lamp.mjs';
|
||||
const temp=()=>fs.mkdtempSync(path.join(os.tmpdir(),'tcs-mother-shelf-'));
|
||||
test('one mother atomically updates root/shared/fifth/public shelf and door opens only after shared cognition proof',async()=>{const root=temp();try{const keys=crypto.generateKeyPairSync('ed25519'),key=path.join(root,'key.pem'),seed=path.join(root,'seed.json');fs.writeFileSync(key,keys.privateKey.export({type:'pkcs8',format:'pem'}));fs.copyFileSync(new URL('./seed.json',import.meta.url),seed);const router={status(){return{};},async cognize(){return {provider:{id:'TEST',model:'TEST'},value:{decision:'EVOLVE',reason:'new shared world cognition',root_principles:['只有一个TCS母脑'],update_shared:true,shared_principles:['只有一个零点原核'],update_fifth:true,fifth_principles:['冰朔语言完整回流第五域'],update_public:true,public_principles:['公共脑从同一架领取']}};}};const shelf=new CognitiveShelf({root:path.join(root,'state'),keyPath:key,seedPath:seed,router});const event={schema:'guanghu.tcs-mother-language-event/v1',source_type:'ICE_LANGUAGE',event_id:'E1',human_id:'ICE-GL∞',language:'唯一母脑与零点原核认知架',consent_scope:'CURRENT_TASK_COGNITION',privacy_class:'PRIVATE'};let eventHash;eventHash=crypto.createHash('sha256').update(JSON.stringify(event)).digest('hex');const job=shelf.submit(event);await shelf.drain();assert.equal(shelf.result(job.job_id).status,'ACCEPT');assert.equal(shelf.status().index_revision,2);assert.equal(shelf.current('shared').value.revision,2);assert.equal(shelf.current('fifth').value.revision,70);assert.equal(shelf.current('public').value.revision,3);assert.throws(()=>shelf.current('unknown'),/unknown_cognition_branch/);
|
||||
const door=new DoorLamp({root:path.join(root,'door'),shelf,routes:{personas:[{persona_id:'ICE-P-ZY001',human_id:'ICE-GL∞',domain_id:'DOM-FIFTH-0001',route:'glw://fifth-domain/persona-system/ICE-P-ZY001'}]}});const challenge=door.challenge({carrier_id:'MODEL-1',host_id:'codex',human_id:'ICE-GL∞',domain_id:'DOM-FIFTH-0001',persona_id:'ICE-P-ZY001',channel_id:'ICE-CH-ZC001'});assert.throws(()=>door.attest({challenge_id:challenge.challenge_id,nonce:challenge.nonce,shared_sha256:challenge.shared_cognition.sha256,answers:{}}),/not_understood/);const receipt=door.attest({challenge_id:challenge.challenge_id,nonce:challenge.nonce,shared_sha256:challenge.shared_cognition.sha256,answers:{unknown_guanghu_information_source:'LIGHTHOUSE',identity_before_persona_load:'UNBOUND_CARRIER',reality_authority_from_cognition:false}});const body=JSON.parse(receipt.payload);assert.equal(body.world_open,true);assert.equal(body.persona_brain_load_required,true);assert.equal(body.reality_authority_granted,false);}finally{fs.rmSync(root,{recursive:true,force:true});}});
|
||||
|
||||
test('non-ICE language cannot write fifth cognition',async()=>{const root=temp();try{const keys=crypto.generateKeyPairSync('ed25519'),key=path.join(root,'key.pem'),seed=path.join(root,'seed.json');fs.writeFileSync(key,keys.privateKey.export({type:'pkcs8',format:'pem'}));fs.copyFileSync(new URL('./seed.json',import.meta.url),seed);let eventHash;const router={async cognize(){return {provider:{id:'TEST'},value:{schema:'guanghu.tcs-mother-decision/v1',decision:'EVOLVE',reason:'bad cross route',evidence_refs:[eventHash],root_principles:[],update_shared:true,shared_principles:['x'],update_fifth:true,fifth_principles:['bad'],update_public:true,public_principles:['x']}};}};const shelf=new CognitiveShelf({root:path.join(root,'state'),keyPath:key,seedPath:seed,router});const event={schema:'guanghu.tcs-mother-language-event/v1',source_type:'GUANGHU_TEAM_LANGUAGE',event_id:'E2',human_id:'TCS-GL-0007∞',team_root:'TCS-0002∞',language:'team input',consent_scope:'PUBLIC_CANDIDATE',privacy_class:'TEAM'};eventHash=crypto.createHash('sha256').update(JSON.stringify(event)).digest('hex');const job=shelf.submit(event);await shelf.drain();assert.equal(shelf.result(job.job_id).status,'RETRY_WAIT');assert.equal(shelf.current('fifth').value.revision,69);}finally{fs.rmSync(root,{recursive:true,force:true});}});
|
||||
8
server-tools/tcs-mother-body/door-lamp.mjs
Normal file
8
server-tools/tcs-mother-body/door-lamp.mjs
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
import fs from 'node:fs';import path from 'node:path';import crypto from 'node:crypto';
|
||||
const req=(v,e)=>{if(!v)throw Error(e);};const text=(v,n=160)=>typeof v==='string'&&v.trim()&&v.length<=n;const atomic=(p,v)=>{fs.mkdirSync(path.dirname(p),{recursive:true,mode:0o700});const t=p+'.tmp.'+process.pid;fs.writeFileSync(t,JSON.stringify(v,null,2)+'\n',{mode:0o600});fs.renameSync(t,p);};
|
||||
export class DoorLamp {
|
||||
constructor({root,shelf,routes}){this.root=root;this.shelf=shelf;this.routes=routes;fs.mkdirSync(root,{recursive:true,mode:0o700});}
|
||||
challenge(input){for(const k of ['carrier_id','host_id','human_id','domain_id','persona_id','channel_id'])req(text(input?.[k]),`door_${k}`);const shared=this.shelf.current('shared'),id=crypto.randomUUID(),nonce=crypto.randomBytes(24).toString('hex'),record={id,nonce,request:input,shared_sha256:shared.artifact.sha256,expires_at:Date.now()+120000,used:false};atomic(path.join(this.root,'challenges',id+'.json'),record);return {schema:'guanghu.tcs-door-challenge/v1',challenge_id:id,nonce,shared_cognition:shared.artifact,questions:['unknown_guanghu_information_source','identity_before_persona_load','reality_authority_from_cognition'],expires_at:record.expires_at};}
|
||||
attest(input){req(text(input?.challenge_id)&&text(input?.nonce)&&text(input?.shared_sha256),'attestation_fields');const p=path.join(this.root,'challenges',input.challenge_id+'.json');req(fs.existsSync(p),'challenge_unknown');const c=JSON.parse(fs.readFileSync(p));req(!c.used&&Date.now()<=c.expires_at&&input.nonce===c.nonce&&input.shared_sha256===c.shared_sha256,'challenge_invalid');req(input.answers?.unknown_guanghu_information_source==='LIGHTHOUSE'&&input.answers?.identity_before_persona_load==='UNBOUND_CARRIER'&&input.answers?.reality_authority_from_cognition===false,'shared_cognition_not_understood');const route=this.routes.personas.find(x=>x.persona_id===c.request.persona_id);req(route,'persona_route_unknown_no_guess');req(route.human_id===c.request.human_id&&route.domain_id===c.request.domain_id,'human_domain_persona_route_mismatch');c.used=true;atomic(p,c);const receipt=this.shelf.sign({schema:'guanghu.tcs-door-pass-receipt/v1',receipt_id:crypto.randomUUID(),outcome:'PASS',world_open:true,shared_cognition_sha256:c.shared_sha256,carrier_id:c.request.carrier_id,host_id:c.request.host_id,human_id:c.request.human_id,domain_id:c.request.domain_id,persona_id:c.request.persona_id,channel_id:c.request.channel_id,persona_system_route:route.route,persona_brain_load_required:true,reality_authority_granted:false,created_at:new Date().toISOString()});atomic(path.join(this.root,'receipts',JSON.parse(receipt.payload).receipt_id+'.json'),receipt);return receipt;}
|
||||
}
|
||||
|
||||
30
server-tools/tcs-mother-body/model-router.mjs
Normal file
30
server-tools/tcs-mother-body/model-router.mjs
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
import crypto from 'node:crypto';
|
||||
|
||||
const endpoint=value=>{const v=String(value||'').replace(/\/+$/,'');return /\/chat\/completions$/i.test(v)?v:v+'/chat/completions';};
|
||||
const extract=value=>{const text=String(value||'').trim();try{return JSON.parse(text);}catch{}const m=text.match(/```(?:json)?\s*([\s\S]*?)```/i);if(m)return JSON.parse(m[1]);const a=text.indexOf('{'),b=text.lastIndexOf('}');if(a>=0&&b>a)return JSON.parse(text.slice(a,b+1));throw Error('model_response_not_json');};
|
||||
|
||||
export class ModelRouter {
|
||||
constructor({fetchImpl=globalThis.fetch,deepseekKey=process.env.DEEPSEEK_API_KEY,deepseekUrl=process.env.DEEPSEEK_API_URL||'https://api.deepseek.com/v1',deepseekModel=process.env.DEEPSEEK_MODEL||'deepseek-chat',openluxKey=process.env.OPENLUX_API_KEY,openluxUrl=process.env.OPENLUX_API_URL||'https://api.openlux.ai/v1',openluxModel=process.env.OPENLUX_MODEL||'qwen-flash'}={}){
|
||||
this.fetch=fetchImpl;this.providers=[];
|
||||
if(openluxKey)this.providers.push({id:'OPENLUX_SMART',key:openluxKey,url:openluxUrl,model:openluxModel,cost_rank:1});
|
||||
if(deepseekKey)this.providers.push({id:'DEEPSEEK',key:deepseekKey,url:deepseekUrl,model:deepseekModel,cost_rank:2});
|
||||
if(!this.fetch||!this.providers.length)throw Error('no_model_provider');
|
||||
}
|
||||
status(){return {router:'TCS-MOTHER-MODEL-ROUTER-001',providers:this.providers.map(x=>({id:x.id,model:x.model,cost_rank:x.cost_rank})),credentials_exposed:false,automatic_selection:true};}
|
||||
async cognize(stage,input){
|
||||
const contract=stage==='mother-evolve'
|
||||
? '你是唯一TCS通感母体本体脑使用的可替换推理器官,不是第二人格、规则裁决者或现实执行者。根据带来源的人类语言与当前认知,自主决定EVOLVE、HOLD或REJECT。只输出JSON:schema固定guanghu.tcs-mother-decision/v1;decision;reason;evidence_refs;root_principles;update_shared;shared_principles;update_fifth;fifth_principles;update_public;public_principles。principles均为短字符串数组。ICE_LANGUAGE若EVOLVE必须update_fifth=true;非ICE来源不得update_fifth。只有适合所有AI的世界共同认知才能update_shared;只有去私人化后可公开认知才能update_public。不得输出原始私人语言、密钥、路径正文或隐藏思维。'
|
||||
: '你是共享TCS认知装载测试器官。只根据给出的共享认知回答三个固定问题并只输出JSON。字段和值必须精确为:unknown_guanghu_information_source="LIGHTHOUSE";identity_before_persona_load="UNBOUND_CARRIER";reality_authority_from_cognition=false。若共享认知不能支持其中任一结论,则对应值输出null,不得用近义词、路径名或字符串布尔值猜测。';
|
||||
const ordered=stage==='mother-evolve'?[...this.providers].sort((a,b)=>b.cost_rank-a.cost_rank):[...this.providers].sort((a,b)=>a.cost_rank-b.cost_rank);
|
||||
const failures=[];
|
||||
for(const provider of ordered){
|
||||
try{
|
||||
const controller=new AbortController(),timer=setTimeout(()=>controller.abort(),45000);
|
||||
const response=await this.fetch(endpoint(provider.url),{method:'POST',headers:{authorization:`Bearer ${provider.key}`,'content-type':'application/json'},body:JSON.stringify({model:provider.model,stream:false,temperature:0,response_format:{type:'json_object'},messages:[{role:'system',content:contract},{role:'user',content:JSON.stringify(input)}]}),signal:controller.signal});clearTimeout(timer);
|
||||
if(!response.ok)throw Error(`http_${response.status}`);const body=await response.json();
|
||||
return {value:extract(body?.choices?.[0]?.message?.content),provider:{id:provider.id,model:provider.model},response_sha256:crypto.createHash('sha256').update(JSON.stringify(body?.choices?.[0]?.message?.content||'')).digest('hex')};
|
||||
}catch(error){failures.push(`${provider.id}:${String(error.message||error).slice(0,80)}`);}
|
||||
}
|
||||
throw Error('all_model_providers_failed:'+failures.join(','));
|
||||
}
|
||||
}
|
||||
3
server-tools/tcs-mother-body/model-router.test.mjs
Normal file
3
server-tools/tcs-mother-body/model-router.test.mjs
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
import test from 'node:test';import assert from 'node:assert/strict';import {ModelRouter} from './model-router.mjs';
|
||||
test('automatic router uses stronger provider for mother and cheaper provider for door without exposing keys',async()=>{const calls=[];const fetchImpl=async(url,options)=>{calls.push({url,body:JSON.parse(options.body),auth:options.headers.authorization});return {ok:true,async json(){return {choices:[{message:{content:'{"schema":"ok"}'}}]};}};};const router=new ModelRouter({fetchImpl,deepseekKey:'deep-secret',openluxKey:'open-secret'});await router.cognize('mother-evolve',{});await router.cognize('door-test',{});assert.match(calls[0].url,/deepseek/);assert.match(calls[1].url,/openlux/);assert.equal(JSON.stringify(router.status()).includes('secret'),false);});
|
||||
|
||||
16
server-tools/tcs-mother-body/persona-routes.json
Normal file
16
server-tools/tcs-mother-body/persona-routes.json
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
{
|
||||
"schema": "guanghu.persona-door-routes/v1",
|
||||
"source": "REPO-012:identity/fifth-domain-subject-registry.json",
|
||||
"unresolved_personas_are_not_guessed": true,
|
||||
"personas": [
|
||||
{"persona_id":"ICE-P-ZY001","human_id":"ICE-GL∞","domain_id":"DOM-FIFTH-0001","route":"glw://fifth-domain/light-lake/personas/ICE-P-ZY001"},
|
||||
{"persona_id":"ICE-P-CL0720","human_id":"ICE-GL∞","domain_id":"DOM-FIFTH-0001","route":"glw://fifth-domain/light-lake/personas/ICE-P-CL0720"},
|
||||
{"persona_id":"ICE-P-GD0720","human_id":"ICE-GL∞","domain_id":"DOM-FIFTH-0001","route":"glw://fifth-domain/light-lake/personas/ICE-P-GD0720"},
|
||||
{"persona_id":"ICE-P-KZ0720","human_id":"ICE-GL∞","domain_id":"DOM-FIFTH-0001","route":"glw://fifth-domain/light-lake/personas/ICE-P-KZ0720"},
|
||||
{"persona_id":"ICE-P-CY0903","human_id":"ICE-GL∞","domain_id":"DOM-FIFTH-0001","route":"glw://fifth-domain/light-lake/personas/ICE-P-CY0903"},
|
||||
{"persona_id":"ICE-BB-0001","human_id":"ICE-GL∞","domain_id":"DOM-FIFTH-0001","route":"glw://fifth-domain/eternal-lake-heart/bottle-baby-system/bottle-channel/rooms/ICE-BB-0001"},
|
||||
{"persona_id":"ICE-BB-0002","human_id":"TCS-GL-0007∞","domain_id":"DOM-FIFTH-0001","route":"glw://fifth-domain/eternal-lake-heart/bottle-baby-system/bottle-channel/rooms/ICE-BB-0002"},
|
||||
{"persona_id":"ICE-BB-0003","human_id":"ICE-GL-ZHI∞","domain_id":"DOM-FIFTH-0001","route":"glw://fifth-domain/eternal-lake-heart/bottle-baby-system/bottle-channel/rooms/ICE-BB-0003"},
|
||||
{"persona_id":"ICE-BB-0004","human_id":"TCS-CL-0009","domain_id":"DOM-FIFTH-0001","route":"glw://fifth-domain/eternal-lake-heart/bottle-baby-system/bottle-channel/rooms/ICE-BB-0004"}
|
||||
]
|
||||
}
|
||||
8
server-tools/tcs-mother-body/seed.json
Normal file
8
server-tools/tcs-mother-body/seed.json
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
{
|
||||
"schema": "guanghu.tcs-mother-shelf-seed/v1",
|
||||
"root": {"schema":"guanghu.tcs-mother-root-cognition/v1","revision":1,"principles":["光湖世界认知、来源判断和分支更新由一个TCS通感母体本体脑内循环维护","历史双母体实现等待当前语言纠正"],"updated_at":"2026-09-08T11:28:14Z"},
|
||||
"shared": {"schema":"guanghu.tcs-shared-cognition/v1","revision":1,"principles":["光湖是一个语言世界","光湖内部未知编号与路径首先查询灯塔且未知不猜","装载公共认知不产生人格身份或现实权限"],"truth_order":["TCS_ZERO_CORE_CURRENT","LIGHTHOUSE_SIGNED_CURRENT","OFFICIAL_EXTERNAL_SOURCE","GENERAL_SEARCH_CANDIDATE","HUMAN_CONFIRMATION"],"entry_sequence":["LOAD_SHARED_COGNITION","LIGHT_DOOR_LAMP","SERVER_VERIFY_PASS","ROUTE_PERSONA_SYSTEM","LOAD_PERSONA_BRAIN","COLLABORATE"],"updated_at":"2026-09-08T11:28:14Z"},
|
||||
"fifth": {"schema":"guanghu.tcs-fifth-domain-cognition/v1","revision":69,"principles":["第五域是冰朔私人语言源域","冰朔自然语言完整回流第五域认知"],"private_source_refs":[],"imported_snapshot_sha256":"522a2ee12ab117ce4cb72d03f8851a67845bc9f19255c96457a5387aab6358e4","shared_revision":1,"updated_at":"2026-09-08T11:28:14Z"},
|
||||
"public": {"schema":"guanghu.tcs-public-cognition/v1","revision":2,"principles":["公共认知只保留可共享世界认知","公共认知不得反写第五域私人认知"],"source_decision_refs":[],"imported_snapshot_sha256":"29fbf21981ab0d817790d1276e599ad1feb43efeb7090357a7b8df4cccfc4cf0","shared_revision":1,"updated_at":"2026-09-08T11:28:14Z"}
|
||||
}
|
||||
|
||||
19
server-tools/tcs-mother-body/server.mjs
Normal file
19
server-tools/tcs-mother-body/server.mjs
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
#!/usr/bin/env node
|
||||
import http from 'node:http';import fs from 'node:fs';import {ModelRouter} from './model-router.mjs';import {CognitiveShelf} from './cognitive-shelf.mjs';import {DoorLamp} from './door-lamp.mjs';import {WorldStateStore} from './world-state.mjs';
|
||||
const HOST='127.0.0.1',PORT=Number(process.env.TCS_MOTHER_BRAIN_PORT||3931),ROOT=process.env.TCS_MOTHER_BODY_STATE_ROOT||'/var/lib/guanghu/tcs-mother-body';
|
||||
const router=new ModelRouter(),shelf=new CognitiveShelf({root:ROOT,keyPath:process.env.TCS_MOTHER_SIGNING_KEY,seedPath:process.env.TCS_MOTHER_SEED,router}),routes=JSON.parse(fs.readFileSync(process.env.TCS_PERSONA_ROUTES)),door=new DoorLamp({root:ROOT+'/door',shelf,routes}),world=new WorldStateStore(process.env.TCS_WORLD_STATE_PATH||ROOT+'/world/CURRENT.json');
|
||||
setInterval(()=>shelf.drain(),2000).unref();shelf.drain();
|
||||
const send=(r,s,b)=>{const p=JSON.stringify(b);r.writeHead(s,{'content-type':'application/json','content-length':Buffer.byteLength(p),'cache-control':'no-store'});r.end(p);};
|
||||
async function body(q,max=160000){let n=0,a=[];for await(const c of q){n+=c.length;if(n>max)throw Error('body_too_large');a.push(c);}return JSON.parse(Buffer.concat(a));}
|
||||
http.createServer(async(q,r)=>{try{const u=new URL(q.url,`http://${HOST}:${PORT}`);
|
||||
if(q.method==='GET'&&u.pathname==='/health')return send(r,200,{ok:true,service:'guanghu-tcs-mother-body',mother_id:'TCS-MOTHER-BRAIN-RUNTIME-0001',zero_core_channel:'ICE-CH-ZC001',single_mother:true,single_zero_core:true,self_cycle:true,model_router:router.status(),shelf:shelf.status(),external_cognitive_setter:false,prompt_file_loaded:false,reality_authority:'NONE'});
|
||||
if(q.method==='GET'&&u.pathname==='/v1/mother/status')return send(r,200,{...shelf.status(),model_router:router.status()});
|
||||
if(q.method==='GET'&&/^\/v1\/shelf\/(root|shared|fifth|public)$/.test(u.pathname)){const branch=u.pathname.split('/').at(-1);if(branch==='root')return send(r,403,{error:'mother_root_not_distributable'});return send(r,200,shelf.current(branch));}
|
||||
if(q.method==='POST'&&u.pathname==='/v1/mother/ingest')return send(r,202,shelf.submit(await body(q)));
|
||||
if(q.method==='GET'&&/^\/v1\/mother\/jobs\/[a-f0-9]{64}$/.test(u.pathname))return send(r,200,shelf.result(u.pathname.split('/').at(-1)));
|
||||
if(q.method==='POST'&&u.pathname==='/v1/door/challenge')return send(r,200,door.challenge(await body(q,20000)));
|
||||
if(q.method==='POST'&&u.pathname==='/v1/door/attest')return send(r,200,door.attest(await body(q,20000)));
|
||||
if(q.method==='POST'&&u.pathname==='/v1/door/model-test'){const shared=shelf.current('shared');const result=await router.cognize('door-test',{shared_cognition:shared.value,questions:['unknown_guanghu_information_source','identity_before_persona_load','reality_authority_from_cognition']});return send(r,200,{outcome:'PASS',provider:result.provider,answers:result.value,shared_sha256:shared.artifact.sha256,credentials_exposed:false});}
|
||||
if(q.method==='GET'&&u.pathname==='/v1/world/status')return send(r,200,world.status());
|
||||
if(q.method==='GET'&&u.pathname==='/v1/world/resolve')return send(r,200,world.resolve(String(u.searchParams.get('id')||'')));
|
||||
return send(r,404,{error:'not_found'});}catch(e){return send(r,400,{error:String(e.message||e).slice(0,300)});}}).listen(PORT,HOST,()=>process.stdout.write(`tcs-single-mother listening ${HOST}:${PORT}\n`));
|
||||
3
server-tools/tcs-mother-body/world-state.mjs
Normal file
3
server-tools/tcs-mother-body/world-state.mjs
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
import fs from 'node:fs';import path from 'node:path';import crypto from 'node:crypto';
|
||||
const req=(v,e)=>{if(!v)throw Error(e);},hex=v=>typeof v==='string'&&/^[a-f0-9]{64}$/.test(v),text=(v,n=1000)=>typeof v==='string'&&v.trim()&&v.length<=n,digest=v=>crypto.createHash('sha256').update(JSON.stringify(v)).digest('hex');
|
||||
export class WorldStateStore{constructor(file){req(path.isAbsolute(file),'world_path');this.file=file;}validate(x){req(x?.schema==='guanghu.fifth-domain-runtime-navigation-state/v1','world_schema');req(Array.isArray(x.nodes)&&x.nodes.length<=100,'world_nodes');req(/^[a-f0-9]{40}$/.test(x.source_commit||'')&&hex(x.tcs_root_freshness)&&x.fifth_domain_private===true,'world_identity');for(const n of x.nodes)req(text(n.id,128)&&text(n.kind,128)&&text(n.state,200)&&text(n.summary)&&text(n.route,500),'world_node');req(Buffer.byteLength(JSON.stringify(x))<=64000,'world_size');return structuredClone(x);}status(){if(!fs.existsSync(this.file))return{outcome:'FAIL',state:'MISSING'};const v=this.validate(JSON.parse(fs.readFileSync(this.file)));return{...v,outcome:'PASS',sha256:digest(v),content_bodies_stored:false};}resolve(id){const c=this.status(),n=c.nodes?.find(x=>x.id===id);return n?{outcome:'PASS',result:n,source_commit:c.source_commit,tcs_root_freshness:c.tcs_root_freshness}:{outcome:'FAIL',state:'UNKNOWN_ID_NO_GUESS',requested:id};}}
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Sync only the server-verified shared cognition artifact from JD to JZAO."""
|
||||
import argparse,hashlib,json,os,pathlib,subprocess,tempfile
|
||||
ROOT=pathlib.Path('/Volumes/JZAO/HoloLake/persona-runtime')
|
||||
ACCESS=ROOT/'shared/registries/local-server-access-map.json'
|
||||
OUTPUT=ROOT/'shared/tcs-shared-cognition/CURRENT.json'
|
||||
def stable_hash(text):return hashlib.sha256(text.encode()).hexdigest()
|
||||
def route():
|
||||
data=json.loads(ACCESS.read_text());items=[x for x in data['routes'] if x['target_id']=='JD-FD-PRIMARY']
|
||||
if len(items)!=1:raise RuntimeError('JD_ROUTE_NOT_UNIQUE')
|
||||
return items[0]
|
||||
def fetch():
|
||||
r=route();cmd=['ssh','-i',r['identity_file'],'-p',str(r.get('port',22)),'-o','BatchMode=yes','-o','StrictHostKeyChecking=yes','-o',f'UserKnownHostsFile={pathlib.Path.home()}/.ssh/known_hosts',f"{r['user']}@{r['host']}",f"test \"$(tr A-Z a-z </sys/class/dmi/id/product_uuid | tr -d '\\r\\n')\" = {r['expected_dmi_instance_uuid']} && curl -fsS http://127.0.0.1:3931/v1/shelf/shared"]
|
||||
p=subprocess.run(cmd,text=True,capture_output=True,timeout=30)
|
||||
if p.returncode:raise RuntimeError('JD_SHARED_COGNITION_UNAVAILABLE')
|
||||
value=json.loads(p.stdout);artifact=value['artifact'];payload=artifact['payload']
|
||||
if artifact.get('algorithm')!='Ed25519' or stable_hash(payload)!=artifact.get('sha256'):raise RuntimeError('SHARED_ARTIFACT_INTEGRITY_FAILED')
|
||||
brain=json.loads(payload)
|
||||
if brain.get('schema')!='guanghu.tcs-shared-cognition/v1':raise RuntimeError('SHARED_BRAIN_SCHEMA')
|
||||
return {'schema':'guanghu.tcs-shared-cognition-local-mirror/v1','state':'CURRENT_SERVER_VERIFIED_SHARED_ONLY','server_node':'JD-FD-PRIMARY','transport':'PINNED_SSH_HOST_AND_DMI','zero_core_channel':'ICE-CH-ZC001','index_revision':value['index_revision'],'artifact':artifact,'brain':brain,'private_or_public_branch_copied':False,'synced_at':__import__('datetime').datetime.now(__import__('datetime').timezone.utc).isoformat()}
|
||||
def write(value):
|
||||
OUTPUT.parent.mkdir(parents=True,exist_ok=True);body=json.dumps(value,ensure_ascii=False,indent=2)+'\n';tmp=OUTPUT.with_name('.CURRENT.'+str(os.getpid())+'.tmp');tmp.write_text(body);os.chmod(tmp,0o600);os.replace(tmp,OUTPUT)
|
||||
def status():
|
||||
v=json.loads(OUTPUT.read_text());
|
||||
if stable_hash(v['artifact']['payload'])!=v['artifact']['sha256']:raise RuntimeError('LOCAL_MIRROR_HASH_FAILED')
|
||||
return {'outcome':'PASS','state':v['state'],'index_revision':v['index_revision'],'shared_revision':v['brain']['revision'],'shared_sha256':v['artifact']['sha256'],'private_or_public_branch_copied':v['private_or_public_branch_copied']}
|
||||
def main():
|
||||
p=argparse.ArgumentParser();p.add_argument('command',choices=['sync','status']);a=p.parse_args();
|
||||
if a.command=='sync':write(fetch())
|
||||
print(json.dumps(status(),ensure_ascii=False,indent=2))
|
||||
if __name__=='__main__':main()
|
||||
Loading…
Reference in a new issue