#!/usr/bin/env python3 """T1 corrected a second time: cut exactly where `research/qc/tailfmt.js` cuts, byte for byte. `codehash.py` cut at the line matching `// OUTPUT` and hashed everything above it, which is one line too late: tailfmt.js `locateAt` says "the banner rule above the OUTPUT line, if there is one, belongs to the tail" (`if (start > 0 && BANNER.test(lines[start - 1])) start -= 1;`), and `headText` then does `lines.slice(0, tailStart).join('\n')` -- a join, so the head has NO trailing newline, and any CR that a CRLF line leaves inside a line is preserved. So: OUT_HEAD = /^\\s*\\/\\/\\s*OUTPUT\\s*(?:$|[\\u2014\\-(])/ (tailfmt line 58) BANNER = /^\\s*\\/\\/\\s*={10,}\\s*$/ (tailfmt line 46) head = '\\n'.join(text.split('\\n')[:start]) This script implements that literally and also tries the neighbouring interpretations, so that "my semantics are wrong" and "the header is wrong" can never be confused again. It is the CONTROL for the census: if the self-provenance headers verify under the exact reading of their own producer, then the constant-extraction in census.py/census2.py is trustworthy and any constant that fails to trace is a corpus fact rather than a measurement artefact. usage: codehash2.py [--out 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") # tailfmt.js line 58, verbatim (em dash and hyphen and open-paren all start a header suffix) OUT_HEAD = re.compile(r"^\s*//\s*OUTPUT\s*(?:$|[\u2014\-(])") # tailfmt.js line 46, verbatim BANNER_RULE = re.compile(r"^\s*//\s*={10,}\s*$") # header fields, with optional comment leader CODE_HDR = re.compile(r"^[ \t]*(?:[#/;*]+[ \t]*)?(?://\s*)?code-sha256:[ \t]*([0-9a-f]{64})", re.I | re.M) OUT_HDR = re.compile(r"^[ \t]*(?:[#/;*]+[ \t]*)?(?://\s*)?out-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_text(text): """tailfmt.js headText(), literally.""" lines = text.split("\n") out_head = None for i, ln in enumerate(lines): if OUT_HEAD.match(ln): out_head = i break if out_head is None: return None, None start = out_head if start > 0 and BANNER_RULE.match(lines[start - 1]): start -= 1 return "\n".join(lines[:start]), start def main(): ap = argparse.ArgumentParser() ap.add_argument("--out", default=HERE) 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 raw = open(cache_path(p), "rb").read() text = raw.decode("utf-8", "replace") mc = CODE_HDR.search(text) mo = OUT_HDR.search(text) if not mc and not mo: continue head, start = head_text(text) if head is None: rows.append({"file": p, "code_header": mc.group(1).lower() if mc else None, "has_output_line": False, "matched": None}) continue # the head's bytes as tailfmt would see them: joined with \n, so its byte length is # len('\n'.join) -- and encoding that is the string tailfmt hashes head_b = head.encode("utf-8") variants = { "tailfmt_headText": sha(head_b), # neighbours, so a near-miss is visible rather than silent "head_plus_trailing_nl": sha(head_b + b"\n"), "head_crlf_joined": sha("\r\n".join(head.split("\n")).encode("utf-8")), "whole_file": sha(raw), } want_c = mc.group(1).lower() if mc else None want_o = mo.group(1).lower() if mo else None rows.append({ "file": p, "has_output_line": True, "banner_rule_above_output": BANNER_RULE.match(text.split("\n")[start]) is not None if start < len(text.split("\n")) else False, "head_bytes": len(head_b), "code_header": want_c, "code_matched_by": sorted(k for k, v in variants.items() if v == want_c) if want_c else [], "out_header": want_o, "out_matched_by": sorted(k for k, v in variants.items() if v == want_o) if want_o else [], "src_has_crlf": b"\r\n" in raw, }) with_code = [r for r in rows if r.get("code_header")] ok = [r for r in with_code if r["code_matched_by"]] bad = [r for r in with_code if not r["code_matched_by"]] with_out = [r for r in rows if r.get("out_header")] ok_out = [r for r in with_out if r["out_matched_by"]] summary = { "scripts_with_code_header": len(with_code), "code_header_verifies_under_tailfmt_headText": sum( 1 for r in ok if "tailfmt_headText" in r["code_matched_by"]), "code_header_matches_only_another_variant": len(ok) - sum( 1 for r in ok if "tailfmt_headText" in r["code_matched_by"]), "code_header_unmatched": len(bad), "scripts_with_out_header": len(with_out), "out_header_matches_head_bytes": sum( 1 for r in ok_out if "tailfmt_headText" in r["out_matched_by"]), "out_header_note": "out-sha256 is the normalised stdout, so it is NOT expected to equal the head", "unmatched_code": [{"file": r["file"], "head_bytes": r["head_bytes"]} for r in bad][:25], } json.dump({"summary": summary, "rows": rows}, open(os.path.join(args.out, "codehash2.json"), "w", encoding="utf-8"), indent=1, ensure_ascii=False) print(json.dumps(summary, indent=1)[:2200]) return 0 if __name__ == "__main__": sys.exit(main())