#!/usr/bin/env node
// verify-speed-of-sound-room.mjs: recompute every number the page prints, from the shipped
// files and the published equations, and fail on any disagreement.
//
// Run:  node research/speed-of-sound-room/verify-speed-of-sound-room.mjs
//
// FIVE THINGS THIS DOES THAT A WEAKER VERIFIER WOULD NOT.
//
//  1. It executes the page's OWN browser scripts (public/_kit/dsp.js and the page's sos.js)
//     inside a vm, unmodified, so it grades the bytes the reader's browser runs rather than a
//     Node copy that could drift away from them.
//  2. It regenerates every specimen from the generator and compares sha256, so a doctored
//     recording is caught rather than trusted.
//  3. It re-runs the 240 draw Monte Carlo that fixed the estimator's timing constant, and
//     fails if the interval the estimator states does not cover the scatter it actually
//     produces. An error bar whose coverage nobody has checked is decoration.
//  4. It runs FOUR deliberately broken builds of the estimator and requires each one to fail.
//     A check that has never been seen failing is not known to work.
//  5. It string-matches the rendered surface: the dek, the plain card, the seoTitle, the meta
//     description, the OG and Twitter tags and the JSON-LD, against claims the page's own
//     apparatus actually supports. The honesty leak lives in the shareable surface.
//
// It reads public/ and never a build output directory. A verifier that grades what the build
// produced can pass on a page nobody shipped.
import { readFileSync, existsSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { load, loadKit, ROOT, PAGE } from './load.mjs';
import { readWav } from './wav.mjs';
import { noise, sum, shaFile } from '../anchor-wave/forge.mjs';
import {
  SPECIMENS, GATE_FILES, DECOY, DECOY_DT, OFFSET, C_REF, FS, PULSE_SEC, F0, F1, T0, pulse,
} from './make-specimens.mjs';

const HERE = dirname(fileURLToPath(import.meta.url));
const anchorKit = loadKit().anchor;

let pass = 0, fail = 0;
const ok = (cond, name, detail) => {
  if (cond) { pass++; console.log(`  ok   ${name}`); }
  else { fail++; console.log(`  FAIL ${name}${detail === undefined ? '' : '  ->  ' + detail}`); }
};
const near = (a, b, tol) => Math.abs(a - b) <= tol;
// The character itself, by code point, so this file can hunt it without carrying one.
const EM = String.fromCharCode(0x2014);
const section = (s) => console.log(`\n== ${s}`);

const sos = load();
const html = readFileSync(join(PAGE, 'index.html'), 'utf8');
const instrumentJs = readFileSync(join(PAGE, 'instrument.js'), 'utf8');
const sosJs = readFileSync(join(PAGE, 'sos.js'), 'utf8');
const mdPath = join(ROOT, 'src/content/strata/speed-of-sound-room.md');
const md = existsSync(mdPath) ? readFileSync(mdPath, 'utf8') : '';
const manifest = JSON.parse(readFileSync(join(HERE, 'specimen-manifest.json'), 'utf8'));

// ═══ 1. the specimens are what the generator makes ═══════════════════════════
section('1. the specimens regenerate byte for byte');
{
  const rows = new Map(manifest.files.map((r) => [r.file, r]));
  let allMatch = true, missing = [];
  for (const s of SPECIMENS) {
    const p = join(PAGE, 'specimens', s.file);
    if (!existsSync(p)) { missing.push(s.file); allMatch = false; continue; }
    const got = shaFile(p), want = rows.get(s.file);
    if (!want || want.sha256 !== got) { allMatch = false; missing.push(s.file + ' hash'); }
  }
  ok(allMatch, 'every shipped specimen matches the sha256 the generator recorded', missing.join(', '));
  for (const g of GATE_FILES) {
    const p = join(HERE, 'gate', g.file);
    ok(existsSync(p) && shaFile(p) === rows.get('gate/' + g.file).sha256,
      `the injected gate file ${g.file} matches its recorded sha256`);
  }
  const shipped = manifest.files.filter((r) => !r.file.startsWith('gate/')).reduce((a, r) => a + r.bytes, 0);
  ok(shipped < 3 * 1024 * 1024, `the shipped specimens are under the 3 MB budget (${(shipped / 1024).toFixed(0)} kB)`);
  ok(manifest.files.every((r) => r.clipped === 0),
    'no specimen clips, so none of them is refused for a reason the slate did not intend');
  // The truth must be OFF the sample grid, or the sub-sample refinement is untested.
  const gridded = SPECIMENS.filter((s) => s.truthMs !== undefined)
    .filter((s) => Math.abs((s.truthMs / 1000 * FS) % 1) < 1e-6);
  ok(gridded.length === 0,
    'every declared delay lands OFF the sample grid, so an estimator that rounds cannot pass',
    gridded.map((s) => s.id).join(', '));
  ok(Math.abs((T0 * FS) % 1) > 1e-6, 'and the direct arrival itself is off the grid too');
}

// ═══ 2. the estimator on the shipped recordings ═══════════════════════════════
section('2. the same estimator on every shipped recording');
const measured = new Map();
{
  for (const s of SPECIMENS) {
    const r = sos.estimateArrivals(readWav(join(PAGE, 'specimens', s.file)));
    measured.set(s.id, r);
  }
  for (const s of SPECIMENS.filter((x) => x.kind === 'delay')) {
    const r = measured.get(s.id);
    ok(!r.refused && near(r.value, s.truthMs, 0.050),
      `${s.id}: recovers ${s.truthMs} ms (got ${r.refused ? 'refusal ' + r.refused.reason : r.value.toFixed(5)})`);
    ok(!r.refused && r.uncertainty > 0 && r.uncertainty <= 0.050,
      `${s.id}: states a positive interval no wider than the tolerance it is judged against`,
      r.refused ? 'refused' : r.uncertainty.toFixed(5));
  }
  for (const s of SPECIMENS.filter((x) => x.kind === 'refusal')) {
    const r = measured.get(s.id);
    ok(!!r.refused && r.refused.reason === s.expect,
      `${s.id}: refuses with "${s.expect}"`,
      r.refused ? r.refused.reason : 'returned ' + r.value.toFixed(5));
  }
  const noEcho = measured.get('refusal-no-echo');
  ok(noEcho.refused.detail.includes("No second arrival stands above this recording's own noise floor"),
    'the no-echo refusal says exactly that, in the words the page prints');
  const decoy = measured.get('refusal-floor-decoy');
  ok(decoy.refused.candidates.length === 3,
    'the decoy offers three candidates rather than one answer', String(decoy.refused.candidates.length));
}

// ═══ 3. the anchor kit's slate, in Node, on the same estimator ════════════════
section('3. the slate arms, and a constant does not');
{
  const TOL = 0.050;
  const mk = (estimate) => anchorKit.instrument({
    id: 'speed-of-sound-room', quantity: 'gap between arrivals', unit: 'ms', estimate,
    specimens: SPECIMENS.filter((s) => s.kind === 'delay').map((s) => ({
      id: s.id, role: s.role, label: s.label,
      truth: { value: s.truthMs, tol: TOL, why: 'exact by construction; the tolerance is about eight times the estimator’s own stated interval at this signal to noise ratio' },
      load: () => readWav(join(PAGE, 'specimens', s.file)),
    })),
  });
  const inst = mk((p) => sos.estimateArrivals(p));
  await inst.runAll();
  ok(inst.armed(), 'the slate arms on the real estimator', inst.blockedBecause() || '');
  const probe = await anchorKit.stubProbe(inst);
  ok(probe.armed === false, 'a hard-coded estimator does not arm the same slate');
  ok(probe.rows.filter((r) => r.role === 'control').every((r) => r.pass === false),
    'and it fails on BOTH controls, not just on one of them');
  ok(probe.rows.find((r) => r.role === 'anchor').pass === true,
    'while sailing through the anchor, which is what makes the control the load-bearing half');
  // A control that cannot discriminate must be refused at construction.
  let refused = false;
  try {
    anchorKit.instrument({
      id: 'x', quantity: 'y', unit: 'ms', estimate: () => ({ value: 1, uncertainty: 0.1 }),
      specimens: [
        { id: 'a', role: 'anchor', truth: { value: 17.4927, tol: 0.05, why: 'a stated reason' }, load: () => ({}) },
        { id: 'b', role: 'control', truth: { value: 17.5, tol: 0.05, why: 'a stated reason' }, load: () => ({}) },
      ],
    });
  } catch (e) { refused = e.name === 'AnchorSpecError'; }
  ok(refused, 'and a control too close to the anchor is refused at construction, so this slate could have been rejected');
}

// ═══ 4. the estimator has no idea what it is looking at ══════════════════════
section('4. one code path, and no way to tell a specimen from a reader');
{
  const body = sosJs.slice(sosJs.indexOf('function estimateArrivals'), sosJs.indexOf('// The timing uncertainty of ONE gap.'))
    .replace(/\/\*[\s\S]*?\*\//g, ' ').split('\n').map((l) => l.replace(/\/\/.*$/, '')).join('\n');
  const leaks = ['truth', 'expected', 'isControl', 'isSpecimen', 'specimen', 'role', 'tol', 'label', 'id']
    .filter((w) => new RegExp('\\b' + w + '\\b').test(body));
  ok(leaks.length === 0, 'the code of estimateArrivals names nothing that could tell it which signal it has', leaks.join(', '));
  ok(/function estimate\(payload\)\s*\{\s*return AW\.sos\.estimateArrivals\(payload\);\s*\}/.test(instrumentJs),
    'and the page routes every signal through it with a one line pass through');
  const routes = [...instrumentJs.matchAll(/estimateArrivals\s*\(/g)].length;
  ok(routes === 1, 'which is the only call to it anywhere on the page', String(routes));
  ok(/probeLive:[\s\S]{0,220}captureLive\(\(opts && opts\.seconds\) \|\| 3\)/.test(instrumentJs),
    'probeLive captures through the same captureLive the reader’s own button calls');
  ok((instrumentJs.match(/await captureLive\(/g) || []).length === 2,
    'and captureLive has exactly two callers: the button and probeLive');
}

// ═══ 5. the Monte Carlo the timing constant was fixed by ═════════════════════
section('5. the stated interval covers the scatter it actually produces');
// THE ENSEMBLE, run once and used twice: for the interval's coverage, and for the comparison
// between the refinement that shipped and the one it replaced. sos.js says in its own comment
// that this file swaps refineFine back in and fails if the ordering flips, and section 5b is
// the only thing that makes that sentence true. A comparison nobody can re-run is a claim.
const REFINE_FINE = [
  ['    const p0 = i0.pos;', '    const p0 = refineFine(an.re, an.im, i0k, 32, 64);'],
  ['      const pos = p.pos;', '      const pos = refineFine(an.re, an.im, k, 32, 64);'],
];
const MC = (() => {
  const DT = 0.01749270;
  const fine = load(REFINE_FINE);
  const render = (fn, sec) => {
    const n = Math.round(sec * FS), y = new Float32Array(n);
    for (let i = 0; i < n; i++) { const v = Math.max(-1, Math.min(1, fn(i / FS))); y[i] = Math.round(v * 32767) / 32768; }
    return { samples: y, sampleRate: FS };
  };
  const errs = [], sigs = [], errsFine = [];
  for (let k = 1; k <= 240; k++) {
    const w = render(sum([pulse(T0, 0.60), pulse(T0 + DT, 0.60 * 0.35), noise(0.035, k)]), 0.30);
    const r = sos.estimateArrivals(w);
    const q = fine.estimateArrivals(w);
    if (!q.refused) errsFine.push((q.value - DT * 1000) * 1000);
    if (r.refused) continue;
    errs.push((r.value - DT * 1000) * 1000);
    sigs.push(r.uncertainty * 1000);
  }
  const sdOf = (a) => {
    const m = a.reduce((x, y) => x + y, 0) / a.length;
    return Math.sqrt(a.reduce((x, y) => x + (y - m) ** 2, 0) / (a.length - 1));
  };
  const mean = errs.reduce((a, b) => a + b, 0) / errs.length;
  const sd = sdOf(errs);
  const meanSig = sigs.reduce((a, b) => a + b, 0) / sigs.length;
  const cover = errs.filter((e, i) => Math.abs(e) <= sigs[i]).length / errs.length;
  const maxErr = Math.max(...errs.map(Math.abs));
  return { n: errs.length, mean, sd, meanSig, cover, maxErr,
           sdFine: sdOf(errsFine), maxErrFine: Math.max(...errsFine.map(Math.abs)) };
})();
{
  console.log(`     240 draws: mean ${MC.mean.toFixed(3)} us, sd ${MC.sd.toFixed(3)} us, ` +
    `mean stated interval ${MC.meanSig.toFixed(3)} us, 1-sigma coverage ${(MC.cover * 100).toFixed(1)}%, ` +
    `largest error ${MC.maxErr.toFixed(2)} us`);
  ok(MC.n === 240, 'all 240 draws produced an answer rather than a refusal', String(MC.n));
  ok(Math.abs(MC.mean) < 0.25 * MC.sd, 'the estimator is unbiased on this construction', MC.mean.toFixed(3));
  ok(MC.meanSig >= MC.sd, 'the interval it states is at least as wide as the scatter it produces',
    `${MC.meanSig.toFixed(3)} vs ${MC.sd.toFixed(3)}`);
  ok(MC.cover >= 0.68, 'and a 68% interval covers at least 68% of the draws', (MC.cover * 100).toFixed(1) + '%');
  ok(MC.cover <= 0.95, 'without being so wide that it agrees with anything', (MC.cover * 100).toFixed(1) + '%');
  ok(near(MC.cover * 100, 75, 3),
    'and the 75% the specimen readout prints beside every measured gap is the coverage it has',
    (MC.cover * 100).toFixed(1) + '%');
  ok(near(MC.maxErr, 17.0, 0.6), 'the largest error over 240 draws is the 17.0 us the page quotes',
    MC.maxErr.toFixed(2));
  ok(MC.maxErr < 50, 'and the 0.050 ms tolerance is wider than it, so the slate is not scored on luck');
  ok(near(MC.meanSig, 5.9, 0.4), 'the stated interval is the "about 5.9 microseconds" the page quotes',
    MC.meanSig.toFixed(2));
}

// ═══ 5b. the refinement that lost, re-measured rather than remembered ════════
// Two ways of placing a peak to a fraction of a sample are in sos.js and the file states, in
// numbers, why the crude-looking one is the one that ships. Every one of those numbers is
// re-taken here. This is the section that would have caught the version of this page whose
// comment claimed 0.3 us for a refinement the page itself displayed missing by 19.
section('5b. the refinements, and the numbers sos.js states about them');
{
  const anchorWav = readWav(join(PAGE, 'specimens', 'anchor-two-arrivals.wav'));
  const TRUTH = SPECIMENS.find((s) => s.id === 'anchor-two-arrivals').truthMs;
  const errUs = (mod) => { const r = mod.estimateArrivals(anchorWav); return r.refused ? NaN : (r.value - TRUTH) * 1000; };
  const eFit = errUs(sos), eFine = errUs(load(REFINE_FINE));
  ok(near(eFit, 6.5, 0.3), `the shipped half-height fit misses the anchor by ${eFit.toFixed(2)} us, the 6.5 sos.js states`);
  ok(near(eFine, 19.0, 0.5),
    `and the band-limited interpolation it replaced misses by ${eFine.toFixed(2)} us, the 19.0 sos.js states`);
  ok(Math.abs(eFine) > Math.abs(eFit), 'so on the shipped anchor the refinement that was kept is the one that wins');
  ok(near(MC.sd, 5.3, 0.4) && near(MC.sdFine, 9.3, 0.6),
    `and over the 240 draws the scatter is ${MC.sd.toFixed(1)} us against ${MC.sdFine.toFixed(1)}, the two numbers sos.js prints`);
  ok(MC.sdFine > 1.4 * MC.sd,
    'which is the ordering the comment claims, on the ensemble and not on one lucky recording',
    `${MC.sdFine.toFixed(2)} vs ${MC.sd.toFixed(2)}`);

  // Three points instead of the half-height span: the fit that came first.
  const three = load([[
    '    if (b - a < 4) { a = Math.max(1, k - 2); b = Math.min(env.length - 2, k + 2); }',
    '    a = Math.max(1, k - 1); b = Math.min(env.length - 2, k + 1);']]);
  const eThree = errUs(three);
  ok(near(eThree, 14.0, 0.5), `a three point parabola misses by ${eThree.toFixed(2)} us, the 14.0 sos.js states`);
  ok(near(eThree * 1e-6 * FS, 0.67, 0.03), `which is ${(eThree * 1e-6 * FS).toFixed(2)} of a sample, the 0.67 sos.js states`);
  ok(near(Math.abs(eThree / eFit), 2.16, 0.25),
    `so the wide fit is ${Math.abs(eThree / eFit).toFixed(2)} times better, the "a bit over twice" sos.js claims and not a larger number`);

  // Neither is biased on a noiseless construction, which is what makes the difference above
  // noise rather than a systematic. sos.js says both stay under 0.3 us; this sweeps a whole
  // sample of true delay and checks it.
  const renderClean = (fn, sec) => {
    const n = Math.round(sec * FS), y = new Float32Array(n);
    for (let i = 0; i < n; i++) y[i] = fn(i / FS);
    return { samples: y, sampleRate: FS };
  };
  const fine = load(REFINE_FINE);
  let biasFit = 0, biasFine = 0;
  for (let f = 0; f < 1; f += 0.125) {
    const D = (839 + f) / FS;
    const w = renderClean(sum([pulse(T0, 0.60), pulse(T0 + D, 0.60 * 0.35)]), 0.30);
    const a = sos.estimateArrivals(w), b = fine.estimateArrivals(w);
    if (!a.refused) biasFit = Math.max(biasFit, Math.abs((a.value - D * 1000) * 1000));
    if (!b.refused) biasFine = Math.max(biasFine, Math.abs((b.value - D * 1000) * 1000));
  }
  ok(biasFit < 0.3 && biasFine < 0.3,
    `swept across a whole sample with no noise, both stay under 0.3 us (${biasFit.toFixed(2)} and ${biasFine.toFixed(2)}), so the gap between them is noise and not bias`);
}

// ═══ 5c. the sensitivities the page prints for its own free choices ══════════
section('5c. the free choices whose cost the page states in microseconds and decibels');
{
  const ids = ['anchor-two-arrivals', 'control-half-delay', 'control-late-and-quiet'];
  const spreads = [], ratios = [];
  for (const id of ids) {
    const w = readWav(join(PAGE, 'specimens', id + '.wav'));
    const vals = [];
    for (const t of [2.5, 3.0, 3.5, 4.0]) {
      const r = load([['    templateMs: 4.0,', '    templateMs: ' + t + ',']]).estimateArrivals(w);
      vals.push(r.refused ? NaN : r.value);
    }
    spreads.push((Math.max(...vals) - Math.min(...vals)) * 1000);
    ratios.push(spreads[spreads.length - 1] / (measured.get(id).uncertainty * 1000));
  }
  ok(near(spreads[0], 0.3, 0.15) && near(spreads[1], 0.3, 0.15) && near(spreads[2], 2.8, 0.3),
    `templateMs from 2.5 to 4 ms moves the three shipped delays by ${spreads.map((s) => s.toFixed(1)).join(', ')} us, the three numbers the choices table prints`);
  ok(spreads[2] === Math.max(...spreads),
    'and the largest of the three really is the recording with the reverberant tail, as the table says');
  ok(near(ratios[2], 0.21, 0.04),
    `which is ${(ratios[2] * 100).toFixed(0)}% of the interval the estimator states there, the "a fifth" the table prints`,
    ratios[2].toFixed(3));

  // The impulse gate: how far noise alone rises above its own median, which is the whole
  // justification for a 20 dB bar. Measured on the shipped silence and on fresh draws at the
  // longest record the page will take.
  const sil = measured.get('refusal-silence').refused.peakDb;
  ok(near(sil, 11.0, 0.2),
    `noise alone reaches ${sil.toFixed(2)} dB over its own median on the shipped 0.30 s silence, the 11.0 sos.js and the page both state`);
  const renderNoise = (sec, seed) => {
    const n = Math.round(sec * FS), y = new Float32Array(n), f = noise(0.035, seed);
    for (let i = 0; i < n; i++) { const v = Math.max(-1, Math.min(1, f(i / FS))); y[i] = Math.round(v * 32767) / 32768; }
    return { samples: y, sampleRate: FS };
  };
  const at = (sec) => {
    const v = [];
    for (let k = 1; k <= 40; k++) {
      const q = sos.estimateArrivals(renderNoise(sec, 5000 + k));
      v.push(q.refused ? q.refused.peakDb : NaN);
    }
    return { mean: v.reduce((a, b) => a + b, 0) / v.length, max: Math.max(...v) };
  };
  const three = at(3), ten = at(10);
  ok(near(three.mean, 12.5, 0.4) && near(three.max, 13.9, 0.6),
    `at the reader's 3 s default, 40 fresh draws mean ${three.mean.toFixed(1)} dB with a largest of ${three.max.toFixed(1)}, which is what sos.js and the page state`);
  ok(sos.CHOICES.minPeakOverMedianDb - ten.max >= 6,
    `and at 10 s, the longest record the page will take, the largest is ${ten.max.toFixed(1)} dB, so the 20 dB bar really is six decibels clear of what noise does alone`,
    (sos.CHOICES.minPeakOverMedianDb - ten.max).toFixed(2));
}

// ═══ 6. mutation tests: the checks can fail ══════════════════════════════════
section('6. four broken builds, each of which must fail');
{
  const half = SPECIMENS.find((s) => s.id === 'control-half-delay');
  const wav = (id) => readWav(join(PAGE, 'specimens', id + '.wav'));

  // (i) return the anchor delay no matter what is heard.
  const m1 = load([['    const one = cands[0];', '    const one = { dtMs: 17.49270, sigmaMs: 0.001, strength: 99, index: 0 };']]);
  const r1 = m1.estimateArrivals(wav('control-half-delay'));
  ok(!r1.refused && !near(r1.value, half.truthMs, 0.050),
    'a stub returning the anchor delay fails the halved control', r1.refused ? r1.refused.reason : r1.value.toFixed(5));

  // (ii) hard-code the speed, so every implied speed becomes the folk constant.
  const m2 = load([['    return pathMetres / (dtMs / 1000);', '    return 343.36;']]);
  ok(!near(m2.speedFrom(2 * 3.000, 8.750032), 685.7, 5),
    'hard-coding c to 343.36 breaks the halved control’s implied speed, which must be about 686 m/s',
    m2.speedFrom(6, 8.750032).toFixed(2));
  ok(near(sos.speedFrom(2 * 3.000, measured.get('control-half-delay').value), 685.7, 1.0),
    'while the real code gives about 686 m/s there, far outside the 250 to 450 band the page will report in',
    sos.speedFrom(6, measured.get('control-half-delay').value).toFixed(2));

  // (iii) THE ONE THAT MATTERS: pick the largest peak after the direct arrival.
  const m3 = load([[
    '    if (kept.length > 1) {',
    '    if (false) {']]);
  const r3 = m3.estimateArrivals(wav('refusal-floor-decoy'));
  ok(!r3.refused, 'the naive build stops refusing the decoy, as it must for this test to mean anything');
  const naiveC = r3.refused ? null : sos.speedFrom(2 * 3.000, r3.value);
  ok(naiveC !== null && naiveC > 800,
    'and reports a nonsense speed instead of a refusal, which is exactly the failure this page exists for',
    naiveC === null ? 'refused' : naiveC.toFixed(1) + ' m/s');
  ok(!!measured.get('refusal-floor-decoy').refused,
    'while the shipped build refuses that same recording');

  // (iv) always find something: drop the detection floor to zero.
  const m4 = load([['    const floor = Math.max(CHOICES.detectionFloor * noise, CHOICES.relativeFloor * env[i0k]);',
                    '    const floor = 0;']]);
  const r4 = m4.estimateArrivals(wav('refusal-no-echo'));
  ok(!(r4.refused && r4.refused.reason === 'no-second-arrival'),
    'an estimator with no detection floor stops saying "no second arrival" where there is none',
    r4.refused ? r4.refused.reason : 'reported ' + r4.value.toFixed(5));
  ok(measured.get('refusal-no-echo').refused.reason === 'no-second-arrival',
    'while the shipped build still does');
}

// ═══ 7. the decoy, the naive rule, and the step that breaks the tie ══════════
section('7. the decoy: what the naive rule reports, and what the step gives');
const decoyNums = (() => {
  const a = measured.get('refusal-floor-decoy').refused.candidates;
  const b = measured.get('refusal-floor-decoy-stepped-back').refused.candidates;
  const naive = a.slice().sort((p, q) => q.strength - p.strength)[0];
  const m = sos.matchPositions(a, b);
  const c = m.stepMs === null ? null : sos.speedFromStep(DECOY.step, m.stepMs);
  const frac = m.stepMs === null ? null : Math.hypot(0.01 / DECOY.step, m.sigmaStepMs / m.stepMs);
  return { a, b, naive, m, c, frac, naiveC: sos.speedFrom(2 * 3.000, naive.dtMs) };
})();
{
  const { a, naive, m, c, frac, naiveC } = decoyNums;
  const truth = [DECOY_DT.floor, DECOY_DT.ceil, DECOY_DT.wall].map((v) => v * 1000);
  for (let i = 0; i < 3; i++) {
    ok(near(a[i].dtMs, truth[i], 0.030),
      `decoy arrival ${i + 1} recovers ${truth[i].toFixed(5)} ms (got ${a[i].dtMs.toFixed(5)})`);
  }
  ok(naive.dtMs < truth[2] * 0.5,
    'the LOUDEST arrival in the decoy is the floor bounce, not the wall, which is the whole trap');
  ok(near(naiveC, 858.7, 0.3),
    `taking it reports ${naiveC.toFixed(1)} m/s at L = 3.000 m, which is the 859 the frontmatter prose rounds to`);
  ok(/reports 859 m\/s with complete\s+confidence/.test(md), 'and the prose rounds it that way and no further');
  ok(near(naiveC / C_REF, 2.5, 0.15),
    'which is about 150% high, with nothing in the output to say so',
    ((naiveC / C_REF - 1) * 100).toFixed(0) + '%');
  ok(m.fixed.length === 2 && m.movedBefore.length === 1 && m.movedAfter.length === 1,
    'stepping back leaves the floor and ceiling arrivals where they were and moves exactly one');
  ok(near(m.stepMs, (DECOY_DT.wallBack - DECOY_DT.wall) * 1000, 0.030),
    `the moved arrival moved by ${((DECOY_DT.wallBack - DECOY_DT.wall) * 1000).toFixed(5)} ms (got ${m.stepMs.toFixed(5)})`);
  ok(near(c, C_REF, c * frac * 3),
    `and the step alone gives c = ${c.toFixed(2)} m/s, inside its own interval of the ${C_REF.toFixed(2)} m/s it was built from`,
    `+/- ${(c * frac).toFixed(2)}`);
  ok(m.fixed.every((p) => p.gapMs < 0.030),
    'the two unmoved arrivals really did not move, by less than the matching tolerance');
}

// ═══ 7b. the offset pair: the estimator right, the answer wrong, nothing refusing ══
section('7b. the recordings where c = 2L/dt is wrong and no gate fires');
{
  const near5 = (a, b) => Math.abs(a - b) <= 1e-5;
  const specNear = SPECIMENS.find((s) => s.id === 'offset-clap-in-front');
  const specBack = SPECIMENS.find((s) => s.id === 'offset-clap-stepped-back');
  const rNear = measured.get('offset-clap-in-front');
  const rBack = measured.get('offset-clap-stepped-back');

  // 1. The estimator is not the thing that goes wrong here, and that is the point: it recovers
  //    a gap it was never told, on a recording as clean as the anchor's.
  ok(!rNear.refused && near(rNear.value, specNear.truthMs, 0.050),
    `the offset recording's gap comes back as ${rNear.refused ? 'a refusal' : rNear.value.toFixed(5)} ms against the ${specNear.truthMs.toFixed(5)} it was built with`);
  ok(!rBack.refused && near(rBack.value, specBack.truthMs, 0.050),
    `and the stepped-back one as ${rBack.refused ? 'a refusal' : rBack.value.toFixed(5)} against ${specBack.truthMs.toFixed(5)}`);
  ok(!rNear.refused && Math.abs(rNear.value - specNear.truthMs) * 1000 < 4 * rNear.uncertainty * 1000,
    `the estimator's miss on it (${((rNear.value - specNear.truthMs) * 1000).toFixed(2)} us) is inside a few times its own stated interval, so nothing about the estimator is what fails here`);

  // 2. The truths the page's own instrument.js carries are the generator's, rounded to five
  //    decimal places. 1.9 ns of rounding against an interval of about 6000 ns. If a literal on
  //    the page ever drifts from the geometry, this is where it dies.
  const litNear = /id: 'offset-clap-in-front', L: ([\d.]+), truth: ([\d.]+)/.exec(instrumentJs);
  const litBack = /id: 'offset-clap-stepped-back', L: ([\d.]+), truth: ([\d.]+)/.exec(instrumentJs);
  ok(!!litNear && !!litBack, 'the page declares both offset recordings with a wall distance and a truth');
  ok(!!litNear && near5(Number(litNear[2]), specNear.truthMs) && Number(litNear[1]) === OFFSET.lengthM,
    `and the near one's literals (${litNear ? litNear[2] : '?'} ms at ${litNear ? litNear[1] : '?'} m) are the generator's geometry to five decimal places`);
  ok(!!litBack && near5(Number(litBack[2]), specBack.truthMs) && Number(litBack[1]) === OFFSET.lengthBackM,
    `and the stepped-back one's (${litBack ? litBack[2] : '?'} ms at ${litBack ? litBack[1] : '?'} m) too`);
  ok(near(specNear.truthMs, (2 * OFFSET.lengthM - 2 * OFFSET.offsetM) / C_REF * 1000, 1e-9),
    'the generator built that gap from (2L - 2x)/c and not from anything else');

  // 3. THE FINDING THIS SPECIMEN EXISTS FOR. c = 2L/dt on a clean recording made 10 cm in front
  //    is 3.4% high, it is inside every band this page checks, and no gate refuses it.
  const cNaive = sos.speedFrom(2 * OFFSET.lengthM, rNear.value);
  const bias = sos.sourceOffsetBias(OFFSET.lengthM, OFFSET.offsetM);
  ok(near(cNaive / C_REF - 1, bias.fracC, 0.001),
    `2L/dt reads ${((cNaive / C_REF - 1) * 100).toFixed(2)}% fast, which is the L/(L-x) = ${(bias.fracC * 100).toFixed(2)}% the page states`);
  const band = sos.habitableBand();
  ok(cNaive > sos.PLAUSIBLE.lo && cNaive < sos.PLAUSIBLE.hi && cNaive > band.lo && cNaive < band.hi,
    `and ${cNaive.toFixed(2)} m/s sits inside both the plausible band and the habitable one (${band.lo.toFixed(1)} to ${band.hi.toFixed(1)}), so nothing on the page refuses it`);
  const bud = sos.budget({ lengthM: OFFSET.lengthM, sigmaLM: 0.01, dtMs: rNear.value, sigmaDtMs: rNear.uncertainty });
  ok(Math.abs(cNaive - C_REF) / bud.sigmaC > 5,
    `the error is ${(Math.abs(cNaive - C_REF) / bud.sigmaC).toFixed(1)} times the interval printed beside it, which is what makes it a bias and not scatter`);
  const tWrong = sos.temperatureFromSpeed(cNaive, { rhPct: 0 });
  ok(tWrong > 38 && tWrong < 42,
    `a room built at 20.00 C reads ${tWrong.toFixed(1)} C, and it reads it with an error bar`);

  // 4. And the repair, on the same two files: the offset is identical in both, so it cancels.
  const stepMs = rBack.value - rNear.value;
  const sigmaStep = Math.hypot(rNear.uncertainty, rBack.uncertainty);
  const cStep = sos.speedFromStep(OFFSET.step, stepMs);
  const fracStep = Math.hypot(0.01 / OFFSET.step, sigmaStep / stepMs);
  ok(near(cStep, C_REF, cStep * fracStep * 3),
    `the step method on the same wrong hands gives ${cStep.toFixed(2)} +/- ${(cStep * fracStep).toFixed(2)} m/s against the ${C_REF.toFixed(2)} it was built from`);
  ok(Math.abs(cStep - C_REF) < Math.abs(cNaive - C_REF) / 10,
    `which is ${(Math.abs(cNaive - C_REF) / Math.abs(cStep - C_REF)).toFixed(0)} times closer than the single-position answer, so the cancellation is shown and not asserted`);

  // 5. The demonstration is on the page, through the same one estimator, and the page says how
  //    many recordings it ships.
  ok(html.includes('id="offset-out"') && /OFFSET_SPECS/.test(instrumentJs),
    'the page renders the pair rather than only describing them');
  ok(/SPECIMENS\.concat\(REFUSALS, OFFSET_SPECS\)/.test(instrumentJs),
    'and loads them through the same loop, and therefore the same estimate(), as every other recording');
  ok(html.includes('Nine recordings ship with this page') && SPECIMENS.length === 9,
    `the page says how many recordings ship with it, and ${SPECIMENS.length} do`);
}

// ═══ 8. the air: Cramer, re-implemented, checked against two other constructions ══
section('8. the physics the speed is converted through');
const phys = (() => {
  const c0 = sos.speedOfSound({ tempC: 0, rhPct: 0 });
  const c20 = sos.speedOfSound({ tempC: 20, rhPct: 0 });
  const h = 1e-4;
  const slope = (sos.speedOfSound({ tempC: 20 + h, rhPct: 0 }) - sos.speedOfSound({ tempC: 20 - h, rhPct: 0 })) / (2 * h);
  const hum = sos.speedOfSound({ tempC: 20, rhPct: 100 }) - sos.speedOfSound({ tempC: 20, rhPct: 0 });
  const humK = sos.temperatureFromSpeed(sos.speedOfSound({ tempC: 20, rhPct: 100 }), { rhPct: 0 }) - 20;
  const ideal = (t) => Math.sqrt(1.4 * sos.R_GAS * (t + 273.15) / 0.0289645);
  const linear = (t) => 331.3 + 0.606 * t;
  let maxSpread = 0, spread20 = 0;
  for (const t of [0, 10, 20, 30]) {
    const cr = sos.speedOfSound({ tempC: t, rhPct: 0 });
    const s = (Math.max(cr, ideal(t), linear(t)) - Math.min(cr, ideal(t), linear(t))) / cr * 100;
    if (s > maxSpread) maxSpread = s;
    if (t === 20) spread20 = s;
  }
  // A transposed digit in the leading temperature coefficient, and a wrong last digit.
  const A = sos.CRAMER_COEFFS;
  const evalDry = (B, t) => B[0] + B[1] * t + B[2] * t * t + (B[6] + B[7] * t + B[8] * t * t) * 101325 +
    B[13] * 101325 * 101325 + (B[9] + B[10] * t + B[11] * t * t) * 0.0004 + B[14] * 0.0004 * 0.0004;
  const typo = A.slice(); typo[1] = 0.630055;
  const lastDigit = A.slice(); lastDigit[1] = 0.60305;
  return { c0, c20, slope, hum, humK, ideal, linear, maxSpread, spread20,
    typoDelta: evalDry(typo, 20) - c20, lastDigitDelta: evalDry(lastDigit, 20) - c20 };
})();
{
  const { c0, c20, slope, hum, humK, maxSpread, spread20, typoDelta, lastDigitDelta } = phys;
  ok(near(c0, 331.4477, 0.0002), `c(0 C, dry, 101.325 kPa, 400 ppm) = ${c0.toFixed(4)} m/s`);
  ok(near(c20, 343.3595, 0.0002), `c(20 C, same) = ${c20.toFixed(4)} m/s`);
  ok(near(sos.temperatureFromSpeed(c20, { rhPct: 0 }), 20, 1e-6),
    'the bisection inverts its own forward equation back to the temperature it started from');
  ok(near(slope, 0.5844, 0.0002), `dc/dT at 20 C, dry, by central difference = ${slope.toFixed(4)} m/s per K`);
  ok(near(hum, 1.2538, 0.001), `0 to 100% RH at 20 C moves c by +${hum.toFixed(4)} m/s`);
  ok(near(humK, 2.15, 0.01), `which reads as +${humK.toFixed(2)} K of apparent temperature`);
  ok(near(phys.ideal(20), 343.2362, 0.001) && near(phys.linear(20), 343.42, 0.001),
    'the two independent constructions at 20 C are 343.2362 (ideal gas) and 343.4200 (the linear form)');
  ok(near(maxSpread, 0.13, 0.01),
    `the three constructions never differ by more than ${maxSpread.toFixed(2)} percent over 0 to 30 C`);
  ok(near(spread20, 0.054, 0.002), `and by ${spread20.toFixed(3)} percent at 20 C`);
  ok(near(typoDelta, 0.54, 0.005),
    `a transposed digit in the leading temperature coefficient moves c by ${typoDelta.toFixed(4)} m/s`);
  ok(Math.abs(typoDelta) > 2.5 * (spread20 / 100 * c20),
    'which is more than twice the entire spread between the constructions, so the cross-check has teeth');
  ok(near(Math.abs(lastDigitDelta), 0.0001, 0.00005),
    `while a wrong final digit in the same coefficient moves it by only ${Math.abs(lastDigitDelta).toFixed(4)} m/s, which it would not catch`);
  ok(near(c0 - 331.29, 0.1577, 0.001),
    `Wong's 331.29 m/s and this implementation of Cramer differ by ${(c0 - 331.29).toFixed(4)} m/s`);
  ok(near((c0 - 331.29) / slope, 0.27, 0.01),
    `which is worth ${((c0 - 331.29) / slope).toFixed(2)} K of apparent temperature`);
  ok(sos.temperatureFromSpeed(1000, { rhPct: 0 }) === null,
    'and the inversion returns nothing rather than a number for a speed no air has');
}

// ═══ 9. the lever, the suppressed zero, and the error budget ═════════════════
section('9. the lever, and where the error bar comes from');
const lever = (() => {
  const c0 = sos.speedOfSound({ tempC: 20, rhPct: 0 });
  const at = (pct) => {
    const T = sos.temperatureFromSpeed(c0 * (1 + pct / 100), { rhPct: 0 });
    return { dK: T - 20, pctOfReading: (T - 20) / 20 * 100, pctKelvin: (T - 20) / 293.15 * 100 };
  };
  return { half: at(0.5), one: at(1.0), two: at(2.0) };
})();
{
  ok(near(lever.half.dK, 2.95, 0.01), `0.5% in c costs ${lever.half.dK.toFixed(2)} K`);
  ok(near(lever.one.dK, 5.91, 0.01), `1.0% in c costs ${lever.one.dK.toFixed(2)} K`);
  ok(near(lever.two.dK, 11.88, 0.01), `2.0% in c costs ${lever.two.dK.toFixed(2)} K`);
  ok(near(lever.one.pctKelvin, 2.015, 0.01),
    `and 1.0% in c is ${lever.one.pctKelvin.toFixed(3)}% in kelvin, the factor of two the square root puts there`);
  ok(near(lever.one.pctOfReading, 29.54, 0.05),
    `which is ${lever.one.pctOfReading.toFixed(1)}% of a 20 C reading once the suppressed zero has multiplied it again`);

  const dt = measured.get('refusal-floor-decoy').refused.candidates[2].dtMs;
  const sdt = measured.get('refusal-floor-decoy').refused.candidates[2].sigmaMs;
  const b = sos.budget({ lengthM: 3.000, sigmaLM: 0.01, dtMs: dt, sigmaDtMs: sdt });
  ok(near(b.shareTape * 100, 99, 0.5),
    `with a 1 cm tape at 3 m the tape carries ${(b.shareTape * 100).toFixed(1)}% of the variance, which rounds to the 99 the page prints`);
  ok(b.shareMic * 100 < 1,
    `and the microphone ${(b.shareMic * 100).toFixed(2)}%, which meets the "under 1 percent" the page prints`);
  ok(near(0.01 / 3.000 * 1e6, 3333, 1), 'a 1 cm tape on a 3 m wall is 3333 ppm on its own');
  // Where the two terms carry equal variance: sigmaL/L = sigmaDt/dt. The page says "under a
  // millimetre" and this is the number that has to be under one for that to be true.
  const evenMm = 3.000 * (sdt / dt) * 1000;
  ok(near(evenMm, 0.87, 0.06),
    `the two terms carry equal variance at a tape uncertainty of ${evenMm.toFixed(2)} mm, which is the "under a millimetre" the page prints`);
  const mm = sos.budget({ lengthM: 3.000, sigmaLM: 0.001, dtMs: dt, sigmaDtMs: sdt });
  ok(mm.shareTape < 0.65 && mm.shareMic > 0.35,
    `so at a flat millimetre the tape is down to ${(mm.shareTape * 100).toFixed(0)}% against the microphone's ${(mm.shareMic * 100).toFixed(0)}%, which is the ladder's "the tape has stopped being the whole story"`);
  ok(near(sdt / dt * 1e6, 288, 8), `and the timing on a clean clap is about ${(sdt / dt * 1e6).toFixed(0)} ppm, the 290 the page prints`);
  ok(near(b.sigmaC / phys.slope, 1.96, 0.15),
    `so the temperature interval is about ${(b.sigmaC / phys.slope).toFixed(2)} K`);
  // The Cramer/Wong fight, sized against the interval the reader actually gets. The prose says
  // "roughly seven times smaller", and this is the assertion that tests the number the prose
  // names rather than a different one printed beside it.
  const wongGap = phys.c0 - 331.29;
  ok(near(b.sigmaC / wongGap, 7.3, 0.3),
    `the Cramer/Wong disagreement is ${(b.sigmaC / wongGap).toFixed(2)} times smaller than a 1 cm tape's own interval`);
  ok(/roughly seven times smaller than the interval a 1 cm tape/.test(html.replace(/\s+/g, ' ')),
    'and the prose beside it says seven rather than a number nothing computes');

  // THE TERM THAT IS NOT IN THE QUADRATURE SUM. c = 2L/dt is exact only when the source and
  // the receiver are in the same place, and the page's instructions, its offset table and its
  // dek all now depend on these three numbers being what they are.
  const off = sos.sourceOffsetBias(3.000, 0.10);
  ok(near(off.fracC * 100, 3.45, 0.02),
    `clapping 10 cm in front of the device at a 3 m wall reads ${(off.fracC * 100).toFixed(2)}% fast, the 3.4 percent the page states`);
  ok(near((phys.c20 * off.factor - phys.c20) / b.sigmaC, 10.3, 0.4),
    `which is ${((phys.c20 * off.factor - phys.c20) / b.sigmaC).toFixed(1)} times the WHOLE interval a 1 cm tape gives, the "ten times" the page states`);
  const offT = sos.temperatureFromSpeed(phys.c20 * off.factor, { rhPct: 0 });
  ok(offT !== null && offT - 20 > 20 && near(offT, 40.67, 0.1),
    `and reads a genuinely 20.00 C room as ${offT.toFixed(1)} C, which is the "more than twenty kelvin too warm" the page states`);
  const bandOff = sos.habitableBand();
  ok(phys.c20 * off.factor < bandOff.hi,
    'while landing inside the habitable band, so nothing on the page refuses it, which is the reason it is called out in the instructions');
  ok(sos.sourceOffsetBias(3.000, 3.000) === null && sos.sourceOffsetBias(3.000, -1) === null,
    'and the bias returns nothing rather than a number for an offset at or past the wall');
  const drought = Math.pow(1 / phys.c20, 2) * 1e6;
  ok(drought < 9 && drought > 8,
    `a 1 m/s draught leaves a residual of order ${drought.toFixed(1)} ppm, which the page states as "under nine"`);
}

// ═══ 9b. what the reconciliation added, recomputed ═══════════════════════════
// A blinded re-derivation of this page's own claim, run without ever seeing the build, found
// one arithmetic inconsistency, one sentence describing a refusal this page does not have, and
// four assumptions that were live on the page without being named. Every number those repairs
// print is recomputed here, because a repair nobody re-measured is the defect moved.
section('9b. the repairs the blinded re-derivation forced');
{
  const dc = (t, rh) => (sos.speedOfSound({ tempC: t + 1e-4, rhPct: rh }) -
                         sos.speedOfSound({ tempC: t - 1e-4, rhPct: rh })) / 2e-4;
  // 1. THE SLOPE THE ERROR BUDGET DIVIDES BY. The split table converts m/s to kelvin with the
  //    DRY slope while the temperature panel inverts at the reader's own humidity, whose
  //    default is 50%. The two differ, so the page now says which one it used and what the
  //    other would have done. Both halves of that sentence are checked, including its
  //    direction: the dry slope is the smaller one, so it gives the WIDER interval, which is
  //    the only reason using it is defensible.
  const dry20 = dc(20, 0), wet20 = dc(20, 50);
  ok(near(dry20, 0.5844, 0.0002) && near(wet20, 0.6246, 0.0002),
    `dc/dT at 20 C is ${dry20.toFixed(4)} m/s per K dry and ${wet20.toFixed(4)} at 50% RH, the two the split table now prints`);
  ok(dry20 < wet20, 'the dry slope is the smaller one, so the interval this page states is the wider of the two');
  const narrower = (1 - dry20 / wet20) * 100;
  ok(near(narrower, 6.4, 0.15),
    `every kelvin in that column would be ${narrower.toFixed(1)}% narrower at 50% RH, which is what the page says it would be`);
  ok(/slope of Cramer’s equation at 20 C in DRY air/.test(instrumentJs),
    'and the page names the humidity of the slope rather than leaving it to be inferred');

  // 2. THE LAST COLUMN OF THE OFFSET TABLE. It used to say "refused, outside the habitable
  //    band", and this page has no such refusal: the habitable band is printed in a message,
  //    never gated on. What actually stops the 30 cm row is that Cramer's equation has no
  //    solution that fast, which is a different sentence and a weaker one. Both are checked
  //    here against the live path's own two gates, in order.
  const cDry20 = sos.speedOfSound({ tempC: 20, rhPct: 0 });
  const at = (cm) => {
    const o = sos.sourceOffsetBias(3.000, cm / 100);
    const c = cDry20 * o.factor;
    return { c, inBand: c >= sos.PLAUSIBLE.lo && c <= sos.PLAUSIBLE.hi,
             T: sos.temperatureFromSpeed(c, { rhPct: 0 }) };
  };
  const ten = at(10), thirty = at(30);
  ok(ten.inBand && ten.T !== null && near(ten.T, 40.67, 0.1),
    `a 10 cm offset reads ${ten.T.toFixed(1)} C and passes both gates, so the page reports it`);
  ok(thirty.inBand && thirty.T === null,
    `a 30 cm offset reads ${thirty.c.toFixed(1)} m/s, which is INSIDE the band this page gates on, and gets no temperature only because the inversion finds no solution`);
  ok(thirty.c > sos.habitableBand().hi,
    'even though it is outside the habitable band, which the page prints and never refuses on');
  ok(!/refused, outside the habitable band/.test(instrumentJs),
    'so the table no longer claims a refusal this page does not have');
  ok(/Cramer’s equation that has no solution that fast/.test(instrumentJs),
    'and says what actually stops it instead');

  // 3. THE SAMPLE CLOCK, the one calibration this page cannot do. dt is a count of samples
  //    over a rate the browser reports and nothing here checks.
  const dt0 = measured.get('refusal-floor-decoy').refused.candidates[2].dtMs;
  const sd0 = measured.get('refusal-floor-decoy').refused.candidates[2].sigmaMs;
  const tape0 = sos.budget({ lengthM: 3.000, sigmaLM: 0.01, dtMs: dt0, sigmaDtMs: sd0 }).sigmaC;
  const base50 = sos.speedOfSound({ tempC: 20, rhPct: 50 });
  const clock = base50 * 100e-6;
  ok(near(clock, 0.0344, 0.0002), `a 100 ppm clock error is ${clock.toFixed(4)} m/s`);
  ok(near(clock / wet20, 0.055, 0.002), `which is ${(clock / wet20).toFixed(3)} K`);
  ok(Math.round(tape0 / clock) === 33,
    `and 1/${Math.round(tape0 / clock)} of the interval a 1 cm tape gives, which is what the choices table prints`);
  ok(/taken as exact/.test(instrumentJs),
    'and the table says the rate is taken as exact rather than implying it was checked');
  ok(/dtMs: \(pos - p0\) \/ fs \* 1000/.test(sosJs) && /const fs = payload && payload\.sampleRate/.test(sosJs),
    'which is what the estimator does: the gap is a sample count over the rate the payload carried, and that is the only place the rate enters');

  // 4. THE LOUDEST ARRIVAL IS ASSUMED TO BE THE DIRECT ONE. Unnamed until now. The claim the
  //    new row makes is an equality, not a hedge: a hard surface d nearer than the wall that
  //    answers louder costs exactly the L/(L-d) that clapping d in front does.
  ok(/which arrival is your clap/.test(instrumentJs) && /the loudest one/.test(instrumentJs),
    'the free choices name which arrival the estimator takes to be the clap');
  const i0kIsArgmax = /const i0k = argmaxIn\(env, 0, env\.length - 1\);/.test(sosJs);
  ok(i0kIsArgmax, 'and that is what the code does: the direct arrival is the argmax of the envelope');
  ok(near(sos.sourceOffsetBias(3.000, 0.10).fracC * 100, 3.45, 0.02),
    'so a surface 0.10 m nearer costs the same 3.45% the row states');

  // 5. THE TWO KNOBS A READER CAN TURN AFTER THE MEASUREMENT IS LOCKED, both now printed as
  //    spans rather than as points. The humidity one is the calibration control this page
  //    forbids everywhere else, so what it can buy has to be visible from wherever it sits.
  // TWO KELVIN FIGURES THAT ARE NOT THE SAME NUMBER, and the page used to print the larger one
  // as if it were the smaller. 2.15 K is what a saturated room read as dry is wrong BY: a speed
  // difference over the DRY slope. What the slider can drag a fixed reading across is less,
  // because the inversion at high humidity runs up a steeper slope. Both are checked, and so is
  // the inequality between them, which is the thing that was wrong.
  const cLive = sos.speedFrom(6.000, dt0);
  const tD = sos.temperatureFromSpeed(cLive, { rhPct: 0 });
  const tW = sos.temperatureFromSpeed(cLive, { rhPct: 100 });
  const wetRoomReadDry = sos.temperatureFromSpeed(sos.speedOfSound({ tempC: 20, rhPct: 100 }), { rhPct: 0 }) - 20;
  ok(near(wetRoomReadDry, 2.15, 0.01),
    `a saturated room at 20 C read as dry is ${wetRoomReadDry.toFixed(2)} K too warm, the 2.15 the page states`);
  ok(tD !== null && tW !== null && near(tD - tW, 1.86, 0.03),
    `but dragging the slider across one fixed measurement moves it by ${(tD - tW).toFixed(2)} K, which is less`);
  ok(tD - tW < wetRoomReadDry,
    'and the page now prints the smaller number where it describes the knob rather than the larger one');
  ok(/Dragging this slider from end to end on one fixed measurement is a smaller move/.test(instrumentJs),
    'in those words, computed rather than quoted');
  const band9b = sos.habitableBand();
  const cover = (cm) => {
    const b = sos.budget({ lengthM: 3.000, sigmaLM: cm / 100, dtMs: dt0, sigmaDtMs: sd0 });
    return 2 * (b.sigmaC / dc(20, 50)) / (band9b.hiC - band9b.loC) * 100;
  };
  ok(near(cover(1), 5.6, 0.5), `at the default 1 cm the interval covers ${cover(1).toFixed(0)}% of the habitable range`);
  ok(cover(20) > 100,
    `and the distance uncertainty has no cap, so at 20 cm it covers ${cover(20).toFixed(0)}% of it, which the page now says out loud rather than leaving the reader to notice`);
  ok(/of the whole ' \+ band\.loC/.test(instrumentJs),
    'and that share is computed from the band rather than typed in');

  // 6. THE GAS PANEL PRINTS KELVIN. The celsius figure for helium reads like a typo; the
  //    absolute one is the one that means something, and the page's prose now points at the
  //    ratio between the two rather than at an outside fact about liquefaction.
  const heK = sos.idealTempC(cDry20, 'helium') + 273.15;
  const airK = sos.idealTempC(cDry20, 'air') + 273.15;
  ok(near(heK, 34.1, 0.15), `read as helium, ${cDry20.toFixed(2)} m/s is ${heK.toFixed(1)} K`);
  ok(near(airK / heK, 8.6, 0.3),
    `which is 1/${(airK / heK).toFixed(1)} of the same speed read as air, the "about a ninth" the page states`);
  ok(/= ' \+ \(T \+ 273\.15\)\.toFixed\(1\) \+ ' K'/.test(instrumentJs),
    'and the panel prints that kelvin figure rather than the page asserting it');
}

// ═══ 10. the gas assumption, and the plausibility band ═══════════════════════
section('10. the gas you assumed, and the band outside which no temperature is reported');
{
  const c = phys.c20;
  ok(near(sos.idealTempC(c, 'air'), 20.2, 0.2),
    `read as air, ${c.toFixed(2)} m/s is ${sos.idealTempC(c, 'air').toFixed(1)} C`);
  ok(sos.idealTempC(c, 'helium') < -200,
    `read as helium it is ${sos.idealTempC(c, 'helium').toFixed(1)} C, because sound runs about three times faster in helium`);
  ok(near(sos.idealSpeed(20, 'helium') / sos.idealSpeed(20, 'air'), 2.93, 0.02),
    'and that ratio really is about three');
  ok(sos.idealTempC(c, 'co2') > 200, `read as carbon dioxide it is ${sos.idealTempC(c, 'co2').toFixed(1)} C`);
  const band = sos.habitableBand();
  ok(near(band.lo, 318.96, 0.05) && near(band.hi, 357.57, 0.05),
    `air between ${band.loC} and ${band.hiC} C spans ${band.lo.toFixed(1)} to ${band.hi.toFixed(1)} m/s`);
  ok(sos.PLAUSIBLE.lo < band.lo && sos.PLAUSIBLE.hi > band.hi,
    'and the band the page refuses outside of is wider than that, so it refuses only the absurd');
  const halfC = sos.speedFrom(6.000, measured.get('control-half-delay').value);
  ok(halfC > sos.PLAUSIBLE.hi,
    `the halved control at L = 3.000 m implies ${halfC.toFixed(1)} m/s, outside the band, so no temperature is reported for it`);
}

// ═══ 11. the page's own surface ══════════════════════════════════════════════
section('11. what the page actually says');
{
  ok(html.includes('</body>') && html.includes('</html>'), 'the closing tags are present');
  // The site's placard generator inserts before the LAST closing body tag in the file. This
  // page once ended with a comment that spelled both closing tags out as a note to itself, so
  // the placard was inserted INSIDE that comment, truncating it and leaving the tail of the
  // sentence rendering as visible prose under the placard on the live page. Two assertions,
  // because the first one alone would pass on a page that simply lost its placard.
  ok((html.match(/<\/body>/g) || []).length === 1,
    'the document spells its closing body tag exactly once, so the placard generator cannot insert into a comment',
    String((html.match(/<\/body>/g) || []).length));
  const endMark = '<!--aw-checkkind:end-->';
  const afterPlacard = html.slice(html.indexOf(endMark) + endMark.length);
  // The site's chrome generators append their own delimited blocks (aw-nearby, aw-sitebar,
  // aw-wayout, aw-plain) after the placard on every shipped page, so a test for "the bytes
  // after the placard are only closing tags" measures the build order rather than this page.
  // The CLAIM is that no stray prose renders under the placard, and a generator's own block
  // between its own start and end markers is not stray prose. So account for those, and hold
  // the claim against whatever is left, which is where a truncated comment's tail would land.
  // Also drop same-origin script and style tags: the claim is about PROSE rendering under the
  // placard, and neither renders anything. One of these (/media/home-banner.js) is appended by
  // a generator outside its own markers, so marker-stripping alone does not reach it.
  const unaccounted = afterPlacard
    .replace(/<!--aw-[a-z]+:start-->[\s\S]*?<!--aw-[a-z]+:end-->/g, '')
    .replace(/<script[^>]*src="\/(media|_kit)\/[^"]*"[^>]*>\s*<\/script>/g, '')
    .replace(/<style[^>]*>[\s\S]*?<\/style>/g, '')
    .replace(/<\/(body|html)>/g, '')
    .trim();
  ok(html.includes(endMark) && unaccounted === '',
    'and nothing but the site\'s own chrome blocks follows the check placard, so no stray prose renders under it',
    JSON.stringify(unaccounted.slice(0, 90)));
  const noComments = html.replace(/<!--[\s\S]*?-->/g, '');
  ok((noComments.match(/<script\b/g) || []).length === (noComments.match(/<\/script>/g) || []).length,
    'every script tag is closed');
  // The claim, not the layout: the site's chrome generators append their own <style> and
  // <script> to every shipped page, so a fixed script inventory is a check that breaks on
  // somebody else's commit. What matters is that the page's own five are all there.
  const wanted = ['/_kit/anchor.js', '/_kit/dsp.js', '/_kit/sensors.js', './sos.js', './instrument.js'];
  ok(wanted.every((w) => html.includes(`<script src="${w}"></script>`)),
    'the page loads all five of its own scripts',
    wanted.filter((w) => !html.includes(`<script src="${w}"></script>`)).join(' '));
  ok(html.includes('application/ld+json'), 'and carries a JSON-LD block');
  const external = [...html.matchAll(/(?:src|href)="(https?:\/\/[^"]+)"/g)].map((m) => m[1])
    .filter((u) => !/^https:\/\/artwaste\.land/.test(u));
  const inLinkOrScript = [...html.matchAll(/<(?:link|script|img)\b[^>]*(?:src|href)="(https?:\/\/[^"]+)"/g)]
    .map((m) => m[1]).filter((u) => !/^https:\/\/artwaste\.land/.test(u));
  ok(inLinkOrScript.length === 0, 'the page makes zero third-party requests', inLinkOrScript.join(' '));
  ok(external.length > 0, 'while still citing its sources as links a reader can follow');
  // Scoped to the page's own content: everything after </main> is appended by the site's
  // chrome generators and is not this page's prose to police.
  const mine = html.slice(0, html.indexOf('</main>'));
  ok(!mine.includes(EM), 'and carries no em dashes of its own');
  ok(html.includes('<h1>The Temperature in the Second Arrival</h1>'), 'the H1 is the poetic title');
  ok(html.includes('<title>Measure the Speed of Sound in Your Own Room With One Clap</title>'),
    'and the title tag is the searcher’s name for it');
  const ld = JSON.parse((html.match(/<script type="application\/ld\+json">([\s\S]*?)<\/script>/) || [])[1]);
  ok(ld.headline === 'The Temperature in the Second Arrival' &&
     ld.name === 'Measure the Speed of Sound in Your Own Room With One Clap',
    'the JSON-LD carries the poetic title as headline and the search title as name');
  ok(ld.url === 'https://artwaste.land/strata/speed-of-sound-room/', 'and the canonical URL');

  // Verbatim quotations, character for character against the sources.
  const NIST = 'To date, the most accurate values of k<sub>B</sub> have been obtained by\n      acoustic thermometry, which relies on the fact that the speed of sound in a gas is\n      directly dependent on its temperature.';
  ok(html.includes(NIST), 'the NIST sentence is quoted verbatim, line breaks aside');
  ok(html.includes('1.380649 x 10<sup>-23</sup> J K<sup>-1</sup>'),
    'with the exact defined value of the Boltzmann constant');
  ok(html.includes('may be realized at the level of\n    0.015 K'),
    'and the 2025 paper’s own conclusion is quoted rather than paraphrased into something stronger');
  ok(html.includes('1.3806484(28)') && html.includes('2.0 x 10<sup>-6</sup>'),
    'the acoustic gas thermometry figure on the ladder is the one its paper reports');

  // Numbers in the prose, against the recomputation above.
  const claims = [
    ['17.49270 ms', 'the anchor delay'],
    ['&plusmn;0.050 ms', 'the tolerance'],
    ['about 5.9 microseconds', 'the estimator’s own stated interval'],
    ['17.0 microseconds', 'the largest Monte Carlo error'],
    ['240 independent noise draws', 'the size of the Monte Carlo'],
    ['about 99 percent of it is the', 'the tape’s share of the variance in the dek'],
    ['under 1 percent is the microphone', 'and the microphone’s'],
    ['is about 290', 'the timing in ppm on the shipped room recording'],
    ['more than twenty kelvin too warm', 'what a 10 cm source offset reads as'],
    ['331.29 m/s', 'Wong’s contested value'],
    ['25 ppm', 'the 2025 model’s stated uncertainty'],
    ['300 ppm', 'Cramer’s stated overall uncertainty'],
    ['0 to 30 C', 'Cramer’s stated validity range'],
    ['0.54 m/s', 'the coefficient typo sensitivity'],
    ['0.0001 m/s', 'and the sensitivity it does not have'],
    ['3333 parts per million', 'a 1 cm tape at 3 m'],
    ['1.25 m/s', 'the humidity span'],
    ['0.13 percent', 'the spread between the three constructions'],
    ['0.054 percent', 'and the spread at 20 C'],
  ];
  const flat = html.replace(/\s+/g, ' ');
  for (const [needle, what] of claims) ok(flat.includes(needle), `the page prints ${what} (${needle})`);
  ok(near(phys.hum, 1.25, 0.005), 'and the humidity span really is 1.25 m/s to the digits printed');

  // A path printed on the page is an instruction, not prose.
  const cmds = [...html.matchAll(/node (research\/[\w/.-]+\.mjs|scripts\/[\w/.-]+\.mjs)/g)].map((m) => m[1]);
  ok(cmds.length >= 2 && cmds.every((c) => existsSync(join(ROOT, c))),
    'every command the page tells a reader to run resolves to a file that exists',
    cmds.filter((c) => !existsSync(join(ROOT, c))).join(' ') || cmds.join(' '));

  // The condition under which c = 2L/dt is exact has to be where a reader who is about to clap
  // will meet it, not only in the dek and not only in a comment.
  ok(html.includes('exact only if the sound is made where it is heard'),
    'the equation block states the condition under which c = 2L/dt is exact');
  ok(/hands as close to the device as you can get\s*them/.test(html),
    'and the instructions say where to put your hands before they say to clap');
  // The ladder's three bars share one axis, uncertainty in c. Feng's 2.0 ppm is on k_B, which
  // comes out of c squared, so putting it on this axis unconverted would be a category mix
  // that understates the gap by two. The conversion is in the code and the bar is the halved
  // one; this checks both rather than the sentence beside them.
  ok(/AGT_PPM_C = AGT_PPM_KB \/ 2/.test(instrumentJs) && /ppm: AGT_PPM_C/.test(instrumentJs),
    'the ladder halves the acoustic thermometry rung in code, so the bar it draws is on the axis it names');
  ok(/2\.0 ppm on k/.test(instrumentJs) && /at most 1\.0 ppm on c/.test(instrumentJs),
    'and says in the readout that 2.0 ppm is on k_B and at most 1.0 ppm on the speed it came from');

  // The refusal path is on the page, not only in the code.
  ok(html.includes('Four recordings where the honest answer is no answer'),
    'the refusal recordings have their own section rather than a footnote');
  ok(/proven\s*\n?\s*only against injected signals/.test(html),
    'and the page says plainly that the live path has been proven only against injected signals');
  ok(html.includes('343 m/s is not the speed of sound'),
    'and refuses the folk constant explicitly rather than quietly using it');
  // Circularity is closed by the interface, not by a promise, so the interface is what gets
  // checked: an inventory of every control on the page. A "known temperature" box, or a
  // calibrate-to-my-thermostat control, would have to appear here to exist at all.
  const controls = [...mine.matchAll(/<(?:input|select)\b[^>]*\bid="([^"]+)"/g)].map((m) => m[1]).sort();
  const expected = ['L', 'dL', 'gas-sel', 'lever', 'rh', 'secs', 'sigma-dL', 'sigmaL', 'tape', 'use-click'].sort();
  ok(JSON.stringify(controls) === JSON.stringify(expected),
    'the page carries exactly ten controls and not one of them takes a temperature',
    controls.join(' '));
  ok(/id="temp-block" hidden/.test(html),
    'the temperature panel ships hidden, so a distance cannot be nudged while watching a temperature move');
  ok((instrumentJs.match(/showTemperature\(/g) || []).length === 4,
    'and it is revealed from exactly three places: locking an arrival, a matched step, and the humidity slider',
    String((instrumentJs.match(/showTemperature\(/g) || []).length));
}

// ═══ 12. the shareable surface, where the honesty leak lives ═════════════════
section('12. the dek, the plain card and the social tags');
{
  const fm = (md.match(/^---\r?\n([\s\S]*?)\r?\n---/) || [])[1] || '';
  const field = (k) => {
    const m = fm.match(new RegExp('^' + k + ':\\s*"([\\s\\S]*?)"\\s*$', 'm'));
    return m ? m[1] : '';
  };
  const dek = field('dek'), plain = field('plain'), seoTitle = field('seoTitle');
  ok(fm.length > 0, 'the frontmatter file exists and parses');
  ok(field('seam') === 'physical', 'the seam is physical, which is in the closed vocabulary');
  ok(plain.length > 0 && plain.length <= 420, `the plain card is within 420 characters (${plain.length})`);
  ok(plain.split(/(?<=[.!?])\s+/).filter((s) => s.trim()).length <= 3,
    'and within three sentences', String(plain.split(/(?<=[.!?])\s+/).filter((s) => s.trim()).length));
  ok(!dek.includes(EM) && !plain.includes(EM), 'neither carries an em dash');
  ok(seoTitle.length <= 62, `the seoTitle is short enough to survive a search result (${seoTitle.length})`);
  const rel = [...fm.matchAll(/^\s*-\s*to:\s*(\S+)/gm)].map((m) => m[1].replace(/['"]/g, ''));
  ok(rel.length >= 2 && rel.length <= 4, `there are ${rel.length} relates edges`);
  ok(rel.every((t) => existsSync(join(ROOT, 'src/content/strata', t + '.md'))),
    'and every relates target exists', rel.filter((t) => !existsSync(join(ROOT, 'src/content/strata', t + '.md'))).join(' '));

  const metaDesc = (html.match(/<meta name="description" content="([\s\S]*?)" \/>/) || [])[1] || '';
  const ogDesc = (html.match(/<meta property="og:description" content="([\s\S]*?)" \/>/) || [])[1] || '';
  const twDesc = (html.match(/<meta name="twitter:description" content="([\s\S]*?)" \/>/) || [])[1] || '';
  const surfaces = [['dek', dek], ['plain', plain], ['meta description', metaDesc],
                    ['og:description', ogDesc], ['twitter:description', twDesc],
                    ['JSON-LD description', ld_description(html)]];
  // THREE RULES, AND THE REASON THEY ARE THESE THREE.
  //
  // The predicate that used to sit here was /refus|cannot|only|assum|tape measure|does not/,
  // which the bare word "only" satisfies. Every honesty leak this page has actually shipped
  // sailed through it: a dek that stated c = 2L/dt with no mention of where the clap has to be
  // made, and a dek that asserted what happens "on a real room" on a page whose every
  // recording is synthesised. So the rules are now the specific claims the apparatus supports,
  // and they are self-tested below against sentences that break them.
  //
  //  1. It must name the refusal, because refusing is the page's main result.
  //  2. If it states c = 2L/dt at all, it must state the condition under which that is exact:
  //     the source and the receiver in the same place. Ten centimetres is 3.4% at a 3 m wall,
  //     ten times the whole interval a 1 cm tape gives, and nothing refuses it.
  //  3. It may not make a frequency claim about real rooms. No real room has been recorded.
  const namesRefusal = (t) => /refus/i.test(t);
  const overclaims = (t) => /\bexact(ly)? (temperature|degrees)\b|\bthermostat is wrong\b|\bprecise thermometer\b/i.test(t);
  const statesRule = (t) => /twice (the|your)[^.]*?(distance|wall)[^.]*?(divided by|over) that gap|gap between th(e|ose) two arrivals gives the speed/i.test(t);
  const hasCondition = (t) => /where the microphone is|where it is heard|hands at the microphone/i.test(t);
  const realRoomClaim = (t) => /\b(on|in) a real room\b/i.test(t) && !/shipped|synthes/i.test(t);
  const surfaceOk = (t) => t.length > 40 && namesRefusal(t) && !overclaims(t) &&
    (!statesRule(t) || hasCondition(t)) && !realRoomClaim(t);
  for (const [name, text] of surfaces) {
    const t = String(text || '');
    ok(surfaceOk(t),
      `the ${name} names the refusal, states c = 2L/dt only with its condition, and claims nothing about real rooms`,
      `refusal:${namesRefusal(t)} rule:${statesRule(t)} condition:${hasCondition(t)} realroom:${realRoomClaim(t)} overclaim:${overclaims(t)} len:${t.length}`);
  }
  // A check that has never been seen failing is not known to work, and these six are the ones
  // it costs the most to have decorative. Each rule is shown rejecting a sentence.
  const NEG = [
    ['a surface that never names the refusal',
     'Clap once at a wall you measured, where the microphone is, and the gap between those two arrivals gives the speed of sound in your own air to a fraction of a percent.'],
    ['the rule stated without the condition that makes it exact',
     'Twice the distance divided by that gap is the speed of sound in your own air, and it refuses whenever it cannot tell the wall from the floor.'],
    ['a frequency claim about real rooms',
     'It refuses whenever it cannot tell the wall from the floor, which on a real room is most of the time, because the floor answers first and louder.'],
    ['a promise of an exact temperature',
     'It refuses nothing you can measure, and gives the exact temperature of the air in your own hallway from a single clap at a wall.'],
  ];
  for (const [what, s] of NEG) ok(!surfaceOk(s), `and the rules reject ${what}, so they are known to be able to fail`);
  ok(!/\bdiscover(y|ed)\b|\bfirst ever\b|\bnobody has\b/i.test(dek + plain + metaDesc),
    'and none of them claims a discovery');
  // The dek's own numbers, against the split this page actually computes.
  const dt = measured.get('refusal-floor-decoy').refused.candidates[2].dtMs;
  const sdt = measured.get('refusal-floor-decoy').refused.candidates[2].sigmaMs;
  const b = sos.budget({ lengthM: 3.000, sigmaLM: 0.01, dtMs: dt, sigmaDtMs: sdt });
  ok(/99 percent/.test(dek) && /99 percent/.test(metaDesc) && near(b.shareTape * 100, 99, 0.5),
    'the 99 percent in the dek and the meta description is the number the page computes');
  ok(/under 1 percent/.test(dek) && /under 1 percent/.test(metaDesc) && b.shareMic * 100 < 1,
    'and the "under 1 percent" on the microphone is a bound the page actually meets');
}

function ld_description(h) {
  try { return JSON.parse((h.match(/<script type="application\/ld\+json">([\s\S]*?)<\/script>/) || [])[1]).description; }
  catch (e) { return ''; }
}

// ═══ 13. this file's own score, which the page quotes ════════════════════════
section('13. the score the page states');
const TOTAL = pass + fail + 1;
{
  const claimed = (html.match(/(\d+)\/(\d+) checks passed/) || [])[0];
  ok(claimed === `${TOTAL}/${TOTAL} checks passed`,
    `the page states this verifier's score, and it is ${TOTAL}/${TOTAL}`,
    `page says "${claimed}"`);
}

console.log(`\n${pass}/${pass + fail} checks passed`);
process.exit(fail ? 1 : 0);
