import fs from "node:fs/promises";
import path from "node:path";
import crypto from "node:crypto";
import { fileURLToPath, pathToFileURL } from "node:url";
import { CHOICES, COMPARE_YEARS, DEFAULTS, DEK, HUME_PUBLISHED, PLAIN, SEO_TITLE, YEAR_RANGE } from "../../public/strata/older-than-the-daily-courant/data.js";
import {
  ageFor,
  anchorResults,
  analyze,
  clockComparison,
  contextFor,
  firstDruryLaneBill,
  formatPercent,
  inventory,
  prepare,
  refusalChecks as engineRefusalChecks,
  trend,
} from "../../public/strata/older-than-the-daily-courant/engine.js";
import { installDom, innerById, normalizeMarkup, stripTags } from "./dom-shim.mjs";

// The verifier has four kinds of evidence, and a green ledger needs all of them:
//   1. an INDEPENDENT recomputation (referenceModel below) that imports nothing from engine.js, and
//      the spec writer's separately computed figures, so a wrong engine goes red;
//   2. the page's REAL render.js run through dom-shim.mjs, so what each panel SAYS after each
//      control moves is compared with (1), and a panel that stops following the controls goes red;
//   3. the shipped static HTML compared with that live render, plus a census of every digit and
//      number word left in the static prose, so a corrupted displayed figure goes red;
//   4. faults planted in COPIES of the data and run through the unmodified engine.

const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
const RESEARCH = path.join(ROOT, "research", "older-than-the-daily-courant");
const RESEARCH_DATA = path.join(RESEARCH, "data");
const PUBLIC_ROOT = path.join(ROOT, "public", "strata", "older-than-the-daily-courant");
const PUBLIC_DATA = path.join(PUBLIC_ROOT, "data");
const INDEX = path.join(PUBLIC_ROOT, "index.html");
const RENDER = path.join(PUBLIC_ROOT, "render.js");
const RECORD = path.join(PUBLIC_ROOT, "record.json");
const CONTENT = path.join(ROOT, "src", "content", "strata", "older-than-the-daily-courant.md");
const LEDGER_KEYS = [
  "anchor_reproduced_by_engine",
  "rendered_figures_asserted",
  "choices_are_live",
  "planted_fault_caught",
  "refusal_asserted",
  "provenance_pinned",
];
const LEDGER = process.argv.includes("--ledger");
const VERBOSE = process.argv.includes("--verbose");

// Figures from the spec writer's own scripts on the raw CSV and SQL dump (specs/older-than-the-daily-courant.md,
// "verified" figures). A different implementation on different bytes, so agreement is evidence.
const SPEC = Object.freeze({
  oldBlocks: { 1725: "64.4", 1735: "68.2", 1740: "74.8", 1750: "78.4", 1760: "62.2", 1770: "50.5", 1780: "45.0", 1790: "34.4", 1795: "33.3" },
  recentBlocks: { 1725: "25.5", 1750: "14.2", 1780: "39.6", 1795: "52.5" },
  clocks: {
    1740: { firstMedian: 36, firstOld: "80.5", pubMedian: 41, pubOld: "83.2", pubN: 381 },
    1800: { firstMedian: 2, firstOld: "18.8", pubMedian: 1, pubOld: "16.8", pubN: 345 },
  },
  unlinkedByKind: { d: 19931, p: 7360, a: 7079, s: 5679, m: 2738, e: 1071, b: 744, u: 190, o: 20, i: 6 },
  rawEvents: 52617,
  performances: 116816,
  unlinked: 44818,
  linked: 71998,
  works: 3678,
  pubWorks: 2285,
  worksYear: 2811,
  partial: 327,
  hume: 1661,
  seasonFault: 26,
  firstDate: "16591029",
  lastDate: "18000916",
  firsts: [{ work: 460, first: "16630528" }, { work: 731, first: "16641105" }, { work: 935, first: "17040605", firstYear: 1672 }, { work: 2653, first: "17730316" }],
  rivalsAges: [136, 25],
});

const failures = [];
const groups = Object.fromEntries(LEDGER_KEYS.map((key) => [key, []]));

function check(group, label, value) {
  const pass = Boolean(value);
  groups[group].push(pass);
  if (!pass) failures.push(`${group}: ${label}`);
  if (VERBOSE && !LEDGER) console.log(`${pass ? "ok  " : "FAIL"} ${group}: ${label}`);
  return pass;
}

const fmt = (value) => new Intl.NumberFormat("en-US").format(value);
const HOUSE_CHROME = /<!--aw-(?:plain|checkkind|nearby|wayout):start-->[\s\S]*?<!--aw-(?:plain|checkkind|nearby|wayout):end-->\s*/g;
function stripHouseChrome(source) {
  return source
    .replace(HOUSE_CHROME, " ")
    .replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi, " ")
    .replace(/<script\b(?=[^>]*\bsrc=["']\/media\/[^"']+["'])(?![^>]*\btype=["']module["'])[^>]*>[\s\S]*?<\/script>/gi, " ");
}

async function readJson(file) {
  return JSON.parse(await fs.readFile(file, "utf8"));
}

async function sha256(file) {
  return crypto.createHash("sha256").update(await fs.readFile(file)).digest("hex");
}

async function loadFrozen(directory) {
  const manifest = await readJson(path.join(directory, "manifest.json"));
  const loaded = { "manifest.json": manifest };
  for (const entry of manifest.files) loaded[entry.file] = await readJson(path.join(directory, entry.file));
  const eventParts = Object.keys(loaded).filter((name) => name.startsWith("events-")).sort();
  const performanceParts = Object.keys(loaded).filter((name) => name.startsWith("performances-")).sort();
  return {
    raw: {
      events: eventParts.flatMap((name) => loaded[name]),
      performances: performanceParts.flatMap((name) => loaded[name]),
      works: loaded["works.json"],
      dictionaries: loaded["dictionaries.json"],
      audit: loaded["audit.json"],
      witnesses: loaded["witnesses.json"],
      manifest,
    },
    loaded,
  };
}

// ---------------------------------------------------------------------------------------------
// 1. The independent recomputation. It shares no code with engine.js: its own date rule, its own
// first-observation table, its own loops. It implements the page's DECLARED rule, not its code.
function referenceModel(raw) {
  const kinds = raw.dictionaries.kinds;
  const venues = raw.dictionaries.venues;
  const titles = raw.dictionaries.titles;
  const isFullDate = (text) => {
    const match = /^(\d{4})(\d{2})(\d{2})$/.exec(text || "");
    if (!match) return false;
    const year = Number(match[1]);
    const month = Number(match[2]);
    const day = Number(match[3]);
    if (year === 0 || month < 1 || month > 12 || day < 1) return false;
    const leap = year < 1752 ? year % 4 === 0 : (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
    const length = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1];
    return day <= length && !(text >= "17520903" && text <= "17520913");
  };
  const eventInfo = new Map(raw.events.map((event) => [event[0], { date: event[1], venue: venues[event[2]] }]));
  const firstSeen = new Map();
  const records = [];
  for (const value of raw.performances) {
    const info = eventInfo.get(value[1]) || { date: "", venue: "" };
    const full = isFullDate(info.date);
    const work = value[3];
    if (work !== null && full && (!firstSeen.has(work) || info.date < firstSeen.get(work))) firstSeen.set(work, info.date);
    records.push({ id: value[0], event: value[1], order: Number(value[5] || 0), kind: kinds[value[2]], work, date: info.date, full, year: full ? Number(info.date.slice(0, 4)) : null, venue: info.venue, title: titles[value[4]] || "" });
  }
  const publication = new Map(raw.works.map((work) => [work[0], /^\d{4}/.test(work[2] || "") ? Number(String(work[2]).slice(0, 4)) : null]));
  const middle = (list) => {
    const sorted = [...list].sort((a, b) => a - b);
    if (!sorted.length) return null;
    return sorted.length % 2 ? sorted[(sorted.length - 1) / 2] : (sorted[sorted.length / 2 - 1] + sorted[sorted.length / 2]) / 2;
  };
  const block = ({ start, end, clock = "full", threshold = 20, novelty = 5, kind = "p" }) => {
    let onBills = 0;
    let noWork = 0;
    let setAside = 0;
    const ages = [];
    const firsts = [];
    for (const record of records) {
      if (!record.full || record.kind !== kind || record.year < start || record.year > end) continue;
      onBills += 1;
      if (record.work === null) {
        noWork += 1;
        continue;
      }
      const observed = Number(firstSeen.get(record.work).slice(0, 4));
      const origin = clock === "pub" ? publication.get(record.work) : observed;
      if (origin === null || origin === undefined || origin > record.year) {
        setAside += 1;
        continue;
      }
      ages.push(record.year - origin);
      firsts.push(observed);
    }
    const old = ages.filter((age) => age >= threshold).length;
    const recent = ages.filter((age) => age <= novelty).length;
    return {
      onBills,
      noWork,
      setAside,
      n: ages.length,
      old,
      recent,
      oldPct: ages.length ? ((100 * old) / ages.length).toFixed(1) : null,
      recentPct: ages.length ? ((100 * recent) / ages.length).toFixed(1) : null,
      medianAge: middle(ages),
      medianFirst: middle(firsts),
      heap: firsts.filter((year) => year >= 1703 && year <= 1707).length,
    };
  };
  const seasonEndOf = (date) => Number(date.slice(0, 4)) + (Number(date.slice(4, 6)) >= 9 ? 1 : 0);
  const firstDruryLane = (year, unit = "calendar") => {
    let best = null;
    for (const event of raw.events) {
      if (venues[event[2]] !== "dl" || !isFullDate(event[1])) continue;
      const key = unit === "season" ? seasonEndOf(event[1]) : Number(event[1].slice(0, 4));
      if (key !== year) continue;
      if (!best || event[1] < best[1] || (event[1] === best[1] && event[0] < best[0])) best = event;
    }
    if (!best) return null;
    const items = records.filter((record) => record.event === best[0]).sort((a, b) => a.order - b.order || a.id - b.id);
    const periodYear = unit === "season" ? seasonEndOf(best[1]) : Number(best[1].slice(0, 4));
    return {
      date: best[1],
      ages: items.map((record) => (["p", "a"].includes(record.kind) && record.work !== null ? periodYear - Number(firstSeen.get(record.work).slice(0, 4)) : null)),
    };
  };
  const unlinkedByKind = {};
  let partial = 0;
  let hume = 0;
  for (const record of records) {
    if (record.work === null) unlinkedByKind[record.kind] = (unlinkedByKind[record.kind] || 0) + 1;
    if (!record.full) partial += 1;
    if (record.full && record.year >= 1660 && record.year <= 1700 && record.title.trim()) hume += 1;
  }
  return { block, firstDruryLane, unlinkedByKind, partial, hume, firstSeen, records };
}

// ---------------------------------------------------------------------------------------------
function anchorChecks(raw, ctx, evidence) {
  const rows = anchorResults(ctx, raw.witnesses);
  const school = rows.filter((row) => row.id.startsWith("scandal-"));
  check("anchor_reproduced_by_engine", "four School for Scandal witnesses agree", school.length === 4 && school.every((row) => row.agrees));
  check("anchor_reproduced_by_engine", "the two named disagreements remain visible", rows.find((row) => row.id === "stoops-first")?.agrees === false && rows.find((row) => row.id === "rivals-first")?.agrees === false);
  check("anchor_reproduced_by_engine", "the anchor counts come from the same run function", rows.find((row) => row.id === "scandal-20")?.computed === 20 && rows.find((row) => row.id === "scandal-57")?.computed === 57 && rows.find((row) => row.id === "scandal-65")?.computed === 65);

  // The expected value is read back out of the transcription as printed, so a fixture edited to
  // agree with a wrong engine goes red here.
  const months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
  const printedAgrees = raw.witnesses.every((witness) => {
    if (witness.type === "count") {
      const printed = /(\d+)(?:st|nd|rd|th) time/.exec(witness.as_written);
      return printed && Number(printed[1]) === witness.expected;
    }
    const printed = /^(?:([A-Z][a-z]+) )?(\d+)\./.exec(witness.as_written);
    if (!printed || witness.expected !== witness.date) return false;
    const monthOkay = !printed[1] || months.indexOf(printed[1]) + 1 === Number(witness.date.slice(4, 6));
    return monthOkay && Number(printed[2]) === Number(witness.date.slice(6, 8));
  });
  check("anchor_reproduced_by_engine", "each expected value is the number or day printed in its transcribed line", printedAgrees);
  const evidenceById = new Map(evidence.map((item) => [item.id, item]));
  const sameTranscription = raw.witnesses.every((witness) => {
    const source = evidenceById.get(witness.id);
    if (!source) return false;
    const shared = ["work", "venue", "date", "type", "expected", "volume", "page", "image_n", "as_written"].filter((key) => key in source);
    return shared.includes("as_written") && shared.includes("date") && shared.every((key) => JSON.stringify(source[key]) === JSON.stringify(witness[key]));
  });
  check("anchor_reproduced_by_engine", "the public witnesses equal the research evidence transcription", sameTranscription);

  const first = ctx.rows.find((row) => row.work === 2743 && row.date === "17770508");
  const doctored = structuredClone(raw);
  doctored.performances.find((value) => value[0] === first.id)[3] = null;
  check("anchor_reproduced_by_engine", "a damaged first-night record breaks the first-observation witness", anchorResults(prepare(doctored, "published"), doctored.witnesses).find((row) => row.id === "scandal-first")?.agrees === false);
  const tenth = ctx.rows.filter((row) => row.work === 2743 && row.venue === "dl" && row.full).sort((a, b) => a.date.localeCompare(b.date) || a.id - b.id)[9];
  const doctoredCount = structuredClone(raw);
  doctoredCount.performances.find((value) => value[0] === tenth.id)[3] = null;
  const countRows = anchorResults(prepare(doctoredCount, "published"), doctoredCount.witnesses);
  check("anchor_reproduced_by_engine", "a missing link inside the run breaks the 20th-night witness", countRows.find((row) => row.id === "scandal-20")?.agrees === false && countRows.find((row) => row.id === "scandal-20")?.computed === 19);
}

function engineChoiceChecks(raw) {
  const probes = {
    origin: { ...DEFAULTS, year: 1740, pool: 1 },
    kind: { ...DEFAULTS, year: 1740, pool: 1 },
    weight: { ...DEFAULTS, year: 1800, pool: 1 },
    linkage: { ...DEFAULTS, year: 1800, pool: 1 },
    unit: { ...DEFAULTS, year: 1800, pool: 1 },
    threshold: { ...DEFAULTS, year: 1750, pool: 5 },
    novelty: { ...DEFAULTS, year: 1750, pool: 5 },
    validity: { ...DEFAULTS, year: 1730, pool: 5 },
    houses: { ...DEFAULTS, year: 1740, pool: 1 },
    pool: { ...DEFAULTS, year: 1750, pool: 5 },
  };
  const signature = (result) => JSON.stringify([result.rows, result.eligible, result.oldShare, result.recentShare, result.medianAge, result.medianFirst, result.unknown, result.linkageCounts, result.label]);
  for (const choice of CHOICES) {
    const outputs = choice.options.map((value) => signature(analyze(contextFor(raw, choice.id === "linkage" ? value : "published"), { ...probes[choice.id], [choice.id]: value })));
    const changes = outputs.some((value) => value !== outputs[0]);
    check("choices_are_live", `${choice.id} changes an engine output`, changes);
    check("choices_are_live", `${choice.id} is declared non-inert, and that declaration is true`, choice.inert === false && changes);
  }
  return probes;
}

function faultChecks(raw, ctx) {
  const clean = analyze(ctx, DEFAULTS);
  check("planted_fault_caught", "the clean default closes: rows equal computed plus unlinked plus set aside", clean.closes && clean.closureTotal === clean.rows && clean.bandsClose);
  const candidate = clean.workRows.find((item) => item.row.kind === "p" && item.row.work !== null);
  const doctored = structuredClone(raw);
  const row = doctored.performances.find((value) => value[0] === candidate.row.id);
  row[3] = null;
  const doctoredResult = analyze(prepare(doctored, "published"), DEFAULTS);
  check("planted_fault_caught", "a planted missing WorkId moves one record from computed to unlinked", doctoredResult.eligible === clean.eligible - 1 && doctoredResult.unknown === clean.unknown + 1 && doctoredResult.closes);
  check("planted_fault_caught", "the WorkId fault is planted in data, not in a result", row[3] === null && candidate.row.work !== null);

  // A partial date planted on a real 1750 event: its mainpieces must leave the bills and be COUNTED
  // as left out, not silently disappear, and each must be refused with the partial-date reason.
  const event = raw.events.find((value) => value[1].startsWith("1750") && ctx.rows.some((item) => item.event === value[0] && item.kind === "p" && item.work !== null));
  const mains = ctx.rows.filter((item) => item.event === event[0] && item.kind === "p");
  const linkedMains = mains.filter((item) => item.work !== null && ageFor(ctx, item, "full", item.year).age !== null);
  const partialCopy = structuredClone(raw);
  partialCopy.events.find((value) => value[0] === event[0])[1] = `${event[1].slice(0, 6)}00`;
  const partialCtx = prepare(partialCopy, "published");
  const partialResult = analyze(partialCtx, DEFAULTS);
  const refused = partialCtx.rows.filter((item) => item.event === event[0] && item.kind === "p").every((item) => ageFor(partialCtx, item, "full", 1750).code === "partial");
  check("planted_fault_caught", "a planted partial date removes that bill's mainpieces from the rows and counts them as left out", mains.length > 0 && partialResult.rows === clean.rows - mains.length && partialResult.excludedPartial === clean.excludedPartial + mains.length);
  check("planted_fault_caught", "a planted partial date lowers the computed denominator by its linked mainpieces and each is refused", partialResult.eligible === clean.eligible - linkedMains.length && refused && partialResult.closes);
}

function refusalEngineChecks(ctx) {
  const refusals = engineRefusalChecks(ctx);
  check("refusal_asserted", "outside-year input is refused", refusals.outside.refused === true && /outside/.test(refusals.outside.reason));
  check("refusal_asserted", "unlinked mainpiece is refused", refusals.unlinked.age === null && /No WorkId/.test(refusals.unlinked.reason));
  check("refusal_asserted", "dance is outside the instrument", refusals.dance.age === null && /outside the work-age instrument/.test(refusals.dance.reason));
  check("refusal_asserted", "a real partial-date linked mainpiece is refused as partial", refusals.partial.row && !refusals.partial.row.full && refusals.partial.code === "partial");
  const early = analyze(ctx, { ...DEFAULTS, year: 1705 });
  check("refusal_asserted", "the 1705 block withholds its old share and says why", early.oldShare === null && early.oldReason === "Withheld because the look-back begins in 1685, before the chosen validity year 1710." && early.recentShare !== null);
  const rows = trend(ctx, DEFAULTS);
  check("refusal_asserted", "a withheld trend row carries its reason", rows[0].old === null && /look-back begins in 1705/.test(rows[0].oldReason));
  const pub = analyze(ctx, { ...DEFAULTS, origin: "pub" });
  check("refusal_asserted", "the publication clock sets aside records with no or later publication year, by reason", pub.missingReasons["no-pub"] > 0 && pub.missingReasons["after-period"] > 0 && pub.missing === pub.missingReasons["no-pub"] + pub.missingReasons["after-period"]);
  check("refusal_asserted", "a season with no Drury Lane bill yields no bill rather than a substitute", firstDruryLaneBill(ctx, 1792, "season").event === null && firstDruryLaneBill(ctx, 1792, "calendar").event !== null);
}

function referenceChecks(raw, ctx, model) {
  const blocks = trend(ctx, { ...DEFAULTS, validity: 1705 });
  let engineAgrees = true;
  let specAgrees = true;
  for (const row of blocks) {
    const ref = model.block({ start: row.year, end: row.year + 4 });
    if (formatPercent(row.old) !== `${ref.oldPct}%` || formatPercent(row.recent) !== `${ref.recentPct}%` || row.eligible !== ref.n || row.medianAge !== ref.medianAge || row.medianFirst !== ref.medianFirst) engineAgrees = false;
    if (SPEC.oldBlocks[row.year] && SPEC.oldBlocks[row.year] !== ref.oldPct) specAgrees = false;
    if (SPEC.recentBlocks[row.year] && SPEC.recentBlocks[row.year] !== ref.recentPct) specAgrees = false;
  }
  check("rendered_figures_asserted", "every five-year block agrees with the independent recomputation", engineAgrees);
  check("rendered_figures_asserted", "the independent recomputation reproduces the spec's separately computed block shares", specAgrees);
  for (const year of COMPARE_YEARS) {
    const engine = clockComparison(ctx, year);
    const first = model.block({ start: year, end: year });
    const pub = model.block({ start: year, end: year, clock: "pub" });
    const spec = SPEC.clocks[year];
    check("rendered_figures_asserted", `calendar ${year} clock comparison agrees with the recomputation and the spec`,
      engine.first.medianAge === first.medianAge && formatPercent(engine.first.oldShare) === `${first.oldPct}%` && engine.publication.medianAge === pub.medianAge && formatPercent(engine.publication.oldShare) === `${pub.oldPct}%` && engine.publication.eligible === pub.n
      && first.medianAge === spec.firstMedian && first.oldPct === spec.firstOld && pub.medianAge === spec.pubMedian && pub.oldPct === spec.pubOld && pub.n === spec.pubN);
  }
  const value = inventory(ctx);
  const kindsAgree = Object.entries(SPEC.unlinkedByKind).every(([code, expected]) => value.byKind.find((row) => row.code === code)?.unlinked === expected && model.unlinkedByKind[code] === expected);
  check("rendered_figures_asserted", "unlinked records by kind agree with the spec and the recomputation", kindsAgree && value.otherKinds === 0);
  check("rendered_figures_asserted", "inventory counts agree with the spec and the recomputation",
    value.recount.rawEvents === SPEC.rawEvents && value.performances === SPEC.performances && value.unlinked === SPEC.unlinked && value.linked === SPEC.linked && value.works === SPEC.works && value.pubWorks === SPEC.pubWorks && value.worksYear === SPEC.worksYear
    && value.partial === SPEC.partial && model.partial === SPEC.partial && value.hume === SPEC.hume && model.hume === SPEC.hume && value.seasonFault === SPEC.seasonFault && value.firstDate === SPEC.firstDate && value.lastDate === SPEC.lastDate);
  check("rendered_figures_asserted", "the inventory's recount of the frozen arrays agrees with the extraction audit",
    value.recount.rawEvents === value.rawEvents && value.recount.performances === value.auditPerformances && value.recount.firstSeenEventIds === value.firstSeenEventIds && value.recount.numericEventIds === value.numericEventIds);
  check("rendered_figures_asserted", "named first observations agree with the spec and the recomputation", SPEC.firsts.every((item) => ctx.firstFull.get(item.work) === item.first && model.firstSeen.get(item.work) === item.first && (!item.firstYear || ctx.firstYear.get(item.work) === item.firstYear)));
}

// ---------------------------------------------------------------------------------------------
// 2 and 3. The real render.js, the shipped static HTML, and the census.
async function renderChecks({ index, record, raw, loaded, manifest, model }) {
  const manifestHashes = new Map(manifest.files.map((entry) => [entry.file, entry.sha256]));
  const dom = installDom(index, {
    serveFile: async (url) => {
      const file = fileURLToPath(url);
      const name = path.basename(file);
      const inside = path.dirname(file) === PUBLIC_DATA;
      const bytes = await fs.readFile(file);
      const hash = crypto.createHash("sha256").update(bytes).digest("hex");
      const pinned = name === "manifest.json" ? record.record.sha256 : manifestHashes.get(name);
      if (!inside || hash !== pinned || !loaded[name]) return { ok: false, json: async () => null };
      return { ok: true, json: async () => loaded[name] };
    },
  });
  const text = (id) => dom.text(id);
  let module;
  let ready = null;
  try {
    module = await import(pathToFileURL(RENDER).href);
    ready = await module.ready;
  } catch (error) {
    dom.errors.push(String(error && error.stack ? error.stack : error));
  }
  check("rendered_figures_asserted", "render.js opened the frozen files and drew the page without an error", ready && ready.refused === false && dom.errors.length === 0 && /is ready/.test(text("page-status")));
  if (!ready) {
    dom.restore();
    return;
  }
  check("rendered_figures_asserted", "every id in index.html is unique", dom.duplicates.length === 0);

  // 3a. The static markup of every live panel equals the live render at the default state.
  // The house's heading-anchor pass (scripts/seo-heads.mjs, applied to this page in the identity sweep of
  // 2026-09-14, 67d8175285) gives every bare h2 and h3 in the static HTML a slug id so a passage can be
  // deep-linked; render.js redraws these panels without them, and this check went red on four panels from
  // that day. An anchor is not a displayed figure, so heading ids are left out on both sides; every word and
  // figure a reader sees is still compared. (Repaired 2026-11-09.)
  const withoutHeadingAnchors = (markup) => String(markup ?? "").replace(/<(h[23])\s+id="[^"]*"/gi, "<$1");
  const EQUALITY = ["headline-status", "record-strip", "analysis", "bill", "trend-note", "comparison", "inventory", "check-current", "check-context", "genest-note", "hume-note"];
  const liveDefault = Object.fromEntries(EQUALITY.map((id) => [id, dom.html(id)]));
  for (const id of EQUALITY) {
    const found = innerById(index, id);
    check("rendered_figures_asserted", `static #${id} equals the live render at the default state`, found && normalizeMarkup(withoutHeadingAnchors(found.inner)) === normalizeMarkup(withoutHeadingAnchors(liveDefault[id])));
  }

  // 3b. The live default figures equal the independent recomputation, not just the engine.
  const ref = model.block({ start: 1750, end: 1754 });
  const headline = `In the 1750 to 1754 block, ${ref.oldPct}% of linked mainpiece performance records were at least 20 years past the first full-date observation of their work, and ${ref.recentPct}% were within 5 years of it.`;
  check("rendered_figures_asserted", "the live default result sentence is the independently recomputed sentence", text("analysis").includes(headline));
  check("rendered_figures_asserted", "record.json headline is that sentence, shipped as plain text in index.html", record.headline === headline && index.includes(headline));
  const sums = (r) => [`Records on the bills ${fmt(r.onBills)}`, `No WorkId, refused an age ${fmt(r.noWork)}`, `Linked, no usable start on this clock ${fmt(r.setAside)}`, `Age computed ${fmt(r.n)}`, `${fmt(r.n)} + ${fmt(r.noWork)} + ${fmt(r.setAside)} = ${fmt(r.onBills)}, the records on the bills: closes`];
  const defaultCheck = text("check-current");
  check("rendered_figures_asserted", "the default check prints the recomputed sums and shares", sums(ref).every((item) => defaultCheck.includes(item))
    && defaultCheck.includes(`${fmt(ref.old)} of ${fmt(ref.n)} = ${ref.oldPct}%`) && defaultCheck.includes(`${fmt(ref.recent)} of ${fmt(ref.n)} = ${ref.recentPct}%`) && defaultCheck.includes(`Median years since first full-date observation ${ref.medianAge}`));
  check("rendered_figures_asserted", "the default record line prints the recomputed rows and unlinked count", text("analysis").includes(`In the record for 1750 to 1754: ${fmt(ref.onBills)} mainpiece performance records with a full date at all venues. ${fmt(ref.noWork)} have no WorkId`));
  const refInventoryStrip = `the frozen record holds ${fmt(model.records.length)} performance records`;
  check("rendered_figures_asserted", "the hero inventory strip prints the recomputed record count and partial dates", text("record-strip").includes(refInventoryStrip) && text("record-strip").includes(`${fmt(model.partial)} have a partial date`) && text("record-strip").includes(`${fmt(SPEC.unlinked)} do not`));
  check("rendered_figures_asserted", "the rendered inventory prints unlinked records by kind", Object.entries(SPEC.unlinkedByKind).every(([code, expected]) => {
    const labels = { d: "dance", p: "mainpiece", a: "afterpiece", s: "song", m: "music", e: "entertainment", b: "ballet", u: "monologue", o: "opera", i: "instrumental" };
    return new RegExp(`${labels[code]} [\\d,]+ ${fmt(expected).replace(/,/g, ",")} `).test(text("inventory"));
  }) && text("inventory").includes(`${fmt(model.partial)} have the day missing`));
  const refBill = model.firstDruryLane(1750);
  check("rendered_figures_asserted", "the default bill is the recomputed first Drury Lane night of calendar 1750, with recomputed ages", text("bill").includes(`First Drury Lane bill in calendar 1750 (inside the 1750 to 1754 block) ${refBill.date.slice(0, 4)}-${refBill.date.slice(4, 6)}-${refBill.date.slice(6, 8)}`) && billAgesMatch(text("bill"), refBill.ages, "first full-date observation"));

  // 3c. The census: after removing the live panels, the controls, and the registered sentences
  // below (each tied to a recomputed or pinned value), no digit and no number word may remain.
  const census = staticCensus(index, EQUALITY, record, raw, model);
  check("rendered_figures_asserted", `every registered static sentence is present (${census.missing.join(" | ") || "none missing"})`, census.missing.length === 0);
  check("rendered_figures_asserted", `no unregistered figure remains in the static prose (${census.tokens.join(", ") || "none"})`, census.tokens.length === 0);

  // 2. The controls drive the real page.
  const refSentence = (label, r, clockPhrase = "the first full-date observation of their work") => `${label}, ${r.oldPct}% of linked mainpiece performance records were at least 20 years past ${clockPhrase}, and ${r.recentPct}% were within 5 years of it.`;
  dom.setValue("year", "1795", "input");
  const late = model.block({ start: 1795, end: 1799 });
  check("rendered_figures_asserted", "slider to 1795: the result sentence is the recomputed 1795 block sentence", text("analysis").includes(refSentence("In the 1795 to 1799 block", late)));
  check("choices_are_live", "slider to 1795: the check follows, with the recomputed sums", sums(late).every((item) => text("check-current").includes(item)) && text("check-current").includes("bill year 1795"));
  check("choices_are_live", "slider to 1795: the status readout follows", text("headline-status").startsWith(`1795 to 1799: ${late.oldPct}% at least 20 years past first full-date observation`));

  dom.setValue("year", "1752", "input");
  const bill1752 = model.firstDruryLane(1752);
  check("choices_are_live", "slider to 1752 in a five-year block: the bill is the first Drury Lane night of 1752, not of the block start",
    text("bill").includes(`First Drury Lane bill in calendar 1752 (inside the 1750 to 1754 block) ${bill1752.date.slice(0, 4)}-${bill1752.date.slice(4, 6)}-${bill1752.date.slice(6, 8)}`) && text("analysis").includes("1750 to 1754") && billAgesMatch(text("bill"), bill1752.ages, "first full-date observation"));
  dom.setValue("unit", "season");
  const season1752 = model.firstDruryLane(1752, "season");
  check("choices_are_live", "unit to season: the bill is the first Drury Lane night of season 1751-1752, aged at the season end",
    text("bill").includes(`First Drury Lane bill in season 1751-1752 (inside the seasons 1749-1750 to 1753-1754 block) ${season1752.date.slice(0, 4)}-${season1752.date.slice(4, 6)}-${season1752.date.slice(6, 8)}`) && text("bill").includes("taken at the end year of season 1751-1752") && billAgesMatch(text("bill"), season1752.ages, "first full-date observation") && text("check-current").includes("Theatrical season derived from the date"));
  dom.setValue("year", "1792", "input");
  check("refusal_asserted", "season 1791-1792 has no Drury Lane bill and the page says so", model.firstDruryLane(1792, "season") === null && text("bill").includes("No full-date Drury Lane bill is recorded for season 1791-1792"));
  dom.setValue("unit", "calendar");
  dom.setValue("year", "1750", "input");

  // Every age sentence names its clock, and no other clock.
  const LABELS = { full: "first full-date observation", year: "first year-known observation", pub: "catalogued publication year", earlier: "earlier of first observation and publication year" };
  dom.setValue("pool", "1");
  dom.setValue("year", "1740", "input");
  for (const origin of Object.keys(LABELS)) {
    dom.setValue("origin", origin);
    const panels = ["analysis", "check-current", "bill", "trend", "headline-status"].map((id) => text(id)).join(" | ");
    const own = [`past ${LABELS[origin]}`, `within 5 years of ${LABELS[origin]}`, `years since ${LABELS[origin]}`].every((phrase) => panels.includes(phrase));
    const foreign = Object.entries(LABELS).filter(([key]) => key !== origin && !(origin === "earlier" && key === "full")).some(([, label]) => [`past ${label}`, `years of ${label}`, `years since ${label}`].some((phrase) => panels.includes(phrase)));
    const foreignFull = origin !== "full" && [`past first full-date observation`, `years of first full-date observation`, `years since first full-date observation`].some((phrase) => panels.includes(phrase));
    check("rendered_figures_asserted", `clock ${origin}: every age phrase in the result, check, bill, trend and status names ${LABELS[origin]} and no other clock`, own && !foreign && !foreignFull);
  }
  dom.setValue("origin", "pub");
  const pub1740 = model.block({ start: 1740, end: 1740, clock: "pub" });
  check("rendered_figures_asserted", "publication clock at 1740: the sentence and check carry the recomputed publication-clock figures",
    text("analysis").includes(refSentence("In calendar 1740", pub1740, "the catalogued publication year of their work")) && text("check-current").includes(`${fmt(pub1740.old)} of ${fmt(pub1740.n)} = ${pub1740.oldPct}%`) && text("check-current").includes(`Linked, no usable start on this clock ${fmt(pub1740.setAside)}`));
  dom.setValue("origin", "full");
  dom.setValue("pool", "5");
  dom.setValue("year", "1750", "input");

  // Each declared choice changes the check and the result through the real page, and the check
  // always equals the engine's result for the state the page is in.
  const probes = engineChoiceChecks.probes;
  for (const choice of CHOICES) {
    const probe = probes[choice.id];
    dom.setValue("pool", String(probe.pool));
    dom.setValue("year", String(probe.year), "input");
    const baseCheck = dom.html("check-current");
    const baseAnalysis = dom.html("analysis");
    let everyOptionMovesCheck = true;
    let someOptionMovesResult = false;
    let checkMatchesState = true;
    for (const option of choice.options.filter((value) => String(value) !== String(probe[choice.id]))) {
      dom.setValue(choice.id, String(option));
      const expected = analyze(contextFor(raw, choice.id === "linkage" ? option : "published"), { ...probe, [choice.id]: option });
      const label = choice.labels[choice.options.indexOf(option)];
      const checkText = text("check-current");
      if (dom.html("check-current") === baseCheck) everyOptionMovesCheck = false;
      if (dom.html("analysis") !== baseAnalysis) someOptionMovesResult = true;
      const shareText = expected.oldShare === null ? "withheld" : formatPercent(expected.oldShare);
      if (!checkText.includes(`Records on the bills ${fmt(expected.rows)}`) || !checkText.includes(`${fmt(expected.old)} of ${fmt(expected.eligible)} = ${shareText}`) || !checkText.includes(label)) checkMatchesState = false;
      dom.setValue(choice.id, String(probe[choice.id]));
    }
    check("choices_are_live", `${choice.id}: every option redraws the check panel`, everyOptionMovesCheck);
    check("choices_are_live", `${choice.id}: some option changes the displayed result`, someOptionMovesResult);
    check("choices_are_live", `${choice.id}: the check shows the rows, shares and label of the state the page is in`, checkMatchesState);
  }
  dom.setValue("pool", "5");
  dom.setValue("year", "1750", "input");

  // Linkage redraws the context panels (inventory and check) and the join counts are all printed.
  dom.setValue("linkage", "title");
  const titled = inventory(contextFor(raw, "title"));
  check("choices_are_live", "linkage to title: the inventory and the check context redraw on the title-matched links",
    text("inventory").includes(`Without a WorkId ${fmt(titled.unlinked)}`) && text("check-context").includes(`Without a WorkId, Add unambiguous normalized-title matches ${fmt(titled.unlinked)}`) && titled.unlinked < SPEC.unlinked);
  const titledResult = analyze(contextFor(raw, "title"), DEFAULTS);
  check("rendered_figures_asserted", "linkage to title: added, ambiguous, unmatched and repaired counts are all printed",
    text("analysis").includes(`${fmt(titledResult.linkageCounts.added)} title joins added, ${fmt(titledResult.linkageCounts.ambiguous)} ambiguous`) && text("analysis").includes(`${fmt(titledResult.linkageCounts.unmatched)} unmatched`));
  dom.setValue("linkage", "published");

  // Quick years, trend rows, and withheld reasons.
  const quick = dom.clickIn("quick-years", "data-year", "1705");
  check("refusal_asserted", "quick year 1705: the withheld old share prints its reason in the result, the check and the status",
    quick === 1 && text("analysis").includes("Withheld because the look-back begins in 1685, before the chosen validity year 1710.") && text("check-current").includes("withheld: Withheld because the look-back begins in 1685") && text("headline-status").includes("old share withheld (Withheld because the look-back begins in 1685"));
  check("refusal_asserted", "the withheld 1725 to 1729 trend row prints its reason", text("trend").includes("withheld Withheld because the look-back begins in 1705, before the chosen validity year 1710."));
  const jump = dom.clickIn("trend", "data-year", "1795");
  check("choices_are_live", "a trend row moves the first layer to its block", jump === 1 && text("analysis").includes(refSentence("In the 1795 to 1799 block", late)));
  const danceYear = (() => {
    for (let year = YEAR_RANGE.min; year <= YEAR_RANGE.max; year += 1) {
      const bill = firstDruryLaneBill(contextFor(raw, "published"), year);
      if (bill.event && bill.items.some((item) => item.kind === "d") && bill.items.some((item) => item.work === null && item.kind === "p")) return year;
    }
    return null;
  })();
  if (danceYear) dom.setValue("year", String(danceYear), "input");
  check("refusal_asserted", "a bill prints the refusals for an unlinked mainpiece and a dance", danceYear !== null && text("bill").includes("refused: No WorkId is present, so age is refused.") && text("bill").includes("refused: This item kind is outside the work-age instrument."));

  // Comparison, works, disclosures, reset.
  dom.setValue("compare-year", "1800");
  const first1800 = model.block({ start: 1800, end: 1800 });
  const pub1800 = model.block({ start: 1800, end: 1800, clock: "pub" });
  check("rendered_figures_asserted", "compare year 1800: the three clock cards print the recomputed figures",
    text("comparison").includes(`${first1800.medianAge} years, median Years since first full-date observation: ${first1800.oldPct}% at least 20`) && text("comparison").includes(`${pub1800.medianAge} ${pub1800.medianAge === 1 ? "year" : "years"}, median Years since catalogued publication year: ${pub1800.oldPct}% at least 20`) && text("comparison").includes(`${fmt(pub1800.n)} linked mainpiece records in calendar 1800 have a start on this clock; ${fmt(pub1800.setAside)} set aside`));
  dom.setValue("work-search", "2743", "input");
  const opened = dom.clickIn("work-list", "data-work-id", "2743");
  check("choices_are_live", "searching 2743 and opening it shows School for Scandal from its first night", opened === 1 && text("work-detail").includes("WorkId 2743") && text("work-detail").includes("1777-05-08") && dom.html("work-list").includes('data-work-id="2743" aria-pressed="true"'));
  dom.setValue("origin", "pub");
  check("choices_are_live", "an open work redraws its ages on the newly chosen clock", text("work-detail").includes("Years since catalogued publication year") && !text("work-detail").includes("years since first full-date observation"));
  dom.setValue("origin", "full");
  const toggled = dom.clickIn("check-context", "data-toggle", "rivals-detail");
  const openMarkup = dom.html("check-context");
  check("choices_are_live", "a fault disclosure opens with aria-expanded kept in step", toggled === 1 && openMarkup.includes('aria-controls="rivals-detail" aria-expanded="true"') && openMarkup.includes('<div class="fault-detail" id="rivals-detail">'));
  dom.clickIn("check-context", "data-toggle", "rivals-detail");
  check("choices_are_live", "the fault disclosure closes again", dom.html("check-context").includes('aria-controls="rivals-detail" aria-expanded="false"'));
  dom.click("reference-toggle");
  check("choices_are_live", "the source-notes disclosure opens with aria-expanded kept in step", dom.get("reference-notes").hidden === false && dom.get("reference-toggle").getAttribute("aria-expanded") === "true");
  dom.click("reset-controls");
  check("choices_are_live", "reset returns every live panel to the shipped default markup", ["analysis", "bill", "check-current", "trend-note", "headline-status", "check-context", "inventory"].every((id) => normalizeMarkup(dom.html(id)) === normalizeMarkup(liveDefault[id])));
  check("rendered_figures_asserted", "the page made no request outside its own data folder", dom.requests.length === manifest.files.length + 1 && dom.requests.every((url) => url.startsWith("file:") && path.dirname(fileURLToPath(url)) === PUBLIC_DATA));
  check("rendered_figures_asserted", "no console error was raised while every control was driven", dom.errors.length === 0);
  dom.restore();
}

function billAgesMatch(billText, refAges, clock) {
  const found = [];
  const pattern = new RegExp(`(\\d+) years since ${clock}|refused: [^.]+\\.`, "g");
  for (const match of billText.matchAll(pattern)) found.push(match[1] === undefined ? null : Number(match[1]));
  return found.length === refAges.length && found.every((value, index) => value === refAges[index]);
}

function staticCensus(index, equalityIds, record, raw, model) {
  let body = stripHouseChrome(index.slice(index.indexOf("<body")));
  const blank = (id) => {
    const found = innerById(body, id);
    if (found) body = body.slice(0, found.start) + body.slice(found.end);
    return found;
  };
  for (const id of equalityIds) blank(id);
  const quick = innerById(body, "quick-years");
  const buttons = [...(quick ? quick.inner : "").matchAll(/data-year="(\d+)">(\d+)</g)];
  const quickOkay = buttons.length >= 2 && buttons.every((match) => match[1] === match[2] && Number(match[1]) >= YEAR_RANGE.min && Number(match[1]) <= YEAR_RANGE.max) && buttons.some((match) => Number(match[1]) === YEAR_RANGE.min) && buttons.some((match) => Number(match[1]) === YEAR_RANGE.max);
  const rangeOkay = stripTags(innerById(body, "range-labels")?.inner || "") === `${YEAR_RANGE.min} ${YEAR_RANGE.max}` && stripTags(innerById(body, "year-display")?.inner || "") === String(DEFAULTS.year);
  const slider = /<input id="year" type="range" min="(\d+)" max="(\d+)" step="1" value="(\d+)" aria-label="Bill year from (\d+) to (\d+)" \/>/.exec(body);
  const sliderOkay = slider && Number(slider[1]) === YEAR_RANGE.min && Number(slider[2]) === YEAR_RANGE.max && Number(slider[3]) === DEFAULTS.year && Number(slider[4]) === YEAR_RANGE.min && Number(slider[5]) === YEAR_RANGE.max;
  for (const id of ["quick-years", "range-labels", "year-display"]) blank(id);
  const selects = [...body.matchAll(/<select id="([a-z-]+)">([\s\S]*?)<\/select>/g)];
  const selectsOkay = CHOICES.every((choice) => {
    const markup = selects.find((match) => match[1] === choice.id)?.[2] || "";
    const options = [...markup.matchAll(/<option value="([^"]*)"( selected)?>([^<]*)<\/option>/g)];
    return options.length === choice.options.length && options.every((match, i) => match[1] === String(choice.options[i]) && match[3] === choice.labels[i] && Boolean(match[2]) === (String(choice.options[i]) === String(DEFAULTS[choice.id])));
  }) && (selects.find((match) => match[1] === "compare-year")?.[2] || "").replace(/ selected/g, "") === COMPARE_YEARS.map((year) => `<option value="${year}">${year}</option>`).join("");
  body = body.replace(/<script[\s\S]*?<\/script>/g, " ").replace(/<!--[\s\S]*?-->/g, " ").replace(/<select[\s\S]*?<\/select>/g, " ");
  const placeholderOkay = /placeholder="School for Scandal or (\d+)"/.exec(body)?.[1] === "2743" && raw.works.find((work) => work[0] === 2743)?.[1].includes("School for Scandal");
  const zenodo = /records\/(\d+)$/.exec(record.record.licence_url)?.[1];
  const scandalFirst = raw.witnesses.find((witness) => witness.id === "scandal-first");
  const genestHref = body.includes(`someaccountofeng0${scandalFirst.volume}geneuoft/page/n${scandalFirst.image_n}/`);
  const registered = [
    { text: DEK, okay: DEK.includes(`leaves ${fmt(inventoryUnlinked(model))} unlinked performance records`) },
    { text: PLAIN, okay: PLAIN.includes(`from ${YEAR_RANGE.min} to ${YEAR_RANGE.max}`) && PLAIN.includes(`at least ${DEFAULTS.threshold} years earlier`) },
    { text: "Layer one: put your hand on a bill", okay: true },
    { text: "Layer two: dismiss the instrument", okay: true },
    { text: `Digital Humanities Quarterly history on ${record.record.retrieved} and did not find a published age distribution`, okay: record.record.retrieved === "2026-09-14" },
    { text: `Frozen extract retrieved ${record.record.retrieved}.`, okay: true },
    { text: `Zenodo ${zenodo}`, okay: Boolean(zenodo) },
    { text: "CC BY-NC 4.0", okay: true },
    { text: `Genest volume ${scandalFirst.volume}, page ${scandalFirst.page}`, okay: genestHref },
  ];
  let text = stripTags(body);
  const missing = [];
  for (const item of registered) {
    if (!item.okay || !text.includes(item.text)) missing.push(item.text.slice(0, 48));
    text = text.split(item.text).join(" ");
  }
  if (!quickOkay) missing.push("quick-year buttons");
  if (!rangeOkay) missing.push("range labels or year readout");
  if (!sliderOkay) missing.push("slider bounds");
  if (!selectsOkay) missing.push("static select options");
  if (!placeholderOkay) missing.push("search placeholder WorkId");
  const tokens = [...text.matchAll(/\d[\d,.]*|\b(?:one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|twenty|thirty|forty|fifty|sixty|seventy|eighty|ninety|hundred|thousand)\b/gi)].map((match) => match[0]);
  return { missing, tokens };
}

function inventoryUnlinked(model) {
  return Object.values(model.unlinkedByKind).reduce((sum, value) => sum + value, 0);
}

function surfaceChecks(index, content, record) {
  check("rendered_figures_asserted", "dek is present verbatim", index.includes(`<p class="dek">${DEK}</p>`));
  check("rendered_figures_asserted", "plain placard is present verbatim", index.includes(`<p class="plain-placard">${PLAIN}</p>`) && index.includes(`<meta name="aw:plain" content="${PLAIN}" />`));
  check("rendered_figures_asserted", "frontmatter dek, plain and seoTitle are verbatim", content.includes(`plain: "${PLAIN}"`) && content.includes(`dek: "${DEK}"`) && content.includes(`seoTitle: "${SEO_TITLE}"`));
  check("rendered_figures_asserted", "SEO title is in the title tag, OG and Twitter", index.includes(`<title>${SEO_TITLE}</title>`) && index.includes(`<meta property="og:title" content="${SEO_TITLE}" />`) && index.includes(`<meta name="twitter:title" content="${SEO_TITLE}" />`));
  check("rendered_figures_asserted", "meta, OG and Twitter descriptions are the dek", index.includes(`<meta name="description" content="${DEK}" />`) && index.includes(`<meta property="og:description" content="${DEK}" />`) && index.includes(`<meta name="twitter:description" content="${DEK}" />`));
  check("rendered_figures_asserted", "canonical is exact", index.includes('<link rel="canonical" href="https://artwaste.land/strata/older-than-the-daily-courant/" />'));
  check("rendered_figures_asserted", "OG, Twitter and JSON-LD image are exact", index.split("https://artwaste.land/og/older-than-the-daily-courant.png").length === 4);
  let jsonLdOk = false;
  try {
    const match = index.match(/<script type="application\/ld\+json">([\s\S]*?)<\/script>/);
    const json = JSON.parse(match[1]);
    jsonLdOk = json["@type"] === "Article" && json.headline === SEO_TITLE && json.description === DEK && json.url === "https://artwaste.land/strata/older-than-the-daily-courant/";
  } catch {
    jsonLdOk = false;
  }
  check("rendered_figures_asserted", "JSON-LD parses and agrees", jsonLdOk);
  check("rendered_figures_asserted", "record choices match the engine choices", JSON.stringify(record.choices) === JSON.stringify(CHOICES));
  check("rendered_figures_asserted", "the Hume figure is labelled as published and differs from the recomputed unit", HUME_PUBLISHED === 949 && SPEC.hume !== HUME_PUBLISHED);
}

async function provenanceChecks(record, researchRaw) {
  const publicFrozen = await loadFrozen(PUBLIC_DATA);
  const researchManifest = researchRaw.manifest;
  check("provenance_pinned", "research and public manifests agree", JSON.stringify(researchManifest) === JSON.stringify(publicFrozen.raw.manifest));
  const recordFiles = new Map(record.files.map((entry) => [entry.file, entry]));
  let allFiles = true;
  for (const entry of researchManifest.files) {
    const researchHash = await sha256(path.join(RESEARCH_DATA, entry.file));
    const publicHash = await sha256(path.join(PUBLIC_DATA, entry.file));
    const bytes = (await fs.stat(path.join(PUBLIC_DATA, entry.file))).size;
    allFiles = allFiles && researchHash === entry.sha256 && publicHash === entry.sha256 && bytes === entry.bytes && recordFiles.get(entry.file)?.sha256 === entry.sha256 && recordFiles.get(entry.file)?.bytes === entry.bytes;
  }
  check("provenance_pinned", "every frozen file matches manifest and record, in both copies", allFiles);
  check("provenance_pinned", "manifest hash is pinned in record", await sha256(path.join(PUBLIC_DATA, "manifest.json")) === record.record.sha256);
  check("provenance_pinned", "record units match numeric PerformanceIds", record.record.units === researchRaw.audit.numeric_performance_ids && record.record.units === researchRaw.performances.length);
  check("provenance_pinned", "record names the MIT source and retrieval", /MIT/.test(record.record.licence) && record.record.retrieved === "2026-09-14");
  const readme = await fs.readFile(path.join(RESEARCH, "README.md"), "utf8");
  const readmeData = researchManifest.files.every((entry) => readme.includes(`| \`${entry.file}\` | ${entry.bytes} | \`${entry.sha256}\` |`)) && readme.includes(`| \`manifest.json\` | ${record.files.find((entry) => entry.file === "manifest.json").bytes} | \`${record.record.sha256}\` |`);
  check("provenance_pinned", "the research README pins every frozen file's bytes and hash", readmeData);
  const scans = (await fs.readdir(path.join(RESEARCH, "evidence", "scans"))).filter((name) => name.endsWith(".jpg")).sort();
  let scansOkay = scans.length === researchRaw.witnesses.length;
  for (const scan of scans) scansOkay = scansOkay && readme.includes(`| \`${scan}\` | \`${await sha256(path.join(RESEARCH, "evidence", "scans", scan))}\` |`);
  check("provenance_pinned", "the README pins the hash of every Genest scan", scansOkay);
}

async function main() {
  const { raw, loaded } = await loadFrozen(RESEARCH_DATA);
  const ctx = contextFor(raw, "published");
  const index = await fs.readFile(INDEX, "utf8");
  const content = await fs.readFile(CONTENT, "utf8");
  const record = await readJson(RECORD);
  const evidence = await readJson(path.join(RESEARCH, "evidence", "witnesses.json"));
  const model = referenceModel(raw);

  anchorChecks(raw, ctx, evidence);
  engineChoiceChecks.probes = engineChoiceChecks(raw);
  faultChecks(raw, ctx);
  refusalEngineChecks(ctx);
  referenceChecks(raw, ctx, model);
  surfaceChecks(index, content, record);
  await renderChecks({ index, record, raw, loaded, manifest: raw.manifest, model });
  await provenanceChecks(record, raw);

  const values = Object.fromEntries(LEDGER_KEYS.map((key) => [key, groups[key].length > 0 && groups[key].every(Boolean)]));
  if (LEDGER) {
    for (const key of LEDGER_KEYS) process.stdout.write(`${key}=${values[key]}\n`);
  } else {
    for (const key of LEDGER_KEYS) console.log(`${key}: ${values[key] ? "PASS" : "FAIL"} (${groups[key].length} assertions)`);
    console.log(`assertions: ${LEDGER_KEYS.reduce((sum, key) => sum + groups[key].length, 0)}`);
    if (failures.length) {
      console.error("Failures:");
      for (const failure of failures) console.error(`- ${failure}`);
    }
  }
  if (failures.length) process.exitCode = 1;
}

main().catch((error) => {
  console.error(error && error.stack ? error.stack : error);
  process.exitCode = 1;
});
