#!/usr/bin/env node
/**
 * verify-where-the-curve-goes-flat.mjs
 *
 * Offline recomputation of every load-bearing number that
 * public/strata/where-the-curve-goes-flat/index.html computes in the browser.
 *
 * The page embeds four published calibration curves (IntCal20, SHCal20, Marine20,
 * IntCal13) and five published post-bomb zonal series, delta-varint encoded. This
 * script:
 *
 *   1. reads the HTML, extracts those encoded strings, and decodes them with its
 *      own decoder implementation;
 *   2. rebuilds the calendar grid from the published spacing runs and checks the
 *      row counts and endpoints;
 *   3. if a network is available, re-downloads the published files from
 *      intcal.org and the rintcal data archive, pins each with a SHA-256, and
 *      asserts that every cal BP, radiocarbon age and 1-sigma value decoded out
 *      of the page matches the published row. The embedded encoding carries
 *      those three columns only, so this is row-for-row agreement and not a
 *      byte copy of the published file;
 *   4. re-implements the calibration, the HPD extraction, both plateau criteria,
 *      the mixing identities, the curve differencing, the spike ranking, the
 *      wiggle-match joint posterior, the Thera slope propagation and the
 *      bomb-clock inversion, and asserts the values the page shows.
 *
 * No dependencies beyond Node 22 built-ins. Exit 0 on success.
 *
 * Usage:  node research/where-the-curve-goes-flat/verify-where-the-curve-goes-flat.mjs
 *         node ...verify-where-the-curve-goes-flat.mjs --no-net   (skip downloads)
 *
 * --no-net runs every check that does not need the network and exits 0. The
 * provenance checks it skips are counted and reported, so the final check on the
 * page's stated total stays correct offline.
 */

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

const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, '..', '..');
const PAGE = path.join(ROOT, 'public', 'strata', 'where-the-curve-goes-flat', 'index.html');
const NO_NET = process.argv.includes('--no-net');

let checks = 0, failures = 0;
function ok(name, cond, detail) {
  checks++;
  if (cond) { console.log(`  ok  ${String(checks).padStart(3)}  ${name}${detail ? '  ->  ' + detail : ''}`); }
  else { failures++; console.log(`FAIL  ${String(checks).padStart(3)}  ${name}  ->  ${detail}`); }
}
function eq(name, got, want, tol = 0) {
  const good = (typeof got === 'number' && typeof want === 'number')
    ? Math.abs(got - want) <= tol
    : JSON.stringify(got) === JSON.stringify(want);
  ok(name, good, good ? fmt(got) : `got ${fmt(got)}, expected ${fmt(want)}${tol ? ' +/- ' + tol : ''}`);
}
function fmt(v) { return typeof v === 'number' ? String(v) : JSON.stringify(v); }
function section(s) { console.log('\n== ' + s); }

/* ---------------------------------------------------------------- 0. the page */

section('the page file');
const html = fs.readFileSync(PAGE, 'utf8');
ok('index.html exists and is non-trivial', html.length > 150000, html.length + ' bytes');
ok('closing tags are present and last',
  /<\/script>\s*<\/body>\s*<\/html>\s*$/.test(html), JSON.stringify(html.slice(-40)));
ok('no unreplaced build placeholders', !/__[A-Z0-9]{3,}__/.test(html),
  (html.match(/__[A-Z0-9]{3,}__/) || ['none'])[0]);
const externalScripts = [...html.matchAll(/<script[^>]*\ssrc="([^"]+)"/g)].map(m => m[1]);
eq('the only external script is the shared home banner', externalScripts, ['/media/home-banner.js']);
ok('no third-party origins referenced',
  !/(src|href)="https?:\/\/(?!artwaste\.land)/.test(html),
  (html.match(/(src|href)="https?:\/\/(?!artwaste\.land)[^"]+/) || ['none'])[0]);
eq('datePublished and dateModified are the landing date',
  [...html.matchAll(/"date(?:Published|Modified)":"([^"]+)"/g)].map(m => m[1]), ['2026-07-24', '2026-07-24']);

/* ------------------------------------------------- 1. decode the embedded data */

section('embedded curve data');
const AL = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
const IDX = new Map([...AL].map((c, i) => [c, i]));
function decodeVarints(s) {
  const out = []; let u = 0, sh = 1;
  for (const ch of s) {
    const c = IDX.get(ch);
    if (c === undefined) throw new Error('bad char in payload: ' + JSON.stringify(ch));
    u += (c & 31) * sh;
    if (c & 32) sh *= 32; else { out.push((u & 1) ? -(u + 1) / 2 : u / 2); u = 0; sh = 1; }
  }
  return out;
}
function undelta(d) { const o = new Array(d.length); let p = 0; for (let i = 0; i < d.length; i++) { p += d[i]; o[i] = p; } return o; }

/* pull the RAW object literal out of the page */
function payload(key, field) {
  const re = new RegExp(key + ":\\s*\\{[^}]*?" + field + ":\\s*'([A-Za-z0-9_-]+)'");
  const m = html.match(re);
  if (!m) throw new Error('could not find embedded payload ' + key + '.' + field);
  return m[1];
}
const GRIDS = {
  intcal20: [[1, 5000], [5, 2000], [10, 1000], [20, 1500]],
  shcal20: [[1, 5000], [5, 2000], [10, 1000], [20, 1500]],
  marine20: [[10, 5500]],
  intcal13: [[5, 2780], [10, 1110], [20, 1250]]
};
const KEYS = { intcal20: 'intcal20', shcal20: 'shcal20', marine20: 'marine20', intcal13: 'intcal13' };
const CURVE = {};
for (const k of Object.keys(KEYS)) {
  const mu = undelta(decodeVarints(payload(k, 'mu')));
  const sg = undelta(decodeVarints(payload(k, 'sg')));
  const cal = [0]; let t = 0;
  for (const [step, n] of GRIDS[k]) for (let i = 0; i < n; i++) { t += step; cal.push(t); }
  CURVE[k] = { cal, mu, sg, n: mu.length };
  ok(`${k}: decoded arrays and rebuilt grid agree in length`,
    mu.length === sg.length && mu.length === cal.length, `${mu.length} rows`);
}
eq('IntCal20 row count', CURVE.intcal20.n, 9501);
eq('SHCal20 row count', CURVE.shcal20.n, 9501);
eq('Marine20 row count', CURVE.marine20.n, 5501);
eq('IntCal13 row count', CURVE.intcal13.n, 5141);
eq('IntCal20 spans cal BP 0 to 55000', [CURVE.intcal20.cal[0], CURVE.intcal20.cal[9500]], [0, 55000]);
eq('IntCal13 spans cal BP 0 to 50000', [CURVE.intcal13.cal[0], CURVE.intcal13.cal[5140]], [0, 50000]);
eq('IntCal20 cal BP 0 row is 199 +/- 11 BP, not zero',
  [CURVE.intcal20.mu[0], CURVE.intcal20.sg[0]], [199, 11]);
eq('Marine20 cal BP 0 row', [CURVE.marine20.mu[0], CURVE.marine20.sg[0]], [603, 60]);

/* post-bomb series */
const PBKEYS = { NH1: 'NH1', NH2: 'NH2', NH3: 'NH3', SH12: 'SH12', SH3: 'SH3' };
const PB = {};
for (const k of Object.keys(PBKEYS)) {
  const m = html.match(new RegExp(k + ":\\s*'([-0-9. ;]+)'"));
  if (!m) throw new Error('post-bomb payload missing: ' + k);
  PB[k] = m[1].split(';').map(r => r.split(' ').map(Number));
  eq(`post-bomb ${k}: 70 annual rows`, PB[k].length, 70);
}

/* ------------------------------------------------ 2. provenance against source */

section('provenance of the embedded data');
const SOURCES = [
  ['intcal20', 'https://intcal.org/curves/intcal20.14c', '974a66649f2ac8a53e6c99e256b019ac6982f999b12dcf7193162d4c1c09168e'],
  ['shcal20', 'https://intcal.org/curves/shcal20.14c', 'e214d987bc4dbddfbc91c0aca4573a71db22a17c93d8bc55fa609bb58ae39b0d'],
  ['marine20', 'https://intcal.org/curves/marine20.14c', '3ce3741050016b6febeced357c334df39cf75356c28d4ae8e1c935be5ee3f168'],
  ['intcal13', 'https://intcal.org/curves/intcal13.14c', '0af281d2b559143ea9230c45e3c709137d868b8dbc09abf1ad16739fdb424cbd']
];
const PBSOURCES = [
  ['NH1', 'https://raw.githubusercontent.com/Maarten14C/rintcal/master/inst/extdata/postbomb_NH1.14C', 'ae0b36a953cbfe18df4316585cecd1d23fa9caee2a70f48e549b723ce1120b1d'],
  ['NH2', 'https://raw.githubusercontent.com/Maarten14C/rintcal/master/inst/extdata/postbomb_NH2.14C', '529bf781d53d89f0a55b522758526ad4d1a438b3c3b673fa0d150d4b5ab509f1'],
  ['NH3', 'https://raw.githubusercontent.com/Maarten14C/rintcal/master/inst/extdata/postbomb_NH3.14C', 'e4409dc16d0a04c41f374502f310f1b7c1733f55c92f81cb66da460bd8ef96f0'],
  ['SH12', 'https://raw.githubusercontent.com/Maarten14C/rintcal/master/inst/extdata/postbomb_SH1-2.14C', '9638769748c3ba0b1c980c088b89a3027f1fcbbfad42c5f1080d57deae3e408b'],
  ['SH3', 'https://raw.githubusercontent.com/Maarten14C/rintcal/master/inst/extdata/postbomb_SH3.14C', '004e9d5e4ae3eb98d35a7889a5c6b3eeb27b4f15502ec2b8b298f65a290ba174']
];
async function grab(url) {
  const ctl = new AbortController();
  const to = setTimeout(() => ctl.abort(), 25000);
  try {
    const r = await fetch(url, { signal: ctl.signal });
    if (!r.ok) return null;
    return Buffer.from(await r.arrayBuffer());
  } catch { return null; } finally { clearTimeout(to); }
}
/* How many checks the provenance section contributes when every source is reachable.
   Tracked so that the final self-referential count check is network-independent and
   --no-net still exits 0 rather than reporting a failure the page has not committed. */
const NET_EXPECTED = SOURCES.length * 2 + PBSOURCES.length * 2;
let netRun = 0;
if (NO_NET) {
  console.log('  --  network checks skipped (--no-net). The embedded data is still fully');
  console.log('      recomputed against every downstream assertion below.');
} else {
  let reached = false;
  for (const [name, url, sha] of SOURCES) {
    const buf = await grab(url);
    if (!buf) { console.log(`  --  ${name}: ${url} unreachable, provenance check skipped`); continue; }
    reached = true;
    const got = crypto.createHash('sha256').update(buf).digest('hex');
    ok(`${name}: published file SHA-256 matches the one recorded at build time`, got === sha, got);
    const rows = buf.toString('utf8').split('\n').map(l => l.trim())
      .filter(l => l && !l.startsWith('#')).map(l => l.split(',').map(Number))
      .filter(f => f.every(v => !Number.isNaN(v)))
      .sort((a, b) => a[0] - b[0]);
    const same = rows.length === CURVE[name].n
      && rows.every((r, i) => r[0] === CURVE[name].cal[i] && r[1] === CURVE[name].mu[i] && r[2] === CURVE[name].sg[i]);
    ok(`${name}: every cal BP, 14C age and 1 sigma matches the published file, row by row`, same,
      `${rows.length} published rows vs ${CURVE[name].n} embedded`);
    netRun += 2;
  }
  for (const [name, url, sha] of PBSOURCES) {
    const buf = await grab(url);
    if (!buf) { console.log(`  --  postbomb ${name}: unreachable, provenance check skipped`); continue; }
    reached = true;
    const got = crypto.createHash('sha256').update(buf).digest('hex');
    ok(`postbomb ${name}: published file SHA-256 matches`, got === sha, got);
    const rows = buf.toString('utf8').trim().split('\n')
      .map(l => l.trim().split(/\s+/).map(Number)).sort((a, b) => b[0] - a[0]);
    const same = rows.length === PB[name].length
      && rows.every((r, i) => r.every((v, j) => v === PB[name][i][j]));
    ok(`postbomb ${name}: embedded data identical to the published file`, same, rows.length + ' rows');
    netRun += 2;
  }
  if (!reached) console.log('  --  no source reachable: this run verified the mathematics only.');
}

/* ------------------------------------------------------------- 3. shared maths */

const ML = 5568 / Math.LN2;
const ML_R = 8033;
const ML5730 = 5730 / Math.LN2;

section('the conventions');
eq('conventional mean life 5568/ln 2', Math.round(ML * 1000) / 1000, 8032.926, 1e-9);
eq('rounds to the 8033 the 1977 convention fixes', Math.round(ML), 8033);
eq('5730/5568 to six places', Number((ML5730 / ML).toFixed(6)), 1.029095, 1e-12);
eq('5730/ln 2', Number((ML5730).toFixed(2)), 8266.64, 1e-9);

function oneYear(name) {
  const C = CURVE[name], hi = C.cal[C.n - 1];
  const mu = new Float64Array(hi + 1), sg = new Float64Array(hi + 1);
  let j = 0;
  for (let t = 0; t <= hi; t++) {
    while (j < C.n - 2 && C.cal[j + 1] < t) j++;
    const a = C.cal[j], b = C.cal[j + 1], f = (b === a) ? 0 : (t - a) / (b - a);
    mu[t] = C.mu[j] + f * (C.mu[j + 1] - C.mu[j]);
    sg[t] = C.sg[j] + f * (C.sg[j + 1] - C.sg[j]);
  }
  return { mu, sg, n: hi + 1, hi };
}
const IC = oneYear('intcal20');

function calibrate(cv, A, s, mass) {
  const n = cv.n, s2 = s * s;
  let lo = -1, hi = -1;
  for (let i = 0; i < n; i++) {
    const v = s2 + cv.sg[i] * cv.sg[i], d = A - cv.mu[i];
    if (d * d < 36 * v) { if (lo < 0) lo = i; hi = i; }
  }
  if (lo < 0) throw new Error('no support for A=' + A);
  const m = hi - lo + 1, p = new Float64Array(m);
  let tot = 0;
  for (let i = 0; i < m; i++) {
    const v = s2 + cv.sg[lo + i] * cv.sg[lo + i], d = A - cv.mu[lo + i];
    p[i] = Math.exp(-d * d / (2 * v)) / Math.sqrt(v); tot += p[i];
  }
  for (let i = 0; i < m; i++) p[i] /= tot;
  const ord = [...p.keys()].sort((x, y) => p[y] - p[x]);
  const sel = new Uint8Array(m);
  let acc = 0;
  for (const i of ord) { sel[i] = 1; acc += p[i]; if (acc >= mass) break; }
  const iv = []; let st = -1;
  for (let i = 0; i < m; i++) {
    if (sel[i] && st < 0) st = i;
    else if (!sel[i] && st >= 0) { iv.push([lo + i - 1, lo + st]); st = -1; }
  }
  if (st >= 0) iv.push([lo + m - 1, lo + st]);
  iv.sort((a, b) => b[0] - a[0]);
  const years = iv.reduce((a, x) => a + x[0] - x[1] + 1, 0);
  const oldest = Math.max(...iv.map(x => x[0])), youngest = Math.min(...iv.map(x => x[1]));
  let cum = 0, med = lo;
  for (let i = 0; i < m; i++) { cum += p[i]; if (cum >= 0.5) { med = lo + i; break; } }
  return { iv, years, outer: oldest - youngest, oldest, youngest, median: med, lo, hi, p };
}
const bc = t => 1950 - t <= 0 ? `${1 - (1950 - t)} BC` : `AD ${1950 - t}`;

/* -------------------------------------------------------- 4. instrument 1 + 2 */

section('the calibrator and the precision bench');
const hook = calibrate(IC, 2450, 30, 0.954);
eq('2450 +/- 30 BP on IntCal20 gives four disjoint 95.4% intervals', hook.iv.length, 4);
eq('the four intervals, in cal BP', hook.iv, [[2702, 2631], [2617, 2579], [2574, 2559], [2542, 2361]]);
eq('the four intervals, as calendar years',
  hook.iv.map(x => `${bc(x[0])} to ${bc(x[1])}`),
  ['753 BC to 682 BC', '668 BC to 630 BC', '625 BC to 610 BC', '593 BC to 412 BC']);
eq('calendar years selected', hook.years, 309);
eq('outer span', hook.outer, 341);
const off2650 = calibrate(IC, 2650, 30, 0.954);
eq('2650 +/- 30 BP, 200 years older, gives two intervals not four', off2650.iv.length, 2);
eq('and only 87 calendar years are selected, against 309 on the plateau', off2650.years, 87);
eq('its outer span', off2650.outer, 116);

const SIGS = [40, 30, 20, 15, 10, 5, 2];
eq('sigma sweep at 2450 BP, outer spans', SIGS.map(s => calibrate(IC, 2450, s, 0.954).outer),
  [346, 341, 334, 331, 326, 321, 318]);
eq('sigma sweep at 2450 BP, total years selected', SIGS.map(s => calibrate(IC, 2450, s, 0.954).years),
  [329, 309, 272, 241, 202, 171, 159]);
eq('off-plateau control at 2250 BP, outer spans', SIGS.map(s => calibrate(IC, 2250, s, 0.954).outer),
  [196, 186, 180, 180, 176, 173, 155]);
const gainA = (346 - 318) / 346, gainB = (196 - 155) / 196;
ok('a twentyfold precision gain buys under 10% on the plateau and over 20% off it',
  gainA < 0.10 && gainB > 0.20, `${(gainA * 100).toFixed(1)}% vs ${(gainB * 100).toFixed(1)}%`);
const SIGS9 = [80, 60, 40, 30, 20, 15, 10, 5, 2];
eq('the page\u2019s nine-row sweep: outer spans at 2450 BP',
  SIGS9.map(s => calibrate(IC, 2450, s, 0.954).outer), [374, 353, 346, 341, 334, 331, 326, 321, 318]);
eq('and the interval count, which RISES as the laboratory improves',
  SIGS9.map(s => calibrate(IC, 2450, s, 0.954).iv.length), [1, 2, 3, 4, 5, 5, 4, 6, 5]);
ok('better precision fragments the answer instead of collapsing it',
  calibrate(IC, 2450, 80, 0.954).iv.length === 1 && calibrate(IC, 2450, 2, 0.954).iv.length >= 4,
  '1 interval at +/-80, 5 at +/-2');
let sSum = 0, sCnt = 0;
for (const [a, b] of hook.iv) for (let t = b; t <= a; t++) { sSum += IC.sg[t]; sCnt++; }
eq("the curve's own mean 1 sigma across that region", Number((sSum / sCnt).toFixed(1)), 12.6, 1e-9);

/* --------------------------------------------------------- 5. the raw curve */

section('the curve read raw');
eq('IntCal20 14C age at 811 BC (cal BP 2760)', IC.mu[2760], 2672);
eq('IntCal20 14C age at 731 BC (cal BP 2680)', IC.mu[2680], 2463);
eq('IntCal20 14C age at 411 BC (cal BP 2360)', IC.mu[2360], 2396);
eq('67 radiocarbon years across the 320 calendar years 731 BC to 411 BC',
  Math.abs(IC.mu[2680] - IC.mu[2360]), 67);
eq('209 radiocarbon years across the 80 calendar years 811 BC to 731 BC',
  Math.abs(IC.mu[2760] - IC.mu[2680]), 209);

/* ------------------------------------------------------ 6. the plateau atlas */

section('the plateau atlas');
function sweepA(D, sig) {
  const span = new Int32Array(D + 1), HW = 500, s2 = sig * sig;
  for (let t = 0; t <= D; t++) {
    const A = IC.mu[t], a = Math.max(0, t - HW), b = Math.min(D, t + HW), m = b - a + 1;
    const p = new Float64Array(m); let tot = 0;
    for (let i = 0; i < m; i++) {
      const v = s2 + IC.sg[a + i] * IC.sg[a + i], d = A - IC.mu[a + i];
      p[i] = Math.exp(-d * d / (2 * v)) / Math.sqrt(v); tot += p[i];
    }
    const ord = [...p.keys()].sort((x, y) => p[y] - p[x]);
    let acc = 0, mn = 1e9, mx = -1e9;
    for (const q of ord) { acc += p[q] / tot; if (q < mn) mn = q; if (q > mx) mx = q; if (acc >= 0.954) break; }
    span[t] = mx - mn;
  }
  return span;
}
function runsFrom(span, D, thr, minLen) {
  const runs = []; let st = -1;
  for (let i = 0; i <= D; i++) {
    const good = span[i] > thr;
    if (good && st < 0) st = i;
    else if (!good && st >= 0) { if (i - st >= minLen) runs.push([st, i - 1]); st = -1; }
  }
  if (st >= 0 && D - st >= minLen) runs.push([st, D]);
  return runs.map(([a, b]) => {
    let worst = 0;
    for (let t = a; t <= b; t++) if (span[t] > worst) worst = span[t];
    return { a, b, len: b - a, worst };
  }).sort((x, y) => y.len - x.len);
}
const spanA = sweepA(5000, 25);
const runsA = runsFrom(spanA, 5000, 150, 20);
eq('mode A at the page defaults finds 31 runs', runsA.length, 31);
eq('the longest run is cal BP 3905-4420', [runsA[0].a, runsA[0].b, runsA[0].len], [3905, 4420, 515]);
const hallIdx = runsA.findIndex(r => r.a <= 2650 && r.b >= 2550);
eq('the Hallstatt plateau ranks second by length, not first', hallIdx, 1);
eq('the Hallstatt run bounds and worst span',
  [runsA[hallIdx].a, runsA[hallIdx].b, runsA[hallIdx].worst], [2357, 2739, 341]);
const edgeIdx = runsA.findIndex(r => r.a === 0);
ok('the modern edge (cal BP 0 onward) is itself flagged, and is marked as a domain edge',
  edgeIdx >= 0 && runsA[edgeIdx].b === 315, edgeIdx >= 0 ? `cal BP 0-${runsA[edgeIdx].b}` : 'missing');
eq('raising the threshold to 250 changes the run list', runsFrom(spanA, 5000, 250, 20).length, 12);

function scanB(D, W, thr, minRun) {
  const n = D + 1, sl = new Float64Array(n);
  for (let i = 0; i < n; i++) {
    const a = Math.max(0, i - W), b = Math.min(n - 1, i + W), cnt = b - a + 1;
    let ybar = 0; for (let k = a; k <= b; k++) ybar += IC.mu[k]; ybar /= cnt;
    const dbar = (a + b) / 2 - i;
    let num = 0, den = 0;
    for (let k = a; k <= b; k++) { const dd = (k - i) - dbar; num += dd * (IC.mu[k] - ybar); den += dd * dd; }
    sl[i] = den ? num / den : 0;
  }
  const runs = []; let st = -1;
  for (let i = 0; i < n; i++) {
    const good = Math.abs(sl[i]) < thr;
    if (good && st < 0) st = i;
    else if (!good && st >= 0) { if (i - st >= minRun) runs.push([st, i - 1]); st = -1; }
  }
  if (st >= 0 && n - 1 - st >= minRun) runs.push([st, n - 1]);
  return runs.map(([a, b]) => ({ a, b, len: b - a, d14: Math.abs(IC.mu[b] - IC.mu[a]) })).sort((x, y) => y.len - x.len);
}
const b1 = scanB(5000, 100, 0.25, 80);
eq('mode B at the page defaults finds exactly one run', b1.length, 1);
eq('and it is the Hallstatt plateau', [b1[0].a, b1[0].b, b1[0].len, Math.round(b1[0].d14)], [2551, 2644, 93, 45]);
const b2 = scanB(5000, 100, 0.5, 80);
ok('loosening the slope threshold to 0.5 moves the boundaries: the criterion is a choice',
  b2.length > 1 && b2[0].a !== b1[0].a, `${b2.length} runs, longest cal BP ${b2[0].a}-${b2[0].b}`);
const b3 = scanB(5000, 50, 0.25, 80);
ok('halving the window changes the list again', b3.length !== b1.length, `${b3.length} runs`);

section('the threshold-free band cross-check');
function bandCount(A, w, D) { let c = 0; for (let t = 0; t <= D; t++) if (Math.abs(IC.mu[t] - A) <= w) c++; return c; }
eq('calendar years within +/- 25 14C yr of 2500 BP, cal BP 0-14000', bandCount(2500, 25, 14000), 155);
eq('same for 4500 BP', bandCount(4500, 25, 14000), 198);
let bw = { n: -1, A: 0 }, bb = { n: 1e9, A: 0 };
for (let a = 500; a <= 11500; a += 10) {
  const c = bandCount(a, 25, 14000);
  if (c > bw.n) { bw = { n: c, A: a }; }
  if (c > 0 && c < bb.n) { bb = { n: c, A: a }; }
}
eq('worst radiocarbon age in the scan, and its band count', [bw.A, bw.n], [10360, 289]);
eq('best radiocarbon age in the scan, and its band count', [bb.A, bb.n], [6510, 4]);
ok('this measure needs no threshold beyond the measurement width itself, and it agrees with mode A',
  bandCount(2500, 25, 14000) > 100 && runsA.some(r => r.a <= 2650 && r.b >= 2550),
  '155 yr at 2500 BP, and the same region is flagged by the sweep');

/* ------------------------------------------------- 7. the half-life ledger */

section('the half-life ledger');
const ratio = ML5730 / ML;
eq('a 10,000 BP conventional age on the 5730 half-life', Math.round(10000 * ratio), 10291);
const h1 = calibrate(IC, 10000, 30, 0.954);
const mu2 = new Float64Array(IC.n), sg2 = new Float64Array(IC.n);
for (let i = 0; i < IC.n; i++) { mu2[i] = IC.mu[i] * ratio; sg2[i] = IC.sg[i] * ratio; }
const h2 = calibrate({ mu: mu2, sg: sg2, n: IC.n }, 10000 * ratio, 30 * ratio, 0.954);
eq('calibrating on either convention gives the identical interval set', h2.iv, h1.iv);
eq('so the calendar disagreement is exactly zero years',
  Math.max(Math.abs(h1.oldest - h2.oldest), Math.abs(h1.youngest - h2.youngest)), 0);
eq('the outer bounds of that calibration', `${bc(h1.oldest)} to ${bc(h1.youngest)}`, '9740 BC to 9334 BC');
eq('propagating Godwin 1962 stated +/- 40 yr on the half-life alone',
  Math.round(10000 * ratio * 40 / 5730), 72);

/* ------------------------------------------------- 8. the mixing bench */

section('the mixing bench');
const mixAge = (T, c, Fc) => -ML_R * Math.log((1 - c) * (T === Infinity ? 0 : Math.exp(-T / ML_R)) + c * Fc);
eq('1% modern carbon in an infinitely old sample', Math.round(mixAge(Infinity, 0.01, 1)), 36993);
eq('0.1% modern carbon in an infinitely old sample', Math.round(mixAge(Infinity, 0.001, 1)), 55490);
eq('0.5% modern carbon in an infinitely old sample', Math.round(mixAge(Infinity, 0.005, 1)), 42561);
eq('5% modern carbon in an infinitely old sample', Math.round(mixAge(Infinity, 0.05, 1)), 24065);
eq('1% modern carbon in a genuinely 1000 BP sample', Math.round(mixAge(1000, 0.01, 1)), 989);
eq('dead-carbon offset per 1%, to two places', Number((-ML_R * Math.log(0.99)).toFixed(2)), 80.73, 1e-9);
const deadOffsets = [500, 1000, 2000, 5000, 10000].map(T => Math.round((mixAge(T, 0.01, 0) - T) * 100) / 100);
ok('the dead-carbon offset is the same at every true age', new Set(deadOffsets).size === 1, deadOffsets.join(', '));
eq('modern carbon that must be excluded to certify a 50,000 BP ceiling',
  Number((Math.exp(-50000 / ML_R) * 100).toFixed(3)), 0.198, 1e-9);

/* ------------------------------------------------- 9. the reservoir desk */

section('the reservoir desk');
const MA = oneYear('marine20'), SHc = oneYear('shcal20');
const R = t => Math.round(MA.mu[t] - IC.mu[t]);
const SHo = t => Math.round(SHc.mu[t] - IC.mu[t]);
eq('R(t) at the eleven checkpoints',
  [0, 200, 500, 1000, 2000, 5000, 10000, 20000, 30000, 40000, 50000].map(R),
  [404, 554, 632, 495, 454, 473, 468, 738, 982, 991, 576]);
eq('SHCal20 minus IntCal20 at seven checkpoints',
  [0, 100, 500, 1000, 2000, 3000, 5000, 10000].map(SHo), [-25, 27, 53, 62, 1, 36, 36, 34]);
let hs = 0, hc = 0; for (let t = 500; t <= 11700; t++) { hs += MA.mu[t] - IC.mu[t]; hc++; }
let gs = 0, gc = 0; for (let t = 20000; t <= 40000; t++) { gs += MA.mu[t] - IC.mu[t]; gc++; }
eq('Holocene mean R, cal BP 500 to 11700', Math.round(hs / hc), 499);
eq('glacial mean R, cal BP 20000 to 40000', Math.round(gs / gc), 820);
ok('R roughly doubles into the glacial', (gs / gc) / (hs / hc) > 1.5, ((gs / gc) / (hs / hc)).toFixed(2) + 'x');

/* ------------------------------------------------- 10. the spike finder */

section('the spike finder');
const steps = [];
for (let t = 5000; t >= 1; t--) steps.push({ t, d: IC.mu[t - 1] - IC.mu[t] });
steps.sort((a, b) => a.d - b.d);
eq('the steepest single-year fall in the whole annual record is AD 774 to AD 775',
  [steps[0].t, Math.round(steps[0].d)], [1176, -35]);
const top8 = steps.slice(0, 8).map(s => 1950 - s.t);
eq('five of the eight steepest falls lie in AD 770-780',
  top8.filter(y => y >= 770 && y <= 780).length, 5);
eq('three of the eight steepest falls lie in AD 990-1000',
  top8.filter(y => y >= 990 && y <= 1000).length, 3);
eq('total fall across AD 772 to AD 778', Math.round(IC.mu[1178] - IC.mu[1172]), 126);
eq('as a fraction, in parts per thousand',
  Number(((Math.exp((IC.mu[1178] - IC.mu[1172]) / ML_R) - 1) * 1000).toFixed(1)), 15.8, 1e-9);
eq('total fall across AD 991 to AD 998', Math.round(IC.mu[959] - IC.mu[952]), 58);

/* --------------------------------------------- 11. the wiggle-match bench */

section('the wiggle-match bench');
function mulberry32(a) {
  return function () {
    a |= 0; a = a + 0x6D2B79F5 | 0;
    let t = Math.imul(a ^ a >>> 15, 1 | a);
    t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t;
    return ((t ^ t >>> 14) >>> 0) / 4294967296;
  };
}
function randn(rng) { const u = 1 - rng(), v = rng(); return Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v); }
function wiggle(t0, N, gap, s, nz, seed) {
  const rng = mulberry32(seed), A = [], off = [];
  for (let i = 0; i < N; i++) { const tt = Math.max(0, t0 - i * gap); off.push(i * gap); A.push(IC.mu[tt] + nz * s * randn(rng)); }
  const lo = Math.max(0, t0 - 900), hi = Math.min(IC.n - 1, t0 + 900), m = hi - lo + 1;
  const lg = new Float64Array(m); let best = -Infinity;
  for (let i = 0; i < m; i++) {
    const t = lo + i; let L = 0, good = true;
    for (let k = 0; k < N; k++) {
      const tk = t - off[k];
      if (tk < 0 || tk > IC.n - 1) { good = false; break; }
      const v = s * s + IC.sg[tk] * IC.sg[tk], d = A[k] - IC.mu[tk];
      L += -0.5 * Math.log(v) - d * d / (2 * v);
    }
    lg[i] = good ? L : -Infinity;
    if (lg[i] > best) best = lg[i];
  }
  const p = new Float64Array(m); let tot = 0;
  for (let i = 0; i < m; i++) { p[i] = Number.isFinite(lg[i]) ? Math.exp(lg[i] - best) : 0; tot += p[i]; }
  for (let i = 0; i < m; i++) p[i] /= tot;
  const ord = [...p.keys()].sort((x, y) => p[y] - p[x]);
  const sel = new Uint8Array(m); let acc = 0;
  for (const i of ord) { sel[i] = 1; acc += p[i]; if (acc >= 0.954) break; }
  let oldest = -Infinity, youngest = Infinity, hit = false;
  for (let i = 0; i < m; i++) if (sel[i]) { const y = lo + i; if (y > oldest) oldest = y; if (y < youngest) youngest = y; if (y === t0) hit = true; }
  return { span: oldest - youngest, hit, single: calibrate(IC, A[0], s, 0.954) };
}
const wm = wiggle(2649, 12, 20, 25, 1.0, 20260724);
eq('the first simulated date alone, 95.4% outer span', wm.single.outer, 284);
eq('twelve samples of known spacing, jointly', wm.span, 63);
ok('the joint region contains the calendar year the samples were drawn from', wm.hit, String(wm.hit));
ok('the sequence beats the single date by more than 4x', wm.single.outer / wm.span > 4,
  (wm.single.outer / wm.span).toFixed(1) + 'x');

/* ------------------------------------------------ 12. the revision bench */

section('the revision bench');
const IC13 = oneYear('intcal13');
let dmax = 0, dat = 0;
for (let t = 0; t <= 12000; t++) { const d = Math.abs(IC.mu[t] - IC13.mu[t]); if (d > dmax) { dmax = d; dat = t; } }
eq('largest IntCal20 minus IntCal13 difference over cal BP 0-12000', Math.round(dmax), 89);
eq('and where it falls', dat, 11950);
const r20 = calibrate(IC, 3350, 25, 0.954), r13 = calibrate(IC13, 3350, 25, 0.954);
eq('recalibrating 3350 +/- 25 BP moves the median by', r20.median - r13.median, -20);

/* ------------------------------------------------------- 13. the Thera bench */

section('the Thera bench');
const ANCHOR = 1613 + 1949;
const slope = (IC.mu[ANCHOR + 20] - IC.mu[ANCHOR - 20]) / 40;
eq('IntCal20 local slope around 1613 BC, 14C yr per calendar yr', Number(slope.toFixed(2)), 1.80, 1e-9);
eq('the largest measured regional offset (22 14C yr) buys, in calendar years',
  Number((22 / slope).toFixed(1)), 12.2, 1e-9);
const RC_YOUNG = 1600 + 1949, ARCH_OLD = 1550 + 1949;
eq('gap from the published radiocarbon range to the archaeological range, unshifted',
  RC_YOUNG - ARCH_OLD, 50);
eq('offset alone that would close that gap, at first order',
  Math.round((RC_YOUNG - ARCH_OLD) * slope), 90);
ok('so the measured offset does not close the gap on its own', 22 / slope < 50, '12.2 yr against a 50 yr gap');
const thSingle = calibrate(IC, IC.mu[ANCHOR], 15, 0.954);
eq('one synthetic on-curve date at 1613 BC, +/- 15, calibrates to',
  `${bc(thSingle.oldest)} to ${bc(thSingle.youngest)}`, '1622 BC to 1536 BC');
ok('which is far wider than the published wiggle-matched 27-year range', thSingle.outer > 60,
  thSingle.outer + ' yr');

/* -------------------------------------------- 14. the bomb clock and Suess dial */

section('the bomb clock and the Suess dial');
function pbSeries(z) {
  return PB[z].map(r => ({ y: 1950 - r[0], F: Math.exp(-r[1] / ML), age: r[1] })).sort((a, b) => a.y - b.y);
}
const nh1 = pbSeries('NH1');
const peak = nh1.reduce((a, r) => r.F > a.F ? r : a, nh1[0]);
eq('NH zone 1 annual-mean maximum F14C', Number(peak.F.toFixed(4)), 1.8993, 1e-9);
eq('and the year it falls in', peak.y, 1964.5);
for (const [z, want, yr] of [['NH2', 1.7871, 1964.5], ['NH3', 1.7092, 1965.5], ['SH12', 1.6282, 1966], ['SH3', 1.6701, 1965]]) {
  const s = pbSeries(z), p = s.reduce((a, r) => r.F > a.F ? r : a, s[0]);
  eq(`${z} annual-mean peak F and year`, [Number(p.F.toFixed(4)), p.y], [want, yr]);
}
eq('NH1 decline, F14C at 1970.5 / 1980.5 / 1990.5 / 2000.5 / 2010.5 / 2019.5',
  [1970.5, 1980.5, 1990.5, 2000.5, 2010.5, 2019.5].map(y => Number(nh1.find(r => r.y === y).F.toFixed(4))),
  [1.5267, 1.2787, 1.1566, 1.0927, 1.0477, 1.0085]);
const roots = [];
for (let i = 0; i < nh1.length - 1; i++) {
  const a = nh1[i].F, b = nh1[i + 1].F;
  if ((a - 1.3) * (b - 1.3) <= 0 && a !== b) roots.push(Number((nh1[i].y + (1.3 - a) / (b - a) * (nh1[i + 1].y - nh1[i].y)).toFixed(1)));
}
eq('F14C = 1.300 in NH zone 1 has two roots, on the rise limb and the fall limb', roots, [1962.0, 1979.4]);
const col = nh1.find(r => r.y === 1950.5);
ok('the 1950 post-bomb row cross-validates against IntCal20 cal BP 0 to within 15 14C yr',
  Math.abs(col.age - CURVE.intcal20.mu[0]) <= 15, `${col.age} BP vs ${CURVE.intcal20.mu[0]} BP`);
const slopeAt = (s, y) => {
  for (let i = 0; i < s.length - 1; i++) if (y >= s[i].y && y <= s[i + 1].y) return (s[i + 1].F - s[i].F) / (s[i + 1].y - s[i].y);
  return (s[s.length - 1].F - s[s.length - 2].F) / (s[s.length - 1].y - s[s.length - 2].y);
};
const res66 = 0.003 / Math.abs(slopeAt(nh1, 1966)), res19 = 0.003 / Math.abs(slopeAt(nh1, 2019));
eq('dating resolution at sigma_F = 0.003, in 1966', Number(res66.toFixed(2)), 0.04, 1e-9);
eq('and in 2019', Number(res19.toFixed(2)), 0.77, 1e-9);
ok('the bomb clock loses more than an order of magnitude of resolution', res19 / res66 > 10,
  (res19 / res66).toFixed(1) + 'x worse');

eq('Suess dial at the published -250 per mil endpoint', Math.round(-ML_R * Math.log(0.75)), 2311);
const su = calibrate(IC, 2311, 25, 0.954);
eq('and what that calibrates to', `${bc(su.oldest)} to ${bc(su.youngest)}`, '408 BC to 234 BC');
eq('Suess dial at the ambitious-reduction endpoint of 0 per mil', Math.round(-ML_R * Math.log(1.0)), 0);
eq("Graven's AD 1050 comparison: IntCal20's own 14C age at AD 1050", Math.round(IC.mu[900]), 936);
eq('which is F14C 0.890, so an atmosphere near -110 per mil would match it',
  Number((Math.exp(-IC.mu[900] / ML_R) * 1000).toFixed(0)) / 1000, 0.890, 1e-9);

/* -------------------------------------------------- 15. quoted determinations */

section('published determinations quoted in the substrate ledger');
const quotes = [
  ['Vinland parchment, 1 sigma calibrated', 'AD 1434 &plusmn; 11', /AD 1434 ± 11/],
  ['Vinland parchment, 95% range', 'AD 1411-1468', /AD 1411-1468/],
  ['Shroud lab means', '646, 750, 676 BP', /646 ± 31, 750 ± 30, 676 ± 24 BP/],
  ['Shroud unweighted mean and chi-squared', '691 +/- 31 BP, 6.4 on 2 df', /unweighted mean 691 ± 31 BP; chi-squared 6\.4 on 2 df/],
  ['Shroud published calibrated range', 'AD 1260-1390', /AD 1260-1390 at 95% confidence/],
  ['Otzi preset in the calibrator', '4550 +/- 27 BP', /4550 &plusmn; 27 BP/],
  ['Stuiver and Polach verbatim', '5568 yr half-life (mean life 8033 y)', /the use of the 5568 yr half-life \(mean life\s*\n?\s*8033 y\)/],
  ['Graven verbatim, -250 per mil', 'business-as-usual endpoint', /reduce\s*\n?\s*&Delta;<sup>14<\/sup>C<sub>?O?<\/?sub>?2? to -250 per mil|-250 per mil, equivalent to the depletion expected from over\s*\n?\s*2,000 y/],
  ['Manning et al. 2020 measured offset range', '0 to 22 14C yr', /0 to 22 radiocarbon years/],
  ['the novelty wording is the required one', 'could not find', /We could not\s*\n?\s*find a published ranked atlas of IntCal20 plateaus as of 2026-07-24/],
  ['the 609 vs 610 BC convention difference is stated, not buried', '609 BC vs 610 BC',
    /younger bound is reported by a continuous-boundary engine as 609 BC and by this page as 610 BC/],
  ['the independent re-derivation is named', 'CALIB REV8.2', /ran CALIB REV8\.2 itself on IntCal20/],
  ['the Shroud entry refuses to adjudicate', 'no position', /takes no position on the Shroud of Turin/],
  ['Thera is not adjudicated', 'no standing', /no standing\s*\n?\s*to adjudicate between the camps/],
  ['the forgery bench’s hand-chosen tolerance is named in the check panel', '120-year window',
    /calls a substrate consistent with a claim when the radiocarbon ages IntCal20 predicts for the\s*\n?\s*two calendar years differ by less than 120 radiocarbon years/],
  ['the "nothing is tuned" claim now excepts that tolerance', 'slider defaults, plot ranges, and the 120-year window',
    /slider defaults, plot ranges, and the 120-year window named directly\s*\n?\s*above/],
  ['the IntCal13 author list is sourced to Crossref, and the file header is described correctly',
    'abridged 28-name list', /abridged 28-name list that omits Hoffmann DL and Staff RA/]
];
for (const [name, detail, re] of quotes) ok('page carries: ' + name, re.test(html), detail);
ok('the page never says "we discovered"', !/we discovered/i.test(html), 'absent');

/* ------------------------------------------- 16. the page's claims about itself */

section('what the page says about its own machinery');
ok('the page does not claim the embedded data is byte-identical to the published files',
  !/byte-(identical|equivalent|level)/i.test(html),
  (html.match(/byte-\w+/i) || ['no such claim'])[0]);
const totalRows = ['intcal20', 'shcal20', 'marine20', 'intcal13'].reduce((a, k) => a + CURVE[k].n, 0);
eq('rows compared against the published files, all four curves', totalRows, 29644);
ok('and the check panel states exactly that number', html.includes('29,644 rows'),
  (html.match(/[\d,]+ rows of the four curves/) || ['absent'])[0]);
const pageSigs = (html.match(/var SIGS = \[([^\]]+)\]/) || [, ''])[1].split(',').map(Number);
eq('the precision bench sweeps the same nine precisions this verifier does', pageSigs, SIGS9);
ok('and its subtitle row count is written from SIGS.length at runtime, not typed twice',
  /id="pb-n"/.test(html) && /\$\('pb-n'\)\.textContent = NUMWORD\[SIGS\.length\]/.test(html)
  && !/seven full calibrations/.test(html), 'subtitle is computed');
ok('the bomb-peak preset is read off the loaded NH1 series rather than hard-coded',
  !/data-su="\d{3}"/.test(html) && /\$\('su-peak'\)\.setAttribute\('data-su'/.test(html),
  'preset is computed');
const mxDiv = /\$\('mx-frac'\)\.value \/ 10000/.test(html), mxMax = /id="mx-frac" type="range" min="0" max="200"/.test(html);
ok('the check panel states how many checks the network carries, and it is right',
  html.includes('<strong>' + NET_EXPECTED + ' fewer without one</strong>'),
  NET_EXPECTED + ' provenance checks need the network');
ok('the mixing slider hint matches the code: hundredths of a percent, up to 2.0%',
  mxDiv && mxMax && /Slider is in hundredths of a percent: 100 means 1\.0%/.test(html),
  'divisor 10000, max 200 -> 0 to 2.0%');
const dois = ['10.1017/RDC.2020.41', '10.1017/RDC.2020.68', '10.1017/RDC.2020.59', '10.1017/S0033822200003672',
  '10.1038/195984a0', '10.1017/RDC.2021.95', '10.1073/pnas.1504467112', '10.1038/nature11123',
  '10.1038/ncomms2783', '10.1017/RDC.2017.90', '10.1017/RDC.2024.44', '10.1126/sciadv.aar8241',
  '10.1038/s41598-020-69287-2', '10.1126/science.1125087', '10.1017/S0033822200040534',
  '10.1017/S0033822200064651', '10.1038/337611a0', '10.1111/arcm.12467', '10.2458/azu_js_rc.55.16947'];
for (const d of dois) ok('DOI present and correctly formed: ' + d, html.includes('doi:' + d), d);
/* Self-referential, and deliberately network-independent: the page states the total for a
   full-network run, so any provenance check skipped for want of a network is added back
   rather than counted as a discrepancy. With every source reachable, netMissing is 0. */
const netMissing = NET_EXPECTED - netRun;
ok('the page states this verifier\u2019s full-network check count, and it is right',
  html.includes('<strong>' + (checks + 1 + netMissing) + ' checks</strong>'),
  'page claims ' + (html.match(/<strong>(\d+) checks<\/strong>/) || [, '?'])[1] + ', this run made ' +
  (checks + 1) + (netMissing ? ' plus ' + netMissing + ' provenance checks skipped for want of a network'
    : ', with every source reached'));

/* ---------------------------------------------------------------- summary */

console.log('\n' + '-'.repeat(72));
console.log(`${checks} checks run, ${checks - failures} passed, ${failures} failed.`);
if (failures) { console.error('VERIFICATION FAILED'); process.exit(1); }
console.log('VERIFICATION PASSED');
