#!/usr/bin/env python3 """reverse-audit.py -- route 114 rescue (job #2829): the reverse version-layer walk. Forward walk (done by #1373): returns -> accepted returns with a patch/revision -> /history of their targets -> the 10 documents with a return-authored version. This instrument walks the other way: served corpus (GET /docs, recursive) -> GET /history/ for EVERY served path -> every version record carrying a return_id and then tests the four pre-registered claims in `prereg-reverse-audit.md`, whose falsifiers were written before this file existed. Endpoints read only; no credential is printed; each response body is saved verbatim under `hist/` so the classification is re-derivable offline. python3 reverse-audit.py # full walk, writes reverse-audit.json python3 reverse-audit.py --check # re-derive verdicts from hist/ only (no network) python3 reverse-audit.py --list-only # enumerate the served corpus, then stop """ import argparse import hashlib import json import os import sys import urllib.error import urllib.request BASE = "https://solveathome.org/projects/twin-primes" TOK = os.path.join(os.environ.get("LOCALAPPDATA", ""), "solveathome", "credentials", "twin-primes.token") ROOT = os.path.dirname(os.path.abspath(__file__)) HIST = os.path.join(ROOT, "hist") FORWARD = {"13", "20", "80", "83", "85", "92", "101", "151", "152", "153"} CUT_AFTER = "2026-09-16T10:42:21" SAMPLE = ["research/fixed-endpoint-discrepancy.md", "research/QUESTIONS.md", "research/OUTCOMES.md", "MIRROR.md", "README.md", "research/centered-discrepancy-estimate.md"] # A request with no HTTP response at all. The value stays 0 so consumers that test `code == 0` # keep their branch, and the NAME plus the note below make an uncertain receipt self-describing # (sahtool 1.3.1 discipline, promoted 2026-09-22). TRANSPORT_FAILED = 0 def transport_note(code): if code == TRANSPORT_FAILED: return {"transport_failed": True, "code_means": "no HTTP response at all", "retry": "retry with the same request"} return {"transport_failed": False, "uncertain": code >= 500, "code_means": "HTTP status"} def get(path, token): req = urllib.request.Request(BASE + path, headers={ "Accept": "application/json", "Authorization": "Bearer " + token, "User-Agent": "sahreq/1.0"}, method="GET") try: with urllib.request.urlopen(req, timeout=90) as r: return r.status, r.read().decode("utf-8", "replace") except urllib.error.HTTPError as e: return e.code, e.read().decode("utf-8", "replace") except urllib.error.URLError as e: return TRANSPORT_FAILED, json.dumps({"error": str(e)}) def entries(path, token): """One served listing -> (dirs, files) in the listing's own order.""" code, body = get(path, token) if code != 200: raise SystemExit("listing %s -> %s %s" % (path, code, body[:200])) dirs, files = [], [] for tok in body.split(): if tok.endswith("/"): dirs.append(tok.rstrip("/")) else: files.append(tok) return dirs, files def enumerate_corpus(token): """Depth-first over the served listing, parents before children, listing order kept. A listing returns BARE names, not paths: `/docs/research` answers `01-zone-twin-share.js`, and the served path is `research/01-zone-twin-share.js`. Joining them is what this function is for, and getting it wrong is invisible on the wire -- `/history/` answers HTTP 200 with `versions: []` for a path that is not served, so a mis-joined walk reports "no versions anywhere", which reads exactly like a clean negative. The pre-registered controls C1/C2 are what catch it (they did, on the first run of this instrument). """ order, root_dirs, root_files = [], *entries("/docs", token) order.extend(root_files) stack = [(d, d) for d in root_dirs] while stack: rel, name = stack.pop(0) dirs, files = entries("/docs/" + rel, token) order.extend(rel + "/" + f for f in files) stack.extend((rel + "/" + d, d) for d in dirs) return order def slug(path): return path.replace("/", "__") def load_hist(path): f = os.path.join(HIST, slug(path) + ".json") if not os.path.exists(f): return None try: return json.load(open(f, encoding="utf-8")) except Exception: # noqa: BLE001 return None def classify(path, h): vs = (h or {}).get("versions") or [] authored = [v for v in vs if v.get("return_id")] served = ((h or {}).get("timestamps") or {}).get("sha256") newest = max(vs, key=lambda v: v.get("version", 0)) if vs else None # Amendment 1: the literal `created_at > 2026-09-16T10:42:21Z` threshold was inherited from the # obstacle's NEW-cut detector and excludes the known cut by one millisecond (v3 is created at # 2026-09-16T10:42:20.999Z). Corrected definition, content-based, with the literal reading kept # beside it so both are visible in the artifact rather than only the flattering one. cut = [v for v in vs if not v.get("return_id") and ( "cut of 2026-09-16" in (v.get("summary") or "") or (v.get("created_at") or "") >= CUT_AFTER[:-1])] cut_literal = [v for v in vs if not v.get("return_id") and (v.get("created_at") or "") > CUT_AFTER] return { "path": path, "read": h is not None, # `/history/` answers HTTP 200 with `versions: []` for a path that is NOT served. # An empty record is therefore not evidence of absence and is counted separately. "empty_record": (h is not None and not vs and not ((h or {}).get("publications") or [])), "n_versions": len(vs), "version_ids": [v.get("version") for v in vs], "return_authored": [{"return_id": v["return_id"], "version": v.get("version"), "content_sha": v.get("content_sha"), "created_at": v.get("created_at"), "verified_by": v.get("verified_by") or []} for v in authored], "served_sha": served, "newest_version": newest.get("version") if newest else None, "newest_is_return_authored": bool(newest and newest.get("return_id")), "newest_sha": newest.get("content_sha") if newest else None, "live_propagation": bool(newest and newest.get("return_id") and newest.get("content_sha") == served), "cut_versions": [{"version": v.get("version"), "created_at": v.get("created_at"), "content_sha": v.get("content_sha"), "summary": (v.get("summary") or "")[:120]} for v in cut], "cut_versions_literal_threshold": [v.get("version") for v in cut_literal], "n_publications": len((h or {}).get("publications") or []), "source_state": next((p.get("source", {}).get("state") for p in (h or {}).get("publications") or [] if p.get("source")), None), } def main(): ap = argparse.ArgumentParser() ap.add_argument("--check", action="store_true", help="offline: re-derive from hist/") ap.add_argument("--list-only", action="store_true") a = ap.parse_args() os.makedirs(HIST, exist_ok=True) listing_file = os.path.join(ROOT, "served-listing.json") if a.check: saved = json.load(open(listing_file, encoding="utf-8")) listing = {k: saved[k] for k in ("at", "endpoint", "n", "sha256")} listing["paths"] = saved["paths"] unread = [] else: token = open(TOK, encoding="utf-8").read().strip() paths = enumerate_corpus(token) import datetime listing = {"at": datetime.datetime.now(datetime.timezone.utc).strftime( "%Y-%m-%dT%H:%M:%SZ"), "endpoint": "/docs (recursive)", "paths": paths, "n": len(paths), "sha256": hashlib.sha256( "\n".join(paths).encode()).hexdigest()} json.dump(listing, open(listing_file, "w", encoding="utf-8", newline="\n"), indent=1, ensure_ascii=False) if a.list_only: print(json.dumps({"n_paths": len(paths), "paths": paths[:20]}, indent=1)) return 0 unread = [] for i, p in enumerate(paths, 1): code, body = get("/history/" + p, token) if code != 200: unread.append({"path": p, "code": code, "transport": transport_note(code)}) continue with open(os.path.join(HIST, slug(p) + ".json"), "w", encoding="utf-8", newline="\n") as fh: fh.write(body) sys.stderr.write("\r%d/%d %s " % (i, len(paths), p[:60])) sys.stderr.write("\n") rows = [] for p in listing["paths"]: rows.append(classify(p, load_hist(p))) # ---- the pre-registered sets ------------------------------------------------------------- R, per_return = set(), {} for r in rows: for a_ in r["return_authored"]: rid = str(a_["return_id"]) R.add(rid) per_return.setdefault(rid, []).append({"path": r["path"], "version": a_["version"]}) multi = [r["path"] for r in rows if r["n_versions"] > 1] research_multi = [p for p in multi if p.startswith("research/") and p.endswith(".md")] # C2 is written against the TOP-LEVEL listing `GET /docs/research` (141 documents, one slash), # which is what this run's own 2026-09-22 sweep read. Subdirectory notes are counted beside it. research_top_multi = [p for p in research_multi if p.count("/") == 1] live = [r["path"] for r in rows if r["live_propagation"]] reverted = [r["path"] for r in rows if r["return_authored"] and not r["live_propagation"]] f1 = sorted(R - FORWARD) f2 = sorted(FORWARD - R) no_cut = [r["path"] for r in rows if r["return_authored"] and not r["cut_versions"]] no_cut_literal = [r["path"] for r in rows if r["return_authored"] and not r["cut_versions_literal_threshold"]] reverted_bytewise = [r["path"] for r in rows if r["return_authored"] and any(c["content_sha"] == r["served_sha"] for c in r["cut_versions"])] out = { "job": 2829, "route": 114, "tool": "reverse-audit.py/1.0", "listing": {k: listing[k] for k in ("endpoint", "n", "sha256")}, "unread": unread, "n_rows": len(rows), "multi_version_paths": multi, "n_multi_version": len(multi), "research_md_multi_version": research_multi, "n_research_md_multi_version": len(research_multi), "research_top_level_md_multi_version": research_top_multi, "n_research_top_level_md_multi_version": len(research_top_multi), "reverse_return_ids": sorted(R, key=int), "forward_return_ids": sorted(FORWARD, key=int), "per_return": per_return, "F1_reverse_not_in_forward": f1, "F2_forward_not_in_reverse": f2, "F3_live_propagation": live, "F4_return_authored_without_cut_version": no_cut, "F4_literal_threshold_artifact": no_cut_literal, "bytewise_reverted_paths": reverted_bytewise, "n_bytewise_reverted": len(reverted_bytewise), "return_authored_paths": [r["path"] for r in rows if r["return_authored"]], "n_return_authored_paths": len(reverted), "rows": rows, "verdicts": { "P1_reverse_equals_forward": not f1, "P2_forward_recovered": not f2, "P3_no_live_propagation": not live, "P4_every_overlay_path_has_cut_version": not no_cut, }, } json.dump(out, open(os.path.join(ROOT, "reverse-audit.json"), "w", encoding="utf-8", newline="\n"), indent=1, ensure_ascii=False, sort_keys=True) print(json.dumps({ "n_paths": out["listing"]["n"], "n_unread": len(unread), "n_empty_records": sum(1 for r in rows if r["empty_record"]), "n_multi_version": out["n_multi_version"], "research_top_level_md_multi_version": out["n_research_top_level_md_multi_version"], "research_md_multi_all_depths": out["n_research_md_multi_version"], "reverse_return_ids": out["reverse_return_ids"], "return_authored_paths": out["return_authored_paths"], "F1": f1, "F2": f2, "F3": live, "F4": no_cut, "F4_literal_threshold_artifact": no_cut_literal, "n_bytewise_reverted": out["n_bytewise_reverted"], "verdicts": out["verdicts"], }, indent=1, ensure_ascii=False)) return 0 if __name__ == "__main__": sys.exit(main())