#!/usr/bin/env python3 """Route 131, the decisive test: is the served `research/QUESTIONS.md` EXACTLY the output of the served generator over the served notes? `route131_census.py` compares the derived cells row by row; this script reproduces the whole file from the generator's own `generate()` template and compares bytes. If they are equal, the index carries no state of its own -- every correction it displays is a function of the notes, so an index-side edit can survive only until the next regeneration. If they differ, the first differing line is reported (with the byte counts), because a near-miss is a different claim from a match. Writes route131-generate.json + the reconstructed file. Prints the verdict and, on a mismatch, the first differences. """ import difflib 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__)) JOB128 = os.path.join(os.path.dirname(HERE), "job128") sys.path.insert(0, JOB128) sys.path.insert(0, HERE) import route128_next as R # noqa: E402 from route131_census import parse_block, indexed_files, summarise # noqa: E402 def cell(s): return re.sub(r"\n", " ", str(s or "").replace("|", "\\|")).strip() def link(p): return "[%s](%s)" % (os.path.basename(p), re.sub(r"^research/", "", p)) def todo_items(txt): """The generator's todoItems(): `**ID. ` headings, reset at `## `, `Ledger:` lines collected.""" items, cur = [], None for i, ln in enumerate(txt.split("\n")): h = re.match(r"^\*\*([A-Za-z0-9]+)\.\s", ln) if h: cur = {"id": h.group(1), "line": i + 1, "ledger": set()} items.append(cur) continue if ln.startswith("## "): cur = None continue if cur: lm = re.match(r"^\s*Ledger:\s*(.*)$", ln) if lm: cur["ledger"].update(re.findall(r"Q-[A-Za-z0-9-]+", lm.group(1))) return items def generate(docs, fetch, quiet=False): """The served generator's own rules, over `fetch(path) -> (code, text)`. Parameterised on the fetch so that route 131's partition can re-run the generator with one note's bytes REPLACED by a pinned revision and ask what the index would then say. That is the difference between asserting that a fix is source-side and measuring it. """ # corpus.js line 37: `const GENERATED = new Set(['SCRIPTS.md', 'QUESTIONS.md'])`, and line 110 drops # them from allMarkdown by BASENAME before bodyMarkdown is derived. Generated files are outputs, # not evidence, so they are not inputs to the index. (Without this the reconstruction listed the # two generated files as unindexed notes -- which is how the reference for the rule was found.) GENERATED = {"SCRIPTS.md", "QUESTIONS.md"} files = [f for f in indexed_files(docs) if os.path.basename(f) not in GENERATED] parsed, rows_no_block = [], [] for p in files: c, txt = fetch(p) if c != 200: sys.exit("fetch %s -> %s" % (p, c)) pb = parse_block(txt) if pb["block"] and pb["block"].get("id"): parsed.append({"path": p, "block": pb["block"], "title": pb["title"]}) else: rows_no_block.append({"path": p, "title": pb["title"]}) by_id = {} for x in parsed: by_id.setdefault(x["block"]["id"], []).append(x) for v in by_id.values(): v.sort(key=lambda y: y["path"]) S = [summarise(by_id[q]) for q in sorted(by_id)] c, todo_txt = fetch("TODO.md") items = todo_items(todo_txt) if c == 200 else [] if not quiet: print("inputs: %d indexed notes, %d ids, %d unindexed notes, %d TODO items" % (len(parsed), len(S), len(rows_no_block), len(items))) out = [] A = out.append A("# Questions: what has been asked here, what it got, and where the record is") A("") A("*(GENERATED from the `` blocks at the top of the notes; never") A("hand-edited. Regenerate with `node research/qc.js --index` or") A("`node research/gen-questions-index.js`. The block format and the gate that") A("enforces it are documented at the top of `qc/questions.js`.)*") A("") A("**Before proposing an attack or briefing an agent:** find the TODO item in") A("section 1, search for the actual object, then read the relevant records and") A("their decisive dependencies. Use [OUTCOMES.md](OUTCOMES.md) for reuse and") A("revisit conditions. An item can span many unrelated attempts; loading every") A("linked note is not the required first step. Verify any conclusion that") A("determines the next move, including an ANSWERED or CLOSED entry.") A("") A("**Status describes the question, not proof strength or review grade.**") A("OPEN: unresolved. PARTIAL: specified parts are resolved. ANSWERED: the bounded") A("question has an answer, which may be a negative finding, finite measurement") A("or completed specification. Its underlying arithmetic target may remain OPEN.") A("CLOSED: the stated premise or approach is closed at its recorded scope; this") A("does not refute every related conjecture. SUPERSEDED: another record replaces") A("this one. Consult the owning note and linked reviews for HELD or other grades.") A("") A("**Multiple records:** conflicting statuses are shown as MIXED. The displayed") A("verdict comes from the last record in path order, not necessarily the newest") A("or most authoritative review. Read the linked records before resolving a") A("disagreement; the generator does not adjudicate it.") A("") A("## 1. By TODO item: what has already run under each") A("") A("| TODO item | question | status | verdict | records |") A("|---|---|---|---|---|") seen = set() for it in items: here = [s for s in S if any(re.sub(r" \(retired\)$", "", t) == it["id"] for t in s["todo"])] for s in here: seen.add(s["id"]) A("| %s | `%s` %s | %s | %s | %s |" % (it["id"], s["id"], cell(s["question"]), s["status"], cell(s["verdict"]), ", ".join(link(f) for f in s["files"]))) for s in [x for x in S if x["id"] not in seen and x["todo"]]: A("| %s | `%s` %s | %s | %s | %s |" % (cell(", ".join(s["todo"])), s["id"], cell(s["question"]), s["status"], cell(s["verdict"]), ", ".join(link(f) for f in s["files"]))) A("") A("## 2. Every question, by id") A("") A("| id | status | question | verdict | TODO | records |") A("|---|---|---|---|---|---|") for s in S: A("| `%s` | %s | %s | %s | %s | %s |" % (s["id"], s["status"], cell(s["question"]), cell(s["verdict"]), cell(", ".join(s["todo"]) or "none"), ", ".join(link(f) for f in s["files"]))) A("") A("## 3. Unindexed notes (%d): title only, until a block is added" % len(rows_no_block)) A("") A("*(Legacy notes written before the ledger existed. A grep for the object still") A("lands here. Add a block when a note is next touched; `node research/qc.js") A("ledger-backlog` lists them.)*") A("") for r in rows_no_block: A("- %s: %s" % (link(r["path"]), cell(r["title"]))) A("") mine = "\n".join(out) return {"text": mine, "notes": parsed, "unindexed": rows_no_block, "by_id": by_id, "ids": sorted(by_id), "rows": S, "todo_items": items} def served_fetch(path): """The served revision of a document path, through the run's fetch cache.""" return R.get(R.PROJECT + "/docs/" + path) def main(): docs = [d for d in open(os.path.join(JOB128, "docs-list.txt"), encoding="utf-8").read().split("\n") if d] G = generate(docs, served_fetch) parsed, rows_no_block, S, items, mine = (G["notes"], G["unindexed"], G["rows"], G["todo_items"], G["text"]) c, served = R.get(R.PROJECT + "/docs/research/QUESTIONS.md") equal = mine == served res = {"generator": "/projects/twin-primes/docs/research/qc/questions.js", "inputs": {"indexed_notes": len(parsed), "ids": len(S), "unindexed": len(rows_no_block), "todo_items": len(items)}, "bytes_reconstructed": len(mine), "bytes_served": len(served), "byte_identical": bool(equal), "sha256_reconstructed": hashlib.sha256(mine.encode("utf-8")).hexdigest(), "sha256_served": hashlib.sha256(served.encode("utf-8")).hexdigest(), "lines_reconstructed": mine.count("\n") + 1, "lines_served": served.count("\n") + 1} if not equal: d = list(difflib.unified_diff(served.split("\n"), mine.split("\n"), "served", "reconstructed", n=1, lineterm="")) res["diff_lines"] = len(d) res["first_differences"] = d[:40] res["differing_line_numbers"] = [i + 1 for i, (a, b) in enumerate(zip(served.split("\n"), mine.split("\n"))) if a != b][:20] json.dump(res, open(os.path.join(HERE, "route131-generate.json"), "w", encoding="utf-8"), indent=1) with open(os.path.join(HERE, "QUESTIONS.reconstructed.md"), "w", encoding="utf-8", newline="\n") as fh: fh.write(mine) print(json.dumps({k: v for k, v in res.items() if k not in ("first_differences",)}, indent=1)[:900]) if not equal: print("\nfirst differences:") for l in res.get("first_differences", [])[:24]: print(" " + l[:220]) return 0 if __name__ == "__main__": sys.exit(main())