#!/usr/bin/env node
// verify-the-two-tables.mjs
//
// Re-derives every number /strata/the-two-tables/ displays, from the data the page
// itself ships, and then reads the rendered figures back OUT of the HTML and requires
// them to equal what was computed here. Exits non-zero on any disagreement.
//
//   node research/the-two-tables/verify-the-two-tables.mjs
//
// PROTOCOL, FIXED BEFORE ANY RESULT WAS SEEN (2026-08-30):
//   object      USDA FSIS Revised Appendix A, Table 3 (chicken) and Table 4 (turkey),
//               the dwell times for a 7-log Salmonella reduction, 136 to 165 F, 1 to 12% fat.
//   anchor      Juneja, Eblen & Marks 2001b report z = 5.5 C for ground chicken and
//               6.1 C for ground turkey, measured on survival curves in a laboratory.
//               One unchanged regression of each published table must land on each,
//               within 2%, and must FAIL when the two anchors are swapped.
//   claim       No model of the form t(T) = sum_k c_k 10^(-(T-Tref)/z_k), c_k >= 0,
//               reproduces Table 3. Tested two ways that share no code: a convexity
//               inequality over three cells, and an exhaustive feasibility search over
//               the two-term family for the strongest triple.
//   success     every assertion below passes and every figure in the page's prose
//               equals the value computed here.
//
// The independent routes, ranked as the house ranks them:
//   * a published value measured by a different method on different material (Juneja's z),
//     which cannot be tuned to because tuning it would not move the table;
//   * a different KIND of statement about the same quantity (an inequality against a
//     search over the whole family);
//   * a different algorithm (golden-section on z, against the page's normal equations;
//     gamma quantiles, against the page's closed form and quadrature);
//   * poison controls that must be REJECTED, including a control on the rounding
//     accounting itself, which is the only thing standing between the convexity scan
//     and a meaningless number.

import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import { execFileSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';

const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, '..', '..');
const PAGE = path.join(ROOT, 'public', 'strata', 'the-two-tables', 'index.html');
const MD   = path.join(ROOT, 'src', 'content', 'strata', 'the-two-tables.md');
const DATA = path.join(HERE, 'data');

let pass = 0, fail = 0, skip = 0;
const F = (x, d) => x.toFixed(d);
const grp = n => String(n).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
function ok(name, cond, detail) {
  const tag = cond ? 'PASS' : 'FAIL';
  if (cond) pass++; else fail++;
  console.log(`${tag} ${String(pass + fail).padStart(3, '0')}  ${name}${detail ? '  ' + detail : ''}`);
}
function note(txt) { console.log(`  ..  ${txt}`); }
function skipped(name, why) { skip++; console.log(`SKIP ---  ${name}  ${why}`); }

// ─────────────────────────────────────────────────────────────────────────────
// 0. the page, and the data it ships
// ─────────────────────────────────────────────────────────────────────────────
const html = fs.readFileSync(PAGE, 'utf8');
const htmlFlat = html.replace(/\s+/g, ' ');   // prose wraps across source lines

function tableFromPage(name) {
  const m = new RegExp('var ' + name + ' = \\[([\\s\\S]*?)\\n    \\];').exec(html);
  if (!m) throw new Error('could not find the ' + name + ' data block in the page');
  return m[1].split('\n').map(s => s.trim().replace(/^'/, '').replace(/',?$/, '')).filter(Boolean);
}
// A printed cell is an interval, not a number. "13 min" is 12.5..13.5 min.
function cellOf(s) {
  s = s.trim();
  if (s === '0') return null;
  const m = /^([0-9.]+)\s*(min|sec)$/.exec(s);
  if (!m) throw new Error('unparsable cell ' + JSON.stringify(s));
  const k = m[2] === 'min' ? 60 : 1;
  const ulp = m[1].includes('.') ? 0.1 : 1.0;
  return { t: parseFloat(m[1]) * k, h: (ulp / 2) * k, txt: s };
}
function parseRows(lines) {
  return lines.map(line => {
    const p = line.split('|');
    return { F: parseInt(p[0], 10), cells: p.slice(1).map(cellOf) };
  });
}
const TAB3 = parseRows(tableFromPage('T3'));
const TAB4 = parseRows(tableFromPage('T4'));
const col = (tab, j) => tab.filter(r => r.cells[j]).map(r => ({ F: r.F, ...r.cells[j] }));

ok('page ships 30 chicken rows and 30 turkey rows of 12 fat columns',
   TAB3.length === 30 && TAB4.length === 30 && TAB3.every(r => r.cells.length === 12),
   `chicken ${TAB3.length}, turkey ${TAB4.length}`);

// the pinned transcription must be byte-identical in meaning to the page's own block,
// or the page and the record have drifted apart the way a JSON island always eventually does
{
  const pinned = JSON.parse(fs.readFileSync(path.join(DATA, 'fsis-appendix-a-tables.json'), 'utf8'));
  const cmp = (rows, tab, label) => {
    let bad = 0, cells = 0;
    rows.forEach((r, i) => r.cells.forEach((c, j) => {
      cells++;
      const pageTxt = tab[i].cells[j] ? tab[i].cells[j].txt : '0 sec.**';
      const pinTxt = c === '0 sec.**' ? '0 sec.**' : c;
      if (tab[i].F !== r.F || pageTxt !== pinTxt) bad++;
    }));
    ok(`${label}: the page's data block matches the pinned transcription cell for cell`, bad === 0,
       `${cells - bad}/${cells} identical`);
  };
  cmp(pinned.tables.table3_chicken.rows, TAB3, 'chicken');
  cmp(pinned.tables.table4_turkey.rows, TAB4, 'turkey');
}

// THE INDEPENDENT TRANSCRIPTION. Michigan State University Extension published the same
// FSIS poultry tables in a document that HAS a text layer. canr.msu.edu answers a fetcher
// with an Incapsula interstitial, but the Internet Archive's copy resolves. This is the one
// check that can catch a systematic misreading of a glyph that both visual readings share.
{
  const f = path.join(DATA, 'msu-transcription.json');
  if (fs.existsSync(f)) {
    const msu = JSON.parse(fs.readFileSync(f, 'utf8'));
    const norm = c => c.startsWith('0 sec') ? 'ZERO' : c.replace(/\s+/g, ' ').trim();
    let cells = 0, bad = [], unmatched = 0;
    for (const [tab, idx] of [[TAB3, 0], [TAB4, 1]]) {
      tab.forEach(r => r.cells.forEach((c, j) => {
        const row = msu[String(j + 1)] && msu[String(j + 1)][String(r.F)];
        if (!row) { unmatched++; return; }
        cells++;
        const mine = c ? norm(c.txt) : 'ZERO';
        if (mine !== row[idx]) bad.push(`${idx ? 'turkey' : 'chicken'} ${r.F}F/${j + 1}%: ours "${mine}" theirs "${row[idx]}"`);
      }));
    }
    // pin the independent source the way the primary one is pinned: an unpinned file that
    // the suite trusts is a file that can drift underneath the check that trusts it.
    {
      const pdf = path.join(DATA, 'msu.pdf');
      const WANT_MSU = '81cac42cdbf2df32522d1b84561cd675772fa29e31523fb70e4c5e80d18d6732';
      if (fs.existsSync(pdf)) {
        const got = crypto.createHash('sha256').update(fs.readFileSync(pdf)).digest('hex');
        ok('the independent MSU transcription PDF has the recorded SHA-256', got === WANT_MSU, got.slice(0, 16) + '...');
      } else {
        skipped('MSU PDF hash', 'data/msu.pdf absent; refetch via the Internet Archive copy named in the README');
      }
    }
    ok('every cell agrees with an INDEPENDENT text-layer transcription (MSU Extension, via the Internet Archive)',
       bad.length === 0 && unmatched === 0 && cells === 720,
       bad.length ? bad.slice(0, 4).join('; ') : `${cells} of 720 cells, chicken and turkey`);
    // and the convention behind the zeros, which changes what the top of the table means
    const zeros = [];
    for (const [tab, idx] of [[TAB3, 0]]) tab.forEach(r => r.cells.forEach((c, j) => {
      if (!c) { const row = msu[String(j + 1)][String(r.F)]; zeros.push(row[idx]); }
    }));
    /* AND THE PAGE MUST NOT CONTRADICT ITSELF ABOUT IT. The body said the MSU transcription
     was reached and all 720 cells agree; the limitations section still said no third
     transcription was reachable. A reader who reads both is misled about what was checked,
     and a stale caveat that survives the arrival of its own evidence is the easiest kind of
     dishonesty to ship by accident. */
  // matched on the reader's text, with tags stripped, because the body's figure is wrapped
  const readerText = html
    .replace(/<script[\s\S]*?<\/script>/gi, ' ').replace(/<style[\s\S]*?<\/style>/gi, ' ')
    .replace(/<!--[\s\S]*?-->/g, ' ').replace(/<[^>]*>/g, ' ')
    .replace(/&nbsp;| /g, ' ').replace(/\s+/g, ' ');
  const agreeClaims = (readerText.match(/720 chicken and turkey cells agree/gi) || []).length;
  ok('and the page does not also claim, further down, that no independent transcription was reachable',
     !/no third transcription was reachable/i.test(readerText) && agreeClaims === 2,
     `body and limitations tell the same story about the MSU cross-check (${agreeClaims} statements of it, no contradiction)`);
  ok('the "0 sec." cells are printed "<10.0 sec" in the independent transcription, so they are a display floor',
       zeros.length > 0 && zeros.every(z => z === 'ZERO'),
       `${zeros.length} zero cells, all rendered as the sub-ten-second marker there`);
  } else {
    skipped('independent MSU transcription', 'data/msu-transcription.json absent; refetch https://web.archive.org/web/2023/https://www.canr.msu.edu/smprv/uploads/files/RTE_Poultry_Tables1.pdf and re-parse');
  }
}

// the primary source, if it is on disk
{
  const pdf = path.join(DATA, 'AppendixA-2021.pdf');
  const WANT = '1b0ff239bd626c278625be30d93c2dc4a0bbc6d1510b5c8047745a5bbf557050';
  if (fs.existsSync(pdf)) {
    const got = crypto.createHash('sha256').update(fs.readFileSync(pdf)).digest('hex');
    ok('pinned FSIS Appendix A PDF has the recorded SHA-256', got === WANT, got.slice(0, 16) + '...');
  } else {
    skipped('pinned FSIS PDF hash', 'data/AppendixA-2021.pdf is not present; re-fetch it from https://www.ncagr.gov/meat-poultry-inspection/Appendix-A12-2021/download');
  }
}

// ─────────────────────────────────────────────────────────────────────────────
// 1. THE PUBLISHED ANCHOR, and a fitter written a different way from the page's
// ─────────────────────────────────────────────────────────────────────────────
// The page fits z by the closed-form normal equations. This is a golden-section
// search on z that minimises the same sum of squares by a different algorithm, so a
// slip in either one shows up as a disagreement rather than as agreement with itself.
const log10 = x => Math.log10(x);
function sseAt(pts, z) {
  // for a given z the best intercept is the mean of log10 t + (T - T0)/z
  const T0 = pts[0].F;
  let m = 0;
  for (const p of pts) m += log10(p.t) + (p.F - T0) / z;
  m /= pts.length;
  let s = 0;
  for (const p of pts) { const d = m - (p.F - T0) / z - log10(p.t); s += d * d; }
  return { sse: s, a: m, predict: FF => Math.pow(10, m - (FF - T0) / z) };
}
function fitZGolden(pts) {
  let lo = 2, hi = 40;
  const phi = (Math.sqrt(5) - 1) / 2;
  let c = hi - phi * (hi - lo), d = lo + phi * (hi - lo);
  for (let i = 0; i < 400; i++) {
    if (sseAt(pts, c).sse < sseAt(pts, d).sse) { hi = d; } else { lo = c; }
    c = hi - phi * (hi - lo); d = lo + phi * (hi - lo);
  }
  const z = (lo + hi) / 2;
  return { z, ...sseAt(pts, z) };
}
function fitZNormal(pts) {                       // the page's route, re-coded
  const n = pts.length;
  let mx = 0, my = 0;
  for (const p of pts) { mx += p.F; my += log10(p.t); }
  mx /= n; my /= n;
  let sxy = 0, sxx = 0;
  for (const p of pts) { sxy += (p.F - mx) * (log10(p.t) - my); sxx += (p.F - mx) ** 2; }
  const b = sxy / sxx, a = my - b * mx;
  return { z: -1 / b, a, predict: FF => Math.pow(10, a + b * FF) };
}
const C3 = [], C4 = [];
for (let j = 0; j < 12; j++) { C3.push(col(TAB3, j)); C4.push(col(TAB4, j)); }
const gA = fitZGolden(C3[0]), nA = fitZNormal(C3[0]);
ok('two different fitting algorithms agree on z to 1e-6 relative',
   Math.abs(gA.z / nA.z - 1) < 1e-6, `golden ${F(gA.z, 6)} F, normal equations ${F(nA.z, 6)} F`);

const PUB_Z_CHICKEN_C = 5.5, PUB_Z_TURKEY_C = 6.1;   // Juneja, Eblen & Marks 2001b
const zChick = fitZGolden(C3[0]).z * 5 / 9, zTurk = fitZGolden(C4[0]).z * 5 / 9;
const rel = (a, b) => Math.abs(a / b - 1);
ok('chicken table regresses to Juneja 2001b published z within 2%',
   rel(zChick, PUB_Z_CHICKEN_C) < 0.02,
   `${F(zChick, 4)} C vs published ${PUB_Z_CHICKEN_C} C, miss ${F(rel(zChick, PUB_Z_CHICKEN_C) * 100, 2)}%`);
ok('turkey table, same unmodified fitter, lands on the OTHER published z within 2%',
   rel(zTurk, PUB_Z_TURKEY_C) < 0.02,
   `${F(zTurk, 4)} C vs published ${PUB_Z_TURKEY_C} C, miss ${F(rel(zTurk, PUB_Z_TURKEY_C) * 100, 2)}%`);
// CONTROL ON THE CONTROL. The anchor above is only worth something if it can reject.
// The two published values are 0.6 C apart and the gate is worth about 0.11 C, so a
// fitter that ignored its input entirely could not pass both. Swap them: both must fail.
ok('control: each table judged against the OTHER species anchor fails the same gate',
   rel(zTurk, PUB_Z_CHICKEN_C) >= 0.02 && rel(zChick, PUB_Z_TURKEY_C) >= 0.02,
   `turkey vs chicken anchor ${F(rel(zTurk, PUB_Z_CHICKEN_C) * 100, 1)}%, chicken vs turkey anchor ${F(rel(zChick, PUB_Z_TURKEY_C) * 100, 1)}%`);
// and a fitter that returned a constant would pass the first and fail the second, so:
ok('control: a constant estimator is rejected',
   rel(5.5, PUB_Z_TURKEY_C) >= 0.02, 'a fitter always answering 5.5 C misses the turkey anchor by ' + F(rel(5.5, PUB_Z_TURKEY_C) * 100, 1) + '%');

// ─────────────────────────────────────────────────────────────────────────────
// 2. what the best possible one-term fit cannot do
// ─────────────────────────────────────────────────────────────────────────────
const fit0 = fitZGolden(C3[0]);
const RES0 = C3[0].map(p => ({ F: p.F, obs: p.t, pred: fit0.predict(p.F), r: fit0.predict(p.F) / p.t - 1, hu: p.h / p.t }));
const WORST0 = RES0.reduce((m, q) => Math.abs(q.r) > Math.abs(m.r) ? q : m, RES0[0]);
const overRounding = RES0.filter(q => Math.abs(q.r) > q.hu).length;
const ratio136 = Math.round(RES0.reduce((m, q) => Math.max(m, Math.abs(q.r) / q.hu), 0));
ok('the best one-term fit misses by more than 5% somewhere in the leanest column',
   Math.abs(WORST0.r) > 0.05,
   `worst ${F(Math.abs(WORST0.r) * 100, 2)}% at ${WORST0.F} F (table ${WORST0.obs} s, fit ${F(WORST0.pred, 1)} s)`);
ok('and most rows miss by more than their own printed rounding',
   overRounding > RES0.length / 2, `${overRounding} of ${RES0.length}; largest ratio to a cell's own rounding ${ratio136}x`);

// ─────────────────────────────────────────────────────────────────────────────
// 2b. THE FLOOR OF THE WORST ERROR. Least squares minimises the SUM of squared log
// residuals, which is not the same objective as the worst relative error, so its worst
// error is an upper bound on what the family can do and NOT the family's floor. The page
// quotes the minimax number; this recomputes it by a route the page does not use. The
// page ternary-searches the closed-form-in-C objective; this one brute-forces a fine grid
// over z AND, at each z, solves for the best C by bisection on the Chebyshev balance
// condition rather than by the closed form, so an error in that closed form shows up.
function worstRelAt(pts, z) {
  const u = pts.map(p => Math.pow(10, -p.F / z) / p.t);
  let lo = 1 / Math.max(...u), hi = 1 / Math.min(...u);      // brackets C
  for (let i = 0; i < 70; i++) {                             // bisect on max(+err) - max(-err)
    const C = (lo + hi) / 2;
    let hiE = -Infinity, loE = -Infinity;
    for (const uu of u) { const e = C * uu - 1; if (e > hiE) hiE = e; if (-e > loE) loE = -e; }
    if (hiE > loE) hi = C; else lo = C;
  }
  const C = (lo + hi) / 2;
  return { w: Math.max(...u.map(uu => Math.abs(C * uu - 1))), C };
}
function fitMinimaxGrid(pts) {
  // a coarse sweep to bracket, then golden-section inside the bracket. Neither step is the
  // page's route (it ternary-searches a closed form for C; this bisects the balance
  // condition instead), so a slip in the page's algebra shows up as a disagreement.
  let best = { w: Infinity, z: 0 }, prev = null, brackLo = 4, brackHi = 30;
  for (let z = 4; z <= 30; z += 0.005) {
    const r = worstRelAt(pts, z);
    if (r.w < best.w) { best = { w: r.w, z, C: r.C }; brackLo = prev === null ? 4 : prev; brackHi = z + 0.005; }
    prev = z;
  }
  const phi = (Math.sqrt(5) - 1) / 2;
  let a = brackLo, b = brackHi, c = b - phi * (b - a), d = a + phi * (b - a);
  for (let i = 0; i < 200; i++) {
    if (worstRelAt(pts, c).w < worstRelAt(pts, d).w) b = d; else a = c;
    c = b - phi * (b - a); d = a + phi * (b - a);
  }
  const z = (a + b) / 2, r = worstRelAt(pts, z);
  return r.w <= best.w ? { w: r.w, z, C: r.C } : best;
}
const MM = C3.map(fitMinimaxGrid);
const MM0 = MM[0];
const MMRES0 = C3[0].map(p => ({ F: p.F, obs: p.t, pred: MM0.C * Math.pow(10, -p.F / MM0.z), r: MM0.C * Math.pow(10, -p.F / MM0.z) / p.t - 1, hu: p.h / p.t }));
const MMWORST0 = MMRES0.reduce((m, q) => Math.abs(q.r) > Math.abs(m.r) ? q : m, MMRES0[0]);
const mmRatio = Math.round(MMRES0.reduce((m, q) => Math.max(m, Math.abs(q.r) / q.hu), 0));
let MMBEST = 0; for (let j = 1; j < 12; j++) if (MM[j].w < MM[MMBEST].w) MMBEST = j;
ok('the minimax fit of the same one-term family beats least squares on the worst error, so the least-squares number is NOT the family floor',
   MM0.w < Math.abs(WORST0.r) - 1e-6,
   `minimax ${F(MM0.w * 100, 4)}% at z = ${F(MM0.z, 4)} F, against least squares ${F(Math.abs(WORST0.r) * 100, 4)}%`);
ok('and that floor is still far outside what the table s own printed rounding allows',
   MM0.w > 0.05 && MMRES0.filter(q => Math.abs(q.r) > q.hu).length > MMRES0.length / 2,
   `${MMRES0.filter(q => Math.abs(q.r) > q.hu).length} of ${MMRES0.length} rows outside their own rounding; largest ratio ${mmRatio}x`);
// CONTROL: minimax must be a floor, so NO other setting of the two parameters may beat it.
// A dense random search that found something lower would mean the quoted floor is wrong.
{
  let seed = 7654321; const rnd = () => (seed = (seed * 1103515245 + 12345) % 2147483648) / 2147483648;
  let bestFound = Infinity;
  for (let i = 0; i < 200000; i++) {
    const z = 4 + rnd() * 26, u = C3[0].map(p => Math.pow(10, -p.F / z) / p.t);
    const C = (1 / Math.max(...u)) + rnd() * ((1 / Math.min(...u)) - (1 / Math.max(...u)));
    const w = Math.max(...u.map(uu => Math.abs(C * uu - 1)));
    if (w < bestFound) bestFound = w;
  }
  ok('control: 200,000 random (z, C) pairs find nothing below the minimax floor, as a floor requires',
     bestFound >= MM0.w - 1e-9,
     `best random ${F(bestFound * 100, 4)}% against the claimed floor ${F(MM0.w * 100, 4)}%`);
}
{
  // the Chebyshev characterisation, which is what makes this fit the minimax one and the
  // only property that notices a wrong constant of proportionality (the worst-error
  // formula itself does not depend on it, so nothing else here would see that error).
  const pos = Math.max(...MMRES0.map(q => q.r)), neg = Math.max(...MMRES0.map(q => -q.r));
  ok('the minimax fit is balanced, so it is genuinely the Chebyshev optimum and not merely close to it',
     Math.abs(pos - neg) < 1e-9 && Math.abs(pos - MM0.w) < 1e-9,
     `largest over-estimate ${F(pos * 100, 6)}%, largest under-estimate ${F(neg * 100, 6)}%, equal to ${Math.abs(pos - neg).toExponential(1)}`);
  // CONTROL: nudge the constant and the balance must break, or the test is decorative
  const bad = MM0.C * 1.001, u = C3[0].map(p => Math.pow(10, -p.F / MM0.z) / p.t);
  const bPos = Math.max(...u.map(uu => bad * uu - 1)), bNeg = Math.max(...u.map(uu => 1 - bad * uu));
  ok('control: a constant of proportionality out by one part in a thousand breaks that balance',
     Math.abs(bPos - bNeg) > 1e-4, `nudged constant gives ${F(bPos * 100, 4)}% against ${F(bNeg * 100, 4)}%`);
}
ok('no fat column does better: the leanest one is not the column picked to flatter the argument',
   MM[MMBEST].w > 0.05 && MMBEST !== 0,
   `smallest worst error over all twelve columns is ${F(MM[MMBEST].w * 100, 2)}% at ${MMBEST + 1}% fat; leanest column ${F(MM0.w * 100, 2)}%`);

// exact Wald-Wolfowitz runs distribution, computed with integer binomials
const nCk = (n, k) => { if (k < 0 || k > n) return 0; let r = 1; for (let i = 0; i < k; i++) r = r * (n - i) / (i + 1); return r; };
function runsPLE(n1, n2, R0) {
  const tot = nCk(n1 + n2, n1); let s = 0;
  for (let r = 2; r <= R0; r++) {
    if (r % 2 === 0) { const k = r / 2; s += 2 * nCk(n1 - 1, k - 1) * nCk(n2 - 1, k - 1); }
    else { const k = (r - 1) / 2; s += nCk(n1 - 1, k) * nCk(n2 - 1, k - 1) + nCk(n1 - 1, k - 1) * nCk(n2 - 1, k); }
  }
  return s / tot;
}
const signs = RES0.map(q => q.r > 0 ? 1 : -1);
const nPos = signs.filter(s => s > 0).length, nNeg = signs.length - nPos;
let RUNS = 1; for (let i = 1; i < signs.length; i++) if (signs[i] !== signs[i - 1]) RUNS++;
const pRuns = runsPLE(nPos, nNeg, RUNS);
// the same structure under the MINIMAX fit, because a claim that the signs are structured
// must not depend on which of the two fits happens to have been used.
const mmRuns = (() => {
  const sg = MMRES0.map(q => q.r > 0 ? 1 : -1);
  let R = 1, n1 = 0;
  for (let i = 0; i < sg.length; i++) { if (sg[i] > 0) n1++; if (i && sg[i] !== sg[i - 1]) R++; }
  return { R, n1, n2: sg.length - n1, p: runsPLE(n1, sg.length - n1, R) };
})();
// which rows a fit asks LESS time for than the table does: the direction that matters
const bandOf = res => { const n = res.filter(q => q.r < 0).map(q => q.F); return n.length ? { lo: Math.min(...n), hi: Math.max(...n) } : { lo: 0, hi: 0 }; };
const band0 = bandOf(RES0), mmBand0 = bandOf(MMRES0);
const firstAllZero = (TAB3.find(r => r.cells.every(c => !c)) || { F: 0 }).F;
ok('the residual sign structure survives refitting for the smallest worst error, so it is not an artefact of least squares',
   mmRuns.p < 1e-3 && mmRuns.R <= 4,
   `minimax fit: ${mmRuns.n1} positive, ${mmRuns.n2} negative, ${mmRuns.R} runs, 1 in ${grp(Math.round(1 / mmRuns.p))}`);
ok('the consumer margin is derived from the table, not asserted: 165 F against the first row that prints no dwell time anywhere',
   firstAllZero === 163 && 165 - firstAllZero === 2,
   `first all-zero row is ${firstAllZero} F, so the margin is ${165 - firstAllZero} F`);
// a control on the runs machinery: a genuinely alternating sequence must be ordinary
ok('runs statistic: the residual signs are far from a coin toss',
   pRuns < 1e-3, `${nPos} positive, ${nNeg} negative, ${RUNS} runs, exact P(R<=${RUNS}) = ${pRuns.toExponential(2)} (1 in ${grp(Math.round(1 / pRuns))})`);
{
  // brute-force the same probability by exhaustive enumeration of all sign patterns
  // with the same counts. A different algorithm for the same number.
  let hits = 0, tot = 0;
  const n = signs.length;
  const rec = (i, left, seq) => {
    if (i === n) { tot++; let R = 1; for (let k = 1; k < n; k++) if (seq[k] !== seq[k - 1]) R++; if (R <= RUNS) hits++; return; }
    if (left > 0) { seq.push(1); rec(i + 1, left - 1, seq); seq.pop(); }
    if (n - i - left > 0) { seq.push(-1); rec(i + 1, left, seq); seq.pop(); }
  };
  rec(0, nPos, []);
  ok('runs probability confirmed by exhaustive enumeration of every arrangement',
     Math.abs(hits / tot - pRuns) < 1e-12, `${grp(hits)} of ${grp(tot)} arrangements = ${(hits / tot).toExponential(2)}`);
}

// ─────────────────────────────────────────────────────────────────────────────
// 3. THE SHAPE TEST, and a completely different kind of statement about it
// ─────────────────────────────────────────────────────────────────────────────
// Route A, the page's: every t(T) = sum_k c_k 10^(-(T-Tref)/z_k) with c_k >= 0 is a
// log-sum-exp of affine functions, hence convex in (T, log t). A convex curve never
// rises above its own chord, so a middle cell whose SMALLEST allowed value exceeds the
// chord through the outer cells' LARGEST allowed values excludes the whole family.
function triple(a, b, c) {
  const lam = (b.F - a.F) / (c.F - a.F);
  const loMid = log10(b.t - b.h), hiChord = (1 - lam) * log10(a.t + a.h) + lam * log10(c.t + c.h);
  const hiMid = log10(b.t + b.h), loChord = (1 - lam) * log10(a.t - a.h) + lam * log10(c.t - c.h);
  return { gap: loMid - hiChord, cap: Math.pow(10, hiChord), floorMid: b.t - b.h,
           verdict: loMid - hiChord > 0 ? 'violates' : (hiMid - loChord <= 0 ? 'consistent' : 'undecidable') };
}
function scan(tab) {
  let viol = 0, cons = 0, und = 0, best = null;
  for (let j = 0; j < 12; j++) {
    const c = col(tab, j);
    for (let a = 0; a < c.length; a++) for (let b = a + 1; b < c.length; b++) for (let d = b + 1; d < c.length; d++) {
      const r = triple(c[a], c[b], c[d]);
      if (r.verdict === 'violates') { viol++; if (!best || r.gap > best.gap) best = { ...r, fat: j + 1, A: c[a], B: c[b], C: c[d] }; }
      else if (r.verdict === 'consistent') cons++; else und++;
    }
  }
  return { viol, cons, und, total: viol + cons + und, best };
}
const S3 = scan(TAB3), S4 = scan(TAB4);
ok('convexity scan of Table 3 finds violations beyond the printed rounding',
   S3.viol > 1000, `${grp(S3.viol)} violate of ${grp(S3.total)} triples`);
// The refusal count needs an anchor from OUTSIDE scan(), which DEFINES total as
// viol+cons+und: asserting that sum against that total is x === x and can never fail.
// The independent number is combinatorial: the sum over the columns of "n choose 3".
function tripleCount(tab) {
  let t = 0;
  for (let j = 0; j < 12; j++) { const n = col(tab, j).length; t += n * (n - 1) * (n - 2) / 6; }
  return t;
}
const EXP3 = tripleCount(TAB3), EXP4 = tripleCount(TAB4);
ok('every triple is accounted for: violating + consistent + undecidable = the count the column lengths demand',
   S3.viol + S3.cons + S3.und === EXP3 && S4.viol + S4.cons + S4.und === EXP4 && EXP3 === 33150 && EXP4 === 43848,
   `${grp(S3.viol)} violate, ${grp(S3.cons)} consistent, ${grp(S3.und)} undecidable, summing to the ${grp(EXP3)} that sum-of-C(n,3) requires (turkey ${grp(EXP4)})`);
ok('Table 4 (turkey), transcribed separately, shows the same thing',
   S4.viol > 1000, `${grp(S4.viol)} of ${grp(S4.total)}`);
note(`strongest chicken triple: ${S3.best.fat}% fat at ${S3.best.A.F}/${S3.best.B.F}/${S3.best.C.F} F, ` +
     `middle cell >= ${F(S3.best.floorMid, 1)} s against a convex cap of ${F(S3.best.cap, 1)} s ` +
     `(excess ${F(S3.best.floorMid / S3.best.cap, 2)}x)`);

// Route B, an entirely different KIND of statement: forget the inequality and SEARCH.
// For a grid of (z1, z2), the two-term family is linear in (c1, c2), so feasibility
// inside the three published rounding boxes is a two-variable linear program. Enumerate
// its vertices exactly. If no (z1, z2) anywhere on a wide grid admits a feasible
// (c1, c2), the family really is excluded, and nothing about convexity was used.
function feasible2D(cons) {                       // cons: [p, q, r] meaning p*c1 + q*c2 <= r
  const EPS = 1e-7;
  const satisfies = (x, y) => cons.every(([p, q, r]) => p * x + q * y <= r + EPS * (1 + Math.abs(r)));
  for (let i = 0; i < cons.length; i++) for (let j = i + 1; j < cons.length; j++) {
    const [p1, q1, r1] = cons[i], [p2, q2, r2] = cons[j];
    const det = p1 * q2 - p2 * q1;
    if (Math.abs(det) < 1e-14) continue;
    const x = (r1 * q2 - r2 * q1) / det, y = (p1 * r2 - p2 * r1) / det;
    if (x >= -EPS && y >= -EPS && satisfies(x, y)) return { x, y };
  }
  return null;
}
function anyTwoTermFits(cells, nz = 160) {
  const T0 = cells[0].F;
  for (let i = 0; i < nz; i++) {
    const z1 = 3 * Math.pow(60 / 3, i / (nz - 1));
    for (let j = 0; j < nz; j++) {
      const z2 = 3 * Math.pow(60 / 3, j / (nz - 1));
      const cons = [[-1, 0, 0], [0, -1, 0]];
      let bad = false;
      for (const c of cells) {
        const a = Math.pow(10, -(c.F - T0) / z1), b = Math.pow(10, -(c.F - T0) / z2);
        if (!isFinite(a) || !isFinite(b)) { bad = true; break; }
        cons.push([a, b, c.t + c.h], [-a, -b, -(c.t - c.h)]);
      }
      if (bad) continue;
      const s = feasible2D(cons);
      if (s) return { z1, z2, c1: s.x, c2: s.y };
    }
  }
  return null;
}
{
  const b = S3.best;
  const hit = anyTwoTermFits([b.A, b.B, b.C]);
  ok('search route: no two-term model anywhere on a 160x160 grid of z pairs fits the strongest triple',
     hit === null, `${b.A.F}/${b.B.F}/${b.C.F} F at ${b.fat}% fat, z searched over 3 to 60 F`);
  // POSITIVE CONTROL on the search: three cells taken FROM a two-term model must be found.
  const T0 = b.A.F;
  const gen = FF => 1200 * Math.pow(10, -(FF - T0) / 14) + 2800 * Math.pow(10, -(FF - T0) / 9);
  const synth3 = [b.A, b.B, b.C].map(c => ({ F: c.F, t: gen(c.F), h: gen(c.F) * 0.01 }));
  const found = anyTwoTermFits(synth3);
  ok('control on the search: three cells generated FROM a two-term model ARE found feasible',
     found !== null, found ? `recovered z = ${F(found.z1, 2)} and ${F(found.z2, 2)} F` : 'nothing found, so the search is broken');
  // and a third route, agreeing with the first: the middle cell is above the chord
  ok('the two routes agree on this triple', b.gap > 0 && hit === null,
     `inequality gap ${F(b.gap, 4)} in log10 seconds, search exhausted`);
}

// POISON CONTROLS on the scan. Tables generated FROM the excluded family, printed to the
// guideline's own precision, must yield ZERO violations, or the counts above are an
// artefact of the rounding arithmetic and mean nothing. Then bend z with temperature and
// require the same scanner to fire.
function fsisFormat(secs) {
  const v = secs >= 60 ? secs / 60 : secs, u = secs >= 60 ? ' min' : ' sec';
  let s = v.toFixed(1); if (s.endsWith('.0')) s = s.slice(0, -2);
  return s + u;
}
function synthTable(fn) {
  const rows = [];
  for (let FF = 136; FF <= 165; FF++) {
    const cells = [];
    for (let k = 0; k < 12; k++) { const t = fn(FF, k); cells.push(t >= 1 ? fsisFormat(t) : '0'); }
    rows.push(`${FF}|${cells.join('|')}`);
  }
  return parseRows(rows);
}
{
  let worst = 0;
  for (const [c1, z1, c2, z2] of [[1200, 14, 2800, 9], [300, 20, 3700, 9.78], [2000, 9, 2000, 13], [0, 10, 4017, 9.78], [500, 25, 3500, 8.5]]) {
    const s = scan(synthTable((FF, k) => (1 + 0.03 * k) * (c1 * Math.pow(10, -(FF - 136) / z1) + c2 * Math.pow(10, -(FF - 136) / z2))));
    worst = Math.max(worst, s.viol);
  }
  ok('control on the control: five tables built FROM the excluded family produce zero violations',
     worst === 0, `worst count ${worst}; the rounding accounting does not manufacture violations`);
  const red = scan(synthTable((FF, k) => (1 + 0.03 * k) * 4000 * Math.pow(10, -(FF - 136) / (9 + 2 * Math.exp(-(((FF - 147) / 6) ** 2))))));
  ok('and the same scanner fires on a table whose z bends with temperature',
     red.viol > 1000, `${grp(red.viol)} violations: the instrument can go red`);
  // the sharpest control of the three: break the rounding accounting and the poison must fail
  const savedH = [];
  const flat = synthTable((FF, k) => (1 + 0.03 * k) * (1200 * Math.pow(10, -(FF - 136) / 14) + 2800 * Math.pow(10, -(FF - 136) / 9)));
  flat.forEach(r => r.cells.forEach(c => { if (c) { savedH.push(c.h); c.h = 0; } }));
  const brokenRounding = scan(flat);
  ok('control: with the printed rounding zeroed, the SAME scanner falsely convicts a convex table',
     brokenRounding.viol > 100,
     `${grp(brokenRounding.viol)} false violations, which is why the rounding interval is load bearing`);
}

// ─────────────────────────────────────────────────────────────────────────────
// 4. the film integrals, by a THIRD route the page does not use
// ─────────────────────────────────────────────────────────────────────────────
const REF_DOSE = 2;
const spfClosed = (A, mu, c2) => c2 < 1e-12 ? Math.exp(A * mu) : Math.pow(1 + A * mu * c2, 1 / c2);
const calibA = (L, c2) => c2 < 1e-12 ? Math.log(L) / REF_DOSE : (Math.pow(L, c2) - 1) / (REF_DOSE * c2);
const evenFilm = (L, dose) => Math.pow(L, dose / REF_DOSE);

// Route: build the film out of equal-probability quantiles of the gamma distribution
// and average exp(-A d) over those pixels. No Laplace transform, no closed form: it is a
// film, summed. The incomplete gamma is inverted by bisection on its series and
// continued-fraction evaluation.
function lowerRegGamma(k, x) {
  if (x <= 0) return 0;
  const lg = lgammaFn(k);
  if (x < k + 1) {
    let ap = k, s = 1 / k, del = s;
    for (let i = 0; i < 4000; i++) { ap += 1; del *= x / ap; s += del; if (Math.abs(del) < Math.abs(s) * 1e-16) break; }
    return s * Math.exp(-x + k * Math.log(x) - lg);
  }
  let b = x + 1 - k, c = 1e300, d = 1 / b, h = d;
  for (let i = 1; i < 4000; i++) {
    const an = -i * (i - k); b += 2; d = an * d + b; if (Math.abs(d) < 1e-300) d = 1e-300;
    c = b + an / c; if (Math.abs(c) < 1e-300) c = 1e-300;
    d = 1 / d; const de = d * c; h *= de; if (Math.abs(de - 1) < 1e-16) break;
  }
  return 1 - Math.exp(-x + k * Math.log(x) - lg) * h;
}
function lgammaFn(x) {
  const g = [676.5203681218851, -1259.1392167224028, 771.32342877765313, -176.61502916214059,
             12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7];
  if (x < 0.5) return Math.log(Math.PI / Math.sin(Math.PI * x)) - lgammaFn(1 - x);
  x -= 1; let a = 0.99999999999980993; const t = x + 7.5;
  for (let i = 0; i < 8; i++) a += g[i] / (x + i + 1);
  return 0.5 * Math.log(2 * Math.PI) + (x + 0.5) * Math.log(t) - t + Math.log(a);
}
function gammaQuantile(k, p) {
  let lo = 1e-14, hi = 1;
  while (lowerRegGamma(k, hi) < p && hi < 1e12) hi *= 2;
  for (let i = 0; i < 200; i++) { const m = (lo + hi) / 2; if (lowerRegGamma(k, m) < p) lo = m; else hi = m; }
  return (lo + hi) / 2;
}
// A film that does not merely thin: a fraction 'frac' of the reference dose spread over
// only 'cover' of the area, the rest bare. This is the case the floor does NOT cover.
const patchySPF = (label, frac, cover) => {
  const Ae = Math.log(label) / REF_DOSE;
  return 1 / (cover * Math.exp(-Ae * REF_DOSE * frac / cover) + (1 - cover));
};
function spfPixels(A, mu, c2, N = 4000) {
  const k = 1 / c2, th = mu * c2;
  let s = 0;
  for (let i = 0; i < N; i++) s += Math.exp(-A * th * gammaQuantile(k, (i + 0.5) / N));
  return N / s;
}
{
  const cases = [[34.5, 0.5, 1], [3, 2, 2.25], [20, 1, 4], [38.79, 0.5, 1.0353]];
  let worst = 0;
  for (const [A, mu, c2] of cases) worst = Math.max(worst, rel(spfPixels(A, mu, c2), spfClosed(A, mu, c2)));
  ok('a film summed pixel by pixel over gamma quantiles reproduces the closed form',
     worst < 1e-4, `${cases.length} cases at roughness c >= 1, worst disagreement ${worst.toExponential(1)}`);
  // THE REFUSAL PATH, asserted rather than hidden: at low roughness with a strong
  // absorber the answer lives in the thinnest patches, and a 4000-pixel film cannot
  // resolve it. The page says so; here is the measurement behind that sentence.
  const bad = rel(spfPixels(50, 0.8, 0.09), spfClosed(50, 0.8, 0.09));
  ok('and the same routine visibly FAILS where a finite film cannot resolve the answer',
     bad > 0.5, `at c^2 = 0.09 the pixel film is out by ${F(bad * 100, 0)}%, because the thin patches carry the integral`);
}

// ─────────────────────────────────────────────────────────────────────────────
// 5. the floor, and the published in-vivo anchors
// ─────────────────────────────────────────────────────────────────────────────
// Ou-Yang, Stanfield, Cole, Appa & Rigel, J Am Acad Dermatol 2012 (PMID 22463921):
// products labelled SPF 70 and 100, applied at 0.5 mg/cm2, measured 19 and 27 in vivo.
const OUYANG = [{ label: 70, spf: 19 }, { label: 100, spf: 27 }];
{
  const lin70 = spfClosed(calibA(70, 1), 0.5, 1), lin100 = spfClosed(calibA(100, 1), 0.5, 1);
  ok('an exponentially rough film, one parameter fixed by the label alone, predicts both measurements within 8%',
     rel(lin70, 19) < 0.08 && rel(lin100, 27) < 0.08,
     `${F(lin70, 3)} vs 19 (${F(rel(lin70, 19) * 100, 1)}%), ${F(lin100, 3)} vs 27 (${F(rel(lin100, 27) * 100, 1)}%)`);
  ok('the even-film rule, on the same two products, is out by a factor of six or more',
     19 / evenFilm(70, 0.5) > 6 && 27 / evenFilm(100, 0.5) > 6,
     `${F(19 / evenFilm(70, 0.5), 2)}x and ${F(27 / evenFilm(100, 0.5), 2)}x`);
  ok('and for the even-film rule to be right, an SPF 70 product would have to test at 130,321',
     Math.round(Math.pow(19, 4)) === 130321, `19^4 = ${grp(Math.round(Math.pow(19, 4)))}`);
}
{
  // The floor holds for EVERY film-thickness distribution, by log-convexity of the
  // moment generating function. Tested on random discrete films the closed form never sees.
  let seed = 20260830;
  const rnd = () => { seed = (seed * 1103515245 + 12345) % 2147483648; return seed / 2147483648; };
  let trials = 0, viol = 0, tight = 0, minRatio = Infinity;
  for (let it = 0; it < 40000; it++) {
    const n = 1 + Math.floor(rnd() * 8), w = [], d = [];
    let sw = 0;
    for (let i = 0; i < n; i++) { const u = rnd(); w.push(u); sw += u; d.push(rnd() * [0.2, 1, 5, 20][Math.floor(rnd() * 4)]); }
    for (let i = 0; i < n; i++) w[i] /= sw;
    const A = rnd() * [0.5, 2, 10, 40][Math.floor(rnd() * 4)] + 0.01;
    let g1 = 0; for (let i = 0; i < n; i++) g1 += w[i] * Math.exp(-A * d[i]);
    if (!(g1 > 1e-12 && g1 < 1)) continue;
    const L = 1 / g1; if (L < 1.0001 || L > 1e12) continue;
    const s = rnd();
    let gs = 0; for (let i = 0; i < n; i++) gs += w[i] * Math.exp(-A * s * d[i]);
    if (!(gs > 1e-12)) continue;
    const ratio = (1 / gs) / Math.pow(L, s);
    trials++; if (ratio < 1 - 1e-9) viol++; if (Math.abs(ratio - 1) < 1e-9) tight++;
    minRatio = Math.min(minRatio, ratio);
  }
  ok('the floor SPF(2s) >= label^s held on every random film distribution tested',
     viol === 0 && trials > 10000, `${grp(trials)} films, ${viol} violations, smallest ratio ${minRatio.toFixed(12)}, ${grp(tight)} even films where it is exactly tight`);
  // POISON: a signed pseudo-distribution is not a film, and must break the floor.
  const w = [1.6, -0.6], d = [0.2, 3], A = 5;
  const g1 = w[0] * Math.exp(-A * d[0]) + w[1] * Math.exp(-A * d[1]), L = 1 / g1, s = 0.3;
  const gs = w[0] * Math.exp(-A * s * d[0]) + w[1] * Math.exp(-A * s * d[1]);
  /* THE POISON THIS TEST ACTUALLY NEEDED, and could not have been without it.
     Every film in the loop above is evaluated at exp(-A*d) and at exp(-A*s*d): the SAME
     film, scaled. The one physical assumption in the whole argument, that reducing the
     dose thins the film rather than breaking it up, is therefore applied to BOTH sides of
     the comparison, where no violation could ever appear. 40,000 films, zero violations,
     and not one of them could have violated. So break the assumption deliberately and
     require the floor to fail: a labelled 50 spread at a quarter dose over half the area,
     with the rest bare, must land BELOW label^0.25, and the same routine at full coverage
     must return the floor exactly. The page states this limit where the inequality is. */
  const pf = evenFilm(50, 0.5), pPatchy = patchySPF(50, 0.25, 0.5);
  ok('poison on the ASSUMPTION: a film that goes patchy rather than thinning breaks the floor, which every test above was structurally unable to see',
     pPatchy < pf - 1e-9 && Math.abs(patchySPF(50, 0.25, 1) - pf) < 1e-9,
     `a labelled 50 at a quarter dose over half the area gives ${F(pPatchy, 3)}, under the floor of ${F(pf, 3)}; at full coverage the same routine returns ${F(patchySPF(50, 0.25, 1), 3)}, the floor exactly`);
  // and the direction matters: it is worse than the scary number the page discusses
  ok('and it goes below the number the under-application story is usually told with, so the page cannot use the floor to dismiss that story outright',
     pPatchy < pf && patchySPF(50, 0.25, 0.25) < pPatchy,
     `half coverage ${F(pPatchy, 2)}, quarter coverage ${F(patchySPF(50, 0.25, 0.25), 2)}, against the even-film ${F(pf, 2)}`);
  ok('poison: a signed pseudo-distribution breaks the floor, so the test is not vacuous',
     (1 / gs) < Math.pow(L, s), `${F(1 / gs, 3)} against a floor of ${F(Math.pow(L, s), 3)}`);
}

// ─────────────────────────────────────────────────────────────────────────────
// 6. THE LYING-SURFACE TEST: what the reader actually sees
// ─────────────────────────────────────────────────────────────────────────────
// Nothing above asserts anything about the page's prose. A verifier can be entirely
// green while the sentence next to the instrument says 1.37 instead of 10.37. So: pull
// every figure out of the rendered document and require it to equal what was computed
// here, and then require the same string to survive as visible text once the scripts,
// styles, comments and tags are stripped.
const zF3 = fit0.z, zC3 = zF3 * 5 / 9, zC4 = fitZGolden(C4[0]).z * 5 / 9;
const localZ = (c, i) => {
  const a = c[i], b = c[i + 1], dT = b.F - a.F;
  const dLo = log10(a.t + a.h) - log10(b.t - b.h);
  const dHi = log10(a.t - a.h) - log10(b.t + b.h);
  const open = !(dHi > 0);   // rounding lets the two printed times cross: no upper bound
  return { z: dT / (log10(a.t) - log10(b.t)), lo: dT / dLo, hi: open ? Infinity : dT / dHi, open };
};
const openPairsIn = tab => { let n = 0; for (let j = 0; j < 12; j++) { const c = col(tab, j); for (let i = 0; i < c.length - 1; i++) if (localZ(c, i).open) n++; } return n; };
const openPairs3 = openPairsIn(TAB3);
const zAll = []; for (let i = 0; i < C3[0].length - 1; i++) zAll.push(localZ(C3[0], i));
// A pair whose printed rounding lets the two times cross has NO upper bound on the z it
// permits, so the consistent set is a ray and dividing through gives a negative number
// that must not be read as an exclusion. localZ marks those open; nothing counts them.
const nExcl = zAll.filter(q => q.lo > zF3 || (!q.open && q.hi < zF3)).length;
{
  ok('the adjacent pairs whose printed rounding lets the two times cross are reported as open-ended, not as a negative upper bound',
     openPairsIn(TAB3) === 8 && openPairsIn(TAB4) === 17 && zAll.filter(q => q.open).length === 0,
     `${openPairsIn(TAB3)} such pairs in chicken and ${openPairsIn(TAB4)} in turkey; none of them in the 1% column the prose quotes`);
  // CONTROL: the old arithmetic (dividing through regardless) really did miscount, so this
  // is a fix and not a decoration. At 6% fat it claimed 16 exclusions where 14 is right.
  const c6 = col(TAB3, 5), z6 = fitZGolden(c6).z;
  let naive = 0, sound = 0;
  for (let i = 0; i < c6.length - 1; i++) {
    const q = localZ(c6, i), hiNaive = 1 / (log10(c6[i].t - c6[i].h) - log10(c6[i + 1].t + c6[i + 1].h));
    if (hiNaive < z6 || q.lo > z6) naive++;
    if (q.lo > z6 || (!q.open && q.hi < z6)) sound++;
  }
  ok('control: dividing through on those pairs would over-count exclusions, so the handling is load-bearing',
     naive > sound && sound === 14, `at 6% fat the naive arithmetic claims ${naive} exclusions where ${sound} is right`);
}
const lin70 = spfClosed(calibA(70, 1), 0.5, 1), lin100 = spfClosed(calibA(100, 1), 0.5, 1);
const floor70 = evenFilm(70, 0.5), floor100 = evenFilm(100, 0.5);
let INFO3 = 0; for (let j = 0; j < 12; j++) INFO3 += C3[j].length;

// the same table read under the NARROWER printing convention, reported so the choice of
// convention is disclosed rather than made quietly
const narrowRows = tableFromPage('T3').map(line => line.split('|').map((c, i) =>
  i === 0 || c === '0' || c.includes('.') ? c : c.replace(/^([0-9]+)/, '$1.0')).join('|'));
const S3N = scan(parseRows(narrowRows));
const TOPCOL = C3[0].filter(q => q.F >= 154);
const FITTOP = fitZGolden(TOPCOL);
const WORSTTOP = TOPCOL.map(q => Math.abs(FITTOP.predict(q.F) / q.t - 1)).reduce((a, b) => Math.max(a, b), 0);
const TAILFIT = fitZGolden(C3[0].filter(q => q.F >= 157));
ok('the narrower printing convention is strictly harder on the shortcut, so the published count is the conservative one',
   S3N.viol > S3.viol, `${grp(S3.viol)} violations as printed, ${grp(S3N.viol)} if trailing zeros are suppressed`);
ok('the table is log-linear on its rows at and above 154 F and not below',
   WORSTTOP < 0.01 && Math.abs(WORST0.r) > 0.05,
   `worst error ${F(WORSTTOP * 100, 2)}% on that block against ${F(Math.abs(WORST0.r) * 100, 2)}% over the column; z there is ${F(FITTOP.z * 5 / 9, 4)} C`);

const EXPECT = {
  cells3: '360', cells3b: '360', info3: String(INFO3),
  zF3: F(zF3, 3), zF3b: F(zF3, 3), zC3: F(zC3, 3), zC3b: F(zC3, 3), zC4: F(zC4, 3),
  pubC3: String(PUB_Z_CHICKEN_C), pubC4: String(PUB_Z_TURKEY_C),
  miss3: F(rel(zC3, PUB_Z_CHICKEN_C) * 100, 2), miss4: F(rel(zC4, PUB_Z_TURKEY_C) * 100, 2),
  zlocMin: F(Math.min(...zAll.map(q => q.z)), 2), zlocMax: F(Math.max(...zAll.map(q => q.z)), 2),
  nExcl: String(nExcl), nPairs: String(zAll.length),
  worst3: F(Math.abs(WORST0.r) * 100, 2), worst3b: F(Math.abs(WORST0.r) * 100, 2),
  worstT3: String(WORST0.F), obs149: String(WORST0.obs), pred149: F(WORST0.pred, 1),
  nres: String(RES0.length), runs: String(RUNS),
  nPos: String(nPos), nNeg: String(nNeg), roundPct: F(WORST0.hu * 100, 1),
  runsOdds: grp(Math.round(1 / pRuns)),
  mmWorst: F(MM0.w * 100, 2), mmZ: F(MM0.z, 3), mmRatio: String(mmRatio),
  worstC3: F((WORST0.F - 32) * 5 / 9, 1),
  lin70b: F(lin70, 2), lin80: F(spfClosed(calibA(80, 1), 0.5, 1), 2),
  floor70c: F(floor70, 2), floor80: F(evenFilm(80, 0.5), 2),
  mmRuns: String(mmRuns.R), mmOdds: grp(Math.round(1 / mmRuns.p)),
  mmBest: F(MM[MMBEST].w * 100, 2), mmBestFat: String(MMBEST + 1),
  openPair3: String(openPairs3),
  bandLo: String(band0.lo), bandHi: String(band0.hi),
  mmBandLo: String(mmBand0.lo), mmBandHi: String(mmBand0.hi),
  allZeroF: String(firstAllZero),
  patchy50: F(patchySPF(50, 0.25, 0.5), 2), patchFloor50: F(evenFilm(50, 0.5), 2),
  viol3: grp(S3.viol), trip3: grp(S3.total), und3: grp(S3.und),
  viol4: grp(S4.viol), trip4: grp(S4.total),
  midMin: String(Math.round(S3.best.floorMid)), convCap: F(S3.best.cap, 1),
  excess: F(S3.best.floorMid / S3.best.cap, 2),
  refdose: '2', margin: String(165 - firstAllZero),
  msuCells: String(TAB3.length * 12 + TAB4.length * 12),
  z162: F(TAILFIT.predict(162), 1),
  zTop: F(FITTOP.z, 3), zTopC: F(FITTOP.z * 5 / 9, 3), worstTop: F(WORSTTOP * 100, 2),
  violNarrow: grp(S3N.viol),
  floor70: F(floor70, 2), floor70b: F(floor70, 2),
  meas70: String(OUYANG[0].spf), meas70b: String(OUYANG[0].spf), meas70c: String(OUYANG[0].spf),
  meas100: String(OUYANG[1].spf),
  need70: grp(Math.round(Math.pow(OUYANG[0].spf, REF_DOSE / 0.5))),
  lin70: F(lin70, 2), lin100: F(lin100, 2),
  lin70err: F(rel(lin70, OUYANG[0].spf) * 100, 1), lin100err: F(rel(lin100, OUYANG[1].spf) * 100, 1),
  ratio70: F(OUYANG[0].spf / floor70, 1), ratio100: F(OUYANG[1].spf / floor100, 1),
  pow4: F(spfClosed(calibA(4, 1), 0.5, 1) / evenFilm(4, 0.5), 2),
  pow70: F(spfClosed(calibA(70, 1), 0.5, 1) / evenFilm(70, 0.5), 2)
};
const rendered = {};
for (const m of html.matchAll(/<b data-fig="([^"]+)">([\s\S]*?)<\/b>/g)) rendered[m[1]] = m[2].replace(/&nbsp;| /g, ' ').trim();
{
  const missing = Object.keys(EXPECT).filter(k => !(k in rendered));
  const extra = Object.keys(rendered).filter(k => !(k in EXPECT));
  const wrong = Object.keys(EXPECT).filter(k => k in rendered && rendered[k] !== EXPECT[k]);
  ok('every figure this verifier computes is present in the page and vice versa',
     missing.length === 0 && extra.length === 0,
     `${Object.keys(rendered).length} figures rendered` + (missing.length ? `; MISSING ${missing}` : '') + (extra.length ? `; UNEXPECTED ${extra}` : ''));
  ok('every figure printed in the page equals the value recomputed here',
     wrong.length === 0,
     wrong.length ? wrong.map(k => `${k}: page "${rendered[k]}" vs computed "${EXPECT[k]}"`).join('; ') : `all ${Object.keys(EXPECT).length} match`);
}
// the same numbers, as VISIBLE TEXT, after everything the reader does not see is removed
{
  const text = html
    .replace(/<script[\s\S]*?<\/script>/gi, ' ')
    .replace(/<style[\s\S]*?<\/style>/gi, ' ')
    .replace(/<!--[\s\S]*?-->/g, ' ')
    .replace(/<[^>]*>/g, ' ')
    .replace(/&nbsp;| /g, ' ');
  const need = ['zF3', 'zC3', 'zC4', 'worst3', 'obs149', 'pred149', 'runsOdds', 'viol3', 'trip3',
                'viol4', 'trip4', 'midMin', 'convCap', 'excess', 'floor70', 'need70', 'lin70',
                'lin100', 'ratio70', 'ratio100', 'pow4', 'pow70', 'zlocMin', 'zlocMax',
                'msuCells', 'z162', 'zTop', 'zTopC', 'worstTop', 'violNarrow'];
  const absent = need.filter(k => !text.includes(EXPECT[k]));
  ok('and each of those figures survives as visible prose once scripts, styles and tags are stripped',
     absent.length === 0, absent.length ? `NOT VISIBLE: ${absent.map(k => k + '=' + EXPECT[k])}` : `${need.length} figures checked in the reader's text`);
  // the shareable surface, one attribute at a time, because a loose regex over the whole
  // head passes when a DIFFERENT tag still carries the right number.
  const surfaces = ['name="description"', 'property="og:description"', 'name="twitter:description"'];
  const texts = surfaces.map(a => {
    const m = new RegExp('<meta ' + a.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + ' content="([^"]*)"').exec(html);
    return m ? m[1] : null;
  });
  // The JSON-LD description is a shareable surface too, and it was the one tag not being
  // string-checked here, which is exactly where an unqualified claim survived once already.
  const ld = JSON.parse(/<script type="application\/ld\+json">([\s\S]*?)<\/script>/.exec(html)[1]);
  // and so are the dek and the plain placard, which are the homepage face of this layer
  const mdSrc = fs.readFileSync(MD, 'utf8');
  const dek = /^dek: "(.*)"$/m.exec(mdSrc)[1], plain = /^plain: "(.*)"$/m.exec(mdSrc)[1];
  texts.push(ld.description, dek, plain);
  surfaces.push('JSON-LD description', 'frontmatter dek', 'frontmatter plain');
  ok('all six shareable description surfaces are present, the JSON-LD and the frontmatter included',
     texts.every(t => t !== null && t.length > 0), surfaces.join(', '));
  const pct = texts.flatMap(t => [...(t || '').matchAll(/(\d+\.\d+) percent/g)].map(m => m[1]));
  /* The number quoted as what the fit CANNOT do has to be the family's floor, not the
     least-squares figure, which is 35% larger and would overstate the finding. Any
     "N.NN percent" on any shareable surface must be the minimax value. */
  ok('every "N.NN percent" claim on the shareable surface is the family floor, not the larger least-squares figure',
     pct.length >= 5 && pct.every(v => v === EXPECT.mmWorst),
     `${pct.length} claims across ${surfaces.length} surfaces: ${[...new Set(pct)].join(', ')} against the computed floor ${EXPECT.mmWorst} (least squares would be ${EXPECT.worst3})`);
  /* AND THE QUALIFIER, which the percent check alone cannot see. 7.66% is the floor on the
     LEANEST column; over all twelve the family gets down to 6.94%, so an unqualified "the
     best possible fit misses by 7.66 percent" is false. The JSON-LD description was exactly
     that once, and every check here passed it, because they all only looked at the digits.
     Any surface that quotes the figure must also say which column it is the floor for. */
  const quoting = texts.filter(t => (t || '').includes(EXPECT.mmWorst));
  const unqualified = quoting.filter(t => !/leanest/i.test(t));
  ok('every surface that quotes the floor also says it is the LEANEST column, because unqualified it would be false',
     quoting.length >= 5 && unqualified.length === 0,
     unqualified.length
       ? `UNQUALIFIED (the family reaches ${EXPECT.mmBest}% at ${EXPECT.mmBestFat}% fat): ${unqualified.map(t => t.slice(0, 70)).join(' | ')}`
       : `${quoting.length} surfaces quote ${EXPECT.mmWorst}%, all of them scoped to the leanest column`);
  /* A surface that quotes the minimax error must not quote the LEAST-SQUARES runs odds
     beside it: the sign structure survives refitting, but the probability does not, and
     pairing the two reads as one result when it is two. 3 runs from 17 and 9 is 1 in
     120,175; from the minimax fit's 19 and 7 it is 1 in 25,300. */
  const mixed = texts.filter(t => (t || '').includes(EXPECT.mmWorst) && (t || '').includes(EXPECT.runsOdds));
  ok('no surface pairs the minimax error with the least-squares runs odds, which belong to a different fit',
     mixed.length === 0,
     mixed.length ? `MIXED: ${mixed.map(t => t.slice(0, 60)).join(' | ')}` : `least-squares odds ${EXPECT.runsOdds} kept off the surfaces that quote the ${EXPECT.mmWorst}% floor (whose odds are ${EXPECT.mmOdds})`);
  // and none of them may claim the floor is unconditional, which it is not
  const overclaim = texts.filter(t => /every (possible )?film geometry|any film geometry|no assumption/i.test(t || ''));
  ok('no shareable surface claims the SPF floor holds over every film geometry, because it needs the film to thin rather than break up',
     overclaim.length === 0,
     overclaim.length ? `OVERCLAIMS: ${overclaim.map(t => t.slice(0, 60)).join(' | ')}` : `${surfaces.length} surfaces clean of the unconditional phrasing`);
  // grouped thousands have to be tokenised whole, or "120,175" reads as two stray numbers
  const nums = texts.flatMap(t => [...(t || '').matchAll(/\b(\d{1,3}(?:,\d{3})+|\d+(?:\.\d+)?)\b/g)].map(m => m[1]));
  const known = new Set(Object.values(EXPECT).concat(['2', '3', '19', '70', '0.5', '24444', '2026', '08', '30']));
  const stray = [...new Set(nums)].filter(v => !known.has(v));
  ok('no number on the shareable surface is unaccounted for',
     stray.length === 0, stray.length ? `unexplained: ${stray.join(', ')}` : `${new Set(nums).size} distinct numbers, all computed or structural`);
}

/* FOOTNOTE 9, against the PDF's own text layer. The page had this backwards once: it said
   the footnote RESTRICTS the rows at or above 145 F to Humidity Options 1 and 2, where the
   document makes those rows ELIGIBLE for 1 and 2 and lets every row use 3 or 4, and puts
   the real restriction on the endpoints BELOW 145 F. On a page whose whole subject is
   reading a record correctly, the reading has to be checked against the record. */
{
  const f = path.join(DATA, 'AppendixA-2021.pdf');
  let txt = '';
  if (fs.existsSync(f)) {
    try {
      txt = execFileSync('pdftotext', ['-layout', '-f', '25', '-l', '38', f, '-'], { encoding: 'utf8' })
        .replace(/°+/g, ' ').replace(/\s+/g, ' ');
    } catch (e) { txt = ''; }
  }
  if (txt) {
    const eligible = /are eligible for FSIS Relative Humidity Options 1 and 2/.test(txt);
    const allMay  = /All time-temperatures may apply FSIS Relative Humidity Options 3 and 4/.test(txt);
    // -layout interleaves a sidebar into this sentence, so it is matched in the two
    // distinctive fragments that survive the interleaving rather than as one run of text.
    const anyOpt  = /145 F plus the dwell time, may apply any of the/i.test(txt) &&
                    /time-temperatures of at least/i.test(txt);
    const below   = /products cooked to an endpoint less than 145 F, should select Option 3 or 4/i.test(txt);
    ok('footnote 9 in the source says ELIGIBLE FOR options 1 and 2, and lets every row use 3 or 4',
       eligible && allMay, `eligibility clause present ${eligible}, all-rows clause present ${allMay}`);
    ok('and the source puts the real restriction on the endpoints BELOW 145 F, not above',
       below && anyOpt, 'source: at or above 145 F may apply ANY option; below 145 F should select Option 3 or 4');
    const flat = html.replace(/&nbsp;/g, ' ').replace(/\s+/g, ' ');
    ok('the page states that reading and not the inversion it used to print',
       /are eligible for<\/em> Relative Humidity Options 1 and 2/.test(flat) &&
       /may apply Options 3 and 4/.test(flat) &&
       /below<\/em> 145/.test(flat) &&
       !/restricts the boxed rows at or above 145 .{0,4}F to Relative Humidity Options 1 and 2/.test(flat),
       'page carries the eligibility, the all-rows clause and the sub-145 F restriction');
    ok('and it no longer says the times are void without humidity, which the guideline contradicts',
       !/The times are void without the humidity/.test(flat) && /situations in which humidity is not needed/i.test(flat),
       'the guideline carries a "Situations when Humidity is Not Needed" section');
  } else {
    skipped('footnote 9 against the PDF text layer', 'AppendixA-2021.pdf absent or pdftotext unavailable');
  }
}

// ─────────────────────────────────────────────────────────────────────────────
// 6b. the published constants, against pinned copies of the source records
// ─────────────────────────────────────────────────────────────────────────────
// Every number this page borrows rather than computes is checked against a stored copy
// of the record it came from, so a mistyped constant cannot agree with itself.
function abstractOf(file) {
  const f = path.join(DATA, file);
  if (!fs.existsSync(f)) return null;
  const j = JSON.parse(fs.readFileSync(f, 'utf8'));
  const r = j.resultList.result[0];
  const ji = r.journalInfo || {};
  /* Strip the HTML TAGS Europe PMC actually uses, not every angle bracket. These abstracts
     write "P <or= 0 x 0001", and a bare /<[^>]+>/ runs from that "<" all the way to the ">"
     of the next real tag, silently deleting the entire Results section, r-squared and all.
     Naming the tags is what makes the quoted statistics reachable at any point below. */
  const TAGS = /<\/?(?:h[1-6]|sup|sub|i|b|em|strong|p|br|u|span)\b[^>]*>/gi;
  return { text: (r.abstractText || '').replace(TAGS, ' ').replace(/\s+/g, ' '),
           title: r.title, pmid: r.pmid, vol: ji.volume, issue: ji.issue,
           firstPage: (r.pageInfo || '').split('-')[0], year: String(r.pubYear || '') };
}

/* THE LOCATOR CHECK, which this verifier did not have and needed.
   A PMID link resolves whatever volume and page are printed beside it, so a wrong first
   page is invisible to a reader who clicks through and invisible to a check that only
   tests the PMID and the quoted sentence. Two of these were wrong. Every citation the
   page prints is now matched, digit for digit, against the stored record's own fields. */
{
  const CITED = [
    ['juneja.json',        '11759761', 'Int. J. Food Microbiol.'],
    ['epmc_25364923.json', '25364923', 'J. Food Prot.'],
    ['epmc_17493070.json', '17493070', 'Br. J. Dermatol.'],
    ['epmc_22463921.json', '22463921', 'J. Am. Acad. Dermatol.'],
    ['epmc_6470949.json',  '6470949',  'J. Pharm. Sci.'],
    ['epmc_34695251.json', '34695251', 'Photodermatol. Photoimmunol. Photomed.']
  ];
  const wrong = [], unchecked = [];
  for (const [file, pmid, journal] of CITED) {
    const r = abstractOf(file);
    if (!r) { unchecked.push(pmid); continue; }
    // the page prints: <em>Journal</em> VOL(ISSUE):FIRSTPAGE (YEAR)
    const want = `<em>${journal}</em> ${r.vol}(${r.issue}):${r.firstPage} (${r.year})`;
    if (!html.includes(want)) {
      const got = new RegExp('<em>' + journal.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '</em>[^(]*\\([0-9]{4}\\)').exec(html);
      wrong.push(`PMID ${pmid}: record says "${want}", page prints "${got ? got[0] : 'NOTHING'}"`);
    }
  }
  ok('every citation locator on the page matches the stored record volume, issue, first page and year',
     wrong.length === 0 && unchecked.length === 0,
     wrong.length ? wrong.join(' | ') : `${CITED.length} citations checked field by field`);
  // CONTROL: the locator test has to be able to fail, so break one on purpose.
  const jj = abstractOf('epmc_25364923.json');
  ok('control: the locator test rejects a wrong first page, so it is not merely finding the journal name',
     jj !== null && !html.includes(`<em>J. Food Prot.</em> ${jj.vol}(${jj.issue}):2043 (${jj.year})`) && html.includes(`<em>J. Food Prot.</em> ${jj.vol}(${jj.issue}):${jj.firstPage} (${jj.year})`),
     `the page prints the record page ${jj ? jj.firstPage : '?'} and not the 2043 it used to`);
  // and the quoted TITLE must be the whole title, not a truncation inside quotation marks
  const oy = abstractOf('epmc_22463921.json');
  ok('the Ou-Yang title is quoted whole, including the clause that shows the direction of the claim',
     oy !== null && html.includes('adequately compensating for lower sunscreen user application amounts'),
     oy ? `title ends "...${oy.title.replace(/\.$/, '').slice(-52)}"` : 'record absent');
  /* And the reader must be told whose paper it is WHERE THE NUMBERS ARE, not only in the
     footer. A disclosure a reader reaches after the argument has been made is not one.
     This requires it in the body, ahead of the blockquote that carries the two values, and
     names the product-tier conclusion that shows the direction of the interest. */
  const flatPage = html.replace(/\s+/g, ' ');
  const beforeQuote = flatPage.split('There was a linear relationship between application density')[0];
  const TIER = 'may not produce sufficient protection at actual consumer usage levels';
  ok('and the reader is told whose paper it is BEFORE the two numbers it supplies, not only in the sources footer',
     /Neutrogena/.test(beforeQuote) && beforeQuote.includes(TIER) &&
     /Neutrogena/.test(flatPage.split('<footer>')[1] || ''),
     'the affiliation and the product-tier conclusion are named in the body ahead of the quotation, and again in the sources');
  ok('and the product-tier conclusion is quoted verbatim from the stored abstract, not paraphrased inside quotation marks',
     oy !== null && oy.text.includes(TIER),
     oy ? `source: "...${(/In contrast[^.]*\./.exec(oy.text) || [''])[0].trim()}"` : 'record absent');
}
{
  const jun = abstractOf('juneja.json');
  if (jun) {
    ok('Juneja 2001b abstract on disk carries the two z-values this page cites',
       /5\.5 degrees C and 6\.1 degrees C/.test(jun.text) && jun.pmid === '11759761',
       `PMID ${jun.pmid}: "${(/The z-values[^.]*\./.exec(jun.text) || [''])[0].trim()}"`);
    ok('and the lag-plus-seven-D recipe the page attributes to it',
       /lag time should be added to the product of 7 and the estimated asymptotic D-value/.test(jun.text) &&
       /many of the survival curves were concave/.test(jun.text));
  } else skipped('Juneja abstract', 'data/juneja.json absent');
  const oy = abstractOf('epmc_22463921.json');
  if (oy) {
    const m = /SPF 70 and 100 applied at 0\.5 mg\/cm\(2\) provided an actual SPF value of, respectively, (\d+) and (\d+)/.exec(oy.text);
    ok('Ou-Yang 2012 abstract on disk gives exactly the two in-vivo values this page uses',
       !!m && Number(m[1]) === OUYANG[0].spf && Number(m[2]) === OUYANG[1].spf,
       m ? `abstract says ${m[1]} and ${m[2]}; page uses ${OUYANG[0].spf} and ${OUYANG[1].spf}` : 'sentence not found');
    ok('and the page quotes its linear-relationship sentence without altering it',
       /There was a linear relationship between application density and the actual SPF/.test(oy.text) &&
       htmlFlat.includes('There was a linear relationship between application density and the'));
  } else skipped('Ou-Yang abstract', 'data/epmc_22463921.json absent');
  const fw = abstractOf('epmc_17493070.json');
  if (fw) {
    ok('Faurschou 2007 abstract on disk says one product labelled SPF 4 and twenty volunteers',
       /20 healthy volunteers/.test(fw.text) && /sunscreen SPF 4 in different amounts/.test(fw.text),
       'the study the fourth-root rule comes from');
    ok('and its own concession, that the exponential relation was not confirmed in vitro, is on the record',
       /this was not confirmed in vitro/.test(fw.text));
  } else skipped('Faurschou abstract', 'data/epmc_17493070.json absent');
  const br = abstractOf('epmc_25364923.json');
  if (br) {
    const q = 'slow-cooked roasts, processed to a computed lethality at or near that required by the regulatory performance standards, as calculated with a state-dependent model, may be underprocessed';
    ok('Breslin 2014 is quoted verbatim from the stored abstract',
       br.text.includes(q) && htmlFlat.includes(q), 'the sentence the safety box rests on');
    ok('and the page also reports that their repair failed in beef and pork',
       /did not reduce the prediction error in beef or pork/.test(br.text) &&
       /did not in beef or pork/.test(htmlFlat));
  } else skipped('Breslin abstract', 'data/epmc_25364923.json absent');
}

// The page carries its own copies of these constants, for its own live panel. If they
// ever drift from the ones checked above, the page's prose and the page's engine part
// company and only the browser would see it. Read them back out of the script.
{
  const pOu = /var OUYANG = \[\{ label: (\d+), dose: ([\d.]+), spf: (\d+) \}, \{ label: (\d+), dose: ([\d.]+), spf: (\d+) \}\];/.exec(html);
  ok('the page\'s own Ou-Yang constants match the ones checked against the abstract',
     !!pOu && Number(pOu[1]) === 70 && Number(pOu[3]) === OUYANG[0].spf && Number(pOu[4]) === 100 && Number(pOu[6]) === OUYANG[1].spf,
     pOu ? `page: SPF ${pOu[1]} -> ${pOu[3]}, SPF ${pOu[4]} -> ${pOu[6]}` : 'declaration not found');
  const pZ = /var PUB_Z_CHICKEN_C = ([\d.]+), PUB_Z_TURKEY_C = ([\d.]+);/.exec(html);
  ok('the page\'s own Juneja anchors match the ones checked against the abstract',
     !!pZ && Number(pZ[1]) === PUB_Z_CHICKEN_C && Number(pZ[2]) === PUB_Z_TURKEY_C,
     pZ ? `page: ${pZ[1]} and ${pZ[2]} C` : 'declaration not found');
  const pRef = /var REF_DOSE = (\d+);/.exec(html);
  ok('the page and this verifier use the same reference application dose',
     !!pRef && Number(pRef[1]) === REF_DOSE, pRef ? `${pRef[1]} mg/cm2` : 'declaration not found');
}

// ─────────────────────────────────────────────────────────────────────────────
// 6c. THE STATIC DISPLAYED FIGURES, string-matched in the reader's own text
// ─────────────────────────────────────────────────────────────────────────────
/* Everything above checks the figures the page wraps in <b data-fig>, which is every
   figure this verifier COMPUTES. That is not every figure the page PRINTS. A number
   sitting in plain prose, or quoted out of a source record, is read by the same reader
   under the same green check panel, and until now nothing here would go red if one of
   them were silently rewritten. A mutation test proved it: the r-squared in the
   Faurschou quotation was corrupted to a different value and all 84 assertions below
   stayed green.
   Every check in this section ties a figure the reader SEES to a value DERIVED here:
   from the page's own data block, from a pinned source record, or from the pinned PDF.
   Never to a literal typed beside it. The two things that must both be true are that the
   derivation is right and that the ink on the page says what the derivation says. */
const RTEXT = html
  .replace(/<script[\s\S]*?<\/script>/gi, ' ')
  .replace(/<style[\s\S]*?<\/style>/gi, ' ')
  .replace(/<!--[\s\S]*?-->/g, ' ')
  .replace(/<[^>]*>/g, ' ')
  .replace(/&nbsp;/g, ' ').replace(/&deg;/g, '').replace(/&sup2;/g, '2')
  .replace(/&minus;/g, '-').replace(/&amp;/g, '&').replace(/&lt;/g, '<')
  .replace(/&ge;/g, '>=').replace(/&middot;/g, '|').replace(/&lang;/g, '<').replace(/&rang;/g, '>')
  .replace(/\s+/g, ' ');
/* The one control that makes this whole section mean anything: the stripper must actually
   remove the page's own script block, or every phrase below could be "found" inside the
   engine's source instead of in the prose a reader reads. */
ok('control: the reader-text stripper really removes the page script, so a match below is ink and not source code',
   !RTEXT.includes('addEventListener') && !RTEXT.includes('var T3 =') && RTEXT.length > 20000,
   `${grp(RTEXT.length)} characters of visible text, no engine source in it`);

// the page spells small counts out; the spelling is part of the figure
const NWORD = { 4: 'four', 5: 'five', 6: 'six', 12: 'twelve', 20: 'twenty', 30: 'thirty', 42: 'forty-two' };
const wordOf = n => NWORD[n];
const capOf = n => { const w = NWORD[n]; return w[0].toUpperCase() + w.slice(1); };
/* the spelling table is a lookup, and a lookup that silently returns undefined turns every
   assertion built on it into the string "undefined", which no page contains, so it would
   fail loudly rather than quietly. Still, say out loud which counts it has to cover. */
ok('the number-word table covers every count the prose spells out rather than prints',
   [4, 5, 6, 12, 20, 30, 42].every(n => typeof NWORD[n] === 'string'), Object.values(NWORD).join(', '));

// ---- the shape of Table 3, from the page's own data block -------------------
{
  const Fs = TAB3.map(r => r.F);
  const nZero = TAB3.reduce((a, r) => a + r.cells.filter(c => !c).length, 0);
  const geom = `${capOf(TAB3.length)} temperature rows from ${Math.min(...Fs)} to ${Math.max(...Fs)} ` +
               `degrees Fahrenheit, ${wordOf(TAB3[0].cells.length)} fat columns from 1 to ${TAB3[0].cells.length} percent`;
  ok('the page\'s opening sentence states the table\'s shape as the shipped data block actually has it',
     RTEXT.includes(geom), `"${geom}"`);
  ok('and the count of instantaneous cells in the prose is the count of empty cells in the data',
     RTEXT.includes(`${capOf(nZero)} of the chicken cells read 0 sec.**`),
     `${nZero} cells carry no time, so the prose must say "${capOf(nZero)}"`);
  // the giveaway row, built from the row itself rather than from memory of it
  const R = TAB3.find(r => r.F === 162);
  const lastZero = R.cells.reduce((a, c, j) => (c ? a : j), -1);
  const firstTime = R.cells.findIndex(c => !!c);
  const secs = parseFloat(/^([0-9.]+)/.exec(R.cells[firstTime].txt)[1]);
  const give = `at ${R.F} F the ${lastZero + 1} percent fat column reads zero while the ` +
               `${firstTime + 1} percent column reads ${secs} seconds`;
  ok('the 162 F giveaway sentence names the columns and the time the transcription actually holds',
     lastZero + 1 === firstTime && RTEXT.includes(give), `"${give}"`);
}

// ---- the counts and labels the controls print -------------------------------
{
  /* "the five rows below" is the size of the block the extrapolation is fitted on, and it
     is a figure a reader can check against the picture. Take it from the fit itself. */
  const tailRows = C3[0].filter(q => q.F >= 157 && q.F < 162).length;
  ok('the row count behind the extrapolated 162 F figure is the size of the block that fit is taken over',
     RTEXT.includes(`continuing the trend of the ${wordOf(tailRows)} rows below`),
     `${tailRows} rows, 157 to 161 F, the block TAILFIT is built from`);
  /* Every fat-column select prints twelve option labels. They are static text, and a
     mislabelled option silently misreads every instrument built on it. Build the list. */
  const wantOpts = Array.from({ length: 12 }, (_, j) => `${j + 1}% fat`);
  const sels = [...html.matchAll(/<select id="(zfat|ffat|cfat)"[\s\S]*?<\/select>/g)];
  const badSel = sels.filter(m => {
    const got = [...m[0].matchAll(/<option value="(\d+)"[^>]*>([^<]*)<\/option>/g)];
    return got.length !== 12 || got.some((o, k) => +o[1] !== k || o[2] !== wantOpts[k]);
  }).map(m => m[1]);
  ok('every fat-column selector labels its twelve options with the column each value indexes',
     sels.length === 3 && badSel.length === 0,
     badSel.length ? `MISLABELLED: ${badSel.join(', ')}` : `${sels.length} selectors, ${wantOpts.length} options each, ${wantOpts[0]} to ${wantOpts[11]}`);
  /* And the label selector's options are the two Ou-Yang products plus the Faurschou one,
     each named with the value it carries, so the option text cannot drift off its value. */
  const lab = /<select id="slabel"[\s\S]*?<\/select>/.exec(html)[0];
  const opts = [...lab.matchAll(/<option value="(\d+)"[^>]*>SPF (\d+)[^<]*<\/option>/g)];
  const named = opts.filter(o => /measured|tested/.test(lab.slice(lab.indexOf(o[0]), lab.indexOf(o[0]) + o[0].length)));
  ok('the SPF selector\'s option text carries the same label as its value, and the measured products are the ones named',
     opts.length >= 5 && opts.every(o => o[1] === o[2]) &&
     named.map(o => +o[1]).sort((a, b) => a - b).join(',') === [4, OUYANG[0].label, OUYANG[1].label].sort((a, b) => a - b).join(','),
     `${opts.length} options; annotated: ${named.map(o => 'SPF ' + o[1]).join(', ')}`);
}

// ---- the bitmap, from the pinned PDF itself ---------------------------------
/* "1105 by 585 pixels at 113 ppi" and "page 37" are the page's account of where its one
   figure came from. Both are recoverable from the pinned PDF, so neither has to be taken
   on trust, and the PNG shipped beside the page has to be that same bitmap. */
{
  const pdf = path.join(DATA, 'AppendixA-2021.pdf');
  let rows = null;
  if (fs.existsSync(pdf)) {
    try {
      rows = execFileSync('pdfimages', ['-list', pdf], { encoding: 'utf8' })
        // columns: page num type width height color comp bpc enc interp object ID x-ppi y-ppi size ratio
        .split('\n').slice(2).map(l => l.trim().split(/\s+/)).filter(p => p.length >= 16)
        .map(p => ({ page: +p[0], type: p[2], w: +p[3], h: +p[4], color: p[5], xppi: +p[12], yppi: +p[13] }));
    } catch (e) { rows = null; }
  }
  if (rows) {
    const png = fs.readFileSync(path.join(ROOT, 'public', 'strata', 'the-two-tables', 'table3.png'));
    const pw = png.readUInt32BE(16), ph = png.readUInt32BE(20);
    const hits = rows.filter(r => r.type === 'image' && r.w === pw && r.h === ph);
    const b = hits[0];
    ok('exactly one image in the whole guideline has the shipped PNG\'s dimensions, and it is an indexed bitmap',
       hits.length === 1 && b.color === 'index',
       `${pw} by ${ph}, ${b ? b.color : 'none'}, on page ${b ? b.page : '?'} of ${rows.length} images in the document`);
    const geom = `${pw} by ${ph} pixels at ${b.xppi} ppi`;
    ok('the pixel dimensions and resolution the page prints are the ones the PDF reports for that bitmap',
       b.xppi === b.yppi && RTEXT.includes(geom), `"${geom}"`);
    ok('and the figure caption\'s page number is the page that bitmap is actually on',
       RTEXT.includes(`), page ${b.page}, Table 3,`), `the bitmap is on page ${b.page}`);
    // the img element must declare the same box, or the browser reserves the wrong space
    ok('the img element declares the bitmap\'s true pixel box',
       html.includes(`src="table3.png" width="${pw}" height="${ph}"`), `width ${pw} height ${ph}`);
    // CONTROL: this has to be able to fail, so require the NEIGHBOURING page number to be absent
    ok('control: the page-number check is not satisfied by any page number, only by the right one',
       !RTEXT.includes(`), page ${b.page + 1}, Table 3,`) && !RTEXT.includes(`), page ${b.page - 1}, Table 3,`),
       `page ${b.page - 1} and ${b.page + 1} are both rejected`);
  } else {
    skipped('the bitmap geometry against the PDF', 'AppendixA-2021.pdf absent or pdfimages unavailable');
  }
}

// ---- the sub-ten-second marker, from the independent PDF's text layer -------
/* The transcription JSON normalises those cells to the token ZERO, so the marker's exact
   spelling cannot be recovered from it. It CAN be recovered from the pinned MSU PDF, which
   is where the claim came from, so the string the page quotes is checked against the
   document it is quoted out of. */
{
  const mp = path.join(DATA, 'msu.pdf');
  let mtxt = '';
  if (fs.existsSync(mp)) {
    try { mtxt = execFileSync('pdftotext', ['-layout', mp, '-'], { encoding: 'utf8' }); } catch (e) { mtxt = ''; }
  }
  if (mtxt) {
    const marker = (/<\s*\d+\.\d+\s*sec/.exec(mtxt) || [''])[0].replace(/\s+/g, ' ').trim();
    const n = (mtxt.match(new RegExp(marker.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g')) || []).length;
    ok('the sub-ten-second marker the page quotes is the exact string the independent document prints',
       marker.length > 0 && RTEXT.includes(`prints ${marker} in those cells instead`),
       `"${marker}", ${n} times in the MSU PDF`);
  } else {
    skipped('the sub-ten-second marker against the MSU PDF', 'data/msu.pdf absent or pdftotext unavailable');
  }
}

// ---- the strongest triple, and the rounding convention ----------------------
{
  const b = S3.best;
  const mid = parseFloat(/^([0-9.]+)/.exec(b.B.txt)[1]);
  ok('the prose names the triple the scan actually found strongest, column and all three rows',
     RTEXT.includes(`at ${b.fat} percent fat: the rows at ${b.A.F}, ${b.B.F} and ${b.C.F} F`),
     `${b.fat}% fat, ${b.A.F}/${b.B.F}/${b.C.F} F`);
  ok('and the middle cell it quotes is what that cell of the data block reads',
     RTEXT.includes(`The middle cell reads ${mid} minutes`), `the cell reads "${b.B.txt}"`);
  // the printing convention, straight out of the interval reader every count above uses
  const c13 = cellOf('13 min'), c84 = cellOf('8.4 min');
  const lo13 = F((c13.t - c13.h) / 60, 1), hi13 = F((c13.t + c13.h) / 60, 1);
  const lo84 = F((c84.t - c84.h) / 60, 2), hi84 = F((c84.t + c84.h) / 60, 2);
  ok('the widths the prose attributes to a whole-minute cell are the ones cellOf actually assigns it',
     RTEXT.includes(`13 min with no decimal is treated here as anywhere from ${lo13} to ${hi13} minutes`) &&
     RTEXT.includes(`13 min means ${F(13, 1)}`),
     `"13 min" is ${lo13} to ${hi13} min here, and ${F(13, 1)} under the narrower reading`);
  ok('and the worked example in the free-choices note matches the same reader, to the second decimal',
     RTEXT.includes(`"13 min" is treated as anywhere in ${lo13} to ${hi13} minutes and a cell reading "8.4 min" as ${lo84} to ${hi84}`),
     `"8.4 min" is ${lo84} to ${hi84} min`);
}

// ---- the least-squares figure, quoted a second time in bare prose -----------
/* 10.37 appears three times: twice inside <b data-fig>, and once in bare prose where the
   argument turns on it. The data-fig check cannot see the third one. */
{
  const n = (RTEXT.match(new RegExp(EXPECT.worst3.replace('.', '\\.'), 'g')) || []).length;
  ok('the bare-prose restatement of the least-squares worst error is the computed one, not a stale copy',
     n === 3 && RTEXT.includes(`so ${EXPECT.worst3} percent is not the smallest worst error this family can manage`),
     `${n} occurrences of ${EXPECT.worst3} in the reader's text, one of them outside any data-fig element`);
}

// ---- the thinned-film headline number, twice in the closing caveats --------
{
  const thin = F(evenFilm(50, 0.5), 1);
  ok('the SPF 50 figure in the closing caveats is the even-film value at a quarter dose, to one decimal',
     RTEXT.includes(`an SPF 50 becomes an SPF ${thin},`) && RTEXT.includes(`can land below ${thin},`),
     `evenFilm(50, ${REF_DOSE / 4}) = ${F(evenFilm(50, 0.5), 4)}, printed ${thin} in both places`);
}

// ---- the borrowed figures, each against the record it was borrowed from ----
{
  const fw = abstractOf('epmc_17493070.json');
  if (fw) {
    /* THE FIGURE THE MUTATION TEST CORRUPTED. The r-squared is not a quantity this page
       computes: it is a PUBLISHED STATISTIC, and the only honest way to check it is against
       the record it was quoted from. MEDLINE encodes this record's decimal points as a
       middle dot, which the harvest renders " x "; the page's caption says so and restores
       them. Restore them here the same way and require the quotation to be the restored
       source, digit for digit. */
    const restore = s => s.replace(/(\d) x (\d)/g, '$1.$2').replace(/r\(2\)/g, 'r2').replace(/cm\(-2\)/g, 'cm-2');
    const src = restore(fw.text).replace(/\s+/g, ' ');
    const m = /follow exponential growth \(r2 = (\d+\.\d+)\)/.exec(src);
    ok('the r-squared the page quotes from Faurschou is the record\'s own, with the decimal restored',
       !!m && RTEXT.includes(`follow exponential growth (r2 = ${m[1]})`),
       m ? `the record encodes it "${(/r\(2\) = [0-9 x]+/.exec(fw.text) || [''])[0]}", so the page must print r2 = ${m[1]}` : 'not in the record');
    ok('and the whole quoted sentence around it is the restored record verbatim, not a paraphrase',
       !!m && RTEXT.includes('"The relation between the sunscreen amount applied and the SPF provided was ' +
                             `most likely to follow exponential growth (r2 = ${m[1]}).`),
       'the sentence the fourth-root rule is sourced to');
    const conc = /(Application of 1 mg cm-2[^]*?almost squared SPF\.)/.exec(src);
    ok('the second quoted sentence, which carries the doses, is the restored record verbatim too',
       !!conc && RTEXT.includes(conc[1]),
       conc ? `"${conc[1].slice(0, 58)}..."` : 'not in the record');
    // CONTROL: the restoration must be a restoration and not a rewrite
    ok('control: the page carries the restored spelling and not the raw MEDLINE one, and says which it did',
       !RTEXT.includes('0 x 903') && /Decimal points restored; the MEDLINE record encodes them as a middle dot/.test(RTEXT),
       'the transformation is disclosed where the quotation is');
    const vols = /(\d+) healthy volunteers/.exec(fw.text), prod = /sunscreen SPF (\d+) in different amounts/.exec(fw.text);
    ok('the study description matches the record: the year, the volunteer count and the single product\'s label',
       !!vols && !!prod &&
       RTEXT.includes(`tested that in vivo in ${fw.year} on ${wordOf(+vols[1])} volunteers`) &&
       RTEXT.includes(`used one product, labelled SPF ${prod[1]}`),
       vols && prod ? `${fw.year}, ${vols[1]} volunteers, SPF ${prod[1]}` : 'record fields absent');
    // the short locator under the blockquote is a different format from the footer's
    ok('the short locator under the Faurschou quotation carries the record\'s own volume, first page and year',
       RTEXT.includes(`Br J Dermatol ${fw.vol}:${fw.firstPage} (${fw.year})`),
       `Br J Dermatol ${fw.vol}:${fw.firstPage} (${fw.year})`);
  } else skipped('the Faurschou figures against the record', 'data/epmc_17493070.json absent');

  const oy = abstractOf('epmc_22463921.json');
  if (oy) {
    const rng = /labeled SPF values ranging from (\d+) to (\d+), applied at ([\d., and]+) mg\/cm\(2\)/.exec(oy.text);
    const nprod = /for (\d+) sunscreen products/.exec(oy.text);
    const doses = rng ? rng[3].split(',').map(s => s.trim().replace(/^and\s+/, '')).filter(Boolean) : [];
    const dosePhrase = doses.length === 4 ? `${doses[0]}, ${doses[1]}, ${doses[2]} and ${doses[3]} mg/cm2` : '';
    ok('the product count, the label range and the four doses the page reports are the record\'s',
       !!rng && !!nprod && doses.length === 4 &&
       RTEXT.includes(`on ${wordOf(+nprod[1])} products labelled SPF ${rng[1]} to ${rng[2]}, at ${dosePhrase}`),
       rng ? `${nprod ? nprod[1] : '?'} products, SPF ${rng[1]} to ${rng[2]}, at ${dosePhrase}` : 'sentence not found');
    ok('and the year and PMID printed beside the Ou-Yang quotation are the record\'s own, matching the link they sit beside',
       RTEXT.includes(`J Am Acad Dermatol (${oy.year}), PMID ${oy.pmid}.`) &&
       html.includes(`https://pubmed.ncbi.nlm.nih.gov/${oy.pmid}/`),
       `(${oy.year}), PMID ${oy.pmid}`);
  } else skipped('the Ou-Yang figures against the record', 'data/epmc_22463921.json absent');

  const fj = abstractOf('epmc_34695251.json');
  if (fj) {
    const md = /median application density of the sunscreen applied in actual use was ([\d.]+) mg\/cm/.exec(fj.text);
    ok('the real-world application density in the sources note is the median the Fujiwara record reports',
       !!md && RTEXT.includes(`median application density of ${md[1]} mg/cm2 on the face`),
       md ? `${md[1]} mg/cm2` : 'sentence not found');
  } else skipped('the Fujiwara median against the record', 'data/epmc_34695251.json absent');

  ok('the two published z-values named in the sources note are the two anchors the fits are tested against',
     RTEXT.includes(`the published z-values of ${PUB_Z_CHICKEN_C} and ${PUB_Z_TURKEY_C} C`),
     `${PUB_Z_CHICKEN_C} and ${PUB_Z_TURKEY_C} C, the same constants the anchor test uses`);
}

// ---- the safety note's numbers, against the guideline's own text layer -----
{
  const f = path.join(DATA, 'AppendixA-2021.pdf');
  let txt = '';
  if (fs.existsSync(f)) {
    try {
      txt = execFileSync('pdftotext', ['-layout', f, '-'], { encoding: 'utf8' }).replace(/°+/g, ' ').replace(/\s+/g, ' ');
    } catch (e) { txt = ''; }
  }
  if (txt) {
    const m = /limiting the total time product temperature is between (\d+) and (\d+) F to (\d+) hours or less/.exec(txt);
    ok('the cooling window and the hour limit in the safety note are the guideline\'s own figures',
       !!m && RTEXT.includes(`between ${m[1]} and ${m[2]} F to ${wordOf(+m[3])} hours or less`),
       m ? `the guideline says ${m[1]} to ${m[2]} F, ${m[3]} hours` : 'sentence not found in the PDF text layer');
  } else {
    skipped('the cooling window against the PDF text layer', 'AppendixA-2021.pdf absent or pdftotext unavailable');
  }
}

// ---- the identifiers, which are citations and not measurements -------------
/* These are NOT quantities. A guideline number and a document date are addresses, and the
   only thing that can go wrong with them is drift, which breaks the citation rather than
   the arithmetic. They are asserted as identifiers: tied to the link the page itself
   publishes, so the printed address and the clickable one cannot part company. */
{
  const href = /href="https:\/\/www\.fsis\.usda\.gov\/guidelines\/([0-9-]+)"/.exec(html);
  ok('identifier: the guideline number printed in the caption is the one in the link the page publishes',
     !!href && RTEXT.includes(`(FSIS-GD-${href[1]}, December 2021),`) &&
     RTEXT.includes(`FSIS-GD-${href[1]}, December 2021,`),
     href ? `FSIS-GD-${href[1]}, printed in the figure caption and again in the sources note` : 'link not found');
  const pmids = [...html.matchAll(/href="https:\/\/pubmed\.ncbi\.nlm\.nih\.gov\/(\d+)\/"/g)].map(m => m[1]);
  const RECS = ['juneja.json', 'epmc_25364923.json', 'epmc_17493070.json',
                'epmc_22463921.json', 'epmc_6470949.json', 'epmc_34695251.json'];
  const want = RECS.map(r => abstractOf(r)).filter(Boolean).map(r => r.pmid).sort();
  ok('identifier: every PubMed link on the page resolves to a record pinned in this directory, and every pinned record is linked',
     want.length === RECS.length && JSON.stringify([...new Set(pmids)].sort()) === JSON.stringify(want),
     `${pmids.length} links: ${[...new Set(pmids)].sort().join(', ')}`);
}

// ---- the static control labels a reader sees before any script runs --------
/* Rule: never assert the literal inside an element the page's own JavaScript overwrites,
   because the reader does not see it. But these labels ARE seen, twice over: with
   scripting off, and in the moment before hydration. So the check is not that the literal
   is some number, it is that the literal is what the control's own default value would
   produce. A slider default moved without moving its label is exactly the drift this
   catches. */
{
  const attrOf = (id, a) => {
    const el = new RegExp('<(?:input|select)[^>]*id="' + id + '"[^>]*>').exec(html);
    if (!el) return null;
    const m = new RegExp(a + '="([^"]*)"').exec(el[0]);
    return m ? m[1] : null;
  };
  const selOf = id => {
    const blk = new RegExp('<select id="' + id + '"[\\s\\S]*?</select>').exec(html);
    const m = blk && /<option value="(\d+)" selected>/.exec(blk[0]);
    return m ? +m[1] : null;
  };
  const nowOf = id => {
    const m = new RegExp('<span class="now" id="' + id + '-now">([^<]*)</span>').exec(html);
    return m ? m[1].replace(/&nbsp;/g, ' ').replace(/&deg;/g, '').replace(/&sup2;/g, '2').trim() : null;
  };
  // instrument 1: the label names the two adjacent rows the slider's default lands on
  const z1 = C3[selOf('zfat')][+attrOf('zrow', 'value')].F;
  const z2 = C3[selOf('zfat')][+attrOf('zrow', 'value') + 1].F;
  ok('the pre-script label on instrument 1 names the row pair its slider actually defaults to',
     nowOf('zrow') === `${z1} and ${z2} F`, `default lands on ${z1} and ${z2} F, label reads "${nowOf('zrow')}"`);
  // instrument 4: three labels, three sliders, one column
  const cc = C3[selOf('cfat')];
  const cRow = k => cc[+attrOf(k, 'value')].F;
  ok('the three pre-script row labels on instrument 4 name the rows its sliders actually default to',
     nowOf('c1') === `${cRow('c1')} F` && nowOf('c2') === `${cRow('c2')} F` && nowOf('c3') === `${cRow('c3')} F`,
     `${cRow('c1')} / ${cRow('c2')} / ${cRow('c3')} F at ${selOf('cfat') + 1}% fat`);
  // and those defaults are deliberately the triple the argument turns on, not an arbitrary three
  ok('and those defaults are the strongest triple the scan found, so the instrument opens on the case in the prose',
     selOf('cfat') + 1 === S3.best.fat && cRow('c1') === S3.best.A.F &&
     cRow('c2') === S3.best.B.F && cRow('c3') === S3.best.C.F,
     `${S3.best.fat}% fat, ${S3.best.A.F}/${S3.best.B.F}/${S3.best.C.F} F`);
  // instrument 2 and 5: a dose and a roughness, each printed to the decimals its step implies
  ok('the pre-script dose label on instrument 2 is its slider default, at the printed precision',
     nowOf('sdose') === `${F(+attrOf('sdose', 'value'), 2)} mg/cm2`,
     `slider value ${attrOf('sdose', 'value')}, label reads "${nowOf('sdose')}"`);
  ok('the pre-script roughness label on instrument 5 is its slider default, at the printed precision',
     nowOf('rough') === F(+attrOf('rough', 'value'), 2),
     `slider value ${attrOf('rough', 'value')}, label reads "${nowOf('rough')}"`);
  // and the dose slider stops where the inequality does, which the limitations section claims
  ok('the dose slider\'s upper stop is the reference dose the limitations section says it is',
     +attrOf('sdose', 'max') === REF_DOSE && RTEXT.includes(`gives a ceiling above it`),
     `max ${attrOf('sdose', 'max')} mg/cm2 against a reference dose of ${REF_DOSE}`);
}

// ─────────────────────────────────────────────────────────────────────────────
// 7. the page as a document
// ─────────────────────────────────────────────────────────────────────────────
ok('the load-bearing closing tags are present', /<\/script>\s*<\/body>\s*<\/html>\s*$/.test(html), 'ends with </script></body></html>');
{
  const m = /<script type="application\/ld\+json">([\s\S]*?)<\/script>/.exec(html);
  let o = null, err = '';
  try { o = JSON.parse(m[1]); } catch (e) { err = e.message; }
  ok('the JSON-LD block parses and carries the Article fields', !!o && o['@type'] === 'Article' &&
     o.datePublished === '2026-08-30' && o.dateModified === '2026-08-30' &&
     o.url === 'https://artwaste.land/strata/the-two-tables/', err || `datePublished ${o && o.datePublished}`);
}
{
  const canon = /<link rel="canonical" href="([^"]+)"/.exec(html)[1];
  const og = /<meta property="og:url" content="([^"]+)"/.exec(html)[1];
  ok('canonical and og:url agree', canon === og && canon === 'https://artwaste.land/strata/the-two-tables/', canon);
}
{
  // built from a code point so this file does not itself carry the character it bans
  const EMDASH = String.fromCharCode(0x2014);
  const files = [PAGE, MD, path.join(HERE, 'README.md'), path.join(HERE, 'verify-the-two-tables.mjs')];
  const bad = files.filter(f => fs.existsSync(f) && fs.readFileSync(f, 'utf8').includes(EMDASH));
  ok('no em dash in any of this layer\'s own files', bad.length === 0, bad.length ? bad.join(', ') : `${files.length} files clean`);
}
{
  const md = fs.readFileSync(MD, 'utf8');
  ok('frontmatter is dated 2026-08-30, published, and in a real seam',
     /^date: 2026-08-30$/m.test(md) && /^draft: false$/m.test(md) && /^seam: "mechanism"$/m.test(md));
  const rel8 = [...md.matchAll(/^  - to: (\S+)$/gm)].map(m => m[1]);
  const missing = rel8.filter(s => !fs.existsSync(path.join(ROOT, 'src', 'content', 'strata', s + '.md')));
  ok('every relates target exists on disk', rel8.length >= 2 && rel8.length <= 4 && missing.length === 0,
     `${rel8.length} edges: ${rel8.join(', ')}` + (missing.length ? `; MISSING ${missing}` : ''));
  const pl = /^plain: "(.*)"$/m.exec(md)[1];
  ok('the plain placard is one line, 90 to 420 characters, no em dash, no raw quote',
     pl.length >= 90 && pl.length <= 420 && !pl.includes(String.fromCharCode(0x2014)) && !pl.includes('"'), `${pl.length} chars`);
  ok('the placard\'s number appears in the layer it describes and is the family floor',
     pl.includes(EXPECT.mmWorst) && !pl.includes(EXPECT.worst3), `placard cites ${EXPECT.mmWorst}`);
}

console.log('');
console.log(`${pass} passed, ${fail} failed, ${skip} skipped.`);
if (fail) { console.error('VERIFICATION FAILED'); process.exit(1); }
/* A skipped assertion is an assertion that did not run, and a suite that exits 0 with
   five of its source checks silently absent is a suite that cannot fail for the reason
   it exists. Every pinned file is on disk; if one goes missing, say so and exit non-zero
   rather than reporting green over a smaller suite. */
if (skip) {
  console.error(`INCOMPLETE: ${skip} check(s) could not run because a pinned data file is missing.`);
  console.error('Re-fetch research/the-two-tables/data/ and run again. Green over a shrunken suite is not green.');
  process.exit(2);
}
