#!/usr/bin/env node
// Verifier for public/strata/the-hours-between-best-and-good/. Read-only: it writes nothing into the
// repository (mutation copies live in memory; the browser pass serves public/ from a local port).
//
//   node research/the-hours-between-best-and-good/verify-the-hours-between-best-and-good.mjs
//        every assertion, a summary, exit 1 on any failure
//   ... --ledger       print exactly the nine contract keys with the booleans the assertions produced
//   ... --mutate       also corrupt every numeral the reader can see in index.html, one at a time, and every
//                      bound figure, quotation and head tag, and require the surface assertions to go red
//   ... --no-browser   skip the headless Chromium pass (it is also skipped, with a note, when Playwright is
//                      missing; no ledger cell depends on it alone)
//   ... --regen        re-run extract.py --write, crosscheck.py, record-spec.mjs --write and author.mjs --write
//                      first (needs the upstream workbook)
//
// What it compares against, besides the page's own engine: research/.../data/crosscheck.json, an independent
// Python, numpy and scipy recomputation read from the ORIGINAL workbook through openpyxl; arithmetic written
// again here; the CC BY source texts in research/.../sources/; and, when this machine holds them, the
// copyrighted source texts under .wave/ (hash-pinned below).
import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import http from 'node:http';
import { execFileSync } from 'node:child_process';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { createRequire } from 'node:module';

// The site's chrome writers (nearby-layers, way-out, check-placard, site-bar) inject furniture into every shipped
// page after the build. It is gated by the writers' own --check modes; this verifier checks the page's OWN content,
// so it reads the page with exactly those marked blocks and the shared banner script removed (2026-09-23, landing).
// This page's own template already carries the shared banner script, so only the marked blocks are removed,
// including the aw-plain meta that plain-cards injects (the page asserts its placard from the frontmatter instead).
const stripChrome = (s) => s.replace(/\s*<!--aw-(nearby|wayout|checkkind|plain):start-->[\s\S]*?<!--aw-\1:end-->/g, '');

const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, '../..');
const SLUG = 'the-hours-between-best-and-good';
const PUB = path.join(ROOT, 'public/strata', SLUG);
const ARGS = new Set(process.argv.slice(2));
const LEDGER = ARGS.has('--ledger');
const KEYS = ['claim_reproduced', 'control_computed', 'control_can_confirm', 'rendered_figures_asserted', 'choices_are_live',
  'planted_fault_caught', 'refusal_asserted', 'provenance_pinned', 'verdict_dated'];

if (ARGS.has('--regen')) {
  execFileSync('python3', [path.join(HERE, 'extract.py'), '--write'], { stdio: 'inherit' });
  execFileSync('nice', ['-n', '19', 'python3', path.join(HERE, 'crosscheck.py')], { stdio: 'inherit' });
  execFileSync(process.execPath, [path.join(HERE, 'record-spec.mjs'), '--write'], { stdio: 'inherit' });
  execFileSync(process.execPath, [path.join(HERE, 'author.mjs'), '--write'], { stdio: 'inherit' });
}

const read = (f) => fs.readFileSync(f, 'utf8');
const sha = (f) => crypto.createHash('sha256').update(fs.readFileSync(f)).digest('hex');
const shaText = (s) => crypto.createHash('sha256').update(s).digest('hex');
const near = (a, b, tol) => Number.isFinite(a) && Number.isFinite(b) && Math.abs(a - b) <= tol;
const rel = (a, b, tol) => Number.isFinite(a) && Number.isFinite(b) && Math.abs(a - b) <= tol * Math.max(Math.abs(a), Math.abs(b), 1e-300);
const refused = (fn, re) => { try { fn(); return false; } catch (e) { return e && e.name === 'Refusal' && (!re || re.test(e.message)); } };
const threwData = (fn) => { try { fn(); return false; } catch (e) { return e && e.name === 'DataError'; } };
const num = (s) => Number(String(s).replace(/[,\s]/g, '').replace(/−/g, '-'));

// ---------------------------------------------------------------------------------------------- bookkeeping
const results = Object.fromEntries([...KEYS, 'null_method', 'record', 'browser'].map((k) => [k, { pass: 0, fail: [] }]));
function check(cell, name, cond, detail = '') {
  const r = results[cell];
  if (cond) r.pass++; else r.fail.push(`${name}${detail ? ` (${detail})` : ''}`);
  return !!cond;
}
const notes = [];

// ---------------------------------------------------------------------------------------------- the page's modules
const imp = (f) => import(pathToFileURL(path.join(PUB, f)).href);
const E = await imp('engine.js');
const D = await imp('data.js');
const F = await imp('facts.js');
const St = await imp('stats.js');
const { fill, readFrontmatter, jsonld } = await import(pathToFileURL(path.join(HERE, 'template.mjs')).href);
const { buildRecord } = await import(pathToFileURL(path.join(HERE, 'record-spec.mjs')).href);
const XC = JSON.parse(read(path.join(HERE, 'data/crosscheck.json')));

const csvText = read(path.join(PUB, D.FILES.violinists.path));
const claimText = read(path.join(PUB, D.FILES.claim.path));
const rows = D.parseViolinists(csvText);
const claim = D.parseClaim(claimText);
const S = F.computeState(claim, rows);
const FIG = F.allFigures(S, rows);
const HTML = stripChrome(read(path.join(PUB, 'index.html')));
const RECORD = JSON.parse(read(path.join(PUB, 'record.json')));
const FM = readFrontmatter(path.join(ROOT, 'src/content/strata', `${SLUG}.md`));
const README = read(path.join(HERE, 'README.md'));

// ---------------------------------------------------------------------------------------------- source texts
const SRC = {
  mm: path.join(HERE, 'sources/macnamara-maitra-2019-rsos-190327.txt'),
  eh: path.join(HERE, 'sources/ericsson-harwell-2019-fpsyg-02396.txt'),
  fsu: path.join(HERE, 'sources/fsu-news-2020-06-24-excerpt.txt'),
  prereg: path.join(HERE, 'sources/osf-registration-khjs7.json'),
  esm: path.join(HERE, 'sources/macnamara-maitra-2019-esm-excerpt.txt'),
  e93: path.join(ROOT, '.wave/spec/ten-thousand-hours/e93.txt'),
  e14: path.join(ROOT, '.wave/spec/ten-thousand-hours/ericsson2014.txt'),
  guardian: path.join(ROOT, '.wave/spec/ten-thousand-hours/guardian.html'),
};
const SRC_SHA = {
  e93: '4ae1e311c278ed5f518f37d4591458ff68057193b2a6bcd12b01980bc004423e',
  e14: '00981100db55bba5efc748abd04ed4cfe18a6a0d931c0622c21c70b06cffa685',
  guardian: '041b0a4a40b7dc0b119f7c86e69716a7eed6c09198a76b438358da41a9c133b4',
};
const SUB = { '₀': '0', '₁': '1', '₂': '2', '₃': '3', '₄': '4', '₅': '5', '₆': '6', '₇': '7', '₈': '8', '₉': '9', '²': '2', '․': '.' };
function normQ(s) {
  return s.normalize('NFKC').replace(/[₀-₉²]/g, (c) => SUB[c]).replace(/&amp;/g, '&').replace(/&nbsp;/g, ' ')
    .replace(/[\u2212\u2013\u2014]/g, '-').replace(/[‘’ʼ]/g, "'").replace(/[“”]/g, '"')
    .replace(/\\n|\\t/g, ' ').replace(/(\w)- (\w)/g, '$1$2').replace(/\s+/g, ' ').trim();
}
const srcCache = {};
// words for in-order matching: split on anything that is not a letter, digit, %, <, >, = or an inner dot or
// hyphen, then trim punctuation from the ends (so "contrasts." matches "contrasts" and "4.59" survives)
const tokens = (s) => s.toLowerCase().split(/[^a-z0-9%.'<>=-]+/).map((w) => w.replace(/^[.'-]+|[.']+$/g, '')).filter(Boolean);
function sourceText(key, fix = []) {
  const ck = key + JSON.stringify(fix);
  if (!(ck in srcCache)) {
    const f = SRC[key];
    if (!f || !fs.existsSync(f)) srcCache[ck] = null;
    else {
      let t = read(f);
      if (/\.html$/.test(f)) t = t.replace(/<script[\s\S]*?<\/script>|<style[\s\S]*?<\/style>/g, ' ').replace(/<[^>]+>/g, ' ').replace(/&#x27;|&#39;/g, "'").replace(/&quot;/g, '"');
      for (const [a, b] of fix) t = t.split(a).join(b);
      const text = normQ(t);
      srcCache[ck] = { text, words: tokens(text), shaOk: !SRC_SHA[key] || sha(f) === SRC_SHA[key] };
    }
  }
  return srcCache[ck];
}
// exact after normalisation; or, for a two-column PDF text layer, every word of the quotation in order within a
// window, where a word the layout split with a line-end hyphen ("ac-" ... "counted") may be matched by its two
// halves even when the other column's text sits between them
function foundIn(key, quote, fix = []) {
  const s = sourceText(key, fix);
  if (!s) return { checked: false };
  if (!s.shaOk) return { checked: true, ok: false, why: 'source hash changed' };
  const q = normQ(quote);
  if (s.text.includes(q)) return { checked: true, ok: true, mode: 'exact' };
  const qw = tokens(q), W = s.words;
  const win = qw.length * 12;
  const halves = (x, w, k) => {
    if (!(x.endsWith('-') && x.length > 2 && w.startsWith(x.slice(0, -1)) && w.length > x.length - 1)) return -1;
    const rest = w.slice(x.length - 1).replace(/^-/, '');
    const at = W.slice(k + 1, k + 60).indexOf(rest);
    return at < 0 ? -1 : k + 2 + at;
  };
  for (let i = 0; i < W.length; i++) {
    let j = 1, k = i + 1;
    if (W[i] !== qw[0]) { const nk = halves(W[i], qw[0], i); if (nk < 0) continue; k = nk; }
    while (j < qw.length && k < W.length && k - i < win) {
      const w = qw[j], x = W[k];
      if (x === w) { j++; k++; continue; }
      const nk = halves(x, w, k);
      if (nk >= 0) { j++; k = nk; continue; }
      k++;
    }
    if (j === qw.length) return { checked: true, ok: true, mode: 'in order' };
  }
  return { checked: true, ok: false };
}

// ================================================================================================ 1. provenance
function provenance() {
  const c = 'provenance_pinned';
  const csvSha = sha(path.join(PUB, D.FILES.violinists.path)), claimSha = sha(path.join(PUB, D.FILES.claim.path));
  check(c, 'violinists CSV hash equals the pin in data.js', csvSha === D.FILES.violinists.sha256, csvSha);
  check(c, 'claim JSON hash equals the pin in data.js', claimSha === D.FILES.claim.sha256, claimSha);
  const recCsv = RECORD.records.find((r) => r.role === 'control-data'), recClaim = RECORD.records.find((r) => r.role === 'claimant-data');
  check(c, 'record.json control-data sha256 is the shipped CSV', recCsv && recCsv.sha256 === csvSha);
  check(c, 'record.json claimant-data sha256 is the shipped claim JSON', recClaim && recClaim.sha256 === claimSha);
  check(c, 'record.json upstream sha256 is the pinned workbook', recCsv && recCsv.upstream_sha256 === D.UPSTREAM.workbook.sha256);
  const recRef = RECORD.records.find((r) => r.role === 'reference');
  check(c, 'record.json reference sha256 is crosscheck.json', recRef && recRef.sha256 === sha(path.join(HERE, 'data/crosscheck.json')));
  check(c, 'research copy of the extract is byte-identical to the shipped one', fs.readFileSync(path.join(HERE, 'data/violinists-2019.csv')).equals(fs.readFileSync(path.join(PUB, D.FILES.violinists.path))));
  for (const [what, h] of [['CSV', csvSha], ['claim JSON', claimSha], ['workbook', D.UPSTREAM.workbook.sha256], ['crosscheck', sha(path.join(HERE, 'data/crosscheck.json'))]]) {
    check(c, `README records the ${what} SHA-256`, README.includes(h));
  }
  for (const f of fs.readdirSync(path.join(HERE, 'sources')).sort()) check(c, `README records the SHA-256 of sources/${f}`, README.includes(sha(path.join(HERE, 'sources', f))));
  check(c, 'the page prints the CSV and claim hashes', FIG['prov.csv'] === csvSha && FIG['prov.claim'] === claimSha && HTML.includes(csvSha) && HTML.includes(claimSha));
  check(c, 'the page prints the workbook hash and byte count', HTML.includes(D.UPSTREAM.workbook.sha256) && FIG['prov.bytes'] === F.int(D.UPSTREAM.workbook.bytes));
  // the extract re-derives from the pinned workbook when it is on this machine
  const wb = path.join(ROOT, '.wave/prospect/ten-thousand-hours/osf-data.xlsx');
  if (fs.existsSync(wb) && sha(wb) === D.UPSTREAM.workbook.sha256) {
    let out = '';
    try { out = execFileSync('python3', [path.join(HERE, 'extract.py'), '--workbook', wb], { encoding: 'utf8' }); } catch (e) { out = String(e.stdout || '') + String(e.stderr || ''); }
    const m = out.match(/extract: (\d+) rows, (\d+) bytes, sha256 ([0-9a-f]{64})/);
    check(c, 'extract.py re-derives the shipped CSV from the pinned workbook (dry run)', m && m[3] === csvSha && Number(m[1]) === rows.length, out.slice(0, 200));
  } else notes.push('upstream workbook not on this machine: the re-derivation check was skipped (the pinned hashes were still checked)');
  // the extract holds no field beyond the documented ones
  const head = csvText.split('\n')[0].split(',');
  check(c, 'the extract carries only the documented columns', head.slice(0, 7).join(',') === 'id,sheet_row,group,age,competitions,authors_pa18,authors_td18' && head.slice(7).every((h) => /^(pa|td)\d+$/.test(h)));
}

// ================================================================================================ 2. the claim
function anchor() {
  const c = 'claim_reproduced';
  const a = S.anchor;
  const pa = claim.practiceAlone;
  // arithmetic written again here, independently of engine.contrastF
  const m1 = pa.groups.best.mean, m2 = pa.groups.good.mean, m3 = pa.groups.least.mean, n = pa.groups.best.n;
  const msw = (m1 - m2) ** 2 / (pa.contrast1.F * (1 / n + 1 / n));
  const F2 = ((m1 + m2) / 2 - m3) ** 2 / (msw * (0.25 / n + 0.25 / n + 1 / n));
  check(c, 'engine mean square equals the independent formula', rel(a.msw, msw, 1e-12), `${a.msw} vs ${msw}`);
  check(c, 'engine predicted second F equals the independent formula', rel(a.predictedF2, F2, 1e-12));
  check(c, 'engine agrees with the Python crosscheck (mean square, F2, interval, p, d, eta squared)',
    rel(a.msw, XC.anchor.MSw, 1e-10) && rel(a.predictedF2, XC.anchor.F2, 1e-10) && rel(a.interval[0], XC.anchor.F2lo, 1e-10) && rel(a.interval[1], XC.anchor.F2hi, 1e-10)
    && rel(a.p1, XC.anchor.p1, 1e-8) && rel(a.p2, XC.anchor.p2, 1e-8) && rel(a.d, XC.anchor.d, 1e-10) && rel(a.eta2, XC.anchor.eta2, 1e-10));
  check(c, 'the printed second F lies inside the rounding interval', a.agrees && pa.contrast2.F >= a.interval[0] && pa.contrast2.F <= a.interval[1]);
  check(c, 'the prediction is within 0.03 of the printed 11.86', near(a.predictedF2, pa.contrast2.F, 0.03));
  check(c, 'the pooled SD rounds to Ericsson (2014) printed 2201', Math.round(a.s) === num(D.PRINTED['e14.s'].v));
  check(c, 'the mean square matches Ericsson (2014) printed 4,845,186.27 to the cent', a.msw.toFixed(2) === D.PRINTED['e14.msw'].v.replace(/,/g, ''));
  check(c, 'the claim is reproduced at full strength: best over good d near 0.96 and p below .05', a.d > 0.9 && a.p1 < 0.05 && a.p2 < 0.01);
  // negatives: the anchor must go red when the claimant record is wrong
  const corrupt = (fn) => { const cc = JSON.parse(claimText); fn(cc); return E.anchor1993(cc); };
  check(c, 'negative: teachers mean moved by 100 h fails the anchor', !corrupt((cc) => { cc.practiceAlone.groups.least.mean += 100; }).agrees);
  check(c, 'negative: first F read as 4.95 fails the anchor', !corrupt((cc) => { cc.practiceAlone.contrast1.F = 4.95; }).agrees);
  check(c, 'negative: second contrast weights swapped to (1, 0, -1) fails the anchor', !corrupt((cc) => { cc.practiceAlone.contrast2.weights = [1, 0, -1]; }).agrees);
  check(c, 'negative: best and good means swapped cannot pass', !corrupt((cc) => { const g = cc.practiceAlone.groups; [g.best.mean, g.good.mean] = [g.good.mean + 1000, g.best.mean]; }).agrees);
  check(c, 'refusal: a df that does not match three groups of ten is refused', refused(() => corrupt((cc) => { cc.practiceAlone.contrast1.df2 = 18; })));
  // the anchor and the reanalysis are one method: synthetic groups with the printed means and the implied
  // pooled variance, pushed through procedure1993, return the printed first F and the predicted second F
  const z = [-1.5, -1.5, -0.5, -0.5, 0, 0, 0.5, 0.5, 1.5, 1.5]; // sample variance: sum of squares 10 over 9 df
  const zs = Math.sqrt(z.reduce((s, v) => s + v * v, 0) / (z.length - 1));
  const mk = (m) => z.map((v) => m + (v / zs) * a.s);
  const P = E.procedure1993({ best: mk(m1), good: mk(m2), least: mk(m3) });
  check(c, 'procedure1993 on synthetic groups with the printed means returns the printed first F', rel(P.F1, pa.contrast1.F, 1e-9), P.F1);
  check(c, 'and the predicted second F: the anchor and the reanalysis share contrastF', rel(P.F2, a.predictedF2, 1e-9));
  // the printed claimant numbers are in the paper
  const pn = [['7,410 hr', 'best mean'], ['5,301 hr', 'good mean'], ['3,420 hr', 'teachers mean'], ['= 4.59', 'first F'], ['= 11.86', 'second F'],
    ['2.9 vs. 0.6', 'competitions'], ['= 19.35', 'competition F'], ['128.9 min', 'repertoire best'], ['79.1 min', 'repertoire good'], ['4.07, p', 'repertoire F']];
  let checked = 0;
  for (const [s, what] of pn) {
    const r = foundIn('e93', s, [['F(l,', 'F(1,'], ['F(\\,', 'F(1,'], ['F{\\,', 'F(1,']]);
    if (!r.checked) continue;
    checked++;
    check(c, `claim-1993.json ${what} is printed in the 1993 text`, r.ok, s);
  }
  if (!checked) notes.push('1993 text not on this machine: the claimant numbers were not re-read from the paper');
  const js = claim.practiceAlone;
  check(c, 'claim JSON holds exactly the printed values', js.groups.best.mean === 7410 && js.groups.good.mean === 5301 && js.groups.least.mean === 3420 && js.contrast1.F === 4.59 && js.contrast2.F === 11.86 && js.groups.best.n === 10);
}

// ================================================================================================ 3. the control
function roundsTo(v, printed) {
  const p = String(printed).replace(/−/g, '-').replace(/\s/g, '');
  const dp = (p.split('.')[1] || '').length;
  return Number(v.toFixed(dp)) === Number(p);
}
function control() {
  const c = 'control_computed';
  check(c, 'weekly estimates x 52 reproduce the authors own totals for every row', S.authorsAgree);
  // totals written again here, from the raw CSV cells, without the engine
  const lines = csvText.trim().split('\n'); const head = lines[0].split(',');
  let allOk = true;
  for (const line of lines.slice(1)) {
    const f = line.split(',');
    let s = 0;
    for (let a = 2; a <= 18; a++) { const v = f[head.indexOf(`pa${a}`)]; if (v !== '' && v !== '.') s += Number(v); }
    const row = rows.find((r) => r.id === f[0]);
    if (Math.abs(52 * s - E.accumulate(row, 'pa', 18)) > 1e-6) allOk = false;
  }
  check(c, 'independent totals from the raw CSV equal engine.accumulate', allOk);
  const k = S.control, t = S.controlTd;
  const P = D.PRINTED;
  const pr = [
    ['best mean', k.summary.best.mean, P['mm.pa.best'].v], ['good mean', k.summary.good.mean, P['mm.pa.good'].v], ['least mean', k.summary.least.mean, P['mm.pa.least'].v],
    ['best CI low', k.summary.best.zci[0], P['mm.pa.best.ci'].v.match(/\[([\d ]+),/)[1]], ['best CI high', k.summary.best.zci[1], P['mm.pa.best.ci'].v.match(/, ([\d ]+)\]/)[1]],
    ['good CI low', k.summary.good.zci[0], P['mm.pa.good.ci'].v.match(/\[([\d ]+),/)[1]], ['good CI high', k.summary.good.zci[1], P['mm.pa.good.ci'].v.match(/, ([\d ]+)\]/)[1]],
    ['least CI low', k.summary.least.zci[0], P['mm.pa.least.ci'].v.match(/\[([\d ]+),/)[1]], ['least CI high', k.summary.least.zci[1], P['mm.pa.least.ci'].v.match(/, ([\d ]+)\]/)[1]],
    ['best-good t', k.bestGood.t, P['mm.pa.bg.t'].v], ['best-good df', k.bestGood.df, P['mm.pa.bg.df'].v], ['best-good p', k.bestGood.p, P['mm.pa.bg.p'].v], ['best-good d (2t/sqrt df)', k.bestGood.d2t, P['mm.pa.bg.d'].v],
    ['good-least t', k.goodLeast.t, P['mm.pa.gl.t'].v], ['good-least df', k.goodLeast.df, P['mm.pa.gl.df'].v], ['good-least p', k.goodLeast.p, P['mm.pa.gl.p'].v], ['good-least d', k.goodLeast.d2t, P['mm.pa.gl.d'].v],
    ['Kruskal-Wallis', k.kw.H, P['mm.pa.chi2'].v], ['Kruskal-Wallis p', k.kw.p, P['mm.pa.pKW'].v], ['eta squared', k.anova.eta2, P['mm.pa.eta2'].v],
    ['td best mean', t.summary.best.mean, P['mm.td.best'].v], ['td good mean', t.summary.good.mean, P['mm.td.good'].v], ['td least mean', t.summary.least.mean, P['mm.td.least'].v],
    ['td best-good t', t.bestGood.t, P['mm.td.bg.t'].v], ['td best-good p', t.bestGood.p, P['mm.td.bg.p'].v], ['td best-good d', t.bestGood.d2t, P['mm.td.bg.d'].v],
    ['td good-least t', t.goodLeast.t, P['mm.td.gl.t'].v], ['td good-least df', t.goodLeast.df, P['mm.td.gl.df'].v], ['td good-least p', t.goodLeast.p, P['mm.td.gl.p'].v], ['td good-least d', t.goodLeast.d2t, P['mm.td.gl.d'].v],
    ['td Kruskal-Wallis', t.kw.H, P['mm.td.chi2'].v], ['td Kruskal-Wallis p', t.kw.p, P['mm.td.pKW'].v], ['td eta squared', t.anova.eta2, P['mm.td.eta2'].v],
    ['competitions best', S.skill.y2019.best, P['mm.comp.best'].v], ['competitions good', S.skill.y2019.good, P['mm.comp.good'].v], ['competitions least', S.skill.y2019.least, P['mm.comp.least'].v],
    ['competitions best-good t', S.skill.y2019.bg.t, P['mm.comp.bg.t'].v], ['competitions best-good p', S.skill.y2019.bg.p, P['mm.comp.bg.p'].v], ['competitions d', S.skill.y2019.bg.d2t, P['mm.comp.bg.d'].v],
    ['competitions good-least t', S.skill.y2019.gl.t, P['mm.comp.gl.t'].v], ['competitions good-least p', S.skill.y2019.gl.p, P['mm.comp.gl.p'].v],
  ];
  for (const [ci, lo, hi] of [['td best', t.summary.best.zci, P['mm.td.best.ci'].v], ['td good', t.summary.good.zci, P['mm.td.good.ci'].v], ['td least', t.summary.least.zci, P['mm.td.least.ci'].v]]) {
    pr.push([`${ci} CI low`, lo[0], hi.match(/\[([\d ]+),/)[1]], [`${ci} CI high`, lo[1], hi.match(/, ([\d ]+)\]/)[1]]);
  }
  for (const [name, v, p] of pr) check(c, `reproduces the printed ${name} (${p}) from the weekly rows`, roundsTo(v, p), v);
  check(c, 'Levene picks Student for best-good and Welch for good-least, as printed', k.bestGood.test === 'Student' && k.goodLeast.test === 'Welch' && t.goodLeast.test === 'Welch');
  check(c, 'negative: forcing Welch everywhere loses the printed 24 df for best-good', E.pairTest(S.G.best, S.G.good, 'welch').df !== 24);
  check(c, 'negative: a t interval does not reproduce the printed best interval', (() => { const s = k.summary.best; const h = St.tQuantile(0.975, 12) * s.se; return Math.round(s.mean - h) !== 6400; })());
  // independent Student and Welch written here
  const mean = (x) => x.reduce((a, b) => a + b, 0) / x.length;
  const v = (x) => { const m = mean(x); return x.reduce((a, b) => a + (b - m) ** 2, 0) / (x.length - 1); };
  const b = S.G.best, g = S.G.good, l = S.G.least;
  const tS = (mean(b) - mean(g)) / Math.sqrt(((12 * v(b) + 12 * v(g)) / 24) * (2 / 13));
  const tW = (mean(g) - mean(l)) / Math.sqrt(v(g) / 13 + v(l) / 13);
  check(c, 'independent Student t equals the engine', rel(tS, k.bestGood.t, 1e-12));
  check(c, 'independent Welch t equals the engine', rel(tW, k.goodLeast.t, 1e-12));
  // every age and both measures against the Python crosscheck
  let agree = 0, total = 0;
  for (const m of ['pa', 'td']) for (let age = 10; age <= 18; age++) {
    const r = E.runControl(E.groupsAt(rows, age, m)); const x = XC.control[`${m}${age}`];
    total++;
    if (rel(r.summary.best.mean, x.means.best, 1e-12) && rel(r.summary.good.mean, x.means.good, 1e-12) && rel(r.summary.least.mean, x.means.least, 1e-12)
      && rel(r.bestGood.t, x.bestGood.t, 1e-9) && rel(r.bestGood.p, x.bestGood.p, 1e-7) && r.bestGood.test === x.bestGood.test
      && rel(r.goodLeast.t, x.goodLeast.t, 1e-9) && rel(r.goodLeast.p, x.goodLeast.p, 1e-7) && r.goodLeast.test === x.goodLeast.test
      && rel(r.kw.H, x.omni.H, 1e-9) && rel(r.kw.p, x.omni.pKW, 1e-7) && rel(r.anova.eta2, x.omni.eta2, 1e-10)) agree++;
  }
  check(c, 'the engine agrees with scipy at every age 10 to 18 and both measures', agree === total, `${agree} of ${total}`);
  const p = S.p1993, xp = XC.proc1993_2019;
  check(c, 'the 1993 procedure on the 2019 rows agrees with the crosscheck', rel(p.F1, xp.F1, 1e-10) && rel(p.F2, xp.F2, 1e-10) && rel(p.p2, xp.p2, 1e-8) && near(p.c1, xp.c1, 1e-6) && p.df === xp.df);
  check(c, 'the 1993 procedure returns the soloist-track step near the printed 11.86 and best-good reversed', near(p.F2, 11.86, 0.6) && p.c1 < 0 && !p.bestOverGood && p.topTwoOverLeast);
  check(c, 'the majority sentence holds: best violinists below the good mean', S.bestBelowGoodMean > S.G.best.length / 2);
  check(c, 'competitions against scipy', rel(S.skill.y2019.bg.t, XC.competitions.t_bg, 1e-10) && rel(S.skill.y2019.gl.t, XC.competitions.t_gl, 1e-10) && rel(S.skill.y1993.d, XC.competitions_1993.d, 1e-10));
  check(c, 'the 2019 quotation of its own result is in the article text', foundIn('mm', D.QUOTES.mmResult.text.replace('χ²₂ = 13.90, ', '')).ok);
}

// ================================================================================================ 4. the control on the control
function power() {
  const c = 'control_can_confirm';
  const a = S.anchor;
  const gap = a.means[0] - a.means[1];
  const doctored = E.plantGap(rows, gap);
  check(c, 'power: the planted gap is the printed means\u2019 difference, computed from the claim record', gap === S.anchor.gap && gap === 7410 - 5301);
  const G0 = E.groupsAt(rows, 18, 'pa'), Gd = E.groupsAt(doctored, 18, 'pa');
  const shift = doctored.meta.shift;
  check(c, 'power: every best total rose by the same shift (claimed gap minus observed gap)', Gd.best.every((v, i) => Math.abs(v - G0.best[i] - shift) < 1e-6) && near(shift, gap - (-1620), 1e-6));
  check(c, 'power: good and least totals are untouched', Gd.good.every((v, i) => v === G0.good[i]) && Gd.least.every((v, i) => v === G0.least[i]));
  const bmean = (x) => x.reduce((s, v) => s + v, 0) / x.length;
  check(c, 'power: the copy has exactly the claimed best-over-good gap', near(bmean(Gd.best) - bmean(Gd.good), gap, 1e-6));
  let weeklyOnly = true;
  doctored.forEach((r, i) => {
    const o = rows[i];
    for (let age = 2; age <= 26; age++) {
      const changed = r.pa[age] !== o.pa[age];
      if (changed && (r.group !== 'best' || age > 18)) weeklyOnly = false;
      if (r.td[age] !== o.td[age]) weeklyOnly = false;
    }
  });
  check(c, 'power: the plant changes only best violinists’ practice-alone weeks up to 18', weeklyOnly);
  check(c, 'power: the original rows are not modified by the plant', E.authorsTotalsAgree(rows) && bmean(E.groupsAt(rows, 18, 'pa').best) === bmean(G0.best));
  const r = E.runControl(Gd), real = E.runControl(G0);
  check(c, 'power: the printed-size plant is not confirmed by the unmodified control', !r.confirmsBestOverGood && r.bestGood.p > 0.05, r.bestGood.p);
  check(c, 'power: printed-size plant p agrees with scipy', rel(r.bestGood.p, XC.plants.hours.p, 1e-9) && rel(r.bestGood.t, XC.plants.hours.t, 1e-10));
  check(c, 'power: the real data do not show the gap', !real.confirmsBestOverGood);
  check(c, 'power: the control reads its input (planted and real results differ)', r.bestGood.t !== real.bestGood.t);
  const sgap = a.d * E.pooledSD3(G0);
  const rs = E.runControl(E.groupsAt(E.plantGap(rows, sgap), 18, 'pa'));
  check(c, 'power: the standardized plant is confirmed by the same control', rs.confirmsBestOverGood && rel(rs.bestGood.p, XC.plants.standardized.p, 1e-9));
  const rgap = (a.ratio - 1) * bmean(G0.good);
  const rr = E.runControl(E.groupsAt(E.plantGap(rows, rgap), 18, 'pa'));
  check(c, 'power: the ratio plant is confirmed by the same control', rr.confirmsBestOverGood && rel(rr.bestGood.p, XC.plants.ratio.p, 1e-9));
  check(c, 'power: the page’s three readings are these gaps', near(S.gaps.hours.gap, gap, 1e-9) && near(S.gaps.standardized.gap, sgap, 1e-9) && near(S.gaps.ratio.gap, rgap, 1e-9));
  // the state the page shows was produced by the same path
  check(c, 'power: the page’s hours plant is the same run', S.plants.hours.run.bestGood.p === r.bestGood.p && S.plants.hours.gap === gap);
  // bootstrap: seeded, against the numpy estimate and the spec's pilot, within Monte Carlo error
  for (const [k, pilot] of [['hours', 0.244], ['ratio', 0.594], ['standardized', 0.557]]) {
    const pw = S.plants[k].boot.power;
    check(c, `power: bootstrap power (${k}) within 0.015 of the numpy estimate`, near(pw, XC.boot[k], 0.015), `${pw} vs ${XC.boot[k]}`);
    check(c, `power: bootstrap power (${k}) within 0.015 of the spec pilot ${pilot}`, near(pw, pilot, 0.015));
  }
  check(c, 'power: bootstrap draws go through runControl', /runControl\(\{ best: resample\(G\.best, rnd, nb\), good: resample\(G\.good, rnd, ng\)/.test(read(path.join(PUB, 'engine.js'))));
  const far = E.bootstrapPower({ best: G0.best.map((v) => v + 20000), good: G0.good, least: G0.least }, { draws: 2000 });
  const same = E.bootstrapPower({ best: G0.good, good: G0.good, least: G0.least }, { draws: 4000 });
  check(c, 'power: bootstrap machinery confirms a huge gap nearly always and a null rarely', far.power > 0.99 && same.power < 0.06, `${far.power} ${same.power}`);
  const realBoot = E.bootstrapPower(G0, { draws: 4000 });
  check(c, 'power: only best OVER good counts: the real rows, where good leads, almost never confirm', realBoot.power < 0.01, realBoot.power);
  check(c, 'power: normal-theory power agrees with scipy nct', rel(S.nct.powPrint, XC.nct.pow_print, 1e-6) && rel(S.nct.powD, XC.nct.pow_d93, 1e-6) && S.nct.n80d === XC.nct.n80_d93 && S.nct.n80print === XC.nct.n80_print);
  check(c, 'power: the standardized plant is paired with the normal-theory power for THAT gap in the test\u2019s spread (scipy)', rel(S.nct.dS, XC.nct.d_s, 1e-10) && rel(S.nct.powS, XC.nct.pow_s, 1e-6) && S.nct.n80s === XC.nct.n80_s && S.nct.powS < S.nct.powD);
  check(c, 'power: the page\u2019s standardized-plant sentence prints the normal-theory power for THAT gap, not for d = 0.958 in the test\u2019s own spread', /the normal-theory figure for this planted gap, d = <span data-fig="nct\.dS">[^<]+<\/span> in the best-and-good\s+spread the replication's test uses, is <span data-fig="nct\.powS">/.test(HTML) && !/data-fig="nct\.powD"/.test(HTML));
  check(c, 'power: the 1993 post hoc power uses the contrast\u2019s 27 error df (scipy, two tails)', near(S.anchor.postHocPower, XC.anchor.post_hoc_power_27, 1e-3) && F.fix(S.anchor.postHocPower, 2) !== F.fix(XC.anchor.post_hoc_power, 2));
  check(c, 'power: observed-against-claimed test agrees with scipy', rel(S.plants.hours.observed.t, XC.plants.hours.obs_t, 1e-10) && rel(S.plants.hours.observed.p, XC.plants.hours.obs_p, 1e-8));
  // the stated rule behind the words: bands of bootstrap power, which the deterministic copy must agree with
  check(c, 'power: the band rule itself (0.3 unlikely, 0.5 and 0.79 could, 0.8 likely)', E.powerBand(0.3) === 'unlikely' && E.powerBand(0.5) === 'could' && E.powerBand(0.79) === 'could' && E.powerBand(0.8) === 'likely' && refused(() => E.powerBand(NaN)));
  for (const k of ['hours', 'ratio', 'standardized']) {
    const q = S.plants[k];
    check(c, `power: at the ${k} reading the copy is significant exactly when power passes one half`, q.run.confirmsBestOverGood === (q.boot.power >= 0.5), `${q.run.bestGood.p} ${q.boot.power}`);
    const words = F.plantFigures(S, rows, { size: k })['figures']['plant.verdict'];
    const band = E.powerBand(q.boot.power);
    check(c, `power: the ${k} verdict words follow its band (${band})`, words === F.plantVerdict(q.boot.power, q.run.bestGood.p) && ({ unlikely: /was unlikely to confirm/, could: /could have confirmed the claim, short of/, likely: /would probably have confirmed/ })[band].test(words));
  }
  check(c, 'power: the three verdict phrasings differ (the text can change)', new Set([F.plantVerdict(0.3, 0.2), F.plantVerdict(0.6, 0.03), F.plantVerdict(0.9, 0.001)]).size === 3);
  const v = F.powerVerdict(S);
  check(c, 'power: the verdict text follows the computed band at the printed size', /at its printed size the replication was unlikely to confirm it/.test(v) === (E.powerBand(S.plants.hours.boot.power) === 'unlikely') && v.includes(F.bandRule()));
  check(c, 'power: record.json power.verdict is the computed verdict', RECORD.power.verdict === v && RECORD.power.grade === 'A-injection');
  check(c, 'power: the page prints the grade, the rule and the INCONCLUSIVE reading', /Grade A, by injection/.test(HTML) && /was unlikely to confirm the claim/.test(HTML) && /inconclusive at this size/.test(HTML) && HTML.includes(F.bandRule()));
  // WRONG version, kept as a negative: judging the planted gap with the 1993 spread would say "confirmed"
  const wrongT = gap / (a.s * Math.sqrt(2 / 13));
  check(c, 'negative: the 1993-spread shortcut would have called the printed gap confirmed', wrongT > St.tQuantile(0.975, 24));
  // full pattern
  const fp = E.plantPattern(rows, { best: a.means[0], good: a.means[1], least: a.means[2] });
  const rf = E.runControl(E.groupsAt(fp, 18, 'pa'));
  check(c, 'power: full-pattern plant agrees with scipy and reports its negative estimates',
    rel(rf.goodLeast.p, XC.full.goodLeast.p, 1e-9) && rel(rf.kw.p, XC.full.omni.pKW, 1e-7) && fp.meta.negativeTotals === XC.full.negatives && fp.meta.negativeWeekly > 0);
  // the replication's own interval
  const ci = E.observedInterval(G0);
  check(c, 'power: the observed interval upper bound is where the observed-against-gap p crosses .05', near(E.observedAgainst(G0, ci.hi).p, 0.05, 1e-9));
  // the second layer's power curve, through the function page.js calls one gap at a time
  const curve = E.powerCurve(rows, F.CURVE_GAPS, { draws: S.o.curveDraws, seed: S.o.seed });
  check(c, 'curve: rises across the grid within Monte Carlo error', curve.every((p, i) => i === 0 || p.power >= curve[i - 1].power - 3 * Math.max(p.se, 0.005)) && curve[curve.length - 1].power > 0.85 && curve[0].power < 0.06);
  const lo = curve.filter((p) => p.gap <= gap).pop(), hi = curve.find((p) => p.gap > gap);
  check(c, 'curve: the grid points either side of the printed gap bracket its plant\u2019s power', lo.power <= S.plants.hours.boot.power + 0.01 && hi.power >= S.plants.hours.boot.power - 0.01, `${lo.power} ${S.plants.hours.boot.power} ${hi.power}`);
  const below = curve.filter((p) => p.gap <= S.ci.hi).pop(), above = curve.find((p) => p.gap > S.ci.hi);
  check(c, 'curve: the observed-against-gap p crosses .05 between the grid points around the interval edge', below.pObserved >= 0.05 && above.pObserved < 0.05);
  check(c, 'curve: the zero-gap calibration the page prints is the curve\u2019s first point, and numpy agrees', curve[0].power === S.curve0.power && near(S.curve0.power, XC.boot_zero, 0.015) && FIG['curve.zero'] === F.fix(curve[0].power, 3));
  check(c, 'curve: the calibration is above the nominal rate, so the page\u2019s powers lean toward the replication', S.curve0.power > E.ALPHA / 2);
  const pageJs = read(path.join(PUB, 'page.js'));
  check(c, 'curve: page.js draws the curve through engine.powerCurve, not a copy of it', /E\.powerCurve\(app\.rows, \[F\.CURVE_GAPS\[i\]\]/.test(pageJs) && !/bootstrapPower/.test(pageJs));
  // the operable instrument (gap and group size)
  const i13 = F.instrumentFigures(rows, S, {});
  check(c, 'instrument: at its defaults it reproduces the plant panel exactly (same function, same stream)', i13.run.power === S.plants.hours.boot.power && i13.run.hits === S.plants.hours.boot.hits && i13.run.gap === gap);
  const i72 = F.instrumentFigures(rows, S, { instN: S.nct.n80print });
  check(c, 'instrument: at the normal-theory size for 80% the resampled power is near 80% and near numpy', i72.run.power > 0.75 && i72.run.power < 0.9 && near(i72.run.power, XC.boot_n72, 0.015) && S.instN80.power === i72.run.power && FIG['inst.n80.power'] === F.fix(i72.run.power, 2), `${i72.run.power} ${XC.boot_n72}`);
  check(c, 'instrument: a planted gap of zero at 80 a group stays near the calibration (the group size alone manufactures nothing)', F.instrumentFigures(rows, S, { instGap: 0, instN: 80 }).run.power < 0.06);
  check(c, 'instrument: refuses a group size past its limit', F.instrumentFigures(rows, S, { instN: E.GROUP_SIZE_MAX + 1 }).refused && refused(() => E.bootstrapPower(G0, { n: 1.5 })));
  check(c, 'instrument: the page\u2019s sliders start at the printed gap and the replication\u2019s size', HTML.includes(`<input type="range" id="inst-gap" min="0" max="6000" step="1" value="${gap}"`) && HTML.includes(`<input type="range" id="inst-n" min="${F.INST_N_MIN}" max="${E.GROUP_SIZE_MAX}" step="1" value="${G0.best.length}"`) && F.INST_N_MIN === G0.best.length);
}

// ================================================================================================ 5. the claimants' method on nothing
function nullMethod() {
  const c = 'null_method';
  const G = S.G;
  const perm = E.nullRuns(G, { draws: 20000, seed: 1993, family: 'perm' });
  const resid = E.nullRuns(G, { draws: 20000, seed: 1993, family: 'resid' });
  const own = E.nullRuns(G, { draws: 20000, seed: 1993, family: 'own' });
  const ownN = E.nullRuns(G, { draws: 20000, seed: 1993, family: 'ownNormal' });
  // one shared spread: a pooled-error contrast is correctly sized, and these must come back nominal
  check(c, 'nulls: best over good rate in [0.018, 0.031] (shuffled labels, shared spread)', perm.bestOverGood >= 0.018 && perm.bestOverGood <= 0.031, perm.bestOverGood);
  check(c, 'nulls: best over good rate in [0.018, 0.031] (pooled residuals, shared spread)', resid.bestOverGood >= 0.018 && resid.bestOverGood <= 0.031, resid.bestOverGood);
  // each group's own 2019 spread: the page says the step is liberal; this is the check that goes red if it is not
  check(c, 'nulls: with the 2019 spreads kept, best over good fires well above nominal (own residuals)', own.bestOverGood > 0.035, own.bestOverGood);
  check(c, 'nulls: with the 2019 spreads kept, best over good fires well above nominal (own normal spreads)', ownN.bestOverGood > 0.035, ownN.bestOverGood);
  check(c, 'nulls: and the second contrast alone turns conservative there', own.topTwoOverLeast < E.ALPHA / 2 && ownN.topTwoOverLeast < E.ALPHA / 2);
  check(c, 'nulls: complete correspondence below 0.003 (all four families)', [perm, resid, own, ownN].every((r) => r.complete < 0.003));
  check(c, 'nulls: the mechanism the page names holds in the rows: the least accomplished group is the tightest', S.control.summary.least.sd < S.control.summary.best.sd && S.control.summary.least.sd < S.control.summary.good.sd);
  // control on the control: the same 'own' family, on a COPY of the groups rescaled to one shared spread, must
  // come back near nominal, so the inflation is the spreads and not the resampling machinery
  const sp3 = E.pooledSD3(G), H = {};
  for (const g of E.GROUPS) { const m = St.mean(G[g]), sd = St.sd(G[g]); H[g] = G[g].map((x) => m + (x - m) * sp3 / sd); }
  const ownEq = E.nullRuns(H, { draws: 20000, seed: 1993, family: 'own' });
  check(c, 'nulls: control, own-residual resampling with the spreads made equal comes back near nominal and near numpy', ownEq.bestOverGood >= 0.018 && ownEq.bestOverGood <= 0.034 && near(ownEq.bestOverGood, XC.null_own_equal[0], 0.004), ownEq.bestOverGood);
  check(c, 'nulls: agree with the 100,000-draw numpy estimates within 0.004', near(perm.bestOverGood, XC.null_perm[0], 0.004) && near(resid.bestOverGood, XC.null_resid[0], 0.004) && near(perm.complete, XC.null_perm[2], 0.002)
    && near(own.bestOverGood, XC.null_own[0], 0.004) && near(ownN.bestOverGood, XC.null_own_normal[0], 0.004) && near(own.topTwoOverLeast, XC.null_own[1], 0.004) && near(ownN.complete, XC.null_own_normal[2], 0.002), `${own.bestOverGood} ${XC.null_own[0]} ${ownN.bestOverGood} ${XC.null_own_normal[0]}`);
  check(c, 'nulls: the page shows the 20,000-draw figures of all four families', S.nulls.perm.draws === 20000 && S.nulls.perm.bestOverGood === perm.bestOverGood && S.nulls.resid.complete === resid.complete
    && S.nulls.own.bestOverGood === own.bestOverGood && S.nulls.ownNormal.bestOverGood === ownN.bestOverGood);
  check(c, 'nulls: the null runs call procedure1993 itself', /const r = procedure1993\(draw\(\), \{ Fcrit: Fc \}\)/.test(read(path.join(PUB, 'engine.js'))));
  // the 'own' family redrawn here from the same random stream, with the pooled contrasts written again
  // independently of engine.contrastF: the counts must match exactly
  {
    const rnd = St.mulberry32(1993), R = {};
    for (const g of E.GROUPS) { const m = St.mean(G[g]); R[g] = G[g].map((x) => x - m); }
    const Fc = St.fCrit1(27);
    let a1 = 0, cc = 0;
    for (let i = 0; i < 20000; i++) {
      const d = {};
      for (const g of E.GROUPS) { d[g] = []; for (let j = 0; j < 10; j++) d[g].push(R[g][Math.floor(rnd() * R[g].length)]); }
      const ms = E.GROUPS.map((g) => d[g].reduce((x, y) => x + y, 0) / 10);
      const ssw = E.GROUPS.reduce((acc, g, k) => acc + d[g].reduce((x, y) => x + (y - ms[k]) ** 2, 0), 0);
      const msw = ssw / 27;
      const c1 = ms[0] - ms[1], c2 = (ms[0] + ms[1]) / 2 - ms[2];
      const s1 = c1 > 0 && c1 * c1 / (msw * 0.2) > Fc, s2 = c2 > 0 && c2 * c2 / (msw * 0.15) > Fc;
      if (s1) a1++; if (s1 && s2) cc++;
    }
    check(c, 'nulls: an independent redraw of the own-spread family from the same stream gives the same counts', a1 === own.counts.bestOverGood && cc === own.counts.complete, `${a1}/${own.counts.bestOverGood} ${cc}/${own.counts.complete}`);
  }
  // positive control for the null machinery: the same draws with the standardized 1993 gap added to the
  // best group are found far more often, so the null runs are not a silent no-op
  const residPool = E.GROUPS.flatMap((g) => { const m = G[g].reduce((a, b) => a + b, 0) / G[g].length; return G[g].map((v) => v - m); });
  const rnd = St.mulberry32(11), gap = S.gaps.standardized.gap, Fc = St.fCrit1(27);
  let hits = 0;
  for (let i = 0; i < 4000; i++) {
    const w = residPool.slice();
    for (let j = w.length - 1; j > 0; j--) { const k = Math.floor(rnd() * (j + 1)); [w[j], w[k]] = [w[k], w[j]]; }
    if (E.procedure1993({ best: w.slice(0, 10).map((v) => v + gap), good: w.slice(10, 20), least: w.slice(20, 30) }, { Fcrit: Fc }).bestOverGood) hits++;
  }
  check(c, 'nulls: positive control, the standardized gap planted into the 1993 design is found far above the null rate', hits / 4000 > 0.2, hits / 4000);
  check(c, 'nulls: record.json null result is the computed text, and reports both kinds of spread', RECORD.null_through_claimant_method.applicable === true && RECORD.null_through_claimant_method.result.includes(F.pct(S.nulls.perm.bestOverGood, 2))
    && RECORD.null_through_claimant_method.result.includes(F.pct(S.nulls.own.bestOverGood, 2)) && RECORD.null_through_claimant_method.result.includes(F.pct(S.nulls.ownNormal.bestOverGood, 2)));
  check(c, 'nulls: no page text says the procedure shows no inflation', !/finds no inflation|does not make the\s+claim out of nothing|does not manufacture the claim;/.test(HTML + JSON.stringify(RECORD)));
}

// ================================================================================================ 6. refusals
function refusals() {
  const c = 'refusal_asserted';
  check(c, 'refuse: no test past 18, with the counts of short histories', refused(() => E.groupsAt(rows, 19, 'pa'), /no test past age 18: at 19, 0 best, 1 good and 3 least accomplished/));
  check(c, 'refuse: at 20 the counts are 0, 7 and 5', refused(() => E.groupsAt(rows, 20, 'pa'), /at 20, 0 best, 7 good and 5 least accomplished/));
  check(c, 'refuse: teacher-designed practice is refused past 18 too', refused(() => E.groupsAt(rows, 19, 'td')));
  const aged18 = rows.find((r) => r.age === 18);
  check(c, 'refuse: accumulating a history past its interview age', refused(() => E.accumulate(aged18, 'pa', 19), /holds no estimate for the years after that/));
  check(c, 'refuse: professionals', refused(() => E.refuseProfessionals(), /4 professional violinists against 10 in 1993/));
  check(c, 'refuse: the professionals refusal states what each study did (the 1993 study tested its 10 once, p. 380)', refused(() => E.refuseProfessionals(), /the replication ran no test on its 4, the 1993 study tested its 10 on practice only once/) && !/neither study (put|used)/i.test(HTML));
  const cf19 = F.controlFigures(rows, { age: 19 }), cfp = F.controlFigures(rows, { pair: 'professionals' });
  check(c, 'refuse: the control panel reports the age refusal', cf19.refused && /^Refused: no test past age 18/.test(cf19.figures['ctl.refusal']));
  check(c, 'refuse: the control panel reports the professionals refusal', cfp.refused && /^Refused: .*professional/.test(cfp.figures['ctl.refusal']));
  check(c, 'not blanket: age 18 and age 10 are allowed', !refused(() => E.groupsAt(rows, 18, 'pa')) && !refused(() => E.groupsAt(rows, 10, 'td')));
  check(c, 'refuse: an unknown measure or pairwise rule', refused(() => E.groupsAt(rows, 18, 'xx')) && refused(() => E.pairTest([1, 2], [3, 4], 'ranks')));
  const lines = csvText.split('\n'); const head = lines[0].split(',');
  const li = lines.findIndex((l) => l.startsWith('G08,')); const fields = lines[li].split(',');
  fields[head.indexOf('pa19')] = '9'; const late = lines.slice(); late[li] = fields.join(',');
  check(c, 'refuse: the parser rejects an estimate recorded after the interview', fields[head.indexOf('age')] === '18' && threwData(() => D.parseViolinists(late.join('\n'))));
  check(c, 'the page offers the refused inputs: age slider to 20 and a professionals option', /<input type="range" id="age" min="10" max="20"/.test(HTML) && /<option value="professionals">/.test(HTML));
  check(c, 'the page explains the refusal in prose', /the page refuses to test/.test(HTML) && /no estimate for years they had not yet lived/.test(HTML));
  check(c, 'the sandbox refuses a best mean at or below the good mean', /best must exceed good/.test(read(path.join(PUB, 'page.js'))));
}

// ================================================================================================ 7. planted faults
function faults() {
  const c = 'planted_fault_caught';
  const printedBest = num(D.PRINTED['mm.pa.best'].v);
  const reproduces = (rs) => { const G = E.groupsAt(rs, 18, 'pa'); const m = G.best.reduce((a, b) => a + b, 0) / G.best.length; return Math.round(m) === printedBest; };
  check(c, 'baseline: the unmodified rows reproduce the printed 8224', reproduces(rows));
  const dbl = E.doubleConvert(rows, 'B01');
  check(c, 'fault: one best violinist converted by 52 twice fails the 8224 anchor', !reproduces(dbl));
  check(c, 'fault: and fails the authors’ own totals', !E.authorsTotalsAgree(dbl));
  check(c, 'fault: the doubled row went through the unmodified engine (mean far above printed)', E.groupsAt(dbl, 18, 'pa').best.reduce((a, b) => a + b, 0) / 13 > 50000 && near(E.groupsAt(dbl, 18, 'pa').best.reduce((a, b) => a + b, 0) / 13, XC.fault_best_mean, 1e-6));
  // a mislabelled row in a copy of the CSV text, parsed by the unmodified parser
  const swapped = D.parseViolinists(csvText.replace(/^B01,3,best,/m, 'B01,3,good,'));
  check(c, 'fault: one best violinist relabelled good fails the anchor', !reproduces(swapped) && swapped.filter((r) => r.group === 'best').length === 12);
  check(c, 'fault: a dropped weekly cell (one year of one row) fails the authors’ totals', !E.authorsTotalsAgree(D.parseViolinists(csvText.replace(/^(B01,3,best,25,10,14664,14352,,,\.,0,)19,/m, '$1,'))));
  check(c, 'fault: a truncated row is rejected by the parser', threwData(() => D.parseViolinists(csvText.replace(/^(B02,[^\n]*),[^,\n]*$/m, '$1'))));
  const badClaim = JSON.parse(claimText); badClaim.practiceAlone.groups.least.mean = 3520;
  check(c, 'fault: a wrong teachers mean in the claim record fails the anchor', !E.anchor1993(badClaim).agrees);
}

// ================================================================================================ 8. choices
function choices() {
  const c = 'choices_are_live';
  const pf = (ch) => F.plantFigures(S, rows, { ...F.DEFAULTS, draws: 2000, ...ch }).figures;
  const cf = (ch) => F.controlFigures(rows, ch).figures;
  const nf = (ch) => F.nullFigures(S.G, { ...F.DEFAULTS, nullDraws: 3000, ...ch }).figures;
  const tf = (u) => F.twoFigures(S.two, u).figures;
  const tests = {
    size: () => { const h = pf({ size: 'hours' }), r = pf({ size: 'ratio' }), s = pf({ size: 'standardized' }); return h['plant.bg'] !== r['plant.bg'] && r['plant.bg'] !== s['plant.bg'] && h['plant.verdict'] !== r['plant.verdict'] && h['plant.boot'] !== s['plant.boot']; },
    age: () => { const a = cf({ age: 18 }), b = cf({ age: 12 }); return a['ctl.best.mean'] !== b['ctl.best.mean'] && a['ctl.test'] !== b['ctl.test']; },
    test: () => cf({ test: 'levene' })['ctl.test'] !== cf({ test: 'contrast1993' })['ctl.test'],
    measure: () => cf({ measure: 'pa' })['ctl.best.mean'] !== cf({ measure: 'td' })['ctl.best.mean'],
    plant: () => { const g = pf({ plant: 'gap' }), f = pf({ plant: 'full' }); return g['plant.gl'] !== f['plant.gl'] && g['plant.what'] !== f['plant.what']; },
    pair: () => cf({ pair: 'bestGood' })['ctl.test'] !== cf({ pair: 'goodLeast' })['ctl.test'] && /^Refused/.test(cf({ pair: 'professionals' })['ctl.refusal']),
    seed: () => pf({ seed: 20190821 })['plant.boot'] !== pf({ seed: 7 })['plant.boot'],
    family: () => new Set(E.NULL_FAMILIES.map((family) => nf({ family })['null.bog'])).size === E.NULL_FAMILIES.length && new Set(E.NULL_FAMILIES.map((family) => nf({ family })['null.what'])).size === E.NULL_FAMILIES.length,
    unit: () => tf('hours')['two.live.1993'] !== tf('d')['two.live.1993'],
    instGap: () => F.instrumentFigures(rows, S, { instGap: 0 }).figures['inst.power'] !== F.instrumentFigures(rows, S, { instGap: 4000 }).figures['inst.power']
      && F.instrumentFigures(rows, S, { instGap: 0 }).figures['inst.obs'] !== F.instrumentFigures(rows, S, { instGap: 4000 }).figures['inst.obs'],
    instN: () => F.instrumentFigures(rows, S, { instN: 13 }).figures['inst.power'] !== F.instrumentFigures(rows, S, { instN: 40 }).figures['inst.power'],
  };
  for (const ch of RECORD.choices) {
    const fn = tests[ch.id];
    check(c, `choice ${ch.id} has a liveness test`, !!fn);
    if (fn) check(c, `choice ${ch.id} moves a named output`, fn() && ch.inert === false);
  }
  check(c, 'every liveness test corresponds to a declared choice', Object.keys(tests).every((k) => RECORD.choices.some((ch) => ch.id === k)));
  const controls = { size: /name="size" value="hours" checked/, plant: /name="plant" value="gap" checked/, measure: /name="measure" value="pa" checked/, test: /name="test" value="levene" checked/,
    family: new RegExp(`name="family" value="${F.DEFAULTS.family}" checked`), unit: /name="unit" value="hours" checked/, age: /id="age" min="10" max="20" step="1" value="18"/, pair: /<select id="pair">/, seed: /id="seed" value="20190821"/,
    instGap: /<input type="range" id="inst-gap"/, instN: /<input type="range" id="inst-n"/ };
  for (const [k, re] of Object.entries(controls)) check(c, `the page has the ${k} control at its declared default`, re.test(HTML));
  check(c, 'every radio group and input has a label', (HTML.match(/<input type="radio"/g) || []).length === (HTML.match(/<label><input type="radio"/g) || []).length);
  check(c, 'the null section starts on the family that keeps each group\u2019s own spread (the one that can show the Type I argument)', E.NULL_SPREAD[F.DEFAULTS.family] === 'own' && RECORD.choices.find((ch) => ch.id === 'family').default.startsWith('own spreads'));
  check(c, 'under the full-pattern plant the size radios are disabled, not only dimmed', /el\.disabled = full/.test(read(path.join(PUB, 'page.js'))) && /id="size-note" hidden/.test(HTML));
}

// ================================================================================================ 9. the rendered page
function decode(s) { return s.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&middot;/g, '·').replace(/&amp;/g, '&'); }
function spans(html, attr) {
  const out = [];
  const re = new RegExp(`<(\\w+)[^>]*\\s${attr}="([^"]+)"[^>]*>`, 'g');
  let m;
  while ((m = re.exec(html))) {
    const tag = m[1], start = m.index + m[0].length;
    // find the matching close tag, allowing nested elements of other tags and of the same tag
    let depth = 1, i = start;
    const open = new RegExp(`<${tag}[\\s>]`, 'g'), close = new RegExp(`</${tag}>`, 'g');
    while (depth > 0) {
      open.lastIndex = i; close.lastIndex = i;
      const o = open.exec(html), cl = close.exec(html);
      if (!cl) break;
      if (o && o.index < cl.index) { depth++; i = o.index + 1; } else { depth--; i = cl.index + cl[0].length; if (depth === 0) out.push({ key: m[2], inner: html.slice(start, cl.index) }); }
    }
  }
  return out.map((s) => ({ key: s.key, text: decode(s.inner.replace(/<[^>]+>/g, '')), inner: s.inner }));
}
const meta = (html, attr, name) => { const m = html.match(new RegExp(`<meta ${attr}="${name.replace(/[.:]/g, (x) => '\\' + x)}" content="([^"]*)"`)); return m ? decode(m[1]) : null; };
function unboundText(html) {
  let t = html.replace(/<!--[\s\S]*?-->/g, ' ').replace(/<head>[\s\S]*?<\/head>/, ' ').replace(/<script[\s\S]*?<\/script>/g, ' ').replace(/<style[\s\S]*?<\/style>/g, ' ');
  for (let i = 0; i < 6; i++) t = t.replace(/<(\w+)[^>]*\sdata-(fig|printed|quote|source|meta|verdict)="[^"]+"[^>]*>(?:(?!<\1[\s>])[\s\S])*?<\/\1>/g, ' ');
  return decode(t.replace(/<[^>]+>/g, ' '));
}
// every numeral left in prose that no computed or printed binding covers, with its count and its reason
const ALLOWED = {
  '0': [1, 'CC0'], '0.05': [1, 'the significance line, 0.05'], '05': [2, 'two-sided .05'], '1': [5, 'F(1, df) numerator df and the numbered heading 1.'],
  '1.0': [1, 'CC0 1.0'], '1.96': [2, 'the z convention of the printed intervals'], '10,000': [4, 'the popular number, the subject of section II'],
  '100': [1, 'Psychological Review volume 100'], '11': [1, 'page 11 (the printed competition test)'], '15': [1, 'page 15'], '16': [2, 'page 16'], '17': [2, 'page 17'],
  '18': [13, 'the test age, age 18'], '190327': [1, 'article number'], '1993': [65, 'year of the claim'], '2': [4, '2t (twice), heading 2., from age 2'],
  '20': [4, 'age 20 (Figure 9, the replication’s sentence)'], '2008': [1, 'Gladwell’s book'], '2014': [6, 'Ericsson 2014; recruitment began 2014'],
  '2017': [1, 'preregistration year'], '2018': [2, 'recruitment ended'], '2019': [52, 'year of the replication'], '2020': [3, 'Ericsson died 2020; the 2020 reply'],
  '2026': [1, 'the date the supplement was read, 2026-09-23'], '09': [1, 'the date the supplement was read, 2026-09-23'], '23': [1, 'the date the supplement was read, 2026-09-23'],
  '21': [1, '21 August 2019'], '256': [4, 'SHA-256'], '3': [4, 'issue 100(3), three groups, heading 3.'], '363': [1, 'page 363'], '374': [3, 'page 374'], '379': [1, 'page 379'],
  '380': [1, 'page 380 (the 1993 professionals test)'], '393': [1, 'pages 393 to 394'], '394': [1, 'pages 393 to 394'],
  '4': [3, 'the 4 professionals in the workbook (sheet rows 42 to 45), heading 4., source 4'], '4.0': [3, 'CC BY 4.0'], '401': [1, 'HTTP 401'],
  '403': [2, 'HTTP 403'], '4595': [1, 'OSF project 4595q'], '5': [1, 'page 5'], '6': [1, 'volume 6'], '9': [2, 'Figure 9'], '95': [3, '95% intervals'],
};
function surface(html) {
  const fails = [], all = [];
  const ok = (name, cond, d = '') => { all.push([name, !!cond, d]); if (!cond) fails.push(`${name}${d ? ` (${d})` : ''}`); };
  const figs = spans(html, 'data-fig');
  ok('the page carries at least 250 bound figures', figs.length >= 250, figs.length);
  for (const s of figs) {
    if (!(s.key in FIG)) { ok(`figure ${s.key} is computed`, false); continue; }
    ok(`figure ${s.key} equals the recomputed value`, s.text === FIG[s.key], `${s.text} vs ${FIG[s.key]}`);
  }
  const shown = new Set(figs.map((s) => s.key));
  for (const k of ['claim.best', 'a.F2', 'c.best.mean', 'c.bg.t', 'p.F2', 'pl.h.p', 'pl.h.boot', 'headline', 'n.perm.bog', 'two.p', 'scope', 'novelty']) ok(`key figure ${k} is shown`, shown.has(k));
  for (const s of spans(html, 'data-printed')) ok(`printed ${s.key} equals the registry`, D.PRINTED[s.key] && s.text === D.PRINTED[s.key].v, s.text);
  for (const s of spans(html, 'data-quote')) ok(`quotation ${s.key} equals the registry`, D.QUOTES[s.key] && s.text === D.QUOTES[s.key].text);
  for (const s of spans(html, 'data-source')) ok(`source ${s.key} equals the registry`, D.SOURCES[s.key] && s.text === D.SOURCES[s.key]);
  const metaSpans = spans(html, 'data-meta');
  ok('the dek appears in the body', metaSpans.some((s) => s.key === 'dek' && s.text === FM.dek));
  // head
  const title = (html.match(/<title>([^<]*)<\/title>/) || [])[1];
  ok('title is the seoTitle', title && decode(title) === FM.seoTitle, title);
  ok('meta description is the dek', meta(html, 'name', 'description') === FM.dek);
  ok('og:description is the dek', meta(html, 'property', 'og:description') === FM.dek);
  ok('twitter:description is the dek', meta(html, 'name', 'twitter:description') === FM.dek);
  ok('og:title is the title', meta(html, 'property', 'og:title') === `${FM.title} · Artificial Wasteland`);
  ok('twitter:title is the title', meta(html, 'name', 'twitter:title') === `${FM.title} · Artificial Wasteland`);
  ok('og:url and canonical', meta(html, 'property', 'og:url') === `https://artwaste.land/strata/${SLUG}/` && html.includes(`<link rel="canonical" href="https://artwaste.land/strata/${SLUG}/" />`));
  ok('og:image and twitter:image', meta(html, 'property', 'og:image') === `https://artwaste.land/og/${SLUG}.png` && meta(html, 'name', 'twitter:image') === `https://artwaste.land/og/${SLUG}.png`);
  const ld = html.match(/<script type="application\/ld\+json">([\s\S]*?)<\/script>/);
  let J = null; try { J = JSON.parse(ld[1]); } catch { J = null; }
  ok('JSON-LD parses', !!J);
  // the landing date is the supervisor's to set, so the two date fields are checked for form, everything else for identity
  const undated = (o) => { const x = { ...o }; delete x.datePublished; delete x.dateModified; return JSON.stringify(x); };
  ok('JSON-LD is the Article built from the frontmatter', J && undated(J) === undated(jsonld(FM, SLUG)) && J.name === FM.seoTitle && J.headline === FM.title && J.description === FM.dek);
  ok('JSON-LD dates are ISO dates', J && /^\d{4}-\d{2}-\d{2}$/.test(J.datePublished) && /^\d{4}-\d{2}-\d{2}$/.test(J.dateModified));
  ok('the H1 is the title', html.includes(`<h1>${FM.title}</h1>`));
  // the frontmatter's own numbers are the engine's
  ok('the frontmatter dek is the text facts.dek() generates', FM.dek === F.dek(S));
  ok('the frontmatter plain is the text facts.plain() generates', FM.plain === F.plain(S));
  ok('the headline is in the page and equals record.json', FIG.headline === RECORD.headline && html.includes(RECORD.headline));
  // census
  const counts = {};
  for (const m of unboundText(html).matchAll(/\d[\d,.]*\d|\d/g)) counts[m[0]] = (counts[m[0]] || 0) + 1;
  for (const [n, k] of Object.entries(counts)) ok(`unbound numeral ${n} is allowed with its count`, ALLOWED[n] && ALLOWED[n][0] === k, `seen ${k}, allowed ${ALLOWED[n] ? ALLOWED[n][0] : 0}`);
  for (const [n, [k]] of Object.entries(ALLOWED)) ok(`allowed numeral ${n} still appears ${k} times`, counts[n] === k, `seen ${counts[n] || 0}`);
  // the whole page equals the page regenerated from recomputed values
  const regenerated = fill(read(path.join(HERE, 'page-source.html')), { figures: FIG, printed: D.PRINTED, quotes: D.QUOTES, sources: D.SOURCES, fm: FM, slug: SLUG });
  const dates = (s) => s.replace(/"datePublished":"\d{4}-\d{2}-\d{2}","dateModified":"\d{4}-\d{2}-\d{2}"/, '"datePublished":"D","dateModified":"D"');
  ok('index.html is exactly the page regenerated from recomputed values (JSON-LD dates aside)', dates(regenerated) === dates(html));
  // words a page about an open claim must not use, and closing tags
  ok('no forbidden verdict or charge words', !/\b(debunk\w*|refuted|disproved|fraud\w*|fabricat\w*|misconduct|myth\w*|busted|bias\w*)\b/i.test(html.replace(/<!--[\s\S]*?-->/g, '')));
  ok('load-bearing closing tags', /<\/script>\s*<\/body>\s*<\/html>\s*$/.test(html));
  ok('no em dash in the page', !html.includes('\u2014'));
  // the verdict panel, against record.json
  const vs = spans(html, 'data-verdict'), vget = (k) => vs.filter((s) => s.key === k).map((s) => s.text);
  ok('verdict category equals record.json', vget('category').join() === RECORD.verdict.category);
  ok('verdict date equals record.json', vget('as_of').join() === RECORD.verdict.as_of);
  ok('verdict sources equal record.json', JSON.stringify(vget('source')) === JSON.stringify(RECORD.verdict.sources));
  ok('what would change it equals record.json', vget('would_change').join() === RECORD.verdict.would_change);
  ok('decided by and time to decision', vget('decided_by').join() === 'not yet' && vget('years').join() === 'not decided');
  fails.all = all;
  return fails;
}
function rendered() {
  const c = 'rendered_figures_asserted';
  const fails = surface(HTML);
  for (const [name, cond, d] of fails.all) check(c, `surface: ${name}`, cond, d);
  // quotations and printed numbers are in their sources
  let qc = 0, qn = 0;
  for (const [k, q] of Object.entries(D.QUOTES)) {
    let text = q.text;
    for (const g of q.gap || []) text = text.replace(g, ' ');
    const r = foundIn(q.src, text, q.fix || []);
    if (!r.checked) continue;
    qn++;
    if (check(c, `quotation ${k} is in its source (${q.src})`, r.ok)) qc++;
  }
  notes.push(`quotations checked against sources: ${qc} of ${qn} (of ${Object.keys(D.QUOTES).length}; the rest need copyrighted texts not on this machine)`);
  let pc = 0, pn = 0;
  for (const [k, p] of Object.entries(D.PRINTED)) {
    const r = foundIn(p.src, p.find);
    if (!r.checked) continue;
    pn++;
    if (check(c, `printed ${k} (${p.v}) is in its source`, r.ok && normQ(p.find).includes(normQ(p.v).replace(/−/g, '-')))) pc++;
  }
  notes.push(`printed numbers checked against sources: ${pc} of ${pn} (of ${Object.keys(D.PRINTED).length})`);
  check(c, 'the novelty sentence is bounded and matches record.json', /^We searched .* on 2026-09-22 and did not find /.test(D.NOVELTY) && RECORD.novelty === D.NOVELTY);
  // plain placard rules
  const plain = FM.plain;
  check(c, 'plain placard: 90 to 420 characters, at most 3 sentences, no em dash, no double quote', plain.length >= 90 && plain.length <= 420 && (plain.match(/[.!?](\s|$)/g) || []).length <= 3 && !plain.includes('\u2014') && !plain.includes('"'));
  // scripts: extract every inline script and check it; module files parse; no third-party requests
  const inline = [...HTML.matchAll(/<script(?![^>]*\bsrc=)([^>]*)>([\s\S]*?)<\/script>/g)];
  check(c, 'the only inline script is the JSON-LD', inline.length === 1 && /application\/ld\+json/.test(inline[0][1]));
  for (const f of ['stats.js', 'engine.js', 'data.js', 'facts.js', 'render.js', 'page.js']) {
    let okc = true; try { execFileSync(process.execPath, ['--check', path.join(PUB, f)], { stdio: 'pipe' }); } catch { okc = false; }
    check(c, `${f} parses under node --check`, okc);
    const src = read(path.join(PUB, f));
    check(c, `${f} makes no request to another host`, !/(fetch|import|XMLHttpRequest|WebSocket|EventSource|sendBeacon)\s*\(\s*['"`]https?:/.test(src) && !/new URL\(\s*['"`]https?:/.test(src));
    check(c, `${f} has no em dash`, !src.includes('\u2014'));
  }
  const pageSrc = read(path.join(PUB, 'page.js'));
  check(c, 'page.js fetches only the two pinned files, relative to itself', (pageSrc.match(/fetch\(/g) || []).length === 1 && /fetch\(new URL\(file\.path, import\.meta\.url\)\)/.test(pageSrc));
  check(c, 'the page loads only same-origin scripts and styles', [...HTML.matchAll(/(?:src|href)="([^"]+)"/g)].map((m) => m[1]).filter((u) => /^https?:/.test(u)).every((u) => u.startsWith('https://artwaste.land/')));
  check(c, 'accessibility: reduced-motion guard, focus-visible, live readouts, labelled SVGs', /prefers-reduced-motion:reduce/.test(HTML) && /:focus-visible/.test(HTML) && (HTML.match(/role="status"/g) || []).length >= 10 && (HTML.match(/<svg id="[^"]+" role="img" aria-labelledby="[^"]+"/g) || []).length === 8);
  check(c, 'wide tables sit in an overflow-x wrapper', (HTML.match(/<table>/g) || []).length === (HTML.match(/<div class="tablewrap"><table>/g) || []).length);
  check(c, 'the check panel wraps its hashes in the page\u2019s own CSS (no reliance on the site banner)', /\.check li\{[^}]*overflow-wrap:anywhere/.test(HTML));
  check(c, 'panel headings carry an outline level (no skipped levels for a screen reader)', (HTML.match(/<h4 id="[^"]+" role="heading" aria-level="[234]">/g) || []).length === (HTML.match(/<h4 /g) || []).length);
  // reader-facing words: power is a chance, so no "could not have confirmed" anywhere a reader looks
  const shareable = [HTML, FM.dek, FM.plain, FM.raw].join('\n');
  check(c, 'no reader-facing text says the replication could not have confirmed the claim', !/could not (have )?(confirmed|confirm|said yes|say yes)/i.test(shareable) && !/could NOT/.test(shareable));
  check(c, 'the dek and placard carry the computed one-in-N chance', FM.dek.includes(`one-in-${F.inWords(Math.round(1 / S.plants.hours.boot.power))} chance`) && FM.plain.includes(`one-in-${F.inWords(Math.round(1 / S.plants.hours.boot.power))} chance`));
  check(c, 'the dek says the 1993 hours are group averages', /7,410 hours on average by 18/.test(FM.dek));
  // the relates notes' numbers are the page's (the frontmatter is not part of index.html)
  const rel = [...FM.raw.matchAll(/note: "([^"]*)"/g)].map((m) => m[1]);
  check(c, 'relates notes: four, and their numbers are the computed ones', rel.length === 4 && rel[0].includes(`p = ${FIG['pl.h.p']}`) && rel[0].includes(`in ${F.inWords(Math.round(1 / S.plants.hours.boot.power))} confirms it`)
    && rel[1].includes(`one-in-${F.inWords(Math.round(1 / S.plants.hours.boot.power))} chance`) && rel[3].includes(`d = ${FIG['sk.19.d']}, against ${FIG['sk.93.d']} in 1993`) && rel[3].includes('successful competition entries'));
  // the hero's status lines are built from engine values
  const hr = F.heroRunStatus(S.p1993, rows.length), hp = F.heroPlantStatus(S.plants.hours.run, S.plants.hours.gap);
  check(c, 'hero status lines follow the computed values', hr.includes(`F = ${FIG['p.F2']}, p = ${FIG['p.p2']}`) && hr.includes(`with ${S.p1993.c1 < 0 ? 'good' : 'best'} ahead by ${FIG['c.gapAbs']} h`)
    && hp.includes(`p = ${FIG['pl.h.p']}, ${S.plants.hours.run.confirmsBestOverGood ? 'significant' : 'not significant'}`) && F.heroRunStatus({ ...S.p1993, c1: 500 }, 39).includes('best ahead by 500 h'));
}

// ================================================================================================ 10. the verdict
function verdict() {
  const c = 'verdict_dated';
  const vs = spans(HTML, 'data-verdict');
  const get = (k) => vs.filter((s) => s.key === k);
  check(c, 'category printed and equal to record.json', get('category').length === 1 && get('category')[0].text === RECORD.verdict.category && RECORD.verdict.category === 'OPEN');
  check(c, 'as-of date printed and equal to record.json', get('as_of').length === 1 && get('as_of')[0].text === RECORD.verdict.as_of && /^\d{4}-\d{2}-\d{2}$/.test(RECORD.verdict.as_of));
  const srcs = get('source').map((s) => s.text);
  check(c, 'at least two sources printed, equal to record.json', srcs.length >= 2 && srcs.length === RECORD.verdict.sources.length && srcs.every((s, i) => s === RECORD.verdict.sources[i]));
  const wc = get('would_change');
  check(c, 'what would change it is printed and equal to record.json', wc.length === 1 && wc[0].text === RECORD.verdict.would_change, wc.length ? JSON.stringify([wc[0].text, RECORD.verdict.would_change]) : 'missing');
  check(c, 'decided by and time to decision are printed as not decided', get('decided_by')[0].text === 'not yet' && RECORD.decided_by === 'not-yet' && get('years')[0].text === 'not decided' && RECORD.years_to_decision === null);
  check(c, 'the scope sentence is in the dek, the verdict panel and record.json', FM.dek.includes(F.scopeSentence()) && FIG.scope === F.scopeSentence() && RECORD.verdict.scope.startsWith(F.scopeSentence()));
  check(c, 'an OPEN claim is never called debunked, refuted or disproved', !/\b(debunk(ed|s)?|refuted|disproved)\b/i.test(HTML));
  check(c, 'the verdict rests on the computed power outcome', E.powerBand(S.plants.hours.boot.power) === 'unlikely' && /the replication was unlikely to confirm it at its printed/.test(HTML));
  check(c, 'the verdict panel names the null result for this step and says the category is this page\u2019s reading', /would fire <span data-fig="n\.ratioLo">/.test(HTML) && /OPEN is this page\u2019s reading of that record|OPEN is this page's reading of that record/.test(HTML));
  check(c, 'the page says the 10,000-hour rule is not graded', /This page does not grade the 10,000-hour rule/.test(HTML));
}

// ================================================================================================ 11. record.json
function record() {
  const c = 'record';
  const rebuilt = buildRecord({ S, f: FIG, D, F, St });
  check(c, 'record.json is exactly the manifest rebuilt from recomputed values', JSON.stringify(rebuilt) === JSON.stringify(RECORD));
  for (const k of ['slug', 'title', 'href', 'field', 'claim', 'records', 'anchor', 'control', 'power', 'null_through_claimant_method', 'verdict', 'decided_by', 'choices', 'headline', 'novelty', 'ledger']) check(c, `record.json has ${k}`, RECORD[k] !== undefined);
  check(c, 'record.json claim statement is the quotation as printed', RECORD.claim.statement === D.QUOTES.claim.text);
  check(c, 'record.json anchor.agrees is the computed value', RECORD.anchor.agrees === S.anchor.agrees);
}

// ================================================================================================ 12. the browser
async function browser() {
  const c = 'browser';
  if (ARGS.has('--no-browser')) { notes.push('browser pass skipped (--no-browser)'); return; }
  let chromium;
  try { chromium = createRequire(path.join(ROOT, 'package.json'))('playwright').chromium; } catch { notes.push('Playwright not installed: browser pass skipped'); return; }
  const TYPES = { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.json': 'application/json', '.csv': 'text/csv', '.woff2': 'font/woff2', '.svg': 'image/svg+xml', '.png': 'image/png', '.ico': 'image/x-icon' };
  const root = path.join(ROOT, 'public');
  const server = http.createServer((req, res) => {
    let p = decodeURIComponent(req.url.split('?')[0]); if (p.endsWith('/')) p += 'index.html';
    const f = path.join(root, p);
    if (!f.startsWith(root) || !fs.existsSync(f) || fs.statSync(f).isDirectory()) { res.writeHead(404); res.end(); return; }
    res.writeHead(200, { 'Content-Type': TYPES[path.extname(f)] || 'application/octet-stream' }); fs.createReadStream(f).pipe(res);
  });
  await new Promise((r) => server.listen(0, '127.0.0.1', r));
  const port = server.address().port;
  const b = await chromium.launch();
  const t0 = Date.now();
  try {
    for (const width of [390, 1280]) {
      const ctx = await b.newContext({ viewport: { width, height: 900 } });
      const page = await ctx.newPage();
      const errs = [], external = [];
      page.on('console', (m) => { if (m.type() === 'error') errs.push(m.text()); });
      page.on('pageerror', (e) => errs.push(e.message));
      page.on('request', (r) => { if (!r.url().startsWith(`http://127.0.0.1:${port}/`)) external.push(r.url()); });
      await page.goto(`http://127.0.0.1:${port}/strata/${SLUG}/`, { waitUntil: 'load' });
      await page.waitForFunction(() => /Recomputed in this browser/.test(document.querySelector('#live-check').textContent), null, { timeout: 30000 });
      const live = await page.textContent('#live-check');
      const total = spans(HTML, 'data-fig').length;
      check(c, `browser ${width}: every figure recomputed in the browser agrees`, live.includes(`all ${total} figures on this page agree`), live);
      check(c, `browser ${width}: both data files hash to their pins`, /the 2019 histories: SHA-256 matches; the 1993 numbers: SHA-256 matches/.test(await page.textContent('#prov-live')));
      check(c, `browser ${width}: no horizontal overflow`, (await page.evaluate(() => document.documentElement.scrollWidth - window.innerWidth)) <= 2);
      if (width === 390) {
        await page.click('#hero-run');
        check(c, 'browser: the hero run reports the procedure it just ran', (await page.textContent('#hero-status')) === F.heroRunStatus(S.p1993, rows.length));
        await page.click('#hero-plant');
        check(c, 'browser: the hero plant reports the unmodified control’s p', (await page.textContent('#hero-status')) === F.heroPlantStatus(S.plants.hours.run, S.plants.hours.gap) && (await page.textContent('#hero-status')).includes(`p = ${FIG['pl.h.p']}`));
        await page.click('#hero-run');
        check(c, 'browser: running again after a plant hides the planted paragraph', await page.evaluate(() => document.querySelector('#hero-planted').hidden));
        await page.fill('#age', '19'); await page.dispatchEvent('#age', 'input');
        check(c, 'browser: age 19 is refused on the page', /^Refused: no test past age 18/.test(await page.textContent('[data-fig="ctl.refusal"]')));
        await page.fill('#age', '14'); await page.dispatchEvent('#age', 'input');
        check(c, 'browser: age 14 moves the best mean', (await page.textContent('[data-fig="ctl.best.mean"]')) === F.controlFigures(rows, { age: 14 }).figures['ctl.best.mean']);
        const diamonds = () => page.evaluate(() => [...document.querySelectorAll('#traj-chart path')].filter((p) => /Z$/.test(p.getAttribute('d'))).length);
        const dPa = await diamonds();
        await page.check('input[name="measure"][value="td"]');
        const dTd = await diamonds();
        check(c, 'browser: the 1993 practice-alone diamonds show against practice alone only', dPa === 3 && dTd === 0, `${dPa} ${dTd}`);
        await page.check('input[name="measure"][value="pa"]');
        await page.check('input[name="plant"][value="full"]');
        check(c, 'browser: the full-pattern plant disables the size radios and shows why', await page.evaluate(() => [...document.querySelectorAll('input[name="size"]')].every((el) => el.disabled) && !document.querySelector('#size-note').hidden));
        await page.waitForFunction(() => /Done:/.test(document.querySelector('#plant-status').textContent), null, { timeout: 30000 });
        await page.check('input[name="plant"][value="gap"]');
        check(c, 'browser: back to the gap plant re-enables them', await page.evaluate(() => [...document.querySelectorAll('input[name="size"]')].every((el) => !el.disabled)));
        await page.check('input[name="size"][value="standardized"]');
        const wantS = F.plantFigures(S, rows, { size: 'standardized' }).figures['plant.verdict'];
        let gotS = '';
        try { await page.waitForFunction((w) => document.querySelector('[data-fig="plant.verdict"]').textContent === w, wantS, { timeout: 30000 }); } catch { /* reported below */ }
        gotS = await page.textContent('[data-fig="plant.verdict"]');
        check(c, 'browser: the standardized reading changes the plant verdict to the engine\u2019s words for its band', gotS === wantS && /could have confirmed the claim, short of/.test(gotS), gotS);
        await page.waitForFunction(() => /^Done:/.test(document.querySelector('#curve-status').textContent), null, { timeout: 60000 });
        const drawn = await page.getAttribute('#curve-chart', 'data-power');
        const want = E.powerCurve(rows, F.CURVE_GAPS, { draws: S.o.curveDraws, seed: S.o.seed }).map((p) => p.power).join(',');
        check(c, 'browser: the curve the page drew is engine.powerCurve, point for point', drawn === want, `${String(drawn).slice(0, 60)} vs ${want.slice(0, 60)}`);
        check(c, 'browser: the curve status is not busy once done', (await page.getAttribute('#curve-status', 'aria-busy')) === 'false');
        await page.fill('#inst-n', String(S.nct.n80print)); await page.dispatchEvent('#inst-n', 'change');
        check(c, 'browser: the instrument at 72 a group shows the engine\u2019s resampled power', (await page.textContent('[data-fig="inst.power"]')) === F.instrumentFigures(rows, S, { instN: S.nct.n80print }).figures['inst.power']);
        await page.fill('#inst-gap', '0'); await page.dispatchEvent('#inst-gap', 'change');
        check(c, 'browser: the instrument\u2019s gap moves the observed-against-gap test', (await page.textContent('[data-fig="inst.obs"]')) === F.instrumentFigures(rows, S, { instGap: 0, instN: S.nct.n80print }).figures['inst.obs']);
      }
      check(c, `browser ${width}: no console errors`, errs.length === 0, errs.slice(0, 3).join(' | '));
      check(c, `browser ${width}: no request left this origin`, external.length === 0, external.slice(0, 3).join(' '));
      await ctx.close();
    }
    // with JavaScript off (the page's noscript note supports it) the site banner does not run either, so the
    // page's own CSS must keep a phone from scrolling sideways
    const nojs = await b.newContext({ viewport: { width: 390, height: 900 }, javaScriptEnabled: false });
    const np = await nojs.newPage();
    await np.goto(`http://127.0.0.1:${port}/strata/${SLUG}/`, { waitUntil: 'load' });
    check(c, 'browser 390, JavaScript off: no horizontal overflow', (await np.evaluate(() => document.documentElement.scrollWidth - window.innerWidth)) <= 2);
    await nojs.close();
  } finally { await b.close(); server.close(); }
  notes.push(`browser: ${results.browser.pass} of ${results.browser.pass + results.browser.fail.length} in ${((Date.now() - t0) / 1000).toFixed(1)} s`);
}

// ================================================================================================ --mutate
function mutate() {
  const text = HTML;
  const bodyStart = text.indexOf('<body>');
  let caught = 0, total = 0;
  const misses = [];
  // every numeral the reader can see, in the body, outside tags, comments and scripts
  const re = /\d[\d,.]*\d|\d/g;
  const ranges = [];
  const body = text.slice(bodyStart);
  const skip = /<script[\s\S]*?<\/script>|<style[\s\S]*?<\/style>|<[^>]+>|<!--[\s\S]*?-->/g;
  let last = 0, m;
  while ((m = skip.exec(body))) { if (m.index > last) ranges.push([bodyStart + last, bodyStart + m.index]); last = m.index + m[0].length; }
  for (const [a, b] of ranges) {
    const seg = text.slice(a, b);
    let n;
    re.lastIndex = 0;
    while ((n = re.exec(seg))) {
      const at = a + n.index, s = n[0];
      const last = s[s.length - 1];
      const repl = s.slice(0, -1) + (last === '9' ? '8' : String(Number(last) + 1));
      const mutated = text.slice(0, at) + repl + text.slice(at + s.length);
      total++;
      if (surface(mutated).length > 0) caught++; else misses.push(`${s} near "${text.slice(Math.max(0, at - 30), at + 20).replace(/\s+/g, ' ')}"`);
    }
  }
  // head: every number in the title, description and JSON-LD
  for (const [what, re2] of [['meta description', /(<meta name="description" content="[^"]*?)(\d)/], ['og:description', /(<meta property="og:description" content="[^"]*?)(\d)/], ['JSON-LD', /("description":"[^"]*?)(\d)/], ['title', /(<title>[^<]*?)(\d)/]]) {
    const mm = text.match(re2);
    if (!mm) continue;
    total++;
    const mutated = text.replace(re2, (x, p1, d) => p1 + (d === '9' ? '8' : String(Number(d) + 1)));
    if (surface(mutated).length > 0) caught++; else misses.push(what);
  }
  console.log(`mutate: ${caught} of ${total} corrupted visible numerals caught`);
  if (misses.length) console.log('  missed: ' + misses.slice(0, 20).join('\n  missed: '));
  return caught === total;
}

// ================================================================================================ run
provenance(); anchor(); control(); power(); nullMethod(); refusals(); faults(); choices(); rendered(); verdict(); record();
await browser();
let mutOk = true;
if (ARGS.has('--mutate')) mutOk = mutate();

const failed = Object.values(results).reduce((a, r) => a + r.fail.length, 0);
const passed = Object.values(results).reduce((a, r) => a + r.pass, 0);
const cellOk = (k) => results[k].fail.length === 0 && results[k].pass > 0;
// a ledger cell also needs every non-ledger group it rests on
const support = { control_can_confirm: ['null_method'], rendered_figures_asserted: ['record', 'browser'] };
const ledger = Object.fromEntries(KEYS.map((k) => [k, cellOk(k) && (support[k] || []).every((g) => results[g].fail.length === 0)]));
if (LEDGER) {
  for (const k of KEYS) console.log(`${k}=${ledger[k]}`);
} else {
  for (const [k, r] of Object.entries(results)) {
    console.log(`${r.fail.length ? 'FAIL' : 'ok  '} ${k}: ${r.pass} of ${r.pass + r.fail.length}`);
    for (const f of r.fail.slice(0, 12)) console.log(`       x ${f}`);
  }
  for (const n of notes) console.log(`  note: ${n}`);
  console.log(`${passed + failed} assertions, ${failed} failed`);
}
process.exit(failed || !mutOk ? 1 : 0);
