#!/usr/bin/env node
// verify-the-lamp-that-is-not-a-point.mjs
//
// Recompute every number the page prints, from the closed forms and from the shipped
// pixels, and refuse to exit 0 on any disagreement.
//
// The page's central claim is that it recovers an exponent it was not told, using a
// response curve it was not told either. Three independent things have to hold for that
// to be true rather than merely printed, and this file checks all three:
//
//   1. THE SPECIMENS ARE WHAT THEY SAY THEY ARE. Regenerate every shipped PNG and every
//      injected Y4M from the closed forms and compare sha256, so a doctored blob is caught.
//   2. THE GROUND TRUTH IS ARITHMETIC, NOT A MEMORY. Re-derive the local exponent by
//      differentiating ln E with respect to ln r symbolically AND by finite difference,
//      and require them to agree; re-derive the global least squares slopes; re-derive
//      Ryer's exact one per cent.
//   3. WHAT THE READER SEES IS WHAT THE ESTIMATOR PRODUCED. Load the real page in a real
//      browser, read the numbers out of the DOM, and compare them with a Node
//      re-implementation of the estimator written from the written protocol rather than
//      copied from the page. Two implementations disagreeing is a build failure.
//
// It also drives the page's OWN estimator through its refusal paths, because a
// measurement page is most likely to lie where it should have refused.
//
//   node research/the-lamp-that-is-not-a-point/verify-the-lamp-that-is-not-a-point.mjs
//   node research/the-lamp-that-is-not-a-point/verify-the-lamp-that-is-not-a-point.mjs --no-dom
import { readFileSync, existsSync, statSync, mkdirSync, writeFileSync, rmSync } from 'node:fs';
import { createServer } from 'node:http';
import { join, resolve, dirname, extname } from 'node:path';
import { fileURLToPath } from 'node:url';
import {
  A_MM, DIST_MM, STEPS, SCENE, LAWS, N_COVERAGE, SPRITE_PERM,
  decodePngGrey, olsExponent, localExponent, sha256,
} from './scene.mjs';
import { main as makeSpecimens, SPECIMENS, GATE_FILES } from './make-specimens.mjs';
import { estimate as nodeEstimate, CHOICES as NODE_CHOICES } from './estimator-node.mjs';
import {
  SYSTEMATICS, runAll as SYSTEMATICS_RUN_ALL, cosmExponent, cosmGlobal,
  wallExponent, wallRatio, ROOMS, patchBiasLeading,
} from './systematics.mjs';

const HERE = dirname(fileURLToPath(import.meta.url));
const ROOT = resolve(HERE, '../..');
const SLUG = 'the-lamp-that-is-not-a-point';
const PAGE_DIR = join(ROOT, 'public/strata', SLUG);
const NO_DOM = process.argv.includes('--no-dom');

const checks = [];
function ok(name, cond, detail) {
  checks.push({ name, pass: !!cond, detail: detail === undefined ? '' : String(detail) });
  return !!cond;
}
function near(name, got, want, tol, detail) {
  const good = typeof got === 'number' && isFinite(got) && Math.abs(got - want) <= tol;
  return ok(name, good, `got ${fmt(got)}, want ${fmt(want)} ± ${tol}${detail ? '; ' + detail : ''}`);
}
const fmt = (v) => (typeof v === 'number' ? (Math.abs(v) < 1e-4 && v !== 0 ? v.toExponential(3) : v.toFixed(6)) : String(v));

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

// ── 1. the specimens are what they say they are ───────────────────────────────
const regen = makeSpecimens();
for (const s of regen.specimens) {
  ok(`specimen ${s.file} regenerates byte for byte`, s.match,
    s.match ? `${s.sha256.slice(0, 16)}` : `on disk ${String(s.onDisk).slice(0, 16)}, regenerated ${s.sha256.slice(0, 16)}`);
}
for (const g of regen.gate) {
  ok(`gate video ${g.file} regenerates byte for byte`, g.match,
    g.match ? `${g.sha256.slice(0, 16)}` : `on disk ${String(g.onDisk).slice(0, 16)}, regenerated ${g.sha256.slice(0, 16)}`);
}
const specBytes = SPECIMENS.reduce((a, s) => a + statSync(join(PAGE_DIR, 'specimens', s.file)).size, 0);
ok('the shipped specimens fit the wave budget of 3 MB', specBytes < 3 * 1024 * 1024,
  `${(specBytes / 1048576).toFixed(2)} MB across ${SPECIMENS.length} files`);
ok('no specimen carries a third-party licence obligation',
  !existsSync(join(PAGE_DIR, 'specimens/LICENCE')) &&
  SPECIMENS.every(() => true) && /CC0 1\.0/.test(html),
  'every frame is generated here from a closed form; the page says so and claims CC0');

// ── 2. the ground truth is arithmetic ─────────────────────────────────────────
// The on-axis irradiance of a uniform Lambertian disc of radius a is E = pi L a^2/(a^2+r^2).
// Its local exponent is p(r) = -d ln E / d ln r. Symbolically that is 2 r^2/(a^2+r^2),
// which equals 2/(1+(a/r)^2). Independently, by centred finite difference in log space.
const symbolic = (r, a = A_MM) => 2 * r * r / (a * a + r * r);
const numeric = (r, a = A_MM) => {
  const h = 1e-5;
  const lnE = (x) => Math.log(a * a / (a * a + x * x));
  return -(lnE(Math.exp(Math.log(r) + h)) - lnE(Math.exp(Math.log(r) - h))) / (2 * h);
};
let worstDeriv = 0;
for (const r of DIST_MM) {
  worstDeriv = Math.max(worstDeriv, Math.abs(symbolic(r) - numeric(r)), Math.abs(symbolic(r) - localExponent(r)));
}
ok('the local exponent agrees between symbolic differentiation, finite difference and the shipped formula',
  worstDeriv < 1e-6, `worst disagreement ${worstDeriv.toExponential(2)} over ${DIST_MM.length} distances`);

const discTruth = olsExponent('disc');
const lineTruth = olsExponent('line');
const planeTruth = olsExponent('plane');
// Recompute the disc slope from the raw law rather than through olsExponent, so a bug in
// that helper cannot make both sides agree with each other and with nothing else.
{
  const xs = DIST_MM.map(Math.log);
  const ys = DIST_MM.map((r) => Math.log(A_MM * A_MM / (A_MM * A_MM + r * r)));
  const mx = xs.reduce((a, b) => a + b, 0) / xs.length;
  const my = ys.reduce((a, b) => a + b, 0) / ys.length;
  let num = 0, den = 0;
  for (let i = 0; i < xs.length; i++) { num += (xs[i] - mx) * (ys[i] - my); den += (xs[i] - mx) ** 2; }
  near('the disc anchor 1.951698 is the least squares slope of ln E against ln r', -num / den, discTruth, 1e-12);
}
near('the disc anchor value printed on the page', discTruth, 1.951698, 5e-7);
near('the line control is exactly 1', lineTruth, 1.0, 1e-12);
near('the plane control is exactly 0', planeTruth, 0.0, 1e-12);
ok('the page prints the disc truth to six places', html.includes('1.951698'));
ok('the page prints the line control truth', html.includes('1.000000'));
ok('the page prints the plane control truth', html.includes('0.000000'));

// Ryer's five times rule, reproduced as algebra. At r = 10a the point-source formula
// overstates E by (a^2+r^2)/r^2, and the local exponent is 2/1.01.
const rFive = 10 * A_MM;
const overstate = (A_MM * A_MM + rFive * rFive) / (rFive * rFive);
near('the point-source overstatement at ten radii is exactly 1.01', overstate, 1.01, 1e-12);
near('and the local exponent there is 2/1.01', localExponent(rFive), 2 / 1.01, 1e-12);
near('which is 1.980198 to six places', localExponent(rFive), 1.980198, 5e-7);
ok('the page prints 1.0100 for the one per cent', html.includes('1.0100'));
ok('the page prints 1.980198 as 2/1.01', html.includes('1.980198') || html.includes('2/1.01'));
ok('the page states the closed form p(r) = 2/(1 + (a/r)^2)',
  /2\/\(1 \+ \(a\/r\)&sup2;\)/.test(html));

// The two phrases the page puts inside <q> are quotations, so they are checked as strings
// against what chapter 6 actually says, transcribed here from the cited page. A quotation
// that is nearly right is the failure mode this check exists for: an earlier draft carried
// "accurate within 1%", which is nowhere in the source and which turns Ryer's exact value at
// one distance into a bound over a range.
const RYER_VERBATIM = [
  'the distance to a light source should be greater than five times the largest dimension of the source',
  'the error from using the inverse square is exactly 1 %',
];
{
  const quoted = [...html.matchAll(/<q>([\s\S]*?)<\/q>/g)].map((m) => m[1].replace(/\s+/g, ' ').trim());
  ok('the page quotes Ryer in exactly two places', quoted.length === 2, quoted.length + ' <q> elements');
  for (const want of RYER_VERBATIM) {
    ok(`the quoted phrase "${want.slice(0, 44)}..." is verbatim from chapter 6`,
      quoted.includes(want), quoted.join(' | ').slice(0, 160));
  }
  ok('and no phrase Ryer never wrote is presented as a quotation',
    !/accurate within 1\s?%/i.test(html), 'the source says the error is exactly 1 %, not accurate within 1%');
  ok('the footer says how many phrases are quoted, and that is how many there are',
    /quoted in two short phrases/.test(html.replace(/\s+/g, ' ')) && quoted.length === 2);
}
// Ryer states the rule in DIAMETERS and the page maps it onto RADII, so the mapping is
// arithmetic and is checked as arithmetic: ten radii is five diameters is five times the
// largest dimension of a disc.
ok('ten source radii really is five times the largest dimension of a disc',
  10 * A_MM === 5 * (2 * A_MM), `${10 * A_MM} mm either way`);

// The sphere, which the plain card used to generalise to and which behaves differently. A
// uniform Lambertian sphere of radius a has intensity pi*L*a^2 in every direction, so from
// its CENTRE it is exactly inverse square at every distance; measured from the glass, as
// this page's protocol says to measure, its local exponent is 2r/(r+a) and not 2/(1+(a/r)^2).
{
  const sphereSym = (r, a = A_MM) => 2 * r / (r + a);
  const sphereNum = (r, a = A_MM) => {
    const h = 1e-5;
    const lnE = (x) => Math.log(1 / ((x + a) * (x + a)));
    return -(lnE(Math.exp(Math.log(r) + h)) - lnE(Math.exp(Math.log(r) - h))) / (2 * h);
  };
  let worst = 0;
  for (const r of DIST_MM) worst = Math.max(worst, Math.abs(sphereSym(r) - sphereNum(r)));
  ok('the sphere-from-the-glass exponent 2r/(r+a) agrees with finite difference', worst < 1e-6,
    `worst disagreement ${worst.toExponential(2)}`);
  near('and it is 5/3 at five radii, where the disc gives 1.923', sphereSym(5 * A_MM), 5 / 3, 1e-12);
  ok('the disc and the sphere really do disagree there, which is why the page names the shape',
    Math.abs(localExponent(5 * A_MM) - sphereSym(5 * A_MM)) > 0.25,
    `disc ${localExponent(5 * A_MM).toFixed(4)} against sphere ${sphereSym(5 * A_MM).toFixed(4)}`);
  ok('the page states the sphere case and its formula rather than leaving the disc to stand for every lamp',
    /2r\/\(r\+a\)/.test(html) && /sphere/i.test(html));
}
// The plain card is a standalone shareable surface, so it cannot inherit "disc" from a body
// it does not travel with.
{
  const pc = (frontmatter.match(/^plain:\s*"([\s\S]*?)"\s*$/m) || [])[1] || '';
  ok('the plain card says which SHAPE the closed form is for, since it travels alone',
    /\b(flat disc|disc|flat source)\b/.test(pc) && /2\/\(1\+\(a\/r\)squared\)/.test(pc.replace(/\s/g, '')),
    pc.slice(0, 90));
}
ok('the sweep runs from the first to the last protocol distance, and the page says so',
  html.includes(`${DIST_MM[0]} mm to ${DIST_MM[DIST_MM.length - 1]} mm`),
  `${DIST_MM[0]} to ${DIST_MM[DIST_MM.length - 1]}`);
// A 5 mm ERROR at 90 mm is 5.56% of r. Placing "to the nearest 5 mm" bounds the error at
// 2.5 mm, which is 2.8%, so the page must say error and not quantisation bin: the sentence
// is checked as well as the arithmetic.
ok('a 5 mm placement error at the nearest distance really is more than 5 per cent',
  100 * 5 / DIST_MM[0] > 5 && html.includes('a 5 mm placement error at the nearest position, 90 mm, is more than 5% in r'),
  `${(100 * 5 / DIST_MM[0]).toFixed(2)}%`);
ok('and the page does not claim that placing to the NEAREST 5 mm is that error',
  !/nearest 5 mm[^.]*more than 5%/.test(html.replace(/\s+/g, ' ')),
  'half a 5 mm bin is 2.5 mm, which is 2.78% of 90 mm, not more than 5%');

// ── 3. the two implementations ────────────────────────────────────────────────
function framesFromSprite(file) {
  const { w, h, pixels } = decodePngGrey(readFileSync(join(PAGE_DIR, 'specimens', file)));
  const fw = SCENE.w, fh = SCENE.h, cols = 8;
  const frames = [];
  for (let cell = 0; cell < STEPS.length; cell++) {
    const cx = (cell % cols) * fw, cy = Math.floor(cell / cols) * fh;
    const green = new Uint8Array(fw * fh);
    for (let y = 0; y < fh; y++) for (let x = 0; x < fw; x++) green[y * fw + x] = pixels[(cy + y) * w + cx + x];
    frames.push({ width: fw, height: fh, green });
  }
  return frames;
}
const nodeRuns = {};
for (const s of SPECIMENS) {
  const id = s.file.replace(/^lamp-/, '').replace(/\.png$/, '');
  nodeRuns[id] = nodeEstimate({ frames: framesFromSprite(s.file) });
  ok(`the node re-implementation returns a number on ${id}`, !nodeRuns[id].refused,
    nodeRuns[id].refused ? JSON.stringify(nodeRuns[id].refused) : `p = ${nodeRuns[id].value.toFixed(5)}`);
}
// The four recovered response curves, laid on top of each other HERE rather than trusting the
// page's own comparison of them. A recovered curve is only ever pinned down up to a scale and
// an offset, because every constraint it was fitted through is a difference, so each one is
// renormalised across the range of code values all four specimens reached before any of them
// are compared. Same definition as the page's, written from it rather than copied.
function curveAt(d, v) {
  const k = d.knots, t = d.theta, m = k.length;
  if (v <= k[0]) return t[0];
  if (v >= k[m - 1]) return t[m - 1];
  let i = 0;
  while (i < m - 2 && v > k[i + 1]) i++;
  const u = (v - k[i]) / (k[i + 1] - k[i]);
  return t[i] * (1 - u) + t[i + 1] * u;
}
function nodeCurveSpread(ds) {
  const vA = Math.max(...ds.map((d) => d.codeRange[0]));
  const vB = Math.min(...ds.map((d) => d.codeRange[1]));
  const pinned = ds.map((d) => {
    const a = curveAt(d, vA), b = curveAt(d, vB);
    return (v) => (curveAt(d, v) - a) / (b - a);
  });
  let worst = 0;
  for (let i = 0; i <= 200; i++) {
    const v = vA + (vB - vA) * i / 200;
    const ys = pinned.map((f) => f(v));
    worst = Math.max(worst, Math.max(...ys) - Math.min(...ys));
  }
  return { spread: worst, vA, vB, n: ds.length };
}
const nodeSpread = nodeCurveSpread(['disc', 'disc-exposure-drift', 'line', 'plane'].map((id) => nodeRuns[id].diagnostics));

// The sprite sheet's cell order is a fixed permutation of step order, so a frame's place
// in the sheet is not its step number: the estimator has to read the band out of pixels.
ok('the sprite order is a permutation of step order, not step order itself',
  new Set(SPRITE_PERM).size === STEPS.length && SPRITE_PERM.some((v, i) => v !== i),
  `${STEPS.length} distinct cells, ${SPRITE_PERM.filter((v, i) => v !== i).length} of them moved`);

near('the node estimator recovers the disc anchor', nodeRuns.disc.value, discTruth, 0.06);
near('the node estimator recovers the disc through an exposure hunt', nodeRuns['disc-exposure-drift'].value, discTruth, 0.06);
near('the node estimator recovers the line control', nodeRuns.line.value, lineTruth, 0.03);
near('the node estimator recovers the plane control', nodeRuns.plane.value, planeTruth, 0.03);
ok('the exposure-drift specimen really does drift',
  nodeRuns['disc-exposure-drift'].diagnostics.gainSpreadPct > 50,
  `${nodeRuns['disc-exposure-drift'].diagnostics.gainSpreadPct.toFixed(0)}% of exposure swing across the sweep`);
ok('assuming the pixels are linear gets the anchor badly wrong, which is the point of the page',
  Math.abs(nodeRuns.disc.diagnostics.naiveExponent - discTruth) > 0.4,
  `linear assumption gives ${nodeRuns.disc.diagnostics.naiveExponent.toFixed(4)} against a true ${discTruth.toFixed(6)}`);
ok('and it gets the controls wrong too, so it is not a lucky constant',
  Math.abs(nodeRuns.line.diagnostics.naiveExponent - 1) > 0.2 &&
  Math.abs(nodeRuns.plane.diagnostics.naiveExponent) < 0.5,
  `line ${nodeRuns.line.diagnostics.naiveExponent.toFixed(4)}, plane ${nodeRuns.plane.diagnostics.naiveExponent.toFixed(4)}`);

// A degenerate estimator must fail this slate. Three of them, each a different lie.
{
  const truths = { disc: discTruth, 'disc-exposure-drift': discTruth, line: lineTruth, plane: planeTruth };
  const tols = { disc: 0.06, 'disc-exposure-drift': 0.06, line: 0.03, plane: 0.03 };
  const stubs = {
    'always returns 2': () => 2,
    'always returns the anchor': () => discTruth,
    'assumes the pixels are linear': (id) => nodeRuns[id].diagnostics.naiveExponent,
  };
  for (const [label, f] of Object.entries(stubs)) {
    const failed = Object.keys(truths).filter((id) => Math.abs(f(id) - truths[id]) > tols[id]);
    ok(`a stub that ${label} fails at least one specimen`, failed.length > 0, `fails ${failed.join(', ')}`);
  }
}

// ── the estimator has no idea what it is looking at ───────────────────────────
const spanStart = instrumentJs.indexOf('ESTIMATOR BEGIN');
const spanEnd = instrumentJs.lastIndexOf('ESTIMATOR END');
const span = spanStart >= 0 && spanEnd > spanStart ? instrumentJs.slice(spanStart, spanEnd) : '';
ok('the estimator span exists and is substantial', span.length > 4000, `${span.length} characters`);
for (const forbidden of ['GROUND_TRUTH', 'GENERATOR_OETF', '1.951698', 'isSpecimen', 'expected',
  'truth', 'A_MM', 'LAWS', 'gainAt', 'olsExponent', 'localExponent', 'specimen']) {
  ok(`the estimator never mentions "${forbidden}"`, !span.includes(forbidden));
}
// And it contains no transfer curve at all, assumed or otherwise: not the generator's own
// exponent, not sRGB's, not the 2.2 the page uses to shade a swatch. The whole point is
// that the curve is recovered from the coverage ladder in the picture.
for (const forbidden of ['2.35', '2.2', 'sRGB', 'gamma', '1.055', '0.0031308']) {
  ok(`the estimator carries no assumed transfer curve: no "${forbidden}"`, !span.includes(forbidden));
}
// The floating-origin search has to be bounded by something, and WHICH something decides
// whether the recovery is honest. Bounding it by the reader's stated source size would hand
// the estimator the one number it is not allowed to know, and would bound precisely the
// parameter that absorbs the source-size effect. It is bounded by the sweep's own nearest
// distance instead, and the span carries no name for a source radius at all.
ok('the floating-origin search is bounded by the sweep, not by any stated source size',
  /0\.5 \* pts\[0\]\.r/.test(span) &&
  !/(radius|ahat|sourceSize|emitter)/i.test(span),
  'r0 is searched over +/- half the nearest lamp distance');
ok('the estimator never branches on where its frames came from',
  !/payload\s*\.\s*(role|kind|source|isLive|id|label)/.test(span));
ok('nothing outside the estimator is called from inside it except its own helpers',
  !/\bAW\s*\./.test(span) && !/document\./.test(span) && !/window\./.test(span));

// probeLive must capture exactly the way the reader's own button does.
ok('the reader\'s button captures with captureSession and measures with the instrument',
  /\$\('go'\)\.addEventListener[\s\S]*?captureSession\([\s\S]*?inst\.measure\(\{ frames: cap\.frames \}\)/.test(instrumentJs));
ok('probeLive captures with the same captureSession and the same instrument',
  /probeLive:[\s\S]*?captureSession\([\s\S]*?inst\.tryMeasure\(\{ frames: cap\.frames \}\)/.test(instrumentJs));
ok('there is exactly one capture path in the page',
  (instrumentJs.match(/AW\.sensors\.captureFrames\(/g) || []).length === 1);
ok('there is exactly one estimator in the page',
  (instrumentJs.match(/^function estimate\(/gm) || []).length === 1);

// ── the gate case is a real discrimination ────────────────────────────────────
ok('the gate case points at this page', caseJson.path === `/strata/${SLUG}/` && caseJson.sensor === 'camera');
for (const key of ['anchor', 'control']) {
  ok(`the gate's ${key} injection exists`, existsSync(join(ROOT, caseJson.inject[key].file)), caseJson.inject[key].file);
}
near('the gate expects the disc video to give the closed-form disc exponent', caseJson.inject.anchor.expect, discTruth, 5e-7);
near('the gate expects the line video to give exactly 1', caseJson.inject.control.expect, lineTruth, 1e-12);
ok('the gate\'s two injected videos have genuinely different true answers',
  Math.abs(caseJson.inject.anchor.expect - caseJson.inject.control.expect) >
  caseJson.inject.anchor.tol + caseJson.inject.control.tol + 0.5,
  `${Math.abs(caseJson.inject.anchor.expect - caseJson.inject.control.expect).toFixed(4)} apart, ` +
  `tolerances sum to ${(caseJson.inject.anchor.tol + caseJson.inject.control.tol).toFixed(2)}`);
ok('and they are different files with different bytes',
  caseJson.inject.anchor.file !== caseJson.inject.control.file &&
  sha256(readFileSync(join(ROOT, caseJson.inject.anchor.file))) !==
  sha256(readFileSync(join(ROOT, caseJson.inject.control.file))));
ok('the injected sweep is long enough for the page to see every step of it',
  caseJson.liveSeconds * 10 >= STEPS.length * 2,
  `${caseJson.liveSeconds} s at 10 frames per second covers ${(caseJson.liveSeconds * 10 / STEPS.length).toFixed(1)} passes of ${STEPS.length} steps`);

// ── the page's own surface ────────────────────────────────────────────────────
const meta = (name) => (html.match(new RegExp(`<meta\\s+(?:name|property)="${name}"\\s+content="([^"]*)"`)) || [])[1] || '';
const fmField = (k) => {
  const m = frontmatter.match(new RegExp(`^${k}:\\s*"([\\s\\S]*?)"\\s*$`, 'm'));
  return m ? m[1] : '';
};
ok('the page has a canonical URL', html.includes(`<link rel="canonical" href="https://artwaste.land/strata/${SLUG}/" />`));
ok('the search title is under 62 characters', (html.match(/<title>([^<]*)<\/title>/) || [])[1].length <= 62,
  `${(html.match(/<title>([^<]*)<\/title>/) || [])[1].length} characters`);
ok('the frontmatter seoTitle is the page title', fmField('seoTitle') === (html.match(/<title>([^<]*)<\/title>/) || [])[1]);
ok('the meta description is present and is the frontmatter dek', meta('description').length > 80 && fmField('dek') === meta('description'));
let ld = null;
try { ld = JSON.parse((html.match(/<script type="application\/ld\+json">([\s\S]*?)<\/script>/) || [])[1]); } catch (e) { ld = null; }
ok('the JSON-LD block parses as JSON', !!ld);
ok('the JSON-LD headline is the poetic title and the name is the search title',
  ld && ld.headline === 'The Lamp That Is Not a Point' && ld.name === fmField('seoTitle'));
ok('the JSON-LD url is the canonical url', ld && ld.url === `https://artwaste.land/strata/${SLUG}/`);
ok('the share card carries the poetic title, not a retracted framing',
  meta('og:title').startsWith('The Lamp That Is Not a Point'));
ok('the frontmatter seam is one of the closed vocabulary', /^seam:\s*"physical"$/m.test(frontmatter));
ok('the frontmatter href points at this page', frontmatter.includes(`href: "/strata/${SLUG}/"`));
const plain = fmField('plain');
ok('the plain card is present and within 420 characters', plain.length > 0 && plain.length <= 420, `${plain.length} characters`);
ok('the plain card is at most three sentences', (plain.match(/[.!?]/g) || []).length <= 3,
  `${(plain.match(/[.!?]/g) || []).length} sentence-ending marks`);
ok('the plain card says what the instrument cannot do', /cannot|will not|refus|not a/i.test(plain));

// The honesty leak lives in the shareable surface, so the claims there are checked against
// what the apparatus supports.
for (const [where, text] of [['dek', fmField('dek')], ['meta description', meta('description')],
  ['og description', meta('og:description')], ['JSON-LD description', ld ? ld.description : '']]) {
  ok(`the ${where} claims no absolute light measurement`,
    !/\blux\b|\bcandela\b|\blumens?\b|\bfoot-?candles?\b/i.test(text));
  ok(`the ${where} does not claim a discovery`, !/first|never before|discover/i.test(text));
}

// No number on this page is ever attached to a photometric unit. That is the hazard the
// whole design turns on: a camera's spectral response is not the eye's, so a value in
// those units would be an invention however carefully it was computed.
const readerText = html.replace(/<script[\s\S]*?<\/script>/g, '').replace(/<style[\s\S]*?<\/style>/g, '')
  .replace(/\s+/g, ' ');
const UNIT_NEXT_TO_A_NUMBER = /\d+(?:\.\d+)?\s*(?:lux|lx|candelas?|cd|lumens?|lm|nits?|foot-?candles?)\b/i;
ok('no number anywhere in the page is given a photometric unit', !UNIT_NEXT_TO_A_NUMBER.test(readerText),
  (readerText.match(UNIT_NEXT_TO_A_NUMBER) || [''])[0]);
ok('and none in the instrument either', !UNIT_NEXT_TO_A_NUMBER.test(instrumentJs));
ok('the page states why the exponent survives the camera\'s spectral mismatch',
  /spectrum does not change/i.test(readerText) && /constant factor/i.test(readerText));
ok('the page prints the assume-linearity exponent beside the recovered one',
  html.includes('id="n-naive"') && /if we had believed the pixels/i.test(readerText));
ok('the page names the area-coverage argument as display-standard-free',
  /coverage is area/i.test(readerText) && /whatever that panel's gamma is/i.test(readerText));
ok('the page credits the halftone-coverage argument rather than re-deriving it as new',
  html.includes('/strata/the-exponent-between-number-and-light/'));
// The limit the page cannot instrument its way out of, so it has to be said instead. The
// behaviour behind this sentence is measured in the rendered-page pass below.
ok('the page says it cannot see the reader\'s tape measure, and says what happens if the lamp stays put',
  /cannot see your tape measure/i.test(readerText) && /near zero/i.test(readerText));

// The stratum's own prose is a shareable surface too, and the two figures it states are
// checked against the recomputation rather than left to drift alongside the page.
const body = frontmatter.split(/^---$/m).slice(2).join('---');
ok('the stratum prose states the closed-form anchor, and it is the recomputed one',
  body.includes('1.951698') && Math.abs(discTruth - 1.951698) < 5e-7);
ok('the stratum prose states the assume-linear exponent, and it rounds to the recomputed one',
  (body.match(/returns \*\*([0-9.]+)\*\*/) || [])[1] ===
  nodeRuns.disc.diagnostics.naiveExponent.toFixed(2),
  `prose says ${(body.match(/returns \*\*([0-9.]+)\*\*/) || [])[1]}, recomputed ` +
  `${nodeRuns.disc.diagnostics.naiveExponent.toFixed(2)}`);
// The prose is a shareable surface that travels without the page, so the three figures it
// quotes about the floating origin are checked against the estimator's own run, in words as
// well as digits: "eight millimetres BEHIND the glass" is a sign, and a sign is a claim.
{
  const dg = nodeRuns.disc.diagnostics;
  ok('the prose states the floating-origin exponent, and it rounds to the recomputed one',
    body.includes('the\nexponent becomes ' + dg.pFreeOrigin.toFixed(2)) ||
    body.includes('exponent becomes ' + dg.pFreeOrigin.toFixed(2)),
    `recomputed ${dg.pFreeOrigin.toFixed(2)}`);
  ok('and the offset it quotes, with the right sign: a negative r0 puts the apparent source BEHIND the glass',
    dg.r0Free < 0 && Math.round(Math.abs(dg.r0Free)) === 8 &&
    /eight millimetres behind the glass/.test(body),
    `r0 = ${dg.r0Free.toFixed(2)} mm`);
  ok('and that the floating fit leaves about a third of the residual, which is the phrase it uses',
    dg.r0RmsFree < dg.r0RmsFixed && Math.abs(dg.r0RmsFixed / dg.r0RmsFree - 3) < 0.5 &&
    /a third of the one the honest fit leaves/.test(body.replace(/\s+/g, ' ')),
    `${(dg.r0RmsFixed / dg.r0RmsFree).toFixed(2)} times`);
}
{
  const targets = [...frontmatter.matchAll(/^\s+- to: (\S+)$/gm)].map((m) => m[1]);
  const missing = targets.filter((t) => !existsSync(join(ROOT, 'src/content/strata', t + '.md')));
  ok(`all ${targets.length} relates targets are slugs that exist`, targets.length >= 2 && missing.length === 0,
    missing.length ? 'missing: ' + missing.join(', ') : targets.join(', '));
}

// Structure: every inline script must be syntactically valid and every tag closed. A
// missing closing tag silently disables all inline JS and the site build does not catch it.
const inlineScripts = [...html.matchAll(/<script(?![^>]*\bsrc=)([^>]*)>([\s\S]*?)<\/script>/g)];
ok('every inline script block closes', (html.match(/<script/g) || []).length === (html.match(/<\/script>/g) || []).length,
  `${(html.match(/<script/g) || []).length} open, ${(html.match(/<\/script>/g) || []).length} closed`);
ok('the page closes body and html', /<\/body>\s*<\/html>\s*$/.test(html.trim() + '\n'));
ok('the only inline script is the JSON-LD block, and it parses as JSON',
  inlineScripts.length === 1 && inlineScripts[0][1].includes('application/ld+json') && !!ld);
ok('every id in the page is unique', (() => {
  const ids = [...html.matchAll(/\bid="([^"]+)"/g)].map((m) => m[1]);
  return new Set(ids).size === ids.length;
})());
// The allowed list is exactly the cited sources and a licence. Each appears as an href the
// reader may follow, never as something the page loads: the check under this one is what
// separates those two, and it is why this one can be an allowlist rather than a ban.
const CITED_HOSTS = ['artwaste.land', 'schema.org', 'homepages.inf.ed.ac.uk', 'arxiv.org',
  'creativecommons.org', 'tftcentral.co.uk'];
for (const [label, src] of [['the page', html], ['the instrument', instrumentJs], ['the lamp page', lampHtml], ['the lamp script', lampJs]]) {
  const foreign = [...src.matchAll(/https?:\/\/([a-z0-9.-]+)/gi)].map((m) => m[1].toLowerCase())
    .filter((h) => !CITED_HOSTS.includes(h));
  ok(`${label} makes no request to a third-party host`, foreign.length === 0, foreign.join(', '));
}
ok('the only offsite links are the three cited sources and a licence, and they are links, not fetches',
  !/fetch\(\s*['"`]https?:/.test(html + instrumentJs + lampJs) &&
  !/new\s+(?:XMLHttpRequest|WebSocket|EventSource)/.test(html + instrumentJs + lampJs));
ok('the verifier path the page prints really exists',
  html.includes(`research/${SLUG}/verify-${SLUG}.mjs`) &&
  existsSync(join(ROOT, `research/${SLUG}/verify-${SLUG}.mjs`)));
ok('the gate path the page prints really exists',
  html.includes('scripts/check-live-sensor.mjs') && existsSync(join(ROOT, 'scripts/check-live-sensor.mjs')));
ok('the specimen generator the page names really exists',
  html.includes(`research/${SLUG}/make-specimens.mjs`) && existsSync(join(HERE, 'make-specimens.mjs')));
ok('the companion lamp page the instrument links to exists', existsSync(join(PAGE_DIR, 'lamp/index.html')) && html.includes('href="./lamp/"'));

// The free choices printed in the page's check panel are the ones the estimator makes.
const choiceOf = (k) => Number((instrumentJs.match(new RegExp(`${k}:\\s*([0-9.e+-]+)`)) || [])[1]);
ok('the printed refusal threshold for the ladder residual is the one in the code',
  choiceOf('maxResidualPct') === 2 && html.includes('2% of full scale'));
ok('the printed clipping threshold is the one in the code',
  choiceOf('clipFraction') === 0.001 && html.includes('0.1% clipped'));
ok('the printed minimum signal is the one in the code',
  choiceOf('minCodeSignal') === 3 && html.includes('3 code values'));
ok('the printed minimum number of distances is the one in the code',
  choiceOf('minDistances') === 6 && /minimum lamp positions for a fit<\/td><td class="n">6</.test(html));
// and the row says what the 6 is out of. It is 6 of the ten lamp POSITIONS, not 6 of the 48
// protocol steps, and putting the two units in one sentence made it read as 6/48.
ok('the minimum-positions row counts positions, not protocol steps',
  /minimum lamp positions for a fit[\s\S]{0,220}?positions in the <span id="n-steps">/.test(html),
  `${DIST_MM.length} positions across ${STEPS.length} steps`);
ok('the printed bootstrap size is the one in the code',
  choiceOf('bootstrap') === 2000 && html.includes('2000 resamples'));
ok('the printed knot count is the one in the code',
  choiceOf('knots') === 17 && html.includes('17 knots'));
ok('the node re-implementation makes the same free choices as the page',
  NODE_CHOICES.knots === choiceOf('knots') && NODE_CHOICES.bootstrap === choiceOf('bootstrap') &&
  NODE_CHOICES.minDistances === choiceOf('minDistances') && NODE_CHOICES.maxResidualPct === choiceOf('maxResidualPct'));
ok('the lamp page drives coverage by area, in whole dither blocks, so k/16 is exact',
  /BAYER/.test(lampJs) && /whole blocks only/.test(lampJs) && /nCoverage: 16/.test(lampJs));
ok('the dither matrix really does put exactly k of its 16 cells below k, for every k',
  (() => {
    const m = (lampJs.match(/var BAYER = \[([\s\S]*?)\];/) || [])[1];
    if (!m) return false;
    const vals = m.match(/-?\d+/g).map(Number);
    if (vals.length !== 16 || new Set(vals).size !== 16) return false;
    for (let k = 0; k <= 16; k++) if (vals.filter((v) => v < k).length !== k) return false;
    return true;
  })());
ok('the lamp page and the estimator agree on the protocol',
  JSON.parse(JSON.stringify(DIST_MM)).join(',') === (lampJs.match(/distancesMm: \[([^\]]+)\]/) || [])[1].replace(/\s/g, ''));

// ── 4. the refusal paths, driven through the page's own estimator ─────────────
// Assembled here rather than in the browser so the shapes are explicit; run against the
// real estimator below when the DOM pass is on, and against the node one always.
function blankFrame(v) {
  const g = new Uint8Array(SCENE.w * SCENE.h).fill(v);
  return { width: SCENE.w, height: SCENE.h, green: g };
}
const discFrames = framesFromSprite('lamp-disc.png');
// The sprite's cell order is a permutation of the step order, so which lamp position and
// which coverage a cell holds comes from the same table the lamp page uses. Nothing below
// is handed to the estimator; it only decides which frames to damage.
const stepOf = (cell) => STEPS[SPRITE_PERM[cell]];
const bare = (f) => ({ width: f.width, height: f.height, green: f.green });
const keepCells = (pred) => discFrames.filter((_, i) => pred(stepOf(i))).map(bare);
const ROI_BOX = (() => {
  const R = NODE_CHOICES.roi, w = SCENE.w, h = SCENE.h;
  return { x0: Math.round(R.x0 * w), x1: Math.round(R.x1 * w), y0: Math.round(R.y0 * h), y1: Math.round(R.y1 * h) };
})();
// Paste a position's unlit card patch over its lit ones, so lit minus unlit is zero there
// and that distance falls under the signal floor. The rest of the frame is untouched, so
// the code band still reads and the calibration ladders still stand.
function silenceDistances(dis) {
  const dark = {};
  discFrames.forEach((f, i) => { const s = stepOf(i); if (s.k === 0) dark[s.di] = f.green; });
  return discFrames.map((f, i) => {
    const s = stepOf(i);
    if (!dis.includes(s.di)) return bare(f);
    const g = Uint8Array.from(f.green);
    for (let y = ROI_BOX.y0; y < ROI_BOX.y1; y++) for (let x = ROI_BOX.x0; x < ROI_BOX.x1; x++) g[y * SCENE.w + x] = dark[s.di][y * SCENE.w + x];
    return { width: f.width, height: f.height, green: g };
  });
}
// A camera whose numbers stop rising with the light: the half-coverage and full-coverage
// card patches are swapped, so somewhere more light produced a smaller number.
function ceilingCamera() {
  const byKey = {};
  discFrames.forEach((f, i) => { const s = stepOf(i); byKey[s.di + ':' + s.k] = f.green; });
  return discFrames.map((f, i) => {
    const s = stepOf(i);
    const partner = s.k === 8 ? byKey[s.di + ':16'] : s.k === 16 ? byKey[s.di + ':8'] : null;
    if (!partner) return bare(f);
    const g = Uint8Array.from(f.green);
    for (let y = ROI_BOX.y0; y < ROI_BOX.y1; y++) for (let x = ROI_BOX.x0; x < ROI_BOX.x1; x++) g[y * SCENE.w + x] = partner[y * SCENE.w + x];
    return { width: f.width, height: f.height, green: g };
  });
}
// The lamp that never actually moved. Every lamp position's card patch is replaced by the
// nearest position's, so the code band still walks the whole sequence while the light on the
// card never changes: the reader who forgot to slide the lamp along the tape measure. This
// one is NOT a refusal and must not become one. The distances come from the sequence, not
// from anything the page measured, so the honest outcome is a number near zero (the answer
// for a source that did not move) and a page that says out loud it cannot see a tape measure.
function lampNeverMoved() {
  const at0 = {};
  discFrames.forEach((f, i) => { const s = stepOf(i); if (s.di === 0) at0[s.k] = f.green; });
  return discFrames.map((f, i) => {
    const s = stepOf(i);
    if (s.di === 0 || !at0[s.k]) return bare(f);
    const g = Uint8Array.from(f.green);
    for (let y = ROI_BOX.y0; y < ROI_BOX.y1; y++) for (let x = ROI_BOX.x0; x < ROI_BOX.x1; x++) g[y * SCENE.w + x] = at0[s.k][y * SCENE.w + x];
    return { width: f.width, height: f.height, green: g };
  });
}
// Each refusal here is named with the EXACT reason it must give. A disjunction would let two
// branches collapse into one without anything going red, which is how a page ends up with one
// refusal wearing four names.
//
// This list is NOT every branch in the estimator, and saying so is the point. Three are not
// here, for three different reasons, and each reason is checked below rather than asserted:
// `ladders-disagree` is a backstop nothing we could build reaches before the monotonicity
// check fires (the guard-ordering sweep in 4b); `no-spread` cannot be reached at all, because
// the estimator groups points by lamp position and the protocol's ten distances are distinct,
// so the log-distance spread is never zero; and `response-singular` needs the normal matrix
// to lose rank, which a ladder that has already passed the minimum-constraints gate does not
// do. A refusal that cannot fire is worth keeping and is not worth pretending to test.
const REFUSALS = [
  { id: 'nothing at all', payload: { frames: [] }, expect: 'no-lamp' },
  { id: 'frames with no lamp in them', payload: { frames: Array.from({ length: 40 }, () => blankFrame(128)) }, expect: 'no-lamp' },
  { id: 'every frame clipped to white', expect: 'no-lamp',
    payload: { frames: discFrames.map((f) => ({ width: f.width, height: f.height, green: f.green.map((v) => (v > 30 ? 255 : v)) })) } },
  { id: 'a sweep with only one lamp position in it', expect: 'sweep-incomplete',
    payload: { frames: keepCells((s) => s.di === 0).concat(keepCells((s) => s.di === 0)) } },
  { id: 'a sweep with no calibration ladder', expect: 'no-ladder',
    payload: { frames: keepCells((s) => [0, 8, 16].includes(s.k)) } },
  { id: 'a sweep whose far half is under the signal floor', expect: 'too-few-distances',
    payload: { frames: silenceDistances([1, 2, 3, 5, 6]) } },
  { id: 'a camera whose numbers stop rising with the light', expect: 'non-monotone',
    payload: { frames: ceilingCamera() } },
];
for (const t of REFUSALS) {
  const out = nodeEstimate(t.payload);
  const reason = out.refused ? out.refused.reason : null;
  const good = reason !== null && (t.expect instanceof RegExp ? t.expect.test(reason) : reason === t.expect);
  ok(`the node estimator refuses ${t.id} instead of guessing`, good,
    reason === null ? `returned ${out.value}` : `reason "${reason}", detail "${out.refused.detail.slice(0, 80)}"`);
}
// The reasons that are absent from that list, and why. `no-spread` fires when every usable
// point sits at the same log distance; the estimator keys points by lamp position, so this
// needs two positions at one distance, which the protocol does not have. That is a fact about
// the protocol and it is checked as one rather than left as a comment.
ok('the no-spread refusal is unreachable because the protocol\'s ten distances are all distinct',
  new Set(DIST_MM).size === DIST_MM.length && DIST_MM.length >= NODE_CHOICES.minDistances,
  `${new Set(DIST_MM).size} distinct distances, ${NODE_CHOICES.minDistances} needed for a fit`);
ok('and every reason string the estimator can print is one this file knows about',
  (() => {
    const inCode = [...instrumentJs.matchAll(/reason: '([a-z-]+)'/g)].map((m) => m[1]);
    const known = ['no-lamp', 'sweep-incomplete', 'no-ladder', 'response-singular', 'non-monotone',
      'ladders-disagree', 'too-few-distances', 'no-spread'];
    return inCode.length >= 8 && inCode.every((r) => known.includes(r));
  })(),
  [...new Set([...instrumentJs.matchAll(/reason: '([a-z-]+)'/g)].map((m) => m[1]))].join(', '));

// ── 4b. the audit of the guards ───────────────────────────────────────────────
// The page prints a panel of CONSTRUCTED cameras: the anchor's own frames put through a
// differently behaved pipeline and handed to the estimator, which is not told. Every row of
// that panel is reproduced here, from the description rather than from the page's code, and
// compared with the page's own run in the DOM pass below. The point of the panel is that two
// of the faults are NOT caught, so this file has to be able to fail in both directions: a
// fault the page says was caught must really refuse, and a fault the page says walked past
// must really return a number, and the number must really be wrong.
const FAULT_STRENGTH = Number((instrumentJs.match(/var FAULT_STRENGTH = ([0-9.]+)/) || [])[1]);
ok('the page applies one strength to all three curve faults, so no row is tuned',
  FAULT_STRENGTH === 0.5 && (instrumentJs.match(/strength: FAULT_STRENGTH/g) || []).length === 3,
  `strength ${FAULT_STRENGTH}`);
const powLutN = (gam) => {
  const lut = new Uint8Array(256);
  for (let v = 0; v < 256; v++) lut[v] = Math.max(0, Math.min(255, Math.round(255 * Math.pow(v / 255, gam))));
  return lut;
};
const applyLutN = (f, lut, fromY) => {
  const g = Uint8Array.from(f.green), y0 = fromY ? Math.floor(fromY * f.height) : 0;
  for (let y = y0; y < f.height; y++) for (let x = 0; x < f.width; x++) g[y * f.width + x] = lut[g[y * f.width + x]];
  return { width: f.width, height: f.height, green: g };
};
const FAULTS_NODE = {
  none: (fr) => fr.map(bare),
  whole: (fr, d) => fr.map((f) => {
    let s = 0;
    for (let i = 0; i < f.green.length; i++) s += f.green[i];
    return applyLutN(f, powLutN(1 + d * (s / f.green.length / 255)), 0);
  }),
  position: (fr, d) => fr.map((f, cell) =>
    applyLutN(f, powLutN(1 + d * (stepOf(cell).di / (DIST_MM.length - 1))), NODE_CHOICES.roi.y0)),
  coverage: (fr, d) => fr.map((f, cell) =>
    applyLutN(f, powLutN(1 + d * (stepOf(cell).k / N_COVERAGE)), 0)),
  ceiling: () => ceilingCamera(),
};
const faultRuns = {};
for (const [id, make] of Object.entries(FAULTS_NODE)) {
  const strength = id === 'none' || id === 'ceiling' ? 0 : FAULT_STRENGTH;
  const out = nodeEstimate({ frames: make(discFrames, strength) });
  faultRuns[id] = { refused: out.refused ? out.refused.reason : null,
    value: out.refused ? null : out.value, residualPct: out.refused ? null : out.diagnostics.residualPct };
}
ok('the fault harness leaves the anchor alone when it is asked for no fault',
  faultRuns.none.refused === null && Math.abs(faultRuns.none.value - nodeRuns.disc.value) < 1e-12,
  `p = ${faultRuns.none.value.toFixed(6)}`);
ok('a camera whose numbers stop rising with the light is refused, and refused by the monotonicity check',
  faultRuns.ceiling.refused === 'non-monotone', String(faultRuns.ceiling.refused));
ok('a camera that re-meters on the whole picture is not refused, and the answer still survives it',
  faultRuns.whole.refused === null && Math.abs(faultRuns.whole.value - discTruth) <= 0.06,
  `p = ${faultRuns.whole.value.toFixed(4)} against ${discTruth.toFixed(6)}`);
for (const id of ['position', 'coverage']) {
  ok(`a camera that re-meters on the ${id === 'position' ? 'lamp position' : 'coverage'} walks past every guard`,
    faultRuns[id].refused === null && Math.abs(faultRuns[id].value - discTruth) > 0.06,
    faultRuns[id].refused ? `refused ${faultRuns[id].refused}` :
      `p = ${faultRuns[id].value.toFixed(4)}, out by ${Math.abs(faultRuns[id].value - discTruth).toFixed(4)}`);
}
ok('and none of the faults that walked past raised the ladder residual anywhere near its threshold',
  Object.values(faultRuns).every((r) => r.residualPct === null || r.residualPct < NODE_CHOICES.maxResidualPct),
  `worst ${Math.max(...Object.values(faultRuns).filter((r) => r.residualPct !== null).map((r) => r.residualPct)).toFixed(3)}% ` +
  `against a threshold of ${NODE_CHOICES.maxResidualPct}%`);
// The strength is claimed to be the largest at which all three still decode. The half of
// that claim which can go wrong silently is the upper end, so it is the half that is checked.
{
  const at08 = nodeEstimate({ frames: FAULTS_NODE.coverage(discFrames, 0.8) });
  ok('0.5 is the largest round strength at which all three faults still decode a sweep',
    !!at08.refused && /sweep-incomplete|no-lamp/.test(at08.refused.reason),
    `at 0.8 the coverage-driven camera gives "${at08.refused ? at08.refused.reason : 'a number'}"`);
}

// THE GUARD ORDERING. The page says the 2% ladder-residual refusal is a backstop it could
// not reach, because any disagreement large enough first turns the fitted curve back on
// itself. That is a claim about which of two guards fires, so it is swept rather than
// asserted: stretch a calibration ladder onto another one's code range, over a range of
// shapes, and record what comes out.
{
  const roiMean = (f) => {
    let s = 0, n = 0;
    for (let y = ROI_BOX.y0; y < ROI_BOX.y1; y++) for (let x = ROI_BOX.x0; x < ROI_BOX.x1; x++) { s += f.green[y * SCENE.w + x]; n++; }
    return s / n;
  };
  const cover = {};
  discFrames.forEach((f, i) => { const s = stepOf(i); (cover[s.di] = cover[s.di] || {})[s.k] = roiMean(f); });
  const stretchOnto = (dis, gamma) => {
    const lo = cover[0][0], hi = cover[0][N_COVERAGE];
    return discFrames.map((f, i) => {
      const s = stepOf(i);
      if (!dis.includes(s.di)) return bare(f);
      const B = cover[s.di];
      const g = Uint8Array.from(f.green);
      for (let y = ROI_BOX.y0; y < ROI_BOX.y1; y++) for (let x = ROI_BOX.x0; x < ROI_BOX.x1; x++) {
        const t = Math.max(0, Math.min(1, (g[y * SCENE.w + x] - B[0]) / (B[N_COVERAGE] - B[0])));
        g[y * SCENE.w + x] = Math.max(0, Math.min(255, Math.round(lo + (hi - lo) * Math.pow(t, gamma))));
      }
      return { width: f.width, height: f.height, green: g };
    });
  };
  const seen = [];
  for (const dis of [[4], [9], [4, 9]]) {
    for (const gamma of [0.7, 0.85, 1.0, 1.15, 1.3]) {
      const out = nodeEstimate({ frames: stretchOnto(dis, gamma) });
      seen.push({ dis: dis.join('+'), gamma,
        reason: out.refused ? out.refused.reason : null,
        residualPct: out.refused ? null : out.diagnostics.residualPct });
    }
  }
  const refusals = seen.filter((s) => s.reason !== null);
  ok('a ladder conflict does make this estimator refuse, over most of the range swept',
    refusals.length >= 5, `${refusals.length} of ${seen.length} conflicts refused`);
  ok('and every one of those refusals is the monotonicity check, not the ladder residual',
    refusals.every((s) => s.reason === 'non-monotone'),
    [...new Set(refusals.map((s) => s.reason))].join(', '));
  ok('the ladder residual never reached its own threshold anywhere in the sweep, which is what the page says about it',
    seen.every((s) => s.residualPct === null || s.residualPct <= NODE_CHOICES.maxResidualPct),
    `worst surviving residual ${Math.max(...seen.filter((s) => s.residualPct !== null).map((s) => s.residualPct)).toFixed(3)}%`);
  ok('the page says that, in those words, rather than calling the residual a tone-mapping detector',
    /backstop/.test(html) && !/tone.mapping detector[^,.]*\bdoes\b/.test(html) &&
    /will not call\s+it a tone-mapping detector/.test(html.replace(/\s+/g, ' ')));
  ok('and the refusal is named for what it observes rather than for a cause it cannot establish',
    !/'tone-mapping'/.test(instrumentJs) && /'ladders-disagree'/.test(instrumentJs));
}

// ── 4c. the four systematics that are NOT the camera ──────────────────────────
// The guard-audit panel above can only build cameras, because a camera is a function from
// light to a number and can therefore be applied to a picture that already exists. The
// lamp, the card and the room change the LIGHT, so each one is measured by re-rendering
// the whole sweep with the fault in the scene and running the same estimator on it. That
// work is in systematics.mjs; this section checks that the page prints what it measures,
// that the control run is bit-faithful to the shipped anchor, and that each row also
// reproduces through a second, independent route.
const sysRuns = SYSTEMATICS_RUN_ALL();
{
  // (i) the variant renderer is the shipped renderer when nothing is faulted. Without this
  // every number below would be measured against an apparatus of its own.
  near('the systematics renderer reproduces the shipped anchor exactly when no fault is set',
    sysRuns.none.value, nodeRuns.disc.value, 1e-12,
    'the control run and the shipped sprite give the same exponent through the same estimator');

  // (ii) every row returns a number and none of them trips a guard. That is the claim the
  // section makes, and it has to be able to fail in that direction.
  const refusedRows = SYSTEMATICS.filter((row) => sysRuns[row.id].refused !== null);
  ok('every one of the systematics rows walks past every guard, which is what the page says about them',
    refusedRows.length === 0, refusedRows.map((r) => `${r.id}: ${sysRuns[r.id].refused}`).join(', '));
  const worstSysResid = Math.max(...SYSTEMATICS.map((row) => sysRuns[row.id].residualPct));
  ok('and none of them raises the ladder residual anywhere near the threshold that would refuse them',
    worstSysResid < 0.05 && worstSysResid < NODE_CHOICES.maxResidualPct,
    `worst ${worstSysResid.toFixed(3)}% against a threshold of ${NODE_CHOICES.maxResidualPct}%`);
  ok('the page states that worst residual and it is the one measured here',
    html.includes(`<span class="mono">${worstSysResid.toFixed(3)}</span>% of full scale against a threshold of 2%`),
    worstSysResid.toFixed(3));

  // (iii) the printed table, cell by cell, against the run just made
  const cell = (key) => (html.match(new RegExp(`data-sys="${key}"[^>]*>([^<]+)<`)) || [])[1];
  const badCells = [];
  for (const row of SYSTEMATICS) {
    if (row.id === 'patch25') continue;                 // quoted in prose, checked below
    const got = sysRuns[row.id];
    if (cell(row.id) !== got.value.toFixed(4)) badCells.push(`${row.id}: page "${cell(row.id)}", measured ${got.value.toFixed(4)}`);
    if (cell(row.id + '-r') !== got.residualPct.toFixed(3)) badCells.push(`${row.id} residual: page "${cell(row.id + '-r')}", measured ${got.residualPct.toFixed(3)}`);
  }
  ok(`all ${2 * (SYSTEMATICS.length - 1)} cells of the systematics table are the numbers this file measured`,
    badCells.length === 0, badCells.join(' | '));
  // and the shifts the prose quotes beside them
  const shift = (id) => sysRuns[id].value - sysRuns.none.value;
  const badShifts = [];
  for (const [id, printed] of [['abl2', '+0.031'], ['abl5', null], ['cos1', '&minus;0.012'],
    ['patch102', '&minus;0.086'], ['patch210', '&minus;0.316'], ['bedroom', '&minus;0.015'], ['bathroom', '&minus;0.041']]) {
    if (printed === null) continue;
    const want = (shift(id) >= 0 ? '+' : '&minus;') + Math.abs(shift(id)).toFixed(3);
    if (want !== printed) badShifts.push(`${id}: page says ${printed}, measured ${want}`);
  }
  ok('and every shift the prose quotes beside a row is that row minus the control',
    badShifts.length === 0, badShifts.join(' | '));
  // "three of them are larger than the effect being measured" is a count, so it is counted.
  {
    const departure = Math.abs(2 - discTruth);
    const bigger = SYSTEMATICS.filter((row) => row.id !== 'none' && row.id !== 'patch25' &&
      Math.abs(sysRuns[row.id].value - sysRuns.none.value) > departure);
    ok('the page says how many of those rows are larger than the departure the page is measuring, and that is how many there are',
      bigger.length === 3 &&
      /<strong>three<\/strong> of them are larger than the whole departure from 2 that this page exists to show, which is 0\.0483/
        .test(html.replace(/\s+/g, ' ')),
      `${bigger.length} rows above ${departure.toFixed(4)}: ${bigger.map((b) => b.id).join(', ')}`);
    near('and that departure is 2 minus the anchor, to the digits the page prints', departure, 0.0483, 5e-5);
  }
  ok('the 5% droop row really does read above 2, which is the sentence next to it',
    sysRuns.abl5.value > 2 && html.includes('it now reads above 2'), sysRuns.abl5.value.toFixed(4));
  ok('the patch the page tells the reader to aim for costs what the page says it costs',
    Math.abs(shift('patch25')) < 0.01 &&
    html.includes('A patch 25 mm across costs <span class="mono">0.006</span>'),
    `25 mm patch: ${shift('patch25').toFixed(4)}`);
  ok('and the sheet of paper it tells them not to use costs about a third of an exponent',
    Math.abs(shift('patch210')) > 0.3 && /an A4 sheet filling the box costs a third of an\s+exponent/.test(html),
    `210 mm patch: ${shift('patch210').toFixed(4)}`);

  // (iv) a second route to each row. The end-to-end runs above go through pixels, an 8-bit
  // quantiser, a fitted response curve and a least squares; the closed forms below go
  // through none of those. Agreement to a thousandth of an exponent is what says the
  // measured shift is the physics and not the pipeline.
  const cosGlobal = cosmGlobal(1) - cosmGlobal(0);
  near('the cos-theta emitter row agrees with the closed-form propagation of the same law',
    shift('cos1'), cosGlobal, 2e-3, `rendered ${shift('cos1').toFixed(4)}, closed form ${cosGlobal.toFixed(4)}`);
  for (const [id, room] of [['bedroom', ROOMS[0]], ['bathroom', ROOMS[1]]]) {
    const closed = wallExponent(room.rho, room.area) - discTruth;
    near(`the ${id} wall row agrees with the closed-form interreflection propagation`,
      shift(id), closed, 3e-3, `rendered ${shift(id).toFixed(4)}, closed form ${closed.toFixed(4)}`);
  }
  // the card patch, against its leading-order term. This one is only expected to agree in
  // ORDER, because (W^2+T^2)/(3r^2) is a first-order expansion and the patch is not small
  // at 90 mm, so the check is that the page's formula points the right way and is the right
  // size, not that it is exact. Saying which of those is being checked is the point.
  const lead = patchBiasLeading(102, Math.sqrt(DIST_MM[0] * DIST_MM[DIST_MM.length - 1]));
  ok('the leading-order card-patch formula on the page has the sign and the scale of the measured shift',
    lead < 0 && shift('patch102') < 0 && Math.abs(lead / shift('patch102')) > 0.3 && Math.abs(lead / shift('patch102')) < 3,
    `leading order at the log-mean distance ${lead.toFixed(4)}, measured ${shift('patch102').toFixed(4)}`);
  ok('and the page prints that formula rather than only its consequences',
    html.includes('(W&sup2; + T&sup2;)/(3r&sup2;)'));

  // (v) the closed forms the prose quotes for a non-Lambertian emitter, and the one thing
  // that makes them safe to quote: at m = 0 the general form must collapse onto the page's
  // own p(r) = 2/(1+(a/r)^2), or it is a different model wearing the same name.
  let worstCollapse = 0;
  for (const r of DIST_MM) worstCollapse = Math.max(worstCollapse, Math.abs(cosmExponent(r, 0) - localExponent(r)));
  ok('the cos^m exponent collapses onto the page\'s closed form at m = 0, to 1e-6',
    worstCollapse < 1e-6, `worst ${worstCollapse.toExponential(2)} over ${DIST_MM.length} distances`);
  near('the page\'s 0.8204 at one radius for a cos-theta emitter is the recomputed value',
    cosmExponent(A_MM, 1), 0.8204, 5e-5);
  near('and its 1.9042 at five radii', cosmExponent(5 * A_MM, 1), 1.9042, 5e-5);
  ok('the page prints both, next to the Lambertian values they replace',
    html.includes('0.8204') && html.includes('1.9042') && html.includes('1.9231'));

  // (vi) THE CONTROLS ARE IMMUNE, which is the reason the page can point at them. An
  // infinite uniform line gives p = 1 and an infinite plane p = 0 for ANY angular law, so
  // those two rows of the slate test the instrument and not the model. Integrated here for
  // three different emitter laws rather than asserted.
  {
    // A line of emitting elements whose radiance goes as cos^m of the angle from their own
    // normal. Integrated by substitution z = r tan(phi), which is what makes the r cancel:
    // dE goes as cos^(m+1)(phi) dphi / r, so E = C/r for every m. Done numerically here,
    // over the substituted variable, so the tail is integrated rather than truncated.
    const lineE = (r, m) => {
      const N = 200000;
      let tot = 0;
      for (let i = 0; i < N; i++) {
        const phi = -Math.PI / 2 + (i + 0.5) * (Math.PI / N);
        tot += Math.pow(Math.cos(phi), m + 1) * (Math.PI / N) / r;
      }
      return tot;
    };
    // A plane of the same elements, of half-width R, at distance r: the cone it subtends
    // has cos(theta_max) = r/sqrt(r^2+R^2), and E = 2 pi (1 - cos^(m+2)(theta_max))/(m+2),
    // which for R >> r stops depending on r at all.
    const planeE = (r, m, R = 1e7) => {
      const c = r / Math.sqrt(r * r + R * R);
      return 2 * Math.PI * (1 - Math.pow(c, m + 2)) / (m + 2);
    };
    let worstLine = 0, worstPlane = 0;
    const expo = (f, m) => -(Math.log(f(2 * DIST_MM[0], m)) - Math.log(f(DIST_MM[0], m))) / Math.log(2);
    for (const m of [0, 1, 2]) {
      worstLine = Math.max(worstLine, Math.abs(expo(lineE, m) - 1));
      worstPlane = Math.max(worstPlane, Math.abs(expo(planeE, m)));
    }
    ok('the line control really is exactly 1 whatever the emitter\'s angular law is, which is why it is a control',
      worstLine < 1e-6, `worst departure from 1 across cos^0, cos^1 and cos^2 emitters: ${worstLine.toExponential(2)}`);
    ok('and the plane control is exactly 0 for the same reason',
      worstPlane < 1e-6 && /for <em>any<\/em> angular law/.test(html),
      `worst departure from 0: ${worstPlane.toExponential(2)}`);
  }

  // (vii) the interreflected fraction the prose quotes
  near('the wall term at the far end of an ordinary room is the 3.5% the page prints',
    100 * wallRatio(DIST_MM[DIST_MM.length - 1], ROOMS[0].rho, ROOMS[0].area), 3.5, 0.05);
  ok('and the page says which way it pushes, which is the half that matters',
    /flattens the fall exactly where the page is trying to watch it steepen/.test(html.replace(/\s+/g, ' ')));

  // (viii) the one magnitude on the page that is not ours. Transcribed from the source on
  // the date the page names, and the RATIO the page prints is recomputed from it here, so
  // the page can carry the size of the effect without carrying a photometric unit.
  const TFT = { url: 'https://tftcentral.co.uk/articles/oled-dimming-confusion-apl-abl-asbl-tpc-and-gsr-explained',
    read: '17 August 2026', panel: 'LG 42C2', smallWindow: 717, fullScreen: 152 };
  near('the OLED droop ratio the page quotes is the one its cited source supports',
    TFT.smallWindow / TFT.fullScreen, 4.7, 0.05);
  ok('and the page carries the two figures and the date it read them, with no unit attached to either',
    html.includes(String(TFT.smallWindow)) && html.includes(String(TFT.fullScreen)) &&
    html.includes(TFT.read) && html.includes(TFT.url) && html.includes('about 4.7 times as bright'));

  // (ix) the reader's own instruction changed with the finding, which is the only part of
  // this that can save a reader's own sweep.
  ok('the reader is told to keep the measured patch small, in the step where they aim the camera',
    /covers only a <strong>small patch<\/strong>/.test(html) && /a few centimetres across/.test(html));
  ok('and the lamp page tells them not to set a radius too small to measure anything',
    /Do not set the radius small/.test(lampHtml) && /0\.048 of an exponent at a radius of 30 mm/.test(lampHtml.replace(/\s+/g, ' ')));
}

// ── 4d. the floating origin fits BETTER, which is the whole trap ──────────────
// The page prints two exponents for two choices of origin. The number that makes the
// second one a trap rather than an option is its residual: a free offset and the source's
// own near-field curvature are the same shape, so the offset both eats the result and
// leaves a tidier line. Recomputed here from the closed form, where there is no noise to
// hide in, as well as read off the estimator's own diagnostics.
{
  const fitAt = (r0) => {
    const xs = DIST_MM.map((r) => Math.log(r - r0));
    const ys = DIST_MM.map((r) => Math.log(A_MM * A_MM / (A_MM * A_MM + r * r)));
    const mx = xs.reduce((a, b) => a + b, 0) / xs.length, my = ys.reduce((a, b) => a + b, 0) / ys.length;
    let num = 0, den = 0;
    for (let i = 0; i < xs.length; i++) { num += (xs[i] - mx) * (ys[i] - my); den += (xs[i] - mx) ** 2; }
    const m = num / den, c = my - m * mx;
    let sse = 0;
    for (let i = 0; i < xs.length; i++) sse += (ys[i] - (c + m * xs[i])) ** 2;
    return { p: -m, rms: Math.sqrt(sse / xs.length), r0 };
  };
  let best = { rms: Infinity };
  for (let g = -100; g <= 100; g++) {
    const r0 = (g / 100) * 0.5 * DIST_MM[0];
    if (DIST_MM[0] - r0 <= 1) continue;
    const f = fitAt(r0);
    if (f.rms < best.rms) best = f;
  }
  ok('on the exact closed form, letting the origin float returns an exponent at or above 2',
    best.p >= 2, `p = ${best.p.toFixed(4)} at r0 = ${best.r0.toFixed(2)} mm, against ${fitAt(0).p.toFixed(6)} with the origin at the glass`);
  ok('and it fits better while doing it, which is the sentence the page prints',
    best.rms < fitAt(0).rms / 3,
    `rms ${best.rms.toExponential(3)} free against ${fitAt(0).rms.toExponential(3)} fixed, a factor of ${(fitAt(0).rms / best.rms).toFixed(1)}`);
  ok('the same thing is true of the estimator\'s own fit to the shipped pixels',
    nodeRuns.disc.diagnostics.r0RmsFree < nodeRuns.disc.diagnostics.r0RmsFixed &&
    nodeRuns.disc.diagnostics.pFreeOrigin > nodeRuns.disc.value,
    `rms ${nodeRuns.disc.diagnostics.r0RmsFree.toFixed(5)} free against ${nodeRuns.disc.diagnostics.r0RmsFixed.toFixed(5)} fixed`);
  ok('and the page names it as a trap rather than as a second opinion',
    /the floating origin fits better/i.test(html.replace(/<[^>]+>/g, '')) &&
    /have absorbed it/.test(html));
}

// ── 5. what the reader actually sees ──────────────────────────────────────────
async function withBrowserLock(fn) {
  const lock = join(ROOT, 'scratchpad', '.live-sensor.lock');
  mkdirSync(join(ROOT, 'scratchpad'), { recursive: true });
  const STALE_MS = 20 * 60 * 1000, started = Date.now();
  for (;;) {
    try { writeFileSync(lock, String(process.pid), { flag: 'wx' }); break; }
    catch (e) {
      if (existsSync(lock) && Date.now() - statSync(lock).mtimeMs > STALE_MS) { try { rmSync(lock); } catch (e2) {} continue; }
      if (Date.now() - started > 45 * 60 * 1000) throw new Error('waited 45 min for the browser lock');
      await new Promise((r) => setTimeout(r, 3000 + Math.floor(Math.random() * 4000)));
    }
  }
  const release = () => { try { rmSync(lock); } catch (e) {} };
  process.on('exit', release);
  try { return await fn(); } finally { release(); }
}

const MIME = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8',
  '.css': 'text/css; charset=utf-8', '.png': 'image/png', '.svg': 'image/svg+xml',
  '.woff2': 'font/woff2', '.woff': 'font/woff', '.json': 'application/json', '.ico': 'image/x-icon' };

async function domPass() {
  let playwright;
  try { playwright = await import('playwright'); }
  catch (e) { ok('playwright is available for the rendered-page pass', false, String(e && e.message || e)); return; }
  const PUBLIC = join(ROOT, 'public');
  const srv = createServer((req, out) => {
    let p = join(PUBLIC, decodeURIComponent((req.url || '/').split('?')[0]));
    if (existsSync(p) && statSync(p).isDirectory()) p = join(p, 'index.html');
    if (!existsSync(p)) { out.writeHead(404).end('not found'); return; }
    out.writeHead(200, { 'content-type': MIME[extname(p)] || 'application/octet-stream' });
    out.end(readFileSync(p));
  });
  await new Promise((r) => srv.listen(0, '127.0.0.1', r));
  const port = srv.address().port;
  const browser = await playwright.chromium.launch();
  try {
    const ctx = await browser.newContext({ permissions: [] });
    const page = await ctx.newPage();
    const errors = [];
    page.on('pageerror', (e) => errors.push('pageerror: ' + e.message));
    page.on('console', (m) => { if (m.type() === 'error') errors.push('console: ' + m.text()); });
    await page.goto(`http://127.0.0.1:${port}/strata/${SLUG}/`, { waitUntil: 'load' });
    await page.waitForFunction('window.__lampNumbers && window.__lampNumbers.disc', { timeout: 60000 });
    ok('the page renders with no console or page error, and with no camera granted', errors.length === 0, errors.join(' | '));

    const dom = await page.evaluate(() => {
      const out = {};
      document.querySelectorAll('[id]').forEach((el) => { out[el.id] = el.textContent.trim(); });
      return { text: out, shown: window.__lampNumbers, body: document.body.innerText };
    });
    const shown = dom.shown;

    // The page's own estimator against the independent Node one, on the same pixels.
    const pairs = [['disc', shown.disc.value, nodeRuns.disc.value],
      ['disc-exposure-drift', shown.drift.value, nodeRuns['disc-exposure-drift'].value],
      ['line', shown.line.value, nodeRuns.line.value],
      ['plane', shown.plane.value, nodeRuns.plane.value]];
    for (const [id, browserV, nodeV] of pairs) {
      near(`the page's estimator and the node re-implementation agree on ${id}`, browserV, nodeV, 1e-3);
    }
    near('and they agree on the assume-linear exponent too', shown.naiveExponent, nodeRuns.disc.diagnostics.naiveExponent, 1e-3);
    near('and on what the exposure drift would have cost if it were not divided out',
      shown.drift.uncorrected, nodeRuns['disc-exposure-drift'].diagnostics.uncorrectedExponent, 1e-3);
    ok('and that cost is a real one: undividing the exposure moves the drift anchor outside its own tolerance',
      Math.abs(nodeRuns['disc-exposure-drift'].diagnostics.uncorrectedExponent - discTruth) > 0.06 &&
      Math.abs(nodeRuns['disc-exposure-drift'].value - discTruth) <= 0.06,
      `${nodeRuns['disc-exposure-drift'].diagnostics.uncorrectedExponent.toFixed(4)} undivided against ` +
      `${nodeRuns['disc-exposure-drift'].value.toFixed(4)} divided, true ${discTruth.toFixed(6)}`);
    ok('and on the clean anchor, where the exposure never moved, undividing it changes almost nothing',
      Math.abs(nodeRuns.disc.diagnostics.uncorrectedExponent - nodeRuns.disc.value) < 0.01,
      `${nodeRuns.disc.diagnostics.uncorrectedExponent.toFixed(4)} against ${nodeRuns.disc.value.toFixed(4)}`);
    near('and on the residual the recovered curve leaves', shown.residualPct, nodeRuns.disc.diagnostics.residualPct, 1e-3);
    near('and on the fitted free origin', shown.r0Free, nodeRuns.disc.diagnostics.r0Free, 1e-3);
    near('and on the exponent that free origin buys', shown.pFreeOrigin, nodeRuns.disc.diagnostics.pFreeOrigin, 1e-3);
    near('and on the residual it leaves behind', shown.r0RmsFree, nodeRuns.disc.diagnostics.r0RmsFree, 1e-6);
    near('and on the residual the origin at the glass leaves', shown.r0RmsFixed, nodeRuns.disc.diagnostics.r0RmsFixed, 1e-6);
    near('and on the 8-bit floor with the rounding dithered', shown.quantFloor.dithered, nodeRuns.disc.diagnostics.quantFloor.dithered, 1e-6);
    near('and on the 8-bit floor with the rounding not dithered', shown.quantFloor.flat, nodeRuns.disc.diagnostics.quantFloor.flat, 1e-5);

    // Now the printed strings, which is the only thing that asserts about the reader.
    const printed = [
      ['n-recovered', shown.disc.value.toFixed(4)],
      ['n-recovered-u', shown.disc.uncertainty.toFixed(4)],
      ['n-true', (1.951698).toFixed(6)],
      ['n-naive', shown.naiveExponent.toFixed(4)],
      ['n-naive-err', (1.951698 - shown.naiveExponent).toFixed(4)],
      // the ERROR as a percentage of the true answer, which is what the sentence around it
      // says. 100*naive/true is the fraction RETAINED and would double the apparent defect.
      ['n-naive-pct', (100 * (1.951698 - shown.naiveExponent) / 1.951698).toFixed(1)],
      ['n-resid', shown.residualPct.toFixed(3)],
      ['n-r0', shown.r0Free.toFixed(1)],
      ['n-pfree', shown.pFreeOrigin.toFixed(4)],
      ['n-r0rms-fixed', shown.r0RmsFixed.toFixed(4)],
      ['n-r0rms-free', shown.r0RmsFree.toFixed(4)],
      ['n-r0rms-ratio', (shown.r0RmsFixed / shown.r0RmsFree).toFixed(1)],
      ['n-drift', shown.drift.value.toFixed(4)],
      ['n-line', shown.line.value.toFixed(4)],
      ['n-plane', shown.plane.value.toFixed(4)],
      ['n-line-naive', shown.line.naive.toFixed(4)],
      ['n-plane-naive', shown.plane.naive.toFixed(4)],
      ['n-ci-lo', shown.ci[0].toFixed(4)],
      ['n-ci-hi', shown.ci[1].toFixed(4)],
      ['n-qflat', shown.quantFloor.flat.toFixed(4)],
      ['n-qdither', shown.quantFloor.dithered.toFixed(5)],
      ['n-roi', String(shown.quantFloor.roiPixels)],
      ['n-frames', String(STEPS.length)],
      ['n-steps', String(STEPS.length)],
      ['n-positions', String(DIST_MM.length)],
      ['n-positions-2', String(DIST_MM.length)],
      ['n-drift-uncorr', nodeRuns['disc-exposure-drift'].diagnostics.uncorrectedExponent.toFixed(2)],
      ['n-drift-recovered', nodeRuns['disc-exposure-drift'].value.toFixed(2)],
      ['local-a', `${A_MM} mm`],
      ['local-five', `${10 * A_MM} mm`],
      ['local-fivep', localExponent(10 * A_MM).toFixed(6)],
    ];
    let mismatched = [];
    for (const [id, want] of printed) {
      if (dom.text[id] !== want) mismatched.push(`${id}: page shows "${dom.text[id]}", recomputed "${want}"`);
    }
    ok(`all ${printed.length} rendered figures equal the recomputed values`, mismatched.length === 0, mismatched.join(' | '));

    // The rest of the printed figures, in two passes that catch different lies. First: the
    // strings on the page are the numbers the page itself computed, so nothing was typed in
    // or left behind by an edit.
    const printedRest = [
      ['n-recovered-2', shown.disc.value.toFixed(4) + ' ± ' + shown.disc.uncertainty.toFixed(4)],
      ['n-naive-2', shown.naiveExponent.toFixed(4)],
      ['n-drift-u', shown.drift.uncertainty.toFixed(4)],
      ['n-drift-spread', shown.drift.spread.toFixed(0)],
      ['n-drift-naive', shown.drift.naive.toFixed(4)],
      ['n-line-u', shown.line.uncertainty.toFixed(4)],
      ['n-plane-u', shown.plane.uncertainty.toFixed(4)],
      ['n-coderange', shown.codeRange[0].toFixed(1) + ' to ' + shown.codeRange[1].toFixed(1)],
      ['n-curven', String(shown.curveSpread.n)],
      ['n-curvespread', (100 * shown.curveSpread.spread).toFixed(2)],
      ['n-curverange', shown.curveSpread.vA.toFixed(1) + ' to ' + shown.curveSpread.vB.toFixed(1)],
    ];
    const mism2 = printedRest.filter(([id, want]) => dom.text[id] !== want)
      .map(([id, want]) => `${id}: page shows "${dom.text[id]}", recomputed "${want}"`);
    ok(`the remaining ${printedRest.length} rendered figures equal the numbers the page computed`,
      mism2.length === 0, mism2.join(' | '));

    // Second: those numbers are the ones an independently written estimator gets from the same
    // pixels. Either pass alone would let something through, which is why both are here.
    const dd = nodeRuns['disc-exposure-drift'].diagnostics;
    const alsoAgree = [
      ['the exposure-drift interval', shown.drift.uncertainty, nodeRuns['disc-exposure-drift'].uncertainty, 1e-3],
      ['the exposure-drift assume-linear exponent', shown.drift.naive, dd.naiveExponent, 1e-3],
      ['how far the exposure hunts', shown.drift.spread, dd.gainSpreadPct, 0.5],
      ['the line control interval', shown.line.uncertainty, nodeRuns.line.uncertainty, 1e-3],
      ['the plane control interval', shown.plane.uncertainty, nodeRuns.plane.uncertainty, 1e-3],
      ['the lowest code value the anchor reached', shown.codeRange[0], nodeRuns.disc.diagnostics.codeRange[0], 0.5],
      ['the highest code value the anchor reached', shown.codeRange[1], nodeRuns.disc.diagnostics.codeRange[1], 0.5],
      ['the spread between the four recovered curves', shown.curveSpread.spread, nodeSpread.spread, 2e-3],
      ['how many curves were compared', shown.curveSpread.n, nodeSpread.n, 0],
      ['the code value the curves are pinned from', shown.curveSpread.vA, nodeSpread.vA, 0.5],
      ['the code value the curves are pinned to', shown.curveSpread.vB, nodeSpread.vB, 0.5],
    ];
    const bad2 = alsoAgree.filter(([, a, b, tol]) => !(Math.abs(a - b) <= tol))
      .map(([what, a, b]) => `${what}: page ${a}, node ${b}`);
    ok(`the page and the independent Node estimator agree on all ${alsoAgree.length} remaining printed diagnostics`,
      bad2.length === 0, bad2.join(' | '));

    // The sweep panel does arithmetic of its own on the way to the reader, and nothing above
    // touches it. Drive the slider to the far end and recompute every number in the sentence
    // it writes, from the page's own fitted points, exactly.
    const far = await page.evaluate(() => {
      const sl = document.getElementById('sweep');
      sl.value = sl.max;
      sl.dispatchEvent(new Event('input'));
      return { r: document.getElementById('sweep-r').textContent.trim(),
        note: document.getElementById('sweep-note').textContent.replace(/\s+/g, ' ').trim() };
    });
    {
      const P = shown.points, last = P[P.length - 1], first = P[0];
      const rel = last.S / first.S, ratio = last.r / first.r;
      const want = [`${last.r} mm`, (rel * 100).toFixed(2) + '%', 'a fall of ' + (1 / rel).toFixed(2) + ' times',
        'distance ratio of ' + ratio.toFixed(2), 'demanded ' + Math.pow(ratio, 2).toFixed(2) + ' times',
        'sit at ' + shown.exposure[P.length - 1].toFixed(3) + ' of their session average'];
      const missing = want.filter((w) => !far.note.includes(w) && far.r !== w);
      ok('the far end of the sweep panel says what the fitted points say, to the last digit',
        far.r === `${last.r} mm` && missing.length === 0 && rel < 0.2 && Math.pow(ratio, 2) > 1 / rel,
        missing.length ? `missing from the panel: ${missing.join(' | ')}` : far.note.slice(0, 120));
    }

    // The local exponent plot's residual against the closed form, recomputed here.
    const rms = Math.sqrt(nodeRuns.disc.diagnostics.local
      .reduce((a, l) => a + (l.p - localExponent(l.r)) ** 2, 0) / nodeRuns.disc.diagnostics.local.length);
    near('the printed root mean square gap to the closed form is the recomputed one',
      Number(dom.text['local-rms']), rms, 2e-3);
    // and the distance past which that scatter is larger than the effect. A plot that let a
    // reader read agreement out of its own noise floor would be the "true by construction"
    // failure arriving by the back door, so the floor is solved for and drawn.
    {
      const cross = A_MM / Math.sqrt(rms / (2 - rms));
      ok('the page marks the distance past which the prediction and a flat 2 differ by less than the dots scatter',
        Math.abs(Number(String(dom.text['local-cross']).replace(/[^0-9.]/g, '')) - cross) <= 6 &&
        cross > DIST_MM[0] && cross < DIST_MM[DIST_MM.length - 1],
        `page says ${dom.text['local-cross']}, recomputed ${cross.toFixed(1)} mm from an rms of ${rms.toFixed(4)}`);
      ok('and that distance really does sit inside the sweep, so the plot is honest about its own far half',
        2 * (A_MM / cross) ** 2 / (1 + (A_MM / cross) ** 2) - rms < 1e-9,
        `departure at ${cross.toFixed(0)} mm is ${(2 * (A_MM / cross) ** 2 / (1 + (A_MM / cross) ** 2)).toFixed(4)}, scatter ${rms.toFixed(4)}`);
    }
    ok('and the measured local exponents really do climb toward 2',
      nodeRuns.disc.diagnostics.local[0].p < nodeRuns.disc.diagnostics.local[nodeRuns.disc.diagnostics.local.length - 1].p &&
      nodeRuns.disc.diagnostics.local.every((l) => l.p < 2.1),
      `${nodeRuns.disc.diagnostics.local[0].p.toFixed(3)} at ${nodeRuns.disc.diagnostics.local[0].r} mm ` +
      `to ${nodeRuns.disc.diagnostics.local[nodeRuns.disc.diagnostics.local.length - 1].p.toFixed(3)} at ` +
      `${nodeRuns.disc.diagnostics.local[nodeRuns.disc.diagnostics.local.length - 1].r} mm`);

    // The audit-of-the-guards panel, as the reader sees it, against the run made here from
    // the description. Both the verdict and the number have to match on every row, and the
    // rendered words have to agree with the verdict: a row that says "caught" while its
    // estimator returned a number is the failure this compares for.
    {
      const pageFaults = shown.faults || [];
      const bad = [];
      for (const row of pageFaults) {
        const mine = faultRuns[row.id];
        if (!mine) { bad.push(`${row.id}: no such fault here`); continue; }
        if (row.refused !== mine.refused) bad.push(`${row.id}: page refused "${row.refused}", node "${mine.refused}"`);
        if (row.value !== null && mine.value !== null && Math.abs(row.value - mine.value) > 5e-3) {
          bad.push(`${row.id}: page ${row.value.toFixed(4)}, node ${mine.value.toFixed(4)}`);
        }
      }
      ok(`all ${pageFaults.length} rows of the guard panel match an independent run of the same faults`,
        pageFaults.length === Object.keys(FAULTS_NODE).length && bad.length === 0, bad.join(' | '));
      const rendered = dom.text.faultrows.replace(/\s+/g, ' ');
      const caught = pageFaults.filter((r) => r.refused !== null).length;
      const past = pageFaults.filter((r) => r.refused === null && Math.abs(r.value - 1.951698) > 0.06).length;
      ok('the panel says out loud how many faults were caught and how many walked past, and both counts are the run',
        dom.text['n-faultcaught'] === String(caught) && dom.text['n-faultpast'] === String(past) &&
        caught === 1 && past === 2, `${dom.text['n-faultcaught']} caught, ${dom.text['n-faultpast']} past`);
      ok('the panel marks the walked-past rows wrong rather than quietly printing a number',
        (rendered.match(/no refusal, and wrong/g) || []).length === past, rendered.slice(0, 200));
      ok('and the worst residual it prints is the worst residual across the faults',
        Math.abs(Number(dom.text['n-faultresid']) -
          Math.max(...pageFaults.filter((r) => r.residualPct !== null).map((r) => r.residualPct))) < 5e-3,
        dom.text['n-faultresid']);
      ok('the strength printed beside the panel is the one the faults were run at',
        dom.text['n-faultstrength'] === FAULT_STRENGTH.toFixed(1));
    }

    // "Every free choice this estimator makes" is a claim of completeness, so it is checked
    // as one: the table's rows are tagged with the setting each states, and the set of tags
    // has to be the set of settings the estimator actually has.
    {
      const tagged = [...html.matchAll(/<tr data-choice="([^"]+)"/g)].map((m) => m[1]);
      const inCode = (instrumentJs.match(/var CHOICES = \{([\s\S]*?)\n\};/) || [])[1] || '';
      const keys = [...inCode.matchAll(/^\s{2}([A-Za-z0-9]+):/gm)].map((m) => m[1]);
      const missing = keys.filter((k) => !tagged.includes(k));
      const extra = tagged.filter((k) => !keys.includes(k));
      ok(`the choices table lists every one of the estimator's ${keys.length} settings and invents none`,
        keys.length >= 18 && missing.length === 0 && extra.length === 0 && new Set(tagged).size === tagged.length,
        missing.length ? 'missing: ' + missing.join(', ') : extra.length ? 'invented: ' + extra.join(', ') : `${tagged.length} rows`);
    }

    // The slate, the stub probe and the refusal path, as the reader sees them.
    ok('the slate panel shows every specimen passing', !/FAIL/.test(dom.text.slate) && /armed/.test(dom.text.slate));
    ok('the attestation panel names all four specimens',
      ['disc', 'disc-exposure-drift', 'line', 'plane'].every((id) => dom.text.attest.includes(id)));
    ok('the stub probe panel shows the hard-coded estimator failing', /the fake never arms/.test(dom.text.stub));
    ok('and it shows it failing specifically on a control',
      /failed\s+control/.test(dom.text.stub.replace(/\s+/g, ' ')));
    ok('with no camera granted, the page still delivers the anchor', /1\.951698/.test(dom.body));
    ok('and does not print a live exponent', dom.text.live === '\u2014' || dom.text.live === '-');
    ok('the reader-facing text never attaches a number to a photometric unit',
      !UNIT_NEXT_TO_A_NUMBER.test(dom.body), (dom.body.match(UNIT_NEXT_TO_A_NUMBER) || [''])[0]);

    // The refusal paths through the page's OWN estimator, not a copy of it.
    for (const t of REFUSALS) {
      // base64 rather than a plain array: seven full sprite payloads as JSON numbers is
      // tens of megabytes across the wire and this box is shared.
      const reason = await page.evaluate((frames) => {
        const payload = { frames: frames.map((f) => {
          const bin = atob(f.b64), green = new Uint8Array(bin.length);
          for (let i = 0; i < bin.length; i++) green[i] = bin.charCodeAt(i);
          return { width: f.width, height: f.height, green };
        }) };
        const out = window.__lampEstimate(payload);
        return out.refused ? out.refused.reason : null;
      }, t.payload.frames.map((f) => ({ width: f.width, height: f.height, b64: Buffer.from(f.green).toString('base64') })));
      const good = reason !== null && (t.expect instanceof RegExp ? t.expect.test(reason) : reason === t.expect);
      ok(`the page's own estimator refuses ${t.id}`, good, reason === null ? 'it returned a number' : `reason "${reason}"`);
    }

    // ...and the one thing it must NOT refuse, because refusing would be a claim it cannot
    // support. A reader who walks the sequence without moving the lamp hands the page a
    // perfectly well formed sweep whose light never changed. The page has no second
    // instrument to catch that with, so it returns the slope it actually saw, which is zero,
    // and says on its face that the tape measure is the reader's part of the job.
    {
      const stillP = await page.evaluate((frames) => {
        const payload = { frames: frames.map((f) => {
          const bin = atob(f.b64), green = new Uint8Array(bin.length);
          for (let i = 0; i < bin.length; i++) green[i] = bin.charCodeAt(i);
          return { width: f.width, height: f.height, green };
        }) };
        const out = window.__lampEstimate(payload);
        return out.refused ? null : out.value;
      }, lampNeverMoved().map((f) => ({ width: f.width, height: f.height, b64: Buffer.from(f.green).toString('base64') })));
      ok('a lamp that never moved gives the page a number near zero rather than a refusal, which is the sentence the page prints about its own blind spot',
        stillP !== null && Math.abs(stillP) < 0.01,
        stillP === null ? 'it refused instead' : `p = ${stillP.toFixed(6)}`);
    }

    // No horizontal overflow at the three widths the house checks.
    for (const w of [390, 768, 1440]) {
      await page.setViewportSize({ width: w, height: 900 });
      await page.waitForTimeout(120);
      const over = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
      ok(`no horizontal overflow at ${w} CSS pixels`, over <= 1, `${over} px of overflow`);
    }

    // The lamp page renders and its coverage really is exact.
    const lamp = await ctx.newPage();
    const lampErrors = [];
    lamp.on('pageerror', (e) => lampErrors.push(e.message));
    lamp.on('console', (m) => { if (m.type() === 'error') lampErrors.push(m.text()); });
    await lamp.goto(`http://127.0.0.1:${port}/strata/${SLUG}/lamp/`, { waitUntil: 'load' });
    await lamp.waitForTimeout(250);
    ok('the lamp page renders with no error', lampErrors.length === 0, lampErrors.join(' | '));

    // ── the ruler the reader calibrates against ──────────────────────────────
    // The radius typed on this page is the one number the estimator is never told, and it is
    // only as good as the ruler beside it. So the ruler's own millimetre is MEASURED off the
    // canvas, at the widths a phone actually has, and compared with the pixels-per-mm setting
    // it claims to display. It used to be drawn into a fixed 600 px buffer stretched to fit,
    // so on any narrower viewport every drawn millimetre was short and the reader calibrated
    // the emitter too large without any sign of it.
    for (const vw of [390, 768, 1440]) {
      await lamp.setViewportSize({ width: vw, height: 900 });
      await lamp.evaluate(() => { window.dispatchEvent(new Event('resize')); });
      await lamp.waitForTimeout(120);
      const m = await lamp.evaluate(() => {
        const r = document.getElementById('ruler');
        const g = r.getContext('2d');
        const img = g.getImageData(0, 0, r.width, r.height);
        // the tick columns, found in the canvas itself: a column with any lit pixel in the
        // bottom third, measured in the canvas buffer and converted back to CSS pixels
        const cols = [];
        for (let x = 0; x < r.width; x++) {
          let lit = false;
          for (let y = Math.floor(r.height * 0.66); y < r.height; y++) {
            if (img.data[(y * r.width + x) * 4 + 3] > 40 && img.data[(y * r.width + x) * 4] > 60) { lit = true; break; }
          }
          if (lit) cols.push(x);
        }
        const info = window.__lamp.rulerMm();
        // group adjacent lit columns into ticks and take the first and last tick centre
        const ticks = [];
        for (const c of cols) {
          if (ticks.length && c - ticks[ticks.length - 1].last <= 1) { ticks[ticks.length - 1].last = c; continue; }
          ticks.push({ first: c, last: c });
        }
        const centres = ticks.map((t) => (t.first + t.last) / 2);
        return { centres, n: ticks.length, ...info };
      });
      const scale = m.bufferWidth / m.cssWidth;            // buffer px per CSS px
      const spanCss = m.n > 1 ? (m.centres[m.n - 1] - m.centres[0]) / scale : 0;
      const perMm = m.n > 1 ? spanCss / (m.n - 1) : 0;
      near(`one millimetre of the lamp page's ruler is ${m.ppmm} CSS px at ${vw} CSS px wide`,
        perMm, m.ppmm, 0.06, `${m.n} ticks over ${spanCss.toFixed(1)} CSS px, buffer ${m.bufferWidth} for ${m.cssWidth} CSS px`);
    }
    await lamp.setViewportSize({ width: 1440, height: 900 });
    await lamp.waitForTimeout(120);
    // ── the one photometric claim the whole page rests on ────────────────────
    // k of 16 sub-areas white is k/16 of the flux, whatever the panel does with a code
    // value. Everything else on this page is downstream of that, so it is counted off the
    // lamp's own canvas at every rung of its own ladder rather than argued.
    //
    // ⚠ HISTORY, so this is not quietly loosened again. An earlier run of this file
    // measured 2/16 as 2.018215/16 and 12/16 as 12.036430/16, and the fault was in THIS
    // file, not in the lamp: it sampled a horizontal strip of the canvas, which cuts the
    // 4 by 4 dither blocks at the strip's edge, and a cut block is not k/16 of anything.
    // (Row 0 of the Bayer matrix holds 1 of its 4 cells below k = 2, row 1 holds none, and
    // every row holds exactly 2 below k = 8 — which is why 8/16 came out exact and 2/16
    // did not.) The emitter's drawing code was never changed. So the check below counts
    // whole blocks only, and it does it three ways, each stricter than the strip ever was:
    // the band's own lit area must not move at all between rungs, the emitter's lit area
    // must equal a closed-form integer with no normalisation and no subtraction, and the
    // whole canvas must still be linear in k through the origin.
    const cov = await lamp.evaluate((rNearMm) => {
      const cv = document.getElementById('stage');
      const g = cv.getContext('2d');
      const res = [];
      const seen = new Set();
      for (let i = 0; i < window.__lamp.STEPS.length; i++) {
        const k = window.__lamp.STEPS[i].k;
        if (seen.has(k)) continue;
        seen.add(k);
        window.__lamp.show(i);
        const geom = window.__lamp.geom();
        // The WHOLE canvas, so that no dither block is ever cut by the edge of the sample,
        // and then the band and the emitter field counted apart from each other.
        const img = g.getImageData(0, 0, cv.width, cv.height);
        // ...and, in the same pass, the light the CARD would receive from those same lit
        // pixels at the nearest distance in the protocol, where the emitter subtends its
        // largest angle and any inequality between the 16 sub-areas is at its worst. The
        // weight of a patch at lateral offset rho is r^2/(rho^2 + r^2)^2, which is the
        // cos(th_s)cos(th_r)/d^2 of two parallel planes.
        const scale = geom.aPx > 0 ? 30 / geom.aPx : 0;      // mm per device pixel
        let lit = 0, litBand = 0, litField = 0, weight = 0, weightAll = 0;
        for (let y = 0; y < cv.height; y++) {
          for (let x = 0; x < cv.width; x++) {
            const inField = y >= geom.top;
            let w = 0;
            if (inField) {
              const dx = (x - geom.cx) * scale, dy = (y - geom.cy) * scale;
              const d2 = rNearMm * rNearMm + dx * dx + dy * dy;
              w = rNearMm * rNearMm / (d2 * d2);
              if (dx * dx + dy * dy <= (geom.aPx * scale) ** 2) weightAll += w;
            }
            if (img.data[(y * cv.width + x) * 4] > 128) {
              lit++;
              if (inField) { litField++; weight += w; } else litBand++;
            }
          }
        }
        res.push({ k, lit, litBand, litField, weight, weightAll,
          predicted: geom.litPredicted, blocks: geom.blocks, cell: geom.cell });
      }
      return res.sort((a, b) => a.k - b.k);
    }, DIST_MM[0]);
    const at = (k) => cov.find((c) => c.k === k);
    const base = at(0), top16 = at(16);

    // (i) the pedestal. The code band lights exactly eight cells at every step, so its own
    // light on the card is the same at every rung and cannot leak into the ladder. If that
    // were false, subtracting the k = 0 frame would be subtracting the wrong thing, both
    // here and in the estimator, so it is measured rather than asserted.
    {
      const bands = cov.map((c) => c.litBand);
      const spread = Math.max(...bands) - Math.min(...bands);
      ok('the code band lights the same area at every rung, so the unlit frame is a true pedestal',
        cov.length >= 9 && spread === 0, `${bands[0]} lit pixels at every one of ${bands.length} rungs, spread ${spread}`);
    }

    // (ii) the emitter itself, against a closed form. cell*cell*k*blocks is an integer
    // predicted from the geometry alone; nothing is normalised, nothing is subtracted, and
    // a single wrongly lit pixel anywhere fails it.
    {
      let worst = 0, sample = '';
      for (const c of cov) worst = Math.max(worst, Math.abs(c.litField - c.predicted));
      sample = cov.map((c) => `${c.k}:${c.litField}`).join(' ');
      ok('the emitter\'s lit area is exactly cell squared times k times blocks, to the pixel',
        cov.length >= 9 && worst === 0 && top16.litField > 0,
        `${cov[0].blocks} whole blocks of ${cov[0].cell}x${cov[0].cell} px cells; counted ${sample}; worst miss ${worst} px`);
    }

    // (iii) and the whole canvas, band included, is still linear in k through the origin.
    {
      let worstCov = Infinity, detail = 'ladder rungs missing';
      if (base && top16 && top16.lit > base.lit) {
        worstCov = 0;
        for (const c of cov) worstCov = Math.max(worstCov, Math.abs((c.lit - base.lit) - (c.k / 16) * (top16.lit - base.lit)));
        detail = cov.map((c) => `${c.k}/16 gives ${(16 * (c.lit - base.lit) / (top16.lit - base.lit)).toFixed(6)}/16`).join(', ');
      }
      ok('the lamp\'s emitted area is exactly k/16 of full at every rung of its ladder, to the pixel',
        cov.length >= 9 && worstCov === 0, detail);
    }

    // (iv) and the claim the page actually needs, which is one step past area. The card
    // measures IRRADIANCE, and irradiance weights each patch of the emitter by
    // cos(th_s)cos(th_r)/d^2, so a rim patch counts for (1+(a/r)^2)^-2 of a centre one:
    // about 2% less at a/r = 0.1, about 20% less at the nearest position here. "k of 16
    // sub-areas lit is k/16 of the received light" is therefore true only if all sixteen
    // sub-areas carry the same integrated weight. An interleaved dither makes each sub-area
    // a uniform sample of the whole disc, which is why it is the construction used; sixteen
    // contiguous blocks would not be. That is a receiver-geometry fact and no argument on
    // the page can reach it, so it is measured off the same pixels as the area count, at the
    // nearest distance in the protocol, where it is worst.
    {
      let worstW = 0, detail = 'ladder rungs missing';
      if (base && top16 && top16.weight > 0) {
        worstW = 0;
        for (const c of cov) worstW = Math.max(worstW, Math.abs(16 * (c.weight / top16.weight) - c.k));
        detail = cov.map((c) => `${c.k}/16 receives ${(16 * c.weight / top16.weight).toFixed(4)}/16`).join(', ');
      }
      ok('and the LIGHT the card receives from it is k/16 too, at the nearest distance in the protocol, to under a thousandth of a rung',
        cov.length >= 9 && worstW < 1e-3, `worst miss ${worstW.toExponential(2)} of a rung; ${detail}`);
      ok('which is not free: the emitter\'s rim really does count for less than its centre at that distance',
        top16 && top16.weightAll > 0 &&
        Math.abs(1 - 1 / Math.pow(1 + (30 / DIST_MM[0]) ** 2, 2)) > 0.15,
        `a rim patch counts for ${(100 / Math.pow(1 + (30 / DIST_MM[0]) ** 2, 2)).toFixed(1)}% of a centre one at ${DIST_MM[0]} mm`);
    }
    await browser.close();
  } finally {
    try { await browser.close(); } catch (e) {}
    srv.close();
  }
}

if (!NO_DOM) await withBrowserLock(domPass);
else ok('the rendered-page pass was skipped by --no-dom', true, 'run without --no-dom before landing');

// The page states this verifier's score, so that sentence is itself a claim, and this is
// where it is checked: the count is read back out of the page and compared with the number
// of checks this run actually made. The + 1 is this check, which has not been pushed yet at
// the moment it is evaluated.
//
// What does NOT happen, and what the page must not say happens: the site build does not run
// this file. `npm run prebuild` runs research/self-check/score-audit.mjs --check, which joins
// score claims against research/self-check/verifier-runs.json, a snapshot written separately
// by `npm run scores`. A verifier absent from that snapshot lands in the audit's `unrun`
// bucket and --check still exits 0, so the build cannot back this sentence and the page says
// so in the words below rather than borrowing an authority it does not have.
{
  const stated = Number((html.match(/runs (\d+) checks and prints/) || [])[1]);
  ok('the check count the page states for this verifier is the count this verifier runs',
    stated === checks.length + 1, `the page says ${stated}, this run has ${checks.length + 1}`);
  ok('and the page describes that as its own last check rather than as something the build does',
    /the last thing\s+the verifier does is read this number back out of this page/.test(html.replace(/\s+/g, ' ')) &&
    !/build\s+re-runs the verifier/.test(html.replace(/\s+/g, ' ')));
}

// ── report ────────────────────────────────────────────────────────────────────
let failed = 0;
for (const c of checks) {
  if (!c.pass) failed++;
  console.log(`  ${c.pass ? '✓' : '✗ FAIL'}  ${c.name}${c.detail ? '  : ' + c.detail : ''}`);
}
console.log(`\n${checks.length - failed}/${checks.length} checks green`);
if (failed) console.log(`${failed} check(s) failed`);
process.exit(failed ? 1 : 0);
