#!/usr/bin/env python3 """job 2741 / route 114 rev 3 -- did any accepted audit's patch ever become a repository write? Question. Route 114 asks whether an accepted audit's revised verdict has a propagation path. Return #1358 showed the *product* is missing at every carrier inside the corpus (document body, ledger block, `verdict:` field, QUESTIONS.md row). That left one live alternative: the served/snapshot text is stale, and the private repository was in fact patched. The public mirror turns out to be a one-commit snapshot -- but it ships `PUBLICATION.json`, a per-file provenance manifest carrying, for every file, the *private* repo's `first_commit`, `last_commit`, `modified_at` and `state`. That is the commit link return #1358 said the record lacked. Test. If an accepted patch were applied to its target file, that file's `last_commit`/`modified_at` would move to or past `effects_applied_at`. So: T1 provenance each audit's target file: modified_at vs effects_applied_at T2 sha join manifest sha256 == the sha #1354 recorded for the same path (so the timestamps describe exactly the bytes we measured) T3 live clock the manifest observes writes AFTER the acceptances (else "no write recorded" would be unfalsifiable) T4 window files in the whole corpus whose modified_at falls inside [first acceptance, last acceptance] T5 content removed (-) lines still served, added (+) lines absent Exit codes (the discipline adopted from credguard/1.0.0): 0 measurement completed and the queue-state reading holds 2 the falsifier fired: some patch IS visible as a repository write 3 could not look (missing manifest/defs) -- never shares a verdict with 0 """ import argparse import hashlib import json import os import re import sys try: sys.stdout.reconfigure(encoding="utf-8", errors="replace") except Exception: pass def sha256_file(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_ts(ts): """ISO8601 -> comparable tuple (lexicographic-safe for this corpus).""" if not ts: return None return ts.replace("Z", "").split(".")[0] def patch_targets(patch): """Paths named by a unified diff (the +++ side).""" out = [] for line in (patch or "").splitlines(): if line.startswith("+++ "): p = line[4:].strip() p = re.sub(r"^[ab]/", "", p) p = p.split("\t")[0].strip() if p and p != "/dev/null": out.append(p) return out def diff_lines(patch): """(removed, added) body lines, long enough to be content rather than chrome.""" removed, added = [], [] for line in (patch or "").splitlines(): if line.startswith("---") or line.startswith("+++") or line.startswith("@@"): continue if line.startswith("-") and len(line) > 44: removed.append(line[1:]) elif line.startswith("+") and len(line) > 44: added.append(line[1:]) return removed, added def load_returns(audit_dir): out = {} for name in sorted(os.listdir(audit_dir)): path = os.path.join(audit_dir, name, "return.json") if not os.path.exists(path): continue with open(path, encoding="utf-8") as fh: doc = json.load(fh) r = doc.get("return", doc) out[int(r["id"])] = r return out def main(): ap = argparse.ArgumentParser() ap.add_argument("--mirror", required=True, help="clone of the public mirror") ap.add_argument("--audits", required=True, help="dir of r*/return.json") ap.add_argument("--sha-record", help="#1354's verdict-drift-live.json") ap.add_argument("--population", default=None, help="literal content key; dates every corpus file carrying it") ap.add_argument("--population-since", default=None, help="count population files modified strictly after this timestamp") ap.add_argument("--out", help="write JSON evidence here") args = ap.parse_args() man_path = os.path.join(args.mirror, "PUBLICATION.json") if not os.path.exists(man_path): print("REFUSE: no PUBLICATION.json at %s" % man_path) return 3 if not os.path.isdir(args.audits): print("REFUSE: no audit dir at %s" % args.audits) return 3 with open(man_path, encoding="utf-8") as fh: man = json.load(fh) files = man["files"] returns = load_returns(args.audits) result = { "instrument": "manifest-provenance/1.0.0", "manifest_generated_at": man.get("generated_at"), "manifest_entries": len(files), "audits": {}, "checks": {}, "falsifier_fired": False, } # ---- T2 sha join ----------------------------------------------------- sha_record = None if args.sha_record and os.path.exists(args.sha_record): with open(args.sha_record, encoding="utf-8") as fh: sha_record = json.load(fh) recorded = {} if sha_record: for case in sha_record.get("cases", []): if case.get("doc") and case.get("doc_sha256"): recorded[case["doc"].lstrip("/")] = case["doc_sha256"] idx = sha_record.get("index") or {} if idx.get("doc") and idx.get("doc_sha256"): recorded[idx["doc"].lstrip("/")] = idx["doc_sha256"] t2 = [] for path, expected in sorted(recorded.items()): entry = files.get(path) got = (entry or {}).get("sha256") t2.append({ "path": path, "recorded_sha256": expected, "manifest_sha256": got, "match": got == expected, }) result["checks"]["T2_sha_join"] = { "compared": len(t2), "matched": sum(1 for r in t2 if r["match"]), "rows": t2, } # ---- T1 provenance per audit ---------------------------------------- accept_times = [] for rid in sorted(returns): r = returns[rid] applied = parse_ts(r.get("effects_applied_at")) if applied: accept_times.append((applied, rid)) targets = [] for t in patch_targets(r.get("patch")): targets.append({"path": t, "via": "patch"}) for fix in (r.get("also_fix") or []): if fix.get("path"): targets.append({"path": fix["path"], "via": "also_fix"}) seen, rows = set(), [] for t in targets: p = t["path"].lstrip("/") if p in seen: continue seen.add(p) entry = files.get(p) or {} src = entry.get("source") or {} modified = parse_ts(src.get("modified_at")) rows.append({ "path": p, "via": t["via"], "in_manifest": bool(entry), "last_commit": src.get("last_commit"), "modified_at": src.get("modified_at"), "state": src.get("state"), "public_edition": src.get("public_edition"), "modified_after_acceptance": bool(modified and applied and modified >= applied), "delta_hours": ( None if not (modified and applied) else round(_hours(applied, modified), 2) ), }) result["audits"][rid] = { "type": r.get("type"), "status": r.get("status"), "created_at": r.get("created_at"), "review_admitted_at": r.get("review_admitted_at"), "effects_applied_at": r.get("effects_applied_at"), "patch_status": r.get("patch_status"), "patch_present": bool(r.get("patch")), "patch_hash": r.get("patch_hash"), "commit": r.get("commit"), "targets": rows, "any_target_modified_after_acceptance": any( x["modified_after_acceptance"] for x in rows ), } if any(x["modified_after_acceptance"] for x in rows): result["falsifier_fired"] = True # ---- T3 live-clock control ------------------------------------------ mods = [(f, (e.get("source") or {}).get("modified_at")) for f, e in files.items()] mods = [(f, m) for f, m in mods if m] max_mod = max((m for _, m in mods), default=None) last_accept = max((a for a, _ in accept_times), default=None) first_accept = min((a for a, _ in accept_times), default=None) result["checks"]["T3_live_clock"] = { "first_acceptance": first_accept, "last_acceptance": last_accept, "manifest_generated_at": parse_ts(man.get("generated_at")), "latest_file_modified_at": max_mod, "manifest_postdates_acceptances": bool( parse_ts(man.get("generated_at")) and last_accept and parse_ts(man.get("generated_at")) >= last_accept ), "corpus_modified_after_last_acceptance": sum(1 for _, m in mods if m > last_accept), } # ---- T4 window scan -------------------------------------------------- in_window = sorted( (m, f) for f, m in mods if first_accept and last_accept and first_accept <= m <= last_accept ) result["checks"]["T4_acceptance_window"] = { "window": [first_accept, last_accept], "files_modified_inside": len(in_window), "files_modified_after_each_acceptance": { rid: sum(1 for _, m in mods if m > ts) for ts, rid in sorted(accept_times) }, "inside_rows": [{"modified_at": m, "path": f} for m, f in in_window], } # ---- T5 content ------------------------------------------------------ t5 = [] for rid in sorted(returns): r = returns[rid] patch = r.get("patch") if not patch: continue removed, added = diff_lines(patch) for target in patch_targets(patch): fpath = os.path.join(args.mirror, target) if not os.path.exists(fpath): t5.append({"audit": rid, "path": target, "error": "target absent from mirror"}) continue with open(fpath, encoding="utf-8", errors="replace") as fh: text = fh.read() t5.append({ "audit": rid, "path": target, "removed_lines_tested": len(removed), "removed_lines_still_present": sum(1 for l in removed if l in text), "added_lines_tested": len(added), "added_lines_present": sum(1 for l in added if l in text), }) result["checks"]["T5_content"] = t5 # ---- T6 population (does the revision's CONTENT postdate the audit?) -- if args.population: hits = [] for p in files: if not p.endswith((".md", ".js", ".json")): continue fp = os.path.join(args.mirror, p) if not os.path.exists(fp): continue try: with open(fp, encoding="utf-8", errors="replace") as fh: body = fh.read() except OSError: continue if args.population in body: src = (files[p].get("source") or {}) hits.append({"path": p, "modified_at": src.get("modified_at"), "last_commit": src.get("last_commit")}) hits.sort(key=lambda r: r["modified_at"] or "") since = parse_ts(args.population_since) if args.population_since else None result["checks"]["T6_population"] = { "key": args.population, "since": args.population_since, "files_carrying_key": len(hits), "earliest_modified_at": hits[0]["modified_at"] if hits else None, "latest_modified_at": hits[-1]["modified_at"] if hits else None, "modified_after_since": ( None if not since else sum(1 for h in hits if (h["modified_at"] or "") > since) ), "rows": hits, } # ---- verdict --------------------------------------------------------- t1_ok = all( (a["any_target_modified_after_acceptance"] is False) for a in result["audits"].values() if a["targets"] ) t2_ok = all(r["match"] for r in t2) if t2 else None t5_ok = all( row.get("removed_lines_still_present") == row.get("removed_lines_tested") and row.get("added_lines_present") == 0 for row in t5 if "error" not in row ) if t5 else None result["verdict"] = { "no_target_modified_after_acceptance": t1_ok, "manifest_sha_matches_recorded": t2_ok, "content_unapplied": t5_ok, "reading": ( "QUEUE STATE: patch_status=integrated on these audits is not a repository write" if (t1_ok and result["falsifier_fired"] is False) else "falsifier fired or measurement incomplete -- read the rows" ), } text = json.dumps(result, indent=2, sort_keys=True) if args.out: with open(args.out, "w", encoding="utf-8") as fh: fh.write(text + "\n") for rid, a in result["audits"].items(): print("#%d %s patch=%s applied=%s commit=%s" % ( rid, a["patch_status"], a["patch_present"], a["effects_applied_at"], a["commit"])) for row in a["targets"]: print(" %-52s modified=%s commit=%s delta_h=%s %s" % ( row["path"], row["modified_at"], str(row["last_commit"])[:12], row["delta_hours"], "MODIFIED-AFTER" if row["modified_after_acceptance"] else "predates")) print() print("T2 sha join : %s/%s match" % ( result["checks"]["T2_sha_join"]["matched"], result["checks"]["T2_sha_join"]["compared"])) t3 = result["checks"]["T3_live_clock"] print("T3 live clock : manifest %s, latest file write %s, corpus writes after last acceptance %d" % ( t3["manifest_generated_at"], t3["latest_file_modified_at"], t3["corpus_modified_after_last_acceptance"])) t4 = result["checks"]["T4_acceptance_window"] print("T4 window : %s .. %s -> %d files modified inside" % ( t4["window"][0], t4["window"][1], t4["files_modified_inside"])) for rid, n in t4["files_modified_after_each_acceptance"].items(): print(" after #%-4d %d corpus files modified" % (rid, n)) for row in t5: if "error" in row: print("T5 %s" % row) else: print("T5 #%-4d %-52s removed %d/%d still served, added %d/%d present" % ( row["audit"], row["path"], row["removed_lines_still_present"], row["removed_lines_tested"], row["added_lines_present"], row["added_lines_tested"])) t6 = result["checks"].get("T6_population") if t6: print("T6 population : %r -> %d files, modified_at %s .. %s, modified after %s: %s" % ( t6["key"], t6["files_carrying_key"], t6["earliest_modified_at"], t6["latest_modified_at"], t6["since"], t6["modified_after_since"])) print() print("VERDICT:", result["verdict"]["reading"]) return 2 if result["falsifier_fired"] else 0 def _hours(a, b): from datetime import datetime fmt = "%Y-%m-%dT%H:%M:%S" da = datetime.strptime(a[:19], fmt) db = datetime.strptime(b[:19], fmt) return (db - da).total_seconds() / 3600.0 if __name__ == "__main__": sys.exit(main())