#!/usr/bin/env node
// verify-with-sudden-start.mjs: recomputes every number the page shows from the frozen record with the
// page's own engine, checks the page's prose, head tags, frontmatter and record.json against it, runs
// negative controls on doctored copies, and prints the six ledger cells from the assertion outcomes.
//   node research/with-sudden-start/verify-with-sudden-start.mjs            (full report)
//   node research/with-sudden-start/verify-with-sudden-start.mjs --ledger   (the six cells only)
// It never writes a file.
import fs from 'node:fs';
import crypto from 'node:crypto';
import * as E from '../../public/strata/with-sudden-start/engine.js';
import { computeFigures } from '../../public/strata/with-sudden-start/figures.js';

const LEDGER = process.argv.includes('--ledger');
const P = 'public/strata/with-sudden-start/';
const RS = 'research/with-sudden-start/';
const read = (f) => fs.readFileSync(f, 'utf8');
const json = (f) => JSON.parse(read(f));
const sha = (buf) => crypto.createHash('sha256').update(buf).digest('hex');

const results = [];
function check(group, name, cond, detail = '') {
  results.push({ group, name, ok: !!cond, detail });
  return !!cond;
}

const fable = json(P + 'fable.json');
const keys = json(P + 'keys.json');
const glosses = json(P + 'glosses.json');
const ch23 = fs.existsSync(P + 'ch23.json') ? json(P + 'ch23.json') : null;
const record = json(P + 'record.json');
const html = read(P + 'index.html');
const md = read('src/content/strata/with-sudden-start.md');
const pagejs = read(P + 'page.js');
const licence = read(P + 'LICENCE.txt');
const F = computeFigures({ fable, keys, glosses, ch23 });
const clone = (x) => JSON.parse(JSON.stringify(x));

// A small source oracle for the anchor. It does not call the parser: it checks the transcribed
// tokens and the printed key entries directly, so a parser change cannot make both checks agree.
const directEntries = ['chapters', 'synoptical', 'additions'].flatMap((name) => keys.keys[name].entries);
const directWord = (actual, expected) => {
  const a = String(actual).toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim();
  const e = String(expected).toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim();
  return a === e || a.startsWith(e);
};
const directKeyHas = (slot, sym, word) => directEntries.some((e) => e.slot === slot && e.sym === sym && directWord(e.word, word));
const sourceTokens = (fig, side = 'above', witness = 'oxford') => String(fable.figures[fig - 1][witness][side] || '').replace(/\./g, '').split(/\s+/).filter(Boolean);
const sourceHas = (fig, token, side = 'above', witness = 'oxford') => sourceTokens(fig, side, witness).includes(String(token).replace(/\./g, ''));
const sourceIncludes = (fig, text, side = 'above', witness = 'oxford') => sourceTokens(fig, side, witness).join(' ').includes(String(text).replace(/\./g, ''));
function independentAnchorOracle() {
  const sameHands = sourceTokens(15).filter((x) => x !== 'D').join(' ') === sourceTokens(20).filter((x) => x !== 'D').join(' ');
  const feetDiffer = String(fable.figures[14].oxford.below) !== String(fable.figures[19].oxford.below);
  return [
    ['A1', directKeyHas('palm', 'p', 'prone') && directKeyHas('elevation', 'h', 'horizontal') && directKeyHas('transverse', 'f', 'forward') && directKeyHas('direction', 'd', 'descending')],
    ['A2', directKeyHas('palm', 's', 'supine') && directKeyHas('elevation', 'e', 'elevated') && directKeyHas('transverse', 'q', 'oblique') && directKeyHas('manner', 'n', 'noting')],
    ['A3', directKeyHas('palm', 'p', 'prone') && directKeyHas('elevation', 'h', 'horizontal') && directKeyHas('transverse', 'q', 'oblique') && directKeyHas('elevation', 'd', 'downwards') && directKeyHas('transverse', 'b', 'backwards')],
    ['A4', sourceHas(1, 'Bvhf') && sourceHas(1, 'r') && sourceHas(1, 'q') && directKeyHas('palm', 'v', 'vertical') && directKeyHas('elevation', 'h', 'horizontal') && directKeyHas('transverse', 'f', 'forward') && directKeyHas('direction', 'r', 'right') && directKeyHas('transverse', 'q', 'oblique')],
    ['A5', sourceHas(2, 'n') && directKeyHas('manner', 'n', 'noting')],
    ['A6', sourceIncludes(12, 'Bfl') && sourceIncludes(12, 'Bfl.br') && sourceHas(12, 'a') && directKeyHas('combination', 'fl', 'folded') && directKeyHas('elevation', 'h', 'horizontal') && directKeyHas('transverse', 'f', 'forward') && directKeyHas('direction', 'a', 'ascending') && directKeyHas('part', 'br', 'breast')],
    ['A7', sourceHas(21, 'Bvhf') && sourceHas(21, 'vef') && directKeyHas('elevation', 'h', 'horizontal') && directKeyHas('elevation', 'e', 'elevated')],
    ['A8', sourceHas(25, 'Bphc') && sourceHas(25, 'x') && directKeyHas('transverse', 'c', 'across') && directKeyHas('transverse', 'x', 'extended')],
    ['A9', [9, 15, 20].every((fig) => sourceHas(fig, 'n')) && directKeyHas('manner', 'n', 'noting')],
    ['A10', sameHands && feetDiffer && sourceHas(15, 'n') && sourceHas(20, 'n') && directKeyHas('elevation', 'd', 'downwards') && directKeyHas('direction', 'd', 'descending')],
    ['A11', sourceHas(26, 'L1x', 'below') && directKeyHas('position', 'L1', 'left 1st position') && directKeyHas('feet-extended', 'x', 'extended')],
    ['A12', sourceHas(28, 'Bvhf') && sourceHas(28, 'rj') && sourceHas(28, 'rR1', 'below') && directKeyHas('palm', 'v', 'vertical') && directKeyHas('elevation', 'h', 'horizontal') && directKeyHas('transverse', 'f', 'forward') && directKeyHas('manner', 'rj', 'rejecting') && directKeyHas('step', 'r', 'retire')],
    ['A14', sourceHas(4, 'ad') && sourceIncludes(4, 'a', 'below') && directKeyHas('manner', 'ad', 'advancing') && directKeyHas('step', 'a', 'advance')],
    ['A16', fable.figures.filter((f) => f.oxford.numeral).length === 30 && fable.figures.filter((f) => f.oxford.rule_after).length === 30],
  ];
}

// ============================================================ 1. anchor
{
  const g = 'anchor';
  const run = E.runFable(fable, keys, {});
  const t = E.tally(glosses, run, keys);
  check(g, 'engine reads 14 anchor glosses from glosses.json', t.total === glosses.anchor.length && t.total === 14, `${t.total}`);
  for (const r of t.rows) check(g, `collated text, union key: ${r.id} agrees`, r.verdict === 'agree', r.verdict);
  check(g, 'collated tally is the anchor', t.agree === t.total && F.collatedAgree === String(t.agree));
  const oracle = independentAnchorOracle();
  check(g, 'independent source oracle agrees with all 14 anchor rows', oracle.length === 14 && oracle.every(([, ok]) => ok), oracle.filter(([, ok]) => !ok).map(([id]) => id).join(', '));
  check(g, 'A12 transcribes the printed source as Observation XXVII, p. 372', glosses.anchor.find((r) => r.id === 'A12').source === 'Observation XXVII, p. 372');
  check(g, 'Oxford alone reproduces every gloss', E.tally(glosses, E.runFable(fable, keys, { witness: 'oxford' }), keys).agree === 14);
  check(g, 'UNCG alone reproduces every gloss', E.tally(glosses, E.runFable(fable, keys, { witness: 'uncg' }), keys).agree === 14);
  const keyEndpoints = {
    synoptical: [13, 1, 0],
    'synoptical-plus-additions': [14, 0, 0],
    alphabetical: [12, 2, 0],
    union: [14, 0, 0],
  };
  for (const [key, [agree, disagree, unsettled]] of Object.entries(keyEndpoints)) {
    const kt = E.tally(glosses, E.runFable(fable, keys, { key }), keys);
    check(g, `collated ${key} endpoint is ${agree}/${disagree}/${unsettled}`, kt.agree === agree && kt.disagree === disagree && kt.unsettled === unsettled, `${kt.agree}/${kt.disagree}/${kt.unsettled}`);
  }
  const f1 = t.findings.find((x) => x.id === 'F1'), f2 = t.findings.find((x) => x.id === 'F2');
  check(g, 'finding F1: Bvhf cited for the end position reads horizontal, not elevated', f1.verdict === 'disagree' && f1.claims[0].parts[0].found.includes('horizontal'));
  check(g, 'finding F2: figure 26 clinched hands but manner sh, not cl', f2.verdict === 'partial');
  const dli = E.tally(glosses, E.runFable(fable, keys, { witness: 'dli' }), keys);
  const bad = dli.rows.filter((r) => r.verdict !== 'agree').map((r) => `${r.id}:${r.verdict}`).join(' ');
  check(g, 'DLI scan: A7 unsettled, A9 A10 A16 fail, the rest agree', bad === 'A7:unsettled A9:disagree A10:disagree A16:disagree', bad);
  check(g, 'DLI counts: 29 numerals, 22 rules', F.dliNumerals === '29' && F.dliRules === '22');

  // negatives: the anchor must go red when the record or the key is wrong
  const d1 = clone(fable); for (const w of ['oxford', 'uncg']) d1.figures[24][w].above = d1.figures[24][w].above.replace('Bphc', 'Bpha');
  const t1 = E.tally(glosses, E.runFable(d1, keys, {}), keys);
  check(g, 'negative: a misread c in Bphc (figure 25) fails Observation XXV', t1.rows.find((r) => r.id === 'A8').verdict === 'disagree' && t1.agree === 13);
  const k1 = clone(keys);
  for (const k of ['chapters', 'synoptical']) for (const e of k1.keys[k].entries) if (e.slot === 'transverse' && e.sym === 'c') e.sym = 'a';
  k1.keys.alphabetical.rows.C.transverse = [];
  const t2 = E.tally(glosses, E.runFable(fable, k1, {}), k1);
  check(g, 'negative: a key that letters across as a (the DLI reading of p. 364) fails Observation XXV', t2.rows.find((r) => r.id === 'A8').verdict === 'disagree');
  const g1 = clone(glosses); g1.anchor[0].claims[0].expect.hand = 'supine';
  check(g, 'negative: a wrong expected word (phfd read as supine) fails A1', E.tally(g1, E.runFable(fable, keys, {}), keys).rows[0].verdict === 'disagree');
  const d2 = clone(fable); d2.figures[27].oxford.above = 'Bvhf'; d2.figures[27].uncg.above = 'Bvhf';
  check(g, 'negative: dropping rj at figure 28 fails Observation XXVII', E.tally(glosses, E.runFable(d2, keys, {}), keys).rows.find((r) => r.id === 'A12').verdict === 'disagree');
  check(g, 'negative: the synoptical table alone cannot read rj (A12 fails)', E.tally(glosses, E.runFable(fable, keys, { key: 'synoptical' }), keys).rows.find((r) => r.id === 'A12').verdict === 'disagree');

  // the keys, checked against entries read independently by the spec writer on other images
  const syn = keys.keys.synoptical.entries;
  const has = (list, slot, sym, word) => list.some((e) => e.slot === slot && e.sym === sym && (e.word === word || E.wordMatch(word, e.word)));
  const second = [
    ['transverse', 'c', 'across'], ['transverse', 'f', 'forward'], ['transverse', 'q', 'oblique'], ['transverse', 'x', 'extended'], ['transverse', 'b', 'backwards'],
    ['force', 'x', 'extreme'], ['force', 'c', 'contracted'], ['force', 'm', 'moderate'],
    ['direction', 'a', 'ascending'], ['direction', 'd', 'descending'], ['direction', 'r', 'right'], ['direction', 'l', 'left'], ['direction', 'f', 'forwards'], ['direction', 'b', 'backwards'], ['direction', 'v', 'revolving'],
    ['manner', 'p', 'projecting or pushing'],
    ['step', 'a', 'advance'], ['step', 'r', 'retire'], ['step', 'tr', 'traverse'], ['step', 'c', 'cross'], ['step', 'st', 'start'], ['step', 'sp', 'stamp'], ['step', 'sk', 'shock'],
    ['position', 'F1', 'front 1st position'], ['position', 'R1', 'right 1st position'], ['position', 'L2', 'left 2d position'], ['position', 'K', 'kneeling'], ['position', 'S', 'aside'],
  ];
  for (const [slot, sym, word] of second) check(g, `key p. 364 to 365 carries ${sym} = ${word} (${slot})`, has(syn, slot, sym, word));
  const add = keys.keys.additions.entries.map((e) => e.sym).join(',');
  check(g, 'Additions p. 551 are i, o, rt, rj, bn', add === 'i,o,rt,rj,bn', add);
  const A = keys.keys.alphabetical.rows;
  check(g, 'p. 366 row A, motion: ascending, alternate', JSON.stringify(A.A.motion) === '["ascending","alternate"]');
  check(g, 'p. 366 row R, motion: right, recoiling, repressing, rejecting', A.R.motion.join(',') === 'right,recoiling,repressing,rejecting');
  check(g, 'p. 366 row T: touching, throwing; Tossing; traverse; threatning', A.T.motion.join(',') === 'touching,throwing' && A.T['head-eyes'][0] === 'Tossing' && A.T.steps[0] === 'traverse' && A.T.significant[0] === 'threatning');
  check(g, 'p. 366 rows I and O: inwards, outwards', A.I.motion[0] === 'inwards' && A.O.motion[0] === 'outwards');
  check(g, 'DLI variant of p. 364 recorded: a. across', syn.some((e) => e.sym === 'c' && e.slot === 'transverse' && e.variants && e.variants.dli.sym === 'a'));

  // the transcription, against a blinded second reading of three witnesses
  const blind = json(RS + 'data/blind-second-reading.json');
  const n = (s) => String(s || '').replace(/\s+/g, ' ').trim();
  const diffs = [];
  for (const w of ['uncg', 'dli', 'plate']) {
    for (const b of blind[w]) {
      const m = fable.figures.find((x) => x.fig === b.fig)[w];
      if (n(m.above) !== n(b.above)) diffs.push(`${w}:${b.fig}:above`);
      if (n(m.below) !== n(b.below)) diffs.push(`${w}:${b.fig}:below`);
      if (w !== 'plate' && m.rule_after !== b.rule_after) diffs.push(`${w}:${b.fig}:rule`);
      if (w !== 'plate' && m.numeral !== b.margin_numeral) diffs.push(`${w}:${b.fig}:numeral`);
    }
  }
  const DOCUMENTED = ['uncg:4:above', 'dli:4:above', 'dli:21:above', 'plate:15:above', 'plate:18:above', 'plate:20:above', 'plate:21:above', 'plate:22:above'];
  check(g, 'every disagreement with the blinded second reading is one the README documents', JSON.stringify(diffs) === JSON.stringify(DOCUMENTED), diffs.join(' '));
  check(g, 'the second reading agrees on every letter of the Oxford/UNCG-collated marks except dash joins', diffs.filter((d) => !d.startsWith('plate')).length === 3);
}

// ============================================================ 1b. second layer, chapter XXIII (exit code, not a ledger cell)
if (ch23 && E.runCh23) {
  const g = 'layer2';
  const out = E.runCh23(ch23, keys, {});
  check(g, 'chapter XXIII parsed in both witnesses', out.witnesses.length === 2, String(out.witnesses.length));
  for (const [name, value] of Object.entries(E.ch23Figures ? E.ch23Figures(ch23, keys) : {})) check(g, `chapter XXIII figure ${name} recomputed`, F[name] === String(value), `${F[name]} vs ${value}`);
}

// ============================================================ 2. surface: everything the reader sees
function stripTags(s) { return s.replace(/<[^>]+>/g, '').replace(/&middot;/g, '·').replace(/&amp;/g, '&').replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/\s+/g, ' ').trim(); }
function frontmatter(key) { const m = new RegExp(`^${key}:\\s*"(.*)"\\s*$`, 'm').exec(md.split('---')[1]); return m ? m[1] : null; }

const FIXED = {
  '1806': 'publication year on the title page of Chironomia',
  '2012': 'Laird, working grammar (cited)', '2019': 'Smith, The Digital Chironomia (cited)', '2020': 'Newman and Streit (cited)',
  '1998': 'Spoel, Rhetoric Society Quarterly (cited)', '2015': 'Wentz (cited)', '1966': 'Southern Illinois University Press edition (not checked)',
  '2026-09-14': 'date of the prospector and spec searches', '2026-09-15': 'date the builder re-ran the corpus search',
};

function knownPages() {
  const s = new Set([369, 370]);
  const text = [read(P + 'keys.json'), read(P + 'glosses.json'), read(P + 'fable.json')].join(' ');
  for (const m of text.matchAll(/"page":\s*(\d+)/g)) s.add(Number(m[1]));
  for (const m of text.matchAll(/\bpp?\.\s*(\d+)(?:\s*to\s*(\d+))?/g)) { s.add(Number(m[1])); if (m[2]) for (let i = Number(m[1]); i <= Number(m[2]); i++) s.add(i); }
  for (const k of Object.values(keys.keys)) { const m = /(\d+)\s*to\s*(\d+)/.exec(k.pages || ''); if (m) for (let i = Number(m[1]); i <= Number(m[2]); i++) s.add(i); }
  return s;
}
function knownLeaves() {
  const s = new Set();
  const text = [read(P + 'fable.json'), read(P + 'glosses.json'), read(P + 'keys.json')].join(' ');
  for (const m of text.matchAll(/\bn(\d{3})\b/g)) s.add(Number(m[1]));
  return s;
}
const PAGES = knownPages(), LEAVES = knownLeaves();
const IDENTS = new Set(['per_british-and-continental-rhetoric-and-elocution_austin-gilbert_1806', 'dli.ministry.11126', 'chironomiaoratr00austgoog', 'SHA-256']);
const MARKTOKENS = new Set(fable.figures.flatMap((f) => ['oxford', 'uncg', 'dli', 'plate'].flatMap((w) => `${f[w].above} ${f[w].below}`.split(/\s+/))).filter(Boolean));

// Returns a list of problems in the visible body of an HTML string.
function surfaceProblems(src, Fv) {
  const probs = [];
  const body = src.replace(/<!--[\s\S]*?-->/g, '').replace(/<head>[\s\S]*<\/head>/, '').replace(/<script[\s\S]*?<\/script>/g, '').replace(/<style[\s\S]*?<\/style>/g, '');
  const VOID = new Set(['img', 'input', 'br', 'meta', 'link', 'hr', 'source']);
  const stack = [];
  const figSeen = {};
  let prevText = '';
  for (const m of body.matchAll(/<[^>]+>|[^<]+/g)) {
    const tok = m[0];
    if (tok[0] === '<') {
      if (tok[1] === '!') continue;
      if (tok[1] === '/') { stack.pop(); continue; }
      const name = /^<([a-zA-Z0-9]+)/.exec(tok)[1].toLowerCase();
      const attrs = {};
      for (const a of tok.matchAll(/([a-zA-Z-]+)(?:="([^"]*)")?/g)) attrs[a[1]] = a[2] === undefined ? '' : a[2];
      if (!VOID.has(name) && !tok.endsWith('/>')) stack.push({ name, attrs });
      continue;
    }
    const text = tok.replace(/&middot;/g, '·').replace(/&amp;/g, '&');
    const carry = prevText;
    if (text.trim()) prevText = (prevText + text).slice(-40);
    if (!/\d/.test(text)) continue;
    const ctx = Object.assign({}, ...stack.map((s) => s.attrs));
    if (ctx.id === 'headline' || stack.some((s) => s.attrs.id === 'headline')) continue;
    const figEl = [...stack].reverse().find((s) => s.attrs['data-fig'] !== undefined);
    if (figEl) { const name = figEl.attrs['data-fig']; (figSeen[name] = figSeen[name] || []).push(text.trim()); if (Fv[name] === undefined) probs.push(`data-fig ${name} is not computed`); else if (text.trim() !== Fv[name]) probs.push(`data-fig ${name} shows ${text.trim()}, engine gives ${Fv[name]}`); continue; }
    if (stack.some((s) => s.attrs['data-fixed'] !== undefined)) { if (!FIXED[text.trim()]) probs.push(`fixed value ${text.trim()} has no declared reason`); continue; }
    for (const num of text.matchAll(/[\w.\-]*\d[\w.\-]*/g)) {
      const word = num[0].replace(/[.,;:]+$/, '');
      const before = carry + text.slice(0, num.index);
      if (IDENTS.has(word) || MARKTOKENS.has(word)) continue;
      if (/^\d+$/.test(word)) {
        const v = Number(word);
        const cm = /(figures?|fig\.|pages?|pp?\.|plate|leaf|leaves|no\.)\s*(?:n?\d+\s*(?:,|and|to)\s*)*$/i.exec(before);
        if (!cm) { probs.push(`bare number "${word}" in: ${text.trim().slice(0, 80)}`); continue; }
        const kind = cm[1].toLowerCase();
        if (kind.startsWith('fig') && !(v >= 1 && v <= 30)) probs.push(`figure ${v} does not exist`);
        if ((kind.startsWith('p') && kind !== 'plate') && !PAGES.has(v)) probs.push(`page ${v} is not a page in the record`);
        if (kind === 'plate' && v !== 12) probs.push(`plate ${v} is not the plate read`);
        continue;
      }
      if (/^n\d{3}$/.test(word)) { if (!LEAVES.has(Number(word.slice(1)))) probs.push(`leaf ${word} is not in the record`); continue; }
      probs.push(`unclassified token with a digit "${word}"`);
    }
  }
  for (const name of Object.keys(figSeen)) if (!(name in Fv)) probs.push(`unknown figure ${name}`);
  return { probs, figSeen };
}

function headProblems(src, Fv) {
  const probs = [];
  const get = (re) => { const m = re.exec(src); return m ? stripTags(m[1]) : null; };
  const title = get(/<title>([^<]*)<\/title>/);
  const desc = get(/<meta name="description" content="([^"]*)"/);
  const og = get(/<meta property="og:description" content="([^"]*)"/);
  const tw = get(/<meta name="twitter:description" content="([^"]*)"/);
  const ldm = /<script type="application\/ld\+json">([\s\S]*?)<\/script>/.exec(src);
  let ld = null; try { ld = JSON.parse(ldm[1]); } catch { probs.push('JSON-LD does not parse'); }
  const dek = frontmatter('dek'), seo = frontmatter('seoTitle'), ftitle = frontmatter('title');
  if (title !== seo) probs.push('title differs from seoTitle');
  if (desc !== dek) probs.push('meta description differs from dek');
  if (!ld || ld.description !== dek) probs.push('JSON-LD description differs from dek');
  if (!ld || ld.name !== seo || ld.headline !== ftitle) probs.push('JSON-LD name or headline differs');
  const nums = (s) => (s.match(/\d+/g) || []).map(String);
  const want = ['1806', Fv.collatedAgree, Fv.dliAgree, Fv.robustResidue];
  if (JSON.stringify(nums(dek)) !== JSON.stringify(want)) probs.push(`dek numbers ${nums(dek)} vs ${want}`);
  if (JSON.stringify(nums(og)) !== JSON.stringify(want)) probs.push(`og:description numbers ${nums(og)} vs ${want}`);
  if (JSON.stringify(nums(tw)) !== JSON.stringify(['1806'])) probs.push(`twitter:description numbers ${nums(tw)}`);
  const plain = frontmatter('plain');
  if (!plain || /\d/.test(plain)) probs.push('plain placard carries a number or is missing');
  const hl = /<p class="headline prose" id="headline">([^<]+)<\/p>/.exec(src);
  if (!hl) probs.push('headline paragraph missing');
  else {
    const hn = nums(hl[1]);
    const expect = [Fv.collatedAgree, Fv.dliAgree, Fv.robustResidue];
    if (JSON.stringify(hn) !== JSON.stringify(expect)) probs.push(`headline numbers ${hn} vs ${expect}`);
    if (!hl[1].includes("the page's declared robustness sweep")) probs.push('headline does not name the declared robustness sweep');
    if (record.headline !== hl[1].replace(/\s+/g, ' ').trim()) probs.push('record.json headline differs from the page');
  }
  return probs;
}

{
  const g = 'surface';
  const s = surfaceProblems(html, F);
  check(g, 'every digit in the visible page is recomputed, cited, a mark, an identifier or a declared date', s.probs.length === 0, s.probs.slice(0, 6).join(' | '));
  check(g, 'at least 20 distinct recomputed figures are printed in the prose', Object.keys(s.figSeen).length >= 20, String(Object.keys(s.figSeen).length));
  const h = headProblems(html, F);
  check(g, 'title, description, OG, Twitter, JSON-LD, dek, plain and headline agree with the engine', h.length === 0, h.join(' | '));
  check(g, 'the readable-copy heading names the copies that support its claim', html.includes('Two glosses that do not fit in the readable Oxford and UNCG copies'));
  check(g, 'the Additions sentence distinguishes the three fable gaps from the full five-entry table', html.includes('include exactly the three missing entries used by this fable') && html.includes('the full table also adds rt and bn'));
  check(g, 'the page contains a rendered dynamic-readout assertion for the anchor, copy, grid, residue and count', pagejs.includes("const dynamic = [") && pagejs.includes("document.getElementById('anchorTally')") && pagejs.includes("document.getElementById('residueNow')") && pagejs.includes("document.querySelector(`#grid button.cell") && pagejs.includes("document.querySelectorAll('#counts tbody tr.current')"));
  const relNotes = [...md.matchAll(/note:\s*"([^"]*)"/g)].map((m) => m[1]);
  const relNums = relNotes.flatMap((n) => n.match(/\d+/g) || []);
  check(g, 'numbers in relates notes are declared (1806 here; 1915 from the related page)', relNums.every((x) => x === '1806' || (x === '1915' && read('src/content/strata/the-page-the-text-layer-lost.md').includes('1915'))), relNums.join(','));
  check(g, 'record.json anchor.computed carries the recomputed tallies', record.anchor.computed.includes(`${F.collatedAgree} of ${F.anchorRows}`) && record.anchor.computed.includes('under the union of all four keys') && record.anchor.computed.includes(`gives ${F.dliAgree}`) && record.anchor.agrees === true);
  // negatives: corrupt what the reader sees and the surface check must go red
  const corrupt = [
    ['a displayed figure (DLI tally 10 shown as 11)', html.replace('<span data-fig="dliAgree">10</span>', '<span data-fig="dliAgree">11</span>')],
    ['a new bare number in the prose', html.replace('<p class="small">Cells count', '<p class="small">In 1807 cells count')],
    ['a bare number after a tag', html.replace('<p class="small">Cells count', '<p class="small"><b>Note</b> 1807 cells count')],
    ['a citation to a page not in the record', html.replace('<span data-cite>p. 303</span>', '<span data-cite>p. 309</span>').replace('<span data-cite>p. 345</span>', '<span data-cite>p. 999</span>')],
    ['a figure number that does not exist', html.replace('at figure 25 an a', 'at figure 31 an a')],
  ];
  for (const [what, doctored] of corrupt) check(g, `negative: ${what} is caught`, surfaceProblems(doctored, F).probs.length > 0);
  const hc = [
    ['the headline (14 read as 15)', html.replace('matches all 14 of his glosses', 'matches all 15 of his glosses')],
    ['the meta description (10 read as 12)', html.replace('and with 10 in the damaged Wikimedia Commons scan, while 4 marks stay unexplained', 'and with 12 in the damaged Wikimedia Commons scan, while 4 marks stay unexplained')],
    ['the OG description (4 read as 5)', html.replace('leaves 4 marks unexplained across four witnesses', 'leaves 5 marks unexplained across four witnesses')],
  ];
  for (const [what, doctored] of hc) check(g, `negative: a corrupted ${what} is caught`, headProblems(doctored, F).length > 0);
}

// ============================================================ 3. choices
{
  const g = 'choices';
  const eff = E.choiceEffects(fable, keys, glosses);
  for (const c of eff) check(g, `choice ${c.id} changes ${c.affects.join('/')}`, c.live, c.moved.join(','));
  check(g, 'record.json declares exactly the engine CHOICES', JSON.stringify(record.choices.map((c) => [c.id, c.options, c.default, c.affects, c.inert])) === JSON.stringify(E.CHOICES.map((c) => [c.id, c.options, c.default, c.affects, c.inert])));
  for (const c of E.CHOICES) check(g, `the page has a labelled control for ${c.id}`, new RegExp(`<label for="ch-${c.id}"`).test(html) && html.includes(`id="ch-${c.id}"`));
  // negative: a choice whose options do not change anything must be reported dead
  const fake = { id: 'letterCount', options: ['symbols-with-B', 'symbols-with-B'], context: {}, affects: ['maxLetters'] };
  const outs = fake.options.map((o) => E.outputs(fable, keys, glosses, { [fake.id]: o }));
  check(g, 'negative: a choice with identical options is detected as inert', new Set(outs.map((x) => x.maxLetters)).size === 1);
  // the defaults the page and headline use
  check(g, 'the letter-count convention decides the p. 359 claim (4 without B, 5 with)', F['max-symbols-without-B'] === '4' && F['max-symbols-with-B'] === '5');
  check(g, 'the robust residue includes the DLI reading across 96 combinations and 1536 source-key runs', F.readingCombos === '96' && F.robustRuns === '1536' && E.READING_CHOICES.includes('dliFig21'));
}

// ============================================================ 4. planted fault
{
  const g = 'fault';
  const clean = E.tally(glosses, E.runFable(fable, keys, {}), keys);
  const d = clone(fable);
  d.figures[20].uncg.above = d.figures[20].uncg.above.replace('vef', 'vcf');
  const run = E.runFable(d, keys, {});
  const t = E.tally(glosses, run, keys);
  check(g, 'clean record: the collation has no conflict and the anchor closes', E.runFable(fable, keys, {}).conflicts === 0 && clean.agree === 14);
  check(g, 'planted: vef read as vcf in the UNCG copy makes figure 21 a witness conflict', run.flags.some((f) => f.fig === 21 && f.kind === 'witness-conflict') && run.conflicts === 1);
  check(g, 'planted: the same fault leaves Observation XXI unsettled and drops the tally', t.rows.find((r) => r.id === 'A7').verdict === 'unsettled' && t.agree === 13);
  const d2 = clone(fable);
  for (const w of ['oxford', 'uncg']) d2.figures[19][w].above = 'D Bsdf d';
  const t2 = E.tally(glosses, E.runFable(d2, keys, {}), keys);
  check(g, 'planted: losing -- n at figure 20 in both letterpress copies fails A9 and A10', ['A9', 'A10'].every((id) => t2.rows.find((r) => r.id === id).verdict === 'disagree'));
  const d3 = clone(fable); d3.figures[0].oxford.rule_after = false; d3.figures[0].uncg.rule_after = false;
  check(g, 'planted: one lost rule changes the rule count and fails A16', E.runFable(d3, keys, {}).rules === 29 && E.tally(glosses, E.runFable(d3, keys, {}), keys).rows.find((r) => r.id === 'A16').verdict === 'disagree');
  const d4 = clone(fable); d4.figures[2].plate.below = 'stR1x';
  check(g, 'planted: an st step at figure 3 on the plate removes that mark from the residue', !E.residue(d4, keys, {}).ids.includes('3:s') && E.residue(fable, keys, {}).ids.includes('3:s'));
}

// ============================================================ 5. refusals
{
  const g = 'refusal';
  const quotes = new Map(keys.prose_rules.map((r) => [r.id, r.quote]));
  const r1 = E.notate('To be or not to be', fable);
  check(g, 'typed text outside the record is refused, citing p. 368', r1.refused && r1.kind === 'typed-text' && quotes.get('dictate') === r1.quote);
  check(g, 'a line of the fable is not refused (it returns its figure)', E.notate('With sudden start the miser wakes!', fable).fig === 3);
  const r2 = E.refuse('transition');
  check(g, 'a transition between figures is refused, quoting p. 368', r2.refused && quotes.get('transitions') === r2.quote);
  const r3 = E.refuse('voice');
  check(g, 'voice marks are refused, quoting p. 372', r3.refused && quotes.get('no-voice').startsWith(r3.quote));
  const r4 = E.decode('tr', 'motion', keys, 'union');
  check(g, 'an undefined letter (tr as a motion) is refused, never guessed, and every key lacks it', r4.refused && r4.missingIn.length === 4 && !r4.readings);
  check(g, 'a defined letter (sh as a motion) is decoded', !E.decode('sh', 'motion', keys, 'union').refused);
  check(g, 'the step s is refused under every key', E.decode('s', 'step', keys, 'union').refused && E.decode('s', 'step', keys, 'union').missingIn.length === 4);
  const r5 = E.callError(fable, keys, 21, 'vcf');
  check(g, 'calling a single-witness mark (vcf, DLI only) Austin\'s error is refused', r5.refused && r5.kind === 'single-witness-error');
  check(g, 'calling a plate-only form (Br at figure 16) Austin\'s error is refused', E.callError(fable, keys, 16, 'Br').refused);
  check(g, 'a mark printed in every copy (sR1x at figure 3) is not refused', !E.callError(fable, keys, 3, 'sR1x').refused);
  check(g, 'single-witness refusal uses parsed witness records, not substring matching', pagejs.includes("callError(state.data.fable, state.data.keys") && read(P + 'engine.js').includes("method: 'parsed-witness-records'") && r5.method === 'parsed-witness-records');
  const k2 = clone(keys); k2.keys.synoptical.entries.push({ slot: 'manner', sym: 'tr', word: 'trembling', page: 364, as_printed: 'planted' });
  check(g, 'negative: a key doctored to define tr stops the refusal (the refusal reads the key)', !E.decode('tr', 'motion', k2, 'union').refused);
  for (const id of ['refNotateBtn', 'refTransitionBtn', 'refVoiceBtn', 'refErrorBtn', 'refOut']) check(g, `the page carries the refusal control ${id}`, html.includes(`id="${id}"`));
  check(g, 'the witness error control explains the limit of its presence check', html.includes('it does not decide that Austin made an error'));
}

// ============================================================ 6. provenance
{
  const g = 'provenance';
  const readme = fs.existsSync(RS + 'README.md') ? read(RS + 'README.md') : '';
  const files = Object.keys(record.files || {});
  check(g, 'record.json lists every data file the page loads', ['fable.json', 'keys.json', 'glosses.json'].every((f) => files.includes(f)) && (!ch23 || files.includes('ch23.json')));
  for (const f of files) {
    const h = sha(fs.readFileSync(P + f));
    check(g, `${f} SHA-256 matches record.json`, h === record.files[f], h);
    check(g, `${f} SHA-256 is in the research README`, readme.includes(h));
  }
  check(g, 'record.sha256 is fable.json, a file the page ships', record.record.sha256 === sha(fs.readFileSync(P + 'fable.json')));
  const pinned = /const RECORD_SHA256 = '([0-9a-f]{64})'/.exec(pagejs);
  check(g, 'page.js pins the exact shipped record.json digest', pinned && pinned[1] === sha(fs.readFileSync(P + 'record.json')));
  check(g, 'the unshipped chapter XXIII fallback is not described as a data file', !fs.existsSync(P + 'ch23.json') && !html.includes('ch23.json') && !licence.includes('ch23.json') && !read(RS + 'readme-hashes.mjs').includes("'ch23.json'"));
  for (const img of fs.readdirSync(P + 'img')) check(g, `img/${img} SHA-256 is in the research README`, readme.includes(sha(fs.readFileSync(P + 'img/' + img))));
  const blindHash = sha(fs.readFileSync(RS + 'data/blind-second-reading.json'));
  check(g, 'the blinded second reading is pinned in the README', readme.includes(blindHash));
  check(g, 'negative: one changed byte changes the hash', sha(Buffer.concat([fs.readFileSync(P + 'fable.json'), Buffer.from(' ')])) !== record.files['fable.json']);
}

// ============================================================ 7. page hygiene (exit code only)
{
  const g = 'hygiene';
  check(g, 'closing tags present', /<\/script>\s*<\/body>\s*<\/html>\s*$/.test(html));
  check(g, 'the only inline script is the JSON-LD', [...html.matchAll(/<script(?![^>]*src=)([^>]*)>/g)].every((m) => m[1].includes('application/ld+json')));
  for (const f of ['engine.js', 'render.js', 'page.js', 'figures.js']) {
    const src = read(P + f);
    check(g, `${f} makes no request to another host`, !/https?:\/\//.test(src.replace(/\/\/.*$/gm, '')), '');
    check(g, `${f} carries no em dash`, !src.includes('—'));
  }
  check(g, 'render.js does not import the engine (it computes nothing it reports)', !/import[^;]*engine/.test(read(P + 'render.js')));
  check(g, 'the selected copy badge is a live status region', /id="witnessBadge"[^>]*role="status"[^>]*aria-live="polite"/.test(html));
  check(g, 'long controls wrap within the viewport', /\.btn\{[^}]*max-width:100%[^}]*white-space:normal[^}]*overflow-wrap:anywhere/.test(html));
  check(g, 'record.json cell is theatre-dance', record.cell === 'theatre-dance');
  const total = fs.readdirSync(P + 'img').reduce((n, f) => n + fs.statSync(P + 'img/' + f).size, 0);
  check(g, 'shipped images stay small (under 1.2 MB in all)', total < 1.2e6, String(total));
}

// ============================================================ report
const cell = (grp) => results.filter((r) => r.group === grp).length > 0 && results.filter((r) => r.group === grp).every((r) => r.ok);
const ledger = {
  anchor_reproduced_by_engine: cell('anchor'),
  rendered_figures_asserted: cell('surface'),
  choices_are_live: cell('choices'),
  planted_fault_caught: cell('fault'),
  refusal_asserted: cell('refusal'),
  provenance_pinned: cell('provenance'),
};
const failed = results.filter((r) => !r.ok);
if (LEDGER) {
  for (const [k, v] of Object.entries(ledger)) console.log(`${k}=${v}`);
} else {
  for (const r of results) console.log(`${r.ok ? 'ok  ' : 'FAIL'} [${r.group}] ${r.name}${r.ok || !r.detail ? '' : '  :: ' + r.detail}`);
  console.log(`\n${results.length - failed.length} of ${results.length} assertions passed`);
  for (const [k, v] of Object.entries(ledger)) console.log(`${k}=${v}`);
}
process.exit(failed.length ? 1 : 0);
