#!/usr/bin/env node
// verify-a-coin-in-every-third-grave.mjs
//
// Recomputes every number the page shows, from the shipped files, with the page's own modules, and
// fails on any disagreement. Six groups of assertions, one per ledger cell; each ledger boolean is the
// conjunction of its group's real outcomes.
//
//   nice -n 19 node research/a-coin-in-every-third-grave/verify-a-coin-in-every-third-grave.mjs
//   nice -n 19 node research/a-coin-in-every-third-grave/verify-a-coin-in-every-third-grave.mjs --ledger
//
// With --ledger, stdout carries exactly the six ledger lines; everything else goes to stderr.
// The permutation census runs in a worker thread (census-thread.mjs), one run at a time: seed 1 at
// 9,999 shuffles for the page's figures, seeds 1 to 10 for the range the page labels as offline, and
// seed 1 at 999 shuffles for the report. Expect about two minutes on one core.
// The verifier never writes a file.

import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import { spawnSync } from 'node:child_process';
import { Worker } from 'node:worker_threads';
import { fileURLToPath } from 'node:url';
import * as E from '../../public/strata/a-coin-in-every-third-grave/engine.js';
import * as F from '../../public/strata/a-coin-in-every-third-grave/figures.js';

const SLUG = 'a-coin-in-every-third-grave';
const HERE = path.dirname(fileURLToPath(import.meta.url));
const REPO = path.join(HERE, '..', '..');
const PUB = path.join(REPO, 'public', 'strata', SLUG);
const RAW = path.join(HERE, 'data', 'raw');
const LEDGER = process.argv.includes('--ledger');
const log = (...a) => (LEDGER ? console.error(...a) : console.log(...a));

// ---------------------------------------------------------------------------------------------------
// Assertion bookkeeping
// ---------------------------------------------------------------------------------------------------

const GROUPS = {
  anchor: 'anchor_reproduced_by_engine',
  surface: 'rendered_figures_asserted',
  choices: 'choices_are_live',
  faults: 'planted_fault_caught',
  refusal: 'refusal_asserted',
  provenance: 'provenance_pinned',
};
const outcomes = Object.fromEntries(Object.keys(GROUPS).map((g) => [g, []]));
const meta = [];
let current = 'provenance';
function group(g) { current = g; log(`\n== ${g}`); }
function check(name, ok, detail = '') {
  const pass = Boolean(ok);
  (current === 'meta' ? meta : outcomes[current]).push({ name, pass });
  if (!pass || !LEDGER) log(`${pass ? '  ok  ' : '  FAIL'} ${name}${detail ? ' :: ' + detail : ''}`);
  return pass;
}
function attempt(name, fn) {
  try { return fn(); } catch (err) { check(name, false, 'threw: ' + (err && err.message ? err.message : err)); return undefined; }
}

const sha = (buf) => crypto.createHash('sha256').update(buf).digest('hex');
const read = (p) => fs.readFileSync(p);
const readText = (p) => fs.readFileSync(p, 'utf8');

// ---------------------------------------------------------------------------------------------------
// Load
// ---------------------------------------------------------------------------------------------------

const DATA_FILES = ['all_graves.csv', 'Code_EM_grave_goods.R', 'printed-tables.json', 'quotes.json', 'figure1-sites.csv', 'all_cemeteries.csv'];
const bytes = Object.fromEntries(DATA_FILES.map((f) => [f, read(path.join(PUB, f))]));
const html = readText(path.join(PUB, 'index.html'));
const md = readText(path.join(REPO, 'src', 'content', 'strata', `${SLUG}.md`));
const recordPath = path.join(PUB, 'record.json');
const record = fs.existsSync(recordPath) ? JSON.parse(readText(recordPath)) : null;
const printed = JSON.parse(bytes['printed-tables.json'].toString('utf8'));
const quotes = JSON.parse(bytes['quotes.json'].toString('utf8')).quotes;

function buildModel(over = {}) {
  return E.buildModel({
    gravesBytes: new Uint8Array(over.gravesBytes || bytes['all_graves.csv']),
    rText: over.rText || bytes['Code_EM_grave_goods.R'].toString('utf8'),
    printed: over.printed || printed,
    sitesText: bytes['figure1-sites.csv'].toString('utf8'),
    cemeteriesBytes: new Uint8Array(bytes['all_cemeteries.csv']),
  });
}
const model = buildModel();

// The census, in a worker thread, one run at a time.
function censusRun(worker, jobs, B, seed, runId) {
  return new Promise((resolve, reject) => {
    const onMsg = (msg) => {
      if (msg.runId !== runId) return;
      worker.off('message', onMsg);
      if (msg.type === 'done') resolve(msg.results); else reject(new Error(msg.message));
    };
    worker.on('message', onMsg);
    worker.postMessage({ type: 'run', jobs, B, seed, runId });
  });
}

// ---------------------------------------------------------------------------------------------------
// Frontmatter
// ---------------------------------------------------------------------------------------------------

function frontmatter(text) {
  const fm = text.split(/^---\s*$/m)[1];
  const get = (k) => { const m = fm.match(new RegExp(`^${k}:\\s*"(.*)"\\s*$`, 'm')); return m ? m[1] : null; };
  const relates = [...fm.matchAll(/-\s*to:\s*([\w-]+)\s*\n\s*note:\s*"(.*)"/g)].map((m) => ({ to: m[1], note: m[2] }));
  return { title: get('title'), dek: get('dek'), seoTitle: get('seoTitle'), plain: get('plain'), seam: get('seam'), href: get('href'), relates };
}
const FM = frontmatter(md);

// ---------------------------------------------------------------------------------------------------
// HTML surface: the functions the negative controls also run
// ---------------------------------------------------------------------------------------------------

const ENT = { lt: '<', gt: '>', amp: '&', quot: '"', apos: "'", nbsp: ' ', middot: '\u00b7', plusmn: '\u00b1', ldquo: '\u201c', rdquo: '\u201d', rsquo: '\u2019' };
const decode = (s) => s.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (m, e) => (e[0] === '#' ? String.fromCodePoint(e[1].toLowerCase() === 'x' ? parseInt(e.slice(2), 16) : Number(e.slice(1))) : (ENT[e.toLowerCase()] ?? m)));
const textOf = (frag) => decode(frag.replace(/<[^>]+>/g, '')).replace(/\s+/g, ' ').trim();

// Every element carrying one of the page's evidence attributes, with its inner text.
const ATTRS = ['data-fig', 'data-printed', 'data-quote', 'data-cite', 'data-offline'];
function attributed(doc) {
  const out = [];
  const re = new RegExp(`<(\\w+)\\b([^>]*\\b(${ATTRS.join('|')})="([^"]*)"[^>]*)>`, 'g');
  for (const m of doc.matchAll(re)) {
    const tag = m[1];
    const start = m.index;
    const openEnd = start + m[0].length;
    let depth = 1;
    const tagRe = new RegExp(`<(/?)${tag}\\b[^>]*>`, 'g');
    tagRe.lastIndex = openEnd;
    let close = null;
    for (let t; (t = tagRe.exec(doc));) {
      depth += t[1] ? -1 : 1;
      if (depth === 0) { close = t; break; }
    }
    if (!close) { out.push({ attr: m[3], value: m[4], text: null, start, end: openEnd }); continue; }
    out.push({ attr: m[3], value: m[4], text: textOf(doc.slice(openEnd, close.index)), start, end: close.index + close[0].length });
  }
  return out;
}

function bodyOf(doc) {
  const b = doc.slice(doc.indexOf('<body'), doc.lastIndexOf('</body>'));
  return b.replace(/<!--[\s\S]*?-->/g, ' ').replace(/<script[\s\S]*?<\/script>/g, ' ').replace(/<style[\s\S]*?<\/style>/g, ' ');
}

function printedValue(spec) {
  const [key, field] = spec.split(':');
  if (/^T\d+$/.test(key)) {
    const t = printed.tables.find((x) => x.table === Number(key.slice(1)));
    if (!t) return null;
    if (field === 'column') return t.columns_as_written.join(' ');
    if (field === 'n') return String(t.n_as_written);
    return null;
  }
  const cell = printed.tables.flatMap((t) => t.cells).find((c) => c.key === key);
  return cell ? (field === 'coef' ? cell.coef : field === 'p' ? cell.p : null) : null;
}

const STRUCTURAL = [/\bTables? \d+(?: to \d+)?/g, /\bFigures? \d+(?: to \d+)?/g, /\bseed 1\b/g, /\bSHA-256\b/g, /\bUTF-8\b/g, /\bISO-8859-1\b/g, /\bwindows-1252\b/g, /\bfigure1-sites\.csv\b/g];

// Returns a list of failures for a document, given the recomputed values. Empty list means clean.
function surfaceFailures(doc, values, offline) {
  const fails = [];
  const body = bodyOf(doc);
  const els = attributed(body);
  for (const el of els) {
    if (el.text === null) { fails.push(`unclosed ${el.attr}=${el.value}`); continue; }
    if (el.attr === 'data-fig') {
      if (!(el.value in values)) fails.push(`unknown figure ${el.value}`);
      else if (el.text !== values[el.value]) fails.push(`figure ${el.value}: page ${el.text}, engine ${values[el.value]}`);
    } else if (el.attr === 'data-printed') {
      const want = printedValue(el.value);
      if (want === null || el.text !== want) fails.push(`printed ${el.value}: page ${el.text}, transcription ${want}`);
    } else if (el.attr === 'data-quote') {
      const q = quotes.find((x) => x.id === el.value);
      if (!q || !q.text.includes(el.text)) fails.push(`quote ${el.value} is not in quotes.json`);
    } else if (el.attr === 'data-cite') {
      if (!(el.text in F.CITATIONS) || el.value !== el.text) fails.push(`citation ${el.value} / ${el.text} is not a declared citation`);
    } else if (el.attr === 'data-offline') {
      if (!(el.value in offline)) fails.push(`unknown offline figure ${el.value}`);
      else if (el.text !== offline[el.value]) fails.push(`offline ${el.value}: page ${el.text}, verifier ${offline[el.value]}`);
    }
  }
  // Enumerate, do not match: remove every attributed element, the declared shuffle options, and the
  // structural references, then require that no digit is left in the visible text.
  let rest = body;
  for (const el of [...els].sort((a, b) => b.start - a.start)) if (el.text !== null) rest = rest.slice(0, el.start) + ' ' + rest.slice(el.end);
  rest = rest.replace(/<option value="(\d+)"( selected)?>([^<]*)<\/option>/g, (m, v, sel, txt) => {
    const perm = E.CHOICES.find((c) => c.id === 'permutations');
    if (!perm.options.includes(Number(v)) || txt !== Number(v).toLocaleString('en-US')) fails.push(`shuffle option ${v} / ${txt} is not a declared option`);
    return ' ';
  });
  let visible = decode(rest.replace(/<[^>]+>/g, ' ')).replace(/\s+/g, ' ');
  for (const re of STRUCTURAL) visible = visible.replace(re, ' ');
  for (const m of visible.matchAll(/\d/g)) fails.push(`bare digit in visible text near "${visible.slice(Math.max(0, m.index - 40), m.index + 20).trim()}"`);
  return fails;
}

function headFailures(doc, values, fm, headline) {
  const fails = [];
  const tag = (re) => { const m = doc.match(re); return m ? decode(m[1]) : null; };
  const title = tag(/<title>([^<]*)<\/title>/);
  const desc = tag(/<meta name="description" content="([^"]*)"/);
  const ogd = tag(/<meta property="og:description" content="([^"]*)"/);
  const twd = tag(/<meta name="twitter:description" content="([^"]*)"/);
  const ogt = tag(/<meta property="og:title" content="([^"]*)"/);
  const canon = tag(/<link rel="canonical" href="([^"]*)"/);
  const ogurl = tag(/<meta property="og:url" content="([^"]*)"/);
  const ogimg = tag(/<meta property="og:image" content="([^"]*)"/);
  const twimg = tag(/<meta name="twitter:image" content="([^"]*)"/);
  if (title !== fm.seoTitle) fails.push(`title "${title}" is not seoTitle`);
  if (desc !== fm.dek) fails.push('meta description is not the dek');
  if (ogt !== `${fm.title} \u00b7 Artificial Wasteland`) fails.push('og:title is not the title');
  const url = `https://artwaste.land/strata/${SLUG}/`;
  if (canon !== url || ogurl !== url) fails.push('canonical or og:url is wrong');
  if (ogimg !== `https://artwaste.land/og/${SLUG}.png` || twimg !== ogimg) fails.push('OG or Twitter image is wrong');
  const ld = doc.match(/<script type="application\/ld\+json">([\s\S]*?)<\/script>/);
  let j = null;
  try { j = JSON.parse(ld[1]); } catch { fails.push('JSON-LD does not parse'); }
  if (j) {
    if (j.description !== fm.dek) fails.push('JSON-LD description is not the dek');
    if (j.headline !== fm.title || j.name !== fm.seoTitle || j.url !== url) fails.push('JSON-LD headline, name or url is wrong');
  }
  const dekHtml = (() => { const m = doc.match(/<p class="dek">([\s\S]*?)<\/p>/); return m ? textOf(m[1]) : null; })();
  if (dekHtml !== fm.dek) fails.push('the page dek is not the frontmatter dek');
  const headHtml = (() => { const m = doc.match(/<p class="headline" id="headline">([\s\S]*?)<\/p>/); return m ? textOf(m[1]) : null; })();
  if (headline !== null && headHtml !== headline) fails.push('the page headline is not record.json headline');
  // Numbers in the shorter descriptions must each be a recomputed value.
  const known = new Set(Object.values(values));
  for (const [name, s] of [['og:description', ogd], ['twitter:description', twd]]) {
    const stripped = s.replace(/\bTables? \d+(?: to \d+)?/g, ' ');
    for (const m of stripped.matchAll(/\d[\d,.]*\d|\d/g)) if (!known.has(m[0])) fails.push(`${name} number ${m[0]} is not a recomputed figure`);
  }
  for (const [name, s] of [['title', fm.title], ['seoTitle', fm.seoTitle]]) if (/\d/.test(s)) fails.push(`${name} has a digit`);
  if (headline !== null && ogd !== headline) fails.push('og:description is not the record.json headline');
  return fails;
}

// Every surface a claim can travel on: the visible page, the head, the frontmatter, the manifest and
// the refusal answers the engine gives.
function surfacesOf(doc, fm, rec, mdText, refusals) {
  const tag = (re) => { const m = doc.match(re); return m ? decode(m[1]) : ''; };
  let ld = {};
  try { ld = JSON.parse(doc.match(/<script type="application\/ld\+json">([\s\S]*?)<\/script>/)[1]); } catch { ld = {}; }
  return [
    ['visible page text', textOf(bodyOf(doc))],
    ['meta description', tag(/<meta name="description" content="([^"]*)"/)],
    ['og:description', tag(/<meta property="og:description" content="([^"]*)"/)],
    ['twitter:description', tag(/<meta name="twitter:description" content="([^"]*)"/)],
    ['JSON-LD description', ld.description || ''],
    ['dek', fm.dek], ['plain', fm.plain], ['relates notes', fm.relates.map((r) => r.note).join(' ')],
    ['frontmatter body', mdText.split(/^---\s*$/m).slice(2).join(' ')],
    ['record.json headline', rec ? rec.headline : ''],
    ['record.json anchor', rec && rec.anchor ? `${rec.anchor.expected} ${rec.anchor.computed}` : ''],
    ['record.json practice', rec ? rec.practice : ''],
    ['refusal answers', refusals],
  ];
}

// Exactness claims, conditioned on what the engine reproduces from the record. "Every digit" is allowed
// only if Table 13's printed sample size comes back too; "her printed tables come back" (plural and
// unqualified) only if every printed coefficient does. On this record neither holds.
const EVERY_DIGIT = /\bevery (?:printed )?digit\b|\bto the last (?:printed )?digit\b|\bdigit for digit\b/i;
const TABLES_BACK = /\b(?:her|brownlee's|the article's|the) (?:own )?printed tables (?:return|come back|reproduce|match)/i;
function claimFailures(surfaces, reproduced) {
  const t13 = reproduced.filter((x) => x.table === 13);
  const nBack = t13.length > 0 && t13.every((x) => x.printedN !== null && x.n === x.printedN);
  const missing = reproduced.filter((x) => !x.coefExact).length;
  const fails = [];
  for (const [name, text] of surfaces) {
    if (!text) continue;
    if (EVERY_DIGIT.test(text) && !nBack) fails.push(`${name} claims every digit, but Table 13's printed N does not come back`);
    if (TABLES_BACK.test(text) && missing > 0) fails.push(`${name} says the printed tables come back, but ${missing} printed coefficients do not`);
  }
  return fails;
}

// The record establishes no cause for the shift, so no surface may name one.
const CAUSE = /\bspreadsheet\b|\bexport(?:ed|ing)? (?:slip|error|fault|bug|glitch)\b|\bslip in (?:a|the)\b|\bcopy[- ]?paste\b|\b(?:caused|introduced) by\b|\bslipped\b/i;
const causeFailures = (surfaces) => surfaces.filter(([, t]) => t && CAUSE.test(t)).map(([n, t]) => `${n} names a cause: "${t.match(CAUSE)[0]}"`);

// A figure that moves when the reader changes a control must sit after a default-run label in its
// section (between two h2 headings), or inside an element the page swaps out when the state leaves
// the default. `moving` is found from the record, not listed by hand.
function staleProseFailures(doc, moving) {
  const body = bodyOf(doc);
  const heads = [...body.matchAll(/<h2\b/g)].map((m) => m.index);
  const labels = [...body.matchAll(/\bdata-default-run="[^"]*"/g)].map((m) => m.index);
  const wrappers = [];
  for (const m of body.matchAll(/<(\w+)\b[^>]*\bdata-default-state="[^"]*"[^>]*>/g)) {
    let depth = 1;
    const re = new RegExp(`<(/?)${m[1]}\\b[^>]*>`, 'g');
    re.lastIndex = m.index + m[0].length;
    for (let t; (t = re.exec(body));) { depth += t[1] ? -1 : 1; if (depth === 0) { wrappers.push([m.index, t.index]); break; } }
  }
  const fails = [];
  for (const el of attributed(body)) {
    if (el.attr !== 'data-fig' || !moving.has(el.value)) continue;
    if (wrappers.some(([a, b]) => el.start > a && el.end <= b)) continue;
    const sectionStart = Math.max(0, ...heads.filter((h) => h < el.start));
    if (labels.some((l) => l > sectionStart && l < el.start)) continue;
    fails.push(`${el.value} moves with a control but sits in prose not labelled as the default run`);
  }
  return fails;
}

// ---------------------------------------------------------------------------------------------------
// Main
// ---------------------------------------------------------------------------------------------------

async function main() {
  const t0 = Date.now();

  // ================================================================================ provenance
  group('provenance');
  const hashes = Object.fromEntries(DATA_FILES.map((f) => [f, sha(bytes[f])]));
  check('record.json exists', record !== null);
  for (const f of DATA_FILES) check(`record.json pins ${f}`, record && record.files && record.files[f] === hashes[f], hashes[f]);
  check('record.sha256 is the grave file', record && record.record && record.record.sha256 === hashes['all_graves.csv']);
  const rawPairs = [['all_graves.csv', 'all_graves.csv'], ['all_cemeteries.csv', 'all_cemeteries.csv'], ['Code_EM_grave_goods.R', 'Code_EM_grave_goods.R'], ['data.csv', 'figure1-sites.csv']];
  for (const [raw, pub] of rawPairs) check(`the shipped ${pub} is byte-identical to the frozen download ${raw}`, sha(read(path.join(RAW, raw))) === hashes[pub]);
  const readme = fs.existsSync(path.join(HERE, 'README.md')) ? readText(path.join(HERE, 'README.md')) : '';
  for (const f of DATA_FILES) check(`README.md records the SHA-256 of ${f}`, readme.includes(hashes[f]));
  check('the printed-tables.json source hash is the frozen article HTML', printed.source.sha256 === sha(read(path.join(RAW, 'full-text.html'))));
  const ex = spawnSync(process.execPath, [path.join(HERE, 'extract.mjs')], { encoding: 'utf8' });
  check('a fresh extraction from the frozen HTML equals the shipped transcription and quotations', ex.status === 0, (ex.stdout + ex.stderr).trim().split('\n').pop());
  const routes = JSON.parse(readText(path.join(HERE, 'data', 'transcription-routes.json')));
  check('the two transcription routes and the spec writer\'s values agree everywhere', routes.disagreements.length === 0 && routes.problems.length === 0, `${routes.disagreements.length} disagreements, ${routes.problems.length} problems`);
  check('route C compared 99 coefficients and route B all 22 tables', routes.compared.routeC_coefficients === 99 && routes.compared.routeB_tables === 22);
  const doctoredBytes = Buffer.from(bytes['all_graves.csv']);
  doctoredBytes[200000] ^= 1;
  check('control: one flipped bit in a copy of the grave file no longer matches its pin', sha(doctoredBytes) !== hashes['all_graves.csv']);
  check('LICENCE.txt names every Brownlee file shipped', ['all_graves.csv', 'all_cemeteries.csv', 'Code_EM_grave_goods.R', 'figure1-sites.csv'].every((f) => readText(path.join(PUB, 'LICENCE.txt')).includes(f)));
  const pubCode = ['engine.js', 'figures.js', 'render.js', 'page.js', 'census-worker.js'].map((f) => readText(path.join(PUB, f))).join('\n');
  check('no script builds a request to another host', !/(fetch|import|Worker)\s*\(\s*['"`]https?:/.test(pubCode) && !/<script[^>]+src="https?:/.test(html) && !/<link[^>]+href="https?:\/\/(?!artwaste\.land)[^"]*"[^>]*rel="stylesheet"/.test(html));
  check('the page does not link the private repository', !/github\.com\/[^"]*Artificial-Wasteland/i.test(html));
  const emDash = /\u2014/;
  for (const f of ['index.html', 'engine.js', 'figures.js', 'render.js', 'page.js', 'census-worker.js', 'LICENCE.txt']) check(`no em dash in ${f}`, !emDash.test(readText(path.join(PUB, f))));
  check('no em dash in the frontmatter file', !emDash.test(md));

  // ================================================================================ anchor
  group('anchor');
  const rep = E.reproduce(model, E.DEFAULTS);
  const t = (r, n) => r.filter((x) => x.table === n);
  const count = (arr, f) => arr.filter((x) => x[f]).length;
  check('Table 13: all 11 printed coefficients come back from the file, realigned', count(t(rep, 13), 'coefExact') === 11);
  check('Table 13: all 11 printed P-values come back as R prints them', count(t(rep, 13), 'pExact') === 11);
  const t2o = rep.find((x) => x.key === 'T2.unfurnished.overall');
  const t2f = rep.find((x) => x.key === 'T2.unfurnished.furnished');
  check('Table 2 unfurnished burial, overall: 0.193 as printed', t2o.coefExact && t2o.printedCoef === '0.193' && E.formatRP(t2o.p) === t2o.printedP);
  check('Table 2 unfurnished burial, furnished period: 0.122 and 1.046e-11 as printed', t2f.coefExact && t2f.pExact && t2f.printedP === '1.046e-11');
  check('Table 17 control (Bavaria, outside the four): 11 coefficients and 11 P-values as labelled', count(t(rep, 17), 'coefExact') === 11 && count(t(rep, 17), 'pExact') === 11);
  const repP = E.reproduce(model, { ...E.DEFAULTS, alignment: 'as-printed' });
  check('control: read as printed, Table 13 gives 0 of 11 and Table 17 still 11', count(t(repP, 13), 'coefExact') === 0 && count(t(repP, 17), 'coefExact') === 11);
  const repAll = E.reproduce(model, { ...E.DEFAULTS, rotateRegions: E.REGIONS });
  check('control: rotating Bavaria too breaks Table 17 to 0 of 11', count(t(repAll, 17), 'coefExact') === 0);
  // The printed value is compared, never fed: doctor it and the computed value does not move.
  const doctoredPrinted = structuredClone(printed);
  const dcell = doctoredPrinted.tables.find((x) => x.table === 13).cells[0];
  dcell.coef = '-0.038';
  const repD = E.reproduce(buildModel({ printed: doctoredPrinted }), E.DEFAULTS);
  const dres = repD.find((x) => x.key === 'T13.dress_accessories');
  check('control: a transposed printed digit (-0.083 to -0.038) turns that cell red', !dres.coefExact);
  check('control: and the computed coefficient does not move with the printed one', dres.coef === rep.find((x) => x.key === 'T13.dress_accessories').coef);
  // A wrong variance for S (1 per cent too large) must fail the printed P-values.
  const ctx = E.makeContext(model);
  const rc = E.readRCode(model.rText, ctx.choices);
  const na = E.subsetRows(model.graves, rc, 'nalamanniafurnished').rows;
  let wrongMatches = 0;
  for (const cell of t(rep, 13)) {
    const k = E.kendall(na.map((r) => E.valueOf(r, 'date', ctx)), na.map((r) => E.valueOf(r, cell.y === 'date' ? cell.x : cell.y, ctx)));
    if (E.pMatches(E.twoSidedNormal(k.S / Math.sqrt(k.varS * 1.01)), cell.printedP)) wrongMatches++;
  }
  check('control: a variance of S one per cent off reproduces at most 2 of Table 13\'s P-values', wrongMatches <= 2, `${wrongMatches} of 11`);
  // Independent implementation: scipy, run separately, stored in data/scipy-reference.json
  const ref = JSON.parse(readText(path.join(HERE, 'data', 'scipy-reference.json')));
  let worstC = 0; let worstP = 0;
  for (const r of rep) {
    const s = ref.cells[r.key];
    if (!s) { check(`scipy has ${r.key}`, false); continue; }
    worstC = Math.max(worstC, Math.abs(r.coef - s.coef));
    worstP = Math.max(worstP, s.p > 1e-15 ? Math.abs(r.p - s.p) / s.p : Math.abs(Math.log10(r.p) - Math.log10(s.p)));
  }
  check('all 157 cells agree with scipy kendalltau/spearmanr: coefficients within 1e-12', worstC < 1e-12, worstC.toExponential(2));
  check('all 157 cells agree with scipy: P-values within a relative 1e-8', worstP < 1e-8, worstP.toExponential(2));
  let we = 0; for (const [x, v] of ref.special.erfc) we = Math.max(we, Math.abs(E.erfc(x) - v) / v);
  let wt = 0; for (const [tv, df, v] of ref.special.t_two_sided) wt = Math.max(wt, Math.abs(E.twoSidedT(tv, df) - v) / v);
  check('erfc agrees with scipy.special.erfc to a relative 1e-10', we < 1e-10, we.toExponential(2));
  check('two-sided t agrees with scipy.stats.t to a relative 1e-10', wt < 1e-10, wt.toExponential(2));
  // Fast grouped tau-b against the plain pairwise count, on the anchor subsets.
  let worstPlain = 0;
  const kent = E.subsetRows(model.graves, rc, 'kent').rows;
  for (const rows of [na, kent]) {
    const xs = rows.map((r) => E.valueOf(r, 'date', ctx));
    for (const key of E.CATEGORY_KEYS) {
      const ys = rows.map((r) => E.valueOf(r, key, ctx));
      const a = E.kendall(xs, ys); const b = E.kendallPlain(xs, ys);
      worstPlain = Math.max(worstPlain, Math.abs(a.tau - b.tau), Math.abs(a.S - b.S), Math.abs(a.p - b.p) / b.p);
    }
    const ys = rows.map((r) => E.valueOf(r, 'none', ctx));
    const a = E.kendall(xs, ys); const b = E.kendallPlain(xs, ys);
    worstPlain = Math.max(worstPlain, Math.abs(a.tau - b.tau), Math.abs(a.p - b.p) / b.p);
  }
  const nd = E.subsetRows(model.graves, rc, 'nalamanniadated').rows;
  const s1 = E.spearman(nd.map((r) => r.n), nd.map((r) => r.date));
  const s2 = E.spearmanPlain(nd.map((r) => r.n), nd.map((r) => r.date));
  worstPlain = Math.max(worstPlain, Math.abs(s1.rho - s2.rho), Math.abs(s1.p - s2.p) / s2.p);
  check('grouped tau-b equals the plain pairwise count on Tables 13 and 21 (all categories and unfurnished) and Spearman on Table 2', worstPlain < 1e-12, String(worstPlain));
  // The plain loop must be able to disagree with the grouped count when the engine's own finish is
  // wrong. Two errors are planted in a copy of engine.js's kendallFinish(), loaded from memory (no file
  // is written), and the same fast-against-plain comparison the page's button runs must go red on each.
  const engineSrc = readText(path.join(PUB, 'engine.js'));
  const naX = na.map((r) => E.valueOf(r, 'date', ctx));
  const naY = na.map((r) => E.valueOf(r, 'dress_accessories', ctx));
  const fastVsPlain = (M) => { const a = M.kendall(naX, naY); const b = M.kendallPlain(naX, naY); return Math.max(Math.abs(a.tau - b.tau), Math.abs(a.p - b.p) / b.p); };
  check('control: the unmutated engine\'s fast and plain routes agree on Table 13 dress accessories', fastVsPlain(E) < 1e-12);
  const MUTANTS = [
    ['the variance of S using 2n+1', 'const v0 = n * (n - 1) * (2 * n + 5);', 'const v0 = n * (n - 1) * (2 * n + 1);'],
    ['a tau-b denominator that ignores ties in the date', 'const denom = Math.sqrt((n0 - tx.pairs) * (n0 - ty.pairs));', 'const denom = Math.sqrt(n0 * (n0 - ty.pairs));'],
  ];
  for (const [name, from, to] of MUTANTS) {
    const targets = engineSrc.split(from).length - 1;
    if (targets !== 1) { check(`control: the mutant "${name}" has exactly one target in engine.js`, false, `${targets} targets`); continue; }
    const M = await import('data:text/javascript;base64,' + Buffer.from(engineSrc.replace(from, to)).toString('base64'));
    const d = fastVsPlain(M);
    check(`control: with ${name} planted in the engine's finish, the fast-against-plain comparison goes red`, d > 1e-6, d.toExponential(2));
  }
  const pairsNa = (na.length * (na.length - 1)) / 2;
  check('control: the pairwise count really counted every pair', E.kendallPlain([1, 2, 3], [1, 3, 2]).S === 1 && pairsNa === 2997576);
  // Kernel used by the permutation test against the grave-level statistic and the general path.
  const jobs = E.censusJobs(model, E.DEFAULTS);
  check('one census job per printed cell', jobs.length === rep.length);
  let wk = 0; let wg = 0;
  const rng = E.mulberry32(99);
  for (const j of jobs) {
    const distinct = [...new Set(j.struct.units.map((u) => u.modal))].sort((a, b) => a - b);
    const g0 = j.struct.units.map((u) => distinct.indexOf(u.modal));
    const stat = E.makeStat(j.struct, j.method, distinct);
    const repCell = rep.find((x) => x.key === j.id);
    wk = Math.max(wk, Math.abs(stat(g0) - repCell.coef));
    for (let k = 0; k < 3; k++) {
      const g = g0.slice();
      for (let i = g.length - 1; i > 0; i--) { const r = Math.floor(rng() * (i + 1)); [g[i], g[r]] = [g[r], g[i]]; }
      wg = Math.max(wg, Math.abs(stat(g) - E.statForAssignment(j.struct, g.map((i) => distinct[i]), j.method)));
    }
  }
  check('the permutation kernel at the observed dates equals the reproduced coefficient for all 157 cells', wk < 1e-12, String(wk));
  check('the fast kernel equals the general path on random date assignments', wg < 1e-12, String(wg));
  // Exact enumeration against brute force over every raw permutation (Table 17, 8 cemeteries).
  const j17 = jobs.find((j) => j.id === 'T17.amulets');
  const exact17 = E.permutationTest(j17.struct, 'kendall', { B: 9999, seed: 1, id: j17.id });
  const units = j17.struct.units.map((u) => u.modal);
  const obs = E.statForAssignment(j17.struct, units, 'kendall');
  let hits = 0; let total = 0;
  const perm = (arr, k) => {
    if (k === arr.length) { total++; if (Math.abs(E.statForAssignment(j17.struct, arr, 'kendall')) >= Math.abs(obs) - 1e-12) hits++; return; }
    for (let i = k; i < arr.length; i++) { [arr[k], arr[i]] = [arr[i], arr[k]]; perm(arr, k + 1); [arr[k], arr[i]] = [arr[i], arr[k]]; }
  };
  perm(units.slice(), 0);
  check('exact enumeration (distinct arrangements) equals brute force over all 40,320 orderings for Table 17 amulets', exact17.exact && Math.abs(exact17.p - hits / total) < 1e-12 && total === 40320, `${exact17.p} vs ${hits}/${total}`);

  // ================================================================================ choices
  group('choices');
  const jobsForChoices = E.censusJobs(model, E.DEFAULTS);
  const strip = (c) => ({ id: c.id, label: c.label, options: c.options, default: c.default, affects: c.affects, inert: false });
  check('record.json declares exactly the engine\'s choices', record && JSON.stringify(record.choices) === JSON.stringify(E.CHOICES.map(strip)));
  const moves = (id, options, affects) => {
    const outs = options.map((o) => F.choiceOutputs(model, { [id]: o }));
    return affects.filter((k) => outs.some((o) => JSON.stringify(o[k]) !== JSON.stringify(outs[0][k])));
  };
  for (const c of E.CHOICES) {
    const moved = attempt(`choice ${c.id} runs`, () => moves(c.id, c.options, c.affects));
    if (moved) check(`choice ${c.id} moves at least one of ${c.affects.join(', ')}`, moved.length > 0, `moved: ${moved.join(', ') || 'nothing'}`);
  }
  const moot = moves('colour', ['red', 'blue'], ['coinShareFour', 'table13Exact', 't2UnfurnishedOverall']);
  check('control: a choice the engine does not read moves nothing, so the test above can fail', moot.length === 0);
  const sel = (id) => { const m = html.match(new RegExp(`<select id="${id}">([\\s\\S]*?)</select>`)); return m ? [...m[1].matchAll(/<option value="([^"]+)"( selected)?>/g)].map((o) => ({ value: o[1], selected: Boolean(o[2]) })) : []; };
  for (const [id, cid] of [['chAlignment', 'alignment'], ['chExclusions', 'exclusions'], ['chUnfurnished', 'unfurnished'], ['chDates', 'dates'], ['exShuffles', 'permutations'], ['censusShuffles', 'permutations'], ['exMeasure', 'measure'], ['exUnit', 'unit'], ['censusUnit', 'unit']]) {
    const c = E.CHOICES.find((x) => x.id === cid);
    const opts = sel(id);
    check(`the page control ${id} offers exactly the options of ${cid}`, JSON.stringify(opts.map((o) => String(o.value))) === JSON.stringify(c.options.map(String)));
    check(`the page control ${id} starts on the default`, opts.filter((o) => o.selected).map((o) => o.value).join() === String(c.default));
  }

  const kentButtons = [...html.matchAll(/<button type="button" id="kent(\w+)"/g)].map((m) => m[1].toLowerCase());
  check('the Kent panel offers exactly the options of rank-by', JSON.stringify(kentButtons) === JSON.stringify(E.CHOICES.find((c) => c.id === 'rank-by').options));
  // The explorer's measure choice goes through the engine's trendJob(). As printed it is the census job
  // itself; a furnishing measure lands on the printed cell for the same cemeteries when there is one.
  let tjPrinted = 0; let tjOwn = 0; let tjMismatch = 0;
  for (const j of jobsForChoices) {
    for (const mv of E.CHOICES.find((c) => c.id === 'measure').options) {
      const tj = E.trendJob(model, j.id, { measure: mv });
      if (!tj.printed) { tjOwn++; continue; }
      tjPrinted++;
      const cj = jobsForChoices.find((x) => x.id === tj.printed.key);
      if (!cj || cj.id !== tj.id || cj.method !== tj.method || JSON.stringify(cj.struct) !== JSON.stringify(tj.struct)) tjMismatch++;
    }
  }
  check('explorer measure: every trend that names a printed cell has that census job\'s cemeteries, variable and statistic', tjMismatch === 0 && tjPrinted > jobsForChoices.length && tjOwn > 0, `${tjPrinted} printed, ${tjOwn} the page's own, ${tjMismatch} mismatched`);
  const trendCoef = (tj) => { const x = E.expandStruct(tj.struct); return tj.method === 'kendall' ? E.kendall(x.xs, x.ys).tau : E.spearman(x.xs, x.ys).rho; };
  const tjObj = E.trendJob(model, 'T13.dress_accessories', { measure: 'objects' });
  const tjUnf = E.trendJob(model, 'T13.dress_accessories', { measure: 'unfurnished' });
  const tjCat = E.trendJob(model, 'T13.dress_accessories', { measure: 'categories' });
  check('explorer measure: objects on Table 13\'s cemeteries is Table 2\'s furnished-period objects cell, value for value', tjObj.printed && tjObj.printed.key === 'T2.objects.furnished' && trendCoef(tjObj) === rep.find((x) => x.key === 'T2.objects.furnished').coef);
  check('explorer measure: unfurnished on Table 13\'s cemeteries prints as Table 2\'s 0.122', tjUnf.printed && tjUnf.printed.key === 'T2.unfurnished.furnished' && E.coefficientMatches(trendCoef(tjUnf), '0.122'));
  check('explorer measure: categories present is never printed, and it is really read (not the object count)', tjCat.printed === null && tjCat.yName === 'categories_present' && Math.abs(trendCoef(tjCat) - trendCoef(tjObj)) > 1e-3);
  let refusedMeasure = false;
  try { E.trendJob(model, 'T13.dress_accessories', { measure: 'weight' }); } catch { refusedMeasure = true; }
  check('control: an unknown measure is refused, not read as the printed one', refusedMeasure);

  // ================================================================================ faults
  group('faults');
  const faults = F.plantedFaults(model);
  for (const f of faults) check(`planted fault caught: ${f.id}`, f.caught, JSON.stringify(f));
  check('the Esslingen fault really doctored rows', faults.find((f) => f.id === 'esslingen-swap').rowsDoctored > 0);
  const again = E.reproduce(model, E.DEFAULTS).find((x) => x.key === 'T2.unfurnished.overall');
  check('the faults doctored copies: the clean record still gives 0.193 afterwards', again.coefExact && again.coef === t2o.coef);
  // Control on the control: a "fault" that changes nothing must not be caught by the same test.
  const idRows = model.graves.rows.map((r) => (r.cemetery === 'Esslingen' ? { ...r, flags: r.flags.slice() } : r));
  const idModel = { ...model, graves: { ...model.graves, rows: idRows } };
  const idCell = E.reproduce(idModel, E.DEFAULTS).find((x) => x.key === 'T2.unfurnished.overall');
  check('control: an identity edit of the same rows leaves Table 2 exact (the fault test is not always red)', idCell.coefExact);
  const esslingen = model.graves.rows.filter((r) => r.cemetery === 'Esslingen');
  check('control: the swapped columns differ in at least one Esslingen grave', esslingen.some((r) => r.flags[10] !== r.flags[11]));

  // ================================================================================ refusal
  group('refusal');
  const ids = [...html.matchAll(/data-ask="([^"]+)"/g)].map((m) => m[1]);
  check('the page offers refusal buttons for grave dates, wealth, beads, the map and a verdict', ['grave-date', 'wealth', 'beads', 'map', 'verdict'].every((q) => ids.includes(q)));
  for (const q of ids) {
    const a = E.ask(model, q);
    check(`refused: ${q}`, a.refused && a.reason.length > 40, a.reason);
    if (a.quote) check(`the refusal ${q} quotes a real sentence (${a.quote})`, quotes.some((x) => x.id === a.quote));
  }
  check('the grave-date refusal names cemetery end dates', /one date per cemetery/.test(E.ask(model, 'grave-date').reason));
  check('the verdict refusal says the anchor shows aligned data', /aligned data/.test(E.ask(model, 'verdict').reason));
  const rhenen = E.ask(model, 'cemetery', 'Rhenen');
  const ailcy = E.ask(model, 'cemetery', 'Ailcy Hill');
  const none = E.ask(model, 'cemetery', 'Atlantis');
  const schretz = E.ask(model, 'cemetery', 'Schretzheim');
  check('refused: a site in the site table with no graves in the file (Rhenen)', rhenen.refused && /no graves/.test(rhenen.reason));
  check('refused: a site marked Not analysed further (Ailcy Hill)', ailcy.refused && /Not analysed further/.test(ailcy.reason));
  check('refused: a cemetery in neither file', none.refused);
  check('control: a cemetery in the file is answered, not refused (Schretzheim, 623 graves)', !schretz.refused && schretz.graves === 623);
  const badHeader = Buffer.from(bytes['all_graves.csv']);
  const at = badHeader.indexOf(Buffer.from(',none,'));
  badHeader[at + 3] = 'm'.charCodeAt(0);
  let threw = false;
  try { E.readGraves(new Uint8Array(badHeader)); } catch { threw = true; }
  check('refused: a grave file with a different header is not read at all', threw);

  // ================================================================================ census (worker)
  log('\n== census (worker thread, one run at a time)');
  const worker = new Worker(new URL('./census-thread.mjs', import.meta.url));
  let census;
  const seedRuns = [];
  let census999;
  try {
    census = await censusRun(worker, jobs, 9999, 1, 1);
    seedRuns.push(census);
    for (let seed = 2; seed <= 10; seed++) seedRuns.push(await censusRun(worker, jobs, 9999, seed, seed));
    census999 = await censusRun(worker, jobs, 999, 1, 100);
  } finally {
    await worker.terminate();
  }
  const holds = seedRuns.map((r) => E.censusSummary(r, { from: 13, to: 21 }).holdPermutation);
  const sigIds = census.filter((r) => F.printedSig(r.printedP)).map((r) => r.id);
  const flips = sigIds.filter((id) => { const v = seedRuns.map((run) => run.find((x) => x.id === id).pPerm < E.ALPHA); return v.some(Boolean) && !v.every(Boolean); });
  const offline = {
    censusRange1321: `${Math.min(...holds)} to ${Math.max(...holds)}`,
    censusFlips: String(flips.length),
    routeDisagreements: String(routes.disagreements.length),
  };
  log(`  ten seeds at 9,999 shuffles, Tables 13 to 21 holding: ${holds.join(', ')}; flipping: ${flips.join(', ')}`);
  log(`  seed 1 at 999 shuffles: ${E.censusSummary(census999, { from: 13, to: 21 }).holdPermutation} hold in Tables 13 to 21`);

  // ================================================================================ surface
  group('surface');
  const all = F.computeFigures(model, { census, kent: true });
  const values = all.values;
  const failures = surfaceFailures(html, values, offline);
  check('every [data-fig], [data-printed], [data-quote], [data-cite] and [data-offline] in index.html is recomputed or matched, and no bare digit remains', failures.length === 0, failures.join(' | '));
  const onPage = new Set(attributed(bodyOf(html)).filter((el) => el.attr === 'data-fig').map((el) => el.value));
  const named = ['fourCatCoefAligned', 'holdGrave1321', 'holdCem1321', 'coinShareFourPrinted', 'coinShareFourAligned', 't13CoefAligned', 't13PAligned', 't2OverallAligned', 't2FurnishedP', 't17CoefAligned', 'hold1321', 'printedSig1321', 'naDressPerm', 'naDressMcse'];
  const missing = named.filter((id) => !onPage.has(id));
  check('the headline, anchor and census figures all appear on the page as asserted figures', missing.length === 0, missing.join(', '));
  const heads = headFailures(html, values, FM, record ? record.headline : null);
  check('head tags, JSON-LD, dek and headline agree with the frontmatter and the engine', heads.length === 0, heads.join(' | '));
  for (const q of quotes) {
    const src = q.source === 'full-text' ? 'full-text.html' : q.source === 'data-page' ? 'data.html' : 'terms.html';
    const text = decode(readText(path.join(RAW, src)).replace(/<script[\s\S]*?<\/script>/gi, ' ').replace(/<\/?(a|em|i|b|strong|sub|sup|span|q|cite|abbr)(\s[^>]*)?>/gi, '').replace(/<[^>]+>/g, ' ')).replace(/\s+/g, ' ');
    check(`quotation ${q.id} is verbatim in the frozen ${src}`, text.includes(q.text));
  }
  check('the plain placard has no em dash, no double quote and at most three sentences', !/\u2014|"/.test(FM.plain) && (FM.plain.match(/[.!?](\s|$)/g) || []).length <= 3 && FM.plain.length >= 90 && FM.plain.length <= 420, `${FM.plain.length} chars`);
  const known = new Set(Object.values(values));
  const plainNums = [...FM.plain.matchAll(/\d[\d,.]*\d|\d/g)].map((m) => m[0]);
  check('every number in the plain placard is a recomputed figure', plainNums.every((n) => known.has(n)), plainNums.join(', '));
  check('the dek says 13 to 15 exactly as the verifier\'s ten seeds give', FM.dek.includes(`${offline.censusRange1321} of the ${values.printedSig1321} category trends`));
  for (const rel of FM.relates) {
    const other = path.join(REPO, 'src', 'content', 'strata', `${rel.to}.md`);
    const exists = fs.existsSync(other);
    check(`relates to ${rel.to}: the page exists`, exists);
    if (!exists) continue;
    const otherText = readText(other);
    const nums = [...rel.note.replace(/\b17C\b/g, '').matchAll(/\d[\d,.]*\d|\d/g)].map((m) => m[0]);
    check(`relates to ${rel.to}: each number in the note is a figure here or appears on that page`, nums.every((n) => known.has(n) || otherText.includes(n)), nums.join(', '));
  }
  check('record.json headline is the sentence the page prints', record && record.headline === textOf(html.match(/<p class="headline" id="headline">([\s\S]*?)<\/p>/)[1]));
  check('record.json anchor is built from the engine and agrees', record && record.anchor && record.anchor.agrees === true && record.anchor.computed.includes(`${values.t13CoefAligned} of 11`));
  check('record.json units is the number of graves', record && record.record.units === model.graves.rows.length);
  // Bounded claims, no named cause, and prose that does not pretend to follow the controls.
  const refusalText = ids.map((q) => E.ask(model, q).reason).join(' ');
  const surfaces = surfacesOf(html, FM, record, md, refusalText);
  const claims = claimFailures(surfaces, rep);
  check('no surface claims more exactness than the engine reproduces (every digit; the printed tables come back)', claims.length === 0, claims.join(' | '));
  check('control: "Table 13 to every digit" goes red on this record', claimFailures([['doctored dek', 'only then do her printed tables return, Table 13 to every digit']], rep).length === 2);
  const printedN = structuredClone(printed);
  printedN.tables.find((x) => x.table === 13).n_as_written = t(rep, 13)[0].n;
  const repN = E.reproduce(buildModel({ printed: printedN }), E.DEFAULTS);
  check('control: had Table 13\'s printed N come back, the same "every digit" claim would be allowed (the check reads the record, not a word list)', claimFailures([['doctored dek', 'Table 13 to every digit']], repN).length === 0);
  const causes = causeFailures(surfaces);
  check('no surface names a cause for the shift, which the record does not establish', causes.length === 0, causes.join(' | '));
  check('control: the old objection ("a slip in a spreadsheet export") goes red', causeFailures([['old objection', 'It is a slip in a spreadsheet export.']]).length === 1);
  const movingIds = new Set();
  for (const alt of [F.censusFigures(model, seedRuns[1]), F.censusFigures(model, census999)]) for (const [k, v] of Object.entries(alt)) if (values[k] !== v) movingIds.add(k);
  const ctxAllRotated = E.makeContext(model, { ...E.DEFAULTS, rotateRegions: E.REGIONS });
  const sevenRowsAll = model.graves.rows.filter((r) => !E.FOUR_REGIONS.includes(r.region));
  if (F.pct1(E.share(sevenRowsAll, 'coins', ctxAllRotated)) !== values.coinShareSeven) movingIds.add('coinShareSeven');
  check('the figures that move with a control are found from the record (another seed, another shuffle count, every region rotated)', movingIds.has('hold1321') && movingIds.has('naDressPerm') && movingIds.has('coinShareSeven'), [...movingIds].join(', '));
  const stale = staleProseFailures(html, movingIds);
  check('every figure that moves with a control is labelled as the default run or swapped out live', stale.length === 0, stale.join(' | '));
  check('control: without its default-run label the section III prose goes red', staleProseFailures(html.replace(' data-default-run="census"', ''), movingIds).length > 0);
  check('control: without its default-state wrapper the seven-region note goes red', staleProseFailures(html.replace(' data-default-state="switch"', ''), movingIds).length === 1);
  const heldAt = (unit) => E.censusSummary(census, { from: 13, to: 21, unit }).holdUnit;
  check('the census unit choice: by the shuffle it gives the page\'s hold count, at the grave the grave count, per cemetery the cemetery count, and the three differ', String(heldAt('cemetery-permutation')) === values.hold1321 && String(heldAt('grave')) === values.holdGrave1321 && String(heldAt('cemetery-level')) === values.holdCem1321 && new Set([heldAt('grave'), heldAt('cemetery-permutation'), heldAt('cemetery-level')]).size === 3, `${heldAt('grave')} / ${heldAt('cemetery-permutation')} / ${heldAt('cemetery-level')}`);

  // Negative controls: the same functions on doctored copies must go red.
  const doctor = (from, to) => { if (!html.includes(from)) throw new Error(`control target missing: ${from}`); return html.replace(from, to); };
  const controls = [
    ['a census figure changed (hold1321 14 to 15)', () => surfaceFailures(doctor('<span data-fig="hold1321">14</span>', '<span data-fig="hold1321">15</span>'), values, offline)],
    ['a bare number added to the prose', () => surfaceFailures(doctor('<h3>A warning about ranks</h3>', '<h3>A warning about ranks</h3><p>Another 42 graves.</p>'), values, offline)],
    ['a printed value corrupted (0.01288 to 0.01228)', () => surfaceFailures(doctor('<span data-printed="T21.vessels:p">0.01288</span>', '<span data-printed="T21.vessels:p">0.01228</span>'), values, offline)],
    ['a quotation edited (rapid to slow)', () => surfaceFailures(doctor('reliant on a rapid turnover', 'reliant on a slow turnover'), values, offline)],
    ['a citation year changed (2021 to 2012)', () => surfaceFailures(doctor('In <span data-cite="2021">2021</span>', 'In <span data-cite="2012">2012</span>'), values, offline)],
    ['the offline range changed (13 to 15 into 12 to 15)', () => surfaceFailures(html.split('<span data-offline="censusRange1321">13 to 15</span>').join('<span data-offline="censusRange1321">12 to 15</span>'), values, offline)],
    ['a shuffle option changed (9999 to 5000)', () => surfaceFailures(doctor('<option value="9999" selected>9,999</option>', '<option value="5000" selected>5,000</option>'), values, offline)],
    ['an unknown figure id', () => surfaceFailures(doctor('<span data-fig="t13K">15</span>', '<span data-fig="t13Kx">15</span>'), values, offline)],
    ['the meta description corrupted (31.6 to 36.1)', () => headFailures(doctor('the file puts a coin in 31.6 per cent', 'the file puts a coin in 36.1 per cent'), values, FM, record ? record.headline : null)],
    ['the og:description corrupted (31.6 to 31.9)', () => headFailures(doctor('coin share from 31.6 per cent to 2.4 per cent', 'coin share from 31.9 per cent to 2.4 per cent'), values, FM, record ? record.headline : null)],
    ['the og:description reworded away from the headline', () => headFailures(doctor('at printed precision while reducing', 'to every digit while reducing'), values, FM, record ? record.headline : null)],
    ['a figure the reader sees in the dek corrupted (61 to 16)', () => surfaceFailures(doctor('<span data-fig="printedSig1321">61</span> category', '<span data-fig="printedSig1321">16</span> category'), values, offline)],
  ];
  for (const [name, run] of controls) {
    const f = attempt(`control runs: ${name}`, run);
    if (f) check(`control goes red: ${name}`, f.length > 0, f.slice(0, 2).join(' | '));
  }

  // ================================================================================ figures the report quotes
  current = 'meta';
  log('\n== report figures (not ledger)');
  log(`  census seed 1, 9,999: Tables 13 to 21 ${values.hold1321} of ${values.printedSig1321}; Tables 2 to 23 ${values.holdAll} of ${values.printedSigAll}; only when shuffled ${values.onlyPerm1321}`);
  log(`  worked cases: NA dress ${values.naDressPerm} +- ${values.naDressMcse}; Kent vessels ${values.kentVesselsPerm}; Kent amulets ${values.kentAmuletsPerm}; Anglian dress ${values.anglianDressPerm} +- ${values.anglianDressMcse}`);
  for (const p of ref.permutation) {
    const r = census.find((x) => x.id === p.key);
    const se = Math.sqrt(p.mcse ** 2 + r.mcse ** 2);
    check(`scipy permutation for ${p.key} (${p.p.toFixed(4)}) and the engine (${r.pPerm.toFixed(4)}) agree within 4 standard errors`, Math.abs(p.p - r.pPerm) <= 4 * Math.max(se, 1e-4));
  }
  const ledger = Object.fromEntries(Object.entries(GROUPS).map(([g, key]) => [key, outcomes[g].length > 0 && outcomes[g].every((o) => o.pass)]));
  if (record && record.ledger) {
    for (const [key, v] of Object.entries(ledger)) check(`record.json ledger ${key} matches what this verifier computed`, record.ledger[key] && record.ledger[key].value === v);
  }

  const failed = [...Object.values(outcomes).flat(), ...meta].filter((o) => !o.pass);
  const totalChecks = Object.values(outcomes).flat().length + meta.length;
  log(`\n${totalChecks} assertions, ${failed.length} failed, ${Math.round((Date.now() - t0) / 1000)} s`);
  if (LEDGER) for (const [key, v] of Object.entries(ledger)) console.log(`${key}=${v}`);
  process.exitCode = failed.length ? 1 : 0;
}

main().catch((err) => { console.error(err); process.exitCode = 1; });
