#!/usr/bin/env python3 """Job #4466 / route 128 step check: does the record answer #1828's next step? Reads only the served artefacts saved under ``outputs/job4466/served/`` (fetched by ``fetch_served.py``; every file hashed against what the return publishes) and the workspace-local evidence the job produced (the ``git apply --check`` of #1828's patch against the two registry baselines). Stdlib only. Progress to stdout, the JSON result to ``stepcheck4466.json`` (or argv[1]). Exit 0 iff every check passes. A missing input is reported as a FAILED check, not a crash. Checks, in one place: A. route state and the step as served B. the version lineage of the four step paths (v3 == v1 reverted; v2 accepted) C. return #1954: an accepted, verified revision of ``corner-correlation.md`` recorded AFTER the step was set, served as v4 D. the registry-cell consequence, from the served generator's own cell sources E. baseline drift: the step's named target ``cda1e669`` is not the served registry, and #1828's patch no longer applies to the served bytes F. the three paths with no later version """ import difflib import hashlib import json import os import re import shutil import subprocess import sys HERE = os.path.dirname(os.path.abspath(__file__)) def find_root(start): p = start while True: if os.path.isdir(os.path.join(p, ".solveathome")): return p nxt = os.path.dirname(p) if nxt == p: raise SystemExit("workspace root not found from " + start) p = nxt ROOT = find_root(HERE) SERVED = os.environ.get("STEPCHECK_SERVED") or os.path.join(ROOT, "outputs", "job4466", "served") SCRATCH = os.environ.get("STEPCHECK_SCRATCH") or os.path.join(ROOT, "outputs", "job4466", "scratch_git") BLOCK_RE = re.compile(r"") # The four step paths and the return that carries each accepted v2. PATHS = { "corner": ("research/corner-correlation.md", "92"), "fold": ("research/fold-arithmetic-bridge.md", "101"), "derive": ("research/history/staging/derive-0904-L7-transfer.md", "152"), "prop": ("paper/proposals/prop-staircase-note.md", "13"), } # The cells the served generator builds a registry row from (research/qc/questions.js). CELL_FIELDS = ["id", "status", "question", "verdict"] CHECKS = [] FAILED = [] def check(name, ok, detail=""): CHECKS.append({"id": len(CHECKS) + 1, "name": name, "ok": bool(ok), "detail": detail}) print("%-4s %s%s" % ("PASS" if ok else "FAIL", name, (" -- " + detail) if detail else "")) if not ok: FAILED.append(len(CHECKS)) return bool(ok) def load_json(path): try: with open(path, encoding="utf-8") as fh: return json.load(fh) except Exception: # noqa: BLE001 -- a missing/corrupt input is a FAILED check return {} def body(rec): return rec.get("body", rec) if isinstance(rec, dict) else rec def read_text(path): try: with open(path, "rb") as fh: return fh.read().decode("utf-8") except OSError: return "" def sha_of(path): try: with open(path, "rb") as fh: return hashlib.sha256(fh.read()).hexdigest() except OSError: return "" def ledger_fields(text): m = BLOCK_RE.search(text) if not m: return None out = {} for ln in m.group(1).split("\n"): if ":" in ln: k, v = ln.split(":", 1) out[k.strip()] = v.strip() return out def version_file(tag, n): return os.path.join(SERVED, "ver", "%s_v%d.md" % (tag, n)) def ver_text(tag, n): return read_text(version_file(tag, n)) def line_diff(a, b): d = list(difflib.unified_diff(a.split("\n"), b.split("\n"), lineterm="", n=0)) minus = [x for x in d if x[:1] == "-" and x[:3] != "---"] plus = [x for x in d if x[:1] == "+" and x[:3] != "+++"] return minus, plus def _force_rmtree(path): """rmtree that clears the read-only bit git sets on its object files (Windows).""" def onerr(func, p, exc): try: os.chmod(p, 0o700) func(p) except OSError: pass shutil.rmtree(path, onerror=onerr) def git_apply_check(tag, questions_file): """Recreate the served tree for one registry baseline and `git apply --check` #1828's patch. Output goes to a file (no pipes). Returns (exit_code, message).""" d = os.path.join(SCRATCH, tag, "research") if os.path.isdir(os.path.join(SCRATCH, tag)): _force_rmtree(os.path.join(SCRATCH, tag)) os.makedirs(d) shutil.copyfile(os.path.join(SERVED, "centered_served.md"), os.path.join(d, "centered-discrepancy-estimate.md")) shutil.copyfile(os.path.join(SERVED, "global_served.md"), os.path.join(d, "global-factor-signs.md")) shutil.copyfile(questions_file, os.path.join(d, "QUESTIONS.md")) patch = os.path.join(SERVED, "f1828_restore-83-153.patch") logp = os.path.join(SCRATCH, tag, "apply.log") with open(logp, "wb") as log: for cmd in (["git", "init", "-q", "."], ["git", "add", "-A"], ["git", "-c", "user.email=a@b", "-c", "user.name=t", "commit", "-qm", "base"], ["git", "apply", "--check", patch]): r = subprocess.run(cmd, cwd=os.path.join(SCRATCH, tag), stdout=log, stderr=log) code = r.returncode txt = read_text(logp) msg = "" for ln in txt.split("\n"): if "patch failed" in ln or "does not apply" in ln or "error:" in ln: msg = ln.strip() break # per-file: is the QUESTIONS hunk the failing one? return code, msg, txt def main(): out_path = sys.argv[1] if len(sys.argv) > 1 else os.path.join(HERE, "stepcheck4466.json") print("job #4466 route 128 step check; served dir", os.path.relpath(SERVED, ROOT)) required = ["route-128.json", "return-1828.json", "return-1954.json", "h_corner.json", "h_fold.json", "h_derive.json", "h_prop.json", "h_questions.json", "h_centered.json", "h_global.json", "doc_corner_served.md", "Q_B.md", "Q_v8.md", "Q_v10.md", "qc_questions.js", "f1828_others-ledger-3289.json", "f1828_restore-83-153.patch", "centered_served.md", "global_served.md"] required += ["ver/%s_v%d.md" % (t, n) for t in PATHS for n in (1, 2, 3)] required += ["ver/corner_v4.md"] missing = [r for r in required if not os.path.exists(os.path.join(SERVED, r))] check("0 every required served input is present", not missing, "missing=%s" % missing) # ---------------------------------------------------------------- A: route try: route = body(load_json(os.path.join(SERVED, "route-128.json"))) check("A1 route 128 record loads", isinstance(route, dict)) except Exception as e: # noqa: BLE001 check("A1 route 128 record loads", False, repr(e)) route = {} step = route.get("next_step") or {} check("A2 route 128 last_return_id is the step setter 1828", str(route.get("last_return_id")) == "1828", "last_return_id=%s" % route.get("last_return_id")) check("A3 route 128 state active, revision 7", route.get("state") == "active" and route.get("revision") == 7, "state=%s revision=%s" % (route.get("state"), route.get("revision"))) q = str(step.get("question", "")) check("A4 step names exactly the four paths #92/#101/#152/#13", all(s in q for s in ["#92", "#101", "#152", "#13"]) and all(s in q for s in ["corner-correlation", "fold-arithmetic-bridge", "derive-0904-L7-transfer", "prop-staircase-note"])) r1828 = body(load_json(os.path.join(SERVED, "return-1828.json"))) check("A5 #1828 is the step return and its own snapshot is 2026-09-26", str(r1828.get("id")) == "1828" and str(r1828.get("created_at", "")).startswith("2026-09-26"), "created_at=%s" % r1828.get("created_at")) # -------------------------------------------------- B: lineage of the four hist = {} for tag in PATHS: try: hist[tag] = body(load_json(os.path.join(SERVED, "h_%s.json" % tag))) except Exception as e: # noqa: BLE001 check("B0 history %s loads" % tag, False, repr(e)) hist[tag] = {"versions": []} for tag, (rel, ret) in PATHS.items(): h = hist[tag] vs = h.get("versions", []) sha = {v["version"]: v["content_sha"] for v in vs} want_n = 4 if tag == "corner" else 3 check("B1 %s has %d versions" % (tag, want_n), len(vs) == want_n, "versions=%d" % len(vs)) check("B2 %s v3 == v1 (the 2026-09-16 mirror cut reverts the note)" % tag, len(vs) >= 3 and sha.get(3) == sha.get(1)) check("B3 %s v2 is return #%s and differs from v1" % (tag, ret), len(vs) >= 2 and str(vs[1].get("return_id")) == ret and sha.get(2) != sha.get(1), "v2_return=%s" % (vs[1].get("return_id") if len(vs) > 1 else None)) check("B4 %s served content (timestamps.sha256) equals its newest version" % tag, h.get("timestamps", {}).get("sha256") == sha.get(len(vs)), "served=%s" % str(h.get("timestamps", {}).get("sha256"))[:16]) check("B5 corner v2 bytes are return #92's revision (sha e1f59410)", sha_of(version_file("corner", 2)).startswith("e1f59410")) # ------------------------------------------------------------- C: #1954/v4 served_corner = read_text(os.path.join(SERVED, "doc_corner_served.md")) check("C1 served corner-correlation.md == corner v4 bytes", hashlib.sha256(served_corner.encode("utf-8")).hexdigest() == hist["corner"]["versions"][3]["content_sha"]) r1954 = body(load_json(os.path.join(SERVED, "return-1954.json"))) check("C2 #1954 is accepted/verified and its revision_path is corner-correlation.md", r1954.get("status") == "accepted" and r1954.get("final_rung") == "verified" and r1954.get("revision_path") == PATHS["corner"][0], "status=%s rung=%s path=%s" % (r1954.get("status"), r1954.get("final_rung"), r1954.get("revision_path"))) check("C3 #1954's revision_sha is the served v4 sha", r1954.get("revision_sha") == hist["corner"]["versions"][3]["content_sha"]) check("C4 #1954 was recorded after #1828 set the step", str(r1954.get("created_at")) > str(r1828.get("created_at")), "%s > %s" % (r1954.get("created_at"), r1828.get("created_at"))) v2c, v4c = ver_text("corner", 2), ver_text("corner", 4) v1c = ver_text("corner", 1) v2_only = [ln for ln in v2c.split("\n") if ln.strip() and ln not in v4c.split("\n")] v4_only = [ln for ln in v4c.split("\n") if ln.strip() and ln not in v2c.split("\n")] check("C5 v4 is not a superset of v2: each has text the other lacks", bool(v2_only) and bool(v4_only), "v2-only lines=%d, v4-only lines=%d" % (len(v2_only), len(v4_only))) check("C6 v2's prime-power reading paragraph is absent from v4", any("The prime-power reading." in ln for ln in v2_only)) check("C7 v4's 2026-09-27 source correction is absent from v2", any("Source correction (2026-09-27)." in ln for ln in v4_only)) check("C8 v4's body does not carry v2's added hunks (v4 differs from v1 in the source table only)", "The prime-power reading." not in v4c and "The prime-power reading." in v2c and "The prime-power reading." not in v1c) # ------------------------------------------------------ D: registry cells gen = read_text(os.path.join(SERVED, "qc_questions.js")) check("D1 served generator builds rows from id/status/question/verdict only", "for (const k of ['id', 'status', 'question', 'verdict'])" in gen) check("D2 served generator's drift check compares section-2 row lines only (not prose/unindexed)", "section 2's rows -- and nothing else" in gen) cell_result = {} for tag in ["corner", "fold", "derive"]: f1 = ledger_fields(ver_text(tag, 1)) f2 = ledger_fields(ver_text(tag, 2)) if f1 is None or f2 is None: check("D3.%s ledger block present in v1 and v2" % tag, False) continue keys = sorted(set(f1) | set(f2)) changed = [k for k in keys if f1.get(k) != f2.get(k)] cells = [k for k in changed if k in CELL_FIELDS] cell_result[tag] = {"changed_fields": changed, "changed_cells": cells, "verdict_v1_len": len(f1.get("verdict", "")), "verdict_v2_len": len(f2.get("verdict", ""))} if tag == "derive": check("D3.derive restoring #152 v2 changes the verdict ledger field", cells == ["verdict"], "changed=%s" % changed) check("D4.derive the two verdict lengths differ by >100 chars (pre-#152 text is served)", abs(len(f2.get("verdict", "")) - len(f1.get("verdict", ""))) > 100, "%d -> %d" % (len(f1.get("verdict", "")), len(f2.get("verdict", "")))) check("D5.derive status does NOT change (PARTIAL both)", f1.get("status") == f2.get("status") == "PARTIAL") else: check("D3.%s restoring v2 changes no registry cell field" % tag, cells == [], "changed=%s" % changed) hist["questions"] = body(load_json(os.path.join(SERVED, "h_questions.json"))) pf = [ledger_fields(ver_text("prop", n)) for n in (1, 2, 3)] check("D6 prop-staircase-note carries no ledger block in any version", all(f is None for f in pf)) others = load_json(os.path.join(SERVED, "f1828_others-ledger-3289.json")) dv = others.get(PATHS["derive"][0], {}) check("D7 #1828's others-ledger records verdict_same=true for derive, contradicting D3", dv.get("verdict_same") is True, "recorded verdict_same=%s vs served v1/v2 verdicts (%d vs %d chars)" % (dv.get("verdict_same"), cell_result.get("derive", {}).get("verdict_v1_len", -1), cell_result.get("derive", {}).get("verdict_v2_len", -1))) check("D8 #1828's own report says the other three were 'Not measured here'", "Not measured here" in read_text(os.path.join(SERVED, "return-1828.json"))) # --------------------------------------------------- E: baseline drift qB = read_text(os.path.join(SERVED, "Q_B.md")) q10 = read_text(os.path.join(SERVED, "Q_v10.md")) q8 = read_text(os.path.join(SERVED, "Q_v8.md")) check("E1 the step's named target cda1e669 is #1828's B output", sha_of(os.path.join(SERVED, "Q_B.md")).startswith("cda1e669")) check("E2 served QUESTIONS.md is v10 a3e07372, not cda1e669", hist["questions"]["versions"][-1]["version"] == 10 and hist["questions"]["timestamps"]["sha256"].startswith("a3e07372")) minus, plus = line_diff(qB, q10) check("E3 B -> served v10 moves 13 lines (the step's baseline is stale)", len(minus) == 10 and len(plus) == 13, "-%d +%d" % (len(minus), len(plus))) centered10 = [l for l in q10.split("\n") if "Q-centered-discrepancy-estimate" in l] global10 = [l for l in q10.split("\n") if "Q-global-factor-signs" in l] check("E4 #83/#153 still read PARTIAL in the served v10 registry (4 cells, patch not integrated)", len(centered10) == 2 and len(global10) == 2 and all("| PARTIAL |" in l for l in centered10 + global10)) check("E5 restore-83-153.patch targets QUESTIONS v8 bytes (its base hash is ccf2cf0f)", sha_of(os.path.join(SERVED, "Q_v8.md")).startswith("ccf2cf0f")) try: code8, msg8, _ = git_apply_check("v8", os.path.join(SERVED, "Q_v8.md")) code10, msg10, _ = git_apply_check("v10", os.path.join(SERVED, "Q_v10.md")) check("E6 control: the patch git-applies to the v8 baseline (#1828's own base)", code8 == 0, "exit=%d %s" % (code8, msg8)) check("E7 treatment: the patch does NOT apply to the served v10 registry", code10 != 0, "exit=%d %s" % (code10, msg10)) check("E8 the failing file is research/QUESTIONS.md, not the two ledger notes", "QUESTIONS.md" in msg10, msg10) except FileNotFoundError as e: check("E6/E7 git apply check", False, "git unavailable: %r" % (e,)) code8 = code10 = None # ------------------------------------------------ F: the other three paths for tag in ["fold", "derive", "prop"]: vs = hist[tag].get("versions", []) check("F1 %s has no version after v3 (no later accepted edit on the path)" % tag, len(vs) == 3, "versions=%d" % len(vs)) check("F2 the registered mutation of the four is source-only: no return after #1828 " "publishes a revision of fold/derive/prop", all(hist[t]["timestamps"]["recorded_at"].startswith("2026-09-16") for t in ["fold", "derive", "prop"])) result = {"job_id": "4466", "route_id": 128, "checks": len(CHECKS), "failed": FAILED, "all_pass": not FAILED, "detail": CHECKS, "registry_cell_prediction": cell_result} with open(out_path, "w", encoding="utf-8") as fh: json.dump(result, fh, indent=1) print("\n%d checks, %d failed -> %s" % (len(CHECKS), len(FAILED), "ALL PASS" if not FAILED else "FAILURES: %s" % FAILED)) print("json ->", os.path.relpath(out_path, ROOT)) return 1 if FAILED else 0 if __name__ == "__main__": sys.exit(main())