#!/usr/bin/env node
// verify-the-clock-that-moved-the-particle.mjs
//
// Recomputes every figure public/strata/the-clock-that-moved-the-particle/ shows, and exits
// non-zero on any disagreement. Where it can, it recomputes WITHOUT the page's engine (its own
// quadratic fit, its own bunch association, its own integer sums) and then requires the engine to
// agree; where the engine is the thing under test (the injection, the refusals, the choices), it
// runs the engine on doctored COPIES of the frozen data and inspects what comes out.
//
//   (no flag)      run everything and print a JSON summary
//   --ledger       print exactly the nine contract keys with the booleans actually computed
//   --no-browser   skip the headless rendered-page pass (the static checks still decide)
//
// It never writes data. Regeneration of the frozen extracts is transcribe.py --regen, and the
// manifest is written by freeze-record.mjs --write; this file calls neither.

import fs from 'node:fs';
import path from 'node:path';
import http from 'node:http';
import crypto from 'node:crypto';
import { execFileSync } from 'node:child_process';
import { createRequire } from 'node:module';
import { fileURLToPath } from 'node:url';
import * as E from '../../public/strata/the-clock-that-moved-the-particle/engine.js';
import * as REP from '../../public/strata/the-clock-that-moved-the-particle/report.js';
import { loadRecord, provenanceOk } from '../../public/strata/the-clock-that-moved-the-particle/data.js';
import { factElements, unboundNumbers, visibleText, metaContent, frontmatter, bodyOf, stripNonProse, normalize } from './surface.mjs';

const SLUG = 'the-clock-that-moved-the-particle';
const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, '../..');
const PAGE = path.join(ROOT, 'public/strata', SLUG);
const RESEARCH = HERE;
const ARGS = process.argv.slice(2);
const LEDGER = ARGS.includes('--ledger');
const NO_BROWSER = ARGS.includes('--no-browser');
const KEYS = ['claim_reproduced', 'control_computed', 'control_can_confirm', 'rendered_figures_asserted',
  'choices_are_live', 'planted_fault_caught', 'refusal_asserted', 'provenance_pinned', 'verdict_dated'];

const results = [];
const notes = [];
function check(cell, name, cond, detail = '') { results.push({ cell, name, pass: Boolean(cond), detail: cond ? '' : String(detail) }); }
function refuses(cell, name, fn, message) {
  let thrown = null;
  try { fn(); } catch (e) { thrown = e; }
  check(cell, name, thrown instanceof RangeError && thrown.message === message,
    thrown ? `threw "${thrown.message}"` : 'accepted the input');
}
const near = (a, b, tol) => Number.isFinite(a) && Number.isFinite(b) && Math.abs(a - b) <= tol;
const deepEqual = (a, b) => JSON.stringify(a) === JSON.stringify(b);

// ------------------------------------------------------------------ inputs

const FILES = ['opera-v1-figure8-digitised.json', 'opera-v1-calibration.json', 'icarus-2011-table1.json',
  'lvd-opera-muon-periods.json', 'published-values.json'];
const bytes = Object.fromEntries(FILES.map((f) => [f, fs.readFileSync(path.join(PAGE, 'data', f))]));
const parse = (f) => JSON.parse(bytes[f].toString('utf8'));
const fresh = () => ({ digitised: parse(FILES[0]), calibration: parse(FILES[1]), icarus: parse(FILES[2]),
  muons: parse(FILES[3]), published: parse(FILES[4]) });
const bundle = fresh();
const record = JSON.parse(fs.readFileSync(path.join(PAGE, 'record.json'), 'utf8'));
const html = fs.readFileSync(path.join(PAGE, 'index.html'), 'utf8');
const md = fs.readFileSync(path.join(ROOT, 'src/content/strata', `${SLUG}.md`), 'utf8');
const readme = fs.readFileSync(path.join(RESEARCH, 'README.md'), 'utf8');
const P = bundle.published, IC = bundle.icarus, MU = bundle.muons, CAL = bundle.calibration, DIG = bundle.digitised;

// The spec's binding numbers, typed here once from the spec so the page's own constants can be
// checked against them rather than against themselves.
const SPEC = {
  allowanceCentre: 2.0, allowanceWidth: 1.0, window: 200, multiplier: 3, px: 2,
  // the page's own declared demonstration sizes (section III spread, section IV slip), typed here
  // so a change to either in the engine is caught rather than followed
  spread: 7, fault: 30,
  // an independent NumPy implementation in the spec pass (.wave/spec/opera-ftl/r2/check.py and
  // sensitivity-results.json) produced these from the same digitisation
  numpyDelta: 62.307972, numpyStat: 7.668835,
  numpyRepeat: [62.2942, 62.3082, 7.6673, 7.6688], numpyEndpoints: [62.0812, 62.4722, 7.6157, 7.7199],
  novelty: 'we searched the Artificial Wasteland corpus, arXiv and web-indexed GitHub results on 2026-09-22 and did not find a browser interactive that combines the digitised OPERA likelihood summary, an injection into the seven ICARUS event timestamps and a leave-one-period-out reconstruction of the LVD-OPERA muon timing change.',
};

// ------------------------------------------------------------------ independent recomputation

// A quadratic least-squares fit in the verifier's own frame (centred and scaled on the data, solved
// by Cramer's rule), returned as raw-x coefficients so two panels can be summed.
function indepQuad(points) {
  const n = points.length;
  const xm = points.reduce((s, p) => s + p.x, 0) / n;
  const sd = Math.sqrt(points.reduce((s, p) => s + (p.x - xm) ** 2, 0) / n);
  const ym = Math.max(...points.map((p) => p.y));
  let S0 = 0, S1 = 0, S2 = 0, S3 = 0, S4 = 0, T0 = 0, T1 = 0, T2 = 0;
  for (const p of points) {
    const t = (p.x - xm) / sd, y = p.y - ym;
    S0 += 1; S1 += t; S2 += t * t; S3 += t ** 3; S4 += t ** 4; T0 += y; T1 += t * y; T2 += t * t * y;
  }
  const det3 = (m) => m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1]) - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0]) + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0]);
  const M = [[S0, S1, S2], [S1, S2, S3], [S2, S3, S4]], rhs = [T0, T1, T2];
  const D = det3(M);
  const sol = [0, 1, 2].map((k) => det3(M.map((row, i) => row.map((v, j) => (j === k ? rhs[i] : v)))) / D);
  const [A, B, C] = sol; // y = A + B t + C t^2
  // raw x: t = (x - xm)/sd
  const a = C / sd ** 2, b = B / sd - (2 * C * xm) / sd ** 2;
  return { a, b, mu: -b / (2 * a), stat: Math.sqrt(-1 / (2 * a)) };
}
const panelPoints = (panel) => panel.points.map((p) => ({ x: p.blind_delay_ns, y: p.log_likelihood }));
const indepFirst = indepQuad(panelPoints(DIG.panels[0]));
const indepSecond = indepQuad(panelPoints(DIG.panels[1]));
const indepCal = CAL.terms.reduce((s, t) => s + Math.round(t.ns * 10), 0) / 10; // integer tenths, exact
const indepBlind = -(indepFirst.b + indepSecond.b) / (2 * (indepFirst.a + indepSecond.a));
const indepStat = Math.sqrt(-1 / (2 * (indepFirst.a + indepSecond.a)));
const indepDelta = indepBlind + indepCal;

function indepIcarus(rows, route, tStopShift = 0) {
  const L = IC.reference.light_tof_ns, s = IC.reference.bunch_spacing_ns, f = IC.fixed_delays;
  return rows.map((r) => {
    if (route === 'printed-flight-times') {
      return { bunch: r.printed_bunch, elapsed: r.printed_elapsed_ns, tof: r.printed_TOF_ns - tStopShift, delta: L - (r.printed_TOF_ns - tStopShift) };
    }
    const start = route === 'timestamps' ? r.T_START_ns
      : r.T_CERN_ns + r.d1C_ns + r.d2C_ns + f.D1_ns + f.d3C_ns + f.d4C_ns + f.d5C_ns + r.d6C_ns;
    const stop = (route === 'timestamps' ? r.T_STOP_ns
      : r.T_LNGS_ns + r.d1L_ns + r.d2L_ns - r.d3L_ns + r.d4L_ns - r.d5L_ns - r.d6L_ns - r.d7L_ns + f.dLFIX_ns) - tStopShift;
    const elapsed = stop - start;
    const k = Math.round((elapsed - L) / s) + 1; // a different association method: round, not argmin
    return { bunch: k, elapsed, start, stop, tof: elapsed - (k - 1) * s, delta: L - (elapsed - (k - 1) * s) };
  });
}
const stats = (xs) => { const m = xs.reduce((a, b) => a + b, 0) / xs.length; return { mean: m, rms: Math.sqrt(xs.reduce((a, b) => a + (b - m) ** 2, 0) / xs.length) }; };
const ROWS = IC.rows;
const indTs = indepIcarus(ROWS, 'timestamps'), indTsStats = stats(indTs.map((e) => e.delta));
const indPf = indepIcarus(ROWS, 'printed-flight-times'), indPfStats = stats(indPf.map((e) => e.delta));
const indDc = indepIcarus(ROWS, 'delay-columns'), indDcStats = stats(indDc.map((e) => e.delta));
const CLAIM = P.opera_v1.delta_ns;
const indPlanted = indepIcarus(ROWS, 'timestamps', CLAIM), indPlantedStats = stats(indPlanted.map((e) => e.delta));
const U = Math.hypot(IC.published.stat_ns, IC.published.syst_ns);
// The page's second scale, recomputed here from its printed definition: population RMS / sqrt(7),
// times sqrt(6/4), in quadrature with the published 9.0 ns. The rule needs the mean above 3u on BOTH.
const scatterScale = (st) => (st.rms / Math.sqrt(7)) * Math.sqrt(6 / 4);
const dataU = (st) => Math.hypot(scatterScale(st), IC.published.syst_ns);
const ruleLine = (st) => Math.max(3 * U, 3 * dataU(st));
const ruleFlag = (st) => st.mean > 3 * U && st.mean > 3 * dataU(st);
const ROUTES = ['timestamps', 'printed-flight-times', 'delay-columns'];
const indRoute = Object.fromEntries(ROUTES.map((rt) => {
  const real = indepIcarus(ROWS, rt), planted = indepIcarus(ROWS, rt, CLAIM);
  return [rt, { real, planted, realStats: stats(real.map((e) => e.delta)), plantedStats: stats(planted.map((e) => e.delta)) }];
}));
// the smallest plant the rule flags, by linearity: the line less the real mean (the engine bisects)
const reachInd = ruleLine(indTsStats) - indTsStats.mean;
// the section III spread copy, built here by the verifier's own arithmetic
const spreadInd = ROWS.map((row, i) => ({ ...row, T_STOP_ns: row.T_STOP_ns - (SPEC.spread - 1) * (indTs[i].delta - indTsStats.mean) }));
const spreadReal = indepIcarus(spreadInd, 'timestamps'), spreadPlanted = indepIcarus(spreadInd, 'timestamps', CLAIM);
const spreadRealStats = stats(spreadReal.map((e) => e.delta)), spreadPlantedStats = stats(spreadPlanted.map((e) => e.delta));
// the section IV slip, applied to a copy by the verifier's own arithmetic
const slipped = (k) => ROWS.map((row) => (row.event === k ? { ...row, T_STOP_ns: row.T_STOP_ns + SPEC.fault } : { ...row }));
function indepAudit(rows) {
  const L = IC.reference.light_tof_ns, s = IC.reference.bunch_spacing_ns, f = IC.fixed_delays;
  const ts = indepIcarus(rows, 'timestamps'), dc = indepIcarus(rows, 'delay-columns');
  const events = rows.map((r, i) => {
    const tsElapsed = r.T_STOP_ns - r.T_START_ns;
    const printedElapsedDelta = L - (r.printed_elapsed_ns - (r.printed_bunch - 1) * s);
    const tofChainGap = (r.printed_elapsed_ns - (r.printed_bunch - 1) * s) - r.printed_TOF_ns;
    return { event: r.event, tsElapsed, printedElapsed: r.printed_elapsed_ns, elapsedGap: tsElapsed - r.printed_elapsed_ns,
      startGap: dc[i].start - r.T_START_ns, stopGap: dc[i].stop - r.T_STOP_ns,
      ts: ts[i].delta, pe: printedElapsedDelta, pf: L - r.printed_TOF_ns, dc: dc[i].delta, printed: r.printed_delta_ns,
      inconsistent: tsElapsed !== r.printed_elapsed_ns || tofChainGap !== 0 || ts[i].delta !== r.printed_delta_ns };
  });
  return { events, flagged: events.filter((e) => e.inconsistent).map((e) => e.event), stats: stats(ts.map((e) => e.delta)), bunches: ts.map((e) => e.bunch) };
}

function indepMuons(rows, omitted = 'none') {
  const out = {};
  for (const c of ['A', 'B']) {
    const g = rows.filter((r) => r.class === c && r.period !== omitted);
    const n = g.reduce((s, r) => s + r.events, 0), w = g.reduce((s, r) => s + r.events * r.mean_ns, 0); // integers, exact
    out[c] = { n, mean: w / n };
  }
  out.contrast = out.A.mean - out.B.mean;
  return out;
}
const indMu = indepMuons(MU.rows);
const indDeletions = MU.rows.map((r) => ({ period: r.period, ...indepMuons(MU.rows, r.period) }));
const indMin = Math.min(...indDeletions.map((d) => d.contrast)), indMax = Math.max(...indDeletions.map((d) => d.contrast));
const dayCount = (a, b) => (Date.parse(`${b}T00:00:00Z`) - Date.parse(`${a}T00:00:00Z`)) / 86400000;

// ------------------------------------------------------------------ the engine, as the page runs it

const r = E.analyse(bundle);
const sens = E.digitisationSensitivity(bundle.digitised, bundle.calibration);

// ================================================================== 1. claim_reproduced
{
  const c = 'claim_reproduced';
  check(c, 'the printed claim is read from the frozen quote, not typed: the quote contains the file\'s 60.7, 6.9 and 7.4',
    P.opera_v1.quote.includes(`(${P.opera_v1.delta_ns.toFixed(1)} ± ${P.opera_v1.stat_ns.toFixed(1)} (stat.) ± ${P.opera_v1.sys_ns.toFixed(1)} (sys.))`));
  check(c, 'engine RULES carry the spec\'s approximation allowance of 2.0 and 1.0 ns',
    E.RULES.approximation.centre_ns === SPEC.allowanceCentre && E.RULES.approximation.width_ns === SPEC.allowanceWidth);
  check(c, 'calibration: the six printed terms sum to the printed total', near(r.calibration.total, CAL.printed_total_ns, 1e-9) && near(indepCal, CAL.printed_total_ns, 1e-9) && r.calibration.totalAgrees);
  check(c, 'calibration: every printed correction equals final minus blind', r.calibration.allTermsAgree
    && CAL.terms.every((t) => Math.abs(t.final_ns.reduce((a, b) => a + b, 0) - t.blind_ns.reduce((a, b) => a + b, 0) - t.ns) < 0.05));
  check(c, 'digitisation ROUND TRIP: stored axis values follow from stored pixels through the same tick list (a consistency check; it cannot catch a misread tick)', r.transcription.every((t) => t.maxXError_ns < 1e-6 && t.maxYError < 1e-6));
  check(c, 'engine fit agrees with the verifier\'s independent fit (centre)', near(r.anchor.delta, indepDelta, 1e-6), `${r.anchor.delta} vs ${indepDelta}`);
  check(c, 'engine fit agrees with the verifier\'s independent fit (width)', near(r.anchor.stat, indepStat, 1e-6), `${r.anchor.stat} vs ${indepStat}`);
  check(c, 'engine fit agrees with the spec pass\'s NumPy fit', near(r.anchor.delta, SPEC.numpyDelta, 1e-5) && near(r.anchor.stat, SPEC.numpyStat, 1e-5));
  check(c, 'per-extraction fits agree with the independent fits', near(r.anchor.panels[0].mu, indepFirst.mu, 1e-6) && near(r.anchor.panels[1].mu, indepSecond.mu, 1e-6)
    && near(r.anchor.panels[0].stat, indepFirst.stat, 1e-6) && near(r.anchor.panels[1].stat, indepSecond.stat, 1e-6));
  const agrees = Math.abs(indepDelta - CLAIM) <= SPEC.allowanceCentre && Math.abs(indepStat - P.opera_v1.stat_ns) <= SPEC.allowanceWidth;
  check(c, 'ANCHOR: the rebuilt claim is within the documented allowance of the printed 60.7 and 6.9', agrees && r.anchorCheck.agrees,
    `centre gap ${indepDelta - CLAIM}, width gap ${indepStat - P.opera_v1.stat_ns}`);
  check(c, 'the rebuilt claim is not weaker than printed: it is at least as far from zero as 60.7', indepDelta >= CLAIM);
  // the printed blind value must never be an input
  const noBlind = fresh(); noBlind.published.opera_v1.blind_ns = 0; noBlind.published.opera_v1.calibration_total_ns = 0;
  check(c, 'the printed 1048.5 ns and printed total are not inputs: zeroing them changes nothing', E.analyse(noBlind).anchor.delta === r.anchor.delta);
  const src = fs.readFileSync(path.join(PAGE, 'engine.js'), 'utf8');
  const fitSrc = src.slice(src.indexOf('export function fitClaimantLikelihood'), src.indexOf('export function anchorCheck'));
  check(c, 'fitClaimantLikelihood reads no printed headline value', !/blind_ns|delta_ns|1048|60\.7|6\.9/.test(fitSrc));
  // negatives: the anchor must go red when the claimant record is wrong
  const shifted30 = fresh(); shifted30.digitised.panels.forEach((p) => p.points.forEach((v) => { v.blind_delay_ns += 30; }));
  let red30 = false; try { red30 = !E.anchorCheck(E.fitClaimantLikelihood(shifted30.digitised, shifted30.calibration), P.opera_v1).agrees; } catch { red30 = true; }
  check(c, 'NEGATIVE: every digitised x moved by 30 ns fails the unmodified anchor', red30);
  const shifted3 = fresh(); shifted3.digitised.panels.forEach((p) => p.points.forEach((v) => { v.blind_delay_ns += 3; }));
  const s3 = E.anchorCheck(E.fitClaimantLikelihood(shifted3.digitised, shifted3.calibration), P.opera_v1);
  check(c, 'NEGATIVE: a 3 ns shift, inside the figure domain, fails the anchor by comparison, not by refusal', !s3.agrees && !s3.centreWithin);
  const calFault = fresh(); calFault.calibration.terms[2].ns += 30;
  check(c, 'NEGATIVE: a calibration term moved by 30 ns fails the anchor', !E.anchorCheck(E.fitClaimantLikelihood(calFault.digitised, calFault.calibration), P.opera_v1).agrees);
  const flat = fresh(); flat.digitised.panels.forEach((p) => { const top = Math.max(...p.points.map((v) => v.log_likelihood)); p.points.forEach((v) => { v.log_likelihood = top + 0.8 * (v.log_likelihood - top); }); });
  const fl = E.anchorCheck(E.fitClaimantLikelihood(flat.digitised, flat.calibration), P.opera_v1);
  check(c, 'NEGATIVE: flattening both curves by 20 per cent fails the width half of the anchor', !fl.widthWithin && fl.centreWithin);
  // sensitivity envelopes against the independent NumPy run
  check(c, 'thresholds and trims envelope matches the NumPy run', near(sens.repeat.centre[0], SPEC.numpyRepeat[0], 5e-4) && near(sens.repeat.centre[1], SPEC.numpyRepeat[1], 5e-4)
    && near(sens.repeat.width[0], SPEC.numpyRepeat[2], 5e-4) && near(sens.repeat.width[1], SPEC.numpyRepeat[3], 5e-4));
  check(c, '±2 pixel end-tick envelope matches the NumPy run', near(sens.endpoints.centre[0], SPEC.numpyEndpoints[0], 5e-4) && near(sens.endpoints.centre[1], SPEC.numpyEndpoints[1], 5e-4)
    && near(sens.endpoints.width[0], SPEC.numpyEndpoints[2], 5e-4) && near(sens.endpoints.width[1], SPEC.numpyEndpoints[3], 5e-4));
  check(c, 'the measured pixel sensitivity is smaller than the gap, as the page says', sens.endpoints.centre[0] - CLAIM > 1 && sens.endpoints.width[0] - P.opera_v1.stat_ns > 0.5);
  const vis = visibleText(html);
  check(c, 'the page states the gap is unresolved and not pixel precision', vis.includes('remains unresolved without the collaboration\'s numerical likelihoods or its original inputs') && vis.includes('does not put it down to pixel precision'));
  const count = (hay, needle) => hay.split(needle).length - 1;
  check(c, 'the page prints both numbers with their labels, every time', count(vis, '(stat., digitised likelihood summary)') === 2 && count(vis, '(stat., paper)') === 1);
  check(c, 'record.anchor.agrees matches, and its tolerance carries the allowance and the qualification',
    record.anchor.agrees === agrees && record.anchor.tolerance.includes('2.0 ns in the centre') && record.anchor.tolerance.includes('1.0 ns in the statistical width')
    && /NOT an independently measured digitisation error/.test(record.anchor.tolerance) && /unresolved/.test(record.anchor.tolerance));
  check(c, 'record.anchor.computed prints the recomputed centre and width', record.anchor.computed.includes(indepDelta.toFixed(6)) && record.anchor.computed.includes(indepStat.toFixed(6)));
}

// ================================================================== 2. control_computed
{
  const c = 'control_computed';
  const ts = E.runIcarus(ROWS, { path: 'timestamps', reference: r.reference });
  check(c, 'timestamp residuals are -2, 0, -5, -19, +7, +3, +18', deepEqual(ts.deltas, [-2, 0, -5, -19, 7, 3, 18]) && deepEqual(indTs.map((e) => e.delta), ts.deltas));
  check(c, 'mean and population RMS agree with the independent arithmetic', near(ts.mean, indTsStats.mean, 1e-12) && near(ts.rms, indTsStats.rms, 1e-12));
  check(c, 'mean 2/7 and RMS 10.497813 round to the printed +0.3 and 10.5',
    Number(ts.mean.toFixed(1)) === IC.published.mean_ns && Number(ts.rms.toFixed(1)) === IC.published.rms_ns && near(ts.rms, 10.497813, 1e-6));
  check(c, 'bunch associations match the printed column and the independent rounding method',
    deepEqual(ts.assignments, ROWS.map((row) => row.printed_bunch)) && deepEqual(indTs.map((e) => e.bunch), ts.assignments));
  const pf = E.runIcarus(ROWS, { path: 'printed-flight-times', reference: r.reference });
  check(c, 'printed flight-time route: -0.285714 and 10.713333', near(pf.mean, indPfStats.mean, 1e-12) && near(pf.mean, -2 / 7, 1e-12) && near(pf.rms, 10.713333, 1e-6));
  const dc = E.runIcarus(ROWS, { path: 'delay-columns', reference: r.reference });
  check(c, 'delay-column route agrees with the independent formula arithmetic', deepEqual(dc.deltas, indDc.map((e) => e.delta)) && near(dc.mean, indDcStats.mean, 1e-12));
  const rec = r.reconcile;
  check(c, 'the T_START formula reproduces every printed T_START', rec.startFormulaExact && indDc.every((e, i) => e.start === ROWS[i].T_START_ns));
  check(c, 'the T_STOP formula lands 9, 5, 5, 5, 5, 5, 5 ns after the printed T_STOP', deepEqual(rec.stopGaps, [9, 5, 5, 5, 5, 5, 5]) && rec.commonStopGap === 5
    && deepEqual(indDc.map((e, i) => e.stop - ROWS[i].T_STOP_ns), rec.stopGaps));
  check(c, 'the delay columns reproduce the final row less a common 5 ns, event 1 included', rec.delayMinusFinal.every((d) => d === -5));
  check(c, 'event 1 by every route: -2, -10, -6, -11', deepEqual(rec.events[0].routes, { timestamps: -2, printedElapsed: -10, printedFlightTime: -6, delayColumns: -11 }));
  check(c, 'only event 1 is inconsistent, and its elapsed gap is -8 ns', deepEqual(rec.inconsistentEvents, [1]) && rec.events[0].elapsedGap === -8);
  check(c, 'record.control.computed carries the recomputed mean and RMS', record.control.computed.includes(ts.mean.toFixed(6)) && record.control.computed.includes(ts.rms.toFixed(6)));
  check(c, 'the printed ICARUS summary in record.control.as_printed matches the frozen values', record.control.as_printed.includes(`+${IC.published.mean_ns} +/- ${IC.published.stat_ns}`) && record.control.as_printed.includes(`${IC.published.syst_ns.toFixed(1)} (syst.)`));
  check(c, 'the control record is the 2011 seven-event sample, not the 2012 study', ROWS.length === 7 && ROWS.every((row) => row.date >= '2011-10-31' && row.date <= '2011-11-06'));
}

// ================================================================== 3. control_can_confirm
{
  const c = 'control_can_confirm';
  const quoted = Number((P.opera_v1.quote.match(/\((\d+\.\d) ±/) || [])[1]);
  check(c, 'the planted size is the claim as printed in the claimants\' own words', r.claimed === CLAIM && quoted === CLAIM && r.power.claimed === quoted);
  const injected = E.injectClaim(ROWS, CLAIM, { path: 'timestamps', claimed: CLAIM });
  const onlyStop = injected.every((row, i) => Object.keys(row).every((k) => (k === 'T_STOP_ns' ? near(ROWS[i][k] - row[k], CLAIM, 1e-9) : deepEqual(row[k], ROWS[i][k]))));
  check(c, 'the injection moved every copied T_STOP by exactly the claim and nothing else', onlyStop);
  check(c, 'the frozen table itself is untouched', deepEqual(ROWS, parse(FILES[2]).rows));
  const p = r.power;
  check(c, 'same function: the page\'s power result is runIcarus on the injected copy', deepEqual(p.planted, E.runIcarus(injected, { path: 'timestamps', reference: r.reference }))
    && deepEqual(p.real, E.runIcarus(ROWS, { path: 'timestamps', reference: r.reference })));
  const tcSrc = fs.readFileSync(path.join(PAGE, 'engine.js'), 'utf8');
  const tcBody = tcSrc.slice(tcSrc.indexOf('export function testControl'), tcSrc.indexOf('export function reconcileIcarus'));
  check(c, 'testControl plants with injectClaim and measures with runIcarus, nothing else', /injectClaim\(rows, claimed/.test(tcBody) && (tcBody.match(/runIcarus\(/g) || []).length === 2 && !/\.push\(/.test(tcBody));
  check(c, 'planted residuals equal the independent arithmetic', p.planted.deltas.every((d, i) => near(d, indPlanted[i].delta, 1e-6)));
  check(c, 'planted residuals are 58.7, 60.7, 55.7, 41.7, 67.7, 63.7, 78.7', p.planted.deltas.every((d, i) => near(d, [58.7, 60.7, 55.7, 41.7, 67.7, 63.7, 78.7][i], 1e-6)));
  check(c, 'planted mean 60.985714, RMS unchanged', near(p.planted.mean, indPlantedStats.mean, 1e-9) && near(p.planted.mean, 60.985714, 1e-6) && near(p.planted.rms, p.real.rms, 1e-9));
  check(c, 'LINEARITY, not evidence: the recovered displacement equals the plant, as a mean of subtractions must once every bunch holds', near(p.recovered, CLAIM, 1e-6));
  check(c, 'bunch assignments unchanged by the injection', p.sameBunches && deepEqual(p.planted.assignments, [2, 2, 3, 1, 3, 4, 2]) && deepEqual(indPlanted.map((e) => e.bunch), [2, 2, 3, 1, 3, 4, 2]));
  check(c, 'u is built from the published 4.9 and 9.0 ns, the 9.0 not divided by sqrt(7)', near(p.real.u, U, 1e-12) && near(U, 10.247439, 1e-6));
  check(c, 'the page\'s three-error rule sits at 3u', E.RULES.sensitivityMultiplier === SPEC.multiplier && near(p.real.threshold, 3 * U, 1e-12));
  check(c, 'opposite outcomes: the real record stays under, the planted one crosses', !p.real.flag && p.planted.flag && p.opposite
    && !ruleFlag(indTsStats) && ruleFlag(indPlantedStats));
  check(c, 'ratios 0.027882 real and 5.951313 planted', near(p.real.ratio, 0.027882, 1e-6) && near(p.planted.ratio, 5.951313, 1e-6));
  const small = ROWS.map((row) => ({ ...row, T_STOP_ns: row.T_STOP_ns - 10 }));
  check(c, 'NEGATIVE: the same rule says no to a 10 ns early arrival planted by hand', !E.runIcarus(small, { path: 'timestamps', reference: r.reference }).flag);
  check(c, 'the second scale is the record\'s own scatter: RMS/sqrt 7 x sqrt(6/4) = 4.859543 ns, line 30.684466 ns, and the stricter published line 30.742316 ns is the one in force',
    near(p.real.statData, scatterScale(indTsStats), 1e-9) && near(p.real.statData, 4.859543, 1e-6) && near(p.real.thresholdData, 3 * dataU(indTsStats), 1e-9)
    && near(p.real.line, ruleLine(indTsStats), 1e-9) && near(p.real.line, 3 * U, 1e-12) && near(p.planted.line, p.real.line, 1e-9));
  check(c, 'the rule flags only above BOTH lines, on the real and the planted record', p.real.flag === ruleFlag(indTsStats) && p.planted.flag === ruleFlag(indPlantedStats));
  const t10 = E.testControl(ROWS, r.reference, 10, 'timestamps');
  check(c, 'NEGATIVE THROUGH testControl: a planted 10 ns returns INCONCLUSIVE', !t10.canConfirm && t10.conclusion === 'INCONCLUSIVE' && /could NOT/.test(t10.verdict));
  check(c, 'the spread copy the page hands the control is the verifier\'s own copy', (() => { const e = E.spreadRecord(ROWS, r.reference); return e.every((row, i) => near(row.T_STOP_ns, spreadInd[i].T_STOP_ns, 1e-9) && Object.keys(row).every((k) => k === 'T_STOP_ns' || deepEqual(row[k], ROWS[i][k]))); })());
  const tSpread = E.testControl(spreadInd, r.reference, CLAIM, 'timestamps');
  check(c, 'the spread copy keeps the mean, multiplies the scatter by 7, keeps every bunch and stays inside the window', near(spreadRealStats.mean, indTsStats.mean, 1e-9)
    && near(spreadRealStats.rms, SPEC.spread * indTsStats.rms, 1e-9) && tSpread.sameBunches && deepEqual(spreadPlanted.map((e) => e.bunch), [2, 2, 3, 1, 3, 4, 2])
    && spreadPlanted.every((e) => Math.abs(e.delta) <= SPEC.window));
  check(c, 'NEGATIVE THROUGH testControl: the claim planted in a record 7 times as scattered returns INCONCLUSIVE (planted mean under that record\'s own line)',
    !tSpread.canConfirm && tSpread.conclusion === 'INCONCLUSIVE' && near(tSpread.planted.mean, spreadPlantedStats.mean, 1e-9)
    && spreadPlantedStats.mean > 3 * U && !ruleFlag(spreadPlantedStats) && near(tSpread.planted.line, ruleLine(spreadPlantedStats), 1e-9));
  const reach = r.reach;
  check(c, 'the reach, bisected on testControl, is the line less the real mean, 30.456602 ns', near(reach.reach, reachInd, 1e-6) && near(reachInd, 30.456602, 1e-6));
  check(c, 'the reach is where the unmodified test changes its answer', E.testControl(ROWS, r.reference, reach.reach + 0.01).canConfirm && !E.testControl(ROWS, r.reference, reach.reach - 0.01).canConfirm);
  check(c, 'the spread copy has no reach inside the window', E.ruleReach(spreadInd, r.reference).reach === null);
  check(c, 'on the printed flight-time route the bunches are read, not reassigned, and the engine says so', r.powerAllPaths[1].real.bunchesReassigned === false
    && r.powerAllPaths[0].real.bunchesReassigned === true && r.powerAllPaths[2].real.bunchesReassigned === true);
  check(c, 'record.power.recovered states the scatter scale, the reach and both negatives', record.power.recovered.includes(p.real.statData.toFixed(6))
    && record.power.recovered.includes(p.real.thresholdData.toFixed(6)) && record.power.recovered.includes(reach.reach.toFixed(6))
    && record.power.recovered.includes(spreadRealStats.rms.toFixed(6)) && /returns INCONCLUSIVE, and so does a planted 10 ns/.test(record.power.recovered));
  check(c, 'every route recovers the claim and crosses the rule', r.powerAllPaths.every((t) => near(t.recovered, CLAIM, 1e-6) && t.sameBunches && t.canConfirm && !t.realFlag));
  check(c, 'the verdict is COULD have confirmed, and the record says grade A', p.canConfirm && record.power.grade === 'A-injection' && /COULD have confirmed/.test(record.power.verdict));
  check(c, 'record.power.recovered prints the recomputed planted mean and recovery', record.power.recovered.includes(p.planted.mean.toFixed(6)) && record.power.recovered.includes(p.recovered.toFixed(6)));
  const vis = visibleText(html);
  check(c, 'the page names the grade and what was not rerun', vis.includes('Grade A here means injection and recovery in published event times') && vis.includes('were not rerun'));
}

// ================================================================== expected static figures
const fx = (x, d) => { const v = Number(x.toFixed(d)); const s = Math.abs(v).toFixed(d); return v < 0 ? `−${s}` : s; };
const sg = (x, d) => { const v = Number(x.toFixed(d)); const s = Math.abs(v).toFixed(d); return v > 0 ? `+${s}` : v < 0 ? `−${s}` : s; };
const firstDelta = indepFirst.mu + indepCal, secondDelta = indepSecond.mu + indepCal;
const ev1 = indTs[0], ev1Printed = ROWS[0];
const V4 = P.opera_v4, MP = MU.published, V2 = P.opera_v2, O12 = P.opera_2012;
const classMeans = (cls) => MU.rows.filter((row) => row.class === cls).map((row) => row.mean_ns);
const EXPECTED = {
  'v1.delta': fx(P.opera_v1.delta_ns, 1), 'v1.stat': fx(P.opera_v1.stat_ns, 1), 'v1.sys': fx(P.opera_v1.sys_ns, 1),
  'v1.sigma': fx(P.opera_v1.significance_sigma, 1), 'v1.blind': fx(P.opera_v1.blind_ns, 1), 'v1.caltotal': fx(CAL.printed_total_ns, 1),
  'v1.events': String(P.opera_v1.events), 'v1.extraction': fx(P.opera_v1.extraction_length_us, 1), 'v1.baseline': String(P.opera_v1.baseline_km_about),
  'v1.gev': String(P.opera_v1.proton_momentum_GeV), 'v1.mc': String(P.opera_v1.simulation_datasets),
  'quote.v1': P.opera_v1.quote, 'quote.method': P.opera_v1.quote_method, 'quote.simulation': P.opera_v1.quote_simulation,
  'quote.v1conclusion': P.opera_v1.quote_conclusion, 'quote.icarus': P.icarus.quote_conclusion, 'quote.cable': V4.quote_cable,
  'quote.february': P.cern_2012.quote_february, 'quote.conclusion': V4.quote_conclusion, 'quote.four': P.cern_2012.quote_four,
  'quote.cause': P.cern_2012.quote_cause, 'quote.km3net': P.km3net_2025.quote, 'quote.muon': V4.muon_quote, 'quote.assumption': MU.drift.assumption,
  'dig.n1': String(DIG.panels[0].points.length), 'dig.n2': String(DIG.panels[1].points.length),
  'first.delta': fx(firstDelta, 1), 'first.stat': fx(indepFirst.stat, 1), 'second.delta': fx(secondDelta, 1), 'second.stat': fx(indepSecond.stat, 1),
  'fit.delta1': fx(indepDelta, 1), 'fit.stat1': fx(indepStat, 1), 'fit.delta2': fx(indepDelta, 2), 'fit.stat2': fx(indepStat, 2),
  'cal.sum': fx(indepCal, 1), 'gap.centre': sg(indepDelta - CLAIM, 2), 'gap.width': sg(indepStat - P.opera_v1.stat_ns, 2),
  'ratio': fx(indepDelta / Math.hypot(indepStat, P.opera_v1.sys_ns), 2),
  'allow.centre': fx(SPEC.allowanceCentre, 1), 'allow.width': fx(SPEC.allowanceWidth, 1),
  'sens.repeat': `${fx(SPEC.numpyRepeat[0], 2)} to ${fx(SPEC.numpyRepeat[1], 2)}`, 'sens.repeatw': `${fx(SPEC.numpyRepeat[2], 3)} to ${fx(SPEC.numpyRepeat[3], 3)}`,
  'sens.end': `${fx(SPEC.numpyEndpoints[0], 2)} to ${fx(SPEC.numpyEndpoints[1], 2)}`, 'sens.endw': `${fx(SPEC.numpyEndpoints[2], 2)} to ${fx(SPEC.numpyEndpoints[3], 2)}`,
  'px': String(SPEC.px), 'rule.z': '1050', 'rule.window': String(SPEC.window),
  'ic.width': String(IC.reference.bunch_width_ns_about), 'ic.spacing': String(IC.reference.bunch_spacing_ns), 'ic.light': String(IC.reference.light_tof_ns),
  'ic.lightunc': fx(IC.reference.light_tof_uncertainty_ns, 1), 'ic.resid': indTs.map((e) => sg(e.delta, 0)).join(', '),
  'ic.mean': sg(indTsStats.mean, 2), 'ic.rms': fx(indTsStats.rms, 2), 'ic.pub.mean': sg(IC.published.mean_ns, 1), 'ic.pub.rms': fx(IC.published.rms_ns, 1),
  'ic.pub.stat': fx(IC.published.stat_ns, 1), 'ic.pub.syst': fx(IC.published.syst_ns, 1), 'ic.bunches': indTs.map((e) => e.bunch).join(', '),
  'ic.lfix': String(IC.fixed_delays.dLFIX_ns), 'ic.lfix4': fx(IC.fixed_delays.dLFIX_page4_ns, 1),
  'pw.resid': indPlanted.map((e) => sg(e.delta, 1)).join(', '), 'pw.mean': sg(indPlantedStats.mean, 2), 'pw.recovered': fx(indPlantedStats.mean - indTsStats.mean, 3),
  'pw.u': fx(U, 2), 'pw.threshold': fx(3 * U, 2), 'pw.realratio': fx(indTsStats.mean / U, 3), 'pw.plantedratio': fx(indPlantedStats.mean / U, 2),
  'pw.verdict': ruleFlag(indPlantedStats) && !ruleFlag(indTsStats) ? 'The control could have confirmed the claim. It did not find it.' : 'INCONCLUSIVE',
  'e1.stop': String(ev1Printed.T_STOP_ns), 'e1.start': String(ev1Printed.T_START_ns), 'e1.tsElapsed': String(ev1.elapsed), 'e1.pElapsed': String(ev1Printed.printed_elapsed_ns),
  'e1.tsTof': String(ev1.elapsed - (ev1.bunch - 1) * IC.reference.bunch_spacing_ns), 'e1.pTof': String(ev1Printed.printed_TOF_ns),
  'e1.tsDelta': sg(ev1.delta, 0), 'e1.pDelta': sg(ev1Printed.printed_delta_ns, 0),
  'rec.common': String(indDc[1].stop - ROWS[1].T_STOP_ns), 'rec.e1': String(indDc[0].stop - ROWS[0].T_STOP_ns),
  'rec.diff': String(Math.abs(ev1.delta - ev1Printed.printed_delta_ns)),
  'rec.e1.pElapsedDelta': sg(IC.reference.light_tof_ns - (ev1Printed.printed_elapsed_ns - (ev1Printed.printed_bunch - 1) * IC.reference.bunch_spacing_ns), 0),
  'pf.mean': sg(indPfStats.mean, 2), 'pf.rms': fx(indPfStats.rms, 2), 'dc.mean': sg(indDcStats.mean, 2),
  'verdict.category': record.verdict.category, 'verdict.asof': record.verdict.as_of, 'verdict.would_change': record.verdict.would_change,
  'days.cern': String(dayCount(P.opera_v1.submitted, P.cern_2012.update)), 'days.v4': String(dayCount(P.opera_v1.submitted, V4.submitted)),
  'days.jhep': String(dayCount(P.opera_v1.submitted, V4.published)),
  'v4.fibre.km': fx(V4.fibre_length_km, 1), 'v4.fibre': fx(V4.fibre_delay_increase_ns, 1), 'v4.osc': fx(V4.oscillator_offset_ppm, 3), 'v4.daq': fx(V4.daq_cycle_s, 1),
  'v4.oscmax': String(V4.oscillator_max_ns), 'v4.corr': fx(V4.corrected_ns, 1), 'v4.stat': fx(V4.stat_ns, 1), 'v4.sysp': fx(V4.sys_plus_ns, 1), 'v4.sysm': fx(V4.sys_minus_ns, 1),
  'v4.events': String(V4.events), 'v4.tt': fx(V4.tt_delta_ns, 1), 'v4.tterr': fx(V4.tt_error_ns, 1), 'v4.ttn': String(V4.tt_events),
  'v4.rpc': fx(V4.rpc_delta_ns, 1), 'v4.rpcerr': fx(V4.rpc_error_ns, 1), 'v4.rpcn': String(V4.rpc_events),
  'mu.total': String(indMu.A.n + indMu.B.n), 'mu.A.n': String(indMu.A.n), 'mu.B.n': String(indMu.B.n), 'mu.A.mean': fx(indMu.A.mean, 2), 'mu.B.mean': fx(indMu.B.mean, 2),
  'mu.contrast': fx(indMu.contrast, 2), 'mu.pub.A': String(MP.class_A_mean_ns), 'mu.pub.Aerr': String(MP.class_A_error_ns), 'mu.pub.B': String(MP.class_B_mean_ns),
  'mu.pub.Berr': String(MP.class_B_error_ns), 'mu.pub.c': fx(MP.contrast_ns, 0), 'mu.pub.cerr': String(MP.contrast_error_ns),
  'mu.round': String(MU.mean_precision_ns), 'mu.classround': fx(MU.mean_precision_ns / 2, 1), 'mu.precision': String(MU.mean_precision_ns),
  'mu.min': fx(indMin, 2), 'mu.max': fx(indMax, 2), 'mu.minP': indDeletions.find((d) => d.contrast === indMin).period, 'mu.maxP': indDeletions.find((d) => d.contrast === indMax).period,
  'mu.omit2012': fx(indDeletions.find((d) => d.period === '2012').contrast, 2),
  'mu.floor': fx(Math.min(...indDeletions.map((d) => Math.abs(d.contrast))) - MU.mean_precision_ns, 2),
  'mu.drift.fit': String(MU.drift.fitted_ns_per_s), 'mu.drift.fiterr': String(MU.drift.fitted_error_ns_per_s), 'mu.drift.direct': fx(MU.drift.direct_ns_per_s, 2), 'mu.drift.directerr': fx(MU.drift.direct_error_ns_per_s, 2),
  'citable': `Recombining the eight published period means gives a local timing change of ${sg(indMu.contrast, 1)} ns. Removing any one period leaves a change between ${sg(indMin, 1)} and ${sg(indMax, 1)} ns.`,
  'novelty': SPEC.novelty,
  'gap.c1': fx(indepDelta - CLAIM, 1),
  'v2.delta': fx(V2.delta_ns, 1), 'v2.stat': fx(V2.stat_ns, 1), 'v2.sysp': fx(V2.sys_plus_ns, 1), 'v2.sysm': fx(V2.sys_minus_ns, 1),
  'v2.n': String(V2.bunched_events), 'v2.int': String(V2.bunched_internal), 'v2.ext': String(V2.bunched_external),
  'v2.bunched': fx(V2.bunched_delta_ns, 1), 'v2.err': fx(V2.bunched_error_ns, 1), 'v2.rms': fx(V2.bunched_rms_ns, 1),
  'quote.v2': V2.quote_confirmed, 'quote.november': P.cern_2012.quote_november, 'quote.march': P.cern_2012.quote_march, 'quote.v4icarus': V4.quote_icarus,
  'o12.delta': fx(O12.delta_ns, 1), 'o12.stat': fx(O12.stat_ns, 1), 'o12.syst': fx(O12.syst_ns, 1), 'quote.o12': O12.quote_confirms,
  'pw.statData': fx(scatterScale(indTsStats), 2), 'pw.uData': fx(dataU(indTsStats), 2), 'pw.thresholdData': fx(3 * dataU(indTsStats), 2),
  'rule.spread': String(SPEC.spread), 'pw.reach': fx(reachInd, 2), 'pw.reachRatio': fx(CLAIM / reachInd, 2),
  'rule.fault': String(SPEC.fault), 'fault.shift': sg(-SPEC.fault / 7, 2),
  'e1.gap': sg(ev1.elapsed - ev1Printed.printed_elapsed_ns, 0), 'e1.gapFault': sg(ev1.elapsed + SPEC.fault - ev1Printed.printed_elapsed_ns, 0),
  'mu.Amax': String(Math.max(...classMeans('A'))), 'mu.Bmin': String(Math.min(...classMeans('B'))),
  'headline': `ICARUS's seven published event times give a mean early arrival of ${fx(indTsStats.mean, 1)} ns; plant OPERA's ${fx(CLAIM, 1)} ns into those same times and the unmodified control returns ${fx(indPlantedStats.mean, 1)} ns, so the control could have seen the claim and did not.`,
};
const EXPECTED_DEK = `In September ${P.opera_v1.submitted.slice(0, 4)} the OPERA experiment reported neutrinos from CERN reaching Gran Sasso ${fx(CLAIM, 1)} nanoseconds sooner than light would have, at ${fx(P.opera_v1.significance_sigma, 1)} standard deviations. Rebuild that number, to within ${fx(indepDelta - CLAIM, 1)} ns, from the collaboration's own likelihood curves, plant an early arrival of the printed size in the seven event times ICARUS published and watch its unmodified control find it, then follow cosmic-ray muons through two detectors to the timing fault that decided the question.`;
const EXPECTED_PLAIN = `In ${P.opera_v1.submitted.slice(0, 4)} an experiment reported neutrinos from near Geneva reaching central Italy slightly faster than light; the cause was later traced to its own timing equipment. This page rebuilds that result ${indepDelta !== CLAIM ? 'approximately ' : ''}from the team's graphs, then hides an early arrival of the printed size in another experiment's ${ROWS.length === 7 ? 'seven' : String(ROWS.length)} neutrinos to show that check could have caught it. It cannot rerun either detector or the original analysis.`;
const TITLE = 'The Clock That Moved the Particle';
const SEO = 'OPERA\'s Faster-Than-Light Neutrino Claim, Rebuilt and Put to the Test';
// Every other number a reader sees: dates, page numbers, identifiers and citations. Each was read
// against its source when the page was written; this list exists so that corrupting any of them
// turns this verifier red.
const INVENTORY = ['2011','256','1109.4897','1','22','2011','8','2011','1109.4897','1','7','1','8','8','1109.4897','1','16','1','1','1109.4897','1','15','2011','21','4','2011','2','22','6','17','2011','1109.4897','2','17','2011','3','24','26','27','2011','31','4','2011','1','1203.3433','3','29','2012','7','713','17','22','2012','2','2','1','1','4','1','1','2','3','4','5','6','7','6','3','7','7','6','4','8','4','2011','25','2012','8','1','1','4','1','1','1','1','1','4','1','2','3','4','5','6','7','7','1','1','1','2011','2012','8','2012','2011','2006','2007','2012','23','2012','23','2012','16','2012','2','47','9.1','29','10','2012','093','10.1007','10','2012','093','1109.4897','4','12','2012','33','8','2012','8','2012','23','2011','2012','2012','1212.1276','6','2012','01','2013','153','10.1007','01','2013','153','1109.4897','1','22','1','3','2025','3','3','8','457','11','2025','10.1038','42005','025','02347','16','2012','2011','2007','2012','2','2007','2008','1','2008','2','2008','3','2009','2010','2011','2012','2','1206.2488','1','18','2007','2008','2012','2008','2008','2012','18','1109.4897','4','20','43','2','1','1','1','1','256','1109.4897','1','22','2011','1','15','8','16','1109.4897','2','17','2011','20','24','27','10','2012','093','12','2012','10.1007','10','2012','093','1109.4897','4','12','2012','6.1','9.1','2.0','1','713','17','22','2012','10.1016','2012.05.033','1203.3433','3','29','2012','1','9','4','6','1206.2488','1','12','2012','2','18','16','18','19','23','2011','18','2011','23','2012','16','2012','8','2012','2012','01','2013','153','10.1007','01','2013','153','1212.1276','6','2012','3','3','8','457','11','2025','10.1038','42005','025','02347','4.0','2026','09','22','2','2012','18','2011','16','2012','2026','09','23','256','2026','09','22','3','6','7','5'];

// ================================================================== what report.js must print, built without report.js
// Every string below is assembled from the verifier's OWN numbers (indepQuad fits, indepIcarus
// routes, integer muon sums, its own audit arithmetic). report.js is never consulted, so a readout,
// a table cell or an arithmetic line that report.js gets wrong cannot agree with these.
const PATH_LABEL = { timestamps: 'the printed timestamps', 'printed-flight-times': 'the printed flight-time row', 'delay-columns': 'the delay columns, through the Section 4 formulas' };
const SHORT = { timestamps: 'timestamps', 'printed-flight-times': 'flight-time row', 'delay-columns': 'delay columns' };
const EXTRACT_LABEL = { both: 'both extractions', first: 'the first extraction only (a subset)', second: 'the second extraction only (a subset)' };
const lst = (xs, d) => xs.map((x) => sg(x, d)).join(', ');
const indFit = (ex) => (ex === 'both' ? { delta: indepDelta, stat: indepStat, blind: indepBlind }
  : ex === 'first' ? { delta: indepFirst.mu + indepCal, stat: indepFirst.stat, blind: indepFirst.mu }
  : { delta: indepSecond.mu + indepCal, stat: indepSecond.stat, blind: indepSecond.mu });
const calTenths = CAL.terms.map((t) => { const b = t.blind_ns.reduce((a, v) => a + Math.round(v * 10), 0) / 10, f = t.final_ns.reduce((a, v) => a + Math.round(v * 10), 0) / 10; return { name: t.name, b, f, d: Math.round((f - b) * 10) / 10, printed: t.ns }; });
const indSens = { repeat: `${fx(SPEC.numpyRepeat[0], 2)} to ${fx(SPEC.numpyRepeat[1], 2)} ns`, repeatW: `${fx(SPEC.numpyRepeat[2], 3)} to ${fx(SPEC.numpyRepeat[3], 3)} ns`,
  end: `${fx(SPEC.numpyEndpoints[0], 2)} to ${fx(SPEC.numpyEndpoints[1], 2)} ns`, endW: `${fx(SPEC.numpyEndpoints[2], 2)} to ${fx(SPEC.numpyEndpoints[3], 2)} ns` };
function expectReadouts(choices = {}) {
  const ch = { extraction: 'both', path: 'timestamps', amplitude: 0, omitted: 'none', fault: 'none', ...choices };
  const fit = indFit(ch.extraction), R = indRoute[ch.path], TS = indRoute.timestamps;
  const act = ch.amplitude === 0 ? R.realStats : R.plantedStats;
  const mu = ch.omitted === 'none' ? indMu : indDeletions.find((d) => d.period === ch.omitted);
  const k = ch.fault === 'none' ? null : Number(ch.fault), audit = indepAudit(k === null ? ROWS : slipped(k));
  const reassigned = ch.path !== 'printed-flight-times';
  return {
    heroFit: `${fx(indepDelta, 1)} ± ${fx(indepStat, 1)} ns`,
    heroGap: `centre ${sg(indepDelta - CLAIM, 2)} ns and width ${sg(indepStat - P.opera_v1.stat_ns, 2)} ns away from the printed values`,
    fitChoice: EXTRACT_LABEL[ch.extraction], fitDelta: fx(fit.delta, 2), fitStat: fx(fit.stat, 2), fitBlind: fx(fit.blind, 2),
    fitLine: `${fx(fit.delta, 2)} ± ${fx(fit.stat, 2)} ns (stat.)${ch.extraction === 'both' ? '' : ', a subset'}`,
    fitSubset: ch.extraction === 'both' ? 'Both extractions, as the claim used them.' : 'This view uses one extraction only. It is a subset of the claim, not the claim.',
    calSum: fx(indepCal, 1),
    calDerived: calTenths.every((t) => t.d === t.printed) ? 'every printed correction equals its final value minus its blind value' : 'a printed correction differs from final minus blind',
    anchorCentre: `${fx(indepDelta, 2)} ns`, anchorWidth: `${fx(indepStat, 2)} ns`,
    gapCentre: `${sg(indepDelta - CLAIM, 2)} ns`, gapWidth: `${sg(indepStat - P.opera_v1.stat_ns, 2)} ns`,
    anchorVerdict: Math.abs(indepDelta - CLAIM) <= SPEC.allowanceCentre && Math.abs(indepStat - P.opera_v1.stat_ns) <= SPEC.allowanceWidth ? 'within the documented approximation allowance' : 'OUTSIDE the documented approximation allowance',
    ratio: fx(indepDelta / Math.hypot(indepStat, P.opera_v1.sys_ns), 2),
    pathLabel: PATH_LABEL[ch.path],
    ctlMean: `${sg(R.realStats.mean, 2)} ns`, ctlRms: `${fx(R.realStats.rms, 2)} ns`, ctlEvent1: `${sg(R.real[0].delta, 0)} ns`,
    ctlResiduals: lst(R.real.map((e) => e.delta), 0), ctlBunches: R.real.map((e) => e.bunch).join(', '),
    ctlBunchMatch: !reassigned ? 'taken from the printed column, not reassigned on this route'
      : R.real.every((e, i) => e.bunch === ROWS[i].printed_bunch) ? 'all seven match the printed bunch column' : 'an assignment differs from the printed column',
    ctlRule: ruleFlag(R.realStats) ? 'crosses the three-error rule' : 'does not cross the three-error rule',
    plantState: ch.amplitude === 0 ? 'the record as published' : `the record with ${fx(CLAIM, 1)} ns planted in every arrival`,
    stripReal: `${sg(R.realStats.mean, 2)} ns`, stripPlanted: `${sg(R.plantedStats.mean, 2)} ns`, stripActive: `${sg(act.mean, 2)} ns`,
    stripScale: `${fx(U, 2)} ns`, stripThreshold: `${fx(ruleLine(act), 2)} ns`, stripRule: ruleFlag(act) ? 'crosses the rule' : 'stays under the rule',
    pwRealResiduals: lst(TS.real.map((e) => e.delta), 1), pwPlantedResiduals: lst(TS.planted.map((e) => e.delta), 1),
    pwRealMean: `${sg(TS.realStats.mean, 3)} ns`, pwPlantedMean: `${sg(TS.plantedStats.mean, 3)} ns`,
    pwRealRms: `${fx(TS.realStats.rms, 3)} ns`, pwPlantedRms: `${fx(TS.plantedStats.rms, 3)} ns`,
    pwRealBunches: TS.real.map((e) => e.bunch).join(', '), pwPlantedBunches: TS.planted.map((e) => e.bunch).join(', '),
    pwRealRatio: fx(TS.realStats.mean / U, 3), pwPlantedRatio: fx(TS.plantedStats.mean / U, 3),
    pwRealScatter: `${fx(scatterScale(TS.realStats), 2)} ns`, pwPlantedScatter: `${fx(scatterScale(TS.plantedStats), 2)} ns`,
    pwRealLine: `${fx(ruleLine(TS.realStats), 2)} ns`, pwPlantedLine: `${fx(ruleLine(TS.plantedStats), 2)} ns`,
    pwRealRule: ruleFlag(TS.realStats) ? 'crosses' : 'does not cross', pwPlantedRule: ruleFlag(TS.plantedStats) ? 'crosses' : 'does not cross',
    pwRecovered: `${fx(TS.plantedStats.mean - TS.realStats.mean, 3)} ns`,
    pwSame: TS.real.every((e, i) => e.bunch === TS.planted[i].bunch) ? 'unchanged' : 'CHANGED',
    pwVerdict: ruleFlag(TS.plantedStats) ? 'The control COULD have confirmed the claim.' : 'The control could NOT have confirmed the claim.',
    pwConclusion: !ruleFlag(TS.plantedStats) ? 'INCONCLUSIVE' : ruleFlag(TS.realStats) ? 'THE CONTROL FLAGS THE REAL RECORD TOO' : 'SENSITIVE TO THE CLAIM, AND DID NOT FIND IT',
    pwReach: `${fx(reachInd, 2)} ns`,
    auditState: k === null ? 'the table as printed' : `a copy with event ${k}'s T_STOP moved ${SPEC.fault} ns later`,
    auditMean: `${sg(audit.stats.mean, 2)} ns`, auditShift: `${sg(audit.stats.mean - indTsStats.mean, 2)} ns`, auditBunches: audit.bunches.join(', '),
    auditFlags: audit.flagged.length === 1 ? `event ${audit.flagged[0]}` : `events ${audit.flagged.join(' and ')}`,
    muOmitted: ch.omitted === 'none' ? 'no period left out' : `period ${ch.omitted} left out`,
    muA: `${mu.A.n} events, ${fx(mu.A.mean, 2)} ns`, muB: `${mu.B.n} events, ${fx(mu.B.mean, 2)} ns`, muContrast: `${sg(mu.contrast, 2)} ns`,
    muBound: `±${fx(MU.mean_precision_ns, 1)} ns`,
    daysCern: EXPECTED['days.cern'], daysV4: EXPECTED['days.v4'], daysJhep: EXPECTED['days.jhep'],
    sensRepeat: indSens.repeat, sensRepeatW: indSens.repeatW, sensEnd: indSens.end, sensEndW: indSens.endW,
  };
}
function expectTables(choices = {}) {
  const ch = { path: 'timestamps', fault: 'none', ...choices };
  const R = indRoute[ch.path];
  const k = ch.fault === 'none' ? null : Number(ch.fault), audit = indepAudit(k === null ? ROWS : slipped(k));
  return {
    calibration: calTenths.map((t) => [t.name, fx(t.b, 1), fx(t.f, 1), sg(t.d, 1), sg(t.printed, 1)]),
    events: R.real.map((e, i) => [String(ROWS[i].event), ROWS[i].date, ROWS[i].type, fx(e.elapsed, 0),
      `${e.bunch}${e.bunch === ROWS[i].printed_bunch ? '' : ' (printed ' + ROWS[i].printed_bunch + ')'}`, fx(e.tof, 0), sg(e.delta, 0)]),
    powerPaths: ROUTES.map((rt) => { const x = indRoute[rt]; return [SHORT[rt], sg(x.realStats.mean, 3), fx(x.realStats.rms, 3), sg(x.plantedStats.mean, 3),
      fx(x.plantedStats.mean - x.realStats.mean, 3), fx(ruleLine(x.realStats), 2), ruleFlag(x.realStats) ? 'crosses' : 'no', ruleFlag(x.plantedStats) ? 'crosses' : 'no',
      rt === 'printed-flight-times' ? 'as printed' : x.real.every((e, i) => e.bunch === x.planted[i].bunch) ? 'unchanged' : 'CHANGED']; }),
    reconcile: audit.events.map((e) => [String(e.event), fx(e.tsElapsed, 0), fx(e.printedElapsed, 0), sg(e.elapsedGap, 0), sg(e.startGap, 0), sg(e.stopGap, 0),
      sg(e.ts, 0), sg(e.pe, 0), sg(e.pf, 0), sg(e.dc, 0), sg(e.printed, 0)]),
    deletions: indDeletions.map((d) => { const row = MU.rows.find((x) => x.period === d.period); return [d.period, row.class, String(row.events), String(d.A.n), fx(d.A.mean, 2), String(d.B.n), fx(d.B.mean, 2), sg(d.contrast, 2)]; }),
  };
}
function expectArithmetic(path, i) {
  const e = indRoute[path].real[i], L = IC.reference.light_tof_ns;
  if (path === 'printed-flight-times') return [`printed flight time for event ${ROWS[i].event}: ${fx(e.tof, 0)} ns (bunch ${e.bunch}, as printed)`, `δt = ${L} − ${fx(e.tof, 0)} = ${sg(e.delta, 0)} ns`];
  const src = path === 'timestamps' ? 'T_STOP − T_START' : 'T_STOP − T_START, each rebuilt from its delays';
  const bd = (e.bunch - 1) * IC.reference.bunch_spacing_ns;
  return [`${src}: ${fx(e.stop, 0)} − ${fx(e.start, 0)} = ${fx(e.elapsed, 0)} ns`, `nearest bunch: ${e.bunch}, so subtract ${bd} ns: ${fx(e.elapsed, 0)} − ${bd} = ${fx(e.tof, 0)} ns`, `δt = ${L} − ${fx(e.tof, 0)} = ${sg(e.delta, 0)} ns`];
}
const EXPECTED_SPREAD = `A copy with every residual ${SPEC.spread} times as far from the mean: RMS ${fx(spreadRealStats.rms, 2)} ns, real mean ${sg(spreadRealStats.mean, 2)} ns, `
  + `planted mean ${sg(spreadPlantedStats.mean, 2)} ns against a line at ${fx(ruleLine(spreadPlantedStats), 2)} ns (its scatter scale is ${fx(scatterScale(spreadPlantedStats), 2)} ns). `
  + `Bunches unchanged. The control ${ruleFlag(spreadPlantedStats) ? 'COULD have confirmed the claim' : 'could NOT have confirmed the claim'}: ${ruleFlag(spreadPlantedStats) ? 'SENSITIVE TO THE CLAIM, AND DID NOT FIND IT' : 'INCONCLUSIVE'}.`;
// Choice states checked statically: every option of every choice, crossed so each extraction, route and
// plant meets several omissions and slips.
const STATIC_STATES = [];
{
  const om = ['none', ...MU.rows.map((row) => row.period)], fa = ['none', '1', '2', '3', '4', '5', '6', '7'];
  let i = 0;
  for (const extraction of ['both', 'first', 'second']) for (const path of ROUTES) for (const amplitude of [0, CLAIM]) {
    STATIC_STATES.push({ extraction, path, amplitude, omitted: om[i % om.length], fault: fa[i % fa.length] }); i++;
  }
  for (const omitted of om) STATIC_STATES.push({ omitted });
  for (const fault of fa) STATIC_STATES.push({ fault });
}

// ================================================================== 4. rendered_figures_asserted
{
  const c = 'rendered_figures_asserted';
  const facts = factElements(html);
  const keys = new Set(facts.map((f) => f.key));
  for (const f of facts) {
    const want = EXPECTED[f.key];
    check(c, `static figure ${f.key}`, want !== undefined && f.text === normalize(want), `shows "${f.text}", expected "${want}"`);
  }
  const unused = Object.keys(EXPECTED).filter((k) => !keys.has(k));
  check(c, 'every expected figure is actually on the page', unused.length === 0, unused.join(', '));
  const unbound = unboundNumbers(html);
  const firstDiff = unbound.findIndex((v, i) => v !== INVENTORY[i]);
  check(c, 'every unbound number on the page is in the reviewed inventory, in order', unbound.length === INVENTORY.length && firstDiff === -1,
    `at ${firstDiff}: page "${unbound[firstDiff]}" vs "${INVENTORY[firstDiff]}" (${unbound.length} vs ${INVENTORY.length})`);
  const fm = frontmatter(md);
  check(c, 'frontmatter dek is the dek the values imply', fm.dek === EXPECTED_DEK, fm.dek);
  check(c, 'the HTML dek matches the frontmatter', normalize(html.match(/<p class="dek" id="dek">([\s\S]*?)<\/p>/)?.[1] ?? '') === EXPECTED_DEK);
  for (const [name, attr] of [['description', 'name'], ['og:description', 'property'], ['twitter:description', 'name']]) {
    check(c, `meta ${name} is the dek`, metaContent(html, name, attr) === EXPECTED_DEK);
  }
  check(c, 'plain placard is the placard the values imply', fm.plain === EXPECTED_PLAIN, fm.plain);
  check(c, 'seoTitle and <title> agree', fm.seoTitle === SEO && (html.match(/<title>([^<]*)<\/title>/)?.[1] ?? '').replace(/&#39;/g, "'") === SEO);
  check(c, 'frontmatter title, href, seam and draft', fm.title === TITLE && fm.href === `/strata/${SLUG}/` && fm.seam === 'mechanism' && fm.draft === 'false');
  for (const [name, attr] of [['og:title', 'property'], ['twitter:title', 'name'], ['og:image:alt', 'property']]) {
    check(c, `meta ${name}`, metaContent(html, name, attr) === `${TITLE} · Artificial Wasteland`);
  }
  check(c, 'og and twitter images point at the slug\'s card', metaContent(html, 'og:image', 'property') === `https://artwaste.land/og/${SLUG}.png` && metaContent(html, 'twitter:image') === `https://artwaste.land/og/${SLUG}.png`);
  check(c, 'canonical and og:url', html.includes(`<link rel="canonical" href="https://artwaste.land/strata/${SLUG}/" />`) && metaContent(html, 'og:url', 'property') === `https://artwaste.land/strata/${SLUG}/`);
  const ld = html.match(/<script type="application\/ld\+json">([\s\S]*?)<\/script>/);
  let json = null; try { json = JSON.parse(ld[1]); } catch { json = null; }
  check(c, 'JSON-LD parses and states the right article', json && json['@type'] === 'Article' && json.name === SEO && json.headline === TITLE && json.description === EXPECTED_DEK
    && json.url === `https://artwaste.land/strata/${SLUG}/` && json.image === `https://artwaste.land/og/${SLUG}.png` && /^\d{4}-\d{2}-\d{2}$/.test(json.datePublished));
  check(c, 'the manifest headline is the headline the page prints', record.headline === EXPECTED.headline && keys.has('headline'));
  check(c, 'the manifest novelty sentence is the spec\'s, verbatim', record.novelty === SPEC.novelty);
  check(c, 'the manifest second-layer sentence matches the page', record.second_layer.result.replace(/-/g, '−').replace(/−one/g, '-one') === EXPECTED.citable);
  check(c, 'JSON-LD publication date is the frontmatter date', json && json.datePublished === fm.date && /^\d{4}-\d{2}-\d{2}$/.test(json.dateModified) && json.dateModified >= json.datePublished);
  check(c, 'share card size and viewport tags', metaContent(html, 'og:image:width', 'property') === '1200' && metaContent(html, 'og:image:height', 'property') === '630'
    && metaContent(html, 'viewport') === 'width=device-width, initial-scale=1' && metaContent(html, 'theme-color') === '#08090c' && metaContent(html, 'twitter:card') === 'summary_large_image');
  // sentences that state a computed fact must appear exactly when the computation says so
  const vis = visibleText(html);
  const p = r.power, rec = r.reconcile, sw = r.sweep;
  const claims = [
    ['every bunch assignment stays', p.sameBunches],
    ['matches the printed bunch column', p.real.assignmentsMatchPrinted],
    ['u and does not cross it', !p.real.flag],
    ['u and does. The rule is the same before and after', p.planted.flag],
    ['Every one of the eight deletions keeps the sign', sw.allKeepSign],
    ['the T_START formula reproduces all seven printed T_START values to the nanosecond', rec.startFormulaExact],
    ['the delay columns reproduce the final row exactly, for all seven events, event 1 included', rec.delayMinusFinal.every((d) => d === rec.delayMinusFinal[0])],
    ['No other event has a disagreement between its timestamps and its elapsed time', deepEqual(rec.inconsistentEvents, [1])],
    ['which is the printed total', r.calibration.totalAgrees],
    ['The recomputed centres agree to the integer', Math.round(indMu.A.mean) === MP.class_A_mean_ns && Math.round(indMu.B.mean) === MP.class_B_mean_ns && Math.round(indMu.contrast) === MP.contrast_ns],
    ['through all three routes the planted claim comes back at exactly', r.powerAllPaths.every((t) => near(t.recovered, CLAIM, 1e-6))],
    ['and the real record never does', r.powerAllPaths.every((t) => !t.realFlag)],
    ['The rebuilt claim is slightly larger than the printed one and slightly less precise', indepDelta > CLAIM && indepStat > P.opera_v1.stat_ns],
    ['to the place they were printed', Number(indTsStats.mean.toFixed(1)) === IC.published.mean_ns && Number(indTsStats.rms.toFixed(1)) === IC.published.rms_ns],
    ['the size that was planted', near(indPlantedStats.mean - indTsStats.mean, CLAIM, 1e-6)],
    ['The RMS stays', near(p.planted.rms, p.real.rms, 1e-9)],
    ['The T_STOP formula lands', deepEqual(rec.stopGaps.slice(1), Array(6).fill(rec.commonStopGap)) && rec.stopGaps[0] !== rec.commonStopGap],
    ['They could not both be right about the neutrinos', V2.bunched_delta_ns - IC.published.mean_ns > 3 * Math.hypot(V2.bunched_error_ns, U)],
    ['come from the same bunched-beam run and the same selection', V2.bunched_internal + V2.bunched_external === V2.bunched_events && V4.tt_events === V2.bunched_events],
    ['these seven events could not have told the corrected value from no effect at all', V4.corrected_ns < reachInd],
    ['They could exclude the claim as printed', CLAIM > reachInd],
    ['the published one is the stricter', 3 * U >= 3 * dataU(indTsStats)],
    ['On this record the two scales nearly agree', Math.abs(scatterScale(indTsStats) - IC.published.stat_ns) < 0.1],
    ['which this table guarantees', Math.max(...classMeans('A')) < Math.min(...classMeans('B'))],
    ['leaves every bunch where it was, and puts that event on the audit', [1, 2, 3, 4, 5, 6, 7].every((k) => { const a = indepAudit(slipped(k)); return deepEqual(a.bunches, indTs.map((e) => e.bunch)) && a.flagged.includes(k) && near(a.stats.mean - indTsStats.mean, -SPEC.fault / 7, 1e-9); })],
    ['On the printed flight-time route the bunches are read from the printed column', r.powerAllPaths[1].real.bunchesReassigned === false],
    ['ns window refuses it first', SPEC.window < IC.reference.bunch_spacing_ns / 2],
    ['the planted record stays inside that window', indPlanted.every((e) => Math.abs(e.delta) <= SPEC.window)],
  ];
  for (const [phrase, truth] of claims) check(c, `claim sentence "${phrase}" is printed exactly when true`, truth ? vis.split(phrase).length - 1 === 1 : !vis.includes(phrase));
  // Every readout, every table cell and every arithmetic line report.js produces, in every checked
  // state, must equal the string the verifier assembled from its own numbers (DEPTH audit finding 1).
  const o = REP.readouts(r, sens);
  const want0 = expectReadouts({});
  check(c, 'report.js readouts and the verifier\'s expectations name exactly the same keys', deepEqual(Object.keys(o).sort(), Object.keys(want0).sort()),
    `only in report.js: ${Object.keys(o).filter((k) => !(k in want0)).join(', ')}; only expected: ${Object.keys(want0).filter((k) => !(k in o)).join(', ')}`);
  for (const st of STATIC_STATES) {
    const rr = E.analyse(bundle, st), got = REP.readouts(rr, sens), want = expectReadouts(st);
    const wrong = Object.keys(want).filter((k) => got[k] !== want[k]);
    check(c, `readouts equal the independent strings (${JSON.stringify(st)})`, wrong.length === 0, wrong.slice(0, 3).map((k) => `${k}: "${got[k]}" vs "${want[k]}"`).join('; '));
    const gt = REP.tables(rr), wt = expectTables(st);
    const badT = Object.keys(wt).filter((k) => !deepEqual(gt[k], wt[k]));
    check(c, `every table cell equals the independent arithmetic (${JSON.stringify(st)})`, badT.length === 0 && deepEqual(Object.keys(gt).sort(), Object.keys(wt).sort()),
      badT.map((k) => `${k}: ${JSON.stringify(gt[k]).slice(0, 120)} vs ${JSON.stringify(wt[k]).slice(0, 120)}`).join('; '));
  }
  for (const path of ROUTES) {
    const rr = E.analyse(bundle, { path });
    const bad = [0, 1, 2, 3, 4, 5, 6].filter((i) => !deepEqual(REP.eventArithmetic(rr, i), expectArithmetic(path, i)));
    check(c, `every event's arithmetic lines equal the independent arithmetic (${path})`, bad.length === 0, bad.map((i) => `event ${i + 1}: ${REP.eventArithmetic(rr, i).join(' / ')}`).join('; '));
  }
  const ref0 = E.icarusReference(IC);
  check(c, 'the spread demonstration sentence equals the independent one', REP.spreadText(E.testControl(E.spreadRecord(ROWS, ref0), ref0, CLAIM), E.RULES.spreadFactor) === EXPECTED_SPREAD,
    REP.spreadText(E.testControl(E.spreadRecord(ROWS, ref0), ref0, CLAIM), E.RULES.spreadFactor));
  // report.js decides nothing, so every branch it prints must follow the analysis it is handed. Each
  // flipped copy below goes to the unmodified formatter. A formatter that typed its answer is an
  // equivalent mutant on the real record (every reachable state prints the same words), and only a
  // flip like these can see it.
  {
    const base = E.analyse(bundle);
    const flip = (fn) => { const x = structuredClone(base); fn(x); return REP.readouts(x, sens); };
    const tflip = (fn) => { const x = structuredClone(base); fn(x); return REP.tables(x); };
    const ref1 = E.icarusReference(IC), sp = E.testControl(E.spreadRecord(ROWS, ref1), ref1, CLAIM);
    const branches = [
      ['pwSame follows sameBunches', flip((x) => { x.power.sameBunches = false; }).pwSame === 'CHANGED'],
      ['pwRealRule follows real.flag', flip((x) => { x.power.real.flag = true; }).pwRealRule === 'crosses'],
      ['pwPlantedRule follows planted.flag', flip((x) => { x.power.planted.flag = false; }).pwPlantedRule === 'does not cross'],
      ['pwVerdict and pwConclusion carry the engine\'s words', (() => { const o = flip((x) => { x.power.verdict = 'could NOT have confirmed the claim'; x.power.conclusion = 'INCONCLUSIVE'; });
        return o.pwVerdict === 'The control could NOT have confirmed the claim.' && o.pwConclusion === 'INCONCLUSIVE'; })()],
      ['ctlBunchMatch follows assignmentsMatchPrinted', flip((x) => { x.control.assignmentsMatchPrinted = false; }).ctlBunchMatch === 'an assignment differs from the printed column'],
      ['ctlBunchMatch follows bunchesReassigned', flip((x) => { x.control.bunchesReassigned = false; }).ctlBunchMatch === 'taken from the printed column, not reassigned on this route'],
      ['ctlRule follows control.flag', flip((x) => { x.control.flag = true; }).ctlRule === 'crosses the three-error rule'],
      ['stripRule follows active.flag', flip((x) => { x.active.flag = true; }).stripRule === 'crosses the rule'],
      ['anchorVerdict follows anchorCheck.agrees', flip((x) => { x.anchorCheck.agrees = false; }).anchorVerdict === 'OUTSIDE the documented approximation allowance'],
      ['calDerived follows allTermsAgree', flip((x) => { x.calibration.allTermsAgree = false; }).calDerived === 'a printed correction differs from final minus blind'],
      ['pwReach follows the reach', flip((x) => { x.reach.reach = null; }).pwReach === 'none inside the association window' && flip((x) => { x.reach.reach = 12.3456; }).pwReach === '12.35 ns'],
      ['auditFlags follows the audit list', flip((x) => { x.audit.reconcile.inconsistentEvents = [1, 4]; }).auditFlags === 'events 1 and 4'],
      ['the route table\'s rule columns follow each route\'s flags', (() => { const t = tflip((x) => { x.powerAllPaths[0].real.flag = true; x.powerAllPaths[0].planted.flag = false; });
        return t.powerPaths[0][6] === 'crosses' && t.powerPaths[0][7] === 'no'; })()],
      ['the route table\'s bunches column follows sameBunches', tflip((x) => { x.powerAllPaths[2].sameBunches = false; }).powerPaths[2][8] === 'CHANGED'],
      ['the events table marks a reassigned bunch', tflip((x) => { x.control.events[5].bunchMatches = false; x.control.events[5].bunch = 1; }).events[5][4] === '1 (printed 4)'],
      ['the spread sentence follows its test', /Bunches CHANGED\. The control COULD have confirmed the claim: SENSITIVE/.test(REP.spreadText({ ...sp, sameBunches: false, verdict: 'COULD have confirmed the claim', conclusion: 'SENSITIVE' }, 7))],
    ];
    for (const [name, ok] of branches) check(c, `report.js branch: ${name}`, ok);
  }
  const outKeys = [...html.matchAll(/data-out="([^"]+)"/g)].map((m) => m[1]);
  check(c, 'every readout slot on the page has a value to show, and every readout has a slot', outKeys.every((k) => k in o)
    && Object.keys(o).filter((k) => !['fitChoice', 'fitDelta', 'fitStat'].includes(k)).every((k) => outKeys.includes(k)),
    [...outKeys.filter((k) => !(k in o)), ...Object.keys(o).filter((k) => !outKeys.includes(k))].join(', '));
}

// ================================================================== 5. choices_are_live
{
  const c = 'choices_are_live';
  const byId = Object.fromEntries(record.choices.map((ch) => [ch.id, ch]));
  check(c, 'the manifest declares the four spec choices and the added slip, none inert', ['extraction', 'path', 'amplitude', 'omitted', 'fault'].every((id) => byId[id] && byId[id].inert === false)
    && record.choices.length === 5);
  const run = (choices) => E.analyse(bundle, choices);
  const optionValues = (id) => [...(html.match(new RegExp(`<select id="${id}"[\\s\\S]*?</select>`))?.[0] ?? '').matchAll(/value="([^"]+)"/g)].map((m) => m[1]);
  const ex = byId.extraction.options.map((o) => run({ extraction: o }).fit);
  check(c, 'extraction moves the fitted early arrival and width', new Set(ex.map((f) => f.delta.toFixed(6))).size === 3 && new Set(ex.map((f) => f.stat.toFixed(6))).size === 3
    && near(ex[1].delta, firstDelta, 1e-6) && near(ex[2].delta, secondDelta, 1e-6));
  const pa = byId.path.options.map((o) => run({ path: o }).control);
  check(c, 'route moves the mean, RMS and event 1 residual', new Set(pa.map((x) => x.mean.toFixed(6))).size === 3 && new Set(pa.map((x) => x.rms.toFixed(6))).size === 2
    && deepEqual(pa.map((x) => x.events[0].delta), [-2, -6, -11]));
  const am = byId.amplitude.options.map((o) => run({ amplitude: o }).active);
  check(c, 'planted amplitude moves every residual, the mean and the rule', am.length === 2 && near(am[1].mean - am[0].mean, CLAIM, 1e-6) && am[0].flag !== am[1].flag
    && am[1].deltas.every((d, i) => d !== am[0].deltas[i]));
  const om = byId.omitted.options.map((o) => run({ omitted: o }).muon);
  check(c, 'muon omission moves counts, means and the contrast, all nine distinct', new Set(om.map((m) => m.contrast.toFixed(6))).size === 9
    && om.every((m, i) => i === 0 || m.A.count + m.B.count < om[0].A.count + om[0].B.count));
  const fa = byId.fault.options.map((o) => run({ fault: o }).audit);
  check(c, 'the slip moves the audit mean by -30/7, adds its event to the flagged list, and never reaches the power test', fa.length === 8
    && fa.every((a, i) => i === 0 ? near(a.control.mean, indTsStats.mean, 1e-12) && deepEqual(a.reconcile.inconsistentEvents, [1])
      : near(a.control.mean - indTsStats.mean, -SPEC.fault / 7, 1e-9) && a.reconcile.inconsistentEvents.includes(i))
    && byId.fault.options.every((o) => deepEqual(run({ fault: o }).power, r.power) && deepEqual(run({ fault: o }).control, r.control)));
  check(c, 'defaults in the manifest are the engine defaults', byId.extraction.default === E.DEFAULT_CHOICES.extraction && byId.path.default === E.DEFAULT_CHOICES.path
    && byId.amplitude.default === E.DEFAULT_CHOICES.amplitude && byId.omitted.default === E.DEFAULT_CHOICES.omitted && byId.fault.default === E.DEFAULT_CHOICES.fault);
  check(c, 'the page offers exactly the slip options', deepEqual(optionValues('fault'), byId.fault.options) && E.RULES.faultShift_ns === SPEC.fault);
  check(c, 'the page offers exactly the extraction options', deepEqual(optionValues('extraction'), byId.extraction.options));
  check(c, 'the page offers exactly the muon options', deepEqual(optionValues('omit'), byId.omitted.options));
  check(c, 'the page offers exactly the three routes', deepEqual([...html.matchAll(/name="path" value="([^"]+)"/g)].map((m) => m[1]), byId.path.options));
  check(c, 'the page offers the two-state plant button', /<button id="plant" type="button" aria-pressed="false"/.test(html) && deepEqual(byId.amplitude.options, [0, CLAIM]));
}

// ================================================================== 6. planted_fault_caught
{
  const c = 'planted_fault_caught';
  const faulty = ROWS.map((row) => ({ ...row }));
  faulty[2].T_STOP_ns += 30;
  const base = E.runIcarus(ROWS, { path: 'timestamps', reference: r.reference });
  const hit = E.runIcarus(faulty, { path: 'timestamps', reference: r.reference });
  check(c, 'a T_STOP moved 30 ns moves the mean by exactly -30/7', near(hit.mean - base.mean, -30 / 7, 1e-9));
  check(c, 'and leaves every bunch identity fixed', deepEqual(hit.assignments, base.assignments));
  const rec = E.reconcileIcarus(faulty, r.reference);
  check(c, 'the baseline consistency audit names event 3 with a 30 ns elapsed gap', rec.inconsistentEvents.includes(3) && rec.events[2].elapsedGap === 30);
  check(c, 'the frozen table is still intact after the fault run', deepEqual(ROWS, parse(FILES[2]).rows));
  check(c, 'the page\'s slip control plants exactly the verifier\'s fault: the same copy, through the same runIcarus and reconcileIcarus', [1, 2, 3, 4, 5, 6, 7].every((k) => {
    const mine = slipped(k), theirs = E.plantFault(ROWS, k);
    const a = E.analyse(bundle, { fault: String(k) }).audit;
    return deepEqual(theirs, mine) && deepEqual(a.control, E.runIcarus(mine, { path: 'timestamps', reference: r.reference }))
      && deepEqual(a.reconcile.inconsistentEvents, indepAudit(mine).flagged);
  }));
  const muFault = fresh(); const row = muFault.muons.rows.find((x) => x.period === '2010'); row.mean_ns += 50;
  const moved = E.aggregateMuons(muFault.muons).contrast - E.aggregateMuons(bundle.muons).contrast;
  check(c, 'a muon period moved by 50 ns moves the contrast by exactly its count share', near(moved, -50 * row.events / indMu.B.n, 1e-9));
  const shifted = fresh(); shifted.digitised.panels.forEach((p) => p.points.forEach((v) => { v.blind_delay_ns += 3; }));
  check(c, 'a claimant-side fault (x moved 3 ns) moves the fitted centre by 3 ns and breaks the anchor',
    near(E.fitClaimantLikelihood(shifted.digitised, shifted.calibration).delta - r.anchor.delta, 3, 1e-6) && !E.anchorCheck(E.fitClaimantLikelihood(shifted.digitised, shifted.calibration), P.opera_v1).agrees);
}

// ================================================================== 7. refusal_asserted
{
  const c = 'refusal_asserted';
  const R = E.REFUSALS, ref = r.reference, copy = () => ROWS.map((row) => ({ ...row }));
  refuses(c, 'a non-finite arrival time', () => { const x = copy(); x[3].T_STOP_ns = NaN; E.runIcarus(x, { path: 'timestamps', reference: ref }); }, R.times);
  refuses(c, 'a missing start time', () => { const x = copy(); delete x[0].T_START_ns; E.runIcarus(x, { path: 'timestamps', reference: ref }); }, R.times);
  refuses(c, 'a missing delay in the delay-column route', () => { const x = copy(); delete x[5].d3L_ns; E.runIcarus(x, { path: 'delay-columns', reference: ref }); }, R.times);
  refuses(c, 'a duplicated event identifier', () => { const x = copy(); x[1].event = 1; E.runIcarus(x, { path: 'timestamps', reference: ref }); }, R.sample);
  refuses(c, 'six events instead of seven', () => E.runIcarus(copy().slice(0, 6), { path: 'timestamps', reference: ref }), R.sample);
  refuses(c, 'an event dated in 2012, from a different sample', () => { const x = copy(); x[6].date = '2012-05-10'; E.runIcarus(x, { path: 'timestamps', reference: ref }); }, R.sample);
  refuses(c, 'a whole bunch spacing planted', () => E.injectClaim(ROWS, IC.reference.bunch_spacing_ns, { path: 'timestamps', claimed: CLAIM }), R.injection);
  refuses(c, 'any other amplitude planted', () => E.injectClaim(ROWS, 30, { path: 'timestamps', claimed: CLAIM }), R.injection);
  refuses(c, 'a non-finite amplitude', () => E.injectClaim(ROWS, NaN, { path: 'timestamps', claimed: CLAIM }), R.injection);
  refuses(c, 'an exact tie between two bunches', () => { const x = copy(); x[0].T_STOP_ns = x[0].T_START_ns + IC.reference.light_tof_ns + IC.reference.bunch_spacing_ns / 2; E.runIcarus(x, { path: 'timestamps', reference: ref }); }, R.bunch);
  refuses(c, 'a residual outside the 200 ns window', () => { const x = copy(); x[0].T_STOP_ns = x[0].T_START_ns + IC.reference.light_tof_ns + 300; E.runIcarus(x, { path: 'timestamps', reference: ref }); }, R.window);
  check(c, 'the window is the spec\'s 200 ns', E.RULES.associationWindow_ns === SPEC.window);
  refuses(c, 'an invalid printed bunch index', () => { const x = copy(); x[2].printed_bunch = 5; E.runIcarus(x, { path: 'timestamps', reference: ref }); }, R.bunch);
  refuses(c, 'an unknown route', () => E.runIcarus(ROWS, { path: 'guess', reference: ref }), R.path);
  const flipped = fresh(); const pts = flipped.digitised.panels[0].points; const ys = pts.map((v) => v.log_likelihood);
  const lo = Math.min(...ys), hi = Math.max(...ys); pts.forEach((v) => { v.log_likelihood = lo + hi - v.log_likelihood; });
  const dom = E.RULES.figureDomain.first;
  check(c, 'the flipped curve stays inside the figure axes, so only its curvature is wrong', pts.every((v) => v.log_likelihood >= dom.y[0] && v.log_likelihood <= dom.y[1]));
  refuses(c, 'a likelihood that bends upward', () => E.fitClaimantLikelihood(flipped.digitised, flipped.calibration), R.curve);
  refuses(c, 'points outside the Figure 8 domain', () => { const d = fresh(); d.digitised.panels[1].points[0].blind_delay_ns = 1200; E.fitClaimantLikelihood(d.digitised, d.calibration); }, R.curve);
  refuses(c, 'fewer than three distinct points', () => { const d = fresh(); d.digitised.panels[0].points = d.digitised.panels[0].points.slice(0, 2); E.fitClaimantLikelihood(d.digitised, d.calibration); }, R.curve);
  refuses(c, 'an unrecognised extraction', () => E.fitClaimantLikelihood(DIG, CAL, 'third'), R.extraction);
  refuses(c, 'two muon periods omitted at once', () => E.aggregateMuons(MU, ['2007', '2008-1']), R.muons);
  refuses(c, 'an unknown muon period', () => E.aggregateMuons(MU, '2013'), R.muons);
  refuses(c, 'a non-positive muon count', () => { const m = fresh().muons; m.rows[0].events = 0; E.aggregateMuons(m); }, R.muons);
  refuses(c, 'a slip in an event that does not exist', () => E.plantFault(ROWS, 8), R.fault);
  refuses(c, 'a slip choice outside none and 1 to 7', () => E.analyse(bundle, { fault: '0' }), R.fault);
  refuses(c, 'a spread factor that does not spread', () => E.spreadRecord(ROWS, ref, 1), R.spread);
  refuses(c, 'an emptied class', () => { const m = fresh().muons; m.rows.forEach((row, i) => { row.class = i === 0 ? 'A' : 'B'; }); E.aggregateMuons(m, '2007'); }, R.muons);
  const vis = visibleText(html);
  check(c, 'the page offers the three refusals and states the domain', ['refuse-bunch', 'refuse-blank', 'refuse-curve'].every((id) => html.includes(`id="${id}"`))
    && vis.includes('The full domain:') && vis.includes('is never mixed in'));
}

// ================================================================== 8. provenance_pinned
{
  const c = 'provenance_pinned';
  const sha = (b) => crypto.createHash('sha256').update(b).digest('hex');
  for (const f of FILES) {
    const h = sha(bytes[f]);
    const rec = record.records.find((x) => x.file === `data/${f}`);
    check(c, `${f}: SHA-256 matches record.json`, rec && rec.sha256 === h, rec ? `${rec.sha256} vs ${h}` : 'no record entry');
    check(c, `${f}: SHA-256 is listed in the README`, readme.includes(h));
    const copyPath = path.join(RESEARCH, 'data', f);
    check(c, `${f}: research copy is byte-identical`, fs.existsSync(copyPath) && sha(fs.readFileSync(copyPath)) === h);
    check(c, `${f}: under 2 MB`, bytes[f].length < 2 * 1024 * 1024);
  }
  const tampered = Buffer.from(bytes[FILES[2]]); tampered[tampered.length - 3] ^= 1;
  check(c, 'NEGATIVE: one flipped bit no longer matches', sha(tampered) !== record.records.find((x) => x.file === `data/${FILES[2]}`).sha256);
  const pageJs = fs.readFileSync(path.join(PAGE, 'page.js'), 'utf8');
  const gateAt = pageJs.indexOf('if (!provenanceOk(provenance))'), computeAt = pageJs.indexOf('digitisationSensitivity(bundle');
  check(c, 'page.js refuses to compute before any computation when provenance fails', gateAt > 0 && computeAt > gateAt && /dataset\.ready = 'mismatch'/.test(pageJs));
  check(c, 'every record has a url, licence and retrieval date (the printed-values file was extended on 2026-09-23)', record.records.every((x) => x.url && x.licence && x.licence_url
    && x.retrieved === (x.file === 'data/published-values.json' ? '2026-09-23' : '2026-09-22')));
  const notice = fs.readFileSync(path.join(PAGE, 'NOTICE.txt'), 'utf8');
  check(c, 'NOTICE.txt names every source', ['1109.4897v1', '1109.4897v2', '1109.4897v4', '1212.1276', '1203.3433v3', '1206.2488v1', 'home.cern', 's42005-025-02347-z'].every((k) => notice.includes(k)));
  check(c, 'data.js checks the same hashes in the browser', /crypto\.subtle\.digest\('SHA-256'/.test(fs.readFileSync(path.join(PAGE, 'data.js'), 'utf8')));
}

// The page's own loader (data.js), run in node against the page's files through a stub fetch: once as
// shipped, once with one byte of the ICARUS table flipped. The status and the refusal must follow.
async function loaderPass() {
  const c = 'provenance_pinned';
  const realFetch = globalThis.fetch;
  const serve = (flip) => async (url) => {
    const u = String(url), f = fileURLToPath(u);
    if (!fs.existsSync(f)) return { ok: false, json: async () => ({}), arrayBuffer: async () => new ArrayBuffer(0) };
    let b = fs.readFileSync(f);
    if (flip && f.endsWith(FILES[2])) { b = Buffer.from(b); b[b.length - 3] ^= 1; }
    const ab = b.buffer.slice(b.byteOffset, b.byteOffset + b.length);
    return { ok: true, json: async () => JSON.parse(b.toString('utf8')), arrayBuffer: async () => ab };
  };
  try {
    globalThis.fetch = serve(false);
    const good = await loadRecord();
    check(c, 'the page\'s loader, as shipped: every file "matches record.json" and the gate opens', good.provenance.length === 5
      && good.provenance.every((p) => p.status === 'matches record.json') && provenanceOk(good.provenance));
    globalThis.fetch = serve(true);
    const bad = await loadRecord();
    const hit = bad.provenance.find((p) => p.file === FILES[2]);
    check(c, 'NEGATIVE: the page\'s loader handed one flipped byte says "DOES NOT MATCH record.json" and the gate shuts', hit && hit.status === 'DOES NOT MATCH record.json'
      && bad.provenance.filter((p) => p.status === 'matches record.json').length === 4 && !provenanceOk(bad.provenance));
  } catch (e) {
    check(c, 'the page\'s loader ran in node', false, e.message);
  } finally {
    globalThis.fetch = realFetch;
  }
}
await loaderPass();

// ================================================================== 9. verdict_dated
{
  const c = 'verdict_dated';
  const vis = visibleText(html);
  check(c, 'category ARTEFACT, dated, decided by the instrument', record.verdict.category === 'ARTEFACT' && record.verdict.as_of === '2026-09-22'
    && record.decided_by === 'instrument' && record.years_to_decision === 1);
  check(c, 'the page prints the category and date as figures the verifier checks', factElements(html).some((f) => f.key === 'verdict.category') && factElements(html).some((f) => f.key === 'verdict.asof'));
  check(c, 'at least two sources in the manifest', record.verdict.sources.length >= 2);
  check(c, 'the page cites the corrected OPERA paper by DOI', html.includes('https://doi.org/10.1007/JHEP10(2012)093') && vis.includes('JHEP 10 (2012) 093'));
  check(c, 'the page cites CERN\'s dated update', html.includes('https://home.cern/opera-experiment-reports-anomaly-in-flight-time-of-neutrinos-from-cern-to-gran-sasso/') && vis.includes('update of 8 June 2012'));
  check(c, 'the page cites the LVD and OPERA muon paper', vis.includes('arXiv:1206.2488v1'));
  check(c, 'the page cites OPERA\'s 2012 remeasurement, which the manifest lists as a verdict source', html.includes('https://doi.org/10.1007/JHEP01(2013)153') && vis.includes('arXiv:1212.1276')
    && record.verdict.sources.some((x) => x.includes('JHEP01(2013)153')));
  check(c, 'the page gives the claimants\' own bunched-beam confirmation from version 2', html.includes('https://arxiv.org/pdf/1109.4897v2') && vis.includes('arXiv:1109.4897v2 (17 November 2011)'));
  check(c, 'what would change the verdict is printed as recorded', factElements(html).some((f) => f.key === 'verdict.would_change' && f.text === record.verdict.would_change));
  check(c, 'the verdict dates agree with the timeline sources', P.cern_2012.update === '2012-06-08' && V4.submitted === '2012-07-12' && V4.published === '2012-10-12');
  const pageFiles = ['index.html', 'engine.js', 'report.js', 'render.js', 'page.js', 'data.js'].map((f) => fs.readFileSync(path.join(PAGE, f), 'utf8')).join('\n');
  const banned = /\b(fraud|fabricat\w*|misconduct|hoax|cover-up|incompetent|debunk\w*|refuted|disproved)\b|Einstein defeated|neutrinos proved faster than light/i;
  check(c, 'no forbidden or sneering words anywhere in the page\'s files', !banned.test(pageFiles) && !banned.test(md), (pageFiles.match(banned) || md.match(banned) || [''])[0]);
  check(c, 'the claim is never called retracted or withdrawn', !/\b(retracted|withdrawn|WITHDRAWN)\b/.test(vis));
}

// ================================================================== hygiene (fails the run, belongs to no cell)
{
  const c = 'hygiene';
  const all = [...['index.html', 'engine.js', 'report.js', 'render.js', 'page.js', 'data.js', 'NOTICE.txt', 'record.json'].map((f) => path.join(PAGE, f)),
    path.join(ROOT, 'src/content/strata', `${SLUG}.md`), ...fs.readdirSync(RESEARCH).filter((f) => /\.(mjs|py|md)$/.test(f)).map((f) => path.join(RESEARCH, f))];
  const dash = all.filter((f) => fs.readFileSync(f, 'utf8').split('\n').some((line) => line.includes(String.fromCharCode(0x2014)) && !line.includes('em-dash-ok')));
  check(c, 'no em dash in any file this page ships or its research uses', dash.length === 0, dash.join(', '));
  const inline = [...html.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/g)];
  check(c, 'the only inline script is the JSON-LD', inline.filter((m) => !/\bsrc=/.test(m[1])).length === 1 && inline.some((m) => /application\/ld\+json/.test(m[1])));
  check(c, 'load-bearing closing tags are present', /<\/script>\s*<\/body>\s*<\/html>\s*$/.test(html));
  for (const f of ['engine.js', 'report.js', 'render.js', 'page.js', 'data.js']) {
    let ok = true; try { execFileSync(process.execPath, ['--check', path.join(PAGE, f)], { stdio: 'ignore' }); } catch { ok = false; }
    check(c, `${f} parses`, ok);
  }
  const js = ['engine.js', 'report.js', 'render.js', 'page.js', 'data.js'].map((f) => fs.readFileSync(path.join(PAGE, f), 'utf8')).join('\n');
  check(c, 'no script names an outside host (the SVG namespace string aside)', !/https?:\/\/(?!www\.w3\.org\/2000\/svg)/.test(js));
  check(c, 'fonts are self-hosted', html.includes('<link rel="stylesheet" href="/fonts/fonts.css" />') && !/fonts\.googleapis|gstatic/.test(html));
  check(c, 'no link to the private repository and no shell command for the reader', !/github\.com\/[^"'\s]*\/Artificial-Wasteland/i.test(html) && !/\bnode\s+\S+\.mjs|\$\s+node/.test(visibleText(html)));
  check(c, 'reduced-motion guard and visible focus styles exist', /prefers-reduced-motion/.test(html) && /:focus-visible/.test(html) && /reduceMotion\(\)/.test(fs.readFileSync(path.join(PAGE, 'render.js'), 'utf8')));
  check(c, 'every readout region is announced', (html.match(/role="status" aria-live="polite"/g) || []).length >= 8);
  const fm = frontmatter(md);
  check(c, 'three to five relates, each to a page that exists', fm.relates.length >= 3 && fm.relates.length <= 5 && fm.relates.every((x) => fs.existsSync(path.join(ROOT, 'src/content/strata', `${x.to}.md`))));
  check(c, 'the ledger gate will find this verifier first', fs.readdirSync(RESEARCH).filter((f) => /^verify.*\.mjs$/.test(f)).sort()[0] === path.basename(fileURLToPath(import.meta.url)));
}

// ================================================================== the rendered page, in a real browser
async function browserPass() {
  const c = 'rendered_figures_asserted';
  let chromium;
  for (const base of [path.join(ROOT, 'package.json'), '/home/liam/tools/package.json']) {
    try { chromium = createRequire(base)('playwright').chromium; break; } catch { /* try the next */ }
  }
  if (!chromium) { notes.push('BROWSER PASS SKIPPED: no Playwright installation was found; the static checks above decided rendered_figures_asserted.'); return; }
  const publicRoot = path.join(ROOT, 'public');
  const mime = { '.html': 'text/html', '.js': 'text/javascript', '.json': 'application/json', '.css': 'text/css', '.woff2': 'font/woff2', '.svg': 'image/svg+xml', '.png': 'image/png', '.ico': 'image/x-icon' };
  const server = http.createServer((req, res) => {
    const u = decodeURIComponent(new URL(req.url, 'http://local').pathname);
    const f = path.join(publicRoot, u.endsWith('/') ? `${u}index.html` : u);
    if (!f.startsWith(publicRoot + path.sep) || !fs.existsSync(f) || !fs.statSync(f).isFile()) { res.writeHead(404); res.end(); return; }
    res.writeHead(200, { 'Content-Type': mime[path.extname(f)] || 'application/octet-stream' }); fs.createReadStream(f).pipe(res);
  });
  await new Promise((ok) => server.listen(0, '127.0.0.1', ok));
  const origin = `http://127.0.0.1:${server.address().port}`;
  let browser;
  const deadline = setTimeout(() => { notes.push('BROWSER PASS hit its 100 s limit'); try { browser && browser.close(); } catch { /* closing */ } }, 100000);
  try {
    browser = await chromium.launch({ headless: true });
    for (const width of [1280, 390]) {
      const ctx = await browser.newContext({ viewport: { width, height: 900 }, reducedMotion: 'reduce' });
      const page = await ctx.newPage(); page.setDefaultTimeout(15000);
      const errors = [], external = [], bad = [];
      page.on('pageerror', (e) => errors.push(e.message));
      page.on('request', (q) => { if (!q.url().startsWith(origin + '/') && !/^(data|blob):/.test(q.url())) external.push(q.url()); });
      page.on('response', (q) => { if (q.status() >= 400 && q.url().includes(`/strata/${SLUG}/`)) bad.push(`${q.status()} ${q.url()}`); });
      await page.goto(`${origin}/strata/${SLUG}/`, { waitUntil: 'networkidle' });
      await page.waitForFunction(() => document.body.dataset.ready);
      check(c, `browser ${width}px: the instrument started`, (await page.getAttribute('body', 'data-ready')) === 'true');
      check(c, `browser ${width}px: no script errors and no failed page requests`, errors.length === 0 && bad.length === 0, [...errors, ...bad].join('; '));
      check(c, `browser ${width}px: no third-party request`, external.length === 0, external.join(', '));
      const overflow = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
      check(c, `browser ${width}px: no horizontal overflow`, overflow <= 0, `${overflow}px`);
      if (width !== 1280) { await ctx.close(); continue; }
      // What the reader sees, compared with the verifier's OWN strings (never report.js): every readout,
      // every cell of the five live tables, the highlighted rows, the arithmetic box, and the chart
      // marks read back through each chart's own labelled ticks.
      const compare = async (label, choices, eventIndex = 0) => {
        const ch = { extraction: 'both', path: 'timestamps', amplitude: 0, omitted: 'none', fault: 'none', ...choices };
        const expected = expectReadouts(ch), tabs = expectTables(ch);
        const shown = await page.locator('[data-out]').evaluateAll((nodes) => nodes.map((n) => ({ key: n.dataset.out, text: n.textContent })));
        const wrong = shown.filter((s) => s.text !== expected[s.key]);
        check(c, `browser: every readout equals the verifier's own string (${label})`, wrong.length === 0 && shown.length > 50, wrong.slice(0, 3).map((w) => `${w.key}: ${w.text} vs ${expected[w.key]}`).join('; '));
        const bodies = await page.evaluate(() => Object.fromEntries(['cal-body', 'event-body', 'power-body', 'reconcile-body', 'deletion-body'].map((id) => [id, {
          rows: Array.from(document.getElementById(id).rows, (tr) => Array.from(tr.cells, (td) => td.textContent)),
          hl: Array.from(document.getElementById(id).rows).findIndex((tr) => tr.classList.contains('hl')) }])));
        const tmap = { 'cal-body': 'calibration', 'event-body': 'events', 'power-body': 'powerPaths', 'reconcile-body': 'reconcile', 'deletion-body': 'deletions' };
        const badT = Object.entries(tmap).filter(([id, k]) => !deepEqual(bodies[id].rows, tabs[k]));
        check(c, `browser: every cell of the five live tables equals the verifier's arithmetic (${label})`, badT.length === 0, badT.map(([id]) => `${id}: ${JSON.stringify(bodies[id].rows[0])}`).join('; '));
        const wantHl = { 'power-body': ROUTES.indexOf(ch.path), 'deletion-body': ch.omitted === 'none' ? -1 : MU.rows.findIndex((x) => x.period === ch.omitted),
          'reconcile-body': ch.fault === 'none' ? 0 : Number(ch.fault) - 1, 'cal-body': -1, 'event-body': -1 };
        check(c, `browser: the highlighted rows are the chosen route, period and event (${label})`, Object.entries(wantHl).every(([id, i]) => bodies[id].hl === i),
          JSON.stringify(Object.fromEntries(Object.keys(wantHl).map((id) => [id, bodies[id].hl]))));
        const arith = await page.locator('#event-arith div').allTextContents();
        check(c, `browser: the arithmetic box shows event ${eventIndex + 1}'s own arithmetic (${label})`, deepEqual(arith, expectArithmetic(ch.path, eventIndex)), arith.join(' / '));
        await checkCharts(label, ch);
      };
      // Each chart is read the way a reader reads it: a mark's position against the chart's own tick labels.
      const checkCharts = async (label, ch) => {
        const g = await page.evaluate(() => {
          const num = (t) => Number(t.textContent.replace('−', '-'));
          const ticks = (sel, attr) => Array.from(document.querySelectorAll(sel)).filter((t) => /^[−-]?\d+(\.\d+)?$/.test(t.textContent.trim()))
            .map((t) => ({ v: num(t), p: Number(t.getAttribute(attr)) }));
          const a = (sel, attr) => Array.from(document.querySelectorAll(sel), (n) => Number(n.getAttribute(attr)));
          return {
            strip: { ticks: ticks('#strip g.axis text', 'x'), dots: a('#strip .dots circle', 'cx'), mean: a('#strip .meanline', 'x1'), rule: a('#strip .rule', 'x1'), claim: a('#strip .claimline', 'x1') },
            lik: { ticks: ticks('#likelihood g.axis text[text-anchor="middle"]', 'x'), fit: a('#likelihood .fitline', 'x1'), printed: a('#likelihood .printedline', 'x1'),
              lo: a('#likelihood .interval', 'x1'), hi: a('#likelihood .interval', 'x2') },
            bunch: { ticks: ticks('#bunches text.axis', 'x'), dots: a('#bunches circle', 'cx'), mismatch: Array.from(document.querySelectorAll('#bunches circle'), (n) => n.classList.contains('mismatch')) },
            mu: { ticks: ticks('#muons text.axis[text-anchor="end"]', 'y'), A: a('#muons line.classline.class-A', 'y1'), B: a('#muons line.classline.class-B', 'y1'),
              pts: a('#muons g.period circle', 'cy'), omitted: Array.from(document.querySelectorAll('#muons g.period'), (n) => n.classList.contains('omitted')) },
          };
        });
        // value at a pixel, from the two outermost labelled ticks; every other tick must sit on the same line
        const axis = (ticks) => {
          const t = [...ticks].sort((p, q) => p.v - q.v), a0 = t[0], a1 = t.at(-1);
          const inv = (px) => a0.v + ((px - a0.p) * (a1.v - a0.v)) / (a1.p - a0.p);
          return { inv, ok: t.length >= 3 && t.every((k) => Math.abs(inv(k.p) - k.v) < 1e-6) };
        };
        const at = (ax, pxs, want, tol) => pxs.length === want.length && pxs.every((px, i) => Math.abs(ax.inv(px) - want[i]) <= tol);
        const R = indRoute[ch.path], act = ch.amplitude === 0 ? R.real : R.planted, actStats = ch.amplitude === 0 ? R.realStats : R.plantedStats;
        const sx = axis(g.strip.ticks);
        check(c, `browser chart: every strip dot, the mean line, the rule line and the claim line sit at their values on the strip's own axis (${label})`,
          sx.ok && at(sx, g.strip.dots, act.map((e) => e.delta), 0.01) && at(sx, g.strip.mean, [actStats.mean], 0.01)
          && at(sx, g.strip.rule, [ruleLine(actStats)], 0.01) && at(sx, g.strip.claim, [CLAIM], 0.01), JSON.stringify(g.strip).slice(0, 200));
        const fit = indFit(ch.extraction), lx = axis(g.lik.ticks);
        check(c, `browser chart: the fitted and printed lines and the one-sigma bar sit at their values on the likelihood axis (${label})`,
          lx.ok && at(lx, g.lik.fit, [fit.delta], 0.01) && at(lx, g.lik.printed, [CLAIM], 0.01) && at(lx, g.lik.lo, [fit.delta - fit.stat], 0.01) && at(lx, g.lik.hi, [fit.delta + fit.stat], 0.01));
        const bx = axis(g.bunch.ticks), L = IC.reference.light_tof_ns;
        check(c, `browser chart: every event sits at its elapsed time less the light flight time, and only a reassigned bunch is marked (${label})`,
          bx.ok && at(bx, g.bunch.dots, R.real.map((e) => e.elapsed - L), 0.01) && deepEqual(g.bunch.mismatch, R.real.map((e, i) => e.bunch !== ROWS[i].printed_bunch)));
        const my = axis(g.mu.ticks), mu = ch.omitted === 'none' ? indMu : indDeletions.find((d) => d.period === ch.omitted);
        check(c, `browser chart: both recombined class lines and all eight period means sit at their values, and only the omitted period is dimmed (${label})`,
          my.ok && at(my, g.mu.A, [mu.A.mean], 0.01) && at(my, g.mu.B, [mu.B.mean], 0.01) && at(my, g.mu.pts, MU.rows.map((x) => x.mean_ns), 0.01)
          && deepEqual(g.mu.omitted, MU.rows.map((x) => x.period === ch.omitted)));
      };
      await compare('default', {});
      check(c, 'browser: the hero shows the independently computed reconstruction', (await page.textContent('[data-out="heroFit"]')) === `${fx(indepDelta, 1)} ± ${fx(indepStat, 1)} ns`);
      await page.focus('#plant'); await page.keyboard.press('Enter');
      check(c, 'browser: the plant button works from the keyboard, the mean moves to the planted value, and the label stays the same while aria-pressed carries the state',
        (await page.textContent('[data-out="stripActive"]')) === `${sg(indPlantedStats.mean, 2)} ns` && (await page.getAttribute('#plant', 'aria-pressed')) === 'true'
        && (await page.textContent('#plant')) === 'Send the claimed early arrival through ICARUS');
      await compare('claim planted', { amplitude: CLAIM });
      await page.check('input[name="path"][value="delay-columns"]');
      check(c, 'browser: the route choice reaches the page', (await page.textContent('[data-out="ctlMean"]')) === `${sg(indDcStats.mean, 2)} ns`);
      await compare('delay columns, planted', { amplitude: CLAIM, path: 'delay-columns' });
      await page.selectOption('#extraction', 'second');
      await page.selectOption('#omit', '2008-2');
      await compare('second extraction, 2008-2 omitted', { amplitude: CLAIM, path: 'delay-columns', extraction: 'second', omitted: '2008-2' });
      check(c, 'browser: omitting 2008-2 shows the most negative contrast', (await page.textContent('[data-out="muContrast"]')) === `${sg(indMin, 2)} ns`);
      await page.check('input[name="path"][value="printed-flight-times"]');
      await page.selectOption('#fault', '3');
      await page.selectOption('#event-pick', '3');
      await compare('flight-time row, slip in event 3, event 4 shown', { amplitude: CLAIM, path: 'printed-flight-times', extraction: 'second', omitted: '2008-2', fault: '3' }, 3);
      // DEPTH audit finding 6: one change touches only its own live region, and a resize touches none
      await page.evaluate(() => {
        const regions = Array.from(document.querySelectorAll('[role="status"][aria-live]'));
        window.__hits = new Set();
        window.__obs = new MutationObserver((ms) => { for (const m of ms) { const reg = regions.find((x) => x.contains(m.target)); if (reg) window.__hits.add(reg.id || reg.dataset.out || reg.className); } });
        regions.forEach((x) => window.__obs.observe(x, { childList: true, characterData: true, subtree: true }));
        const sel = document.getElementById('omit'); sel.value = '2011'; sel.dispatchEvent(new Event('change'));
      });
      await page.waitForTimeout(100);
      const afterChange = await page.evaluate(() => { const h = [...window.__hits]; window.__hits.clear(); return h; });
      await page.setViewportSize({ width: 1100, height: 900 });   // a real resize, so the page's resize handler redraws
      await page.waitForTimeout(600);
      const afterResize = await page.evaluate(() => { const h = [...window.__hits]; window.__obs.disconnect(); return h; });
      await page.setViewportSize({ width: 1280, height: 900 });
      await page.waitForTimeout(600);
      const flood = { afterChange, afterResize };
      check(c, 'browser: leaving out a muon period rewrites only the muon readout, and a resize rewrites no live region', deepEqual(flood.afterChange, ['mu-readout']) && flood.afterResize.length === 0,
        JSON.stringify(flood));
      await page.click('#spread');
      check(c, 'browser: the spread button hands the unmodified control a 7-times scattered record and shows INCONCLUSIVE', (await page.textContent('#spread-out')) === EXPECTED_SPREAD,
        await page.textContent('#spread-out'));
      for (const [id, key] of [['refuse-bunch', 'injection'], ['refuse-blank', 'times'], ['refuse-curve', 'curve']]) {
        await page.click(`#${id}`);
        check(c, `browser: the ${id} button shows the engine's refusal`, (await page.textContent('#refusal-out')) === E.REFUSALS[key]);
      }
      const prov = await page.locator('#provenance-list li').allTextContents();
      notes.push(`browser provenance: ${prov.map((t) => t.split(':')[1]?.trim().split(',').pop().trim()).join(' | ')}`);
      check(c, 'browser: the five files are listed with their byte counts', prov.length === 5 && FILES.every((f) => prov.some((t) => t.startsWith(f) && t.includes(`${bytes[f].length} bytes`))));
      check(c, 'browser: the page hashed every file itself and each matches record.json', prov.length === 5 && prov.every((t) => t.includes('matches record.json'))
        && (await page.getAttribute('#provenance-alert', 'hidden')) !== null);
      await ctx.close();
      // NEGATIVE, in the real browser: serve one data file with one byte changed. The page must refuse.
      const tctx = await browser.newContext({ viewport: { width: 1280, height: 900 }, reducedMotion: 'reduce' });
      const tpage = await tctx.newPage(); tpage.setDefaultTimeout(15000);
      const flipped = Buffer.from(bytes[FILES[2]]); flipped[flipped.length - 3] ^= 1;
      await tpage.route(`**/strata/${SLUG}/data/${FILES[2]}`, (route) => route.fulfill({ status: 200, contentType: 'application/json', body: flipped }));
      await tpage.goto(`${origin}/strata/${SLUG}/`, { waitUntil: 'networkidle' });
      await tpage.waitForFunction(() => document.body.dataset.ready);
      const tprov = await tpage.locator('#provenance-list li').allTextContents();
      const touts = await tpage.locator('[data-out]').allTextContents();
      check('provenance_pinned', 'browser NEGATIVE: with one byte of the ICARUS table changed, the page shows the mismatch, raises the alert and computes nothing',
        (await tpage.getAttribute('body', 'data-ready')) === 'mismatch' && (await tpage.getAttribute('#provenance-alert', 'hidden')) === null
        && tprov.some((t) => t.startsWith(FILES[2]) && t.includes('DOES NOT MATCH record.json')) && touts.length > 50 && touts.every((t) => t === 'not computed'));
      await tctx.close();
    }
  } catch (e) {
    check(c, 'browser pass completed', false, e.message);
  } finally {
    clearTimeout(deadline);
    try { await browser?.close(); } catch { /* already closed */ }
    server.close();
  }
}

if (!NO_BROWSER) await browserPass();
else notes.push('BROWSER PASS SKIPPED by --no-browser; the static checks decided rendered_figures_asserted.');

// ------------------------------------------------------------------ outcome
const ledger = Object.fromEntries(KEYS.map((k) => {
  const rows = results.filter((x) => x.cell === k);
  return [k, rows.length > 0 && rows.every((x) => x.pass)];
}));
const failures = results.filter((x) => !x.pass);
const manifestAgrees = KEYS.every((k) => record.ledger[k] && record.ledger[k].value === ledger[k]);
if (LEDGER) {
  for (const k of KEYS) console.log(`${k}=${ledger[k]}`);
} else {
  const perCell = Object.fromEntries([...KEYS, 'hygiene'].map((k) => [k, `${results.filter((x) => x.cell === k && x.pass).length}/${results.filter((x) => x.cell === k).length}`]));
  console.log(JSON.stringify({ pass: failures.length === 0 && manifestAgrees, assertions: results.length, perCell, ledger, manifestAgrees, notes,
    failures: failures.map((x) => `[${x.cell}] ${x.name}${x.detail ? ': ' + x.detail : ''}`) }, null, 2));
}
process.exit(failures.length === 0 && manifestAgrees ? 0 : 1);
