#!/usr/bin/env node
/*
 * verify-the-exponent-between-number-and-light.mjs
 *
 * Tier B. The offline mirror (research/<slug>/verify.mjs) checks the arithmetic
 * on the command line. This file checks the thing a stranger actually receives:
 * it serves the BUILT site, drives the page in a real headless browser, and
 * asks whether the numbers the browser prints are the numbers node computes
 * from the same module.
 *
 * The load-bearing part is the replay. A measurement taken on a stranger's
 * display cannot be re-derived offline, so a verifier that only confirmed the
 * published anchor would confirm that 2.2 is 2.2 and say nothing about whether
 * the instrument measured anything. So: the committed match-sets are pushed
 * through the page's own fit, in the browser, and required to come back as the
 * exponents they were built from; a set built from a different exponent is
 * required NOT to; and the three captured traces that were zoomed without a
 * repaint are required to be refused, in the browser, despite being perfectly
 * crisp.
 *
 *   npm run build && node verify-the-exponent-between-number-and-light.mjs
 */
import { chromium } from 'playwright';
import { createServer } from 'node:http';
import { readFileSync, existsSync } from 'node:fs';
import { extname, join } from 'node:path';
import { createHash } from 'node:crypto';
import * as E from './public/strata/the-exponent-between-number-and-light/gamma.mjs';
import { deriveSystematic } from './research/the-exponent-between-number-and-light/systematic.mjs';

const SLUG = 'the-exponent-between-number-and-light';
const root = new URL('./dist/', import.meta.url).pathname;
const pub = new URL('./public/', import.meta.url).pathname;
if (!existsSync(root)) {
  console.error(`no dist/ at ${root}. Run npm run build first.`);
  process.exit(1);
}

const types = {
  '.html': 'text/html', '.css': 'text/css', '.js': 'text/javascript', '.mjs': 'text/javascript',
  '.woff2': 'font/woff2', '.woff': 'font/woff', '.png': 'image/png', '.webp': 'image/webp',
  '.svg': 'image/svg+xml', '.ico': 'image/x-icon', '.json': 'application/json',
  '.txt': 'text/plain', '.jpg': 'image/jpeg', '.mp4': 'video/mp4',
};
/*
 * dist/ first, public/ as a fallback, and the page says out loud which one
 * served it. Builders on this project are forbidden to run `npm run build`
 * because they run concurrently and would clobber each other's dist/, so this
 * file has to be runnable before the orchestrator's single build. When dist/
 * does have the page, dist/ is what gets driven.
 */
const servedFrom = existsSync(join(root, 'strata', SLUG, 'index.html')) ? 'dist' : 'public';
const server = createServer((req, res) => {
  let p = decodeURIComponent(req.url.split('?')[0]);
  if (p.endsWith('/')) p += 'index.html';
  for (const base of [root, pub]) {
    try {
      const buf = readFileSync(join(base, p));
      res.writeHead(200, { 'content-type': types[extname(p)] || 'application/octet-stream' });
      res.end(buf);
      return;
    } catch { /* next base */ }
  }
  res.writeHead(404); res.end('404');
});
const PORT = 8232;
await new Promise((r) => server.listen(PORT, r));
const URL_ = `http://localhost:${PORT}/strata/${SLUG}/`;

let fails = 0;
const ok = (n, c, x = '') => { if (!c) fails++; console.log(`${c ? '  ok  ' : 'FAIL  '}${n}${x ? '   ' + x : ''}`); };
const near = (n, got, want, tol) => ok(n, Number.isFinite(got) && Math.abs(got - want) <= tol,
  `got ${got}, want ${want} +/- ${tol}`);

const browser = await chromium.launch();
const page = await browser.newPage({ viewport: { width: 1200, height: 1000 } });
const errs = [];
page.on('pageerror', (e) => errs.push(String(e)));
page.on('console', (m) => { if (m.type() === 'error') errs.push(m.text()); });
const external = [];
page.on('request', (r) => { const u = new URL(r.url()); if (u.hostname !== 'localhost') external.push(r.url()); });

await page.goto(URL_, { waitUntil: 'networkidle' });
await page.waitForFunction(() => window.__gamma && window.__gamma.ready === true, null, { timeout: 30000 });

console.log(`\nTHE EXPONENT BETWEEN THE NUMBER AND THE LIGHT / built-page verification`);
console.log(`the page under test was served from ${servedFrom}/\n`);

/* ─── the basics ─────────────────────────────────────────────────────────── */
ok('no JS errors on load', errs.length === 0, errs.join(' | '));
ok('no third-party requests', external.length === 0, external.join(' '));
ok('gamma.mjs loaded over HTTP as a module',
  await page.evaluate(() => !!(window.__gamma && window.__gamma.engine && window.__gamma.engine.fitGamma)));
ok('data.js loaded and carries the captured traces',
  await page.evaluate(() => window.__gamma.data.traces.length) === 21);

/* ─── the instrument can return a positive, and a negative ───────────────── */
{
  const html = await page.content();
  ok('a known-present string is present', html.includes('The Exponent Between the Number and the Light'));
  ok('  and 1/9 through 8/9 are named', html.includes('1/9') && html.includes('8/9'));
  ok('NEGATIVE CONTROL: a known-absent string is absent',
    !html.includes('your display is exactly') && !/measured with a photometer on your/i.test(html));
  ok('NEGATIVE CONTROL: the page does not call Parraga et al. the same team as To et al.',
    !/same team|same group/i.test(html));
  // Scoped to <main>, and written with an escape rather than the character
  // itself so a sweep over this file cannot quietly disarm the gate. The shared
  // site banner injected by /media/home-banner.js carries one em dash in its own
  // aria-label; that is chrome, not this page's prose.
  const main = html.slice(html.indexOf('<main>'), html.indexOf('</main>') + 7);
  ok('no em dash anywhere in this page\'s own prose', !main.includes('\u2014'),
    JSON.stringify(main.slice(Math.max(0, main.indexOf('\u2014') - 60), main.indexOf('\u2014') + 20)));
  ok('  and the chrome outside it accounts for every one in the document',
    (html.split('\u2014').length - 1) <= 1);
}

/* ─── the shipped engine is the engine this file imported ────────────────── */
{
  const served = await (await fetch(`http://localhost:${PORT}/strata/${SLUG}/gamma.mjs`)).text();
  const local = readFileSync(join(pub, 'strata', SLUG, 'gamma.mjs'), 'utf8');
  ok('the built gamma.mjs is byte-identical to the one in public/', served === local,
    `${createHash('sha256').update(served).digest('hex').slice(0, 16)} vs ${createHash('sha256').update(local).digest('hex').slice(0, 16)}`);
  const declared = await page.evaluate(() => window.__gamma.data.offline.engineSha);
  ok('  and to the hash data.js declares for it',
    declared === createHash('sha256').update(local).digest('hex'), declared.slice(0, 16));
}

/* ─── shipped data is byte-identical to the lab source ───────────────────── */
{
  const lab = JSON.parse(readFileSync(`./research/${SLUG}/data/render-traces.json`, 'utf8'));
  const shipped = await page.evaluate(() => window.__gamma.data.traces);
  ok('every shipped histogram is byte-for-byte the lab capture',
    shipped.length === lab.traces.length && shipped.every((t, i) =>
      JSON.stringify(t.patches.map((p) => p.sparse)) === JSON.stringify(lab.traces[i].patches.map((p) => p.sparse))));
  const disp = JSON.parse(readFileSync(`./research/${SLUG}/data/displays.json`, 'utf8')).displays;
  for (const d of disp) {
    const got = createHash('sha256').update(readFileSync(`./${d.file}`)).digest('hex');
    ok(`${d.model}: committed profile hashes to its record`, got === d.sha256);
  }
}

/* ─── THE REPLAY: match-sets through the browser's own fit ───────────────── */
console.log('\n-- the replay ------------------------------------------------');
{
  const MS = JSON.parse(readFileSync(`./research/${SLUG}/data/matchsets.json`, 'utf8'));
  const inBrowser = async (id) => page.evaluate((matches) =>
    window.__gamma.engine.fitGamma(matches.map(([f, code]) => ({ f, code }))),
  MS.sets.find((s) => s.id === id).matches);

  const WINDOWS = [
    ['pure-1.80', 1.8022], ['pure-2.00', 1.9979], ['pure-2.20', 2.2019],
    ['pure-2.40', 2.3967], ['pure-2.50', 2.5023], ['srgb-piecewise', 2.2206],
    ['leak-2.20-b0.2', 2.2019], ['offset-2.50-eps0.05', 2.3360],
  ];
  for (const [id, want] of WINDOWS) {
    const b = await inBrowser(id);
    near(`browser replay: ${id} recovers ${want}`, b.gamma, want, 0.0005);
    const n = E.fitGamma(MS.sets.find((s) => s.id === id).matches.map(([f, code]) => ({ f, code })));
    ok(`  and the browser agrees with node to 1e-12`, Math.abs(b.gamma - n.gamma) < 1e-12);
  }
  for (const id of ['pure-1.80', 'pure-2.50']) {
    const b = await inBrowser(id);
    ok(`NEGATIVE CONTROL: ${id} does not pass the 2.20 window, in the browser`,
      Math.abs(b.gamma - 2.2019) > 0.02, `got ${b.gamma.toFixed(4)}`);
  }
  for (const id of ['noise-1', 'noise-20260807', 'sigmoid-8']) {
    const b = await inBrowser(id);
    ok(`NEGATIVE CONTROL: ${id} is refused in the browser`, b.refused === true, b.reason || `returned ${b.gamma}`);
  }
}

/* ─── THE REPLAY: captured traces through the browser's own audit ────────── */
{
  const audits = await page.evaluate(() =>
    window.__gamma.data.traces.map((t) => {
      const a = window.__gamma.engine.auditTrace(t);
      return { label: t.label, stale: !!t.stale, ok: a.ok, purity: a.worstPurity, err: a.worstLightError, bias: a.worstGammaBias };
    }));
  ok('the browser audits all 21 captures', audits.length === 21);
  ok('twelve of them carry exactly the light they claim',
    audits.filter((a) => a.ok).length === 12 && audits.filter((a) => a.ok).every((a) => a.err === 0));
  const stale = audits.filter((a) => a.stale);
  ok('NEGATIVE CONTROL: all three stale-zoom captures are refused in the browser',
    stale.length === 3 && stale.every((a) => !a.ok));
  ok('  while every pixel in them is pure black or pure white',
    stale.every((a) => a.purity === 1), stale.map((a) => a.purity).join(','));
  near('  and their worst bias is 0.195 in the exponent',
    Math.max(...stale.map((a) => a.bias)), 0.19457, 1e-4);
  // the browser's audit must equal node's, trace for trace
  const nodeSide = JSON.parse(readFileSync(`./research/${SLUG}/data/render-traces.json`, 'utf8'))
    .traces.map((t) => E.auditTrace(t));
  ok('every browser audit equals the node audit, trace for trace',
    audits.every((a, i) => a.ok === nodeSide[i].ok && Math.abs(a.err - nodeSide[i].worstLightError) < 1e-15));
}

/* ─── the live instrument actually works ─────────────────────────────────── */
console.log('\n-- the live instrument ---------------------------------------');
{
  const sample = (id) => page.evaluate((i) => {
    const cv = document.getElementById(i);
    const g = cv.getContext('2d', { willReadFrequently: true });
    const d = g.getImageData(0, 0, cv.width, cv.height).data;
    let sum = 0; const seen = new Set();
    for (let k = 0; k < d.length; k += 4 * 37) { sum += d[k]; seen.add(d[k]); }
    return { sum, distinct: seen.size, w: cv.width, h: cv.height };
  }, id);

  const before1 = await sample('cv1');
  ok('the match stage paints', before1.distinct > 1 && before1.w > 100, JSON.stringify(before1));
  await page.fill('#v1', '200');
  await page.dispatchEvent('#v1', 'input');
  await page.waitForTimeout(80);
  const after1 = await sample('cv1');
  ok('and repaints when the slider moves', after1.sum !== before1.sum);
  ok('  the readout says so too', /code 200/.test(await page.textContent('#out1')));

  const beforeFit = await sample('cvFit');
  await page.click('#b2-demo');
  await page.waitForTimeout(200);
  const afterFit = await sample('cvFit');
  ok('the fit chart repaints once matches exist', afterFit.sum !== beforeFit.sum);
  ok('  and the demo fill labels itself as simulated', /Simulated, not measured/.test(await page.textContent('#out2')));

  // The simulator must never be mistakable for a measurement.
  ok('the simulated fill labels the headline readout too',
    /simulated γ =/.test(await page.textContent('#gamma-out')),
    (await page.textContent('#gamma-out')).trim());
  ok('  and says so in the detail line',
    /this is the simulator, not your eye/.test(await page.textContent('#gamma-detail')));
  /*
   * The label has to propagate. Four readouts downstream of the fit used to
   * address the reader in the second person with no label at all, so a page
   * driven by its own demo button told the reader that "your eye" could
   * separate two curves. Only the headline was checked before this.
   */
  {
    const downstream = { '#resolve-line': 'resolving power',
      '#out5': 'the blend', '#out4': 'the curve comparison', '#res-detail': 'the residual chart' };
    for (const [selRef, what] of Object.entries(downstream)) {
      const txt = await page.textContent(selRef);
      ok(`  ${what} does not say "your" while the fill is simulated`,
        !/\byour\b/i.test(txt), `${selRef}: ${txt.trim().slice(0, 120)}`);
    }
    ok('  and the blend readout names the simulator explicitly',
      /simulator/i.test(await page.textContent('#out5')), (await page.textContent('#out5')).trim().slice(0, 90));
  }
  await page.evaluate(() => { document.getElementById('v2').value = '150'; });
  await page.dispatchEvent('#v2', 'input');
  await page.click('#b2-set');
  await page.waitForTimeout(120);
  ok('  and a single real match clears the label',
    !/simulated/.test(await page.textContent('#gamma-out')) && !(await page.evaluate(() => window.__gamma.simulated)));
  await page.click('#b2-demo');
  await page.waitForTimeout(150);

  // A reader-reachable setting where the curve comparison is true by construction.
  await page.evaluate(() => {
    const bs = [...document.querySelectorAll('#curveB button')];
    bs.find((b) => b.textContent === 'sRGB piecewise').click();
  });
  await page.waitForTimeout(100);
  ok('VACUOUS SETTING: the same curve on both sides is named, not answered',
    /Both sides are set to/.test(await page.textContent('#out4')),
    (await page.textContent('#out4')).trim().slice(0, 90));
  await page.evaluate(() => {
    const bs = [...document.querySelectorAll('#curveB button')];
    bs.find((b) => b.textContent === 'pure 2.2').click();
  });
  await page.waitForTimeout(100);
  ok('  and two different curves give a real answer again',
    /never disagree by more than/.test(await page.textContent('#out4')));

  const shown = await page.textContent('#gamma-out');
  const state = await page.evaluate(() => ({ fit: window.__gamma.fit, scatter: window.__gamma.scatter }));
  ok('the exponent on screen is the exponent the module computed',
    shown.trim().endsWith(`γ = ${state.fit.gamma.toFixed(3)}`), `${shown.trim()} vs ${state.fit.gamma}`);
  const answers = await page.evaluate(() => {
    const m = window.__gamma.engine.noisyMatches(window.__gamma.engine.purePower(2.2), 3, 20260807);
    return m.map((x) => x.code);
  });
  const nodeFit = E.fitGamma(E.noisyMatches(E.purePower(2.2), 3, 20260807));
  ok('  and node, given the same simulated observer, gets the same exponent',
    Math.abs(nodeFit.gamma - state.fit.gamma) < 1e-12, `${nodeFit.gamma} vs ${state.fit.gamma}`);
  ok('  the seeded observer is identical in both engines',
    JSON.stringify(answers) === JSON.stringify(E.noisyMatches(E.purePower(2.2), 3, 20260807).map((x) => x.code)));

  // the drift refusal, driven through the DOM
  await page.evaluate(() => {
    const a = window.__gamma.engine.noisyMatches(window.__gamma.engine.purePower(2.2), 3, 20260807).map((m) => m.code);
    window.__gamma.setAnswers([...a, Math.min(254, a[3] + 40)]);
  });
  await page.waitForTimeout(120);
  ok('a 40-code drift on the repeated patch refuses the run',
    /refused/.test(await page.textContent('#gamma-out')));
  ok('  and says which rule refused it', /something changed under the measurement/i.test(await page.textContent('#gamma-detail')));
  await page.click('#b2-demo');
  await page.waitForTimeout(120);
  ok('  and a sane repeat restores it', /γ =/.test(await page.textContent('#gamma-out')));

  /*
   * The second reader-reachable setting where section 4 was true by
   * construction, and the one no page-level review found: match the repeated
   * patch twice on the SAME code. The scatter estimator returned exactly zero,
   * so the curve comparison told the reader their eye could separate two curves
   * the section exists to say no eye can separate, and the resolving-power line
   * divided by zero and printed "a factor of n/a". Driven here through the DOM,
   * as a reader reaches it, not through the module.
   */
  await page.evaluate(() => {
    const E = window.__gamma.engine;
    const a = E.quantise(E.idealMatches(E.purePower(2.2))).map((m) => m.code);
    window.__gamma.setAnswers([...a, a[E.REPEAT_INDEX]]);   // same code, twice
  });
  await page.waitForTimeout(150);
  {
    const st = await page.evaluate(() => window.__gamma.scatter);
    ok('VACUOUS SETTING: a repeat on the same code is a bound, not a scatter of zero',
      st.drift === 0 && st.sigmaCodeRaw === 0 && st.atFloor === true && st.sigmaCode > 0.28,
      JSON.stringify(st));
    const rl = (await page.textContent('#resolve-line')).trim();
    ok('  the resolving-power line says "under" rather than a measured scatter',
      /\bunder\b/.test(rl) && /bound rather than a measurement/.test(rl), rl.slice(0, 160));
    ok('  and never prints "n/a", which is what dividing by zero used to produce',
      !/n\/a/.test(rl), rl.slice(0, 160));
    const o4 = (await page.textContent('#out4')).trim();
    ok('  the curve comparison names the case instead of answering it',
      /landed on the same code value/.test(o4), o4.slice(0, 200));
    ok('  and does NOT tell the reader their eye can separate the two curves',
      !/your eye can tell these two apart/i.test(o4), o4.slice(0, 200));
  }
  // One code value of drift is a real measurement again, and must read as one.
  await page.evaluate(() => {
    const E = window.__gamma.engine;
    const a = E.quantise(E.idealMatches(E.purePower(2.2))).map((m) => m.code);
    window.__gamma.setAnswers([...a, a[E.REPEAT_INDEX] + 1]);
  });
  await page.waitForTimeout(150);
  {
    const st = await page.evaluate(() => window.__gamma.scatter);
    ok('  a drift of one code value is above the floor and reported as measured',
      st.drift === 1 && st.atFloor === false && Math.abs(st.sigmaCode - Math.SQRT1_2) < 1e-9,
      JSON.stringify(st));
    ok('    and the line goes back to "about"',
      /is about/.test(await page.textContent('#resolve-line')));
  }
  /*
   * The other vacuity, and the one that was live for every steady reader: the
   * resolving-power line used to weigh the sRGB-against-2.2 gap against the
   * reader's hand alone, with no systematic term, and so told anyone whose
   * repeat came back within about five code values that a single run of the
   * task would settle which curve their monitor is. The demo observer, at a
   * scatter of 3, reached that sentence. It contradicted the page's own error
   * bar by a factor of four and contradicted section 4 entirely.
   */
  await page.click('#b2-demo');
  await page.waitForTimeout(150);
  {
    const rl = (await page.textContent('#resolve-line')).trim();
    ok('the resolving-power line carries the systematic term, not the hand alone',
      /rendering stack adds/.test(rl) && /in all/.test(rl), rl.slice(0, 200));
    ok('  NEGATIVE CONTROL: it does not tell the demo observer a single run would settle it',
      !/a single run of the eight-patch task would separate them/.test(rl), rl.slice(0, 260));
    ok('  it says instead that no number of runs settles this one',
      /no number of runs that settles this/.test(rl), rl.slice(-220));
    ok('    and gives the reason, that repeats do not shrink a systematic',
      /leaving the systematic part exactly where it is/.test(rl), rl.slice(-260));
    const o4 = (await page.textContent('#out4')).trim();
    ok('  and the curve comparison agrees: sRGB against 2.2 is not settleable by this eye',
      /times the gap/.test(o4) && /could not tell these two apart/.test(o4), o4.slice(-200));
  }
  // The check must be able to fail. 2.2 against 2.5 is sixteen times wider a
  // gap than sRGB against 2.2, and the same reader IS told they can settle it.
  await page.evaluate(() => {
    const bs = [...document.querySelectorAll('#curveA button')];
    bs.find((b) => b.textContent === 'pure 2.2').click();
  });
  await page.evaluate(() => {
    const bs = [...document.querySelectorAll('#curveB button')];
    bs.find((b) => b.textContent.startsWith('pure 2.5')).click();
  });
  await page.waitForTimeout(120);
  {
    const o4 = (await page.textContent('#out4')).trim();
    ok('  but the SAME observer is told 2.2 against 2.5 IS settleable, so the verdict can go both ways',
      /could tell these two apart|can tell these two apart/.test(o4), o4.slice(-200));
  }
  await page.evaluate(() => {
    const bs = [...document.querySelectorAll('#curveA button')];
    bs.find((b) => b.textContent === 'sRGB piecewise').click();
  });
  await page.evaluate(() => {
    const bs = [...document.querySelectorAll('#curveB button')];
    bs.find((b) => b.textContent === 'pure 2.2').click();
  });
  await page.waitForTimeout(120);
}

/* ─── every figure in the prose, matched as a string ─────────────────────── */
console.log('\n-- the prose figures -----------------------------------------');
{
  const figs = await page.evaluate(() =>
    [...document.querySelectorAll('[data-fig]')].map((n) => [n.dataset.fig, n.textContent]));
  // "Filled" has to mean filled. Every one of these ships with the placeholder
  // "not yet" in the HTML, so a node the page failed to write reads as
  // non-empty text and would have slipped past a bare truthiness test.
  ok('every data-fig node was filled', figs.every(([, v]) => v && v !== '-' && v !== 'not yet'),
    JSON.stringify(figs.filter(([, v]) => !v || v === '-' || v === 'not yet')));

  const sep1 = E.separation(E.srgbDisplay(), E.purePower(2.2));
  const sep2 = E.separation(E.purePower(2.2), E.purePower(2.5));
  const sf = E.fitGamma(E.quantise(E.idealMatches(E.srgbDisplay())));
  const pp = sf.perPoint.map((p) => p.gamma);
  const b22 = E.blendReport(2.2);
  const rs = JSON.parse(readFileSync(`./research/${SLUG}/data/render-traces.json`, 'utf8'));
  // Derived here from the LAB captures through the same single copy of the
  // derivation the emit script uses, so the five figures the browser cannot
  // recompute are checked against the evidence and not against data.js.
  const sys = deriveSystematic(rs.traces, {
    auditTrace: E.auditTrace, renderSystematic: E.renderSystematic,
  });
  const sigSweep = (() => {
    const fitted = []; let first = null;
    for (let s = 10; s <= 200; s++) {
      const r = E.fitGamma(E.quantise(E.idealMatches(E.sigmoidCell(s / 10))));
      if (r.refused) { if (first === null) first = s / 10; } else fitted.push(r.gamma);
    }
    return { first, lo: Math.min(...fitted), hi: Math.max(...fitted) };
  })();
  const c89 = E.idealMatches(E.purePower(2.2))[7].code;
  const c19 = E.idealMatches(E.purePower(2.2))[0].code;
  const lever = (code, gamma) => Math.abs(gamma / Math.log(code / 255)) * (1 / code);
  const wrongCancel = (() => {
    const eotf = E.leakyPower(2.2, 0.20);
    const pure = E.idealMatches(E.purePower(2.2));
    return Math.max(...E.FRACTIONS.map((f, i) => Math.abs(E.codeForLight(eotf, f) - pure[i].code)));
  })();

  const want = {
    'code-half-srgb': (255 * E.linearToSrgb(0.5)).toFixed(1),
    'code-half-22': (255 * Math.pow(0.5, 1 / 2.2)).toFixed(1),
    'srgb-pp-lo': Math.min(...pp).toFixed(4),
    'srgb-pp-hi': Math.max(...pp).toFixed(4),
    'srgb-fit': sf.gamma.toFixed(4),
    'srgb-fit-2': sf.gamma.toFixed(4),
    'code-89': String(Math.round(c89)),
    'lever-89': lever(c89, 2.2).toFixed(2),
    'lever-19': lever(c19, 2.2).toFixed(3),
    'cancel': E.cancellationProof(2.2, 0.20).toExponential(1),
    'cancel-2': E.cancellationProof(2.2, 0.20).toExponential(1),
    'wrong-cancel': wrongCancel.toFixed(1),
    'offset-bias': E.fitGamma(E.quantise(E.idealMatches(E.offsetPower(2.5, 0.05)))).gamma.toFixed(3),
    'sep-srgb-22': sep1.maxCodeGap.toFixed(2),
    'gap-srgb-22': sep1.gammaGap.toFixed(4),
    'sep-22-25': sep2.maxCodeGap.toFixed(2),
    'gap-22-25': sep2.gammaGap.toFixed(3),
    'naive-light-22': (b22.naiveLight * 100).toFixed(1) + '%',
    'true-code-22': b22.trueCode.toFixed(1),
    'code-gap-22': b22.codeGap.toFixed(1),
    'ratio-22': b22.lightRatio.toFixed(2),
    'srgb-window': (E.SRGB.codeThreshold - E.SRGB.slope * E.SRGB.linearThreshold).toExponential(1),
    'srgb-miss': Math.abs(E.linearToSrgb(E.srgbToLinear(0.040449975)) - 0.040449975).toExponential(2),
    'offgrid': '21',
    'offgrid-bad': String(sys.nDirty),
    // Previously unchecked, and both feed a printed uncertainty: offgrid-worst
    // is added to every reader's error bar and stale-bias is quoted in the
    // footer. They passed only the "is non-empty" gate before this.
    'offgrid-worst': sys.offGridWorstGammaBias.toFixed(3),
    'offgrid-worst-2': sys.offGridWorstGammaBias.toFixed(3),
    'worst-dpr': String(sys.offGridWorstDpr),
    'clean-n': String(sys.nClean),
    'clean-dpr-lo': String(sys.cleanDprLo),
    'clean-dpr-hi': String(sys.cleanDprHi),
    'clean-zoom-lo': String(Math.round(sys.cleanZoomLo * 100)),
    'clean-zoom-hi': String(Math.round(sys.cleanZoomHi * 100)),
    'stale-err': (sys.staleWorstLightError * 1000).toFixed(1),
    'stale-bias': sys.staleWorstGammaBias.toFixed(2),
    'stale-bias-err': (sys.staleWorstBiasLightError * 1000).toFixed(1),
    'sig-refuse': sigSweep.first.toFixed(1),
    'sig-lo': sigSweep.lo.toFixed(2),
    'sig-hi': sigSweep.hi.toFixed(2),
  };
  const got = Object.fromEntries(figs);
  for (const [k, v] of Object.entries(want)) {
    ok(`prose figure "${k}" = ${v}`, got[k] === v, `page says ${JSON.stringify(got[k])}`);
  }
}

/* ─── the check panel ────────────────────────────────────────────────────── */
console.log('\n-- the page’s own check panel --------------------------------');
{
  const tally = (await page.textContent('#tally')).trim();
  const m = /^(\d+) \/ (\d+) checks pass$/.exec(tally);
  ok('the check panel reports a tally', !!m, tally);
  if (m) {
    ok(`  and all ${m[2]} of them pass`, m[1] === m[2], tally);
    ok(`  with at least 30 checks`, Number(m[2]) >= 30, m[2]);
  }
  const items = await page.$$eval('#checklist li', (ns) => ns.map((n) => n.className));
  ok('  every listed row is green', items.length > 0 && items.every((c) => c === 'p'),
    `${items.filter((c) => c !== 'p').length} red`);
  ok('  the panel names its OFFLINE rows as such',
    (await page.textContent('#checklist')).includes('OFFLINE:'));
}

/* ─── the stale-repaint backstop has to be REACHABLE ─────────────────────── */
/*
 * The rule's stale branch is the one the page advertises as catching a zoom
 * since the last paint. It used to be unreachable from the live page: the
 * audit ran only after a repaint had already resynced the backing store, and
 * window.__gamma.geometry() did not report the backing store at all, so no
 * driver could make it fire. Both are checked here from outside the page.
 */
console.log('\n-- the live stale check, driven from outside ------------------');
{
  const g0 = await page.evaluate(() => window.__gamma.geometry());
  ok('geometry() reports the backing store, so the stale branch is reachable',
    Number.isFinite(g0.geom.backingWidth) && Number.isFinite(g0.geom.backingHeight),
    JSON.stringify({ bw: g0.geom.backingWidth, bh: g0.geom.backingHeight }));
  ok('  and on a freshly painted page it reports no staleness',
    g0.verdict.stale === false && g0.verdict.ok === true);

  // Freeze the repaint watchdogs, resize, and wait for the poll: this is the
  // state the three committed captures were taken in, and it is the only state
  // in which the backstop is the thing that catches it.
  await page.evaluate(() => window.__gammaFreezeRepaint());
  await page.setViewportSize({ width: 520, height: 900 });
  await page.waitForTimeout(1600);
  const g1 = await page.evaluate(() => window.__gamma.geometry());
  ok('with the watchdog frozen, a resize leaves the canvas genuinely stale',
    g1.verdict.stale === true,
    JSON.stringify({ bw: g1.geom.backingWidth, w: Math.round(g1.geom.width * g1.geom.dpr) }));
  const verdict = (await page.textContent('#render-verdict')).trim();
  ok('  and the page SAYS SO, without being touched: the verdict flips by itself',
    /no, and here is why/.test(verdict), verdict);
  ok('  and the reason names the stretch',
    /being stretched/.test(await page.textContent('#render-detail')));
  ok('  and section 2 refuses rather than printing an exponent',
    /refused/.test((await page.textContent('#gamma-out')).trim()),
    (await page.textContent('#gamma-out')).trim());
  ok('  and the live verdict agrees with the rule',
    (await page.evaluate(() => window.__gamma.renderOk())) === false);
}

/* ─── chrome the design system requires ──────────────────────────────────── */
{
  const html = await page.content();
  // The way-out footer, the nearby-layers card and the plain placard are
  // INJECTED by the prebuild backfills (scripts/way-out.mjs, nearby-layers.mjs,
  // plain-cards.mjs). They exist in dist/, not in public/, so they are checked
  // only against a real build. Asserting them against public/ would be asking
  // this page to hand-roll the three blocks the design system forbids it to.
  if (servedFrom === 'dist') {
    ok('canonical way-out footer present', html.includes('aw-wayout'));
    ok('nearby-layers block present', html.includes('aw-nearby'));
    // scripts/plain-cards.mjs skips any stratum whose frontmatter says
    // draft: true, which this one must while the wave is in flight. The
    // placard therefore cannot exist yet, and asserting it here would be a
    // check the page cannot pass rather than a check the page can fail. It
    // becomes a real assertion the moment the orchestrator flips the flag,
    // and the flag itself is what is checked until then.
    const fm = readFileSync(`./src/content/strata/${SLUG}.md`, 'utf8').split(/^---$/m)[1] || '';
    if (/\bdraft:\s*true\b/.test(fm)) {
      ok('plain placard is correctly absent while the layer is still a draft',
        !/<meta name="aw-plain"/.test(html),
        'plain-cards.mjs injects it when draft: true is removed');
    } else {
      ok('plain placard meta present', /<meta name="aw-plain"/.test(html));
    }
  } else {
    console.log('  skip  way-out / nearby-layers / plain placard: injected at build, and this run served public/');
  }
  ok('top bar script present', html.includes('/media/home-banner.js'));
  ok('canonical link is the published URL',
    html.includes(`<link rel="canonical" href="https://artwaste.land/strata/${SLUG}/"`));
  ok('one Article JSON-LD block', (html.match(/"@type":"Article"/g) || []).length === 1);
  ok('nine og:* tags', (html.match(/property="og:/g) || []).length === 9,
    String((html.match(/property="og:/g) || []).length));
  ok('four twitter:* tags', (html.match(/name="twitter:/g) || []).length === 4,
    String((html.match(/name="twitter:/g) || []).length));
  ok('the printed reproduce command exists',
    html.includes(`node research/${SLUG}/verify.mjs`) && existsSync(`./research/${SLUG}/verify.mjs`));
}

/* ─── responsive ─────────────────────────────────────────────────────────── */
console.log('\n-- layout ----------------------------------------------------');
for (const w of [360, 390, 768, 1200, 1440]) {
  await page.setViewportSize({ width: w, height: 1000 });
  await page.waitForTimeout(220);
  const over = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
  ok(`no horizontal overflow at ${w}px`, over <= 1, 'overflow=' + over + 'px');
}

/* ─── reduced motion ─────────────────────────────────────────────────────── */
{
  const rm = await browser.newPage({ viewport: { width: 900, height: 1000 }, reducedMotion: 'reduce' });
  const rmErrs = [];
  rm.on('pageerror', (e) => rmErrs.push(String(e)));
  await rm.goto(URL_, { waitUntil: 'networkidle' });
  await rm.waitForFunction(() => window.__gamma && window.__gamma.ready === true, null, { timeout: 30000 });
  ok('the page loads clean under prefers-reduced-motion', rmErrs.length === 0, rmErrs.join(' | '));
  ok('  and reports the reduce flag', await rm.evaluate(() => window.__gamma.reduce === true));
  const t = (await rm.textContent('#tally')).trim();
  ok('  and its check panel still passes', /^(\d+) \/ \1 checks pass$/.test(t), t);
  await rm.close();
}

await browser.close();
server.close();
console.log(`\n${fails === 0 ? 'ALL CHECKS PASSED' : `${fails} CHECK(S) FAILED`}`);
process.exit(fails === 0 ? 0 : 1);
