#!/usr/bin/env node
// verify-all-the-better-to-count-you-with.mjs
//
// Recomputes every number the page shows and fails on any disagreement.
//   node research/all-the-better-to-count-you-with/verify-all-the-better-to-count-you-with.mjs            default
//   ... --full     re-run every tree search in results.json (about 20 CPU-minutes; default re-runs a declared sample)
//   ... --ledger   print only the six ledger cells, each computed from its own assertions
//   ... --quick    skip re-running searches (working mode; cannot pass)
//
// Every assertion belongs to a group; a ledger cell is true only if its group ran and every assertion
// in it passed. Groups: provenance, anchor, surface, choices, fault, refusal, search, results, hygiene.
import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import { fileURLToPath } from 'node:url';

const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.join(HERE, '..', '..');
const SLUG = 'all-the-better-to-count-you-with';
const PUB = path.join(ROOT, 'public', 'strata', SLUG);
const MD = path.join(ROOT, 'src', 'content', 'strata', SLUG + '.md');
const LEDGER = process.argv.includes('--ledger');
const FULL = process.argv.includes('--full');
// --quick skips re-running the tree searches (for working on the page); the results group then does not
// run, so rendered_figures_asserted is printed false and the exit code is non-zero.
const QUICK = process.argv.includes('--quick');

const E = await import(path.join(PUB, 'engine.js'));
const FIG = await import(path.join(PUB, 'figures.js'));
const bytes = (p) => fs.readFileSync(p);
const sha = (b) => crypto.createHash('sha256').update(b).digest('hex');
const readJson = (name) => JSON.parse(fs.readFileSync(path.join(PUB, name), 'utf8'));
const ex = readJson('tehrani2013.json');
const pr = readJson('printed.json');
const res = readJson('results.json');
const rec = readJson('record.json');
const html = fs.readFileSync(path.join(PUB, 'index.html'), 'utf8');
const pageJs = fs.readFileSync(path.join(PUB, 'page.js'), 'utf8');
const md = fs.readFileSync(MD, 'utf8');

const outcomes = {};
let failures = 0;
function check(group, name, ok, detail = '') {
  (outcomes[group] ||= []).push({ name, ok: !!ok });
  if (!ok) failures++;
  if (!LEDGER) console.log(`${ok ? 'ok  ' : 'FAIL'} [${group}] ${name}${!ok && detail ? '  :: ' + detail : ''}`);
}
const deepEqual = (a, b) => JSON.stringify(a) === JSON.stringify(b);

// ============================================================ provenance
{
  const G = 'provenance';
  const pubBytes = Object.fromEntries(['tehrani2013.json', 'printed.json', 'results.json'].map((n) => [n, bytes(path.join(PUB, n))]));
  check(G, 'record.sha256 is the SHA-256 of tehrani2013.json', sha(pubBytes['tehrani2013.json']) === rec.record.sha256);
  for (const [n, b] of Object.entries(pubBytes)) {
    check(G, `record.files["${n}"] matches its bytes`, rec.files[n] === sha(b), rec.files[n] + ' vs ' + sha(b));
    check(G, `research copy of ${n} is byte-identical`, sha(bytes(path.join(HERE, 'data', n))) === sha(b));
  }
  const readme = fs.readFileSync(path.join(HERE, 'README.md'), 'utf8');
  const rawFiles = ['pone.0078871.s004.docx', 'pone.0078871.s005.docx', 'pone.0078871.s006.docx', 'article.html', 'table1-large.png', 'fig2-large.png'];
  for (const n of ['tehrani2013.json', 'printed.json', 'results.json']) check(G, `README pins ${n}`, readme.includes(sha(pubBytes[n])));
  for (const n of rawFiles) {
    const h = sha(bytes(path.join(HERE, 'data', 'raw', n)));
    check(G, `README pins raw/${n}`, readme.includes(h));
  }
  for (const s of Object.values(ex.sources)) check(G, `extract records the hash of ${s.file}`, sha(bytes(path.join(HERE, 'data', 'raw', s.file))) === s.sha256);
  check(G, 'Table 1 transcription names the hash of the image it was read from', sha(bytes(path.join(HERE, 'data', 'raw', 'table1-large.png'))) === pr.table1.png_sha256);
  // re-extract from the raw DOCX and article, and require byte-identical extracts
  const X = await import(path.join(HERE, 'extract.mjs'));
  check(G, 'tehrani2013.json re-extracts byte for byte from the DOCX files', JSON.stringify(X.tehrani, null, 1) + '\n' === pubBytes['tehrani2013.json'].toString('utf8'));
  check(G, 'printed.json re-extracts byte for byte (every quotation found verbatim in article.html)', JSON.stringify(X.printed, null, 1) + '\n' === pubBytes['printed.json'].toString('utf8'));
  // control: a one-character change in a copy must change the hash
  const doctored = Buffer.from(pubBytes['tehrani2013.json']);
  doctored[doctored.indexOf('1-111020011010211012110120')] = 0x30;
  check(G, 'control: a doctored copy of the extract fails the pinned hash', sha(doctored) !== rec.record.sha256);
  check(G, 'record.units is the number of coded cells', rec.record.units === ex.matrix.rows.length * 72 && rec.record.units === 4176);
}

// ============================================================ anchor
{
  const G = 'anchor';
  const rows = FIG.anchorTable(ex, pr, E.DEFAULTS);
  const agreeIds = rows.filter((r) => r.agrees).map((r) => r.id);
  check(G, 'engine reproduces six printed network figures at printed precision', deepEqual(agreeIds, ['network-delta', 'network-q', 's3-delta', 's3-q', 'ea-delta', 'ea-q']), agreeIds.join(','));
  check(G, 'the two "other taxa" figures stay disagreements', rows.filter((r) => !r.agrees).map((r) => r.id).join(',') === 'rest-delta,rest-q');
  // independent implementation, written here, of p-distance, delta and Q-residual
  const coded = ex.matrix.rows.map((r) => r.states_as_written);
  const names = coded.map((_, i) => i);
  const eaNames = new Set(pr.groups.find((g) => g.id === 'eastAsian').members);
  const idx43 = names.filter((i) => !eaNames.has(ex.matrix.rows[i].name));
  function indep(taxa) {
    const n = taxa.length;
    const d = [];
    for (let i = 0; i < n; i++) { d.push([]); for (let j = 0; j < n; j++) {
      let diff = 0, tot = 0;
      for (let c = 0; c < 72; c++) { const a = coded[taxa[i]][c], b = coded[taxa[j]][c]; if ('?-'.includes(a) || '?-'.includes(b)) continue; tot++; if (a !== b) diff++; }
      d[i].push(tot ? diff / tot : 0);
    } }
    let meanD = 0, pairs = 0;
    for (let i = 0; i < n; i++) for (let j = i + 1; j < n; j++) { meanD += d[i][j]; pairs++; }
    meanD /= pairs;
    let sd = 0, sq = 0, k = 0;
    for (let a = 0; a < n; a++) for (let b = a + 1; b < n; b++) for (let c = b + 1; c < n; c++) for (let e = c + 1; e < n; e++) {
      const s = [d[a][b] + d[c][e], d[a][c] + d[b][e], d[a][e] + d[b][c]].sort((x, y) => y - x);
      sd += s[0] === s[2] ? 0 : (s[0] - s[1]) / (s[0] - s[2]);
      sq += ((s[0] - s[1]) / meanD) ** 2;
      k++;
    }
    return { delta: sd / k, q: sq / k, quartets: k };
  }
  const i43 = indep(idx43);
  const net = E.networkBlock(ex, pr);
  check(G, 'independent re-implementation agrees with the engine: delta, 43 tales', Math.abs(i43.delta - net.without.meanDelta) < 1e-12);
  check(G, 'independent re-implementation agrees with the engine: Q-residual, 43 tales', Math.abs(i43.q - net.without.meanQ) < 1e-12);
  check(G, 'independent quartet count, 43 tales', i43.quartets === net.without.quartets && i43.quartets === 123410);
  check(G, 'independent re-implementation, delta for 58 tales', Math.abs(indep(names).delta - net.full.meanDelta) < 1e-12);
  const computed = `${net.without.meanDelta.toFixed(5)} and ${net.without.meanQ.toFixed(6)}`;
  check(G, 'record.json anchor.computed is what the engine produces', rec.anchor.computed === computed, rec.anchor.computed + ' vs ' + computed);
  check(G, 'record.json anchor.expected quotes the printed pair', rec.anchor.expected.includes('0.28') && rec.anchor.expected.includes('0.024') && pr.quotations.find((q) => q.id === 'caption-s3-delta').quote.includes(rec.anchor.expected.replace(/^"|"$/g, '').split('"')[0].slice(0, 20)));
  check(G, 'record.json anchor.agrees is the engine verdict', rec.anchor.agrees === (E.printsAs(net.without.meanDelta, '0.28') && E.printsAs(net.without.meanQ, '0.024')));
  // negatives: the anchor must go red when the record or the rule is wrong
  const gapAsZero = structuredClone(ex);
  for (const r of gapAsZero.matrix.rows) r.states_as_written = r.states_as_written.replace(/-/g, '0');
  const bad1 = FIG.anchorTable(gapAsZero, pr, E.DEFAULTS);
  check(G, 'negative: a parser that reads gaps as state 0 fails the Figure S3 anchor', !(bad1.find((r) => r.id === 's3-delta').agrees && bad1.find((r) => r.id === 's3-q').agrees));
  const bad2 = FIG.anchorTable(ex, pr, { ...E.DEFAULTS, distance: 'mismatch' });
  check(G, 'negative: counting a gap as a difference reproduces fewer than six', bad2.filter((r) => r.agrees).length < 6);
  const swapped = structuredClone(ex);
  const wk3 = swapped.matrix.rows.find((r) => r.name === 'WK3');
  const s = wk3.states_as_written; // swap trait 1 and trait 7
  wk3.states_as_written = s[6] + s.slice(1, 6) + s[0] + s.slice(7);
  const n2 = E.networkBlock(swapped, pr);
  check(G, 'negative: swapping two cells in one row moves the anchor off record.json', `${n2.without.meanDelta.toFixed(5)} and ${n2.without.meanQ.toFixed(6)}` !== rec.anchor.computed);
}

// ============================================================ search (the parsimony engine, checked independently)
const F = FIG.figures(ex, pr, res);
{
  const G = 'search';
  const rows = ex.matrix.rows.map((r) => Array.from(r.states_as_written));
  const nameIdx = new Map(ex.matrix.rows.map((r, i) => [r.name, i]));
  // parse Newick into adjacency lists, independently of engine.fromNewick
  function parse(nw) {
    let p = 0; const adj = new Map(); let next = 1000;
    const link = (a, b) => { (adj.get(a) || adj.set(a, []).get(a)).push(b); (adj.get(b) || adj.set(b, []).get(b)).push(a); };
    const node = () => {
      if (nw[p] === '(') { p++; const v = next++; for (;;) { link(v, node()); if (nw[p] === ',') { p++; continue; } p++; break; } return v; }
      let q = p; while (!',();'.includes(nw[p])) p++; return nameIdx.get(nw.slice(q, p));
    };
    node();
    return adj;
  }
  // naive Sankoff length on an arbitrary tree; missing (? and -) compatible with every state
  function length(adj, bug = false) {
    let total = 0;
    for (let c = 0; c < 72; c++) {
      const states = [...new Set(rows.map((r) => r[c]).filter((x) => !'?-'.includes(x)))];
      const rec2 = (v, from) => {
        if (v < 1000) { const x = rows[v][c]; return states.map((s) => (('?-'.includes(x) && !bug) ? 0 : (x === s || (bug && '?-'.includes(x) && s === '0') ? 0 : Infinity))); }
        const cost = states.map(() => 0);
        for (const w of adj.get(v)) { if (w === from) continue; const cc = rec2(w, v); const mn = Math.min(...cc); cc.forEach((x, i) => { cost[i] += Math.min(x, mn + 1); }); }
        return cost;
      };
      const root = [...adj.keys()].find((k) => k >= 1000);
      total += Math.min(...rec2(root, -1));
    }
    return total;
  }
  const trees = res.baseline.newick.map(parse);
  const lens = trees.map((t) => length(t));
  check(G, `independent Sankoff length of all ${trees.length} shipped baseline trees equals the reported shortest length`, lens.every((l) => l === res.baseline.bestLen), lens.join(','));
  check(G, 'the shipped trees are distinct', new Set(res.baseline.newick).size === res.baseline.newick.length);
  check(G, 'negative: a length routine that reads missing cells as state 0 gets a different length', length(trees[0], true) !== res.baseline.bestLen);
  // m and g, independently
  let m = 0, g = 0;
  for (let c = 0; c < 72; c++) {
    const cnt = {}; for (const r of rows) if (!'?-'.includes(r[c])) cnt[r[c]] = (cnt[r[c]] || 0) + 1;
    const v = Object.values(cnt); m += v.length - 1; g += v.reduce((a, b) => a + b, 0) - Math.max(...v);
  }
  check(G, 'minimum and maximum steps recomputed independently', m === res.baseline.m && g === res.baseline.g && m === 138 && g === 838);
  check(G, 'retention index is (g - length) / (g - m)', Math.abs((g - res.baseline.bestLen) / (g - m) - res.baseline.RI) < 1e-12);
  check(G, 'RI 0.7257 prints as 0.72 only by truncation, never by rounding', !E.printsAs(res.baseline.RI, '0.72') && E.truncatesTo(res.baseline.RI, '0.72'));
  const best43 = Math.min(...res.seeds.noEastAsian.map((s) => s.bestLen));
  const ri43 = res.seeds.noEastAsian.find((s) => s.bestLen === best43).RI;
  check(G, 'RI with the East Asian tales removed reaches 0.76 by neither rounding nor truncation', !E.printsAs(ri43, '0.76') && !E.truncatesTo(ri43, '0.76'));
  // most parsimonious state at an ancestor, checked by a pendant leaf: s is possible at X iff a leaf in state s hung at X adds 0 steps
  const S = new E.Searcher(E.parsimonyData(ex));
  const Gs = E.groupSets(ex, pr, 'tree');
  let pendantAgree = 0, pendantTotal = 0;
  for (const nw of res.baseline.newick.slice(0, 3)) {
    const T = E.fromNewick(S, nw);
    const r = E.rootOnGroup(S, T, Gs.eastAsian);
    const sets = E.mprSets(S, T, r.ingroupNode);
    // rebuild the same tree as adjacency with engine node ids, then add a pendant leaf at the ingroup node
    const adj = new Map();
    for (let v = 0; v < 2 * 58 - 2; v++) for (let k = 0; k < 3; k++) { const w = T[v * 3 + k]; if (w >= 0) (adj.get(v < 58 ? v : v + 1000) || adj.set(v < 58 ? v : v + 1000, []).get(v < 58 ? v : v + 1000)).push(w < 58 ? w : w + 1000); }
    for (const [c, s] of [[3, 1], [62, 1], [25, 0], [4, 0]]) {
      const extra = 57 + 1; // a 59th row index
      rows[extra] = rows[0].map(() => '?'); rows[extra][c - 1] = String(s);
      const X = r.ingroupNode + 1000;
      adj.get(X).push(extra); adj.set(extra, [X]);
      const with1 = length(adj);
      adj.get(X).pop(); adj.delete(extra); rows.length = 58;
      const possible = with1 === res.baseline.bestLen;
      pendantTotal++;
      if (possible === sets[c - 1].states.includes(s)) pendantAgree++;
    }
  }
  check(G, 'ancestral state sets agree with an independent pendant-leaf test', pendantAgree === pendantTotal, pendantAgree + ' of ' + pendantTotal);
  check(G, 'ATU 123 is in every tree found, as the Results say of PAUP\'s trees', res.baseline.presence.atu123 === res.baseline.treeCount);
  check(G, 'deleting the uninformative trait 2 shortens every tree by its own steps and changes no gap', F.c2drop === '3' && E.GROUP_IDS.every((id) => res.deletions.c2.gaps[id].gap === res.baseline.gaps[id].gap));
  const allChars = Array.from({ length: 72 }, (_, i) => i + 1);
  const emptyNetwork = E.networkBlock(ex, pr, E.DEFAULTS, allChars);
  check(G, 'empty character set marks network statistics undefined instead of zero', emptyNetwork.full.valid === false && emptyNetwork.without.valid === false && emptyNetwork.full.meanDelta === null && emptyNetwork.full.meanQ === null && emptyNetwork.without.meanDelta === null && emptyNetwork.without.meanQ === null);
  const emptyData = E.parsimonyData(ex, { dropChars: allChars });
  let emptySearchRefused = false;
  try { E.treesJob(ex, pr, { dropChars: allChars, groups: [] }); } catch (e) { emptySearchRefused = /No informative characters remain/.test(e.message); }
  check(G, 'empty parsimony search is refused because it has no informative characters', emptyData.C === 0 && emptyData.informative.length === 0 && emptySearchRefused);
}

// ============================================================ results: re-run the searches
if (QUICK) { failures++; if (!LEDGER) console.log('SKIP [results] --quick: tree searches not re-run, so this run cannot pass'); }
else {
  const G = 'results';
  const MR = await import(path.join(HERE, 'make-results.mjs'));
  const t0 = Date.now();
  const sample = FULL ? null : { skipCladeGaps: true, seeds: [0], singles: [0, 34, 69], random: [0, 19, 39], removal: [0, 29] };
  const only = FULL ? null : ['baseline', 'seeds', 'deletions', 'placement', 'removal'];
  const again = MR.runPlan(ex, pr, { only, sample });
  const strip = (b) => { const c = structuredClone(b); const walk = (nd) => { delete nd.gap; nd.children.forEach(walk); }; if (c.consensus) c.consensus.top.forEach(walk); return c; };
  check(G, 'baseline search re-run reproduces results.json' + (FULL ? '' : ' (clade gaps checked with --full)'), FULL ? deepEqual(again.baseline, res.baseline) : deepEqual(strip(again.baseline), strip(res.baseline)));
  for (const key of Object.keys(again.seeds)) {
    const want = FULL ? res.seeds[key] : [res.seeds[key][0]];
    check(G, `seed spread "${key}" re-run reproduces results.json` + (FULL ? '' : ' (first seed)'), deepEqual(again.seeds[key], want));
  }
  if (FULL) check(G, 'gap spread re-run reproduces results.json', deepEqual(again.gapSpread, res.gapSpread));
  for (const k of Object.keys(res.deletions)) check(G, `deletion ${k} re-run reproduces results.json`, deepEqual(again.deletions[k], res.deletions[k]));
  check(G, 'placement, all traits and index traits, reproduce', deepEqual(again.placement.full, res.placement.full) && deepEqual(again.placement.index, res.placement.index));
  for (const x of again.placement.singles) check(G, `placement single deletion #${x.index} reproduces`, deepEqual(x, res.placement.singles[x.index]));
  for (const x of again.placement.random) check(G, `placement random draw #${x.index} reproduces`, deepEqual(x, res.placement.random[x.index]));
  check(G, 'removal, none and East Asian, reproduce', deepEqual(again.removal.full, res.removal.full) && deepEqual(again.removal.eastAsian, res.removal.eastAsian));
  for (const x of again.removal.random) check(G, `removal random draw #${x.index} reproduces`, deepEqual(x, res.removal.random[x.index]));
  check(G, 'results.json declares the plan the engine runs', deepEqual(res.plan, E.PLAN));
  check(G, 'every null list is complete', res.placement.singles.length === E.parsimonyData(ex).informative.length - 1 && res.placement.random.length === E.PLAN.placementNull.draws && res.removal.random.length === E.PLAN.removalNull.draws);
  if (!LEDGER) console.log(`     re-ran ${FULL ? 'every' : 'a sample of the'} tree searches in ${Math.round((Date.now() - t0) / 1000)} s`);
}

// ============================================================ surface: what the reader sees
const TEMPLATES = {
  seoTitle: () => 'Little Red Riding Hood Phylogeny: Tehrani 2013 Rechecked',
  title: () => 'All the Better to Count You With',
  dek: (F) => `Jamshid Tehrani coded ${F.tales} tellings of Little Red Riding Hood, The Wolf and the Kids and the East Asian Tiger Grandmother on ${F.chars} plot traits, and his matrix is public. This page runs it in your browser. ${F.anchorAgree} printed network statistics come back at the paper's precision; neither retention index does. Then the paper's own arguments on its own matrix. No trait shared by ATU 333 and ATU 123 is missing from the ${F.treeEA} East Asian tales, it says: as written that is false, since ${F.literalCount} coded states are, but none of those ${F.literalCount} is reconstructed at the two types' common ancestor on any of the ${F.ancestralTrees} shortest trees found by this page's bounded search, which does not establish the claim across all ${F.paperMpts} MPTs. The ${F.africanCount} African and Antiguan tales retain the tested branch with a ${F.placeC1home}-step search-found gap after this page's ${F.indexTraitCount}-trait deletion.`,
  og: (F) => `Tehrani's ${F.tales}-tale Little Red Riding Hood matrix run in your browser: ${F.anchorAgree} printed network statistics reproduce. This page finds ${F.literalCount} shared states absent from ${F.treeEA} East Asian tales on the matrix, but its bounded ${F.ancestralTrees}-tree search does not establish the claim across all ${F.paperMpts} paper MPTs.`,
  plain: () => 'A researcher scored 58 versions of Little Red Riding Hood and related tales on 72 story features and built family trees from them. This page reruns his numbers from his own table, lets you delete features to see which groupings survive, and tests three of his arguments. It cannot say which tale is oldest or how tales really travelled, only what his coding supports.',
};
const decode = (s) => s.replace(/&middot;/g, '·').replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&nbsp;/g, ' ').replace(/&#(\d+);/g, (_, d) => String.fromCodePoint(Number(d)));
const textOf = (frag) => decode(frag.replace(/<[^>]+>/g, '')).replace(/\s+/g, ' ').trim();
function frontmatter(src) {
  const m = src.match(/^---\n([\s\S]*?)\n---/);
  const out = {};
  if (!m) return out;
  for (const line of m[1].split('\n')) { const k = line.match(/^(\w+):\s*"(.*)"\s*$/); if (k) out[k[1]] = k[2]; }
  out.seam = (m[1].match(/^seam:\s*"?(\w+)"?/m) || [])[1];
  out.relates = [...m[1].matchAll(/-\s*to:\s*([\w-]+)/g)].map((x) => x[1]);
  return out;
}
// Elements whose content is checked by its own rule, and removed before the digit census.
const MARKED = /<(span|td|p|li|blockquote|cite|em|label)\b([^>]*\bdata-(?:fig|quote|printed|char|state|cite|legend)\b[^>]*)>/;
function elementSpans(src, attr) {
  // returns [{attrValue, inner, start, end}] for elements carrying attr (non-nested use only)
  const out = [];
  const re = new RegExp(`<(\\w+)\\b[^>]*\\b${attr}(?:="([^"]*)")?[^>]*>`, 'g');
  let m;
  while ((m = re.exec(src))) {
    const tag = m[1];
    let depth = 1, i = re.lastIndex;
    const openRe = new RegExp(`<${tag}\\b|</${tag}>`, 'g');
    openRe.lastIndex = i;
    let mm;
    while (depth && (mm = openRe.exec(src))) { if (mm[0].startsWith('</')) depth--; else depth++; }
    const end = mm ? mm.index : src.length;
    out.push({ value: m[2] ?? '', inner: src.slice(re.lastIndex, end), start: m.index, end: end + tag.length + 3 });
  }
  return out;
}
const HOUSE_CHROME = /<!--aw-(?:plain|checkkind|nearby|wayout):start-->[\s\S]*?<!--aw-(?:plain|checkkind|nearby|wayout):end-->\s*/g;
function stripHouseChrome(src) {
  return src
    .replace(HOUSE_CHROME, ' ')
    .replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi, ' ')
    .replace(/<script\b(?=[^>]*\bsrc=["']\/media\/[^"']+["'])(?![^>]*\btype=["']module["'])[^>]*>[\s\S]*?<\/script>/gi, ' ');
}
const CITE_TOKENS = new Set(['2013', '8', '11', '78871', '10.1371', 'journal.pone.0078871', '0078871', '2026-09-14', '3.0', '2002', '19', '2051', '2059', '2010', '365', '3923', '3933', '1999', '15', '2016', '31', '3', '24', '2017', '4', '2026', '09', '14', '12', '1812', '1889']);
function surfaceFailures(page, mdSrc, Fv) {
  const fails = [];
  const fm = frontmatter(mdSrc);
  // data-fig
  const figs = elementSpans(page, 'data-fig');
  if (figs.length < 100) fails.push('too few data-fig elements: ' + figs.length);
  for (const f of figs) {
    const got = textOf(f.inner);
    if (!(f.value in Fv)) fails.push('data-fig with no figure: ' + f.value);
    else if (got !== Fv[f.value]) fails.push(`data-fig ${f.value}: page "${got}" vs engine "${Fv[f.value]}"`);
  }
  // data-headline: the whole sentence, rebuilt from recomputed figures, as plain text (the wave gate
  // searches shipped files for the headline verbatim, so it carries no inner markup)
  const heads = elementSpans(page, 'data-headline');
  if (heads.length !== 1) fails.push('expected exactly one data-headline element, found ' + heads.length);
  for (const h of heads) {
    if (/</.test(h.inner)) fails.push('the headline carries markup');
    if (textOf(h.inner) !== FIG.headline(Fv)) fails.push('headline on the page is not the recomputed headline');
  }
  // data-quote
  for (const q of elementSpans(page, 'data-quote')) {
    const quote = pr.quotations.find((x) => x.id === q.value);
    const got = textOf(q.inner.replace(/<cite[\s\S]*?<\/cite>/, ''));
    if (!quote) fails.push('unknown quotation ' + q.value);
    else if (got !== quote.quote) fails.push('quotation altered: ' + q.value);
  }
  // data-printed: a printed value must stand in its quotation, or in the Table 1 transcription
  for (const p of elementSpans(page, 'data-printed')) {
    const got = textOf(p.inner);
    const [kind, key] = p.value.split(':');
    if (kind === 'table1') { const r = pr.table1.rows.find((x) => x.character === Number(key)); if (!r || got !== `${r.east_asian} / ${r.atu123} / ${r.atu333}`) fails.push('Table 1 printed cell altered: ' + p.value); }
    else if (kind === 'table1trait') { const r = pr.table1.rows.find((x) => x.character === Number(key)); if (!r || got !== r.trait_as_printed) fails.push('Table 1 trait label altered: ' + p.value); }
    else { const quote = pr.quotations.find((x) => x.id === kind); if (!quote || !new RegExp(`(^|[^0-9.])${got.replace(/[.]/g, '\\.')}($|[^0-9])`).test(quote.quote)) fails.push(`printed value "${got}" not in quotation ${kind}`); }
  }
  for (const c of elementSpans(page, 'data-char')) {
    const got = textOf(c.inner);
    if (!/^\d+$/.test(got) || Number(got) < 1 || Number(got) > 72 || (c.value && c.value !== got)) fails.push('trait number out of range or altered: ' + got);
  }
  // where a trait number is followed by its File S1 name, the name must be that trait's
  for (const m of page.matchAll(/<span data-char>(\d+)<\/span> ([^<]+)<\/td>/g)) {
    const ch = ex.characters[Number(m[1]) - 1];
    if (!ch || decode(m[2]).trim() !== ch.name) fails.push(`trait ${m[1]} is labelled "${m[2]}" but File S1 calls it "${ch ? ch.name : 'nothing'}"`);
  }
  // where a state code is followed by its File S1 label, the label must be that state's
  for (const m of page.matchAll(/<span data-state="(\d+):(\d+)">\[(\d+)\]<\/span> ([^<]+)<\/td>/g)) {
    const ch = ex.characters[Number(m[1]) - 1];
    const labels = ch ? ch.states.filter((x) => x.code_as_written === m[2]).map((x) => x.label_as_written) : [];
    if (m[2] !== m[3] || !labels.includes(decode(m[4]).trim())) fails.push(`state ${m[1]}:${m[2]} is labelled "${m[4]}"`);
  }
  const rowsCoded = E.codedRows(ex);
  for (const st of elementSpans(page, 'data-state')) {
    const [c, s] = st.value.split(':').map(Number);
    const got = textOf(st.inner);
    if (!got.includes(String(s)) || !rowsCoded.some((r) => r[c - 1] === s)) fails.push('state reference altered: ' + st.value + ' "' + got + '"');
  }
  const REFS = [/File S[12]/g, /Table S1/g, /Figure S[13]/g, /Table 1\b/g, /Figure [24]\b/g, /ATU (333|123)/g];
  for (const c of elementSpans(page, 'data-cite')) {
    let ct = textOf(c.inner);
    for (const re of REFS) ct = ct.replace(re, ' ');
    for (const tok of ct.match(/\d[\d.\-]*/g) || []) if (!CITE_TOKENS.has(tok.replace(/[.\-]$/, ''))) fails.push('unlisted number in a citation: ' + tok);
  }
  // the census: after removing every checked element, head, scripts, styles and comments, no digit may remain
  let body = stripHouseChrome(page).replace(/<!--[\s\S]*?-->/g, '').replace(/<head>[\s\S]*?<\/head>/, '').replace(/<script[\s\S]*?<\/script>/g, '');
  for (const attr of ['data-headline', 'data-quote', 'data-fig', 'data-printed', 'data-char', 'data-state', 'data-cite', 'data-legend']) {
    const spans = elementSpans(body, attr).sort((a, b) => b.start - a.start);
    for (const s of spans) body = body.slice(0, s.start) + ' ' + body.slice(s.end);
  }
  let text = decode(body.replace(/<[^>]+>/g, ' '));
  const allowed = [/ATU (333|123)/g, /File S[12]/g, /Table S1/g, /Figure S[13]/g, /Table 1\b/g, /Figure [24]\b/g, /SplitsTree 4\.13/g, /PAUP 4/g, /MrBayes 3\.2/g, /CC BY 3\.0/g, /SHA-256/g,
    ...ex.matrix.rows.filter((r) => /\d/.test(r.name)).map((r) => new RegExp(`\\b${r.name}\\b`, 'g'))];
  for (const re of allowed) text = text.replace(re, ' ');
  const stray = text.match(/\d+/g);
  if (stray) fails.push('bare digits no assertion covers: ' + [...new Set(stray)].join(', '));
  // head, frontmatter, record
  const head = page.match(/<head>([\s\S]*?)<\/head>/)[1];
  const metaOf = (sel) => { const m = head.match(new RegExp(`<meta ${sel} content="([^"]*)"`)); return m ? decode(m[1]) : null; };
  const title = decode(head.match(/<title>([^<]*)<\/title>/)[1]);
  if (title !== TEMPLATES.seoTitle(Fv) || fm.seoTitle !== title) fails.push('seoTitle / <title> disagree');
  if (fm.title !== TEMPLATES.title()) fails.push('frontmatter title');
  const dek = TEMPLATES.dek(Fv);
  if (metaOf('name="description"') !== dek) fails.push('meta description is not the recomputed dek');
  if (fm.dek !== dek) fails.push('frontmatter dek is not the recomputed dek');
  const og = TEMPLATES.og(Fv);
  if (metaOf('property="og:description"') !== og || metaOf('name="twitter:description"') !== og) fails.push('og/twitter description is not recomputed');
  const ld = JSON.parse(head.match(/<script type="application\/ld\+json">([\s\S]*?)<\/script>/)[1]);
  if (ld.description !== og || ld.name !== title || ld.headline !== TEMPLATES.title()) fails.push('JSON-LD disagrees');
  if (fm.plain !== TEMPLATES.plain(Fv)) fails.push('plain placard changed');
  if (!(fm.plain.includes(Fv.tales) && fm.plain.includes(Fv.chars))) fails.push('plain placard numbers');
  if (rec.headline !== FIG.headline(Fv)) fails.push('record.json headline is not recomputed');
  if (!page.replace(/\s+/g, ' ').includes(rec.headline)) fails.push('the page does not ship record.json headline verbatim in its source');
  if (!page.includes('https://artwaste.land/og/' + SLUG + '.png') || !page.includes(`<link rel="canonical" href="https://artwaste.land/strata/${SLUG}/" />`)) fails.push('canonical or og:image');
  return fails;
}
{
  const G = 'surface';
  const fails = surfaceFailures(html, md, F);
  check(G, 'every displayed figure, quotation, printed value, citation number and head tag is recomputed or verbatim', fails.length === 0, fails.slice(0, 12).join(' | '));
  const visibleDeks = elementSpans(html, 'data-dek');
  check(G, 'visible dek in page body equals frontmatter dek', visibleDeks.length === 1 && textOf(visibleDeks[0].inner) === frontmatter(md).dek, visibleDeks.length === 1 ? textOf(visibleDeks[0].inner) + ' vs ' + frontmatter(md).dek : 'expected one visible dek');
  // the page's worded claims, each tied to the result that makes it true; a claim whose result changes goes red
  const B = res.baseline, P = res.placement, Rm = res.removal, c5 = res.deletions.c5;
  const rg = P.random.map((x) => x.gap);
  const claims = [
    ['"every one of the paper\'s eight named groups is in all ... trees found"', E.GROUP_IDS.every((id) => B.presence[id] === B.treeCount), 'every one of the paper\'s eight named groups is in all'],
    ['"not one is held by a wide margin"', E.GROUP_IDS.every((id) => B.gaps[id].gap <= 3), 'not one is held by a wide margin'],
    ['"it is present in all the trees this search found too" (ATU 123)', B.presence.atu123 === B.treeCount, 'it is present in all the trees this search found too'],
    ['"stops being in every shortest tree" (trait 5, Little Red Riding Hood)', c5.presence.redHood < c5.treeCount, 'stops being in every shortest tree'],
    ['"two of the seven in that group (RH3 and Iran) do not have it"', (() => { const rows = E.codedRows(ex); const nm = E.taxaOf(ex); return pr.groups.find((g) => g.id === 'redHood').members.filter((m) => rows[nm.indexOf(m)][4] !== 1).join(',') === 'RH3,Iran'; })(), '(RH3 and Iran) do not have it'],
    ['"Read as shared by most tales of each type, it holds"', F.majorityCount === '0', 'it holds: <span data-fig="majorityCount">'],
    ['"The placement does not rest on the index\'s traits"', P.index.c1home.gap > 0 && P.index.c1home.present === P.index.c1home.of && P.index.c1.gap > 0, 'The placement does not rest on the index'],
    ['"inside the spread of random seven-trait deletions"', P.index.c1home.gap >= Math.min(...rg) && P.index.c1home.gap <= Math.max(...rg), 'inside the spread of random seven-trait deletions'],
    ['"the full ATU 123 group is no longer in every shortest tree" without the index traits', P.index.c1home.atu123Present < P.index.c1home.of && P.index.c1home.atu123Gap === 0, 'is no longer in every shortest tree (gap'],
    ['"The African tales stay with The Wolf and the Kids"', P.index.c1home.present === P.index.c1home.of && P.random.every((x) => x.present === x.of), 'The African tales stay with The Wolf and the Kids'],
    ['"Neither retention index comes back"', !E.printsAs(B.RI, '0.72') && !E.printsAs(Math.min(...res.seeds.noEastAsian.map((x) => x.RI).filter((_, i, a) => res.seeds.noEastAsian[i].bestLen === Math.min(...res.seeds.noEastAsian.map((y) => y.bestLen)))), '0.76'), 'Neither retention index comes back'],
    ['"further away still" (gap as a state)', Math.abs(res.seeds.gapState[0].RI - 0.72) > Math.abs(B.RI - 0.72), 'further away still'],
    ['"the delta score falls" when the East Asian tales are removed', Rm.eastAsian.meanDelta < Rm.full.meanDelta, 'The delta score falls from'],
    ['"only if the state is the only one" ambiguity is inert (no tallied state is ever ambiguous)', B.ancestral.tally.every((t) => t.among === 0) && B.ancestralTableS1.tally.every((t) => t.among === 0), 'none of the tallied states is ever one of several equally good states'],
    ['"Trait 2 ... is the one trait that cannot change any tree"', (() => { const d = E.parsimonyData(ex); return d.informative.length === 71 && !d.informative.includes(2); })(), 'is the one trait that cannot change any tree'],
    ['no search reported a constrained tree shorter than its unconstrained one', [...P.singles, ...P.random, P.full, ...Object.values(P.index)].every((x) => !x.missed) && E.GROUP_IDS.every((id) => !B.gaps[id].unconstrainedMissed), 'is what this search found, so it is an upper bound'],
  ];
  for (const [what, ok, phrase] of claims) check(G, 'worded claim holds on the results: ' + what, ok && html.includes(phrase), html.includes(phrase) ? '' : 'phrase not found in page: ' + phrase);
  const nFig = elementSpans(html, 'data-fig').length;
  check(G, `the census covers ${nFig} figure elements`, nFig >= 100);
  // controls: corrupt what the reader sees, in copies, and require red
  const corrupt = [
    ['a figure in prose', html.replace('<span data-fig="gap_atu333">2</span>', '<span data-fig="gap_atu333">3</span>')],
    ['a figure in the anchor table', html.replace('<span data-fig="noEADelta">0.2820</span>', '<span data-fig="noEADelta">0.2830</span>')],
    ['a quotation', html.replace('average delta score of 0.3 and', 'average delta score of 0.2 and')],
    ['a printed value', html.replace('<td class="n" data-printed="results-mpts-ri">0.72</td>', '<td class="n" data-printed="results-mpts-ri">0.74</td>')],
    ['a bare number added to prose', html.replace('Six agree, one of them', 'Six agree, 7 of them')],
    ['the meta description', html.replace("this page's 7-trait deletion", "this page's 8-trait deletion")],
    ['a trait number beside its File S1 name', html.replace('<span data-char>62</span> Rescued', '<span data-char>63</span> Rescued')],
    ['a trait number out of range', html.replace('trait <span data-char>45</span>, "Victim rescued"', 'trait <span data-char>75</span>, "Victim rescued"')],
    ['a state label', html.replace('<span data-state="4:2">[2]</span> male', '<span data-state="4:2">[2]</span> female')],
    ['a number in the headline', html.replace('matrix. Bounded search: none of 6', 'matrix. Bounded search: none of 7')],
    ['a citation number', html.replace('Molecular Biology and Evolution</em> 19:', 'Molecular Biology and Evolution</em> 91:')],
  ];
  for (const [what, doc] of corrupt) {
    check(G, `control: corrupting ${what} is caught`, doc !== html && surfaceFailures(doc, md, F).length > 0, doc === html ? 'the corruption did not apply' : '');
  }
  check(G, 'control: a changed plain placard is caught', surfaceFailures(html, md.replace('58 versions', '59 versions'), F).length > 0);
  const F2 = { ...F, literalCount: '5' };
  check(G, 'control: a wrong engine figure makes the page disagree', surfaceFailures(html, md, F2).length > 0);
}

// ============================================================ choices
{
  const G = 'choices';
  const effects = E.choiceEffects(ex, pr, res);
  for (const c of effects) {
    if (c.inert) {
      check(G, `choice ${c.id} is declared inert, and is: ${c.outputs.join(' | ')}`, !c.moves && c.reason.length > 20);
      check(G, `the page prints the reason ${c.id} is inert`, textOf(html).includes(c.reason));
    } else check(G, `choice ${c.id} changes its output: ${c.outputs.join(' | ')}`, c.moves);
  }
  check(G, 'record.json declares exactly the engine\'s choices', deepEqual(rec.choices, E.CHOICES.map((c) => ({ id: c.id, label: c.label, options: c.options, default: c.default, affects: c.affects, inert: !!c.inert }))));
  for (const c of E.CHOICES) check(G, `the page offers every option of ${c.id}`, c.options.every((o) => html.includes(`name="${c.id}" value="${o}"`)));
  check(G, 'the browser choice proof changes the intended DOM panels and checks inertness', pageJs.includes('function choiceDomProbe') && pageJs.includes('CHOICE_OUTPUTS') && pageJs.includes("dispatchEvent(new Event('change'") && pageJs.includes('DOM control probe'));
  check(G, 'live choice prose derives East Asian, character and deletion lengths from loaded state', pageJs.includes('missing from all ${G.eastAsian.length} East Asian tales') && pageJs.includes('With all ${ex.characters.length} traits') && pageJs.includes('sets of ${deleted.length} traits') && pageJs.includes('random ${deleted.length}-trait deletions'));
  // control on the control: a sham choice whose options compute the same thing must not pass as live
  const sham = ['skip', 'skip'].map((o) => E.choiceOutput(ex, pr, res, 'distance', o));
  check(G, 'control: a sham choice with identical options is detected as not moving', sham[0] === sham[1]);
}

// ============================================================ planted fault
{
  const G = 'fault';
  const clean = E.sharedStates(ex, pr, E.DEFAULTS);
  const doctored = structuredClone(ex);
  const tg11 = doctored.matrix.rows.find((r) => r.name === 'TG11');
  check(G, 'TG11 carries state 0 at trait 62 in the clean record', tg11.states_as_written[61] === '0');
  tg11.states_as_written = tg11.states_as_written.slice(0, 61) + '1' + tg11.states_as_written.slice(62);
  const dirty = E.sharedStates(doctored, pr, E.DEFAULTS);
  check(G, 'planted fault: the literal list loses trait 62', clean.some((s) => s.character === 62) && !dirty.some((s) => s.character === 62) && dirty.length === clean.length - 1);
  const d0 = E.networkBlock(ex, pr).full.meanDelta, d1 = E.networkBlock(doctored, pr).full.meanDelta;
  check(G, 'planted fault: the delta score moves off 0.29702', d0.toFixed(5) === '0.29702' && d1.toFixed(5) !== '0.29702');
  const Fd = FIG.figures(doctored, pr, res);
  check(G, 'planted fault: the headline builder changes on the doctored data', FIG.headline(Fd) !== FIG.headline(F));
  // Table 1: one more East Asian passer-by rescue makes row 45 agree, so the recount sees single tales
  const t1d = structuredClone(ex);
  const tg6 = t1d.matrix.rows.find((r) => r.name === 'TG6');
  tg6.states_as_written = tg6.states_as_written.slice(0, 44) + '1' + tg6.states_as_written.slice(45);
  check(G, 'planted fault: one tale changed at trait 45 moves the Table 1 recount', E.table1Recount(t1d, pr, E.DEFAULTS).filter((r) => r.agree).length === 5 && F.table1Agree === '4 of 5');
  // the search: a planted row that makes an African tale identical to Grimm must break the African group in the found trees
  const moved = structuredClone(ex);
  moved.matrix.rows.find((r) => r.name === 'Africa1').states_as_written = ex.matrix.rows.find((r) => r.name === 'Grimm').states_as_written;
  const r = E.treesJob(moved, pr, { seed: 1, startTrees: 4, start: res.baseline.newick, effort: { replicates: 2, ratchetIterations: 5, maxTrees: 50 }, groups: ['african'], gapsFor: [] });
  check(G, 'planted fault: recoding Africa1 as Grimm removes the African group from the trees found', r.presence.african === 0);
}

// ============================================================ refusals
{
  const G = 'refusal';
  for (const k of Object.keys(E.REFUSALS)) {
    const r = E.refuse(k);
    check(G, `refuses "${k}" with a reason`, r.refused && r.reason.length > 40);
    check(G, `the page has a button for "${k}"`, html.includes(`data-refuse="${k}"`));
  }
  check(G, 'control: an unknown request is not treated as a refusal', !E.refuse('nonsense').refused && !E.refuse('').refused);
  const outside = E.taleRow(ex, 'Shrek');
  check(G, 'a tale outside the 58 coded rows is refused, not guessed', outside.refused && outside.reason === E.REFUSALS.newTale);
  check(G, 'control: a coded tale is returned as written', !E.taleRow(ex, 'Grimm').refused && E.taleRow(ex, 'Grimm').as_written === ex.matrix.rows[0].states_as_written);
  let threw = false; try { E.readCell('X'); } catch { threw = true; }
  check(G, 'a cell outside 0-9, ? and - is refused', threw);
  const S = new E.Searcher(E.parsimonyData(ex));
  threw = false; try { E.fromNewick(S, res.baseline.newick[0].replace('Grimm', 'Shrek')); } catch { threw = true; }
  check(G, 'a tree naming a tale not in the matrix is refused', threw);
  const T = E.fromNewick(S, res.baseline.newick[0]);
  const names = E.taxaOf(ex);
  check(G, 'rooting on a set of tales that is not a group of the tree is refused (null)', E.rootOnGroup(S, T, [names.indexOf('Grimm'), names.indexOf('TG1')]) === null);
}

// ============================================================ hygiene
{
  const G = 'hygiene';
  const inline = [...html.matchAll(/<script(?![^>]*\bsrc=)([^>]*)>([\s\S]*?)<\/script>/g)];
  check(G, 'the only inline script is the JSON-LD, and it parses', inline.length === 1 && /application\/ld\+json/.test(inline[0][1]) && (() => { try { JSON.parse(inline[0][2]); return true; } catch { return false; } })());
  check(G, 'load-bearing closing tags present', /<\/script>\s*<\/body>\s*<\/html>\s*$/.test(html));
  for (const f of ['engine.js', 'figures.js', 'render.js', 'page.js', 'search-worker.js']) {
    const src = fs.readFileSync(path.join(PUB, f), 'utf8');
    const urls = [...src.matchAll(/\bhttps?:\/\/[^\s'"`<>]+/g)].map((m) => m[0]);
    const unexpected = urls.filter((u) => u !== 'http://www.w3.org/2000/svg');
    check(G, `${f} makes no third-party request`, unexpected.length === 0, unexpected.join(', '));
    check(G, `${f} has no em dash`, !src.includes('\u2014'));
  }
  const pageLines = html.split('\n').filter((l) => l.includes('\u2014') && !l.includes('em-dash-ok'));
  check(G, 'index.html has no unmarked em dash', pageLines.length === 0);
  check(G, 'matrix canvas is decorative and selection uses the labelled controls', html.includes('<canvas id="mx" aria-hidden="true"></canvas>') && !pageJs.includes('matrixHit('));
  check(G, 'the primary trait action uses File S1 wording and names its progressive timing', html.includes('The victim wears a red cap/hood') && html.includes('Switch off a named trait to start a progressive search: early length and group presence arrive first, while the complete gap ledger can take about half a minute.'));
  check(G, 'record.json slug, href and title', rec.slug === SLUG && rec.href === `/strata/${SLUG}/` && rec.title === TEMPLATES.title());
  const fm = frontmatter(md);
  check(G, 'frontmatter seam is groundtruth and relates has 3 to 5 existing slugs', fm.seam === 'groundtruth' && fm.relates.length >= 3 && fm.relates.length <= 5 && fm.relates.every((s) => fs.existsSync(path.join(ROOT, 'src', 'content', 'strata', s + '.md'))));
}

// ============================================================ ledger
const allOk = (g) => (outcomes[g] || []).length > 0 && outcomes[g].every((o) => o.ok);
const ledger = {
  anchor_reproduced_by_engine: allOk('anchor') && allOk('search'),
  rendered_figures_asserted: allOk('surface') && allOk('results'),
  choices_are_live: allOk('choices'),
  planted_fault_caught: allOk('fault'),
  refusal_asserted: allOk('refusal'),
  provenance_pinned: allOk('provenance'),
};
if (LEDGER) {
  for (const [k, v] of Object.entries(ledger)) console.log(`${k}=${v}`);
} else {
  const n = Object.values(outcomes).reduce((a, g) => a + g.length, 0);
  console.log(`\n${n - failures} of ${n} assertions passed; ledger ${JSON.stringify(ledger)}`);
  const mismatch = Object.entries(ledger).filter(([k, v]) => !rec.ledger[k] || rec.ledger[k].value !== v);
  if (mismatch.length) { console.log('record.json ledger disagrees with the computed ledger: ' + mismatch.map(([k]) => k).join(', ')); failures++; }
}
process.exit(failures ? 1 : 0);
