#!/usr/bin/env python3 """Does a `code-sha256` header trace to the file's own bytes -- and if not, WHICH copy broke it? Two candidate explanations for a header that fails on the served bytes: (1) the code above the banner was edited after embedding -> stale header (2) the publisher rewrote the head when serving it -> the served copy is not the authored copy They are distinguishable because a second, independent copy of the authored tree exists on this machine (`job587/pub/research`, the root #1357's own artifact names). So for every served script with a header: A served == snapshot and header verifies everywhere self-consistent provenance B served != snapshot header verifies on BOTH harmless: the tail moved, the head did not C served != snapshot verifies on snapshot, NOT on served the publisher edited the head D verifies on neither genuinely stale header usage: headtrace.py [--out dir] [--snapshot DIR] """ import argparse import hashlib import json import os import re import sys sys.stdout.reconfigure(encoding="utf-8", errors="replace") HERE = os.path.dirname(os.path.abspath(__file__)) RUN = os.path.dirname(HERE) CACHE = os.path.join(RUN, "job128", "cache") LIST = os.path.join(RUN, "job128", "docs-list.txt") EXTS = (".py", ".js", ".mjs", ".sh", ".ts", ".cjs") OUT_HEAD = re.compile(r"^\s*//\s*OUTPUT\s*(?:$|[\u2014\-(])") BANNER_RULE = re.compile(r"^\s*//\s*={10,}\s*$") CODE_HDR = re.compile(r"^[ \t]*(?:[#/;*]+[ \t]*)?(?://\s*)?code-sha256:[ \t]*([0-9a-f]{64})", re.I | re.M) def sha(b): return hashlib.sha256(b).hexdigest() def cache_path(p): return os.path.join(CACHE, "_projects_twin-primes_docs_" + p.replace("/", "_") + ".txt") def head_headtext(text): """tailfmt.js headText(): lines before the banner rule, joined with \\n (no trailing newline).""" lines = text.split("\n") idx = next((i for i, ln in enumerate(lines) if OUT_HEAD.match(ln)), None) if idx is None: return None start = idx - 1 if idx > 0 and BANNER_RULE.match(lines[idx - 1]) else idx return "\n".join(lines[:start]), start def main(): ap = argparse.ArgumentParser() ap.add_argument("--out", default=HERE) ap.add_argument("--snapshot", default="D:/AI/TwinPrimeProject/job587/pub") args = ap.parse_args() docs = [l.strip() for l in open(LIST, encoding="utf-8") if l.strip()] rows = [] for p in docs: if os.path.splitext(p)[1].lower() not in EXTS or not os.path.exists(cache_path(p)): continue served = open(cache_path(p), "rb").read() hh = head_headtext(served.decode("utf-8", "replace")) mh = CODE_HDR.search(served.decode("utf-8", "replace")) if not mh: continue want = mh.group(1).lower() # the snapshot copy lives at the same path under the published root snap = os.path.join(args.snapshot, p) sbytes = open(snap, "rb").read() if os.path.exists(snap) else None # The second copy on this machine is a CRLF checkout (that is precisely what #1357 measured: # 1118 CRLF files), while the served corpus is LF. A fingerprint taken over the head is # end-of-line sensitive, so each copy is tested under its own reading and under the # LF-normalised reading, and only an unreconciled difference is called a difference. def verifies(b, ws, want): """(matched, matched_under_lf_normalisation)""" t = b.decode("utf-8", "replace") r = head_headtext(t) if r is None: return False, False h = r[0] exact = sha(h.encode("utf-8")) == want lf = sha(h.replace("\r\n", "\n").encode("utf-8")) == want # and the same head extracted from an LF-normalised copy of the whole file r2 = head_headtext(t.replace("\r\n", "\n")) lf2 = r2 is not None and sha(r2[0].encode("utf-8")) == want return exact, (exact or lf or lf2) served_ok, served_ok_lf = verifies(served, None, want) snap_ok, snap_ok_lf = (None, None) if sbytes is not None: snap_ok, snap_ok_lf = verifies(sbytes, None, want) same_content_lf = (sbytes is not None and sbytes.replace(b"\r\n", b"\n") == served.replace(b"\r\n", b"\n")) if sbytes is None: cls = "no-snapshot-copy" elif same_content_lf and served_ok and snap_ok_lf is False: # identical text once line endings are normalised, but the second copy's own byte reading # fails the fingerprint: that is an EOL fact about the checkout, not a content difference cls = "A same-content (EOL-only difference) header-verifies" elif sbytes == served and served_ok: cls = "A same-copy header-verifies" elif same_content_lf and served_ok: cls = "B differs-only-in-EOL head-intact" elif snap_ok_lf and served_ok_lf: cls = "B differs head-intact" elif snap_ok_lf and not served_ok_lf: cls = "C differs head-broken-by-publication" elif not snap_ok_lf and served_ok_lf: cls = "C' differs authored-head-broken" else: cls = "D differs header-stale-in-both" rows.append({"file": p, "class": cls, "served_bytes": len(served), "snapshot_bytes": len(sbytes) if sbytes else None, "served_head_bytes": len(hh[0].encode("utf-8")) if hh else None, "served_head_verifies": served_ok, "served_head_verifies_lf": served_ok_lf, "snapshot_head_verifies": snap_ok, "snapshot_head_verifies_lf": snap_ok_lf, "snapshot_has_crlf": b"\r\n" in (sbytes or b""), "served_sha": sha(served), "snapshot_sha": sha(sbytes) if sbytes else None}) counts = {} for r in rows: counts[r["class"]] = counts.get(r["class"], 0) + 1 summary = { "served_scripts_with_code_header": len(rows), "class_counts": counts, "header_verifies_on_served_bytes": sum(1 for r in rows if r["served_head_verifies"]), "header_verifies_on_served_bytes_lf_tolerant": sum(1 for r in rows if r["served_head_verifies_lf"]), "snapshot_copies_with_crlf": sum(1 for r in rows if r["snapshot_has_crlf"]), "class_C_files": [r["file"] for r in rows if r["class"].startswith("C")][:25], "class_C_rows": [{"file": r["file"], "served_lf": r["served_head_verifies_lf"], "snapshot_lf": r["snapshot_head_verifies_lf"], "d_bytes": (r["snapshot_bytes"] or 0) - r["served_bytes"]} for r in rows if r["class"].startswith("C")][:8], "class_D_files": [r["file"] for r in rows if r["class"].startswith("D")][:25], "class_A_prime_files": [r["file"] for r in rows if r["class"].startswith("A'")][:25], "note": "class C is the interesting one: the served copy is not the authored copy, so its own " "fingerprint cannot trace -- and any constant census reading served bytes alone inherits it", } json.dump({"summary": summary, "rows": rows}, open(os.path.join(args.out, "headtrace.json"), "w", encoding="utf-8"), indent=1, ensure_ascii=False) print(json.dumps(summary, indent=1)[:2400]) return 0 if __name__ == "__main__": sys.exit(main())