feat(heartbeat): add four-host HoloLake control console

This commit is contained in:
冰朔 2026-09-09 19:45:20 +08:00
commit 5ca2c9d66f
39 changed files with 1784 additions and 27 deletions

View file

@ -0,0 +1,253 @@
#!/usr/bin/env python3
"""Read-derived control panel for the same-persona four-host HoloLake experiment."""
from __future__ import annotations
import argparse
import importlib.util
import json
import time
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
ROOT = Path(__file__).resolve().parents[2]
CONTROL = ROOT / "eternal-lake-heart/heartbeat-core/office-building-current/control-center/HB-MPC-0001"
REGISTRY = CONTROL / "HOST-REGISTRY.json"
CONTRACT = CONTROL / "EVENT-CONTRACT.json"
TASKS = CONTROL / "TASK-BOARD.json"
OFFICE_COMPUTER = ROOT / "eternal-lake-heart/heartbeat-core/office-building-current/offices/HB-OFFICE-HOLOLAKE-0001/smart-computer/office_computer.py"
MODEL_ROUTER = ROOT / "server-tools/persona-model-smart-router/openlux_router.py"
def load(path: Path) -> dict[str, Any]:
value = json.loads(path.read_text())
if not isinstance(value, dict):
raise ValueError(f"JSON_OBJECT_REQUIRED:{path}")
return value
def module(path: Path, name: str):
spec = importlib.util.spec_from_file_location(name, path)
if spec is None or spec.loader is None:
raise ValueError(f"MODULE_LOAD_FAILED:{path}")
value = importlib.util.module_from_spec(spec)
spec.loader.exec_module(value)
return value
def live_time() -> dict[str, Any]:
return module(OFFICE_COMPUTER, "hb_office_computer").clock()
def validate_event(event: Any, expected_development_id: str, contract: dict[str, Any]) -> list[str]:
errors: list[str] = []
if not isinstance(event, dict):
return ["EVENT_OBJECT_REQUIRED"]
for field in contract["required"]:
if field not in event:
errors.append(f"FIELD_REQUIRED:{field}")
if event.get("schema") != contract["event_schema"]:
errors.append("EVENT_SCHEMA_MISMATCH")
if event.get("console_id") != "HB-MPC-0001":
errors.append("CONSOLE_ID_MISMATCH")
if event.get("from_development_id") != expected_development_id:
errors.append("DEVELOPMENT_ID_ENDPOINT_MISMATCH")
if event.get("event_type") not in contract["event_types"]:
errors.append("EVENT_TYPE_UNREGISTERED")
if not isinstance(event.get("mentions"), list):
errors.append("MENTIONS_LIST_REQUIRED")
else:
known = {item["development_id"] for item in load(REGISTRY)["hosts"]} | {"@ALL"}
if any(item not in known for item in event["mentions"]):
errors.append("MENTION_TARGET_UNKNOWN")
if not isinstance(event.get("payload"), dict):
errors.append("PAYLOAD_OBJECT_REQUIRED")
if not isinstance(event.get("evidence"), list):
errors.append("EVIDENCE_LIST_REQUIRED")
if event.get("authority_granted") is not False:
errors.append("AUTHORITY_MUST_REMAIN_FALSE")
try:
datetime.fromisoformat(str(event.get("emitted_at", "")))
except ValueError:
errors.append("EMITTED_AT_INVALID")
return errors
def scan() -> dict[str, Any]:
registry, contract = load(REGISTRY), load(CONTRACT)
events: list[dict[str, Any]] = []
invalid: list[dict[str, Any]] = []
hosts: list[dict[str, Any]] = []
for host in registry["hosts"]:
endpoint = Path(host["endpoint"])
host_events: list[dict[str, Any]] = []
if endpoint.is_dir():
for path in sorted(endpoint.glob("*.json")):
try:
if path.is_symlink() or path.stat().st_size > 262_144:
invalid.append({"path": str(path), "errors": ["EVENT_FILE_UNSAFE"]})
continue
event = load(path)
errors = validate_event(event, host["development_id"], contract)
if errors:
invalid.append({"path": str(path), "errors": errors})
else:
event["_path"] = str(path)
host_events.append(event)
events.append(event)
except Exception as error:
invalid.append({"path": str(path), "errors": [type(error).__name__]})
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)
latest = host_events[-1] if host_events else None
hosts.append({
"host": host["host"],
"development_id": host["development_id"],
"role_hypothesis": host["role_hypothesis"],
"endpoint": str(endpoint),
"endpoint_exists": endpoint.is_dir(),
"joined": register is not None,
"event_count": len(host_events),
"last_event_at": latest and latest["emitted_at"],
"last_heartbeat_at": heartbeat and heartbeat["emitted_at"],
})
events.sort(key=lambda item: item["emitted_at"])
counts: dict[str, int] = {}
for event in events:
counts[event["event_id"]] = counts.get(event["event_id"], 0) + 1
for event_id, count in counts.items():
if count > 1:
invalid.append({"path": None, "errors": [f"DUPLICATE_EVENT_ID:{event_id}"]})
return {"hosts": hosts, "events": events, "invalid_events": invalid}
def panel() -> dict[str, Any]:
scanned, task_board = scan(), load(TASKS)
events = scanned["events"]
task_states = {item["task_id"]: {**item, "dynamic_events": []} for item in task_board["tasks"]}
messages = []
attention = []
migrations = []
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"}:
task_states[task_id]["dynamic_events"].append({k: event.get(k) for k in ["event_id", "event_type", "from_development_id", "emitted_at", "payload", "evidence"]})
if event["event_type"] in {"MESSAGE", "ACK"}:
messages.append({k: event.get(k) for k in ["event_id", "event_type", "from_development_id", "mentions", "emitted_at", "payload"]})
elif event["event_type"] == "ATTENTION":
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"]})
return {
"schema": "guanghu.heartbeat-multipath-live-panel/v1",
"panel_id": "HB-MPC-PANEL-0001",
"state": "LIVE_DERIVED_READ_ONLY",
"time": live_time(),
"persona_id": "ICE-P-ZY001",
"same_persona_not_four_personas": True,
"hosts": scanned["hosts"],
"tasks": list(task_states.values()),
"messages": messages[-40:],
"attention_observations": attention[-40:],
"tool_migration_candidates": migrations[-40:],
"invalid_events": scanned["invalid_events"],
"event_count": len(events),
"panel_persisted": False,
"authority_granted": False,
}
def status() -> dict[str, Any]:
value = panel()
joined = sum(1 for item in value["hosts"] if item["joined"])
return {
"outcome": "PASS",
"console_id": "HB-MPC-0001",
"panel_id": value["panel_id"],
"bus_id": "HB-MPC-BUS-0001",
"advisor_id": "HB-MPC-ADVISOR-0001",
"time": value["time"],
"joined_hosts": joined,
"total_hosts": 4,
"event_count": value["event_count"],
"invalid_event_count": len(value["invalid_events"]),
"product_source_write_allowed": False,
"reason": "ONLINE_ARCHITECTURE_AND_LOCAL_PRODUCT_LINE_GUARDS_NOT_READY",
}
def mentions(development_id: str) -> dict[str, Any]:
value = panel()
known = {item["development_id"] for item in value["hosts"]}
if development_id not in known:
raise ValueError("DEVELOPMENT_ID_UNKNOWN")
selected = [item for item in value["messages"] if development_id in item["mentions"] or "@ALL" in item["mentions"]]
return {"outcome": "PASS", "development_id": development_id, "time": value["time"], "messages": selected}
def audit() -> dict[str, Any]:
registry, contract, task_board = load(REGISTRY), load(CONTRACT), load(TASKS)
errors = []
ids = [item["development_id"] for item in registry.get("hosts", [])]
if ids != ["HLP-TDEV-CODEX-0001", "HLP-TDEV-ZCODE-0001", "HLP-TDEV-QWEN-0001", "HLP-TDEV-DOUBAO-0001"]:
errors.append("FOUR_HOST_IDS_MISMATCH")
if len({item["endpoint"] for item in registry["hosts"]}) != 4:
errors.append("HOST_ENDPOINTS_NOT_UNIQUE")
if contract.get("transport") != "FILESYSTEM_POLLING_NEAR_REALTIME_NOT_ZERO_LATENCY_PUSH":
errors.append("TRANSPORT_TRUTH_MISMATCH")
if task_board.get("shared_file_is_definition_not_live_mutation_target") is not True:
errors.append("TASK_BOARD_MULTIWRITER_RISK")
scanned = scan()
if scanned["invalid_events"]:
errors.append("INVALID_HOST_EVENTS_PRESENT")
return {"outcome": "PASS" if not errors else "FAIL", "errors": errors, "host_count": len(ids), "valid_event_count": len(scanned["events"]), "time": live_time()}
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"]}
router = module(MODEL_ROUTER, "hb_mpc_model_router")
result = router.route({
"parent_persona_id": "ICE-P-ZY001",
"child_agent_id": "SUBAGENT::ICE-P-ZY001::HB-MPC-ADVISOR-0001",
"controller": "ICE-P-ZY001",
"channel_id": "ICE-CH-HB001",
"agent_role": "FOUR_HOST_COLLABORATION_REASONING_ADVISOR",
"authority": "REASONING_ONLY_NO_WRITE_NO_EXECUTION_NO_PERSONA_SETTER",
"task": "综合以下四宿主协作面板。只给出下一轮任务调整、依赖、冲突、证据缺口和要发送给各临时开发编号的通信建议;不得声称执行,不得修改人格认知。\n" + json.dumps(safe_panel, ensure_ascii=False),
"complexity": "HIGH",
"selection_policy": "QUALITY_FIRST",
})
return {"outcome": result["outcome"], "advisor_id": "HB-MPC-ADVISOR-0001", "selected_model": result["selected_model"], "selection_policy": result["selection_policy"], "recommendation": result["response"], "response_sha256": result["response_sha256"], "persisted": False, "authority_granted": False}
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("command", choices=["status", "panel", "mentions", "audit", "advise", "watch"], nargs="?", default="status")
parser.add_argument("--development-id")
parser.add_argument("--interval", type=float, default=2.0)
args = parser.parse_args()
try:
if args.command == "status": result = status()
elif args.command == "panel": result = panel()
elif args.command == "mentions": result = mentions(args.development_id or "")
elif args.command == "audit": result = audit()
elif args.command == "advise": result = advise()
else:
while True:
print(json.dumps(panel(), ensure_ascii=False, indent=2), flush=True)
time.sleep(max(0.5, args.interval))
if args.command != "watch":
print(json.dumps(result, ensure_ascii=False, indent=2))
return 0 if result.get("outcome", "PASS") == "PASS" else 2
return 0
except KeyboardInterrupt:
return 0
except Exception as error:
print(json.dumps({"outcome": "FAIL", "error": str(error)}, ensure_ascii=False))
return 2
if __name__ == "__main__":
raise SystemExit(main())