#!/usr/bin/env python3 """Route 131: partition the served registry into durable (source-side) and ephemeral (index-side) corrections, gated on the served generator's own code. The generator is `research/qc/questions.js` (served, 18651 bytes). Its rules, quoted from the file: indexedFiles() the notes it reads are `history/staging/**` plus top-level `research/*.md` only parseBlock() the block is looked for in the FIRST 60 LINES (`slice(0, 60)`), keys must match `^([a-z]+):`, and id/status/question/verdict must all be non-empty with status in OPEN | PARTIAL | ANSWERED | CLOSED | SUPERSEDED summarise() notes are grouped by id; `status` is the single status when the group agrees and `'MIXED (' + basename: status ; … + ')'` when it does not; `verdict` and `question` come from the LAST note in path order ("NOT chronology or review precedence"); `files` is every file of the group; `todo` is the union over the group generate() section 1 lists each question under the TODO item(s) its block names (then the retired ones), section 2 lists every id This script re-implements that rule over the SERVED bytes and compares it to the SERVED index. The comparison is the measurement the route asks for: a row the rule reproduces is regeneration-stable (a regeneration keeps it); a row it does not reproduce carries something no served note's ledger block supports -- an index-side correction, which the next regeneration discards. Writes route131.json. Prints the partition, then the named rows of each class. """ import json import os import re import subprocess 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) import route128_next as R # noqa: E402 shared fetch/cache import registry_cites as RC # noqa: E402 shared registry row parser BLOCK_RE = re.compile(r"") KEY_RE = re.compile(r"^([a-z]+):\s*(.*)$") ID_RE = re.compile(r"^Q-[A-Za-z0-9][A-Za-z0-9-]*$") STATUSES = {"OPEN", "PARTIAL", "ANSWERED", "CLOSED", "SUPERSEDED"} HEAD_LINES = 60 def norm(x): return re.sub(r"\s+", " ", str(x or "")).strip() def parse_block(text): """The generator's parseBlock(), faithfully: first 60 lines, `^([a-z]+):`, four required fields.""" head = "\n".join(text.split("\n")[:HEAD_LINES]) m = BLOCK_RE.search(head) title = "" for l in text.split("\n"): if l.startswith("# "): title = l[2:].strip() break if not m: return {"title": title, "block": None, "problems": []} fields, problems = {}, [] for raw in m.group(1).split("\n"): ln = raw.strip() if not ln: continue km = KEY_RE.match(ln) if not km: problems.append("unparseable line %r" % ln) continue fields[km.group(1)] = km.group(2).strip() for k in ("id", "status", "question", "verdict"): if not fields.get(k): problems.append("missing field %r" % k) if fields.get("status") and fields["status"] not in STATUSES: problems.append("status %r not in %s" % (fields["status"], sorted(STATUSES))) if fields.get("id") and not ID_RE.match(fields["id"]): problems.append("id %r does not look like Q-slug" % fields["id"]) todo = [] for s in (fields.get("todo") or "none").split(","): s = s.strip() if not s or s == "none": continue todo.append({"id": re.sub(r"\s*\(retired\)\s*$", "", s), "retired": "(retired)" in s}) return {"title": title, "block": dict(fields, todo=todo), "problems": problems} def indexed_files(docs): """The generator's indexedFiles(): staging notes plus top-level research markdown.""" out = [] for d in docs: if "history/staging/" in d and d.endswith(".md"): out.append(d) elif re.match(r"^research/[^/]+\.md$", d): out.append(d) return sorted(out) def summarise(group): """The generator's summarise(): status agreement rule, verdict from the LAST note in path order.""" last = group[-1]["block"] statuses = [] for x in group: if x["block"]["status"] not in statuses: statuses.append(x["block"]["status"]) if len(statuses) == 1: status = statuses[0] else: status = "MIXED (" + "; ".join("%s: %s" % (os.path.basename(x["path"]), x["block"]["status"]) for x in group) + ")" todo, seen = [], set() for x in group: for t in x["block"]["todo"]: key = t["id"] + (" (retired)" if t["retired"] else "") if key not in seen: seen.add(key) todo.append(key) return {"id": group[0]["block"]["id"], "question": last["question"], "status": status, "verdict": last["verdict"], "files": [x["path"] for x in group], "todo": todo} def link_of(path): """The generator's link(): [basename](path without the research/ prefix).""" rel = path base = os.path.basename(rel) return "[%s](%s)" % (base, re.sub(r"^research/", "", rel)) def main(): docs = [d for d in open(os.path.join(JOB128, "docs-list.txt"), encoding="utf-8").read().split("\n") if d] files = indexed_files(docs) parsed, unindexed, malformed = [], 0, [] for p in files: c, txt = R.get(R.PROJECT + "/docs/" + p) if c != 200: malformed.append({"path": p, "problem": "docs %s" % c}) continue pb = parse_block(txt) if not pb["block"] or not pb["block"].get("id"): unindexed += 1 continue parsed.append({"path": p, "block": pb["block"], "problems": pb["problems"], "title": pb["title"], "sha256": __import__("hashlib").sha256( txt.encode("utf-8", "replace")).hexdigest()}) for pr in pb["problems"]: malformed.append({"path": p, "problem": pr}) 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"]) simulated = {qid: summarise(g) for qid, g in by_id.items()} print("generator inputs: %d notes read, %d carry no usable block (unindexed), %d question ids, " "%d malformed-field findings" % (len(files), unindexed, len(simulated), len(malformed))) # the served index, parsed by the same utility route 131's predecessor used c, served_txt = R.get(R.PROJECT + "/docs/research/QUESTIONS.md") rows = RC.parse_registry(served_txt) print("served index: %d rows over %d ids in %d layouts" % (len(rows), len({q for q, _ in rows}), len({t for _, t in rows}))) # compare row by row, per layout, on the three derived cells def cmp_cell(a, b): return norm(a) == norm(b) stable, mismatch = [], [] for (qid, table), row in sorted(rows.items()): sim = simulated.get(qid) if sim is None: mismatch.append({"qid": qid, "table": table, "why": "id absent from the generator's inputs", "served_status": row["status"], "served_verdict_len": len(row["verdict"])}) continue status_ok = cmp_cell(row["status"], sim["status"]) verdict_ok = cmp_cell(row["verdict"], sim["verdict"]) files_ok = cmp_cell(row["records"], ", ".join(link_of(f) for f in sim["files"])) rec = {"qid": qid, "table": table, "line": row["line"], "served_status": row["status"], "sim_status": sim["status"], "status_ok": status_ok, "verdict_ok": verdict_ok, "files_ok": files_ok, "records": row["records"][:120], "notes": [f for f in sim["files"]], "verdict_len_served": len(row["verdict"]), "verdict_len_sim": len(sim["verdict"]), "served_verdict_head": row["verdict"][:180], "sim_verdict_head": sim["verdict"][:180]} (stable if (status_ok and verdict_ok and files_ok) else mismatch).append(rec) # also: ids the generator emits that have no row at all in the served index served_ids = {q for q, _ in rows} absent = sorted(set(simulated) - served_ids) # classification of CORRECTIONS: for each row, does the note it NAMES carry the row's status? named, carried_own, carried_sibling, index_only, composite = {}, 0, [], [], [] status_of = {} for qid, group in by_id.items(): for x in group: status_of[x["path"]] = x["block"]["status"] for (qid, table), row in sorted(rows.items()): m = re.search(r"\(([^()]+)\)", row["records"]) target = m.group(1).strip().lstrip("./") if m else "" tpath = "research/" + target if not target.startswith("research/") else target own = status_of.get(tpath) named[qid] = {"records_target": tpath, "own_note_status": own} sim = simulated.get(qid) if own is not None and norm(own) == norm(row["status"]): carried_own += 1 continue # The generator's own composite (line 282) is NOT an index-side edit: it is what the rule emits # when the notes carrying an id disagree, and it is reproduced by the rule (proved separately by # route131_generate.py's byte-identical reconstruction). Counting it as index-only would be a # classification error of exactly the kind this census exists to find. if sim and norm(row["status"]) == norm(sim["status"]) and sim["status"].startswith("MIXED ("): composite.append({"qid": qid, "table": table, "served_status": row["status"], "own_note": tpath, "own_note_status": own, "note_statuses": {f: status_of.get(f) for f in sim["files"]}}) continue sim_notes = [f for f in (sim or {}).get("files") or []] sib = [f for f in sim_notes if status_of.get(f) == row["status"]] if sib: carried_sibling.append({"qid": qid, "table": table, "served_status": row["status"], "own_note": tpath, "own_note_status": own, "carried_by": sib}) else: index_only.append({"qid": qid, "table": table, "line": row["line"], "served_status": row["status"], "own_note": tpath, "own_note_status": own, "sim_status": (sim or {}).get("status"), "notes_with_id": sim_notes, "note_statuses": {f: status_of.get(f) for f in sim_notes}}) out = {"generator": "/projects/twin-primes/docs/research/qc/questions.js", "inputs": {"notes_read": len(files), "unindexed": unindexed, "ids": len(simulated), "malformed_findings": len(malformed)}, "served_rows": len(rows), "served_ids": len(served_ids), "rows_reproduced_by_the_generators_own_rule": len(stable), "rows_not_reproduced": len(mismatch), "ids_emitted_but_absent_from_index": absent, "mismatches": mismatch, "malformed": malformed, "corrections": {"carried_by_the_named_note": carried_own, "generator_composite_mixed": len(composite), "carried_by_a_sibling_note": len(carried_sibling), "index_only": len(index_only)}, "carried_by_sibling": carried_sibling, "index_only": index_only, "generator_composite": composite, "named_note_resolution": named} json.dump(out, open(os.path.join(HERE, "route131.json"), "w", encoding="utf-8"), indent=1) print("\nrows reproduced by the generator's own rule: %d of %d" % (len(stable), len(rows))) print("rows NOT reproduced: %d (status/verdict/files cell differences)" % len(mismatch)) for m in mismatch: print(" %-16s tbl%d %-40s served=%-42s sim=%s" % ( m.get("why", ""), m["table"], m["qid"], (m["served_status"] or "")[:42], (m.get("sim_status") or "")[:34])) print("ids the generator emits that the index does not carry:", absent) print("\ncorrections: carried by the named note=%d | generator composite MIXED=%d | " "by a sibling note=%d | INDEX-ONLY=%d" % (carried_own, len(composite), len(carried_sibling), len(index_only))) for x in composite: print(" MIXED (generator-derived) %-34s tbl%d own note status=%s of %s" % (x["qid"], x["table"], x["own_note_status"], len(x["note_statuses"]))) for x in index_only[:14]: print(" INDEX-ONLY %-38s tbl%d served=%-10s own note=%-44s own_status=%s" % ( x["qid"], x["table"], x["served_status"], x["own_note"], x["own_note_status"])) return 0 if __name__ == "__main__": sys.exit(main())