// smaller-than-we-could-see · verify.mjs
//
//   node research/smaller-than-we-could-see/verify.mjs
//   node research/smaller-than-we-could-see/verify.mjs --selftest    # the negative controls
//   node research/smaller-than-we-could-see/verify.mjs --no-camera   # skip the 23 s re-analysis
//
// Four sections:
//   1. the arithmetic, against closed forms and published tables, not against itself
//   2. the assembly, rebuilt from the members and required to be byte-identical
//   3. the members' own committed numbers, re-derived here by a second route
//   4. the page, in a real browser, if a dist/ build exists
//
// Plus --selftest, which plants a defect in each invariant and requires it to go
// red. A gate that cannot fail proves nothing, which is the whole subject of two
// of the layers on the page being checked.

import { readFileSync, existsSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
import { createServer } from 'node:http';
import * as S from '../../public/strata/smaller-than-we-could-see/engine/stats.mjs';
import * as Bench from '../../public/strata/smaller-than-we-could-see/engine/bench.mjs';
import { DATA } from '../../public/strata/smaller-than-we-could-see/engine/data.mjs';
import { build, serialise, OUT } from './build-data.mjs';
import { apply as inlineApply } from './inline-numbers.mjs';

const HERE = dirname(fileURLToPath(import.meta.url));
const ROOT = join(HERE, '..', '..');
const SKIP_CAMERA = process.argv.includes('--no-camera');

let n = 0, fails = 0;
function ok(name, pass, detail = '') {
  n++;
  if (!pass) fails++;
  console.log(`${pass ? 'ok  ' : 'FAIL'}  ${name}${detail ? '   ' + detail : ''}`);
}
const near = (a, b, tol, name) => ok(name, Math.abs(a - b) <= tol, `${a} vs ${b} (tol ${tol})`);
const app = (slug) => DATA.apparatus.find((a) => a.slug === slug);
const foil = (slug) => DATA.foils.find((f) => f.slug === slug);

/* ═══════════════════ 1 · the arithmetic, against something else ═══════════ */

console.log('\n1 · the arithmetic, against closed forms and published values');

// erf and erfc, against values from Abramowitz and Stegun table 7.1
near(S.erf(1), 0.8427007929497149, 1e-15, 'erf(1)');
near(S.erf(0.5), 0.5204998778130465, 1e-15, 'erf(0.5)');
near(S.erfc(3), 2.2090496998585441e-5, 1e-19, 'erfc(3)');
near(S.erfc(5), 1.5374597944280351e-12, 1e-26, 'erfc(5)');
near(S.erfc(6), 2.1519736712498913e-17, 1e-31, 'erfc(6)');
// the tails are computed from erfc rather than 1 - erf, so they keep their digits
near(S.normCdf(-6.361340902404056), 1e-10, 1e-21, 'the standard normal at -6.36 is a real 1e-10');
near(S.normQuantile(0.975), 1.959963984540054, 1e-12, 'the normal quantile at 0.975');
near(S.normQuantile(0.8), 0.8416212335729143, 1e-12, 'the normal quantile at 0.80');
ok('the quantile inverts the CDF over four decades',
  [0.5, 0.9, 0.99, 0.999, 0.9999].every((p) => Math.abs(S.normCdf(S.normQuantile(p)) - p) < 1e-12));

// the binomial, against hand-computable cases
near(S.binomPmf(10, 5, 0.5), 252 / 1024, 1e-14, 'Bin(10, 1/2) at 5 is 252/1024');
near(S.binomSf(10, 8, 0.5), 56 / 1024, 1e-14, 'the upper tail of Bin(10, 1/2) at 8 is 56/1024');
near(S.binomSf(20, 15, 0.5), 0.020694732666015625, 1e-14, 'the exact sign-test tail at 15 of 20');
ok('the pmf of Bin(40, 0.3) sums to one',
  Math.abs(Array.from({ length: 41 }, (_, k) => S.binomPmf(40, k, 0.3)).reduce((a, b) => a + b, 0) - 1) < 1e-12);
ok('a discrete test spends less than its alpha budget', S.actualSize(254, 0.2, 0.05) < 0.05,
  S.actualSize(254, 0.2, 0.05).toFixed(6));
ok('power is monotone in the true rate',
  [0.2, 0.25, 0.3, 0.4, 0.6, 0.9].every((p, i, xs) => i === 0 || S.binomPower(254, 0.2, 0.05, p) >= S.binomPower(254, 0.2, 0.05, xs[i - 1])));

// the incomplete beta and Student's t, against published table values
near(S.betai(2, 3, 0.5), 0.6875, 1e-12, 'the regularised incomplete beta I(0.5; 2, 3) is 11/16');
near(S.studentTQuantile(0.975, 8), 2.3060041350333, 1e-9, "Student's t at 0.975 with 8 degrees of freedom");
near(S.studentTQuantile(0.975, 1), 12.706204736174698, 1e-7, "Student's t at 0.975 with 1 degree of freedom");
near(S.studentTQuantile(0.95, 10), 1.8124611228107335, 1e-9, "Student's t at 0.95 with 10 degrees of freedom");
ok('t converges on the normal as the degrees of freedom grow',
  Math.abs(S.studentTQuantile(0.975, 1e7) - 1.959963984540054) < 1e-5);

// the resolution is exactly what it is defined to be
for (const a of DATA.apparatus) {
  if (a.model.kind === 'threshold') continue;
  const r = Bench.resolution(a, DATA.conventions);
  near(Bench.detect(a, r, DATA.conventions), DATA.conventions.power, 1e-6,
    `${a.slug}: power at its own resolution is the power demanded`);
}

/* ══════════════════ 2 · the assembly, rebuilt from the members ════════════ */

console.log('\n2 · the assembly, rebuilt from the members and compared byte for byte');

const rebuilt = await build({ camera: SKIP_CAMERA ? app('the-camera-in-the-noise').raw : null });
const committedText = readFileSync(OUT, 'utf8');
const rebuiltText = serialise(rebuilt);
ok(`the committed data.mjs is exactly what rebuilding from the members produces${SKIP_CAMERA ? ' (camera reused)' : ''}`,
  committedText === rebuiltText,
  committedText === rebuiltText ? `${committedText.length} bytes` : 'A MEMBER HAS CHANGED, or this portal has drifted from it');

ok('every number the page uses came from a member file or a member module',
  DATA.apparatus.every((a) => typeof a.source === 'string' && a.source.length > 0)
  && DATA.foils.every((f) => typeof f.source === 'string' && f.source.length > 0));
for (const a of [...DATA.apparatus, ...DATA.foils]) {
  const path = a.source.split(' ')[0];
  if (path.includes('{')) continue;                 // a brace-expanded pair, checked below
  ok(`${a.slug}: its named source exists on disk`, existsSync(join(ROOT, path)), path);
}

/* ═════════ 3 · the members' own numbers, re-derived by a second route ═════ */

console.log("\n3 · the members' own committed numbers, re-derived here");

// the line-up: its p-value and its interval, both recomputed from its counts
const lu = app('the-line-up');
near(S.binomSf(lu.raw.clean.n, lu.raw.clean.correct, lu.raw.clean.chance), lu.raw.clean.p, 1e-9,
  "the line-up's committed p-value re-derives from its own committed counts");
const w = S.wilson(lu.raw.clean.correct, lu.raw.clean.n, 0.95, 1.96);
ok("the line-up's committed interval is a Wilson score interval at a rounded z of 1.96",
  Math.abs(w.lower - lu.interval.committed[0]) < 1e-15 && Math.abs(w.upper - lu.interval.committed[1]) < 1e-15,
  `[${w.lower.toFixed(15)}, ${w.upper.toFixed(15)}]`);
const wExact = S.wilson(lu.raw.clean.correct, lu.raw.clean.n, 0.95);
ok('and the unrounded z moves it in the seventh decimal, which is how the rounding was identified',
  Math.abs(wExact.upper - w.upper) > 1e-7 && Math.abs(wExact.upper - w.upper) < 1e-5,
  (wExact.upper - w.upper).toExponential(2));
// and the exact interval is wider than the score interval, as it must be
const cp = S.clopperPearson(lu.raw.clean.correct, lu.raw.clean.n, 0.95);
ok('the exact interval contains the score interval', cp.lower < w.lower && cp.upper > w.upper,
  `[${cp.lower.toFixed(6)}, ${cp.upper.toFixed(6)}]`);

// the pendulum: recompute the span straight from the layer's own module
const P = await import('../../public/strata/the-string-that-beats-seconds/physics.mjs');
const span = P.normalGravity(90) / P.normalGravity(0) - 1;
near(span, app('the-string-that-beats-seconds').question.effect, 1e-15,
  "the pendulum's pole-to-equator span comes from the layer's own GRS80 function");
near(span * 100, 0.53024, 5e-6, "and it matches the figure the layer's own page prints");
// the crossover angle: check it by the definition, not by the bisection that found it
const pend = app('the-string-that-beats-seconds');
const bias = (d) => Math.abs(1 / P.amplitudeFactor(d) ** 2 - 1);
near(bias(pend.raw.crossoverDegrees), pend.resolution.value, 1e-9,
  'at the crossover angle the ignored-amplitude bias equals the screening floor exactly');
ok('and the crossover is a genuine crossing, not an endpoint',
  bias(pend.raw.crossoverDegrees - 1) < pend.resolution.value && bias(pend.raw.crossoverDegrees + 1) > pend.resolution.value);

// the battery: the layer's own published noise ratio, recomputed
const bat = app('the-battery-that-cant-tell');
near(bat.resolution.alsoPublished.value / bat.question.effect, bat.resolution.alsoPublished.ratio, 1e-9,
  "the battery's committed noise ratio is its floor over its gap");
ok('the battery interval contains zero, which is why its layer refused', bat.interval.includesZero,
  `[${bat.interval.lower.toFixed(6)}, ${bat.interval.upper.toFixed(6)}]`);
ok('the battery interval has the right degrees of freedom for two groups of five', bat.interval.df === 8);

// the clock foil: recompute it from the layer's own estimator over its own trace
const [V, D] = await Promise.all([
  import('../../public/strata/the-clock-in-the-glass/vsync.mjs'),
  import('../../public/strata/the-clock-in-the-glass/data.js'),
]);
const trace = D.TRACES.find((t) => t.label === 'ctl-clamped');
const r = V.estimate(D.decode(trace));
const clock = foil('the-clock-in-the-glass');
near(r.hz, clock.reported, 0, "the clock foil's rate is what the layer's own estimator returns today");
ok('its coherence is exactly one, not a rounded one', r.R === 1, String(r.R));
ok('its interval vanishes at every printed decimal', r.hzCI95 < 1e-12, r.hzCI95.toExponential(3));
ok('its answer is wrong by more than a hundredth of a hertz', Math.abs(r.hz - trace.truth) > 0.01,
  (r.hz - trace.truth).toFixed(6));
ok('THE POINT: neither the coherence nor the interval catches it',
  !V.gate(r).fail.some((f) => f.code === 'coherence') && V.gate(r).pass === false
  && V.gate(r).fail.some((f) => f.code === 'quantum'),
  'caught only by: ' + V.gate(r).fail.map((f) => f.code).join(', '));

// the census foil: the ratio, recomputed from the layer's own committed headline
const cen = foil('the-case-nobody-ran');
const H = JSON.parse(readFileSync(join(ROOT, 'public/strata/the-case-nobody-ran/data.json'), 'utf8')).headline;
ok('the census denominator is the loops actually re-run, not the whole population',
  cen.ran === H.emptySays.held + H.emptySays.silent + H.emptySays.vacuous && cen.ran !== cen.population,
  `${cen.ran} re-run of ${cen.population} found`);
near(cen.fraction, (H.emptySays.silent + H.emptySays.vacuous) / cen.ran, 1e-15,
  'and the fraction is over that denominator');

/* ═══════════════════════ 4 · the claims this page makes ═══════════════════ */
//
// Each claim is a NAMED PREDICATE over the whole dataset, not a line of inline
// arithmetic. That matters here for the same reason the census foil exists: a
// check written inline can only be tested by reading it, while a predicate can
// be handed deliberately broken data and required to notice. Section 5 does
// exactly that to every one of these.

const CLAIMS = [
  {
    name: 'three of the four apparatus were looking for something below one of their own resolutions',
    test: (d) => d.apparatus.filter((a) => a.question.effect / a.resolution.value < 1).length === 3,
    show: (d) => d.apparatus.map((a) => `${a.slug} ${(a.question.effect / a.resolution.value).toFixed(3)}`).join(', '),
    // planting: nudge one refusal above its own resolution
    break: (d) => { d.apparatus[0].resolution.value = d.apparatus[0].question.effect / 2; },
  },
  {
    name: 'and exactly one is far above one, which is the instrument that speaks',
    test: (d) => d.apparatus.filter((a) => a.question.effect / a.resolution.value >= 5).length === 1,
    show: (d) => d.apparatus.filter((a) => a.ratio >= 5).map((a) => a.slug).join(''),
    break: (d) => { d.apparatus.find((a) => a.slug === 'the-camera-in-the-noise').resolution.value *= 20; },
  },
  {
    name: 'the ratio range the page prints is the actual range of its refusals',
    test: (d) => {
      const rs = d.apparatus.filter((a) => a.ratio < 1).map((a) => a.ratio);
      return d.findings.ratioMin === Math.min(...rs) && d.findings.ratioMax === Math.max(...rs);
    },
    show: (d) => `${d.findings.ratioMin.toFixed(4)} to ${d.findings.ratioMax.toFixed(4)}`,
    break: (d) => { d.findings.ratioMin = 0.01; },
  },
  {
    name: 'every positive control here carries a larger effect than the question it was a control for',
    test: (d) => {
      const c = d.apparatus.filter((a) => a.control);
      return c.length === 3 && c.every((a) => a.control.effect / a.question.effect > 1);
    },
    show: (d) => d.apparatus.filter((a) => a.control).map((a) => (a.control.effect / a.question.effect).toFixed(1) + '×').join(', '),
    break: (d) => { d.apparatus.find((a) => a.control).control.effect = 0; },
  },
  {
    name: 'the control range the page prints is the actual range',
    test: (d) => {
      const rs = d.apparatus.filter((a) => a.control).map((a) => a.control.effect / a.question.effect);
      return Math.abs(d.findings.controlOverQuestionMin - Math.min(...rs)) < 1e-12
          && Math.abs(d.findings.controlOverQuestionMax - Math.max(...rs)) < 1e-12;
    },
    show: (d) => `${d.findings.controlOverQuestionMin.toFixed(2)}× to ${d.findings.controlOverQuestionMax.toFixed(2)}×`,
    break: (d) => { d.findings.controlOverQuestionMax = 100; },
  },
  {
    name: 'exactly one resolution here is estimated from the result it describes, and it is labelled',
    test: (d) => {
      const retro = d.apparatus.filter((a) => a.resolution.external === false);
      return retro.length === 1 && typeof retro[0].resolution.externalNote === 'string'
        && retro[0].resolution.externalNote.length > 20;
    },
    show: (d) => d.apparatus.filter((a) => a.resolution.external === false).map((a) => a.slug).join(''),
    // planting: strip the label off the awkward one, which is the exact thing
    // a page would be tempted to do
    break: (d) => { d.apparatus.find((a) => a.resolution.external === false).resolution.externalNote = ''; },
  },
  {
    name: 'the other three resolutions are external to the result they describe',
    test: (d) => d.apparatus.filter((a) => a.resolution.external === true).length === 3,
    show: (d) => d.apparatus.filter((a) => a.resolution.external === true).map((a) => a.slug).join(', '),
    break: (d) => { d.apparatus.find((a) => a.resolution.external === true).resolution.external = false; },
  },
  {
    name: "where both exist, a resolution and an interval's upper end agree within a quarter",
    test: (d) => d.apparatus.filter((a) => a.interval).every((a) => {
      const u = a.interval.upperAboveChance != null ? a.interval.upperAboveChance : a.interval.upper;
      return Math.abs(u / a.resolution.value - 1) < 0.25;
    }),
    show: (d) => d.apparatus.filter((a) => a.interval).map((a) => {
      const u = a.interval.upperAboveChance != null ? a.interval.upperAboveChance : a.interval.upper;
      return (u / a.resolution.value).toFixed(4) + '×';
    }).join(', '),
    break: (d) => { d.apparatus.find((a) => a.interval).interval.upper *= 3; },
  },
  {
    name: 'the alpha claim in section 03 is what the engine actually returns',
    test: (d) => {
      const bat = d.apparatus.find((a) => a.slug === 'the-battery-that-cant-tell');
      const at = (x, alpha) => {
        const c = { alpha, power: 0.8, coverageFactor: 2 };
        return Bench.detect(bat, x * Bench.resolution(bat, c), c);
      };
      // the sentence says the odds worsen at BOTH sampled points, and that the
      // quarter-resolution case worsens more than the half-resolution one
      const halfDrop = at(0.5, 0.05) / at(0.5, 0.001);
      const qtrDrop = at(0.25, 0.05) / at(0.25, 0.001);
      return halfDrop > 1.5 && qtrDrop > halfDrop;
    },
    show: (d) => {
      const bat = d.apparatus.find((a) => a.slug === 'the-battery-that-cant-tell');
      const at = (x, alpha) => {
        const c = { alpha, power: 0.8, coverageFactor: 2 };
        return Bench.detect(bat, x * Bench.resolution(bat, c), c);
      };
      return `half ${at(0.5, 0.05).toFixed(3)}->${at(0.5, 0.001).toFixed(3)}, quarter ${at(0.25, 0.05).toFixed(3)}->${at(0.25, 0.001).toFixed(3)}`;
    },
    // planting: a model whose power does not depend on alpha at all
    break: (d) => { d.apparatus.find((a) => a.slug === 'the-battery-that-cant-tell').model = { kind: 'threshold', threshold: 0.05 }; },
  },
  {
    name: 'the clock foil is wrong by far more than the interval it quotes',
    test: (d) => {
      const c = d.foils.find((f) => f.slug === 'the-clock-in-the-glass');
      return c.errorOverInterval > 1e6 && !c.caughtBy.includes('coherence');
    },
    show: (d) => d.foils.find((f) => f.slug === 'the-clock-in-the-glass').errorOverInterval.toExponential(2),
    break: (d) => { d.foils.find((f) => f.slug === 'the-clock-in-the-glass').caughtBy.push('coherence'); },
  },
  {
    name: 'the census foil counts its silent checks over the loops it actually re-ran',
    test: (d) => {
      const c = d.foils.find((f) => f.slug === 'the-case-nobody-ran');
      return c.ran < c.population && Math.abs(c.fraction - c.stillGreen / c.ran) < 1e-12;
    },
    show: (d) => {
      const c = d.foils.find((f) => f.slug === 'the-case-nobody-ran');
      return `${c.stillGreen} of ${c.ran} re-run, out of ${c.population} found`;
    },
    break: (d) => { const c = d.foils.find((f) => f.slug === 'the-case-nobody-ran'); c.ran = c.population; },
  },
];

console.log('\n4 · the claims on the page');
for (const c of CLAIMS) ok(c.name, c.test(DATA), c.show(DATA));

// the shipped page must actually contain the sentences this file is about
const PAGE = readFileSync(join(ROOT, 'public/strata/smaller-than-we-could-see/index.html'), 'utf8');
for (const [what, needle] of [
  ['it names the sibling portal', '/strata/the-search-that-could-have-succeeded/'],
  ['it names the paper that argues against its own method', 'Hoenig and Heisey'],
  ['it names Lenth', 'Lenth 2001'],
  ['it names equivalence testing as the correct alternative', 'equivalence test'],
  ['it states the criterion that decides which numbers are legitimate', 'external to the data at hand'],
  ['it names the one member whose number is the condemned kind', 'The battery is the one that is not clean'],
  ['it distinguishes a limit of blank from a limit of detection', 'limit of blank'],
  ['it declares that it is using "resolution" loosely', 'VIM 4.14'],
  ['it carries the canonical way out', 'aw-wayout'],
]) ok(what, PAGE.includes(needle));
// The head is a different surface from the body and it drifted once already:
// the meta description shipped "between 3 and 37" while the data said 2.9, and
// 2.9 is not between 3 and 37. Caught by curling the LIVE page after landing,
// which is the lesson the dek pass wrote down. Pinned here so it cannot recur.
{
  const lo = DATA.findings.controlOverQuestionMin.toFixed(1);
  const hi = DATA.findings.controlOverQuestionMax.toFixed(1);
  const heads = PAGE.match(/<meta [^>]*(?:name|property)="(?:description|og:description|twitter:description)"[^>]*>/g) || [];
  const claiming = heads.filter((h) => /times larger|planted between/.test(h));
  ok('every head description that quotes the control range quotes the computed one',
    claiming.length > 0 && claiming.every((h) => h.includes(lo) && h.includes(hi)),
    `${claiming.length} of ${heads.length} head descriptions make the claim; range is ${lo} to ${hi}`);
}
// Every computed figure the prose quotes is written into the HTML statically as
// well as filled at load, so a reader without JavaScript gets a number instead
// of a hole. That static copy is a second place a figure can go stale, so it is
// recomputed from the engine here and required to match exactly.
{
  const r = inlineApply(PAGE, false);
  ok('every figure inlined in the prose equals what the engine computes',
    r.mismatched.length === 0,
    r.mismatched.length === 0 ? `${r.total} figures` : r.mismatched.map((m) => `${m.id}: "${m.was}" vs "${m.want}"`).join(' | '));
  ok('and the prose quotes a good number of them', r.total >= 25, String(r.total));
}
ok('the page never claims to have proved an absence',
  !/\b(proves|proven|demonstrates) that there is no\b/i.test(PAGE));
ok('and every apparatus and foil it lists is linked',
  DATA.apparatus.every((a) => PAGE.includes(a.href)) && DATA.foils.every((f) => PAGE.includes(f.href)));

/* ═════════════════════════════ 5 · the negative controls ═════════════════ */
//
// Every claim above, handed a copy of the real dataset with one thing broken,
// and required to notice. A claim that stays green here is not measuring what
// its name says, which is the defect the census foil counted 234 times.

if (process.argv.includes('--selftest')) {
  console.log('\n5 · the negative controls: every claim above, run against planted data');
  let sn = 0, sf = 0;
  for (const c of CLAIMS) {
    const broken = structuredClone(DATA);
    c.break(broken);
    const stillGreen = c.test(broken);
    sn++; if (stillGreen) sf++;
    console.log(`${stillGreen ? 'FAIL' : 'ok  '}  goes red when planted: ${c.name}`);
  }
  // and the assembly comparison itself, which is not in CLAIMS
  sn++;
  const tampered = serialise(rebuilt).replace('"alpha": 0.05', '"alpha": 0.06');
  if (tampered === committedText) { sf++; console.log('FAIL  goes red when planted: a tampered data.mjs'); }
  else console.log('ok    goes red when planted: a tampered data.mjs');
  console.log(`\n${sn - sf} / ${sn} negative controls fire`);
  n += sn; fails += sf;
}

/* ═══════════════════════════════ 6 · the page in a browser ═══════════════ */

const DIST = join(ROOT, 'dist');
if (!existsSync(DIST)) {
  console.log('\nSKIP  browser pass: no dist/ build found (run npm run build first)');
} else {
  // Resolve playwright the way scripts/og/generate.mjs does: the repo's own
  // node_modules first, then the container's global install. A bare "not
  // installed" here would be exactly the false negative this page is about.
  let chromium = null;
  try { ({ chromium } = await import('playwright')); }
  catch {
    try { ({ chromium } = (await import('/opt/node22/lib/node_modules/playwright/index.js')).default); }
    catch { /* genuinely absent */ }
  }
  if (!chromium) {
    console.log('\nSKIP  browser pass: playwright not resolvable from either location');
  } else {
    console.log('\n6 · the page, in a real browser');
    const { readFile } = await import('node:fs/promises');
    const types = { '.html': 'text/html', '.mjs': 'text/javascript', '.js': 'text/javascript',
                    '.css': 'text/css', '.json': 'application/json', '.svg': 'image/svg+xml',
                    '.woff2': 'font/woff2', '.png': 'image/png', '.ico': 'image/x-icon' };
    const server = createServer(async (req, res) => {
      let p = decodeURIComponent(req.url.split('?')[0]);
      if (p.endsWith('/')) p += 'index.html';
      try {
        const body = await readFile(join(DIST, p));
        const ext = p.slice(p.lastIndexOf('.'));
        res.writeHead(200, { 'content-type': types[ext] || 'application/octet-stream' });
        res.end(body);
      } catch { res.writeHead(404); res.end('not found'); }
    });
    // port 0: let the OS choose, so a stale server from an interrupted run
    // cannot make this look like a failure of the page.
    await new Promise((done) => server.listen(0, '127.0.0.1', done));
    const PORT = server.address().port;
    const browser = await chromium.launch({ args: ['--no-sandbox'] });
    const errors = [];
    for (const motion of ['no-preference', 'reduce']) {
      const page = await browser.newPage({ reducedMotion: motion, viewport: { width: 1280, height: 900 } });
      page.on('console', (m) => { if (m.type() === 'error') errors.push(m.text()); });
      page.on('pageerror', (e) => errors.push(String(e)));
      // domcontentloaded, not networkidle: the shared home banner keeps a
      // connection open and the page would never be declared idle.
      await page.goto(`http://127.0.0.1:${PORT}/strata/smaller-than-we-could-see/`, { waitUntil: 'domcontentloaded', timeout: 30000 });
      await page.waitForFunction(() => document.getElementById('checkhead')?.textContent?.includes('checks pass'), undefined, { timeout: 30000 });
      const head = await page.$eval('#checkhead', (e) => e.textContent);
      const m = /(\d+) \/ (\d+) checks pass/.exec(head);
      ok(`the in-page panel is all green (${motion})`, m && m[1] === m[2], head);
      ok(`the panel runs at least ten checks (${motion})`, m && Number(m[2]) >= 10);
      const rows = await page.$$eval('#bench-rows tr', (t) => t.length);
      ok(`the bench renders one row per apparatus (${motion})`, rows === DATA.apparatus.length, String(rows));
      const fourRows = await page.$$eval('#four-rows tr', (t) => t.length);
      ok(`the table of four is populated (${motion})`, fourRows === 4, String(fourRows));
      // the dial actually changes the verdicts
      await page.$eval('#dial', (el) => { el.value = '0'; el.dispatchEvent(new Event('input')); });
      const atLow = await page.$eval('#bench-rows', (e) => e.textContent);
      await page.$eval('#dial', (el) => { el.value = '1000'; el.dispatchEvent(new Event('input')); });
      const atHigh = await page.$eval('#bench-rows', (e) => e.textContent);
      ok(`moving the dial changes what the instruments say (${motion})`, atLow !== atHigh);
      // and the reader's own tool responds
      await page.$eval('#r-n', (el) => { el.value = '20'; el.dispatchEvent(new Event('input')); });
      const small = await page.$eval('#r-resolution', (e) => e.textContent);
      // The largest sample the input permits, timed. This assertion exists
      // because the first version of criticalCount was quadratic and this very
      // check hung the browser for minutes at n = 20000. A page a reader can
      // lock up by typing a number into it is a defect, so the budget is here.
      const t0 = Date.now();
      await page.$eval('#r-n', (el) => { el.value = '100000'; el.dispatchEvent(new Event('input')); });
      const big = await page.$eval('#r-resolution', (e) => e.textContent);
      const elapsed = Date.now() - t0;
      ok(`the reader's tool answers at the largest sample it allows, quickly (${motion})`,
        elapsed < 4000, `${elapsed} ms at n = 100000`);
      ok(`a larger sample gives a finer resolution (${motion})`,
        parseFloat(small.replace('+', '')) > parseFloat(big.replace('+', '')), `${small.trim()} then ${big.trim()}`);
      // no horizontal overflow at three widths
      for (const width of [390, 768, 1440]) {
        await page.setViewportSize({ width, height: 900 });
        const over = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
        ok(`no horizontal overflow at ${width}px (${motion})`, over <= 1, `${over}px`);
      }
      await page.close();
    }
    ok('no javascript errors on load', errors.length === 0, errors.slice(0, 3).join(' | '));
    await browser.close();
    await new Promise((done) => server.close(done));
  }
}

console.log(`\n${n - fails} / ${n} checks pass`);
process.exit(fails === 0 ? 0 : 1);
