#!/usr/bin/env node
// verify-the-seeds-beneath-the-steps.mjs
// Recomputes every number public/strata/the-seeds-beneath-the-steps/ shows and fails on any
// disagreement. It imports the page's own engine unchanged, and checks it against a separately
// written calibrator in this file, the spec writer's independent Python results, and the inherited
// NumPy results. It writes nothing unless given --regen.
//   (no flag)   every assertion, a JSON summary, exit non-zero on any failure
//   --ledger    print exactly the nine contract keys with the booleans actually computed
//   --mutate    also corrupt displayed figures, head tags, frontmatter, engine and formatter code
//               in memory and require the assertions to go red
//   --regen     rewrite record.json from the computed results, refusing if anything else fails
//   --no-browser  skip the headless browser (the rendered cell then cannot pass)
//   --with-sources  require the gitignored source CSVs and fail if they are absent
import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import {spawnSync} from 'node:child_process';
import {fileURLToPath, pathToFileURL} from 'node:url';
import * as ENGINE from '../../public/strata/the-seeds-beneath-the-steps/engine.js';
import * as REPORT from '../../public/strata/the-seeds-beneath-the-steps/report.js';
import {META, QUOTES, SOURCES, TIMELINE, RELATED, CHOICES, AUTHORS, citation, PAGE_URL, IMAGE, SLUG} from '../../public/strata/the-seeds-beneath-the-steps/content.js';
import {DATA_FILES, CURVE_FILE} from '../../public/strata/the-seeds-beneath-the-steps/data.js';
import {FRAME, OSL_BAND} from '../../public/strata/the-seeds-beneath-the-steps/render.js';

// The site's chrome writers (nearby-layers, way-out, check-placard, site-bar) inject furniture into every shipped
// page after the build. It is gated by the writers' own --check modes; this verifier checks the page's OWN content,
// so it reads the page with exactly those marked blocks and the shared banner script removed (2026-09-23, landing).
const stripChrome = (s) => s.replace(/\s*<!--aw-(nearby|wayout|checkkind):start-->[\s\S]*?<!--aw-\1:end-->/g, '')
  .replace(/\s*<script src="\/media\/home-banner\.js" defer><\/script>/g, '');

const HERE = path.dirname(fileURLToPath(import.meta.url)), ROOT = path.resolve(HERE, '../..');
const PUB = path.join(ROOT, 'public/strata', SLUG);
const KEYS = ['claim_reproduced', 'control_computed', 'control_can_confirm', 'rendered_figures_asserted', 'choices_are_live', 'planted_fault_caught', 'refusal_asserted', 'provenance_pinned', 'verdict_dated'];
const LABELS = {claim_reproduced: 'anchor:all-eleven-raw-seed-calibrations', control_computed: 'control:three-fraction-calibrations-and-sweep', control_can_confirm: 'power:grade-B-published-sensitivity-no-injection', rendered_figures_asserted: 'surface:bound-figures-quotes-head-browser', choices_are_live: 'choices:each-moves-its-output', planted_fault_caught: 'fault:raw-pollen-seed-and-curve-corruption', refusal_asserted: 'refuse:non-dates-bad-inputs-and-inferences', provenance_pinned: 'provenance:sha256-and-quote-audit', verdict_dated: 'verdict:open-dated-sourced-would-change'};
const ARG = new Set(process.argv.slice(2));
const outcomes = Object.fromEntries(KEYS.map(k => [k, []]));
const injection = [];   // grade A injection outcomes would live here; grade B has none by construction
const notes = [];
let count = 0, mutations = 0, browserSummary = null;
const check = (key, name, ok) => { count++; outcomes[key].push({name, pass: Boolean(ok)}); };
const near = (a, b, tol) => Number.isFinite(a) && Number.isFinite(b) && Math.abs(a - b) <= tol;
const raises = (fn, re) => { try { fn(); return false; } catch (e) { return re.test(e.message); } };
const read = f => fs.readFileSync(f, 'utf8');
const sha = buf => crypto.createHash('sha256').update(buf).digest('hex');
const EM = String.fromCharCode(0x2014);   // spelled out so this file never contains the character it checks for

// The fault checks the page describes, with the sizes it prints.
export const FAULTS = Object.freeze({pollenId: 'CAMS-190358A', pollenShift: 0.02, seedId: 'USGS-1803', seedShift: 500, curveShift: 100});
// Values from the spec writer's independent Python calibration (check.py, 2026-09-22), a third implementation.
const SPEC = Object.freeze({
  seeds: {'USGS-1803': [20880, 21377], 'USGS-1810': [22547, 23171], 'USGS-1808': [22574, 23160]},
  pollen: {'CAMS-190357A': [20954, 25920], 'CAMS-190358A': [20416, 25125], 'CAMS-190359A': [20302, 24975]},
  firsts: [300, 800, 1100, 1900, 2000, 2200], shifts: [180, 338, 341]
});
const COLUMN = `${FRAME.bottom.toFixed(2)} to ${FRAME.top.toFixed(2)} m`;

let record = JSON.parse(read(path.join(PUB, 'record.json')));
const html = stripChrome(read(path.join(PUB, 'index.html')));
const fmPath = path.join(ROOT, 'src/content/strata', `${SLUG}.md`);
const frontmatter = fs.existsSync(fmPath) ? read(fmPath) : '';
const audit = JSON.parse(read(path.join(HERE, 'quote-audit.json')));
const bundle = {...Object.fromEntries(Object.entries(DATA_FILES).map(([k, f]) => [k, JSON.parse(read(path.join(PUB, 'data', f)))])), curveText: read(path.join(PUB, 'data', CURVE_FILE))};

// ---------------------------------------------------------------- an independent calibrator
// Written apart from engine.js: binary-search interpolation, a threshold (not rank-walk) HPD, and
// its own fraction transform. It never calls the engine.
function indCurve(text) {
  const rows = text.split('\n').filter(l => /^\d/.test(l)).map(l => l.split(',').map(Number)).sort((a, b) => a[0] - b[0]);
  const n = 55001, mu = new Float64Array(n), sg = new Float64Array(n);
  for (let t = 0; t < n; t++) {
    let lo = 0, hi = rows.length - 1;
    while (hi - lo > 1) { const m = (lo + hi) >> 1; if (rows[m][0] <= t) lo = m; else hi = m; }
    const [x0, y0, s0] = rows[lo], [x1, y1, s1] = rows[hi], f = x1 === x0 ? 0 : (t - x0) / (x1 - x0);
    mu[t] = y0 + (y1 - y0) * f; sg[t] = s0 + (s1 - s0) * f;
  }
  return {mu, sg, rows: rows.length};
}
const IC = indCurve(bundle.curveText);
function indCal(value, sigma, fraction = false) {
  const n = IC.mu.length, w = new Float64Array(n); let tot = 0;
  for (let t = 0; t < n; t++) {
    const m = fraction ? Math.exp(-IC.mu[t] / 8033) : IC.mu[t], s = fraction ? m * IC.sg[t] / 8033 : IC.sg[t];
    const V = sigma * sigma + s * s; w[t] = Math.exp(-((value - m) ** 2) / (2 * V)) / Math.sqrt(V); tot += w[t];
  }
  let mean = 0; for (let t = 0; t < n; t++) { w[t] /= tot; mean += t * w[t]; }
  const sorted = Float64Array.from(w).sort().reverse();
  let acc = 0, h = 0; for (const v of sorted) { acc += v; h = v; if (acc >= 0.954) break; }
  let low = -1, high = -1; const runs = []; let start = -1;
  for (let t = 0; t <= n; t++) {
    const on = t < n && w[t] >= h;
    if (on) { if (low < 0) low = t; high = t; if (start < 0) start = t; }
    else if (start >= 0) { runs.push([start, t - 1]); start = -1; }
  }
  return {low, high, mid: (low + high) / 2, half: (high - low) / 2, mean, runs};
}
const indSeed = Object.fromEntries(bundle.seeds.map(s => [s.id, indCal(s.age, s.sigma)]));
const indPollen = Object.fromEntries(bundle.pollen.map(p => [p.id, indCal(p.fraction, p.fractionSigma, true)]));
const indPollenAge = Object.fromEntries(bundle.pollen.map(p => [p.id, indCal(p.age, p.sigma)]));
function indSweep() {
  return bundle.context.pairs.map(pair => {
    const s = bundle.seeds.find(x => x.id === pair.seed), pol = indPollen[pair.pollen];
    let first = null;
    for (let R = 0; R <= 8000 && first === null; R += 100) {
      const c = indCal(s.age - R, s.sigma);
      if (Math.max(0, pol.low - c.high, c.low - pol.high) > 0) first = R;
    }
    return first;
  });
}
const INDEPENDENT = JSON.parse(read(path.join(HERE, 'independent-results.json')));   // the inherited NumPy implementation
let SWEEP = null, ROUNDING = null;   // computed once and shared by every figure that quotes them
const sweepOnce = () => SWEEP || (SWEEP = ENGINE.pairedOverlapSweep(bundle, ENGINE.parseCurve(bundle.curveText)));
// The tolerances row: each released pollen fraction and its sigma moved by half a last digit, at all
// four corners, through the same calibrator; the largest movement of any range end, in years.
function roundingShift(E, b, curve, control) {
  let moved = 0;
  for (const p of b.pollen) for (const df of [-0.00005, 0.00005]) for (const ds of [-0.00005, 0.00005]) {
    const q = structuredClone(p); q.fraction += df; q.fractionSigma += ds;
    const x = E.summarizeCalibration(E.calibrateMeasurement(q, curve, {domain: 'fraction'})), base = control.rows.find(r => r.measurement.id === p.id).summary;
    moved = Math.max(moved, Math.abs(x.low - base.low), Math.abs(x.high - base.high));
  }
  return moved;
}
const roundingOnce = P => ROUNDING ?? (ROUNDING = roundingShift(ENGINE, bundle, ENGINE.parseCurve(bundle.curveText), P.control));
const suffix = x => x.sample.split('.').at(-1);

// ---------------------------------------------------------------- the mathematics
function mathematicalTests(E, emit) {
  const b = bundle, curve = E.parseCurve(b.curveText);
  const group = (key, fn) => { try { fn((name, ok) => emit(key, name, ok)); } catch (e) { emit(key, `exception: ${e.message}`, false); } };
  const P = E.prepare(b, curve);

  group('claim_reproduced', t => {
    const a = P.anchor;
    t('eleven seed rows calibrated', a.rows.length === 11 && b.seeds.length === 11);
    t('every seed row reproduces within 20 years at both ends, midpoint and half-span', a.agrees && a.rows.every(r => r.maxGap <= 20));
    for (const r of a.rows) t(`${r.measurement.id} within tolerance`, r.agrees && Object.values(r.gaps).every(g => Math.abs(g) <= 20));
    t('headline rows are USGS-1810 and USGS-1803', a.old.measurement.id === 'USGS-1810' && a.young.measurement.id === 'USGS-1803');
    t('older headline endpoint 22.86 ± 0.32 reproduced', near(a.old.summary.mid, 22860, 20) && near(a.old.summary.half, 320, 20));
    t('younger headline endpoint 21.13 ± 0.25 reproduced', near(a.young.summary.mid, 21130, 20) && near(a.young.summary.half, 250, 20));
    t('claim reproduced at full strength, not weaker: span within 20 years of 1.73 ka', near(a.span, 1730, 20) && a.old.summary.mid >= 22860 - 20);
    for (const r of a.rows) {
      const i = indSeed[r.measurement.id];
      t(`independent calibrator agrees on ${r.measurement.id}`, near(r.summary.low, i.low, 1) && near(r.summary.high, i.high, 1) && near(r.summary.mean, i.mean, 0.01));
      t(`independent calibrator also reproduces the release for ${r.measurement.id}`, ['low', 'high', 'mid', 'half'].every(k => Math.abs(i[k] - r.measurement.published[k]) <= 20));
      const np = INDEPENDENT.seeds[r.measurement.id];
      t(`inherited NumPy implementation agrees on ${r.measurement.id}`, np && np.low === r.summary.low && np.high === r.summary.high && near(np.mean, r.summary.mean, 1e-6));
    }
    for (const [id, [lo, hi]] of Object.entries(SPEC.seeds)) { const r = a.rows.find(x => x.measurement.id === id); t(`spec writer's independent envelope for ${id}`, r.summary.low === lo && r.summary.high === hi); }
    t('the oldest recomputed midpoint is USGS-1808, not the headline row', a.maximum.measurement.id === 'USGS-1808' && near(a.maximum.summary.mid, 22867, 0.5));
    t('printed columns are compared, never used as input', (() => { const c = structuredClone(b.seeds); c.forEach(s => { s.published.mid += 1000; }); const x = E.runAnchor(c, curve); return x.rows.every((r, i) => r.summary.mid === a.rows[i].summary.mid) && !x.agrees; })());
    t('envelope midpoints, not posterior means, are what the release printed', P.midpoint.within === 11 && P.mean.within < 11 && P.mean.maxGap > 20);
    t('posterior means independently fail on the same rows', P.mean.rows.every(r => (Math.abs(indSeed[r.id].mean - r.published) <= 20) === r.within));
    const bad = structuredClone(b.seeds); bad.find(s => s.id === FAULTS.seedId).age += FAULTS.seedShift;
    t('negative: a corrupted raw seed age fails the anchor', !E.runAnchor(bad, curve).agrees);
  });

  group('control_computed', t => {
    const c = P.control;
    t('control is the three ancient pollen rows and nothing else', c.rows.length === 3 && c.rows.every(r => r.measurement.kind === 'ancient-pollen') && c.rows.map(r => r.measurement.id).join() === 'CAMS-190357A,CAMS-190358A,CAMS-190359A');
    t('control calibrates in fraction space', c.domain === 'fraction' && c.rows.every(r => r.summary.domain === 'fraction'));
    t('every pollen row reproduces the release within 25 years', c.agrees && c.rows.every(r => r.maxGap <= 25));
    for (const r of c.rows) {
      const i = indPollen[r.measurement.id], [lo, hi] = SPEC.pollen[r.measurement.id];
      t(`independent fraction calibration agrees on ${r.measurement.id}`, near(r.summary.low, i.low, 1) && near(r.summary.high, i.high, 1) && near(r.summary.mean, i.mean, 0.01));
      t(`spec writer's independent envelope for ${r.measurement.id}`, r.summary.low === lo && r.summary.high === hi);
      const np = INDEPENDENT.pollen[r.measurement.id].fraction;
      t(`inherited NumPy implementation agrees on ${r.measurement.id}`, np.low === r.summary.low && np.high === r.summary.high);
      t(`${r.measurement.id} lies inside 26.5 to 20 ka`, r.insideLGM && r.summary.low >= 20000 && r.summary.high <= 26500);
    }
    t('the article’s printed 23.4 ± 2.5 to 22.6 ± 2.3 ka follows from the recomputed first and last rows', (c.rows[0].summary.mid / 1000).toFixed(1) === '23.4' && (c.rows[0].summary.half / 1000).toFixed(1) === '2.5' && (c.rows[2].summary.mid / 1000).toFixed(1) === '22.6' && (c.rows[2].summary.half / 1000).toFixed(1) === '2.3');
    const top = b.context.pairs.filter(p => p.pollen === 'CAMS-190357A').map(p => P.anchor.rows.find(r => r.measurement.id === p.seed).summary.mid);
    t('page claim: at the top layer the pollen midpoint is older than every seed beside it', top.length === 3 && top.every(m => c.rows[0].summary.mid > m));
    const blankCal = Number(QUOTES.blank.match(/(\d+) calendar years/)[1]);
    t('page claim: that ordering is smaller than the printed blank correction, and the pollen range contains each of those seed midpoints', blankCal === 2500 && Math.max(...top.map(m => c.rows[0].summary.mid - m)) < blankCal && top.every(m => c.rows[0].summary.low <= m && m <= c.rows[0].summary.high));
    const moved = roundingShift(E, b, curve, c);
    t('check panel: half a last released digit moves a pollen range end by years, not decades, and inside the 25-year tolerance', moved >= 3 && moved < E.SETTINGS.pollenTolerance);
    const youngPollen = structuredClone(b.pollen); youngPollen.forEach(p => { p.fraction = 0.21; });
    const yc = E.runControl(youngPollen, curve, b.osl), yv = E.visibleEvidence(P.anchor, yc, 'pollen', 'measured');
    t('the trench gap sees pollen on either side: pollen doctored younger than the seeds reads younger, not overlapping', yv.pollenSide === 'younger' && yv.gapToPollen > 0 && near(yv.gapToPollen, P.anchor.envelopeLow - Math.max(...yc.rows.map(r => r.summary.high)), 1e-9));
    const f0 = E.pairFixed(b, curve, 0), wrong = E.comparePair(b, curve, {pairIndex: 3, reservoir: 500}, f0), right = E.comparePair(b, curve, {pairIndex: 0, reservoir: 500}, f0);
    t('the per-pair cache the page keeps is ignored for another pair and used for its own', wrong.pollen.id === 'CAMS-190358A' && wrong.measured.id === 'USGS-1805' && right.pollen === f0.pollen && right.measured === f0.measured);
    t('page claim: each printed pollen range spans close to five thousand years', P.sensitivity.widths.every(w => w.width >= 4500 && w.width <= 5000));
    t('OSL rows carried alongside, unchanged', JSON.stringify(c.osl) === JSON.stringify(b.osl) && b.osl.map(o => [o.minimumAge, o.uncertainty].join()).join(';') === '21500,1900;20600,2100;18000,1800');
    for (const r of P.osl.rows) {
      const src = b.osl.find(o => o.id === r.id), ratio = 1000 * src.dose / src.doseRate;
      t(`OSL ${r.id}: dose over dose rate recomputed`, near(r.ratio, ratio, 1e-9) && r.low < ratio && r.high > ratio);
    }
    t('each printed OSL minimum lies within the rounding of its printed columns', P.osl.allConsistent);
    t('negative: an OSL age off by 0.3 ka fails the rounding check', (() => { const o = structuredClone(b.osl); o[1].minimumAge += 300; return !E.oslArithmetic(o).allConsistent; })());
    // The young-end pair, recomputed against the independent calibrator at the grid points that
    // bracket its first separation, and its whole scan through the page's own sweep function.
    const seed0 = b.seeds.find(x => x.id === b.context.pairs[0].seed), pol0 = indPollen[b.context.pairs[0].pollen];
    for (const R of [0, 200, 300, 1000]) {
      const i = indCal(seed0.age - R, seed0.sigma), want = Math.max(0, pol0.low - i.high, i.low - pol0.high);
      t(`pair 0 envelope gap at R = ${R} matches the independent calibrator`, near(E.comparePair(b, curve, {pairIndex: 0, reservoir: R}).gap, want, 1));
    }
    const sw0 = E.sweepPair(b, curve, 0);
    t('pair 0 first separates at R = 300 on the 100-year grid, after overlapping at 200', sw0.first === SPEC.firsts[0] && sw0.previous === 200 && sw0.scan.length === 81 && sw0.returns.length === 0);
    const L = P.layers;
    t('four labelled layers hold two aliquots each', L.tested.length === 4 && L.tested.every(x => x.ids.length === 2));
    for (const x of L.tested) {
      const [p, q] = x.ids.map(id => b.seeds.find(s => s.id === id)), z = Math.abs(p.age - q.age) / Math.hypot(p.sigma, q.sigma);
      t(`layer ${x.label}: statistic and p-value recomputed`, near(x.z, z, 1e-12) && near(x.T, z * z, 1e-9) && near(x.p, 1 - integrateNormal(z), 2e-7) && x.consistent === (x.p >= 0.05));
    }
    t('only layer 1a is inconsistent at the 5% level', L.inconsistent.join() === '1a');
    t('page claim: aliquots that share a sample number share a released elevation', L.tested.every(x => new Set(x.ids.map(id => b.seeds.find(q => q.id === id).elevation)).size === 1));
    // How much of the range rests on one aliquot, recomputed from the independent calibrator.
    const mids = Object.fromEntries(b.seeds.map(q => [q.id, indSeed[q.id].mid])), all = b.seeds.map(q => q.id);
    const spread = ids => Math.max(...ids.map(id => mids[id])) - Math.min(...ids.map(id => mids[id]));
    const full = spread(all), loo = all.map(id => ({id, span: spread(all.filter(x => x !== id))}));
    const most = loo.reduce((a, x) => full - x.span > full - a.span ? x : a), other = Math.max(...loo.filter(x => x !== most).map(x => full - x.span));
    t('leave one out: the spread of the eleven midpoints, and with each set aside, match the independent calibrator', near(P.leaveOneOut.full, full, 1e-9) && P.leaveOneOut.rows.length === 11 && P.leaveOneOut.rows.every(r => near(r.span, loo.find(x => x.id === r.id).span, 1e-9)));
    t('leave one out: only USGS-1803, one aliquot of the inconsistent sample number, moves the span by more than ten years', P.leaveOneOut.most.id === most.id && most.id === 'USGS-1803' && near(P.leaveOneOut.largestOther, other, 1e-9) && other <= 10 && L.tested.find(x => x.label === L.inconsistent[0]).ids.includes(most.id));
  });

  group('control_can_confirm', t => {
    const s = P.sensitivity, pub = x => b.pollen.find(p => p.id === x).published;
    t('the page prints the grade the engine declares, and the engine plants nothing', E.POWER.grade === 'B-published-sensitivity' && E.POWER.injection === null && s.grade === E.POWER.grade && s.injection === null && html.includes(`<p class="grade">Grade ${E.POWER.grade[0]} · published sensitivity</p>`) && META.powerScope.startsWith(`Grade ${E.POWER.grade[0]}, published sensitivity.`));
    t('printed headline span 1.73 ka, from the printed columns', s.span === 22860 - 21130 && s.span === 1730);
    t('computed analogue of the span', near(s.computedSpan, 1730.5, 1e-9));
    t('published pollen widths 4.97, 4.72 and 4.69 ka', s.widths.map(w => w.width).join() === [pub('CAMS-190357A'), pub('CAMS-190358A'), pub('CAMS-190359A')].map(p => p.high - p.low).join() && s.widths.map(w => w.width).join() === '4970,4720,4690');
    t('every published pollen range contains the printed headline interval', s.allContained && s.widths.every(w => w.low <= 21130 && w.high >= 22860));
    t('every width exceeds the span, so the narrow span is INCONCLUSIVE', s.allWider && s.narrowSpan === 'INCONCLUSIVE');
    t('younger scenario: headline midpoints move to 13.63 to 15.36 ka', s.shiftedLow === 13630 && s.shiftedHigh === 15360);
    t('younger scenario: full seed envelope 20.88 to 23.18 becomes 13.38 to 15.68 ka', s.envelopeLow === 20880 && s.envelopeHigh === 23180 && s.shiftedEnvelopeLow === 13380 && s.shiftedEnvelopeHigh === 15680);
    t('youngest published pollen edge 20.30 ka; gaps 4.94 and 4.62 ka', s.youngestPollen === 20300 && s.midpointGap === 4940 && s.envelopeGap === 4620);
    t('resolution threshold 2.88 ka', s.thresholdShift === 23180 - 20300);
    t('coarse separation holds on the stated premises', s.coarseSeparated && s.coarse === 'SEPARABLE, IF THE PREMISES HOLD');
    t('the scenario used is the stated 7,500 calendar years', s.shift === 7500 && E.SETTINGS.calendarTranslation === 7500);
    const narrow = structuredClone(b.pollen); narrow.forEach(p => { p.published.low = 21500; p.published.high = 22500; });
    t('negative: pollen ranges narrower than the span would not be INCONCLUSIVE', E.publishedSensitivity(P.anchor, narrow).narrowSpan !== 'INCONCLUSIVE');
    const young = structuredClone(b.pollen); young.forEach(p => { p.published.low -= 6000; });
    t('negative: a pollen edge younger than the moved seeds would not separate', !E.publishedSensitivity(P.anchor, young).coarseSeparated);
  });

  group('choices_are_live', t => {
    // Each effect assertion is tagged with the choice it proves live, and the last assertion
    // requires every declared choice to have one that passed.
    const effects = [], te = (id, name, ok) => { effects.push({id, ok: Boolean(ok)}); t(`${id}: ${name}`, ok); };
    const v = ev => E.visibleEvidence(P.anchor, P.control, ev, 'measured');
    te('evidence', '11, 14 and 17 determinations', v('seeds').count === 11 && v('pollen').count === 14 && v('all').count === 17 && v('all').osl.length === 3 && v('pollen').osl.length === 0);
    const m = E.visibleEvidence(P.anchor, P.control, 'pollen', 'measured'), y = E.visibleEvidence(P.anchor, P.control, 'pollen', 'younger');
    te('scenario', 'moves the seed envelope by exactly 7,500 years', y.seedLow === m.seedLow - 7500 && y.seedHigh === m.seedHigh - 7500);
    te('scenario', 'changes Last Glacial Maximum containment and the gap', m.seedsInsideLGM && !y.seedsInsideLGM && m.gapToPollen === 0 && y.gapToPollen > 4000 && m.pollenSide === 'overlapping' && y.pollenSide === 'older');
    t('scenario never moves the pollen', JSON.stringify(y.rows.filter(r => r.material === 'pollen').map(r => r.summary.mid)) === JSON.stringify(m.rows.filter(r => r.material === 'pollen').map(r => r.summary.mid)));
    te('statistic', 'changes the agreement count and the largest difference', P.midpoint.within !== P.mean.within && P.midpoint.maxGap !== P.mean.maxGap);
    const pairs = [0, 1, 2, 3, 4, 5].map(i => E.comparePair(b, curve, {pairIndex: i, reservoir: 1000}));
    te('pair', 'changes the seed and the gap', new Set(pairs.map(p => p.seed.mid)).size === 6 && new Set(pairs.map(p => p.gap)).size > 1);
    const r0 = E.comparePair(b, curve, {pairIndex: 0, reservoir: 0}), r1 = E.comparePair(b, curve, {pairIndex: 0, reservoir: 1000});
    te('reservoir', 'changes the seed calibration and the gap', r1.seed.mid < r0.seed.mid && r1.gap > r0.gap && r1.calendarShift > 1000);
    t('reservoir leaves the pollen fixed', r1.pollen.mid === r0.pollen.mid && r1.pollen.low === r0.pollen.low);
    const cal = E.comparePair(b, curve, {pairIndex: 0, convention: 'calendar'});
    te('convention', 'changes the seed by translation, not recalibration', cal.seed.mid === r0.seed.mid - 7500 && cal.seed.half === r0.seed.half && cal.gap !== r0.gap);
    const df = E.diagnostic(b.pollen, curve, 'fraction'), da = E.diagnostic(b.pollen, curve, 'age');
    te('domain', 'changes the diagnostic midpoints and the source agreement', df.rows.every((r, i) => r.shown.mid !== da.rows[i].shown.mid) && df.agrees && !da.agrees);
    t('the control stays in fraction space whatever the diagnostic shows', E.runControl(b.pollen, curve, b.osl).domain === 'fraction');
    t('every declared choice has a passing effect assertion; a choice declared inert would need its own inertness assertion here', CHOICES.every(c => !c.inert && effects.some(e => e.id === c.id && e.ok)) && effects.every(e => CHOICES.some(c => c.id === e.id)));
  });

  group('planted_fault_caught', t => {
    const pol = structuredClone(b.pollen); pol.find(p => p.id === FAULTS.pollenId).fraction += FAULTS.pollenShift;
    const faulty = E.runControl(pol, curve, b.osl), row = faulty.rows.find(r => r.measurement.id === FAULTS.pollenId);
    const clean = P.control.rows.find(r => r.measurement.id === FAULTS.pollenId);
    t('pollen fraction +0.02 fails source reproduction', !faulty.agrees && !row.agrees);
    t('and moves that date younger', row.summary.mid < clean.summary.mid - 1000);
    t('and leaves the other two pollen dates alone', faulty.rows.filter(r => r.measurement.id !== FAULTS.pollenId).every(r => r.agrees));
    const seeds = structuredClone(b.seeds); seeds.find(s => s.id === FAULTS.seedId).age += FAULTS.seedShift;
    const fa = E.runAnchor(seeds, curve), fr = fa.rows.find(r => r.measurement.id === FAULTS.seedId);
    t('seed age +500 fails the anchor', !fa.agrees && !fr.agrees);
    t('and moves that seed older', fr.summary.mid > P.anchor.young.summary.mid + 400);
    const lines = b.curveText.split('\n').map(l => /^\d/.test(l) ? l.replace(/^(\d+),(\d+)/, (_, a, c14) => `${a},${Number(c14) + FAULTS.curveShift}`) : l).join('\n');
    t('a curve shifted by 100 radiocarbon years fails the anchor', !E.runAnchor(b.seeds, E.parseCurve(lines)).agrees);
    const planted = structuredClone(b.pollen); planted[0].fraction = planted[0].fraction * 1;
    t('control on an unmodified copy still agrees (the fault, not the copying, breaks it)', E.runControl(planted, curve, b.osl).agrees);
  });

  group('refusal_asserted', t => {
    const ctx = kind => b.context.rows.find(r => r.kind === kind);
    t('a track horizon is refused with its own reason', raises(() => E.calibrateMeasurement({...ctx('track-horizon'), units: 'F14C'}, curve), /walking surface/));
    t('modern pollen is refused with its own reason', raises(() => E.calibrateMeasurement({...ctx('modern-pollen'), units: 'F14C'}, curve), /bomb-era/));
    t('the procedural blank is refused with its own reason', raises(() => E.calibrateMeasurement({...ctx('blank'), units: 'F14C'}, curve), /procedural blank/));
    t('context-row refusal is the engine’s own', b.context.rows.every(r => E.calibrateContextRow(r, curve).refused));
    const mp = ctx('modern-pollen');
    t('a modern fraction relabelled as ancient is still refused', raises(() => E.calibrateMeasurement({id: 'x', kind: 'ancient-pollen', units: 'F14C', fraction: mp.fraction, fractionSigma: mp.fractionSigma}, curve), /modern carbon/));
    const s0 = b.seeds[0];
    t('non-finite age refused', raises(() => E.calibrateMeasurement({...s0, age: NaN}, curve), /finite measurement/));
    t('zero laboratory error refused', raises(() => E.calibrateMeasurement({...s0, sigma: 0}, curve), /positive laboratory uncertainty/));
    for (const R of [50, 8100, -100]) t(`reservoir ${R} refused`, raises(() => E.calibrateMeasurement(s0, curve, {reservoir: R}), /0 to 8000/));
    t('undocumented probability mass refused', raises(() => E.calibrateMeasurement(s0, curve, {mass: 0.683}), /95.4%/));
    t('seed in fraction space refused', raises(() => E.calibrateMeasurement(s0, curve, {domain: 'fraction'}), /radiocarbon years BP/));
    t('wrong units refused', raises(() => E.calibrateMeasurement({...s0, units: 'ka'}, curve), /radiocarbon years BP/));
    t('pollen with a seed reservoir correction refused', raises(() => E.calibrateMeasurement(b.pollen[0], curve, {reservoir: 100}), /no seed reservoir/));
    t('a control made of seeds refused', raises(() => E.runControl(b.seeds.slice(0, 3), curve), /three ancient pollen/));
    t('an anchor missing a row refused', raises(() => E.runAnchor(b.seeds.slice(1), curve), /eleven/));
    for (const i of [6, 1.5, -1]) t(`unverified pair ${i} refused`, raises(() => E.selectPair(b, i), /same-horizon/));
    t('calendar translation and radiocarbon subtraction together refused', raises(() => E.comparePair(b, curve, {pairIndex: 0, reservoir: 100, convention: 'calendar'}), /cannot be applied together/));
    t('any other calendar shift refused', raises(() => E.translateSummary(P.anchor.rows[0].summary, 5000), /7,500/));
    for (const q of ['individual', 'combined', 'osl']) { const r = E.unsupportedRequest(q); t(`inference refused, and labelled a statement of scope: ${q}`, r.refused && r.kind === 'scope' && /^REFUSED, a statement of scope/.test(r.message)); }
    const un = E.unsupportedRequest('unpaired', b, curve, P), fr = E.unsupportedRequest('fixedReservoir', b, curve, P);
    t('unpaired: the engine’s own pair map refuses the headline seed with its nearest-looking pollen', un.refused && un.kind === 'engine' && un.message.startsWith('REFUSED: only the verified same-horizon seed and pollen pairs may be compared.') && un.message.includes(P.anchor.old.measurement.id) && un.message.includes('CAMS-190358A'));
    const withPair = {...b, context: {...b.context, pairs: [...b.context.pairs, {seed: P.anchor.old.measurement.id, pollen: 'CAMS-190358A', elevation: 1197.28}]}};
    t('negative: had the map paired them, the same request would not be refused', E.unsupportedRequest('unpaired', withPair, curve, P).refused === false);
    t('fixedReservoir: the engine’s pair comparison refuses the illustration applied again as R', fr.refused && fr.kind === 'engine' && fr.message.startsWith('REFUSED: calendar translation and radiocarbon subtraction cannot be applied together.'));
    t('negative: the same R under the radiocarbon convention alone is a scenario the engine runs', !raises(() => E.comparePair(b, curve, {pairIndex: 0, reservoir: E.SETTINGS.calendarTranslation}), /./));
    t('a request put to the engine without the loaded record is an error, not a quiet refusal', raises(() => E.unsupportedRequest('unpaired'), /needs the loaded record/));
    t('an unknown inference is an error, not a quiet pass', raises(() => E.unsupportedRequest('constructor'), /unknown inference/));
    const three = structuredClone(b.layers); three.rows.find(r => r.label === '1e').label = '1a';
    t('a sample number with three aliquots is refused, not tested as a pair', raises(() => E.layerConsistency(b.seeds, three), /pairs of aliquots/));
    t('unknown statistic refused', raises(() => E.statisticAgreement(P.anchor.rows, 'median'), /envelope midpoint or the posterior mean/));
    t('consistency test outside its implemented range refused', raises(() => E.chiSquareSurvival(4, 4), /two to four/));
    const dup = structuredClone(b.layers); dup.rows.push({...dup.rows[0]});
    t('an ambiguous layer label refused', raises(() => E.layerConsistency(b.seeds, dup), /claim the same seed row|exactly one/));
    t('negative control: a valid seed is not refused', !raises(() => E.calibrateMeasurement(s0, curve), /./));
  });

  return P;
}

// ---------------------------------------------------------------- the further results
function furtherTests(P, emit) {
  const b = bundle, curve = ENGINE.parseCurve(b.curveText);
  const t = (name, ok) => emit('control_computed', name, ok);
  const sweep = ENGINE.pairedOverlapSweep(b, curve);
  t('first separations 300, 800, 1,100, 1,900, 2,000, 2,200', sweep.map(r => r.first).join() === SPEC.firsts.join());
  t('first separations recomputed by the independent calibrator', indSweep().join() === SPEC.firsts.join());
  t('inherited NumPy sweep agrees', INDEPENDENT.pairs.map(p => p.first).join() === SPEC.firsts.join());
  t('previous grid value is one step below', sweep.every(r => r.previous === r.first - 100));
  t('no pair returns to overlap after separating (every later point scanned)', sweep.every(r => r.returns.length === 0 && r.scan.length === 81));
  t('page claim: each first separation is the seed passing below its pollen’s younger edge', sweep.every(r => { const x = r.scan.find(q => q.reservoir === r.first); return x.gap > 0 && near(x.gap, r.pollenLow - x.high, 1e-9); }));
  let cached = true;
  for (let i = 0; i < b.context.pairs.length; i++) {
    const f = ENGINE.pairFixed(b, curve, i);
    for (const opts of [{reservoir: 0}, {reservoir: 2000}, {convention: 'calendar'}]) {
      const x = ENGINE.comparePair(b, curve, {pairIndex: i, ...opts}, f), y = ENGINE.comparePair(b, curve, {pairIndex: i, ...opts});
      cached = cached && JSON.stringify([x.seed, x.measured, x.pollen, x.gap]) === JSON.stringify([y.seed, y.measured, y.pollen, y.gap]);
    }
  }
  t('the per-pair cache the page keeps changes no result, on every pair', cached);
  const d = ENGINE.diagnostic(b.pollen, curve, 'age');
  t('Gaussian-age approximation moves midpoints younger by 180, 338 and 341 years', d.rows.map(r => r.shift).join() === SPEC.shifts.join());
  t('independent: the same shifts', b.pollen.map(p => indPollen[p.id].mid - indPollenAge[p.id].mid).join() === SPEC.shifts.join());
  t('the approximation fails source reproduction on every row', d.rows.every(r => !r.agrees));
  const L = P.layers;
  t('four labelled layers hold two aliquots each', L.tested.length === 4 && L.tested.every(x => x.ids.length === 2));
  t('layer labels join to the release uniquely', ENGINE.joinLayers(b.seeds, b.layers).length === 11);
  const a = b.seeds.find(s => s.id === 'USGS-1803'), c = b.seeds.find(s => s.id === 'USGS-1828');
  const z = Math.abs(a.age - c.age) / Math.hypot(a.sigma, c.sigma);
  const p1 = 1 - integrateNormal(z);
  t('layer 1a: 460 ± 127 years, 3.61 standard errors, independently', near(L.tested.find(x => x.label === '1a').z, z, 1e-12) && z.toFixed(2) === '3.61');
  t('layer 1a p-value checked by numerical integration', near(L.tested.find(x => x.label === '1a').p, p1, 2e-7));
  t('only layer 1a is inconsistent at the 5% level', L.inconsistent.join() === '1a');
  t('Sidak family p for four layers', near(L.familyP, 1 - (1 - p1) ** 4, 1e-6));
  for (const x of L.tested) t(`layer ${x.label} p-value independent`, near(x.p, 1 - integrateNormal(x.z), 2e-7));
}
// Two-sided p for a standard normal statistic, by Simpson's rule, written apart from engine.erfc.
function integrateNormal(z) {
  const n = 20000, h = z / n, f = x => Math.exp(-x * x / 2) / Math.sqrt(2 * Math.PI);
  let s = f(0) + f(z); for (let i = 1; i < n; i++) s += (i % 2 ? 4 : 2) * f(i * h);
  return 2 * s * h / 3;   // P(|Z| <= z)
}

// ---------------------------------------------------------------- what the reader sees
const ENT = {'&amp;': '&', '&lt;': '<', '&gt;': '>', '&quot;': '"', '&#39;': "'", '&middot;': '·', '&nbsp;': ' '};
const clean = s => s.replace(/<br\s*\/?>/g, ' ').replace(/<[^>]+>/g, '').replace(/&[a-z#0-9]+;/g, m => ENT[m] ?? m).replace(/\s+/g, ' ').trim();
function elements(src, attr) {
  const out = [], re = new RegExp(`<([a-z0-9]+)\\b[^>]*\\b${attr}="([^"]+)"[^>]*>`, 'g'); let m;
  while ((m = re.exec(src))) {
    const tag = m[1], start = m.index, open = m.index + m[0].length;
    let depth = 1, i = open; const tre = new RegExp(`<(/?)${tag}\\b[^>]*>`, 'g'); tre.lastIndex = open; let n;
    while (depth && (n = tre.exec(src))) { depth += n[1] ? -1 : (n[0].endsWith('/>') ? 0 : 1); i = n.index; }
    const end = tre.lastIndex;
    out.push({key: m[2], inner: src.slice(open, i), text: clean(src.slice(open, i)), start, end});
  }
  return out;
}
const byId = (src, id) => { const m = elements(src, 'id').find(e => e.key === id); return m ? m.text : null; };
const metaContent = (src, name, attr = 'name') => { const m = src.match(new RegExp(`<meta ${attr}="${name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}" content="([^"]*)"`)); return m ? clean(m[1]) : null; };
const words = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven'];

function expectedFacts(P) {
  const S = ENGINE.SETTINGS, ka = REPORT.ka, yr = REPORT.yr, a = P.anchor;
  const pub = r => `${ka(r.measurement.published.mid, 2)} ± ${ka(r.measurement.published.half, 2)} ka`;
  const raw = r => `${yr(r.measurement.age)} ± ${yr(r.measurement.sigma)} radiocarbon years`;
  const share = Object.values(bundle.context.pairs.reduce((o, p) => ({...o, [p.pollen]: (o[p.pollen] || 0) + 1}), {})).sort((x, y) => y - x);
  const page = key => { const e = audit.pages.find(p => p.key === key && p.found_on_page); return e ? `PDF page ${e.pdf_page}` : 'unverified'; };
  const overlap = AUTHORS.pigati2023.filter(n => AUTHORS.bennett2021.includes(n)).length;
  const counts = new Set(bundle.pollen.map(p => p.count));
  const th = bundle.context.rows.filter(r => r.kind === 'track-horizon').map(r => r.elevation);
  const pe = bundle.pollen.map(p => p.elevation);
  // The one pair whose seed sample number is not the stem of its pollen's (1a for 1aa, and so on).
  const lone = bundle.context.pairs.filter(p => suffix(bundle.pollen.find(x => x.id === p.pollen)).slice(0, -1) !== suffix(bundle.seeds.find(x => x.id === p.seed)).replace(/\d+$/, ''));
  return {
    coauthors2021: String(AUTHORS.bennett2021.length - 1), oldId: a.old.measurement.id, youngId: a.young.measurement.id,
    printedOld: pub(a.old), printedYoung: pub(a.young), rawOld: raw(a.old), rawYoung: raw(a.young),
    anchorMethod: `Each raw age is calibrated against IntCal20 with a uniform calendar prior on a one-year grid. The printed ± is not a standard deviation: it is half the width of the ${(S.mass * 100).toFixed(1)}% highest-density range, and the printed age is that range's midpoint. The comparison tolerance, ${S.seedTolerance} calendar years per end, midpoint and half-span, covers the printed rounding, the curve's native spacing and a whole-year interval routine; it is not extra dating uncertainty.`,
    printedSpan: `${ka(a.publishedSpan, 2)} ka`, maxId: a.maximum.measurement.id, printed1808: pub(a.maximum),
    summaryPage: page('summary'), headlinePage: page('headline'), definitivePage: page('definitive'),
    surfacesRange: `${Math.min(...th).toFixed(2)} to ${Math.max(...th).toFixed(2)} m`,
    pollenElevations: `${Math.min(...pe).toFixed(2)} to ${Math.max(...pe).toFixed(2)} m`,
    oldElevation: pe.includes(Number(a.old.measurement.elevation.toFixed(2))) ? 'a pollen elevation' : `${a.old.measurement.elevation.toFixed(3)} m`,
    elevationOnlySeed: lone.length === 1 ? lone[0].seed : 'more than one', elevationOnlySample: lone.length === 1 ? suffix(bundle.seeds.find(x => x.id === lone[0].seed)) : 'more than one',
    sweepLastFirst: sweepOnce().every(r => r.first !== null) ? yr(Math.max(...sweepOnce().map(r => r.first))) : 'not every pair separates',
    translation: yr(S.calendarTranslation), columnRange: COLUMN, lgmEdge: `${ka(S.lgmYoung, 0)} to ${ka(S.lgmYoungAlt, 0)} ka`,
    overlap2023: String(overlap), authors2023: String(AUTHORS.pigati2023.length),
    grains: counts.size === 1 ? yr([...counts][0]) : 'differing counts',
    reservoirRule: `R runs from 0 to ${yr(S.maxReservoir)} radiocarbon years in steps of ${S.reservoirStep}. Corrected age = measured age − R. The sources agree on no ancient value of R; the slider explores an assumption, it does not measure one.`,
    sweepLimits: `First separation on this ${S.reservoirStep}-year scenario grid is a descriptive comparison, not a confidence limit, a maximum allowable reservoir age or a measured correction. The ${words[bundle.context.pairs.length]} comparisons are not ${words[bundle.context.pairs.length]} experiments: ${words[share[0]]} seeds share one pollen date, ${words[share[1]]} share another, and every one shares the calibration curve. Envelope overlap ignores any gaps inside a highest-density set; the full ranges are listed.`,
    ageFormula: `−${S.meanLife} × ln F`,
    calibrator: `IntCal20, linearly interpolated onto a one-year grid from 0 to ${yr(S.maxCalendar)} calendar BP, with a uniform calendar prior and the curve's own uncertainty added to each measurement's. The ${(S.mass * 100).toFixed(1)}% highest-density set keeps separate ranges separate.`,
    seedFormula: 'v(t) = laboratory σ² + curve σ(t)² p(t) ∝ exp[−(age − curve age(t))² / 2v(t)] / √v(t)',
    fractionFormula: `curve F(t) = exp[−curve age(t) / ${S.meanLife}] curve σF(t) = curve F(t) × curve σ(t) / ${S.meanLife} the same Gaussian form, in fraction space`,
    tolerances: `${S.seedTolerance} calendar years for seeds, ${S.pollenTolerance} for pollen, per range end, midpoint and half-span. The pollen fractions are released to four decimals; moving a fraction and its error by half a last digit moves a range end by at most ${roundingOnce(P)} years here. Neither tolerance is dating uncertainty.`,
    layerMethod: `Two aliquots that share a Figure 2A sample number are compared with T = (a₁ − a₂)² / (σ₁² + σ₂²), chi-squared with one degree of freedom, two-sided, at the ${Math.round(S.consistencyLevel * 100)}% level, using the released one-sigma laboratory errors. With ${words[P.layers.k]} sample numbers tested, the smallest p is also given after a Šidák adjustment. The test says whether two ages could be one; it cannot say why they are not.`,
    faults: `The verifier adds ${FAULTS.pollenShift} to a copy of one pollen fraction and ${FAULTS.seedShift} radiocarbon years to a copy of one seed age, runs the unchanged engine, and requires the reproduction to fail and the result to move. These are fault checks, not power tests.`,
    asOf: META.asOf, verdict: META.verdict
  };
}
const META_IDS = {dek: 'dek', headline: 'headline', novelty: 'novelty', 'would-change': 'wouldChange', 'verdict-scope': 'verdictScope', 'null-reason': 'nullReason', 'power-scope': 'powerScope', decision: 'decision'};
// Numerals allowed in visible prose outside every bound element, each with its reason and, where it
// names a value, a check that it is that value.
function allowlist(P) {
  const S = ENGINE.SETTINGS, lgmQuote = QUOTES.lgm;
  return [
    [/^\(?(20\d\d)\)?[.,;]?$/, 'the publication year of a cited source', tok => SOURCES.some(s => String(s.year) === tok.replace(/\D/g, ''))],
    [/^2\.$/, 'the site name Locality 2, as the sources print it', () => QUOTES.blank.includes('Locality 2') && html.includes('at a site called Locality 2.')],
    [/^1950\.?$/, 'AD 1950, the zero point of the BP scale', () => true],
    [/^TH\d(\.)?$/, 'a track-horizon label printed in the claim', tok => bundle.context.rows.some(r => r.sample === `Track_horizon_${tok.replace(/\D/g, '')}`)],
    [/^2A$/, 'the control paper’s figure number', () => audit.quotes.length > 0],
    [/^\(?\d[a-z]{1,2}\)?[,.;]?$/, 'a Figure 2A sample number', tok => bundle.layers.rows.some(r => r.label === tok.replace(/[(),.;]/g, ''))],
    [/^\(?USGS-\d{4}(\.\d)?\)?[,.;]?$/, 'an AMS identifier from the release', tok => bundle.seeds.some(s => s.id === tok.replace(/^\(|[),.;]+$/g, ''))],
    [/^CAMS-\d{6}A?[,.;]?$/, 'an AMS identifier from the release', tok => [...bundle.pollen, ...bundle.context.rows].some(s => s.id === tok.replace(/[,.;]$/, ''))],
    [/^7,500$/, 'the calendar translation, in option text', tok => tok === REPORT.yr(S.calendarTranslation)],
    [/^7,500-year$/, 'the calendar translation, in option text', tok => tok === `${REPORT.yr(S.calendarTranslation)}-year`],
    [/^IntCal20[,.]?$/, 'the name of the calibration curve', () => true],
    [/^F14C[,.]?$/, 'the name of the measured quantity', () => true],
    [/^(Mean_calibrated_ages)$/, 'a column name', () => true],
    [/^2025-3046[,.]?$/, 'the fact sheet series number', tok => SOURCES.find(s => s.id === 'usgs2026').venue.endsWith(tok.replace(/[,.]$/, ''))],
    [/^(26\.5|20)$/, 'the narrower Last Glacial Maximum reading, from the quoted window', tok => lgmQuote.includes(tok)],
    [/^1σ$/, 'the one-sigma label of a column', () => true],
    [/^(95\.4%|5%)$/, 'the stated probability mass or test level', tok => tok === `${(S.mass * 100).toFixed(1)}%` || tok === `${Math.round(S.consistencyLevel * 100)}%`],
    [/^(68%\)|95%\)\.?|\(68%\)|\(95%\)\.)$/, 'the dictionary’s sigma labels', () => true],
    [/^±$/, 'a symbol', () => true]
  ];
}
function unbound(src) {
  let h = src.replace(/<head>[\s\S]*?<\/head>/, ' ').replace(/<script[\s\S]*?<\/script>/g, ' ').replace(/<svg[\s\S]*?<\/svg>/g, ' ').replace(/<!--[\s\S]*?-->/g, ' ');
  for (const attr of ['data-fact', 'data-quote', 'data-out', 'data-source', 'data-timeline']) {
    for (const e of elements(h, attr).sort((x, y) => y.start - x.start)) h = h.slice(0, e.start) + ' ' + h.slice(e.end);
  }
  for (const id of Object.keys(META_IDS)) { const e = elements(h, 'id').find(x => x.key === id); if (e) h = h.slice(0, e.start) + ' ' + h.slice(e.end); }
  // The assay office's record of this layer (scripts/assay-fold.mjs) quotes counts and dates
  // about the layer, not figures of it; set aside like the related-layers nav (2026-10-30).
  h = h.replace(/<details class="aw-assay"[\s\S]*?<\/details>/, ' ').replace(/<style[\s\S]*?<\/style>/g, ' ');
  h = h.replace(/<nav class="related"[\s\S]*?<\/nav>/, ' ').replace(/<[^>]+>/g, ' ');
  return clean(h).split(' ').filter(tok => /\d/.test(tok));
}
const numbersIn = s => [...s.matchAll(/\d[\d.,]*\d|\d/g)].map(m => m[0]);

function surfaceChecks(src, fm, P, emit) {
  const t = (name, ok) => emit('rendered_figures_asserted', name, ok);
  const facts = expectedFacts(P), bound = elements(src, 'data-fact');
  for (const e of bound) t(`static figure ${e.key}`, facts[e.key] !== undefined && e.text === facts[e.key]);
  t('every expected static figure is on the page', Object.keys(facts).every(k => bound.some(e => e.key === k)));
  const quoted = elements(src, 'data-quote');
  for (const e of quoted) t(`quotation ${e.key} printed verbatim`, QUOTES[e.key] !== undefined && e.text === QUOTES[e.key]);
  t('every quotation in content.js is on the page', Object.keys(QUOTES).every(k => quoted.some(e => e.key === k)));
  for (const [id, key] of Object.entries(META_IDS)) t(`visible ${id} is the checked copy`, byId(src, id) === META[key]);
  for (const tok of unbound(src)) t(`unbound numeral "${tok}" is structural`, allowlist(P).some(([re, , ok]) => re.test(tok) && ok(tok)));
  // Numbers inside the checked copy are recomputed from the record, not trusted.
  const a = P.anchor, yearOf = id => String(SOURCES.find(s => s.id === id).year);
  t('dek numbers: claim year, printed ends, control year', JSON.stringify(numbersIn(META.dek)) === JSON.stringify([yearOf('bennett2021'), REPORT.ka(a.old.measurement.published.mid, 2), REPORT.ka(a.young.measurement.published.mid, 2), yearOf('pigati2023')]));
  const days = (x, y) => (Date.parse(SOURCES.find(q => q.id === y).date.split(' (')[0]) - Date.parse(SOURCES.find(q => q.id === x).date.split(' (')[0])) / 86400000;
  t('page claim: the objection was in print within four months of the claim', src.includes('The objection was in print within four months of the claim.') && days('bennett2021', 'madsen2022') > 0 && days('bennett2021', 'madsen2022') < 120);
  t('page claim: the 2025 first author was a 2021 coauthor', src.includes('whose first author was also a 2021 coauthor') && AUTHORS.bennett2021.includes(SOURCES.find(q => q.id === 'holliday2025').authors.split(', ')[0]));
  t('page claim: the claimants replied in the same issue', src.includes('The claimants replied in the same issue') && SOURCES.find(q => q.id === 'madsen2022').venue.split(',')[0] === SOURCES.find(q => q.id === 'pigati2022').venue.split(',')[0] && SOURCES.find(q => q.id === 'madsen2022').date === SOURCES.find(q => q.id === 'pigati2022').date);
  t('dek says eleven, and there are eleven', META.dek.includes(`all ${words[bundle.seeds.length]} from`));
  const J = ENGINE.joinLayers(bundle.seeds, bundle.layers), lab = id => J.find(x => x.id === id)?.label, seed = id => bundle.seeds.find(x => x.id === id);
  t('page claim: USGS-1810 and USGS-1808 are different sample numbers released at one elevation', src.includes('is USGS-1810, a different sample (Figure 2A labels it 3a, against 2a for USGS-1808) released at the same elevation') && lab('USGS-1810') === '3a' && lab('USGS-1808') === '2a' && seed('USGS-1810').elevation === seed('USGS-1808').elevation && suffix(seed('USGS-1810')) !== suffix(seed('USGS-1808')));
  const th = bundle.context.rows.filter(r => r.kind === 'track-horizon').map(r => r.elevation), lowestDated = Math.min(...bundle.seeds.map(x => x.elevation), ...bundle.pollen.map(x => x.elevation));
  t('page claim: the drawn frame holds every released surface and sample, and the placed quartz band lies between the lowest track horizon and the lowest radiocarbon sample', FRAME.bottom < Math.min(...th) && FRAME.top > Math.max(...th, ...bundle.seeds.map(x => x.elevation), ...bundle.pollen.map(x => x.elevation)) && OSL_BAND.top < lowestDated && OSL_BAND.bottom > Math.min(...th) && OSL_BAND.leader < OSL_BAND.top && OSL_BAND.leader > OSL_BAND.bottom && src.includes('The quartz level is placed from the article\'s description, just below the lowest radiocarbon sample; the release gives no elevation for it.') && bundle.osl.every(o => !('elevation' in o)));
  t('page claim: the pollen sample numbers echo the seed samples beside them', src.includes('The pollen sample numbers 1aa, 1dd and 1ff echo the seed samples 1a, 1d and 1f beside them') && bundle.pollen.map(suffix).join() === '1aa,1dd,1ff' && bundle.pollen.every(q => bundle.context.pairs.some(p => p.pollen === q.id && suffix(seed(p.seed)) === suffix(q).slice(0, -1))));
  t('page claim: the verdict box and the dated record name the same objections', ['seed', 'pollen', 'luminescence'].every(w => META.verdictScope.includes(w) && TIMELINE.find(e => e.source === 'rhode2024').text.includes(w)) && META.verdictScope.includes('less consistent than reported') && META.verdictScope.includes('the claimants reject each'));
  t('headline number is the printed span', JSON.stringify(numbersIn(META.headline)) === JSON.stringify([REPORT.ka(a.publishedSpan, 2)]));
  t('plain, SEO title, OG description and would-change carry no numbers', [META.plain, META.seoTitle, META.ogDescription, META.wouldChange].every(s => numbersIn(s).length === 0));
  t('novelty and decision dates are the as-of date and the claim month', JSON.stringify(numbersIn(META.novelty)) === JSON.stringify(META.asOf.split('-')) && META.decision.includes(`September ${yearOf('bennett2021')}`) && META.decision.includes(META.asOf) && SOURCES[0].date.startsWith('24 September'));
  // The dated record, the sources and the related strata, each against content.js.
  const tl = elements(src, 'data-timeline');
  t('eleven dated events, in order', tl.length === TIMELINE.length && tl.every((e, i) => Number(e.key) === i));
  const month = d => new Date(`1 ${d}`).getTime();
  t('the dated record runs forward in time', TIMELINE.every((e, i) => i === 0 || month(e.date) >= month(TIMELINE[i - 1].date)));
  for (const [i, e] of tl.entries()) {
    const want = TIMELINE[i], s = SOURCES.find(x => x.id === want.source);
    t(`timeline ${i} text, date and source`, e.inner.includes(`<span class="when">${want.date}</span>`) && e.inner.includes(`<p>${want.text}</p>`) && e.inner.includes(`href="#source-${want.source}"`) && s && s.date.includes(want.date.split(' ')[1]) && (s.date.includes(want.date.split(' ')[0]) || s.date.startsWith(want.date)));
  }
  t('timeline numbers come from quotations', [['23', 'factSheet'], ['21', 'factSheet'], ['1947', 'malpais'], ['7,400', 'malpais'], ['7,500', 'rachal'], ['5', 'holliday'], ['21', 'holliday']].every(([n, q]) => QUOTES[q].includes(n) || QUOTES[q].replace(/(\d)(\d{3})\b/g, '$1,$2').includes(n)));
  const refs = elements(src, 'data-source');
  t('every source listed once, in order', refs.map(e => e.key).join() === SOURCES.map(s => s.id).join());
  for (const e of refs) {
    const s = SOURCES.find(x => x.id === e.key), role = s.role[0].toUpperCase() + s.role.slice(1);
    t(`source ${s.id} printed field by field`, e.text === `${role}. ${citation(s)} ${s.url} · ${s.date}. ${s.note}` && e.inner.includes(`href="${s.url}"`));
  }
  const rel = [...src.matchAll(/<div><a href="\/strata\/([\w-]+)\/">([^<]+)<\/a><p>([^<]+)<\/p><\/div>/g)];
  t('related strata printed with their notes', rel.length === RELATED.length && rel.every((m, i) => m[1] === RELATED[i].slug && clean(m[2]) === RELATED[i].title && clean(m[3]) === RELATED[i].note));
  t('related strata exist', RELATED.every(r => fs.existsSync(path.join(ROOT, 'public/strata', r.slug, 'index.html'))));
  // The head.
  t('SEO title', clean(src.match(/<title>([\s\S]*?)<\/title>/)?.[1] ?? '') === META.seoTitle);
  t('poetic H1', clean(src.match(/<h1>([\s\S]*?)<\/h1>/)?.[1] ?? '') === META.title);
  t('canonical URL', src.includes(`<link rel="canonical" href="${PAGE_URL}">`));
  t('meta description is the dek', metaContent(src, 'description') === META.dek);
  const og = {'og:type': 'article', 'og:site_name': 'Artificial Wasteland', 'og:title': `${META.title} · Artificial Wasteland`, 'og:description': META.ogDescription, 'og:url': PAGE_URL, 'og:image': IMAGE, 'og:image:width': '1200', 'og:image:height': '630', 'og:image:alt': `${META.title} · Artificial Wasteland`};
  for (const [k, v] of Object.entries(og)) t(`meta ${k}`, metaContent(src, k, 'property') === v);
  const tw = {'twitter:card': 'summary_large_image', 'twitter:title': `${META.title} · Artificial Wasteland`, 'twitter:description': META.ogDescription, 'twitter:image': IMAGE};
  for (const [k, v] of Object.entries(tw)) t(`meta ${k}`, metaContent(src, k) === v);
  const inline = [...src.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/g)].filter(m => !/\bsrc=/.test(m[1]));
  t('the only inline script is the JSON-LD', inline.length === 1 && inline[0][1].includes('application/ld+json'));
  try {
    const j = JSON.parse(inline[0][2]);
    for (const [k, v] of Object.entries({'@context': 'https://schema.org', '@type': 'Article', name: META.seoTitle, headline: META.title, description: META.dek, url: PAGE_URL, image: IMAGE, datePublished: META.date, dateModified: META.date})) t(`JSON-LD ${k}`, j[k] === v);
    t('JSON-LD author and publisher', j.author?.name === 'Artificial Wasteland' && j.publisher?.name === 'Artificial Wasteland');
  } catch (e) { t(`JSON-LD parses: ${e.message}`, false); }
  t('module script and load-bearing closing tags', src.includes('<script type="module" src="./page.js"></script>\n</body>\n</html>') && src.trim().endsWith('</html>'));
  t('self-hosted fonts', src.includes('<link rel="stylesheet" href="/fonts/fonts.css">'));
  t('no shell command or private repository link for the reader', !/github\.com\/[^\s"/]+\/Artificial-Wasteland|\bnode research\/|\bnpm (run|install)\b|\bpython3? /.test(src));
  t('no judgement of people and no verdict words the OPEN status forbids', !/\b(debunk\w*|refuted|disproved|fraud\w*|fabricat\w*|misconduct|hoax|cover-up|dishonest\w*|settled)\b/i.test(clean(src)));
  // Frontmatter.
  for (const [k, v] of Object.entries({title: META.title, dek: META.dek, seoTitle: META.seoTitle, plain: META.plain, seam: 'groundtruth', href: `/strata/${SLUG}/`})) t(`frontmatter ${k}`, fm.includes(`\n${k}: "${v}"\n`));
  t('frontmatter date and published flag', fm.includes(`\ndate: ${META.date}\n`) && /\ndraft: false\n/.test(fm));
  t('frontmatter tags include the wave tags', /tags: \[[^\]]*"immersive"[^\]]*"interactive"[^\]]*"show-the-check"[^\]]*"extraordinary-claims"/.test(fm));
  const fmRel = [...fm.matchAll(/  - to: ([\w-]+)\n    note: "([^"]+)"/g)];
  t('frontmatter relates: three to five real edges matching the page', fmRel.length >= 3 && fmRel.length <= 5 && fmRel.every((m, i) => m[1] === RELATED[i].slug && m[2] === RELATED[i].note));
  t('plain placard: 90 to 420 characters, at most three sentences, no double quote, no em dash', META.plain.length >= 90 && META.plain.length <= 420 && (META.plain.match(/[.!?](\s|$)/g) || []).length <= 3 && !META.plain.includes('"') && !META.plain.includes(EM));
}

function staticFileChecks(emit) {
  const t = (name, ok) => emit('rendered_figures_asserted', name, ok);
  for (const f of ['engine.js', 'data.js', 'content.js', 'report.js', 'render.js', 'page.js', 'sweep-worker.js']) {
    const src = read(path.join(PUB, f));
    t(`node syntax check ${f}`, spawnSync(process.execPath, ['--check', '--input-type=module'], {input: src, encoding: 'utf8'}).status === 0);
    t(`${f} makes no third-party request`, !/\b(fetch|import|Worker|XMLHttpRequest|WebSocket|EventSource|sendBeacon)\s*\(\s*['"`]https?:/.test(src) && !/new URL\(\s*['"`]https?:/.test(src) && !/src\s*=\s*['"`]https?:/.test(src));
  }
  t('data.js fetches only same-origin relative files', /new URL\('\.\/data\/' \+ name, import\.meta\.url\)/.test(read(path.join(PUB, 'data.js'))));
  t('render.js computes no reported result', !/\b(calibrateMeasurement|summarizeCalibration|envelopeGap|publishedSensitivity|runAnchor|runControl|comparePair|sweepPair|diagnostic|layerConsistency|oslArithmetic)\s*\(/.test(read(path.join(PUB, 'render.js'))) && /^import \{ka, short\} from '\.\/report\.js';\nimport \{SETTINGS\} from '\.\/engine\.js';$/m.test(read(path.join(PUB, 'render.js'))));
  const css = read(path.join(PUB, 'style.css'));
  t('reduced-motion guard and visible focus', css.includes('@media (prefers-reduced-motion:reduce)') && css.includes(':focus-visible{outline:3px'));
  t('every grid child is allowed to shrink', (css.match(/grid-template-columns/g) || []).length >= 6 && (css.match(/min-width:0/g) || []).length >= 8);
  const own = [...fs.readdirSync(PUB).filter(f => fs.statSync(path.join(PUB, f)).isFile()).map(f => path.join(PUB, f)), ...fs.readdirSync(path.join(PUB, 'data')).filter(f => /\.json$/.test(f)).map(f => path.join(PUB, 'data', f)),
    ...fs.readdirSync(HERE).filter(f => /\.(mjs|py|md|json)$/.test(f)).map(f => path.join(HERE, f)), fmPath].filter(f => fs.existsSync(f));
  for (const f of own) t(`no em dash in ${path.relative(ROOT, f)}`, !read(f).includes(EM));
  const slider = html.match(/<input type="range" id="reservoir"[^>]*>/)?.[0] ?? '';
  emit('choices_are_live', 'slider bounds wired to the engine’s grid', slider.includes(`min="0" max="${ENGINE.SETTINGS.maxReservoir}" step="${ENGINE.SETTINGS.reservoirStep}" value="0"`));
  emit('choices_are_live', 'every choice has a control on the page', ['show-seeds', 'show-pollen', 'show-quartz', 'younger', 'stat-midpoint', 'stat-mean', 'pair', 'reservoir', 'convention', 'domain-fraction', 'domain-age', 'reset'].every(id => html.includes(`id="${id}"`)));
  emit('choices_are_live', 'convention options are the declared ones', /<option value="radiocarbon">[^<]+<\/option><option value="calendar">[^<]+<\/option>/.test(html));
}

// ---------------------------------------------------------------- provenance
function provenanceChecks(emit) {
  const t = (name, ok) => emit('provenance_pinned', name, ok);
  const readme = fs.existsSync(path.join(HERE, 'README.md')) ? read(path.join(HERE, 'README.md')) : '';
  for (const r of record.records) {
    const pub = path.join(PUB, r.path), res = path.join(HERE, r.path);
    t(`${r.name} SHA-256 pinned`, fs.existsSync(pub) && sha(fs.readFileSync(pub)) === r.sha256);
    if (fs.existsSync(res)) t(`${r.name} research copy has the same bytes`, sha(fs.readFileSync(res)) === r.sha256);
    else notes.push(`${r.path}: no research copy present; the public copy is pinned`);
    t(`${r.name} README carries its hash and URL`, readme.includes(r.sha256) && readme.includes(r.url));
    t(`${r.name} licence, source and retrieval date`, r.licence.length > 20 && /^https:\/\//.test(r.licence_url) && /^https:\/\//.test(r.url) && r.retrieved === META.asOf);
  }
  const shipped = fs.readdirSync(path.join(PUB, 'data'));
  t('every shipped data file is in record.json', shipped.every(f => record.records.some(r => r.path === `data/${f}`)));
  t('every file the page loads is pinned', [...Object.values(DATA_FILES), CURVE_FILE].every(f => record.records.some(r => r.path === `data/${f}`)));
  const header = bundle.curveText.split('\n').filter(l => l.startsWith('#'));
  const authors = header.slice(2, 8).join(' ').replace(/#/g, '').split('. 2020.')[0].split(',').map(s => s.trim()).filter(Boolean);
  t('IntCal20 file intact: 9,501 rows, header citation, 42 authors', IC.rows === 9501 && header.some(l => l.includes('doi: 10.1017/RDC.2020.41')) && authors.length === 42 && /Reimer and 41 coauthors/.test(SOURCES.find(s => s.id === 'reimer2020').authors));
  const notice = read(path.join(PUB, 'NOTICE.txt'));
  t('NOTICE names the USGS statement, the curve licence and the article terms', ["for the most part, is in the public domain", "creativecommons.org/licenses/by/4.0", "not for redistribution", "layers.json", "CC BY-NC 4.0"].every(k => notice.replace(/\s+/g, ' ').includes(k)));
  t('no restricted article bytes kept in research', !fs.readdirSync(HERE, {recursive: true}).some(f => /\.pdf$|claimant\.txt$|control\.txt$|science.*\.html$/i.test(String(f))));
  t('every quotation audited verbatim against its source', Object.entries(QUOTES).every(([k, q]) => audit.quotes.some(a => a.key === k && a.verbatim && a.quote_sha256 === sha(Buffer.from(q)))));
  t('every quotation source was retrieved with HTTP 200', audit.retrievals.every(r => r.status === 200 && /^[0-9a-f]{64}$/.test(r.sha256)));
  // The six pairs, re-derived from the shipped extracts on every run: a seed and a pollen date are
  // paired exactly when their released elevations agree to the 2023 table's two decimals.
  const derived = bundle.seeds.flatMap(q => bundle.pollen.filter(p => Math.abs(q.elevation - p.elevation) <= 0.005).map(p => `${q.id}|${p.id}|${p.elevation}`)).sort();
  t('the six same-elevation pairs re-derived from the shipped extracts', derived.length === 6 && JSON.stringify(derived) === JSON.stringify(bundle.context.pairs.map(p => `${p.seed}|${p.pollen}|${p.elevation}`).sort()));
  // Re-extract the frozen JSON from the source CSVs when they are present (they are gitignored).
  const csv = f => { const p = path.join(HERE, 'data', f); return fs.existsSync(p) ? read(p).trim().split('\n').slice(1).map(l => l.split(',')).filter(r => r[0]) : null; };
  const seedsCsv = csv('source-seeds.csv'), ctrlCsv = csv('source-control.csv');
  if (seedsCsv && ctrlCsv) {
    t('seed extract matches the release by column position', seedsCsv.length === 11 && seedsCsv.every(r => { const s = bundle.seeds.find(x => x.id === r[1]); return s && near(s.age, Number(r[5]) * 1000, 1e-6) && near(s.sigma, Number(r[6]) * 1000, 1e-6) && near(s.published.low, Math.min(r[7], r[8]) * 1000, 1e-6) && near(s.published.high, Math.max(r[7], r[8]) * 1000, 1e-6) && near(s.published.mid, Number(r[9]) * 1000, 1e-6) && near(s.published.half, Number(r[10]) * 1000, 1e-6); }));
    t('pollen extract matches the release by column position', bundle.pollen.every(p => { const r = ctrlCsv.find(x => x[1] === p.id); return r && p.fraction === Number(r[6]) && p.fractionSigma === Number(r[7]) && near(p.published.mid, Number(r[12]) * 1000, 1e-6) && near(p.published.half, Number(r[13]) * 1000, 1e-6); }));
    t('pairs share a released elevation in the control table', bundle.context.pairs.every(p => { const s = ctrlCsv.find(x => x[1] === p.seed), q = ctrlCsv.find(x => x[1] === p.pollen); return s && q && s[2] === q[2] && Number(s[2]) === p.elevation; }));
  } else if (ARG.has('--with-sources')) t('source CSVs present, as --with-sources requires', false);
  else notes.push('source CSVs absent (research/*/data/*.csv is gitignored); the frozen JSON is pinned by hash and the pairs are re-derived from it');
}

// ---------------------------------------------------------------- the dated verdict
function verdictChecks(emit) {
  const t = (name, ok) => emit('verdict_dated', name, ok);
  const facts = Object.fromEntries(elements(html, 'data-fact').map(e => [e.key, e.text]));
  t('category OPEN in the record and on the page', record.verdict.category === 'OPEN' && META.verdict === 'OPEN' && facts.verdict === 'OPEN');
  t('as-of date in the record and on the page', record.verdict.as_of === META.asOf && facts.asOf === META.asOf);
  t('at least two sources, each printed field by field and linked', record.verdict.sources.length >= 2 && record.verdict.sources.every(c => SOURCES.some(s => citation(s) === c && html.includes(`id="source-${s.id}"`))));
  t('the sources include the objection, the reply and the support', ['rhode2024', 'pigati2024', 'holliday2025', 'usgs2026'].every(id => record.verdict.sources.includes(citation(SOURCES.find(s => s.id === id)))));
  t('what would change it, verbatim on the page', record.verdict.would_change === META.wouldChange && byId(html, 'would-change') === META.wouldChange);
  t('no decision date asserted', record.decided_by === 'not-yet' && record.years_to_decision === null && byId(html, 'decision') === META.decision);
  t('the claimants’ reply is given with its evidence', html.includes(`data-quote="reply2024"`) && html.includes('data-quote="response2022"') && html.includes('data-quote="modernPollen"'));
  t('the category is labelled as the page’s mapping', META.verdictScope.includes('no source has voted on the word') && byId(html, 'verdict-scope') === META.verdictScope);
  t('headline and novelty in the record and on the page', record.headline === META.headline && record.novelty === META.novelty && byId(html, 'headline') === META.headline && byId(html, 'novelty') === META.novelty);
  t('novelty is bounded', /^we searched .+ on 2026-09-22 and did not find /.test(META.novelty));
}

// ---------------------------------------------------------------- formatter against independent numbers
function reportChecks(R, P, emit) {
  const t = (name, ok) => emit('rendered_figures_asserted', name, ok);
  const base = R.baseReadouts(P), num = s => (String(s).replace(/−/g, '-').replace(/,/g, '').match(/-?\d+(\.\d+)?/g) || []).map(Number);
  const old = indSeed['USGS-1810'], young = indSeed['USGS-1803'];
  t('formatter: anchorOld', JSON.stringify(num(base.anchorOld)) === JSON.stringify([+(old.mid / 1000).toFixed(4), +(old.half / 1000).toFixed(4)]));
  t('formatter: anchorYoung', JSON.stringify(num(base.anchorYoung)) === JSON.stringify([+(young.mid / 1000).toFixed(4), +(young.half / 1000).toFixed(4)]));
  t('formatter: anchorSpan', near(num(base.anchorSpan)[0], (old.mid - young.mid) / 1000, 5e-5));
  t('formatter: powerGap', near(num(base.powerGap)[0], (20300 - (23180 - 7500)) / 1000, 5e-3));
  t('formatter: powerThreshold', near(num(base.powerThreshold)[0], 2.88, 5e-3));
  t('formatter: powerWidths', JSON.stringify(num(base.powerWidths)) === '[4.97,4.72,4.69]');
  t('formatter: layer 1a z', num(base.layerStatus).includes(3.61) && base.layerStatus.startsWith('Sample 1a: USGS-1803 and USGS-1828 differ by 460'));
  t('formatter: anchor status counts', /^REPRODUCED: 11 of 11 seed envelopes/.test(base.anchorStatus) && base.anchorStatus.includes(`${Math.max(...bundle.seeds.map(s => Math.max(...['low', 'high', 'mid', 'half'].map(k => Math.abs(indSeed[s.id][k] - s.published[k])))))} years (USGS-1808)`));
  t('formatter: statistic readouts', R.statisticReadout(P, 'mean').startsWith(`Posterior means: ${bundle.seeds.filter(s => Math.abs(indSeed[s.id].mean - s.published.mid) <= 20).length} of 11`));
  const y = R.trenchReadouts(ENGINE.visibleEvidence(P.anchor, P.control, 'pollen', 'younger'));
  const indGap = Math.min(...Object.values(indPollen).map(p => p.low)) - (Math.max(...Object.values(indSeed).map(s => s.high)) - 7500);
  t('formatter: younger gap', near(num(y.trenchGap)[0], indGap / 1000, 5e-4) && y.trenchLGM === 'outside' && y.trenchGap.endsWith('the pollen older'));
  // Leave one out, against the independent calibrator.
  const mids = bundle.seeds.map(q => indSeed[q.id].mid), full = Math.max(...mids) - Math.min(...mids);
  const spans = bundle.seeds.map((q, i) => { const m = mids.filter((_, j) => j !== i); return {id: q.id, change: full - (Math.max(...m) - Math.min(...m))}; });
  const most = spans.reduce((a, x) => x.change > a.change ? x : a), other = Math.max(...spans.filter(x => x !== most).map(x => x.change));
  t('formatter: leave-one-out sentence', base.looStatus === `Across all eleven recomputed midpoints the seeds span ${(full / 1000).toFixed(4)} ka. Set ${most.id} aside and they span ${((full - most.change) / 1000).toFixed(4)} ka; setting aside any other single aliquot changes the span by at most ${Math.round(other)} years.`);
  // Every conclusion a live sentence states must follow its computed state. Doctored copies of the
  // data go through the unmodified engine, and the sentence has to change with the result.
  const curve = ENGINE.parseCurve(bundle.curveText);
  const sd = structuredClone(bundle.seeds); P.anchor.rows.forEach((r, i) => { sd[i].published.mid = Math.round(r.summary.mean); });
  const aMean = ENGINE.runAnchor(sd, curve), Pm = {...P, mean: ENGINE.statisticAgreement(aMean.rows, 'mean'), midpoint: ENGINE.statisticAgreement(aMean.rows, 'midpoint')};
  t('formatter: the statistic verdict follows the count, not the button', R.statisticReadout(P, 'mean').endsWith('The printed column is not a posterior mean.') && R.statisticReadout(P, 'midpoint').endsWith('The printed column matches the middle of the range.') && Pm.mean.outside === 0 && R.statisticReadout(Pm, 'mean').endsWith('The printed column matches a posterior mean.') && Pm.midpoint.outside > 0 && R.statisticReadout(Pm, 'midpoint').endsWith('The printed column is not the middle of the range.'));
  const older = structuredClone(bundle.seeds); older.forEach(q => { q.age += 7000; });
  const vOld = ENGINE.visibleEvidence(ENGINE.runAnchor(older, curve), P.control, 'pollen', 'younger'), tOld = R.trenchReadouts(vOld);
  t('formatter: the younger-scenario words follow Last Glacial Maximum containment and the gap', vOld.seedsInsideLGM && vOld.pollenSide === 'overlapping' && tOld.trenchStatus.includes('stays inside the Last Glacial Maximum') && !tOld.trenchStatus.includes('leaves') && tOld.trenchStatus.includes('overlapping the seeds') && !/ka older/.test(tOld.trenchStatus) && tOld.trenchGap === 'overlapping' && R.trenchReadouts(ENGINE.visibleEvidence(P.anchor, P.control, 'seeds', 'younger')).trenchStatus.includes('and leaves the Last Glacial Maximum'));
  const pyo = structuredClone(bundle.pollen); pyo.forEach(q => { q.fraction = 0.21; });
  const cy = ENGINE.runControl(pyo, curve, bundle.osl), tY = R.trenchReadouts(ENGINE.visibleEvidence(P.anchor, cy, 'pollen', 'measured')), tYq = R.trenchReadouts(ENGINE.visibleEvidence(P.anchor, cy, 'all', 'measured'));
  t('formatter: pollen doctored younger than the seeds is reported younger, and the page stops saying it supports the old ages', !tY.trenchStatus.includes('supports the old ages') && tY.trenchStatus.includes('ka younger than the seeds') && tY.trenchGap.endsWith('the pollen younger') && !tYq.trenchStatus.includes('supports the old ages'));
  t('formatter: the ten-second sentence is printed on the real data', R.trenchReadouts(ENGINE.visibleEvidence(P.anchor, P.control, 'pollen', 'measured')).trenchStatus.startsWith('Independent material supports the old ages'));
  t('formatter: the quartz sentence attributes the minimum-age reading and gives the critics’ reading', R.trenchReadouts(ENGINE.visibleEvidence(P.anchor, P.control, 'all', 'measured')).trenchStatus.includes('The authors report them as minimum ages for that level, and the critics argue they may instead be too old'));
  const pag = structuredClone(bundle.pollen); pag.forEach(q => { q.age += 2000; });
  const dOld = ENGINE.diagnostic(pag, curve, 'age');
  t('formatter: the approximation’s direction follows the sign of its shift', dOld.rows.every(r => r.shift < 0) && R.diagnosticReadout(dOld).includes('years older than the fraction calculation') && !R.diagnosticReadout(dOld).includes('younger') && R.diagnosticReadout(ENGINE.diagnostic(bundle.pollen, curve, 'age')).includes('341 years younger than the fraction calculation'));
  const ob = structuredClone(bundle.osl); ob[1].minimumAge += 300;
  const oslBad = R.baseReadouts({...P, osl: ENGINE.oslArithmetic(ob)}).oslStatus;
  t('formatter: a failing OSL row is named, and the sentence stops saying each lies within rounding', oslBad.startsWith('NOT consistent') && !oslBad.includes('each printed minimum age lies within') && oslBad.includes(ob[1].id) && base.oslStatus.startsWith('Consistent') && base.oslStatus.includes('each printed minimum age lies within the rounding'));
  const unique = structuredClone(bundle.layers); unique.rows.forEach((r, i) => { r.label = `u${i}`; });
  t('formatter: with no shared sample number the layer sentence says nothing was tested', R.baseReadouts({...P, layers: ENGINE.layerConsistency(bundle.seeds, unique)}).layerStatus === 'No sample number holds two aliquots, so nothing was tested.');
  return {indGap};
}

// ---------------------------------------------------------------- run
// --regen writes the manifest first (with every ledger cell provisionally false) so that checks
// which read record.json see the regenerated file, then rewrites it with the computed ledger.
if (ARG.has('--regen')) {
  const P0 = ENGINE.prepare(bundle, ENGINE.parseCurve(bundle.curveText));
  record = buildRecord(P0, Object.fromEntries(KEYS.map(k => [k, false])));
  fs.writeFileSync(path.join(PUB, 'record.json'), JSON.stringify(record, null, 2) + '\n');
}
const P = mathematicalTests(ENGINE, check);
furtherTests(P, check);
surfaceChecks(html, frontmatter, P, check);
staticFileChecks(check);
provenanceChecks(check);
verdictChecks(check);
const {indGap} = reportChecks(REPORT, P, check);

if (ARG.has('--mutate')) {
  const red = (src, fm) => { const r = []; surfaceChecks(src, fm, P, (_k, _n, ok) => r.push(ok)); return r.some(ok => !ok); };
  const corrupt = s => s.replace(/\d/, d => String((Number(d) + 3) % 10)) === s ? s + ' altered' : s.replace(/\d/, d => String((Number(d) + 3) % 10));
  for (const attr of ['data-fact', 'data-quote']) for (const e of elements(html, attr)) {
    const changed = e.inner.includes(e.text) ? corrupt(e.text) : null;
    const altered = changed ? html.slice(0, e.start) + html.slice(e.start, e.end).replace(e.text, changed) : html.slice(0, e.start) + html.slice(e.start, e.end).replace(/>([^<]*[a-z][^<]*)</, (m, x) => `>${x} altered<`) + html.slice(e.end);
    const full = changed ? altered + html.slice(e.end) : altered;
    check('rendered_figures_asserted', `mutation caught: ${attr} ${e.key}`, full !== html && red(full, frontmatter)); mutations++;
  }
  for (const [name, from, to] of [
    ['meta description', `<meta name="description" content="In 2021,`, `<meta name="description" content="In 2020,`],
    ['og description', 'The old age survives the younger scenario if', 'The old age fails the younger scenario if'],
    ['JSON-LD description', '"description":"In 2021, radiocarbon dates on seeds', '"description":"In 2021, radiocarbon dates on sand'],
    ['title', '<title>How Old Are', '<title>How Young Are'],
    ['dek number', 'ranged from 22.86 to 21.13 thousand', 'ranged from 22.96 to 21.13 thousand'],
    ['headline span', 'confirm the 1.73 ka span', 'confirm the 1.37 ka span'],
    ['verdict word', 'data-fact="verdict">OPEN<', 'data-fact="verdict">VINDICATED<'],
    ['unbound prose numeral', 'and four sample numbers are shared by two aliquots each', 'and 4 sample numbers are shared by two aliquots each'],
    ['sample label claim', 'labels it 3a, against 2a for USGS-1808', 'labels it 2a, against 3a for USGS-1808'],
    ['pollen sample-number claim', 'The pollen sample numbers 1aa, 1dd and 1ff echo', 'The pollen sample numbers 1aa, 1dd and 1ee echo'],
    ['quartz placement disclosure', 'The quartz level is placed from the article', 'The quartz level is measured from the article'],
    ['option text', 'Translate 7,500 calendar years', 'Translate 7,000 calendar years'],
    ['source field', 'Science 382(6666), 73-75.', 'Science 382(6666), 73-79.'],
    ['timeline text', 'adds 5 seed dates and 21 bulk-sediment dates', 'adds 6 seed dates and 21 bulk-sediment dates'],
    ['related note', 'Its gold-196 half-life rests on three', 'Its gold-196 half-life rests on four']
  ]) { const altered = html.replace(from, to); check('rendered_figures_asserted', `mutation caught: ${name}`, altered !== html && red(altered, frontmatter)); mutations++; }
  for (const key of ['dek', 'plain', 'seoTitle', 'title']) {
    const changed = frontmatter.replace(`${key}: "${META[key]}"`, `${key}: "${META[key]} altered"`);
    check('rendered_figures_asserted', `mutation caught: frontmatter ${key}`, changed !== frontmatter && red(html, changed)); mutations++;
  }
  const engineSrc = read(path.join(PUB, 'engine.js'));
  const faults = [
    ['probability mass', 'mass: 0.954,', 'mass: 0.9,'],
    ['mean life', 'meanLife: 8033,', 'meanLife: 8267,'],
    ['curve error dropped', 'const variance = error * error + errors[t] * errors[t]', 'const variance = error * error'],
    ['HPD rank order reversed', 'order.sort((a, b) => r.p[b] - r.p[a] || a - b);', 'order.sort((a, b) => r.p[a] - r.p[b] || a - b);'],
    ['pollen control in age space', "summarizeCalibration(calibrateMeasurement(m, curve, {domain: 'fraction'}));\n    return {measurement: m, summary, insideLGM", "summarizeCalibration(calibrateMeasurement(m, curve, {domain: 'age'}));\n    return {measurement: m, summary, insideLGM"],
    ['reservoir added instead of subtracted', 'm.age - reservoir', 'm.age + reservoir'],
    ['translation size', 'calendarTranslation: 7500,', 'calendarTranslation: 7000,'],
    ['envelope gap sign', 'return Math.max(0, b.low - a.high, a.low - b.high);', 'return Math.max(0, b.high - a.low, a.low - b.high);'],
    ['youngest pollen taken as oldest', 'const youngestPollen = Math.min(...pollen.map(x => x.published.low));', 'const youngestPollen = Math.max(...pollen.map(x => x.published.low));'],
    ['span from computed, not printed', 'span: claimHigh - claimLow,', 'span: anchor.span,'],
    ['statistic swapped', "const value = statistic === 'midpoint' ? r.summary.mid : r.summary.mean;", "const value = statistic === 'midpoint' ? r.summary.mean : r.summary.mid;"],
    ['layer statistic unweighted', 'const T = members.reduce((a, m, i) => a + w[i] * (m.age - mean) ** 2, 0)', 'const T = members.reduce((a, m, i) => a + (m.age - mean) ** 2 / 10000, 0)'],
    ['sweep stops at first overlap', 'const firstIndex = scan.findIndex(x => x.gap > 0);', 'const firstIndex = scan.findIndex(x => x.gap > 1000);'],
    ['refusal removed', "if (Object.hasOwn(NOT_A_DATE, m.kind)) throw Error(NOT_A_DATE[m.kind]);", ''],
    ['OSL rounding ignored', 'const consistent = r.minimumAge + S.oslAgeHalfUnit >= low && r.minimumAge - S.oslAgeHalfUnit <= high;', 'const consistent = true;'],
    ['pair map bypassed', 'return selectPair(data, data.context.pairs.findIndex(p => p.seed === seedId && p.pollen === pollenId));', 'return selectPair(data, 0);'],
    ['pair cache used for the wrong pair', 'const base = fixed && fixed.pairIndex === pairIndex ? fixed : pairFixed(data, curve, pairIndex);', 'const base = fixed ? fixed : pairFixed(data, curve, pairIndex);'],
    ['trench gap one-directional', 'const gapToPollen = envelopeGap({low: seedLow, high: seedHigh}, {low: pollenLow, high: pollenHigh});', 'const gapToPollen = Math.max(0, pollenLow - seedHigh);'],
    ['leave-one-out keeps every row', 'const span = spread(anchor.rows.filter((_, j) => j !== i));', 'const span = spread(anchor.rows);'],
    ['three aliquots tested as a pair', 'if ([...groups.values()].some(ids => ids.length > 2))', 'if (false)']
  ];
  for (const [name, from, to] of faults) {
    const changed = engineSrc.replace(from, to), r = [];
    if (changed !== engineSrc) {
      try { const E = await import(`data:text/javascript;base64,${Buffer.from(changed).toString('base64')}#${mutations}`); const MP = mathematicalTests(E, (_k, _n, ok) => r.push(ok)); }
      catch { r.push(false); }
    }
    check('rendered_figures_asserted', `engine mutation caught: ${name}`, changed !== engineSrc && r.some(ok => !ok)); mutations++;
  }
  const reportSrc = read(path.join(PUB, 'report.js')).replace("from './engine.js'", `from '${pathToFileURL(path.join(PUB, 'engine.js')).href}'`);
  for (const [name, from, to] of [
    ['ka rounding', 'export const ka = (n, d = 3) => (n / 1000).toFixed(d);', 'export const ka = (n, d = 3) => (n / 1001).toFixed(d);'],
    ['posterior mean shown as midpoint', 'export const pm = (s, d = 4) => `${ka(s.mid, d)} ± ${ka(s.half, d)} ka`;', 'export const pm = (s, d = 4) => `${ka(s.mean, d)} ± ${ka(s.half, d)} ka`;'],
    ['gap shown from midpoints', 'powerGap: `${ka(s.envelopeGap, 2)} ka`,', 'powerGap: `${ka(s.midpointGap, 2)} ka`,'],
    ['younger LGM word fixed', "const lgm = view.seedsInsideLGM ? 'stays inside' : 'leaves';", "const lgm = 'leaves';"],
    ['statistic verdict fixed', '${s.outside === 0 ? `The printed column matches ${what}.` : `The printed column is not ${what}.`}', 'The printed column is not ${what}.'],
    ['approximation direction fixed', "const dir = x => x > 0 ? 'younger' : x < 0 ? 'older' : 'no different';", "const dir = x => 'younger';"],
    ['OSL tail fixed', "${o.allConsistent ? 'each printed minimum age lies within the rounding of its printed columns.' : `the printed minimum age of ${list(oslBad)} lies outside the rounding of its printed columns.`}", 'each printed minimum age lies within the rounding of its printed columns.'],
    ['pollen sentence fixed', "const pollenNow = view.pollenSide === 'overlapping'", 'const pollenNow = true'],
    ['leave-one-out sentence', 'Set ${loo.most.id} aside and they span ${ka(loo.most.span, 4)} ka', 'Set ${loo.most.id} aside and they span ${ka(loo.full, 4)} ka']
  ]) {
    const changed = reportSrc.replace(from, to), r = [];
    if (changed !== reportSrc) { try { const R = await import(`data:text/javascript;base64,${Buffer.from(changed).toString('base64')}#r${mutations}`); reportChecks(R, P, (_k, _n, ok) => r.push(ok)); } catch { r.push(false); } }
    check('rendered_figures_asserted', `formatter mutation caught: ${name}`, changed !== reportSrc && r.some(ok => !ok)); mutations++;
  }
}

if (!ARG.has('--no-browser')) {
  const timer = setTimeout(() => { console.error('Browser validation exceeded 115 seconds.'); process.exit(1); }, 115000);
  try {
    const {browserCheck} = await import('./browser-check.mjs');
    const r = await browserCheck();
    check('rendered_figures_asserted', 'browser: readouts, tables, controls, keyboard, layout and network', r.assertions > 1000 && r.errors.length === 0 && r.externalRequests === 0);
    const s = r.snapshot, num = x => (String(x ?? '').replace(/−/g, '-').replace(/,/g, '').match(/-?\d+(\.\d+)?/g) || []).map(Number);
    const old = indSeed['USGS-1810'], young = indSeed['USGS-1803'];
    check('rendered_figures_asserted', 'reader sees the older anchor the independent calibrator gives', near(num(s.anchorOld)[0], old.mid / 1000, 5e-5) && near(num(s.anchorOld)[1], old.half / 1000, 5e-5));
    check('rendered_figures_asserted', 'reader sees the younger anchor the independent calibrator gives', near(num(s.anchorYoung)[0], young.mid / 1000, 5e-5) && near(num(s.anchorYoung)[1], young.half / 1000, 5e-5));
    check('rendered_figures_asserted', 'reader sees the grade-B gap from the printed numbers', near(num(s.powerGap)[0], 4.62, 5e-3) && s.powerCoarse === 'SEPARABLE, IF THE PREMISES HOLD' && s.powerNarrow === 'INCONCLUSIVE');
    check('rendered_figures_asserted', 'reader sees the younger-scenario gap the independent calibrator gives', near(num(s.youngerGap)[0], indGap / 1000, 5e-4));
    check('rendered_figures_asserted', 'reader sees the first separations the independent sweep gives', JSON.stringify(s.sweepTable.map(row => num(row[4])[0])) === JSON.stringify(indSweep()));
    check('rendered_figures_asserted', 'reader sees the domain shifts the independent calibrator gives', JSON.stringify(s.diagTable.map(row => num(row[3])[0])) === JSON.stringify(bundle.pollen.map(p => Math.round(indPollen[p.id].mid - indPollenAge[p.id].mid))));
    check('rendered_figures_asserted', 'reader sees the separation at R = 300 for the young-end pair', /^Outer envelopes separated by 0\.0\d\d ka\. R = 300 radiocarbon years subtracted/.test(s.pairAt300));
    check('rendered_figures_asserted', 'reader sees posterior means fail on the independent count', s.meanReadout.startsWith(`Posterior means: ${bundle.seeds.filter(x => Math.abs(indSeed[x.id].mean - x.published.mid) <= 20).length} of 11`));
    browserSummary = {assertions: r.assertions, widths: r.widths, externalRequests: r.externalRequests, errors: r.errors};
  } catch (e) { check('rendered_figures_asserted', `browser verification: ${e.message}`, false); }
  finally { clearTimeout(timer); }
} else check('rendered_figures_asserted', 'browser verification skipped by --no-browser', false);

// ---------------------------------------------------------------- the ledger and the manifest
const pass = k => outcomes[k].length > 0 && outcomes[k].every(r => r.pass);
const ledger = Object.fromEntries(KEYS.map(k => [k, k === 'control_can_confirm' ? pass(k) && injection.length > 0 && injection.every(r => r.pass) : pass(k)]));

function buildRecord(P, ledger) {
  const a = P.anchor, c = P.control, s = P.sensitivity, pm = REPORT.pm;
  const log = JSON.parse(read(path.join(HERE, 'retrieval-log.json')));
  const origin = key => log.find(r => r.name === key && /sciencebase\.gov\/catalog/.test(r.url) && !/r\.jina\.ai/.test(r.url))?.url;
  const proxy = key => log.find(r => r.name === key && r.status === 200)?.url;
  const usgs = id => `https://www1.usgs.gov/pir/api/identifiers/USGS:${id}`;
  const rel = [
    ['claimant-data', 'seeds.json', 'seeds', '6036950cd34eb12031174c77', bundle.seeds.length],
    ['control-data', 'pollen.json', 'control', '647782fed34e3ac335becbb0', bundle.pollen.length],
    ['control-data', 'osl.json', 'osl', '647782fed34e3ac335becbb0', bundle.osl.length],
    ['reference', 'context.json', 'control', '647782fed34e3ac335becbb0', bundle.context.rows.length],
    ['reference', 'field-map.json', 'dictionary', '647782fed34e3ac335becbb0', 3]
  ].map(([role, name, key, id, units]) => ({role, name, path: `data/${name}`, url: proxy(key), original_url: origin(key),
    licence: 'Derived factual numeric extract of a USGS data release; the release is "for the most part" public domain and may contain copyrighted items', licence_url: usgs(id),
    retrieved: META.asOf, sha256: sha(fs.readFileSync(path.join(PUB, 'data', name))), units}));
  rel.push({role: 'reference', name: 'layers.json', path: 'data/layers.json', url: 'https://geography.berkeley.edu/sites/default/files/science.adh5007.pdf', original_url: 'https://doi.org/10.1126/science.adh5007',
    licence: 'Factual sample labels transcribed from the text layer of Figure 2A; no figure or article text is reproduced', licence_url: 'https://www.science.org/about/science-licenses-journal-article-reuse',
    retrieved: META.asOf, sha256: sha(fs.readFileSync(path.join(PUB, 'data', 'layers.json'))), units: bundle.layers.rows.length});
  rel.push({role: 'reference', name: 'intcal20.14c', path: 'data/intcal20.14c', url: 'https://intcal.org/curves/intcal20.14c', original_url: 'https://intcal.org/curves/intcal20.14c',
    licence: 'IntCal20 curve as published by its authors; the article is CC BY 4.0 and no contrary notice is in the curve file', licence_url: 'https://creativecommons.org/licenses/by/4.0/',
    retrieved: META.asOf, sha256: sha(fs.readFileSync(path.join(PUB, 'data', 'intcal20.14c'))), units: IC.rows});
  const src = id => citation(SOURCES.find(x => x.id === id));
  return {
    slug: SLUG, title: META.title, href: `/strata/${SLUG}/`, field: 'archaeology',
    claim: {statement: QUOTES.summary, claimants: AUTHORS.bennett2021.join(', '), citation: src('bennett2021'), year: 2021,
      headline_as_printed: 'calibrated ages that range from 22.86 ± 0.32 to 21.13 ± 0.25 ka (N=11)'},
    records: rel,
    anchor: {what: 'All eleven released raw seed ages recalibrated against IntCal20 by the page’s engine; 95.4% envelope midpoints and half-spans compared with the release, headline rows USGS-1810 and USGS-1803.',
      expected: '22.86 ± 0.32 to 21.13 ± 0.25 ka (N=11); the release also prints 22.87 ± 0.30 ka for USGS-1808',
      computed: `${pm(a.old.summary)} to ${pm(a.young.summary)}; oldest recomputed midpoint ${REPORT.ka(a.maximum.summary.mid, 4)} ka (${a.maximum.measurement.id}); largest difference from the release ${a.maxGap} calendar years over all 11 rows`,
      agrees: a.agrees, tolerance: '20 calendar years per envelope end, midpoint and half-span: printed rounding to 0.01 ka, the curve’s native 10-year spacing here and a whole-year interval routine. Not added dating uncertainty; fixed before the comparison.'},
    control: {name: 'Three ancient terrestrial-pollen dates from the seed levels, each calibrated separately from its measured F14C, with the published OSL minimum ages carried alongside',
      citation: src('pigati2023'), computed: c.rows.map(r => `${r.measurement.id} ${pm(r.summary)}`).join('; '),
      as_printed: 'the resulting calibrated ages range from 23.4 ± 2.5 ka to 22.6 ± 2.3 ka; the minimum OSL age of the sampled horizon is >21.5 ± 1.9 ka'},
    power: {grade: 'B-published-sensitivity',
      planted: `No injection is possible: the laboratory control cannot be rerun. The claim’s printed span, ${REPORT.ka(s.span, 2)} ka, is set against the control authors’ printed pollen ranges, and the full printed seed envelope is moved ${REPORT.yr(s.shift)} calendar years younger, the scale of the modern-analogue argument.`,
      recovered: `Pollen widths ${s.widths.map(w => REPORT.ka(w.width, 2)).join(', ')} ka, all wider than the span and all containing the headline interval; moved envelope ${REPORT.ka(s.shiftedEnvelopeLow, 2)} to ${REPORT.ka(s.shiftedEnvelopeHigh, 2)} ka lies ${REPORT.ka(s.envelopeGap, 2)} ka below the youngest pollen edge; resolution threshold ${REPORT.ka(s.thresholdShift, 2)} ka.`,
      verdict: `${s.narrowSpan === 'INCONCLUSIVE' ? 'the control could NOT have confirmed the narrow claim (and the page says inconclusive)' : 'the control COULD have confirmed the narrow claim'}: its published resolution ${s.coarseSeparated ? `separates a Last Glacial Maximum age from a chronology about ${REPORT.yr(s.shift)} calendar years younger only if the pollen dates its layer and the processing correction holds` : `does not separate a Last Glacial Maximum age from a chronology about ${REPORT.yr(s.shift)} calendar years younger`}, while the ${REPORT.ka(s.span, 2)} ka span, the occupation duration, reworking and the sample-to-track link are ${s.narrowSpan}.`},
    null_through_claimant_method: {applicable: false, what: META.nullReason, result: 'No null discovery rate is claimed.'},
    verdict: {category: META.verdict, as_of: META.asOf, sources: ['rhode2024', 'pigati2024', 'holliday2025', 'rachal2025', 'usgs2026'].map(src),
      source_urls: ['rhode2024', 'pigati2024', 'holliday2025', 'rachal2025', 'usgs2026'].map(id => SOURCES.find(x => x.id === id).url), would_change: META.wouldChange},
    decided_by: 'not-yet', years_to_decision: null,
    years_to_decision_note: 'No decision date is asserted; the record is still argued as of 2026-09-22.',
    choices: CHOICES, headline: META.headline, novelty: META.novelty,
    ledger: Object.fromEntries(KEYS.map(k => [k, {value: ledger[k], assertion: LABELS[k]}]))
  };
}
const expectedRecord = buildRecord(P, ledger);
if (ARG.has('--regen')) {
  fs.writeFileSync(path.join(PUB, 'record.json'), JSON.stringify(expectedRecord, null, 2) + '\n');
  console.error('record.json written with the ledger this run computed; run again without --regen to confirm it.');
}
const manifest = JSON.stringify(JSON.parse(read(path.join(PUB, 'record.json')))) === JSON.stringify(expectedRecord);
const failures = KEYS.flatMap(k => outcomes[k].filter(r => !r.pass).map(r => `${k}: ${r.name}`));
if (!manifest) failures.push('record.json differs from the manifest the verifier computes (run with --regen after a clean pass).');
if (ARG.has("--tokens")) console.error(JSON.stringify(unbound(html)));
if (ARG.has("--ledger")) for (const k of KEYS) console.log(`${k}=${ledger[k]}`);
else console.log(JSON.stringify({pass: failures.length === 0, assertions: count, mutations, browser: browserSummary, notes: [...new Set(notes)], ledger, failures}, null, 2));
if (failures.length) { console.error(failures.join('\n')); process.exitCode = 1; }
