#!/usr/bin/env node
// verify-the-apparatus-is-the-finding.mjs
//
// Recomputes every number the page displays, from the pinned primary sources, and
// string-matches the rendered figures out of the HTML. Exits non-zero on any disagreement.
//
// Run:  node research/the-apparatus-is-the-finding/verify-the-apparatus-is-the-finding.mjs
//
// PROTOCOL, FIXED BEFORE ANY RESULT WAS SEEN (see research/.../README.md for the long form):
//   object     : three published datasets, each carrying a comparison whose two arms were
//                produced by different measuring apparatus.
//   instruments: (1) a literal "(b)(4)" string counter; (2) a counter of the glyphs OCR
//                leaves where a redaction box was, specified from ONE letter and then run
//                unchanged over all 458; (3) plain arithmetic on a 61-row satellite series;
//                (4) decade sums of GBIF year facets.
//   prediction : holding the apparatus fixed moves or inverts findings 1 and 2. Finding 3
//                is subjected to a control that can kill it, and the result of that control
//                is reported either way.
//   success    : every displayed figure reproduces; the poison controls are REJECTED; the
//                both-arms fault trips no differential check.

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

const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, '..', '..');
const DATA = path.join(HERE, 'data');
const PAGE = path.join(ROOT, 'public', 'strata', 'the-apparatus-is-the-finding', 'index.html');

let pass = 0, fail = 0;
const failures = [];
function ok(label, cond, detail) {
  if (cond) { pass++; console.log(`PASS ${String(pass + fail).padStart(3, '0')}  ${label}${detail ? '  ' + detail : ''}`); }
  else { fail++; failures.push(label); console.log(`FAIL ${String(pass + fail).padStart(3, '0')}  ${label}${detail ? '  ' + detail : ''}`); }
}
function near(label, a, b, tol, detail) { ok(label, Math.abs(a - b) <= tol, detail || `${a} vs ${b} (tol ${tol})`); }

// ---------------------------------------------------------------- pinned sources
const SHA = {
  'transparency-crl-0001-of-0001.json.gz': '70cbed3528a9db5fd590bcb41141d05510203bc606eb12e2c5163e279a20f998',
  'infra_global_time_series_v20230816.csv': '289bf6765494052c048dd35e963d76e88048233904dd44b028e65c6b9e5cd2af',
  'gbif-plant-holotypes-by-year.json': '202731ebe517ae1399d14402d7ba91bf6c79ac2ab24cf88a29aeb6dea183ac54',
  'gbif-plant-specimens-by-year.json': 'ae1690900725e336cdf9f1cb2dc13ccb86a783dc73234550c5aabffbc41568af',
  'gbif-animal-holotypes-by-year.json': '1d4c63959c49bf148190108580fd53625bfbcd69ae6df31a1dcd3e4b6d1b0a82',
  'gbif-animal-specimens-by-year.json': '6d4f7d0bc8694dbc728f69e82de5a3078cefff82e0ed2aa58bdd488f9798ceb1',
  'gbif-plant-holotypes-by-year-unfiltered.json': 'd177ccb3cc3665439c9865e06d1c43adc52c040e15edd48e5583427294777da6'
};
console.log('--- pinned primary data -------------------------------------------------');
for (const [f, want] of Object.entries(SHA)) {
  const p = path.join(DATA, f);
  if (!fs.existsSync(p)) { ok(`pinned file present: ${f}`, false, '(missing)'); continue; }
  const got = crypto.createHash('sha256').update(fs.readFileSync(p)).digest('hex');
  ok(`pinned file matches its recorded SHA-256: ${f}`, got === want, got.slice(0, 16));
}
if (fail) { console.log('\nCannot continue without the pinned sources.'); process.exit(1); }

const CRL = JSON.parse(zlib.gunzipSync(fs.readFileSync(path.join(DATA, 'transparency-crl-0001-of-0001.json.gz'))).toString('utf8'));
const CSV = fs.readFileSync(path.join(DATA, 'infra_global_time_series_v20230816.csv'), 'utf8').trim();
const FAC = f => {
  const d = JSON.parse(fs.readFileSync(path.join(DATA, f), 'utf8'));
  const o = {};
  for (const c of d.facets.find(x => x.field === 'YEAR').counts) o[c.name] = c.count;
  return { total: d.count, years: o };
};
const GB = {
  plantHolo: FAC('gbif-plant-holotypes-by-year.json'),
  plantAll: FAC('gbif-plant-specimens-by-year.json'),
  animalHolo: FAC('gbif-animal-holotypes-by-year.json'),
  animalAll: FAC('gbif-animal-specimens-by-year.json')
};
// The same plant-holotype query without basisOfRecord=PRESERVED_SPECIMEN, pinned so that the
// sensitivity figures the page prints are checked here rather than taken on trust.
const GB_UNFILTERED = FAC('gbif-plant-holotypes-by-year-unfiltered.json');

const HTML = fs.readFileSync(PAGE, 'utf8');
const ISLAND = JSON.parse(HTML.slice(
  HTML.indexOf('>', HTML.indexOf('<script type="application/json" id="aif-data"')) + 1,
  HTML.indexOf('</script>', HTML.indexOf('<script type="application/json" id="aif-data"'))
));
// what the reader actually sees: no scripts, no styles, no comments, no attributes
const TEXT = HTML
  .replace(/<script[\s\S]*?<\/script>/gi, ' ')
  .replace(/<style[\s\S]*?<\/style>/gi, ' ')
  .replace(/<!--[\s\S]*?-->/g, ' ')
  .replace(/<[^>]*>/g, ' ')
  .replace(/&middot;/g, '.').replace(/&times;/g, 'x').replace(/&amp;/g, '&')
  .replace(/&copy;/g, '©').replace(/&reg;/g, '®')
  .replace(/&larr;/g, '<-').replace(/&lt;/g, '<').replace(/&gt;/g, '>')
  .replace(/\s+/g, ' ');   // one space between words, so a phrase check is not defeated by markup

const shown = [];
// Count a rendered figure only where it stands as a whole numeric token, so that "0.80"
// inside "0.805" and "25" inside "1,258" do not paper over a corrupted occurrence. The
// expected COUNT is asserted, not mere presence: mutating any one of several occurrences
// of the same figure has to go red.
function countFig(text, s) {
  let n = 0, i = 0;
  while ((i = text.indexOf(s, i)) >= 0) {
    const before = i === 0 ? ' ' : text[i - 1];
    const after = text.slice(i + s.length);
    if (!/[0-9.,+\-]/.test(before) && !/^[0-9]/.test(after) && !/^[.,][0-9]/.test(after)) n++;
    i += s.length;
  }
  return n;
}
const SHOW_DEBUG = process.argv.includes('--figure-counts');
// How many whole-token occurrences of each rendered figure the served HTML must carry.
// Written down once, so that corrupting ONE of several occurrences drops the count and
// goes red. A figure missing from this table is itself a failure.
const EXPECTED = {
  '458': 8,
  '309': 2,
  '149': 2,
  '0.229': 1,
  '0.076': 1,
  '2.99': 1,
  '162': 5,
  '296': 2,
  '443': 2,
  '96.7': 2,
  '5.19': 4,
  '3.95': 2,
  '0.337': 2,
  '0.333': 2,
  '1.011': 3,
  '0.354': 1,
  '0.283': 1,
  '0.80': 1,
  '0.290': 1,
  '0.241': 2,
  '1.1': 1,
  '295': 1,
  '148': 1,
  '0.266': 1,
  '0.051': 1,
  '0.072': 1,
  '0.282': 1,
  '7,164': 1,
  '8,389': 2,
  '+17.1': 1,
  '+3.0': 1,
  '979': 1,
  '79.9': 1,
  '1,225': 1,
  '+716': 1,
  '25': 2,
  '8,464': 1,
  '623': 1,
  '130': 1,
  '1,276': 1,
  '2,651': 1,
  '2020-10-01': 2,
  '2021-06-01': 2,
  '2021-12-01': 2,
  '19,285': 3,
  '5,100': 3,
  '3.78': 1,
  '3,052': 1,
  '640': 1,
  '5,855': 1,
  '746': 1,
  '0.210': 1,
  '0.127': 1,
  '0.943': 1,
  '0.805': 2,
  '157': 1,
  '17': 1,
  '0.302': 1,
  '0.001': 2,
  '0.624': 1,
  '6.4': 1,
  '1.3': 1,
  '9.0': 1,
  '98.8': 1,
  '99.0': 1,
  '5.63': 1,
  '4.95': 1,
  '14': 4,
  '0.945': 2,
  '0.163': 1,
  '1.08': 1,
  '81': 1,
  '0.067': 1,
  '0.002': 1,
  '201': 2,
  '98': 1,
  '0.750': 1,
  '0.830': 1,
  '1.95': 1,
  '0.97': 1,
  '1.01': 1,
  '19,633': 1,
  '6,853': 1,
  // Provenance, identifiers and free parameters. These sit in prose and in the apparatus footer,
  // nothing on the page rewrites them at runtime, and until now not one of them was asserted: a
  // mutation test corrupted three of them and this file stayed green with 252 assertions.
  '1,068,107': 1,
  '2026-08-26': 2,
  '1,000': 6,
  '2,498': 2,
  '2.5': 2,
  '42e0cc14b63ba5491f458147ca33206a': 1,
  '10.6084/m9.figshare.24309475': 1,
  '625': 3,
  'PMC10764273': 1,
  '61': 1,
  '16': 2,
  '23': 2,
  '80': 1,
  '8,642': 1,
  '8,552': 1,
  '9,829': 1,
  '9,715': 1,
  '11,192': 1,
  '11,040': 1,
  '1800,2026': 1,
  '2026-08-30': 2,
  '13,478': 1,
  '14,397': 1,
  '13,142': 1,
  '15,530': 1,
  '18,310': 1,
  '20,293': 1,
  '25,800': 1,
  '13,399': 1,
  '15,451': 1,
  '12,070': 1,
  '25,027': 1,
  '14,088': 1,
  '36,812': 1,
  '15,444': 1,
  '31,530': 1,
  '15,177': 1,
  '30,016': 1,
  '11,394': 1,
  '24,279': 1,
  '8,967': 1,
  '22,529': 1,
  '13,593': 1,
  '1.5': 1,
  '999': 3,
  'CC0 1.0': 1,
  'CC BY 4.0': 2,
  '403': 1
};
function shows(label, rendered) {
  shown.push(rendered);
  const got = countFig(TEXT, rendered);
  if (SHOW_DEBUG) { console.log(`      [count] ${JSON.stringify(rendered)} x${got}   (${label})`); return; }
  const want = EXPECTED[rendered];
  ok(`page displays ${label} as ${rendered}, ${want} time${want === 1 ? '' : 's'}`,
    want !== undefined && got === want, want === undefined ? 'NOT IN THE EXPECTED TABLE' : (got === want ? '' : `found ${got}`));
}
const fx = (v, d) => (Math.round(v * 10 ** d) / 10 ** d).toFixed(d);
const grp = v => String(Math.round(v)).replace(/\B(?=(\d{3})+(?!\d))/g, ',');

// ---------------------------------------------------------------- instruments
// Instrument 1: the literal FOIA exemption-4 mark.
const MARK = /\(b\)\s*\(4\)/g;
// Instrument 2: what OCR leaves where a black redaction box was. Written from ONE letter
// (CRL_BLA761400_20240820.pdf, which renders two redactions as "O@" and "(C)") and then run
// unchanged over all 458. Shares no code and no characters with instrument 1.
const BOX = /(?<![A-Za-z0-9])(?:[©®]|[oO@]{2,4})(?![A-Za-z0-9])/g;
// Instrument 3, added after the first two disagreed with the page's explanation of them: whether
// the text was produced by something that read a page image. A native PDF text layer emits nothing
// where the FDA seal sits, because the seal is artwork; a page reader emits its best guess at it.
// SEAL is the count of characters emitted before the first letterhead phrase, or -1 if there is none.
const LETTERHEAD = /U\.?\s?S\.?\s+FOOD|DEPARTMENT OF HEALTH|FOOD AND DRUG/i;
const JUNKTOK = /(?<![A-Za-z0-9])[A-Za-z]{1,2}(?![A-Za-z0-9])/g;
const REALSHORT = new Set(['a', 'A', 'I', 'i', 'of', 'OF', 'to', 'TO', 'in', 'IN', 'is', 'IS', 'it', 'IT',
  'be', 'BE', 'by', 'BY', 'or', 'OR', 'on', 'ON', 'as', 'AS', 'at', 'AT', 'an', 'AN', 'if', 'IF', 'no', 'NO',
  'do', 'DO', 'we', 'WE', 'so', 'SO', 'us', 'US', 'MD', 'mg', 'ml', 'Dr', 'PhD', 'Mr', 'Ms', 'II', 'III',
  'IV', 'V', 'X', 'C', 'F', 'pH', 'vs', 'et', 'al', 'g', 'L', 'mL', 'kg', 'n', 'p', 'e', 'U']);
const countMarks = t => (t.match(MARK) || []).length;
const countBoxes = t => (t.match(BOX) || []).length;
const sealPrefix = t => { const m = LETTERHEAD.exec(t); return m ? t.slice(0, m.index).trim().length : -1; };
const countJunk = t => (t.match(JUNKTOK) || []).filter(x => !REALSHORT.has(x)).length;

function featurise(records) {
  return records.map(r => {
    const t = r.text || '';
    const y = parseInt(r.letter_year, 10);
    return [t.length, countMarks(t), countBoxes(t),
      Number.isFinite(y) ? y : 0,
      r.approval_status === 'Unapproved' ? 1 : 0,
      (r.file_name || '').startsWith('CRL_') ? 0 : 1,
      sealPrefix(t), countJunk(t)];
  });
}
const ROWS = featurise(CRL.results);
const [CH, MK, BX, YR, ST, PI, SP, JK] = [0, 1, 2, 3, 4, 5, 6, 7];
const agg = (rows, pick) => {
  let n = 0, c = 0, h = 0;
  for (const r of rows) { n++; c += r[CH]; h += pick(r); }
  return { n, chars: c, hits: h, per1k: c > 0 ? 1000 * h / c : NaN };
};
const pMarks = r => r[MK], pBoxes = r => r[BX], pBoth = r => r[MK] + r[BX];
const sel = f => ROWS.filter(f);
const rng = seed => { let x = seed >>> 0; return () => { x = (1664525 * x + 1013904223) >>> 0; return x / 4294967296; }; };
function permutationP(a, b, pick, seed, N = 999) {
  const all = a.concat(b), na = a.length;
  const obs = Math.abs(agg(a, pick).per1k - agg(b, pick).per1k);
  const rnd = rng(seed); let ge = 0;
  for (let t = 0; t < N; t++) {
    const s = all.slice();
    for (let i = s.length - 1; i > 0; i--) { const j = Math.floor(rnd() * (i + 1)); const q = s[i]; s[i] = s[j]; s[j] = q; }
    if (Math.abs(agg(s.slice(0, na), pick).per1k - agg(s.slice(na), pick).per1k) >= obs - 1e-12) ge++;
  }
  return (ge + 1) / (N + 1);
}

console.log('\n--- the page holds the data it says it holds -----------------------------');
ok('the page embeds one row per record and they match this recomputation',
  ISLAND.crl.rows.length === ROWS.length &&
  ISLAND.crl.rows.every((r, i) => r.length === 8 && r.every((v, j) => v === ROWS[i][j])),
  `${ISLAND.crl.rows.length} rows`);
ok('the page embeds the satellite series byte for byte', ISLAND.infra.trim() === CSV);
for (const k of Object.keys(GB)) {
  ok(`the page embeds the GBIF ${k} facet unchanged`,
    JSON.stringify(ISLAND.gbif[k]) === JSON.stringify(GB[k]));
}

// ---------------------------------------------------------------- PANEL ONE
console.log('\n--- panel one: openFDA Complete Response Letters -------------------------');
const appr = agg(sel(r => r[ST] === 0), pMarks), unap = agg(sel(r => r[ST] === 1), pMarks);
const apprT = agg(sel(r => r[ST] === 0), pBoth), unapT = agg(sel(r => r[ST] === 1), pBoth);
const nat = agg(sel(r => r[PI] === 0), pMarks), scn = agg(sel(r => r[PI] === 1), pMarks);
const natB = agg(sel(r => r[PI] === 0), pBoxes), scnB = agg(sel(r => r[PI] === 1), pBoxes);
const natT = agg(sel(r => r[PI] === 0), pBoth), scnT = agg(sel(r => r[PI] === 1), pBoth);
const y24a = agg(sel(r => r[ST] === 0 && r[YR] === 2024), pMarks);
const y24u = agg(sel(r => r[ST] === 1 && r[YR] === 2024), pMarks);
const cross = [[0, 0], [0, 0]];
for (const r of ROWS) cross[r[ST]][r[PI]]++;
const diag = cross[0][1] + cross[1][0];

// ANCHOR the page did not choose: openFDA publishes the record count inside its own export.
ok('ANCHOR: the parse reproduces openFDA’s own published record count',
  ROWS.length === CRL.meta.results.total, `${ROWS.length} vs meta.results.total ${CRL.meta.results.total}`);
ok('ANCHOR: the export date in the file is the one the page prints',
  CRL.meta.last_updated === ISLAND.crl.last_updated, CRL.meta.last_updated);
// ANCHOR on the instrument: FOIA has nine numbered exemptions.
// The capture is one OR TWO digits, so 0 and anything from 10 up are reachable and the assertion
// can actually fail. A one-digit capture would have made "in 1..9" true by construction.
const exemptions = [...CRL.results.map(r => r.text || '').join('\n').matchAll(/\(b\)\s*\((\d{1,2})\)/g)]
  .map(m => Number(m[1]));
const uniqEx = [...new Set(exemptions)].sort((a, b) => a - b);
ok('ANCHOR: every FOIA exemption number the parse emits is in 1..9',
  uniqEx.length > 0 && uniqEx.every(d => d >= 1 && d <= 9), `saw ${uniqEx.join(', ')}`);
ok('and exemption 4 is the modal one, as trade-secret redaction requires',
  exemptions.filter(d => d === 4).length > exemptions.filter(d => d !== 4).length / 2);

shows('the record count', '458');
shows('the approved count', '309');
shows('the unapproved count', '149');
shows('the naive unapproved density', fx(unap.per1k, 3));
shows('the naive approved density', fx(appr.per1k, 3));
shows('the naive ratio', fx(unap.per1k / appr.per1k, 2));
shows('the transparency-release count', String(nat.n));
shows('the approval-package count', String(scn.n));
shows('the diagonal count', String(diag));
shows('the diagonal share', fx(100 * diag / ROWS.length, 1));
shows('the marker-instrument pipeline ratio', fx(nat.per1k / scn.per1k, 2));
shows('the glyph-instrument pipeline ratio', fx(scnB.per1k / natB.per1k, 2));
shows('the release total density', fx(natT.per1k, 3));
shows('the scan total density', fx(scnT.per1k, 3));
shows('the two-instrument pipeline ratio', fx(natT.per1k / scnT.per1k, 3));
shows('the approved total density', fx(apprT.per1k, 3));
shows('the unapproved total density', fx(unapT.per1k, 3));
shows('the inverted ratio', fx(unapT.per1k / apprT.per1k, 2));
shows('the 2024 approved density', fx(y24a.per1k, 3));
shows('the 2024 unapproved density', fx(y24u.per1k, 3));
shows('the two-instrument agreement percentage', fx(Math.abs(100 * (natT.per1k / scnT.per1k - 1)), 1));

ok('the naive comparison really does show a large gap in the published direction',
  unap.per1k / appr.per1k > 2.5, `${fx(unap.per1k / appr.per1k, 3)}x`);
ok('INDEPENDENT ROUTE: the two instruments disagree about which pipeline is more redacted',
  nat.per1k > scn.per1k && scnB.per1k > natB.per1k,
  `marks ${fx(nat.per1k / scn.per1k, 2)}x one way, glyphs ${fx(scnB.per1k / natB.per1k, 2)}x the other`);
ok('and together they put the two pipelines within 5 percent of each other',
  Math.abs(natT.per1k / scnT.per1k - 1) < 0.05, `${fx(natT.per1k / scnT.per1k, 4)}`);
ok('the headline inverts once the instrument stops reading the scanner',
  unapT.per1k / apprT.per1k < 1, `${fx(unapT.per1k / apprT.per1k, 3)}`);
ok('the year control points the same way (inside 2024 the gap reverses)',
  y24a.per1k > y24u.per1k, `${fx(y24a.per1k, 3)} vs ${fx(y24u.per1k, 3)}`);
ok('the grouping variable and the batch are more than 96 percent collinear',
  diag / ROWS.length > 0.96, `${fx(100 * diag / ROWS.length, 1)} percent`);

// ------ INSTRUMENT 3. This is what killed the page's first explanation of panel one, which was
// that one arm is a native PDF text layer and the other a flatbed scan. It is not: both arms carry
// the signature of something that read a page image, at rates that do not separate them.
const ocrOf = f => {
  let n = 0, g = 0, jk = 0, ch = 0;
  for (const r of ROWS.filter(f)) { jk += r[JK]; ch += r[CH]; if (r[SP] >= 0) { n++; if (r[SP] > 0) g++; } }
  return { n, g, pct: 100 * g / n, junk1k: 1000 * jk / ch };
};
const ocrRel = ocrOf(r => r[PI] === 0), ocrPkg = ocrOf(r => r[PI] === 1);
shows('the transparency-release letterhead-garble share', fx(ocrRel.pct, 1));
shows('the approval-package letterhead-garble share', fx(ocrPkg.pct, 1));
shows('the transparency-release junk-token density', fx(ocrRel.junk1k, 2));
shows('the approval-package junk-token density', fx(ocrPkg.junk1k, 2));
shows('the junk-token gap between the batches', fx(100 * (ocrRel.junk1k / ocrPkg.junk1k - 1), 0));
ok('INSTRUMENT 3: the transparency-release arm is NOT a clean text layer, it is page-read too',
  ocrRel.pct > 90, `${ocrRel.g} of ${ocrRel.n} letters carry garble before the letterhead`);
ok('and the two batches do not separate on that signature, though their marker densities differ 5x',
  Math.abs(ocrRel.pct - ocrPkg.pct) < 5 && Math.abs(ocrRel.junk1k / ocrPkg.junk1k - 1) < 0.25,
  `${fx(ocrRel.pct, 1)} vs ${fx(ocrPkg.pct, 1)} percent; junk ${fx(ocrRel.junk1k, 2)} vs ${fx(ocrPkg.junk1k, 2)}`);
// The retired claims, by phrase. The words themselves still appear where the page REFUTES them,
// so a bare word test would be satisfied by deleting the refutation, which is the wrong direction.
{
  const RETIRED = ['It was the scanner', 'flatbed', 'a scan of paper', 'native PDF text layer',
    'scanner glyphs', 'the difference between reading a PDF and photographing one',
    'approval-package scan', 'read by optical character recognition'];
  const still = RETIRED.filter(p => TEXT.toLowerCase().includes(p.toLowerCase()));
  ok('the retired mechanism claims are gone from the page', still.length === 0, still.join(' | '));
  ok('and the page says out loud that the first explanation was wrong',
    /That story is wrong and\s+the file says so/i.test(TEXT));
}
ok('and the page discloses that it cannot say which step inside that pipeline differs',
  /cannot tell you\s+which step inside it differs/i.test(TEXT));

// ------ how strong is any of it? The page prints these, so they are asserted here.
const SEED = 20260830;
const pPipeBoth = permutationP(sel(r => r[PI] === 0), sel(r => r[PI] === 1), pBoth, SEED);
const pStatBoth = permutationP(sel(r => r[ST] === 0), sel(r => r[ST] === 1), pBoth, SEED);
const pStatMark = permutationP(sel(r => r[ST] === 0), sel(r => r[ST] === 1), pMarks, SEED);
shows('the batch permutation p on both instruments', fx(pPipeBoth, 3));
shows('the status permutation p on both instruments', fx(pStatBoth, 3));
shows('the status permutation p on the marker alone', fx(pStatMark, 3));
ok('the marker-only status gap is decisive', pStatMark < 0.05, `p = ${fx(pStatMark, 3)}`);
ok('LOAD-BEARING: with both instruments the two batches are indistinguishable',
  pPipeBoth > 0.5, `p = ${fx(pPipeBoth, 3)}`);
ok('NOT LOAD-BEARING, and the page says so: the 0.80 reversal is not significant',
  pStatBoth > 0.05, `p = ${fx(pStatBoth, 3)}`);
{
  const dens = r => pBoth(r) / Math.max(r[CH], 1);
  const trimmed = ROWS.slice().sort((x, y) =>
    (dens(y) - dens(x)) || (y[CH] - x[CH]) || (y[MK] - x[MK]) || (y[BX] - x[BX]) || (y[YR] - x[YR])).slice(20);
  const tr = agg(trimmed.filter(r => r[ST] === 1), pBoth).per1k / agg(trimmed.filter(r => r[ST] === 0), pBoth).per1k;
  shows('the ratio after trimming the twenty densest letters', fx(tr, 2));
  ok('and it does not survive trimming twenty of 458 letters, which the page prints',
    tr > 1, `${fx(tr, 2)} after the trim, against ${fx(unapT.per1k / apprT.per1k, 2)} before`);
  const CLAIMED = ['the headline inverts', 'the finding inverts', 'It turns over',
    'does not merely weaken', 'the finding inverts under two independent controls'];
  const left = CLAIMED.filter(p => TEXT.toLowerCase().includes(p.toLowerCase()));
  ok('the page no longer asserts an inversion anywhere', left.length === 0, left.join(' | '));
  ok('and it says in so many words that the headline does not turn over',
    /does not turn over\. It goes away/i.test(TEXT) && /That is not\s+an inversion/i.test(TEXT));
}
{
  const a24 = sel(r => r[ST] === 0 && r[YR] === 2024);
  const a24rel = a24.filter(r => r[PI] === 0), a24pkg = a24.filter(r => r[PI] === 1);
  const share = 100 * agg(a24rel, pMarks).hits / agg(a24, pMarks).hits;
  shows('the 2024 approved arm size', String(a24.length));
  shows('the share of that arm\u2019s marks carried by two letters', fx(share, 0));
  shows('the 2024 approved density with those two letters removed', fx(agg(a24pkg, pMarks).per1k, 3));
  ok('the 2024 cut rests on two letters and the page prints that rather than calling it a control',
    a24.length === 14 && a24rel.length === 2 && share > 75 &&
    agg(a24pkg, pMarks).per1k < y24u.per1k,
    `${a24rel.length} of ${a24.length} letters carry ${fx(share, 0)} percent of the marks`);
  ok('and the page does not claim two independent controls',
    !/two independent controls/i.test(TEXT));
}

// The exhibit: a letter the marker counter scores at zero and that is plainly redacted.
const exRec = CRL.results.find(r => r.file_name === ISLAND.exhibit.file);
ok('the exhibit letter exists in the export', !!exRec, ISLAND.exhibit.file);
ok('the exhibit quote is verbatim from the export’s own text field',
  !!exRec && (exRec.text || '').replace(/\s+/g, ' ').includes(ISLAND.exhibit.quote));
ok('the marker counter really does score the exhibit at zero',
  !!exRec && countMarks(exRec.text || '') === 0, `marks = ${exRec ? countMarks(exRec.text) : '?'}`);
ok('and the glyph counter does not',
  !!exRec && countBoxes(exRec.text || '') > 0, `glyphs = ${exRec ? countBoxes(exRec.text) : '?'}`);
ok('the exhibit quote is rendered on the page', TEXT.includes('FEI'), 'the redacted establishment identifier');
ok('the exhibit sentence carries the marker count in the served HTML',
  TEXT.includes(`scores at ${countMarks(exRec.text || '')} redactions`));
// the two panel-one tables, cell by cell
shows('the cross-tab approved/scan cell', String(cross[0][1]), 1);
shows('the cross-tab unapproved/native cell', String(cross[1][0]), 1);
shows('the instrument table release marker density', fx(nat.per1k, 3), 1);
shows('the instrument table scan marker density', fx(scn.per1k, 3), 1);
shows('the instrument table release glyph density', fx(natB.per1k, 3), 1);
shows('the instrument table scan glyph density', fx(scnB.per1k, 3), 1);

// SENSITIVITY: two looser glyph sets must not change the conclusion.
{
  const variants = {
    'digits included': /(?<![A-Za-z0-9])(?:[©®]|[oO0@]{2,4})(?![A-Za-z0-9])/g,
    'glyph only': /(?<![A-Za-z0-9])[©®](?![A-Za-z0-9])/g
  };
  for (const [name, rx] of Object.entries(variants)) {
    let nc = 0, nh = 0, sc = 0, sh = 0;
    for (const r of CRL.results) {
      const t = r.text || '';
      const both = countMarks(t) + (t.match(rx) || []).length;
      if ((r.file_name || '').startsWith('CRL_')) { nc += t.length; nh += both; } else { sc += t.length; sh += both; }
    }
    const ratio = (1000 * nh / nc) / (1000 * sh / sc);
    // Printed in the SAME direction as the headline 1.011 (release over approval package). The page
    // used to print the reciprocals, 1.03 and 0.99, and invite the reader to compare them with 1.01.
    shows(`the ${name} variant ratio`, fx(ratio, 2));
    ok(`SENSITIVITY (${name}): the two batches still land within 5 percent`,
      Math.abs(ratio - 1) < 0.05, `ratio ${fx(ratio, 3)}`);
  }
}

// POISON CONTROL: doctor the DATA, re-run the UNMODIFIED counters, require the answer to move.
{
  const poisoned = CRL.results.map(r => ({
    ...r,
    text: (r.file_name || '').startsWith('CRL_') ? (r.text || '').replace(MARK, '####') : r.text
  }));
  const pr = featurise(poisoned);
  const pn = agg(pr.filter(r => r[PI] === 0), pBoth), ps = agg(pr.filter(r => r[PI] === 1), pBoth);
  ok('POISON CONTROL: stripping the markers from one pipeline breaks the agreement',
    Math.abs(pn.per1k / ps.per1k - 1) > 0.05, `poisoned ratio ${fx(pn.per1k / ps.per1k, 3)}`);
  const restored = featurise(CRL.results);
  ok('and the undoctored corpus is unchanged afterwards',
    restored.every((r, i) => r.every((v, j) => v === ROWS[i][j])));
}

// ---------------------------------------------------------------- PANEL TWO
console.log('\n--- panel two: Sentinel-1 offshore structures ----------------------------');
function parseCsv(text) {
  const lines = text.trim().split('\n'), head = lines[0].split(',');
  return lines.slice(1).map(l => {
    const p = l.split(','), o = {};
    head.forEach((h, j) => { o[h] = j === 0 ? p[j] : parseInt(p[j], 10); });
    return o;
  });
}
const TS = parseCsv(CSV);
const standing = r => r.oil + r.probable_oil + r.possible_oil + r.other + r.wind;
const median = a => { const s = [...a].sort((x, y) => x - y); const n = s.length; return n % 2 ? s[(n - 1) / 2] : (s[n / 2 - 1] + s[n / 2]) / 2; };
const DEC21 = TS[TS.length - 2];
const growthFrom = i => 100 * (DEC21.oil - TS[i].oil) / TS[i].oil;
const dOil = TS.slice(1).map((r, i) => r.oil - TS[i].oil);
const dTot = TS.slice(1).map((r, i) => standing(r) - standing(TS[i]));
const interiorOil = dOil.slice(3, dOil.length - 2).map(Math.abs);
const interiorTot = dTot.slice(3, dTot.length - 2).map(Math.abs);
const gain = DEC21.oil - TS[0].oil, add = TS[2].oil - TS[0].oil;
const dec17 = TS.find(r => r.detect_date === '2017-12-01');

ok('the series is 61 monthly rows, 2017-01-01 to 2022-01-01',
  TS.length === 61 && TS[0].detect_date === '2017-01-01' && TS[60].detect_date === '2022-01-01');
shows('the January 2017 oil count', grp(TS[0].oil));
shows('the December 2021 oil count', grp(DEC21.oil));
shows('the growth measured from January', '+' + fx(growthFrom(0), 1));
shows('the growth measured from March', '+' + fx(growthFrom(2), 1));
shows('the sixty-day addition', grp(add));
shows('the share of the five-year gain in the first sixty days', fx(100 * add / gain, 1));
shows('the five-year gain', grp(gain));
shows('the first monthly change', '+' + grp(dOil[0]));
shows('the interior median monthly change in oil', grp(median(interiorOil)));
shows('the December 2017 oil count', grp(dec17.oil));
shows('the final-month drop in the standing total', grp(-dTot[dTot.length - 1]));
shows('the interior median absolute monthly change in the standing total', grp(median(interiorTot)));
shows('the January 2017 unclassified count', grp(TS[0].other));
shows('the December 2021 unclassified count', grp(DEC21.other));

ok('the paper’s 16 percent reproduces from the file when measured from January',
  Math.abs(growthFrom(0) - 16) < 2, `${fx(growthFrom(0), 1)} percent`);
ok('and collapses when measured from March, two months later',
  growthFrom(2) < 5, `${fx(growthFrom(2), 1)} percent`);
ok('more than half the five-year gain arrives in the first two months',
  add / gain > 0.5, `${fx(100 * add / gain, 1)} percent`);
ok('the page calls them oil structures and two months, not platforms and sixty days',
  !/\bplatforms?\b/i.test(TEXT) && !/sixty days/i.test(TEXT));
ok('the first month is more than ten times the interior median monthly change',
  dOil[0] > 10 * median(interiorOil), `+${dOil[0]} against ${median(interiorOil)}`);
{
  const two = [];
  for (let i = 0; i + 2 < TS.length; i++) two.push(TS[i + 2].oil - TS[i].oil);
  const sorted = [...two].sort((a, b) => b - a);
  ok('no other two-month window in the record comes near the opening jump',
    sorted[0] === add && sorted[1] < add / 2, `largest ${sorted[0]}, next ${sorted[1]}`);
}
ok('ANCHOR (Sentinel-1B stopped operating 23 December 2021, per the paper’s Extended Data Fig. 1): the final month collapses',
  dTot[dTot.length - 1] < -median(interiorTot), `${dTot[dTot.length - 1]} against a median of ${median(interiorTot)}`);
ok('with the ramp finished, the detector records no net oil growth 2017-12 to 2021-12',
  dec17.oil >= DEC21.oil, `${dec17.oil} then ${DEC21.oil}`);
ok('the unclassified class more than doubles, which construction cannot explain',
  DEC21.other / TS[0].other > 2, `${TS[0].other} to ${DEC21.other}`);

// three defensible crossings
{
  const defs = [['oil', r => r.oil], ['oil+probable+possible', r => r.oil + r.probable_oil + r.possible_oil],
    ['oil_other', r => r.oil_other]];
  const hits = defs.map(([n, f]) => [n, (TS.find(r => r.wind > f(r)) || {}).detect_date]);
  for (const [n, d] of hits) { ok(`crossing under "${n}" is dated ${d}`, !!d); shows(`the ${n} crossing`, d); }
  ok('the three defensible definitions give three different crossing dates',
    new Set(hits.map(h => h[1])).size === 3, hits.map(h => h[1]).join(' / '));
}

// POISON CONTROL, rebuilt. The old one flattened the first two months, which made the statistic
// identically zero: it printed 0.0 percent and could not have gone red for any bug in any code path.
// This one reorders the same fifty-nine monthly changes. The endpoints, the total gain and the whole
// multiset of changes are preserved; only the shape moves. It runs through the SAME rampShare used
// on the real series, and it can genuinely fail: about four reorderings in a hundred still front-load.
{
  const rampShare = series => (series[2].oil - series[0].oil) / (series[series.length - 2].oil - series[0].oil);
  ok('the statistic under test is the one the page prints', Math.abs(rampShare(TS) - add / gain) < 1e-12,
    `${fx(100 * rampShare(TS), 1)} percent`);
  const deltas = []; for (let i = 1; i <= 59; i++) deltas.push(TS[i].oil - TS[i - 1].oil);
  const reordered = seed => {
    const d = deltas.slice(), rnd = rng(seed);
    for (let i = d.length - 1; i > 0; i--) { const j = Math.floor(rnd() * (i + 1)); const q = d[i]; d[i] = d[j]; d[j] = q; }
    const out = [{ ...TS[0] }]; let cur = TS[0].oil;
    for (let i = 0; i < 59; i++) { cur += d[i]; out.push({ ...TS[i + 1], oil: cur }); }
    out.push({ ...TS[60] });
    return out;
  };
  const one = reordered(20260830);
  ok('POISON CONTROL: the reordering preserves both endpoints and the whole multiset of monthly changes',
    one[0].oil === TS[0].oil && one[59].oil === TS[59].oil && one.length === TS.length &&
    JSON.stringify(one.slice(1, 60).map((r, i) => r.oil - one[i].oil).sort((a, b) => a - b)) ===
    JSON.stringify(deltas.slice().sort((a, b) => a - b)),
    `gain ${one[59].oil - one[0].oil} either way`);
  ok('POISON CONTROL: and it destroys the finding, through the same statistic',
    !(rampShare(one) > 0.5), `${fx(100 * rampShare(one), 1)} percent after reordering`);
  // the same reordering as a significance statement, which is what the page prints
  let ge = 0; const rnd = rng(20260830), obs = (deltas[0] + deltas[1]) / gain;
  for (let t = 0; t < 999; t++) {
    const d = deltas.slice();
    for (let i = d.length - 1; i > 0; i--) { const j = Math.floor(rnd() * (i + 1)); const q = d[i]; d[i] = d[j]; d[j] = q; }
    if ((d[0] + d[1]) / gain >= obs - 1e-12) ge++;
  }
  const pRamp = (ge + 1) / 1000;
  shows('the reordering p for panel two', fx(pRamp, 3));
  ok('POISON CONTROL: the front-loading is extreme against reorderings of the same changes',
    pRamp < 0.05, `p = ${fx(pRamp, 3)} over 999 reorderings, ${ge} at least as front-loaded`);
  ok('and the real series is unchanged afterwards', TS[0].oil === 7164 && TS[2].oil === 8143);
}

// ---------------------------------------------------------------- PANEL THREE
console.log('\n--- panel three: GBIF type specimens by decade ---------------------------');
const decades = fac => {
  const o = {};
  for (const y in fac.years) { const d = Math.floor(parseInt(y, 10) / 10) * 10; o[d] = (o[d] || 0) + fac.years[y]; }
  return o;
};
const ph = decades(GB.plantHolo), pa = decades(GB.plantAll);
const ah = decades(GB.animalHolo), aa = decades(GB.animalAll);
const DECS = [1900, 1910, 1920, 1930, 1940, 1950, 1960, 1970, 1980, 1990, 2000, 2010];
const perM = (h, a, d) => 1e6 * h[d] / a[d];
const pearson = (x, y) => {
  const n = x.length, mx = x.reduce((s, v) => s + v, 0) / n, my = y.reduce((s, v) => s + v, 0) / n;
  let sxy = 0, sxx = 0, syy = 0;
  for (let i = 0; i < n; i++) { sxy += (x[i] - mx) * (y[i] - my); sxx += (x[i] - mx) ** 2; syy += (y[i] - my) ** 2; }
  return sxy / Math.sqrt(sxx * syy);
};
const lp = DECS.map(d => Math.log(perM(ph, pa, d)));
const la = DECS.map(d => Math.log(perM(ah, aa, d)));
const r3 = pearson(lp, la);
const pIdx = perM(ph, pa, 2010) / perM(ph, pa, 1930);
const aIdx = perM(ah, aa, 2010) / perM(ah, aa, 1930);

// NOT AN ANCHOR, and the page no longer sells it as one. Every one of these queries carries a
// year=1800,2026 filter, so each matching record falls in exactly one bucket and the facet sum equals
// the reported count by construction. What it catches is a truncated or corrupted pinned file, which
// is worth catching; what it cannot catch is anything about the world.
for (const [k, fac] of Object.entries(GB)) {
  const sum = Object.values(fac.years).reduce((a, b) => a + b, 0);
  ok(`INTEGRITY (not an anchor): the ${k} year buckets sum to the count in the same file`,
    sum === fac.total, `${sum} vs ${fac.total}`);
}
ok('and the page says so rather than calling it an anchor',
  /sum to the reported total by construction/i.test(TEXT) && /catches a truncated file/i.test(TEXT));
// the filter sensitivity the page prints, now from a pinned file rather than from memory
{
  const dec = (fac, a, b) => Object.entries(fac.years)
    .filter(([y]) => +y >= a && +y <= b).reduce((s, [, v]) => s + v, 0);
  shows('the unfiltered 1930s plant holotype count', grp(dec(GB_UNFILTERED, 1930, 1939)));
  shows('the unfiltered 2010s plant holotype count', grp(dec(GB_UNFILTERED, 2010, 2019)));
  ok('SENSITIVITY: dropping basisOfRecord=PRESERVED_SPECIMEN does not change the shape',
    dec(GB_UNFILTERED, 1930, 1939) / dec(GB_UNFILTERED, 2010, 2019) > 2.5,
    `${fx(dec(GB_UNFILTERED, 1930, 1939) / dec(GB_UNFILTERED, 2010, 2019), 2)}x against ${fx(ph[1930] / ph[2010], 2)}x filtered`);
}
shows('the 1930s plant holotype count', grp(ph[1930]));
shows('the 2010s plant holotype count', grp(ph[2010]));
shows('the raw fall factor', fx(ph[1930] / ph[2010], 2));
shows('the 1930s plant types per million', grp(perM(ph, pa, 1930)));
shows('the 2010s plant types per million', grp(perM(ph, pa, 2010)));
shows('the 1930s animal types per million', grp(perM(ah, aa, 1930)));
shows('the 2010s animal types per million', grp(perM(ah, aa, 2010)));
shows('the plant index', fx(pIdx, 3));
shows('the animal index', fx(aIdx, 3));
shows('the correlation of the two logged curves', fx(r3, 3));

ok('the striking raw finding is real: plant holotypes fall more than threefold from the 1930s',
  ph[1930] / ph[2010] > 3, `${fx(ph[1930] / ph[2010], 2)}x`);
ok('DISCRIMINATING CONTROL: animals, untouched by any botanical digitisation programme, fall too',
  aIdx < 0.5, `animals index at ${fx(aIdx, 3)} against plants at ${fx(pIdx, 3)}`);
ok('and the two curves are the same curve across twelve decades',
  r3 > 0.85, `r = ${fx(r3, 3)}`);
ok('THE PANEL IS THEREFORE REPORTED AS A FAILURE, and the page says so',
  /did not survive its own control/i.test(TEXT) && /the explanation does not/i.test(TEXT));

// POISON CONTROL, rebuilt. The old one synthesised a perfectly flat animal curve, whose index is
// 1.000 by arithmetic identity: it could not have gone red for any bug anywhere. This one blends the
// REAL animal curve towards flat and walks the blend until the verdict flips, through the same
// verdict function used on the real data. The flip point is a number that can be wrong.
{
  const verdict = (h, a) => (perM(h, a, 2010) / perM(h, a, 1930)) < 0.5;   // true = animals collapse too
  ok('the verdict function reproduces the real result', verdict(ah, aa) === true, `index ${fx(aIdx, 3)}`);
  const flat = {}; for (const d of DECS) flat[d] = aa[d] * perM(ah, aa, 1930) / 1e6;
  const blend = l => { const o = {}; for (const d of DECS) o[d] = (1 - l) * ah[d] + l * flat[d]; return o; };
  let flip = null;
  for (let i = 0; i <= 1000; i++) { const l = i / 1000; if (!verdict(blend(l), aa)) { flip = l; break; } }
  ok('POISON CONTROL: blending the animal curve towards flat does flip the verdict',
    flip !== null && flip > 0.2 && flip < 0.8, `flips at ${fx(flip, 3)} of the way to flat`);
  ok('and the real curve is nowhere near that: it would have to move most of the way',
    flip > 0.4, `${fx(100 * flip, 0)} percent of the way to flat`);
  ok('and the real animal facet is unchanged afterwards',
    ah[2010] === decades(GB.animalHolo)[2010] && verdict(ah, aa) === true);
}

// ---------------------------------------------------------------- THE BENCH
console.log('\n--- the bench: one fault, one arm, then both -----------------------------');
const NAT = ROWS.filter(r => r[PI] === 0).slice()
  .sort((a, b) => (a[CH] - b[CH]) || (a[MK] - b[MK]) || (a[BX] - b[BX]));
const ARM_A = NAT.filter((_, i) => i % 2 === 0);
const ARM_B = NAT.filter((_, i) => i % 2 === 1);
// Derived here too, from the pinned corpus, rather than written down and compared with itself.
// The old line read `const P = 0.805` and the page's own 0.805 was string-matched against it, which
// asserted that two literals agreed and nothing else.
const glyphShare = f => { const rows = ROWS.filter(f); return agg(rows, pBoxes).hits / agg(rows, pBoth).hits; };
const G0 = glyphShare(r => r[PI] === 0), G1 = glyphShare(r => r[PI] === 1);
const P = Math.round(1000 * (G1 - G0) / (1 - G0)) / 1000;
ok('the fault fraction is DERIVED from the corpus, not asserted',
  Math.abs((G1 - G0) / (1 - G0) - P) < 5e-4 && P > 0.5 && P < 0.95,
  `glyph share ${fx(G0, 3)} in the release batch and ${fx(G1, 3)} in the approval package, so p = ${fx(P, 3)}`);
const ANCHOR_FACTOR = 1.5;
const faulted = (rows, p) => rows.map(r => { const k = Math.round(p * r[MK]); return [r[CH], r[MK] - k, r[BX] + k, r[YR], r[ST], r[PI], r[SP], r[JK]]; });
const lcg = seed => { let x = seed >>> 0; return () => { x = (1664525 * x + 1013904223) >>> 0; return x / 4294967296; }; };
function permP(a, b, pick, seed) {
  const all = a.concat(b), na = a.length, N = 999;
  const obs = Math.abs(agg(a, pick).per1k - agg(b, pick).per1k);
  const rnd = lcg(seed); let ge = 0;
  for (let t = 0; t < N; t++) {
    const s = all.slice();
    for (let i = s.length - 1; i > 0; i--) { const j = Math.floor(rnd() * (i + 1)); const tmp = s[i]; s[i] = s[j]; s[j] = tmp; }
    if (Math.abs(agg(s.slice(0, na), pick).per1k - agg(s.slice(na), pick).per1k) >= obs - 1e-12) ge++;
  }
  return (ge + 1) / (N + 1);
}
function state(mode, p, armA = ARM_A, armB = ARM_B) {
  const A = mode === 'none' ? armA : faulted(armA, p);
  const B = mode === 'both' ? faulted(armB, p) : armB;
  const mA = agg(A, pMarks), mB = agg(B, pMarks), tA = agg(A, pBoth), tB = agg(B, pBoth);
  const refuse = !(mA.chars > 0 && mB.chars > 0 && (mA.hits + mB.hits) > 0);
  const rel = 100 * (mA.per1k - mB.per1k) / ((mA.per1k + mB.per1k) / 2);
  const pv = refuse ? NaN : permP(A, B, pMarks, 20260830);
  const half = rows => { const e = [], o = []; rows.forEach((r, i) => (i % 2 ? o : e).push(r)); return Math.abs(agg(e, pMarks).per1k - agg(o, pMarks).per1k); };
  const between = Math.abs(mA.per1k - mB.per1k);
  const within = Math.max(half(A), half(B));
  const flags = {
    size: Math.abs(mA.n - mB.n) / ((mA.n + mB.n) / 2) > 0.10,
    balance: Math.abs(mA.chars / mA.n - mB.chars / mB.n) / ((mA.chars / mA.n + mB.chars / mB.n) / 2) > 0.10,
    gap: Math.abs(rel) > 50,
    perm: !refuse && pv < 0.05,
    split: between > within * 2,
    placebo: false,
    anchor: !(tA.per1k / mA.per1k < ANCHOR_FACTOR && tB.per1k / mB.per1k < ANCHOR_FACTOR)
  };
  return { mA, mB, tA, tB, rel, pv, flags, refuse, between, within,
    anchorA: tA.per1k / mA.per1k, anchorB: tB.per1k / mB.per1k };
}
const S0 = state('none', P), SA = state('a', P), SB = state('both', P);
const DIFFERENTIAL = ['size', 'balance', 'gap', 'perm', 'split', 'placebo'];
const nflag = s => DIFFERENTIAL.filter(k => s.flags[k]).length;

shows('the bench arm count', String(NAT.length));
shows('the measured fault fraction', fx(P, 3));
shows('the clean relative difference', fx(Math.abs(S0.rel), 0));
shows('the one-arm relative difference', fx(Math.abs(SA.rel), 0));
shows('the both-arms relative difference', fx(Math.abs(SB.rel), 0));
shows('the clean permutation p', fx(S0.pv, 3));
shows('the one-arm permutation p', fx(SA.pv, 3));
shows('the both-arms permutation p', fx(SB.pv, 3));
shows('the both-arms understatement factor', fx(S0.mA.per1k / SB.mA.per1k, 1));
shows('the clean anchor ratio', fx(Math.max(S0.anchorA, S0.anchorB), 1));
shows('the both-arms anchor ratio', fx(Math.max(SB.anchorA, SB.anchorB), 1));
shows('the clean split-half ratio', fx(S0.between / S0.within, 2));

ok('the two arms come from one population and the split is balanced on length',
  !S0.flags.balance && !S0.flags.size,
  `${grp(S0.mA.chars / S0.mA.n)} vs ${grp(S0.mB.chars / S0.mB.n)} characters`);
ok('CLEAN: no differential check fires on the untouched arms', nflag(S0) === 0, `${nflag(S0)} flags`);
ok('CLEAN: the absolute anchor is satisfied too', !S0.flags.anchor,
  `x${fx(S0.anchorA, 2)} and x${fx(S0.anchorB, 2)}`);
ok('POISON CONTROL: a fault on ONE arm is caught by at least three checks',
  nflag(SA) >= 3, `${nflag(SA)} differential flags: ${DIFFERENTIAL.filter(k => SA.flags[k]).join(', ')}`);
ok('POISON CONTROL ON THE CONTROL: the SAME fault on BOTH arms trips no differential check',
  nflag(SB) === 0, `${nflag(SB)} differential flags`);
ok('and the both-arms battery is not merely as clean as the untouched one, it is cleaner',
  Math.abs(SB.rel) < Math.abs(S0.rel) && SB.pv > S0.pv,
  `${fx(Math.abs(SB.rel), 1)} vs ${fx(Math.abs(S0.rel), 1)} percent, p ${fx(SB.pv, 3)} vs ${fx(S0.pv, 3)}`);
ok('while the answer it certifies is wrong by the factor the fault applied',
  S0.mA.per1k / SB.mA.per1k > 4, `reads ${fx(S0.mA.per1k / SB.mA.per1k, 2)}x low`);
ok('THE ONE NON-DIFFERENTIAL CHECK SEES IT', SB.flags.anchor,
  `anchor x${fx(SB.anchorA, 2)} and x${fx(SB.anchorB, 2)} against a limit of ${ANCHOR_FACTOR}`);
ok('STRUCTURAL (no RNG): the both-arms fault leaves the relative arm difference within 10 points',
  Math.abs(Math.abs(SB.rel) - Math.abs(S0.rel)) < 10,
  `${fx(Math.abs(S0.rel), 1)} then ${fx(Math.abs(SB.rel), 1)}`);
ok('STRUCTURAL (no RNG): the one-arm fault moves it by more than 100 points',
  Math.abs(SA.rel) - Math.abs(S0.rel) > 100, `${fx(Math.abs(SA.rel), 1)}`);

// ------ THE SWEEP. The claim "no differential check fires on the both-arms setting" was previously
// asserted at exactly one value of p, on a control the reader can move continuously. It is false at
// about half of the settings the slider reaches, for a reason that is now content on the page. So the
// whole grid is swept here, at full permutation reps, and the band the page prints is asserted.
{
  const grid = [];
  for (let i = 0; i < 201; i++) grid.push(Math.round(i * 5) / 1000);
  const bothFlags = [], oneFlags = [];
  let permEverFires = false, refused = 0;
  for (const p of grid) {
    const sb = state('both', p);
    if (sb.refuse) { refused++; bothFlags.push(null); }
    else { bothFlags.push(nflag(sb)); if (sb.flags.perm) permEverFires = true; }
    const sa = state('a', p);
    oneFlags.push(sa.refuse ? null : nflag(sa));
  }
  const fire = bothFlags.filter(v => v !== null && v > 0).length;
  const quietIdx = grid.map((p, i) => (bothFlags[i] === 0 ? i : -1)).filter(i => i >= 0);
  const at = grid.indexOf(P);
  let lo = at, hi = at;
  while (quietIdx.includes(lo - 1)) lo--;
  while (quietIdx.includes(hi + 1)) hi++;
  const missed = oneFlags.filter(v => v === 0).length;
  shows('the number of slider settings swept', String(grid.length));
  shows('the number of both-arms settings that flag', String(fire));
  shows('the low edge of the quiet band', fx(grid[lo], 3));
  shows('the high edge of the quiet band', fx(grid[hi], 3));
  ok('SWEEP: the measured fault sits inside a quiet band, not on an isolated quiet point',
    bothFlags[at] === 0 && hi > lo, `quiet from ${fx(grid[lo], 3)} to ${fx(grid[hi], 3)}`);
  ok('SWEEP: and outside it the both-arms fault IS caught, which the page states and explains',
    fire > 0 && fire < grid.length, `${fire} of ${grid.length} settings flag at least one differential check`);
  ok('SWEEP: the permutation check never fires in the both-arms setting anywhere on the grid',
    !permEverFires, 'gap and split-half are the only two that ever do');
  ok('SWEEP: the one-arm fault is missed at small p, which the page does not hide',
    missed > 0 && missed < grid.length, `missed at ${missed} of ${grid.length} settings`);
  ok('and the page prints the swept band rather than promising the single point',
    TEXT.includes(`${fire} put at least one differential flag`) &&
    TEXT.includes(`from ${fx(grid[lo], 3)} to ${fx(grid[hi], 3)}`));
}

// ------ three of the six differential checks cannot move under this fault. The page used to count
// all six as evidence that they "went quieter". They are bit-identical in all three settings.
{
  const inert = ['size', 'balance', 'placebo'];
  const same = inert.every(k => S0.flags[k] === false && SA.flags[k] === false && SB.flags[k] === false);
  ok('THREE OF THE SIX differential checks are constants under this fault',
    same && S0.mA.n === S0.mB.n && SA.mA.n === SA.mB.n && SB.mA.n === SB.mB.n &&
    S0.mA.chars === SA.mA.chars && S0.mA.chars === SB.mA.chars,
    'size, balance and placebo are identical in all three settings');
  ok('so only three of the six can move, and the page says three rather than six',
    /Three of the six differential checks can\s+move/i.test(TEXT) &&
    !/Six of the seven checks/i.test(TEXT));
  ok('and the split-half check sits within 5 percent of its threshold on untouched data, which the page prints',
    Math.abs(S0.between / S0.within - 2) / 2 < 0.05,
    `${fx(S0.between / S0.within, 2)} against a threshold of 2`);
}
// the refusal path must verify itself
{
  const empty = state('none', P, [], ARM_B);
  ok('REFUSAL PATH: the bench refuses when an arm is emptied, and says how many checks ran',
    empty.refuse === true);
  const back = state('none', P);
  ok('and the restored bench reproduces the clean state to the bit',
    back.mA.per1k === S0.mA.per1k && back.pv === S0.pv);
}
// a fault of zero size must change nothing at all
{
  const z = state('both', 0);
  ok('CONTROL: a fault of size zero is a no-op in every cell',
    z.mA.per1k === S0.mA.per1k && z.mB.per1k === S0.mB.per1k && nflag(z) === 0);
}

// ---------------------------------------------------------------- the shareable surface
console.log('\n--- the shareable surface ------------------------------------------------');
const head = HTML.slice(0, HTML.indexOf('</head>'));
const metaDesc = (head.match(/<meta name="description" content="([^"]*)"/) || [])[1] || '';
const ld = JSON.parse(head.slice(head.indexOf('{', head.indexOf('application/ld+json')), head.indexOf('}\n', head.indexOf('application/ld+json')) + 1));
ok('the JSON-LD parses and carries the Article fields',
  ld['@type'] === 'Article' && !!ld.name && !!ld.headline && !!ld.description && !!ld.url);
ok('JSON-LD dates are the wave date', ld.datePublished === '2026-08-30' && ld.dateModified === '2026-08-30');
ok('the canonical link is the slug’s own URL',
  head.includes('<link rel="canonical" href="https://artwaste.land/strata/the-apparatus-is-the-finding/" />'));
// Every crawler-facing string is checked against what this file actually proves, not by keyword.
// The previous guards were keyword-shaped and a rewritten description sailed through them.
const ogDesc = (head.match(/<meta property="og:description" content="([^"]*)"/) || [])[1] || '';
const twDesc = (head.match(/<meta name="twitter:description" content="([^"]*)"/) || [])[1] || '';
const MD = fs.readFileSync(path.join(ROOT, 'src', 'content', 'strata', 'the-apparatus-is-the-finding.md'), 'utf8');
const dek = (MD.match(/^dek:\s*"([\s\S]*?)"\s*$/m) || [])[1] || '';
const plain = (MD.match(/^plain:\s*"([\s\S]*?)"\s*$/m) || [])[1] || '';
// This file was silently overwritten once, during this build, by another page's frontmatter: same
// byte count, different stratum, and every figure check downstream stayed green because they read the
// HTML. So the first thing asserted about it is that it is this slug's frontmatter at all.
const mdTitle = (MD.match(/^title:\s*"([^"]*)"/m) || [])[1] || '';
const mdHref = (MD.match(/^href:\s*"([^"]*)"/m) || [])[1] || '';
const mdSeo = (MD.match(/^seoTitle:\s*"([^"]*)"/m) || [])[1] || '';
ok('IDENTITY: the frontmatter file belongs to this slug and not to another page',
  mdTitle === 'The Apparatus Is the Finding' &&
  mdHref === '/strata/the-apparatus-is-the-finding/' &&
  mdSeo === ld.name && mdTitle === ld.headline,
  `${mdTitle} . ${mdHref}`);
const SURFACES = { 'meta description': metaDesc, 'og:description': ogDesc, 'twitter:description': twDesc,
  'the dek': dek, 'the plain placard': plain, 'the JSON-LD description': ld.description };
ok('every crawler-facing string exists and is not empty',
  Object.values(SURFACES).every(v => v && v.length > 40), Object.keys(SURFACES).join(', '));
// (1) the mechanism this file cannot support must not appear on any of them
for (const [k, v] of Object.entries(SURFACES))
  ok(`SURFACE (${k}): does not claim a scanner, a flatbed or a photograph`,
    !/\b(flatbed|scanner|photograph\w*)\b/i.test(v), v.slice(0, 70) + '...');
// (2) none of them may say the headline inverts, because at p = 0.163 it does not
for (const [k, v] of Object.entries(SURFACES))
  ok(`SURFACE (${k}): does not claim an inversion`,
    !/\binvert(s|ed|ing)?\b|\binversion\b/i.test(v), '');
// (3) none of them may say every or all checks went quiet: three cannot move and the anchor fires
for (const [k, v] of Object.entries(SURFACES))
  ok(`SURFACE (${k}): does not claim every check went quiet`,
    !/every (differential )?check[^.]{0,40}(quiet|go quiet)/i.test(v) &&
    !/every check that caught/i.test(v), '');
// (4) the page reports one of its three panels as a failure, so no surface may imply three wins
for (const [k, v] of Object.entries(SURFACES))
  ok(`SURFACE (${k}): does not promise that all three findings collapse`,
    !/all three/i.test(v), '');
// The overclaim this page is most likely to make on a crawler-facing string is to assert the mechanism
// for all three panels, when one of the three is reported as a refutation of it. So every surface that
// counts to three must also scope the count.
for (const [k, v] of Object.entries(SURFACES))
  ok(`SURFACE (${k}): counts to three and then scopes the count`,
    !/\bthree\b/i.test(v) ||
    /(two of them|two of the three|twice|the third|one says no|one of them|failed|loses|refut)/i.test(v),
    v.slice(0, 60) + '...');
ok('SURFACE: no surface asserts the mechanism holds in every one of the three',
  !Object.values(SURFACES).some(v => /in (each|every) one[^.]{0,80}(different apparatus|different machines)/i.test(v)));
ok('SURFACE: the dek and the plain placard both say the third panel failed',
  /(failed|loses|does not survive|refut)/i.test(dek) && /(survive|control|third)/i.test(plain));
ok('SURFACE: the meta description still says what the page is',
  /three real datasets/i.test(metaDesc) && /bench/i.test(metaDesc));
// the numbers a surface quotes must be numbers this file verified
for (const [k, v] of Object.entries(SURFACES)) {
  const nums = (v.match(/(?<![0-9A-Za-z.,])[0-9][0-9,]*(?:\.[0-9]+)?(?![0-9])/g) || [])
    .filter(x => !/^(1|2|3|4|5|6|7|8|9|10|12|20|1,000)$/.test(x))
    .filter(x => !/^(1[89]|20)[0-9]{2}$/.test(x));   // a calendar year is not a computed figure
  ok(`SURFACE (${k}): every figure it quotes is one this file checked`,
    nums.every(x => EXPECTED[x] !== undefined || shown.includes(x)),
    nums.filter(x => EXPECTED[x] === undefined && !shown.includes(x)).join(', ') || nums.join(' '));
}
ok('the page states the generalisable rule verbatim',
  TEXT.includes('A DIFFERENTIAL CHECK SEES ONLY THE PART OF A FAULT THAT IS NOT COMMON TO BOTH OF ITS SIDES'));
ok('and the page shows where that rule bites, rather than stating an absolute it breaks',
  /the part of a fault that is not common\s+to both sides/i.test(TEXT) &&
  !TEXT.includes('CANNOT SEE ANY FAULT APPLIED TO BOTH'));
ok('the page states that panel three refutes the page’s own thesis',
  /panel that did not survive its own control/i.test(TEXT));
ok('the page discloses that its own plant-versus-animal control is itself a differential',
  /invisible to it/i.test(TEXT));
ok('the load-bearing closing tags are present',
  HTML.trimEnd().endsWith('</script>\n</body>\n</html>'));
ok('no em dash anywhere in the page', !HTML.includes(String.fromCharCode(0x2014)));
ok('zero third-party requests',
  !/https?:\/\/(?!artwaste\.land|schema\.org|download\.open\.fda\.gov|doi\.org|open\.fda\.gov)[^"' )]+/.test(
    HTML.replace(/<a [^>]*href="https?:\/\/[^"]*"/g, '<a')));
// ------------------------------------------------ provenance, identifiers, and everything left over
// WHY THIS SECTION EXISTS. A mutation test corrupted three figures a reader can see in the served HTML
// (1,068,107 bytes, the figshare DOI, and the year=1800,2026 facet range) and every assertion above
// stayed green, because every one of them was about a value this program COMPUTES and those three sit
// in prose and provenance that nothing above recomputed. Everything from here down ties a figure the
// reader is served to something derived from an artefact on disk. Where the figure is an IDENTIFIER
// rather than a measurement it is checked as an identifier, and labelled that way.
console.log('\n--- provenance, identifiers, and every remaining rendered figure ---------');
const README = fs.readFileSync(path.join(HERE, 'README.md'), 'utf8');
const RMD = README.replace(/\s+/g, ' ');
const INLINE = [...HTML.matchAll(/<script([^>]*)>([\s\S]*?)<\/script>/gi)]
  .filter(m => !/src=|application\/(ld\+)?json/i.test(m[1])).map(m => m[2])[0] || '';
// Pull a recorded value out of the research record rather than retyping it beside the assertion.
function grab(re, what) {
  const m = re.exec(RMD);
  ok(`the research record states ${what}`, !!m, m ? m[1] : 'NOT FOUND IN README');
  return m ? m[1] : ' ';
}

// --- panel one: the export, its size, the filenames and the exemption set --------------------------
const zipBytes = Number(grab(/json\.zip., fetched [0-9-]+, ([0-9][0-9,]*) bytes/,
  'the size of the openFDA export as downloaded').replace(/,/g, ''));
const gzBytes = Number(grab(/json\.gz. \(([0-9][0-9,]*) bytes/,
  'the size of the gzip pinned in its place').replace(/,/g, ''));
const gzOnDisk = fs.statSync(path.join(DATA, 'transparency-crl-0001-of-0001.json.gz')).size;
ok('the pinned gzip is exactly the size the research record gives it', gzOnDisk === gzBytes,
  `${grp(gzOnDisk)} bytes on disk`);
// The .zip itself is NOT pinned (it was recompressed to a .gz to stay under 2 MB), so its byte count
// cannot be recomputed here. It is checked against the research record and for consistency with the
// artefact that IS pinned, and this file says so rather than pretending it is derived.
ok('NOT RECOMPUTABLE: the .zip is not pinned, so its byte count is cross-checked, not derived',
  zipBytes > gzOnDisk && zipBytes / gzOnDisk < 1.02,
  `${grp(zipBytes)} zipped against ${grp(gzOnDisk)} gzipped, x${fx(zipBytes / gzOnDisk, 4)}`);
shows('the openFDA export size in bytes', grp(zipBytes));

const hasFile = f => CRL.results.some(r => r.file_name === f);
const relFile = (/Files named ([A-Za-z0-9_@.]+\.pdf) come from the [0-9]+ transparency release/.exec(TEXT) || [])[1];
const pkgFile = (/Files named ([A-Za-z0-9_@.]+\.pdf) were lifted out of a Drugs@FDA approval package/.exec(TEXT) || [])[1];
ok('IDENTIFIER: the transparency-release filename in the prose is a real record in the export',
  !!relFile && hasFile(relFile), String(relFile));
ok('and the file name really does put it in the family that sentence assigns it',
  !!relFile && relFile.startsWith('CRL_'));
ok('IDENTIFIER: the approval-package filename in the prose is a real record in the export',
  !!pkgFile && hasFile(pkgFile), String(pkgFile));
ok('and that file name really does put it in the family its sentence assigns it',
  !!pkgFile && !pkgFile.startsWith('CRL_'));
const exFileServed = (/<span class="mono" id="ex-file">([^<]*)<\/span>/.exec(HTML) || [])[1];
ok('IDENTIFIER: the exhibit filename the reader is served is the record this file scored at zero',
  exFileServed === ISLAND.exhibit.file && hasFile(exFileServed), String(exFileServed));

// The exemption set is a STATIC displayed claim: nothing rewrites #ck-exempt at runtime, so a reader
// really would be shown whatever is in the served HTML. It was never compared with the observed set.
const exBounds = /outside ([0-9]+) to ([0-9]+) is broken/.exec(TEXT);
ok('the page prints the range of FOIA exemption numbers a parse may emit', !!exBounds,
  exBounds ? exBounds[0] : 'NOT PRINTED');
ok('ANCHOR, with the bounds read off the page instead of retyped here: every emitted number is inside it',
  !!exBounds && uniqEx.every(d => d >= +exBounds[1] && d <= +exBounds[2]), `saw ${uniqEx.join(', ')}`);
const WORDS = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'];
ok('and the page spells the same upper bound out in words in the same sentence, so the two must agree',
  !!exBounds && exBounds[1] === '1' && TEXT.includes(`FOIA has ${WORDS[+exBounds[2]]} numbered exemptions`),
  exBounds ? `1 to ${exBounds[2]}` : 'NOT PRINTED');
const exServed = (/<span class="mono" id="ck-exempt">([^<]*)<\/span>/.exec(HTML) || [])[1];
ok('STATIC CLAIM: the exemption set the page prints is exactly the set this parse observed',
  exServed === uniqEx.join(', '), `served "${exServed}" against observed "${uniqEx.join(', ')}"`);
const exFreq = {}; for (const d of exemptions) exFreq[d] = (exFreq[d] || 0) + 1;
const modalEx = Object.keys(exFreq).sort((a, b) => exFreq[b] - exFreq[a])[0];
const namedEx = /is exemption ([0-9]+), trade secrets/.exec(TEXT);
ok('and the exemption the page names as the one that matters is the modal one in the corpus',
  !!namedEx && namedEx[1] === String(modalEx), `page says ${namedEx ? namedEx[1] : '?'}, corpus says ${modalEx}`);
shows('the export date openFDA stamped on the file', CRL.meta.last_updated);
// The year on the third toggle is static text. It has to be the year the page's own program filters
// on AND the year this file measured, or the reader is told a subgroup that nobody computed.
{
  const yLabel = (/approved vs unapproved, ([0-9]{4}) only/.exec(TEXT) || [])[1];
  const progYear = Number((/r\[ST\] === 0 && r\[YR\] === ([0-9]{4})/.exec(INLINE) || [])[1]);
  ok('the year on the toggle, the year the page program filters on and the year this file measured are one year',
    yLabel === String(progYear) &&
    agg(sel(r => r[ST] === 0 && r[YR] === progYear), pMarks).per1k === y24a.per1k &&
    agg(sel(r => r[ST] === 1 && r[YR] === progYear), pMarks).per1k === y24u.per1k,
    `label ${yLabel}, program ${progYear}`);
}
// The per-1,000 denominator is recovered from the instrument's own output rather than retyped.
const SCALE = Math.round(appr.per1k * appr.chars / appr.hits);
ok('the density denominator recovered from the instrument itself is a round thousand', SCALE === 1000, String(SCALE));
shows('the density denominator the page prints', grp(SCALE));

// --- panel two: the deposit, its identifiers, its quotations ---------------------------------------
const CSVFILE = path.join(DATA, 'infra_global_time_series_v20230816.csv');
const csvBytes = fs.statSync(CSVFILE).size;
const csvMd5 = crypto.createHash('md5').update(fs.readFileSync(CSVFILE)).digest('hex');
ok('the deposited file the page names is the file pinned here', TEXT.includes(path.basename(CSVFILE)));
shows('the deposited series size in bytes', grp(csvBytes));
shows('the deposited series size in kilobytes', fx(csvBytes / 1000, 1));
shows('the deposited series MD5', csvMd5);
const doi = grab(/\[(10\.6084\/m9\.figshare\.[0-9]+)\]\(https:\/\/doi\.org\/\1\)/, 'the figshare DOI of the deposit');
const pageDoi = /<a href="https:\/\/doi\.org\/([^"]+)">figshare ([^<]+)<\/a>/.exec(HTML);
ok('IDENTIFIER: the DOI the page prints is the DOI the page links to',
  !!pageDoi && pageDoi[1] === pageDoi[2], pageDoi ? `${pageDoi[2]} into ${pageDoi[1]}` : 'no figshare link found');
ok('IDENTIFIER: and it is the deposit the research record pins', !!pageDoi && pageDoi[1] === doi);
shows('the figshare DOI', doi);
const vol = grab(/Nature ([0-9]+) \([0-9]{4}\)/, 'the journal volume');
const volYear = grab(/Nature [0-9]+ \(([0-9]{4})\)/, 'the year of publication');
const paperTitle = grab(/\*(Satellite mapping[^*]+)\*, Nature/, 'the title of the paper');
ok('IDENTIFIER: the page carries the volume and year in both places it cites the paper',
  TEXT.includes(`Nature ${vol} (${volYear})`) && TEXT.includes(`Nature ${vol}, ${volYear}`));
ok('IDENTIFIER: and the citation under the blockquote is the title on record',
  TEXT.includes(`Paolo et al., ${paperTitle.replace(/\s+/g, ' ')}, Nature ${vol}, ${volYear}.`));
shows('the journal volume', vol);
shows('the PMC accession the quotations were checked against', grab(/full text at (PMC[0-9]+)/, 'the PMC accession'));
shows('the number of monthly rows in the series', String(TS.length));
ok('the span the page prints is the span of its own first and last rows',
  TEXT.includes(`January ${TS[0].detect_date.slice(0, 4)} to January ${TS[TS.length - 1].detect_date.slice(0, 4)}`) &&
  TS[0].detect_date.slice(5, 7) === '01' && TS[TS.length - 1].detect_date.slice(5, 7) === '01');
// Every block quotation in the research record has to be carried verbatim, either by the page or, for
// the exhibit, by the export's own text field. A quotation that drifts is a misquotation, not a figure.
{
  const RQ = [...README.matchAll(/(?:^> .*\n)+/gm)]
    .map(b => b[0].replace(/^> /gm, '').replace(/\s+/g, ' ').trim());
  const exText = ((exRec && exRec.text) || '').replace(/\s+/g, ' ');
  ok('the research record carries the quotations the page rests on', RQ.length >= 3, `${RQ.length} blocks`);
  for (const q of RQ)
    ok(`QUOTATION (not a measurement): carried verbatim, "${q.slice(0, 44)}..."`,
      TEXT.includes(q) || exText.includes(q));
  const hedge = grab(/The paper wrote "([^"]+)"/, 'the hedge the page quotes back at the paper');
  ok('QUOTATION: the page carries that hedge verbatim', TEXT.includes(hedge));
}
// The quoted headline percentage is the PAPER's figure, not this page's measurement, so it is taken
// from the research record and then required to be both on the page and within two points of what the
// deposited file actually gives from January. Reading it off the page would have asserted nothing.
const q16 = grab(/paper.s "about ([0-9]+)%"/, 'the percentage the paper published');
ok('QUOTED FIGURE (the paper’s, not this page’s): within two points of the growth measured here from January',
  Math.abs(growthFrom(0) - Number(q16)) < 2, `${q16} quoted against ${fx(growthFrom(0), 1)} measured`);
ok('and the page quotes it inside the paper’s own sentence, not as its own result',
  TEXT.includes(`increased by about ${q16}% over the past half a decade`));
shows('the percentage quoted from the paper', q16);
// Likewise the decommissioning date: from the record, then checked against the series it predicts.
const s1bDay = grab(/S1B stopped operating on ([0-9]+) December ([0-9]{4})/, 'the day Sentinel-1B stopped');
const s1bYear = (/S1B stopped operating on [0-9]+ December ([0-9]{4})/.exec(RMD) || [])[1];
ok('the satellite stop date on record falls in the last full month of the series',
  `${s1bYear}-12-01` === DEC21.detect_date && +s1bDay >= 1 && +s1bDay <= 31,
  `${s1bDay} December ${s1bYear} against a final full month of ${DEC21.detect_date}`);
ok('and the page carries that date in both the quotation and the sentence that reads it',
  (TEXT.match(new RegExp(`${s1bDay} December ${s1bYear}`, 'g')) || []).length === 2);
shows('the day of the month the satellite stopped', s1bDay);
shows('the front-loaded share as the verdict line rounds it', fx(100 * add / gain, 0));
{
  const defs = [['high-confidence oil only', r => r.oil],
    ['oil plus probable plus possible', r => r.oil + r.probable_oil + r.possible_oil],
    ['oil_other', r => r.oil_other]];
  for (const [n, f] of defs) {
    const row = TS.find(r => r.wind > f(r));
    ok(`the ${n} crossing row exists in the pinned series`, !!row, row ? row.detect_date : 'none');
    shows(`the wind count at the ${n} crossing`, grp(row.wind));
    shows(`the oil count at the ${n} crossing`, grp(f(row)));
  }
}

// --- panel three: the facet range, the fetch, and every cell of the decade table --------------------
// year=1800,2026 is an IDENTIFIER, a query facet range, not a measurement. It is still worth pinning:
// the page's whole "this is not an anchor" argument rests on it, and the filter it names is exactly
// what makes the range checkable, because the facets it produced can hold no year outside it.
{
  const allYears = Object.values(GB).flatMap(f => Object.keys(f.years).map(Number));
  const yLo = Math.min(...allYears), yHi = Math.max(...allYears);
  const printed = /year=([0-9]{4}),([0-9]{4})/.exec(TEXT);
  ok('IDENTIFIER: the facet range the page prints is exactly the span of years the pinned facets hold',
    !!printed && +printed[1] === yLo && +printed[2] === yHi,
    printed ? `page ${printed[1]},${printed[2]} against data ${yLo},${yHi}` : 'not printed');
  ok('and all four pinned query URLs in the research record carry that same range',
    (RMD.match(new RegExp(`api\\.gbif\\.org[^ ]*year=${yLo},${yHi}`, 'g')) || []).length === 4,
    `${(RMD.match(/api\.gbif\.org[^ ]*year=/g) || []).length} query URLs recorded`);
  shows('the GBIF year facet range', `${yLo},${yHi}`);
}
shows('the GBIF fetch date', grab(/four .facet=year. queries, all fetched ([0-9-]+) and pinned/,
  'the date the facets were fetched'));
for (const d of DECS) {
  shows(`the ${d}s plant holotype count`, grp(ph[d]));
  shows(`the ${d}s animal holotype count`, grp(ah[d]));
}
ok('every decade label in the table is one of the twelve decades this file computes',
  DECS.every(d => TEXT.includes(`${d}s`)));
ok('and the decade the page calls the peak is the argmax of the pinned plant facet',
  TEXT.includes(`The ${DECS.reduce((a, b) => (ph[b] > ph[a] ? b : a))}s hold`));

// --- the free parameters the page prints, read out of the code that uses them ----------------------
shows('the bench anchor threshold', String(ANCHOR_FACTOR));
{
  const splitF = Number((/within \* ([0-9.]+)/.exec(state.toString()) || [])[1]);
  ok('the split-half threshold read out of the bench code is the one the page prints',
    Number.isFinite(splitF) && TEXT.includes(`against a threshold of ${splitF}`), String(splitF));
  const slack = 100 * (splitF - S0.between / S0.within) / splitF;
  ok('and the page’s "two and a half percent from firing" is the slack the clean data leaves',
    Math.abs(slack - 2.5) < 0.6 && /two and a half percent from firing/.test(TEXT),
    `${fx(slack, 2)} percent below the threshold`);
  const NP = Number((/N = ([0-9]+)/.exec(permutationP.toString()) || [])[1]);
  const pageNP = Number((/na = a\.length, N = ([0-9]+)/.exec(INLINE) || [])[1]);
  ok('the relabelling count in this file and in the page’s own program are the same number',
    NP === pageNP && Number.isFinite(NP), `${NP} here, ${pageNP} in the page`);
  shows('the number of relabellings', String(NP));
}
shows('the openFDA licence', grab(/Licence: (CC0 1\.0) via/, 'the openFDA licence'));
shows('the deposit licence', grab(/, (CC BY 4\.0)\. File/, 'the figshare deposit licence'));
shows('the status the Pianola Institute returned to this build',
  grab(/returned \*\*HTTP ([0-9]{3})\*\*/, 'the status code that stopped the fourth panel'));
{
  const MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July',
    'August', 'September', 'October', 'November', 'December'];
  const dp = new Date(ld.datePublished + 'T00:00:00Z');
  ok('the human date in the placard is the machine date in the JSON-LD',
    TEXT.includes(`${dp.getUTCDate()} ${MONTHS[dp.getUTCMonth()]} ${dp.getUTCFullYear()}`), ld.datePublished);
}

ok('every figure asserted above was found in the rendered text', shown.length > 55, `${shown.length} figures string-matched`);
// A key added to EXPECTED with no shows() call that reaches it is a silent no-op: it looks like
// coverage and asserts nothing. Require every key to have been used.
{
  const unused = Object.keys(EXPECTED).filter(k => !shown.includes(k));
  ok('no figure sits in the EXPECTED table without an assertion that reaches it',
    unused.length === 0, unused.length ? `unused: ${unused.join(', ')}` : `${Object.keys(EXPECTED).length} keys, all used`);
}

// ------------------------------------------- the page's own script actually runs
// A missing closing tag silently disables every inline script and no site build catches it.
// So run the page's script here, under a stub DOM, and require its own check panel to be green.
console.log('\n--- the page’s inline script, executed --------------------------------');
{
  const scripts = [...HTML.matchAll(/<script([^>]*)>([\s\S]*?)<\/script>/gi)]
    .filter(m => !/src=|application\/(ld\+)?json/i.test(m[1])).map(m => m[2]);
  ok('the page carries exactly one inline program', scripts.length === 1, `${scripts.length} found`);
  const islandText = HTML.slice(
    HTML.indexOf('>', HTML.indexOf('id="aif-data"')) + 1, HTML.indexOf('</script>', HTML.indexOf('id="aif-data"')));
  const els = {}, kids = {};
  const stubCtx = new Proxy({}, { get: () => () => {}, set: () => true });
  // Children are CACHED, so that what the page writes into each tbody survives the run and can be
  // compared with the tbody the reader is served. Without that, four whole tables render unchecked.
  const mk = id => ({
    id, _text: '', _html: '', value: '', checked: false, clientWidth: 600, clientHeight: 190, width: 0, height: 0,
    get textContent() { return this._text; }, set textContent(v) { this._text = String(v); },
    get innerHTML() { return this._html; }, set innerHTML(v) { this._html = String(v); },
    classList: { toggle() {}, add() {}, remove() {} }, parentNode: { classList: { toggle() {} } },
    addEventListener() {},
    querySelector(sel) { const k = id + ' ' + sel; return kids[k] || (kids[k] = mk(k)); },
    getContext: () => stubCtx
  });
  const radios = {
    p1i: [{ value: 'marks', checked: true }, { value: 'both', checked: false }],
    p1s: [{ value: 'status', checked: true }, { value: 'pipe', checked: false }, { value: 'y2024', checked: false }],
    p3m: [{ value: 'raw', checked: true }, { value: 'norm', checked: false }, { value: 'index', checked: false }],
    bm: [{ value: 'none', checked: true }, { value: 'a', checked: false }, { value: 'both', checked: false }]
  };
  for (const k in radios) radios[k].forEach(r => { r.parentNode = { classList: { toggle() {} } }; r.addEventListener = () => {}; });
  const prevDoc = globalThis.document, prevWin = globalThis.window;
  globalThis.document = {
    getElementById: id => id === 'aif-data' ? { textContent: islandText } : (els[id] || (els[id] = mk(id))),
    querySelector: sel => { const m = /input\[name=(\w+)\]:checked/.exec(sel); return m ? radios[m[1]].find(r => r.checked) : mk(sel); },
    querySelectorAll: sel => { const m = /input\[name=(\w+)\]/.exec(sel); return m ? radios[m[1]] : []; }
  };
  globalThis.window = { addEventListener() {}, matchMedia: () => ({ matches: false }), devicePixelRatio: 1 };
  let runErr = null;
  try { new Function(scripts[0])(); } catch (e) { runErr = e; }
  globalThis.document = prevDoc; globalThis.window = prevWin;
  ok('the page’s inline program runs to completion without throwing', !runErr, runErr ? String(runErr) : '');
  const panel = (els['check-rows'] || {})._html || '';
  const nFail = (panel.match(/>FAIL/g) || []).length, nPass = (panel.match(/>PASS/g) || []).length;
  ok('the page’s own check panel renders and is green', nPass > 10 && nFail === 0, `${nPass} pass, ${nFail} fail`);
  if (nFail) panel.split('</div>').filter(x => x.includes('FAIL')).forEach(x => console.log('     ' + x.replace(/<[^>]*>/g, '')));
  ok('the page’s live readout agrees with this file’s naive ratio',
    ((els['p1-out'] || {})._text || '').includes(fx(unap.per1k / appr.per1k, 3)),
    (els['p1-out'] || {})._text);
  ok('the page’s bench readout agrees with this file’s clean arm densities',
    ((els['b-out'] || {})._text || '').includes(fx(S0.mA.per1k, 3)) &&
    ((els['b-out'] || {})._text || '').includes(fx(S0.mB.per1k, 3)),
    (els['b-out'] || {})._text);

  // ---- EVERY RENDERED FIGURE, live against served.
  // The static text in the HTML and the value the program computes were previously checked against
  // this file SEPARATELY, so a change to the program alone (a permutation seed, say) left the served
  // text and this file agreeing while the reader saw something else. Here the two are compared to
  // each other, which closes that.
  {
    const served = {};
    for (const m of HTML.matchAll(/<span\b[^>]*\bid="([a-z0-9-]+)"[^>]*>([^<]*)<\/span>/g))
      served[m[1]] = m[2].trim();
    const ids = Object.keys(served).filter(id => served[id] && els[id] && els[id]._text);
    const bad = ids.filter(id => els[id]._text.trim() !== served[id]);
    ok('EVERY FIGURE: what the program renders equals what the reader is served, id by id',
      ids.length > 40 && bad.length === 0,
      bad.length ? bad.map(id => `${id}: served ${served[id]} but rendered ${els[id]._text}`).join('; ')
                 : `${ids.length} live figures matched`);
  }

  // ---- EVERY TABLE CELL, not a hand-listed sample of them.
  // The served HTML carries a static tbody for each of the four tables; the program overwrites it on
  // load. Previously 30 of those cells appeared in no assertion at all, and a whole table body could
  // be corrupted with the verifier green. Here the rendered tbody must equal the served one, cell for
  // cell, so any divergence anywhere in any table goes red.
  const servedTbody = id => {
    const t = HTML.indexOf(`id="${id}"`);
    if (t < 0) return null;
    const a = HTML.indexOf('<tbody>', t), b = HTML.indexOf('</tbody>', a);
    return a < 0 || b < 0 ? null : HTML.slice(a + 7, b);
  };
  const norm = h => (h || '').replace(/\s+/g, ' ').trim();
  let cells = 0;
  for (const id of ['p1-cross', 'p1-instr-table', 'p2-cross', 'p3-table']) {
    const live = norm((kids[id + ' tbody'] || {})._html);
    const served = norm(servedTbody(id));
    cells += (served.match(/<td/g) || []).length;
    ok(`EVERY CELL: the served <${id}> body is exactly what the program renders`,
      !!live && !!served && live === served,
      live === served ? `${(served.match(/<td/g) || []).length} cells` : `\n     served: ${served}\n     live:   ${live}`);
  }
  ok('and that covers every cell of all four tables', cells >= 45, `${cells} cells checked`);
}

// ---------------------------------------------------------------- verdict
console.log('\n-------------------------------------------------------------------------');
console.log(`${pass} passed, ${fail} failed, ${shown.length} rendered figures string-matched.`);
if (fail) { console.log('FAILURES:'); failures.forEach(f => console.log('  - ' + f)); process.exit(1); }
console.log('Agreement is not proof: both instruments here were written by one author, and a shared');
console.log('misreading of what a redaction looks like on paper would survive every check above.');
process.exit(0);
