#!/usr/bin/env node
/**
 * verify-viazovska-magic.mjs
 *
 * Re-derives every number that public/strata/viazovska-magic/index.html ships, and
 * asserts the page's shipped text matches. It imports NO constant from the page: it
 * reads the page only to find out what the page claims.
 *
 * Primary source for every formula below:
 *   Maryna S. Viazovska, "The sphere packing problem in dimension 8",
 *   Annals of Mathematics 185 (2017) 991-1015, doi:10.4007/annals.2017.185.3.7,
 *   arXiv:1603.04246 (v1 14 Mar 2016, v2 4 Apr 2017; 22 pages, 2 figures).
 * Equation labels in comments are the arXiv v2 LaTeX source's own labels.
 *
 * Why this is not tautological. Five of the checks can only pass if the whole chain
 * (Fourier coefficients, modular transformation rules, kernel assembly, transform
 * convention, scaling) is right:
 *
 *   A. The rebuilt q-series must reproduce the coefficients PRINTED in the paper for
 *      phi_-4, phi_-2, phi_0, h, psi_I and psi_S. Nothing here is copied from the page.
 *   B. The kernel assembled from phi_0(i/t) and psi_S(i/t) must equal the kernel
 *      assembled from phi_0(it), phi_-2(it), phi_-4(it) and psi_I(it). These use
 *      different modular forms at different points; they agree only if the
 *      transformation rule (eqn 30) and psi_I|_-2 S = psi_S are both right.
 *   C. Both must equal the six-term expansions A_0^(6), A_inf^(6), B_0^(6), B_inf^(6)
 *      TRANSCRIBED LITERALLY from the paper, to within the paper's own tail bound.
 *   D. The brute-force eight-dimensional radial Fourier transform of g must land on
 *      g-hat. The left side never touches the kernel B.
 *   E. The E8 density must come out of lattice enumeration and a Gram determinant,
 *      never out of pi^4/384.
 *
 * Run:  node research/viazovska-magic/verify-viazovska-magic.mjs
 */

'use strict';

import fs from 'node:fs';
import path from 'node:path';
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', 'viazovska-magic', 'index.html');

const PI = Math.PI;
const SQRT2 = Math.SQRT2;
const KMAX = 40;        // highest power k retained in e^(-pi k t); the paper uses 6
const NPAN = 800;       // Simpson panels on [0,1]
const TSPLIT = 4;

let passes = 0;
const failures = [];

function pass(name, detail) {
  passes += 1;
  console.log(`PASS ${String(passes).padStart(2, '0')}  ${name}${detail ? ': ' + detail : ''}`);
}
function assert(name, cond, detail) {
  if (cond) { pass(name, detail); return; }
  failures.push(`${name}: ${detail}`);
  console.error(`FAIL      ${name}: ${detail}`);
}
function close(name, actual, expected, tol, digits = 12) {
  const err = Math.abs(actual - expected);
  assert(name, Number.isFinite(actual) && err <= tol,
    `${Number(actual).toPrecision(digits)} vs ${Number(expected).toPrecision(digits)} (|diff| ${err.toExponential(2)}, tol ${tol.toExponential(2)})`);
}

/* ══════════════════════ 1. exact modular q-series ══════════════════════ */

function conv(a, b, N) {
  const o = new Array(N + 1).fill(0n);
  for (let i = 0; i < a.length && i <= N; i++) {
    if (a[i] === 0n) continue;
    for (let j = 0; j < b.length && i + j <= N; j++) o[i + j] += a[i] * b[j];
  }
  return o;
}
function addS(a, b, N, s = 1n) {
  const o = new Array(N + 1).fill(0n);
  for (let i = 0; i <= N; i++) o[i] = (a[i] || 0n) + s * (b[i] || 0n);
  return o;
}
const scal = (a, s) => a.map((x) => x * s);
function invUnit(a, N) {
  if (a[0] !== 1n) throw new Error('inverse of a non-unit series');
  const o = new Array(N + 1).fill(0n);
  o[0] = 1n;
  for (let n = 1; n <= N; n++) {
    let s = 0n;
    for (let k = 1; k <= n; k++) s += (a[k] || 0n) * o[n - k];
    o[n] = -s;
  }
  return o;
}
function sigmaB(n, p) {
  let s = 0n;
  for (let d = 1; d <= n; d++) if (n % d === 0) s += BigInt(d) ** BigInt(p);
  return s;
}

/* Viazovska eqns 20-22 (E_k Fourier expansions), 26-28 (phi definitions). */
function buildPhi(N) {
  const M = N + 2;
  const E2 = new Array(M + 1).fill(0n), E4 = new Array(M + 1).fill(0n), E6 = new Array(M + 1).fill(0n);
  E2[0] = 1n; E4[0] = 1n; E6[0] = 1n;
  for (let n = 1; n <= M; n++) {
    E2[n] = -24n * sigmaB(n, 1);
    E4[n] = 240n * sigmaB(n, 3);
    E6[n] = -504n * sigmaB(n, 5);
  }
  const E4sq = conv(E4, E4, M), E4cu = conv(E4sq, E4, M), E6sq = conv(E6, E6, M);
  const disc = addS(E4cu, E6sq, M, -1n);          // E4^3 - E6^2 = 1728 Delta
  const dq = new Array(M).fill(0n);
  for (let n = 0; n < M; n++) {
    const c = disc[n + 1];
    if (c % 1728n !== 0n) throw new Error('E4^3 - E6^2 is not 1728 * (an integral series)');
    dq[n] = c / 1728n;                            // Delta / q
  }
  const inv = invUnit(dq, M - 1);
  const vm4 = conv(E4sq, inv, N + 1);                                   // varphi_-4 inner
  const vm2 = scal(conv(conv(E4, E6, N + 1), inv, N + 1), -1n);         // varphi_-2 inner
  const jIn = conv(E4cu, inv, N + 1);                                   // j inner
  const E2sq = conv(E2, E2, N + 1);
  const phiM4 = vm4;
  const phiM2 = addS(conv(vm4, E2, N + 1), vm2, N + 1);
  let phi0 = conv(vm4, E2sq, N + 1);
  phi0 = addS(phi0, scal(conv(vm2, E2, N + 1), 2n), N + 1);
  phi0 = addS(phi0, jIn, N + 1);
  phi0[1] -= 1728n;
  return { phiM4, phiM2, phi0, jIn };             // index i -> coefficient of q^(i-1)
}

/* Viazovska eqns 33 (h) and 37 (psi_I), in y = q^(1/8). */
function buildPsi(N) {
  const D = 8 * N + 16;
  const t00 = new Array(D + 1).fill(0n), t01 = new Array(D + 1).fill(0n), t10 = new Array(D + 1).fill(0n);
  t00[0] = 1n; t01[0] = 1n;
  for (let n = 1; 4 * n * n <= D; n++) { t00[4 * n * n] += 2n; t01[4 * n * n] += (n % 2 === 0 ? 2n : -2n); }
  for (let n = 0; (2 * n + 1) ** 2 <= D; n++) t10[(2 * n + 1) ** 2] += 2n;
  const pw = (b, p) => { let o = new Array(D + 1).fill(0n); o[0] = 1n; for (let i = 0; i < p; i++) o = conv(o, b, D); return o; };
  const t00_4 = pw(t00, 4), t01_4 = pw(t01, 4), t10_4 = pw(t10, 4);
  const t00_8 = conv(t00_4, t00_4, D), t10_8 = conv(t10_4, t10_4, D);
  function div(num, den, shift, N2) {
    const lead = den[shift];
    if (lead === 0n) throw new Error('bad leading coefficient in theta quotient');
    const o = new Array(N2 + 1).fill(0n);
    for (let n = 0; n <= N2; n++) {
      let v = num[n] || 0n;
      for (let j = 1; j <= n; j++) v -= (den[shift + j] || 0n) * o[n - j];
      if (v % lead !== 0n) throw new Error('theta quotient did not divide exactly');
      o[n] = v / lead;
    }
    return o;
  }
  const h = div(scal(addS(t00_4, t01_4, D), 128n), t10_8, 8, D - 8);      // index i -> y^(i-8)
  const gg = div(scal(addS(t01_4, t10_4, D, -1n), 128n), t00_8, 0, D);    // index i -> y^i
  const psiI = new Array(D - 7).fill(0n);
  for (let i = 0; i < h.length && i < psiI.length; i++) psiI[i] += h[i];
  for (let i = 0; i + 8 < psiI.length && i < gg.length; i++) psiI[i + 8] += gg[i];
  const jac = addS(addS(t01_4, t10_4, D), t00_4, D, -1n);                 // Jacobi identity residual
  return { h, psiI, jacobi: jac };
}

const NQ = Math.ceil(KMAX / 2) + 2;
const PHI = buildPhi(NQ + 1);
const PSI = buildPsi(NQ + 1);
const cPhi0 = (n) => PHI.phi0[n + 1] ?? 0n;
const cPhi2 = (n) => PHI.phiM2[n + 1] ?? 0n;
const cPhi4 = (n) => PHI.phiM4[n + 1] ?? 0n;
const cPsiI = (h) => PSI.psiI[4 * h + 8] ?? 0n;      // h = 2n : coefficient of q^(h/2)
const cPsiS = (h) => (h % 2 === 0 ? 0n : 2n * cPsiI(h));

/* --- A. the published coefficients (Viazovska eqns 29a-c, the h expansion, 38-40) --- */
const anchors = [
  ['phi_-4 at q^-1..q^3', [-1, 0, 1, 2, 3].map(cPhi4), ['1', '504', '73764', '2695040', '54755730']],
  ['phi_-2 at q^0..q^4', [0, 1, 2, 3, 4].map(cPhi2), ['720', '203040', '9417600', '223473600', '3566782080']],
  ['phi_0 at q^1..q^4', [1, 2, 3, 4].map(cPhi0), ['518400', '31104000', '870912000', '15697152000']],
  ['h at q^-1..q^3', [0, 8, 16, 24, 32].map((i) => PSI.h[i]), ['1', '16', '-132', '640', '-2550']],
  ['psi_I at q^-1..q^2', [-2, 0, 1, 2, 3, 4].map(cPsiI), ['1', '144', '-5120', '70524', '-626688', '4265600']],
  ['psi_S at q^(1/2)..q^(7/2)', [1, 3, 5, 7].map(cPsiS), ['-10240', '-1253376', '-48328704', '-1059078144']]
];
for (const [name, got, want] of anchors) {
  assert(`published series: ${name}`, got.map(String).join(',') === want.join(','),
    got.map(String).join(', ') + (got.map(String).join(',') === want.join(',') ? '' : ' != ' + want.join(', ')));
}
assert('Jacobi identity theta_01^4 + theta_10^4 = theta_00^4',
  PSI.jacobi.every((x) => x === 0n), 'residual series is identically zero');
assert('j-invariant anchor q^1 coefficient',
  PHI.jIn[2] === 196884n, `c_j(1) = ${PHI.jIn[2]}`);

/* ══════════════════════ 2. the kernels A(t) and B(t) ══════════════════════ */
/* Viazovska section 5:  A = -t^2 phi_0(i/t) - (36/pi^2) psi_I(it)
                         B = -t^2 phi_0(i/t) + (36/pi^2) psi_I(it)
   large t:  = -t^2 phi_0(it) + (12/pi) t phi_-2(it) - (36/pi^2) phi_-4(it) -/+ (36/pi^2) psi_I(it)
   small t:  = -t^2 phi_0(i/t) +/- (36/pi^2) t^2 psi_S(i/t)                                */
const C36 = 36 / (PI * PI), C12 = 12 / PI;

function mkInf(sgn) {
  const a = new Float64Array(KMAX + 1), b = new Float64Array(KMAX + 1), c = new Float64Array(KMAX + 1);
  const e2 = -C36 * (Number(cPhi4(-1)) + sgn * Number(cPsiI(-2)));
  for (let k = 0; k <= KMAX; k++) {
    a[k] = -C36 * sgn * Number(cPsiI(k));
    if (k % 2 === 0) {
      const n = k / 2;
      a[k] += -C36 * Number(cPhi4(n));
      b[k] = C12 * Number(cPhi2(n));
      c[k] = -Number(cPhi0(n));
    }
  }
  return { e2, a, b, c };
}
function mkZero(sgn) {
  const d = new Float64Array(KMAX + 1);
  for (let k = 1; k <= KMAX; k++) d[k] = (k % 2 === 0) ? -Number(cPhi0(k / 2)) : sgn * C36 * Number(cPsiS(k));
  return d;
}
const Ainf = mkInf(1), Binf = mkInf(-1), A0 = mkZero(1), B0 = mkZero(-1);

const evalInf = (K, t) => {
  let s = K.e2 * Math.exp(2 * PI * t);
  for (let k = 0; k < K.a.length; k++) {
    const e = Math.exp(-PI * k * t);
    s += (K.a[k] + K.b[k] * t + K.c[k] * t * t) * e;
    if (k > 2 && e === 0) break;
  }
  return s;
};
const evalZero = (d, t) => {
  if (t <= 0) return 0;
  let s = 0;
  for (let k = 1; k < d.length; k++) { const e = Math.exp(-PI * k / t); if (e === 0) break; s += d[k] * e; }
  return t * t * s;
};
const kernelAt = (t, which) =>
  t <= 1 ? evalZero(which === 'A' ? A0 : B0, t) : evalInf(which === 'A' ? Ainf : Binf, t);

/* the paper's own remainder bounds, R_0^(m) and R_inf^(m), section 5 */
function tailSum(m, z) {   // sum_{k>=m} 2 e^{2 sqrt2 pi sqrt k} z^k
  if (z <= 0) return 0;
  let s = 0;
  for (let k = m; k < m + 500; k++) {
    const term = 2 * Math.exp(2 * SQRT2 * PI * Math.sqrt(k) + k * Math.log(z));
    s += term;
    if (term < 1e-320) break;
  }
  return s;
}
const R0 = (m, t) => (t * t + 36 / PI ** 2) * tailSum(m, Math.exp(-PI / t));
const Rinf = (m, t) => (t * t + 12 / PI * t + 36 / PI ** 2) * tailSum(m, Math.exp(-PI * t));

/* --- B. the two modular representations must agree where both converge --- */
{
  /* honest tolerance: the two truncations' own provable remainders, plus a
     double-precision roundoff allowance of 1e-13 relative to the value itself */
  let ok = true, note = '', best = Infinity, bestT = 0, pts = 0;
  for (let i = 0; i <= 80; i++) {
    const t = 0.45 + (2.6 - 0.45) * i / 80;
    for (const [z, inf] of [[A0, Ainf], [B0, Binf]]) {
      pts += 1;
      const u = evalZero(z, t), v = evalInf(inf, t);
      const bound = R0(KMAX + 1, t) + Rinf(KMAX + 1, t) + 1e-13 * Math.max(Math.abs(u), Math.abs(v));
      if (!(Math.abs(u - v) <= bound)) { ok = false; note = `exceeded at t = ${t.toFixed(3)}`; }
      const rel = Math.abs(u - v) / Math.max(Math.abs(v), 1e-300);
      if (t > 0.85 && t < 1.25 && rel < best) { best = rel; bestT = t; }
    }
  }
  assert('two independent modular representations of the kernel agree', ok,
    ok ? `${pts} sample points, every one inside its own truncation bound; best relative agreement ${best.toExponential(2)} at t = ${bestT.toFixed(3)}` : note);
}

/* --- C. the paper's own six-term expansions, transcribed literally --- */
function paperA0_6(t) {
  const e = (n) => Math.exp(-PI * n / t);
  return t * t * (-368640 / PI ** 2 * e(1) - 518400 * e(2) - 45121536 / PI ** 2 * e(3)
    - 31104000 * e(4) - 1739833344 / PI ** 2 * e(5));
}
function paperB0_6(t) {
  const e = (n) => Math.exp(-PI * n / t);
  return t * t * (368640 / PI ** 2 * e(1) - 518400 * e(2) + 45121536 / PI ** 2 * e(3)
    - 31104000 * e(4) + 1739833344 / PI ** 2 * e(5));
}
function paperAinf_6(t) {
  const e = (n) => Math.exp(-PI * n * t);
  return -72 / PI ** 2 * Math.exp(2 * PI * t) - 23328 / PI ** 2
    + 184320 / PI ** 2 * e(1) - 5194368 / PI ** 2 * e(2) + 22560768 / PI ** 2 * e(3)
    - 250583040 / PI ** 2 * e(4) + 869916672 / PI ** 2 * e(5)
    + t * (8640 / PI + 2436480 / PI * e(2) + 113011200 / PI * e(4))
    - t * t * (518400 * e(2) + 31104000 * e(4));
}
function paperBinf_6(t) {
  const e = (n) => Math.exp(-PI * n * t);
  return -12960 / PI ** 2 - 184320 / PI ** 2 * e(1) - 116640 / PI ** 2 * e(2)
    - 22560768 / PI ** 2 * e(3) + 56540160 / PI ** 2 * e(4) - 869916672 / PI ** 2 * e(5)
    + t * (8640 / PI + 2436480 / PI * e(2) + 113011200 / PI * e(4))
    - t * t * (518400 * e(2) + 31104000 * e(4));
}
{
  let ok = true, note = '';
  const round = (x) => 1e-14 * Math.abs(x);
  for (const t of [0.35, 0.5, 0.7, 0.85, 1.0]) {
    const r = R0(6, t);
    const dA = Math.abs(evalZero(A0, t) - paperA0_6(t)), dB = Math.abs(evalZero(B0, t) - paperB0_6(t));
    if (!(dA <= r + round(paperA0_6(t)) && dB <= r + round(paperB0_6(t)))) { ok = false; note = `small-t mismatch at t=${t}`; }
  }
  for (const t of [1.0, 1.3, 1.8, 2.5]) {
    const r = Rinf(6, t);
    const dA = Math.abs(evalInf(Ainf, t) - paperAinf_6(t)), dB = Math.abs(evalInf(Binf, t) - paperBinf_6(t));
    if (!(dA <= r + round(paperAinf_6(t)) && dB <= r + round(paperBinf_6(t)))) { ok = false; note = `large-t mismatch at t=${t}`; }
  }
  assert('rebuilt kernels agree with the paper\'s printed six-term expansions', ok,
    ok ? 'all nine sample points lie inside the paper\'s own R_0^(6) / R_inf^(6) bounds' : note);
}
/* the leading coefficients the paper states explicitly */
close('e^(2 pi t) coefficient of A = -72/pi^2', Ainf.e2, -72 / PI ** 2, 1e-12);
assert('e^(2 pi t) coefficient of B = 0', Binf.e2 === 0, `${Binf.e2}`);
close('constant term of A = -23328/pi^2', Ainf.a[0], -23328 / PI ** 2, 1e-9);
close('constant term of B = -12960/pi^2', Binf.a[0], -12960 / PI ** 2, 1e-9);
close('t-linear coefficient = 8640/pi (both kernels)', Ainf.b[0], 8640 / PI, 1e-9);
assert('the t-linear coefficient is (12/pi) c_{phi_-2}(0)', cPhi2(0) === 720n, `c_{phi_-2}(0) = ${cPhi2(0)}`);

/* ══════════════════════ 3. g and g-hat ══════════════════════ */
const sinc = (x) => (Math.abs(x) < 1e-8 ? 1 - x * x / 6 : Math.sin(x) / x);

function makeNodes(d, n) {
  const t = new Float64Array(n + 1), v = new Float64Array(n + 1), w = new Float64Array(n + 1);
  for (let i = 0; i <= n; i++) {
    t[i] = i / n; v[i] = evalZero(d, t[i]);
    w[i] = (i === 0 || i === n) ? 1 : (i % 2 ? 4 : 2);
  }
  return { t, v, w, n };
}
function transformAt(inf, nd, r) {
  const P = inf.e2, C = inf.a[0], L = inf.b[0];
  const r2 = r * r, s = r2 - 2, u = PI * r2 / 2, g2 = PI * r2;
  let low = 0;
  for (let i = 0; i <= nd.n; i++) low += nd.w[i] * nd.v[i] * Math.exp(-g2 * nd.t[i]);
  low /= 3 * nd.n;
  const b = PI * s;
  low -= P * (b === 0 ? 1 : -Math.expm1(-b) / b);
  low -= C * (g2 === 0 ? 1 : -Math.expm1(-g2) / g2);
  low -= L * (g2 < 1e-6 ? 0.5 - g2 / 3 + g2 * g2 / 8 : (1 - Math.exp(-g2) * (1 + g2)) / (g2 * g2));
  let high = 0;
  for (let k = 1; k < inf.a.length; k++) {
    const al = PI * (k + r2), e = Math.exp(-al);
    if (e === 0) break;
    high += inf.a[k] * e / al
      + inf.b[k] * e * (1 / al + 1 / al ** 2)
      + inf.c[k] * e * (1 / al + 2 / al ** 2 + 2 / al ** 3);
  }
  const J = low + high, sU = sinc(u) ** 2, sS = sinc(PI * s / 2) ** 2;
  return (PI / 2160) * (P * PI * s / 4 * sS + L / 4 * sU + C * PI * r2 / 4 * sU
    + PI * PI * r2 * r2 / 4 * sU * J);
}
const nA = makeNodes(A0, NPAN), nB = makeNodes(B0, NPAN);
const nAfine = makeNodes(A0, 4 * NPAN), nBfine = makeNodes(B0, 4 * NPAN);
const g = (r) => transformAt(Ainf, nA, r);
const ghat = (r) => transformAt(Binf, nB, r);

/* the quadrature is honest only if refining it does not move the answer.
   Two grids: the 41-point one the page sweeps on load (this is the number the page ships),
   and a 401-point one that is too expensive for the page but not for a script. */
function quadSweep(n) {
  let worst = 0;
  for (let i = 0; i <= n; i++) {
    const r = 4 * i / n;
    const gf = transformAt(Ainf, nAfine, r), hf = transformAt(Binf, nBfine, r);
    if (Math.abs(gf) > 1e-25) worst = Math.max(worst, Math.abs(g(r) - gf) / Math.abs(gf));
    if (Math.abs(hf) > 1e-25) worst = Math.max(worst, Math.abs(ghat(r) - hf) / Math.abs(hf));
  }
  return worst;
}
const quadWorst = quadSweep(40);       // r = 0, 0.1, ..., 4 : the grid the page ships
const quadWorst401 = quadSweep(400);   // r = 0, 0.01, ..., 4 : the stronger offline sweep
assert('Simpson quadrature has converged', quadWorst401 < 1e-9,
  `refining 800 -> 3200 panels moves the answer by at most ${quadWorst.toExponential(4)} relative on the page's 41-point grid and ${quadWorst401.toExponential(4)} on a 401-point grid, below every digit the page prints`);

/* normalisation and zero orders */
close('g(0) = 1', g(0), 1, 1e-14);
close('g-hat(0) = 1', ghat(0), 1, 1e-14);
/* the same Richardson-extrapolated difference quotient the page uses, coded here from
   scratch: the h^2 truncation term cancels, leaving the function's own roundoff */
const DERIV_H = 1e-4;
function deriv(f, x, h = DERIV_H) {
  const d1 = (f(x + h) - f(x - h)) / (2 * h), d2 = (f(x + 2 * h) - f(x - 2 * h)) / (4 * h);
  return (4 * d1 - d2) / 3;
}
const gpSqrt2 = deriv(g, SQRT2);
const ghpSqrt2 = deriv(ghat, SQRT2);
{
  close('g\'(sqrt2) = -sqrt2/60 (a SIMPLE zero), measured not assumed', gpSqrt2, -SQRT2 / 60, 1e-11);
  assert('g-hat\'(sqrt2) = 0 (a DOUBLE zero)', Math.abs(ghpSqrt2) < 1e-12,
    `measured ${ghpSqrt2.toExponential(2)}, against ${gpSqrt2.toExponential(2)} for g at the same radius: ${Math.round(Math.log10(Math.abs(gpSqrt2 / ghpSqrt2)))} orders of magnitude apart`);
  assert('g\'(2) = 0 (a DOUBLE zero at the second shell)', Math.abs(deriv(g, 2)) < 1e-12,
    `measured ${deriv(g, 2).toExponential(2)}`);
}
{
  let maxG = -Infinity, minH = Infinity;
  for (let i = 0; i <= 8000; i++) {
    const r = 5 * i / 8000;
    minH = Math.min(minH, ghat(r));
    if (r >= SQRT2) maxG = Math.max(maxG, g(r));
  }
  assert('sampled sign conditions hold on [0,5]', maxG < 1e-20 && minH > -1e-20,
    `max g on [sqrt2,5] = ${maxG.toExponential(2)}, min g-hat on [0,5] = ${minH.toExponential(2)}`);
  assert('the shell zeros are zero to roundoff, and only there',
    Math.abs(g(SQRT2)) < 1e-15 && Math.abs(g(2)) < 1e-15 && g(1.6) < -1e-6 && ghat(1.6) > 1e-6,
    `g(sqrt2) = ${g(SQRT2).toExponential(2)}, g(1.6) = ${g(1.6).toExponential(4)}, g-hat(1.6) = ${ghat(1.6).toExponential(4)}`);
}
/* The shell zeros do NOT all read the same size, and saying "about 1e-33" everywhere would be
   false at sqrt2. The double zeros are pure cancellation; the simple zero at sqrt2 amplifies
   the last bit of r^2 at first order, and the size of that is predictable exactly. */
const zeroDoubles = (() => {
  let w = 0;
  for (let k = 1; k <= 8; k++) {
    const r = Math.sqrt(2 * k);
    w = Math.max(w, Math.abs(ghat(r)));
    if (k >= 2) w = Math.max(w, Math.abs(g(r)));
  }
  return w;
})();
const zeroSimple = g(SQRT2);
const zeroPredicted = -Number.EPSILON / 60;
assert('every DOUBLE zero reads below 1e-32 absolute', zeroDoubles < 1e-32,
  `largest is ${zeroDoubles.toExponential(3)}`);
assert('the SIMPLE zero at sqrt2 does not, and reads -eps/60 instead',
  Math.abs(zeroSimple - zeroPredicted) <= Math.abs(zeroPredicted) * 1e-6 && Math.abs(zeroSimple) > 1e3 * zeroDoubles,
  `g(sqrt2) = ${zeroSimple.toExponential(10)} against -eps/60 = ${zeroPredicted.toExponential(10)}; Math.SQRT2**2 - 2 = ${(Math.SQRT2 * Math.SQRT2 - 2).toExponential(3)} = 2 eps, and the slope -sqrt2/60 turns that into -eps/60`);

/* --- D. the brute-force eight-dimensional radial Fourier transform --- */
function besselJ3(x) {
  const n = 2000;
  let s = 0;
  for (let i = 0; i <= n; i++) {
    const th = PI * i / n, w = (i === 0 || i === n) ? 1 : (i % 2 ? 4 : 2);
    s += w * Math.cos(3 * th - x * Math.sin(th));
  }
  return s / (3 * n);
}
function hankel8(f, s, RMAX, n) {
  let sum = 0;
  for (let i = 0; i <= n; i++) {
    const r = RMAX * i / n, w = (i === 0 || i === n) ? 1 : (i % 2 ? 4 : 2);
    sum += w * f(r) * besselJ3(2 * PI * r * s) * r ** 4;
  }
  return 2 * PI * (RMAX * sum / (3 * n)) / s ** 3;
}
{
  let worst = 0, worstS = 0;
  for (const s of [0.4, 0.75, 1.2]) {
    const num = hankel8(g, s, 5.5, 1200), ex = ghat(s);
    const rel = Math.abs(num - ex) / Math.abs(ex);
    if (rel > worst) { worst = rel; worstS = s; }
  }
  assert('brute-force 8-D Fourier transform of g lands on g-hat', worst < 1e-9,
    `worst relative difference ${worst.toExponential(2)} at s = ${worstS}; nothing on the left used the kernel B`);
}
/* the same machinery reproduces the closed-form transform of the comparison witness,
   which is what certifies the transform convention itself */
const gaussW = (r, a) => (1 - a * r * r) * Math.exp(-PI * r * r);
const gaussHatW = (s, a) => (1 - 4 * a / PI + a * s * s) * Math.exp(-PI * s * s);
{
  const a = PI / 5, s = 0.75;
  const num = hankel8((r) => gaussW(r, a), s, 4.5, 1200);
  close('Hankel convention check on (1 - a r^2)e^(-pi r^2)', num, gaussHatW(s, a), 1e-9, 10);
}

/* ══════════════════════ 4. the E8 lattice ══════════════════════ */
function bareiss(mat) {
  const a = mat.map((row) => row.map(BigInt));
  let sign = 1n, prev = 1n;
  for (let k = 0; k < a.length - 1; k++) {
    let p = k;
    while (p < a.length && a[p][k] === 0n) p++;
    if (p === a.length) return 0n;
    if (p !== k) { const t = a[p]; a[p] = a[k]; a[k] = t; sign = -sign; }
    const pv = a[k][k];
    for (let i = k + 1; i < a.length; i++)
      for (let j = k + 1; j < a.length; j++) a[i][j] = (a[i][j] * pv - a[i][k] * a[k][j]) / prev;
    prev = pv;
  }
  return sign * a[a.length - 1][a.length - 1];
}
const E8_GRAM = [
  [2, 0, -1, 0, 0, 0, 0, 0], [0, 2, 0, -1, 0, 0, 0, 0], [-1, 0, 2, -1, 0, 0, 0, 0],
  [0, -1, -1, 2, -1, 0, 0, 0], [0, 0, 0, -1, 2, -1, 0, 0], [0, 0, 0, 0, -1, 2, -1, 0],
  [0, 0, 0, 0, 0, -1, 2, -1], [0, 0, 0, 0, 0, 0, -1, 2]
];
function enumerateE8(maxN2) {
  const counts = new Map(), lim = 4 * maxN2;
  for (const odd of [false, true]) {
    const vals = [], mc = Math.floor(Math.sqrt(lim));
    for (let y = -mc; y <= mc; y++) if ((Math.abs(y) % 2 === 1) === odd) vals.push(y);
    (function visit(depth, ss, sc) {
      if (depth === 8) {
        if (sc % 4 !== 0) return;
        counts.set(ss / 4, (counts.get(ss / 4) || 0) + 1);
        return;
      }
      for (const y of vals) { const n = ss + y * y; if (n <= lim) visit(depth + 1, n, sc + y); }
    })(0, 0, 0);
  }
  return counts;
}
const sigma3 = (n) => { let s = 0; for (let d = 1; d <= n; d++) if (n % d === 0) s += d ** 3; return s; };

const E8counts = enumerateE8(8);
const E8det = Number(bareiss(E8_GRAM));
const E8norms = [...E8counts.keys()].filter((x) => x > 0).sort((a, b) => a - b);
const E8min2 = E8norms[0];
const V8 = PI ** 4 / 24;
const E8density = V8 * Math.pow(Math.sqrt(E8min2) / 2, 8) / Math.sqrt(E8det);

assert('E8 Gram determinant = 1 (exact integer elimination)', E8det === 1, `det = ${E8det}`);
assert('E8 minimum non-zero squared norm = 2', E8min2 === 2, `min = ${E8min2}`);
assert('E8 shell counts from enumeration = 240 sigma_3(k)',
  [1, 2, 3, 4].every((k) => E8counts.get(2 * k) === 240 * sigma3(k)),
  [1, 2, 3, 4].map((k) => E8counts.get(2 * k)).join(', '));
close('E8 lower density, from lattice data alone', E8density, PI ** 4 / 384, 2e-15);

/* the upper bound from the witness, by the Cohn-Elkies formula with the sqrt2 rescaling */
const magicUpper = Math.pow(2, 4) * (g(0) / ghat(0)) * V8 * Math.pow(0.5, 8);
close('Cohn-Elkies upper bound from the magic function', magicUpper, PI ** 4 / 384, 2e-15);
assert('the two bars are the same number', Math.abs(magicUpper - E8density) < 2e-15,
  `upper ${magicUpper.toFixed(15)} vs lower ${E8density.toFixed(15)}`);
assert('the paper\'s printed decimal', (PI ** 4 / 384).toFixed(5) === '0.25367',
  `pi^4/384 = ${(PI ** 4 / 384).toFixed(12)}`);

/* ══════════════════════ 5. the Poisson ledger ══════════════════════ */
function ledger(a, K = 14) {
  let sp = 1, fo = gaussHatW(0, a), th = 1, dth = 0;
  for (let k = 1; k <= K; k++) {
    const N = 240 * sigma3(k), r = Math.sqrt(2 * k), q = Math.exp(-2 * PI * k);
    sp += N * gaussW(r, a); fo += N * gaussHatW(r, a);
    th += N * q; dth += k * N * q;
  }
  return { sp, fo, th, dth, waste: fo - gaussHatW(0, a) };
}
{
  const L = ledger(0.5);
  assert('Poisson summation over E8 closes for the Gaussian witness',
    Math.abs(L.sp - L.fo) < 1e-15, `both sides = ${L.sp.toPrecision(16)} (difference ${(L.sp - L.fo).toExponential(2)})`);
  close('theta_{E8}(i) = E4(i)', L.th, 1.4557628922687086, 1e-12);
  close('D E4(i) = E4(i)/pi  (Ramanujan + E2(i) = 3/pi, E6(i) = 0)', L.dth, L.th / PI, 1e-15);
  /* E4(i) has a closed form; matching it certifies the shell counts independently */
  const GAMMA14 = 3.6256099082219083119;   // Gamma(1/4)
  close('E4(i) = 3 Gamma(1/4)^8 / (2 pi)^6', L.th, 3 * GAMMA14 ** 8 / (2 * PI) ** 6, 1e-12);
}

/* ══════════════════════ 6. the sign certificate ══════════════════════ */
function tailBound(K, zmax) {
  if (zmax <= 0) return 1e-300;
  let s = 0;
  for (let k = K + 1; k < K + 400; k++) {
    const term = 2 * Math.exp(2 * SQRT2 * PI * Math.sqrt(k) + k * Math.log(zmax));
    s += term;
    if (term < 1e-320) break;
  }
  return s * (1 + 1e-7) + 1e-300;
}
function certifySmall(d, want) {
  const XMAX = Math.exp(-PI);
  let leaves = 0, worst = Infinity;
  const Q = (x1, x2) => {
    let lo = 0, hi = 0;
    for (let k = 1; k <= KMAX; k++) {
      const p1 = d[k] * Math.pow(x1, k - 1), p2 = d[k] * Math.pow(x2, k - 1);
      lo += Math.min(p1, p2); hi += Math.max(p1, p2);
    }
    const tl = tailBound(KMAX, x2) / Math.max(x1 > 0 ? x1 : x2, 1e-300);
    const pd = (Math.abs(lo) + Math.abs(hi) + 1) * 64 * Number.EPSILON;
    return [lo - pd - tl, hi + pd + tl];
  };
  (function rec(x1, x2, depth) {
    const e = Q(x1, x2);
    if (want < 0 && e[1] < 0) { leaves++; worst = Math.min(worst, -e[1]); return; }
    if (want > 0 && e[0] > 0) { leaves++; worst = Math.min(worst, e[0]); return; }
    if (depth > 40) throw new Error('small-t sign certificate failed');
    const m = (x1 + x2) / 2; rec(x1, m, depth + 1); rec(m, x2, depth + 1);
  })(0, XMAX, 0);
  return { leaves, worst };
}
function certifyMid(inf, want) {
  let leaves = 0, worst = Infinity;
  const F = (t1, t2) => {
    let lo = Math.min(inf.e2 * Math.exp(2 * PI * t1), inf.e2 * Math.exp(2 * PI * t2));
    let hi = Math.max(inf.e2 * Math.exp(2 * PI * t1), inf.e2 * Math.exp(2 * PI * t2));
    for (let k = 0; k <= KMAX; k++) {
      const a = inf.a[k], b = inf.b[k], c = inf.c[k];
      if (a === 0 && b === 0 && c === 0) continue;
      const q = (t) => a + b * t + c * t * t;
      let qlo = Math.min(q(t1), q(t2)), qhi = Math.max(q(t1), q(t2));
      if (c !== 0) { const tv = -b / (2 * c); if (tv > t1 && tv < t2) { qlo = Math.min(qlo, q(tv)); qhi = Math.max(qhi, q(tv)); } }
      const e1 = Math.exp(-PI * k * t2), e2v = Math.exp(-PI * k * t1);
      const cands = [qlo * e1, qlo * e2v, qhi * e1, qhi * e2v];
      lo += Math.min(...cands); hi += Math.max(...cands);
    }
    const rad = (t2 * t2 + 12 * t2 / PI + 36 / PI ** 2) * tailBound(KMAX, Math.exp(-PI * t1));
    const pd = (Math.abs(lo) + Math.abs(hi) + 1) * 128 * Number.EPSILON;
    return [lo - pd - rad, hi + pd + rad];
  };
  (function rec(t1, t2, depth) {
    const e = F(t1, t2);
    if (want < 0 && e[1] < 0) { leaves++; worst = Math.min(worst, -e[1]); return; }
    if (want > 0 && e[0] > 0) { leaves++; worst = Math.min(worst, e[0]); return; }
    if (depth > 40) throw new Error('mid-t sign certificate failed');
    const m = (t1 + t2) / 2; rec(t1, m, depth + 1); rec(m, t2, depth + 1);
  })(1, TSPLIT, 0);
  return { leaves, worst };
}
function certifyTail(inf, want) {
  const T = TSPLIT, y = Math.exp(-PI * T);
  let S0 = 0, S1 = 0, S2 = 0;
  for (let k = 1; k <= KMAX; k++) {
    const p = Math.pow(y, k - 1);
    S0 += Math.abs(inf.a[k]) * p; S1 += Math.abs(inf.b[k]) * p; S2 += Math.abs(inf.c[k]) * p;
  }
  const tl = tailBound(KMAX, y) / y;
  const E = y * (S0 + S1 * T + S2 * T * T + tl * (1 + T + T * T));
  const lin = inf.b[0] * T + inf.a[0];
  if (want > 0) {
    if (!(lin - E > 0)) throw new Error('tail sign certificate failed (positive)');
    return { E, lin, margin: lin - E };
  }
  const dom = inf.e2 * Math.exp(2 * PI * T);
  if (!(-dom - (lin + E) > 0)) throw new Error('tail sign certificate failed (negative)');
  return { E, lin, dom, margin: -dom - (lin + E) };
}
const cAs = certifySmall(A0, -1), cBs = certifySmall(B0, 1);
const cAm = certifyMid(Ainf, -1), cBm = certifyMid(Binf, 1);
const cAt = certifyTail(Ainf, -1), cBt = certifyTail(Binf, 1);
assert('sign certificate on (0,1]: A < 0 and B > 0', cAs.worst > 0 && cBs.worst > 0,
  `A enclosure at most ${(-cAs.worst).toFixed(2)}, B enclosure at least ${cBs.worst.toFixed(2)}, no bisection needed`);
assert('sign certificate on [1,4]: A < 0 and B > 0', cAm.worst > 0 && cBm.worst > 0,
  `${cAm.leaves} + ${cBm.leaves} sub-intervals, worst margins ${(-cAm.worst).toFixed(4)} and ${cBm.worst.toFixed(4)}`);
assert('sign certificate on [4,inf): A < 0 and B > 0', cAt.margin > 0 && cBt.margin > 0,
  `tail bound ${cAt.E.toExponential(3)}; A dominant ${cAt.dom.toExponential(6)}, B surviving ${cBt.lin.toFixed(6)}`);

/* the certificate must be falsifiable: corrupting one Fourier coefficient must break it */
{
  const bad = { e2: Binf.e2, a: Float64Array.from(Binf.a), b: Float64Array.from(Binf.b), c: Float64Array.from(Binf.c) };
  bad.a[0] *= 4;      // pretend the constant term of B were -51840/pi^2 instead of -12960/pi^2
  let broke = false;
  try { certifyMid(bad, 1); } catch { broke = true; }
  assert('the certificate is falsifiable', broke,
    'multiplying one kernel coefficient by 4 makes the [1,4] certificate fail, as it must');
}

/* ══════════════════════ 7. the paper record ══════════════════════ */
const V1_D8 = Date.UTC(2016, 2, 14, 13, 0, 35);     // arXiv:1603.04246v1 submission stamp
const V1_D24 = Date.UTC(2016, 2, 21, 17, 57, 5);    // arXiv:1603.06518v1 submission stamp
const gapDays = Math.floor((V1_D24 - V1_D8) / 86400000);
assert('dimension-24 preprint follows dimension-8 by 7 days', gapDays === 7,
  `${((V1_D24 - V1_D8) / 86400000).toFixed(6)} elapsed days, floor ${gapDays}`);
assert('journal pagination 991-1015 is 25 pages inclusive', 1015 - 991 + 1 === 25, '25');

/* ══════════════════════ 8. THE COUPLING: read the page and compare ══════════════════════ */

const html = fs.readFileSync(PAGE, 'utf8');

/* the page must not have lost its closing tags, or none of its script runs */
for (const tag of ['</script>', '</body>', '</html>']) {
  assert(`the shipped page still closes ${tag}`, html.includes(tag), 'present');
}
{
  /* Only loading tags can make a request. Prose <a href>, <link rel=canonical> and the
     OG / JSON-LD absolute URLs are metadata, not fetches. */
  const loaders = html.match(/<(script|img|iframe|video|audio|source|embed|object)\b[^>]*>/gi) || [];
  const styles = html.match(/<link\b[^>]*rel=["']?(stylesheet|preload|preconnect|dns-prefetch)[^>]*>/gi) || [];
  const offsite = [...loaders, ...styles].filter((tag) => /(src|href|data)\s*=\s*["']?(https?:)?\/\//i.test(tag));
  assert('the shipped page makes no third-party request', offsite.length === 0,
    offsite.length ? offsite.join(' | ') : `${loaders.length + styles.length} loading tags, all same-origin`);
}
const RECOMPUTED = {
  'density': E8density,
  'paper.decimal': Number((PI ** 4 / 384).toFixed(5)),
  'e8.det': E8det,
  'e8.min2': E8min2,
  'e8.lattice.factor': Math.pow(E8min2 / 2, 4) / Math.sqrt(E8det),
  'e8.shell1': E8counts.get(2),
  'e8.shell2': E8counts.get(4),
  'e8.shell3': E8counts.get(6),
  'e8.shell4': E8counts.get(8),
  'gauss.bound': V8 * Math.pow(1 / Math.sqrt(PI / 5) / 2, 8) / (1 - 4 * (PI / 5) / PI),
  'gauss.ratio': (V8 * Math.pow(1 / Math.sqrt(PI / 5) / 2, 8) / (1 - 4 * (PI / 5) / PI)) / E8density,
  'gauss.half': V8 * Math.pow(1 / Math.sqrt(0.5) / 2, 8) / (1 - 4 * 0.5 / PI),
  'gauss.half.ratio': (V8 * Math.pow(1 / Math.sqrt(0.5) / 2, 8) / (1 - 4 * 0.5 / PI)) / E8density,
  'ledger.half.sum': ledger(0.5).sp,
  'ledger.half.fhat0': gaussHatW(0, 0.5),
  'ledger.half.waste': ledger(0.5).waste,
  'ledger.half.deficit': 1 - gaussHatW(0, 0.5),
  'ledger.half.realdeficit': 1 - ledger(0.5).sp,
  'ledger.half.share': ledger(0.5).waste / (1 - gaussHatW(0, 0.5)),
  'ledger.half.ifnowaste': 1 / ledger(0.5).sp,
  'e4i': ledger(0.5).th,
  'de4i': ledger(0.5).dth,
  'e4i.overpi': ledger(0.5).th / PI,
  'cert.small.A': -cAs.worst,
  'cert.small.B': cBs.worst,
  'cert.mid.A': -cAm.worst,
  'cert.mid.A.n': cAm.leaves,
  'cert.mid.B': cBm.worst,
  'cert.mid.B.n': cBm.leaves,
  'cert.tail.E': cAt.E,
  'cert.tail.A': cAt.dom,
  'cert.tail.B': cBt.lin,
  'cert.remainder': (1 + 12 / PI + 36 / PI ** 2) * tailBound(KMAX, Math.exp(-PI)),
  /* This verifier's independent value for g'(sqrt2) is the CLOSED FORM -sqrt2/60, which is what
     the paper's asymptotics give. The page ships a measured difference quotient. Both are
     compared against the same printed text, from opposite directions, which is the point. */
  'gp.sqrt2': -SQRT2 / 60,
  'ghp.sqrt2': ghpSqrt2,
  'B.e2': Binf.e2,
  'g0': g(0),
  'ghat0': ghat(0),
  'zero.simple': zeroSimple,
  'zero.predicted': zeroPredicted,
  'zero.doubles': zeroDoubles,
  'hankel.value': hankel8(g, 0.75, 5.5, 1200),
  'quad.worst': quadWorst,
  'paper.gap': gapDays,
  'paper.journalpages': 1015 - 991 + 1
};

const EXACT_KEYS = new Set(['e8.det', 'e8.min2', 'e8.lattice.factor', 'paper.gap',
  'paper.journalpages', 'cert.mid.A.n', 'cert.mid.B.n', 'B.e2',
  'e8.shell1', 'e8.shell2', 'e8.shell3', 'e8.shell4']);
/* Rows the HTML states as inequalities. +1 = a lower bound, -1 = an upper bound. The live
   value must be on the correct side AND within one unit of the last place printed, so a bound
   rounded the wrong way fails even when its digits look right. */
const BOUND_KEYS = {
  'cert.small.A': -1, 'cert.small.B': +1,
  'cert.mid.A': -1, 'cert.mid.B': +1,
  'cert.tail.E': -1, 'cert.tail.B': +1,
  'cert.remainder': -1, 'quad.worst': -1,
  'zero.doubles': -1
};
/* Rows the maths says are exactly zero, where the page ships "0" and measures a quotient. */
const NEAR_KEYS = { 'ghp.sqrt2': 1e-12 };
/* Numbers that are transcriptions, not computations. The page must tag these data-quote, NOT
   data-check: a transcription placed in a column headed "recomputed live" is a lie about
   provenance even when the number is right. */
const QUOTED_KEYS = { 'paper.factor': '1.000001', 'paper.arxivpages': '22' };

function cleanNum(t) {
  return t
    .replace(/&minus;|&#8722;/g, '-')
    .replace(/&nbsp;|&#160;|&thinsp;|&#8201;/g, '')
    .replace(/\u2212/g, '-')
    .replace(/[\s,\u2009\u202f\u00a0]/g, '');
}
function sigDigits(t) {
  const m = cleanNum(t).split(/[eE]/)[0].replace(/[^0-9]/g, '').replace(/^0+/, '');
  return Math.max(1, m.length);
}
/* the value of one unit in the last place the HTML actually printed */
function lastPlace(t) {
  const parts = cleanNum(t).split(/[eE]/);
  const exp = parts[1] ? parseInt(parts[1], 10) : 0;
  const mant = parts[0].replace(/^[-+]/, ''), dot = mant.indexOf('.');
  const decimals = dot < 0 ? 0 : mant.length - dot - 1;
  return Math.pow(10, exp - decimals);
}

const found = new Map();
const rx = /data-check="([^"]+)"[^>]*>([^<]*)</g;
let m;
while ((m = rx.exec(html)) !== null) if (!found.has(m[1])) found.set(m[1], m[2]);

const quoted = new Map();
const rxq = /data-quote="([^"]+)"[^>]*>([^<]*)</g;
let mq;
while ((mq = rxq.exec(html)) !== null) if (!quoted.has(mq[1])) quoted.set(mq[1], mq[2]);

assert('the page ships at least 30 data-check values', found.size >= 30, `${found.size} found`);
for (const key of Object.keys(RECOMPUTED)) {
  assert(`the page ships a value for "${key}"`, found.has(key), found.has(key) ? found.get(key) : 'MISSING');
}
/* the provenance check: nothing that is only a transcription may wear the data-check label */
for (const [key, want] of Object.entries(QUOTED_KEYS)) {
  assert(`"${key}" is tagged as a transcription, not as a live computation`,
    quoted.has(key) && !found.has(key) && cleanNum(quoted.get(key)).trim() === want,
    quoted.has(key) ? `data-quote="${key}" reads ${quoted.get(key)}` : 'MISSING from data-quote');
}
for (const key of quoted.keys()) {
  assert(`the page's data-quote="${key}" is one this verifier knows the provenance of`,
    key in QUOTED_KEYS, key in QUOTED_KEYS ? 'known' : 'UNKNOWN');
}

let compared = 0, mismatched = 0, bounds = 0;
for (const [key, text] of found) {
  if (!(key in RECOMPUTED)) {
    failures.push(`page ships data-check="${key}" which this verifier does not recompute`);
    console.error(`FAIL      unrecomputed shipped value: ${key} = ${text}`);
    continue;
  }
  const shipped = parseFloat(cleanNum(text));
  const live = RECOMPUTED[key];
  compared += 1;
  let ok;
  if (key in BOUND_KEYS) {
    const dir = BOUND_KEYS[key];
    const side = dir > 0 ? live >= shipped : live <= shipped;
    const tight = Math.abs(live - shipped) <= lastPlace(text) * (1 + 1e-9);
    ok = side && tight;
    bounds += 1;
    if (!ok) {
      console.error(`FAIL      shipped "${key}" states ${dir > 0 ? '>=' : '<='} ${text}, but the enclosure is ${live}` +
        (side ? ' (correct side, but rounded further out than one printed unit)' : ' (WRONG SIDE: the page claims more than was proved)'));
    }
  } else if (key in NEAR_KEYS) {
    ok = Math.abs(live) < NEAR_KEYS[key];
    if (!ok) console.error(`FAIL      "${key}" should be numerically zero but measures ${live}`);
  } else if (EXACT_KEYS.has(key)) {
    ok = (live === shipped);
    if (!ok) console.error(`FAIL      shipped "${key}" = ${text} but recomputed ${live}`);
  } else {
    ok = Math.abs(live - shipped) <= Math.max(Math.abs(live), Math.abs(shipped)) * Math.pow(10, -(sigDigits(text) - 1)) * 0.75;
    if (!ok) console.error(`FAIL      shipped "${key}" = ${text} but recomputed ${live}`);
  }
  if (!ok) mismatched += 1;
}
assert('every shipped number matches the independent recomputation', mismatched === 0,
  `${compared} shipped numbers compared (${bounds} of them stated inequalities, each tested for the correct SIDE of the bound as well as its digits), ${mismatched} mismatches`);

/* A bound rounded the wrong way must actually fail, or the direction test is decoration. */
{
  const dir = BOUND_KEYS['cert.small.B'];
  const live = RECOMPUTED['cert.small.B'];
  const wrongWay = '12303.09';                     // the round-to-nearest value, above the enclosure
  const side = dir > 0 ? live >= parseFloat(wrongWay) : live <= parseFloat(wrongWay);
  assert('the outward-rounding test is falsifiable', !side,
    `stating "Q_B >= ${wrongWay}" would claim more than the enclosure ${live.toFixed(5)} proves, and this test rejects it`);
}

/* the page also prints the paper's series coefficients inside its own check table; those
   literals live in the HTML, so they can be compared against the rebuild too */
for (const [name, got, want] of anchors) {
  const literal = "['" + want.join("', '") + "']";
  assert(`the page's printed anchors for ${name} are in the HTML and match the rebuild`,
    html.includes(literal) && got.map(String).join(',') === want.join(','), literal);
}
assert('the page prints a command that runs',
  html.includes('node research/viazovska-magic/verify-viazovska-magic.mjs')
  && fs.existsSync(path.join(ROOT, 'research', 'viazovska-magic', 'verify-viazovska-magic.mjs')),
  'the printed verifier path exists');

/* ══════════════════════ summary ══════════════════════ */
console.log('');
if (failures.length) {
  console.error(`${failures.length} CHECK(S) FAILED`);
  process.exit(1);
}
console.log(`${passes} checks passed, ${compared} of them comparing the shipped page against an independent recomputation.`);
console.log(`E8: det ${E8det}, min norm^2 ${E8min2}, shells ${[1, 2, 3, 4].map((k) => E8counts.get(2 * k)).join(', ')}`);
console.log(`density: lower ${E8density.toFixed(12)}  upper ${magicUpper.toFixed(12)}  pi^4/384 ${(PI ** 4 / 384).toFixed(12)}`);
console.log(`kernel at t = 1: A = ${kernelAt(1, 'A').toPrecision(12)}  B = ${kernelAt(1, 'B').toPrecision(12)}`);
console.log(`g(1.6) = ${g(1.6).toExponential(10)}   g-hat(1.6) = ${ghat(1.6).toExponential(10)}`);
process.exit(0);
