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__":

View file

@ -48,10 +48,10 @@ class Tests(unittest.TestCase):
def test_current_evolution_and_old_sequence_boundary(self):
value = C.timeline()
self.assertEqual(value["current"]["node_id"], "HB-MPC-0001")
self.assertEqual(value["current"]["node_id"], "HLP-STAGE1-NATIVE-REGISTRY-001")
current = C.load(C.CURRENT)
self.assertIsNone(current["current_product_module"])
self.assertEqual(current["current_generation_module_numbering"], "NOT_YET_REDERIVED")
self.assertEqual(current["current_generation_module_numbering"], "HLP-NATIVE-MOD-001_TO_018_REDERIVED")
def test_brain_loader_returns_current_generation(self):
value = L.load("恢复HoloLake开发线")

View file

@ -0,0 +1,64 @@
#!/usr/bin/env python3
import json
from pathlib import Path
import unittest
ROOT = Path(__file__).resolve().parents[2]
SHELF = ROOT / "eternal-lake-heart/heartbeat-core/office-building-current/offices/HB-OFFICE-HOLOLAKE-0001/smart-bookshelf/009-stage1-language-world-native"
REGISTRY = SHELF / "MODULE-REGISTRY.json"
GATES = SHELF / "ACCEPTANCE-GATES.json"
class NativeStage1Test(unittest.TestCase):
def setUp(self):
self.registry = json.loads(REGISTRY.read_text())
self.modules = self.registry["modules"]
self.by_id = {item["module_id"]: item for item in self.modules}
def test_exact_current_18_module_numbers(self):
expected = [f"HLP-NATIVE-MOD-{number:03d}" for number in range(1, 19)]
self.assertEqual([item["module_id"] for item in self.modules], expected)
self.assertEqual(self.registry["module_count"], 18)
self.assertEqual(self.registry["generation"], "HLP-GEN-LANGUAGE-WORLD-NATIVE-0001")
def test_dependencies_are_known_and_acyclic(self):
known = set(self.by_id)
graph = {item["module_id"]: set(item["depends_on"]) for item in self.modules}
self.assertTrue(all(deps <= known for deps in graph.values()))
visiting, visited = set(), set()
def visit(node):
self.assertNotIn(node, visiting, f"cycle at {node}")
if node in visited: return
visiting.add(node)
for dep in graph[node]: visit(dep)
visiting.remove(node); visited.add(node)
for node in graph: visit(node)
def test_dual_git_is_foundation_and_never_mixes_private_data(self):
self.assertEqual(self.by_id["HLP-NATIVE-MOD-001"]["gate"], "G0")
self.assertEqual(self.by_id["HLP-NATIVE-MOD-002"]["gate"], "G0")
self.assertIn("NO_USER_DATA_PUSH", self.by_id["HLP-NATIVE-MOD-001"]["data_boundary"])
self.assertIn("NO_AUTO_UPLOAD", self.by_id["HLP-NATIVE-MOD-002"]["data_boundary"])
self.assertIn("NO_SHARED_PERSONA_SESSION_CONCURRENCY", self.registry["product_runtime"])
def test_canvas_agents_and_deterministic_organs_are_split(self):
self.assertEqual(self.by_id["HLP-NATIVE-MOD-006"]["component_type"], "DETERMINISTIC_COMPOSITION_GRAPH_RUNTIME")
self.assertEqual(self.by_id["HLP-NATIVE-MOD-007"]["component_type"], "MODEL_BACKED_POOL_STEWARD_AGENT")
self.assertEqual(self.by_id["HLP-NATIVE-MOD-010"]["component_type"], "DETERMINISTIC_CANVAS_LAYOUT_AND_RENDER_RUNTIME")
self.assertEqual(self.by_id["HLP-NATIVE-MOD-011"]["component_type"], "MODEL_BACKED_PROJECTION_AGENT")
def test_human_review_and_regulatory_visibility_are_stage_one(self):
self.assertEqual(self.by_id["HLP-NATIVE-MOD-014"]["gate"], "G4")
self.assertEqual(self.by_id["HLP-NATIVE-MOD-016"]["gate"], "G5")
self.assertIn("NOT_GOVERNMENT_SYSTEM", self.by_id["HLP-NATIVE-MOD-016"]["authority"])
self.assertIn("NO_REAL_TRUST_ROOT", self.by_id["HLP-NATIVE-MOD-017"]["authority"])
def test_gate_membership_covers_every_module_once(self):
gates = json.loads(GATES.read_text())["gates"]
flattened = [module for gate in gates for module in gate["modules"]]
self.assertEqual(set(flattened), set(self.by_id))
self.assertEqual(len(flattened), len(set(flattened)))
if __name__ == "__main__":
unittest.main()

View file

@ -61,6 +61,8 @@ class SharedPersonaContextTest(unittest.TestCase):
self.assertEqual(brain['generation']['id'], 'HLP-GEN-LANGUAGE-WORLD-NATIVE-0001')
self.assertFalse(brain['legacy_may_override_current'])
self.assertEqual(brain['multipath_console']['console_id'], 'HB-MPC-0001')
self.assertEqual(brain['stage1']['registry_id'], 'HLP-STAGE1-NATIVE-REGISTRY-001')
self.assertEqual(brain['stage1']['module_count'], 18)
if __name__ == '__main__':

View file

@ -46,7 +46,7 @@ function expandPattern(value) {
function validateQueuedEvent(host, eventPath) {
const rule = POLICY.hosts[host];
if (!rule || rule.write_mode !== "BRANCH_LOCAL_ONLY") throw new Error("HOST_NOT_ACTIVE_BRANCH");
if (!rule || rule.role !== "REPLACEABLE_HOST" || !["BRANCH_LOCAL_ONLY", "HOST_LOCAL_UNLESS_ACTIVE_ZERO_CORE_CONSOLE"].includes(rule.write_mode)) throw new Error("HOST_NOT_ACTIVE_BRANCH");
const real = fs.realpathSync(eventPath);
if (!real.includes("/ingress/persona-events/pending/")) throw new Error("EVENT_NOT_IN_PENDING_INGRESS");
const allowed = rule.allowed_write_roots.some((item) => new RegExp(`^${expandPattern(item)}(?:/.*)?$`).test(real));
@ -74,20 +74,15 @@ if (command === "caller") {
process.exit(caller === "codex" ? 0 : 2);
}
if (command !== "accept") {
process.stderr.write("usage: branch-event-door.mjs caller | accept --host HOST --event PENDING_JSON\n");
process.exit(2);
}
if (caller !== "codex") {
process.stderr.write(`BRANCH_EVENT_ACCEPT_REJECTED caller=${caller}; only current Codex primary task may accept\n`);
if (!['validate', 'accept'].includes(command)) {
process.stderr.write("usage: branch-event-door.mjs caller | validate --host HOST --event PENDING_JSON | accept --host HOST --event PENDING_JSON\n");
process.exit(2);
}
const host = argsValue(args, "--host");
const eventPath = argsValue(args, "--event");
if (!host || !eventPath) {
process.stderr.write("accept requires --host and --event\n");
process.stderr.write(`${command} requires --host and --event\n`);
process.exit(2);
}
@ -98,6 +93,16 @@ catch (error) {
process.exit(2);
}
if (command === "validate") {
process.stdout.write(`${JSON.stringify({ outcome: "PASS", state: "BRANCH_EVENT_PREFLIGHT_VALID", host, event_id: checked.event.event_id, event_path: checked.real, shared_write_performed: false }, null, 2)}\n`);
process.exit(0);
}
if (caller !== "codex") {
process.stderr.write(`BRANCH_EVENT_ACCEPT_REJECTED caller=${caller}; only current Codex primary task may accept\n`);
process.exit(2);
}
const run = spawnSync(process.execPath, [RUNNER, "append", "--allowed-root", MEMORY_ROOT, "--store", STORE, "--event", checked.real], { encoding: "utf8" });
if (run.status !== 0 || !run.stdout.includes('"outcome": "PASS"')) {
process.stderr.write(run.stderr || run.stdout || "BRANCH_EVENT_APPEND_FAILED\n");

View file

@ -39,6 +39,9 @@ class RootAgentTest(unittest.TestCase):
self.assertEqual(MODULE.resolve(output, 'ORG-FD-LTH-SANITIZER-001', None)['result']['object_kind'], 'DETERMINISTIC_SANITIZATION_AND_HASH_GUARD')
self.assertEqual(MODULE.resolve(output, 'SYS-GLW-ELH-ENG-0001', None)['result']['object_kind'], 'FIFTH_DOMAIN_PRIVATE_LANGUAGE_ENGINEERING_SYSTEM')
self.assertEqual(MODULE.resolve(output, 'HLP-LANG-PROJ-STAGE1-0001', None)['result']['lifecycle'], 'VERIFIED_DONOR_FROZEN_NOT_CURRENT_PRODUCT_SEQUENCE')
self.assertEqual(MODULE.resolve(output, 'HLP-STAGE1-NATIVE-REGISTRY-001', None)['result']['object_kind'], 'HOLOLAKE_LANGUAGE_WORLD_NATIVE_STAGE1_MODULE_REGISTRY')
self.assertEqual(MODULE.resolve(output, 'HLP-NATIVE-MOD-001', None)['result']['lifecycle'], 'REGISTERED_REQUIREMENTS_DEFINED_IMPLEMENTATION_NOT_STARTED')
self.assertEqual(MODULE.resolve(output, 'CH-ZERO-CORE-LPM', None)['result']['object_kind'], 'PUBLIC_LANGUAGE_PERSONA_SYSTEM_CHANNEL')
again = MODULE.refresh(ROOT, output, pointer, 'test')
self.assertEqual(again['state'], 'CURRENT_IDEMPOTENT')