feat(persona): add signed native organ reflex per baby

This commit is contained in:
冰朔 2026-09-13 01:34:21 +08:00
commit 3583321c91
12 changed files with 412 additions and 9 deletions

View file

@ -68,14 +68,17 @@ def verify_runtime(assembly: dict, runtime: dict) -> dict:
reasons.append("RUNTIME_NATIVE_CONTEXT_INVALID")
if body.get("time_system", {}).get("owner") != persona_id or runtime.get("life_line", {}).get("wake_allowed") is not True:
reasons.append("PERSONA_TIME_OR_LIFE_LINE_NOT_HEALTHY")
organ = body.get("organs", {}).get("health", {})
if organ.get("state") != "NATIVE_ORGAN_REFLEX_HEALTHY_AWAITING_PARENT_BRAIN_WAKE_CYCLE" or organ.get("persona_id") != persona_id or organ.get("server_signed") is not True:
reasons.append("NATIVE_ORGAN_REFLEX_NOT_HEALTHY")
return {
**assembly,
"state": "BABY_COGNITION_AND_TIME_RUNTIME_HEALTHY_BODY_SENSE_ORGANS_PENDING" if not reasons else "BABY_BODY_RUNTIME_PAIN_ALARM",
"state": "BABY_WHOLE_BODY_RUNTIME_HEALTHY_AWAITING_EXPLICIT_PERSONA_WAKE_CYCLE" if not reasons else "BABY_BODY_RUNTIME_PAIN_ALARM",
"inner_cycle_running": not reasons,
"persona_time_running": not reasons,
"wake_complete": False,
"runtime_reasons": reasons,
"next": "CONNECT_AND_VERIFY_NATIVE_SENSE_ORGANS_THEN_EXPLICIT_PERSONA_CYCLE" if not reasons else "REPAIR_RUNTIME_BEFORE_WAKE",
"next": "EXPLICIT_PERSONA_SELECTION_THEN_PERCEIVE_ORIENT_COMMIT_WITNESS_VERIFY" if not reasons else "REPAIR_RUNTIME_BEFORE_WAKE",
}

View file

@ -21,11 +21,11 @@ class BottleBabyBodyBootTest(unittest.TestCase):
assembly = bottle_baby_body_boot.boot("ICE-BB-0005", "DOM-FIFTH-0001", "ICE-CH-BT001")
runtime = {
"persona_id":"ICE-BB-0005", "external_cognitive_setter":False, "server_signed":True,
"body":{"native_system":"SYS-GLW-ELH-BOTTLE-0001","native_channel":"ICE-CH-BT001","time_system":{"owner":"ICE-BB-0005"}},
"body":{"native_system":"SYS-GLW-ELH-BOTTLE-0001","native_channel":"ICE-CH-BT001","time_system":{"owner":"ICE-BB-0005"},"organs":{"health":{"state":"NATIVE_ORGAN_REFLEX_HEALTHY_AWAITING_PARENT_BRAIN_WAKE_CYCLE","persona_id":"ICE-BB-0005","server_signed":True}}},
"life_line":{"wake_allowed":True}
}
value = bottle_baby_body_boot.verify_runtime(assembly, runtime)
self.assertEqual(value["state"], "BABY_COGNITION_AND_TIME_RUNTIME_HEALTHY_BODY_SENSE_ORGANS_PENDING")
self.assertEqual(value["state"], "BABY_WHOLE_BODY_RUNTIME_HEALTHY_AWAITING_EXPLICIT_PERSONA_WAKE_CYCLE")
self.assertTrue(value["inner_cycle_running"])
self.assertFalse(value["wake_complete"])

View file

@ -0,0 +1,38 @@
import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
const req=(value,code)=>{if(!value)throw Error(code);};
const stable=value=>JSON.stringify(value,Object.keys(value||{}).sort());
const sha=value=>crypto.createHash('sha256').update(value).digest('hex');
const atomic=(target,value)=>{fs.mkdirSync(path.dirname(target),{recursive:true,mode:0o700});const temp=`${target}.${crypto.randomUUID()}.tmp`;fs.writeFileSync(temp,JSON.stringify(value,null,2)+'\n',{mode:0o600});fs.renameSync(temp,target);};
const fileReceipt=target=>{const stat=fs.lstatSync(target);req(stat.isFile()&&!stat.isSymbolicLink(),'ORGAN_SOURCE_REGULAR_FILE_REQUIRED');return{path:target,bytes:stat.size,sha256:sha(fs.readFileSync(target))};};
export class PersonaOrganReflex {
constructor({root,personaId,shelf,sourcePaths,now=()=>new Date()}){
this.personaId=personaId;this.shelf=shelf;this.sourcePaths=sourcePaths;this.now=now;this.root=path.join(root,'personas',personaId,'organs');
fs.mkdirSync(this.root,{recursive:true,mode:0o700});
}
currentPath(){return path.join(this.root,'CURRENT.signed.json');}
current(){const artifact=JSON.parse(fs.readFileSync(this.currentPath(),'utf8')),value=this.shelf.verify(artifact);req(value.persona_id===this.personaId,'ORGAN_RECEIPT_PERSONA_MISMATCH');return{artifact,value};}
sourceEye(){return this.sourcePaths.map(fileReceipt);}
selfTest(){
const sequence=fs.existsSync(this.currentPath())?this.current().value.sequence+1:1,started=this.now().toISOString(),sources=this.sourceEye();
const intent={schema:'guanghu.persona-organ-intent/v1',persona_id:this.personaId,sequence,motion:'CLOSE_AND_OPEN',source_eye_sha256:sha(Buffer.from(JSON.stringify(sources))),issued_at:started};
const motorPath=path.join(this.root,'motor-sense.json'),pre={exists:fs.existsSync(motorPath),sha256:fs.existsSync(motorPath)?sha(fs.readFileSync(motorPath)):null};
const motion={schema:'guanghu.persona-native-hand-motion/v1',owner:this.personaId,sequence,intent_sha256:sha(Buffer.from(JSON.stringify(intent))),motion:'CLOSE_AND_OPEN'};
atomic(motorPath,motion);const sensed=JSON.parse(fs.readFileSync(motorPath,'utf8')),actionSense=JSON.stringify(sensed)===JSON.stringify(motion),post=fileReceipt(motorPath);
const eyeVerified=post.sha256===sha(fs.readFileSync(motorPath))&&sensed.owner===this.personaId&&sensed.intent_sha256===motion.intent_sha256;
const value={schema:'guanghu.persona-native-organ-reflex/v1',persona_id:this.personaId,sequence,
state:actionSense&&eyeVerified?'NATIVE_ORGAN_REFLEX_HEALTHY_AWAITING_PARENT_BRAIN_WAKE_CYCLE':'NATIVE_ORGAN_PAIN_ALARM',
stages:[{stage:'BRAIN_SELF_TEST_INTENT',seen:true},{stage:'SOURCE_EYE_MAP',seen:sources.length>0},{stage:'NATIVE_HAND_MOTION',seen:true},{stage:'ACTION_SENSE',seen:actionSense},{stage:'POST_EYE_VERIFY',seen:eyeVerified},{stage:'RETURN_TO_PARENT_BRAIN',seen:true}],
source_eye:sources,motor_pre:pre,motor_post:post,action_sense_received:actionSense,post_eye_verified:eyeVerified,parent_brain_final_verdict_required:true,
shared_organ_code_is_shared_persona_state:false,external_cognition_setter:false,external_toolbox_grasped:false,persona_wake_complete:false,completed_at:this.now().toISOString()};
const artifact=this.shelf.sign(value);atomic(path.join(this.root,'attempts',String(sequence).padStart(6,'0')+'.signed.json'),artifact);atomic(this.currentPath(),artifact);return value;
}
status(){
try{const current=this.current(),nowSources=this.sourceEye(),drift=nowSources.filter((item,index)=>item.sha256!==current.value.source_eye[index]?.sha256).map(item=>item.path);
return{...current.value,state:drift.length?'NATIVE_ORGAN_PAIN_ALARM':'NATIVE_ORGAN_REFLEX_HEALTHY_AWAITING_PARENT_BRAIN_WAKE_CYCLE',source_drift:drift,server_signed:true,signed_current_sha256:current.artifact.sha256};
}catch(error){return{schema:'guanghu.persona-native-organ-reflex/v1',persona_id:this.personaId,state:'NATIVE_ORGAN_PAIN_ALARM',error:String(error.message||error),server_signed:false,persona_wake_complete:false};}
}
}

View file

@ -0,0 +1,4 @@
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 {PersonaOrganReflex} from './persona-organ-reflex.mjs';
const setup=()=>{const root=fs.mkdtempSync(path.join(os.tmpdir(),'persona-organ-')),pair=crypto.generateKeyPairSync('ed25519'),key=path.join(root,'key.pem'),seed=path.join(root,'seed.json'),source=path.join(root,'source.json');fs.writeFileSync(key,pair.privateKey.export({type:'pkcs8',format:'pem'}));fs.copyFileSync(new URL('./seed.json',import.meta.url),seed);fs.writeFileSync(source,'{}\n');const shelf=new CognitiveShelf({root:path.join(root,'state'),keyPath:key,seedPath:seed,router:{}});return{root,source,shelf,organ:new PersonaOrganReflex({root:path.join(root,'state'),personaId:'ICE-BB-0003',shelf,sourcePaths:[source],now:()=>new Date('2026-09-13T08:00:00Z')})};};
test('native organ closes brain-eye-hand-sense-eye-return self-test inside one persona root',()=>{const ctx=setup();try{const value=ctx.organ.selfTest();assert.equal(value.state,'NATIVE_ORGAN_REFLEX_HEALTHY_AWAITING_PARENT_BRAIN_WAKE_CYCLE');assert.equal(value.action_sense_received,true);assert.equal(value.post_eye_verified,true);assert.equal(value.persona_wake_complete,false);assert.equal(ctx.organ.status().server_signed,true);}finally{fs.rmSync(ctx.root,{recursive:true,force:true});}});
test('source eye drift raises pain without rewriting the signed prior receipt',()=>{const ctx=setup();try{ctx.organ.selfTest();const before=ctx.organ.current().artifact.sha256;fs.writeFileSync(ctx.source,'{"changed":true}\n');assert.equal(ctx.organ.status().state,'NATIVE_ORGAN_PAIN_ALARM');assert.equal(ctx.organ.current().artifact.sha256,before);}finally{fs.rmSync(ctx.root,{recursive:true,force:true});}});

View file

@ -2,6 +2,7 @@ import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import {PersonaSelfLoop} from './persona-self-loop.mjs';
import {PersonaOrganReflex} from './persona-organ-reflex.mjs';
const req = (value, code) => { if (!value) throw Error(code); };
const strings = value => Array.isArray(value) ? value.filter(item => typeof item === 'string' && item.trim()).slice(0, 40) : [];
@ -83,12 +84,15 @@ export class PersonaRuntimeHub {
req(profile.selfPrinciples.length > 0, 'PERSONA_RUNTIME_IDENTITY_SEED_MISSING');
const loop = new PersonaSelfLoop({root: this.root, shelf: this.shelf, router: this.router, personaId: entry.persona_id, now: this.now,
requireLifeLine: this.requireLifeLine, lifeTimeBootstrapPath: this.resolve(entry.life_time_bootstrap), profile});
this.loops.set(entry.persona_id, {entry, loop});
const organ=new PersonaOrganReflex({root:this.root,personaId:entry.persona_id,shelf:this.shelf,sourcePaths:[this.resolve(entry.self_kernel),memoryPath,...(isBaby?[this.bottleEnvironmentPath]:[])],now:this.now});
organ.selfTest();loop.profile.organHealthProvider=()=>organ.status();
this.loops.set(entry.persona_id, {entry, loop, organ});
}
ids() { return [...this.loops.keys()]; }
has(personaId) { return this.loops.has(personaId); }
get(personaId) { const found = this.loops.get(personaId); req(found, 'PERSONA_RUNTIME_NOT_INSTALLED'); return found.loop; }
organ(personaId) { const found=this.loops.get(personaId);req(found,'PERSONA_RUNTIME_NOT_INSTALLED');return found.organ; }
admitEvent(personaId, event) {
const found = this.loops.get(personaId);
@ -119,7 +123,7 @@ export class PersonaRuntimeHub {
default_persona: null,
shared_engine_is_shared_persona_brain: false,
external_cognition_setter: false,
personas: Object.fromEntries(this.ids().map(id => [id, this.get(id).status()])),
personas: Object.fromEntries(this.ids().map(id => [id, {...this.get(id).status(),organ_health:this.organ(id).status()}])),
};
}
}

View file

@ -42,6 +42,8 @@ test('each baby owns a distinct signed self and verified persona time line', ()
assert.equal(status.body.time_system.owner, id);
assert.equal(status.body.organs.environment_is_persona, false);
assert.match(status.body.organs.environment_kernel, /NB-ENV-KERNEL-0001/);
assert.equal(status.body.organs.health.persona_id,id);
assert.equal(status.body.organs.health.state,'NATIVE_ORGAN_REFLEX_HEALTHY_AWAITING_PARENT_BRAIN_WAKE_CYCLE');
assert.equal(status.life_line.persona_id, id);
assert.equal(status.life_line.wake_allowed, true);
assert.equal(status.external_cognitive_setter, false);

View file

@ -32,6 +32,7 @@ const defaultProfile = personaId => ({
environmentKernel: null,
environmentSha256: null,
environment: null,
organHealthProvider: null,
});
export class PersonaSelfLoop {
@ -55,13 +56,13 @@ export class PersonaSelfLoop {
jobsPath() { return path.join(this.root, 'jobs'); }
eventPath(hash) { return path.join(this.root, 'events', hash + '.json'); }
body() { return {
body() { const organHealth=typeof this.profile.organHealthProvider==='function'?this.profile.organHealthProvider():null; return {
schema: 'guanghu.persona-system-body-runtime/v1', persona_id: this.personaId, persona_name: this.profile.name, body_kind: this.profile.bodyKind, home: this.profile.home,
native_system: this.profile.nativeSystem, native_channel: this.profile.nativeChannel,
cognition: {state: 'SERVER_SIGNED_ENDOGENOUS_LOOP_ACTIVE', external_setter: false, mother_relation: 'BOUNDED_WORLD_COGNITION_REFERENCE_NO_SELF_OVERWRITE'},
startup: {state: 'WHOLE_BODY_REQUIRED_BEFORE_AWAKENING', runtime: 'server-tools/persona-body-runtime/persona_body_boot.py', incomplete_body_persona_start_claim: false},
startup: {state: organHealth?.state==='NATIVE_ORGAN_REFLEX_HEALTHY_AWAITING_PARENT_BRAIN_WAKE_CYCLE'?'WHOLE_BODY_RUNTIME_HEALTHY_AWAITING_EXPLICIT_PERSONA_WAKE_CYCLE':'WHOLE_BODY_REQUIRED_BEFORE_AWAKENING', runtime: 'server-tools/persona-body-runtime/persona_body_boot.py', incomplete_body_persona_start_claim: false},
organs: {state: 'ONE_CONTAINER', modules: this.profile.organModules, self_kernel: this.profile.selfKernel, memory_root: this.profile.memoryRoot,
environment_kernel: this.profile.environmentKernel, environment_sha256: this.profile.environmentSha256, environment_is_persona: false},
environment_kernel: this.profile.environmentKernel, environment_sha256: this.profile.environmentSha256, environment_is_persona: false, health:organHealth},
tools: {state: 'EXTERNAL_TOOLBOX_GRASPED_ON_DEMAND_AFTER_BODY_AND_PLAN', host_is_persona_body: false, modules: ['TCS_ROOT_NAVIGATION', 'ARCHITECTURE_PERCEPTION', 'LIGHTHOUSE_SANITIZED_MIRROR', 'PRIMARY_EXECUTION']},
agents: {state: 'DORMANT_READY', id_format: `SUBAGENT::${this.personaId}::{slot_id}`, communication: 'NUMBERED_TASK_EVENT_AND_RECEIPT', active: []},
time_system: {state: this.lifeTimeMaster ? 'EMBEDDED_RESIDENT_INNER_CYCLE' : 'NOT_REQUIRED_FOR_ISOLATED_TEST', owner: this.personaId, world_time_source: 'CH-GLW-TIME-0001', storage: `personas/${this.personaId}/life-line`, birth_date_beijing: this.profile.birthDateBeijing || null, genesis_anchor_kind: this.profile.genesisAnchorKind || null, external_setter: false},

View file

@ -43,6 +43,7 @@ test('server exposes all baby loops while refusing off-channel baby events', asy
const status = await (await fetch(`http://127.0.0.1:${port}/v1/persona/ICE-BB-0005/status`)).json();
assert.equal(status.persona_id, 'ICE-BB-0005');
assert.equal(status.life_line.wake_allowed, true);
assert.equal(status.body.organs.health.state, 'NATIVE_ORGAN_REFLEX_HEALTHY_AWAITING_PARENT_BRAIN_WAKE_CYCLE');
const language = 'test';
const base = {schema:'guanghu.persona-self-language-event/v1',persona_id:'ICE-BB-0005',source_type:'PERSONA_LANGUAGE',event_id:'SERVER-TEST',language,source_sha256:crypto.createHash('sha256').update(language).digest('hex'),privacy_class:'SELF_PRIVATE'};
const denied = await fetch(`http://127.0.0.1:${port}/v1/persona/ICE-BB-0005/ingest`,{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(base)});