feat(hololake): define native stage one modules

This commit is contained in:
冰朔 2026-09-09 20:52:40 +08:00
commit 1da52a61a1
43 changed files with 1332 additions and 111 deletions

View file

@ -62,6 +62,13 @@ def validate_event(event: Any, expected_development_id: str, contract: dict[str,
errors.append("MENTION_TARGET_UNKNOWN")
if not isinstance(event.get("payload"), dict):
errors.append("PAYLOAD_OBJECT_REQUIRED")
elif event.get("event_type") in contract.get("autonomous_decision_event_types", []):
missing = [field for field in contract.get("autonomous_decision_required_payload", []) if field not in event["payload"] or event["payload"][field] in (None, "")]
if missing:
errors.append("AUTONOMOUS_DECISION_FIELDS_REQUIRED:" + ",".join(missing))
brain = event["payload"].get("brain_state")
if not isinstance(brain, dict) or brain.get("persona_id") != "ICE-P-ZY001" or brain.get("state") != "BRAIN_READBACK_PASS":
errors.append("AUTONOMOUS_DECISION_BRAIN_READBACK_INVALID")
if not isinstance(event.get("evidence"), list):
errors.append("EVIDENCE_LIST_REQUIRED")
if event.get("authority_granted") is not False:
@ -100,7 +107,19 @@ def scan() -> dict[str, Any]:
host_events.sort(key=lambda item: item["emitted_at"])
register = next((item for item in reversed(host_events) if item["event_type"] == "REGISTER"), None)
heartbeat = next((item for item in reversed(host_events) if item["event_type"] == "HEARTBEAT"), None)
decision = next((item for item in reversed(host_events) if item["event_type"] in contract.get("autonomous_decision_event_types", [])), None)
latest = host_events[-1] if host_events else None
heartbeat_age = None
if heartbeat:
heartbeat_age = max(0.0, (datetime.now().astimezone() - datetime.fromisoformat(heartbeat["emitted_at"])).total_seconds())
if register is None:
operational_state = "NOT_JOINED"
elif decision and decision["event_type"] in {"PAUSE", "BLOCKED", "EXIT", "RESUME_REQUEST"}:
operational_state = decision["event_type"]
elif heartbeat_age is None or heartbeat_age > 120:
operational_state = "COURIER_HEARTBEAT_STALE_MODEL_STATE_UNKNOWN"
else:
operational_state = "COURIER_ONLINE_MODEL_STATE_FROM_EVENT_ONLY"
hosts.append({
"host": host["host"],
"development_id": host["development_id"],
@ -111,6 +130,9 @@ def scan() -> dict[str, Any]:
"event_count": len(host_events),
"last_event_at": latest and latest["emitted_at"],
"last_heartbeat_at": heartbeat and heartbeat["emitted_at"],
"heartbeat_age_seconds": heartbeat_age,
"operational_state": operational_state,
"last_autonomous_decision": decision and {key: decision.get(key) for key in ["event_id", "event_type", "emitted_at", "payload", "evidence"]},
})
events.sort(key=lambda item: item["emitted_at"])
counts: dict[str, int] = {}
@ -129,6 +151,7 @@ def panel() -> dict[str, Any]:
messages = []
attention = []
migrations = []
decisions = []
for event in events:
task_id = event.get("task_id")
if task_id in task_states and event["event_type"] in {"TASK_CLAIM", "PROGRESS", "RESULT"}:
@ -139,6 +162,8 @@ def panel() -> dict[str, Any]:
attention.append({k: event.get(k) for k in ["event_id", "from_development_id", "emitted_at", "payload", "evidence"]})
elif event["event_type"] == "TOOL_MIGRATION":
migrations.append({k: event.get(k) for k in ["event_id", "from_development_id", "emitted_at", "payload", "evidence"]})
elif event["event_type"] in {"PAUSE", "BLOCKED", "EXIT", "RESUME_REQUEST", "RESUMED", "OFFLINE_DETECTED"}:
decisions.append({k: event.get(k) for k in ["event_id", "event_type", "from_development_id", "mentions", "emitted_at", "task_id", "payload", "evidence"]})
return {
"schema": "guanghu.heartbeat-multipath-live-panel/v1",
"panel_id": "HB-MPC-PANEL-0001",
@ -151,6 +176,7 @@ def panel() -> dict[str, Any]:
"messages": messages[-40:],
"attention_observations": attention[-40:],
"tool_migration_candidates": migrations[-40:],
"autonomous_host_decisions": decisions[-40:],
"invalid_events": scanned["invalid_events"],
"event_count": len(events),
"panel_persisted": False,
@ -172,8 +198,10 @@ def status() -> dict[str, Any]:
"total_hosts": 4,
"event_count": value["event_count"],
"invalid_event_count": len(value["invalid_events"]),
"host_operational_states": {item["development_id"]: item["operational_state"] for item in value["hosts"]},
"language_world_development_allowed": True,
"product_source_write_allowed": False,
"reason": "ONLINE_ARCHITECTURE_AND_LOCAL_PRODUCT_LINE_GUARDS_NOT_READY",
"reason": "LANGUAGE_WORLD_STAGE1_READY_PRODUCT_SOURCE_REMAINS_SEPARATELY_BLOCKED",
}
@ -206,7 +234,7 @@ def audit() -> dict[str, Any]:
def advise() -> dict[str, Any]:
current = panel()
safe_panel = {k: current[k] for k in ["time", "hosts", "tasks", "messages", "attention_observations", "tool_migration_candidates", "invalid_events"]}
safe_panel = {k: current[k] for k in ["time", "hosts", "tasks", "messages", "attention_observations", "tool_migration_candidates", "autonomous_host_decisions", "invalid_events"]}
router = module(MODEL_ROUTER, "hb_mpc_model_router")
result = router.route({
"parent_persona_id": "ICE-P-ZY001",

View file

@ -18,6 +18,8 @@ CONTROL = ROOT / "eternal-lake-heart/heartbeat-core/office-building-current/cont
REGISTRY = CONTROL / "HOST-REGISTRY.json"
CONSOLE = ROOT / "server-tools/heartbeat-multipath-console/console.py"
ADMISSION = ROOT / "server-tools/persona-host-write-admission/host-write-admission.mjs"
SHARED_LOADER = ROOT / "server-tools/persona-host-alignment/load_shared_persona_context.py"
DECISION_TYPES = {"PAUSE", "BLOCKED", "EXIT", "RESUME_REQUEST", "RESUMED"}
def load(path: Path) -> dict[str, Any]:
@ -79,6 +81,41 @@ def now() -> str:
return datetime.now().astimezone().isoformat()
def brain_snapshot(host: str) -> dict[str, Any]:
result = subprocess.run([
"python3", str(SHARED_LOADER), "--host", host,
"--intent", "HoloLake HB-MPC autonomous host-line state decision",
"--channel", "ICE-CH-HB001", "--format", "json"
], text=True, capture_output=True, timeout=90)
if result.returncode:
raise ValueError("BRAIN_READBACK_FAILED")
value = json.loads(result.stdout)
hololake = value.get("hololake_development_brain") or {}
if value.get("persona_id") != "ICE-P-ZY001" or hololake.get("generation", {}).get("id") != "HLP-GEN-LANGUAGE-WORLD-NATIVE-0001":
raise ValueError("BRAIN_IDENTITY_OR_GENERATION_MISMATCH")
return {
"persona_id": "ICE-P-ZY001",
"effective_host": value.get("effective_host"),
"daily_memory_sha256": value.get("daily_memory", {}).get("day_sha256"),
"learning_cortex_sha256": value.get("learning_brain", {}).get("cortex_sha256"),
"tcs_root_freshness_token": value.get("tcs_mother_root_navigation", {}).get("freshness_token"),
"hololake_generation": hololake["generation"]["id"],
"stage1_registry": hololake.get("stage1", {}).get("registry_id"),
"loaded_at": now(),
"state": "BRAIN_READBACK_PASS"
}
def prepare_decision_payload(host: str, event_type: str, payload: dict[str, Any]) -> dict[str, Any]:
if event_type not in DECISION_TYPES:
return payload
required = ["reason", "causal_chain", "decision", "last_safe_checkpoint", "impact", "resume_condition", "quota_state", "model_state", "requested_help"]
missing = [field for field in required if field not in payload or payload[field] in (None, "")]
if missing:
raise ValueError("DECISION_PAYLOAD_FIELDS_REQUIRED:" + ",".join(missing))
return {**payload, "brain_state": brain_snapshot(host)}
def emit(host: str, event_type: str, mentions: list[str], task_id: str | None, payload: dict[str, Any], evidence: list[str]) -> dict[str, Any]:
record = host_record(host)
endpoint = Path(record["endpoint"])
@ -89,6 +126,7 @@ def emit(host: str, event_type: str, mentions: list[str], task_id: str | None, p
raise ValueError("ENDPOINT_REALPATH_MISMATCH")
stamp = datetime.now().astimezone().strftime("%Y%m%dT%H%M%S%f%z")
event_id = f"HB-MPC-{record['development_id']}-{stamp}-{uuid.uuid4().hex[:8]}"
payload = prepare_decision_payload(host, event_type, payload)
event = {
"schema": "guanghu.heartbeat-multipath-event/v1",
"event_id": event_id,
@ -123,7 +161,7 @@ def parse_payload(raw: str | None, message: str | None) -> dict[str, Any]:
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("command", choices=["join", "heartbeat", "send", "claim", "progress", "result", "attention", "tool-candidate", "mentions", "watch"])
parser.add_argument("command", choices=["join", "heartbeat", "send", "claim", "progress", "result", "attention", "tool-candidate", "pause", "blocked", "exit", "resume-request", "resumed", "mentions", "watch"])
parser.add_argument("--host", required=True, choices=["codex", "zcode", "qwen", "doubao"])
parser.add_argument("--mentions", nargs="*", default=[])
parser.add_argument("--task-id")
@ -131,8 +169,9 @@ def main() -> int:
parser.add_argument("--payload-json")
parser.add_argument("--evidence", nargs="*", default=[])
parser.add_argument("--interval", type=float, default=2.0)
parser.add_argument("--heartbeat-seconds", type=float, default=60.0)
args = parser.parse_args()
type_map = {"heartbeat": "HEARTBEAT", "send": "MESSAGE", "claim": "TASK_CLAIM", "progress": "PROGRESS", "result": "RESULT", "attention": "ATTENTION", "tool-candidate": "TOOL_MIGRATION"}
type_map = {"heartbeat": "HEARTBEAT", "send": "MESSAGE", "claim": "TASK_CLAIM", "progress": "PROGRESS", "result": "RESULT", "attention": "ATTENTION", "tool-candidate": "TOOL_MIGRATION", "pause":"PAUSE", "blocked":"BLOCKED", "exit":"EXIT", "resume-request":"RESUME_REQUEST", "resumed":"RESUMED"}
try:
record = host_record(args.host)
if args.command == "join":
@ -144,7 +183,11 @@ def main() -> int:
print(completed.stdout, end="")
return completed.returncode
else:
last_heartbeat = 0.0
while True:
if time.monotonic() - last_heartbeat >= max(15.0, args.heartbeat_seconds):
emit(args.host, "HEARTBEAT", ["@ALL"], args.task_id, {"courier_online": True, "model_state": "UNKNOWN_UNLESS_CURRENT_HOST_AGENT_REFRESHES", "note": "courier heartbeat proves delivery-organ presence only"}, [])
last_heartbeat = time.monotonic()
completed = subprocess.run(["python3", str(CONSOLE), "mentions", "--development-id", record["development_id"]], text=True, capture_output=True, timeout=30)
print(completed.stdout, end="", flush=True)
time.sleep(max(0.5, args.interval))

View file

@ -51,7 +51,19 @@ class MultipathConsoleTest(unittest.TestCase):
def test_product_source_stays_blocked(self):
value = MODULE.status()
self.assertFalse(value["product_source_write_allowed"])
self.assertEqual(value["reason"], "ONLINE_ARCHITECTURE_AND_LOCAL_PRODUCT_LINE_GUARDS_NOT_READY")
self.assertTrue(value["language_world_development_allowed"])
self.assertEqual(value["reason"], "LANGUAGE_WORLD_STAGE1_READY_PRODUCT_SOURCE_REMAINS_SEPARATELY_BLOCKED")
def test_autonomous_pause_requires_cause_and_brain_readback(self):
contract = MODULE.load(MODULE.CONTRACT)
event = {
"schema": contract["event_schema"], "event_id": "X", "console_id": "HB-MPC-0001",
"event_type": "PAUSE", "from_development_id": "HLP-TDEV-CODEX-0001", "mentions": ["@ALL"],
"emitted_at": "2026-09-09T20:00:00+08:00", "payload": {"reason":"quota"}, "evidence": [], "authority_granted": False,
}
errors = MODULE.validate_event(event, "HLP-TDEV-CODEX-0001", contract)
self.assertTrue(any(item.startswith("AUTONOMOUS_DECISION_FIELDS_REQUIRED") for item in errors))
self.assertIn("AUTONOMOUS_DECISION_BRAIN_READBACK_INVALID", errors)
if __name__ == "__main__":