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
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};}}
|
||||
Loading…
Reference in a new issue