#!/usr/bin/env python3 """Validate the citation set against the URL map, and optionally against the live site. usage: python3 validate_citations.py [--urls data/urls-2026-11-09.jsonl] [--cites data/citations-2026-11-09.jsonl] [--live] Offline: every cite_url must be a 200 page that does not redirect and is its own canonical; ids unique; quotes non-empty. --live: each quote must still appear verbatim in the page's Markdown twin (whitespace-normalised). Exit 1 on failure. """ import argparse, json, re, sys, urllib.request def load(path): with open(path, encoding="utf-8") as f: return [json.loads(l) for l in f if l.strip()] def norm(s): return re.sub(r"\s+", " ", s).strip() def main(): ap = argparse.ArgumentParser() ap.add_argument("--urls", default="data/urls-2026-11-09.jsonl") ap.add_argument("--cites", default="data/citations-2026-11-09.jsonl") ap.add_argument("--live", action="store_true") a = ap.parse_args() urls = {r["url"]: r for r in load(a.urls)} cites = load(a.cites) problems = [] if len({c["id"] for c in cites}) != len(cites): problems.append("duplicate ids") for c in cites: u = urls.get(c["cite_url"]) if not u: problems.append(f"{c['id']}: {c['cite_url']} not in URL map"); continue if u["first_status"] != 200: problems.append(f"{c['id']}: {c['cite_url']} answers {u['first_status']} -> cite {u['redirects_to']}") if u["canonical"] and u["canonical"] != c["cite_url"]: problems.append(f"{c['id']}: canonical is {u['canonical']}") if not c["quote"].strip(): problems.append(f"{c['id']}: empty quote") redirects = [r for r in urls.values() if r["redirects_to"]] print(f"offline: {len(cites)} citations, {len(urls)} URLs in map, {len(redirects)} redirecting URLs") if a.live: cache = {} for c in cites: if c["md_twin"] not in cache: req = urllib.request.Request(c["md_twin"], headers={"User-Agent": "validate-citations/1.0"}) try: cache[c["md_twin"]] = norm(urllib.request.urlopen(req, timeout=90).read().decode("utf-8")) except Exception as e: cache[c["md_twin"]] = None; problems.append(f"{c['md_twin']}: {e}") text = cache[c["md_twin"]] if text is not None and norm(c["quote"]) not in text: problems.append(f"{c['id']}: quote no longer on {c['md_twin']}") print(f"live: fetched {len(cache)} Markdown twins") for p in problems: print(" -", p) print("PASS" if not problems else f"FAIL ({len(problems)})") sys.exit(1 if problems else 0) if __name__ == "__main__": main()