#!/usr/bin/env node
// verify-your-owne-side.mjs
//
// Recomputes every figure and verdict the page shows from the same modules the page loads, and fails
// on any disagreement. Each group carries negative controls: a control doctors a COPY of a record
// (or of the page's HTML) and runs the SAME unmodified code, and passes only if the doctoring is caught.
//
//   node research/your-owne-side/verify-your-owne-side.mjs
//   node research/your-owne-side/verify-your-owne-side.mjs --ledger
//
// It never writes a file. collation.json and record.json are written by make-collation.mjs and
// make-record.mjs.

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.resolve(HERE, '../..');
const SLUG = 'your-owne-side';
const PUB = path.join(ROOT, 'public/strata', SLUG);

const E = await import(path.join(PUB, 'engine.js'));
const C = await import(path.join(PUB, 'collate.js'));
const F = await import(path.join(PUB, 'figures.js'));
const T = await import(path.join(HERE, 'headline.mjs'));

const LEDGER = process.argv.includes('--ledger');
const results = [];
function check(group, id, ok, detail = '') {
  results.push({ group, id, ok: !!ok, detail });
  if (!LEDGER) console.log(`${ok ? 'ok  ' : 'FAIL'} [${group}] ${id}${detail ? `  (${detail})` : ''}`);
}
function refuses(fn, code) {
  try { fn(); return false; } catch (e) { return e instanceof E.Refusal && (!code || e.code === code); }
}
const sha = (buf) => crypto.createHash('sha256').update(buf).digest('hex');
const readJSON = (f) => JSON.parse(fs.readFileSync(f, 'utf8'));
const clone = (x) => structuredClone(x);
const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
const mod = (a, n) => ((a % n) + n) % n;
const partner = (d) => (d[0] === 'M' ? 'W' : 'M') + d.slice(1);
const pairKey = (a, b) => [a, b].sort().join('-');

const FILES = ['playford-1651.json', 'sharp-part2-1913.json', 'readings.json', 'collation.json'];
const tx = readJSON(path.join(PUB, 'playford-1651.json'));
const sharp = readJSON(path.join(PUB, 'sharp-part2-1913.json'));
const readings = readJSON(path.join(PUB, 'readings.json'));
const collation = readJSON(path.join(PUB, 'collation.json'));
const record = readJSON(path.join(PUB, '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(path.join(ROOT, 'src/content/strata', `${SLUG}.md`), 'utf8');
const readme = fs.readFileSync(path.join(HERE, 'README.md'), 'utf8');
const uadRaw = readJSON(path.join(HERE, 'data/raw/upadouble-transcriptions.json'));
const D0 = { tx, sharp, readings, collation };

// =============================================================================================
// provenance
// =============================================================================================
{
  const G = 'provenance';
  for (const f of FILES) {
    const buf = fs.readFileSync(path.join(PUB, f));
    const h = sha(buf);
    check(G, `provenance:sha256-matches ${f} = record.json`, record.files && record.files[f] === h, h.slice(0, 16));
    check(G, `provenance:sha256-in-readme ${f}`, readme.includes(h));
    const copy = path.join(HERE, 'data', f);
    check(G, `provenance:research-copy-identical ${f}`, fs.existsSync(copy) && sha(fs.readFileSync(copy)) === h);
    check(G, `control: one appended byte changes the hash of ${f}`, sha(Buffer.concat([buf, Buffer.from(' ')])) !== record.files[f]);
  }
  check(G, 'provenance:record.sha256 is the primary extract', record.record.sha256 === record.files['playford-1651.json']);
  const rawDir = path.join(HERE, 'data/raw');
  for (const f of fs.readdirSync(rawDir)) {
    const h = sha(fs.readFileSync(path.join(rawDir, f)));
    check(G, `provenance:raw-source-in-readme ${f}`, readme.includes(h), h.slice(0, 16));
  }
  check(G, 'provenance:the Commons PDF hash in the transcription is in the README', readme.includes(tx.witness.sha256));
  for (const [pid, p] of Object.entries(uadRaw.pages)) check(G, `provenance:Up a Double page hash in README (${pid})`, readme.includes(p.sha256_html));
  const lic = fs.readFileSync(path.join(PUB, 'LICENCE.txt'), 'utf8');
  for (const needle of ['commons.wikimedia.org', 'archive.org/details/countrydancebook12shar', 'colinhume.com', 'playforddances.com', 'NonCommercial', 'upadouble.info', 'Attribution 4.0']) {
    check(G, `provenance:LICENCE.txt names ${needle}`, lic.includes(needle));
  }
  check(G, 'provenance: Commons terms are not frozen to the stale 1931 threshold', !readme.includes('before 1931') && !lic.includes('before 1 January 1931'));
}

// =============================================================================================
// anchor: the same engine the page uses, on the frozen record, against printed values
// =============================================================================================
const nc = E.runNewcastle(tx, E.DEFAULTS);
const grid = E.nonesuchGrid(tx, E.DEFAULTS);
const cellOf = (g, l, h) => g.flat().find((c) => c.leftHand === l && c.singleHey === h);
const circ = cellOf(grid, 'own-place', 'circular-progressive-handing');
const corner = cellOf(grid, 'as-faced', 'corner-hey');
{
  const G = 'anchor';
  // --- the book's own statements in Newcastle, with the pairs parsed straight from the printed words
  const seg2B1 = tx.pages.newcastle.rows[1].B[0].as_written;
  const m = seg2B1.match(/The firſt man and (\d)\. Wo\. take hands and meet,\s*the firſt Wo\. and (\d)\. man/);
  check(G, 'anchor: the printed pairs parse from Newcastle p. 77, second row', !!m);
  const named = nc.statements.filter((s) => s.id === 'named-pair');
  check(G, `anchor:book the first man stands beside woman ${m && m[1]}`, !!m && named.some((s) => s.pair.join() === `M1,W${m[1]}` && s.holds));
  check(G, `anchor:book the first woman stands beside man ${m && m[2]}`, !!m && named.some((s) => s.pair.join() === `W1,M${m[2]}` && s.holds));
  const contrary = nc.statements.find((s) => s.id === 'contrary');
  const home = nc.statements.find((s) => s.id === 'home');
  check(G, "anchor:book 'Now every man is with his owne Wo. in the Co. place.' holds", contrary && contrary.holds);
  check(G, "anchor:book 'So each falls into his place as at firſt.' holds", home && home.holds);
  const terminal = nc.snapshots.find((s) => s.label === 'nc3B-3').pos;
  const immutableHome = Object.freeze({ ...nc.home });
  const terminalHome = Object.entries(immutableHome).every(([d, station]) => terminal[d] === station);
  check(G, 'anchor: every terminal Newcastle position equals the immutable starting map', terminalHome);
  check(G, 'anchor: no line of Newcastle failed to dance', nc.failures.length === 0, `${nc.failures.length} failures`);
  // recheck the contrary place geometrically from the final state after part 3A, without the engine's evaluator
  const snap3A = nc.snapshots.find((s) => s.label === 'nc3A-3').pos;
  const geo = ['1', '2', '3', '4'].every((c) => mod(snap3A['M' + c] - nc.home['M' + c], 8) === 4 && mod(snap3A['W' + c] - snap3A['M' + c], 8) === mod(nc.side, 8));
  check(G, 'anchor: independent geometry agrees every couple is together four stations round from home', geo);
  const bad = clone(tx);
  bad.pages.newcastle.rows[1].B[0].as_written = seg2B1.replace('3. Wo.', '2. Wo.');
  check(G, "control: a transposed ordinal ('3. Wo.' read as '2. Wo.') fails the printed pair", E.runNewcastle(bad, E.DEFAULTS).statements.filter((s) => s.id === 'named-pair').some((s) => !s.holds));

  // --- Sharp 1913, Newcastle: names the 1651 text never prints
  const sc = E.sharpNewcastleChecks(nc, sharp);
  check(G, 'anchor:sharp-1913 all of Sharp\'s Newcastle statements reproduced', sc.length === 7 && sc.every((c) => c.holds), `${sc.filter((c) => c.holds).length} of ${sc.length}`);
  for (const c of sc) check(G, `anchor:sharp-1913 ${c.id}`, c.holds, c.text.slice(0, 60));
  const diag = sharp.newcastle.diagram.ring_clockwise_from_top.map((s) => (s.startsWith('circle') ? 'M' : 'W') + s.split(' ')[1]);
  const byStation = Object.fromEntries(Object.entries(nc.home).map(([d, s]) => [s, d]));
  const engineCW = [0, 1, 2, 3, 4, 5, 6, 7].map((k) => byStation[mod(nc.home.M1 - k, 8)]);
  const i1 = diag.indexOf('M1');
  check(G, "anchor: the engine's home ring, read clockwise from man 1, is Sharp's p. 58 diagram (circles men, squares women)", same(engineCW, [...diag.slice(i1), ...diag.slice(0, i1)]), engineCW.join(' '));
  const ccwLines = ['g0', 'g1', 'g2', 'g3'].map((g) => E.sharpNewcastleChecks(E.runNewcastle(tx, { coupleNumbering: 'counter-clockwise', wallSplit: g }), sharp).find((c) => c.id === 'nc-p3-B1').holds);
  check(G, "control: numbered counter-clockwise (woman on the man's right), no split gives Sharp's lines of four", ccwLines.every((x) => !x));
  const cwLines = ['g0', 'g1', 'g2', 'g3'].map((g) => E.sharpNewcastleChecks(E.runNewcastle(tx, { wallSplit: g }), sharp).find((c) => c.id === 'nc-p3-B1').holds);
  check(G, 'anchor: numbered clockwise, exactly one split gives them', cwLines.filter(Boolean).length === 1);
  const bs = clone(sharp);
  const row = bs.newcastle.rows.find((r) => r.id === 'nc-p3-B1');
  row.text = row.text.replace('first man and third woman', 'first man and second woman');
  check(G, "control: Sharp's line doctored ('third woman' to 'second woman') is not reproduced", !E.sharpNewcastleChecks(nc, bs).find((c) => c.id === 'nc-p3-B1').holds);

  // --- Sharp's Figure 20, the progressive circular hey
  const h = E.progressiveCircularHey(['1', '2', '3', '4', '5', '6', '7', '8'], [1, -1, -1, -1, -1, 1, 1, 1]);
  const counts = h.changes.map((c) => c.passes.length);
  const WN = { one: 1, two: 2, three: 3, four: 4 };
  const st = sharp.conventions.fig20_start.text;
  const firstFour = [...st.matchAll(/\b(one|two|three|four) pairs?\b/g)].map((x) => WN[x[1]]);
  check(G, "anchor:fig20 'one pair only ... two pairs ... three pairs ... four pairs'", same(counts.slice(0, 4), firstFour), counts.join(','));
  const endWords = sharp.conventions.fig20_end.text.match(/occupy the same time i\.e\. (\w+) changes/);
  const k = endWords ? WN[endWords[1]] : 0;
  check(G, "anchor:fig20 'the initial and final movements thus occupy the same time i.e. four changes'", k === 4 && same(counts.slice(-k), firstFour.slice().reverse()) && counts.slice(k, -k).every((x) => x === 4));
  const p2 = st.match(/second by two pairs Nos\. (\d) and (\d), and Nos\. (\d) and (\d)/);
  check(G, "anchor:fig20 second change 'Nos. 1 and 3, and Nos. 2 and 8'", !!p2 && same(h.changes[1].passes.map((p) => pairKey(p.a, p.b)).sort(), [pairKey(p2[1], p2[2]), pairKey(p2[3], p2[4])].sort()));
  check(G, 'anchor:fig20 diagram A (after the fourth change) reproduced', same(h.changes[3].after, sharp.conventions.fig20_diagram_a.clockwise_from_top), h.changes[3].after.join(''));
  check(G, 'anchor:fig20 diagram B (end of a circuit) reproduced', same(h.changes[7].after, sharp.conventions.fig20_diagram_b.clockwise_from_top), h.changes[7].after.join(''));
  const stopText = sharp.conventions.fig20_end.text;
  const stopsWant = [stopText.match(/Nos\. (\d) and (\d), upon reaching/).slice(1, 3), ...[...stopText.match(/following order, Nos\. ([\d and,]+)\./)[1].matchAll(/(\d) and (\d)/g)].map((x) => [x[1], x[2]])].map((p) => p.sort().join(''));
  const stopsGot = [];
  let prev = [];
  for (const c of h.changes) { const nw = c.stopped.filter((d) => !prev.includes(d)); if (nw.length) stopsGot.push(nw.sort().join('')); prev = c.stopped; }
  check(G, "anchor:fig20 stopping order 'Nos. 1 and 2 ... Nos. 3 and 8, 4 and 7, 5 and 6'", same(stopsGot, stopsWant), stopsGot.join(' '));
  const eight = WN[(sharp.conventions.circuit.text.match(/there will be (\w+) simultaneous passings/) || [])[1]] || (/eight simultaneous/.test(sharp.conventions.circuit.text) ? 8 : 0);
  const perDancer = {};
  for (const c of h.changes) for (const p of c.passes) { perDancer[p.a] = (perDancer[p.a] || 0) + 1; perDancer[p.b] = (perDancer[p.b] || 0) + 1; }
  check(G, "anchor:fig20 every dancer makes one circuit of 'eight ... changes'", eight === 8 && Object.values(perDancer).every((x) => x === 8));
  check(G, 'anchor: the Nonesuch circular cell is this same hey (same pass count and length)', circ.summary.passes === counts.reduce((a, b) => a + b, 0) && circ.count === h.changes.length);
  const hFlip = E.progressiveCircularHey(['1', '2', '3', '4', '5', '6', '7', '8'], [-1, 1, 1, 1, 1, -1, -1, -1]);
  check(G, 'control: the hey run with every direction reversed does not reproduce diagram A', !hFlip.changes[3] || !same(hFlip.changes[3].after, sharp.conventions.fig20_diagram_a.clockwise_from_top));
  const badDiag = clone(sharp.conventions.fig20_diagram_a.clockwise_from_top);
  [badDiag[0], badDiag[1]] = [badDiag[1], badDiag[0]];
  check(G, 'control: a diagram A with two numbers transposed is not reproduced', !same(h.changes[3].after, badDiag));

  // --- Sharp's Figure 21, the straight hey
  const sh = E.straightHey(['1', '2', '3', '4', '5', '6', '7', '8'], 2);
  const neut = sharp.conventions.fig21_neutrals.text.match(/two neutrals, Nos\. (\d) and (\d)/);
  check(G, "anchor:fig21 'in the second change, there will be two neutrals, Nos. 2 and 7'", !!neut && same(sh.changes[1].neutral.slice().sort(), [neut[1], neut[2]].sort()));

  // --- Pfitzinger's corner hey
  const ord = (x) => x.replace(/(st|nd|rd|th)$/, '');
  function pfPairs(line) {
    const out = [];
    let mm = line.match(/(\d+(?:st|nd|rd|th)) Man and (\d+(?:st|nd|rd|th)) Man change places/);
    if (mm) out.push(['M' + ord(mm[1]), 'M' + ord(mm[2])]);
    mm = line.match(/the (\d+(?:st|nd|rd|th)) and (\d+(?:st|nd|rd|th)) Women doing the same/);
    if (mm) out.push(['W' + ord(mm[1]), 'W' + ord(mm[2])]);
    if (/the other Couples doing the same/.test(line)) {
      const used = new Set(out.flat().map((d) => d.slice(1)));
      const others = ['1', '2', '3', '4'].filter((c) => !used.has(c));
      out.push(['M' + others[0], 'M' + others[1]], ['W' + others[0], 'W' + others[1]]);
    }
    mm = line.match(/the (\d+(?:st|nd|rd|th)) Couple doing the same/);
    if (mm) out.push(['M' + ord(mm[1]), 'W' + ord(mm[1])]);
    return out.map((p) => pairKey(p[0], p[1])).sort();
  }
  const pf = readings.pfitzinger.lines;
  const ch = (t, n) => t.filter((x) => x.change === n).map((x) => pairKey(x.a, x.b)).sort();
  check(G, "anchor:pfitzinger A3 1-2 'change places by right hand' pairs", same(ch(corner.trace, 1), pfPairs(pf['IV-A3-1-2'])) && corner.trace.filter((x) => x.change === 1).every((x) => x.hand === 'right'), ch(corner.trace, 1).join(' '));
  check(G, "anchor:pfitzinger A3 3-4 'by left hand' pairs, the 3rd Couple crossing", same(ch(corner.trace, 2), pfPairs(pf['IV-A3-3-4'])) && corner.trace.filter((x) => x.change === 2).every((x) => x.hand === 'left'), ch(corner.trace, 2).join(' '));
  const ns = E.runNonesuch(tx, { leftHand: 'as-faced', singleHey: 'corner-hey' });
  check(G, "anchor:pfitzinger A2 'slip to his left into his Partner's place'", ns.entering.M1 === 'women-1' && ns.entering.W1 === 'men-1' && /slip to his left into his Partner/.test(pf['IV-A2-1-2']));
  check(G, "anchor:pfitzinger A3 5-16 'until all are back in their original places' after sixteen bars", Object.entries(ns.hey.paths).every(([d, p]) => p[p.length - 1] === `${E.ownSideOf(d)}-${d.slice(1)}`) && /until all are back in their original places/.test(pf['IV-A3-5-16']));
  const badPf = pf['IV-A3-1-2'].replace('2nd Man change', '3rd Man change');
  check(G, "control: Pfitzinger's line doctored ('2nd Man' to '3rd Man') no longer matches", !same(ch(corner.trace, 1), pfPairs(badPf)));
  const bottom = corner.trace.filter((x) => x.place === 'bottom');
  check(G, "anchor:hume 'cross with your partner at the bottom': every bottom crossing is between partners", bottom.length === 4 && bottom.every((x) => partner(x.a) === x.b) && /cross with your partner at the bottom/.test(readings.hume.corner.text));

  // --- Sharp's Part I tables of duple minor-set rounds
  const parseRow = (r) => ({ order: [...r.matchAll(/[A-H]/g)].map((x) => x[0]), sets: [...r.matchAll(/\[(\w) (\w)\]/g)].map((x) => x[1] + x[2]) });
  for (const [tbl, letters] of [[sharp.conventions.rounds_table, 'ABCDEFG'], [sharp.conventions.rounds_table_even, 'ABCDEFGH']]) {
    const n = tbl.first_row + tbl.rows.length - 1;
    const run = E.dupleMinor(letters.split(''), n);
    const ok = tbl.rows.every((r, i) => {
      const round = tbl.first_row + i;
      const want = parseRow(r);
      const before = round === 1 ? letters.split('') : run.log[round - 2].after;
      return same(before, want.order) && same(run.log[round - 1].sets.map((s) => s.join('')), want.sets);
    });
    check(G, `anchor:sharp Part I p. 21 table for ${letters.length} couples, rows ${tbl.first_row} to ${n}, order and minor-sets`, ok);
  }
  const badRow = clone(sharp.conventions.rounds_table.rows);
  badRow[3] = badRow[3].replace('[B D]', '[B E]');
  const run7 = E.dupleMinor('ABCDEFG'.split(''), 9);
  check(G, 'control: a doctored table row is not reproduced', run7.log[3].sets.map((s) => s.join('')).join() !== parseRow(badRow[3]).sets.join());

  // --- Up a Double's 4312 from its 152 bars and Sharp's own music column
  const s5 = E.sharpNonesuch(sharp, readings, { sharpRounds: 'from-bars' });
  const uad = readings.upadouble.nonesuch_sharp;
  check(G, "anchor:uad the structured fields match Up a Double's own sentence", uad.text.includes(`permuted by: ${uad.permutation}`) && uad.text.includes(`lasts ${uad.bars} bars`));
  let fixed = 0, per = 0;
  for (const p of sharp.nonesuch.parts) {
    const strains = {};
    let cur = null;
    for (const r of p.rows) {
      if (r.music) cur = r.music;
      for (const s of cur.split(' and ')) {
        const end = r.bars ? Number(r.bars.match(/(\d+)\s*$/)[1]) : 0;
        strains[s] = Math.max(strains[s] || 0, end);
      }
    }
    const bars = Object.entries(strains).reduce((a, [s, v]) => a + (v || 8), 0);
    if (p.subheading && /minor-set/i.test(p.subheading)) per += bars; else fixed += bars;
  }
  check(G, `anchor: Sharp's bar column, summed independently: ${fixed} fixed bars and ${per} a round`, fixed === s5.bars.fixed && per === s5.bars.perRound);
  check(G, `anchor:uad ${uad.bars} bars is ${(uad.bars - fixed) / per} rounds`, s5.rounds === (uad.bars - fixed) / per && s5.totalBars === uad.bars);
  check(G, `anchor:uad the engine reproduces the permutation ${uad.permutation}`, s5.order === uad.permutation, s5.order);
  check(G, 'anchor: the fifth part hey returns every dancer to its place', s5.heyReturns);
  const calls = uad.second_part_calls;
  const roundOf = { 'II.A2': 2, 'II.AB3': 3, 'II.AB4': 4, 'II.AB5': 5 };
  let callsOk = true;
  for (const c of calls) {
    const tag = c.split(' ')[0];
    if (!(tag in roundOf)) continue;
    const pairs = [];
    const m1 = c.match(/(\d)s repeat with (\d)s/);
    if (m1) pairs.push([m1[1], m1[2]]);
    const m2 = c.match(/as (\d)s start with (\d)s/);
    if (m2) pairs.push([m2[1], m2[2]]);
    const m3 = c.match(/slip down just below (\d)s/);
    if (m3) pairs.push(['1', m3[1]]);
    const want = pairs.map((p) => p.sort().join('')).sort();
    const got = s5.log[roundOf[tag] - 1].sets.map((s) => s.slice().sort().join('')).sort();
    if (!same(want, got)) callsOk = false;
  }
  check(G, "anchor:uad the call sheet's minor-sets for rounds 2 to 5 match the engine's rounds", callsOk);
  const s7 = E.sharpNonesuch(sharp, readings, { sharpRounds: 'usual-practice' });
  check(G, "anchor: Sharp's usual practice takes 7 rounds and ends 1423", s7.rounds === 7 && s7.order === '1423' && s7.totalBars === fixed + 7 * per);
  const badUad = clone(readings);
  badUad.upadouble.nonesuch_sharp.bars = 150;
  check(G, 'control: 150 bars is not a whole number of rounds, and the engine refuses', refuses(() => E.sharpNonesuch(sharp, badUad, {}), 'bars-do-not-fit'));
  const badBars = clone(sharp);
  badBars.nonesuch.parts[1].rows[1].bars = badBars.nonesuch.parts[1].rows[1].bars.replace('8', '6');
  let badOrder = null;
  try { badOrder = E.sharpNonesuch(badBars, readings, {}).order; } catch (e) { badOrder = 'refused'; }
  check(G, "control: Sharp's second part doctored to 6 bars a half no longer gives 4312", badOrder !== uad.permutation, String(badOrder));

  // --- A la Mode de France's handing order
  const amdf = E.aModeHandingOrder(tx);
  const fp = E.firstPassesOf(circ.trace, 'M1', 3);
  const match = (xs) => xs.length === 3 && xs.every((x, i) => x.dancer === amdf[i].dancer && (!amdf[i].hand || amdf[i].hand === x.hand));
  check(G, "anchor: the circular hey hands 'his Wo. ... his left hand to the 2. Wo. the right to the 3.'", match(fp), fp.map((x) => `${x.dancer}:${x.hand}`).join(' '));
  check(G, 'control: the corner hey does not hand in that order', !match(E.firstPassesOf(corner.trace, 'M1', 3)));
}

// =============================================================================================
// the second layer: the grid on Nonesuch's last block
// =============================================================================================
{
  const G = 'layer2';
  const v = (g) => ['own-place', 'as-faced'].flatMap((l) => ['circular-progressive-handing', 'corner-hey'].map((h) => (cellOf(g, l, h).owneSide.holds ? 1 : 0))).join('');
  check(G, 'grid: the two held readings pass and the two mixed readings fail', v(grid) === '1001', v(grid));
  check(G, 'grid: each column keeps one encounter trace whatever the slip', grid[0][0].key === grid[1][0].key && grid[0][1].key === grid[1][1].key);
  check(G, 'grid: the two heys give different traces', grid[0][0].key !== grid[0][1].key);
  const cs = circ.summary, ks = corner.summary;
  check(G, 'grid: circular hey 11 changes, 32 passes, none same-sex, each of 16 man-woman pairs met twice, 4 top crossings', circ.count === 11 && cs.passes === 32 && cs.sameSex === 0 && cs.distinctPairs === 16 && cs.maxMeetings === 2 && cs.crossTop === 4);
  check(G, 'grid: corner hey 8 changes, 28 passes (every one of the 28 pairs of eight dancers once), 12 same-sex, no top crossing', corner.count === 8 && ks.passes === 28 && ks.distinctPairs === (8 * 7) / 2 && ks.maxMeetings === 1 && ks.sameSex === 12 && ks.crossTop === 0);
  const mixed = [cellOf(grid, 'own-place', 'corner-hey'), cellOf(grid, 'as-faced', 'circular-progressive-handing')];
  check(G, 'grid: in both mixed readings every dancer finishes on the wrong side', mixed.every((c) => c.owneSide.per.every((p) => !p.endsOwn)));
  check(G, "grid: sensitivity, mirror convention: only the circular column passes", v(E.nonesuchGrid(tx, { sideConvention: 'mirror' })) === '1010');
  check(G, 'grid: sensitivity, corner hey run until the hey start is restored: only the own-place row passes', v(E.nonesuchGrid(tx, { cornerLength: 'until-hey-start-restored' })) === '1100');
  check(G, "grid: sensitivity, the stricter 'only up' test: only Sharp's reading passes", v(E.nonesuchGrid(tx, { owneSideTest: 'only-up-after-last-crossing' })) === '1000');
  // the slip, from vectors, without the engine's helper: facing f, left is f turned a quarter counter-clockwise
  const left = ([x, y]) => [-y, x];
  const manLeftX = left([0, -1])[0];
  const womanLeftX = left([0, 1])[0];
  const menX = -1;
  check(G, "grid: independent geometry, woman on the man's right: 'to the left hand' as faced sends each dancer to the partner's side", manLeftX === -menX && womanLeftX === menX && E.leftOfFacing('down', 'woman-on-mans-right') === 'women' && E.leftOfFacing('up', 'woman-on-mans-right') === 'men');
  const lh = E.sharpLeftHand(sharp);
  check(G, "grid: Sharp's fourth part is the man's own left, his fifth part the man's own right", lh.manFacing === 'down' && lh.partIV.hand === 'his own left' && lh.partV.hand === 'his own right');
  const fakePath = { M1: ['men-1', 'men-2', 'men-3', 'men-4', 'women-4', 'women-3', 'women-2', 'women-1'] };
  check(G, "control: the side test fails a man who comes up the women's side", !E.owneSideCheck(fakePath, 'own-side-after-last-crossing').holds);
  const goodPath = { M1: ['women-1', 'women-2', 'women-3', 'women-4', 'men-4', 'men-3', 'men-2', 'men-1'] };
  check(G, "control: the side test passes a man who comes up the men's side", E.owneSideCheck(goodPath, 'own-side-after-last-crossing').holds);
}

// =============================================================================================
// choices: each is a real parameter, and each moves what it says it moves
// =============================================================================================
{
  const G = 'choices';
  const recChoices = record.choices.map((c) => ({ id: c.id, options: c.options, default: c.default, affects: c.affects, inert: !!c.inert }));
  const engChoices = E.CHOICES.map((c) => ({ id: c.id, options: c.options, default: c.default, affects: c.affects, inert: !!c.inert }));
  check(G, 'choices: record.json declares exactly the engine CHOICES', same(recChoices, engChoices));
  const verdict = (o, l, h) => cellOf(E.nonesuchGrid(tx, o), l, h).owneSide.holds;
  const OUT = {
    leftHand: (o) => JSON.stringify(E.runNonesuch(tx, o).entering) + verdict(o, o.leftHand, o.singleHey),
    singleHey: (o) => E.traceKey(E.runNonesuch(tx, o).hey.trace),
    sideConvention: (o) => JSON.stringify(E.runNonesuch(tx, { ...o, leftHand: 'as-faced' }).entering),
    owneSideTest: (o) => verdict(o, 'as-faced', 'corner-hey'),
    cornerLength: (o) => verdict(o, 'as-faced', 'corner-hey'),
    yourWe: (o) => E.runNewcastle(tx, o).statements.find((s) => s.id === 'contrary').holds,
    coupleNumbering: (o) => E.sharpNewcastleChecks(E.runNewcastle(tx, o), sharp).find((c) => c.id === 'nc-p3-B1').holds,
    wallSplit: (o) => E.runNewcastle(tx, o).encounters.filter((e) => e.verb === 'change places with opposite').map((e) => pairKey(e.a, e.b)).join(' '),
    sharpRounds: (o) => E.sharpNonesuch(sharp, readings, o).order,
  };
  for (const c of E.CHOICES.filter((x) => !x.inert)) {
    const outs = c.options.map((opt) => OUT[c.id]({ ...E.DEFAULTS, [c.id]: opt }));
    check(G, `choices:each-changes-an-output ${c.id} moves ${c.affects.join(', ')}`, new Set(outs).size > 1, outs.map((x) => String(x).slice(0, 24)).join(' | '));
  }
  const encKey = (e) => `${e.part || e.block}|${e.strain || ''}|${e.seg}|${e.verb}|${e.a}|${e.b}`;
  const placesAndMeetings = (o) => {
    const n = E.runNewcastle(tx, o);
    const parts = [JSON.stringify(n.snapshots.map((s) => s.pos)), n.encounters.map(encKey).join(';')];
    for (const h of ['circular-progressive-handing', 'corner-hey']) {
      const s = E.runNonesuch(tx, { ...o, singleHey: h });
      parts.push(JSON.stringify(s.entering), JSON.stringify(s.hey.paths), E.traceKey(s.hey.trace), s.encounters.map(encKey).join(';'));
    }
    return parts.join('#');
  };
  const SECONDARY = {
    siding: (o) => JSON.stringify(E.sidingOutput(readings, sharp, o.siding)),
    set: (o) => JSON.stringify(E.setOutput(tx, sharp, o.set)),
    arming: (o) => JSON.stringify(E.armingOutput(tx, sharp, o.arming)),
  };
  for (const c of E.CHOICES.filter((x) => x.inert)) {
    const pm = c.options.map((opt) => placesAndMeetings({ ...E.DEFAULTS, [c.id]: opt }));
    const sec = c.options.map((opt) => SECONDARY[c.id]({ ...E.DEFAULTS, [c.id]: opt }));
    check(G, `choices: ${c.id} is inert on places and encounters in both dances`, new Set(pm).size === 1);
    check(G, `choices: ${c.id} is live on its drawn output (${c.affects.join(', ')})`, new Set(sec).size > 1, sec.map((x) => x.slice(0, 50)).join(' | '));
    check(G, `choices: record.json marks ${c.id} inert`, record.choices.find((x) => x.id === c.id).inert === true);
  }
  const ringMirror = E.runNewcastle(tx, { ...E.DEFAULTS, sideConvention: 'mirror' });
  check(G, 'choices: sideConvention changes Nonesuch entering positions but not Newcastle ring positions',
    same(nc.home, ringMirror.home) && same(nc.pos, ringMirror.pos) && same(nc.snapshots.map((s) => s.pos), ringMirror.snapshots.map((s) => s.pos)));
  check(G, 'control: the same places-and-meetings comparison does see a live choice (yourWe)', placesAndMeetings(E.DEFAULTS) !== placesAndMeetings({ ...E.DEFAULTS, yourWe: 'own-woman-literal' }));
  const st = E.setOutput(tx, sharp, 'playford-key'), ss = E.setOutput(tx, sharp, 'sharp-setting');
  check(G, "choices: the book's key and Sharp count a single, a set and a double the same, and differ only on the first single's direction", st.count === ss.count && st.countPerDouble === ss.countPerDouble && st.firstSingle !== ss.firstSingle);
}

// =============================================================================================
// planted faults: doctor a copy of the record, run the unmodified engine
// =============================================================================================
{
  const G = 'fault';
  const struck = clone(tx);
  struck.pages.newcastle.rows[1].A[0].as_written = 'Sides all with your owne';
  struck.pages.newcastle.rows[1].A[1].as_written = 'Sides with the next';
  const rs = E.runNewcastle(struck, E.DEFAULTS);
  check(G, "fault: with 'and change places with them' struck, the printed pairs fail", rs.statements.filter((s) => s.id === 'named-pair').some((s) => !s.holds));
  check(G, 'fault: ... and the Contrary place fails', !rs.statements.find((s) => s.id === 'contrary').holds);
  check(G, "fault: ... and 'So each falls into his place as at firſt.' fails", !rs.statements.find((s) => s.id === 'home').holds);
  check(G, 'fault: the clean record still holds all three', nc.statements.every((s) => s.holds));
  const finalReflect = clone(tx);
  finalReflect.pages.newcastle.rows[2].B[1].as_written = finalReflect.pages.newcastle.rows[2].B[1].as_written.replace('turne S. change places with your oppoſite', 'fall back from each other');
  const noFinalReflect = E.runNewcastle(finalReflect, E.DEFAULTS);
  check(G, 'fault: removing the final reflection from the data breaks the independent terminal-home check', !Object.entries(noFinalReflect.home).every(([d, station]) => noFinalReflect.pos[d] === station));
  check(G, 'fault: removing the final reflection also breaks the eight-identity opposite witness', !E.sharpNewcastleChecks(noFinalReflect, sharp).find((c) => c.id === 'nc-p3-opposite').holds);
  const nextOwne = clone(tx);
  nextOwne.pages.newcastle.rows[1].A[1].as_written = 'Sides all with your owne, and change places with them';
  check(G, "fault: 'the next' misread as 'your owne' fails the printed pairs", E.runNewcastle(nextOwne, E.DEFAULTS).statements.filter((s) => s.id === 'named-pair').some((s) => !s.holds));
  const dbl = clone(tx);
  dbl.pages.nonesuch.blocks[2].segments[2].as_written = dbl.pages.nonesuch.blocks[2].segments[2].as_written.replace('ſingle Hey', 'D. Hey');
  check(G, "fault: 'the ſingle Hey' misread as 'the D. Hey' is refused, not guessed", refuses(() => E.runNonesuch(dbl, E.DEFAULTS), 'no-reading'));
  const lhFault = clone(tx);
  lhFault.pages.nonesuch.blocks[2].segments[1].as_written = lhFault.pages.nonesuch.blocks[2].segments[1].as_written.replace('Firſt man ſlip to the left hand', 'Firſt man ſlip to the fore');
  check(G, 'fault: an unreadable clause in the disputed slip is refused and named', refuses(() => E.runNonesuch(lhFault, E.DEFAULTS), 'unknown-clause'));
  const uadFault = clone(readings);
  uadFault.upadouble.nonesuch_sharp.permutation = '4321';
  check(G, 'fault: a transposed permutation string in the record no longer agrees with the engine', E.sharpNonesuch(sharp, uadFault, {}).order !== uadFault.upadouble.nonesuch_sharp.permutation);
  const collFault = clone(tx);
  collFault.pages.newcastle.rows[2].A[0].as_written = 'Arms all with your We. and change places with them';
  const cf = C.collateAll(collFault, uadRaw).find((d) => d.dance === 'newcastle');
  check(G, "fault: copying Up a Double's 'with them' into the transcription changes the collation", cf.hunks.length !== collation.dances.find((d) => d.dance === 'newcastle').hunks.length);
}

// =============================================================================================
// refusals
// =============================================================================================
{
  const G = 'refusal';
  check(G, "refuse:no-reading 'the D. Hey'", refuses(() => E.compileClause('Then the D. Hey'), 'no-reading'));
  check(G, 'refuse:not-transcribed a dance outside the four pages', refuses(() => E.segmentsOf(tx, 'upon-a-summers-day'), 'not-transcribed'));
  check(G, "refuse:unbounded-repeat the 1651 Nonesuch endpoint ('Doe thus to the laſt.')", refuses(() => E.endpointOf(tx, 'nonesuch', E.DEFAULTS), 'unbounded-repeat'));
  check(G, "refuse:set-size-open All a Mode de France ('Longwayes for as many as will')", refuses(() => E.endpointOf(tx, 'all-a-mode-de-france', E.DEFAULTS), 'set-size-open'));
  check(G, 'refuse:not-a-performance-record calling a trace what was danced', refuses(() => E.claimHistoricalPerformance(), 'not-a-performance-record'));
  check(G, 'refuse:bad-choice an undeclared reading', refuses(() => E.runNonesuch(tx, { singleHey: 'reel' }), 'bad-choice'));
  const lit = E.runNewcastle(tx, { yourWe: 'own-woman-literal' });
  const before = lit.snapshots.find((s) => s.label === 'nc2B-2').pos;
  const after = lit.snapshots.find((s) => s.label === 'nc3A-1').pos;
  check(G, "refuse: 'your We.' as each man's own woman cannot be danced, is reported, and moves nobody (no silent repair)", lit.failures.some((f) => f.seg === 'nc3A-1') && same(before, after) && !lit.statements.find((s) => s.id === 'contrary').holds);
  check(G, 'refuse: the Newcastle endpoint, which the text does fix, is not refused', E.endpointOf(tx, 'newcastle', E.DEFAULTS).identity === true);
  for (const k of ['double', 'summers', 'nonesuch', 'amdf', 'history']) {
    check(G, `refuse: the page offers the '${k}' refusal and page.js wires it`, html.includes(`data-refuse="${k}"`) && new RegExp(`\\b${k}: \\(\\) => E\\.`).test(pagejs));
  }
}

// =============================================================================================
// surface: what the reader sees
// =============================================================================================
const figs = F.computeFigures(D0);
const facts = T.factsFrom(E, tx);
function corpusDigits() {
  const all = [tx, sharp, readings, collation].map((x) => JSON.stringify(x)).join(' ');
  return { text: all, runs: new Set(all.match(/\d+/g)) };
}
const CORPUS = corpusDigits();
const stripTags = (s) => s.replace(/<[^>]+>/g, '').replace(/&middot;/g, '·').replace(/&ldquo;|&rdquo;/g, '"').replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/\s+/g, ' ').trim();
const normalizeDek = (s) => stripTags(s).replaceAll('ſ', 's');
const meta = (h, attr, name) => { const m = h.match(new RegExp(`<meta ${attr}="${name}" content="([^"]*)"`)); return m ? m[1] : null; };
const fmOf = (text, field) => { const m = text.match(new RegExp(`^${field}: "(.*)"$`, 'm')); return m ? m[1] : null; };

function surfaceProblems(h, mdText, rec, f, fa) {
  const p = [];
  const bodyOnly = h.slice(h.indexOf('<body>'));
  // data-fig spans
  const figSpans = [...bodyOnly.matchAll(/<span data-fig="(\w+)">([^<]*)<\/span>/g)];
  if (figSpans.length < 40) p.push(`only ${figSpans.length} data-fig spans`);
  for (const [, k, v] of figSpans) if (!(k in f) || f[k] !== v) p.push(`data-fig ${k}: page ${v}, computed ${f[k]}`);
  // dek and headline in the body
  const dekBody = (bodyOnly.match(/<p class="dek">([\s\S]*?)<\/p>/) || [])[1] || '';
  if (stripTags(dekBody) !== T.dek(f, fa, 'ſ')) p.push('body dek differs from the recomputed template');
  if (normalizeDek(dekBody) !== fmOf(mdText, 'dek')) p.push('visible body dek differs from frontmatter dek');
  const hl = (bodyOnly.match(/<p class="headline" id="headline"(?: [^>]*)?>([\s\S]*?)<\/p>/) || [])[1] || '';
  if (stripTags(hl) !== T.headline(f, fa)) p.push('body headline differs from the recomputed template');
  if (rec.headline !== T.headline(f, fa)) p.push('record.json headline differs from the recomputed template');
  // head tags
  const title = (h.match(/<title>([^<]*)<\/title>/) || [])[1];
  if (title !== T.SEO_TITLE) p.push('title tag');
  const desc = meta(h, 'name', 'description');
  if (desc !== T.dek(f, fa, 's')) p.push('meta description differs from the recomputed dek');
  for (const [a, n] of [['property', 'og:description'], ['name', 'twitter:description'], ['property', 'og:title'], ['name', 'twitter:title'], ['property', 'og:image:alt']]) {
    const v = meta(h, a, n) || '';
    const digits = v.match(/\d+/g) || [];
    if (!digits.every((d) => d === '1651')) p.push(`${n} carries an unverified number`);
  }
  for (const [a, n] of [['property', 'og:url'], ['property', 'og:image'], ['name', 'twitter:image']]) if (!(meta(h, a, n) || '').includes(`/${SLUG}`)) p.push(`${n} slug`);
  if (!h.includes(`<link rel="canonical" href="https://artwaste.land/strata/${SLUG}/" />`)) p.push('canonical');
  const ld = h.match(/<script type="application\/ld\+json">([\s\S]*?)<\/script>/);
  try {
    const j = JSON.parse(ld[1]);
    if (j.description !== T.dek(f, fa, 's')) p.push('JSON-LD description');
    if (j.name !== T.SEO_TITLE || j.headline !== T.TITLE) p.push('JSON-LD name or headline');
    if (!String(j.url).includes(SLUG)) p.push('JSON-LD url');
  } catch (e) { p.push('JSON-LD does not parse'); }
  // frontmatter
  if (fmOf(mdText, 'title') !== T.TITLE) p.push('frontmatter title');
  if (fmOf(mdText, 'seoTitle') !== T.SEO_TITLE) p.push('frontmatter seoTitle');
  if (fmOf(mdText, 'dek') !== T.dek(f, fa, 's')) p.push('frontmatter dek differs from the recomputed template');
  if (fmOf(mdText, 'plain') !== T.PLAIN) p.push('frontmatter plain');
  if (fmOf(mdText, 'href') !== `/strata/${SLUG}/`) p.push('frontmatter href');
  if (rec.title !== T.TITLE) p.push('record title');
  // every digit in the visible body is accounted for
  let b = bodyOnly.replace(/<script[\s\S]*?<\/script>/g, '').replace(/<style[\s\S]*?<\/style>/g, '').replace(/<!--[\s\S]*?-->/g, '');
  b = b.replace(/<blockquote class="print" id="n3Text" data-quote="nonesuch-block-3">([\s\S]*?)<\/blockquote>/g, (m0, inner) => {
    const want = tx.pages.nonesuch.blocks[2].segments.map((s) => s.as_written).join(' / ');
    if (stripTags(inner) !== want) p.push('the printed block of Nonesuch in the page is not the transcription verbatim');
    return '';
  });
  if (!/data-quote="nonesuch-block-3"/.test(b) && !h.includes('data-quote="nonesuch-block-3"')) p.push('the printed block of Nonesuch is missing');
  b = b.replace(/<q>([\s\S]*?)<\/q>/g, (m0, inner) => {
    const t = stripTags(inner);
    if (/\d/.test(t) && !CORPUS.text.includes(JSON.stringify(t).slice(1, -1))) p.push(`quotation with a number not verbatim in the record: ${t.slice(0, 60)}`);
    return '';
  });
  b = b.replace(/<span data-fig="(\w+)">([^<]*)<\/span>/g, '');
  b = b.replace(/<span (?:class="mono" )?data-cite>([^<]*)<\/span>/g, (m0, inner) => {
    for (const d of inner.match(/\d+/g) || []) if (!CORPUS.runs.has(d)) p.push(`citation ${inner} is not in the record`);
    return '';
  });
  b = b.replace(/<option value="([^"]*)">([^<]*)<\/option>/g, (m0, val, text) => {
    const g = val.match(/^g(\d)$/);
    if (g) { const k = Number(g[1]); if (text !== `between stations ${mod(k - 1, 8)} and ${k}`) p.push(`option ${val} label ${text}`); return ''; }
    for (const d of text.match(/\d+/g) || []) if (!CORPUS.runs.has(d)) p.push(`option ${text} carries a number not in the record`);
    return '';
  });
  b = b.replace(/<[^>]+>/g, ' ');
  const left = b.match(/\d+/g);
  if (left) p.push(`digits in the visible text that nothing accounts for: ${left.slice(0, 8).join(', ')}`);
  return p;
}
{
  const G = 'surface';
  // the verifier's own recomputation of the load-bearing figures, from engine primitives
  const mine = {
    circPasses: String(circ.trace.length), cornerPasses: String(corner.trace.length),
    cornerSameSex: String(corner.trace.filter((t) => t.a[0] === t.b[0]).length),
    circChanges: String(Math.max(...circ.trace.map((t) => t.change))), cornerChanges: String(Math.max(...corner.trace.map((t) => t.change))),
    uadOrder: E.sharpNonesuch(sharp, readings, {}).order, sharpHeld: String(E.sharpNewcastleChecks(nc, sharp).filter((c) => c.holds).length),
    gridPass: String(grid.flat().filter((c) => c.owneSide.holds).length),
  };
  for (const [k, v] of Object.entries(mine)) check(G, `surface: figures.js ${k} = the verifier's own ${v}`, figs[k] === v);
  const recoll = C.collateAll(tx, uadRaw);
  const sigs = (ds) => ds.flatMap((d) => [...d.hunks, ...d.markDiffs].map((x) => x.sig)).join('\n');
  check(G, 'surface: collation.json is exactly what collate.js computes now', sigs(recoll) === sigs(collation.dances) && recoll.every((d, i) => d.ourWords === collation.dances[i].ourWords));
  check(G, 'surface: every collation difference carries a resolution read from the scan', collation.dances.every((d) => [...d.hunks, ...d.markDiffs].every((x) => typeof x.resolution === 'string' && x.resolution.length > 20)));
  check(G, 'surface: facts behind the sentences hold', facts.bookHolds && facts.heldPass && facts.mixedWrong);
  const probs = surfaceProblems(html, md, record, figs, facts);
  check(G, 'surface:static-figures every figure, sentence, head tag and frontmatter field matches the recomputation', probs.length === 0, probs.slice(0, 4).join(' / '));
  check(G, 'surface: record.json headline is also shipped verbatim in the page headline data', html.includes(`data-headline="${T.headline(figs, facts)}"`));
  check(G, 'surface: visible body dek equals frontmatter dek', normalizeDek((html.match(/<p class="dek">([\s\S]*?)<\/p>/) || [])[1] || '') === fmOf(md, 'dek'));
  check(G, 'surface: the Newcastle card checks every terminal position against the starting map', pagejs.includes('const terminalHome = Object.entries(run.home).every') && pagejs.includes('holds: terminalHome'));
  check(G, 'surface: default-only numeric snapshots name their live control settings', html.includes('At the default clockwise numbering') && html.includes("At the default woman-on-man's-right convention") && html.includes('In the default bar-count view'));
  check(G, 'surface: OG and Twitter descriptions name the default convention and test', html.includes('og:description" content="Playford') && html.includes('twitter:description" content="Run Playford') && (html.match(/default woman-on-man's-right convention/g) || []).length >= 5);
  check(G, 'surface: the coverage placard names only the executed Nonesuch blocks', T.PLAIN.includes("second and third blocks") && md.includes("second and third blocks") && html.includes("Nonesuch's second and third blocks"));
  check(G, 'surface: Up a Double is described as separate variants and both relevant pages are linked', html.includes('as separate variants') && html.includes('https://upadouble.info/index.php?devisor=John+Playford') && html.includes('https://upadouble.info/dance.php?id=Nonesuch-Sharp'));
  check(G, 'surface: dynamic handing and left-hand panels are live status regions', /<div id="handingPanel" role="status" aria-live="polite"><\/div>/.test(html) && /<div id="leftHandPanel" role="status" aria-live="polite"><\/div>/.test(html));
  check(G, 'surface: the hand-order predicate requires the complete three-item result', pagejs.includes('xs.length === amdf.length'));
  check(G, 'surface: long trace and figure lists collapse to one column on narrow screens', /@media \(max-width:640px\)\{ol\.trace,ul\.figs\{columns:1\}\}/.test(html));
  const controls = [
    ['a data-fig figure corrupted (32 to 33)', html.replace('<span data-fig="circPasses">32</span>', '<span data-fig="circPasses">33</span>'), md, record],
    ['the meta description corrupted (28 passes to 29 passes)', html.replace('the other in 28 passes', 'the other in 29 passes'), md, record],
    ['a bare number added to the prose', html.replace('Press <b>next line</b>.', 'Press <b>next line</b> 14 times.'), md, record],
    ['a citation corrupted (p. 103 to p. 903)', html.replace('<span data-cite>p. 103</span>', '<span data-cite>p. 903</span>'), md, record],
    ["a quotation's numeral corrupted (the 3. to the 4.)", html.replace('the right to the 3. and ſo forward', 'the right to the 4. and ſo forward'), md, record],
    ['the frontmatter dek corrupted (12 to 13)', html, md.replace('include 12 such pairs', 'include 13 such pairs'), record],
    ['the visible dek corrupted (12 to 13)', html.replace('<span data-fig="cornerSameSex">12</span>', '<span data-fig="cornerSameSex">13</span>'), md, record],
    ['the record headline corrupted', html, md, { ...record, headline: record.headline.replace('28', '27') }],
    ['the JSON-LD description corrupted', html.replace('"description":"John Playford printed', '"description":"John Playford published'), md, record],
    ["the dek's reconstruction figure corrupted (4312 to 4313)", html.replace("the Sharp reconstruction's 4312 is", "the Sharp reconstruction's 4313 is"), md, record],
    ['a numeral in the printed Nonesuch block corrupted (the 2. Cu. to the 3. Cu.)', html.replace('the 2. Cu. as much, third as much', 'the 3. Cu. as much, third as much'), md, record],
    ['a figure copied into a span with the wrong key', html.replace('<span data-fig="rounds">5</span> rounds. Run his', '<span data-fig="usualRounds">5</span> rounds. Run his'), md, record],
  ];
  for (const [name, h2, md2, rec2] of controls) {
    const doctored = surfaceProblems(h2, md2, rec2, figs, facts);
    check(G, `control: ${name} is caught`, h2 !== html || md2 !== md || rec2 !== record ? doctored.length > 0 : false, doctored[0] || 'NOT CAUGHT');
  }
  // closing tags and inline scripts
  check(G, 'surface: load-bearing closing tags present', /<\/script>\s*<\/body>\s*<\/html>\s*$/.test(html));
  const inline = [...html.matchAll(/<script(?![^>]*\bsrc=)([^>]*)>([\s\S]*?)<\/script>/g)];
  check(G, 'surface: the only inline script is the JSON-LD', inline.length === 1 && /ld\+json/.test(inline[0][1]));
  check(G, 'surface: accessible readouts (role=status) and labelled controls', (html.match(/role="status"/g) || []).length >= 10 && [...html.matchAll(/<select id="(\w+)"/g)].every(([, id]) => html.includes(`for="${id}"`)));
  check(G, 'surface: a prefers-reduced-motion guard in CSS and in page.js', html.includes('prefers-reduced-motion') && pagejs.includes('prefers-reduced-motion'));
  const runtime = ['engine.js', 'render.js', 'page.js', 'figures.js', 'collate.js'].map((f) => fs.readFileSync(path.join(PUB, f), 'utf8')).join('\n');
  check(G, 'surface: no third-party request in any script (no absolute http URL fetched, no import from a host)', !/fetch\(\s*['"`]https?:/.test(runtime) && !/import\s[^;]*from\s+['"]https?:/.test(runtime) && !/new\s+(WebSocket|EventSource)\(/.test(runtime));
  // em dashes
  const authored = [path.join(PUB, 'index.html'), ...['engine.js', 'render.js', 'page.js', 'figures.js', 'collate.js', 'LICENCE.txt'].map((f) => path.join(PUB, f)), path.join(ROOT, 'src/content/strata', `${SLUG}.md`), ...fs.readdirSync(HERE).filter((f) => /\.(mjs|md)$/.test(f)).map((f) => path.join(HERE, f))];
  const EM = String.fromCharCode(0x2014);
  const withEm = authored.filter((f) => fs.readFileSync(f, 'utf8').split('\n').some((l) => l.includes(EM) && !/em-dash-ok/.test(l) && !/[“”]/.test(l)));
  check(G, 'surface: no em dash in any authored file', withEm.length === 0, withEm.map((f) => path.basename(f)).join(' '));
  const jsonEm = FILES.filter((f) => fs.readFileSync(path.join(PUB, f), 'utf8').split('\n').some((l) => l.includes(EM) && !/em-dash-ok/.test(l) && !/[“”]/.test(l)));
  check(G, "surface: every source's em dash in the data files is marked em-dash-ok or sits inside curly quotes", jsonEm.length === 0, jsonEm.join(' '));
  // relates point at pages that exist
  const rel = [...md.matchAll(/^\s+- to: ([a-z0-9-]+)$/gm)].map((x) => x[1]);
  check(G, 'surface: 3 to 5 relates, each an existing stratum', rel.length >= 3 && rel.length <= 5 && rel.every((s) => fs.existsSync(path.join(ROOT, 'src/content/strata', `${s}.md`))), rel.join(' '));
}

// =============================================================================================
// ledger
// =============================================================================================
const groupOk = (g) => results.some((r) => r.group === g) && results.filter((r) => r.group === g).every((r) => r.ok);
const ledger = {
  anchor_reproduced_by_engine: groupOk('anchor'),
  rendered_figures_asserted: groupOk('surface'),
  choices_are_live: groupOk('choices'),
  planted_fault_caught: groupOk('fault'),
  refusal_asserted: groupOk('refusal'),
  provenance_pinned: groupOk('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 [k, v] of Object.entries(ledger)) {
    const claimed = record.ledger && record.ledger[k] && record.ledger[k].value;
    console.log(`${claimed === v ? 'ok  ' : 'FAIL'} [ledger] ${k}: computed ${v}, record.json ${claimed}`);
    if (claimed !== v) failed.push({ id: `ledger ${k}` });
  }
  console.log(`\n${results.length} assertions, ${failed.length} failed`);
}
process.exit(failed.length ? 1 : 0);
