feat: define Guanghu systems channels and persona body

This commit is contained in:
冰朔 2026-09-08 16:14:14 +08:00
commit c3f133ecf8
23 changed files with 562 additions and 57 deletions

View file

@ -54,6 +54,12 @@ def atomic(path: Path, value: dict[str, Any]) -> None:
os.replace(temp,path)
def persist(path: Path, value: dict[str, Any]) -> None:
value.pop("binding_sha256", None)
value["binding_sha256"] = digest(stable(value))
atomic(path, value)
def activate(event: dict[str, Any], state: Path) -> dict[str, Any]:
for k in ("parent_persona_id","session_id","channel_id","current_intent_sha256","model_runtime"):
if not isinstance(event.get(k),str) or not event[k].strip(): raise CommandError(f"REQUIRED_FIELD:{k}")
@ -64,18 +70,18 @@ def activate(event: dict[str, Any], state: Path) -> dict[str, Any]:
generation=(previous or {}).get("generation",0)+1
config=load(MAP)
team=[]
for slot in config["agent_slots"]:
for slot in [*config["agent_slots"], *config.get("treatment_slots", [])]:
team.append({
"child_agent_id":f"SUBAGENT::{event['parent_persona_id']}::{slot['slot_id']}",
"slot_id":slot["slot_id"], "agent_role":slot["agent_role"],
"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",
"deterministic_organ":slot["deterministic_organ"], "task_authority":"NONE_UNTIL_PARENT_ENVELOPE"
"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":"ACTIVE_UNDER_CURRENT_PERSONA","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,"prior_generation_invalidated":bool(previous),"credentials_stored":False,"authority_granted":False}
result["binding_sha256"]=digest(stable(result))
atomic(current_path,result)
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}
persist(current_path,result)
return result
@ -85,16 +91,43 @@ def dispatch(event: dict[str, Any], state: Path) -> dict[str, Any]:
matches=[x for x in current["team"] if x["child_agent_id"]==event.get("child_agent_id")]
if len(matches)!=1: raise CommandError("CHILD_AGENT_NOT_IN_ACTIVE_TEAM")
if not isinstance(event.get("task"),str) or not event["task"].strip(): raise CommandError("TASK_REQUIRED")
if any(x.get("runtime_state") == "ACTIVE" for x in current["team"]): raise CommandError("ANOTHER_AGENT_ALREADY_ACTIVE")
item=matches[0]
item["runtime_state"]="ACTIVE"; item["model_context_loaded"]=True
current["state"]="ONE_AGENT_ACTIVE"; current["active_agent_count"]=1
persist(state/"CURRENT.json",current)
runtime=current["model_runtime"]
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)
item=matches[0]
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")})
return {**result,"generation":current["generation"],"child_agent_id":item["child_agent_id"],"model_runtime":runtime,"model_api_invoked":True}
if runtime not in {"codex","qwen"}: raise CommandError("GATEWAY_DISPATCH_NOT_CONFIGURED")
cmd=[os.sys.executable,str(ROOT/"server-tools/persona-execution-limb-agent/persona_limb_agent.py"),"run","--persona",current["parent_persona_id"],"--task-id",event.get("task_id","SUBAGENT-TASK"),"--task",event["task"],"--runtime",runtime,"--cwd",event.get("cwd",str(ROOT))]
completed=subprocess.run(cmd,text=True,capture_output=True,timeout=240,check=False)
return {"outcome":"PASS" if completed.returncode==0 else "FAIL","generation":current["generation"],"child_agent_id":event["child_agent_id"],"model_runtime":runtime,"model_api_invoked":True,"receipt":completed.stdout[-20000:],"error":completed.stderr[-2000:]}
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")})
outcome=result["outcome"]
returned={**result,"generation":current["generation"],"child_agent_id":item["child_agent_id"],"model_runtime":runtime,"model_api_invoked":True}
else:
if runtime not in {"codex","qwen"}: raise CommandError("GATEWAY_DISPATCH_NOT_CONFIGURED")
cmd=[os.sys.executable,str(ROOT/"server-tools/persona-execution-limb-agent/persona_limb_agent.py"),"run","--persona",current["parent_persona_id"],"--task-id",event.get("task_id","SUBAGENT-TASK"),"--task",event["task"],"--runtime",runtime,"--cwd",event.get("cwd",str(ROOT))]
completed=subprocess.run(cmd,text=True,capture_output=True,timeout=240,check=False)
outcome="PASS" if completed.returncode==0 else "FAIL"
returned={"outcome":outcome,"generation":current["generation"],"child_agent_id":event["child_agent_id"],"model_runtime":runtime,"model_api_invoked":True,"receipt":completed.stdout[-20000:],"error":completed.stderr[-2000:]}
item["model_context_loaded"]=False
if outcome == "PASS":
item["runtime_state"]="DORMANT_READY"
current["state"]="READY_UNDER_CURRENT_PERSONA_NO_AGENT_RUNNING"; current["active_agent_count"]=0
item["last_receipt_sha256"]=digest(stable({k:v for k,v in returned.items() if k not in {"receipt","response","error"}}))
returned["final_slot_state"]="DORMANT_READY"
else:
item["runtime_state"]="SYMPTOM_REPORTED"
current["state"]="SYMPTOM_REPORTED_TREATMENT_AVAILABLE"; current["active_agent_count"]=0
current["treatment_signal"]={"failed_slot_id":item["slot_id"],"failure_class":"MODEL_OR_EXECUTION_FAILURE","treatment_router":"TCS-AGENT-TREATMENT-ROUTER-001"}
returned["final_slot_state"]="SYMPTOM_REPORTED"
persist(state/"CURRENT.json",current)
return returned
except Exception as error:
item["runtime_state"]="SYMPTOM_REPORTED"; item["model_context_loaded"]=False
current["state"]="SYMPTOM_REPORTED_TREATMENT_AVAILABLE"; current["active_agent_count"]=0
current["treatment_signal"]={"failed_slot_id":item["slot_id"],"failure_class":type(error).__name__,"treatment_router":"TCS-AGENT-TREATMENT-ROUTER-001"}
persist(state/"CURRENT.json",current)
raise
def main() -> int:

View file

@ -10,8 +10,10 @@ def event(persona='ICE-P-ZY001', session='s1'):
class Tests(unittest.TestCase):
def test_every_slot_is_model_backed_and_owned_by_parent(self):
with tempfile.TemporaryDirectory() as t, patch.object(M,'runtime_available',return_value=True):
v=M.activate(event(),Path(t)); self.assertEqual(len(v['team']),4)
v=M.activate(event(),Path(t)); self.assertEqual(len(v['team']),8)
self.assertTrue(all(x['model_cognition_required'] and x['controller']=='ICE-P-ZY001' for x in v['team']))
self.assertTrue(all(x['runtime_state']=='DORMANT_READY' and not x['model_context_loaded'] for x in v['team']))
self.assertEqual(v['active_agent_count'],0)
def test_persona_switch_rebinds_all_slots_and_invalidates_generation(self):
personas=iter(sorted(M.registered_personas()))
first=next(personas); second=next(x for x in personas if x!=first)
@ -24,5 +26,26 @@ class Tests(unittest.TestCase):
with tempfile.TemporaryDirectory() as t:
with self.assertRaisesRegex(M.CommandError,'NOT_REGISTERED'): M.activate(event('PER-NOT-REAL'),Path(t))
with patch.object(M,'runtime_available',return_value=False), self.assertRaisesRegex(M.CommandError,'PROVIDER_UNAVAILABLE'): M.activate(event(),Path(t))
def test_dispatch_activates_only_selected_slot_then_releases_it(self):
with tempfile.TemporaryDirectory() as t, patch.object(M,'runtime_available',return_value=True):
state=Path(t); current=M.activate(event(),state); selected=current['team'][0]
def fake(*args,**kwargs):
during=M.load(state/'CURRENT.json')
self.assertEqual(during['active_agent_count'],1)
self.assertEqual([x['slot_id'] for x in during['team'] if x['runtime_state']=='ACTIVE'],[selected['slot_id']])
return __import__('subprocess').CompletedProcess(args[0],0,'{}','')
with patch.object(M.subprocess,'run',side_effect=fake):
receipt=M.dispatch({'generation':current['generation'],'child_agent_id':selected['child_agent_id'],'task':'read only'},state)
after=M.load(state/'CURRENT.json')
self.assertEqual(receipt['final_slot_state'],'DORMANT_READY'); self.assertEqual(after['active_agent_count'],0)
def test_failed_limb_emits_symptom_for_treatment_team(self):
with tempfile.TemporaryDirectory() as t, patch.object(M,'runtime_available',return_value=True):
state=Path(t); current=M.activate(event(),state); selected=current['team'][0]
failed=__import__('subprocess').CompletedProcess([],1,'','broken')
with patch.object(M.subprocess,'run',return_value=failed):
receipt=M.dispatch({'generation':current['generation'],'child_agent_id':selected['child_agent_id'],'task':'read only'},state)
after=M.load(state/'CURRENT.json')
self.assertEqual(receipt['final_slot_state'],'SYMPTOM_REPORTED')
self.assertEqual(after['treatment_signal']['treatment_router'],'TCS-AGENT-TREATMENT-ROUTER-001')
if __name__=='__main__': unittest.main()