#!/usr/bin/env node
// verify-enf-mains-hum.mjs
//
// The page measures the reader's own room, so nothing about it can be checked by looking at
// the reader. What CAN be checked is everything else, and this checks it in four ways that
// fail differently:
//
//   A. THE SPECIMENS REGENERATE. make-specimens.mjs is re-run into a scratch directory and
//      the hashes compared. A doctored anchor is caught here and only here.
//   B. THE ARITHMETIC IS REDONE IN NODE, by loading the page's own engine.js. Every number
//      the page computes at run time is recomputed here from the same file and the same
//      committed inputs.
//   C. THE PAGE IS OPENED IN A REAL BROWSER and its DOM is compared, character for
//      character, against B. A verifier that asserts about values and not about the rendered
//      page has checked something nobody reads.
//   D. THE SHIPPED SURFACES ARE READ: the frontmatter, the dek, the plain card, the meta
//      description and the JSON-LD, because the honesty leak lives in the shareable surface.
//
// And it asserts the REFUSALS, not only the successes. A measurement page is most likely to
// lie exactly where it should have said nothing.
//
//   node research/enf-mains-hum/verify-enf-mains-hum.mjs
//   node research/enf-mains-hum/verify-enf-mains-hum.mjs --no-browser   (skips part C)
import { readFileSync, existsSync, mkdtempSync, rmSync, mkdirSync, writeFileSync, statSync, readdirSync } from 'node:fs';
import { createHash } from 'node:crypto';
import { execFileSync } from 'node:child_process';
import { createServer } from 'node:http';
import { join, resolve, extname } from 'node:path';
import { tmpdir } from 'node:os';
import { fileURLToPath } from 'node:url';
import vm from 'node:vm';

const ROOT = resolve(fileURLToPath(new URL('../..', import.meta.url)));
const SPEC = join(ROOT, 'public/strata/enf-mains-hum/specimens');
const PAGE = join(ROOT, 'public/strata/enf-mains-hum');
const NO_BROWSER = process.argv.includes('--no-browser');

let pass = 0; const fails = [];
function ok(name, cond, detail) {
  if (cond) { pass++; console.log(`  ok   ${name}`); }
  else { fails.push(name + (detail ? '  ' + detail : '')); console.log(`  FAIL ${name}${detail ? '  ' + detail : ''}`); }
}
function near(name, got, want, tol, unit) {
  ok(`${name}: ${fmt(got)} vs ${fmt(want)} ${unit || ''}`.trim(), Math.abs(got - want) <= tol,
    Math.abs(got - want) <= tol ? '' : `differs by ${fmt(Math.abs(got - want))}, tolerance ${tol}`);
}
function fmt(v) { return typeof v === 'number' ? (Math.abs(v) < 1e-4 ? v.toExponential(3) : String(Math.round(v * 1e6) / 1e6)) : String(v); }
const sha = (p) => createHash('sha256').update(readFileSync(p)).digest('hex');

const html = readFileSync(join(PAGE, 'index.html'), 'utf8');
const pagejs = readFileSync(join(PAGE, 'page.js'), 'utf8');
const enginejs = readFileSync(join(PAGE, 'engine.js'), 'utf8');
const md = readFileSync(join(ROOT, 'src/content/strata/enf-mains-hum.md'), 'utf8');
const hashes = JSON.parse(readFileSync(join(ROOT, 'research/enf-mains-hum/hashes.json'), 'utf8'));
const calib = JSON.parse(readFileSync(join(ROOT, 'research/enf-mains-hum/calibration.json'), 'utf8'));
const daily = JSON.parse(readFileSync(join(SPEC, 'nordic-2023-daily.json'), 'utf8'));

// The page's own engine, loaded exactly as the browser loads it.
const sb = { window: {}, console };
const ctx = vm.createContext(sb);
vm.runInContext(readFileSync(join(ROOT, 'public/_kit/dsp.js'), 'utf8'), ctx);
vm.runInContext(enginejs, ctx);
const E = sb.window.AW.enf, DSP = sb.window.AW.dsp, P = E.P;
const readWav = (p) => { const b = readFileSync(p); return E.parseWav(b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength)); };

// ── A. the specimens regenerate ────────────────────────────────────────────────
console.log('\nA. THE SPECIMENS REGENERATE FROM A CLOSED FORM');
{
  const tmp = mkdtempSync(join(tmpdir(), 'enf-verify-'));
  const s = join(tmp, 'spec'), g = join(tmp, 'gate');
  mkdirSync(s); mkdirSync(g);
  try {
    execFileSync(process.execPath, [join(ROOT, 'research/enf-mains-hum/make-specimens.mjs')], {
      cwd: ROOT, stdio: 'pipe', env: Object.assign({}, process.env, { AW_SPEC_OUT: s, AW_GATE_OUT: g }),
    });
    for (const [rel, want] of Object.entries(hashes.regenerated)) {
      const base = rel.split('/').pop();
      const built = rel.includes('/gate/') ? join(g, base) : join(s, base);
      const shipped = join(ROOT, rel);
      ok(`${base} regenerates byte-for-byte`, existsSync(built) && sha(built) === want && sha(shipped) === want,
        existsSync(built) ? `rebuilt ${sha(built).slice(0, 12)}, shipped ${sha(shipped).slice(0, 12)}, expected ${want.slice(0, 12)}` : 'not rebuilt');
    }
  } finally { rmSync(tmp, { recursive: true, force: true }); }
  for (const [rel, want] of Object.entries(hashes.pinned)) {
    ok(`${rel.split('/').pop()} matches its pinned hash`, existsSync(join(ROOT, rel)) && sha(join(ROOT, rel)) === want);
  }
  let bytes = 0;
  for (const f of readdirSync(SPEC)) bytes += statSync(join(SPEC, f)).size;
  ok(`shipped specimens are ${(bytes / 1024 / 1024).toFixed(2)} MB, under the 3 MB budget`, bytes < 3 * 1024 * 1024);
  ok('a LICENCE ships beside the specimens', existsSync(join(SPEC, 'LICENCE')));
  const lic = readFileSync(join(SPEC, 'LICENCE'), 'utf8');
  ok('the LICENCE carries the ENF-WHU copyright notice verbatim', lic.includes('Copyright (c) 2023 HUA GUANG') &&
    lic.includes('THE SOFTWARE IS PROVIDED "AS IS"'));
  ok('the LICENCE records the Zenodo carve-out that keeps Continental Europe out of this repository',
    lic.includes('**/Fingrid` are licensed under') && lic.includes('cannot publish our pre-processed version under an open'));
  ok('no Continental Europe / TransnetBW data is shipped', !readdirSync(SPEC).some((f) => /transnet|continental|ce-/i.test(f)));
}

// ── B. the arithmetic, redone here ─────────────────────────────────────────────
console.log('\nB. EVERY COMPUTED NUMBER, REDONE IN NODE FROM THE SAME ENGINE');

// the page's frozen truths, read out of page.js so they cannot drift from what ships
function constOf(re, what) {
  const m = pagejs.match(re);
  if (!m) { fails.push('could not read ' + what + ' out of page.js'); return NaN; }
  return Number(m[1]);
}
const T_ANCHOR = constOf(/anchor:\s*([\d.]+),/, 'the anchor truth');
const T_REAL = constOf(/real:\s*([\d.]+),/, 'the real-whu truth');
const T_S60 = constOf(/synth60:\s*([\d.]+),/, 'the synth-60 truth');
const TOL = constOf(/const TOL = ([\d.]+);/, 'the slate tolerance');
const TOL_REAL = constOf(/const TOL_REAL = ([\d.]+);/, 'the real recording’s own tolerance');
// Per specimen, because they are not all justified by the same evidence: the real recording's
// tolerance is the worst disagreement the whole-dataset sweep found, and the others are the
// window-schedule argument plus the demonstrated floor.
const tolOf = (id) => (id === 'real-whu' ? TOL_REAL : TOL);
const MIS_PPM = constOf(/const MISCLOCK_PPM = (\d+);/, 'the mis-clock ppm');
const START = constOf(/startSecond: (\d+),/, 'the anchor start second');
const SECS = constOf(/seconds: (\d+) \}/, 'the anchor length');
const MIS_FACTOR = 1 / (1 + MIS_PPM / 1e6);
const T_MIS = T_ANCHOR * MIS_FACTOR;

// the day, decoded the way the page decodes it
const dayBuf = readFileSync(join(SPEC, 'nordic-day.bin'));
const dayI16 = new Int16Array(dayBuf.buffer, dayBuf.byteOffset, dayBuf.length / 2);
const day = new Float64Array(dayI16.length);
for (let i = 0; i < day.length; i++) day[i] = 50 + dayI16[i] / 1000;
ok('the shipped log day is 86400 one-second samples', day.length === 86400);

// (1) the anchor's frozen truth IS the trapezoid of the log over the file
{
  let s = 0;
  for (let k = 0; k < SECS; k++) s += 0.5 * (day[START + k] + day[START + k + 1]);
  near('the anchor truth is the log’s own exact time-mean', s / SECS, T_ANCHOR, 5e-7, 'Hz');
}

// (2) the same untouched estimator on every shipped specimen
const R = {};
R.anchor = E.estimate(readWav(join(SPEC, 'anchor-nordic.wav')));
R.s60 = E.estimate(readWav(join(SPEC, 'synth-60.wav')));
R.real = E.estimate(readWav(join(SPEC, 'real-whu.wav')));
R.nul = E.estimate(readWav(join(SPEC, 'null-whu.wav')));
{
  const w = readWav(join(SPEC, 'anchor-nordic.wav'));
  R.mis = E.estimate({ samples: E.resampleByFactor(w.samples, MIS_FACTOR), sampleRate: w.sampleRate });
}
for (const [id, r, truth] of [['anchor-nordic', R.anchor, T_ANCHOR], ['synth-60', R.s60, T_S60],
                              ['real-whu', R.real, T_REAL], ['misclock-nordic', R.mis, T_MIS]]) {
  ok(`${id} is inside its declared tolerance`, !r.refused && Math.abs(r.value - truth) <= tolOf(id),
    r.refused ? 'refused: ' + r.refused.reason : `off by ${((r.value - truth) * 1000).toFixed(3)} mHz, tol ${(tolOf(id) * 1000).toFixed(0)} mHz`);
  ok(`${id} claims an interval no wider than that tolerance`, !r.refused && r.uncertainty <= tolOf(id));
}
// The one specimen with a wider tolerance has it because the sweep measured it, and the page
// has to say the same number the record does.
ok(`real-whu's tolerance ${(TOL_REAL * 1000).toFixed(0)} mHz is the sweep's worst disagreement ${calib.realSet.maxAbsMilliHz} mHz rounded up`,
  TOL_REAL * 1000 >= calib.realSet.maxAbsMilliHz && TOL_REAL * 1000 < calib.realSet.maxAbsMilliHz + 1 &&
  pagejs.includes(`which was ${calib.realSet.maxAbsMilliHz} mHz, rounded up`));
ok('and the 60 Hz control keeps the tighter tolerance that makes it catch a nominal-returning estimator',
  Math.abs(T_S60 - 60) * 1000 > TOL * 1000 && Math.abs(T_S60 - 60) * 1000 < 13);

// (3) the slate can actually discriminate: no anchor/control pair is closer than the slack
for (const [a, av] of [['anchor-nordic', T_ANCHOR], ['real-whu', T_REAL]]) {
  for (const [c, cv] of [['synth-60', T_S60], ['misclock-nordic', T_MIS]]) {
    ok(`${a} and ${c} are separable (${(Math.abs(av - cv) * 1000).toFixed(1)} mHz apart, ${((tolOf(a) + tolOf(c)) * 1000).toFixed(0)} mHz of slack)`,
      Math.abs(av - cv) > tolOf(a) + tolOf(c));
  }
}

// (4) a constant estimator must fail the slate. This is the stub probe, redone here, because
//     the page showing it is not the same as it being true.
{
  const stub = () => ({ value: T_ANCHOR, uncertainty: TOL / 10 });
  const rows = [['anchor-nordic', T_ANCHOR], ['real-whu', T_REAL], ['synth-60', T_S60], ['misclock-nordic', T_MIS]]
    .map(([id, truth]) => ({ id, pass: Math.abs(stub().value - truth) <= tolOf(id) }));
  ok('a hard-coded estimator passes the first anchor', rows[0].pass);
  ok('and fails every other specimen, including both controls', rows.slice(1).every((r) => !r.pass));
}

// (5) the per-window comparison the page draws: the estimator against the estimand the log
//     defines, computed here with the page's own Hann-squared weighting recipe.
function trueWindowMeans(times) {
  const N = 400, T = P.windowSeconds;
  return times.map((t) => {
    let s = 0, ws = 0;
    for (let i = 0; i < N; i++) {
      const frac = i / (N - 1);
      const taper = 0.5 - 0.5 * Math.cos(2 * Math.PI * frac);
      const wt = taper * taper;
      const u = START + t - T / 2 + frac * T;
      const k = Math.floor(u);
      s += wt * (day[k] + (day[k + 1] - day[k]) * (u - k)); ws += wt;
    }
    return s / ws;
  });
}
const anchorTimes = R.anchor.diagnostics.trace.map((p) => p.t);
const TW = trueWindowMeans(anchorTimes);
const ANCHOR_SCATTER = Math.sqrt(TW.reduce((a, v, i) => a + (R.anchor.diagnostics.trace[i].hz - v) ** 2, 0) / TW.length);
const ANCHOR_MAXERR = Math.max(...TW.map((v, i) => Math.abs(R.anchor.diagnostics.trace[i].hz - v)));
const TW_MEAN = TW.reduce((a, b) => a + b, 0) / TW.length;
ok(`the anchor is recovered to ${(ANCHOR_SCATTER * 1000).toFixed(3)} mHz RMS per window against the log`, ANCHOR_SCATTER < 0.0015);
ok(`and never misses a window by more than ${(ANCHOR_MAXERR * 1000).toFixed(3)} mHz`, ANCHOR_MAXERR < 0.004);

// (5b) "it moved" has to be capable of coming out no. The 60 Hz control is held at a constant
//      frequency by construction, so a drift test that cannot return "noise" on it is not a
//      test. The anchor, which carries a real grid's real wander, must come out the other way.
ok(`the anchor's trace is real movement (reduced chi-square ${R.anchor.diagnostics.traceChiSq.toFixed(0)})`,
  R.anchor.diagnostics.traceChiSq > 100);
ok(`the real recording's trace is real movement (${R.real.diagnostics.traceChiSq.toFixed(1)})`,
  R.real.diagnostics.traceChiSq > 3);
ok(`the CONSTANT specimen's trace is NOT movement (${R.s60.diagnostics.traceChiSq.toFixed(2)}), ` +
  `even though its range is ${R.s60.diagnostics.driftMilliHz.toFixed(1)} mHz`,
  R.s60.diagnostics.traceChiSq < 3 && R.s60.diagnostics.driftMilliHz > 0);
ok('the page reports the drift test rather than a bare range',
  /reduced chi-square of/.test(pagejs) && /does not show your grid moving/.test(pagejs));

// (6) the second layer. The absolute reading moves by what arithmetic says; the shape does not.
function shapeCompare(a, b) {
  const n = Math.min(a.length, b.length);
  const ma = a.slice(0, n).reduce((x, p) => x + p.hz, 0) / n, mb = b.slice(0, n).reduce((x, p) => x + p.hz, 0) / n;
  let num = 0, da = 0, db = 0, maxd = 0;
  for (let i = 0; i < n; i++) {
    const u = a[i].hz - ma, v = b[i].hz - mb;
    num += u * v; da += u * u; db += v * v; maxd = Math.max(maxd, Math.abs(u - v));
  }
  return { corr: num / Math.sqrt(da * db), maxd, n };
}
const MIS = {};
{
  const w = readWav(join(SPEC, 'anchor-nordic.wav'));
  for (const ppm of [80, MIS_PPM]) {
    const f = 1 / (1 + ppm / 1e6);
    const r = E.estimate({ samples: E.resampleByFactor(w.samples, f), sampleRate: w.sampleRate });
    const sc = shapeCompare(R.anchor.diagnostics.trace, r.diagnostics.trace);
    const back = E.estimate({ samples: E.resampleByFactor(E.resampleByFactor(w.samples, f), 1 / f), sampleRate: w.sampleRate });
    MIS[ppm] = { value: r.value, shift: r.value - R.anchor.value, predicted: R.anchor.value * f - R.anchor.value,
      corr: sc.corr, maxd: sc.maxd, roundTrip: Math.abs(back.value - R.anchor.value), res: r };
    const m = MIS[ppm];
    ok(`at ${ppm} ppm the reading moves ${(m.shift * 1000).toFixed(3)} mHz where arithmetic predicts ${(m.predicted * 1000).toFixed(3)}`,
      Math.abs(m.shift - m.predicted) < 0.0015);
    // A correlation is the wrong instrument for this claim and is kept only as a readout. Two
    // runs of a deterministic estimator over traces whose fractional variation is ~1e-3 will
    // correlate above 0.999 even if the estimator is badly wrong, so a threshold on it cannot
    // go red. The falsifiable form is a bound on the RESIDUAL, two-sided, in the units the page
    // prints: the shape must move by no more than the estimator's own run-to-run scatter allows,
    // and it must move by SOMETHING, or the resample did nothing and the control is a no-op.
    ok(`at ${ppm} ppm the shape correlation is ${m.corr.toFixed(6)}`, m.corr > 0.9999);
    const scatter = ANCHOR_SCATTER * Math.SQRT2;
    ok(`at ${ppm} ppm the shape residual is ${(m.maxd * 1e6).toFixed(1)} uHz, inside the ` +
      `${(2 * scatter * 1e6).toFixed(1)} uHz two runs of this estimator differ by anyway, and not zero`,
      m.maxd > 0 && m.maxd <= 2 * scatter);
    ok(`at ${ppm} ppm the shape moves ${(m.maxd * 1000).toFixed(3)} mHz against an absolute shift of ${(Math.abs(m.shift) * 1000).toFixed(2)} mHz`,
      Math.abs(m.shift) > 10 * m.maxd);
  }
  // The claim the page makes about 100 ppm, checked as arithmetic.
  near('100 ppm on a 50 Hz grid is 5.0 mHz', 50 * 100e-6 * 1000, 5.0, 1e-9, 'mHz');
}

// (7) dating. The right answer is found, the mis-clocked copy finds the same one, and a real
//     recording of a different grid does not find anything.
const DATE = {};
for (const [k, r] of [['anchor', R.anchor], ['mis', MIS[MIS_PPM].res], ['real', R.real]]) {
  const tr = r.diagnostics.trace;
  DATE[k] = E.matchTrace(tr.map((p) => p.hz), tr.map((p) => p.t), day, 0, 1);
}
const TRUE_SECOND = START + P.windowSeconds / 2;
ok(`the anchor dates itself to second ${DATE.anchor.bestOffsetSeconds}, which is the true ${TRUE_SECOND}`,
  DATE.anchor.bestOffsetSeconds === TRUE_SECOND);
ok(`the mis-clocked copy dates itself to the same second`, DATE.mis.bestOffsetSeconds === TRUE_SECOND);
ok(`the match is r = ${DATE.anchor.best.toFixed(5)} against a best wrong answer of ${DATE.anchor.runnerUp.toFixed(5)}`,
  DATE.anchor.best > 0.99 && DATE.anchor.best - DATE.anchor.runnerUp > 0.05);
ok(`the mis-clocked match is just as strong (r = ${DATE.mis.best.toFixed(5)})`,
  Math.abs(DATE.mis.best - DATE.anchor.best) < 0.001);
ok(`the Wuhan recording finds NO match in this day (best r = ${DATE.real.best.toFixed(5)}, ` +
  `its own best wrong answer ${DATE.real.runnerUp.toFixed(5)}, margin ${(DATE.real.best - DATE.real.runnerUp).toFixed(5)})`,
  DATE.real.best - DATE.real.runnerUp < 0.02 && DATE.real.best < 0.99);
ok('and it does not land on the anchor’s second either', DATE.real.bestOffsetSeconds !== TRUE_SECOND);
// The height of the control's peak is NOT what makes it a non-match, and the page says so.
// Two things have to be true for that sentence to be honest: the control's peak really is
// high in absolute terms (so a height threshold would be a live trap), and the margin really
// does separate the two cases by a wide factor.
const MARGIN = { anchor: DATE.anchor.best - DATE.anchor.runnerUp, real: DATE.real.best - DATE.real.runnerUp };
ok(`the control's peak is high in absolute terms (${DATE.real.best.toFixed(5)}), which is why height alone cannot settle it`,
  DATE.real.best > 0.8);
ok(`the margin separates them by ${(MARGIN.anchor / MARGIN.real).toFixed(0)}x (${MARGIN.anchor.toFixed(5)} against ${MARGIN.real.toFixed(5)})`,
  MARGIN.anchor / MARGIN.real > 10);
ok(`the median candidate in the control's own search is ${DATE.real.nullMedian.toFixed(4)}, far below its peak`,
  Math.abs(DATE.real.nullMedian) < 0.05);
// matchTrace sorts EVERY score, the winning one included, so the maximum is always above the
// 99.9th percentile by construction. The caption must not describe that line as a threshold
// the peak had to clear, because clearing it is arithmetically guaranteed.
{
  const cap = html.replace(/\s+/g, ' ');
  ok('the caption calls that line what it is: the percentile of every candidate, the true one included',
    /99\.9th percentile of the scores at every candidate second, the true one included/.test(cap));
  ok('and it says plainly that standing above it settles nothing',
    /standing above it settles nothing/.test(cap));
}

// The two-source signal, built once here and reused by the mutation suite, so the page's
// demonstration and the verifier's cannot be different signals. The interferer's amplitude is
// the anchor's own 2f line, measured by AW.enf.lineAmplitude, which is the claim the page
// prints beside it.
const A2_ANCHOR = E.lineAmplitude(readWav(join(SPEC, 'anchor-nordic.wav')).samples, 1000, 2 * T_ANCHOR);
const A4_ANCHOR = E.lineAmplitude(readWav(join(SPEC, 'anchor-nordic.wav')).samples, 1000, 4 * T_ANCHOR);
function twoSourceSignal(w) {
  const x = new Float64Array(w.samples.length);
  const f4 = 4 * (T_ANCHOR + 0.050);
  for (let i = 0; i < x.length; i++) x[i] = w.samples[i] + A2_ANCHOR * Math.sin(2 * Math.PI * f4 * i / w.sampleRate + 0.3);
  return { samples: x, sampleRate: w.sampleRate };
}

// ── the refusals, which are where a measurement page lies ──────────────────────
console.log('\nB2. THE REFUSAL PATHS');
ok(`the shipped null recording refuses (${R.nul.refused && R.nul.refused.reason})`,
  !!R.nul.refused && R.nul.refused.reason === 'no-mains-line');
ok('and emits no value at all', R.nul.value === undefined);
{
  const d = R.nul.diagnostics;
  for (const line of [100, 120, 200, 240]) {
    ok(`the null recording's ${line} Hz band is ${d.bestSnrDbPerLine[line].toFixed(1)} dB, under the ${P.snrFloorDb} dB floor`,
      d.bestSnrDbPerLine[line] < P.snrFloorDb);
  }
}
{
  const w = readWav(join(SPEC, 'anchor-nordic.wav'));
  const short = E.estimate({ samples: w.samples.subarray(0, 5 * w.sampleRate), sampleRate: w.sampleRate });
  ok('a capture shorter than one window refuses rather than shrinking the window',
    !!short.refused && short.refused.reason === 'too-short');
  const slow = E.estimate({ samples: w.samples, sampleRate: 300 });
  ok('a sample rate that cannot carry a 240 Hz line refuses', !!slow.refused && slow.refused.reason === 'rate-too-low');
  ok('an empty payload refuses', !!E.estimate({ samples: new Float64Array(0), sampleRate: 1000 }).refused);
  ok('a payload with no sample rate refuses', !!E.estimate({ samples: w.samples }).refused);
  // Two sources: a second tone at 4f of a grid 50 mHz away, exactly as loud as the anchor's
  // OWN 2f line, which is measured rather than asserted. The page demonstrates this live and
  // prints both amplitudes; this is the same signal, built the same way.
  const two = E.estimate(twoSourceSignal(w));
  ok('a second source at 4f makes the harmonics disagree and the estimator refuses',
    !!two.refused && two.refused.reason === 'harmonics-disagree');
  // and the rule is not so tight that it fires on the clean anchor
  ok(`without the second source the same file answers (worst chi-square ${R.anchor.diagnostics.chiWorst.toFixed(1)} of ${P.chiSqMax})`,
    !R.anchor.refused && R.anchor.diagnostics.chiWorst < P.chiSqMax);
}
// Nominal is chosen from the data. A 60 Hz specimen must not be read as 50, and vice versa.
ok('the 60 Hz specimen is read as a 60 Hz grid', R.s60.diagnostics.nominal === 60);
ok('the 50 Hz specimens are read as 50 Hz grids',
  R.anchor.diagnostics.nominal === 50 && R.real.diagnostics.nominal === 50 && R.mis.diagnostics.nominal === 50);
ok('the estimator source contains no branch that could tell it what it is looking at',
  !/isSpecimen|isControl|isLive|expected|payload\.truth|payload\.answer/.test(enginejs));

// THE RULE THE PAGE PRINTS IS THE RULE THE CODE RUNS. Two legs, and they are different
// rules: each harmonic must clear the floor in at least minWindows windows ANYWHERE, and
// then EITHER harmonic must carry at least minWindowFraction of the windows. A panel that
// printed "both harmonics in half the windows" would be describing a stricter estimator
// than the one that ships, so both legs are pinned to a signal that separates them.
{
  const lcg = (seed) => { let s = seed >>> 0; return () => { s = (1664525 * s + 1013904223) >>> 0; return s / 4294967296 - 0.5; }; };
  const partial = (burstSeconds) => {
    const fs = 1000, n = fs * 60, x = new Float64Array(n), r = lcg(4242);
    for (let i = 0; i < n; i++) {
      const t = i / fs;
      x[i] = 0.5 * Math.sin(2 * Math.PI * 100 * t) + 0.02 * (r() + r() + r());
      if (t < burstSeconds) x[i] += 0.5 * Math.sin(2 * Math.PI * 200 * t + 0.4);
    }
    return { samples: x, sampleRate: fs };
  };
  const minority = E.estimate(partial(14));
  ok(`4f in a MINORITY of windows (${minority.diagnostics ? minority.diagnostics.perHarmonic[50][4] : '?'} of ` +
     `${minority.diagnostics ? minority.diagnostics.windows : '?'}) still answers, as the code says and the panel now says too`,
    !minority.refused && Math.abs(minority.value - 50) < 0.002,
    minority.refused ? 'refused: ' + minority.refused.reason : '');
  const tooFew = E.estimate(partial(6));
  ok(`4f in fewer than the ${P.minWindows} windows the rule needs refuses`,
    !!tooFew.refused && tooFew.refused.reason === 'no-mains-line' && tooFew.diagnostics.perHarmonic[50][4] < P.minWindows,
    tooFew.refused ? '' : 'it answered ' + (tooFew.value || 0).toFixed(5));
  ok('the panel states the both-harmonics rule without claiming the same windows',
    /2f AND 4f each clear the floor in at least \$\{P\.minWindows\} windows, not necessarily the same ones/.test(pagejs));
  ok('and states the coverage rule as EITHER harmonic, which is what the code counts',
    /at least one of the two clears it in \$\{\(100 \* P\.minWindowFraction\)\.toFixed\(0\)\}% of the windows/.test(pagejs));
}

// THE LIVE PAYLOAD IS THE SAME SHAPE A SPECIMEN PRESENTS. Two ways, because the regex above
// only catches a branch that names itself: the page must hand tryMeasure samples and a rate
// and nothing else, and the estimator must return an identical answer when a payload carries
// the reader-only fields anyway.
ok('measureLive hands the estimator only samples and a sample rate',
  /inst\.tryMeasure\(\{ samples: signal\.samples, sampleRate: signal\.sampleRate \}\)/.test(pagejs));
{
  const w = readWav(join(SPEC, 'real-whu.wav'));
  const plain = E.estimate({ samples: w.samples, sampleRate: w.sampleRate });
  const decorated = E.estimate({ samples: w.samples, sampleRate: w.sampleRate, seconds: w.seconds,
    clockPairs: [{ contextTime: 0, performanceTime: 0 }], processing: { echoCancellation: false },
    settings: { deviceId: 'x' }, truth: 42, expected: 42, isSpecimen: true });
  ok('and the estimator returns the identical value when a payload carries reader-only fields',
    plain.value === decorated.value && plain.uncertainty === decorated.uncertainty);
}

// ── the two constants the page prints as physics rather than as choices ────────
console.log('\nB2b. THE CRAMER-RAO CONSTANT AND THE ANTI-ALIAS FILTER, MEASURED');
{
  // The page says its interval starts from the Cramer-Rao bound for a single tone. That is a
  // checkable statement, so it is checked here against the exact Fisher information of the
  // three parameter model (amplitude, frequency, phase) rather than against a remembered
  // formula. A comment that disagrees with the constant beside it is exactly how the wrong
  // constant survived the last build.
  const fs = 1000, T = P.windowSeconds, N = Math.round(T * fs);
  const exactCrb = (A, f, phi, sigma) => {
    const dA = new Float64Array(N), df = new Float64Array(N), dp = new Float64Array(N);
    for (let n = 0; n < N; n++) {
      const t = n / fs, arg = 2 * Math.PI * f * t + phi;
      dA[n] = Math.sin(arg); df[n] = A * Math.cos(arg) * 2 * Math.PI * t; dp[n] = A * Math.cos(arg);
    }
    const v = [dA, df, dp], I = [[0, 0, 0], [0, 0, 0], [0, 0, 0]];
    for (let i = 0; i < 3; i++) for (let j = 0; j < 3; j++) {
      let s = 0; for (let n = 0; n < N; n++) s += v[i][n] * v[j][n];
      I[i][j] = s / (sigma * sigma);
    }
    const det = I[0][0] * (I[1][1] * I[2][2] - I[1][2] * I[2][1]) - I[0][1] * (I[1][0] * I[2][2] - I[1][2] * I[2][0]) +
                I[0][2] * (I[1][0] * I[2][1] - I[1][1] * I[2][0]);
    return Math.sqrt((I[0][0] * I[2][2] - I[0][2] * I[2][0]) / det);
  };
  for (const db of [40, 25]) {
    const snr = Math.pow(10, db / 10);
    // the in-band SNR this page measures, written back as the sigma that produces it:
    // SNR = A^2*N/(6*sigma^2*ln2)
    const sigma = Math.sqrt(N / (6 * Math.LN2 * snr));
    const exact = exactCrb(1, 100.123, 0.7, sigma);
    near(`sigmaLine at ${db} dB in-band is the exact single-tone Cramer-Rao bound`,
      E.sigmaLine(snr, T) * 1000, exact * 1000, 0.01 * exact * 1000, 'mHz');
  }
  ok(`the shipped constant is ${E.CRLB_CONST.toFixed(6)}, which is sqrt(12/(3 ln2))/(2 pi)`,
    Math.abs(E.CRLB_CONST - Math.sqrt(12 / (3 * Math.LN2)) / (2 * Math.PI)) < 1e-12);
  ok('the engine comment states that same constant',
    enginejs.includes(`= ${E.CRLB_CONST.toFixed(6)}/(T*sqrt(SNR_inband)) Hz`) &&
    enginejs.includes(`// ${E.CRLB_CONST.toFixed(6)}...`),
    'the constant in the comment must be the constant in the code');
  ok('and the derivation the comment points at exists in the README',
    /Where the Cramer-Rao constant comes from/.test(readFileSync(join(ROOT, 'research/enf-mains-hum/README.md'), 'utf8')));

  // The anti-alias filter, measured by pushing tones through the shipped decimator. The
  // panel names three frequencies; each is checked rather than described.
  const tone = (hz, fsIn, secs) => {
    const x = new Float64Array(Math.round(fsIn * secs));
    for (let i = 0; i < x.length; i++) x[i] = Math.sin(2 * Math.PI * hz * i / fsIn);
    return x;
  };
  const respAt = (hz) => {
    const dec = E.decimate(tone(hz, 48000, 3), 48000, P.targetRate, P.cutoffHz);
    // the tone lands at hz or, above the output Nyquist, at its alias; measure where it lands
    const out = dec.sampleRate, folded = Math.abs(hz - out * Math.round(hz / out));
    const a = E.lineAmplitude(dec.samples.subarray(out, dec.samples.length - out), out, folded);
    return a;
  };
  const r300 = respAt(300), r400 = respAt(400), r500 = respAt(500);
  ok(`the anti-alias passband edge really is 300 Hz (measured ${(20 * Math.log10(r300)).toFixed(2)} dB)`,
    r300 > 0.98 && r300 < 1.02);
  ok(`${P.cutoffHz} Hz really is the half-amplitude point (measured ${r400.toFixed(3)}, ${(20 * Math.log10(r400)).toFixed(2)} dB)`,
    Math.abs(r400 - 0.5) < 0.03);
  ok(`the stopband edge really is 500 Hz (measured ${r500.toExponential(2)})`, r500 < 0.02);
  // and the thing the filter is actually for: a tone above the output Nyquist must not turn
  // up inside the analysis band pretending to be something else.
  const alias = respAt(600);
  ok(`a 600 Hz tone does not alias into the 400 Hz slot (amplitude ${alias.toExponential(2)})`, alias < 1e-3);
  ok('and the page labels that number as the half-amplitude point, not as the passband edge',
    /half amplitude at \$\{P\.cutoffHz\} Hz, passband edge 300 Hz, stopband edge 500 Hz/.test(pagejs));
}

// ── the regulation arithmetic ──────────────────────────────────────────────────
console.log('\nB3. THE REGULATION PANEL');
const REG = (() => {
  const YEAR = 365 * 86400;
  let present = 0, outside = 0, full = 0, any = 0, lo = 99, hi = -99;
  for (const r of daily.rows) {
    present += r.present; outside += r.outside;
    if (r.present === r.seconds) full++;
    if (r.present > 0) { any++; lo = Math.min(lo, r.min); hi = Math.max(hi, r.max); }
  }
  const coverage = present / YEAR;
  const S = (k) => daily.rows.reduce((a, r) => a + (r[k] || 0), 0);
  return { YEAR, present, outside, full, any, lo, hi, coverage, minutes: outside / 60,
    allowance: 15000, proRata: 15000 * coverage, S,
    minAny: S('minAny'), minMean: S('minMean'), minAll: S('minAll'), complete: S('minutesComplete'),
    boundary: S('boundary'), rounded: S('outsideRounded'), below: S('below'), above: S('above'),
    outside50: S('outside50') };
})();
ok('the daily table has one row per day of 2023', daily.rows.length === 365);
// The deposit's timestamps are naive local time WITH daylight saving, so binning by row index
// would put every day after March one hour out of step with its own label. The rows are binned
// by timestamp instead, and the two days that are not 86400 seconds long are the proof that
// they were: if this ever comes back "365 days of 86400 seconds", the binning has regressed.
{
  const odd = daily.rows.filter((r) => r.seconds !== 86400).map((r) => `${r.day} ${r.seconds}s`);
  ok(`exactly two local days are not 86400 seconds long (${odd.join(', ')})`,
    odd.length === 2 && odd[0] === '2023-03-26 82800s' && odd[1] === '2023-10-29 90000s');
  ok('and the local days still sum to the year',
    daily.rows.reduce((a, r) => a + r.seconds, 0) === 365 * 86400);
  ok('the note says how the rows are binned, since a "day" here is a local day',
    /binned by each row's own timestamp rather than by row index/.test(daily.note));
  ok('the page counts a day complete against its own length, not against 86400',
    /r\.present === r\.seconds/.test(pagejs));
}
ok(`the band summed against is the Nordic ±100 mHz of Annex III Table 1`, daily.band === 0.100 &&
  /Annex III Table 1/.test(daily.bandSource));
ok(`coverage is ${(100 * REG.coverage).toFixed(2)}% of the year (${REG.present.toLocaleString('en')} seconds)`,
  REG.present > 0 && REG.coverage < 1);
ok(`${REG.minutes.toFixed(1)} minutes outside the band, against a pro rata allowance of ${REG.proRata.toFixed(0)}`,
  REG.minutes > 0);
ok('the page does not present this as the regulation’s own annual test',
  /not the regulation’s own test/.test(pagejs) && /pro rata/.test(pagejs));
ok('the day shipped as a specimen is one of the days the table calls complete',
  daily.rows.some((r) => r.day === '2023-06-03' && r.present === r.seconds && r.seconds === 86400));

// THE AGGREGATION RULE, which is the one free choice on this panel that could reverse its
// verdict. The regulation names a number of minutes in Article 127(4) and Annex III Table 2 and
// does not there say how a one-per-second log becomes minutes; Article 131(1)(a)(iv) does say,
// four articles later, and the page reports that rule. The other three ship so that a reader can
// see what the choice was worth, and one of them is worth the whole answer.
{
  const rules = [['time outside', REG.minutes], ['any second', REG.minAny],
                 ['mean', REG.minMean], ['every second', REG.minAll]];
  for (const [n, v] of rules) ok(`rule "${n}" gives ${v.toFixed(1)} minutes`, v > 0);
  const flipped = rules.filter(([, v]) => v > REG.proRata);
  ok(`exactly one of the four rules exceeds the pro rata allowance, and it is the any-second rule ` +
    `(${REG.minAny} against ${REG.proRata.toFixed(0)})`,
    flipped.length === 1 && flipped[0][0] === 'any second');
  ok('so the panel cannot print one rule and call it the answer, and the page prints all four',
    /THE RULE THAT TURNS SECONDS INTO MINUTES/.test(pagejs) &&
    /minutes holding ANY second outside/.test(pagejs) &&
    /minutes whose MEAN is outside/.test(pagejs) &&
    /minutes with EVERY second outside/.test(pagejs));
  ok('the page names Article 131(1)(a)(iv) as what settles it, and quotes the criterion',
    /Article 131\(1\)\(a\)\(iv\)/.test(pagejs) &&
    /the total time in/.test(pagejs) && /larger than the/.test(pagejs) &&
    /distinguishing between negative and positive/.test(pagejs));
  ok('and quotes ENTSO-E stating the same method for its own published figures',
    /outside the 100-1000 mHz range, time is measured/.test(pagejs));
  // That quoted range has an upper end. It is only honest to call it irrelevant if it is.
  const maxDev = 1000 * Math.max(Math.abs(REG.hi - 50), Math.abs(50 - REG.lo));
  ok(`the 1000 mHz upper end of ENTSO-E's range never binds here (largest deviation ${maxDev.toFixed(1)} mHz)`,
    maxDev < 1000);
}

// THE EDGE OF THE BAND. Article 131 says "larger than" and definition (156) makes the standard
// frequency deviation the 100 mHz limiting the range, so the comparison is strict. It is only
// strict if it is done in the log's own units: in binary floating point `Math.abs(v - 50) > 0.100`
// silently takes the inclusive reading, because the double nearest 49.9000 is 0.10000000000000142
// from 50. This is what that costs, on this log, in minutes.
{
  ok(`the double nearest 49.9000 really is further from 50 than 0.1 is, which is the trap`,
    Math.abs(49.9 - 50) > 0.1 && Math.abs(50.1 - 50) > 0.1);
  ok(`${REG.boundary} seconds of the year sit exactly on the band edge`, REG.boundary > 0);
  ok(`counting them inside (the regulation's word) rather than outside (what floating point does) ` +
    `is worth ${(REG.boundary / 60).toFixed(1)} minutes: ${REG.minutes.toFixed(1)} against ${((REG.outside + REG.boundary) / 60).toFixed(1)}`,
    Math.abs(((REG.outside + REG.boundary) / 60) - (REG.minutes + REG.boundary / 60)) < 1e-9);
  ok(`and rounding this 0.1 mHz log onto a whole-millihertz grid moves it the other way, to ` +
    `${(REG.rounded / 60).toFixed(1)} minutes`, REG.rounded < REG.outside);
  ok('none of the three alternatives reverses the verdict, which the page says',
    REG.minutes <= REG.proRata && (REG.outside + REG.boundary) / 60 <= REG.proRata &&
    REG.rounded / 60 <= REG.proRata && /None of the three moves the verdict/.test(pagejs));
  ok('the shipped table carries the direction split Article 131 asks for, and it adds up',
    REG.below + REG.above === REG.outside && REG.below > 0 && REG.above > 0);
}

// THE AUTHORITY'S OWN NUMBER. Without it this panel is a count with nothing to be wrong against.
// ENTSO-E, 2023 Annual Load-Frequency Control Report, Figure 20: the Nordic synchronous area spent
// 9714 minutes outside its standard frequency range in 2023, 4508 of them below and 5206 above.
{
  const ENTSOE = { total: 9714, below: 4508, above: 5206 };
  const scaled = REG.minutes / REG.coverage;
  ok(`this page's count scaled to a whole year is ${scaled.toFixed(0)} minutes against ENTSO-E's own ` +
    `${ENTSOE.total}, a gap of ${(100 * (scaled / ENTSOE.total - 1)).toFixed(1)}%`,
    Math.abs(scaled / ENTSOE.total - 1) < 0.10);
  const above = (REG.above / 60) / REG.coverage;
  ok(`and the above-band half alone is ${above.toFixed(0)} against ENTSO-E's ${ENTSOE.above}`,
    Math.abs(above / ENTSOE.above - 1) < 0.10);
  ok('the page prints the authority’s number beside its own rather than only its own',
    /WHAT THE AUTHORITY ITSELF PUBLISHES/.test(pagejs) && /9714/.test(pagejs) &&
    /4508/.test(pagejs) && /5206/.test(pagejs));
  // Figure 20's legend labels its series with Continental Europe's threshold. The count settles
  // which threshold it is really carrying, and the page shows the count rather than arguing.
  ok(`scored against the Continental Europe band instead, the same covered year gives ` +
    `${(REG.outside50 / 60).toFixed(0)} minutes, ${(REG.outside50 / REG.outside).toFixed(1)}x more, so 9714 cannot be that count`,
    REG.outside50 / REG.outside > 5 && (REG.outside50 / 60) / REG.coverage > 5 * ENTSOE.total);
  ok('and the page says the band is per synchronous area and not transferable',
    /not transferable/.test(pagejs));
}
{
  let lo = 99, hi = -99;
  for (const v of day) { lo = Math.min(lo, v); hi = Math.max(hi, v); }
  const row = daily.rows.find((r) => r.day === '2023-06-03');
  ok(`the shipped day and the daily table agree on that day's extremes`,
    Math.abs(lo - row.min) <= 0.0005 && Math.abs(hi - row.max) <= 0.0005,
    `bin ${lo}..${hi} vs table ${row.min}..${row.max}`);
}

// ── the blind spot the search band creates, which the page now declares ────────
// ENFSI 5.1.1(b) is +/- 1 Hz AROUND THE LINE, so referred back to the grid the window is
// +/- 0.5 Hz at 2f and +/- 0.25 Hz at 4f. A grid further off nominal than that carries its 4f
// line out of the window, and the page stops answering. The claim in "What this is not" is that
// this is reachable on the very year the page ships, so it is checked on that year's own
// extremes rather than asserted.
console.log('\nB3b. THE SEARCH BAND’S BLIND SPOT');
{
  const lcg = (s0) => { let s = s0 >>> 0; return () => { s = (1664525 * s + 1013904223) >>> 0; return s / 4294967296 - 0.5; }; };
  const gridAt = (f0, seed) => {
    const fs = 1000, n = fs * 60, x = new Float64Array(n), r = lcg(seed);
    for (let i = 0; i < n; i++) {
      x[i] = 0.5 * Math.sin(2 * Math.PI * 2 * f0 * i / fs) + 0.25 * Math.sin(2 * Math.PI * 4 * f0 * i / fs + 0.7) + 0.02 * (r() + r() + r());
    }
    return { samples: x, sampleRate: fs };
  };
  const grid = 50, edge = P.searchHz / Math.max.apply(null, P.harmonics);
  ok(`the grid-referred search window is ±${(P.searchHz / P.harmonics[0]).toFixed(2)} Hz at 2f and only ±${edge.toFixed(2)} Hz at 4f`,
    Math.abs(edge - 0.25) < 1e-12);
  const wellInside = E.estimate(gridAt(grid + 0.20, 999));
  ok(`a grid 200 mHz off nominal is still read correctly (${wellInside.value?.toFixed(5)})`,
    !wellInside.refused && Math.abs(wellInside.value - (grid + 0.20)) < 0.002);
  for (const f of [REG.lo, REG.hi]) {
    const r = E.estimate(gridAt(f, 999));
    const h4 = (4 * f).toFixed(3);
    ok(`at ${f.toFixed(4)} Hz, this year's own extreme, 4f is at ${h4} Hz outside the ${4 * grid} ± ${P.searchHz} Hz ` +
      `window and the page refuses (${r.refused ? r.refused.reason : 'IT ANSWERED'})`,
      !!r.refused && Math.abs(4 * f - 200) > P.searchHz);
    ok(`  and the refusal blames a missing line rather than the excursion, which is why the page ` +
      `has to say this itself`, r.refused.reason === 'no-mains-line');
  }
  // Nearer the edge the failure wears the other mask: both lines are found, one of them is the
  // band edge rather than the harmonic, and they disagree.
  const nearEdge = E.estimate(gridAt(grid + 0.28, 999));
  ok(`just outside the window the refusal is "harmonics disagree" instead (${nearEdge.refused?.reason})`,
    nearEdge.refused?.reason === 'harmonics-disagree');
  ok('the page declares this blind spot, with this year’s extremes as the evidence',
    /goes blind exactly when the grid gets interesting/.test(html) &&
    html.includes(REG.lo.toFixed(4)) && html.includes(REG.hi.toFixed(4)));
}

// ── the sample clock fit, which nothing else on this page can exercise ─────────
// The mis-clocked specimen proves the ESTIMATOR reads a ratio. It says nothing about fitKappa,
// which is the arithmetic that turns two browser clocks into that ratio, and the live gate cannot
// test it either: Chromium's fake audio device has no crystal, so contextTime and performanceTime
// come off the same software clock and kappa is 1 by construction there. So it is tested here,
// on pairs with a planted slope, including the SIGN, which is the half a reader would never catch.
console.log('\nB3c. THE SAMPLE CLOCK FIT');
{
  const pairsFor = (ppm, n = 100, jitter = 0) => {
    const out = []; let seed = 7;
    const rnd = () => { seed = (1103515245 * seed + 12345) % 2147483648; return seed / 2147483648 - 0.5; };
    for (let i = 0; i < n; i++) {
      const contextTime = i * 0.1;
      out.push({ contextTime, performanceTime: contextTime / (1 + ppm / 1e6) + jitter * rnd() });
    }
    return out;
  };
  for (const ppm of [-120, -12, 0, 37, 500]) {
    const f = E.fitKappa(pairsFor(ppm));
    ok(`a clock planted ${ppm} ppm fast is recovered as ${f.ppm?.toFixed(3)} ppm`,
      !f.refused && Math.abs(f.ppm - ppm) < 0.01);
  }
  // The sign is the whole point: an audio clock running fast makes every measured frequency come
  // out LOW, so the correction multiplies by (1 + ppm/1e6). The page does exactly that, and the
  // mis-clocked specimen's own truth is built from the same convention, so this ties the three
  // together rather than checking one against itself.
  {
    const ppm = MIS_PPM;
    const f = E.fitKappa(pairsFor(ppm));
    const corrected = MIS[ppm].value * (1 + f.ppm / 1e6);
    ok(`and applying it the way the page applies it undoes the mis-clocked specimen: ` +
      `${MIS[ppm].value.toFixed(6)} -> ${corrected.toFixed(6)} against the anchor's ${R.anchor.value.toFixed(6)}`,
      Math.abs(corrected - R.anchor.value) < 0.002);
    ok('the page applies the correction in that direction and never merges it into the raw reading',
      /out\.value \* \(1 \+ kap\.ppm \/ 1e6\)/.test(pagejs) && /never merged into one number/.test(pagejs));
  }
  ok('a fit with too few readings refuses rather than returning a confident slope',
    E.fitKappa(pairsFor(0, 4)).refused === 'too-few-samples');
  ok('a fit over too short a span refuses, because a suspended context reports a flat clock',
    E.fitKappa(pairsFor(0, 100).map((p) => ({ contextTime: p.contextTime / 200, performanceTime: p.performanceTime / 200 })))
      .refused === 'span-too-short');
  ok('and the page says the live gate cannot exercise this path, rather than implying it did',
    /fake audio device/.test(html.replace(/\s+/g, ' ')) &&
    /that device is not a crystal/.test(html.replace(/\s+/g, ' ')));
}

// ── the offline calibration the page quotes ────────────────────────────────────
console.log('\nB4. THE OFFLINE CALIBRATION THE PAGE QUOTES');
{
  const c = calib, n = c.nullSet, r = c.realSet, s = c.swept;
  // WHAT WAS SWEPT, asserted first, because this is the one block on the page that a reader
  // cannot re-run: it needs 1.4 GB that is not in this repository. The previous build of this
  // page recorded four numbers from a sweep and not one word about what the sweep read, and
  // that is exactly where its two worst errors lived: eleven "recordings" that were ten
  // recordings and a crop of one of them, and "the whole dataset" that was about a dozen
  // files. So the record now carries the file list, and these checks tie the arithmetic
  // together tightly enough that a mis-stated sweep cannot stay consistent with itself.
  ok(`the record says which null files were read (${s.nullFiles.length} of them, named)`,
    Array.isArray(s.nullFiles) && s.nullFiles.length === n.files &&
    s.nullFiles.every((f) => /^H0\/O\d\d$/.test(f.file) && f.seconds > 0 && f.sha256.length === 64));
  ok('no crop is counted as a recording: every null file is an H0 ORIGINAL (O01..O10)',
    new Set(s.nullFiles.map((f) => f.file)).size === s.nullFiles.length &&
    s.nullFiles.every((f) => /^H0\/O(0[1-9]|10)$/.test(f.file)));
  ok(`the excerpt count is the sum of what those durations allow (${s.nullFiles.map((f) => f.excerpts).join('+')} = ${n.excerpts})`,
    s.nullFiles.reduce((a, f) => a + f.excerpts, 0) === n.excerpts &&
    s.nullFiles.every((f) => f.excerpts === Math.floor(f.seconds / 60)));
  ok(`and the cell count is at most four lines per excerpt (${n.cells} <= ${4 * n.excerpts})`,
    n.cells <= 4 * n.excerpts && n.cells > 0);
  ok(`the sweep read ${(s.bytes / 1e9).toFixed(2)} GB and the page says so`,
    s.bytes > 0 && pagejs.includes(`sweptBytes: ${s.bytes}`) &&
    html.includes(`${(s.bytes / 1e9).toFixed(1)} gigabytes`));
  ok('the page no longer calls that half a gigabyte', !/half a gigabyte/.test(html));
  ok(`every H1 recording in the dataset was swept, not a subset (${s.realRecordings} of them, ${r.attempts} excerpts)`,
    s.realRecordings === r.recordings && s.realRecordings === 130 && r.attempts > 1000);
  ok('the two failure modes are counted separately and add up',
    r.produced === r.rightNominal + r.wrongNominal && r.wrongNominal === r.wrongNominalCases.length);
  ok(`the ${r.wrongNominal} wrong-nominal answers are on the page, file by file`,
    r.wrongNominalCases.every((w) => pagejs.includes(`file: '${w.file}', at: ${w.atSecond}, read: ${w.read}, reference: ${w.reference}`)));
  ok('and the page states the gross failure RATE in words a reader meets before the numbers',
    /confidently wrong about which grid you are on/.test(html) &&
    html.includes(`three of them said 60 Hz in a country whose grid is 50 Hz`));
  ok('the accuracy statistics are over the right-nominal excerpts only, and say so',
    /the other \$\{CAL\.realRightNominal\}, which chose the right nominal/.test(pagejs));
  const want = {
    sweptNullFiles: s.nullFiles.length, sweptRealRecordings: s.realRecordings,
    sweptBytes: s.bytes, sweptAudioSeconds: s.audioSeconds,
    nullFiles: n.files, nullExcerpts: n.excerpts, nullRefused: n.refused, nullCells: n.cells,
    nullMedianDb: n.medianDb, nullP90Db: n.p90Db, nullP99Db: n.p99Db, nullMaxDb: n.maxDb, nullAtFloor: n.cellsAtOrAboveFloor,
    realAttempts: r.attempts, realProduced: r.produced, realWrongNominal: r.wrongNominal,
    realRightNominal: r.rightNominal,
    realMedian: r.medianAbsMilliHz, realP90: r.p90AbsMilliHz,
    realMax: r.maxAbsMilliHz, realRms: r.rmsMilliHz, inside1: r.inside1Sigma, inside2: r.inside2Sigma,
    chiMedian: r.chiMedian, chiP90: r.chiP90, chiMax: r.chiMax,
    looseProduced: c.bothHarmonics.produced, looseWrongNominal: c.bothHarmonics.wrongNominal,
  };
  for (const [k, v] of Object.entries(want)) {
    const m = pagejs.match(new RegExp(k + ':\\s*(-?[\\d.]+)'));
    ok(`page.js CAL.${k} = ${v} matches calibration.json`, m && Number(m[1]) === v, m ? `page says ${m[1]}` : 'not found');
  }
  for (const row of c.monteCarlo) {
    ok(`the Monte Carlo row at ${row.measuredDb} dB is on the page`,
      pagejs.includes(`[${row.measuredDb}, ${row.rmsMilliHz}, ${row.crlbMilliHz}, ${row.ratio}]`));
    ok(`and the shipped inefficiency ${P.inefficiency} is at or above its ratio ${row.ratio}`, P.inefficiency >= row.ratio);
  }
  ok('the calibration was measured at the settings that ship',
    c.settings.windowSeconds === P.windowSeconds && c.settings.hopSeconds === P.hopSeconds &&
    c.settings.zeroPad === P.zeroPad && c.settings.snrFloorDb === P.snrFloorDb &&
    c.settings.chiSqMax === P.chiSqMax && c.settings.systematicFloorHz === P.systematicFloorHz &&
    c.settings.inefficiency === P.inefficiency);
  ok(`the reported interval never claims better than the ${(P.systematicFloorHz * 1000).toFixed(1)} mHz ` +
    `RMS (${r.rmsMilliHz} mHz) actually demonstrated on real recordings`, P.systematicFloorHz * 1000 >= r.rmsMilliHz);
  ok(`and its coverage is honest: ${r.inside1Sigma}/${r.produced} inside 1 sigma is between 55% and 85%`,
    r.inside1Sigma / r.produced > 0.55 && r.inside1Sigma / r.produced < 0.85);
}

// ── D. the shipped surfaces ────────────────────────────────────────────────────
console.log('\nD. THE SURFACES A STRANGER ACTUALLY SEES');
const fmY = md.match(/^---\n([\s\S]*?)\n---/);
const fm = fmY ? fmY[1] : '';
const field = (k) => { const m = fm.match(new RegExp('^' + k + ': "([\\s\\S]*?)"$', 'm')); return m ? m[1] : null; };
ok('the frontmatter seam is mechanism', /^seam: "mechanism"$/m.test(fm));
ok('href marks it immersive', /^href: "\/strata\/enf-mains-hum\/"$/m.test(fm));
ok('it is not a draft', /^draft: false$/m.test(fm));
ok('relates carries between two and five edges, each with a note',
  (fm.match(/^ {2}- to: /gm) || []).length >= 2 && (fm.match(/^ {2}- to: /gm) || []).length <= 5 &&
  (fm.match(/^ {2}- to: /gm) || []).length === (fm.match(/^ {4}note: /gm) || []).length);
for (const m of fm.matchAll(/^ {2}- to: (\S+)$/gm)) {
  ok(`relates target ${m[1]} exists`, existsSync(join(ROOT, 'src/content/strata', m[1] + '.md')));
}
const dek = field('dek'), plain = field('plain'), seoTitle = field('seoTitle');
ok(`the plain card is ${plain.length} characters, under 420`, plain.length <= 420);
ok('the plain card is at most three sentences', (plain.match(/[.!?](\s|$)/g) || []).length <= 3);
ok('the plain card says what the instrument cannot do', /cannot/.test(plain));
ok(`the seoTitle is ${seoTitle.length} characters`, seoTitle.length <= 62);
ok('the seoTitle appears verbatim as the page <title>', html.includes(`<title>${seoTitle}</title>`));
ok('no em dash anywhere in the page or the frontmatter', !html.includes('—') && !pagejs.includes('—') &&
  !enginejs.includes('—') && !md.includes('—'));
ok('no &mdash; entity smuggling one past the gate', !html.includes('&mdash;'));

// THE DEK'S OWN FACTUAL CLAIMS. This is the most-copied sentence on the page: it is the meta
// description, the card on three index pages, the RSS description and the search index text.
// The checks below are deliberately about the SENTENCE and not about the digits: an assertion
// that "the number 110 appears somewhere in the dek" passed happily while the dek said eleven
// recordings ship and one does. Each one here names the subject the dek names.
ok(`the dek quotes the ${MIS_PPM} ppm mis-clock`, /a thousand parts per million/.test(dek));
{
  const claimed = 49;
  ok(`the dek says the reading moves ${claimed} mHz and it moves ${(Math.abs(MIS[MIS_PPM].shift) * 1000).toFixed(1)}`,
    dek.includes(`move ${claimed} millihertz`) && Math.abs(Math.abs(MIS[MIS_PPM].shift) * 1000 - claimed) < 0.5);
  // "the shape moves one [millihertz]" is a claim with a number in it, and it has to be the
  // number the apparatus produces. It also has to stay a comparison to the run-to-run scatter
  // rather than the "does not move at all" the dek used to say, because it does move.
  const shapeMilli = MIS[MIS_PPM].maxd * 1000, noise = ANCHOR_SCATTER * Math.SQRT2 * 1000;
  ok(`the dek says the shape moves one mHz and it moves ${shapeMilli.toFixed(2)}`,
    /the shape of the recovered trace moves one\b/.test(dek) && Math.abs(shapeMilli - 1) < 0.5);
  ok(`and it compares that to the ${noise.toFixed(2)} mHz two runs differ by, without claiming zero`,
    /about what two runs of the same estimator differ by/.test(dek) && !/does not move at all/.test(dek) &&
    shapeMilli / noise < 2 && shapeMilli / noise > 0.5);
}
ok(`the dek's correlation ${DATE.mis.best.toFixed(5)} is what the matcher returns for the MIS-CLOCKED copy it is talking about`,
  /mis-clocked recording's exact second[\s\S]*?correlation 0\.99927/.test(dek) && DATE.mis.best.toFixed(5) === '0.99927');
ok(`the dek's best wrong answer ${DATE.mis.runnerUp.toFixed(3)} is the MIS-CLOCKED copy's runner-up, not the anchor's ${DATE.anchor.runnerUp.toFixed(3)}`,
  dek.includes(`a best wrong answer of ${DATE.mis.runnerUp.toFixed(3)}`) &&
  DATE.mis.runnerUp.toFixed(3) !== DATE.anchor.runnerUp.toFixed(3));
// The null-set sentence, which is where the previous build claimed eleven shipped recordings
// and shipped one. Both halves are checked: what SHIPS, counted in the specimens directory,
// and what was measured OFFLINE, against the record of the sweep.
{
  const nullWavs = readdirSync(SPEC).filter((f) => /null/.test(f) && f.endsWith('.wav'));
  ok(`exactly ${nullWavs.length} recording with no mains hum ships, and the dek says one`,
    nullWavs.length === 1 && /One real recording with no mains hum in it ships/.test(dek));
  ok('and it does not say the offline set ships', !/recordings that have no mains hum in them are shipped/.test(dek));
  ok(`the dek's offline numbers are the sweep's: ${calib.nullSet.refused} excerpts of ${calib.nullSet.files} recordings`,
    dek.includes(`refused all ${calib.nullSet.excerpts} excerpts of the ten silent recordings`) &&
    calib.nullSet.files === 10 && calib.nullSet.refused === calib.nullSet.excerpts);
  ok(`the dek carries the gross failure rate (${calib.realSet.wrongNominal} of ${calib.realSet.produced})`,
    dek.includes(`three of the ${calib.realSet.produced} answers`) && calib.realSet.wrongNominal === 3);
  ok('the dek says the 60 Hz control is synthesised, because it is',
    /a synthesised 60 hertz grid held off nominal/.test(dek));
}
ok('the dek names four specimens and the page ships four', (dek.match(/,/g) || []).length > 3 &&
  (pagejs.match(/role: '(anchor|control)'/g) || []).length === 4);
ok('neither the dek nor the plain card claims the reader’s own recording can be dated',
  !/dat(e|ing) your/i.test(dek) && !/dat(e|ing) your/i.test(plain.replace('cannot date your recording', '')));
ok('the page says out loud that a live capture is never matched against anything',
  /Your live capture is never matched against anything/.test(html));

// head tags and the JSON-LD, which is where a retracted framing survives
ok('canonical points at this slug', html.includes('<link rel="canonical" href="https://artwaste.land/strata/enf-mains-hum/" />'));
const ld = html.match(/<script type="application\/ld\+json">\s*([\s\S]*?)\s*<\/script>/);
ok('the JSON-LD block parses as JSON', !!ld && (() => { try { JSON.parse(ld[1]); return true; } catch (e) { return false; } })());
if (ld) {
  const j = JSON.parse(ld[1]);
  ok('JSON-LD name equals the seoTitle', j.name === seoTitle);
  ok('JSON-LD headline equals the poetic title', j.headline === field('title'));
  ok('JSON-LD url equals the canonical', j.url === 'https://artwaste.land/strata/enf-mains-hum/');
  const meta = html.match(/<meta name="description" content="([\s\S]*?)" \/>/);
  ok('the meta description and the JSON-LD description agree', meta && meta[1] === j.description);
  ok('the meta description does not promise to date the reader’s recording', !/date your/i.test(meta[1]));
  ok('the share cards make no claim the page retracts',
    !/proves|authenticat|identifies/i.test(html.match(/og:description" content="([\s\S]*?)"/)[1] +
      html.match(/twitter:description" content="([\s\S]*?)"/)[1]));
}
// Scripts, structure, and the no-third-party rule. The site's chrome generators append a
// <style> and a <script> to every shipped page, so nothing here may pin the bytes before
// </body> or count the whole document's script tags: the assertions are about what this page
// AUTHORED, which is everything before the first chrome marker.
// ⚠ This used to be html.split(/<!--aw-[a-z]+:start-->/)[0], which was right in spirit and
// wrong in mechanism: the site-bar generator injects near the TOP of <body>, so truncating at
// the first marker threw away the whole rest of the document including this page's own
// trailing <script src> tags, and the four-script check went red for a reason that had nothing
// to do with the page. Cut the chrome OUT instead of cutting the document short.
const authored = html
  .replace(/<!--aw-[a-z]+:start-->[\s\S]*?<!--aw-[a-z]+:end-->/g, '')
  .replace(/<script[^>]*src="\/media\/[^"]*"[^>]*>\s*<\/script>/g, '');
ok('the document closes its tags', /<\/body>\s*<\/html>\s*$/.test(html.trim()) && html.includes('<body>'));
ok('script tags are balanced', (html.match(/<script/g) || []).length === (html.match(/<\/script>/g) || []).length);
ok('the page loads its own four scripts by src, in order',
  /_kit\/dsp\.js[\s\S]*_kit\/sensors\.js[\s\S]*_kit\/anchor\.js[\s\S]*\.\/engine\.js[\s\S]*\.\/page\.js/.test(authored));
{
  // The Organization node that scripts/seo-heads.mjs writes into every page's JSON-LD names the
  // site's own Bluesky profile as its sameAs (lib/site-identity.mjs, SITE_SAME_AS). It reached this
  // page on 2026-08-21 and turned both absolute-URL checks below red: house identity, not a script
  // reaching for another origin. That one string is lifted out before they look, and nothing else
  // is, so any other absolute URL still fails them. (Repaired 2026-11-08, claude-gifted-feynman-94pojd.)
  const HOUSE_SAME_AS = ['https://bsky.app/profile/artwaste.land'];
  const lift = (s) => HOUSE_SAME_AS.reduce((t, u) => t.split(`"${u}"`).join('""'), s);
  const bodies = [...lift(authored).matchAll(/<script(?![^>]*\bsrc=)[^>]*>([\s\S]*?)<\/script>/g)].map((m) => m[1]);
  ok('the only inline script this page authored is the JSON-LD', bodies.length === 1);
  // Not "no fetch to another origin": no absolute URL in script content AT ALL, in any shape,
  // including one assigned to a variable first. Citations with URLs in them live in the static
  // HTML, where they are prose a reader can see rather than a string a script could reach for.
  ok('no absolute URL appears anywhere in this page’s script content',
    !/https?:\/\//.test(pagejs) && !/https?:\/\//.test(enginejs) && bodies.every((b) => !/https?:\/\/(?!schema\.org|artwaste\.land)/.test(b)));
  ok('the only absolute URLs this page authored are its own canonical, share and schema tags',
    (lift(authored).match(/https?:\/\/[^"'\s]+/g) || []).every((u) => /^https:\/\/(artwaste\.land|schema\.org)/.test(u)));
  ok('every script the page loads is same-origin',
    [...html.matchAll(/<script src="([^"]+)"/g)].every((m) => m[1].startsWith('/') || m[1].startsWith('./')));
  ok('the content security policy forbids other origins', /connect-src 'self'/.test(html) && /default-src 'self'/.test(html));
}
// the standards text the page quotes
const ENFSI362 = 'Calibration/measurement should be routinely carried out on the database clock ' +
  'source used in the digitisation process of the ENF. A correction factor to the database ENF ' +
  'estimates would need to be applied for data that had been collated using a soundcard that had ' +
  'a bias in its sampling frequency.';
ok('the ENFSI 3.6.2 quotation is verbatim', html.replace(/\s+/g, ' ').includes(ENFSI362));
ok('the quotation carries its issue number and date, as that document requires of quotations',
  /Issue No\. 001, 2 June 2009/.test(html));
ok('the Nordic and Continental Europe standard frequency ranges are both named, correctly',
  /&plusmn;100 mHz<\/span> for the Nordic/.test(html) && /&plusmn;50 mHz<\/span> for Continental Europe/.test(html));
ok('the 15 000 minute target is attributed to Table 2, and Article 127(6) is named as the escape',
  /Table 2 a target/.test(html) && /Article 127\(6\)/.test(html));
// The page's title claim, and the one fact on the page that is about a grid being a clock rather
// than about this estimator. Every number in it is quoted from SAFA Policy 1 section B-7, and the
// consequence the page draws from them is arithmetic on the nominal frequency.
{
  const flat = html.replace(/\s+/g, ' ');
  ok('the time control bullet quotes SAFA B-7 by section, tolerance and offset',
    /B-7-1-3-1, B-7-1-4 and B-7-1-5/.test(flat) &&
    /tolerated<\/em> within <span class="num">&plusmn;20 s<\/span>/.test(flat) &&
    /time correction frequency offset of <span class="num">&plusmn;10 mHz<\/span>/.test(flat));
  ok('and the set-points it derives from a ±10 mHz offset are the arithmetic ones',
    /49\.990 or\s*50\.010 Hz/.test(flat) && Math.abs((50 - 0.010) - 49.990) < 1e-12);
  ok('and it says the deliberate offset is twice the crystal error the second layer is about',
    /twice the 5 mHz/.test(flat) && Math.abs(2 * (100e-6 * 50) - 0.010) < 1e-12);
}
ok('the verifier command printed on the page is this file',
  html.includes('node research/enf-mains-hum/verify-enf-mains-hum.mjs') &&
  existsSync(join(ROOT, 'research/enf-mains-hum/verify-enf-mains-hum.mjs')));
ok('the gate command printed on the page exists too',
  html.includes('node scripts/check-live-sensor.mjs --only=enf-mains-hum') &&
  existsSync(join(ROOT, 'scripts/check-live-sensor.mjs')) &&
  existsSync(join(ROOT, 'research/anchor-wave/cases/enf-mains-hum.json')));
{
  const c = JSON.parse(readFileSync(join(ROOT, 'research/anchor-wave/cases/enf-mains-hum.json'), 'utf8'));
  ok('the gate case injects two files with genuinely different true answers',
    Math.abs(c.inject.anchor.expect - c.inject.control.expect) > c.inject.anchor.tol + c.inject.control.tol);
  for (const k of ['anchor', 'control']) ok(`the injected ${k} file exists`, existsSync(join(ROOT, c.inject[k].file)));
  const a = E.estimate(readWav(join(ROOT, c.inject.anchor.file)));
  const b = E.estimate(readWav(join(ROOT, c.inject.control.file)));
  ok(`the injected anchor really is ${c.inject.anchor.expect} Hz (offline: ${a.value.toFixed(5)})`,
    Math.abs(a.value - c.inject.anchor.expect) < c.inject.anchor.tol);
  ok(`the injected control really is ${c.inject.control.expect} Hz (offline: ${b.value.toFixed(5)})`,
    Math.abs(b.value - c.inject.control.expect) < c.inject.control.tol);
  ok('the live capture asked for is at least one analysis window long', c.liveSeconds >= P.windowSeconds);
}

// ── C. the rendered page ───────────────────────────────────────────────────────
if (!NO_BROWSER) {
  console.log('\nC. THE PAGE AS RENDERED, AGAINST EVERYTHING ABOVE');
  await withBrowserLock(async () => {
    const { chromium } = await import('playwright');
    const MIME = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript', '.css': 'text/css',
      '.json': 'application/json', '.wav': 'audio/wav', '.woff2': 'font/woff2', '.svg': 'image/svg+xml',
      '.ico': 'image/x-icon', '.png': 'image/png', '.txt': 'text/plain' };
    const PUBLIC = join(ROOT, 'public');
    const srv = createServer((req, out) => {
      let p = join(PUBLIC, decodeURIComponent((req.url || '/').split('?')[0]));
      if (existsSync(p) && statSync(p).isDirectory()) p = join(p, 'index.html');
      if (!existsSync(p)) { out.writeHead(404).end('not found'); return; }
      out.writeHead(200, { 'content-type': MIME[extname(p)] || 'application/octet-stream' });
      out.end(readFileSync(p));
    });
    await new Promise((r) => srv.listen(0, '127.0.0.1', r));
    const port = srv.address().port;
    const browser = await chromium.launch();
    // WHAT THE GATE'S FAKE AUDIO DEVICE ACTUALLY REPORTS FOR THE TWO CLOCKS. The page says the
    // live gate cannot check its sample-clock panel, and that is a claim about a real browser,
    // so it is measured rather than reasoned about: Chromium is launched with exactly the flags
    // scripts/check-live-sensor.mjs uses and asked for the same regression the panel runs.
    {
      const fake = await chromium.launch({ args: ['--use-fake-ui-for-media-stream',
        '--use-fake-device-for-media-stream',
        `--use-file-for-fake-audio-capture=${join(ROOT, 'research/enf-mains-hum/gate/inject-a.wav')}%noloop`,
        '--autoplay-policy=no-user-gesture-required'] });
      try {
        const pg = await (await fake.newContext()).newPage();
        await pg.goto(`http://127.0.0.1:${port}/strata/enf-mains-hum/`, { waitUntil: 'load' });
        await pg.waitForFunction(() => window.AW && window.AW.enf && window.AW.enf.fitKappa, null, { timeout: 60000 });
        const got = await pg.evaluate(async () => {
          const ctx = new (window.AudioContext || window.webkitAudioContext)();
          try { if (ctx.state === 'suspended') await ctx.resume(); } catch (e) { /* reported below */ }
          if (typeof ctx.getOutputTimestamp !== 'function') return { absent: true };
          const pairs = []; const t0 = performance.now();
          await new Promise((res) => {
            const id = setInterval(() => {
              let ts; try { ts = ctx.getOutputTimestamp(); } catch (e) { ts = null; }
              if (ts && isFinite(ts.contextTime) && isFinite(ts.performanceTime)) {
                const last = pairs[pairs.length - 1];
                if (!last || ts.contextTime > last.contextTime) {
                  pairs.push({ contextTime: ts.contextTime, performanceTime: ts.performanceTime / 1000 });
                }
              }
              if (performance.now() - t0 > 7000) { clearInterval(id); res(); }
            }, 100);
          });
          return { fit: window.AW.enf.fitKappa(pairs), n: pairs.length, rate: ctx.sampleRate };
        });
        ok('the gate’s fake audio device does report two clocks, so the panel is not simply dead there',
          !got.absent && got.fit && !got.fit.refused, JSON.stringify(got));
        // The load-bearing half: what it reports is not a crystal. A consumer crystal is spec'd
        // to about 100 ppm and this page's whole second layer is about that size of error. If
        // this ever comes back inside that, the page's account of what the gate can and cannot
        // check is wrong and has to be rewritten rather than quietly kept.
        ok(`and what it reports is not a crystal: ${got.fit?.ppm?.toFixed(0)} ppm over ` +
          `${got.fit?.spanSeconds?.toFixed(1)} s, an order of magnitude outside the 100 ppm a real one is spec'd to`,
          Math.abs(got.fit?.ppm) > 100);
        ok('so the gate cannot stand in for the offline sample-clock checks, and the page says so',
          /fake audio device/.test(html.replace(/\s+/g, ' ')));
      } finally { await fake.close(); }
    }
    try {
      for (const width of [390, 768, 1440]) {
        const c = await browser.newContext({ viewport: { width, height: 900 } });
        const pg = await c.newPage();
        const errs = [];
        pg.on('pageerror', (e) => errs.push('pageerror: ' + e.message));
        pg.on('console', (m) => { if (m.type() === 'error') errs.push('console: ' + m.text()); });
        await pg.goto(`http://127.0.0.1:${port}/strata/enf-mains-hum/`, { waitUntil: 'load' });
        await pg.waitForFunction(() => document.getElementById('mis-out').textContent.includes('ppm') &&
          document.getElementById('net').textContent.length > 50, null, { timeout: 180000 });
        const over = await pg.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
        ok(`no horizontal overflow at ${width} px`, over <= 1, `overflows by ${over} px`);
        ok(`no console or page errors at ${width} px`, errs.length === 0, errs.join(' | '));
        if (width === 1440) {
          const dom = await pg.evaluate(() => {
            const t = (id) => (document.getElementById(id) || {}).textContent || '';
            return { attest: t('attest'), trace: t('trace-cap'), date: t('date-out'), nul: t('null-out'),
              reg: t('reg-out'), mis: t('mis-out'), stub: t('stub'), choices: t('choices'),
              calib: t('calib'), state: t('slate-state'), sources: t('sources'), net: t('net'),
              all: document.body.innerText };
          });
          const has = (label, hay, needle) => ok(`the page shows ${label}: ${needle}`, hay.includes(needle),
            `not found in the rendered page`);
          // the slate, as the reader sees it, against what Node computed
          has('the anchor', dom.attest, `expected ${T_ANCHOR.toFixed(5)} Hz, measured ${R.anchor.value.toFixed(5)} Hz`);
          has('the real co-anchor', dom.attest, `expected ${T_REAL.toFixed(5)} Hz, measured ${R.real.value.toFixed(5)} Hz`);
          has('the 60 Hz control', dom.attest, `expected ${T_S60.toFixed(5)} Hz, measured ${R.s60.value.toFixed(5)} Hz`);
          has('the mis-clock control', dom.attest, `expected ${T_MIS.toFixed(5)} Hz, measured ${R.mis.value.toFixed(5)} Hz`);
          ok('the page reports itself armed', /ARMED\./.test(dom.state) && !/NOT ARMED/.test(dom.state));
          ok('the stub probe is shown failing on both controls',
            /failed\s+control synth-60/.test(dom.stub) && /failed\s+control misclock-nordic/.test(dom.stub) &&
            /The fake never arms/.test(dom.stub));
          // the anchor against the log
          has('the per-window scatter', dom.trace, `${(ANCHOR_SCATTER * 1000).toFixed(3)} mHz RMS`);
          has('the worst window', dom.trace, `${(ANCHOR_MAXERR * 1000).toFixed(3)} mHz`);
          has('the log’s own windowed mean', dom.trace, TW_MEAN.toFixed(6));
          has('what the page recovered', dom.trace, R.anchor.value.toFixed(6));
          // the drift test, and the specimen on which it must come out negative
          const moved = await pg.evaluate(() => (document.getElementById('moved') || {}).textContent || '');
          has('the anchor’s drift chi-square', moved, R.anchor.diagnostics.traceChiSq.toFixed(2));
          has('the constant specimen’s drift chi-square', moved, R.s60.diagnostics.traceChiSq.toFixed(2));
          ok('and the page calls that one noise rather than movement',
            /synth-60[\s\S]{0,80}noise, no movement shown/.test(moved), moved.slice(0, 400));
          // the second layer
          has('the 80 ppm shift', dom.mis, `${(MIS[80].shift * 1000).toFixed(3)} mHz`);
          has('the 80 ppm prediction', dom.mis, `${(MIS[80].predicted * 1000).toFixed(3)} mHz`);
          has('the 80 ppm shape correlation', dom.mis, MIS[80].corr.toFixed(6));
          has('the interpolator’s own share', dom.mis, `${Math.round(MIS[80].roundTrip * 1e6)} microhertz`);
          // dating
          has('the anchor’s match', dom.date, `r = ${DATE.anchor.best.toFixed(5)}`);
          has('its best wrong answer', dom.date, `r = ${DATE.anchor.runnerUp.toFixed(5)}`);
          has('the mis-clocked match', dom.date, `r = ${DATE.mis.best.toFixed(5)}`);
          has('the Wuhan non-match', dom.date, `r = ${DATE.real.best.toFixed(5)}`);
          has('the candidate count', dom.date, String(DATE.anchor.candidates));
          ok('the page states that both found the same second', /Both found it/.test(dom.date));
          has('the anchor’s margin', dom.date, MARGIN.anchor.toFixed(5));
          has('the control’s margin', dom.date, MARGIN.real.toFixed(5));
          has('the ratio between the two margins', dom.date, `${(MARGIN.anchor / MARGIN.real).toFixed(0)} times`);
          has('the median candidate in the control’s search', dom.date, DATE.real.nullMedian.toFixed(4));
          ok('the page names the margin, not the peak height, as the statistic it reports',
            /the margin, not the height/.test(dom.date), dom.date.slice(-500));
          // the two-source demonstration, which only exists once a reader presses it, so the
          // verifier presses it. The amplitude claim in that panel is the one a skeptic caught
          // being 15x wrong, so it is checked as a measured ratio and not as prose.
          {
            await pg.click('#two-go');
            await pg.waitForFunction(() => !document.getElementById('two-out').textContent.includes('mixing and re-running'),
              null, { timeout: 120000 });
            const two = await pg.evaluate(() => document.getElementById('two-out').textContent);
            has('the interferer’s amplitude', two, A2_ANCHOR.toFixed(4));
            has('the anchor’s own 2f line', two, `2f line is ${A2_ANCHOR.toFixed(4)}`);
            has('the anchor’s own 4f line', two, `4f line is ${A4_ANCHOR.toFixed(4)}`);
            has('the ratio to the line it lands on', two, `${(A2_ANCHOR / A4_ANCHOR).toFixed(1)}x the 4f line`);
            ok('and the estimator refuses the two-source signal in the browser too',
              /refused, reason: harmonics-disagree/.test(two), two.slice(0, 200));
          }
          // the null
          ok('the null recording is shown refusing', /refused, reason: no-mains-line/.test(dom.nul));
          for (const line of [100, 120, 200, 240]) {
            has(`the null ${line} Hz level`, dom.nul, `${R.nul.diagnostics.bestSnrDbPerLine[line].toFixed(1)} dB`);
          }
          ok('no frequency is emitted anywhere in the null panel', !/\b(49|50|59|60)\.\d{4}\s*Hz/.test(dom.nul));
          // the regulation
          has('the covered seconds', dom.reg, REG.present.toLocaleString('en'));
          has('the minutes outside', dom.reg, `${REG.minutes.toFixed(1)} minutes`);
          has('the pro rata allowance', dom.reg, `${REG.proRata.toFixed(0)} minutes`);
          has('the coverage', dom.reg, `${(100 * REG.coverage).toFixed(2)}%`);
          has('the year extremes', dom.reg, `${REG.lo.toFixed(4)} Hz`);
          has('the 15 000 minute target', dom.reg, '15,000 minutes');
          // the reconciliation additions, as rendered rather than as source
          has('the any-second rule, which is the one that reverses the verdict', dom.reg, REG.minAny.toFixed(1));
          has('the mean rule', dom.reg, REG.minMean.toFixed(1));
          has('the every-second rule', dom.reg, REG.minAll.toFixed(1));
          has('the article that settles which rule applies', dom.reg, 'Article 131(1)(a)(iv)');
          has('the band-edge count', dom.reg, REG.boundary.toLocaleString('en'));
          has('what the float comparison would have given instead', dom.reg, ((REG.outside + REG.boundary) / 60).toFixed(1));
          has('ENTSO-E’s own published figure for this grid and year', dom.reg, (9714).toLocaleString('en') + ' minutes');
          has('and this page’s own count scaled against it', dom.reg, (REG.minutes / REG.coverage).toFixed(0) + ' minutes');
          ok('the rendered panel marks one of the four rules as the one that goes the other way',
            /OUTSIDE/.test(dom.reg) && /inside/.test(dom.reg));
          // the free choices and the calibration, verbatim from the engine and the json
          has('the window length', dom.choices, `${P.windowSeconds} s, Hann, hop ${P.hopSeconds} s`);
          has('the SNR floor', dom.choices, `${P.snrFloorDb} dB`);
          has('the systematic floor', dom.choices, `${(P.systematicFloorHz * 1000).toFixed(1)} mHz`);
          has('the null-set summary', dom.calib, `${calib.nullSet.refused} of ${calib.nullSet.excerpts} excerpts`);
          has('the real-set RMS', dom.calib, `RMS ${calib.realSet.rmsMilliHz.toFixed(2)}`);
          has('the interval coverage', dom.calib, `${calib.realSet.inside1Sigma} of ${calib.realSet.rightNominal} inside 1 sigma`);
          has('what was swept', dom.calib, `${(calib.swept.bytes / 1e9).toFixed(2)} GB of audio`);
          has('the wrong-nominal rate', dom.calib, `${calib.realSet.wrongNominal} of those ${calib.realSet.produced} announced a 60 Hz grid`);
          for (const w of calib.realSet.wrongNominalCases) {
            has('a wrong-nominal case', dom.calib, `${w.file} at ${w.atSecond} s read ${w.read.toFixed(5)} Hz`);
          }
          // licences, on the page and not only in a file
          has('the Zenodo carve-out', dom.sources, 'Fingrid` are licensed under the CC-BY 4.0');
          has('the ENF-WHU copyright holder', dom.sources, 'Copyright (c)');
          ok('the page states the Continental Europe series is not redistributable',
            /NOT redistributable/.test(dom.sources));
          ok('the network list shows nothing off-origin', /0 of them to another origin/.test(dom.net));
          // ENFSI clause 6.3 prescribes competing hypotheses, not a verdict, and this page must
          // not slip into verdict vocabulary anywhere. The three words are allowed exactly once
          // each, in the one sentence that disowns them.
          {
            const hits = dom.all.match(/\b(proves|authenticates|identifies)\b/g) || [];
            ok('the verdict words appear only in the sentence that disowns them',
              dom.all.includes('Nothing here proves, authenticates or identifies.') && hits.length === 3,
              `found ${hits.length}: ${hits.join(', ')}`);
          }
        }
        await c.close();
      }
    } finally { await browser.close(); srv.close(); }
  });
}

// ── E. the checks can fail ─────────────────────────────────────────────────────
// Everything above is green. That is exactly the state a verifier is in when it is testing
// nothing, so this section breaks the engine on purpose, one defect at a time, and requires
// a NAMED check to go red for each. A mutant that survives is reported as surviving rather
// than quietly dropped, because "we could not make this check fail" is the finding.
//
// Each defect is a single textual substitution into the same engine.js the page loads, run in
// a fresh sandbox. The substitution failing to apply is itself a failure: a no-op replace
// would leave the honest engine in place and quietly turn the whole section green.
console.log('\nE. THE CHECKS CAN FAIL: single defects injected into the engine, each shown going red');
{
  const dspSrc = readFileSync(join(ROOT, 'public/_kit/dsp.js'), 'utf8');
  function loadEngine(src) {
    const s = { window: {}, console: { log() {}, warn() {}, error() {} } };
    const c = vm.createContext(s);
    vm.runInContext(dspSrc, c);
    vm.runInContext(src, c);
    return s.window.AW.enf;
  }
  function wavFor(Eng, name) {
    const b = readFileSync(join(SPEC, name));
    return Eng.parseWav(b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength));
  }
  // Deterministic noise. No Math.random and no clock, so these cases are the same every run.
  function lcg(seed) { let s = seed >>> 0; return () => { s = (1664525 * s + 1013904223) >>> 0; return s / 4294967296 - 0.5; }; }
  // A single isolated line, which is what a grid is NOT: magnetostriction puts energy at 2f
  // AND 4f, so one line on its own is a tone, not a mains hum.
  function isolatedLine(hz, amp, seed) {
    const fs = 1000, n = fs * 60, x = new Float64Array(n), r = lcg(seed);
    for (let i = 0; i < n; i++) x[i] = amp * Math.sin(2 * Math.PI * hz * i / fs) + 0.02 * (r() + r() + r());
    return { samples: x, sampleRate: fs };
  }
  // The same line WITH its 4f partner, which is what a grid looks like.
  function gridPair(hz, seed) {
    const fs = 1000, n = fs * 60, x = new Float64Array(n), r = lcg(seed);
    for (let i = 0; i < n; i++) {
      x[i] = 0.5 * Math.sin(2 * Math.PI * hz * i / fs) + 0.25 * Math.sin(2 * Math.PI * 2 * hz * i / fs + 0.7) + 0.02 * (r() + r() + r());
    }
    return { samples: x, sampleRate: fs };
  }
  // Two sources: the anchor with a foreign tone at 4f of a grid 50 mHz away, as loud as the
  // anchor's own 2f line. This is the signal the page's own "add a second source" button
  // builds, built by the same function used in part B.
  const twoSources = (Eng) => twoSourceSignal(wavFor(Eng, 'anchor-nordic.wav'));
  // Does the whole slate still stand up under this engine?
  function slateRed(Eng) {
    const red = [];
    for (const [id, file, truth] of [['anchor-nordic', 'anchor-nordic.wav', T_ANCHOR],
                                     ['synth-60', 'synth-60.wav', T_S60],
                                     ['real-whu', 'real-whu.wav', T_REAL]]) {
      const r = Eng.estimate(wavFor(Eng, file));
      if (r.refused || !(Math.abs(r.value - truth) <= tolOf(id)) || !(r.uncertainty <= tolOf(id))) red.push(id);
    }
    const w = wavFor(Eng, 'anchor-nordic.wav');
    const m = Eng.estimate({ samples: Eng.resampleByFactor(w.samples, MIS_FACTOR), sampleRate: w.sampleRate });
    if (m.refused || !(Math.abs(m.value - T_MIS) <= TOL) || !(m.uncertainty <= TOL)) red.push('misclock-nordic');
    return red;
  }
  const nullEmits = (Eng) => !Eng.estimate(wavFor(Eng, 'null-whu.wav')).refused;

  // First the honest poles, so each defect below is judged against a stated starting point
  // rather than against an assumption. Every one of these could come out the other way.
  ok('honest engine: the whole slate stands', slateRed(E).length === 0, slateRed(E).join(', '));
  ok('honest engine: the null recording is refused', !nullEmits(E));
  ok('honest engine: two sources at odds are refused',
    E.estimate(twoSources(E)).refused?.reason === 'harmonics-disagree');
  ok('honest engine: a single isolated 100 Hz line is refused, because a grid appears at 2f and 4f',
    E.estimate(isolatedLine(100, 0.5, 12345)).refused?.reason === 'no-mains-line');
  ok('honest engine: the same line WITH its 200 Hz partner is answered',
    Math.abs((E.estimate(gridPair(100, 999)).value ?? 0) - 50) < 0.002);
  ok(`honest engine: the interval on real audio is at least the ${(P.systematicFloorHz * 1000).toFixed(1)} mHz demonstrated floor`,
    E.estimate(wavFor(E, 'real-whu.wav')).uncertainty >= P.systematicFloorHz);

  // name, substitution, and the named consequence that must follow
  const MUTANTS = [
    ['the estimator returns a constant 50.000 Hz',
     'function estimate(payload) {', 'function estimate(payload) { return { value: 50, uncertainty: 0.001 };',
     (M) => ({ red: slateRed(M).length === 4 && nullEmits(M),
               says: `slate red on ${slateRed(M).join(', ') || 'nothing'}; null ${nullEmits(M) ? 'emitted a number' : 'still refused'}` })],

    ['the estimator returns the nominal it chose',
     'return {\n      value: mean,', 'return {\n      value: top,',
     (M) => ({ red: slateRed(M).includes('synth-60') && slateRed(M).includes('anchor-nordic'),
               says: `slate red on ${slateRed(M).join(', ') || 'nothing'} (synth-60 sits 12.9 mHz off nominal, against a 12 mHz tolerance, which is what makes it catch this)` })],

    ['the sub-bin refinement is skipped and the raw peak bin is returned',
     'const hz = D.refineGoertzel(windowed, fs, coarse - spec.hzPerBin, coarse + spec.hzPerBin, P.goertzelIters);',
     'const hz = (kLo + kBest) * spec.hzPerBin;',
     (M) => ({ red: slateRed(M).length >= 3, says: `slate red on ${slateRed(M).join(', ') || 'nothing'}` })],

    ['the in-band SNR floor is removed, so nothing is ever refused for weakness',
     'snrFloorDb: 20,', 'snrFloorDb: -Infinity,',
     (M) => ({ red: slateRed(M).length === 4, says: `slate red on ${slateRed(M).join(', ') || 'nothing'} (with no floor the 50 and 60 Hz noise bins tie and the nominal cannot be chosen)` })],

    ['the harmonic agreement check is disabled',
     'chiSqMax: 50,', 'chiSqMax: Infinity,',
     (M) => { const r = M.estimate(twoSources(M));
              return { red: !r.refused, says: r.refused ? 'two sources still refused' : `two sources averaged into ${r.value.toFixed(5)} Hz, a number that is neither of them` }; }],

    ['the both-harmonics rule is dropped, so one line is enough',
     'const bothOf = (F0) => Math.min(', 'const bothOf = (F0) => Math.max(',
     (M) => { const r = M.estimate(isolatedLine(100, 0.5, 12345));
              return { red: !r.refused, says: r.refused ? 'the isolated line was still refused' : `an isolated tone was reported as a grid at ${r.value.toFixed(5)} Hz` }; }],

    // The sample clock layer, which the browser gate provably cannot reach: under a fake audio
    // device both clocks are the same software clock, so an inverted ratio there is invisible.
    // Inverted here it is not, and this is the check that says so.
    ['the sample clock ratio is inverted, so a fast clock is reported as a slow one',
     'const kappa = 1 / slope;', 'const kappa = slope;',
     (M) => {
       const pairs = [];
       for (let i = 0; i < 100; i++) pairs.push({ contextTime: i * 0.1, performanceTime: i * 0.1 / (1 + 500 / 1e6) });
       const f = M.fitKappa(pairs);
       return { red: !(Math.abs(f.ppm - 500) < 0.01),
                says: `a clock planted 500 ppm fast is reported as ${f.ppm.toFixed(3)} ppm` };
     }],

    ['the demonstrated accuracy floor is removed from the interval',
     'systematicFloorHz: 0.0030,', 'systematicFloorHz: 0,',
     (M) => { const u = M.estimate(wavFor(M, 'real-whu.wav')).uncertainty;
              return { red: u < P.systematicFloorHz,
                       says: `claims ±${(u * 1000).toFixed(3)} mHz on real room audio, where this estimator has only ever demonstrated ${(P.systematicFloorHz * 1000).toFixed(1)} mHz` }; }],
  ];

  for (const [name, from, to, judge] of MUTANTS) {
    const src = enginejs.replace(from, to);
    if (src === enginejs) { ok(`MUTANT applies: ${name}`, false, 'the substitution matched nothing, so this defect was never actually injected'); continue; }
    ok(`MUTANT applies: ${name}`, true);
    let verdict;
    try { verdict = judge(loadEngine(src)); }
    catch (e) { verdict = { red: true, says: 'the mutant threw: ' + e.message }; }
    ok(`  and it goes red: ${verdict.says}`, verdict.red,
      verdict.red ? '' : 'THIS MUTANT SURVIVED. A check that cannot fail is not a check.');
    // The page lists these defects. A defect injected here but not shown to the reader, or one
    // described to the reader that is not actually injected, are both drift, so the two lists
    // are pinned to each other.
    const flat = html.replace(/\s+/g, ' ');
    ok(`  and the page tells the reader about it`, flat.includes(name.replace(/\s+/g, ' ')),
      `"${name}" is injected by this verifier but does not appear in the page's own list of defects`);
  }

  // Two defects this slate provably cannot see, recorded here rather than left for a reader to
  // discover. Saying which mutants survive is part of saying what the slate is worth.
  for (const [name, from, to] of [
    ['forcing the log-parabolic interpolation to zero', 'const coarse = (kLo + kBest + delta) * spec.hzPerBin;', 'const coarse = (kLo + kBest + 0 * delta) * spec.hzPerBin;'],
  ]) {
    const src = enginejs.replace(from, to);
    ok(`KNOWN SURVIVOR is still a survivor: ${name}`, src !== enginejs && slateRed(loadEngine(src)).length === 0,
      'the parabolic step is only a starting point for the Goertzel search, which is why removing it changes nothing. ' +
      'If this ever goes red the page description of the method is wrong.');
    ok('  and the page records it as a survivor', html.replace(/\s+/g, ' ').includes(name));
    // The page states HOW MUCH it changes. That bound is checked, not asserted.
    const M = loadEngine(src);
    let worst = 0;
    for (const [file, base] of [['anchor-nordic.wav', R.anchor], ['synth-60.wav', R.s60], ['real-whu.wav', R.real]]) {
      const r = M.estimate(wavFor(M, file));
      if (!r.refused) worst = Math.max(worst, Math.abs(r.value - base.value));
    }
    ok(`  and it moves every specimen by under the 20 nanohertz the page claims (worst ${(worst * 1e9).toFixed(1)} nHz)`,
      worst < 20e-9 && html.includes('under 20 nanohertz'));
  }

  // The two figures the new panel prints, recomputed rather than transcribed.
  {
    const chi = loadEngine(enginejs.replace('chiSqMax: 50,', 'chiSqMax: Infinity,'));
    const r = chi.estimate(twoSources(chi));
    ok(`the page's stated two-source average ${r.value.toFixed(5)} Hz is what the mutant actually returns`,
      !r.refused && html.includes(`${r.value.toFixed(5)} Hz`));
    const nf = loadEngine(enginejs.replace('systematicFloorHz: 0.0030,', 'systematicFloorHz: 0,'));
    const u = nf.estimate(wavFor(nf, 'real-whu.wav')).uncertainty * 1000;
    ok(`the page's stated ${u.toFixed(2)} mHz floorless interval is what the mutant actually claims`,
      html.includes(`${u.toFixed(2)} mHz on real room audio`));
  }
}

console.log(`\n${fails.length ? '✗' : '✓'} ${pass} checks passed, ${fails.length} failed`);
if (fails.length) { for (const f of fails) console.log('   ' + f); process.exit(1); }

// One browser at a time on this box: it is shared with a live fleet and 7.7 GB does not hold
// two Chromiums plus a wave. This is the same lock scripts/check-live-sensor.mjs takes, on
// purpose, so the two never run at once.
async function withBrowserLock(fn) {
  const lock = join(ROOT, 'scratchpad', '.live-sensor.lock');
  mkdirSync(join(ROOT, 'scratchpad'), { recursive: true });
  const STALE_MS = 20 * 60 * 1000, started = Date.now();
  for (;;) {
    try { writeFileSync(lock, String(process.pid), { flag: 'wx' }); break; }
    catch (e) {
      if (existsSync(lock) && Date.now() - statSync(lock).mtimeMs > STALE_MS) { rmSync(lock, { force: true }); continue; }
      if (Date.now() - started > 45 * 60 * 1000) throw new Error('verify: waited 45 min for the browser lock');
      await new Promise((r) => setTimeout(r, 3000 + Math.floor(Math.random() * 4000)));
    }
  }
  const release = () => { try { rmSync(lock, { force: true }); } catch (e) {} };
  process.on('exit', release);
  try { return await fn(); } finally { release(); }
}
