Files
rune/scripts/gen_construction_commands_truth.py
T

714 lines
29 KiB
Python

#!/usr/bin/env python3
"""gen_construction_commands_truth.py — freeze/replay parity truth for
construction_commands (dichotomy wave, #2479 gap-close tranche).
Freeze mode (default): exercises the LIVE Python oracle
(src/rune/construction_commands.py — RUNE_CONSTRUCTION_COMMANDS_CORE
pinned python, poisoned-truth law) across every command/branch and
records (input, expected) pairs into
src/rust/construction_commands/frozen_cc_truth.json.
Replay mode (--replay): re-runs the SAME scenarios with the Rust core
delegation ACTIVE (pin lifted post-import) and asserts both kernel-level
(loader direct) and facade-level (dispatch end-to-end through a real
ConstructionInterface + segment-architecture store) parity against the
frozen file.
Truth groups:
* command / dispatch_prep / dispatch_finish — kernel decision
surfaces. `command` expected values are literal oracle returns; the
prep/finish groups' expected values are the kernel surfaces the
facade consumes, derived from the oracle's observable pieces
(command() return, ledger state, interface envelope rules) — the
facade-only dispatch_exec group pins the END-TO-END equivalence.
* dispatch_exec — facade-only (real interface + segment-store IO
stays in Python): whole dispatch runs against seeded stores.
Clock law: the oracle's recorded_at seam is time.strftime(time.gmtime())
— the generator patches the ORACLE module's `time` attribute with a
frozen gmtime, so kernels receive `now` as an argument (recorded_at is
byte-stable across processes).
Idempotency-ledger law: the module-global `_outcomes` ledger evolves
across a case SEQUENCE within one process; freeze and replay run the
identical case list with unique per-case command ids, so ledger
evolution is identical. Kernel cases are otherwise stateless
(prior_outcome is an explicit input; replay-pair cases derive prior
from the oracle's own first-delivery envelope).
Hash law: PYTHONHASHSEED=0 enforced by re-exec (resume projections
derive obligation ids from hash() — frozen truth must never embed
process-random hashes).
"""
import copy
import json
import os
import shutil
import sys
import tempfile
import time as _real_time
from pathlib import Path
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TRUTH_PATH = os.path.join(REPO, "src", "rust", "construction_commands", "src",
"frozen_cc_truth.json")
REPLAY = "--replay" in sys.argv
# Hash law: determinism across processes (re-exec BEFORE any oracle work).
if os.environ.get("PYTHONHASHSEED") != "0":
os.environ["PYTHONHASHSEED"] = "0"
os.execv(sys.executable, [sys.executable] + sys.argv)
os.environ["RUNE_CONSTRUCTION_COMMANDS_CORE"] = "python" # poisoned-truth law
sys.path.insert(0, os.path.join(REPO, "src"))
from rune import scaffold as sc # noqa: E402
from rune import construction_commands as oracle_mod # noqa: E402
FROZEN_TS = 1791892800 # 2026-10-13T12:00:00Z
FROZEN_NOW = _real_time.strftime("%Y-%m-%dT%H:%M:%SZ", _real_time.gmtime(FROZEN_TS))
assert FROZEN_NOW == "2026-10-13T12:00:00Z"
class _FrozenTime:
"""Patches the ORACLE module's `time` namespace (recorded_at seam)."""
@staticmethod
def gmtime():
return _real_time.gmtime(FROZEN_TS)
@staticmethod
def strftime(fmt, t=None):
return _real_time.strftime(fmt, t)
oracle_mod.time = _FrozenTime
if REPLAY:
sys.path.insert(0, os.path.join(REPO, "src", "rune"))
import ccmd_loader # noqa: E402 (kernel-level replay side)
# replay law: the facade pass must exercise the LIVE Rust delegation
# path — the pin is lifted AFTER import (facade reads env at call time).
del os.environ["RUNE_CONSTRUCTION_COMMANDS_CORE"]
_DIR_SEQ = [0]
_CASE_SEQ = [0]
def fresh_dir():
"""Deterministic per-case dir — replay recreates the same paths."""
_DIR_SEQ[0] += 1
d = os.path.join(tempfile.gettempdir(), f"cc_truth_frozen_{_DIR_SEQ[0]:03d}")
shutil.rmtree(d, ignore_errors=True)
os.makedirs(d)
return d
class _Probe:
"""Stand-in for the serving scaffold: the validator only calls
.load(), and here it returns the PRE-LOADED doc (deep-copied per
call like a real load)."""
def __init__(self, doc):
self._doc = doc
def load(self):
return copy.deepcopy(self._doc)
def probe(doc):
return None if doc is None else _Probe(doc)
def seed_store(d, cid="c1", phase="draft", identities=None,
purpose="dichotomy truth"):
store = os.path.join(d, ".rune", "scaffold")
s = sc.Scaffold(store, "proj")
doc = s.init(purpose=purpose)
sc.add_entity(doc, id=f"contract:{cid}", kind="contract",
identities=identities if identities is not None else {"scope": []},
evidence_refs=["e"])
doc["entities"][-1]["phase"] = phase
s.commit(doc, what="seed")
return store
def run_exec(seed, specs):
"""Seed a store then run a dispatch call sequence against it
(oracle during freeze, delegated facade during replay)."""
d = fresh_dir()
store = seed_store(d, **seed)
rets = []
for spec in specs:
kwargs = copy.deepcopy(spec)
if kwargs.pop("internal", False):
cwd = os.getcwd()
os.chdir(d)
try:
rets.append(oracle_mod.dispatch(kwargs.pop("command_type"),
**kwargs))
finally:
os.chdir(cwd)
else:
kwargs["store_path"] = store + "|proj"
rets.append(oracle_mod.dispatch(kwargs.pop("command_type"),
**kwargs))
return rets
_GROUPS: dict = {}
def _rec(group, name, inp, expected):
_GROUPS.setdefault(group, []).append(
{"name": name, "input": inp, "expected": expected})
def cmd_case(rec_name, *, command_type, construction_id="c1",
correlation_id="corr-1", command_id=None, payload=None,
doc=None):
"""Kernel command case: input IS the ccm_command payload; expected is
the literal oracle `command()` return."""
_CASE_SEQ[0] += 1
cid = command_id if command_id is not None else f"cmd-k{_CASE_SEQ[0]:03d}"
doc = copy.deepcopy(doc)
ret = oracle_mod.command(
command_type, construction_id=construction_id,
correlation_id=correlation_id, command_id=cid,
payload=copy.deepcopy(payload or {}), scaffold=probe(doc),
)
inp = {"command_type": command_type, "construction_id": construction_id,
"correlation_id": correlation_id, "command_id": cid,
"payload": copy.deepcopy(payload or {}), "now": FROZEN_NOW,
"prior_outcome": None, "scaffold_doc": doc}
_rec("command", rec_name, inp, ret)
def cmd_pair_case(rec_name, *, command_type, construction_id="c1",
command_id="cmd-1", payload=None, doc=None):
"""Idempotency replay: the oracle delivers the SAME command_id twice;
prior_outcome is its own first envelope. expected = second return."""
doc = copy.deepcopy(doc)
payload0 = copy.deepcopy(payload or {})
first = oracle_mod.command(
command_type, construction_id=construction_id,
correlation_id="corr-1", command_id=command_id,
payload=copy.deepcopy(payload0), scaffold=probe(doc),
)
prior = copy.deepcopy(first)
second = oracle_mod.command(
command_type, construction_id=construction_id,
correlation_id="corr-1", command_id=command_id,
payload=copy.deepcopy(payload0), scaffold=probe(doc),
)
inp = {"command_type": command_type, "construction_id": construction_id,
"correlation_id": "corr-1", "command_id": command_id,
"payload": payload0, "now": FROZEN_NOW,
"prior_outcome": prior, "scaffold_doc": doc}
_rec("command", rec_name, inp, second)
def c_cmd_replay_accept(rec_name="command-replay-returns-prior-plus-flag"):
cmd_pair_case(rec_name, command_type="RESUME",
doc={"entities": [{"id": "contract:c1", "phase": "draft"}]})
def c_cmd_replay_refusal(rec_name="command-replay-of-refused-envelope"):
cmd_pair_case(rec_name, command_type="START",
doc={"entities": [{"id": "contract:c1", "phase": "approved"}]})
def c_cmd_unknown():
cmd_case("command-unknown-pause", command_type="PAUSE")
def c_cmd_lowercase_unknown():
cmd_case("command-vocabulary-exact-match", command_type="start")
def c_cmd_no_construction_id():
cmd_case("command-empty-construction-id-refused", command_type="RESUME",
construction_id="")
def c_cmd_no_scaffold():
cmd_case("command-no-serving-scaffold-refused", command_type="RESUME")
def c_cmd_unknown_construction():
cmd_case("command-unknown-construction-refused", command_type="RESUME",
doc={"entities": [{"id": "project:proj", "kind": "project"}]})
def c_cmd_doc_without_entities():
cmd_case("command-doc-without-entities-key", command_type="RESUME",
doc={})
def c_cmd_request_state():
cmd_case("command-request-state-accepts-read-only", command_type="REQUEST_STATE",
doc={"entities": [{"id": "project:proj", "kind": "project"},
{"id": "contract:c1", "phase": "draft"}]})
def c_cmd_request_state_closed():
# REQUEST_STATE ignores the phase entirely (read-only projection)
cmd_case("command-request-state-phase-agnostic", command_type="REQUEST_STATE",
doc={"entities": [{"id": "contract:c1", "phase": "closed"}]})
def c_cmd_resume_draft():
cmd_case("command-resume-draft-accepts", command_type="RESUME",
doc={"entities": [{"id": "contract:c1", "phase": "draft"}]})
def c_cmd_resume_closed():
cmd_case("command-resume-closed-refuses", command_type="RESUME",
doc={"entities": [{"id": "contract:c1", "phase": "closed"}]})
def c_cmd_resume_abandoned():
cmd_case("command-resume-abandoned-refuses", command_type="RESUME",
doc={"entities": [{"id": "contract:c1", "phase": "abandoned"}]})
def c_cmd_start_draft():
cmd_case("command-start-draft-accepts-approved", command_type="START",
doc={"entities": [{"id": "contract:c1", "phase": "draft"}]})
def c_cmd_start_approved():
cmd_case("command-start-approved-refuses", command_type="START",
doc={"entities": [{"id": "contract:c1", "phase": "approved"}]})
def c_cmd_pa_user():
cmd_case("command-provide-approval-user-provenance",
command_type="PROVIDE_APPROVAL", payload={"approved_by": "user"},
doc={"entities": [{"id": "contract:c1", "phase": "draft"}]})
def c_cmd_pa_missing_provenance():
cmd_case("command-provide-approval-provenance-required",
command_type="PROVIDE_APPROVAL", payload={},
doc={"entities": [{"id": "contract:c1", "phase": "draft"}]})
def c_cmd_pa_substrate():
cmd_case("command-provide-approval-substrate-refused",
command_type="PROVIDE_APPROVAL",
payload={"approved_by": "substrate"},
doc={"entities": [{"id": "contract:c1", "phase": "draft"}]})
def c_cmd_pa_building():
cmd_case("command-provide-approval-draft-only",
command_type="PROVIDE_APPROVAL", payload={"approved_by": "user"},
doc={"entities": [{"id": "contract:c1", "phase": "building"}]})
def c_cmd_ack_ok():
for phase in ("failed", "building", "verifying"):
cmd_case(f"command-acknowledge-{phase}-accepts-building",
command_type="ACKNOWLEDGE_BLOCKER",
doc={"entities": [{"id": "contract:c1", "phase": phase}]})
def c_cmd_ack_draft():
cmd_case("command-acknowledge-draft-refuses",
command_type="ACKNOWLEDGE_BLOCKER",
doc={"entities": [{"id": "contract:c1", "phase": "draft"}]})
def c_cmd_pc_authority():
cmd_case("command-context-user-authority-forged", command_type="PROVIDE_CONTEXT",
payload={"add_paths": ["src/x.py"], "approved_by": "user"},
doc={"entities": [{"id": "contract:c1", "phase": "draft"}]})
def c_cmd_pc_substrate_authority():
cmd_case("command-context-never-user-forged-substrate",
command_type="PROVIDE_CONTEXT",
payload={"add_paths": ["src/x.py"], "reason": "extra surface"},
doc={"entities": [{"id": "contract:c1", "phase": "draft"}]})
def c_cmd_pc_empty():
cmd_case("command-context-empty-add-paths-refused", command_type="PROVIDE_CONTEXT",
payload={"add_paths": []},
doc={"entities": [{"id": "contract:c1", "phase": "draft"}]})
def c_cmd_pc_missing():
cmd_case("command-context-missing-add-paths-refused", command_type="PROVIDE_CONTEXT",
payload={},
doc={"entities": [{"id": "contract:c1", "phase": "draft"}]})
def c_cmd_pc_truthy_string():
# `payload.get("add_paths") or []` passes ANY truthy value through —
# a truthy non-list rides into args (execute-side crash parity)
cmd_case("command-context-truthy-non-list-rides-through",
command_type="PROVIDE_CONTEXT", payload={"add_paths": "src"},
doc={"entities": [{"id": "contract:c1", "phase": "draft"}]})
def c_cmd_pc_reason_null():
# payload.get(key, default): a PRESENT null wins over the default
cmd_case("command-context-present-null-reason-wins", command_type="PROVIDE_CONTEXT",
payload={"add_paths": ["a"], "reason": None},
doc={"entities": [{"id": "contract:c1", "phase": "draft"}]})
def c_cmd_pc_reason_default():
cmd_case("command-context-default-reason", command_type="PROVIDE_CONTEXT",
payload={"add_paths": ["a"]},
doc={"entities": [{"id": "contract:c1", "phase": "draft"}]})
def prep_case(rec_name, *, command_type, construction_id="c1",
correlation_id="corr-1", command_id=None, payload=None,
prior=None, serving_error=None, expected=None, doc=None):
_CASE_SEQ[0] += 1
cid = command_id if command_id is not None else f"cmd-p{_CASE_SEQ[0]:03d}"
inp = {"command_type": command_type, "construction_id": construction_id,
"correlation_id": correlation_id, "command_id": cid,
"payload": copy.deepcopy(payload or {}), "now": FROZEN_NOW,
"prior_outcome": copy.deepcopy(prior),
"serving_error": serving_error, "scaffold_doc": copy.deepcopy(doc)}
_rec("dispatch_prep", rec_name, inp, expected)
def c_prep_serving_unavailable():
exc = ("import failed: " + "z" * 210)
env = {"accepted": False, "executed": False, "success": False,
"error": f"serving unavailable: {exc}"[:200],
"command_type": "START", "construction_id": "c1"}
prep_case("dispatch-prep-serving-unavailable-truncated", command_type="START",
serving_error=exc,
expected={"kind": "final", "record": False, "envelope": env})
def c_prep_serving_unavailable_unicode():
# s[:200] slices CHARACTERS — a multibyte exc makes byte-truncation
# (the char-vs-byte quirk) observable
exc = "失败" * 150
env = {"accepted": False, "executed": False, "success": False,
"error": f"serving unavailable: {exc}"[:200],
"command_type": "START", "construction_id": "c1"}
assert len(env["error"]) == 200 # codepoints, not bytes
prep_case("dispatch-prep-serving-unavailable-rune-truncation",
command_type="START", serving_error=exc,
expected={"kind": "final", "record": False, "envelope": env})
def c_prep_replay():
prior = {"accepted": True, "op": "resume",
"args": {"contract_id": "c1"}, "command_id": "cmd-1",
"construction_id": "c1", "correlation_id": "corr-1",
"recorded_at": "2026-10-13T11:00:00Z", "idempotent_replay": False}
env = {"accepted": True, "executed": False, "success": True,
"idempotent_replay": True, "op": "resume",
"command_type": "RESUME", "construction_id": "c1",
"correlation_id": "corr-1", "command_id": "cmd-1"}
prep_case("dispatch-prep-replay-no-second-execution", command_type="RESUME",
prior=prior,
expected={"kind": "final", "record": False, "envelope": env})
def c_prep_refusal():
doc = {"entities": [{"id": "contract:c1", "phase": "approved"}]}
reason = "START requires draft phase (current: approved)"
intent = {"accepted": False, "reason": reason, "command_id": "cmd-r01",
"construction_id": "c1", "correlation_id": "corr-1",
"recorded_at": FROZEN_NOW, "idempotent_replay": False}
env = {"accepted": False, "executed": False, "success": True,
"reason": reason, "command_type": "START",
"construction_id": "c1", "correlation_id": "corr-1",
"command_id": "cmd-r01", "idempotent_replay": False}
prep_case("dispatch-prep-refusal-is-protocol-outcome", command_type="START",
command_id="cmd-r01", doc=doc,
expected={"kind": "final", "record": True, "intent": intent,
"envelope": env})
def _intent(op, args, cid="cmd-x01", construction_id="c1"):
return {"accepted": True, "op": op, "args": args, "command_id": cid,
"construction_id": construction_id, "correlation_id": "corr-1",
"recorded_at": FROZEN_NOW, "idempotent_replay": False}
def c_prep_exec_start():
doc = {"entities": [{"id": "contract:c1", "phase": "draft"}]}
prep_case("dispatch-prep-exec-start", command_type="START", command_id="cmd-x01", doc=doc,
expected={"kind": "exec", "record": True, "op": "transition",
"args": {"contract_id": "c1", "phase": "approved"},
"evidence_ref": "command:cmd-x01",
"intent": _intent("transition", {"contract_id": "c1",
"phase": "approved"})})
def c_prep_exec_approval_provenance():
doc = {"entities": [{"id": "contract:c1", "phase": "draft"}]}
args = {"contract_id": "c1", "phase": "approved", "approved_by": "user"}
prep_case("dispatch-prep-exec-approval-provenance-suffix",
command_type="PROVIDE_APPROVAL", payload={"approved_by": "user"},
command_id="cmd-x01", doc=doc,
expected={"kind": "exec", "record": True, "op": "transition",
"args": args,
"evidence_ref": "command:cmd-x01 approved_by:user",
"intent": _intent("transition", args)})
def c_prep_exec_amend():
doc = {"entities": [{"id": "contract:c1", "phase": "draft"}]}
args = {"contract_id": "c1", "add_paths": ["a"],
"reason": "substrate context", "authority": "substrate"}
prep_case("dispatch-prep-exec-amend-scope", command_type="PROVIDE_CONTEXT",
payload={"add_paths": ["a"]}, command_id="cmd-x01", doc=doc,
expected={"kind": "exec", "record": True, "op": "amend_scope",
"args": args, "evidence_ref": "",
"intent": _intent("amend_scope", args)})
def c_prep_exec_request_state():
doc = {"entities": [{"id": "contract:c1", "phase": "draft"}]}
args = {"contract_id": "c1"}
prep_case("dispatch-prep-exec-request-state-resume", command_type="REQUEST_STATE",
command_id="cmd-x01", doc=doc,
expected={"kind": "exec", "record": True, "op": "resume",
"args": args, "evidence_ref": "",
"intent": _intent("resume", args)})
def finish_case(rec_name, env, intent=None, command_type="START",
construction_id="c1"):
intent = intent or {"accepted": True, "op": "transition",
"args": {"contract_id": construction_id},
"command_id": "cmd-1", "construction_id": construction_id,
"correlation_id": "corr-1", "recorded_at": FROZEN_NOW,
"idempotent_replay": False}
expected = {"accepted": True, "executed": True,
"success": bool(env.get("success")),
"envelope": copy.deepcopy(env),
"command_type": command_type,
"construction_id": construction_id,
"correlation_id": intent.get("correlation_id", ""),
"command_id": intent.get("command_id", ""),
"idempotent_replay": False}
inp = {"command_type": command_type, "construction_id": construction_id,
"intent": copy.deepcopy(intent), "env": copy.deepcopy(env)}
_rec("dispatch_finish", rec_name, inp, expected)
def c_finish_success():
finish_case("dispatch-finish-success-transition-envelope",
{"schema": 1, "operation": "transition", "success": True,
"ids": {"contract_id": "c1"}, "state": {"phase": "approved"},
"evidence": [], "errors": [], "warnings": []})
def c_finish_failure():
finish_case("dispatch-finish-failure-carries-envelope",
{"schema": 1, "operation": "transition", "success": False,
"ids": {"contract_id": "c1"}, "state": {},
"evidence": [], "errors": [{"error": "VERIFICATION_FAILED",
"detail": "boom"}],
"warnings": []})
def c_finish_truthiness_string():
finish_case("dispatch-finish-success-truthy-string", {"success": "yes"})
def c_finish_truthiness_zero():
finish_case("dispatch-finish-success-falsy-zero", {"success": 0})
def c_finish_truthiness_missing():
finish_case("dispatch-finish-success-missing-key-falsy", {"ids": {}})
def c_finish_truthiness_null():
finish_case("dispatch-finish-success-null-falsy", {"success": None})
def c_finish_passthrough_ids():
intent = {"accepted": True, "op": "resume", "args": {"contract_id": "zz"},
"command_id": "cmd-77", "construction_id": "zz",
"correlation_id": "corr-77", "recorded_at": FROZEN_NOW,
"idempotent_replay": False}
finish_case("dispatch-finish-command-provenance-passthrough",
{"success": True, "ids": {"contract_id": "zz"}}, intent=intent,
command_type="RESUME", construction_id="zz")
# ── facade-only group: dispatch END-TO-END through real stores ──────────────
def exec_case(rec_name, seed, specs):
rets = run_exec(seed, specs)
_rec("dispatch_exec", rec_name,
{"seed": seed, "specs": copy.deepcopy(specs)}, rets)
def c_exec_start_end_to_end():
exec_case("dispatch-exec-start-moves-draft-to-approved",
{"cid": "c1"},
[{"command_type": "START", "construction_id": "c1",
"command_id": "cmd-start-1"}])
def c_exec_second_start_refused():
exec_case("dispatch-exec-second-start-refused", {"cid": "c1"},
[{"command_type": "START", "construction_id": "c1",
"command_id": "cmd-first"},
{"command_type": "START", "construction_id": "c1",
"command_id": "cmd-second"}])
def c_exec_idempotent_replay():
spec = {"command_type": "START", "construction_id": "c1",
"command_id": "cmd-idem-1"}
exec_case("dispatch-exec-idempotent-replay-no-double-execution",
{"cid": "c1"}, [spec, dict(spec)])
def c_exec_resume_projection():
exec_case("dispatch-exec-resume-read-only-projection",
{"cid": "c1", "phase": "building",
"identities": {"scope": ["src/a.py"],
"need": "build the thing",
"origin": "builder", "resolution": "BUILD",
"toolchain": {"selected_language": "python"}}},
[{"command_type": "RESUME", "construction_id": "c1",
"command_id": "cmd-resume-1"}])
def c_exec_unknown_command():
exec_case("dispatch-exec-pause-refused-not-in-vocabulary", {"cid": "c1"},
[{"command_type": "PAUSE", "construction_id": "c1",
"command_id": "cmd-pause-1"}])
def c_exec_provide_context_amends():
exec_case("dispatch-exec-provide-context-amends-scope-sorted",
{"cid": "c1", "identities": {"scope": ["src/m.py"]}},
[{"command_type": "PROVIDE_CONTEXT", "construction_id": "c1",
"command_id": "cmd-ctx-1",
"payload": {"add_paths": ["zeta.py", "alpha.py"]}},
{"command_type": "RESUME", "construction_id": "c1",
"command_id": "cmd-ctx-2"}])
def c_exec_acknowledge_blocker():
exec_case("dispatch-exec-acknowledge-blocker-retries-building",
{"cid": "c1", "phase": "failed"},
[{"command_type": "ACKNOWLEDGE_BLOCKER", "construction_id": "c1",
"command_id": "cmd-ack-1"}])
def c_exec_rune_internal_sandbox():
# rune-internal mode (default store_path) against an EMPTY cwd — a
# hermetic fresh store is served, so unknown construction refuses
# deterministically without touching the real repo store
exec_case("dispatch-exec-rune-internal-fresh-store-refused", {},
[{"command_type": "REQUEST_STATE", "construction_id": "ghost",
"command_id": "cmd-sandbox-1", "internal": True}])
def c_exec_provenance_refusal():
exec_case("dispatch-exec-substrate-cannot-approve", {"cid": "c1"},
[{"command_type": "PROVIDE_APPROVAL", "construction_id": "c1",
"command_id": "cmd-pas-1",
"payload": {"approved_by": "substrate"}}])
CASES = [
c_cmd_replay_accept, c_cmd_replay_refusal, c_cmd_unknown,
c_cmd_lowercase_unknown, c_cmd_no_construction_id, c_cmd_no_scaffold,
c_cmd_unknown_construction, c_cmd_doc_without_entities,
c_cmd_request_state, c_cmd_request_state_closed, c_cmd_resume_draft,
c_cmd_resume_closed, c_cmd_resume_abandoned, c_cmd_start_draft,
c_cmd_start_approved, c_cmd_pa_user, c_cmd_pa_missing_provenance,
c_cmd_pa_substrate, c_cmd_pa_building, c_cmd_ack_ok, c_cmd_ack_draft,
c_cmd_pc_authority, c_cmd_pc_substrate_authority, c_cmd_pc_empty,
c_cmd_pc_missing, c_cmd_pc_truthy_string, c_cmd_pc_reason_null,
c_cmd_pc_reason_default,
c_prep_serving_unavailable, c_prep_serving_unavailable_unicode,
c_prep_replay, c_prep_refusal, c_prep_exec_start,
c_prep_exec_approval_provenance, c_prep_exec_amend,
c_prep_exec_request_state,
c_finish_success, c_finish_failure, c_finish_truthiness_string,
c_finish_truthiness_zero, c_finish_truthiness_missing,
c_finish_truthiness_null, c_finish_passthrough_ids,
c_exec_start_end_to_end, c_exec_second_start_refused,
c_exec_idempotent_replay, c_exec_resume_projection,
c_exec_unknown_command, c_exec_provide_context_amends,
c_exec_acknowledge_blocker, c_exec_rune_internal_sandbox,
c_exec_provenance_refusal,
]
def main():
if REPLAY:
# the replay side consumes the frozen file ONLY — the freeze
# case-runners must NOT re-run through the delegated facade
# here (they would evolve the module ledger before the
# comparison passes and turn fresh deliveries into replays)
with open(TRUTH_PATH) as f:
groups = json.load(f)["cases"]
else:
for c in CASES:
c()
groups = _GROUPS
total = sum(len(v) for v in groups.values())
if REPLAY:
failures = 0
checked = 0
for group, cases in groups.items():
for case in cases:
spec = CALLS.get(group)
if spec is None:
continue
checked += 1
got = spec(copy.deepcopy(case["input"]))
want = copy.deepcopy(case["expected"])
if got != want:
failures += 1
print(f"DIVERGE [{group}] {case['name']}")
print(" got: ", json.dumps(got, sort_keys=True,
default=str)[:600])
print(" want:", json.dumps(want, sort_keys=True,
default=str)[:600])
print(f"replay: {checked - failures}/{checked} ({total} recorded)")
return 1 if failures else 0
doc = {
"frozen": FROZEN_NOW,
"oracle": "src/rune/construction_commands.py",
"pin": "RUNE_CONSTRUCTION_COMMANDS_CORE=python + PYTHONHASHSEED=0",
"note": ("Frozen via scripts/gen_construction_commands_truth.py against the "
"live Python oracle; the oracle's recorded_at time seam patched to "
+ FROZEN_NOW + ". Kernel groups (command, dispatch_prep, "
"dispatch_finish) replay through ccm_loader; the dispatch_exec "
"group is facade-only (real ConstructionInterface + segment-store "
"IO stays in Python)."),
"cases": groups,
}
os.makedirs(os.path.dirname(TRUTH_PATH), exist_ok=True)
with open(TRUTH_PATH, "w") as f:
json.dump(doc, f, indent=1)
f.write("\n")
print(f"frozen {total} cases → {os.path.relpath(TRUTH_PATH, REPO)}")
return 0
CALLS = {
"command": lambda i: ccmd_loader.command(i),
"dispatch_prep": lambda i: ccmd_loader.dispatch(i),
"dispatch_finish": lambda i: ccmd_loader.dispatch_finish(i),
"dispatch_exec": lambda i: run_exec(i["seed"], i["specs"]),
}
if __name__ == "__main__":
sys.exit(main())