#!/usr/bin/env node
// verify-inharmonicity-railsback.mjs — recompute every number this page reports, and then
// try to break it.
//
//   node research/inharmonicity-railsback/verify-inharmonicity-railsback.mjs
//
// It reads public/, never the build output. It does NOT reimplement the estimator: inharm.js, the file
// the browser loads, is executed in a vm sandbox with the same kit file that sits above it,
// so there is no second implementation for this script to be right about while the shipped
// one is wrong. The five declared truths and their 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, because a verifier that only shows the
// estimator agreeing with itself proves nothing. A hard-coded stub is pushed through the real
// slate and must fail. The window sweep must FIRE on the trap rather than merely exist. Five
// refusal paths are each fed a signal built to trigger them and must each refuse in the right
// place. And the specimens are regenerated from their closed forms and compared by sha256, so
// a doctored blob is caught rather than trusted.
import { readFileSync, existsSync, statSync, mkdtempSync, rmSync, mkdirSync, readdirSync } from 'node:fs';
import { join, dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { tmpdir } from 'node:os';
import vm from 'node:vm';
import { writeWav, tone, sum, noise } from '../anchor-wave/forge.mjs';
import { stringConstants, bFromGeometry, clampedPartials, clampedResidual, pinnedPartials, fitPinned, pluck, STEEL }
  from './strings.mjs';
import { GEOMETRY, SPECIMENS, GATE_FILES, readWav, HARMONIC_F0, GLIDE_CENTS, GLIDE_TAU, NYQ_FRAC, stiffSpecimen, harmonicSpecimen }
  from './make-specimens.mjs';

const HERE = dirname(fileURLToPath(import.meta.url));
const ROOT = resolve(HERE, '../..');
const SLUG = 'inharmonicity-railsback';
const PAGE_DIR = join(ROOT, 'public/strata', SLUG);
const SPEC_DIR = join(PAGE_DIR, 'specimens');
const GATE_DIR = join(HERE, 'gate');
const SR = 48000;

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}`);
const section = (t) => console.log(`\n${t}`);

// ── load the shipped estimator, exactly as the browser stacks it ──────────────
function loadShipped() {
  const sandbox = { window: {}, console };
  vm.createContext(sandbox);
  for (const f of ['public/_kit/dsp.js', 'public/_kit/anchor.js', `public/strata/${SLUG}/inharm.js`]) {
    vm.runInContext(readFileSync(join(ROOT, f), 'utf8'), sandbox, { filename: f });
  }
  return sandbox.window.AW;
}
const AW = loadShipped();
const IH = AW.inharm;
const C = IH.C;

const html = readFileSync(join(PAGE_DIR, 'index.html'), 'utf8');
const instrumentJs = readFileSync(join(PAGE_DIR, 'instrument.js'), 'utf8');
const inharmJs = readFileSync(join(PAGE_DIR, 'inharm.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 declaredTruths() {
  const t = {};
  const block = instrumentJs.match(/const TRUTH = \{([\s\S]*?)\};/);
  if (block) for (const m of block[1].matchAll(/(\w+):\s*(-?[\d.eE+-]+)/g)) t[m[1]] = Number(m[2]);
  const tols = {};
  for (const m of instrumentJs.matchAll(/id: '([\w-]+)', role: '(\w+)'[\s\S]{0,220}?tol: ([^,]+),/g)) {
    tols[m[1]] = { role: m[2], expr: m[3].trim() };
  }
  return { values: t, tols };
}
const DECL = declaredTruths();

// The tolerance expressions are written as multipliers of the truth, so evaluate them the
// same way the browser does rather than restating the numbers.
function tolOf(id) {
  const e = DECL.tols[id];
  if (!e) return null;
  const m = e.expr.match(/^([\d.eE+-]+)\s*\*\s*TRUTH\.(\w+)$/);
  if (m) return Number(m[1]) * DECL.values[m[2]];
  return Number(e.expr);
}

const SLATE = [
  { id: 'stiff-anchor', key: 'stiffAnchor', geom: 'stiff-anchor', file: 'stiff-anchor.wav' },
  { id: 'harmonic-zero', key: 'harmonicZero', geom: null, file: 'harmonic-zero.wav' },
  { id: 'fret-open', key: 'fretOpen', geom: 'fret-open', file: 'fret-open.wav' },
  { id: 'fret-12th', key: 'fret12th', geom: 'fret-12th', file: 'fret-12th.wav' },
  { id: 'stiff-control', key: 'stiffControl', geom: 'stiff-control', file: 'stiff-control.wav' },
];

// ═════════════════════════════════════════════════════════════════════════════
section('files the page needs');
for (const f of ['index.html', 'instrument.js', 'inharm.js']) {
  ok(existsSync(join(PAGE_DIR, f)), `public/strata/${SLUG}/${f} exists`);
}
{
  let bytes = 0;
  for (const f of readdirSync(SPEC_DIR)) bytes += statSync(join(SPEC_DIR, f)).size;
  ok(bytes < 3 * 1024 * 1024, `shipped specimens are under the 3 MB budget (${(bytes / 1048576).toFixed(2)} MB)`);
}

// ═════════════════════════════════════════════════════════════════════════════
section('the specimens regenerate byte for byte');
{
  const tmp = mkdtempSync(join(tmpdir(), 'inharm-verify-'));
  mkdirSync(join(tmp, 'spec')); mkdirSync(join(tmp, 'gate'));
  const want = JSON.parse(readFileSync(join(HERE, 'hashes.json'), 'utf8'));
  const { createHash } = await import('node:crypto');
  const shaOf = (p) => createHash('sha256').update(readFileSync(p)).digest('hex');
  for (const s of SPECIMENS) {
    const b = s.build();
    const r = writeWav(join(tmp, 'spec', s.file), { sampleRate: SR, seconds: b.seconds }, b.fn);
    const committed = shaOf(join(SPEC_DIR, s.file));
    ok(r.sha256 === committed && r.sha256 === want[s.file],
      `${s.file} regenerates to the committed bytes`, `${r.sha256.slice(0, 12)} vs ${committed.slice(0, 12)}`);
  }
  for (const s of GATE_FILES) {
    const b = s.build();
    const r = writeWav(join(tmp, 'gate', s.file), { sampleRate: SR, seconds: b.seconds }, b.fn);
    const committed = shaOf(join(GATE_DIR, s.file));
    ok(r.sha256 === committed && r.sha256 === want[s.file],
      `gate/${s.file} regenerates to the committed bytes`, `${r.sha256.slice(0, 12)} vs ${committed.slice(0, 12)}`);
  }
  rmSync(tmp, { recursive: true, force: true });
}

// ═════════════════════════════════════════════════════════════════════════════
section('the physics that generated them');
// The two limits the clamped-end determinant has to collapse to. These are the only checks
// that the transcendental condition in strings.mjs is the right equation at all.
{
  // EI -> 0 with T fixed: the roots must approach the ideal string's n f0.
  const g = { d: 1e-9, L: 0.62, f0: 196 };
  const c = stringConstants(g);
  const roots = clampedPartials(c, 5);
  let worst = 0;
  for (let n = 1; n <= 5; n++) worst = Math.max(worst, Math.abs(roots[n - 1] - n * 196) / (n * 196));
  ok(worst < 1e-6, `with the bending term driven to zero the clamped roots become the ideal string (worst ${worst.toExponential(2)})`);
}
{
  // T -> 0: the clamped-clamped BEAM, whose eigenvalues solve cos(kL)cosh(kL) = 1, giving
  // frequency ratios 1 : 2.7565 : 5.4039 against the first mode. Fletcher's string equation
  // has to contain the beam as its zero-tension limit or it is not the right equation.
  const rho = 7850, d = 1e-3, L = 0.5;
  const A = Math.PI * d * d / 4, I = Math.PI * Math.pow(d, 4) / 64, rhoL = rho * A;
  const c = { E: STEEL.E, I, rhoL, T: 1e-9, L, f0: 20, B: 1 };
  const roots = clampedPartials(c, 3);
  near(roots[1] / roots[0], 2.75654, 2e-3, 'at zero tension the second mode is 2.7565 times the first, the clamped-clamped beam');
  near(roots[2] / roots[0], 5.40392, 5e-3, 'and the third is 5.4039 times the first');
}
// The geometry shortcut the page states must equal the full constant.
for (const [name, g] of Object.entries(GEOMETRY)) {
  const c = stringConstants(g);
  near(bFromGeometry(g) / c.B, 1, 1e-12, `B = pi^2 E d^2/(64 rho L^4 f0^2) matches pi^2 E I/(T L^2) for ${name}`);
}
// Nothing synthesised may sit above Nyquist, or the specimen contains energy no model here
// predicts and "exact by construction" is false.
{
  let worstHz = 0;
  for (const name of Object.keys(GEOMETRY)) {
    const b = stiffSpecimen(name, { seconds: 1, onset: 0.1, seed: 1 });
    worstHz = Math.max(worstHz, b.clamped[b.clamped.length - 1]);
  }
  const hz = harmonicSpecimen({ seconds: 1, onset: 0.1, seed: 1 });
  worstHz = Math.max(worstHz, hz.clamped[hz.clamped.length - 1]);
  ok(worstHz < NYQ_FRAC * SR, `no synthesised partial sits above ${NYQ_FRAC} of the sample rate (worst ${worstHz.toFixed(0)} Hz)`);
}

// ═════════════════════════════════════════════════════════════════════════════
section('the clamped-versus-pinned model gap the page claims');
// The page says the clamped end acts almost entirely as a common factor on every partial,
// well fitted by 1 + (2/pi)sqrt(B) + (4/pi^2)B, which the fit absorbs into F and not into B,
// and then states three leftovers in B, to two decimal places each. Those three numbers are
// FORMATTED HERE from the recomputation and string-matched against the page, rather than
// checked against a hand-set band that would pass whether or not the printed number is right.
// An earlier draft asserted a band of [-2.6, -2.0] per cent under a page that printed -2.6
// while this file printed -2.53, and both halves stayed green.
const gapOf = (name) => {
  const c = stringConstants(GEOMETRY[name]);
  const roots = clampedPartials(c, 30).filter((f) => f < NYQ_FRAC * SR);
  const fit = fitPinned(roots);
  return { rel: fit.B / c.B - 1, fit, c };
};
for (const [name, g] of Object.entries(GEOMETRY)) {
  const { fit, c } = gapOf(name);
  const predicted = 1 + 2 * Math.sqrt(c.B) / Math.PI + 4 * c.B / (Math.PI * Math.PI);
  ok(Math.abs(fit.F / g.f0 / predicted - 1) < 3e-3,
    `${name}: the clamped shift in F is the common factor 1+(2/pi)sqrt(B)+(4/pi^2)B to 0.3 per cent`,
    `got ${(fit.F / g.f0).toFixed(6)}, predicted ${predicted.toFixed(6)}`);
}
// The slate's four stiff strings, which are the set the page's sentence names.
const SLATE_GEOM = ['fret-open', 'fret-12th', 'stiff-anchor', 'stiff-control'];
const slateGaps = SLATE_GEOM.map((n) => ({ name: n, rel: gapOf(n).rel, B: stringConstants(GEOMETRY[n]).B }));
{
  const flexible = slateGaps.reduce((a, b) => (b.B < a.B ? b : a));
  const stiffest = slateGaps.reduce((a, b) => (b.B > a.B ? b : a));
  const biggestUp = slateGaps.reduce((a, b) => (b.rel > a.rel ? b : a));
  const pc = (r, d) => (r * 100).toFixed(d);
  ok(html.includes(`<span class="mono">+${pc(flexible.rel, 2)}</span> per cent on the`),
    `the page prints +${pc(flexible.rel, 2)} per cent for the most flexible string on the slate (${flexible.name})`);
  ok(html.includes(`<span class="mono">+${pc(biggestUp.rel, 2)}</span> per cent at its largest`),
    `and +${pc(biggestUp.rel, 2)} per cent as the largest positive gap anywhere on the slate (${biggestUp.name})`);
  ok(html.includes(`<span class="mono">&minus;${pc(-stiffest.rel, 1)}</span> per cent on the stiffest`),
    `and -${pc(-stiffest.rel, 1)} per cent on the stiffest (${stiffest.name}), each formatted here from the recomputation and matched against the page`);
  ok(flexible.name === 'fret-open' && stiffest.name === 'stiff-control' && biggestUp.name === 'fret-12th',
    'and the three strings those numbers belong to are the ones the sentence describes');
  ok(slateGaps.every((g) => g.rel <= biggestUp.rel && g.rel >= stiffest.rel),
    'with no string on the slate outside the range the page states');
}

// ═════════════════════════════════════════════════════════════════════════════
section('the truths the page declares are the truths the geometry gives');
for (const s of SLATE) {
  const declared = DECL.values[s.key];
  if (s.geom === null) { ok(declared === 0, `${s.id}: declared truth is exactly 0`); continue; }
  const exact = stringConstants(GEOMETRY[s.geom]).B;
  ok(Math.abs(declared / exact - 1) < 5e-5,
    `${s.id}: the declared truth ${declared} is the geometry's B to five figures`, `exact ${exact}`);
}
{
  const r = DECL.values.fret12th / DECL.values.fretOpen;
  near(r, 4, 1e-3, 'the shipped fret pair differs by exactly the factor of four the model predicts');
}

// ═════════════════════════════════════════════════════════════════════════════
section('the shipped estimator on the shipped specimens');
const results = {};
for (const s of SLATE) {
  const w = readWav(join(SPEC_DIR, s.file));
  const r = IH.estimate(w);
  results[s.id] = r;
  const truth = DECL.values[s.key], tol = tolOf(s.id);
  ok(!r.refused, `${s.id}: the estimator returns a number`, r.refused && r.refused.reason);
  if (r.refused) continue;
  ok(Math.abs(r.value - truth) <= tol,
    `${s.id}: B = ${r.value.toExponential(4)} is inside the declared tolerance of ${truth.toExponential(4)}`,
    `off by ${Math.abs(r.value - truth).toExponential(3)}, tolerance ${tol.toExponential(3)}`);
  ok(r.uncertainty <= tol,
    `${s.id}: the claimed 2 sigma (${r.uncertainty.toExponential(2)}) is no wider than the tolerance it is judged against`);
}
{
  const z = results['harmonic-zero'];
  ok(Math.abs(z.value) < 1e-6, `the string with no stiffness reads |B| = ${Math.abs(z.value).toExponential(2)}, under 1e-6`);
  ok(Math.abs(z.value) <= z.uncertainty,
    'and its interval covers zero, so the page can say "not distinguishable from zero" rather than inventing a small stiffness');
  // The claim the page and instrument.js make is about the TOLERANCE, not about the number
  // that happened to come back: 1e-6 is nearly forty times below the smallest B any string
  // with stiffness on this page has. Assert that, and the measured value separately.
  const ratio = DECL.values.fretOpen / tolOf('harmonic-zero');
  ok(ratio >= 39 && instrumentJs.includes('nearly forty times below'),
    `the 1e-6 bound is ${ratio.toFixed(1)} times below the smallest B with stiffness on the slate, which is the "nearly forty times" instrument.js states`);
  ok(Math.abs(z.value) < DECL.values.fretOpen / 39,
    'and the measured value clears the same bound, which is what makes it a bound and not a shrug');
}
{
  // The page says the delta-method interval is the standard first-order treatment and not the
  // only one, and that Fieller's exact interval agrees with it to better than 1e-5 here. That
  // is a checkable claim, so it is checked: Fieller solves the quadratic
  //   (b - t a)^2 = t^2 (varB - 2 t covAB + t^2 varA)  in the ratio, from the same OLS moments.
  const fieller = (f, t) => {
    const A = f.a * f.a - t * t * f.varA;
    const Bq = -2 * (f.a * f.b - t * t * f.covAB);
    const Cq = f.b * f.b - t * t * f.varB;
    const disc = Bq * Bq - 4 * A * Cq;
    if (!(A > 0) || !(disc >= 0)) return null;
    const r = Math.sqrt(disc);
    return ((-Bq + r) / (2 * A) - (-Bq - r) / (2 * A)) / 2;
  };
  let worst = 0;
  for (const s of SLATE) {
    const r = results[s.id];
    const fit = IH.fitStiffString(r.diagnostics.partials);
    const half = fieller(fit.fit, 2);
    ok(half !== null, `${s.id}: Fieller's interval exists, so the intercept is well enough determined for the first-order form to be safe`);
    if (half !== null) worst = Math.max(worst, Math.abs(half / r.uncertainty - 1));
  }
  ok(worst < 1e-5, `Fieller's exact interval and the delta-method interval this page prints agree to ${worst.toExponential(1)}, better than the 1 part in 100,000 the page claims`);
  ok(html.includes('better than one part in\n    100,000 on all five shipped strings'), 'and the page states that comparison rather than calling the delta method the only honest choice');
}
{
  const r = results['fret-12th'].value / results['fret-open'].value;
  near(r, 4, 0.05, `the fret ratio MEASURED through the full pipeline comes back at ${r.toFixed(4)}, not just in the geometry`);
}
{
  // The page states the RANGE the free exponent lands in, so the range is recomputed here,
  // rounded outward to the three decimals the page prints, and string-matched. A hand-set
  // band of +/- 0.06 stood behind this sentence once, which would have passed at p = 1.94
  // under a page claiming three digits.
  const ps = ['stiff-anchor', 'fret-open', 'fret-12th', 'stiff-control'].map((id) => results[id].diagnostics.exponent);
  const lo = (Math.floor(Math.min(...ps) * 1000) / 1000).toFixed(3);
  const hi = (Math.ceil(Math.max(...ps) * 1000) / 1000).toFixed(3);
  ok(html.includes(`between <span class="mono">${lo}</span> and\n    <span class="mono">${hi}</span>`),
    `the four stiff strings return p in [${lo}, ${hi}], which is the range the page prints`,
    ps.map((p) => p.toFixed(4)).join(' '));
  for (const id of ['stiff-anchor', 'fret-open', 'fret-12th', 'stiff-control']) {
    const d = results[id].diagnostics;
    ok(d.exponent >= Number(lo) && d.exponent <= Number(hi),
      `${id}: refitting with the exponent free returns p = ${d.exponent.toFixed(4)}, inside the bounds the page states`);
  }
  const stiffest = ps[3];
  ok(Math.min(...ps) === stiffest,
    `and the worst of the four is the stiffest string (p = ${stiffest.toFixed(4)}), which is what the page says it is`);
}
for (const id of SLATE.map((s) => s.id)) {
  ok(results[id].diagnostics.nPartials >= C.minPartials,
    `${id}: ${results[id].diagnostics.nPartials} partials survived the ${C.promDb} dB prominence gate`);
}

// ═════════════════════════════════════════════════════════════════════════════
section('the trap, and the window sweep that has to catch it');
const trap = readWav(join(SPEC_DIR, 'glide-trap.wav'));
const trapSingle = IH.estimate(trap);
const trapSweep = await IH.sweep(trap);
const trapFlat = IH.flatness(trapSweep);
ok(trapSingle.value > 1e-6,
  `at the page's own ${C.windowSeconds} s window the estimator invents B = ${trapSingle.value.toExponential(3)} for a string whose true B is exactly 0`);
{
  const worst = trapSweep.filter((r) => r.B !== null).reduce((a, b) => (b.B > a.B ? b : a));
  ok(worst.B > DECL.values.fretOpen,
    `and at ${worst.windowSeconds} s it invents ${worst.B.toExponential(3)}, more than the true B of the plain guitar string on the slate (${DECL.values.fretOpen.toExponential(3)})`);
  ok(worst.B / trapSweep[0].B > 5, `the fabricated B climbs by more than five times across the sweep (${(worst.B / trapSweep[0].B).toFixed(1)}x)`);
}
ok(trapFlat.verdict === 'not-stiffness', `the flatness test FIRES on the trap and refuses the number (verdict: ${trapFlat.verdict})`);
ok(Math.abs(trapSingle.diagnostics.exponent - 2) > 2 * trapSingle.diagnostics.exponentSigma,
  `and the exponent test rejects it too: p = ${trapSingle.diagnostics.exponent.toFixed(3)} +/- ${trapSingle.diagnostics.exponentSigma.toFixed(3)}, which excludes 2`);
{
  const anchorFlat = IH.flatness(await IH.sweep(readWav(join(SPEC_DIR, 'stiff-anchor.wav'))));
  ok(anchorFlat.verdict === 'flat', `the same test passes real stiffness (anchor verdict: ${anchorFlat.verdict})`);
  const zeroFlat = IH.flatness(await IH.sweep(readWav(join(SPEC_DIR, 'harmonic-zero.wav'))));
  ok(zeroFlat.verdict === 'flat',
    `and passes a string with no stiffness at all rather than calling a flat line at zero contaminated (verdict: ${zeroFlat.verdict})`);
}
{
  // The trap and the harmonic control differ ONLY by the glide, which is the whole claim.
  const a = harmonicSpecimen({ seconds: 3.2, onset: 0.15, seed: 20260818, glideCents: 0 });
  const b = harmonicSpecimen({ seconds: 3.2, onset: 0.15, seed: 20260818, glideCents: GLIDE_CENTS });
  ok(a.clamped.length === b.clamped.length && a.clamped.every((f, i) => f === b.clamped[i]),
    'the trap and the harmonic control are the same ladder, the same seed and the same envelope, differing only in the glide');
}
{
  // The flatness rule must be able to fail in the other direction too: a sweep that is flat
  // by construction must not be called contaminated, and one that climbs must not be called
  // flat. Feed the judge synthetic rows so the rule itself is exercised, not just the data.
  const flatRows = [0.3, 0.5, 0.8].map((w, i) => ({ windowSeconds: w, B: 1e-4 + i * 1e-9, uncertainty: 1e-6, refused: null, nPartials: 20 }));
  const climbRows = [0.3, 0.5, 0.8].map((w, i) => ({ windowSeconds: w, B: 1e-5 * (i + 1) * 3, uncertainty: 1e-9, refused: null, nPartials: 20 }));
  ok(IH.flatness(flatRows).verdict === 'flat', 'the flatness rule calls a genuinely flat sweep flat');
  ok(IH.flatness(climbRows).verdict === 'not-stiffness', 'and a genuinely climbing sweep not-stiffness');
  ok(IH.flatness([{ windowSeconds: 0.3, B: null, uncertainty: null, refused: { reason: 'x' }, nPartials: null }]).verdict === 'inconclusive',
    'and says inconclusive rather than guessing when too few windows produced a number');

  // The contaminated branch, which nothing on the page exercises: the shipped anchor sweeps
  // flat and the trap sweeps not-stiffness, so a claim made about this branch can rot unseen.
  // It did: the page said "the interval below is widened to cover the drift" while the readout
  // printed the single fit's own 2 sigma, because the widened number was computed and never
  // read. Both halves are checked here now, on rows built to land in that branch.
  const drift = [0.3, 0.5, 0.8].map((w, i) => ({ windowSeconds: w, B: 1.0e-4 + i * 5e-6, uncertainty: 1e-6, refused: null, nPartials: 20 }));
  const dFlat = IH.flatness(drift);
  ok(dFlat.verdict === 'contaminated', 'a sweep that drifts past the error bars but not past half of B is called contaminated', dFlat.verdict);
  const wide = IH.reportedInterval(1.0e-4, 1e-6, dFlat);
  ok(wide.widened && wide.uncertainty > 1e-6,
    `and the interval reportedInterval hands back is widened, ${wide.uncertainty.toExponential(2)} against the single fit's 1.00e-6`);
  ok(drift.every((r) => r.B - r.uncertainty >= 1.0e-4 - wide.uncertainty && r.B + r.uncertainty <= 1.0e-4 + wide.uncertainty),
    'and it covers every window in the sweep, error bars included, which is what "widened to cover the drift" has to mean');
  const same = IH.reportedInterval(1e-4, 1e-6, IH.flatness(flatRows));
  ok(same.uncertainty === 1e-6 && same.widened === false,
    'while a flat sweep leaves the fit\'s own interval exactly alone');
  ok(/const rep = IH\.reportedInterval\(B, out\.uncertainty, flat\);/.test(instrumentJs)
    && /bLine\(B, rep\.uncertainty\)/.test(instrumentJs) && /rep\.widened/.test(instrumentJs),
    'and the readout prints the interval that call returns and words the sentence off the same flag, so the widening cannot be described without being applied');
  ok(/flat\.verdict === 'inconclusive'/.test(instrumentJs),
    "the readout has an arm for the fourth verdict too, rather than letting inconclusive fall through to another verdict's copy");
}
{
  // ONE payload constructor, for the shipped WAVs and for the microphone alike. The page tells
  // the reader the estimator "is handed samples and a sample rate and nothing else, so it has
  // no way to know which is which"; an earlier draft passed the live capture's `processing` and
  // `settings` fields straight through, which was a provenance tag on exactly one path.
  ok(/function payload\(samples, sampleRate, seconds\) \{\s*return \{ samples, sampleRate, seconds \};\s*\}/.test(instrumentJs),
    'instrument.js builds every estimator payload through one three-argument constructor');
  ok(!/\{\s*samples:/.test(instrumentJs),
    'and no second payload literal exists anywhere in it, so the live path cannot carry a field a specimen does not');
  ok(/inst\.measure\(cap\.signal\)/.test(instrumentJs) && /inst\.tryMeasure\(\(await captureLive\(.+\)\)\.signal\)/.test(instrumentJs),
    'both the reader\'s button and the gate\'s probeLive hand the estimator that payload and not the capture wrapper around it');
  ok(/AW\.sensors\.capabilities\(\)\.microphone/.test(instrumentJs.slice(instrumentJs.indexOf('function liveError'))),
    'and a failed capture is only called a missing microphone API when capabilities() agrees that it is one');
}

// ═════════════════════════════════════════════════════════════════════════════
section('the control on the control: a hard-coded estimator must fail this slate');
{
  const mk = (estimate) => AW.anchor.instrument({
    id: 'verify-slate', quantity: 'B', unit: '', estimate,
    specimens: SLATE.map((s) => ({
      id: s.id, role: s.id === 'stiff-anchor' ? 'anchor' : 'control',
      label: s.id,
      truth: { value: DECL.values[s.key], tol: tolOf(s.id), why: 'read out of the shipped instrument.js by the verifier' },
      load: () => readWav(join(SPEC_DIR, s.file)),
    })),
  });
  const real = mk(IH.estimate);
  await real.runAll();
  ok(real.armed(), 'the real estimator arms the slate that the shipped page declares', real.blockedBecause());

  const stub = mk(() => ({ value: DECL.values.stiffAnchor, uncertainty: tolOf('stiff-anchor') / 10 }));
  await stub.runAll();
  ok(!stub.armed(), 'a stub that always returns the anchor value does NOT arm it');
  const rows = stub.report().specimens;
  ok(rows.find((r) => r.id === 'stiff-anchor').pass === true, 'the stub sails through the anchor, as it must, or the test would prove nothing');
  ok(rows.filter((r) => r.role === 'control' && r.pass === false).length === 4, 'and dies on all four controls at once');

  const probe = await AW.anchor.stubProbe(real);
  ok(probe.armed === false, 'AW.anchor.stubProbe, the same call the page makes on your device, also refuses to arm');
}
{
  // The kit's own vacuity guard, exercised on THIS page's numbers: a control that sits inside
  // the anchor's tolerance must be refused at construction.
  let threw = null;
  try {
    AW.anchor.instrument({
      id: 'vacuous', quantity: 'B', unit: '', estimate: () => ({ value: 0, uncertainty: 0 }),
      specimens: [
        { id: 'a', role: 'anchor', truth: { value: DECL.values.stiffAnchor, tol: tolOf('stiff-anchor'), why: 'the shipped anchor' }, load: () => ({}) },
        { id: 'b', role: 'control', truth: { value: DECL.values.stiffAnchor * 1.001, tol: tolOf('stiff-anchor'), why: 'deliberately too close' }, load: () => ({}) },
      ],
    });
  } catch (e) { threw = e; }
  ok(threw && threw.name === 'AnchorSpecError', 'a control placed inside the anchor tolerance is refused at construction, not at run time');
}

// ═════════════════════════════════════════════════════════════════════════════
section('the refusal paths, each fed a signal built to trigger it');
{
  const silent = { samples: new Float64Array(SR * 2), sampleRate: SR };
  const r = IH.estimate(silent);
  ok(r.refused && r.refused.reason === 'no-onset', 'silence refuses as no-onset rather than reporting a number', JSON.stringify(r.refused || r.value));
}
{
  const tmp = mkdtempSync(join(tmpdir(), 'inharm-ref-'));
  const hiss = noise(0.0009, 3);
  writeWav(join(tmp, 'sine.wav'), { sampleRate: SR, seconds: 3 },
    (t) => 0.45 * Math.exp(-t / 1.2) * Math.sin(2 * Math.PI * 220 * t) + hiss(t));
  const r = IH.estimate(readWav(join(tmp, 'sine.wav')));
  ok(r.refused && r.refused.reason === 'too-few-partials',
    'one pure sine refuses as too-few-partials: B needs the high ones and they are not there', JSON.stringify(r.refused || r.value));
  const loud = noise(0.06, 11);
  writeWav(join(tmp, 'hiss.wav'), { sampleRate: SR, seconds: 3 }, (t) => Math.exp(-t / 1.2) * loud(t));
  const h = IH.estimate(readWav(join(tmp, 'hiss.wav')));
  ok(h.refused, `pure noise refuses (${h.refused ? h.refused.reason : 'it did not, it returned ' + h.value})`);
  rmSync(tmp, { recursive: true, force: true });
}
{
  const short = { samples: new Float64Array(1000), sampleRate: SR };
  const r = IH.estimate(short);
  ok(r.refused && r.refused.reason === 'too-short', 'a recording shorter than the window refuses as too-short');
}
{
  // A recording long enough for the window, but with the pluck too late in it. This is the
  // case a naive implementation handles by quietly sliding the window earlier, which would
  // silently analyse the wrong part of the recording.
  const tmp = mkdtempSync(join(tmpdir(), 'inharm-late-'));
  const b = stiffSpecimen('stiff-anchor', { seconds: 3.2, onset: 2.6, seed: 7 });
  writeWav(join(tmp, 'late.wav'), { sampleRate: SR, seconds: 3.2 }, b.fn);
  const late = readWav(join(tmp, 'late.wav'));
  const r = IH.estimate(late, { windowSeconds: 1.2 });
  ok(r.refused && r.refused.reason === 'window-too-long',
    'a pluck too late in the recording for the window refuses as window-too-long rather than quietly sliding the window earlier',
    JSON.stringify(r.refused || r.value));
  const rows = await IH.sweep(late, { seconds: [0.3, 1.2] });
  ok(rows[0].B !== null && rows[1].refused,
    'and a sweep that cannot fit one of its windows drops that point and keeps the rest, rather than failing whole');
  rmSync(tmp, { recursive: true, force: true });
}
{
  const w = readWav(join(SPEC_DIR, 'stiff-anchor.wav'));
  const r = IH.estimate(w, { windowSeconds: 8 });
  ok(r.refused && r.refused.reason === 'too-short',
    'a window longer than the whole recording refuses as too-short before it looks for anything');
}
{
  ok(IH.estimate({ samples: null, sampleRate: SR }).refused.reason === 'no-signal', 'no samples at all refuses as no-signal');
}
{
  // THE FREE PHYSICAL REFUSAL, added 2026-08-17 after the blinded re-derivation pointed out
  // that this page had no path for it. B = pi^2 E I / (T L^2) is positive for every string
  // that exists, so a 2 sigma interval lying entirely below zero is proof of contamination
  // that costs nothing and needs no tolerance. A RISING pitch glide reaches it: the same
  // ladder as the trap, glided the other way.
  const tmp = mkdtempSync(join(tmpdir(), 'inharm-neg-'));
  const rise = harmonicSpecimen({ seconds: 3.2, onset: 0.15, seed: 20260818, glideCents: -GLIDE_CENTS });
  writeWav(join(tmp, 'rise.wav'), { sampleRate: SR, seconds: 3.2 }, rise.fn);
  const r = IH.estimate(readWav(join(tmp, 'rise.wav')));
  ok(r.refused && r.refused.reason === 'negative-stiffness',
    'a ladder that goes FLAT as it rings refuses as negative-stiffness rather than reporting a negative B',
    JSON.stringify(r.refused || r.value));
  ok(r.refused && r.diagnostics.B + 2 * r.diagnostics.sigmaB < 0,
    `and it really is confidently negative: B = ${r.diagnostics ? r.diagnostics.B.toExponential(2) : '?'} with 2 sigma entirely below zero`);
  rmSync(tmp, { recursive: true, force: true });

  // The negative counterpart, which is the half that stops this refusal from being a rule that
  // fires on everything: the string with B EXACTLY ZERO must still be measured, because its
  // interval covers zero rather than sitting below it. If this ever flips, the anchor slate
  // loses its only control on an estimator that finds stiffness in everything.
  const zero = IH.estimate(readWav(join(SPEC_DIR, 'harmonic-zero.wav')));
  ok(!zero.refused, 'while the string with no stiffness at all is still measured, not refused as negative');
  ok(Math.abs(zero.value) <= zero.uncertainty,
    `because its interval COVERS zero (B = ${zero.value.toExponential(2)}, 2 sigma ${zero.uncertainty.toExponential(2)}) rather than lying below it`);
  for (const row of await IH.sweep(readWav(join(SPEC_DIR, 'harmonic-zero.wav')))) {
    ok(row.B !== null, `and at every window in the sweep too (${row.windowSeconds} s)`);
  }
  // THE BAND EDGE. A pitch search that ends on the edge of its own range has not found a
  // pitch, and before 2026-08-17 this page took the edge for a measurement: a bass guitar's
  // low E came back as a confident B with a flat window sweep. Every string a reader is
  // plausibly holding that sits below the band is driven through here.
  const mkString = (f0, B, seconds = 4.0, seed = 777) => {
    const freqs = pinnedPartials(f0, B, 60).filter((x) => x < NYQ_FRAC * SR);
    const fn = pluck({ freqs, onset: 0.15, seed, tau0: 2.0 });
    const n = Math.round(seconds * SR), s = new Float64Array(n);
    for (let i = 0; i < n; i++) s[i] = fn(i / SR);
    return { samples: s, sampleRate: SR, seconds };
  };
  for (const [label, f0, B] of [['a five-string bass low B', 30.87, 8e-6], ['a bass guitar low E', 41.20, 1e-5],
    ['a bass guitar A', 55.00, 1.5e-5], ["a piano's A0", 27.50, 4e-5]]) {
    const out = IH.estimate(mkString(f0, B));
    ok(out.refused && out.refused.reason === 'pitch-out-of-band',
      `${label} at ${f0} Hz, below the ${C.f0Lo} Hz floor, refuses as pitch-out-of-band instead of reporting a number`,
      JSON.stringify(out.refused || out.value));
  }
  // and the other half: strings just INSIDE the band must still be measured, or the new rule
  // has simply narrowed the page rather than made it honest.
  for (const [f0, B] of [[65.41, 3e-5], [82.41, 2e-5], [110, 5e-5]]) {
    const out = IH.estimate(mkString(f0, B));
    ok(!out.refused && Math.abs(out.value / B - 1) < 0.05,
      `while a string at ${f0} Hz, just inside the floor, is measured and comes back within 5 per cent (${out.refused ? 'refused ' + out.refused.reason : out.value.toExponential(2)})`);
  }
  ok(html.includes('<span class="mono">B = &minus;3.7e-3</span>'),
    'and the free-choice table prints the wrong answer this page used to give a bass guitar, rather than quietly fixing it');

  ok(/fit\.B \+ 2 \* fit\.sigmaB < 0/.test(inharmJs),
    'the rule really is "the whole 2 sigma interval below zero" and not "B below zero", which would fire on half the flexible strings there are');
  ok(html.includes('A fit whose whole interval sits <i>below</i> zero'),
    'and the page states the rule in those terms rather than promising a stricter one');
}

// ═════════════════════════════════════════════════════════════════════════════
section('the arithmetic the page prints from B');
{
  near(IH.octaveStretchCents(0), 0, 1e-12, 'a string with no stiffness forces no octave stretch at all');
  const B = 1e-3;
  near(IH.octaveStretchCents(B), 1200 * Math.log2(Math.sqrt((1 + 4 * B) / (1 + B))),
    1e-9, 'the beatless octave is 600 log2((1+4B)/(1+B)) cents wide of 2:1');
  near(IH.partialCents(4e-4, 10), 600 * Math.log2(1 + 4e-4 * 100), 1e-12, 'partial n sits 600 log2(1 + B n^2) cents above n times the fundamental');
  ok(IH.octaveStretchCents(1e-3) > 0 && IH.octaveStretchCents(1e-3) < IH.octaveStretchCents(1e-2),
    'and the stretch grows with B, monotonically, over the range a real instrument spans');
  near(IH.bAfterLengthRatio(1e-4, 0.5), 4e-4, 1e-15, 'halving the speaking length at fixed tension quadruples B');

  // WHICH PAIR OF PARTIALS YOU SILENCE is a free choice the page used to make silently, and
  // the blinded re-derivation called it the biggest single lever on the flagship number. The
  // page now prints all three, so all three are recomputed here from the definition rather
  // than from the shipped helper: match the lower note's partial 2j to the upper note's j.
  for (const j of [1, 2, 3]) {
    for (const B of [1e-5, 4.44e-4, 2.5e-3]) {
      const lower = 2 * j * Math.sqrt(1 + B * (2 * j) ** 2);   // lower note's partial 2j, in units of F_l
      const upper = j * Math.sqrt(1 + B * j * j);              // upper note's partial j, in units of F_u
      const ratio = lower / upper;                             // the F_u/F_l a beatless match forces
      near(IH.octaveStretchAt(B, j), 1200 * Math.log2(ratio / 2), 1e-9,
        `the ${2 * j}:${j} octave at B = ${B.toExponential(2)} is ${IH.octaveStretchAt(B, j).toFixed(4)} cents wide of 2:1, straight from setting those two partials equal`);
    }
  }
  ok(Math.abs(IH.octaveStretchAt(1e-5, 1) - IH.octaveStretchCents(1e-5)) < 1e-15,
    'and the j = 1 case is exactly the 2:1 formula the page derives in the open');
  {
    // The page says the 4:2 and 6:3 rules come out at four and nine times the 2:1 answer for
    // small B. That is a statement about a limit, so check it as one: the ratio has to
    // approach 4 and 9 as B falls, and it must NOT be asserted as exact at real stiffness.
    const small = 1e-7, big = 5e-3;
    near(IH.octaveStretchAt(small, 2) / IH.octaveStretchAt(small, 1), 4, 1e-4, 'as B falls the 4:2 rule approaches four times the 2:1 rule');
    near(IH.octaveStretchAt(small, 3) / IH.octaveStretchAt(small, 1), 9, 1e-4, 'and the 6:3 rule nine times it');
    ok(IH.octaveStretchAt(big, 3) / IH.octaveStretchAt(big, 1) < 8.5,
      `while at B = ${big} the factor has already fallen to ${(IH.octaveStretchAt(big, 3) / IH.octaveStretchAt(big, 1)).toFixed(2)}, so the page says "for B small" and not "always"`);
    ok(html.includes('For B small they come out at four times and nine times'),
      'and the page states it as the small-B limit it is');
  }
  ok(/id="cons-one"/.test(html) && /id="cons-two"/.test(html) && /id="cons-three"/.test(html)
    && /cons-two/.test(instrumentJs) && /cons-three/.test(instrumentJs),
    'the consequence panel has a slot for all three rules and instrument.js fills all three, so one cannot be quietly dropped back to a single number');
}

// ═════════════════════════════════════════════════════════════════════════════
// Everything in this section was added on 2026-08-17, in reconciliation against a blinded
// re-derivation of this page's claim that was produced without ever seeing the page. Three of
// its findings survived contact with the shipped code, and each one is a number the page now
// prints, so each one is recomputed here rather than asserted.
section('the choices a blinded re-derivation named, and the numbers the page now prints for them');
{
  // ONE. The partial ceiling is not only a precision knob. On a string whose ends are clamped
  // rather than hinged, fitting the pinned closed form gives a B that DEPENDS on how many
  // partials you fit, and the dependence changes sign. The page prints the two ends of that
  // range for two of its own specimens; recompute both from the exact clamped roots.
  const nMaxBias = (geom, N) => {
    const c = stringConstants(GEOMETRY[geom]);
    return (fitPinned(clampedPartials(c, N).slice(0, N)).B / c.B - 1) * 100;
  };
  for (const [geom, lo, hi] of [['stiff-anchor', '+0.46', '-0.37'], ['stiff-control', '+0.51', '-2.53']]) {
    const at6 = nMaxBias(geom, 6), at30 = nMaxBias(geom, 30);
    const f = (v) => (v >= 0 ? '+' : '') + v.toFixed(2);
    ok(f(at6) === lo, `${geom}: fitting six partials of the exact clamped string overstates B by ${f(at6)} per cent, which is what the page prints`, `got ${f(at6)}, page says ${lo}`);
    ok(f(at30) === hi, `${geom}: fitting thirty understates it by ${f(at30)} per cent, the other number the page prints`, `got ${f(at30)}, page says ${hi}`);
    ok(at6 > 0 && at30 < 0, `${geom}: and the bias really does change sign between the two, which is why the page calls the ceiling part of the answer`);
  }
  ok(html.includes('<span class="mono">+0.46</span> per cent high over six partials') &&
     html.includes('<span class="mono">&minus;0.37</span> per cent low over thirty'),
    'the free-choice table states those two numbers for the anchor');
  ok(html.includes('<span class="mono">+0.51</span> to\n        <span class="mono">&minus;2.53</span>'),
    'and those two for the stiffest string');
  {
    // The page claims the 30-partial cap binds below 720 Hz at every sample rate a browser
    // offers, which is what makes this one choice the same for every reader of a low string.
    const bindsBelow = C.nyqFrac * 44100 / C.nCap;
    ok(bindsBelow >= 660 && C.nyqFrac * 48000 / C.nCap >= 720,
      `the ceiling of ${C.nCap} binds below ${(C.nyqFrac * 48000 / C.nCap).toFixed(0)} Hz at 48 kHz and ${bindsBelow.toFixed(0)} Hz at 44.1 kHz`);
    for (const g of ['stiff-anchor', 'fret-open', 'fret-12th', 'stiff-control']) {
      ok(Math.floor(C.nyqFrac * 44100 / GEOMETRY[g].f0) >= C.nCap,
        `so ${g} reaches the same ${C.nCap} partials at 44.1 kHz as at 48 kHz, and the sample rate cannot move its answer`);
    }
  }
}
{
  // TWO. The clamped-versus-pinned gap is not a property of the specimens alone: a real nut or
  // agraffe is neither a hinge nor a clamp either. The page now says where that gap goes, and
  // the answer is that almost all of it lands on F. Recompute both halves.
  const c = stringConstants(GEOMETRY['fret-open']);
  const fit = fitPinned(clampedPartials(c, 30));
  const fPct = (fit.F / c.f0 - 1) * 100, bPct = (fit.B / c.B - 1) * 100;
  near(fPct, 0.4, 0.05, `at a plain guitar string's stiffness the clamped end moves F by ${fPct.toFixed(2)} per cent, which is the 0.4 the page prints`);
  near(bPct, 0.1, 0.05, `and B by only ${bPct.toFixed(2)} per cent, which is the 0.1 the page prints`);
  ok(Math.abs(fPct) > 3 * Math.abs(bPct),
    'so the termination is overwhelmingly an F effect at this stiffness, which is what the page tells the reader');
  const s = stringConstants(GEOMETRY['stiff-control']);
  const sPct = (fitPinned(clampedPartials(s, 30)).B / s.B - 1) * 100;
  near(Math.abs(sPct), 2.5, 0.05, `and reaches ${Math.abs(sPct).toFixed(2)} per cent in B on the stiffest specimen, the 2.5 the page prints`);
  ok(html.includes('applies to your string as well'),
    'and the page says the gap applies to the reader\'s own string, not only to the slate');
}
{
  // THREE. The unison bias. The page said "about ten per cent on a piano's middle range" for
  // months; that came from a planning note whose prototype was never run here, and neither the
  // blinded re-derivation nor this check can reproduce it. So build the unisons and measure.
  // Each voice is an independent pluck of the same ladder, detuned, summed. Unequal amplitudes
  // and unequal decays are included on purpose, because those are what the re-derivation
  // guessed the missing 9 per cent had to come from.
  const F0 = 261.63, B_TRUE = 4.44e-4;
  const base = pinnedPartials(F0, B_TRUE, 34).filter((f) => f < NYQ_FRAC * SR);
  const unison = (voices, seed) => {
    const fns = voices.map((v, i) => pluck({
      freqs: base.map((f) => f * Math.pow(2, v.cents / 1200)),
      onset: 0.15, amp: v.amp, tau0: v.tau0, seed: seed + i, noise: i === 0 ? 0.0009 : 0,
    }));
    const n = Math.round(4.0 * SR), out = new Float64Array(n);
    for (let i = 0; i < n; i++) { let s = 0; for (const fn of fns) s += fn(i / SR); out[i] = s; }
    return { samples: out, sampleRate: SR, seconds: 4.0 };
  };
  const MODELS = [
    ['one string, no unison at all', [{ cents: 0, amp: 0.42, tau0: 1.3 }]],
    ['three strings at +/-1.5 cents', [{ cents: -1.5, amp: 0.14, tau0: 1.3 }, { cents: 0, amp: 0.14, tau0: 1.3 }, { cents: 1.5, amp: 0.14, tau0: 1.3 }]],
    ['three strings at +/-3 cents', [{ cents: -3, amp: 0.14, tau0: 1.3 }, { cents: 0, amp: 0.14, tau0: 1.3 }, { cents: 3, amp: 0.14, tau0: 1.3 }]],
    ['two strings at +/-1 cent', [{ cents: -1, amp: 0.21, tau0: 1.3 }, { cents: 1, amp: 0.21, tau0: 1.3 }]],
    ['three at +/-1.5, unequal amplitude', [{ cents: -1.5, amp: 0.21, tau0: 1.3 }, { cents: 0, amp: 0.126, tau0: 1.3 }, { cents: 1.5, amp: 0.073, tau0: 1.3 }]],
    ['three at +/-1.5, unequal decay', [{ cents: -1.5, amp: 0.14, tau0: 1.3 }, { cents: 0, amp: 0.14, tau0: 0.8 }, { cents: 1.5, amp: 0.14, tau0: 0.5 }]],
    ['three at +/-3, unequal amplitude and decay', [{ cents: -3, amp: 0.21, tau0: 1.3 }, { cents: 0, amp: 0.126, tau0: 0.8 }, { cents: 3, amp: 0.073, tau0: 0.5 }]],
  ];
  let worst = 0, worstLabel = '';
  MODELS.forEach(([label, voices], i) => {
    const r = IH.estimate(unison(voices, 6100 + 10 * i));
    ok(!r.refused, `unison model "${label}" is measured rather than refused`, r.refused && r.refused.reason);
    if (r.refused) return;
    const pct = Math.abs(r.value / B_TRUE - 1) * 100;
    if (pct > worst) { worst = pct; worstLabel = label; }
    ok(pct < 10, `"${label}": B comes back ${pct.toFixed(2)} per cent off, nowhere near the ten per cent this page used to claim`);
  });
  ok(worst < 1, `the worst of the seven is "${worstLabel}" at ${worst.toFixed(2)} per cent, under the one per cent the page now prints`);
  ok(html.includes(`<span class="mono">${worst.toFixed(2)}</span> per cent at worst`),
    `and the page prints that recomputed figure, ${worst.toFixed(2)}, character for character`);
  ok(html.includes('never measured by anyone here') && html.includes('never run in this repository'),
    'and the page says where the retracted ten per cent came from rather than quietly deleting it');
  ok(!/Expect an answer good to about ten per cent/.test(html),
    'while the retracted claim itself is gone from the page as a claim');
  ok(html.includes('no real piano has ever been through'),
    'and does not let a bound on seven synthetic notes stand in for a real piano');
}
{
  // FOUR. Two checks that had no way to fail, both now given one.
  //
  // The free exponent is found by golden section inside a bracket. When there is no minimum
  // inside it the search walks to a wall and returns the wall, and the page used to print that
  // wall in bold with an error bar, as though the fit had found an exponent of six.
  const zero = IH.estimate(readWav(join(SPEC_DIR, 'harmonic-zero.wav')));
  ok(zero.diagnostics.exponentPegged === true,
    `on the string with no stiffness the exponent search really does end on its bracket (p = ${zero.diagnostics.exponent.toFixed(3)}), so there is something for the readout to catch`);
  ok(/exponentPegged/.test(instrumentJs) && /no minimum at all/.test(instrumentJs),
    'and the readout has an arm that says so instead of quoting the bracket edge as a value of p');
  for (const id of ['stiff-anchor', 'fret-open', 'fret-12th', 'stiff-control', 'glide-trap']) {
    const w = readWav(join(SPEC_DIR, id + '.wav'));
    ok(IH.estimate(w).diagnostics.exponentPegged === false,
      `while ${id}, which has a real minimum in p, is NOT flagged as pegged, so the flag discriminates`);
  }
  // The fret test's band is built from the reader's own two intervals, so it GROWS as the
  // measurement gets worse; past a point it covers 3 and 5 as well as 4 and the test says
  // "held" to every possible answer. All three arms are driven here, on the shipped rule.
  const FLOOR = Number(instrumentJs.match(/const FRET_FLOOR = ([\d.]+);/)[1]);
  ok(FLOOR > 0, `the fret floor is read out of the shipped instrument.js (${FLOOR}) rather than restated here`);
  const pair = (bo, uo, bf, uf) => IH.fretRatioVerdict({ value: bo, uncertainty: uo }, { value: bf, uncertainty: uf }, FLOOR);
  {
    const v = pair(1.37e-5, 1e-8, 5.48e-5, 4e-8);
    ok(v.verdict === 'held' && Math.abs(v.ratio - 4) < 0.01, `a clean pair at exactly four is held (ratio ${v.ratio.toFixed(3)}, band ${v.half.toFixed(2)})`);
  }
  {
    const v = pair(1.37e-5, 1e-8, 4.11e-5, 3e-8);
    ok(v.verdict === 'failed' && Math.abs(v.ratio - 3) < 0.01, `a clean pair at three FAILS, so the test can still fail (ratio ${v.ratio.toFixed(3)}, band ${v.half.toFixed(2)})`);
  }
  {
    // The case that used to be reported as a confirmation: a thin string on a resonant body,
    // where each partial is pulled a few cents and the two intervals are ~18 per cent each.
    const v = pair(1.44e-5, 2.5e-6, 5.24e-5, 9.2e-6);
    ok(v.verdict === 'no-power',
      `a pair whose own error bars span ${(v.ratio - v.half).toFixed(2)} to ${(v.ratio + v.half).toFixed(2)} is called no-power, not held (ratio ${v.ratio.toFixed(3)})`);
    ok(Math.abs(v.ratio - 4) <= v.half,
      'even though the old two-arm rule would have called that same pair a confirmation, which is what made it a test that could not fail');
  }
  ok(pair(0, 0, 1e-4, 1e-8).verdict === 'not-measured' && pair(-1e-6, 1e-8, 1e-4, 1e-8).verdict === 'not-measured',
    'and a zero or negative open-string B yields no verdict at all rather than a ratio through zero');
  ok(/IH\.fretRatioVerdict\(o, f, FRET_FLOOR\)/.test(instrumentJs) && !/const decisive/.test(instrumentJs),
    'the drawing code calls that rule rather than carrying a second copy of it');
  ok(html.includes('This did not test the prediction') === false,
    'and the third arm lives in the code that runs, not as prose on the page promising it');
}
{
  // FIVE. Whose sigma the flatness gate uses is a real choice, and the page now says which and
  // why. Both halves of its reason are recomputed: the spread on the zero string, and the
  // smallest sigma in that same sweep, which a stricter rule would have judged it against.
  const rows = (await IH.sweep(readWav(join(SPEC_DIR, 'harmonic-zero.wav')))).filter((r) => r.B !== null);
  const vals = rows.map((r) => r.B);
  const spread = Math.max(...vals) - Math.min(...vals);
  const minSigma = Math.min(...rows.map((r) => r.uncertainty / 2));
  ok(spread > C.flatSigmaMult * minSigma,
    `on the B = 0 control the spread is ${spread.toExponential(1)} against a smallest sigma of ${minSigma.toExponential(1)}, so a rule built on the smallest sigma would refuse the specimen that has to pass`);
  ok(html.includes(`spread\n        is ${spread.toExponential(1)} against a smallest sigma of ${minSigma.toExponential(1)}`),
    `and the page prints both of those recomputed numbers, ${spread.toExponential(1)} and ${minSigma.toExponential(1)}`);
  ok(html.includes('it is the <i>largest</i> in the sweep, which\n        errs permissive'),
    'and names which sigma the shipped rule uses, and which way it errs');
  ok(/Math\.max\.apply\(null, good\.map\(\(r\) => r\.uncertainty \/ 2\)\)/.test(inharmJs),
    'and the shipped code really does take the largest, so the page is describing the rule it runs');
}

// ═════════════════════════════════════════════════════════════════════════════
section('what the reader actually sees');
const CANONICAL = `https://artwaste.land/strata/${SLUG}/`;
const fmField = (name) => {
  const m = md.match(new RegExp('^' + name + ': "([\\s\\S]*?)"$', 'm'));
  return m ? m[1] : null;
};
const dek = fmField('dek'), plain = fmField('plain'), seoTitle = fmField('seoTitle'), title = fmField('title');
ok(html.includes(`<title>${seoTitle}</title>`), 'the page title is the frontmatter seoTitle, character for character');
ok(html.includes(`content="${dek}"`), 'the meta description is the frontmatter dek, character for character');
ok(html.includes(`<h1>${title}</h1>`), 'the H1 is the frontmatter title');
ok(html.includes(`<link rel="canonical" href="${CANONICAL}" />`), 'the canonical URL is right');
ok(fmField('seam') === 'number', 'the seam is one of the closed vocabulary, and it is "number"');
ok(md.includes('draft: false'), 'the page is not a draft');
ok(plain.length <= 420, `the plain card is ${plain.length} characters, inside the 420 limit`);
ok((plain.match(/\./g) || []).length <= 3, 'and three sentences or fewer');
{
  const targets = [...md.matchAll(/^\s+- to: ([\w-]+)$/gm)].map((m) => m[1]);
  ok(targets.length >= 2 && targets.length <= 4, `relates carries ${targets.length} edges`);
  const missing = targets.filter((t) => !existsSync(join(ROOT, 'src/content/strata', t + '.md')));
  ok(missing.length === 0, 'every relates target exists in src/content/strata', missing.join(', '));
}
{
  const m = html.match(/<script type="application\/ld\+json">([\s\S]*?)<\/script>/);
  ok(!!m, 'the page carries a JSON-LD block');
  const ld = JSON.parse(m[1]);
  ok(ld.headline === title, 'the JSON-LD headline is the frontmatter title, so a retracted framing cannot survive in the social card');
  ok(ld.name === seoTitle, 'and its name is the seoTitle');
  ok(ld.url === CANONICAL, 'and its url is the canonical URL');
}
{
  const opens = (html.match(/<script\b/g) || []).length;
  const closes = (html.match(/<\/script>/g) || []).length;
  ok(opens === closes, `every script tag is closed (${opens} open, ${closes} close)`);
  const b = html.lastIndexOf('</body>'), h = html.lastIndexOf('</html>');
  ok(b > 0 && h > b, 'the document closes its body and then its html, in that order');
  const own = [...html.matchAll(/<script src="([^"]+)"><\/script>/g)].map((m) => m[1]);
  ok(own.length === 5 && own.includes('./inharm.js') && own.includes('./instrument.js'),
    `the page loads its own five scripts (${own.join(' ')})`);
}
{
  // No third-party absolute URL anywhere in executable script content. The JSON-LD block is
  // data, not script, and is excluded on purpose; every other inline script and both sibling
  // modules are searched.
  const inline = [...html.matchAll(/<script(?![^>]*ld\+json)[^>]*>([\s\S]*?)<\/script>/g)].map((m) => m[1]).join('\n');
  const scripts = inline + '\n' + instrumentJs + '\n' + inharmJs;
  const urls = [...scripts.matchAll(/https?:\/\/[^\s'"`)]+/g)].map((m) => m[0])
    .filter((u) => !u.startsWith('https://artwaste.land'));
  ok(urls.length === 0, 'no absolute third-party URL appears in any executable script on this page', urls.join(' '));
}
{
  const files = { 'index.html': html, 'instrument.js': instrumentJs, 'inharm.js': inharmJs, 'the frontmatter': md };
  const bad = Object.entries(files).filter(([, s]) => s.includes('—')).map(([n]) => n);
  ok(bad.length === 0, 'no em dash in any file this page ships', bad.join(', '));
}
{
  // A path printed on the page is an instruction. Both must resolve.
  const paths = [...html.matchAll(/<code>node ([\w./-]+\.mjs)/g)].map((m) => m[1]);
  const missing = paths.filter((p) => !existsSync(join(ROOT, p)));
  ok(paths.length >= 2, `the page prints ${paths.length} runnable commands`);
  ok(missing.length === 0, 'every command the page prints names a file that exists', missing.join(' '));
}
{
  // The free-choice table's values are injected from C at run time, so what can drift is the
  // PROSE around them. These are the settings the prose names explicitly.
  ok(html.includes('60 cents of downward pitch glide'), `the page states the trap's glide, and the generator uses ${GLIDE_CENTS} cents`);
  ok(GLIDE_CENTS === 60, 'and the generator really does use 60 cents');
  ok(html.includes('0.5 second') && GLIDE_TAU === 0.5, `the page states the glide time constant and the generator uses ${GLIDE_TAU} s`);
  ok(html.includes('648 mm and at 324 mm'), 'the page states the shipped fret pair lengths');
  ok(Math.abs(GEOMETRY['fret-open'].L - 0.648) < 1e-9 && Math.abs(GEOMETRY['fret-12th'].L - 0.324) < 1e-9,
    'and the generator really does use 648 mm and 324 mm');
  // The reader is offered a full attestation, so it must not arrive full of float noise: the
  // kit writes tolerances as 7.959000000000001e-7 and the page's own tidy() exists for that.
  ok(/\$\('attest'\)\.textContent = tidy\(inst\.attest\(8\)\)/.test(instrumentJs),
    'the attestation panel goes through the same float tidying the slate does');
  {
    // Run the SHIPPED tidy, lifted out of instrument.js, rather than a copy of it here.
    const src = instrumentJs.match(/const tidy = \(s\) => [\s\S]*?\);\n/);
    const tidy = src ? new Function(`${src[0]} return tidy;`)() : null;
    ok(tidy && tidy('tolerance 7.959000000000001e-7, expected 0.0000031836000000000003, B 2.48e-3')
      === 'tolerance 7.959e-7, expected 3.184e-6, B 2.48e-3',
      'and that tidying really does catch both shapes the kit emits, while leaving a short number alone');
  }

  // Every source with a magnitude on the page carries its read status, and the one the two
  // magnitudes actually came from is named.
  ok(html.includes("ASTRA: The McNair Scholars'") && html.includes('<b>Read in full.</b>'),
    'the open companion the two quoted magnitudes come from is cited by name and marked read');
  ok(html.includes('one to two percentage point') && html.includes('absence of any overlap on wound'),
    'and the sources list says which magnitudes came from it');
  ok(!html.includes('standard piano wire tables'),
    'no claim about the contents of the Fletcher paper nobody here could open survives on the page');

  // Two things the page says it shows the reader, which have to be things it shows.
  ok(/residRmsHz2/.test(instrumentJs) && html.includes('is printed under the readout'),
    'the fit residual the "what this cannot do" list says is printed really is written into the meta line');
  for (const id of ['live-derived', 'live-meta', 'fret-you']) {
    ok(new RegExp(`id="${id}"[^>]*role="status"[^>]*aria-live="polite"`).test(html),
      `#${id}, which is filled in after a button press, is announced rather than changing in silence`);
  }
  ok(html.includes('doi:10.1121/1.1906888') && html.includes('twelve years earlier'),
    'and the page names the 1952 paper that stops it calling Fletcher 1964 the origin of the relation');

  // The two B values the page quotes in prose, each with the geometry it says they come from.
  const fo = GEOMETRY['fret-open'], sc = GEOMETRY['stiff-control'];
  ok(html.includes('3.98e-5, which is\n    what 0.33 mm plain steel gives at 648 mm and 246.94 Hz'),
    'the page quotes 3.98e-5 with the geometry it came from');
  ok(Math.abs(stringConstants(fo).B - 3.98e-5) < 5e-8 && fo.d === 3.30e-4 && fo.L === 0.648 && fo.f0 === 246.94,
    'and 0.33 mm at 648 mm and 246.94 Hz really is B = 3.98e-5', String(stringConstants(fo).B));
  ok(html.includes('2.48e-3, which is what 1.00 mm\n    gives at 390 mm and 261.63 Hz'),
    'the page quotes 2.48e-3 with the geometry it came from');
  ok(Math.abs(stringConstants(sc).B - 2.48e-3) < 5e-6 && sc.d === 1.00e-3 && sc.L === 0.39 && sc.f0 === 261.63,
    'and 1.00 mm at 390 mm and 261.63 Hz really is B = 2.48e-3', String(stringConstants(sc).B));

  // The runaway the page points at: at B = 0.01, partial 10 sits at 14.1 times the fundamental
  // and 600 cents sharp of ten times it.
  ok(html.includes('it sits at 14.1\n    times it, a full 600 cents sharp'), 'the page states where partial 10 lands at B = 0.01');
  near(10 * Math.sqrt(1 + 0.01 * 100) / 10, 1.41421, 5e-5, 'and partial 10 really is 14.1 times the fundamental at B = 0.01');
  near(IH.partialCents(0.01, 10), 600, 1e-9, 'and really is 600 cents sharp of ten times it');

  // The ideal-scaling claim in the consequence panel: halve L per octave, keep the wire, and
  // B goes as f0 squared. Checked by scaling a real geometry rather than by algebra alone.
  {
    const g = GEOMETRY['fret-open'];
    const up = { d: g.d, L: g.L / 2, f0: g.f0 * 2 };
    near(stringConstants(up).B / stringConstants(g).B, 4, 1e-9,
      'under ideal scaling, halving the length and doubling the pitch quadruples B, which is B proportional to f0 squared');
    ok(html.includes('B proportional to f0<sup>2</sup>'), 'and the page states it in those terms');
  }

  // The specimen labels on the page name dimensions; those have to be the generator's.
  const labelChecks = [
    ['stiff-anchor', '1.05 mm wire, 620 mm, 196 Hz', { d: 1.05e-3, L: 0.62, f0: 196.0 }],
    ['fret-open', '0.33 mm, 648 mm, open', { d: 3.30e-4, L: 0.648, f0: 246.94 }],
    ['stiff-control', '1.00 mm wire, 390 mm, 261.63 Hz', { d: 1.00e-3, L: 0.39, f0: 261.63 }],
  ];
  for (const [id, label, g] of labelChecks) {
    const gg = GEOMETRY[id];
    ok(instrumentJs.includes(label) && gg.d === g.d && gg.L === g.L && gg.f0 === g.f0,
      `the slate's label for ${id} names the dimensions the generator actually used`);
  }
}

// ═════════════════════════════════════════════════════════════════════════════
section('the live-sensor gate case');
{
  ok(caseJson.sensor === 'microphone' && caseJson.path === `/strata/${SLUG}/`, 'the case file points at this page and names the microphone');
  const a = resolve(ROOT, caseJson.inject.anchor.file), b = resolve(ROOT, caseJson.inject.control.file);
  ok(existsSync(a) && existsSync(b), 'both injected files exist');
  const ra = IH.estimate(readWav(a)), rb = IH.estimate(readWav(b));
  ok(Math.abs(ra.value - caseJson.inject.anchor.expect) <= caseJson.inject.anchor.tol,
    `the anchor injection really does measure ${caseJson.inject.anchor.expect} (offline: ${ra.value.toExponential(4)})`);
  ok(Math.abs(rb.value - caseJson.inject.control.expect) <= caseJson.inject.control.tol,
    `the control injection really does measure ${caseJson.inject.control.expect} (offline: ${rb.value.toExponential(4)})`);
  ok(Math.abs(caseJson.inject.anchor.expect - caseJson.inject.control.expect) > caseJson.inject.anchor.tol + caseJson.inject.control.tol,
    'and the two are further apart than the sum of their tolerances, so a live path returning its anchor cannot pass both');
  const gA = stringConstants(GEOMETRY['inject-a']).B, gB = stringConstants(GEOMETRY['inject-b']).B;
  ok(Math.abs(ra.value / gA - 1) < 0.02 && Math.abs(rb.value / gB - 1) < 0.02,
    'and both injected answers are within 2 per cent of the B their geometry says they have');
}

// ═════════════════════════════════════════════════════════════════════════════
// The page states its own score, and that sentence is audited by
// research/self-check/score-audit.mjs, which RUNS this file and compares. So the comparison
// is made here too, and it is kept OUT of the tally: a check that counts itself changes the
// number it is checking.
{
  const total = pass + fail;
  let drift = false;
  const claimed = html.match(/(\d+)\/(\d+) checks passed/);
  if (!claimed) { drift = true; console.log('  FAIL  the page states no verifier score at all'); }
  else if (Number(claimed[1]) !== pass || Number(claimed[2]) !== total) {
    drift = true;
    console.log(`  FAIL  the page claims "${claimed[0]}" and this run is ${pass}/${total}`);
  }
  console.log(`\n${pass}/${total} checks passed`);
  process.exit(fail || drift ? 1 : 0);
}
