#!/usr/bin/env node
// verify-no-absolute-loudness.mjs — recomputes every number the page prints, and then tries
// to break it.
//
//   node research/no-absolute-loudness/verify-no-absolute-loudness.mjs
//
// It reads public/, never a build output, and it runs the page's OWN estimator: lkfs.js runs in
// a vm sandbox with the same two kit files the browser loads before it, so there is no second
// implementation for this file to be right about while the shipped one is wrong. The four
// declared truths and the four tolerances are parsed out of the shipped instrument.js rather
// than restated here, so a truth edited on the page turns this red.
//
// Half of what follows is deliberately negative. A verifier that only shows the estimator
// agreeing with itself proves nothing; these ones remove a stage of the Recommendation, flip a
// digit of a published coefficient, and feed the refusal paths signals built to trigger them,
// and each of those must FAIL in the specific place it is supposed to fail.
import { readFileSync, existsSync, statSync } from 'node:fs';
import { join, dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { execFileSync } from 'node:child_process';
import vm from 'node:vm';
import { loadLkfs } from './make-specimens.mjs';

const HERE = dirname(fileURLToPath(import.meta.url));
const ROOT = resolve(HERE, '../..');
const PAGE_DIR = join(ROOT, 'public/strata/no-absolute-loudness');
const SLUG = 'no-absolute-loudness';

let pass = 0, fail = 0;
const ok = (cond, msg, detail) => {
  if (cond) { pass++; console.log(`  ok    ${msg}`); }
  else { fail++; console.log(`  FAIL  ${msg}${detail === undefined ? '' : '  [' + detail + ']'}`); }
};
const near = (a, b, tol, msg) => ok(Math.abs(a - b) <= tol, msg, `got ${a}, want ${b} ± ${tol}`);

// ── load the shipped module, exactly as the browser does ──────────────────────
const AW = loadLkfs();
const L = AW.lkfs;

// AW.anchor as well, so the slate can be assembled here the way instrument.js assembles it.
const anchorSandbox = { window: {}, console };
vm.createContext(anchorSandbox);
vm.runInContext(readFileSync(join(ROOT, 'public/_kit/anchor.js'), 'utf8'), anchorSandbox, { filename: 'anchor.js' });
const ANCHOR = anchorSandbox.window.AW.anchor;

const html = readFileSync(join(PAGE_DIR, 'index.html'), 'utf8');
const instrumentJs = readFileSync(join(PAGE_DIR, 'instrument.js'), 'utf8');
const md = readFileSync(join(ROOT, 'src/content/strata', SLUG + '.md'), 'utf8');
const caseJson = JSON.parse(readFileSync(join(ROOT, 'research/anchor-wave/cases', SLUG + '.json'), 'utf8'));

// The truths the shipped page declares, read out of the shipped page.
function declared() {
  const t = {};
  const block = instrumentJs.match(/const TRUTH = \{([\s\S]*?)\};/);
  if (block) for (const m of block[1].matchAll(/(\w+):\s*(-?[\d.]+)/g)) t[m[1]] = Number(m[2]);
  const tols = [...instrumentJs.matchAll(/id:\s*'([\w-]+)',\s*role:\s*'(\w+)'[\s\S]*?tol:\s*([\d.]+)/g)]
    .map((m) => ({ id: m[1], role: m[2], tol: Number(m[3]) }));
  return { truths: t, tols };
}
const DEC = declared();

// ── a minimal 16-bit PCM WAV reader, so the specimens are read from the files that ship ──
function readWav(path) {
  const b = readFileSync(path);
  let off = 12, sr = 48000, ch = 1, data = null;
  while (off + 8 <= b.length) {
    const id = b.toString('ascii', off, off + 4), sz = b.readUInt32LE(off + 4);
    if (id === 'fmt ') { ch = b.readUInt16LE(off + 10); sr = b.readUInt32LE(off + 12); }
    if (id === 'data') { data = b.subarray(off + 8, off + 8 + sz); break; }
    off += 8 + sz + (sz & 1);
  }
  const n = data.length / (2 * ch);
  const x = new Float32Array(n);
  for (let i = 0; i < n; i++) x[i] = data.readInt16LE(i * 2 * ch) / 32768;
  return { samples: x, sampleRate: sr, seconds: n / sr };
}

const SR = 48000;
const dbToAmp = (db) => Math.pow(10, db / 20);
const estimate = L.makeEstimator();

console.log('\nno-absolute-loudness — verifying every number the page prints\n');

// ═══ 1. the Recommendation's own arithmetic ═══════════════════════════════════
console.log('the standard, re-derived from its printed tables:');

const k997 = L.kGainDbPublished(997);
near(k997, 0.691014, 5e-6, 'K-weighting gain at 997 Hz from Table 1 and Table 2 is +0.691014 dB');
ok(Math.abs(k997 + L.OFFSET) < 2e-5,
  'the Recommendation\'s -0.691 offset cancels that gain, as NOTE 1 says it does',
  `residual ${(k997 + L.OFFSET).toExponential(2)} dB`);

const closed = 10 * Math.log10(0.5) + k997 + L.OFFSET;
near(closed, -3.010286, 1e-5, 'closed form for a 997 Hz sine at full scale is -3.010286 LKFS');
near(Number(closed.toFixed(2)), -3.01, 1e-9,
  'and it rounds to the -3.01 LKFS the Recommendation prints');

const d48 = L.designK(48000);
ok(d48.residual < 1e-14,
  'the reconstructed analogue prototype regenerates all ten printed coefficients at 48 kHz',
  `worst residual ${d48.residual.toExponential(2)}`);
ok(d48.exact48 && d48.stages[0] === L.TABLE_1 && d48.stages[1] === L.TABLE_2,
  'and at 48 kHz the page still uses the printed values verbatim rather than the reconstruction');
const d441 = L.designK(44100);
near(d441.worstDevDb, 0.0053, 5e-5,
  'at 44.1 kHz the redesigned filter differs from the published 48 kHz curve by at most 0.0053 dB');
ok(d441.worstDevHz > 20 && d441.worstDevHz < 20000,
  'and that worst case is inside the 20 Hz to 20 kHz band the page quotes it over',
  String(d441.worstDevHz));
ok(html.includes('0.0053 dB'), 'the page prints that 0.0053 dB figure');
ok(L.G_MONO === 1.0, 'the single-channel weight is Table 3\'s 1.0');
ok(L.GAMMA_A === -70 && L.GAMMA_R_DROP === 10 && L.BLOCK_S === 0.4 && L.OVERLAP === 0.75,
  'block length, overlap and both gate thresholds are the Recommendation\'s (400 ms, 75%, -70 LKFS, -10 LU)');

// The 40 Hz control's truth, from the published coefficients alone.
const truth40 = 10 * Math.log10(0.5) + L.kGainDbPublished(40) + L.OFFSET;
near(truth40, -9.2682, 5e-5, 'closed form for a 40 Hz sine at full scale is -9.2682 LKFS');
near(DEC.truths.hz40, -9.2682, 1e-9, 'and that is the truth instrument.js declares for it');
near(DEC.truths.anchor, -3.01, 1e-9, 'the anchor truth instrument.js declares is the published -3.01');
near(DEC.truths.minus30, -33.01, 1e-9, 'and the -30 dBFS control\'s is the published value 30 dB down');

// The two-level control's truth, by an INDEPENDENT analytic route: no filtering, no blocking,
// no accumulation. A 997 Hz sine of piecewise-constant amplitude has a block mean square that
// is just the amplitude-weighted mean, and the block structure over 10 s at a 100 ms hop is
// fixed arithmetic: 97 blocks, of which 37 are wholly loud, 6 straddle a transition at 25%,
// 50% and 75%, and 54 are wholly quiet.
function twoLevelAnalytic() {
  const gk = Math.pow(10, L.kGainDbPublished(997) / 10);
  const zl = gk * Math.pow(dbToAmp(-10), 2) / 2, zq = gk * Math.pow(dbToAmp(-50), 2) / 2;
  const lOf = (z) => L.OFFSET + 10 * Math.log10(z);
  const blocks = [];
  for (let i = 0; i < 37; i++) blocks.push(zl);
  for (const p of [0.25, 0.5, 0.75, 0.75, 0.5, 0.25]) blocks.push(p * zl + (1 - p) * zq);
  for (let i = 0; i < 54; i++) blocks.push(zq);
  const abs = blocks.filter((z) => lOf(z) > L.GAMMA_A);
  const lr = lOf(abs.reduce((a, b) => a + b, 0) / abs.length);
  const used = abs.filter((z) => lOf(z) > lr - L.GAMMA_R_DROP);
  return { gated: lOf(used.reduce((a, b) => a + b, 0) / used.length), ungated: lr,
           nBlocks: blocks.length, nUsed: used.length };
}
const TL = twoLevelAnalytic();
ok(TL.nBlocks === 97 && TL.nUsed === 43,
  'the two-level specimen has 97 gating blocks and exactly 43 survive both gates',
  `${TL.nBlocks} / ${TL.nUsed}`);
near(TL.gated, -13.3243, 5e-4, 'its analytic gated loudness is -13.3243 LKFS');
near(DEC.truths.twoLevel, -13.3243, 1e-9, 'and that is the truth instrument.js declares for it');
near(TL.gated - TL.ungated, 3.53, 0.01,
  'an estimator that never gates lands 3.53 LU below it');

// ═══ 2. the specimens as shipped ══════════════════════════════════════════════
console.log('\nthe shipped specimens:');
const regen = execFileSync(process.execPath, [join(HERE, 'make-specimens.mjs'), '--check'],
  { cwd: ROOT, encoding: 'utf8' });
ok(!/DIFF/.test(regen), 'every WAV regenerates byte for byte from the committed generator',
  regen.split('\n').filter((l) => /DIFF/.test(l)).join('; '));
const hashes = JSON.parse(readFileSync(join(HERE, 'hashes.json'), 'utf8'));
ok(Object.keys(hashes).length === 6, 'six files are hashed: four specimens and two gate injections',
  String(Object.keys(hashes).length));
let specBytes = 0;
for (const k of Object.keys(hashes)) if (k.startsWith('specimens/')) specBytes += statSync(join(PAGE_DIR, k)).size;
ok(specBytes < 3 * 1024 * 1024, 'the shipped specimens are under the 3 MB budget',
  `${(specBytes / 1048576).toFixed(2)} MB`);

// ═══ 3. the slate, through the shipped estimator ══════════════════════════════
console.log('\nthe slate, run through the same estimator the page ships:');
const SPEC = {
  'sine-997-0dbfs': { role: 'anchor', truth: DEC.truths.anchor, tol: 0.1 },
  'sine-997-minus30': { role: 'control', truth: DEC.truths.minus30, tol: 0.1 },
  'sine-40-0dbfs': { role: 'control', truth: DEC.truths.hz40, tol: 0.1 },
  'two-level-997': { role: 'control', truth: DEC.truths.twoLevel, tol: 0.4 },
};
for (const [id, s] of Object.entries(SPEC)) {
  const declaredTol = (DEC.tols.find((t) => t.id === id) || {}).tol;
  ok(declaredTol === s.tol, `${id}: the tolerance on the page is ${s.tol} LU`, String(declaredTol));
}
const payloads = {};
for (const id of Object.keys(SPEC)) payloads[id] = readWav(join(PAGE_DIR, 'specimens', id + '.wav'));
const got = {};
for (const [id, s] of Object.entries(SPEC)) {
  const r = estimate(payloads[id]);
  got[id] = r;
  ok(!r.refused && Math.abs(r.value - s.truth) <= s.tol,
    `${id}: recovered ${r.refused ? 'REFUSED' : r.value.toFixed(4)} LKFS against ${s.truth} ± ${s.tol}`,
    r.refused ? r.refused.reason : String(r.value));
  ok(!r.refused && r.uncertainty <= s.tol,
    `${id}: its own claimed interval (± ${r.refused ? '?' : r.uncertainty.toFixed(4)}) is no wider than that tolerance`);
}

// The tolerances are this project's allowance, not a published one, so the page has to show
// that they are not deciding anything: the actual recoveries have to sit far inside them.
const worstDelta = Math.max(...Object.entries(SPEC).map(([id, s]) => Math.abs(got[id].value - s.truth)));
ok(worstDelta <= 0.003, `the worst of the four recoveries misses its truth by ${worstDelta.toFixed(4)} LKFS, inside the 0.003 the page quotes`);
ok(worstDelta * 30 < Math.min(...Object.values(SPEC).map((s) => s.tol)),
  'which is more than thirty times inside the tightest tolerance on the slate, so no tolerance decides a pass');
ok(/>0.003</.test(html) && /an allowance chosen here, not a published one/.test(html),
  'and the page prints that figure and says plainly that the tolerance is its own choice');

// The kit's own rules, applied to the shipped slate.
const slateSpec = Object.entries(SPEC).map(([id, s]) => ({
  id, role: s.role, truth: { value: s.truth, tol: s.tol, why: 'checked in verify-no-absolute-loudness.mjs' },
  load: () => payloads[id],
}));
function buildInstrument(est) {
  return ANCHOR.instrument({ id: 'v', quantity: 'gated loudness', unit: 'LKFS', estimate: est,
    specimens: slateSpec.map((s) => Object.assign({}, s, { truth: Object.assign({}, s.truth) })) });
}
const realInst = buildInstrument(estimate);
await realInst.runAll();
ok(realInst.armed(), 'the slate arms', realInst.blockedBecause() || '');
let separated = true;
for (const a of slateSpec.filter((s) => s.role === 'anchor')) {
  for (const c of slateSpec.filter((s) => s.role === 'control')) {
    if (Math.abs(a.truth.value - c.truth.value) <= a.truth.tol + c.truth.tol) separated = false;
  }
}
ok(separated, 'every anchor/control pair is further apart than the sum of their tolerances');
near(Math.abs(DEC.truths.anchor - DEC.truths.minus30), 30, 0.001,
  'the extremes of the slate are 30 LU apart');

const stub = await ANCHOR.stubProbe(realInst);
ok(stub.armed === false, 'an estimator that always returns the anchor value does NOT arm the slate');
ok(stub.rows.filter((r) => r.role === 'control').every((r) => r.pass === false),
  'and it fails every one of the three controls');

// ═══ 4. the mutations — the checks that prove the checks can fail ═════════════
console.log('\nmutations, each of which must be caught by a specific specimen:');
async function runMutant(est) {
  const m = buildInstrument(est);
  await m.runAll();
  const rep = m.report();
  return { armed: rep.armed, failed: rep.specimens.filter((s) => !s.pass).map((s) => s.id), rep };
}

// "K-weighting skipped" means the two biquads AND the -0.691 that exists only to cancel their
// gain at 997 Hz: gated mean square reported straight in dBFS, which is the same number the
// Recommendation gives for any 997 Hz signal and a different one everywhere else.
const NO_K = { kWeight: false, offset: 0 };
const noK = await runMutant(L.makeEstimator(NO_K));
ok(noK.armed === false, 'K-weighting skipped: the slate does not arm');
ok(noK.failed.length === 1 && noK.failed[0] === 'sine-40-0dbfs',
  'and the ONLY specimen it fails is the 40 Hz one: the anchor, the anchor 30 dB down and the ' +
  'two-level gating control all still pass, because all three are at 997 Hz where the filter ' +
  'gain and the -0.691 offset cancel',
  noK.failed.join(',') || 'nothing failed');
const noKat40 = L.gatedLoudness(payloads['sine-40-0dbfs'].samples, SR, NO_K);
near(noKat40.value - got['sine-40-0dbfs'].value, 6.2579, 0.02,
  'an unweighted estimator misses the 40 Hz specimen by 6.26 dB');
ok(html.includes('6.26 dB'), 'the page prints that 6.26 dB figure');
// The size of that agreement is a CLOSED FORM, not a coincidence of these files' durations.
// In the steady state the two estimators differ by exactly K(997) - 0.691 = 1.4095e-5 dB, and
// an earlier version of this file asserted only the empirical 5e-6 seen on the shipped
// specimens: a 6-second anchor would have turned that red with nothing wrong. So the identity
// is asserted first, the measured gaps are required to sit UNDER it (they approach it from
// below as the filter's start transient washes out), and the duration behaviour is shown.
const CLOSED_GAP = k997 + L.OFFSET;
near(CLOSED_GAP, 1.4095e-5, 1e-8,
  'the two estimators differ, in the steady state, by exactly K(997) - 0.691 = 0.000014 dB');
ok(html.includes('K(997) - 0.691 = 0.000014 dB'),
  'and the page prints that closed form rather than only the number it happened to measure');
for (const id of ['sine-997-0dbfs', 'sine-997-minus30', 'two-level-997']) {
  const r = L.gatedLoudness(payloads[id].samples, SR, NO_K);
  const gap = Math.abs(got[id].value - r.value);
  ok(gap <= CLOSED_GAP + 1e-9,
    `${id}: the measured gap (${gap.toExponential(2)} dB) sits under that closed form, as it must`,
    gap.toExponential(3));
  ok(gap <= 5e-6, `${id}: and under the five millionths of a decibel the page quotes for these files`,
    gap.toExponential(3));
}
{
  const tone = (secs) => { const n = Math.round(secs * SR), x = new Float32Array(n);
    for (let i = 0; i < n; i++) x[i] = Math.sin(2 * Math.PI * 997 * i / SR); return x; };
  const gapAt = (secs) => {
    const x = tone(secs);
    return Math.abs(estimate({ samples: x, sampleRate: SR }).value - L.gatedLoudness(x, SR, NO_K).value);
  };
  const short = gapAt(4), long = gapAt(20);
  ok(long > short && long < CLOSED_GAP,
    `the gap grows with duration towards that closed form (${short.toExponential(2)} at 4 s, ${long.toExponential(2)} at 20 s, limit ${CLOSED_GAP.toExponential(2)})`);
}
ok(html.includes('five millionths of a decibel'),
  'and the page states the size of the measured agreement rather than calling it exact');
ok(!/agrees[\s\S]{0,40}with the Recommendation to within five millionths/.test(html),
  'and does not attribute that agreement to the Recommendation, which prints only two decimals');

const noRel = await runMutant(L.makeEstimator({ gate: 'absolute' }));
ok(noRel.armed === false, 'relative gate removed: the slate does not arm');
ok(noRel.failed.length === 1 && noRel.failed[0] === 'two-level-997',
  'and only the two-level control catches it', noRel.failed.join(','));
const noGate = await runMutant(L.makeEstimator({ gate: 'none' }));
ok(noGate.failed.includes('two-level-997'), 'gating removed entirely: the two-level control catches it');
const ungated = L.gatedLoudness(payloads['two-level-997'].samples, SR, { gate: 'none' });
near(got['two-level-997'].value - ungated.value, 3.53, 0.02,
  'an ungated estimator misses the two-level specimen by 3.53 dB');

// ── the two stages this slate CANNOT discriminate, asserted as failures of the slate ──
// A verifier that only records the mutations its own page catches is an advertisement. These
// two are the holes, and they are checked in the direction that keeps them honest: if a later
// specimen ever closes one, these lines go red and the page's own "what is uncertain" section
// has to be rewritten, which is the correct way round.
const noAbs = await runMutant(L.makeEstimator({ gate: 'relative' }));
ok(noAbs.armed === true && noAbs.failed.length === 0,
  'absolute gate removed: NOT caught. The slate arms without it, and the page says so',
  noAbs.failed.join(',') || 'nothing failed');
ok(/absolute gate removed/.test(instrumentJs) && /NOT CAUGHT/.test(instrumentJs),
  'the page ships that fourth crippled estimator and labels its row NOT CAUGHT');
ok(/not caught by this slate at\s+all/i.test(html.replace(/<[^>]+>/g, ' ')),
  'and the page prose names it as uncaught rather than leaving it to the table');
// Why it is not caught: nothing on the slate is quiet enough for the absolute gate to bite.
// The quietest gating block anywhere on it is the two-level control's -50 dBFS section.
const twoLevelQuiet = L.OFFSET + 10 * Math.log10(Math.pow(dbToAmp(-50), 2) / 2 * Math.pow(10, k997 / 10));
ok(twoLevelQuiet > L.GAMMA_A + 10,
  `the quietest block on the slate is the two-level control's quiet section at ${twoLevelQuiet.toFixed(1)} LKFS, far above the ${L.GAMMA_A} LKFS gate`,
  twoLevelQuiet.toFixed(3));
ok(html.includes('-53 LKFS'), 'and the page prints that figure, rounded');
// The absolute gate is not untested, only unreachable from the slate: it is exercised here.
const tone75 = (() => { const n = SR * 3, x = new Float32Array(n), a = dbToAmp(-75);
  for (let i = 0; i < n; i++) x[i] = a * Math.sin(2 * Math.PI * 997 * i / SR); return x; })();
const noAbsQuiet = L.gatedLoudness(tone75, SR, { gate: 'relative' });
ok(!noAbsQuiet.refused && noAbsQuiet.value < L.GAMMA_A,
  `and an estimator without it reports ${noAbsQuiet.refused ? 'REFUSED' : noAbsQuiet.value.toFixed(2)} LKFS for a tone the real one refuses outright`);

// The block length, the other stage the slate names and cannot test.
const block200 = await runMutant(L.makeEstimator({ blockS: 0.2 }));
ok(block200.armed === true,
  'a 200 ms gating block instead of the Recommendation\'s 400 ms also arms this slate',
  block200.failed.join(',') || 'nothing failed');
const block1000 = await runMutant(L.makeEstimator({ blockS: 1.0 }));
ok(block1000.armed === false && block1000.failed.includes('two-level-997'),
  'a 1000 ms block IS caught, by the two-level control, which is a fact about that specimen rather than a defence of the slate',
  block1000.failed.join(','));
ok(html.includes('200 ms blocks') && html.includes('1000 ms'),
  'and the page names the block length as a stage its four specimens cannot discriminate, with both results');

// Digits of a published coefficient, altered. Table 2's a1 is printed as -1.99004745483398.
// The same block-and-gate arithmetic runs on an already-filtered signal, so the ONLY thing
// that changes between the two runs below is the coefficient.
function withA1(a1) {
  const st = { a: [1, a1, 0.99007225036621], b: [1, -2, 1] };
  return function (payload) {
    const y = L.biquad(L.biquad(payload.samples, L.TABLE_1), st);
    const r = L.gatedLoudness(y, payload.sampleRate, { kWeight: false });
    return r.refused ? { refused: r.refused } : { value: r.value, uncertainty: r.uncertainty };
  };
}
const asPrinted = await runMutant(withA1(-1.99004745483398));
ok(asPrinted.armed === true,
  'reproducing the K-weighting stage by stage from the printed coefficients arms the slate',
  asPrinted.failed.join(','));
const lastDigit = await runMutant(withA1(-1.99004745483397));
ok(lastDigit.armed === true,
  'changing the LAST printed digit of Table 2 a1 changes nothing measurable, as the Recommendation itself says of small variations');
const thirdDecimal = await runMutant(withA1(-1.98904745483398));
ok(thirdDecimal.armed === false,
  'but changing its third decimal place breaks the slate', thirdDecimal.failed.join(','));
ok(thirdDecimal.failed.includes('sine-40-0dbfs'),
  'and the 40 Hz control is what catches it, because that is where the RLB high-pass does its work',
  thirdDecimal.failed.join(','));

// ═══ 5. the refusals ══════════════════════════════════════════════════════════
console.log('\nthe refusal paths, each fed a signal built to trigger it:');
const sine = (hz, amp, secs, sr = SR) => {
  const n = Math.round(secs * sr), x = new Float32Array(n);
  for (let i = 0; i < n; i++) x[i] = amp * Math.sin(2 * Math.PI * hz * i / sr);
  return x;
};
const silence = estimate({ samples: new Float32Array(SR * 3), sampleRate: SR });
ok(silence.refused && silence.refused.reason === 'below-gate',
  'digital silence is refused as below-gate, not reported as a very quiet number',
  JSON.stringify(silence.refused || silence.value));
const short = estimate({ samples: sine(997, 1, 0.3), sampleRate: SR });
ok(short.refused && short.refused.reason === 'too-short',
  'a 0.3 s window is refused as too-short', JSON.stringify(short.refused || short.value));
const hot = new Float32Array(SR * 3);
for (let i = 0; i < hot.length; i++) hot[i] = Math.max(-0.995, Math.min(0.995, 1.6 * Math.sin(2 * Math.PI * 997 * i / SR)));
const clip = estimate({ samples: hot, sampleRate: SR });
ok(clip.refused && clip.refused.reason === 'clipped', 'a flat-topped window is refused as clipped',
  JSON.stringify(clip.refused || clip.value));
ok(!got['sine-997-0dbfs'].refused,
  'and a 997 Hz sine AT full scale is not refused as clipped, which the naive test would have done');
const veryQuiet = estimate({ samples: sine(997, dbToAmp(-75), 3), sampleRate: SR });
ok(veryQuiet.refused && veryQuiet.refused.reason === 'below-gate',
  'a tone 75 dB down is refused: every block is under the -70 LKFS absolute gate');

const noiseOf = (seed, secs) => { const r = L.mulberry32(seed); const x = new Float32Array(SR * secs);
  for (let i = 0; i < x.length; i++) x[i] = 0.05 * (r() * 2 - 1); return x; };
const noiseCap = { samples: noiseOf(9, 13), sampleRate: SR, seconds: 13 };
// The alignment threshold has to be set from BOTH sides, and a check that only ever sees one
// of them is the kind that cannot fail. Below: three different noise records, none of which
// contains a chirp, must all be refused; and a probe 60 dB down in noise must still be found.
let worstNoise = 0;
for (const [seed, secs] of [[9, 13], [77, 14], [1234, 20]]) {
  const a = L.alignProbe(noiseOf(seed, secs), SR);
  worstNoise = Math.max(worstNoise, a.refused ? a.prominence : Infinity);
  ok(a.refused && a.refused.reason === 'unaligned',
    `white noise (seed ${seed}, ${secs} s) with no chirp in it refuses alignment rather than picking a peak`,
    JSON.stringify(a.refused ? a.prominence : a.startSample));
}
ok(worstNoise < L.ALIGN_MIN_PROMINENCE && worstNoise > 6,
  `the best peak noise alone can fake is ${worstNoise.toFixed(2)}x the correlation median, under the ${L.ALIGN_MIN_PROMINENCE}x threshold`);
ok(html.includes('>7.5<'), 'and the page prints that 7.5x figure, rounded');
const noiseAnalysis = await L.analyse(noiseCap, async (p) => realInst.tryMeasure(p));
ok(noiseAnalysis.refused && noiseAnalysis.refused.reason === 'unaligned',
  'and analyse() then reports no segment numbers at all');

// ═══ 6. the second layer, on captures whose answers are built in ══════════════
console.log('\nthe derived figures, on synthetic captures with exactly known answers:');
const PROBE = L.buildProbe(SR);
const SCHED = L.SCHEDULE;
const loudStart = SCHED.find((s) => s.id === 'loud').t0;

// A capture is: `lead` seconds of noise, then the probe multiplied by a loop model, then a
// tail. The loop model here is a per-segment gain, which is exactly what a flat-per-band loop
// is, so the expected residual at each band is exactly that gain in decibels.
function makeCapture({ lead = 0.4, seconds = 14, bandGainDb = {}, stepDb = 0, noiseAmp = 1e-3,
                       probeGainDb = 0 } = {}) {
  const n = Math.round(seconds * SR);
  const x = new Float32Array(n);
  const rnd = L.mulberry32(77);
  for (let i = 0; i < n; i++) {
    const t = i / SR - lead;
    const j = Math.round(t * SR);
    let v = j >= 0 && j < PROBE.length ? PROBE[j] : 0;
    if (v !== 0) {
      let g = dbToAmp(probeGainDb);
      const seg = SCHED.find((s) => t >= s.t0 && t < s.t1);
      if (seg && seg.hz && bandGainDb[seg.hz] !== undefined) g *= dbToAmp(bandGainDb[seg.hz]);
      if (t >= loudStart) g *= dbToAmp(stepDb);
      v *= g;
    }
    x[i] = v + noiseAmp * (rnd() * 2 - 1);
  }
  return { samples: x, sampleRate: SR, seconds };
}
const measure = async (p) => realInst.tryMeasure(p);

const flat = await L.analyse(makeCapture({}), measure);
ok(!flat.refused, 'a synthetic capture of the probe aligns', JSON.stringify(flat.refused || ''));
near(flat.align.latencySeconds, 0.4, 2 / SR, 'alignment recovers the injected 0.400 s offset');
near(flat.agc.db, 0, 0.02, 'a fixed-gain loop gives a gain excursion of 0.00 dB');
ok(flat.bandsSurviving.length === L.BANDS.length, 'all seven bands survive a clean loop',
  flat.bandsSurviving.join(','));
near(flat.flatness.spreadDb, 0, 0.05, 'and its loop non-flatness is 0.00 dB peak to peak');
near(flat.oneConstant.db, 0, 0.05, 'and the 250 Hz against 4 kHz figure is 0.00 dB');
near(flat.window.ceilingLkfs, -3.010286, 1e-4,
  'the usable window is measured up to the -3.010286 LKFS a full-scale 997 Hz sine reads');
ok(flat.window.widthDb > 30, 'and down to the synthetic noise floor', String(flat.window.widthDb));

// ── the ceiling is the CALIBRATION POINT, not the top of the scale ────────────
// The sentence "nothing that is not clipping can read above a full-scale sine" is false, and
// this page's own tone bench refutes it. These lines are the refutation, run every time.
near(L.kPeakGainDb(SR), 4.0431, 5e-4,
  'the K-weighting rises to +4.0431 dB, its high-frequency asymptote');
const fullScale20k = estimate({ samples: (() => {
  const n = SR, x = new Float32Array(n);
  for (let i = 0; i < n; i++) x[i] = Math.sin(2 * Math.PI * 20000 * i / SR); return x; })(), sampleRate: SR });
ok(!fullScale20k.refused, 'a clean full-scale 20 kHz sine is not refused as clipped',
  JSON.stringify(fullScale20k.refused || ''));
near(fullScale20k.value, 0.342, 5e-4,
  'and the armed instrument reads it at 0.342 LKFS, which is what the tone bench prints');
near(fullScale20k.value - L.ceilingLkfs(SR), 3.352, 1e-3,
  'that is 3.35 dB ABOVE the ceiling, so the ceiling is the 997 Hz calibration point and not a limit');
ok(html.includes('0.342 LKFS') && html.includes('3.35 dB') && html.includes('+4.04 dB'),
  'and the page prints all three of those figures where it states the correction');
ok(!/nothing that is not clipping can read above what a sine at digital\s+full scale reads/.test(html),
  'and the unqualified version of that sentence is gone from the page');
ok(!/noise floor and digital clipping/.test(html) && !/noise floor and digital clipping/.test(md),
  'and neither the page nor the stratum markdown describes the window as reaching digital clipping');

// The other side of the alignment threshold. A probe 60 dB below the level the flat capture
// used, sitting in the same noise, must still be located: the threshold rejects noise without
// rejecting a signal a reader could plausibly deliver through a bad speaker at low volume.
const faint = L.alignProbe(makeCapture({ probeGainDb: -60 }).samples, SR);
ok(!faint.refused && faint.prominence > 4 * L.ALIGN_MIN_PROMINENCE,
  `a probe attenuated 60 dB still aligns, at ${faint.refused ? 'REFUSED' : faint.prominence.toFixed(0)}x the correlation median`,
  JSON.stringify(faint.refused || ''));
ok(html.includes('>100<'), 'and the page prints that 100x figure, rounded');

// "60 dB down" is an attenuation from the clean capture, NOT a signal-to-noise ratio, and the
// page said the second thing for a while. Measured against the fixed 1e-3 uniform noise floor
// the attenuated chirp sits about 4.6 dB UNDER the noise and the measured tones about 15 dB
// under, which is a stronger claim than the one that was printed, and it is the true one.
{
  const clean = makeCapture({ probeGainDb: -60, noiseAmp: 0 }).samples;
  const noiseRms = 1e-3 / Math.sqrt(3);           // uniform on [-1e-3, 1e-3]
  const segRms = (seg) => {
    const a = Math.round((0.4 + seg.t0) * SR), b = Math.round((0.4 + seg.t1) * SR);
    let s = 0; for (let i = a; i < b; i++) s += clean[i] * clean[i];
    return Math.sqrt(s / (b - a));
  };
  const chirpDb = 20 * Math.log10(segRms(SCHED.find((s) => s.kind === 'chirp')) / noiseRms);
  const toneDb = 20 * Math.log10(segRms(SCHED.find((s) => s.id === 'ref-a')) / noiseRms);
  near(chirpDb, -4.6, 0.15, `its alignment chirp sits ${chirpDb.toFixed(2)} dB UNDER the noise around it`);
  near(toneDb, -15.4, 0.3, `and its measured tones ${toneDb.toFixed(1)} dB under`);
  ok(html.includes('4.6 dB') && html.includes('attenuated'),
    'and the page says attenuated by 60 dB, with the level the chirp actually reaches, rather than "buried 60 dB into the noise"');
  ok(!/probe buried\s+<span class="mono">60 dB<\/span>\s+into the noise/.test(html),
    'the overstated version of that sentence is gone');
}

const stepped = await L.analyse(makeCapture({ stepDb: -6 }), measure);
near(stepped.agc.db, -6, 0.05,
  'a loop that drops 6.00 dB after the loud sweep is measured as a -6.00 dB excursion');
near(stepped.flatness.spreadDb, 0, 0.05,
  'and that step does not leak into the non-flatness figure, because every band precedes it');

const tilt = { 125: -3, 250: -2, 500: -1, 1000: 0, 2000: 1, 4000: 2, 8000: 3 };
const tilted = await L.analyse(makeCapture({ bandGainDb: tilt }), measure);
near(tilted.flatness.spreadDb, 6, 0.05, 'a loop tilted 6.00 dB across the bands measures 6.00 dB');
near(tilted.oneConstant.db, 4, 0.05,
  'and the single-constant error between 250 Hz and 4 kHz comes out at the built-in 4.00 dB');
const worstBand = Math.max(...L.BANDS.map((hz) =>
  Math.abs(tilted.bands.find((x) => x.hz === hz).residualDb - tilt[hz])));
ok(worstBand <= 0.05, 'every one of the seven band residuals recovers its built-in gain to 0.05 dB',
  `worst ${worstBand.toFixed(4)} dB`);

// A band that never arrives.
function killBand(cap, hz) {
  const seg = SCHED.find((s) => s.id === 'band-' + hz);
  const y = new Float32Array(cap.samples);
  const rnd = L.mulberry32(5);
  const a = Math.round((0.4 + seg.t0) * SR), b = Math.round((0.4 + seg.t1) * SR);
  for (let i = a; i < b; i++) y[i] = 1e-3 * (rnd() * 2 - 1);
  return { samples: y, sampleRate: SR, seconds: cap.seconds };
}
const dropped = await L.analyse(killBand(makeCapture({}), 125), measure);
const b125 = dropped.bands.find((b) => b.hz === 125);
ok(b125.dropped && b125.dropped.reason === 'tone-not-found',
  'a band replaced by noise is dropped by name as tone-not-found',
  JSON.stringify(b125.dropped));
ok(dropped.bandsSurviving.length === 6 && !dropped.bandsSurviving.includes(125),
  'and the spread is then quoted over the six survivors only');
let killed = makeCapture({});
for (const hz of [125, 250, 500, 1000]) killed = killBand(killed, hz);
const tooFew = await L.analyse(killed, measure);
ok(tooFew.flatness.refused && tooFew.flatness.refused.reason === 'too-few-bands',
  'with only three bands left the page refuses to quote a spread at all',
  JSON.stringify(tooFew.flatness.refused || tooFew.flatness.spreadDb));
ok(tooFew.oneConstant.refused && tooFew.oneConstant.refused.reason === 'band-missing',
  'and the single-constant figure is refused because 250 Hz is one of the missing bands');

// ═══ 6b. the tone bench, which every reader gets with no permission ═══════════
console.log('\nthe tone bench (the claim that 997 Hz is the ONLY place a missing filter hides):');
const BENCH_FREQS = [...instrumentJs.match(/const FREQS = \[([\s\S]*?)\];/)[1].matchAll(/[\d.]+/g)]
  .map((m) => Number(m[0]));
ok(BENCH_FREQS.length === 32 && BENCH_FREQS.includes(997) && BENCH_FREQS[0] === 20 &&
   BENCH_FREQS[BENCH_FREQS.length - 1] === 20000,
  'the bench offers 32 stops from 20 Hz to 20 kHz and includes the Recommendation\'s 997 Hz',
  BENCH_FREQS.join(','));
ok(html.includes('id="fslider"') && html.includes('max="31"') &&
   html.includes(`value="${BENCH_FREQS.indexOf(997)}"`),
  'the slider in the page has one stop per frequency and starts on 997 Hz');
// The gap between a K-weighted reading and an unweighted one is K(f) - 0.691, and the claim on
// the page is that it is zero at exactly one frequency in the whole audio band.
let crossings = 0, crossAt = 0, prev = L.kGainDbPublished(20) + L.OFFSET;
for (let hz = 21; hz <= 20000; hz++) {
  const v = L.kGainDbPublished(hz) + L.OFFSET;
  if ((prev < 0 && v >= 0) || (prev > 0 && v <= 0)) { crossings++; crossAt = hz; }
  prev = v;
}
ok(crossings === 1, `the weighted and unweighted readings meet at exactly one frequency between 20 Hz and 20 kHz`, String(crossings));
ok(Math.abs(crossAt - 997) <= 1, `and it is 997 Hz, the frequency the Recommendation calibrates at`, String(crossAt));
// The bench runs the real estimator on a tone it generates. Reproduce it here at three stops.
const benchSine = (hz) => sine(hz, 1, 1.0);
for (const hz of [20, 40, 997, 20000]) {
  const w = estimate({ samples: benchSine(hz), sampleRate: SR });
  const p = L.gatedLoudness(benchSine(hz), SR, NO_K);
  ok(!w.refused && !p.refused, `the bench measures a full-scale ${hz} Hz sine without refusing it`,
    JSON.stringify((w.refused || p.refused) || ''));
  if (w.refused || p.refused) continue;
  near(w.value - p.value, L.kGainDbPublished(hz) + L.OFFSET, 0.02,
    `and at ${hz} Hz the gap between them is the K-weighting gain less 0.691, as the page says`);
}
// The clip test, tightened. A clean full-scale sine at 20 Hz moves less than one sixteen-bit
// code per sample near its own peak; the previous tolerance called that a flat top and refused
// it. This is the check that would have caught that, and it must be able to fail.
const slow = estimate({ samples: sine(20, 1, 3), sampleRate: SR });
ok(!slow.refused, 'a clean 20 Hz sine at full scale is not refused as clipped', JSON.stringify(slow.refused || ''));
ok(L.flatTopFraction(sine(20, 1, 3), L.CLIP_LEVEL, L.CLIP_RUN) === 0,
  'and no part of it is counted as flat-topped at all');
const oldEps = (() => { const x = sine(20, 1, 3); let flat = 0, run = 1;
  for (let i = 1; i < x.length; i++) {
    if (Math.abs(x[i]) >= L.CLIP_LEVEL && Math.abs(x[i] - x[i - 1]) <= 1 / 32768) run++;
    else { if (run >= L.CLIP_RUN) flat += run; run = 1; }
  }
  return flat / x.length; })();
ok(oldEps > L.CLIP_FRACTION,
  `while the one-code tolerance this page used to carry would have called ${(oldEps * 100).toFixed(2)}% of it flat-topped and refused it`);
ok(L.FLAT_EPS === 1e-6 && html.includes('less than one sixteen-bit code per sample'),
  'and the page names the tightened tolerance and why it had to be tightened');

// ═══ 7. duration independence, which is why a 4 s anchor is legitimate ════════
console.log('\nduration independence of the anchor:');
const durations = [4, 8, 20].map((s) => estimate({ samples: sine(997, 1, s), sampleRate: SR }).value);
ok(Math.max(...durations) - Math.min(...durations) < 0.001,
  'a stationary 997 Hz tone reads the same at 4 s, 8 s and 20 s',
  durations.map((d) => d.toFixed(6)).join(' / '));
near(durations[0], -3.010286, 1e-4, 'and all three land on the closed form');

// ═══ 7b. the slate at the READER'S sampling rate, not at 48 kHz ═══════════════
// The specimens ship as 48 kHz files, but the page decodes them with decodeAudioData into the
// same AudioContext the microphone arrives in, which resamples them to the hardware's own rate.
// So the redesigned filters are exercised by the slate on exactly the readers who depend on
// them, and the commonest way to get BS.1770 wrong — using the printed 48 kHz coefficients
// verbatim at some other rate — is caught by the anchor rather than by nothing at all. This
// section proves both halves: that a correct redesign arms at four other rates, and that the
// verbatim-coefficient implementation does NOT.
//
// The specimens are re-synthesised here at each rate from the same closed forms the generator
// uses, which is what the browser's resampler is approximating. A truth fixed by a closed form
// does not move with the sampling rate; only the filter does.
console.log('\nthe slate at sampling rates other than 48 kHz:');
function specimensAtRate(fs) {
  const two = (() => {
    const n = Math.round(10 * fs), x = new Float32Array(n);
    const aq = dbToAmp(-50), al = dbToAmp(-10);
    for (let i = 0; i < n; i++) { const t = i / fs; x[i] = (t >= 3 && t < 7 ? al : aq) * Math.sin(2 * Math.PI * 997 * t); }
    return x;
  })();
  return [
    { id: 'sine-997-0dbfs', role: 'anchor', truth: { value: DEC.truths.anchor, tol: 0.1, why: 'the published calibration value, checked here' },
      load: () => ({ samples: sine(997, 1, 4, fs), sampleRate: fs }) },
    { id: 'sine-997-minus30', role: 'control', truth: { value: DEC.truths.minus30, tol: 0.1, why: 'the same value 30 dB down, checked here' },
      load: () => ({ samples: sine(997, dbToAmp(-30), 3, fs), sampleRate: fs }) },
    { id: 'sine-40-0dbfs', role: 'control', truth: { value: DEC.truths.hz40, tol: 0.1, why: 'a closed form over the printed tables, checked here' },
      load: () => ({ samples: sine(40, 1, 3, fs), sampleRate: fs }) },
    { id: 'two-level-997', role: 'control', truth: { value: DEC.truths.twoLevel, tol: 0.4, why: 'a closed form over the gating rule, checked here' },
      load: () => ({ samples: two, sampleRate: fs }) },
  ];
}
async function slateAtRate(fs, est) {
  const m = ANCHOR.instrument({ id: 'r' + fs, quantity: 'gated loudness', unit: 'LKFS',
    estimate: est, specimens: specimensAtRate(fs) });
  await m.runAll();
  const rep = m.report();
  return { armed: rep.armed, failed: rep.specimens.filter((s) => !s.pass).map((s) => s.id),
           got: Object.fromEntries(rep.specimens.map((s) => [s.id, s.got])), blocked: rep.blocked };
}
for (const fs of [44100, 32000, 22050, 96000]) {
  const r = await slateAtRate(fs, estimate);
  ok(r.armed, `the four specimens still arm the slate at ${fs} Hz, through the regenerated filters`,
    r.blocked || '');
}

// The bug, built and run. Nothing is redesigned: the printed 48 kHz biquads are applied at
// whatever rate the payload arrives at, which is what a naive implementation does.
const verbatim48 = function (payload) {
  const y = L.biquad(L.biquad(payload.samples, L.TABLE_1), L.TABLE_2);
  const r = L.gatedLoudness(y, payload.sampleRate, { kWeight: false });
  return r.refused ? { refused: r.refused } : { value: r.value, uncertainty: r.uncertainty };
};
const naiveAnchorAt = (fs) => verbatim48({ samples: sine(997, 1, 4, fs), sampleRate: fs }).value;
for (const [fs, want] of [[44100, -2.8013], [32000, -1.6777], [96000, -3.6597]]) {
  near(naiveAnchorAt(fs), want, 5e-4,
    `the printed 48 kHz coefficients used verbatim at ${fs} Hz read the anchor at ${want} LKFS`);
  const bad = await slateAtRate(fs, verbatim48);
  ok(bad.armed === false && bad.failed.includes('sine-997-0dbfs'),
    `and that slate does NOT arm at ${fs} Hz: the anchor is what catches it`,
    bad.failed.join(',') || 'nothing failed');
}
const naiveOk48 = await slateAtRate(48000, verbatim48);
ok(naiveOk48.armed === true,
  'while at 48 kHz the verbatim coefficients ARE the right ones and the same code arms, which is why this bug survives a 48 kHz-only slate',
  naiveOk48.blocked || '');
ok(html.includes('-2.8013') && html.includes('-1.6777') && html.includes('-3.6597'),
  'and the page prints all three of those misreadings');
ok(/measured\s+<em>at your rate, through the regenerated filters<\/em>/.test(html),
  'and says in as many words that the slate is measured at the reader\'s own sampling rate');

// The other end: below about 22 kHz the redesign's own worst error is wider than the tolerance
// the specimens are judged against, so an HONEST implementation cannot arm. That is the correct
// direction to fail in and it is a reader for whom this page is dead. Named, with the number.
for (const [fs, want] of [[32000, 0.0319], [22050, 0.0817], [16000, 0.1522]]) {
  near(L.designK(fs).worstDevDb, want, 5e-4,
    `the redesign's worst deviation from the published curve is ${want} dB at ${fs} Hz`);
}
ok(L.designK(16000).worstDevDb > 0.1,
  'which at 16 kHz is wider than the 0.1 LU tolerance the specimens carry');
const low = await slateAtRate(16000, estimate);
ok(low.armed === false && /claimed uncertainty/.test(low.blocked || ''),
  'so at 16 kHz the slate refuses to arm on its own honest error bar, not on a wrong answer',
  low.blocked || 'it armed');
ok(html.includes('0.152 dB') && html.includes('0.082 dB') && html.includes('0.032 dB'),
  'and the page prints that whole ladder rather than only the flattering 44.1 kHz figure');

// ═══ 7bb. the relative gate's blind spot, which is why the excursion is two windows ══
// BS.1770's relative gate discards any block more than 10 LU below its own window's level, so a
// large gain change measured INSIDE one window is partly hidden by the standard's own gate. That
// is the reason the page measures its gain excursion as two separate reference tones rather than
// as one long window, and the page states the sizes; here they are, recomputed.
console.log('\nthe relative gate\'s blind spot, and the two-window measurement that steps round it:');
function steppedTone(dropDb, secs) {
  const n = Math.round(secs * SR), x = new Float32Array(n);
  for (let i = 0; i < n; i++) {
    const t = i / SR;
    x[i] = (t < secs / 2 ? 1 : dbToAmp(dropDb)) * Math.sin(2 * Math.PI * 997 * i / SR);
  }
  return x;
}
{
  const x = steppedTone(-20, 6);
  const one = estimate({ samples: x, sampleRate: SR });
  const ung = L.gatedLoudness(x, SR, { gate: 'none' });
  near(one.value, -3.2308, 5e-4,
    'a -20 dB step halfway through a 6 s tone reads -3.2308 LKFS gated, as the page says');
  near(ung.value, -5.9774, 5e-4, 'against -5.9774 with no gating at all');
  ok(one.diagnostics.blocks === 57 && one.diagnostics.used === 30,
    'and the relative gate has thrown away 27 of the 57 blocks, which are the whole quiet half',
    `${one.diagnostics.blocks} blocks, ${one.diagnostics.used} used`);
  ok(html.includes('-3.2308 LKFS') && html.includes('-5.9774') && html.includes('27 of the 57 blocks'),
    'and the page prints all three of those figures');
}
// Two windows recover a commanded step exactly, which is what analyse() does with its two
// reference tones. If this ever stopped being exact, the first result on the page would be
// measuring the gate rather than the reader's chain.
for (const drop of [-6, -12, -20]) {
  const x = steppedTone(drop, 6), half = Math.round(3 * SR);
  const a = estimate({ samples: x.subarray(0, half), sampleRate: SR });
  const b = estimate({ samples: x.subarray(half), sampleRate: SR });
  near(b.value - a.value, drop, 1e-3,
    `measured as two separate windows, a commanded ${drop}.00 dB step comes back as ${(b.value - a.value).toFixed(4)} dB`);
}
ok(/Twice, and not once across the whole recording/.test(html),
  'and the page says why it takes two windows rather than one');

// ═══ 7c. the floor the INSTRUMENT puts under the reader's floor ═══════════════
// The usable window is measured down to a gated loudness, and the gate is -70 LKFS. Only blocks
// above it are averaged, so a reported floor is above -70 by construction and the window is
// capped at ceiling minus (-70) whatever the hardware does. A page that printed "your usable
// window is 52 dB" without saying that 67 dB is the lid its own estimator imposes would be
// manufacturing part of its own conclusion.
console.log('\nthe cap the -70 LKFS absolute gate puts on the usable window:');
const noiseAt = (targetLkfs, secs) => {
  const probe = (a) => { const r = L.mulberry32(31); const n = Math.round(secs * SR), x = new Float32Array(n);
    for (let i = 0; i < n; i++) x[i] = a * (r() * 2 - 1); return x; };
  const first = estimate({ samples: probe(0.01), sampleRate: SR });
  return probe(0.01 * Math.pow(10, (targetLkfs - first.value) / 20));
};
const floorWindowS = L.PROBE.lead - 2 * 0.1;     // the silent segment, trimmed as analyse() trims it
near(floorWindowS, 0.8, 1e-9, 'the noise-floor window is 0.8 s of the reader\'s opening silence');
ok(floorWindowS >= L.BLOCK_S + 2 * L.HOP_S,
  'which is longer than the 0.6 s three gating blocks need, so a quiet room is refused for being quiet and never for being short');
for (const t of [-50, -65, -69.5]) {
  const r = estimate({ samples: noiseAt(t, 4), sampleRate: SR });
  ok(!r.refused && Math.abs(r.value - t) < 0.1,
    `a floor at ${t} LKFS is reported as ${r.refused ? 'REFUSED' : r.value.toFixed(2)}, uncensored`,
    r.refused ? r.refused.reason : '');
}
for (const t of [-70.5, -75, -82]) {
  const r = estimate({ samples: noiseAt(t, 4), sampleRate: SR });
  ok(r.refused && r.refused.reason === 'below-gate',
    `a floor at ${t} LKFS is refused outright rather than reported as a smaller number`,
    r.refused ? r.refused.reason : String(r.value));
}
// And the cap is the GATE's doing, not the signal's: the same record measured without the
// absolute gate returns a perfectly good number below -70.
const ungatedFloor = L.gatedLoudness(noiseAt(-75, 4), SR, { gate: 'relative' });
ok(!ungatedFloor.refused && ungatedFloor.value < L.GAMMA_A,
  `without that gate the same record reads ${ungatedFloor.refused ? 'REFUSED' : ungatedFloor.value.toFixed(2)} LKFS, so the lid is the estimator's and not the signal's`);
const capDb = L.ceilingLkfs(SR) - L.GAMMA_A;
near(capDb, 66.99, 0.01,
  'so the widest usable window this page can ever print is 66.99 dB, the gate to the calibration point');
ok(/about\s+<span class="mono">67 dB<\/span>/.test(html) &&
   /the\s+estimator's limit and not your hardware's/.test(html),
  'and the page names that cap as the instrument\'s rather than the reader\'s');
ok(/widest this figure can ever be/.test(instrumentJs),
  'and the window tile prints it beside the number, computed rather than asserted');

// ═══ 8. the gate injections ═══════════════════════════════════════════════════
console.log('\nthe two files the live-sensor gate injects as a microphone:');
for (const [key, file] of [['anchor', 'inject-a.wav'], ['control', 'inject-b.wav']]) {
  const cap = readWav(join(HERE, 'gate', file));
  const win = { samples: cap.samples.subarray(0, Math.round(caseJson.liveSeconds * SR)),
                sampleRate: SR, seconds: caseJson.liveSeconds };
  const a = await L.analyse(win, measure);
  const refA = a.segments.find((s) => s.id === 'ref-a');
  const spec = caseJson.inject[key];
  ok(refA && refA.measure && !refA.measure.refused &&
     Math.abs(refA.measure.value - spec.expect) <= spec.tol,
    `${file}: the reference tone measures ${refA && refA.measure && !refA.measure.refused ? refA.measure.value.toFixed(4) : 'REFUSED'} against the case file's ${spec.expect} ± ${spec.tol}`);
  if (key === 'anchor') caseJson.__gotA = refA.measure.value;
  else caseJson.__gotB = refA.measure.value;
}
near(caseJson.__gotA - caseJson.__gotB, 12, 0.02,
  'the two injections are exactly 12.00 dB apart, as built');
ok(Math.abs(caseJson.inject.anchor.expect - caseJson.inject.control.expect) >
   caseJson.inject.anchor.tol + caseJson.inject.control.tol,
  'and the case file\'s two tolerances cannot bridge that gap, which is the gate\'s fourth check');
near(L.flatExpectationLkfs(997, SR, L.PROBE.amp), -20.0877, 5e-4,
  'the expected reading for the probe\'s reference tone through a unity loop is -20.0877 LKFS');
ok(caseJson.inject.anchor.expect === -20.0877 && caseJson.inject.control.expect === -32.0877,
  'and those are the two numbers in the case file');
ok(caseJson.liveSeconds >= L.PROBE_SECONDS + 1.5,
  'the gate captures long enough to hold the whole probe plus alignment slack',
  `${caseJson.liveSeconds} s vs ${L.PROBE_SECONDS} s`);

// ═══ 9. the page's own surface ════════════════════════════════════════════════
console.log('\nthe page, as a reader receives it:');

// All of this page's JavaScript lives in two files that node can parse. Nothing is inline,
// so nothing can be silently disabled by an unclosed tag in the middle of the document.
// Only the region this build wrote. The site's chrome generators append a nearby-layers bar,
// a check-kind card and a way-out block to every shipped page, each with its own <style> and
// one with an inline <script>, so an assertion over the whole file would be an assertion about
// somebody else's generator. Everything below is about the page's own bytes.
// ⚠ This was html.split(/<!--aw-[a-z]+:start-->/)[0]. Right idea, wrong mechanism: the
// site-bar generator injects near the TOP of <body>, so truncating at the first chrome marker
// discarded most of the page, and nine assertions about quotations, specimen truths and the
// page's own scripts went red for a reason that had nothing to do with this page. Cut the
// chrome OUT rather than cutting the document short.
const OWN = html
  .replace(/<!--aw-[a-z]+:start-->[\s\S]*?<!--aw-[a-z]+:end-->/g, '')
  .replace(/<script[^>]*src="\/media\/[^"]*"[^>]*>\s*<\/script>/g, '');
const scripts = [...OWN.matchAll(/<script([^>]*)>([\s\S]*?)<\/script>/g)];
let inlineJs = 0, jsonldOk = false, jsonld = null;
const ownSrcs = [];
for (const [, attrs, body] of scripts) {
  if (/\bsrc=/.test(attrs)) { ownSrcs.push(attrs.match(/src="([^"]+)"/)[1]); continue; }
  if (/application\/ld\+json/.test(attrs)) {
    try { jsonld = JSON.parse(body); jsonldOk = true; } catch (e) { jsonldOk = false; }
    continue;
  }
  if (body.trim()) inlineJs++;
}
ok(inlineJs === 0, 'the page carries no inline JavaScript of its own at all', String(inlineJs));
const resolveSrc = (s) => (s.startsWith('/') ? join(ROOT, 'public', s.slice(1)) : join(PAGE_DIR, s));
ok(ownSrcs.length === 5 && ownSrcs.every((s) => existsSync(resolveSrc(s))),
  'and every script it does load resolves to a file that ships',
  ownSrcs.filter((s) => !existsSync(resolveSrc(s))).join(' ') || ownSrcs.join(' '));
ok(jsonldOk, 'and the JSON-LD block is valid JSON');
for (const f of ['lkfs.js', 'instrument.js']) {
  let good = true;
  try { execFileSync(process.execPath, ['--check', join(PAGE_DIR, f)]); } catch (e) { good = false; }
  ok(good, `${f} parses under node --check`);
}
const opens = (html.match(/<script\b/g) || []).length, closes = (html.match(/<\/script>/g) || []).length;
ok(opens === closes && /<\/body>/.test(html) && /<\/html>/.test(html),
  'its script tags balance and it closes body and html', `${opens} open, ${closes} close`);

// No third-party request from any script this page runs.
const scriptText = [readFileSync(join(PAGE_DIR, 'lkfs.js'), 'utf8'), instrumentJs].join('\n');
const foreign = [...scriptText.matchAll(/https?:\/\/[^\s'"`)]+/g)].map((m) => m[0]);
ok(foreign.length === 0, 'neither shipped script contains an absolute URL of any kind',
  foreign.join(' '));
const srcs = [...html.matchAll(/<(?:script|link|img)[^>]*(?:src|href)="([^"]+)"/g)].map((m) => m[1])
  .filter((u) => /^https?:/.test(u) && !u.startsWith('https://artwaste.land'));
ok(srcs.length === 0, 'and the page loads nothing from another origin', srcs.join(' '));

// The quotations, character for character. Read at source from the free ITU PDF on
// 2026-08-17; see research/no-absolute-loudness/README.md.
const QUOTES = [
  'If a 0 dB FS, 1 kHz (997 Hz to be exact, see Notes 1 and 2) sine wave is applied to the left, centre, or right channel input, the indicated loudness will equal −3.01 LKFS.',
  'NOTE 1 – The constant −0.691 in equation (2) cancels out the K-weighting gain for 997 Hz.',
  'These filter coefficients are for a sampling rate of 48 kHz. Implementations at other sampling rates will require different coefficient values, which should be chosen to provide the same frequency response that the specified filter provides at 48 kHz.',
  'It should be noted that while this algorithm has been shown to be effective for use on audio programmes that are typical of broadcast content, the algorithm is not, in general, suitable for use to estimate the subjective loudness of pure tones.',
];
const flatHtml = OWN.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ');
for (const q of QUOTES) {
  ok(flatHtml.includes(q), `the quotation "${q.slice(0, 46)}…" is on the page verbatim`);
}
// The count, counted rather than restated. Three of the QUOTES above are single sentences and
// the coefficient one is two, so the page quotes FIVE sentences in three blockquotes. The page
// footer said three, the README said four, and this line said four; all three were wrong in
// different directions, which is what a restated number does. This one counts.
const quotedSentences = QUOTES.reduce((n, q) => n + q.split(/(?<=\.)\s+/).filter(Boolean).length, 0);
ok(quotedSentences === 5 && html.split('<blockquote>').length - 1 === 3,
  `the page carries three blockquotes holding ${quotedSentences} quoted sentences`,
  `${quotedSentences} sentences, ${html.split('<blockquote>').length - 1} blockquotes`);
ok(html.includes('quotes five sentences, in three blockquotes'),
  'and the page footer states that count in those terms');
ok(readFileSync(join(HERE, 'README.md'), 'utf8').includes('five sentences, in three blockquotes'),
  'and so does the research README, so the three places cannot drift apart again');

// The four declared truths, as the reader sees them in the specimen table. A truth edited in
// instrument.js and left stale in the page's own prose is the exact drift this catches.
for (const [name, v] of Object.entries(DEC.truths)) {
  ok(flatHtml.includes(String(v) + ' LKFS'),
    `the ${name} truth (${v} LKFS) is printed in the page's own specimen table`);
}

// Every printed coefficient appears on the page's own source only inside lkfs.js, and the
// page renders them from there. Check the module still holds the printed values.
const printed = [1.53512485958697, -2.69169618940638, 1.19839281085285, -1.69065929318241,
                 0.73248077421585, -1.99004745483398, 0.99007225036621];
const inModule = printed.every((v) =>
  L.TABLE_1.b.includes(v) || L.TABLE_1.a.includes(v) || L.TABLE_2.a.includes(v) || L.TABLE_2.b.includes(v));
ok(inModule, 'all seven non-trivial coefficients of Table 1 and Table 2 are in the shipped module');

// The shareable surface. A retracted framing surviving in the OG tags has shipped here before.
const fm = md.match(/^---\n([\s\S]*?)\n---/)[1];
const field = (k) => { const m = fm.match(new RegExp('^' + k + ': "([\\s\\S]*?)"$', 'm')); return m ? m[1] : null; };
const dek = field('dek'), plain = field('plain'), seoTitle = field('seoTitle');
ok(html.includes('<title>' + seoTitle + '</title>'), 'the page title is the frontmatter seoTitle');
ok(jsonld && jsonld.headline === 'Loud Compared to What' && jsonld.name === seoTitle,
  'the JSON-LD carries the poetic title as headline and the search title as name');
ok(html.includes('<h1>Loud Compared to What</h1>'), 'and the H1 is the poetic title');
// The honesty leak lives in the shareable surface, so every surface a stranger sees before
// the page loads has to carry the same limit the page carries: a level relative to something
// inside the hardware, and no absolute pressure figure anywhere.
//
// THE SHAPE OF THE ASSERTION MATTERS MORE THAN THE ASSERTION. The version this file shipped
// with tested `/relative to|full scale|cannot report/`, which is presence of a substring, and
// an og:description reading "it just cannot tell you what the loudness is relative to" went
// green on the very words it was denying. A check that passes whether or not the rule holds is
// worse than no check, because it is a claim that the rule was checked. So each surface must
// now (a) NAME full scale as the reference, (b) contain no sentence denying that the page
// knows what its level is relative to, (c) quote no absolute pressure figure, and (d) not
// call the count of slate answers "published", because two of the four are this project's own
// closed forms and the page's own uncertainty panel says so.
const namesTheLimit = (t) => /\bfull scale\b/i.test(t);
const deniesTheLimit = (t) =>
  /\b(?:cannot|can't|could not|does not|doesn't|will not|won't|never)\b[^.]{0,80}\bwhat\b[^.]{0,50}\brelative to\b/i.test(t);
const claimsPressure = (t) =>
  /\d\s*(?:dB|decibels?)\s*(?:SPL|\(?A\)?\b)/i.test(t) ||
  /\b\d+(?:\.\d+)?\s*(?:dB|decibels?)\b[^.]{0,60}\b(?:in your room|in the air|of (?:sound )?pressure|SPL)\b/i.test(t) ||
  /\b(?:your|the|this)\s+room\b[^.]{0,60}\b\d+(?:\.\d+)?\s*(?:dB|decibels?)\b/i.test(t) ||
  /\bdecibels? of (?:sound )?pressure in your room\b/i.test(t);
const overclaimsPublished = (t) =>
  /\b(?:four|4)\b[^.]{0,30}\bpublished\b/i.test(t) || /\bpublished\b[^.]{0,30}\b(?:four|4)\b/i.test(t);
const surfaceOk = (t) => t.length > 40 && namesTheLimit(t) && !deniesTheLimit(t) &&
                         !claimsPressure(t) && !overclaimsPublished(t);

// The control on the control. Every predicate above is exercised on a string built to trip it,
// including the two strings that actually shipped in these tags and had to be retracted, so a
// green line below means the predicate can go red rather than merely that it did not.
const SURFACE_TRAPS = [
  ['a surface that denies knowing its own reference',
   'Your browser can measure loudness beautifully. It just cannot tell you what the loudness is relative to. Four answers recovered first, relative to full scale.'],
  ['a surface that calls all four slate answers published',
   'A level relative to the full scale of your sound card. Four published answers recovered first, then a probe through your own speaker.'],
  ['a surface that quotes a room in bare decibels',
   'A level relative to the full scale of your sound card, and your room is 72 decibels while it does it.'],
  ['a surface that quotes dB SPL',
   'This page reports 54 dB SPL for your room, relative to the full scale of your sound card.'],
  ['a surface that never names the reference at all',
   'Your browser can measure loudness beautifully, and this page will tell you exactly how loud your room is, live, from your own microphone.'],
];
for (const [what, trap] of SURFACE_TRAPS) {
  ok(!surfaceOk(trap), `the shareable-surface test rejects ${what}`, trap.slice(0, 60));
}
ok(deniesTheLimit('It just cannot tell you what the loudness is relative to.') &&
   !deniesTheLimit('It just cannot tell you what full scale is worth in pascals.'),
  'and the denial test separates denying the reference from naming the missing conversion');

for (const [name, text] of [['dek', dek], ['plain', plain],
                            ['meta description', (html.match(/<meta name="description" content="([\s\S]*?)" \/>/) || [])[1]],
                            ['og:description', (html.match(/<meta property="og:description" content="([\s\S]*?)" \/>/) || [])[1]],
                            ['twitter:description', (html.match(/<meta name="twitter:description" content="([\s\S]*?)" \/>/) || [])[1]],
                            ['JSON-LD description', jsonld && jsonld.description]]) {
  const t = String(text || '');
  ok(surfaceOk(t),
    `the ${name} names full scale as the reference, does not deny it, quotes no pressure and does not call four answers published`,
    `names: ${namesTheLimit(t)}, denies: ${deniesTheLimit(t)}, pressure: ${claimsPressure(t)}, published: ${overclaimsPublished(t)}`);
}
ok(!/\d\s*dB\s*SPL/i.test(html), 'and no figure in dB SPL appears anywhere on the page');

// The card a stranger actually sees. Three head tags point at it; a missing file makes every
// share of this page a broken card, which is the shareable surface failing in the most
// literal way there is.
const ogHref = (html.match(/<meta property="og:image" content="https:\/\/artwaste\.land\/([^"]+)"/) || [])[1];
ok(ogHref === 'og/no-absolute-loudness.png' && existsSync(join(ROOT, 'public', ogHref)),
  'the og:image this page names exists in public/', String(ogHref));
ok(jsonld && jsonld.image === 'https://artwaste.land/' + ogHref &&
   html.includes(`<meta name="twitter:image" content="https://artwaste.land/${ogHref}"`),
  'and twitter:image and the JSON-LD image point at the same file');
// The naive form of this check (does the risk vocabulary appear anywhere?) fires on the page's
// own disclaimer, so it would force the disclaimer to be deleted to go green, which is the
// opposite of what it is for. What actually matters is whether any sentence USES that
// vocabulary rather than denying it. So: find every sentence carrying it, and require each one
// to be a denial. "85 dB is the limit for eight hours" would fail this; "there is no dose, no
// threshold, and no statement about whether any sound is safe" passes.
const RISK = /\b(safe|unsafe|hearing (?:damage|loss|risk)|hearing-(?:damage|safety)|exposure|dose|LAeq|85\s*dB)\b/i;
const DENIAL = /\b(no|not|nothing|never|cannot|does not|will not)\b/i;
// A bare "no" anywhere in the sentence is not a denial of the risk claim: "85 dB is safe for
// no more than eight hours" would have gone green on the "no" in "no more". So a sentence that
// touches this vocabulary must ALSO carry no level figure at all. A safety claim needs a
// number to be a safety claim, and the page's disclaimers do not have one.
const LEVEL_FIGURE = /\b\d+(?:\.\d+)?\s*(?:dB|dBA|decibels?|LKFS|LU|pascals?|Pa)\b/i;
const usesRisk = (s) => RISK.test(s) && (!DENIAL.test(s) || LEVEL_FIGURE.test(s));
ok(usesRisk('85 dB is safe for no more than eight hours.') &&
   !usesRisk('There is no dose, no time-weighted average, no threshold, and no statement about whether any sound is safe.'),
  'the hearing-risk test separates a threshold claim from a denial, rather than passing on any stray "no"');
const sentences = [flatHtml, md].join(' ').split(/(?<=[.!?])\s+/);
const risky = sentences.filter((s) => RISK.test(s));
const undenied = risky.filter(usesRisk);
ok(risky.length >= 3 && undenied.length === 0,
  `every one of the ${risky.length} sentences that touch exposure or hearing risk denies it and carries no level figure`,
  undenied.join(' // '));
ok(/definitional, not a result/.test(html),
  'the page labels the one claim that could not be contradicted by a measurement as definitional');

// ── the zero promise, kept exactly where it holds and withdrawn where it does not ──
// "Every one of them could come back at zero, and the page says so when it does" was true of
// the gain excursion, the non-flatness and the 250 Hz/4 kHz figure, and FALSE of the usable
// window, which is a distance from a measured floor to a fixed calibration point and is
// bounded away from zero by the -70 LKFS refusal. The promise now names three, and each of
// those three has to carry an actual zero branch in the shipped renderer.
// Each tile's own expression, cut out of the shipped renderer: from its real assignment (the
// one that reads the analysis, not the line that blanks it on a refusal) to wherever the next
// tile begins. Scoped like that, a sentence belonging to a neighbouring tile cannot satisfy
// the assertion for this one.
const tileBlock = (id) => {
  const i = instrumentJs.indexOf(`$('${id}').textContent = a.`);
  if (i < 0) return '';
  const rest = instrumentJs.slice(i + `$('${id}').textContent = a.`.length);
  const j = rest.search(/\$\('(?:r|n)-/);
  return j < 0 ? rest : rest.slice(0, j);
};
for (const [tile, id] of [['gain excursion', 'n-agc'], ['loop non-flatness', 'n-flat'],
                          ['250 Hz against 4 kHz', 'n-one']]) {
  ok(/zero to within the interval/.test(tileBlock(id)),
    `the ${tile} tile carries an explicit "that is zero to within the interval" branch`,
    `${tileBlock(id).length} chars found`);
}
ok(/cannot come back at zero/.test(tileBlock('n-win')) &&
   !/zero to within the interval/.test(tileBlock('n-win')),
  'and the usable-window tile says in as many words that it cannot come back at zero, and promises no zero branch');
ok(/The first three could each come back at zero/.test(html) &&
   /The first three could each come back at zero/.test(md),
  'the dek promises the zero result for three of the four, on the page and in the stratum markdown');
ok(/Three of the four could have come back at zero/.test(html.replace(/\s+/g, ' ')),
  'and the body says the same thing rather than "each of those"');
ok(!/Every one of them could come back at zero/.test(html) &&
   !/Every one of them could come back at zero/.test(md),
  'the overclaimed version of that promise is gone from both');

// The headline count, which the page stated two different ways: "three measurements" in the
// dek, the lede and the JSON-LD, against a grid of four result tiles.
const tiles = (html.match(/id="r-(?:agc|flat|one|win)"/g) || []).length;
ok(tiles === 4, 'the results grid renders four tiles', String(tiles));
for (const [name, text] of [['dek', dek], ['page dek', html.match(/<p class="dek">([\s\S]*?)<\/p>/)[1]],
                            ['meta description', (html.match(/<meta name="description" content="([\s\S]*?)" \/>/) || [])[1]],
                            ['JSON-LD description', jsonld && jsonld.description]]) {
  const t = String(text || '').replace(/\s+/g, ' ');
  ok(/four measurements of your own hardware/.test(t) && !/three measurements/.test(t),
    `the ${name} counts four measurements, matching the four tiles`);
}

// The refusals the page enumerates, counted against the list it prints. A specimen that will
// not load used to be a fifth way to fail that the page did not name and did not handle: the
// rejection escaped runAll() and the page stalled on its placeholder for ever. It is now the
// first item in the list and it is caught.
const refuseList = (html.match(/<h3>The five ways this page refuses<\/h3>\s*<ul>([\s\S]*?)<\/ul>/) || [])[1];
ok(Boolean(refuseList) && (refuseList.match(/<li>/g) || []).length === 5,
  'the page enumerates five refusals under a heading that says five',
  refuseList ? String((refuseList.match(/<li>/g) || []).length) : 'no list found');
ok(/main\(\)\.catch\(renderSlateFailure\)/.test(instrumentJs) &&
   /function renderSlateFailure/.test(instrumentJs) &&
   /the slate could not be run/.test(instrumentJs),
  'and a specimen that fails to load renders that refusal instead of stalling on the placeholder');
ok(/\$\('go'\)\.disabled = true;/.test(instrumentJs.slice(instrumentJs.indexOf('function renderSlateFailure'))),
  'and the failure path disables the button rather than leaving a dead control armed');

// 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(' '));

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

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