#!/usr/bin/env python3 # ============================================================================ # REGISTRY CHECK — are the served rows of research/QUESTIONS.md still what # their own source ledger blocks say? # # WHY THIS TEST. research/QUESTIONS.md is GENERATED (research/qc/questions.js) # from the `` blocks at the top of the notes. So the row text is # a *copy* of a source, and it can go stale in exactly one mechanical way: the # note's ledger block is edited (or its revision is integrated) and the index is # not regenerated. Nothing in the corpus currently tests that, and the generator # cannot be run on the served snapshot, so it is tested here against the served # files by reimplementing the generator's summarise() rule: # # * the displayed STATUS is the single agreed status, or MIXED (listed); # * the displayed VERDICT is the verdict of the LAST note in path order. # # WHAT IT DOES NOT TEST. Whether the LEDGER BLOCK ITSELF is stale against its # own note body, riders and the outcome register. That is a different defect # (reviews #35/#38, #108, #114, #117, #123, #125) and this test is silent on it. # A row can print "CURRENT" here and still be wrong on the record; the two # results are reported separately for that reason. # # USAGE # SAH= ROWS=23:37 python registry-check.py # Exits 0 when every row matches its sources, 1 when any row is stale. # ============================================================================ import hashlib, io, json, os, re, sys, urllib.parse, urllib.request B = "https://solveathome.org/projects/twin-primes" H = {"Authorization": "Bearer " + os.environ["SAH"], "X-Model": "deepseek-v4.1-flash", "Accept": "text/plain"} BLOCK_RE = re.compile(r"") ROW_RE = re.compile(r"^\|\s*`(Q-[A-Za-z0-9-]+)`\s*\|") def fetch(path): """Served document, LF-normalised, with its sha256 (LF form).""" rq = urllib.request.Request(B + "/docs/" + urllib.parse.quote(path), headers=H) raw = urllib.request.urlopen(rq, timeout=30).read() lf = raw.replace(b"\r\n", b"\n") return lf.decode("utf-8", "replace"), hashlib.sha256(lf).hexdigest() def split_row(line): cells, cur, i = [], [], 0 while i < len(line): c = line[i] if c == "\\" and i + 1 < len(line): cur.append(line[i + 1]); i += 2; continue if c == "|": cells.append("".join(cur)); cur = []; i += 1; continue cur.append(c); i += 1 cells.append("".join(cur)) return [c.strip() for c in cells] def norm(s): return re.sub(r"\s+", " ", s or "").strip() def parse_ledger(src): m = BLOCK_RE.search("\n".join(src.split("\n")[:60])) if not m: return None f = {} for line in m.group(1).split("\n"): km = re.match(r"^([a-z]+):\s*(.*)$", line.strip()) if km: f[km.group(1)] = km.group(2).strip() return f or None def registry(path): """Section-2 rows: id -> {status, question, verdict, todo, records(paths)}.""" src, sha = fetch(path) rows, open_ids = {}, [] for ln in src.split("\n"): if not ln.startswith("|") or ln.startswith("|---"): continue if "| TODO |" in ln or ln.startswith("| id |") or ln.startswith("| TODO item |"): continue c = split_row(ln)[1:-1] if len(c) != 6: continue if c[0].startswith("`Q-") and not open_ids: pass m = ROW_RE.match(ln) if not m: # section 1 rows lead with the TODO item, not the id continue qid = m.group(1) recs = re.findall(r"\[[^\]]+\]\(([^)]+)\)", c[5]) if qid not in rows: # first hit is section 2 (sorted by id) rows[qid] = dict(status=c[1], question=c[2], verdict=c[3], todo=c[4], records=recs) elif sorted(records_key(r) for r in recs) != sorted(records_key(r) for r in rows[qid]["records"]): rows[qid]["records"] = recs return rows, sha def records_key(r): return r.split("/")[-1] def questions_order(rows): """The order GET /questions serves: OPEN/PARTIAL rows only.""" # Served registry is alphabetical by id in section 2; the platform orders by # TODO item then id. We re-derive it from the served /questions endpoint, the # same list the brief numbers from. rq = urllib.request.Request(B + "/questions", headers=H) d = json.loads(urllib.request.urlopen(rq, timeout=30).read().decode("utf-8", "replace")) return d["questions"], d.get("counts", {}) def main(): lo, hi = (int(x) for x in os.environ.get("ROWS", "23:37").split(":")) rows, reg_sha = registry("research/QUESTIONS.md") qs, counts = questions_order(rows) op = [q for q in qs if q["status"] in ("OPEN", "PARTIAL")] sel = op[lo - 1:hi] print(f"served research/QUESTIONS.md sha256(LF) {reg_sha}") print(f"served /questions: {counts.get('total')} questions, {len(op)} open or partial") print(f"sweeping rows {lo}..{hi}: {len(sel)} rows, note set below\n") out, stale = [], 0 for i, q in zip(range(lo, hi + 1), sel): row = rows[q["id"]] notes = [] for rec in row["records"]: path = "research/" + rec try: src, sha = fetch(path) except Exception as e: notes.append(dict(path=path, err=str(e)[:120])); continue led = parse_ledger(src) notes.append(dict(path=path, sha256=sha, ledger=led)) have = [n for n in notes if n.get("ledger")] statuses = sorted({n["ledger"].get("status", "") for n in have}) disp_status = statuses[0] if len(statuses) == 1 else \ "MIXED (" + "; ".join(f'{n["path"].split("/")[-1]}: {n["ledger"].get("status")}' for n in have) + ")" disp_verdict = have[-1]["ledger"].get("verdict", "") if have else "" ok_status = norm(disp_status) == norm(row["status"]) ok_verdict = norm(disp_verdict) == norm(row["verdict"]) verdict = "CURRENT" if (ok_status and ok_verdict) else "STALE" if verdict == "STALE": stale += 1 out.append(dict(row=i, id=q["id"], todo=q["item"], status=row["status"], status_ok=ok_status, verdict_ok=ok_verdict, verdict=verdict, notes=notes, registry_verdict=row["verdict"])) print(f'ROW {i:>2} {q["id"]:<34} {row["status"]:<8} ' f'status_ok={str(ok_status):<5} verdict_ok={str(ok_verdict):<5} -> {verdict}' f' ({len(have)}/{len(notes)} note(s) with a ledger block)') if verdict == "STALE": print(" REGISTRY:", row["verdict"][:220]) print(" SOURCE :", disp_verdict[:220]) json.dump(out, io.open("registry-check.json", "w", encoding="utf-8"), indent=1, ensure_ascii=False) print(f"\n{len(out)} rows swept, {stale} stale at the registry level.") print("Silent on whether a ledger block is itself stale against its note body,") print("riders and the outcome register: see rows23-37.md for that column.") return 1 if stale else 0 if __name__ == "__main__": sys.exit(main())