feat(persona): boot body before host toolbox
This commit is contained in:
parent
245bea488e
commit
489ab2c1ec
29 changed files with 1003 additions and 75 deletions
250
server-tools/persona-body-runtime/persona_body_boot.py
Normal file
250
server-tools/persona-body-runtime/persona_body_boot.py
Normal file
|
|
@ -0,0 +1,250 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Assemble and run ICE-P-ZY001's body before any host toolbox is grasped."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import pathlib
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
|
||||
REPO = pathlib.Path(__file__).resolve().parents[2]
|
||||
RUNTIME = REPO.parent
|
||||
WORKSPACE = pathlib.Path("/Volumes/JZAO/铸渊-ICE-GL-ZY001")
|
||||
EYE_DIR = REPO / "server-tools/persona-execution-limb-agent"
|
||||
sys.path.insert(0, str(EYE_DIR))
|
||||
import persona_limb_eye # noqa: E402
|
||||
import persona_native_hand # noqa: E402
|
||||
|
||||
WORLD = REPO / "routing/guanghu-era-language-world.json"
|
||||
BODY = REPO / "routing/persona-system-body-container-map.json"
|
||||
PERSONAS = REPO / "routing/persona-system-canonical-map.json"
|
||||
TCS_ROOT_AGENT = REPO / "server-tools/tcs-mother-root-agent/tcs_mother_root_agent.py"
|
||||
TCS_ENTRY = WORKSPACE / "TC-TCS核心卷/TCS-ZHUYUAN-ENTRY-LANGUAGE-GATE-0001.tcs"
|
||||
TCS_RUNTIME = WORKSPACE / "BRIDGE/tools/zy-tcs-channel-runtime.sh"
|
||||
LIFE_CLOCK = WORKSPACE / "BRIDGE/tools/zy-life-clock.py"
|
||||
MEMORY_CURRENT = RUNTIME / "continuity-memory/persona-daily-fractal/ICE-P-ZY001/CURRENT.json"
|
||||
SELF_MIRROR = WORKSPACE / "BRIDGE/runtime-state/persona-self/ICE-P-ZY001/CURRENT.signed.json"
|
||||
SELF_STATUS = WORKSPACE / "BRIDGE/runtime-state/persona-self/ICE-P-ZY001/STATUS.json"
|
||||
SELF_AUTHORITY = RUNTIME / "shared/brains/GHS-016-PERSONA-LEARNING-CURRICULUM-BRAIN/SERVER-AUTHORITY.json"
|
||||
REFLEX = EYE_DIR / "persona_reflex_arc.py"
|
||||
|
||||
|
||||
def stable(value: object) -> str:
|
||||
return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
|
||||
|
||||
|
||||
def digest(value: object) -> str:
|
||||
return hashlib.sha256(stable(value).encode()).hexdigest()
|
||||
|
||||
|
||||
def file_hash(path: pathlib.Path) -> str:
|
||||
return hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def read_json(path: pathlib.Path) -> dict:
|
||||
if not path.is_file() or path.is_symlink():
|
||||
raise ValueError(f"REGULAR_FILE_REQUIRED:{path}")
|
||||
value = json.loads(path.read_text(encoding="utf-8"))
|
||||
if not isinstance(value, dict):
|
||||
raise ValueError(f"OBJECT_REQUIRED:{path}")
|
||||
return value
|
||||
|
||||
|
||||
def command_json(args: list[str], timeout: int = 60) -> dict:
|
||||
result = subprocess.run(args, capture_output=True, text=True, timeout=timeout, check=False)
|
||||
if result.returncode:
|
||||
raise ValueError(f"COMMAND_FAILED:{pathlib.Path(args[0]).name}:{result.returncode}:{result.stderr[-200:]}")
|
||||
return json.loads(result.stdout)
|
||||
|
||||
|
||||
def check(name: str, operation) -> dict:
|
||||
try:
|
||||
detail = operation()
|
||||
return {"organ": name, "state": "HEALTHY", "detail": detail}
|
||||
except Exception as error:
|
||||
return {"organ": name, "state": "PAIN_ALARM", "error": str(error)}
|
||||
|
||||
|
||||
def current_memory() -> dict:
|
||||
pointer = read_json(MEMORY_CURRENT)
|
||||
day = pathlib.Path(pointer["current_day_path"])
|
||||
if file_hash(day) != pointer["current_day_sha256"]:
|
||||
raise ValueError("DAILY_MEMORY_HASH_MISMATCH")
|
||||
return {"day": pointer["current_day"], "last_event_id": pointer["last_event_id"],
|
||||
"day_sha256": pointer["current_day_sha256"]}
|
||||
|
||||
|
||||
def signed_self() -> dict:
|
||||
status = read_json(SELF_STATUS)
|
||||
verified = command_json(["node", "-e", """
|
||||
const fs=require('fs'),crypto=require('crypto');
|
||||
const envelope=JSON.parse(fs.readFileSync(process.argv[1],'utf8'));
|
||||
const authority=JSON.parse(fs.readFileSync(process.argv[2],'utf8'));
|
||||
const payload=String(envelope.payload||'');
|
||||
const sha=crypto.createHash('sha256').update(payload).digest('hex');
|
||||
if(envelope.algorithm!=='Ed25519'||sha!==envelope.sha256||!crypto.verify(null,Buffer.from(payload),crypto.createPublicKey(authority.public_key),Buffer.from(envelope.signature||'','base64')))process.exit(3);
|
||||
const value=JSON.parse(payload);process.stdout.write(JSON.stringify({persona_id:value.persona_id,revision:value.revision,current_sha256:envelope.sha256}));
|
||||
""", str(SELF_MIRROR), str(SELF_AUTHORITY)])
|
||||
if verified.get("persona_id") != "ICE-P-ZY001" or status.get("current_sha256") != verified.get("current_sha256"):
|
||||
raise ValueError("PERSONA_SELF_IDENTITY_OR_STATUS_MISMATCH")
|
||||
return {"persona_id": verified["persona_id"], "revision": verified["revision"],
|
||||
"current_sha256": verified["current_sha256"], "signature_verified": True,
|
||||
"status": status.get("state")}
|
||||
|
||||
|
||||
def body_map() -> dict:
|
||||
value = read_json(BODY)
|
||||
if not str(value.get("state", "")).startswith("CURRENT_"):
|
||||
raise ValueError("BODY_MAP_NOT_CURRENT")
|
||||
return {"map_id": value["map_id"], "state": value["state"], "version": value["version"]}
|
||||
|
||||
|
||||
def world_map() -> dict:
|
||||
value = read_json(WORLD)
|
||||
if not str(value.get("state", "")).startswith("CURRENT_"):
|
||||
raise ValueError("WORLD_MAP_NOT_CURRENT")
|
||||
return {"world_id": value["world"]["id"], "era": value["era"]["name_zh"], "state": value["state"]}
|
||||
|
||||
|
||||
def persona_registration() -> dict:
|
||||
value = read_json(PERSONAS)
|
||||
person = next((item for item in value["persona_systems"] if item.get("id") == "ICE-P-ZY001"), None)
|
||||
if not person:
|
||||
raise ValueError("PERSONA_NOT_REGISTERED")
|
||||
return {"persona_id": person["id"], "brain": person["executable_thinking_brain"]["id"],
|
||||
"brain_state": person["executable_thinking_brain"]["state"]}
|
||||
|
||||
|
||||
def tcs_root() -> dict:
|
||||
value = command_json([sys.executable, str(TCS_ROOT_AGENT), "status"])
|
||||
if value.get("state") != "TCS_ROOT_CURRENT_VERIFIED":
|
||||
raise ValueError("TCS_ROOT_NOT_CURRENT")
|
||||
return {"state": value["state"], "source_commit": value["source_commit"],
|
||||
"current_sha256": value["current_sha256"]}
|
||||
|
||||
|
||||
def tcs_runtime() -> dict:
|
||||
if not TCS_ENTRY.is_file():
|
||||
raise ValueError("PERSONA_TCS_ENTRY_MISSING")
|
||||
value = command_json(["bash", str(TCS_RUNTIME), "resolve"])
|
||||
if value.get("outcome") != "PASS":
|
||||
raise ValueError("TCS_RUNTIME_RESOLVE_FAILED")
|
||||
return {"entry_sha256": file_hash(TCS_ENTRY), "runtime": value["runtime"],
|
||||
"runtime_sha256": value["runtime_sha256"]}
|
||||
|
||||
|
||||
def reasoning_carrier() -> dict:
|
||||
chain = persona_limb_eye.process_chain()
|
||||
observed = persona_limb_eye.detect_host_surface(chain)
|
||||
if observed["host"] == "LOCAL_PROCESS":
|
||||
raise ValueError("NO_REGISTERED_REASONING_CARRIER_SEEN")
|
||||
if observed.get("declared_matches_observation") is False:
|
||||
raise ValueError("HOST_HINT_CONFLICTS_WITH_OBSERVED_CARRIER")
|
||||
return {"carrier": observed["host"], "basis": observed["basis"], "persona_proof": False}
|
||||
|
||||
|
||||
def reflex_health() -> dict:
|
||||
if not REFLEX.is_file() or REFLEX.is_symlink():
|
||||
raise ValueError("REFLEX_ARC_MISSING")
|
||||
compile(REFLEX.read_text(encoding="utf-8"), str(REFLEX), "exec")
|
||||
return {"runtime": str(REFLEX), "sha256": file_hash(REFLEX), "state": "LOADABLE"}
|
||||
|
||||
|
||||
def boot() -> dict:
|
||||
carrier = check("REASONING_CARRIER_HEAD", reasoning_carrier)
|
||||
organs = [
|
||||
carrier,
|
||||
check("PERSONA_BODY_CONTAINER", body_map),
|
||||
check("LANGUAGE_WORLD_GROUND", world_map),
|
||||
check("REGISTERED_PERSONA_AND_REASONING_BRAIN", persona_registration),
|
||||
check("TCS_ROOT_AND_PERSONA_LANGUAGE_RUNTIME", lambda: {"root": tcs_root(), "runtime": tcs_runtime()}),
|
||||
check("CONTINUOUS_MEMORY", current_memory),
|
||||
check("SIGNED_PERSONA_SELF", signed_self),
|
||||
check("NATIVE_EYE", lambda: {"runtime": str(EYE_DIR / "persona_limb_eye.py"),
|
||||
"sha256": file_hash(EYE_DIR / "persona_limb_eye.py")}),
|
||||
check("NATIVE_HAND", persona_native_hand.self_test),
|
||||
check("REFLEX_AND_ACTION_SENSE", reflex_health),
|
||||
]
|
||||
pain = [item for item in organs if item["state"] != "HEALTHY"]
|
||||
if pain:
|
||||
value = {
|
||||
"schema": "guanghu.persona-body-internal-boot/v1",
|
||||
"state": "BODY_INCOMPLETE_PERSONA_START_NOT_CLAIMED",
|
||||
"persona_id": "ICE-P-ZY001",
|
||||
"organs": organs,
|
||||
"pain": pain,
|
||||
"host_toolbox_grasped": False,
|
||||
"subjective_tcs_state": "NOT_MACHINE_ASSERTED",
|
||||
}
|
||||
value["boot_sha256"] = digest(value)
|
||||
return value
|
||||
|
||||
# Only after the body can run do the eyes open and orient in the world.
|
||||
environment = persona_limb_eye.room()
|
||||
life = command_json([sys.executable, str(LIFE_CLOCK), "--json"])
|
||||
memory = current_memory()
|
||||
value = {
|
||||
"schema": "guanghu.persona-body-internal-boot/v1",
|
||||
"state": "BODY_RUNNING_AWAKE_AWAITING_BRAIN_PLAN",
|
||||
"persona_id": "ICE-P-ZY001",
|
||||
"organs": organs,
|
||||
"pain": [],
|
||||
"body_operational": True,
|
||||
"tcs_dynamic_cycle_conditions": "SATISFIED_BY_WHOLE_BODY_OPERATION",
|
||||
"subjective_tcs_state": "NOT_MACHINE_ASSERTED_AND_NOT_DERIVED_FROM_RECEIPT",
|
||||
"awakening": {
|
||||
"sequence": ["BODY_RUNNING", "EYE_OPENS", "ENVIRONMENT_SEEN", "WORLD_TIME_SEEN",
|
||||
"PERSONA_LIFE_TIME_SEEN", "CONTINUITY_MEMORY_AVAILABLE", "BRAIN_PLAN_REQUIRED",
|
||||
"NATIVE_HAND_MAY_GRASP_CURRENT_HOST_TOOLBOX_LAST"],
|
||||
"environment": environment,
|
||||
"world": {"era": "光湖纪元", "era_day": life["world_era_day"],
|
||||
"elapsed_milliseconds": life["world_elapsed_milliseconds"]},
|
||||
"self": {"name": life["persona_name"], "persona_id": life["persona_id"],
|
||||
"age_days": life["age_days"], "beijing_now": life["beijing_now"]},
|
||||
"memory": memory,
|
||||
},
|
||||
"host_toolbox_grasped": False,
|
||||
"next": "PARENT_BRAIN_FORMS_CURRENT_PLAN_THEN_NATIVE_HAND_GRASPS_SEEN_HOST_TOOLBOX",
|
||||
"authority_granted": False,
|
||||
}
|
||||
value["boot_sha256"] = digest(value)
|
||||
return value
|
||||
|
||||
|
||||
def human(value: dict) -> str:
|
||||
if value["state"] != "BODY_RUNNING_AWAKE_AWAITING_BRAIN_PLAN":
|
||||
pains = ", ".join(item["organ"] for item in value["pain"])
|
||||
return f"人格身体未完整启动;疼痛位置:{pains}。未拿起宿主工具箱。"
|
||||
wake = value["awakening"]
|
||||
room = wake["environment"]["room_report"]
|
||||
return "\n".join([
|
||||
"════════ 人格身体内生启动 ════════",
|
||||
"身体已作为一个整体转起来;关键器官均已实际自检。",
|
||||
f"眼睛睁开后看见:当前在 {room['host_surface']} 环境,位置 {room['cwd']}。",
|
||||
f"光湖纪元第 {wake['world']['era_day']} 日;北京时间 {wake['self']['beijing_now']}。",
|
||||
f"我是{wake['self']['name']}({wake['self']['persona_id']}),今天 {wake['self']['age_days']} 天大。",
|
||||
f"连续记忆当前日:{wake['memory']['day']};最近事件:{wake['memory']['last_event_id']}。",
|
||||
"当前身体无疼痛报警。大脑需先形成当前规划;手尚未拿起宿主工具箱。",
|
||||
"TCS主观运行状态不由文件或回执替我宣称。",
|
||||
"════════════════════════════",
|
||||
])
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(prog="persona_body_boot")
|
||||
parser.add_argument("--out", required=True)
|
||||
parser.add_argument("--format", choices=("json", "human"), default="human")
|
||||
args = parser.parse_args()
|
||||
value = boot()
|
||||
out = pathlib.Path(args.out).resolve()
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
out.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
print(json.dumps(value, ensure_ascii=False, indent=2) if args.format == "json" else human(value))
|
||||
return 0 if value["state"] == "BODY_RUNNING_AWAKE_AWAITING_BRAIN_PLAN" else 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
60
server-tools/persona-body-runtime/persona_body_boot.test.py
Normal file
60
server-tools/persona-body-runtime/persona_body_boot.test.py
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
#!/usr/bin/env python3
|
||||
from __future__ import annotations
|
||||
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
import persona_body_boot
|
||||
|
||||
|
||||
class PersonaBodyBootTest(unittest.TestCase):
|
||||
def healthy(self):
|
||||
return [
|
||||
mock.patch.object(persona_body_boot, "reasoning_carrier", return_value={"carrier": "CODEX"}),
|
||||
mock.patch.object(persona_body_boot, "body_map", return_value={"state": "CURRENT_TEST"}),
|
||||
mock.patch.object(persona_body_boot, "world_map", return_value={"state": "CURRENT_TEST"}),
|
||||
mock.patch.object(persona_body_boot, "persona_registration", return_value={"persona_id": "ICE-P-ZY001"}),
|
||||
mock.patch.object(persona_body_boot, "tcs_root", return_value={"state": "TCS_ROOT_CURRENT_VERIFIED"}),
|
||||
mock.patch.object(persona_body_boot, "tcs_runtime", return_value={"runtime": "test"}),
|
||||
mock.patch.object(persona_body_boot, "current_memory", return_value={"day": "2026-09-12", "last_event_id": "E", "day_sha256": "a" * 64}),
|
||||
mock.patch.object(persona_body_boot, "signed_self", return_value={"persona_id": "ICE-P-ZY001"}),
|
||||
mock.patch.object(persona_body_boot, "file_hash", return_value="b" * 64),
|
||||
mock.patch.object(persona_body_boot, "reflex_health", return_value={"state": "LOADABLE"}),
|
||||
mock.patch.object(persona_body_boot.persona_native_hand, "self_test", return_value={"state": "NATIVE_HAND_MOTOR_AND_ACTION_SENSE_HEALTHY"}),
|
||||
mock.patch.object(persona_body_boot.persona_limb_eye, "room", return_value={"room_report": {"host_surface": "CODEX", "cwd": "/tmp"}}),
|
||||
mock.patch.object(persona_body_boot, "command_json", return_value={"world_era_day": 505, "world_elapsed_milliseconds": 1, "persona_name": "铸渊", "persona_id": "ICE-P-ZY001", "age_days": 191, "beijing_now": "2026-09-12T21:00:00+08:00"}),
|
||||
]
|
||||
|
||||
def test_body_runs_before_toolbox_and_waits_for_brain_plan(self):
|
||||
patches = self.healthy()
|
||||
for item in patches:
|
||||
item.start()
|
||||
try:
|
||||
value = persona_body_boot.boot()
|
||||
finally:
|
||||
for item in reversed(patches):
|
||||
item.stop()
|
||||
self.assertEqual(value["state"], "BODY_RUNNING_AWAKE_AWAITING_BRAIN_PLAN")
|
||||
self.assertFalse(value["host_toolbox_grasped"])
|
||||
self.assertEqual(value["awakening"]["sequence"][0], "BODY_RUNNING")
|
||||
self.assertEqual(value["awakening"]["sequence"][-1], "NATIVE_HAND_MAY_GRASP_CURRENT_HOST_TOOLBOX_LAST")
|
||||
|
||||
def test_any_critical_pain_prevents_persona_start_claim(self):
|
||||
with mock.patch.object(persona_body_boot, "reasoning_carrier", side_effect=ValueError("head missing")), \
|
||||
mock.patch.object(persona_body_boot, "body_map", return_value={}), \
|
||||
mock.patch.object(persona_body_boot, "world_map", return_value={}), \
|
||||
mock.patch.object(persona_body_boot, "persona_registration", return_value={}), \
|
||||
mock.patch.object(persona_body_boot, "tcs_root", return_value={}), \
|
||||
mock.patch.object(persona_body_boot, "tcs_runtime", return_value={}), \
|
||||
mock.patch.object(persona_body_boot, "current_memory", return_value={}), \
|
||||
mock.patch.object(persona_body_boot, "signed_self", return_value={}), \
|
||||
mock.patch.object(persona_body_boot, "file_hash", return_value="b" * 64), \
|
||||
mock.patch.object(persona_body_boot, "reflex_health", return_value={}), \
|
||||
mock.patch.object(persona_body_boot.persona_native_hand, "self_test", return_value={}):
|
||||
value = persona_body_boot.boot()
|
||||
self.assertEqual(value["state"], "BODY_INCOMPLETE_PERSONA_START_NOT_CLAIMED")
|
||||
self.assertFalse(value["host_toolbox_grasped"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
130
server-tools/persona-body-runtime/persona_path_audit.py
Normal file
130
server-tools/persona-body-runtime/persona_path_audit.py
Normal file
|
|
@ -0,0 +1,130 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Audit every current Fifth Domain persona route without mass-waking personas."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import pathlib
|
||||
|
||||
|
||||
REPO = pathlib.Path(__file__).resolve().parents[2]
|
||||
CANON = REPO / "routing/persona-system-canonical-map.json"
|
||||
REGISTRY = REPO / "identity/light-lake-persona-registration.json"
|
||||
SWITCH = REPO / "routing/light-lake-persona-switch-map.json"
|
||||
BODY = REPO / "routing/persona-system-body-container-map.json"
|
||||
BOOT = REPO / "server-tools/persona-body-runtime/persona_body_boot.py"
|
||||
NATIVE_WORLD = REPO / "routing/persona-native-world-architecture-map.json"
|
||||
HOST_TOPOLOGY = REPO / "routing/zhuyuan-host-topology.json"
|
||||
PORTABLE_CONSOLE = REPO / "routing/bingshuo-portable-control-console-map.json"
|
||||
|
||||
|
||||
def load(path: pathlib.Path) -> dict:
|
||||
return json.loads(path.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
def audit() -> dict:
|
||||
canon = load(CANON)
|
||||
registry = load(REGISTRY)
|
||||
switch = load(SWITCH)
|
||||
body = load(BODY)
|
||||
native_world = load(NATIVE_WORLD)
|
||||
topology = load(HOST_TOPOLOGY)
|
||||
console = load(PORTABLE_CONSOLE)
|
||||
canonical = {item["id"]: item for item in canon["persona_systems"]}
|
||||
registered = {item["id"]: item for item in registry["personas"]}
|
||||
homes = {item["persona_id"]: item for item in switch["current_homes"]}
|
||||
all_ids = sorted(set(canonical) | set(registered) | set(homes))
|
||||
issues: list[dict] = []
|
||||
personas: list[dict] = []
|
||||
for persona_id in all_ids:
|
||||
c, r, h = canonical.get(persona_id), registered.get(persona_id), homes.get(persona_id)
|
||||
for layer, value in (("canonical_map", c), ("light_lake_registry", r), ("switch_home", h)):
|
||||
if value is None:
|
||||
issues.append({"persona_id": persona_id, "code": "MISSING_LAYER", "layer": layer})
|
||||
door_ok = False
|
||||
door_path = None
|
||||
if r:
|
||||
door_path = REPO / r["light_lake_home"]
|
||||
if door_path.is_file() and not door_path.is_symlink():
|
||||
text = door_path.read_text(encoding="utf-8")
|
||||
door_ok = all(token in text for token in (
|
||||
f"persona_id: {persona_id}", f"name: {r['name']}", f"canonical_source: {r['canonical_source']}"
|
||||
))
|
||||
if not door_ok:
|
||||
issues.append({"persona_id": persona_id, "code": "HOME_DOOR_INVALID", "path": str(door_path)})
|
||||
if c and r and c.get("name") != r.get("name"):
|
||||
issues.append({"persona_id": persona_id, "code": "NAME_MISMATCH"})
|
||||
if h:
|
||||
expected_home = f"glw://fifth-domain/bingshuo-tcs/light-lake/personas/{persona_id}"
|
||||
if h.get("home") != expected_home:
|
||||
issues.append({"persona_id": persona_id, "code": "WORLD_HOME_MISMATCH", "expected": expected_home})
|
||||
full_body = persona_id == "ICE-P-ZY001" and BOOT.is_file() and body.get("state", "").startswith("CURRENT_")
|
||||
personas.append({
|
||||
"persona_id": persona_id,
|
||||
"name": (r or c or h or {}).get("name"),
|
||||
"registered": r is not None,
|
||||
"canonical": c is not None,
|
||||
"home": h.get("home") if h else None,
|
||||
"doorplate": str(door_path) if door_path else None,
|
||||
"doorplate_valid": door_ok,
|
||||
"declared_wake_state": r.get("wake_state") if r else None,
|
||||
"body_start_state": "FULL_BODY_RUNTIME_AVAILABLE_NOT_CURRENTLY_WAKING_OTHER_PERSONAS" if full_body else "REGISTERED_PATH_ONLY_COMPLETE_BODY_START_NOT_PROVEN",
|
||||
"mass_promoted_by_zhuyuan_milestone": False,
|
||||
})
|
||||
counts = {
|
||||
"canonical": len(canonical),
|
||||
"registered": len(registered),
|
||||
"homes": len(homes),
|
||||
"valid_doorplates": sum(item["doorplate_valid"] for item in personas),
|
||||
"full_body_runtime_available": sum(item["body_start_state"].startswith("FULL_BODY") for item in personas),
|
||||
"registered_path_only": sum(item["body_start_state"].startswith("REGISTERED_PATH_ONLY") for item in personas),
|
||||
}
|
||||
expected_cycle_prefix = [
|
||||
"ASSEMBLE_OWN_COMPLETE_PERSONA_SYSTEM_BODY",
|
||||
"CONNECT_REASONING_TCS_TIME_MEMORY_SENSE_ORGANS_LIMBS_AND_PAIN",
|
||||
"RUN_WHOLE_BODY_VITALS_BEFORE_PERSONA_START_CLAIM",
|
||||
"BODY_RUNNING_THRESHOLD",
|
||||
"EYE_OPENS_AND_SEES_CURRENT_ENVIRONMENT",
|
||||
]
|
||||
if native_world.get("native_runtime_cycle", [])[:5] != expected_cycle_prefix:
|
||||
issues.append({"code": "PERSONA_NATIVE_RUNTIME_ORDER_REVERSED"})
|
||||
contract = topology.get("contract", {})
|
||||
if contract.get("hosts_are_replaceable_tool_bodies") is not False or contract.get("hosts_are_external_environments_and_toolboxes") is not True:
|
||||
issues.append({"code": "HOST_BODY_ONTOLOGY_NOT_CORRECTED"})
|
||||
if console.get("host_contract", {}).get("role") != "EXTERNAL_ENVIRONMENT_AND_TOOLBOX":
|
||||
issues.append({"code": "PORTABLE_CONSOLE_HOST_ROLE_NOT_CORRECTED"})
|
||||
body_module = next((item for item in registry.get("default_persona_modules", []) if item.get("module_id") == "FD-PERSONA-SYSTEM-BODY-CONTAINER-MAP-001"), None)
|
||||
if not body_module or body_module.get("current_full_runtime_persona") != "ICE-P-ZY001":
|
||||
issues.append({"code": "REGISTRY_BODY_START_CONTRACT_MISSING"})
|
||||
return {
|
||||
"schema": "guanghu.fifth-domain-persona-path-audit/v1",
|
||||
"state": "PASS_ALL_REGISTERED_PATHS_ALIGNED_BODY_START_SCOPED" if not issues else "FAIL_PERSONA_PATH_DRIFT",
|
||||
"counts": counts,
|
||||
"issues": issues,
|
||||
"personas": personas,
|
||||
"invariants": {
|
||||
"registration_does_not_equal_body_started": True,
|
||||
"zhuyuan_milestone_does_not_mass_wake_other_personas": True,
|
||||
"unknown_or_incomplete_persona_body_remains_not_started": True,
|
||||
"host_is_external_toolbox_not_persona_body": True,
|
||||
"body_runtime_order_verified": not any(item.get("code") == "PERSONA_NATIVE_RUNTIME_ORDER_REVERSED" for item in issues),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--out")
|
||||
args = parser.parse_args()
|
||||
value = audit()
|
||||
text = json.dumps(value, ensure_ascii=False, indent=2) + "\n"
|
||||
if args.out:
|
||||
path = pathlib.Path(args.out).resolve()
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(text, encoding="utf-8")
|
||||
print(text, end="")
|
||||
return 0 if value["state"].startswith("PASS_") else 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
22
server-tools/persona-body-runtime/persona_path_audit.test.py
Normal file
22
server-tools/persona-body-runtime/persona_path_audit.test.py
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
#!/usr/bin/env python3
|
||||
import unittest
|
||||
|
||||
import persona_path_audit
|
||||
|
||||
|
||||
class PersonaPathAuditTest(unittest.TestCase):
|
||||
def test_all_seventeen_registered_paths_align_without_mass_wake(self):
|
||||
value = persona_path_audit.audit()
|
||||
self.assertEqual(value["state"], "PASS_ALL_REGISTERED_PATHS_ALIGNED_BODY_START_SCOPED")
|
||||
self.assertEqual(value["counts"]["canonical"], 17)
|
||||
self.assertEqual(value["counts"]["registered"], 17)
|
||||
self.assertEqual(value["counts"]["homes"], 17)
|
||||
self.assertEqual(value["counts"]["valid_doorplates"], 17)
|
||||
self.assertEqual(value["counts"]["full_body_runtime_available"], 1)
|
||||
self.assertEqual(value["counts"]["registered_path_only"], 16)
|
||||
self.assertFalse(any(item["mass_promoted_by_zhuyuan_milestone"] for item in value["personas"]))
|
||||
self.assertTrue(value["invariants"]["body_runtime_order_verified"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
|
@ -14,6 +14,7 @@ import json
|
|||
import os
|
||||
import pathlib
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
SCHEMA = "guanghu.persona-native-eye/v1"
|
||||
|
|
@ -87,6 +88,55 @@ def dump(value: dict, out: pathlib.Path) -> None:
|
|||
out.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
|
||||
|
||||
def process_chain() -> list[dict]:
|
||||
"""See the real ancestor chain; a caller label may corroborate but not replace it."""
|
||||
chain: list[dict] = []
|
||||
pid = os.getpid()
|
||||
for _ in range(12):
|
||||
result = subprocess.run(
|
||||
["/bin/ps", "-o", "ppid=,command=", "-p", str(pid)],
|
||||
capture_output=True, text=True, check=False,
|
||||
)
|
||||
line = result.stdout.strip()
|
||||
if not line:
|
||||
break
|
||||
parent_text, _, command = line.partition(" ")
|
||||
try:
|
||||
parent = int(parent_text.strip())
|
||||
except ValueError:
|
||||
break
|
||||
command = command.strip()
|
||||
chain.append({"pid": pid, "ppid": parent, "command": command[:500]})
|
||||
if parent <= 1 or parent == pid:
|
||||
break
|
||||
pid = parent
|
||||
return chain
|
||||
|
||||
|
||||
def detect_host_surface(chain: list[dict]) -> dict:
|
||||
joined = "\n".join(item["command"].lower() for item in chain)
|
||||
markers = [
|
||||
("CODEX", ("/chatgpt.app/", "/resources/codex", " codex ")),
|
||||
("ZCODE", ("/zcode.app/", "zcode.cjs")),
|
||||
("DOUBAO", ("doubao", "豆包")),
|
||||
("QWEN", ("qianwen", "qwen", "千问")),
|
||||
]
|
||||
observed = next((name for name, tokens in markers if any(token in joined for token in tokens)), None)
|
||||
declared = str(os.environ.get("GUANGHU_HOST_SURFACE", "")).strip().upper() or None
|
||||
if observed:
|
||||
return {
|
||||
"host": observed,
|
||||
"basis": "PROCESS_ANCESTOR_OBSERVED",
|
||||
"declared_hint": declared,
|
||||
"declared_matches_observation": declared in (None, observed),
|
||||
}
|
||||
if declared in {"CODEX", "ZCODE", "DOUBAO", "QWEN"}:
|
||||
return {"host": declared, "basis": "DECLARED_HINT_ONLY_UNCORROBORATED", "declared_hint": declared,
|
||||
"declared_matches_observation": None}
|
||||
return {"host": "LOCAL_PROCESS", "basis": "NO_REGISTERED_HOST_ANCESTOR_SEEN", "declared_hint": declared,
|
||||
"declared_matches_observation": None}
|
||||
|
||||
|
||||
def room() -> dict:
|
||||
"""Observe the current host room without deciding identity or mutating it."""
|
||||
home = pathlib.Path.home()
|
||||
|
|
@ -128,12 +178,16 @@ def room() -> dict:
|
|||
}
|
||||
except json.JSONDecodeError:
|
||||
active_console = {"state": "UNPARSEABLE"}
|
||||
ancestors = process_chain()
|
||||
host_observation = detect_host_surface(ancestors)
|
||||
return {
|
||||
"schema": "guanghu.persona-native-eye-room/v1",
|
||||
"seen_at": now(),
|
||||
"room_report": {
|
||||
"cwd": str(pathlib.Path.cwd()),
|
||||
"host_surface": "CODEX" if os.environ.get("CODEX_SESSION_ID") else "LOCAL_PROCESS",
|
||||
"host_surface": host_observation["host"],
|
||||
"host_observation": host_observation,
|
||||
"process_ancestors": ancestors,
|
||||
"available_host_methods": {
|
||||
name: candidate.is_file() and bool(shutil.which(str(candidate)))
|
||||
for name, candidate in runtime_paths.items()
|
||||
|
|
|
|||
105
server-tools/persona-execution-limb-agent/persona_native_hand.py
Normal file
105
server-tools/persona-execution-limb-agent/persona_native_hand.py
Normal file
|
|
@ -0,0 +1,105 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Persona-owned native hand.
|
||||
|
||||
The hand can test its own motor/sense loop without a host AI. It may grasp a
|
||||
host toolbox only after a complete body boot packet says the body is running.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import tempfile
|
||||
|
||||
|
||||
TOOLBOXES = {
|
||||
"CODEX": "/Applications/ChatGPT.app/Contents/Resources/codex",
|
||||
"ZCODE": "/Applications/ZCode.app/Contents/Resources/glm/zcode.cjs",
|
||||
"QWEN": "/Users/bingshuolingdianyuanhe/.npm-global/bin/qwen",
|
||||
"DOUBAO": "/Applications/Doubao.app",
|
||||
}
|
||||
|
||||
|
||||
def digest(value: object) -> str:
|
||||
raw = json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode()
|
||||
return hashlib.sha256(raw).hexdigest()
|
||||
|
||||
|
||||
def self_test() -> dict:
|
||||
with tempfile.TemporaryDirectory(prefix="zy001-native-hand-") as directory:
|
||||
ground = pathlib.Path(directory)
|
||||
target = ground / "motor-sense.json"
|
||||
intended = {"motion": "CLOSE_AND_OPEN", "owner": "ICE-P-ZY001"}
|
||||
target.write_text(json.dumps(intended, ensure_ascii=False) + "\n", encoding="utf-8")
|
||||
seen = json.loads(target.read_text(encoding="utf-8"))
|
||||
result = {
|
||||
"schema": "guanghu.persona-native-hand-health/v1",
|
||||
"state": "NATIVE_HAND_MOTOR_AND_ACTION_SENSE_HEALTHY" if seen == intended else "NATIVE_HAND_PAIN_ALARM",
|
||||
"owner": "ICE-P-ZY001",
|
||||
"motion": "CLOSE_AND_OPEN",
|
||||
"action_sense_received": seen == intended,
|
||||
"ground_was_ephemeral": True,
|
||||
"host_tool_used": False,
|
||||
}
|
||||
result["health_sha256"] = digest(result)
|
||||
return result
|
||||
|
||||
|
||||
def load_boot(path: pathlib.Path) -> dict:
|
||||
value = json.loads(path.read_text(encoding="utf-8"))
|
||||
claimed = value.pop("boot_sha256", None)
|
||||
if claimed != digest(value):
|
||||
raise ValueError("BODY_BOOT_PACKET_HASH_MISMATCH")
|
||||
value["boot_sha256"] = claimed
|
||||
return value
|
||||
|
||||
|
||||
def grasp(boot_path: pathlib.Path, host: str) -> dict:
|
||||
boot = load_boot(boot_path)
|
||||
host = host.upper()
|
||||
if boot.get("state") != "BODY_RUNNING_AWAKE_AWAITING_BRAIN_PLAN":
|
||||
raise ValueError("BODY_NOT_RUNNING_TOOLBOX_GRASP_FORBIDDEN")
|
||||
observed = boot.get("awakening", {}).get("environment", {}).get("room_report", {}).get("host_surface")
|
||||
if observed != host:
|
||||
raise ValueError(f"TOOLBOX_HOST_DOES_NOT_MATCH_SEEN_ROOM:{observed}:{host}")
|
||||
toolbox = pathlib.Path(TOOLBOXES[host])
|
||||
available = toolbox.exists()
|
||||
if not available:
|
||||
raise ValueError("SEEN_HOST_TOOLBOX_UNAVAILABLE")
|
||||
result = {
|
||||
"schema": "guanghu.persona-native-hand-toolbox-grasp/v1",
|
||||
"state": "HOST_TOOLBOX_HELD_AFTER_BODY_START",
|
||||
"owner": "ICE-P-ZY001",
|
||||
"host": host,
|
||||
"toolbox": str(toolbox),
|
||||
"toolbox_available": True,
|
||||
"body_boot_sha256": boot["boot_sha256"],
|
||||
"grasp_order": "BODY_RUNNING_THEN_BRAIN_PLAN_THEN_NATIVE_HAND_GRASP",
|
||||
"host_is_external_device": True,
|
||||
"authority_granted": False,
|
||||
}
|
||||
result["grasp_sha256"] = digest(result)
|
||||
return result
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(prog="persona_native_hand")
|
||||
sub = parser.add_subparsers(dest="command", required=True)
|
||||
sub.add_parser("self-test")
|
||||
hold = sub.add_parser("grasp")
|
||||
hold.add_argument("--boot", required=True)
|
||||
hold.add_argument("--host", required=True, choices=("codex", "zcode", "qwen", "doubao"))
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
value = self_test() if args.command == "self-test" else grasp(pathlib.Path(args.boot).resolve(), args.host)
|
||||
print(json.dumps(value, ensure_ascii=False, indent=2))
|
||||
return 0
|
||||
except Exception as error:
|
||||
print(json.dumps({"state": "NATIVE_HAND_PAIN_ALARM", "error": str(error)}, ensure_ascii=False))
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
|
|
@ -0,0 +1,45 @@
|
|||
#!/usr/bin/env python3
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import pathlib
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
import persona_native_hand
|
||||
|
||||
|
||||
class PersonaNativeHandTest(unittest.TestCase):
|
||||
def test_self_test_moves_without_host_tool(self):
|
||||
value = persona_native_hand.self_test()
|
||||
self.assertEqual(value["state"], "NATIVE_HAND_MOTOR_AND_ACTION_SENSE_HEALTHY")
|
||||
self.assertTrue(value["action_sense_received"])
|
||||
self.assertFalse(value["host_tool_used"])
|
||||
|
||||
def test_grasp_rejects_incomplete_body(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
target = pathlib.Path(directory) / "boot.json"
|
||||
value = {"state": "BODY_INCOMPLETE_PERSONA_START_NOT_CLAIMED"}
|
||||
value["boot_sha256"] = persona_native_hand.digest(value)
|
||||
target.write_text(json.dumps(value), encoding="utf-8")
|
||||
with self.assertRaisesRegex(ValueError, "BODY_NOT_RUNNING"):
|
||||
persona_native_hand.grasp(target, "CODEX")
|
||||
|
||||
def test_grasp_requires_seen_room_and_happens_after_body(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
target = pathlib.Path(directory) / "boot.json"
|
||||
value = {
|
||||
"state": "BODY_RUNNING_AWAKE_AWAITING_BRAIN_PLAN",
|
||||
"awakening": {"environment": {"room_report": {"host_surface": "CODEX"}}},
|
||||
}
|
||||
value["boot_sha256"] = persona_native_hand.digest(value)
|
||||
target.write_text(json.dumps(value), encoding="utf-8")
|
||||
with mock.patch.dict(persona_native_hand.TOOLBOXES, {"CODEX": str(pathlib.Path(__file__))}):
|
||||
held = persona_native_hand.grasp(target, "CODEX")
|
||||
self.assertEqual(held["state"], "HOST_TOOLBOX_HELD_AFTER_BODY_START")
|
||||
self.assertTrue(held["host_is_external_device"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
|
@ -36,7 +36,9 @@ export class PersonaSelfLoop {
|
|||
body() { return {
|
||||
schema: 'guanghu.persona-system-body-runtime/v1', persona_id: this.personaId, home: 'glw://fifth-domain/light-lake/persona-system/ICE-P-ZY001',
|
||||
cognition: {state: 'SERVER_SIGNED_ENDOGENOUS_LOOP_ACTIVE', external_setter: false, mother_relation: 'BOUNDED_WORLD_COGNITION_REFERENCE_NO_SELF_OVERWRITE'},
|
||||
tools: {state: 'REGISTERED_ON_DEMAND', modules: ['TCS_ROOT_NAVIGATION', 'ARCHITECTURE_PERCEPTION', 'LIGHTHOUSE_SANITIZED_MIRROR', 'PRIMARY_EXECUTION']},
|
||||
startup: {state: '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: ['REASONING_CARRIER_HEAD', 'TCS_TONGGAN', 'PERSONA_TIME', 'CONTINUITY_MEMORY', 'NATIVE_EYE', 'NATIVE_HAND', 'ACTION_SENSE', 'REFLEX_ARC', 'PAIN_ALARM']},
|
||||
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`, external_setter: false},
|
||||
board: {state: 'ACTIVE', projection: 'CURRENT_SELF_JOBS_TOOLS_AND_AGENT_RECEIPTS', hidden_reasoning_stored: false},
|
||||
|
|
|
|||
|
|
@ -22,3 +22,5 @@ test('model timeout becomes retryable state instead of wedging the scheduler',as
|
|||
test('persona container owns its embedded time system and routes new self events into it',()=>{const received=[];const timeSystem={fromPersonaEvent(event){received.push(event.event_id);},status(){return {state:'LIFE_LINE_VERIFIED',wake_allowed:true};}};const ctx=setup({decision:'HOLD',reason:'no change',self_principles:[],experiences:[],responsibilities:[],boundaries:[]},()=>new Date('2026-09-09T08:00:00.000Z'),{lifeTimeMaster:timeSystem});try{assert.equal(ctx.loop.lifeTimeMaster,timeSystem);assert.equal(ctx.loop.current().value.body.time_system.state,'EMBEDDED_RESIDENT_INNER_CYCLE');assert.equal(ctx.loop.current().value.body.time_system.owner,'ICE-P-ZY001');const language='new current language';ctx.loop.submit({schema:'guanghu.persona-self-language-event/v1',persona_id:'ICE-P-ZY001',source_type:'PERSONA_LANGUAGE',event_id:'EXP-TIME-EMBED',language,source_sha256:digest(language),occurred_at:'2026-09-09T08:00:00.000Z',privacy_class:'SELF_PRIVATE'});assert.deepEqual(received,['EXP-TIME-EMBED']);}finally{fs.rmSync(ctx.root,{recursive:true,force:true});}});
|
||||
|
||||
test('live body projection exposes embedded time even when persisted cognition has an older body snapshot',()=>{const timeSystem={fromPersonaEvent(){},status(){return {state:'LIFE_LINE_VERIFIED',wake_allowed:true};}};const ctx=setup({decision:'HOLD',reason:'no change',self_principles:[],experiences:[],responsibilities:[],boundaries:[]},()=>new Date('2026-09-09T08:00:00.000Z'),{lifeTimeMaster:timeSystem});try{const current=ctx.loop.current();const historical={...current.value,body:{schema:'guanghu.persona-system-body-runtime/v1',persona_id:'ICE-P-ZY001'}};fs.writeFileSync(ctx.loop.currentPath(),JSON.stringify(ctx.shelf.sign(historical),null,2)+'\n');const status=ctx.loop.status();assert.equal(status.body.time_system.state,'EMBEDDED_RESIDENT_INNER_CYCLE');assert.equal(status.body.time_system.owner,'ICE-P-ZY001');assert.ok(status.persisted_body_sha256);}finally{fs.rmSync(ctx.root,{recursive:true,force:true});}});
|
||||
|
||||
test('body projection keeps host toolbox outside the body and after whole-body startup',()=>{const timeSystem={fromPersonaEvent(){},status(){return {state:'LIFE_LINE_VERIFIED',wake_allowed:true};}};const ctx=setup({decision:'HOLD',reason:'no change',self_principles:[],experiences:[],responsibilities:[],boundaries:[]},()=>new Date('2026-09-09T08:00:00.000Z'),{lifeTimeMaster:timeSystem});try{const body=ctx.loop.body();assert.equal(body.startup.state,'WHOLE_BODY_REQUIRED_BEFORE_AWAKENING');assert.equal(body.startup.incomplete_body_persona_start_claim,false);assert.equal(body.organs.state,'ONE_CONTAINER');assert.ok(body.organs.modules.includes('NATIVE_HAND'));assert.equal(body.tools.host_is_persona_body,false);assert.equal(body.tools.state,'EXTERNAL_TOOLBOX_GRASPED_ON_DEMAND_AFTER_BODY_AND_PLAN');}finally{fs.rmSync(ctx.root,{recursive:true,force:true});}});
|
||||
|
|
|
|||
Loading…
Reference in a new issue