#!/usr/bin/env python3 """freshness-triager -- route 114 triage: three questions the route's own hour never covered. TRIAGE, not a re-run. Return #1354 already measured, with its own checker, that 4 of 4 audited documents still serve the pre-audit text and 3 of 3 index rows still publish the pre-audit verdict. Those numbers are CITED here, not recomputed. What this instrument adds is the part the route calls its weakest and its most expensive step, measured ONCE over the whole served snapshot instead of over four documents: Q0 CONTROL -- are the four documents the checker measured the same TEXT as the served snapshot used here? Byte-level sha256 does NOT settle this on this machine: the snapshot was written with CRLF and the served bytes are LF, so a byte comparison reports a false mismatch for every file. The control therefore compares content with newlines normalised, and reports the byte-level mismatch SEPARATELY as a measured property of the snapshot (Q0b). Q1 FALSIFIER -- the route's own stop condition is "an accepted audit whose revision IS already served in the document it names". It ran that search on four named files. This runs it over every file in the snapshot: does any audit's replacement fragment appear ANYWHERE served? Q2 CAPACITY -- the route's weakest assumption is that the note's own ledger record is the intended carrier of a revised verdict, with the generator's rule "the verdict comes from the last record in path order". Has any id in this corpus EVER carried more than one record? If none ever has, the rule has never carried a revision and no id is evidence that it can. Q3 FIDELITY -- the generator's header claims the index is generated from the note records "so it cannot drift from them". Test that invariant over every record, not three rows: does the index represent EVERY record of the id -- the status when there is one record, and the per-file status list (the generator's `MIXED (file: status; ...)` form) when there are more? Two lookup traps are handled explicitly, because both produce false mismatch: a row is anchored on the BACKTICKED id (`| `Q-id` |`), since an id also appears inside other rows' prose; and a multi-record id is not required to carry a bare status token. PRE-REGISTERED EXPECTATIONS (written before the run, file created before execution): Q0 four matching TEXT (newlines normalised) -> else exit 2, everything below is void. Q0b is reported either way: if the snapshot is not byte-identical, every sha256-keyed freshness comparison run on this machine reports a false mismatch, which is itself a corpus-input defect. Q1 zero hits anywhere -> the falsifier survives at corpus scale, and the route is NOT defeated by the literal-reading failure mode it names Q2 zero ids with >= 2 records -> the mechanism has never carried a revision Q3 every id represented -> the index is a faithful projection of the records, so a freshness gate belongs at the record layer (the route's step 3), not in the index, and the existing multi-record form is the shape such a gate should use Read-only: reads the snapshot and the saved copies. stdout is the artifact; findings to stderr. """ import hashlib import json import os import re import sys ROOT = sys.argv[1] if len(sys.argv) > 1 else r"D:/AI/TwinPrimeProject/job587/pub/research" SAVED = sys.argv[2] if len(sys.argv) > 2 else ( r"D:/AI/TwinPrimeProject/.solveathome/twin-primes/runs/bf5-52d91a5cccf8de95/evidence/returns/1354") OUT = sys.argv[3] if len(sys.argv) > 3 else r"D:/AI/TwinPrimeProject/job2735/freshness-triage.json" # the four audit cases, exactly as return #1354 registered them (id, doc, replacement fragment) CASES = [ (151, "research/fixed-endpoint-discrepancy.md", "stronger sufficient input for the band piece P_band only"), (152, "research/history/staging/derive-0904-L7-transfer.md", "5.158065"), (153, "research/global-factor-signs.md", "status: ANSWERED"), (101, "research/fold-arithmetic-bridge.md", "Proposition 6"), ] # the shas #1354 recorded for those documents (its artifact verdict-drift-live.json) RECORDED_SHAS = { "research/fixed-endpoint-discrepancy.md": "19b6b12c228ec9decd4bd5328cf28b84c63e257ed04dbf55938ea687397f801d", "research/history/staging/derive-0904-L7-transfer.md": "6ffd659cce7f0fe97069d8f2420c346916fdab2c32d92bf20e0d850511f245a9", "research/global-factor-signs.md": "0509638b58b7458b0eeddc0525745cafef5bd508d01ad65e74cc88b583ba72bb", "research/fold-arithmetic-bridge.md": "2d41665acfc82347f8ca9749e39e7e88f2ad842bb0de05f6b17d56ece84aca3c", } INDEX_DOC = "research/QUESTIONS.md" BLOCK = re.compile(r"", re.S) FIELD = re.compile(r"^([a-z_]+):\s?(.*)$") def walk(root): out = [] for dirpath, dirnames, filenames in os.walk(root): dirnames[:] = [d for d in dirnames if d not in (".git", "node_modules")] for fn in filenames: p = os.path.join(dirpath, fn) out.append(p.replace("\\", "/")) return sorted(out) def sha256(path): h = hashlib.sha256() with open(path, "rb") as fh: for chunk in iter(lambda: fh.read(1 << 20), b""): h.update(chunk) return h.hexdigest() def parse_block(body): """One ledger record: field -> value, continuation lines appended to the open field.""" rec, key = {}, None for raw in body.splitlines(): if not raw.strip(): continue m = FIELD.match(raw) if m: key = m.group(1) rec[key] = m.group(2).strip() elif key: rec[key] = (rec[key] + " " + raw.strip()).strip() return rec def main(): files = walk(ROOT) text_of = {} rels = {} for p in files: rel = os.path.relpath(p, ROOT).replace("\\", "/") rels[p] = rel print("snapshot root: %s" % ROOT, file=sys.stderr) print("files: %d" % len(files), file=sys.stderr) result = {"tool": "freshness-triager/1.0", "root": ROOT, "files": len(files)} # ---- Q0: control, are the four measured documents these bytes? ------------------------- def snap_path(doc): """Docs are named relative to the docs base ('research/x.md'); the snapshot root may itself be that research tree, so accept either spelling.""" for cand in (doc, doc[len("research/"):] if doc.startswith("research/") else doc): p = os.path.join(ROOT, cand.replace("/", os.sep)) if os.path.exists(p): return p, cand return None, None q0 = [] for _, doc, _ in CASES: p, _rel = snap_path(doc) raw = open(p, "rb").read() if p else None # text identity: newlines normalised (the snapshot carries CRLF, the served bytes LF) norm = hashlib.sha256(raw.replace(b"\r\n", b"\n")).hexdigest() if raw else None q0.append({"doc": doc, "in_snapshot": raw is not None, "byte_sha256": hashlib.sha256(raw).hexdigest() if raw else None, "byte_identical_to_served": (hashlib.sha256(raw).hexdigest() == RECORDED_SHAS[doc]) if raw else False, "normalised_sha256": norm, "text_matches_1354_recorded_sha": norm == RECORDED_SHAS[doc], "crlf": raw.count(b"\r\n") if raw else None}) result["q0_control"] = { "cases": q0, "all_text_match": all(c["text_matches_1354_recorded_sha"] for c in q0), "byte_identical": sum(1 for c in q0 if c["byte_identical_to_served"]), } # Q0b: how general is the byte-level mismatch across the snapshot? crlf_files = sum(1 for p in files if b"\r\n" in open(p, "rb").read()) result["q0b_byte_identity_hazard"] = { "snapshot_files": len(files), "files_with_crlf": crlf_files, "note": ("the snapshot index records the CRLF digests, so a sha256-keyed freshness check " "against the served declared sha reports a mismatch for every file here, while the " "text is identical"), } print("Q0 control all_text_match=%s byte_identical=%d/%d crlf_files=%d" % (result["q0_control"]["all_text_match"], result["q0_control"]["byte_identical"], len(q0), crlf_files), file=sys.stderr) if not result["q0_control"]["all_text_match"]: print(json.dumps(result, indent=1, sort_keys=True)) return 2 # ---- Q1: falsifier, corpus-wide -------------------------------------------------------- RESOLVED = {doc: snap_path(doc)[1] for _, doc, _ in CASES} q1 = [] for audit, doc, frag in CASES: hits = [] for p in files: try: with open(p, "r", encoding="utf-8", errors="ignore") as fh: t = fh.read() except OSError: continue if frag in t: hits.append(rels[p]) q1.append({"audit_return": audit, "fragment": frag, "named_doc": doc, "named_doc_snapshot_rel": RESOLVED[doc], "hits": hits, "hit_count": len(hits), "named_doc_contains_it": RESOLVED[doc] in hits}) result["q1_falsifier"] = { "cases": q1, "any_hit": any(c["hit_count"] for c in q1), "hits_outside_named_doc": sorted({h for c in q1 for h in c["hits"] if h != c["named_doc_snapshot_rel"]}), } print("Q1 any_hit=%s outside=%d" % (result["q1_falsifier"]["any_hit"], len(result["q1_falsifier"]["hits_outside_named_doc"])), file=sys.stderr) # ---- Q2/Q3: records and index fidelity ------------------------------------------------- records = [] # (file, block_index, rec) for p in files: if not p.endswith(".md"): continue try: with open(p, "r", encoding="utf-8", errors="ignore") as fh: t = fh.read() except OSError: continue if "