#!/usr/bin/env node
// verify-slanted-edge-mtf.mjs: recompute everything the page prints, from the page's own code.
//
// This loads public/strata/slanted-edge-mtf/{render,esfr,specimens}.js and public/_kit/dsp.js
// byte for byte (never a Node copy, and never a build output), reruns the whole slate, the
// refusal battery and every table, regenerates the specimen manifest and the two injected
// camera streams and compares their hashes, and then goes back to the shipped HTML and checks
// that the sentences around those numbers are the sentences the numbers support.
//
// It is written so that each check COULD fail: the estimator is handed decoy fields to prove
// it never reads them, a constant estimator is run over the real slate to prove the slate
// discriminates, a blank wall is pushed through at five noise levels to prove the page cannot
// be made to answer nothing, and the free choices named in the page's own prose are compared
// against the defaults the code actually uses.
//
//   node research/slanted-edge-mtf/verify-slanted-edge-mtf.mjs
//   node research/slanted-edge-mtf/verify-slanted-edge-mtf.mjs --verbose
import { readFileSync, existsSync, readdirSync } from 'node:fs';
import { createHash } from 'node:crypto';
import vm from 'node:vm';
import { join } from 'node:path';
import { loadKit, ROOT, PAGE } from './load.mjs';
import { buildManifest, renderOf, sha256Of } from './make-specimens.mjs';
import { build as buildGateFrames, GATE_SPECIMENS, truthOf } from './make-gate-frames.mjs';

const VERBOSE = process.argv.includes('--verbose');
let pass = 0, fail = 0;
const fails = [];
function ok(cond, what, detail) {
  if (cond) { pass++; if (VERBOSE) console.log(`  ok   ${what}`); }
  else { fail++; fails.push(what + (detail ? '  ' + detail : '')); console.log(`  FAIL ${what}${detail ? '  ' + detail : ''}`); }
}
const near = (a, b, tol) => isFinite(a) && isFinite(b) && Math.abs(a - b) <= tol;
function section(t) { console.log('\n' + t); }

const AW = loadKit();
const R = AW.edgeRender, E = AW.esfr, S = AW.edgeSpecimens;
const HTML = readFileSync(join(PAGE, 'index.html'), 'utf8');
// The same source with runs of whitespace flattened to one space. Prose assertions run
// against this, because a sentence is the same sentence wherever the line happens to wrap:
// an assertion that fails when a paragraph is re-wrapped is testing the layout, not the
// claim, and it tempts the next editor to fix the check instead of the text. Several of
// the patterns below still carry \s*\n?\s* for exactly that reason and no longer need to.
const FLAT = HTML.replace(/\s+/g, ' ');
const MD_PATH = join(ROOT, 'src/content/strata/slanted-edge-mtf.md');
const MD = existsSync(MD_PATH) ? readFileSync(MD_PATH, 'utf8') : '';

const est = (entry, options) => {
  const img = renderOf(entry.kind ? entry : { kind: 'edge', params: entry.params });
  return E.esfr({ width: img.width, height: img.height, rgba: img.rgba },
    Object.assign({}, E.DEFAULTS, options || {}));
};
const resid = (entry, options) => {
  const r = est(entry, options);
  if (r.refused) return null;
  return r.mtf50 / R.mtf50True(entry.params) - 1;
};

// ── 1. the estimator cannot know what it is looking at ────────────────────────
section('1. the estimator is blind to provenance');
{
  const src = readFileSync(join(PAGE, 'esfr.js'), 'utf8');
  ok(E.estimate.length === 1, 'estimate() takes exactly one argument, the payload',
    `got ${E.estimate.length}`);
  const forbidden = ['isControl', 'isSpecimen', 'specimenId', 'expected', 'truth', 'role'];
  const hits = forbidden.filter((w) => new RegExp('\\b' + w + '\\b').test(src));
  ok(hits.length === 0, 'esfr.js mentions no word by which a specimen could identify itself',
    hits.join(', '));
  for (const id of S.sfr.map((s) => s.id).concat(S.peak.map((s) => s.id))) {
    ok(!src.includes(id), `esfr.js does not contain the specimen id "${id}"`);
  }

  // The payload is watched. Reading anything but the pixels would show up here, and so
  // would an answer that changed when decoy fields were attached.
  const img = renderOf(S.sfr[0]);
  const plain = { width: img.width, height: img.height, rgba: img.rgba };
  const decoyed = Object.assign({}, plain, {
    id: 'blur-1.0', role: 'anchor', truth: 0.179965, expected: 0.179965, isControl: false,
  });
  const seen = new Set();
  const spy = new Proxy(decoyed, {
    get(t, k) { seen.add(String(k)); return t[k]; },
    has(t, k) { seen.add(String(k)); return k in t; },
  });
  const a = E.estimate(plain), b = E.estimate(spy);
  const extra = [...seen].filter((k) => !['width', 'height', 'rgba'].includes(k));
  ok(extra.length === 0, 'the estimator read no field of the payload but width, height and rgba',
    extra.join(', '));
  ok(a.value === b.value, 'attaching the answer to the payload does not change the answer',
    `${a.value} vs ${b.value}`);
}

// ── 2. the slate ──────────────────────────────────────────────────────────────
section('2. the slate: the same estimator recovers four known blurs and three known peaks');
const slateRows = [];
for (const s of S.sfr) {
  const truth = R.mtf50True(s.params);
  const tol = truth * S.TOL_FRACTION;
  const r = est(s, {});
  ok(!r.refused, `${s.id} is answered, not refused`, r.refused ? r.refused.reason : '');
  if (r.refused) continue;
  ok(near(r.mtf50, truth, tol), `${s.id}: ${r.mtf50.toFixed(6)} within ${tol.toFixed(6)} of ${truth.toFixed(6)}`,
    `off by ${(r.mtf50 - truth).toFixed(6)}`);
  ok(r.uncertainty <= tol, `${s.id}: the claimed interval ${r.uncertainty.toFixed(6)} is no wider than the tolerance`);
  slateRows.push({ id: s.id, truth, got: r.mtf50 });
}
for (const s of S.peak) {
  const truth = R.peakTrue(s.params).peak;
  const tol = truth * S.TOL_FRACTION;
  const r = est(s, {});
  ok(!r.refused, `${s.id} peak is answered`, r.refused ? r.refused.reason : '');
  if (r.refused) continue;
  ok(near(r.peak, truth, tol), `${s.id}: peak ${r.peak.toFixed(4)} within ${tol.toFixed(4)} of ${truth.toFixed(4)}`);
  const u = 0.5 * (r.peakCi[1] - r.peakCi[0]);
  ok(u <= tol, `${s.id}: the claimed peak interval ${u.toFixed(5)} is no wider than the tolerance`);
}
{
  // every anchor/control pair on each slate is genuinely separable
  for (const list of [S.sfr, S.peak]) {
    const truth = (s) => (list === S.sfr ? R.mtf50True(s.params) : R.peakTrue(s.params).peak);
    const anchor = list.find((s) => s.role === 'anchor');
    for (const c of list.filter((s) => s.role === 'control')) {
      const gap = Math.abs(truth(anchor) - truth(c));
      const slack = (Math.abs(truth(anchor)) + Math.abs(truth(c))) * S.TOL_FRACTION;
      ok(gap > slack, `${anchor.id} and ${c.id} are ${gap.toFixed(4)} apart against ${slack.toFixed(4)} of slack`);
    }
  }
  // and a constant estimator fails at least one control on each slate
  for (const list of [S.sfr, S.peak]) {
    const truth = (s) => (list === S.sfr ? R.mtf50True(s.params) : R.peakTrue(s.params).peak);
    const anchor = list.find((s) => s.role === 'anchor');
    const constant = truth(anchor);
    const failed = list.filter((s) => s.role === 'control')
      .filter((c) => Math.abs(constant - truth(c)) > Math.abs(truth(c)) * S.TOL_FRACTION);
    ok(failed.length === list.filter((s) => s.role === 'control').length,
      `an estimator that always returns ${constant.toFixed(4)} fails every control on this slate`,
      `${failed.length} of ${list.filter((s) => s.role === 'control').length}`);
  }
}

// ── 3. the anchor is not true by construction ─────────────────────────────────
section('3. the anchor distinguishes two candidate truths');
{
  const a = S.sfr[0];
  const gaussOnly = Math.sqrt(Math.log(2) / 2) / (Math.PI * a.params.sigma);
  const system = R.mtf50True(a.params);
  const got = est(a, {}).mtf50;
  ok(near(gaussOnly, 0.1873906, 1e-6), `the blur alone crosses half at ${gaussOnly.toFixed(6)}`);
  ok(near(system, 0.1799650, 1e-6), `blur times pixel crosses half at ${system.toFixed(6)}`);
  const gap = gaussOnly / system - 1;
  ok(near(gap, 0.0412617, 1e-5), `the two candidates are ${(gap * 100).toFixed(2)} per cent apart`);
  ok(Math.abs(got / system - 1) < 0.015, 'the estimator lands within 1.5 per cent of the system truth');
  ok(Math.abs(got / gaussOnly - 1) > 0.025, 'and more than 2.5 per cent away from the blur-only value');
  // The generator and the estimator are different mathematics. If render.js ever grew a
  // Fourier transform, this page's anchor would stop being independent of its own answer.
  const rsrc = readFileSync(join(PAGE, 'render.js'), 'utf8');
  ok(!/\bfft\b/i.test(rsrc), 'render.js contains no transform: it draws pixels and states closed forms');
  ok(!readFileSync(join(PAGE, 'esfr.js'), 'utf8').includes('erf('), 'esfr.js contains no erf: it never evaluates the generator');
}

// ── 4. the tables, exactly as the page computes them ──────────────────────────
section('4. every table the page prints');
const N = {};
{
  const inband = S.tables.angles.filter((t) => !t.gateOff).map((t) => resid(t, {}));
  ok(inband.every((v) => v !== null), 'every in-gate angle is answered');
  N.angleSpread = Math.max(...inband) - Math.min(...inband);
  ok(N.angleSpread < 0.002, `the answer varies by ${(N.angleSpread * 100).toFixed(2)} percentage points across the admitted angles`);
  ok(near(N.angleSpread, 0.0012393, 2e-5), 'the angle spread is what the page prints', N.angleSpread.toExponential(4));
  for (const t of S.tables.angles.filter((x) => x.gateOff)) {
    const r = est(t, { geometryGate: false });
    ok(true, `${t.angleDeg} degrees with the gate off: ${r.refused ? r.refused.reason : r.mtf50.toFixed(6)}`);
  }
  for (const t of S.tables.angles.filter((x) => !x.gateOff)) {
    const gated = est(t, {});
    ok(!gated.refused, `${t.angleDeg} degrees passes the geometry gate`);
  }
  const steep = est({ params: Object.assign({}, S.sfr[0].params, { angleDeg: 20 }) }, {});
  ok(steep.refused && steep.refused.reason === 'geometry', 'and 20 degrees does not');
}
{
  // THE CONTRAST BOUND, AND WHY THIS CHECK SWEEPS INSTEAD OF READING THE TABLE.
  //
  // The departure from truth here is 8-bit quantisation noise, which is not monotone in the
  // contrast: neighbouring pairs differ by a factor of twenty. A check that maxed over the
  // rows the page happens to display therefore could not fail on the thing that matters,
  // because the page would be grading its own sample. So this measures the shipped rows,
  // then sweeps the SAME family at a quarter of the page's step, and fails if anything
  // finer beats the figure the page prints. It also pins the grid itself as regular, so a
  // later edit cannot quietly drop the inconvenient rows and restore a prettier number.
  const FLOOR = S.CONTRAST_CODE_FLOOR;
  const spanOfImage = (img) => {
    let lo = 255, hi = 0;
    for (let i = 0; i < img.rgba.length; i += 4) {
      const v = img.rgba[i];
      if (v < lo) lo = v;
      if (v > hi) hi = v;
    }
    return hi - lo;
  };
  const spanOf = (params) => spanOfImage(R.renderEdge(params));
  const base = S.tables.contrasts[0].params;
  const measure = (lo) => {
    const params = Object.assign({}, base, { lo, hi: 1 - lo });
    const img = R.renderEdge(params);
    const r = E.esfr({ width: img.width, height: img.height, rgba: img.rgba },
      Object.assign({}, E.DEFAULTS));
    return { lo, codes: spanOfImage(img), err: r.refused ? null : r.mtf50 / R.mtf50True(params) - 1,
      refused: r.refused ? r.refused.reason : null };
  };
  const worstOf = (list) => list.reduce((a, b) => (Math.abs(b.err) > Math.abs(a.err) ? b : a));
  const bestOf = (list) => list.reduce((a, b) => (Math.abs(b.err) < Math.abs(a.err) ? b : a));

  // the grid the page displays, exactly as the page walks it
  const los = S.tables.contrasts.map((t) => t.lo);
  const step = 0.02;
  ok(S.tables.contrasts.every((t) => Math.abs(t.hi - (1 - t.lo)) < 1e-12),
    'every contrast row is a symmetric pair about mid grey');
  ok(los.every((v, i) => i === 0 || Math.abs(v - los[i - 1] - step) < 1e-9),
    `the contrast rows are a regular sweep in steps of ${step}, not a chosen handful`);
  ok(los.length >= 20, `the sweep is ${los.length} pairs wide`);

  const shipped = S.tables.contrasts.map((t) => measure(t.lo));
  ok(shipped.every((x) => x.err !== null), 'every row of the sweep is answered');
  const wide = shipped.filter((x) => x.codes >= FLOOR);
  const narrow = shipped.filter((x) => x.codes < FLOOR);
  const wWide = worstOf(wide), wNarrow = worstOf(narrow), bNarrow = bestOf(narrow);
  N.contrastWorstWide = wWide.err;
  N.contrastWorstNarrow = wNarrow.err;
  N.contrastBestNarrow = bNarrow.err;
  N.contrastNarrowBeatingWide = narrow.filter((x) => Math.abs(x.err) < Math.abs(wWide.err)).length;
  ok(near(Math.abs(N.contrastWorstWide), 0.0195547, 2e-5),
    `while the edge spans at least ${FLOOR} code values the worst row of the sweep is out by ` +
    `${(N.contrastWorstWide * 100).toFixed(2)} per cent`, `at lo ${wWide.lo}, ${wWide.codes} codes`);
  ok(near(Math.abs(N.contrastWorstNarrow), 0.0750590, 5e-5),
    `and below it the worst row is out by ${(N.contrastWorstNarrow * 100).toFixed(2)} per cent at ` +
    `${wNarrow.codes} code values`);
  ok(near(Math.abs(N.contrastBestNarrow), 0.0007368, 5e-5),
    `while the best narrow row, at ${bNarrow.codes} code values, is out by only ` +
    `${(N.contrastBestNarrow * 100).toFixed(2)} per cent`);
  ok(N.contrastNarrowBeatingWide > 0,
    `${N.contrastNarrowBeatingWide} of the ${narrow.length} narrow rows beat the worst wide one, ` +
    'so the page is right that this is an envelope and not a threshold');
  ok(Math.abs(N.contrastWorstNarrow) > 3 * Math.abs(N.contrastWorstWide),
    'and the quantisation limit is still real rather than noise in the table');

  // the sweep the page cannot afford to do for itself: a quarter of its step, same family,
  // same estimator, same defaults. This is the assertion that can actually fail.
  const fineStep = step / 4;
  const fine = [];
  for (let n = 0; ; n++) {
    const lo = los[0] + n * fineStep;
    if (lo > los[los.length - 1] + 1e-9) break;
    fine.push(measure(Number(lo.toFixed(6))));
  }
  const fineWide = fine.filter((x) => x.err !== null && x.codes >= FLOOR);
  const fWorst = worstOf(fineWide);
  N.contrastFineWorstWide = fWorst.err;
  N.contrastFineRows = fine.length;
  ok(fine.every((x) => x.err !== null), `all ${fine.length} rows of the finer sweep are answered`);
  ok(Math.abs(N.contrastFineWorstWide) <= Math.abs(N.contrastWorstWide) * (1 + 1e-9),
    `a sweep at a quarter of the page's step (${fine.length} specimens) finds nothing worse than ` +
    `the ${(N.contrastWorstWide * 100).toFixed(2)} per cent the page prints`,
    `it found ${(N.contrastFineWorstWide * 100).toFixed(3)} per cent at lo ${fWorst.lo}`);
  ok(Math.abs(N.contrastFineWorstWide) < 0.02,
    'so the whole family above the stated code floor is inside two per cent');
  // specimens.js tells the reader how wide that finer sweep is. A count typed into a comment
  // is exactly the kind of number that survives the grid being edited underneath it, so the
  // sweep asserts its own size against the sentence that describes it.
  const SRC = readFileSync(join(PAGE, 'specimens.js'), 'utf8');
  const claimed = Number((SRC.match(/quarter of this step \((\d+) specimens/) || [])[1]);
  ok(claimed === N.contrastFineRows,
    `specimens.js says the finer sweep is ${claimed} specimens and it is ${N.contrastFineRows}`);

  // the column is the span the pixels actually carry, not the rounded difference of the
  // two encoded levels, which is one larger on the 4:1 pair the printed target uses
  const anchorSpan = spanOf(S.sfr[0].params);
  ok(anchorSpan === 107, 'the 0.20/0.80 pair spans 107 code values in the rendered pixels', String(anchorSpan));
  ok(Math.round(255 * (R.srgbEncode(0.8) - R.srgbEncode(0.2))) === 108,
    'while the rounded difference of the encoded levels is 108, which is why the page reads the pixels');
  const inst0 = readFileSync(join(PAGE, 'instrument.js'), 'utf8');
  ok(/function codeSpanOf/.test(inst0) && /codes = codeSpanOf\(t\)/.test(inst0),
    'and the page fills that column from the rendered pixels');
}
{
  const byNoise = new Map();
  for (const t of S.tables.dataLength) {
    if (!byNoise.has(t.noise)) byNoise.set(t.noise, {});
    byNoise.get(t.noise)[t.halfWidth] = resid(t, t.options);
  }
  N.fullWidthAtHalfPercentNoise = byNoise.get(0.005)[64];
  N.limitedAtHalfPercentNoise = byNoise.get(0.005)[16];
  ok(near(N.fullWidthAtHalfPercentNoise, -0.2054621, 5e-5),
    `at 0.5 per cent noise the whole row gives ${(N.fullWidthAtHalfPercentNoise * 100).toFixed(1)} per cent`);
  ok(near(N.limitedAtHalfPercentNoise, -0.0026488, 5e-5),
    `and plus or minus 16 pixels gives ${(N.limitedAtHalfPercentNoise * 100).toFixed(2)} per cent`);
  ok(Math.abs(N.fullWidthAtHalfPercentNoise) > 0.15, 'the choice the page calls a twenty per cent effect really is one');
  const clean = byNoise.get(0);
  const spread = Math.max(...Object.values(clean)) - Math.min(...Object.values(clean));
  ok(spread < 1e-9, 'and on a noiseless specimen the same choice does nothing at all, which is why it goes unstated elsewhere');
  ok(E.DEFAULTS.halfWidth === 16, 'the page ships the limited window it recommends');
}
{
  const truth = R.mtf50True(S.tables.corrections[0].params);
  for (const t of S.tables.corrections) {
    N['corr_' + t.id] = est(t, t.options).mtf50 / truth - 1;
  }
  ok(near(N.corr_all, 0.0082578, 2e-5), `the fully corrected pipeline sits ${(N.corr_all * 100).toFixed(2)} per cent from the closed form`);
  ok(near(N.corr_noderiv, -0.0011773, 2e-5), 'the derivative correction is worth what the page says');
  ok(near(N.corr_nobin, 0.0058703, 2e-5), 'the bin correction is worth what the page says');
  ok(near(N.corr_noangle, 0.0044209, 2e-5), 'the angle correction is worth what the page says');
  ok(near(N.corr_nogamma, -0.0054317, 2e-5), 'the linearisation is worth what the page says');
  const g = S.tables.gammaHigh.map((t) => est(t, t.options).mtf50 / R.mtf50True(t.params) - 1);
  N.gammaHighShift = g[1] - g[0];
  N.gammaLowShift = N.corr_nogamma - N.corr_all;
  ok(near(Math.abs(N.gammaLowShift), 0.0136895, 5e-5), `skipping the linearisation moves a 4:1 edge by ${(Math.abs(N.gammaLowShift) * 100).toFixed(2)} points`);
  ok(near(Math.abs(N.gammaHighShift), 0.0661325, 5e-5), `and a near black-to-white edge by ${(Math.abs(N.gammaHighShift) * 100).toFixed(2)} points`);
  ok(Math.abs(N.gammaHighShift) > 4 * Math.abs(N.gammaLowShift),
    'so keeping the printed target low in contrast is worth what the page claims');
}
{
  let base = null;
  for (const t of S.tables.sharpen) {
    const r = est(t, {});
    const tp = R.mtf50pTrue(t.params);
    if (t.gain === 0) base = { m: r.mtf50, p: r.mtf50p };
    ok(near(r.peak, tp.peak, Math.max(0.01, tp.peak * 0.01)),
      `sharpening gain ${t.gain}: peak ${r.peak.toFixed(4)} against a closed form of ${tp.peak.toFixed(4)}`);
    if (t.gain === 3.0) {
      N.sharpenInflateMtf50 = r.mtf50 / base.m;
      N.sharpenInflateMtf50p = r.mtf50p / base.p;
      N.sharpenPeak = r.peak;
    }
  }
  ok(near(N.sharpenInflateMtf50, 1.7401367, 5e-4), `MTF50 is inflated ${N.sharpenInflateMtf50.toFixed(2)} times`);
  ok(near(N.sharpenInflateMtf50p, 1.2470432, 5e-4), `and MTF50P only ${N.sharpenInflateMtf50p.toFixed(2)} times`);
  ok(near(N.sharpenPeak, 2.7410396, 5e-4), `with a peak of ${N.sharpenPeak.toFixed(3)}`);
  ok(N.sharpenInflateMtf50 > N.sharpenInflateMtf50p * 1.3,
    'so the peak-relative number really does resist what the headline number does not');
  const unsharp = est(S.tables.sharpen[0], {});
  ok(near(unsharp.peak, 1, 1e-9), 'an unsharpened edge peaks at exactly 1.000, which is why it is not on the peak slate');
}
{
  // THE BLIND REGIME. The flagship's instrument is the peak, and the page's sentence beside
  // the reader's own peak now says what a reading of 1.000 does NOT rule out. That sentence
  // is only allowed to stand because these rows exist: every one of them has a true peak of
  // exactly 1.000 in closed form, the estimator reads exactly 1.000 off every one, and the
  // headline number has still moved. If a row ever climbed above unity the demonstration
  // would be of something else and this check fails.
  let base = null, identical = 0;
  for (const t of S.tables.blind) {
    const r = est(t, {});
    const tp = R.peakTrue(t.params).peak;
    const tm = R.mtf50True(t.params);
    if (t.id === 'none') base = { m: r.mtf50, p: r.mtf50p };
    ok(near(tp, 1, 1e-9), `blind row "${t.id}": its TRUE peak is exactly 1.000 in closed form`, tp.toFixed(9));
    ok(near(r.peak, 1, 1e-9), `and the estimator reads exactly 1.000 off it`, r.peak.toFixed(9));
    ok(Math.abs(r.mtf50 / tm - 1) < S.TOL_FRACTION,
      `and recovers its MTF50 to ${(Math.abs(r.mtf50 / tm - 1) * 100).toFixed(2)} per cent, so the row is a measurement and not an artefact`);
    if (r.mtf50 === r.mtf50p) identical++;
    if (t.id === 'narrow') { N.blindInflate = r.mtf50 / base.m; N.blindTrueInflate = tm / R.mtf50True(S.tables.blind[0].params); }
  }
  ok(identical === S.tables.blind.length,
    `MTF50P is bit-identical to MTF50 on all ${S.tables.blind.length} of them, because half of a peak of 1.000 is 0.500`,
    `${identical} of ${S.tables.blind.length}`);
  ok(near(N.blindInflate, 1.4329698, 5e-4),
    `and the headline number is still inflated ${N.blindInflate.toFixed(2)} times while the peak says nothing`);
  ok(near(N.blindTrueInflate, 1.4246200, 5e-4),
    `which the closed forms agree with: the TRUE MTF50 ratio is ${N.blindTrueInflate.toFixed(4)}`);
  ok(N.blindInflate > 1.3, 'so a peak of 1.000 rules out much less than an earlier draft of this page implied');
  // and the readout no longer contradicts itself in the band between the floor and 1.01
  const INSTFLAT = readFileSync(join(PAGE, 'instrument.js'), 'utf8').replace(/\s+/g, ' ');
  ok(!/which is at or below 1\.000/.test(INSTFLAT),
    'the readout no longer tells a reader whose peak printed 1.006 that it is at or below 1.000');
  ok(!/Nothing here is adding contrast at any spatial frequency/.test(INSTFLAT),
    'and no longer reads a null peak as proof that nothing was added');
  ok(/floor<\/strong> of this statistic/.test(INSTFLAT),
    'it says instead that 1.000 is the floor of the statistic');
  ok(/id="t-blind"/.test(HTML) && /id="n-blindinflate"/.test(HTML),
    'and the page shows the measured size of the blind regime rather than asserting it');
}
{
  // THE OTHER SIDE OF LIMITING THE DATA LENGTH. The noise table can only ever report that a
  // short window is free, because its specimen has nothing in its tails. This one puts a
  // veiling halo there, which is the failure that wants the window WIDER, and pins the
  // direction: at plus or minus 16 pixels the estimate reads HIGH, and it improves as the
  // window opens. If that ever inverts, the page's paragraph is wrong and this fails.
  const clean = R.mtf50True(S.tables.flare[0].params);
  const halo5 = S.tables.flare.find((t) => t.id === 'halo5');
  const halo10 = S.tables.flare.find((t) => t.id === 'halo10');
  N.flareTrueCost = R.mtf50True(halo5.params) / clean - 1;
  ok(near(N.flareTrueCost, -0.0376808, 5e-6),
    `a 5 per cent halo costs the TRUE response ${(N.flareTrueCost * 100).toFixed(2)} per cent`);
  const at = (t, hw) => est(t, { halfWidth: hw }).mtf50 / R.mtf50True(t.params) - 1;
  N.flare16 = at(halo5, 16); N.flare64 = at(halo5, 64);
  ok(near(N.flare16, 0.0453349, 5e-5),
    `and the window this page ships reads ${(N.flare16 * 100).toFixed(2)} per cent HIGH on it`);
  ok(near(N.flare64, 0.0076951, 5e-5),
    `while the whole row lands at ${(N.flare64 * 100).toFixed(2)} per cent`);
  for (const t of [halo5, halo10]) {
    const seq = S.tables.flareWidths.map((hw) => at(t, hw));
    ok(seq.every((e) => e > 0), `${t.id}: every window reads high on a halo, so the sign of the bias is not a coincidence`);
    ok(seq[seq.length - 1] < seq[1], `${t.id}: and opening the window from 16 to 64 pixels improves it`,
      seq.map((e) => (e * 100).toFixed(2)).join(', '));
  }
  // the two tables really do want the window moved opposite ways, which is the claim
  ok(Math.abs(N.fullWidthAtHalfPercentNoise) > 0.15 && N.flare16 > 0.03,
    'noise wants the window short by twenty points and glare wants it long by four, which is what the page says');
  ok(/id="t-flare"/.test(HTML) && /opposite directions/.test(FLAT),
    'and the page prints both rather than the one that flatters its own choice');
  // NEGATIVE GAIN IS THE SAME CLOSED FORM, not a second model bolted on
  const RSRC = readFileSync(join(PAGE, 'render.js'), 'utf8');
  ok(/if \(!gain\) return phi\(s \/ sigma\);/.test(RSRC) && /if \(!g\) return a;/.test(RSRC),
    'the generator and its closed form take both signs of the gain through one expression');
  for (const t of S.tables.flare) {
    const m = R.systemMTF(0, t.params);
    ok(near(m, 1, 1e-12), `${t.id}: its transfer is still exactly 1.000 at zero frequency, so it is a redistribution and not a gain`);
  }
}
{
  // THE STRAIGHT-LINE FIT, WHICH THE PAGE HAS ALWAYS NAMED AND NEVER MEASURED. `bow` is a
  // property of the scene, so the closed form must NOT move with it: if it did, the table
  // would be measuring the generator instead of the estimator, and the whole point would be
  // gone. That is the first assertion here.
  const flat = S.tables.fitResidual.find((t) => t.id === 'clean');
  for (const t of S.tables.fitResidual) {
    ok(near(R.mtf50True(t.params), R.mtf50True(flat.params), 1e-12),
      `${t.id}: its closed form is identical to the straight clean specimen's, so the table prices the FIT and not the truth`);
  }
  const truth = R.mtf50True(flat.params);
  const got = {};
  for (const t of S.tables.fitResidual) {
    const r = est(t, {});
    ok(!r.refused, `${t.id} is answered rather than refused`, r.refused ? r.refused.reason : '');
    if (r.refused) continue;
    got[t.id] = { rms: r.fitRmsPx, err: r.mtf50 / truth - 1 };
  }
  N.fitRmsClean = got.clean.rms;
  ok(near(got.clean.rms, 0.006917, 5e-5), `a clean straight edge scatters ${got.clean.rms.toFixed(4)} px about its fitted line`);
  ok(near(got['bow-1.0'].rms, 0.298503, 5e-4), `a pixel of bow raises that to ${got['bow-1.0'].rms.toFixed(3)} px`);
  ok(near(got['bow-1.0'].err, -0.0299870, 5e-5), `and costs ${(got['bow-1.0'].err * 100).toFixed(2)} per cent`);
  ok(near(got['bow-2.0'].err, -0.1264046, 5e-5), `two pixels of bow costs ${(got['bow-2.0'].err * 100).toFixed(2)} per cent`);
  ok(near(got['noise-1.0'].rms, 0.409442, 5e-4), `and one per cent noise raises the same scatter to ${got['noise-1.0'].rms.toFixed(3)} px`);
  // every degraded row is LOW, which is the only directional claim the page makes
  for (const id of ['bow-0.5', 'bow-1.0', 'bow-2.0', 'noise-0.5', 'noise-1.0']) {
    ok(got[id].err < 0, `${id}: the answer comes back low, which is the direction the page states`,
      (got[id].err * 100).toFixed(2) + '%');
  }
  // the scatter is monotone in the bow, so the diagnostic really does track the defect
  ok(got['bow-0.5'].rms < got['bow-1.0'].rms && got['bow-1.0'].rms < got['bow-2.0'].rms,
    'the scatter rises monotonically with the bow');
  // AND IT IS NOT A CONVERSION FACTOR. The page says so; this is why it has to. 0.5 per
  // cent noise raises the scatter to about the same place a pixel of bow does and costs
  // almost nothing, because the limited window absorbs it. A page that quoted a single
  // "rms means x per cent" rule would be wrong here, and would look right on either half.
  ok(Math.abs(got['noise-0.5'].err) < 0.005 && got['noise-0.5'].rms > 0.15,
    `0.5 per cent noise scatters ${got['noise-0.5'].rms.toFixed(3)} px and costs only ` +
    `${(got['noise-0.5'].err * 100).toFixed(2)} per cent, so the scatter is not a conversion factor`);
  ok(/not a conversion factor/.test(FLAT), 'and the page says that rather than implying a scale');
  // the diagnostic reaches the reader, which is the whole reason to have measured it
  const IF = readFileSync(join(PAGE, 'instrument.js'), 'utf8').replace(/\s+/g, ' ');
  ok(/d\.fitRmsPx\.toFixed\(3\)/.test(IF), 'the reader\'s own scatter is printed beside their own reading');
  ok(/id="t-fitresidual"/.test(HTML) && /id="n-rmsbow"/.test(HTML),
    'and the table that says what that scale is worth is on the page');
  // the bow parameter defaults to zero, so nothing already committed moved
  const RS = readFileSync(join(PAGE, 'render.js'), 'utf8');
  ok(/const bow = o\.bow \|\| 0;/.test(RS), 'bow defaults to zero in the generator');
  ok((RS.match(/const bow = o\.bow \|\| 0;/g) || []).length === 2,
    'and in BOTH renderEdge and renderEdgeFamily, which the byte-identity check below depends on');
  const bp = Object.assign({}, flat.params, { bow: 1.0 });
  const one = R.renderEdge(bp), fam = R.renderEdgeFamily(bp, [{ lo: bp.lo, hi: bp.hi }])[0];
  let identical = one.rgba.length === fam.rgba.length;
  for (let i = 0; identical && i < one.rgba.length; i++) if (one.rgba[i] !== fam.rgba[i]) identical = false;
  ok(identical, 'a bowed specimen renders byte-identically through the single and the family path');
}
{
  const s = S.sfr[3];
  const r = est(s, {});
  let over = 0, under = 0;
  for (let i = 0; i < r.esf.length; i++) {
    over = Math.max(over, r.esf[i] - s.params.hi);
    under = Math.max(under, s.params.lo - r.esf[i]);
  }
  const span = s.params.hi - s.params.lo;
  N.haloOver = over / span; N.haloUnder = under / span;
  ok(near(N.haloOver, 0.6617156, 1e-4), `the halo overshoots ${(N.haloOver * 100).toFixed(1)} per cent above the light side`);
  ok(near(N.haloUnder, 0.6561744, 1e-4), `and undershoots ${(N.haloUnder * 100).toFixed(1)} per cent below the dark side`);
  ok(N.haloOver > 0.05 && N.haloUnder > 0.05, 'so the bands the page tells the reader to look for are really there');
}

// ── 5. the refusals ───────────────────────────────────────────────────────────
section('5. the refusal path, which is where a measurement page is most likely to lie');
for (const t of S.refusals) {
  const img = renderOf(t);
  const r = E.estimate({ width: img.width, height: img.height, rgba: img.rgba });
  ok(r.refused && r.refused.reason === t.expect,
    `${t.id} refuses with "${t.expect}"`, r.refused ? `got ${r.refused.reason}` : `got ${r.value}`);
  if (r.refused) ok(r.refused.detail && r.refused.detail.length > 30, `${t.id} says what it could not do`);
}
{
  const g = est(S.straightNoGate, S.straightNoGate.options);
  ok(g.refused && g.refused.reason === 'sparse-bins',
    'an upright edge is refused even with the angle rule switched off, on the bins it cannot fill',
    g.refused ? g.refused.reason : String(g.mtf50));
  ok(g.refused && near(g.emptyFraction, 0.75, 1e-9), 'and 75.0 per cent of its quarter-pixel bins are empty');
  // A blank wall must never yield a number, at any noise level, under any seed.
  let answered = 0;
  for (const noise of [0.002, 0.004, 0.01, 0.02, 0.05]) {
    for (const seed of [1, 2, 3, 4, 5]) {
      const img = R.renderFlat({ width: S.ROI, height: S.ROI, level: 0.5, noise, seed });
      const r = E.estimate({ width: img.width, height: img.height, rgba: img.rgba });
      if (!r.refused) answered++;
    }
  }
  ok(answered === 0, 'a blank wall is refused at every noise level and every seed tried (25 of them)',
    `${answered} produced a number`);
  // A frame smaller than the region is refused rather than stretched.
  const small = R.renderEdge(Object.assign({}, S.sfr[0].params, { width: 64, height: 64 }));
  const rs = E.estimate({ width: 64, height: 64, rgba: small.rgba });
  ok(rs.refused && rs.refused.reason === 'roi-too-small', 'a frame smaller than the region is refused');
  // An empty payload is refused rather than throwing.
  const rn = E.estimate({ width: 0, height: 0, rgba: null });
  ok(rn.refused && rn.refused.reason === 'no-image', 'and so is nothing at all');
}

// ── 6. the specimens and the injected streams regenerate byte for byte ────────
section('6. the specimens and the two injected camera streams');
{
  const committed = join(PAGE, 'specimens/SPECIMENS.json');
  ok(existsSync(committed), 'the specimen manifest is committed');
  if (existsSync(committed)) {
    const want = JSON.stringify(buildManifest(), null, 2) + '\n';
    const got = readFileSync(committed, 'utf8');
    ok(want === got, 'regenerating the specimens from the shipped render.js reproduces the committed manifest exactly',
      want === got ? '' : 'the generator and the manifest disagree');
    const doc = JSON.parse(got);
    ok(doc.specimens.length === S.sfr.length + S.peak.length + S.refusals.length,
      `the manifest holds all ${doc.specimens.length} specimens`);
    for (const rec of doc.specimens) {
      const entry = { kind: rec.params.level !== undefined ? 'flat' : 'edge', params: rec.params };
      ok(sha256Of(renderOf(entry)) === rec.sha256, `${rec.id} redraws to the committed sha256`);
    }
  }
}
{
  const frames = buildGateFrames(false);
  for (const f of frames) {
    ok(existsSync(f.path), `${f.file} is committed`);
    if (!existsSync(f.path)) continue;
    const bytes = readFileSync(f.path);
    ok(bytes.subarray(0, 10).toString() === 'YUV4MPEG2 ', `${f.file} is a Y4M stream`);
  }
  // regenerate into memory and compare hashes with what is on disk
  const { writeY4M } = await import('../anchor-wave/forge.mjs');
  const os = await import('node:os');
  const tmp = os.tmpdir();
  const rebuilt = [];
  for (const g of GATE_SPECIMENS) {
    const p = Object.assign({ width: 320, height: 240, sub: 16 }, g.params);
    const img = R.renderEdge(p);
    const res = writeY4M(join(tmp, 'sem-' + g.file), { w: 320, h: 240, fps: 15, frames: 6 },
      () => (x, y) => img.rgba[(y * 320 + x) * 4]);
    rebuilt.push({ file: g.file, sha: res.sha256, truth: truthOf(g.params) });
  }
  for (const r of rebuilt) {
    const onDisk = createHash('sha256').update(readFileSync(join(ROOT, 'research/slanted-edge-mtf/gate', r.file))).digest('hex');
    ok(onDisk === r.sha, `${r.file} regenerates byte for byte`);
  }
  const casePath = join(ROOT, 'research/anchor-wave/cases/slanted-edge-mtf.json');
  ok(existsSync(casePath), 'the live-sensor case file exists');
  if (existsSync(casePath)) {
    const c = JSON.parse(readFileSync(casePath, 'utf8'));
    ok(c.sensor === 'camera' && c.path === '/strata/slanted-edge-mtf/', 'the case points at this page and this sensor');
    const a = rebuilt[0], b = rebuilt[1];
    ok(near(c.inject.anchor.expect, a.truth, 5e-6), `the injected anchor's expected value is its closed form ${a.truth.toFixed(6)}`);
    ok(near(c.inject.control.expect, b.truth, 5e-6), `the injected control's expected value is its closed form ${b.truth.toFixed(6)}`);
    const gap = Math.abs(a.truth - b.truth), slack = c.inject.anchor.tol + c.inject.control.tol;
    ok(gap > slack * 4, `the two injected truths are ${gap.toFixed(4)} apart against ${slack.toFixed(4)} of combined slack`);
    ok(a.truth !== b.truth, 'and they are genuinely different answers, not the same file twice');
    for (const s of S.sfr.concat(S.peak)) {
      const gapA = Math.abs(R.mtf50True(s.params) - a.truth), gapB = Math.abs(R.mtf50True(s.params) - b.truth);
      ok(gapA > c.inject.anchor.tol * 2 && gapB > c.inject.control.tol * 2,
        `the injected blurs are well clear of the shipped ${s.id}`,
        `gaps ${gapA.toFixed(4)} and ${gapB.toFixed(4)}`);
    }
  }
}

// ── 7. the page's own surface ─────────────────────────────────────────────────
section('7. the sentences on the page, against the numbers that back them');
{
  ok(/<\/script>\s*<\/body>\s*<\/html>\s*$/.test(HTML.trim() + '\n') || HTML.includes('</body>'),
    'the document closes its body');
  ok(HTML.includes('</html>'), 'and its html');
  const opens = (HTML.match(/<script\b/g) || []).length, closes = (HTML.match(/<\/script>/g) || []).length;
  ok(opens === closes, `the ${opens} script tags are balanced`);
  const ld = HTML.match(/<script type="application\/ld\+json">([\s\S]*?)<\/script>/);
  ok(!!ld, 'there is a JSON-LD block');
  if (ld) {
    let doc = null;
    try { doc = JSON.parse(ld[1]); } catch (e) { /* reported below */ }
    ok(!!doc, 'the JSON-LD parses as JSON');
    if (doc) {
      ok(doc.headline === 'The Edge That Came Back Sharper', 'its headline is the page H1');
      ok(HTML.includes('<h1>The Edge That Came Back Sharper</h1>'), 'and the H1 really says that');
      ok(doc.url === 'https://artwaste.land/strata/slanted-edge-mtf/', 'its url is this page');
      ok(/peaks? above 1\.000/.test(doc.description), 'its description carries the claim the page is built on');
    }
  }
  // THE SHAREABLE SURFACE. These four strings are the ones that travel without the page
  // attached, so they are held to what the apparatus can support and no further.
  //
  // The apparatus is four synthetic edges, a refusal battery and one injected camera
  // stream. It measures no population of devices, so the checks below PIN THE HEDGE rather
  // than the boast: an earlier draft said "the curve most phones return peaks above 1.000",
  // a quantified claim about a population nothing here has ever measured, and the check
  // that stood beside it only asserted the string "1.000" was present, which is true
  // whatever phones do. A check that cannot fail in the direction that matters is not a
  // check. The frequency words are therefore forbidden outright.
  const shareable = [];
  for (const m of HTML.matchAll(/<meta (?:name|property)="(?:description|og:description|twitter:description)" content="([^"]*)"/g)) shareable.push(m[1]);
  const ld2 = HTML.match(/<script type="application\/ld\+json">([\s\S]*?)<\/script>/);
  if (ld2) { try { shareable.push(JSON.parse(ld2[1]).description); } catch (e) { /* reported above */ } }
  shareable.push((MD.match(/^dek:\s*"([\s\S]*?)"\s*$/m) || [])[1] || '');
  ok(shareable.length >= 5, 'description, og:description, twitter:description, the JSON-LD and the dek are all present');
  const POPULATION = /\b(?:most|many|nearly all|almost all|every|all)\s+(?:modern\s+|consumer\s+)?(?:phones?|cameras?|devices?|handsets?|smartphones?|pipelines?)\b/i;
  for (const t of shareable) {
    ok(/1\.000/.test(t), 'the shareable text states the above-unity fact, which the sharpened specimens demonstrate');
    ok(!POPULATION.test(t),
      'and makes no quantified claim about a population of devices, which nothing here has measured',
      (t.match(POPULATION) || [])[0]);
    ok(!/\blens\b/i.test(t) || /\bno lens\b/i.test(t),
      'and names a lens only to deny that the number is one');
    ok(!/\blp\/mm\b/.test(t), 'and does not promise line pairs per millimetre at the sensor');
  }
  // and it must say whose response it is: the chain, not the camera on its own, which is
  // what the whole second half of the page exists to establish
  for (const t of shareable.slice(0, 4)) {
    ok(/imaging chain|chain'?s|passive optical system/i.test(t),
      'and attributes the response to the imaging chain rather than to the camera alone',
      t.slice(0, 80));
  }
  ok(!/Real Sharpness/i.test(HTML), 'and the page title promises no "real sharpness" it refuses to deliver');
  ok(N.sharpenPeak > 1.05, 'a response above 1.000 is demonstrated on a shipped specimen rather than asserted');
  // the card those tags name has to exist, or every share advertises a 404
  ok(existsSync(join(ROOT, 'public/og/slanted-edge-mtf.png')),
    'the social card the head names exists at public/og/slanted-edge-mtf.png');
}
{
  // A path printed on the page is an instruction. Both must exist, character for character.
  const cmds = [...HTML.matchAll(/<code>node ([^<]+)<\/code>/g)].map((m) => m[1].trim());
  ok(cmds.length >= 2, 'the page tells the reader how to recheck it');
  for (const c of cmds) {
    const file = c.split(/\s+/)[0];
    ok(existsSync(join(ROOT, file)), `the command "node ${c}" names a file that exists`);
  }
  ok(cmds.some((c) => c.includes('verify-slanted-edge-mtf.mjs')), 'including this verifier');
  ok(cmds.some((c) => c.includes('check-live-sensor.mjs --only=slanted-edge-mtf')), 'and the live-sensor gate');
}
{
  // The free choices the page names must be the defaults the code uses. This is the check
  // that catches prose drifting away from an edited constant.
  const D = E.DEFAULTS;
  const claims = [
    [D.roi === 128, '128 &times; 128'],
    [D.halfWidth === 16, '&plusmn;16'],
    [D.binsPerPixel === 4, '4'],
    [D.alpha === 0.5, 'Tukey, &alpha; = 0.5'],
    [D.pad === 512, '512'],
    [D.minAngleDeg === 2 && D.maxAngleDeg === 15, '2'],
    [D.maxClipFraction === 0.001, '0.1%'],
    [D.maxEmptyBinFraction === 0.1, '10%'],
    [D.maxRelInterval === 0.15, '&plusmn;15%'],
    [D.bootstrap === 96, '96'],
    [D.blockRows === 8, 'blocks of 8 image rows'],
    [D.peakLimit === 0.5, '0.5'],
  ];
  for (const [held, text] of claims) {
    ok(held, `the shipped default behind "${text}" is what the page says`);
    ok(HTML.includes(text), `and the page's own list of choices contains "${text}"`);
  }
  ok(S.ROI === D.roi, 'the catalogue and the estimator agree on the region size');
}
{
  // The quotations. These are verbatim from the free preview of the standard; editing one
  // to suit the prose would turn "verbatim" into a lie, so the verifier pins them.
  const q1 = 'The OTF is a complex function whose modulus has unity value at zero spatial';
  const q2 = 'a meaningful MTF of the camera can only be approximated through the SFR';
  ok(HTML.includes(q1), 'the OTF quotation is on the page, unedited');
  ok(HTML.includes(q2), 'and the MTF note is quoted, unedited');
  ok(HTML.includes('ISO 12233:2024, 3.20, Note 1 to entry'), 'the OTF quotation is attributed to its clause');
  ok(HTML.includes('3.18, Note 1 to entry'), 'and so is the MTF note');
  ok(HTML.includes('fifth edition, dated 2024-09'), 'the edition and date are stated');
  ok(HTML.includes('Annex D'), 'and the annex the algorithm lives in is named');
  ok(/not reproduced here/.test(HTML), 'and the page says it does not reproduce the standard');
  ok(!/sfrmat/i.test(HTML), 'the page does not claim to ship the standard\'s own code');
  ok(/not the standard's own algorithm/.test(HTML) || /as published in the open literature/.test(FLAT),
    'the page distinguishes the published method from the standard');
}
{
  // The printed sheet uses the shared kit's fiducial convention and says so.
  const kit = readFileSync(join(ROOT, 'public/_kit/printable.js'), 'utf8');
  const m = kit.match(/const FID = \{ size: (\d+), x0: (\d+), y0: (\d+), x1: (\d+), y1: (\d+) \}/);
  ok(!!m, 'the shared kit still declares the fiducial convention this page relies on');
  if (m) {
    const [, size, x0, y0, x1, y1] = m.map(Number);
    ok(size === 4 && x0 === 20 && y0 === 15 && x1 === 170 && y1 === 215,
      'the convention is size 4 at (20,15) and (170,215) millimetres');
    ok(x1 - x0 === 150, 'the fiducial span is 150 mm');
    ok(HTML.includes('20 and 170 mm across and 15 and 215 mm down'), 'and the page states those positions');
    ok(HTML.includes('150.000'), 'and the span it converts by');
  }
  const inst = readFileSync(join(PAGE, 'instrument.js'), 'utf8');
  ok(inst.includes("AW.printable.sheet("), 'the sheet is built by the shared kit, not by a private copy');
  ok(inst.includes('AW.printable.state()'), 'and millimetres are gated on the kit calling itself calibrated');
  ok(/markSpanMM: 40/.test(inst), 'the patch carries its own pair of marks 40 mm apart');

  // ── THE CALIBRATION MUST BE A MULTIPLIER, NOT A DOOR ──────────────────────────
  // This is the check the whole printable register turns on, and it is the easiest one on
  // the page to pass by accident. If `calibrated` were used only as a boolean that unlocks
  // the readout, the reader could type 142 or 150 and get the SAME cycles per millimetre,
  // the ruler could not detect a mis-scaled print because it never entered the arithmetic,
  // and the page's whole reason for existing would invert. Two traps make the wrong code
  // look exactly like the right code in a diff: FID.x1 - FID.x0 and RULER_MM are BOTH 150,
  // so a nominal and a measurement are interchangeable on sight; and the kit's only scale
  // helper, specify(), DIVIDES by the scale, which is correct for pre-compensating geometry
  // you are about to print and backwards for measuring something already printed.
  ok(/const trueMM = nominal \* cal\.scale;/.test(inst),
    'the measured ruler enters the arithmetic: the printed span is the drawn span TIMES the scale');
  ok(/pxPerMM: dpx \/ trueMM/.test(inst),
    'and the pixels-per-millimetre is taken against that printed span, not against the drawn one');
  ok(!/dpx \/ nominal/.test(inst),
    'the drawn span is never used as if it were the printed one');
  ok(!/AW\.printable\.specify\(/.test(inst),
    'and the kit helper that divides by the scale, which is the wrong direction here, is not reached for');
  {
    // Run the kit's own calibration to prove the scale carries the printer's error, and
    // state the stake: what a reader would be told if the ruler were only a door.
    const kitAPI = (() => {
      const g = globalThis.window || (globalThis.window = {});
      vm.runInThisContext(kit, { filename: 'public/_kit/printable.js' });
      return g.AW.printable;
    })();
    const c = kitAPI.calibration(kitAPI.RULER_MM, 142);
    ok(c.ok && near(c.scale, 142 / 150, 1e-12),
      `a 150 mm ruler measuring 142 gives a scale of ${c.scale.toFixed(5)}, which is the printer's error and not a flag`);
    const dpx = 900, nominal = 40;
    const right = dpx / (nominal * c.scale);      // what the shipped expression computes
    const doorOnly = dpx / nominal;               // what a boolean-only calibration would
    ok(near(doorOnly / right, c.scale, 1e-12) && Math.abs(1 - c.scale) > 0.05,
      `so a calibration used only as a door would report every millimetre ` +
      `${((1 - c.scale) * 100).toFixed(1)} per cent low on that sheet, which is the size of the thing being caught`);
    ok(!kitAPI.calibration(kitAPI.RULER_MM, 120).ok,
      'and a measurement further out than any printer goes is refused rather than believed');
  }
  // FIT TO PAGE, AS ARITHMETIC RATHER THAN FOLKLORE. The register has never measured a
  // printer. What it has is two calculations, and the page now shows both instead of
  // asserting a range: an A4 page scaled onto US Letter, and an A4 page scaled inside the
  // margin a consumer printer cannot reach. Both are recomputed here from the paper table
  // the shared kit holds, so the sentence cannot drift from the constants behind it.
  const pm = kit.match(/const PAPERS = \{ A4: \{ w: ([\d.]+), h: ([\d.]+) \}, Letter: \{ w: ([\d.]+), h: ([\d.]+) \} \}/);
  ok(!!pm, 'the shared kit still declares the paper sizes the fit-to-page arithmetic uses');
  if (pm) {
    const [, aw, ah, lw, lh] = pm.map(Number);
    const a4OntoLetter = Math.min(lw / aw, lh / ah);
    const marginFit = (mm) => Math.min((aw - 2 * mm) / aw, (ah - 2 * mm) / ah);
    ok(near(a4OntoLetter, 0.9407407, 1e-6), `A4 fitted onto US Letter is ${(a4OntoLetter * 100).toFixed(1)} per cent`);
    ok(near(marginFit(4), 0.9619048, 1e-6), `and inside a 4 mm margin ${(marginFit(4) * 100).toFixed(1)} per cent`);
    ok(near(marginFit(6), 0.9428571, 1e-6), `and inside a 6 mm margin ${(marginFit(6) * 100).toFixed(1)} per cent`);
    ok(HTML.includes(`min(215.9&thinsp;/&thinsp;210, 279.4&thinsp;/&thinsp;297)`),
      'and the page shows that first calculation rather than asserting its answer');
    ok(/id="n-fitletter"/.test(HTML) && /id="n-fitmargin4"/.test(HTML) && /id="n-fitmargin6"/.test(HTML),
      'and prints all three figures from the constants, not from prose');
    ok(!/lands somewhere near 94 to 96 per cent/.test(FLAT),
      'and no longer states a measured range the register never measured');
  }
  // the patch's own geometry, which is what the millimetre conversion is scaled by
  const num = (k) => { const m = inst.match(new RegExp(k + ':\\s*([0-9.]+)')); return m ? Number(m[1]) : NaN; };
  const sizeMM = num('sizeMM'), markSpan = num('markSpanMM'), markY = num('markYMM'),
        markMM = num('markMM'), ang = num('angleDeg');
  ok(sizeMM === 70 && markSpan === 40 && markY === 80 && markMM === 3 && ang === 5,
    'the printed patch is 70 mm square, its edge is at 5.000 degrees and its marks are 40.000 mm apart',
    `${sizeMM} ${markSpan} ${markY} ${markMM} ${ang}`);
  // the marks are placed symmetrically about the patch centre, so their centres are the
  // stated span apart no matter what the patch size is
  ok(/for \(const dx of \[-P\.markSpanMM \/ 2, P\.markSpanMM \/ 2\]\)/.test(inst),
    'and they are placed at plus and minus half that span from the patch centre');
  const t5 = Math.tan(ang * Math.PI / 180);
  ok(near(sizeMM / 2 - (sizeMM / 2) * t5, 31.9379, 5e-4),
    'the edge polygon meets the top of the patch at 31.9379 mm, which is 5.000 degrees');
  // nothing on the sheet may reach the paper edge, and the whole sheet must fit US Letter
  ok(20 + sizeMM <= 170, 'the printed patch fits inside the fiducial frame horizontally');
  ok(15 + 14 + markY + 8 <= 215, 'and vertically');
  ok(/height:279mm/.test(inst), 'the sheet is held to 279 mm so it fits US Letter as well as A4');
  ok(/size:auto/.test(inst), 'and the page size follows the paper rather than demanding A4');
  ok(HTML.includes('check-print-geometry.mjs'), 'the page names the gate that measures the sheet');
}
{
  // no third-party fetch of any kind
  for (const f of ['index.html', 'instrument.js', 'esfr.js', 'render.js', 'specimens.js']) {
    const src = readFileSync(join(PAGE, f), 'utf8');
    const bad = [...src.matchAll(/(?:src|href)\s*=\s*["']https?:\/\/([^"'\/]+)/g)].map((x) => x[1])
      .filter((h) => f !== 'index.html');
    ok(bad.length === 0, `${f} loads nothing from another origin`, bad.join(', '));
    if (f !== 'index.html') {
      ok(!/fetch\(\s*["']https?:/.test(src) && !/XMLHttpRequest/.test(src), `${f} makes no absolute request`);
    }
  }
  const html = HTML;
  ok(!/<script[^>]+src=["']https?:/.test(html), 'no script is loaded from another origin');
  // <link rel="canonical"> is metadata, not a fetch; every other rel must stay on-origin.
  const offOriginLinks = [...html.matchAll(/<link\b[^>]*>/g)]
    .filter((m) => /href=["']https?:/.test(m[0]) && !/rel="canonical"/.test(m[0]));
  ok(offOriginLinks.length === 0, 'no stylesheet, font or icon is loaded from another origin',
    offOriginLinks.map((m) => m[0]).join(' '));
  ok(!/url\(\s*['"]?https?:/.test(html), 'and no CSS url points off-origin');
}
{
  // the frontmatter, and the dek that will be shown beside the page everywhere else
  ok(MD.length > 0, 'the frontmatter entry exists at src/content/strata/slanted-edge-mtf.md');
  if (MD) {
    const fm = MD.split('---')[1] || '';
    const field = (k) => { const m = fm.match(new RegExp('^' + k + ':\\s*"([\\s\\S]*?)"\\s*$', 'm')); return m ? m[1] : null; };
    const dek = field('dek'), plain = field('plain'), seo = field('seoTitle');
    ok(/^seam:\s*"groundtruth"/m.test(fm), 'the seam is groundtruth');
    ok(/^href:\s*\/strata\/slanted-edge-mtf\/\s*$/m.test(fm) || /^href:\s*"\/strata\/slanted-edge-mtf\/"/m.test(fm),
      'the href marks it immersive');
    ok(!!dek && dek.length > 80, 'there is a dek');
    ok(!!plain, 'there is a plain placard');
    if (plain) {
      ok(plain.length <= 420, `the placard is ${plain.length} characters, inside the 420 limit`);
      ok((plain.match(/[.!?](\s|$)/g) || []).length <= 3, 'and at most three sentences');
      ok(!plain.includes('—'), 'and carries no em dash');
      ok(/cannot|not\b/.test(plain), 'and says what the instrument cannot do');
    }
    ok(!!seo && seo.length <= 60, `the seoTitle is ${seo ? seo.length : 0} characters`);
    ok(seo === (HTML.match(/<title>([^<]*)<\/title>/) || [])[1], 'and it is the page title');
    const relates = [...MD.matchAll(/^\s*- to:\s*([a-z0-9-]+)\s*$/gm)].map((m) => m[1]);
    ok(relates.length >= 2 && relates.length <= 4, `there are ${relates.length} related layers`);
    for (const r of relates) {
      ok(existsSync(join(ROOT, 'src/content/strata', r + '.md')), `related layer ${r} exists`);
    }
    // the dek must be the paragraph the reader sees, not a different promise
    const onPage = (HTML.match(/<p class="dek">([\s\S]*?)<\/p>/) || [])[1] || '';
    const norm = (s) => s.replace(/\s+/g, ' ').replace(/&[a-z]+;/g, '').trim();
    ok(norm(onPage).length > 100, 'the page carries a dek paragraph');
    ok(norm(dek || '').slice(0, 60) === norm(onPage).slice(0, 60),
      'and it opens with the same words as the frontmatter dek');
  }
}
{
  // the page must not describe a score it does not print, and must not overstate the wave
  ok(!/\b\d+\s*(?:\/|\s+of\s+)\s*\d+\s+(?:checks?|green|passes?|passing|assertions?|tests?|verified)\b/i.test(HTML),
    'the page states no verifier score, so there is none to drift');
  ok(!/first page (?:in|of)/i.test(HTML), 'the page claims no priority it has not established');
  ok(!/\bmy lens\b/i.test(HTML), 'and never calls the number a lens measurement');
}

// ── 8. what the page says about its own instrument ────────────────────────────
// Everything in this section was added after two skeptics read the page. Each check exists
// because a sentence here was once true of nothing, or true of only the rows on display.
section('8. the page\'s claims about its own honesty, which are the easiest ones to get wrong');
const INST = readFileSync(join(PAGE, 'instrument.js'), 'utf8');
const ESRC = readFileSync(join(PAGE, 'esfr.js'), 'utf8');
{
  // THE BIAS IS NOT IN THE INTERVAL. The page used to say it was carried into every
  // interval below; it is carried into none of them, because a bias is identical in every
  // bootstrap resample. Both halves are checked: that the code really does exclude it, and
  // that the prose really does say so.
  const bias = S.sfr.map((s) => {
    const r = est(s, {});
    const truth = R.mtf50True(s.params);
    return { id: s.id, offset: r.mtf50 - truth, u: r.uncertainty,
      ratio: Math.abs(r.mtf50 - truth) / r.uncertainty,
      inside: Math.abs(r.mtf50 - truth) <= r.uncertainty };
  });
  N.biasOutsideInterval = bias.filter((b) => !b.inside).length;
  ok(near(bias[0].offset, 0.00148611, 5e-7),
    `the anchor sits ${bias[0].offset.toFixed(6)} cycles/pixel from its closed form`);
  ok(near(bias[0].u, 0.00012004, 5e-7),
    `while the interval it prints is plus or minus ${bias[0].u.toFixed(6)}`);
  ok(near(bias[0].ratio, 12.3798, 1e-3),
    `so the offset is ${bias[0].ratio.toFixed(1)} times the interval printed beside it`);
  ok(N.biasOutsideInterval === 3,
    `and on ${N.biasOutsideInterval} of the ${bias.length} slate specimens the exactly known ` +
    'closed form falls outside this page\'s own 95 per cent interval');
  ok(/const combined = Math\.sqrt\(uncertainty \* uncertainty \+ axisTerm \* axisTerm\);/.test(ESRC),
    'the interval is still the bootstrap and the axis term and nothing else, with no bias term smuggled in');
  ok(!/carried into every interval/.test(FLAT),
    'and the page no longer claims that residual is carried into every interval');
  ok(/no bootstrap can see it/.test(FLAT), 'it says instead why no bootstrap can see it');
  ok(/id="t-bias"/.test(HTML) && /id="n-biasoutside"/.test(HTML),
    'and shows the four offsets against the four intervals rather than arguing the point');
  ok(/sits outside that interval, not inside it/.test(INST),
    'and the reader\'s own readout says the same thing beside their own number');
}
{
  // THE NEAR-NYQUIST WARNING FIRES BELOW NYQUIST. It is a warning band at nine tenths of
  // the sampling limit, so the sentence it triggers must not tell the reader their number
  // is above a limit it is below. A phone on a fine printed edge lands in that band.
  const band = [0.28, 0.26, 0.24].map((sigma) => {
    const p = Object.assign({}, S.sfr[0].params, { sigma });
    return Object.assign({ sigma }, est({ params: p }, {}));
  });
  ok(band.every((b) => b.nearNyquist && !b.aboveNyquist && b.mtf50 > 0.45 && b.mtf50 < 0.5),
    'between 0.45 and 0.5 cycles per pixel the flag fires and the answer is still below the sampling limit',
    band.map((b) => b.mtf50.toFixed(4)).join(', '));
  const over = [0.22, 0.20].map((sigma) => {
    const p = Object.assign({}, S.sfr[0].params, { sigma });
    return est({ params: p }, {});
  });
  ok(over.every((b) => b.nearNyquist && b.aboveNyquist && b.mtf50 > 0.5),
    'and above it both flags fire', over.map((b) => b.mtf50.toFixed(4)).join(', '));
  ok(!/above 0\.5 cycles per pixel, which is the sampling limit/.test(INST),
    'so the readout no longer states a number about the reader\'s frame that is false in that band');
  ok(/d\.aboveNyquist/.test(INST) && /within a tenth of the/.test(INST),
    'and it branches on which side of the limit the answer actually landed');
  ok(!/beyondNyquist/.test(INST) && !/beyondNyquist/.test(ESRC),
    'and the flag is no longer named for the thing it does not mean');
}
{
  // THE SHALLOW ROWS. The prose used to say "the two shallow rows" and name a floor of
  // about half a degree; the table has three, and the shallowest of them answers cleanly.
  // Both numbers now come out of the catalogue, and this pins the tie.
  const gateOff = S.tables.angles.filter((t) => t.gateOff);
  N.gateOffRows = gateOff.length;
  ok(N.gateOffRows === 3, `${N.gateOffRows} rows of the angle table are run with the gate off`);
  const answered = gateOff
    .map((t) => { const r = est(t, { geometryGate: false });
      return r.refused ? null : { deg: t.angleDeg, err: r.mtf50 / R.mtf50True(t.params) - 1 }; })
    .filter(Boolean).sort((a, b) => a.deg - b.deg);
  ok(answered.length === gateOff.length, 'and every one of them answers a clean specimen');
  ok(near(answered[0].deg, 0.25, 1e-9), `the shallowest is ${answered[0].deg} degrees`);
  ok(Math.abs(answered[0].err) < 0.01,
    `and it lands within ${(Math.abs(answered[0].err) * 100).toFixed(2)} per cent of its closed form`);
  ok(!/The two shallow rows/.test(FLAT), 'the prose no longer says two');
  ok(!/between about half a degree and two degrees/.test(FLAT),
    'and no longer names a floor the row above it contradicts');
  ok(/id="n-gateoffrows"/.test(HTML) && /id="n-shallowest"/.test(HTML),
    'both counts are printed from the catalogue rather than typed into the sentence');
}
{
  // THE CITATIONS. Each one is checked for the thing a reader following it would find.
  ok(!/slope-error term are both from it/.test(FLAT),
    'the page no longer credits Burns and Williams with the frequency-axis term');
  ok(/own propagation of the fitted/.test(FLAT), 'and says whose that term is');
  ok(/axisTerm = main\.mtf50 \* Math\.abs\(Math\.tan\(th\)\) \* dTheta/.test(ESRC),
    'and the code really is a propagation into the abscissa, not that paper\'s ordinate attenuation');
  const bore = (HTML.match(/<li>G\. D\. Boreman[\s\S]*?<\/li>/) || [])[0] || '';
  ok(bore.length > 0, 'the Boreman citation is on the page');
  ok(/TT52/.test(bore) && /eISBN-9780819480453/.test(bore),
    'and its volume number and its link name the same edition: TT52, 2001, eISBN 9780819480453');
  ok(!/eISBN-9781510639379/.test(bore),
    'the second edition\'s ISBN is not used as the link for the first edition');
  ok(/TT121/.test(bore), 'and the page names the other edition rather than blurring the two');
  ok(/states half of that in its own terms clause/.test(FLAT),
    'the ISO note is credited with the half of the unity bound it actually states');
  ok(!/puts the same fact in its own terms clause/.test(FLAT), 'and not with the other half');
  ok(/beyond the two short attributed quotations above, is not reproduced here/.test(FLAT),
    'and the non-reproduction sentence admits the two quotations on the same page');
  ok(!/the number every lens review quotes/.test(FLAT),
    'MTF50 is no longer called the number every lens review quotes');
  ok(!/no printer prints to the edge/.test(FLAT),
    'and the page no longer denies that borderless printing exists');
  // THE README IS A SHIPPED DOCUMENT TOO, and it is where this exact citation drifted: the
  // page was corrected to TT52/eISBN-9780819480453 and the README was left naming TT52 while
  // linking the second edition. Nothing read the README, so nothing could catch it. Now the
  // two are held to the same volume by the same check.
  const RD = readFileSync(join(ROOT, 'research/slanted-edge-mtf/README.md'), 'utf8');
  ok(/TT52/.test(RD) && /eISBN-9780819480453/.test(RD),
    'the README cites the same Boreman volume the page does: TT52, 2001, eISBN 9780819480453');
  ok(!/TT52[\s\S]{0,400}eISBN-9781510639379/.test(RD),
    'and never labels TT52 with the second edition\'s link');
  for (const [name, src] of [['the page', HTML], ['the README', RD]]) {
    const usesFirst = /eISBN-9780819480453/.test(src), usesSecond = /eISBN-9781510639379/.test(src);
    ok(usesFirst && !usesSecond, `${name} links exactly one edition of Boreman, the one it names`);
  }
  // THE ONE CLAIM ABOUT A CLAUSE NOBODY HERE HAS READ. The page says the standard fits the
  // edge with a fifth-order polynomial. That is true, but Annex D is paywalled and the README
  // says outright it was not read, so the page has to name where the claim DID come from:
  // the fourth edition's foreword change list, which is in that edition's free preview. A
  // page that states what a paywalled clause specifies without saying how it knows is
  // indistinguishable from one that guessed.
  ok(/fifth-order polynomial/.test(FLAT), 'the page names the standard\'s edge fit');
  ok(/foreword of the fourth edition, ISO 12233:2023/.test(FLAT),
    'and names the foreword it read that from, rather than implying it read the annex');
  ok(/which we have not read/.test(FLAT),
    'and says plainly that the annex itself was not read');
  ok(/5th-order polynomial equation to fit the edge/.test(RD),
    'the README carries the foreword sentence the claim rests on, verbatim');
  ok(/[Nn]ot read/.test(RD), 'and still records that the annex body was not read');
}
{
  // THE HASH PANEL must test what its heading says. Rendering from the manifest's own
  // parameters proves only that render.js is deterministic; rendering from specimens.js
  // catches the catalogue drifting away from the manifest, which is the failure the
  // heading promises to catch.
  ok(/const CATALOGUE = new Map\(\)/.test(INST) && /CATALOGUE\.get\(rec\.group \+ ':' \+ rec\.id\)/.test(INST),
    'the in-browser hash panel renders from specimens.js and looks the manifest record up by id');
  ok(!/params: rec\.params/.test(INST),
    'and never renders a specimen from the parameters the manifest itself recorded');
  ok(/UNRECORDED/.test(INST), 'and says so when specimens.js holds a specimen the manifest does not');
}
{
  // ARIA. A live region is for a change the reader caused. Six of these panels fill once
  // during load, and announcing four tables at a screen reader is not an accommodation.
  for (const id of ['slate', 'slate-peak', 'stub', 'stub-peak', 'hashes', 'attest', 'ready', 'n-refusals']) {
    const m = HTML.match(new RegExp('id="' + id + '"[^>]*>'));
    ok(m && !/aria-live/.test(m[0]), `#${id} fills at load, so it is page content and not a live region`);
  }
  for (const id of ['live', 'live2', 'livenote', 'mmline', 'peakverdict', 'halonote', 'rulerout', 'clicklist']) {
    const m = HTML.match(new RegExp('id="' + id + '"[^>]*>'));
    ok(m && /aria-live="polite"/.test(m[0]), `#${id} changes when the reader acts, so it stays a live region`);
  }
}
{
  // THE ROUTE THE PAGE PUSHES FIRST is the one least likely to show the effect the dek
  // advertises, and the page has to say so where the buttons are.
  ok(/downscaled preview/.test(FLAT),
    'the page warns that the live route is usually a downscaled preview, which does not overshoot');
  ok(/still-capture pipeline/.test(FLAT), 'and names the route where the sharpening lives');
}

// ── summary ───────────────────────────────────────────────────────────────────
console.log(`\n${pass} passed, ${fail} failed`);
if (fail) { console.log('\nfailures:'); for (const f of fails) console.log('  ' + f); }
process.exit(fail ? 1 : 0);
