Files
rune/scripts/close_contract_inference_trace.py
Nick a0537fe04a chore(store): close inference_trace dichotomy contract BUILDER-2026-10-14T20:00:12Z-7ba2e4-factory-gap-dk (parity a3b6544b; landed port b5228ace, phase B e41562aa)
Walked draft->approved->building->verifying->closed in ONE process via
the designed iface.close() entry (quality-gate law). Contract covers the
inference_trace 4/6 -> 8/8 RUST gap-close: record_trace/read_traces IO
ported into the kernel + three parity-driven defect fixes (ensure_ascii
escaping, limit-0 all-lines, malformed-line ValueError class via
Err-envelope + fallback re-raise) — quirks #24-#26.
2026-10-14 21:04:03 +01:00

171 lines
7.9 KiB
Python

#!/usr/bin/env python3
"""Close the #2479 dichotomy-wave inference_trace gap contract (Rust IO
port) in ONE process (shared-store clobber hazard; segment transitions
can take ~60s each — do NOT split across processes).
QUALITY-GATE LAW (scaffold.py, 2026-10-13): entering `closed` happens via
iface.close(contract_id, observed_evidence=..., scope_files=...) — the
predicted-vs-observed quality computation — never a raw transition.
Resumable: if an open factory-gap-dk contract already exists in the store
(e.g. a prior walk stopped at `verifying`), the LATEST is resumed and
duplicates are abandoned with a note. Otherwise the canonical
submit_need → approved → building → verifying walk runs first.
Usage: close_contract_inference_trace.py
"""
import json
import os
import sys
from pathlib import Path
REPO = Path(__file__).resolve().parents[1]
os.environ.setdefault(
"CS_RUST_LIB",
str(REPO / "src" / "rust" / "capability_scoring" / "target" / "release" / "libcapability_scoring.so"),
)
sys.path.insert(0, str(REPO / "src"))
from rune.construction_interface import ConstructionInterface
PARITY_SHA = "fca6cfc7"
LANDED_PORT = "b5228ace"
LANDED_PHASE_B = "e41562aa"
EVIDENCE = f"parity {PARITY_SHA}"
NEED_TEXT = (
"inference_trace dichotomy gap-close (RUST): name-preserving port of "
"the 2 audit-missing IO functions (record_trace, read_traces) into "
"src/rust/inference_trace with the file IO itself in the kernel "
"(mkdir, I1 source-guard rotation replace chain, O_APPEND write, file "
"reads; path resolution stays the facade's _trace_path seam and the "
"facade passes module rotation knobs read at call time so the "
"TRACE_ROTATE_BYTES monkeypatch contract survives) + it_record_trace/"
"it_read_traces FFI + it_loader wrappers + facade delegation with "
"byte-identical _py_record_trace/_py_read_traces fallbacks "
"(RUNE_IT_CORE=python pin). Extends the landed FULL port "
f"{LANDED_PORT} + phase B {LANDED_PHASE_B} without duplicating it. "
"Parity-driven defect fixes proven by the frozen truth: serialize/"
"format_record ensure_ascii escaping (json.dumps \\uXXXX lowercase, "
"astral surrogate pairs vs raw UTF-8 — quirk #24), limit=0 "
"lines[-0:] keeps ALL lines (read_select + cli_tail — quirk #25), "
"malformed JSONL line ValueError crash class via Err-envelope + "
"facade fallback re-raise (quirk #26). Frozen truth: 17-case gap "
"corpus via the shared freeze_truth.py harness + scripts/"
"it_freeze_seams rig (RUNE_IT_CORE=python, relative RUNE_HOME, "
"cwd-is-the-rig, row-private stores; rotation matrix, unicode line "
"law, limit 0/2/99, missing stores, crash class, round-trip), gen x2 "
"+ --verify x2 byte-identical; gap_battery.rs replays it VERBATIM in "
"a throwaway cwd (cargo test 9/9). Live parity scripts/"
"check_inference_trace_parity.py: seam 17/17 + FFI composites 17/17. "
"Landed PARITY=1 flow preserved byte-identical modulo the original "
"freeze's baked worktree root. cargo build + clippy -D warnings + fmt "
"clean; Python suite both pins 108/108 (p1_03 memory_selection "
"failures pre-exist at pristine HEAD, outside this cone). Dichotomy "
"audit 4/6 PARTIAL -> 8/8 FULL (wave at 125/192 FULL). Delivered on "
"gitea/master: feat " + PARITY_SHA + "."
)
OBSERVED_DETAIL = (
f"inference_trace RUST dichotomy completion — parity commit {PARITY_SHA} "
f"(extends landed port {LANDED_PORT} + phase B {LANDED_PHASE_B}); fn "
"coverage 4/6 PARTIAL -> 8/8 FULL (audit regenerated, row now 8/8 "
"RUST; wave FULL 65% = 125/192). Frozen truth 17 harness cases "
"byte-identical across gen x2 and freeze_truth --verify x2 "
"(src/rust/inference_trace/src/frozen_it_gap_truth.json, scripts/"
"gen_inference_trace_gap_truth.py + scripts/it_freeze_seams rig); "
"cargo battery replays it verbatim (gap_battery.rs; 9/9 incl. the "
"landed truth_battery) with cli_tail count-0 consistency pinned; "
"live parity 17/17 seam + 17/17 FFI composites via scripts/"
"check_inference_trace_parity.py; landed PARITY=1 flow byte-identical "
"modulo the original freeze's baked worktree root. clippy -D warnings "
"+ cargo fmt clean. Python suite green both pins (108/108 live + "
"108/108 RUNE_IT_CORE=python over test_p0_07_inference_trace + "
"inference_paths + p1_01/02/06/07 consumers; test_p1_03 "
"memory_selection failures proven pre-existing at pristine HEAD via "
"git stash, outside this port's cone). Fix-first: ensure_ascii py_"
"escape emitter (quirk #24), limit-0 all-lines quirk (quirk #25), "
"malformed-line Err envelope + authentic re-raise via fallback "
"(quirk #26) — all in docs/dichotomy-oracle-quirks.json. Documented "
"divergences: kernel parse-error MESSAGE text differs cross-language "
"(class pinned, message rides the fallback); fs::rename vs "
"os.replace identical on POSIX. Evidence files: verification/it-*."
"{log,exit} + verification/summary-inference_trace.md."
)
SCOPE_FILES = [
"src/rune/inference_trace.py",
"src/rune/it_loader.py",
"src/rust/inference_trace/src/lib.rs",
"src/rust/inference_trace/src/truth_battery.rs",
"src/rust/inference_trace/src/gap_battery.rs",
"src/rust/inference_trace/src/frozen_it_gap_truth.json",
"scripts/gen_inference_trace_gap_truth.py",
"scripts/it_freeze_seams/sitecustomize.py",
"scripts/check_inference_trace_parity.py",
"scripts/close_contract_inference_trace.py",
"docs/dichotomy-rebase-honest-audit.md",
"docs/dichotomy-oracle-quirks.json",
"verification/summary-inference_trace.md",
]
iface = ConstructionInterface(builder="factory-gap-dk")
# ── resume-or-submit ────────────────────────────────────────────────────────
def _open_factory_gap_dk(d):
found = []
for ent in d.get("entities", []):
cid = ent.get("id", "")
if isinstance(cid, str) and cid.startswith("contract:BUILDER-") \
and cid.endswith("factory-gap-dk") \
and ent.get("phase") not in ("closed", "abandoned", "failed"):
found.append((cid[len("contract:"):], ent.get("phase")))
return sorted(found)
doc = iface.scaffold.load()
existing = _open_factory_gap_dk(doc)
if existing:
cid, phase = existing[-1] # latest wins
print(f"resuming contract {cid} (phase {phase}); "
f"{len(existing) - 1} duplicate(s) to abandon")
for dup_cid, _ in existing[:-1]:
r = iface.transition(dup_cid, "abandoned",
evidence_ref="duplicate submission — close walk "
"retried after a refused raw "
"closed transition (quality-gate law)")
print(f"abandoned {dup_cid}:", "ok" if r.get("success") else json.dumps(r)[:200])
if not r.get("success"):
sys.exit(1)
else:
r = iface.submit_need(NEED_TEXT, origin="builder")
print("submit_need:", json.dumps(r)[:300])
if not r.get("success"):
print("NEED FAILED — aborting")
sys.exit(1)
cid = r["ids"]["contract_id"]
print("contract_id:", cid)
for phase in ("approved", "building", "verifying"):
t = iface.transition(cid, phase, evidence_ref=EVIDENCE)
ok = t.get("success")
print(f"transition->{phase}:", "ok" if ok else json.dumps(t)[:300])
if not ok:
sys.exit(1)
# ── the designed entry to `closed`: close() computes contract_quality ──────
c = iface.close(cid, observed_evidence=[{
"kind": "port_evidence",
"detail": OBSERVED_DETAIL,
}], scope_files=SCOPE_FILES)
print("close:", json.dumps(c)[:300])
if not c.get("success"):
sys.exit(1)
doc = iface.scaffold.load()
e = iface.scaffold.contract(doc, cid)
print("FINAL PHASE:", e.get("phase") if e else "MISSING")
if not e or e.get("phase") != "closed":
sys.exit(1)
print("CLOSED", cid)