#!/usr/bin/env node
/*
 * verify.mjs: the offline mirror behind /strata/the-exponent-between-number-and-light/.
 *
 * It imports the SHIPPED module, public/strata/<slug>/gamma.mjs, and re-derives
 * everything the page prints from the committed evidence. Two things are true
 * of every window below and they matter more than the code:
 *
 *   1. Every expected value is a LITERAL, written out here by hand. None of
 *      them is computed by the thing being tested. A file that asks the code
 *      under test what the answer should be and then agrees with it is not a
 *      check.
 *   2. The negative controls are load-bearing. A match-set built from a
 *      different exponent must fail the first exponent's window; a match-set of
 *      noise must be refused; and the three captured traces that were zoomed
 *      without a repaint must be refused despite being perfectly crisp. If any
 *      of those quietly passed, the instrument would be decorative.
 *
 *   node research/the-exponent-between-number-and-light/verify.mjs
 *
 * Offline. No network. A couple of seconds from a clean checkout.
 */
import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import { fileURLToPath } from 'node:url';
import * as G from '../../public/strata/the-exponent-between-number-and-light/gamma.mjs';
import { deriveSystematic } from './systematic.mjs';

const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.join(HERE, '..', '..');
const SLUG = 'the-exponent-between-number-and-light';
const R = (p) => path.join(ROOT, p);
const D = (f) => JSON.parse(fs.readFileSync(path.join(HERE, 'data', f), 'utf8'));
const html0 = () => fs.readFileSync(R(`public/strata/${SLUG}/index.html`), 'utf8');

let pass = 0, fail = 0;
const ok = (cond, label, detail) => {
  if (cond) { pass++; console.log(`  ok    ${label}`); }
  else { fail++; console.log(`  FAIL  ${label}${detail ? '   ' + detail : ''}`); }
};
const near = (got, want, tol, label) =>
  ok(Number.isFinite(got) && Math.abs(got - want) <= tol, label, `got ${got}, want ${want} +/- ${tol}`);
const eq = (got, want, label) =>
  ok(got === want, label, `got ${JSON.stringify(got)}, want ${JSON.stringify(want)}`);
const section = (s) => console.log(`\n-- ${s} ${'-'.repeat(Math.max(0, 62 - s.length))}`);

console.log('THE EXPONENT BETWEEN THE NUMBER AND THE LIGHT / offline verification\n');

/* ═══ 1. the standard, as transcribed ═══════════════════════════════════════ */
section('1. IEC 61966-2-1:1999, as published by the ICC registry');
eq(G.SRGB.linearThreshold, 0.0031308, 'the forward threshold is 0.0031308');
eq(G.SRGB.codeThreshold, 0.04045, 'the inverse threshold is 0.04045');
eq(G.SRGB.slope, 12.92, 'the linear segment slope is 12.92');
eq(G.SRGB.a, 0.055, 'the offset is 0.055');
eq(G.SRGB.exponent, 2.4, 'the exponent inside the formula is 2.4');
near(G.SRGB.slope * G.SRGB.linearThreshold, 0.04045, 2e-6, 'the two segments meet at the threshold');
{
  // The standard's two thresholds are not exactly each other's image. 12.92 x
  // 0.0031308 is 0.040449936, and the inverse threshold is written 0.04045, so
  // there is a window 6.4e-8 wide in which the two branches disagree about
  // which one applies. Outside it the round trip is exact to double precision.
  const lo = 12.92 * 0.0031308, hi = 0.04045;
  near(hi - lo, 6.4e-8, 1e-11, 'the two published thresholds differ by 6.4e-8');
  let inside = 0, outside = 0;
  for (let i = 0; i <= 1000000; i++) {
    const v = i / 1000000;
    const d = Math.abs(G.linearToSrgb(G.srgbToLinear(v)) - v);
    if (v >= lo && v <= hi) inside = Math.max(inside, d); else outside = Math.max(outside, d);
  }
  ok(outside < 1e-15, 'outside that window the transfer function inverts itself exactly',
    `worst ${outside.toExponential(2)}`);
  let worst = 0;
  for (let i = 0; i <= 4000000; i++) {
    const v = (i / 4000000) * 0.1;
    worst = Math.max(worst, Math.abs(G.linearToSrgb(G.srgbToLinear(v)) - v));
  }
  near(worst, 2.917e-8, 1e-10, 'and inside it the standard misses itself by 2.92e-8');
}
near(255 * G.linearToSrgb(0.5), 187.516, 0.001, 'half the light on an exact sRGB display is code 187.516');
near(255 * Math.pow(0.5, 1 / 2.2), 186.084, 0.001, 'and code 186.084 on a pure 2.2 display');

section('1b. the provenance of those five constants, which the page got wrong once');
/*
 * The page used to cite w3.org/Graphics/Color/sRGB.html for these numbers. That
 * document is the 1996 proposal, not the 1999 standard, its equations are
 * one-bit PNGs so it carries no readable constant at all, and the breakpoints
 * its images DO show are a different pair. This block pins the difference so
 * the wrong citation cannot come back quietly.
 */
{
  const W3C_1996 = { linear: 0.00304, code: 0.03928 };   // read off srgb10/srgb12/srgb18/srgb20
  ok(G.SRGB.linearThreshold !== W3C_1996.linear && G.SRGB.codeThreshold !== W3C_1996.code,
    'the shipped constants are NOT the 1996 proposal\'s 0.00304 / 0.03928',
    `${G.SRGB.linearThreshold} / ${G.SRGB.codeThreshold}`);
  // 1996 sat at the tangency of the two branches; 1999 moved to their crossing.
  const lin = (b) => 12.92 * b;
  const pow = (b) => 1.055 * Math.pow(b, 1 / 2.4) - 0.055;
  const tangency = Math.pow((12.92 * 2.4) / 1.055, 1 / (1 / 2.4 - 1));
  near(tangency, 0.00304123, 1e-8, 'the exact tangency of the two branches is 0.00304123');
  near(pow(W3C_1996.linear) - lin(W3C_1996.linear), 9.76e-6, 1e-8,
    '  so at the 1996 breakpoint the branches still differ by 9.76 parts per million');
  let cLo = 0.003, cHi = 0.0032;
  for (let i = 0; i < 200; i++) {
    const m = (cLo + cHi) / 2;
    if ((pow(cLo) - lin(cLo)) * (pow(m) - lin(m)) <= 0) cHi = m; else cLo = m;
  }
  near((cLo + cHi) / 2, 0.00313067, 1e-8, 'the two branches cross at 0.00313067');
  near(Math.abs(pow(G.SRGB.linearThreshold) - lin(G.SRGB.linearThreshold)), 2.85e-8, 1e-10,
    '  and the 1999 breakpoint sits there, closing the step to 2.85e-8');
  ok(pow(W3C_1996.linear) - lin(W3C_1996.linear)
     > 300 * Math.abs(pow(G.SRGB.linearThreshold) - lin(G.SRGB.linearThreshold)),
  '  which is the "small numerical error caused by rounding" the 1996 banner admits to');
}

/* ═══ 2. the match-sets, replayed ═══════════════════════════════════════════ */
section('2. the committed match-sets, replayed through the shipped fit');
const MS = D('matchsets.json');
eq(MS.fractions.length, 8, 'eight fractions are committed');
ok(MS.fractions.every((f, i) => Math.abs(f - (i + 1) / 9) < 1e-11), 'and they are 1/9 through 8/9');
const setById = new Map(MS.sets.map((s) => [s.id, s]));
const fitOf = (id) => {
  const s = setById.get(id);
  if (!s) throw new Error(`no match-set ${id}`);
  return G.fitGamma(s.matches.map(([f, code]) => ({ f, code })));
};

/*
 * The windows. Hand-written literals, one per case. Each was read once off a
 * run and then frozen; nothing here recomputes them.
 */
const RECOVERY = [
  ['pure-1.80', 1.8022, 0.0005],
  ['pure-2.00', 1.9979, 0.0005],
  ['pure-2.20', 2.2019, 0.0005],
  ['pure-2.40', 2.3967, 0.0005],
  ['pure-2.50', 2.5023, 0.0005],
  ['srgb-piecewise', 2.2206, 0.0005],
  ['leak-2.20-b0.02', 2.2019, 0.0005],
  ['leak-2.20-b0.05', 2.2019, 0.0005],
  ['leak-2.20-b0.2', 2.2019, 0.0005],
  ['offset-2.50-eps0.02', 2.4304, 0.0005],
  ['offset-2.50-eps0.05', 2.3360, 0.0005],
  ['offset-2.50-eps0.1', 2.1887, 0.0005],
];
for (const [id, want, tol] of RECOVERY) near(fitOf(id).gamma, want, tol, `${id} recovers ${want}`);

section('2b. the negative controls on the fit');
const W22 = [2.2019, 0.02]; // the window a 2.20 display lands in
ok(Math.abs(fitOf('pure-2.20').gamma - W22[0]) <= W22[1], 'the 2.20 set passes the 2.20 window');
for (const id of ['pure-1.80', 'pure-2.00', 'pure-2.40', 'pure-2.50']) {
  const g = fitOf(id).gamma;
  ok(Math.abs(g - W22[0]) > W22[1],
    `NEGATIVE CONTROL: ${id} does NOT pass the 2.20 window`, `got ${g.toFixed(4)}`);
}
for (const id of ['noise-1', 'noise-7', 'noise-20260807']) {
  const r = fitOf(id);
  ok(r.refused, `NEGATIVE CONTROL: ${id} is refused, not fitted`, r.refused ? '' : `returned ${r.gamma}`);
}
for (const id of ['sigmoid-8', 'sigmoid-12']) {
  const r = fitOf(id);
  ok(r.refused && r.reason === 'residual',
    `NEGATIVE CONTROL: ${id}, a bare liquid-crystal response, is refused`, r.reason || `returned ${r.gamma}`);
}
{
  // 200 fresh noise sets, generated here, all of which must be refused.
  let refused = 0;
  for (let s = 1; s <= 200; s++) if (G.fitGamma(G.noiseMatches(s)).refused) refused++;
  eq(refused, 200, 'NEGATIVE CONTROL: 200 further noise match-sets are all refused');
}

section('2c. what cancels, and what does not');
for (const [id, b] of [['leak-2.20-b0.02', 0.02], ['leak-2.20-b0.05', 0.05], ['leak-2.20-b0.2', 0.20]]) {
  const g = fitOf(id).gamma, base = fitOf('pure-2.20').gamma;
  ok(Math.abs(g - base) < 1e-9, `${b * 100}% flare or black leak shifts the exponent by nothing`,
    `difference ${Math.abs(g - base).toExponential(2)}`);
}
ok(G.cancellationProof(2.2, 0.20) < 1e-9, 'and no single match moves either',
  `largest ${G.cancellationProof(2.2, 0.20).toExponential(2)} code values`);
ok(Math.abs(fitOf('offset-2.50-eps0.05').gamma - 2.5) > 0.1,
  'an offset INSIDE the power does bias it, and by a lot',
  `2.500 reads back as ${fitOf('offset-2.50-eps0.05').gamma.toFixed(4)}`);

section('2d. the simulated observers');
{
  const rows = MS.sets.filter((s) => s.role === 'observer');
  eq(rows.length, 12, 'twelve simulated observer runs are committed');
  const bySd = {};
  for (const s of rows) {
    const sd = Number(/sd(\d+)/.exec(s.id)[1]);
    const r = G.fitGamma(s.matches.map(([f, code]) => ({ f, code })));
    (bySd[sd] ||= []).push(r);
  }
  ok(bySd[2].every((r) => !r.refused && Math.abs(r.gamma - 2.2) < 0.05),
    'a scatter of 2 code values recovers 2.2 to within 0.05 every time',
    bySd[2].map((r) => r.gamma.toFixed(3)).join(' '));
  ok(bySd[4].every((r) => !r.refused && Math.abs(r.gamma - 2.2) < 0.10),
    'a scatter of 4 code values recovers it to within 0.10 every time',
    bySd[4].map((r) => r.gamma.toFixed(3)).join(' '));
  ok(bySd[16].some((r) => r.refused || Math.abs(r.gamma - 2.2) > 0.10),
    'and a scatter of 16 does not, which is the honest limit of the method',
    bySd[16].map((r) => (r.refused ? 'refused' : r.gamma.toFixed(3))).join(' '));
}

section('2e. the refusals reachable from the page');
eq(G.fitGamma(G.quantise(G.idealMatches(G.purePower(2.2))).slice(0, 4)).reason, 'few-points',
  'four matches is too few');
eq(G.fitGamma(G.FRACTIONS.map((f) => ({ f, code: 254 }))).reason, 'railed',
  'eight matches jammed at the rail are refused');
{
  const m = G.quantise(G.idealMatches(G.purePower(2.2)));
  eq(G.fitGamma(m.map((x, i) => ({ f: x.f, code: m[7 - i].code }))).reason, 'non-monotone',
    'a reversed match-set is not a transfer function');
}
ok(G.repeatScatter(120, 145).refused && G.repeatScatter(120, 145).reason === 'drift',
  'a repeat 25 code values apart is drift');
near(G.repeatScatter(120, 126).sigmaCode, 4.2426, 0.0001, 'a repeat 6 apart is a scatter of 4.2426');

section('2f. VACUOUS SETTING: a repeat that lands twice on the same code');
/*
 * Reachable in nine clicks without moving the slider. The scatter estimator
 * returned exactly zero, resolvingPower divided by it, and section 4 told the
 * reader their eye could separate two curves the whole section exists to say no
 * eye can separate. The floor is 1/sqrt(12), the sd of a one-code rounding
 * error, and `atFloor` is what the page prints the caveat off.
 */
{
  const z = G.repeatScatter(140, 140);
  eq(z.drift, 0, 'a reader who matches 4/9 twice on the same code has a drift of 0');
  eq(z.sigmaCodeRaw, 0, '  and the raw estimator does return exactly zero');
  ok(z.atFloor, '  which is flagged as being at the floor, not measured');
  near(z.sigmaCode, 0.288675, 1e-6, '  so the reported scatter is the quantisation floor, 0.2887');
  ok(z.sigmaCode > 0, '  and is strictly positive, so nothing downstream divides by zero');
  const m = G.quantise(G.idealMatches(G.purePower(2.2)));
  const gap = G.separation(G.srgbDisplay(), G.purePower(2.2)).gammaGap;
  const rp = G.resolvingPower(z.sigmaCode, gap, m);
  ok(Number.isFinite(rp.sigmaGamma) && Number.isFinite(rp.factor) && Number.isFinite(rp.repeatsNeeded),
    '  and the resolving power is finite rather than n/a',
    `${rp.sigmaGamma} / ${rp.factor} / ${rp.repeatsNeeded}`);
  ok(rp.sigmaGamma > 0, '  with a strictly positive uncertainty on the exponent',
    rp.sigmaGamma.toExponential(3));
  // Zero is the only drift the floor catches: one code value already gives
  // 1/sqrt(2) = 0.707, which is above 1/sqrt(12). The floor is a guard on the
  // degenerate case, not a fudge applied to real answers.
  ok(!G.repeatScatter(140, 141).atFloor, '  a drift of 1 is already above the floor');
  near(G.repeatScatter(140, 141).sigmaCode, 0.70711, 1e-5, '  reporting 0.7071 rather than the floor');
  ok(!G.repeatScatter(140, 142).atFloor, '  and so is a drift of 2');
  near(G.repeatScatter(140, 142).sigmaCode, 1.41421, 1e-5, '  reporting 1.4142');
  // resolvingPower must not be askable a question with no answer either.
  eq(G.resolvingPower(1, 0, m).factor, null, 'a gap of zero returns no factor rather than infinity');
}

section('2g. the 0.1% is inside this method\'s own arithmetic floor');
/*
 * To et al. report their psychophysical gamma landing about 0.1% from a
 * photometer. That is one run, and it is smaller than what 8-bit rounding alone
 * does to THIS reduction with a perfect eye and a perfect power law behind it.
 * The page says so; these are the numbers it says it with.
 */
{
  const devs = [];
  for (let g = 1800; g <= 2600; g++) {
    const gam = g / 1000;
    devs.push(((G.fitGamma(G.quantise(G.idealMatches(G.purePower(gam)))).gamma - gam) / gam) * 100);
  }
  eq(devs.length, 801, '801 true exponents from 1.800 to 2.600 in steps of 0.001');
  const mean = devs.reduce((a, b) => a + b, 0) / devs.length;
  const sd = Math.sqrt(devs.reduce((a, b) => a + (b - mean) * (b - mean), 0) / devs.length);
  const worst = Math.max(...devs.map(Math.abs));
  near(sd, 0.1880, 0.0005, 'quantisation alone moves the exponent by 0.19% sd');
  near(worst, 0.5057, 0.0005, '  and by 0.51% at worst');
  ok(sd > 0.1, '  which is larger than the 0.1% To et al. report, so that figure is not a precision',
    `${sd.toFixed(3)}% against 0.1%`);
  ok(worst > 5 * 0.1, '  and the worst case is five times it');
  ok(html0().includes('0.19 per cent') && html0().includes('0.51 per cent'),
    '  and both figures are on the page in those words');
}
ok(!G.canPaintHalftone({ dpr: 5, top: 0, left: 0, width: 600, height: 198 }).ok,
  'a device pixel ratio of 5 is refused');
ok(!G.canPaintHalftone({ dpr: 1, top: 0, left: 0, width: 600, height: 40 }).ok,
  'a band of 40 CSS pixels is refused');
ok(!G.canPaintHalftone({ dpr: 1, top: 0, left: 0, width: 600, height: 198, backingWidth: 480, backingHeight: 158 }).ok,
  'a patch painted for a box it is no longer in is refused');
ok(G.canPaintHalftone({ dpr: 1, top: 0, left: 0, width: 600, height: 198, backingWidth: 600, backingHeight: 198 }).ok,
  'and one painted for the box it is in is not');

/* ═══ 3. the captured render traces ═════════════════════════════════════════ */
section('3. the captured render traces, replayed through the shipped audit');
const RT = D('render-traces.json');
eq(RT.traces.length, 21, '21 traces are committed');
eq([...new Set(RT.traces.map((t) => t.engine))].sort().join(','), 'chromium,firefox,webkit',
  'from three different rendering engines');
ok(RT.traces.every((t) => t.patches.length === 9), 'each carries all nine patches');
ok(RT.traces.every((t) => t.patches.every((p) => p.sparse.reduce((a, [, n]) => a + n, 0) === p.px)),
  'and every histogram accounts for every pixel of its region');
ok(RT.traces.every((t) => t.jsErrors.length === 0), 'no JavaScript error was thrown during any capture');

const audits = RT.traces.map((t) => ({ t, a: G.auditTrace(t) }));
const clean = audits.filter(({ a }) => a.ok);
const dirty = audits.filter(({ a }) => !a.ok);
eq(clean.length, 12, 'twelve captures carry exactly the light they claim');
ok(clean.every(({ a }) => a.worstLightError === 0),
  'and "exactly" means zero, not small', clean.map(({ a }) => a.worstLightError).join(','));
eq(dirty.length, 9, 'nine do not');

section('3b. the negative control that is not synthetic');
const stale = audits.filter(({ t }) => t.stale);
eq(stale.length, 3, 'three captures were zoomed to 125% without a repaint, one per engine');
ok(stale.every(({ a }) => !a.ok), 'NEGATIVE CONTROL: every one of them is refused by the audit');
ok(stale.every(({ a }) => a.worstPurity === 1),
  '  and every one of them is 100.000% pure black and white while being refused',
  stale.map(({ a }) => a.worstPurity).join(','));
/*
 * These two used to sit next to each other as "their worst light error is 18.5
 * parts per thousand" followed by "which is worth 0.195 in the exponent". Both
 * assertions were true and the sentence they made was false: the two maxima are
 * different captures. Each row now carries its own capture, and one further row
 * asserts that they are not the same one, so the false pairing cannot come back
 * without turning a check red.
 */
{
  const byErr = stale.slice().sort((x, y) => y.a.worstLightError - x.a.worstLightError)[0];
  const byBias = stale.slice().sort((x, y) => y.a.worstGammaBias - x.a.worstGammaBias)[0];
  near(byErr.a.worstLightError, 0.018519, 1e-5,
    `  the worst stale light error is 18.5 parts per thousand, on ${byErr.t.engine}`);
  near(byErr.a.worstGammaBias, 0.12190, 1e-4,
    '  and THAT capture is worth 0.122 in the exponent, not 0.195');
  near(byBias.a.worstGammaBias, 0.19457, 1e-4,
    `  the worst stale exponent bias is 0.195, on ${byBias.t.engine}`);
  near(byBias.a.worstLightError, 0.0092593, 1e-6,
    '  and THAT capture is off in light by only 9.3 parts per thousand');
  ok(byErr.t.label !== byBias.t.label,
    '  so the two maxima are different captures and must never be joined by "worth"',
    `${byErr.t.engine} vs ${byBias.t.engine}`);
  ok(!/parts per thousand more light than it claimed, worth/.test(
    fs.readFileSync(R(`public/strata/${SLUG}/index.html`), 'utf8')),
  '  NEGATIVE CONTROL: the page does not carry the sentence that joined them');
}
ok(stale.every(({ t }) => t.zoom === 1.25), '  all three at the same zoom, so the engines can be compared');

section('3c. geometry as a predictor, measured rather than assumed');
{
  const off = (x) => Math.abs(x - Math.round(x)) > 0.02;
  const offGrid = RT.traces.filter((t) => off(t.geometry.width * t.dpr) || off(t.geometry.height * t.dpr)
    || off(t.geometry.top * t.dpr) || off(t.geometry.left * t.dpr));
  eq(offGrid.length, 21, 'every one of the 21 captures was off the device pixel grid somewhere');
  const dirtyLabels = new Set(dirty.map(({ t }) => t.label));
  eq(offGrid.filter((t) => dirtyLabels.has(t.label)).length, 9,
    'and only nine of those were damaged, which is why geometry does not refuse');
  const nonStaleDirty = dirty.filter(({ t }) => !t.stale);
  near(Math.max(...nonStaleDirty.map(({ a }) => a.worstGammaBias)), 0.08132, 1e-4,
    'the worst a non-stale rendering stack did was 0.081 in the exponent');
  const worstRow = nonStaleDirty.slice().sort((x, y) => y.a.worstGammaBias - x.a.worstGammaBias)[0];
  eq(worstRow.t.dpr, 3, '  and it was the single ratio-3 capture, which is therefore NOT clean');
  const cleanDprs = clean.map(({ t }) => t.dpr);
  eq(Math.max(...cleanDprs), 2,
    'the twelve exact captures reach ratio 2 and no further; the page must not say 3',
    `ratios ${Math.min(...cleanDprs)} to ${Math.max(...cleanDprs)}`);
  const cleanZooms = clean.map(({ t }) => t.zoom);
  ok(Math.min(...cleanZooms) === 0.9 && Math.max(...cleanZooms) === 1.25,
    '  and they span zoom 90 to 125 per cent, which the page does say');
}

section('3d. the frozen offline block, re-derived rather than trusted');
/*
 * offGridWorstGammaBias is added to EVERY reader's printed error bar and
 * staleWorstGammaBias is printed in the footer. Both were shipped as a frozen
 * blob that nothing re-computed: a stale run of script 4 would have carried a
 * wrong error bar past all three layers of checking. deriveSystematic is the
 * single copy of that derivation; here it runs over the raw captures and the
 * result is compared field by field against what data.js actually ships.
 */
{
  const shipped = JSON.parse(fs.readFileSync(R(`public/strata/${SLUG}/data.js`), 'utf8')
    .replace(/^[\s\S]*?export default /, '').replace(/;\s*$/, ''));
  // Derived from the LAB file, not from data.js, so this compares the shipped
  // block against the evidence rather than against itself.
  const fresh = deriveSystematic(RT.traces, {
    auditTrace: G.auditTrace, renderSystematic: G.renderSystematic,
  });
  const got = shipped.offline.renderSystematic;
  for (const k of Object.keys(fresh)) {
    ok(JSON.stringify(got[k]) === JSON.stringify(fresh[k]),
      `offline.renderSystematic.${k} is what the traces give`,
      `shipped ${JSON.stringify(got[k])}, re-derived ${JSON.stringify(fresh[k])}`);
  }
  eq(Object.keys(got).length, Object.keys(fresh).length,
    'and data.js ships no extra key that this file never checked');
}

section('3e. the sigmoid control, swept instead of sampled');
/*
 * P4 was stated flat on two steepnesses, both of them past the residual limit.
 * Swept, the rule turns out to have a boundary, and below it a sigmoid IS
 * fitted. What saves the finding is what comes back: an exponent near 1.
 */
{
  const rows = [];
  for (let s = 10; s <= 200; s++) {
    rows.push({ s: s / 10, r: G.fitGamma(G.quantise(G.idealMatches(G.sigmoidCell(s / 10)))) });
  }
  const refused = rows.filter((x) => x.r.refused);
  const fitted = rows.filter((x) => !x.r.refused);
  eq(rows.length, 191, '191 steepnesses from 1.0 to 20.0 in steps of 0.1');
  eq(refused.length, 124, 'the residual rule refuses 124 of them');
  eq(fitted.length, 67, 'and fits 67');
  eq(Math.min(...refused.map((x) => x.s)), 7.7, 'the boundary is at steepness 7.7');
  ok(refused.every((x) => x.r.reason === 'residual'), '  and every refusal is on the residual');
  ok(fitted.every((x) => x.s < 7.7), '  every fit is below the boundary, so the rule is monotone in steepness');
  near(Math.min(...fitted.map((x) => x.r.gamma)), 1.0102, 5e-4, '  the shallowest fit returns 1.01');
  near(Math.max(...fitted.map((x) => x.r.gamma)), 1.2968, 5e-4, '  the steepest fit that gets through returns 1.30');
  ok(fitted.every((x) => x.r.gamma < 1.3),
    '  so nothing that gets through lands anywhere near the 2.2 reference display, or Poynton’s 2.35 to 2.55');
  const flat = G.fitGamma(G.FRACTIONS.map((f) => ({ f, code: Math.round(f * 255) })));
  ok(!flat.refused && flat.gamma < 1.05,
    'KNOWN GAP: a reader who sets code = fraction x 255 is fitted, not refused',
    `returns ${flat.gamma.toFixed(3)} with rmsLog ${flat.rmsLog.toFixed(4)}; the page says so in "what this page does not claim"`);
  const htmlP4 = fs.readFileSync(R(`public/strata/${SLUG}/index.html`), 'utf8');
  ok(!/P4 held\.<\/b>/.test(htmlP4),
    '  and P4 no longer states the flat version of that claim');
}

/* ═══ 4. the displays ═══════════════════════════════════════════════════════ */
section('4. the two panels, and what they say about themselves');
const DISP = D('displays.json').displays;
eq(DISP.length, 2, 'two EDID-derived profiles are committed');
for (const d of DISP) {
  const p = R(d.file);
  ok(fs.existsSync(p), `${d.model}: the profile file is present`);
  const got = crypto.createHash('sha256').update(fs.readFileSync(p)).digest('hex');
  eq(got, d.sha256, `${d.model}: the committed bytes hash to the recorded SHA-256`);
  near(d.declaredGamma, 2.2, 1e-4, `${d.model}: declares a gamma of 2.2`);
}
ok(DISP[0].sha256 !== DISP[1].sha256, 'the two profiles are different files');
eq(new Set(DISP.map((d) => d.declaredGamma)).size, 1,
  'and both of them declare the identical value, which is the point');

/* ═══ 5. what the page ships ════════════════════════════════════════════════ */
section('5. the shipped page and its data');
const PAGE = R(`public/strata/${SLUG}/index.html`);
const html = fs.readFileSync(PAGE, 'utf8');
const dataJs = fs.readFileSync(R(`public/strata/${SLUG}/data.js`), 'utf8');
const DATA = JSON.parse(dataJs.slice(dataJs.indexOf('export default ') + 15, dataJs.lastIndexOf(';')));

eq(DATA.traces.length, RT.traces.length, 'data.js ships every captured trace');
ok(DATA.traces.every((t, i) => JSON.stringify(t.patches) === JSON.stringify(
  RT.traces[i].patches.map((p) => ({ k: p.k, nominal: p.nominal, px: p.px, sparse: p.sparse })))),
'and every shipped histogram is byte-for-byte the lab capture');
eq(DATA.displays.length, 2, 'and both display profiles');
ok(DATA.displays.every((d, i) => d.sha256 === DISP[i].sha256), 'with their recorded hashes');
eq(DATA.offline.engineSha,
  crypto.createHash('sha256').update(fs.readFileSync(R(`public/strata/${SLUG}/gamma.mjs`))).digest('hex'),
  'the engine hash in data.js is the hash of the engine actually shipped');
eq(DATA.offline.tracesSha, DATA.tracesSha, 'the two copies of the trace hash agree');
eq(DATA.offline.observerCommitted, false, 'and the page states that no observer is committed');

section('5b. the page says only things that are true');
ok(html.includes('node research/the-exponent-between-number-and-light/verify.mjs'),
  'the reproduce command printed on the page is this file');
for (const f of ['1-sources.mjs', '2-capture-render-traces.mjs', '3-build-matchsets.mjs', '4-emit-page-data.mjs']) {
  ok(html.includes(`node research/${SLUG}/${f}`) && fs.existsSync(path.join(HERE, f)),
    `the script ${f} is named on the page and exists`);
}
ok(fs.existsSync(R(`verify-${SLUG}.mjs`)), 'the browser-driving verifier exists');
ok(html.includes('about 0.1%') || html.includes('0.1 per cent'),
  'the published accuracy figure is on the page');
ok(/ViewSonic G810 CRT/.test(html), 'and it is attributed to the CRT it was measured on');
ok(/Parraga/.test(html) && /Xiao/.test(html) && /Poynton/.test(html) && /To, L\./.test(html),
  'all four sources are cited by name');
ok(!/same team|same group/i.test(html),
  'NEGATIVE CONTROL: the page does not claim Parraga et al. are the same group as To et al.');
ok(!/your display is exactly|proves your monitor is/i.test(html),
  'NEGATIVE CONTROL: the page does not claim to have settled which curve a display is');

/*
 * The provenance the page got wrong once, pinned three ways so it cannot come
 * back: the retracted sentence must be absent, both documents must be named
 * with what each actually contains, and the 1996 breakpoints must appear so a
 * reader can check the substitution rather than take it.
 */
ok(!/constants\s*\n?\s*taken from the W3C reference text/i.test(html.replace(/\s+/g, ' ')),
  'NEGATIVE CONTROL: the page no longer says the constants were taken from the W3C text');
{
  const engineSrc = fs.readFileSync(R(`public/strata/${SLUG}/gamma.mjs`), 'utf8');
  ok(!/transcribed from that text/i.test(engineSrc),
    'NEGATIVE CONTROL: nor does the engine\'s own comment');
  ok(/registry\.color\.org/.test(engineSrc) && /0\.00304/.test(engineSrc),
    '  and the engine names both documents where a reader of the code will meet them');
}
ok(/registry\.color\.org\/rgb-registry\/srgb/.test(html),
  'the ICC registry, which does publish 0.0031308 and names the standard, is cited');
ok(/sRGB\.pdf/.test(html) && /12\.02/.test(html),
  '  as is ICC\'s sRGB.pdf, together with the typo it prints');
ok(/0\.00304/.test(html) && /0\.03928/.test(html),
  'the 1996 proposal\'s different breakpoints are stated, not hidden');
ok(/one-bit PNGs|1-bit PNGs/i.test(html),
  '  along with the reason nobody could have read them off that page as text');
ok(/second hand/i.test(html),
  'the reference-display 2.2, which is behind the paywall, is flagged as second hand');
ok(/seven recursively halved|seven matches in all/i.test(html),
  'To et al.\'s seven recursive matches are not conflated with Xiao et al.\'s eight fractions');
ok(/F\(6,56\) = 25\.2/.test(html) && /F\(6,56\) = 113/.test(html),
  'the same paper\'s two p < 0.0001 results are quoted beside its two null ones');
// The em-dash gate, written with an escape rather than the character itself so
// that a sweep over this file can never quietly disarm it. It did once.
eq((html.match(/\u2014/g) || []).length, 0, 'no em dash appears in the page source');
eq((html.match(/&mdash;|&#8212;|&#x2014;/gi) || []).length, 0, 'and none is hiding as an entity either');

/* ═══ 6. the arithmetic the page prints in prose ════════════════════════════ */
section('6. the figures the page prints');
{
  const sep1 = G.separation(G.srgbDisplay(), G.purePower(2.2));
  const sep2 = G.separation(G.purePower(2.2), G.purePower(2.5));
  near(sep1.maxCodeGap, 1.4808, 0.001, 'sRGB and pure 2.2 differ by at most 1.481 code values');
  near(sep1.gammaGap, 0.01870, 0.0002, 'and by 0.0187 in the fitted exponent');
  near(sep2.maxCodeGap, 11.9587, 0.001, 'pure 2.2 and pure 2.5 differ by at most 11.959 code values');
  ok(sep2.maxCodeGap / sep1.maxCodeGap > 8, 'eight times as far apart');

  /*
   * The other way section 4 could be made vacuous, and the one that was live
   * for every steady reader: the resolving-power line compared the gap against
   * the reader's hand ALONE. This page's own error bar carries a systematic
   * term the captures bought, and it is larger than the sRGB-against-2.2 gap by
   * a factor of four, so no number of repeats settles that argument. These
   * three checks are what stops the page quoting a run count for it again.
   */
  const shippedSys = JSON.parse(fs.readFileSync(R(`public/strata/${SLUG}/data.js`), 'utf8')
    .replace(/^[\s\S]*?export default /, '').replace(/;\s*$/, '')).offline.renderSystematic;
  const sysBias = shippedSys.offGridWorstGammaBias;
  near(sysBias, 0.08132, 1e-4, 'the systematic a rendering stack can add is 0.081 in the exponent');
  ok(sysBias > sep1.gammaGap,
    '  which is LARGER than the sRGB-against-2.2 gap, so no repeat count settles that argument',
    `${sysBias.toFixed(4)} against ${sep1.gammaGap.toFixed(4)}, a factor of ${(sysBias / sep1.gammaGap).toFixed(1)}`);
  ok(sysBias < sep2.gammaGap,
    '  and SMALLER than the 2.2-against-2.5 gap, so that one is still settleable and the check can fail',
    `${sysBias.toFixed(4)} against ${sep2.gammaGap.toFixed(4)}`);
  // What the reader's hand alone would have said, so the size of the error is
  // on the record: a scatter of 2.83 code values, which is the demo observer,
  // propagates to 0.018 in the exponent, just UNDER the gap. That is the
  // comparison the page used to print, and it is why the demo fill itself
  // reached "a single run would separate them".
  {
    const rpDemo = G.resolvingPower(2.8284, sep1.gammaGap, G.quantise(G.idealMatches(G.purePower(2.2))));
    ok(rpDemo.sigmaGamma < sep1.gammaGap,
      '  the demo observer\'s hand alone is under the gap, which is how the old line got there',
      `${rpDemo.sigmaGamma.toFixed(4)} against ${sep1.gammaGap.toFixed(4)}`);
    ok(Math.sqrt(rpDemo.sigmaGamma ** 2 + sysBias ** 2) > sep1.gammaGap,
      '  and is over it once the systematic is added, which is what the page now prints',
      `${Math.sqrt(rpDemo.sigmaGamma ** 2 + sysBias ** 2).toFixed(4)}`);
  }

  const b = G.blendReport(2.2);
  eq(b.naiveCode, 127.5, 'half of 0 and 255 in code space is 127.5');
  near(b.naiveLight, 0.21764, 1e-5, 'which carries 21.76% of the light');
  near(b.trueCode, 186.0837, 1e-4, 'half the light is code 186.084');
  near(b.lightRatio, 2.29740, 1e-5, 'so the naive blend is 2.297 times too dark');

  const sf = G.fitGamma(G.quantise(G.idealMatches(G.srgbDisplay())));
  const pp = sf.perPoint.map((p) => p.gamma);
  near(Math.min(...pp), 2.20170, 1e-4, 'on an exact sRGB display the per-patch exponents run from 2.2017');
  near(Math.max(...pp), 2.27771, 1e-4, 'up to 2.2777');
  near(sf.spread, 0.07602, 1e-4, 'a spread of 0.076 with no reader involved at all');
  const cont = G.idealMatches(G.srgbDisplay()).map((m) => Math.log(m.f) / Math.log(m.code / 255));
  ok(cont.every((g, i) => i === 0 || g > cont[i - 1]),
    'before rounding, those exponents climb monotonically across the range',
    cont.map((g) => g.toFixed(4)).join(' '));
  ok(!pp.every((g, i) => i === 0 || g > pp[i - 1]),
    'and 8-bit rounding alone is enough to break that climb, which is the leverage argument',
    pp.map((g) => g.toFixed(4)).join(' '));
}

/* ═══ done ══════════════════════════════════════════════════════════════════ */
console.log(`\n${fail === 0 ? 'ALL CHECKS PASSED' : `${fail} CHECK(S) FAILED`}  (${pass}/${pass + fail})`);
process.exit(fail === 0 ? 0 : 1);
