#!/usr/bin/env python3 """reversion-audit.py -- the COMPLETE served-inventory reversion audit (route 128, job 2962). What it does differently from the two instruments already on the record. Return #1400 swept the 141 documents of `research/*.md`; return #1556 swept 56 *candidate paths* taken from the served RETURN RECORDS' `revision_path` field. Both are subsets of the served tree, and #1556's set is derived from another artifact's bookkeeping -- a document whose revision was reverted without a return record naming it cannot be seen there at all. This instrument asks the SERVING LAYER ITSELF what it holds: it walks the `/docs` listings recursively (20 directories, 1211 files on 2026-09-24), asks `/history/` for every one of them, and classifies each version list. Classification (endpoints only; SHA-256 decides, no content computation enters the test): * `single_version_control` -- 1 version: cannot be a revert; the negative control population. * `three_version_revert` -- sha(v3) == sha(v1) != sha(v2) AND the served `/docs` bytes hash to v1. The discarded middle version carries `return_id` and `verified_by`, so "an accepted revision is not being served" is a field of the record, not an inference. * `three_version_but_served_elsewhere` -- same sha pattern with the served bytes NOT equal to v1: the pattern-without-reversion negative control. * `three_version_other`, `two_versions`, `many_versions`, `no_history`. For every revert the discarded blob is fetched by sha and diffed against the served bytes twice: raw, and whitespace-normalised (internal runs collapsed, blank lines dropped). `norm_change == 0` with `raw_change > 0` is pure reflow/link-stripping and is reported as `cosmetic`; `norm_change > 0` is `substantive` and the changed normalised lines are shown, because "the flags matter" is the route's weakest assumption and a line count is not an answer to it. python3 reversion-audit.py --state [--limit N] [--offline] """ import argparse import difflib import hashlib import json import os import re import sys HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) import sahget # noqa: E402 BASE = "https://solveathome.org/projects/twin-primes" STATUS = re.compile(r"\b(OPEN|ANSWERED|PARTIAL|REFUTED|CLOSED|SHAPE-ONLY|SUPERSEDED|ACCEPTED|" r"ROBUST|STALE|STALE-REVISION|RESOLVED|BLOCKED|PENDING)\b") ROW = re.compile(r"^\|\s*`(Q-[A-Za-z0-9._-]+)`\s*\|([^|]*)\|") LINK = re.compile(r"\[([^\]]*)\]\([^)]*\)") HEAD = re.compile(r"^#{1,4}\s+(.*)$") def norm_lines(text): out = [] for ln in (text or "").splitlines(): s = re.sub(r"\s+", " ", ln).strip() if s: out.append(s) return out def norm_lines_nolink(text): """The stronger normalisation a link-stripping mirror pass would need: `[text](target)` -> text. Return #1402 read one of these documents as "reflow/link-stripping only"; a count that survives BOTH normalisations cannot be explained by whitespace or by links, which is the point of carrying the second one. """ return [LINK.sub(r"\1", s) for s in norm_lines(text)] def headings(text): return [m.group(1).strip() for m in (HEAD.match(l) for l in (text or "").splitlines()) if m] def _diff_lines(x, y): return sum(1 for l in difflib.unified_diff(x, y, n=0, lineterm="") if l[:1] in "+-" and not l.startswith(("+++", "---"))) def changed(a, b): """(normalised changed-line count, raw changed-line count) between two texts.""" return (_diff_lines(norm_lines(a), norm_lines(b)), _diff_lines((a or "").splitlines(), (b or "").splitlines())) def changed_examples(a, b, limit=4): """The changed normalised lines themselves, tagged with which side they are on.""" ex = [] for l in difflib.unified_diff(norm_lines(a), norm_lines(b), n=0, lineterm=""): if l[:1] in "+-" and not l.startswith(("+++", "---")): ex.append(l[:160]) if len(ex) >= limit: break return ex def inventory(g, root=""): """Walk the /docs listings recursively. A trailing slash is a directory.""" files, dirs, todo, seen = [], [], [root], set() while todo: d = todo.pop() if d in seen: continue seen.add(d) code, data, _ = g.get("%s/docs%s" % (BASE, "/" + d if d else "")) if code != 200: dirs.append({"dir": d or "/", "listing": code}) continue dirs.append({"dir": d or "/", "listing": 200}) for n in data.decode("utf-8", "replace").splitlines(): n = n.strip() if not n: continue p = (d + "/" + n) if d else n (todo.append(p.rstrip("/")) if n.endswith("/") else files.append(p)) return sorted(set(files)), dirs def classify(g, path): rec = {"path": path, "prefix": path.split("/")[0]} code, data, meta = g.get("%s/history/%s" % (BASE, path)) if code != 200: rec["kind"] = "no_history" rec["http"] = code return rec try: h = json.loads(data) except Exception: # noqa: BLE001 rec["kind"] = "unparsable_history" return rec vs = h.get("versions") or [] rec["n_versions"] = len(vs) rec["version_shas"] = [v.get("content_sha") for v in vs] rec["version_returns"] = [v.get("return_id") for v in vs] rec["version_verified_by"] = [v.get("verified_by") or [] for v in vs] rec["version_summaries"] = [(v.get("summary") or "")[:100] for v in vs] rec["skipped"] = h.get("skipped") if not vs: rec["kind"] = "no_versions" return rec # --- the STABLE reading, which the fixed three-version shape cannot express -------------------- # A cut that re-imports a pre-cut file does not add a new content revision: it publishes an OLD # sha as the NEWEST version. So the general test is: does the newest version's content equal an # earlier version's content while a distinct verified revision sits between them? A document that # gained a genuine later revision (a repair, or a superseding return) fails this test by # construction -- which is why this rule cannot silently drop a repaired document the way the # three-version rule drops it from BOTH counts (it is then neither "reverted" nor "repaired"). shas = rec["version_shas"] revert_at = [k for k in range(1, len(shas)) if shas[k] == shas[0] and shas[k - 1] != shas[0]] rec["revert_at_versions"] = [k + 1 for k in revert_at] rec["discarded_candidates"] = [rec["version_returns"][k - 1] for k in revert_at] rec["newest_version_is_an_older_sha"] = bool(revert_at) and shas[-1] == shas[0] if len(vs) == 1: rec["kind"] = "single_version_control" return rec if len(vs) == 2: rec["kind"] = "two_versions" return rec if len(vs) == 3: s1, s2, s3 = rec["version_shas"] if s3 == s1 and s2 != s1: scode, sdata, _ = g.get("%s/docs/%s" % (BASE, path)) rec["served_http"] = scode rec["served_is_v1"] = (hashlib.sha256(sdata).hexdigest() == s1) if scode == 200 else None if rec["served_is_v1"]: rec["kind"] = "three_version_revert" rec["discarded_sha"] = s2 rec["discarded_return"] = rec["version_returns"][1] rec["discarded_verified_by"] = rec["version_verified_by"][1] # the discarded blob, by sha, and the two diffs against the served bytes bcode, bdata, _ = g.get("https://solveathome.org/files/%s" % s2) rec["discarded_http"] = bcode if bcode == 200: a = sdata.decode("utf-8", "replace") b = bdata.decode("utf-8", "replace") nrm, raw = changed(a, b) rec["raw_change"] = raw rec["norm_change"] = nrm rec["nolink_change"] = _diff_lines(norm_lines_nolink(a), norm_lines_nolink(b)) rec["classification"] = ("identical" if raw == 0 else ("cosmetic" if nrm == 0 else "substantive")) rec["changed_examples"] = changed_examples(a, b) # A section that exists only in the discarded revision is the sharpest form of # "this flag matters": whole blocks of prose cannot be a mirror reflow. hs, hd = set(headings(a)), set(headings(b)) rec["headings_only_in_discarded"] = sorted(hd - hs) rec["headings_only_in_served"] = sorted(hs - hd) rec["status_tokens_in_diff"] = sorted({m.group(0) for l in changed_examples(a, b, 60) for m in [STATUS.search(l)] if m}) else: rec["classification"] = "unknown" else: rec["kind"] = "three_version_but_served_elsewhere" else: rec["kind"] = "three_version_other" return rec rec["kind"] = "many_versions" return rec def registry(served, discarded): """Row-level comparison of two QUESTIONS.md layouts.""" def rows(t): out = {} for ln in (t or "").splitlines(): m = ROW.match(ln) if m: out[m.group(1)] = m.group(2).strip() return out a, b = rows(served), rows(discarded) flips = [{"slug": k, "served": a[k], "discarded": b[k]} for k in sorted(set(a) & set(b)) if a[k] != b[k]] return {"served_rows": len(a), "discarded_rows": len(b), "only_in_served": sorted(set(a) - set(b)), "only_in_discarded": sorted(set(b) - set(a)), "status_flips": flips} def main(): ap = argparse.ArgumentParser() ap.add_argument("--state", required=True) ap.add_argument("--limit", type=int, default=0) ap.add_argument("--offline", action="store_true") ap.add_argument("--out", default=None) a = ap.parse_args() g = sahget.Get(a.state) files, dirs = inventory(g, "") if a.limit: files = files[:a.limit] print(json.dumps({"stage": "inventory", "files": len(files), "dirs": len(dirs), "network_calls": g.calls}, indent=1)) rows = [] for i, p in enumerate(files, 1): try: rows.append(classify(g, p)) except RuntimeError as e: if a.offline: raise print("skip %s: %s" % (p, e)) continue if i % 200 == 0: print(json.dumps({"progress": i, "of": len(files), "network_calls": g.calls})) revs = [r for r in rows if r.get("kind") == "three_version_revert"] kinds = {} for r in rows: kinds[r.get("kind")] = kinds.get(r.get("kind"), 0) + 1 by_prefix = {} for r in revs: by_prefix[r["prefix"]] = by_prefix.get(r["prefix"], 0) + 1 # --- controls ------------------------------------------------------------------------------ # Review #154 named three documents. Two of them still carry the three-version signature; the # third, research/fixed-endpoint-discrepancy.md, does NOT -- and the reason is not a defect of the # detector but a fact about the record found here for the first time: it was REPAIRED on # 2026-09-19 (job #2680) and its served revision (v4, return #1333) says so in its own text. The # control therefore asserts the repair, not an exception to it: the document must be multi-version, # its served bytes must equal its LATEST version, and its served text must carry the re-application # marker. A detector that had simply lost the document would fail this. named = ["research/QUESTIONS.md", "research/global-factor-signs.md"] repaired = "research/fixed-endpoint-discrepancy.md" got = {r["path"]: r.get("kind") for r in rows} fr = next((r for r in rows if r["path"] == repaired), None) or {} rcode, rdata, _ = g.get("%s/docs/%s" % (BASE, repaired)) rtext = rdata.decode("utf-8", "replace") if rcode == 200 else "" marker = "Re-applied 2026-09-19" controls = { "positive_review_154_documents_still_reverted": {p: got.get(p) for p in named}, "positive_both_still_fire": all(got.get(p) == "three_version_revert" for p in named), "positive_third_document_is_REPAIRED_not_reverted": { "path": repaired, "kind": fr.get("kind"), "n_versions": fr.get("n_versions"), "served_sha": hashlib.sha256(rdata).hexdigest()[:12] if rcode == 200 else None, "latest_version_sha": (fr.get("version_shas") or [None])[-1], "marker_in_served_text": marker in rtext, "holds": (fr.get("kind") == "many_versions" and marker in rtext and hashlib.sha256(rdata).hexdigest() == (fr.get("version_shas") or [None])[-1]), }, "negative_single_version_flagged": sum(1 for r in rows if r.get("kind") == "single_version_control" and r.get("classification")), "negative_pattern_without_reversion_instances": [r["path"] for r in rows if r.get("kind") == "three_version_but_served_elsewhere"], "absent_path_is_visible": None, } # The first version of this control asserted 404 at /history for an absent path and FAILED: the # history endpoint answers 200 with `versions: []` for a path it has never heard of, and only # /docs answers 404. So "no version record" and "no such document" are the same answer from # /history, which is a property of the serving layer worth stating rather than hiding -- the # population this audit can classify is exactly the set of paths WITH a version record. bogus = "research/THIS-DOCUMENT-DOES-NOT-EXIST-2962.md" hcode, hdata, _ = g.get("%s/history/%s" % (BASE, bogus)) dcode, _, _ = g.get("%s/docs/%s" % (BASE, bogus)) try: hv = len((json.loads(hdata) or {}).get("versions") or []) except Exception: # noqa: BLE001 hv = None controls["absent_path_is_visible"] = { "history_http": hcode, "history_versions": hv, "docs_http": dcode, "reading": ("an absent path and an untracked document are the same answer from /history (200, " "0 versions); only /docs answers 404. The audited population is therefore the " "paths that carry a version record, and that is what the counts below range over."), "holds": (hcode == 200 and hv == 0 and dcode == 404), } # --- registry diff ------------------------------------------------------------------------- reg = None q = next((r for r in rows if r["path"] == "research/QUESTIONS.md"), None) if q and q.get("discarded_sha"): scode, sdata, _ = g.get("%s/docs/research/QUESTIONS.md" % BASE) bcode, bdata, _ = g.get("https://solveathome.org/files/%s" % q["discarded_sha"]) if bcode == 200: reg = registry(sdata.decode("utf-8", "replace"), bdata.decode("utf-8", "replace")) twos = [r for r in rows if r.get("kind") == "two_versions"] mans = [r for r in rows if r.get("kind") == "many_versions"] # The stable population, over every document the serving layer keeps versions for. tracked = [r for r in rows if (r.get("n_versions") or 0) > 1] historical = [r for r in tracked if r.get("revert_at_versions")] still_cut = [r for r in historical if r.get("newest_version_is_an_older_sha")] re_revisioned = [r for r in historical if not r.get("newest_version_is_an_older_sha")] out = { "tool": "reversion-audit.py (job 2962, route 128)", "non_revert_version_tracked": { "two_versions": [{"path": r["path"], "shas": r["version_shas"], "returns": r["version_returns"], "first_equals_second": r["version_shas"][0] == r["version_shas"][1]} for r in twos], "many_versions": [{"path": r["path"], "shas": r["version_shas"], "returns": r["version_returns"]} for r in mans], }, "substantive_vs_cosmetic": { "substantive": sum(1 for r in revs if r.get("classification") == "substantive"), "cosmetic": sum(1 for r in revs if r.get("classification") == "cosmetic"), "identical": sum(1 for r in revs if r.get("classification") == "identical"), "surviving_both_normalisations": sum(1 for r in revs if (r.get("nolink_change") or 0) > 0), }, "method": ("the served /docs listings are walked recursively and /history/ is read for " "EVERY file, so the population is the served tree itself and not a candidate list " "derived from return records"), "inventory": {"files": len(files), "directories": [d["dir"] for d in dirs], "files_with_a_version_record": sum(1 for r in rows if (r.get("n_versions") or 0) > 0), "files_with_no_version_record": kinds.get("no_versions", 0) + kinds.get("no_history", 0)}, "network_calls": g.calls, "kinds": kinds, "reverts": revs, "reverts_by_prefix": by_prefix, "revert_count": len(revs), "stable_reading": { "multi_version_documents": len(tracked), "historically_reverted": [{"path": r["path"], "at_versions": r["revert_at_versions"], "discarded_returns": r["discarded_candidates"], "n_versions": r["n_versions"]} for r in historical], "still_serving_the_reverted_content": sorted(r["path"] for r in still_cut), "re_revisioned_since_the_cut": sorted(r["path"] for r in re_revisioned), "reading": ("a document is CUT-REVERTED today when its newest version's content equals an " "earlier version's content with a distinct verified revision in between. " "That is the general form of the defect; the three-version shape is its most " "common instance and is not stable under later revisions."), }, "registry": reg, "controls": controls, } out["discarded_returns"] = sorted([r.get("discarded_return") for r in revs], key=lambda x: (x is None, x)) dest = a.out or os.path.join(HERE, "served-reversion-audit.json") with open(dest, "w", encoding="utf-8", newline="\n") as fh: json.dump(out, fh, indent=1, sort_keys=True) fh.write("\n") print(json.dumps({"kinds": kinds, "reverts": len(revs), "by_prefix": by_prefix, "controls": controls, "registry_flips": (reg or {}).get("status_flips"), "network_calls": g.calls, "wrote": dest}, indent=1)) return 0 if __name__ == "__main__": sys.exit(main())