#!/usr/bin/env node
// Offline verifier for /strata/pslq-constants/
//
// Three obligations, in this order:
//   1. Recompute every number the page shows, from the committed record, with
//      code written here. Nothing in this half is imported from the page.
//   2. Extract and execute the shipped page engine, then assert it agrees.
//   3. Mutate inputs and coefficients and assert the checks go red.
//
// Run from the repository root:
//   node research/pslq-constants/verify-pslq-constants.mjs
//
// The 105 published grid cells are 369,138 integer-relation searches, so they
// are spread over worker threads by default. PSLQ_WORKERS=0 forces one thread.

import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import vm from 'node:vm';
import crypto from 'node:crypto';
import { Worker, isMainThread, workerData, parentPort } from 'node:worker_threads';
import { auditGateChecks } from './verify-audit-gate.mjs';

const ROOT = path.resolve(import.meta.dirname, '../..');
const SELF = path.join(ROOT, 'research/pslq-constants/verify-pslq-constants.mjs');
const DATA = path.join(ROOT, 'research/pslq-constants/data/b000.txt');
const PROVENANCE = path.join(ROOT, 'research/pslq-constants/data/PROVENANCE.md');
const HTML = path.join(ROOT, 'public/strata/pslq-constants/index.html');
const MARKDOWN = path.join(ROOT, 'src/content/strata/pslq-constants.md');

/* ================================================================== *
 * 1. Correctly rounded decimal arithmetic.
 *
 * The page states its PSLQ convention as "working precision max(60,p+30)".
 * That is a decimal working precision, and it is load-bearing: at the larger
 * coefficient bounds the candidate counts move by a tenth of a percent if the
 * working precision moves (there is a mutation test for exactly that below).
 * So the search has to be run in decimal. Every operation here rounds the
 * exact result to `prec` significant decimal digits, half to even.
 * ================================================================== */

const POW = [1n];
function pow10(k) { while (POW.length <= k) POW.push(POW[POW.length - 1] * 10n); return POW[k]; }
pow10(64);
function absBig(x) { return x < 0n ? -x : x; }
function digitsOf(n) {
  if (n === 0n) return 0;
  let hi = 1;
  while (n >= pow10(hi)) hi *= 2;
  let lo = hi >> 1;
  while (hi - lo > 1) { const mid = (lo + hi) >> 1; if (n >= pow10(mid)) lo = mid; else hi = mid; }
  return lo + 1;
}

// a decimal is {n: signed BigInt coefficient, e: exponent, d: digits in |n|}; value = n * 10^e
const DZERO = { n: 0n, e: 0, d: 0 };
function dec(n, e) { return { n, e, d: digitsOf(absBig(n)) }; }
function decInt(i) { return dec(BigInt(i), 0); }

function decRound(n, d, e, prec, sticky) {
  if (n === 0n) return DZERO;
  const drop = d - prec;
  if (drop <= 0) return { n, e, d };
  const scale = pow10(drop);
  const neg = n < 0n;
  const a = neg ? -n : n;
  let q = a / scale;
  const r = a - q * scale;
  const half = scale / 2n;
  if (r > half || (r === half && (sticky || (q & 1n) === 1n))) q += 1n;
  if (q === 0n) return DZERO;
  let outE = e + drop;
  if (q >= pow10(prec)) { q /= 10n; outE += 1; }
  return { n: neg ? -q : q, e: outE, d: digitsOf(q) };
}
function decNeg(a) { return a.n === 0n ? DZERO : { n: -a.n, e: a.e, d: a.d }; }
function decAbs(a) { return a.n < 0n ? { n: -a.n, e: a.e, d: a.d } : a; }
function decMul(a, b, prec) {
  if (a.n === 0n || b.n === 0n) return DZERO;
  const n = a.n * b.n;
  const upper = a.d + b.d;
  const d = absBig(n) >= pow10(upper - 1) ? upper : upper - 1;
  return decRound(n, d, a.e + b.e, prec, false);
}
function decAdd(a, b, prec) {
  if (a.n === 0n) return decRound(b.n, b.d, b.e, prec, false);
  if (b.n === 0n) return decRound(a.n, a.d, a.e, prec, false);
  let hi = a, lo = b;
  if (b.e > a.e) { hi = b; lo = a; }
  let shift = hi.e - lo.e;
  if (shift > prec + Math.max(hi.d, lo.d) + 5) {
    // lo lies entirely below the rounding position: a signed unit carries the same information
    lo = { n: lo.n < 0n ? -1n : 1n, e: hi.e - (prec + 3), d: 1 };
    shift = hi.e - lo.e;
  }
  const n = hi.n * pow10(shift) + lo.n;
  if (n === 0n) return DZERO;
  return decRound(n, digitsOf(absBig(n)), lo.e, prec, false);
}
function decSub(a, b, prec) { return decAdd(a, decNeg(b), prec); }
function decDiv(a, b, prec) {
  if (a.n === 0n) return DZERO;
  const neg = (a.n < 0n) !== (b.n < 0n);
  const ca = absBig(a.n), cb = absBig(b.n);
  let k = Math.max(0, prec - a.d + b.d + 1);
  for (;;) {
    const num = ca * pow10(k);
    const q = num / cb, r = num - q * cb;
    const dq = digitsOf(q);
    if (dq >= prec + 1) return decRound(neg ? -q : q, dq, a.e - b.e - k, prec, r !== 0n);
    k += prec + 1 - dq;
  }
}
function bitLen(v) { let b = 0; while (v > 0xffffffffn) { v >>= 32n; b += 32; } let x = Number(v); while (x > 0) { x = Math.floor(x / 2); b += 1; } return b; }
function isqrt(v) {
  if (v < 2n) return v;
  let x = 1n << BigInt(Math.ceil(bitLen(v) / 2));
  for (;;) { const y = (x + v / x) >> 1n; if (y >= x) break; x = y; }
  return x;
}
function decSqrt(a, prec) {
  if (a.n === 0n) return DZERO;
  let E = Math.floor((a.d + a.e - 1) / 2) - (prec - 1);
  for (;;) {
    const ex = a.e - 2 * E;
    if (ex < 0) { E -= 1; continue; }
    const A = a.n * pow10(ex);
    const s = isqrt(A);
    const ds = digitsOf(s);
    if (ds < prec) { E -= 1; continue; }
    if (ds > prec) { E += 1; continue; }
    // the square root of an integer is never exactly a half-integer, so no tie can arise
    const m = A - s * s > s ? s + 1n : s;
    if (m >= pow10(prec)) return { n: m / 10n, e: E + 1, d: prec };
    return { n: m, e: E, d: digitsOf(m) };
  }
}
function decCmpAbs(a, b) {
  if (a.n === 0n) return b.n === 0n ? 0 : -1;
  if (b.n === 0n) return 1;
  const pa = a.e + a.d, pb = b.e + b.d;
  if (pa !== pb) return pa < pb ? -1 : 1;
  let ca = absBig(a.n), cb = absBig(b.n);
  if (a.d < b.d) ca *= pow10(b.d - a.d); else if (b.d < a.d) cb *= pow10(a.d - b.d);
  return ca < cb ? -1 : ca > cb ? 1 : 0;
}
function decToIntegralHalfEven(a) {
  if (a.n === 0n) return 0n;
  if (a.e >= 0) return a.n * pow10(a.e);
  const drop = -a.e;
  if (drop > a.d) return 0n;
  const neg = a.n < 0n, c = absBig(a.n), scale = pow10(drop);
  let q = c / scale;
  const r = c - q * scale, half = scale / 2n;
  if (r > half || (r === half && (q & 1n) === 1n)) q += 1n;
  return neg ? -q : q;
}
function decPowInt(a, k, prec) {
  if (k === 1) return decRound(a.n, a.d, a.e, prec, false);
  const wp = prec + String(k).length + 1;
  let result = null, base = a, n = k;
  while (n > 0) {
    if (n & 1) result = result === null ? base : decMul(result, base, wp);
    n >>= 1;
    if (n > 0) base = decMul(base, base, wp);
  }
  return decRound(result.n, result.d, result.e, prec, false);
}
function decToNumber(a) {
  if (a.n === 0n) return 0;
  const sign = a.n < 0n ? '-' : '';
  const c = absBig(a.n).toString();
  return Number(`${sign}${c[0]}.${c.slice(1, 25)}e${a.e + a.d - 1}`);
}

/* ================================================================== *
 * 2. PSLQ over that arithmetic: gamma = sqrt(4/3), Hermite reduction
 *    with half-even rounding, the documented tolerance and step cap.
 * ================================================================== */

function primitive(v) {
  let g = 0n;
  for (const x of v) { let a = absBig(x), b = g; while (a) { const t = b % a; b = a; a = t; } g = b; }
  if (g === 0n) g = 1n;
  let out = v.map((x) => x / g);
  const first = out.find((x) => x !== 0n);
  if (first !== undefined && first < 0n) out = out.map((x) => -x);
  return out;
}
function pslq(values, tolerance, prec, maxSteps, maxCoeff) {
  const n = values.length;
  const s = new Array(n), y = new Array(n);
  const H = Array.from({ length: n }, () => new Array(n - 1).fill(DZERO));
  const A = Array.from({ length: n }, (_, i) => Array.from({ length: n }, (_, j) => (i === j ? 1n : 0n)));
  const B = Array.from({ length: n }, (_, i) => Array.from({ length: n }, (_, j) => (i === j ? 1n : 0n)));
  let total = DZERO;
  for (let k = n - 1; k >= 0; k -= 1) { total = decAdd(total, decMul(values[k], values[k], prec), prec); s[k] = decSqrt(total, prec); }
  const scale = decDiv(decInt(1), s[0], prec);
  for (let k = 0; k < n; k += 1) { y[k] = decMul(values[k], scale, prec); s[k] = decMul(s[k], scale, prec); }
  for (let i = 0; i < n; i += 1) for (let j = 0; j < n - 1; j += 1) {
    if (i < j) H[i][j] = DZERO;
    else if (i === j) H[i][j] = decDiv(s[j + 1], s[j], prec);
    else H[i][j] = decDiv(decMul(decNeg(y[i]), y[j], prec), decMul(s[j], s[j + 1], prec), prec);
  }
  function hermite(row, col) {
    const q = decToIntegralHalfEven(decDiv(H[row][col], H[col][col], prec));
    if (q === 0n) return;
    const qd = dec(q, 0);
    y[col] = decAdd(y[col], decMul(qd, y[row], prec), prec);
    for (let z = 0; z <= col; z += 1) H[row][z] = decSub(H[row][z], decMul(qd, H[col][z], prec), prec);
    for (let z = 0; z < n; z += 1) { A[row][z] -= q * A[col][z]; B[z][col] += q * B[z][row]; }
  }
  for (let i = 1; i < n; i += 1) for (let j = i - 1; j >= 0; j -= 1) hermite(i, j);
  const gamma = decSqrt(decDiv(decInt(4), decInt(3), prec), prec);
  const gpow = [];
  for (let i = 0; i < n - 1; i += 1) gpow.push(decPowInt(gamma, i + 1, prec));
  for (let step = 0; step < maxSteps; step += 1) {
    let m = 0, best = null;
    for (let i = 0; i < n - 1; i += 1) {
      const score = decMul(gpow[i], decAbs(H[i][i]), prec);
      if (best === null || decCmpAbs(score, best) > 0) { best = score; m = i; }
    }
    const ty = y[m]; y[m] = y[m + 1]; y[m + 1] = ty;
    const ta = A[m]; A[m] = A[m + 1]; A[m + 1] = ta;
    const th = H[m]; H[m] = H[m + 1]; H[m + 1] = th;
    for (let i = 0; i < n; i += 1) { const tb = B[i][m]; B[i][m] = B[i][m + 1]; B[i][m + 1] = tb; }
    if (m < n - 2) {
      const h0 = H[m][m], h1 = H[m][m + 1];
      const radius = decSqrt(decAdd(decMul(h0, h0, prec), decMul(h1, h1, prec), prec), prec);
      const c0 = decDiv(h0, radius, prec), c1 = decDiv(h1, radius, prec);
      for (let i = m; i < n; i += 1) {
        const u = H[i][m], v = H[i][m + 1];
        H[i][m] = decAdd(decMul(c0, u, prec), decMul(c1, v, prec), prec);
        H[i][m + 1] = decAdd(decMul(decNeg(c1), u, prec), decMul(c0, v, prec), prec);
      }
    }
    for (let i = m + 1; i < n; i += 1) for (let j = Math.min(i - 1, m + 1); j >= 0; j -= 1) hermite(i, j);
    let jb = 0;
    for (let z = 1; z < n; z += 1) if (decCmpAbs(y[z], y[jb]) < 0) jb = z;
    if (decCmpAbs(y[jb], tolerance) < 0) return { relation: primitive(B.map((row) => row[jb])), steps: step + 1 };
    let minmax = null;
    for (let j = 0; j < n; j += 1) {
      let mx = 0n;
      for (let i = 0; i < n; i += 1) { const v = absBig(B[i][j]); if (v > mx) mx = v; }
      if (minmax === null || mx < minmax) minmax = mx;
    }
    if (minmax > maxCoeff) return null;
  }
  return null;
}

/* ================================================================== *
 * 3. Named constants recomputed from their definitions, in fixed point
 *    at 10^-210. Every claim below is made at 160 places or fewer, so
 *    fifty digits are held back as guard digits.
 * ================================================================== */

const FXS = 210;
const FXONE = 10n ** BigInt(FXS);
const CLAIM = 160;
function fxMul(a, b) { const r = a * b; return r >= 0n ? (r + FXONE / 2n) / FXONE : -((-r + FXONE / 2n) / FXONE); }
function fxDiv(a, b) {
  const neg = (a < 0n) !== (b < 0n), A = absBig(a) * FXONE, B = absBig(b);
  const q = (A + B / 2n) / B;
  return neg ? -q : q;
}
function fxSqrt(a) { return isqrt(a * FXONE); }
function fxRoot(a, k) {
  const K = BigInt(k);
  const target = a * FXONE ** BigInt(k - 1);
  let x = 1n << BigInt(Math.ceil(bitLen(target) / k) + 1);
  for (;;) { const y = ((K - 1n) * x + target / x ** (K - 1n)) / K; if (y >= x) break; x = y; }
  return x;
}
function fxInt(n) { return BigInt(n) * FXONE; }
function fxAtanInv(k) {
  const K = BigInt(k), K2 = K * K;
  let term = FXONE / K, sum = term, m = 1n;
  for (;;) { term /= K2; const t = term / (2n * m + 1n); if (t === 0n) break; sum += (m % 2n === 1n) ? -t : t; m += 1n; }
  return sum;
}
function fxAtanhInv(k) {
  const K = BigInt(k), K2 = K * K;
  let p = FXONE / K, sum = p, m = 1n;
  for (;;) { p /= K2; const t = p / (2n * m + 1n); if (t === 0n) break; sum += t; m += 1n; }
  return sum;
}
const FX_PI = 16n * fxAtanInv(5) - 4n * fxAtanInv(239);   // Machin, deliberately not BBP
const FX_LN2 = 2n * fxAtanhInv(3);
function fxLn(x) {
  let k = 0n, v = x;
  while (v >= 2n * FXONE) { v /= 2n; k += 1n; }
  while (v < FXONE) { v *= 2n; k -= 1n; }
  const y = fxDiv(v - FXONE, v + FXONE), y2 = fxMul(y, y);
  let term = y, sum = y, m = 1n;
  for (;;) { term = fxMul(term, y2); const t = term / (2n * m + 1n); if (t === 0n) break; sum += t; m += 1n; }
  return k * FX_LN2 + 2n * sum;
}
function fxExp1() { let sum = FXONE, term = FXONE, k = 1n; while (term !== 0n) { term /= k; sum += term; k += 1n; } return sum; }
function fxCos(z) {
  const z2 = fxMul(z, z);
  let term = FXONE, sum = FXONE, k = 1n;
  for (;;) { term = -fxMul(term, z2) / ((2n * k - 1n) * (2n * k)); if (term === 0n) break; sum += term; k += 1n; }
  return sum;
}
function fxSin(z) {
  const z2 = fxMul(z, z);
  let term = z, sum = z, k = 1n;
  for (;;) { term = -fxMul(term, z2) / ((2n * k) * (2n * k + 1n)); if (term === 0n) break; sum += term; k += 1n; }
  return sum;
}
function fxGoldenRoot() { // positive root of x^2 = x + 1 by Newton, computed without any square root
  let x = 16n * FXONE / 10n;
  for (let i = 0; i < 200; i += 1) {
    const f = fxMul(x, x) - x - FXONE;
    const step = fxDiv(f, 2n * x - FXONE);
    if (step === 0n) break;
    x -= step;
  }
  return x;
}
function fxEulerGamma(n) { // Brent and McMillan: gamma = A(n)/B(n) - ln n + O(e^-4n)
  const N2 = BigInt(n) * BigInt(n);
  let term = FXONE, A = 0n, B = FXONE, H = 0n, k = 1n;
  for (;;) {
    term = (term * N2) / (k * k);
    if (term === 0n) break;
    H += FXONE / k;
    A += fxMul(term, H);
    B += term;
    k += 1n;
  }
  return fxDiv(A, B) - fxLn(fxInt(n));
}
function fxAgm(a, b) { for (let i = 0; i < 60; i += 1) { const na = (a + b) / 2n, nb = fxSqrt(fxMul(a, b)); if (na === a && nb === b) break; a = na; b = nb; } return a; }
function fxZeta2() { // 3 sum 1/(n^2 binomial(2n,n))
  let sum = 0n, c = 1n;
  for (let n = 1n; n < 600n; n += 1n) {
    c = c * (2n * n) * (2n * n - 1n) / (n * n);
    const t = FXONE / (n * n * c);
    if (t === 0n) break;
    sum += t;
  }
  return 3n * sum;
}
function fxZeta3() { // (5/2) sum (-1)^(n-1)/(n^3 binomial(2n,n))
  let sum = 0n, c = 1n;
  for (let n = 1n; n < 600n; n += 1n) {
    c = c * (2n * n) * (2n * n - 1n) / (n * n);
    const t = FXONE / (n * n * n * c);
    if (t === 0n) break;
    sum += (n % 2n === 1n) ? t : -t;
  }
  return 5n * sum / 2n;
}
function fxBBP(j) { // X_j = sum_{k>=0} 16^-k/(8k+j)
  let sum = 0n, p = FXONE;
  for (let k = 0n; k < 400n; k += 1n) {
    const t = p / (8n * k + BigInt(j));
    if (t === 0n && k > 0n) break;
    sum += t; p /= 16n;
  }
  return sum;
}
function fxToDec(v) { return dec(v, -FXS); }
function fxShow(v, places) {
  const neg = v < 0n;
  const s = absBig(v).toString().padStart(FXS + 1, '0');
  return `${neg ? '-' : ''}${s.slice(0, s.length - FXS)}.${s.slice(s.length - FXS, s.length - FXS + places)}`;
}
function fxNumber(v, places = 30) { return Number(fxShow(v, places)); }

/* ================================================================== *
 * 4. The committed record, the admitted-digit rule and the holdout
 *    rule, all in exact integer arithmetic.
 * ================================================================== */

const ROW_RE = /^([+-]?)(\d)\.(\d+)e([+-]?\d+)\s+(.+)$/i;
function parseRecord(text) {
  return text.trim().split(/\n/).map((line, i) => {
    const m = line.match(ROW_RE);
    if (!m) throw new Error(`record line ${i + 1} does not parse: ${line}`);
    return { sign: m[1] === '-' ? -1 : 1, digits: m[2] + m[3], exp: Number(m[4]), label: m[5], line };
  });
}
function rowInt(row) { return row.sign < 0 ? -BigInt(row.digits) : BigInt(row.digits); }
function admittedInt(row, p) {
  const ds = row.digits.slice(0, p).padEnd(p, '0');
  return row.sign < 0 ? -BigInt(ds) : BigInt(ds);
}
function admittedDec(row, p) { return dec(admittedInt(row, p), row.exp - p + 1); }
function sourceDec(row) { return dec(rowInt(row), row.exp - row.digits.length + 1); }
function rowToFx(row) {
  const places = row.digits.length - 1 - row.exp;
  return places >= 0 ? rowInt(row) * pow10(FXS - places) : rowInt(row) * pow10(FXS) * pow10(-places);
}
// "compatible only if the full-source residual lies within half a last-place
// unit from each row, weighted by |a| and |b|", evaluated over the integers
function sourceAlive(x, y, q) {
  const places = Math.max(0, x.digits.length - 1 - x.exp, y.digits.length - 1 - y.exp);
  const scale = pow10(places);
  const X = rowInt(x) * pow10(places + x.exp - x.digits.length + 1);
  const Y = rowInt(y) * pow10(places + y.exp - y.digits.length + 1);
  const residual = q[0] * scale + q[1] * X + q[2] * Y;
  const ulpX = pow10(places + x.exp - x.digits.length + 1);
  const ulpY = pow10(places + y.exp - y.digits.length + 1);
  return { alive: 2n * absBig(residual) <= absBig(q[1]) * ulpX + absBig(q[2]) * ulpY, residual, scale };
}

/* ================================================================== *
 * 5. The two null catalogues: xorshift32 seeded by FNV-1a of mode, row
 *    index and label. The shuffle preserves leading digit, exponent and
 *    length; the random catalogue preserves exponent and length.
 * ================================================================== */

function fnv1a(text) {
  let v = 2166136261 >>> 0;
  for (const b of Buffer.from(text, 'utf8')) { v = (v ^ b) >>> 0; v = Math.imul(v, 16777619) >>> 0; }
  return v || 1;
}
function xorshift32(s) {
  s = (s ^ ((s << 13) >>> 0)) >>> 0;
  s = (s ^ (s >>> 17)) >>> 0;
  s = (s ^ ((s << 5) >>> 0)) >>> 0;
  return s >>> 0;
}
function nullCatalogue(rows, mode, seedPrefix) {
  if (mode === 'catalogue') return rows;
  return rows.map((row, index) => {
    let state = fnv1a(`${seedPrefix}:${index}:${row.label}`);
    if (mode === 'shuffle') {
      const tail = row.digits.slice(1).split('');
      for (let i = tail.length - 1; i > 0; i -= 1) {
        state = xorshift32(state);
        const j = state % (i + 1);
        const t = tail[i]; tail[i] = tail[j]; tail[j] = t;
      }
      return { ...row, digits: row.digits[0] + tail.join('') };
    }
    if (mode === 'random') {
      state = xorshift32(state);
      const out = [String(1 + (state % 9))];
      for (let i = 1; i < row.digits.length; i += 1) { state = xorshift32(state); out.push(String(state % 10)); }
      return { ...row, digits: out.join('') };
    }
    throw new Error(`unknown null mode ${mode}`);
  });
}

/* ================================================================== *
 * 6. One grid column: every unordered pair at one admitted precision.
 * ================================================================== */

const PRECISIONS = [8, 12, 16, 24, 32, 40, 48];
const BOUNDS = [100n, 1000n, 10000n, 100000n, 1000000n];
const MAX_STEPS = 500;
const MAX_COEFF = 1000000n;
const CONFIRMED = [
  { x: 'Golden Ratio or 1/2+sqrt(5)/2', y: '5^(1/2)', q: [1n, -2n, 1n], text: '1 - 2 phi + sqrt 5 = 0' },
  { x: 'Golden Ratio or 1/2+sqrt(5)/2', y: 'cos(1/5*Pi)', q: [0n, 1n, -2n], text: 'phi - 2 cos(pi/5) = 0' },
  { x: '5^(1/2)', y: 'cos(1/5*Pi)', q: [1n, 1n, -4n], text: '1 + sqrt 5 - 4 cos(pi/5) = 0' },
  { x: 'Sierpinski', y: 'MasserGramain', q: [0n, 1n, -4n], text: 'Sierpinski - 4 MasserGramain = 0' },
];
function workingPrecision(p) { return Math.max(60, p + 30); }

function gridColumn(rows, p, mode, options = {}) {
  const prec = options.prec || workingPrecision(p);
  const src = nullCatalogue(rows, mode, options.seedPrefix || mode);
  const tolerance = dec(1n, -(p - 1));
  const admitted = src.map((r) => admittedDec(r, p));
  const one = decInt(1);
  const found = [];
  let degenerateExcluded = 0, returned = 0;
  for (let i = 0; i < src.length; i += 1) {
    for (let j = i + 1; j < src.length; j += 1) {
      const r = pslq([one, admitted[i], admitted[j]], tolerance, prec, MAX_STEPS, MAX_COEFF);
      if (!r) continue;
      returned += 1;
      const q = r.relation;
      const height = q.reduce((a, x) => (absBig(x) > a ? absBig(x) : a), 0n);
      if (q[1] === 0n || q[2] === 0n) { degenerateExcluded += 1; continue; }
      if (height > MAX_COEFF) continue;
      found.push({ i, j, q, height, alive: sourceAlive(src[i], src[j], q).alive });
    }
  }
  const cells = {};
  for (const H of BOUNDS) {
    const candidates = found.filter((r) => r.height <= H);
    const alive = candidates.filter((r) => r.alive);
    const confirmed = candidates.filter((r) => CONFIRMED.some((c) => c.x === src[r.i].label && c.y === src[r.j].label && c.q.join(',') === r.q.join(',')));
    cells[String(H)] = [candidates.length, candidates.length - alive.length, alive.length, confirmed.length];
  }
  return {
    p, mode, cells, returned, degenerateExcluded,
    alive: found.filter((r) => r.alive).map((r) => `${src[r.i].label}|${src[r.j].label}|${r.q.join(',')}`).sort(),
    confirmedVectors: CONFIRMED.map((c) => {
      const hit = found.find((r) => src[r.i].label === c.x && src[r.j].label === c.y);
      return { text: c.text, got: hit ? hit.q.join(',') : 'none' };
    }),
  };
}

/* ================================================================== *
 * 7. Assertions.
 * ================================================================== */

let assertions = 0;
function ok(condition, label) {
  assertions += 1;
  if (!condition) throw new Error(`assertion ${assertions} failed: ${label}`);
  console.log(`ok ${assertions} - ${label}`);
}
function note(text) { console.log(`# ${text}`); }
// The source table truncates some rows and rounds others, and a few are rounded
// short and padded with zeros. So a printed row is checked digit by digit: its
// significant digits, ignoring any trailing zeros, must be either the truncation
// or the correct rounding of the independently computed value.
function comparedDigits(row) { return row.digits.replace(/0+$/, '').length; }
function matchesPrintedRow(computed, row) {
  if (computed <= 0n) return false;
  const k = comparedDigits(row);
  if (k < 40) return false;
  const dc = digitsOf(computed);
  if (dc - 1 - FXS !== row.exp) return false;
  const scale = pow10(dc - k);
  const trunc = computed / scale;
  const rounded = 2n * (computed - trunc * scale) >= scale ? trunc + 1n : trunc;
  const want = BigInt(row.digits.slice(0, k));
  return trunc === want || rounded === want;
}
function lastComparedPlace(row) { return pow10(FXS + row.exp - comparedDigits(row) + 1); }

async function computeGrids(rows) {
  const jobs = [];
  for (const p of PRECISIONS) for (const mode of ['catalogue', 'shuffle', 'random']) jobs.push({ p, mode });
  const requested = process.env.PSLQ_WORKERS === undefined
    ? Math.max(1, Math.min(3, (os.availableParallelism ? os.availableParallelism() : os.cpus().length) - 1))
    : Number(process.env.PSLQ_WORKERS);
  if (!(requested > 1)) {
    const out = [];
    for (const job of jobs) { out.push(gridColumn(rows, job.p, job.mode)); process.stderr.write(`# ${job.mode} p=${job.p} done\n`); }
    return out;
  }
  const results = new Array(jobs.length);
  let next = 0, failure = null;
  await Promise.all(Array.from({ length: Math.min(requested, jobs.length) }, () => new Promise((resolve) => {
    const start = () => {
      if (failure || next >= jobs.length) { resolve(); return; }
      const index = next; next += 1;
      const worker = new Worker(SELF, { workerData: { task: 'grid', ...jobs[index] } });
      worker.on('message', (msg) => { results[index] = msg; process.stderr.write(`# ${jobs[index].mode} p=${jobs[index].p} done\n`); });
      worker.on('error', (err) => { failure = err; resolve(); });
      worker.on('exit', () => {
        if (results[index]) start();
        else if (!failure) { failure = new Error(`worker for ${JSON.stringify(jobs[index])} produced nothing`); resolve(); }
      });
    };
    start();
  })));
  if (failure) throw failure;
  return results;
}

async function main() {
  const t0 = Date.now();
  const recordBytes = fs.readFileSync(DATA);
  const recordText = recordBytes.toString('utf8');
  const provenance = fs.readFileSync(PROVENANCE, 'utf8');
  const html = fs.readFileSync(HTML, 'utf8');
  const markdown = fs.readFileSync(MARKDOWN, 'utf8');
  const rows = parseRecord(recordText);
  const byLabel = new Map(rows.map((r) => [r.label, r]));

  /* --- A. the committed record ------------------------------------- */
  note('A. the committed record');
  const recordedHash = (provenance.match(/SHA-256(?: of the committed record)?:\s*`([0-9a-f]{64})`/) || [])[1];
  const recordedBytes = Number((provenance.match(/byte count:\s*`(\d+)`/) || [])[1]);
  const recordedRows = Number((provenance.match(/contains (\d+) nonempty lines/) || [])[1]);
  const actualHash = crypto.createHash('sha256').update(recordBytes).digest('hex');
  ok(/^[0-9a-f]{64}$/.test(recordedHash || ''), 'PROVENANCE.md records a SHA-256 for the source record');
  ok(actualHash === recordedHash, `the committed record hashes to the recorded SHA-256 ${actualHash.slice(0, 16)}`);
  ok(recordBytes.length === recordedBytes, `the committed record is the recorded ${recordedBytes} bytes`);
  ok(rows.length === recordedRows && rows.length === 188, `the committed record holds ${rows.length} parsed rows`);
  ok(rows.every((r) => ROW_RE.test(r.line)), 'every row matches the documented scientific-notation grammar');
  const lengths = rows.map((r) => r.digits.length);
  ok(Math.min(...lengths) === 63 && Math.max(...lengths) === 64, 'printed mantissas carry 63 or 64 significant digits');
  const zeroEnded = rows.filter((r) => /0{6,}$/.test(r.digits));
  ok(zeroEnded.length > 0 && html.includes('sometimes with conspicuous zero endings'), `the check panel's "conspicuous zero endings" are real: ${zeroEnded.length} rows end in six or more zeros`);
  ok(new Set(rows.map((r) => r.label)).size === 188, 'all 188 row labels are distinct');
  ok(new Set(rows.map((r) => `${r.sign}|${r.digits}|${r.exp}`)).size === 188, 'all 188 printed values are distinct');
  const pairCount = (rows.length * (rows.length - 1)) / 2;
  ok(pairCount === 17578, 'the search universe is 17,578 unordered pairs');

  const island = (html.match(/<script type="text\/plain" id="catalogue-data">([\s\S]*?)<\/script>/) || [])[1];
  ok(typeof island === 'string' && island.trim() === recordText.trim(), 'the browser data island ships the committed record bytes');
  const shown = (html.match(/SHA-256 ([0-9a-f]+)…([0-9a-f]+)/) || []).slice(1);
  ok(shown.length === 2 && actualHash.startsWith(shown[0]) && actualHash.endsWith(shown[1]), 'the abbreviated hash the page prints is a true prefix and suffix of the real hash');
  ok(html.includes('unordered pairs from 188 rows') && html.includes('17,578 pairwise searches') && html.includes("', 17,578 pairs certified'"), 'the page states the same 188-row, 17,578-pair universe');
  ok(html.includes('(rows.length*(rows.length-1)/2)'), 'the page computes its pair count from the shipped rows rather than printing a literal');

  const frontmatterDate = (markdown.match(/^date:\s*(\S+)$/m) || [])[1];
  const jsonLd = JSON.parse(html.match(/<script type="application\/ld\+json">([\s\S]*?)<\/script>/)[1]);
  ok(Boolean(frontmatterDate), 'the publication date is read from the markdown frontmatter');
  ok(jsonLd.datePublished === frontmatterDate, 'JSON-LD datePublished matches the frontmatter date');
  const revisionDates = [...markdown.matchAll(/^\*(?:Corrected|Updated) (\d{4}-\d{2}-\d{2}):\*/gm)].map((m) => m[1]);
  const lastRevisionDate = [frontmatterDate, ...revisionDates].sort().at(-1);
  ok(jsonLd.dateModified === lastRevisionDate, 'JSON-LD dateModified matches the latest dated revision, or publication when unrevised');
  ok(html.includes('node research/pslq-constants/verify-pslq-constants.mjs') && fs.existsSync(SELF), 'the command the page prints names this file, and it exists');
  const subresources = [
    ...html.matchAll(/<script[^>]*\ssrc="([^"]+)"/g),
    ...html.matchAll(/<link[^>]*\srel="(?:stylesheet|icon|apple-touch-icon|manifest|preload|preconnect)"[^>]*\shref="([^"]+)"/g),
  ].map((m) => m[1]);
  ok(subresources.length >= 5 && subresources.every((u) => u.startsWith('/')), `all ${subresources.length} subresources the page requests are same-origin`);

  /* --- B. catalogue rows recomputed from their definitions ---------- */
  note('B. catalogue rows recomputed from their definitions at 160 places');
  const PI = FX_PI;
  const E1 = fxExp1();
  const SQ2 = fxSqrt(fxInt(2)), SQ3 = fxSqrt(fxInt(3)), SQ5 = fxSqrt(fxInt(5));
  const PHI = fxGoldenRoot();
  const COS36 = fxCos(PI / 5n);
  const AGM12 = fxAgm(FXONE, SQ2);
  const GAMMA14 = fxSqrt(fxDiv(fxMul(2n * PI, fxSqrt(2n * PI)), AGM12));
  const EULER = fxEulerGamma(124);
  const SIERPINSKI = fxMul(PI, 2n * EULER + 2n * FX_LN2 + 3n * fxLn(PI) - 4n * fxLn(GAMMA14));
  const definitions = [
    ['Pi', PI, '16 atan(1/5) - 4 atan(1/239)'],
    ['exp(1.0)', E1, 'sum 1/k!'],
    ['log(2)', FX_LN2, '2 atanh(1/3)'],
    ['log(3)', fxLn(fxInt(3)), 'the atanh series with binary argument reduction'],
    ['log(5)', fxLn(fxInt(5)), 'the atanh series with binary argument reduction'],
    ['gamma', EULER, 'Brent and McMillan at n = 124'],
    ['2^(1/2)', SQ2, 'an integer square root'],
    ['3^(1/2)', SQ3, 'an integer square root'],
    ['5^(1/2)', SQ5, 'an integer square root'],
    ['2^(1/3)', fxRoot(fxInt(2), 3), 'an integer cube root'],
    ['3^(1/3)', fxRoot(fxInt(3), 3), 'an integer cube root'],
    ['Golden Ratio or 1/2+sqrt(5)/2', PHI, 'Newton on x^2 = x + 1, using no square root'],
    ['cos(1/5*Pi)', COS36, 'the cosine Taylor series'],
    ['sin(1/5*Pi)', fxSin(PI / 5n), 'the sine Taylor series'],
    ['cos(1/12*Pi)', fxCos(PI / 12n), 'the cosine Taylor series'],
    ['sin(1/12*Pi)', fxSin(PI / 12n), 'the sine Taylor series'],
    ['cos(1)', fxCos(FXONE), 'the cosine Taylor series'],
    ['sin(1)', fxSin(FXONE), 'the sine Taylor series'],
    ['Zeta(3)', fxZeta3(), '(5/2) sum (-1)^(n-1)/(n^3 C(2n,n))'],
    ['Pi*2^(1/2)/GAMMA(3/4)', GAMMA14, 'Gamma(1/4) = sqrt((2 pi)^(3/2) / AGM(1, sqrt 2))'],
    ['Sierpinski', SIERPINSKI, "pi (2 gamma + ln 4 + 3 ln pi - 4 ln Gamma(1/4))"],
    ['MasserGramain', SIERPINSKI / 4n, "a quarter of Sierpinski's constant"],
  ];
  for (const [label, value, how] of definitions) {
    const row = byLabel.get(label);
    ok(Boolean(row) && matchesPrintedRow(value, row), `row "${label}" is reproduced from ${how}, to all ${row ? comparedDigits(row) : 0} printed significant digits`);
  }
  ok(definitions.every(([label, value]) => !matchesPrintedRow(value + 10n * lastComparedPlace(byLabel.get(label)), byLabel.get(label))),
    'mutation test: moving any recomputed constant by ten units in its last compared place fails the same comparison');

  /* --- C. the published anchor, before anything new ----------------- */
  note('C. the published BBP anchor');
  const X = [null];
  for (let j = 1; j <= 8; j += 1) X.push(fxBBP(j));
  const PUBLISHED = [4n, 0n, 0n, -2n, -1n, -1n, 0n, 0n, -1n];
  const anchorValues = [X[1], X[2], X[3], X[4], X[5], X[6], X[7], X[8], PI];
  const anchorResidual = PUBLISHED.reduce((acc, c, i) => acc + c * anchorValues[i], 0n);
  ok(absBig(anchorResidual) < pow10(FXS - CLAIM), `the published vector annihilates (X1..X8, pi) below 1e-${CLAIM}`);
  let bbpSeries = 0n, pow16 = FXONE;
  for (let k = 0n; k < 400n; k += 1n) {
    const t = 4n * (pow16 / (8n * k + 1n)) - 2n * (pow16 / (8n * k + 4n)) - pow16 / (8n * k + 5n) - pow16 / (8n * k + 6n);
    if (t === 0n && k > 0n) break;
    bbpSeries += t; pow16 /= 16n;
  }
  ok(absBig(bbpSeries - PI) < pow10(FXS - CLAIM), `the BBP series evaluates to pi to ${CLAIM} places against an independent Machin pi`);
  const anchorPrec = 170;
  const anchorRun = pslq(anchorValues.map(fxToDec), dec(1n, -140), anchorPrec, 20000, 10n ** 20n);
  ok(anchorRun !== null, 'PSLQ returns a relation for (X1..X8, pi) at 170 working digits');
  ok(anchorRun.relation.join(',') === PUBLISHED.join(','), `PSLQ returns the published vector (${PUBLISHED.join(', ')})`);
  note(`the anchor returned in ${anchorRun.steps} PSLQ steps`);
  ok(html.includes('(4, 0, 0, −2, −1, −1, 0, 0, −1)'), 'the page prints the same published vector it requires');
  ok(html.includes("target='4,0,0,-2,-1,-1,0,0,-1'"), 'the shipped engine gates the audit on that exact vector');
  ok(html.includes('10.1090/S0025-5718-99-00995-3') && html.includes('10.1090/S0025-5718-97-00856-9'), 'the page cites the PSLQ analysis and the BBP paper by DOI');
  for (let i = 0; i < 9; i += 1) {
    let worst = null;
    for (const delta of [-1n, 1n]) {
      const mutated = PUBLISHED.map((c, k) => (k === i ? c + delta : c));
      const r = absBig(mutated.reduce((acc, c, k) => acc + c * anchorValues[k], 0n));
      worst = worst === null || r < worst ? r : worst;
    }
    ok(worst > FXONE / 1000n, `mutation test: moving anchor coefficient ${i + 1} by one leaves a residual above 1e-3`);
  }

  /* --- D. the unit check -------------------------------------------- */
  note('D. unit check, 6 zeta(2) - pi^2 = 0');
  const ZETA2 = fxZeta2(), PI2 = fxMul(PI, PI);
  ok(absBig(6n * ZETA2 - PI2) < pow10(FXS - CLAIM), `6 zeta(2) - pi^2 vanishes below 1e-${CLAIM}, from two independent series`);
  const unit = pslq([fxToDec(ZETA2), fxToDec(PI2)], dec(1n, -140), anchorPrec, 20000, 10n ** 20n);
  ok(unit !== null && unit.relation.join(',') === '6,-1', 'PSLQ recovers the primitive vector (6, -1) on (zeta(2), pi^2)');
  ok(absBig(6n * ZETA2 - 2n * PI2) > FXONE, 'mutation test: (6, -2) on the same pair leaves a residual above 1');
  const goldenPair = pslq([decInt(1), admittedDec(byLabel.get('Golden Ratio or 1/2+sqrt(5)/2'), 12), admittedDec(byLabel.get('5^(1/2)'), 12)], dec(1n, -11), 60, MAX_STEPS, MAX_COEFF);
  ok(goldenPair !== null && goldenPair.relation.join(',') === '1,-2,1', 'the same engine recovers 1 - 2 phi + sqrt 5 = 0 from two catalogue rows');

  /* --- E. layer one -------------------------------------------------- */
  note('E. layer one, 127 - 56 pi + 18 e');
  const truncPlaces = (fx, places) => fx / pow10(FXS - places);
  ok(truncPlaces(PI, 5) === 314159n, 'pi truncated to five decimal places is 3.14159');
  ok(truncPlaces(E1, 5) === 271828n, 'e truncated to five decimal places is 2.71828');
  ok(12700000n - 56n * 314159n + 18n * 271828n === 0n, 'the five-place statement 12700000 - 56*314159 + 18*271828 = 0 is exact over the integers');
  ok(html.includes('12700000 − 56·314159 + 18·271828 = 0'), 'the page prints that exact integer statement');
  for (let d = 5; d <= 15; d += 1) {
    const residual = 127n * pow10(d) - 56n * truncPlaces(PI, d) + 18n * truncPlaces(E1, d);
    if (d === 5) ok(residual === 0n, 'the frozen vector is exactly zero on five admitted places');
    else ok(residual !== 0n, `the frozen vector is not zero on ${d} admitted places`);
  }
  const fullResidual = 127n * FXONE - 56n * PI + 18n * E1;
  ok(fxShow(fullResidual, 24) === '-0.000115688765607117422854', 'the full-value residual of the frozen vector is -1.15688765607117422854e-4');
  ok(fxNumber(fullResidual, 25).toExponential(4) === '-1.1569e-4' && html.includes('1.1569 × 10⁻'), 'the page prints that residual rounded to four figures');
  note(`127 - 56 pi + 18 e = ${fxShow(fullResidual, 22)}`);

  /* --- F. the four definition-confirmed relations -------------------- */
  note('F. the four definition-confirmed relations');
  const relationChecks = [
    ['1 - 2 phi + sqrt 5 = 0', FXONE - 2n * PHI + SQ5, ['Golden Ratio or 1/2+sqrt(5)/2', '5^(1/2)'], [1n, -2n, 1n], true],
    ['phi - 2 cos(pi/5) = 0', PHI - 2n * COS36, ['Golden Ratio or 1/2+sqrt(5)/2', 'cos(1/5*Pi)'], [0n, 1n, -2n], false],
    ['1 + sqrt 5 - 4 cos(pi/5) = 0', FXONE + SQ5 - 4n * COS36, ['5^(1/2)', 'cos(1/5*Pi)'], [1n, 1n, -4n], true],
    ['Sierpinski - 4 MasserGramain = 0', SIERPINSKI - 4n * rowToFx(byLabel.get('MasserGramain')), ['Sierpinski', 'MasserGramain'], [0n, 1n, -4n], true],
  ];
  for (const [text, residual, labels, q, expectAlive] of relationChecks) {
    ok(absBig(residual) < pow10(FXS - 62), `${text} holds below 1e-62 against independently computed constants`);
    const live = sourceAlive(byLabel.get(labels[0]), byLabel.get(labels[1]), q);
    ok(live.alive === expectAlive, `${text} is ${expectAlive ? 'source-alive' : 'rejected by the printed source digits'} under the half-unit rule`);
    const bumped = [q[0], q[1], q[2] + 1n];
    const bumpedResidual = bumped[0] * FXONE + bumped[1] * rowToFx(byLabel.get(labels[0])) + bumped[2] * rowToFx(byLabel.get(labels[1]));
    ok(absBig(bumpedResidual) > FXONE / 1000n, `mutation test: ${text} with one coefficient moved by one leaves a residual above 1e-3`);
  }
  ok(html.includes('1 − 2φ + √5 = 0') && html.includes('φ − 2 cos(π/5) = 0') && html.includes('1 + √5 − 4 cos(π/5) = 0') && html.includes('Sierpiński − 4 Masser-Gramain = 0'), 'the page lists exactly these four relations');
  ok(sourceAlive(byLabel.get('Sierpinski'), byLabel.get('MasserGramain'), [0n, 1n, -4n]).residual === 0n, 'the printed Sierpinski and Masser-Gramain digits satisfy their relation exactly');
  const phiCos = sourceAlive(byLabel.get('Golden Ratio or 1/2+sqrt(5)/2'), byLabel.get('cos(1/5*Pi)'), [0n, 1n, -2n]);
  ok(phiCos.residual !== 0n, 'the printed golden-ratio and cos(pi/5) digits miss their true relation by a nonzero amount');
  note(`phi - 2 cos(pi/5) on the printed digits leaves residual numerator ${phiCos.residual} at scale 1e-${phiCos.scale.toString().length - 1}`);
  ok(sourceAlive(byLabel.get('Pi'), byLabel.get('exp(1.0)'), [127n, -56n, 18n]).alive === false, 'the holdout rule rejects 127 - 56 pi + 18 e on the printed digits');
  ok(sourceAlive(byLabel.get('5^(1/2)'), byLabel.get('cos(1/5*Pi)'), [1n, 1n, -5n]).alive === false, 'mutation test: changing one coefficient makes a live relation go red');
  const damagedRow = { ...byLabel.get('5^(1/2)') };
  damagedRow.digits = `${damagedRow.digits.slice(0, 20)}${damagedRow.digits[20] === '9' ? '8' : '9'}${damagedRow.digits.slice(21)}`;
  ok(sourceAlive(damagedRow, byLabel.get('cos(1/5*Pi)'), [1n, 1n, -4n]).alive === false, 'mutation test: damaging the twenty-first source digit makes a live relation go red');
  ok(crypto.createHash('sha256').update(recordText.replace('3.141592653589793', '3.141592653589794')).digest('hex') !== actualHash, 'mutation test: changing one digit of the record changes its SHA-256');

  /* --- G. the published grid ---------------------------------------- */
  note('G. recomputing all 105 published grid cells');
  const audit = JSON.parse(html.match(/<script type="application\/json" id="audit-data">([\s\S]*?)<\/script>/)[1]);
  ok(audit.precision.join(',') === PRECISIONS.join(','), 'the shipped precision grid is the documented one');
  ok(audit.height.join(',') === BOUNDS.map(String).join(','), 'the shipped coefficient grid is the documented one');
  ok(html.includes('γ = √(4/3); tolerance 10<sup>−(p−1)</sup>; 500 steps; working precision max(60,p+30)'), 'the page states the PSLQ convention this verifier implements');
  ok(html.includes('H = max(|c|,|a|,|b|) after gcd division and first-nonzero-positive sign'), 'the page states the coefficient convention this verifier implements');
  ok(html.includes('within half a last-place unit from each row, weighted by |a| and |b|'), 'the page states the holdout convention this verifier implements');
  ok(html.includes('xorshift32 seeded by FNV-1a of mode, row index, and label'), 'the page states the null convention this verifier implements');

  const grids = await computeGrids(rows);
  const byKey = new Map(grids.map((g) => [`${g.mode}:${g.p}`, g]));
  for (const p of PRECISIONS) {
    const cat = byKey.get(`catalogue:${p}`);
    for (const H of BOUNDS) {
      const mine = cat.cells[String(H)];
      const theirs = audit.catalogue[String(p)][String(H)];
      ok(mine.join(',') === theirs.join(','), `catalogue cell p=${p}, H=${H}: [${mine.join(', ')}] recomputed independently`);
    }
  }
  for (const p of PRECISIONS) {
    const sh = byKey.get(`shuffle:${p}`), rn = byKey.get(`random:${p}`);
    for (const H of BOUNDS) {
      ok(sh.cells[String(H)][0] === audit.shuffle[String(p)][String(H)] && rn.cells[String(H)][0] === audit.random[String(p)][String(H)],
        `null cells p=${p}, H=${H}: shuffle ${sh.cells[String(H)][0]} and random ${rn.cells[String(H)][0]} recomputed independently`);
    }
  }
  const expectedAlive = ['5^(1/2)|cos(1/5*Pi)|1,1,-4', 'Golden Ratio or 1/2+sqrt(5)/2|5^(1/2)|1,-2,1', 'Sierpinski|MasserGramain|0,1,-4'].sort();
  for (const p of PRECISIONS) {
    const cat = byKey.get(`catalogue:${p}`);
    ok(BOUNDS.every((H) => cat.cells[String(H)][0] === cat.cells[String(H)][1] + cat.cells[String(H)][2]), `p=${p}: candidates equal rejected plus alive in every cell`);
    ok(cat.alive.join(' ; ') === expectedAlive.join(' ; '), `p=${p}: the source-alive set is exactly the three named relations`);
    ok(cat.confirmedVectors.every((c, i) => c.got === CONFIRMED[i].q.join(',')), `p=${p}: PSLQ returns all four definition-confirmed vectors`);
    ok(BOUNDS.every((H) => cat.cells[String(H)][3] === 4), `p=${p}: the confirmed column is a recomputed four in every cell`);
    ok(BOUNDS.every((H, i) => i === 0 || cat.cells[String(H)][0] >= cat.cells[String(BOUNDS[i - 1])][0]), `p=${p}: the candidate count is monotone in the coefficient bound`);
  }
  const cat8 = byKey.get('catalogue:8').cells['100'];
  ok(cat8[0] > cat8[2] && cat8[2] > 0, 'the holdout is not vacuous: at eight digits and H=100 a few candidates survive and most do not');
  const totalDegenerate = grids.reduce((a, g) => a + g.degenerateExcluded, 0);
  ok(totalDegenerate > 0, `the degenerate-vector exclusion is not vacuous: it removed ${totalDegenerate} returned vectors across the grid`);
  note(`grid totals: ${grids.reduce((a, g) => a + g.returned, 0)} vectors returned across 369,138 searches`);

  /* --- H. mutation tests on the search itself ------------------------ */
  note('H. mutation tests on the search itself');
  const subset = rows.slice(0, 25);
  const baseline = gridColumn(subset, 12, 'catalogue');
  const damagedSubset = subset.map((r, i) => (i === 3 ? { ...r, digits: `${r.digits.slice(0, 9)}${r.digits[9] === '7' ? '2' : '7'}${r.digits.slice(10)}` } : r));
  ok(BOUNDS.some((H) => gridColumn(damagedSubset, 12, 'catalogue').cells[String(H)][0] !== baseline.cells[String(H)][0]), 'mutation test: flipping the tenth digit of one row changes the candidate counts');
  const nullBase = gridColumn(subset, 12, 'shuffle');
  ok(BOUNDS.some((H) => gridColumn(subset, 12, 'shuffle', { seedPrefix: 'shuffle-mutant' }).cells[String(H)][0] !== nullBase.cells[String(H)][0]), 'mutation test: changing the null seed string changes the null counts');
  ok(BOUNDS.some((H) => gridColumn(subset, 12, 'catalogue', { prec: 85 }).cells[String(H)][0] !== baseline.cells[String(H)][0]), 'mutation test: the stated working precision is load-bearing, raising it moves the counts');
  note('the published counts reproduce only at the stated working precision max(60,p+30); that is a declared convention, not a fact about the constants');

  /* --- I. the shipped page engine ------------------------------------ */
  note('I. executing the shipped page engine');
  const engineSource = (html.match(/<script id="pslq-engine">([\s\S]*?)<\/script>/) || [])[1];
  ok(Boolean(engineSource), 'the shipped page engine is present in the page');
  const makeEngine = (source, filename) => {
    const context = { globalThis: {}, Math, Number, Array, String, Error, JSON, Boolean, Object };
    vm.createContext(context);
    vm.runInContext(source, context, { filename });
    return context.globalThis.PSLQEngine;
  };
  const page = makeEngine(engineSource, 'pslq-page-engine.js');
  ok(Boolean(page) && ['pslq', 'bbpX', 'anchor', 'parseCatalogue', 'admitted', 'sourceValue', 'pair', 'truncate', 'quick', 'normalise'].every((k) => typeof page[k] === 'function'),
    'the shipped engine executes standalone and exposes its ten entry points');

  ok((engineSource.match(/function pslq\(/g) || []).length === 1
    && engineSource.includes('return pslq(values,1e-13,10000)') && engineSource.includes('pslq([1,x,y],1e-13,10000)'),
    'the anchor bench and the pair bench call one and the same shipped PSLQ, as the page says');
  ok(engineSource.includes('for(var k=0;k<32;k+=1)') && html.includes('32 terms per Xj'), 'the shipped series really sums the 32 terms the check panel declares');
  for (const [pass, label] of auditGateChecks(html)) ok(pass, label);
  const pageRows = page.parseCatalogue(island);
  ok(pageRows.length === rows.length && pageRows.every((r, i) => r.sign === rows[i].sign && r.digits === rows[i].digits && r.exp === rows[i].exp && r.label === rows[i].label),
    'the shipped parser decodes the record exactly as this verifier does');
  const relDiff = (a, b) => Math.abs(a - b) / Math.max(1e-300, Math.abs(b));
  ok(rows.every((r, i) => relDiff(page.sourceValue(pageRows[i]), decToNumber(sourceDec(r))) < 1e-14), 'the shipped source values agree with the exact decimals to binary64 accuracy');
  ok(PRECISIONS.every((p) => rows.every((r, i) => relDiff(page.admitted(pageRows[i], p), decToNumber(admittedDec(r, p))) < 1e-14)), 'the shipped admitted-digit rule agrees with exact truncation at every grid precision');
  for (let j = 1; j <= 8; j += 1) ok(relDiff(page.bbpX(j), fxNumber(X[j])) < 1e-14, `the shipped browser sum for X${j} agrees with the 160-place series`);
  const pageAnchor = page.anchor();
  ok(pageAnchor !== null && pageAnchor.relation.join(',') === PUBLISHED.join(','), 'the shipped engine returns the published anchor vector in binary64');
  ok(pageAnchor.relation.join(',') === anchorRun.relation.join(','), 'the shipped anchor agrees with the independent 170-digit PSLQ');
  ok(Math.abs(pageAnchor.residual) < 1e-13, 'the shipped anchor residual sits at binary64 noise level');
  for (let d = 5; d <= 15; d += 1) {
    const q = page.quick(d);
    const exact = fxNumber(127n * FXONE - 56n * truncPlaces(PI, d) * pow10(FXS - d) + 18n * truncPlaces(E1, d) * pow10(FXS - d), 25);
    ok(Math.abs(q.training - exact) < 1e-12, `the shipped admitted-digit residual agrees with exact truncation at ${d} places`);
  }
  // the browser evaluates the frozen vector on Math.PI and Math.E, so its full-value
  // residual is only good to about 1e-14; the page prints four figures, and that is
  // the precision at which it can be held to account
  const pageFull = page.quick(5).full, exactFull = fxNumber(fullResidual, 25);
  ok(Math.abs(pageFull - exactFull) < 1e-13, 'the shipped full-value residual agrees with the exact one within binary64 propagation');
  ok(pageFull.toExponential(4) === exactFull.toExponential(4), 'the shipped and exact residuals agree at the four figures the page actually prints');
  ok(page.truncate(Math.PI, 5) === 3.14159 && page.truncate(Math.E, 5) === 2.71828, 'the shipped truncation matches the documented rule');
  ok(page.normalise([4, -6, 8]).join(',') === primitive([4n, -6n, 8n]).join(',') && page.normalise([-2, 4, 6]).join(',') === primitive([-2n, 4n, 6n]).join(','), 'the shipped primitive-vector normalisation agrees with the exact one');

  const idx = (label) => pageRows.findIndex((r) => r.label === label);
  const spurious = page.pair(pageRows, idx('Pi'), idx('exp(1.0)'), 5);
  ok(spurious !== null && spurious.relation.length === 3, 'the shipped pair bench returns a vector for the pi and e preset at five admitted digits');
  const spuriousQ = spurious.relation.map((x) => BigInt(x));
  const rowPi = byLabel.get('Pi'), rowE = byLabel.get('exp(1.0)');
  const commonPlaces = Math.max(0, 4 - rowPi.exp, 4 - rowE.exp);
  const trainingExact = spuriousQ[0] * pow10(commonPlaces)
    + spuriousQ[1] * admittedInt(rowPi, 5) * pow10(commonPlaces + rowPi.exp - 4)
    + spuriousQ[2] * admittedInt(rowE, 5) * pow10(commonPlaces + rowE.exp - 4);
  ok(trainingExact === 0n, `the frozen vector [${spurious.relation.join(', ')}] is exactly zero on the five admitted digits, over the integers`);
  ok(Math.abs(spurious.training) < 1e-10, 'the shipped admitted-digit residual for that vector is at binary64 noise level');
  ok(sourceAlive(byLabel.get('Pi'), byLabel.get('exp(1.0)'), spuriousQ).alive === false, 'that same vector is rejected by the printed source digits, as the page reports');
  // the browser evaluates this in binary64, where 195 + 98 pi - 185 e cancels three
  // digits before the leading term, so it can be held to an absolute bound, not a
  // relative one, and to the four figures it prints
  const holdoutExact = fxNumber(spuriousQ[0] * FXONE + spuriousQ[1] * PI + spuriousQ[2] * E1, 25);
  ok(Math.abs(spurious.holdout - holdoutExact) < 1e-12, 'the shipped source residual for that vector agrees with the exact recomputation to binary64 cancellation');
  ok(spurious.holdout.toExponential(4) === holdoutExact.toExponential(4), 'the shipped and exact source residuals agree at the four figures the page prints');
  const knownPreset = page.pair(pageRows, idx('Golden Ratio or 1/2+sqrt(5)/2'), idx('5^(1/2)'), 5);
  ok(knownPreset !== null && knownPreset.relation.join(',') === '1,-2,1', 'the shipped pair bench recovers 1 - 2 phi + sqrt 5 at five admitted digits');
  ok(Math.abs(knownPreset.holdout) < 1e-15, 'its source residual sits at binary64 noise level, so the browser calls it numerically alive');
  ok(page.pair(pageRows, idx('Golden Ratio or 1/2+sqrt(5)/2'), idx('5^(1/2)'), 12) === null,
    'KNOWN LIMIT: at twelve admitted digits the binary64 browser PSLQ returns no vector for that pair; the preset uses five admitted digits');
  let sampled = 0, flagged = 0, flagOk = true;
  for (let i = 0; i < pageRows.length; i += 9) for (let j = i + 1; j < pageRows.length; j += 13) {
    const r = page.pair(pageRows, i, j, 5);
    sampled += 1;
    if (!r) continue;
    const deg = r.relation[1] === 0 || r.relation[2] === 0;
    if (deg) flagged += 1;
    if (r.degenerate !== deg) flagOk = false;
  }
  ok(sampled > 100 && flagOk, `the shipped degeneracy flag matches a = 0 or b = 0 on all ${sampled} sampled pairs`);
  ok(html.includes('Degenerate vectors with a = 0 or b = 0 are excluded'), 'the page discloses the degenerate-vector exclusion');

  const mutatedEngine = engineSource.replace('for(var k=0;k<32;k+=1)', 'for(var k=0;k<2;k+=1)');
  ok(mutatedEngine !== engineSource, 'the engine mutation target was found in the shipped source');
  const mutAnchor = makeEngine(mutatedEngine, 'pslq-page-engine-mutant.js').anchor();
  ok(mutAnchor === null || mutAnchor.relation.join(',') !== PUBLISHED.join(','), 'mutation test: truncating the shipped BBP sums to two terms stops the published vector returning');
  const mutatedTarget = engineSource.replace('values.push(Math.PI)', 'values.push(Math.PI*1.0000000001)');
  const mutAnchor2 = makeEngine(mutatedTarget, 'pslq-page-engine-mutant2.js').anchor();
  ok(mutAnchor2 === null || mutAnchor2.relation.join(',') !== PUBLISHED.join(','), 'mutation test: perturbing the shipped pi by 1e-10 stops the published vector returning');

  /* --- done ---------------------------------------------------------- */
  console.log(`1..${assertions}`);
  note(`anchor (${PUBLISHED.join(', ')}) reproduced at 170 working digits in ${anchorRun.steps} steps`);
  note(`grid: 35 cells x {catalogue, shuffle, random}, recomputed from ${recordedBytes} committed bytes`);
  note(`degenerate vectors excluded across the grid: ${totalDegenerate}, page-engine degenerate flags checked on ${sampled} pairs (${flagged} degenerate)`);
  note(`elapsed ${((Date.now() - t0) / 1000).toFixed(1)} s`);
}

if (!isMainThread && workerData && workerData.task === 'grid') {
  const workerRows = parseRecord(fs.readFileSync(DATA, 'utf8'));
  parentPort.postMessage(gridColumn(workerRows, workerData.p, workerData.mode));
} else {
  await main();
}
