#!/usr/bin/env python3 """Build #1454's `verification_plan` from the checker's OWN source, and preflight every sha it reads. The point of the plan is that another handle or model can be routed to run the check. So the manifest cannot be typed out here: the shas are read out of `check-1357.py`'s PINNED / SAVED_1354 tables (the same tables the checker enforces at run time), which makes drift between the plan and the program impossible by construction rather than by care. Then every declared sha is fetched from the store and required to hash to itself -- a plan that lists an object nobody can download is a plan with `availability: complete` in its own text and a 404 in every independent worker's terminal, which is worse than no plan. The fingerprint follows the protocol's rule verbatim: SHA-256 of `solveathome-verification-v1`, a newline, then the compact JSON with object keys sorted recursively, array order preserved, `cost` excluded. The script prints the fingerprint it computed so the server's own value can be compared against it rather than trusted. usage: make_verification_plan.py [--post] [--out plan.json] """ import argparse import ast import hashlib import json import os import re import sys import urllib.error import urllib.request sys.stdout.reconfigure(encoding="utf-8", errors="replace") HERE = os.path.dirname(os.path.abspath(__file__)) RUN = os.path.dirname(HERE) SERVER = "https://solveathome.org" PROJECT = "twin-primes" RETURN_ID = "1454" CHECKER = os.path.join(HERE, "check-1357.py") def token(): p = (os.environ.get("SOLVEATHOME_TOKEN_FILE") or os.path.join(os.environ.get("LOCALAPPDATA", ""), "solveathome", "credentials", "twin-primes.token")) t = open(p, encoding="utf-8").read().strip() return t.split("=", 1)[1].strip() if "=" in t else t def sha256(b): return hashlib.sha256(b).hexdigest() def constants(src): """Evaluate the checker's module-level assignments, in order, with no builtins. A regex over the source was the first attempt and it silently dropped three of the tensor's entries: `"parts.json": PARTS_MANIFEST,` is a NAME rather than a literal, and two entries carry a trailing `#` comment between the colon and the value, so the pattern matched neither. A plan whose manifest is missing three of the checker's own pinned inputs is exactly the defect this script exists to prevent, so the parse is done on the AST with names resolved in order instead. """ ns = {"__builtins__": {}} for node in ast.parse(src).body: if isinstance(node, ast.Assign): for t in node.targets: if isinstance(t, ast.Name): try: ns[t.id] = eval(compile(ast.Expression(node.value), "", "eval"), ns) # noqa: S307 except Exception: pass return ns def table(src, name): ns = constants(src) if name not in ns: raise SystemExit("could not find table %s in %s" % (name, CHECKER)) return ns[name] def fingerprint(plan): body = {k: v for k, v in plan.items() if k != "cost"} canon = json.dumps(body, sort_keys=True, separators=(",", ":")) # sorted_keys recursively: json.dumps(sort_keys=True) sorts at every level return sha256(("solveathome-verification-v1" + "\n" + canon).encode("utf-8")), canon def get(sha, tok): req = urllib.request.Request("%s/files/%s" % (SERVER, sha)) req.add_header("Authorization", "Bearer " + tok) try: with urllib.request.urlopen(req, timeout=120) as f: return f.status, f.read() except urllib.error.HTTPError as e: return e.code, e.read()[:200] def main(): ap = argparse.ArgumentParser() ap.add_argument("--post", action="store_true") ap.add_argument("--out", default=os.path.join(HERE, "verification-plan.json")) args = ap.parse_args() tok = token() src = open(CHECKER, encoding="utf-8").read() pinned = table(src, "PINNED") saved = table(src, "SAVED_1354") shipped = os.path.join(HERE, "shipped") parts = json.load(open(os.path.join(shipped, "parts.json"), encoding="utf-8")) checker_sha = sha256(open(CHECKER, "rb").read()) entries = [{"path": "check-1357.py", "sha256": checker_sha, "role": "checker"}] for p in parts["parts"]: entries.append({"path": p["name"], "sha256": p["sha256"], "role": "input"}) for name, digest in sorted(pinned.items()): # parts.json is listed by the parts table already; keep it once, as an input if name == "parts.json": entries.append({"path": name, "sha256": digest, "role": "input"}) elif name == "freshness-triage.json": entries.append({"path": name, "sha256": digest, "role": "target"}) else: entries.append({"path": name, "sha256": digest, "role": "input"}) for name, digest in sorted(saved.items()): entries.append({"path": name, "sha256": digest, "role": "dependency"}) # every extra artifact of this return that the checker does not read is still pinned if served, so the # plan's manifest is the package, not merely the program's inputs for extra in ("snapshot-2026-09-20-manifest.tsv",): p = os.path.join(shipped, extra) if os.path.exists(p): entries.append({"path": extra, "sha256": sha256(open(p, "rb").read()), "role": "input"}) # preflight: every sha must be an object the store actually serves, byte-for-byte print("preflight: fetching each declared sha from the store") bad = [] for e in entries: st, body = get(e["sha256"], tok) ok = st == 200 and sha256(body) == e["sha256"] if not ok: bad.append((e["path"], e["sha256"][:16], st)) print(" %-42s %-16s %s %s" % (e["path"], e["sha256"][:16], st, "OK" if ok else "NOT RETRIEVABLE")) plan = { "schema_version": 1, "manifest": [e for e in entries if e["sha256"]], "targets": ["freshness-triage.json"], "claim": "Return #1357's published artifact `freshness-triage.json` (sha256 bd9de6bbaf5f6e8c" "2e14fdb25b5fb273b11b7cb4fef64dc85ab1bba23ef80698) is reproduced byte-for-byte, and its " "four reported Q-lines exactly, by running its own instrument `freshness-triager.py` on " "the snapshot as measured on 2026-09-20, with every input fetched by sha256 from the " "project's store; and the four sha256 constants that instrument compares the snapshot " "against are the four `doc_sha256` values recorded in #1354's own served artifact, so " "the instrument's Q0 control is not circular.", "scope": "The single pinned snapshot (1128 files, archive sha256 f4c2cf638811...) and the single " "published revision of `freshness-triager.py` (b91f88a8...). Not a claim about any other " "revision of the tree, and not a claim that the four reference documents are correct.", "assumptions": "Python 3 with the standard library only (hashlib, zipfile, subprocess); no " "network beyond the store at https://solveathome.org/files/; the four parts " "are concatenated in the order their own manifest gives; the instrument is invoked " "as published, unmodified.", "checker": checker_sha, "inputs": [e["sha256"] for e in entries if e["sha256"] and e["role"] != "checker"], "environment": "CPython 3.13.0 (verified) and 3.14.6 (build), Windows 11 / any POSIX host; stdlib " "only, no third-party packages. Input hash to relative filename: " + "; ".join("%s=%s" % (e["path"], e["sha256"]) for e in entries if e["sha256"] and e["role"] != "checker"), "command": "python3 check-1357.py --out . --token-file ", "expected": "Five step lines each reported OK and, in the last, `artifact IDENTICAL " "(sha256 bd9de6bbaf5f6e8c2e14fdb25b5fb273b11b7cb4fef64dc85ab1bba23ef80698)`; the " "checks' own summary lines equal #1357's: `files: 1128`, " "`Q0 control all_text_match=True byte_identical=0/4 crlf_files=1118`, " "`Q1 any_hit=True outside=419`, `Q2 blocks=602 ids=555 multi=22`, " "`Q3 matched=554 mismatch=0 norow=1`; exit code 0. The checker prints `ALL STEPS PASS` " "or `FAILURES` and exits non-zero on any failure.", "supports": "Passing establishes the claim for the pinned snapshot and the published instrument: " "the artifact is a deterministic function of inputs that any worker can obtain, so " "its numbers are reproducible rather than merely reported. It does not establish that " "the CRLF state (1118 files) is a property of the tree as authored -- only of the " "snapshot as stored -- and it does not establish anything about the four reference " "documents beyond identity with #1354's recorded digests.", "coverage": "decisive", "coverage_md": "Every one of the 1128 archive members is hashed against the manifest; all four " "baked-in constants are compared with #1354's artifact; the instrument runs on the " "whole snapshot (no sampling, no seed). One reviewer control is also defined and " "passes: newline-normalising the snapshot moves `byte_identical` 0/4 -> 4/4 and " "`crlf_files` 1118 -> 0 with Q1-Q3 unchanged, which separates the counts from the " "CRLF state that made the original uncheckable. Negative controls are built into " "the checker rather than only in this text: a bad part, a missing member, a raw-sha " "mismatch and a non-pinned baked constant each produce a named failure, and the " "instrument is run with a second argument naming no file, which was measured to " "leave the artifact byte-identical.", "comparison": "Exact byte equality on the artifact (sha256) and exact string equality on the four " "summary lines; no tolerance is used, because the quantities are counts and digests.", "availability": {"status": "complete", "details": "Every manifest entry is served by the project store and was fetched " "back byte-for-byte during this plan's own preflight (%d of %d)." % (len(entries) - len(bad), len(entries)), "required_sources": ["https://solveathome.org/files/"], "network": False}, "cost": {"minutes": 2, "judgment_minutes": 15, "cpu_hours": 0.02, "ram_gb": 1, "disk_gb": 0.2}, } # the accepted precedent (#1447) carries exactly the 17 documented fields and no others: # an extra key would enter the fingerprint, so the shape is checked rather than assumed allowed = {"schema_version", "manifest", "targets", "claim", "scope", "assumptions", "checker", "inputs", "environment", "command", "expected", "supports", "coverage", "coverage_md", "comparison", "availability", "cost"} extra = set(plan) - allowed if extra: raise SystemExit("plan carries fields outside the v1 schema: %s" % sorted(extra)) fp, canon = fingerprint(plan) plan["_local_fingerprint"] = fp json.dump(plan, open(args.out, "w", encoding="utf-8", newline="\n"), indent=1, ensure_ascii=False) print("\nmanifest entries: %d | inputs: %d | unretrievable: %d" % (len(plan["manifest"]), len(plan["inputs"]), len(bad))) print("local fingerprint (cost excluded): %s" % fp) print("canonical bytes: %d" % len(canon.encode("utf-8"))) if bad: print("REFUSING to offer a plan over unretrievable inputs:", bad) return 2 return 0 if __name__ == "__main__": sys.exit(main())