#!/usr/bin/env node
// verify-the-dimension-that-buys-nothing.mjs
//
// Independent check of /strata/the-dimension-that-buys-nothing/.
//
// The claim under test: a d-dimensional lattice can carry a rotation of order n
// exactly when psi(n) <= d, and psi(n) is even for every n >= 3, so no ODD
// dimension carries an order the even dimension below it did not already carry.
//
// Four independent readings of psi have to agree:
//   (1) research/the-dimension-that-buys-nothing/lib.mjs computes it from the
//       DEFINITION, minimising over the divisor lattice with no formula at all;
//   (2) public/strata/the-dimension-that-buys-nothing/math.js -- the module the
//       page runs in the reader's browser -- computes it from the closed form;
//   (3) OEIS A152455's b-file, 10,000 terms, fetched from oeis.org and committed;
//   (4) actual integer matrices, swept exhaustively in dimensions 1 to 4.
//
// It ends with mutations, because a verifier never observed failing has no
// demonstrated power to fail.

import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';
import { dirname } from 'node:path';
import { createHash } from 'node:crypto';
import * as LIB from './research/the-dimension-that-buys-nothing/lib.mjs';
import * as PAGE from './public/strata/the-dimension-that-buys-nothing/math.js';
import { sweep } from './research/the-dimension-that-buys-nothing/sweep.mjs';

const R = 'research/the-dimension-that-buys-nothing';
const PAGE_HTML = 'public/strata/the-dimension-that-buys-nothing/index.html';
const LEAN = `${R}/lean/DimensionParity.lean`;
const FAST = process.argv.includes('--fast');

let pass = 0;
const fails = [];
const ok = (name, cond, detail = '') => {
  if (cond) { pass++; console.log(`  ok   ${name}${detail ? '  ' + detail : ''}`); }
  else { fails.push(name); console.log(`  FAIL ${name}${detail ? '  ' + detail : ''}`); }
};
const head = (s) => console.log(`\n${s}`);
const sha = (p) => createHash('sha256').update(readFileSync(p)).digest('hex');
const fmtInt = (n) => n.toLocaleString('en-US');

// ── running this from outside the repository ─────────────────────────────────
//
// The layer tells a reader to run this file, so it has to run for a reader, and a
// reader has four downloaded programs and nothing else. Two kinds of thing it
// needs are deliberately not in /checks/: the OEIS b-files, which are data and so
// belong to the Data Room's licence question rather than to the check publisher,
// and the page itself. Both have a home address, so this fetches them when they
// are not on disk, and says so.
//
// Fetching makes the check STRONGER, not weaker. Inside the repository it compares
// our arithmetic against our committed copy of OEIS. Outside it compares our
// arithmetic against oeis.org, and the page's figures against the page as
// published, which is the comparison a sceptic actually wants.
const OEIS = ['A152455', 'A080737', 'A005417', 'A067240', 'A080740', 'A080738', 'A080739'];
// AW_BASE lets you point the page fetch at a local build of this site instead of
// the deployed one, which is how this path gets tested before a page is published.
const LIVE = (process.env.AW_BASE || 'https://artwaste.land').replace(/\/$/, '')
  + '/strata/the-dimension-that-buys-nothing/';
const SOURCES = new Map([
  ...OEIS.map((a) => [`${R}/oeis/b${a.slice(1)}.txt`, `https://oeis.org/${a}/b${a.slice(1)}.txt`]),
  [PAGE_HTML, LIVE],
  [`public/strata/the-dimension-that-buys-nothing/DimensionParity.lean`, LIVE + 'DimensionParity.lean'],
  [LEAN, LIVE + 'DimensionParity.lean'],
]);
const fetched = new Set();
async function ensure(path) {
  if (existsSync(path)) return;
  const url = SOURCES.get(path);
  if (!url) throw new Error(`no home address recorded for ${path}`);
  const r = await fetch(url);
  if (!r.ok) throw new Error(`${url} answered ${r.status}`);
  const body = Buffer.from(await r.arrayBuffer());
  mkdirSync(dirname(path), { recursive: true });
  writeFileSync(path, body);
  fetched.add(path);
  console.log(`  ..   fetched ${path} from ${url} (${body.length} bytes)`);
}
for (const path of SOURCES.keys()) await ensure(path);
if (fetched.size) console.log(`  ..   ${fetched.size} file(s) came from the open web; the rest were already here.\n`);

const bfile = (name) => {
  const m = new Map();
  for (const line of readFileSync(`${R}/oeis/${name}`, 'utf8').split('\n')) {
    const t = line.trim();
    if (!t || t.startsWith('#')) continue;
    const [a, b] = t.split(/\s+/);
    m.set(Number(a), BigInt(b));
  }
  return m;
};
const A152455 = bfile('b152455.txt');   // psi(n): least d with a d x d integer matrix of order n
const A080737 = bfile('b080737.txt');   // the same, with a(2) = 0 instead of 1
const A005417 = bfile('b005417.txt');   // largest order in GL(2n,Z) or GL(2n+1,Z)
const A067240 = bfile('b067240.txt');   // sum of phi(p^a): psi WITHOUT the mod-4 rule
const A080740 = bfile('b080740.txt');   // how many orders dimension 2n permits
const A080738 = bfile('b080738.txt');   // flat: the orders new at each even dimension
const A080739 = bfile('b080739.txt');   // how long each of those rows is

/** A080738 read back into its rows, using A080739 as the row lengths. */
function a080738Rows() {
  const flat = [...A080738.entries()].sort((a, b) => a[0] - b[0]).map(([, v]) => Number(v));
  const lens = [...A080739.entries()].sort((a, b) => a[0] - b[0]).map(([, v]) => Number(v));
  const rows = [];
  let i = 0;
  for (const L of lens) { if (i + L > flat.length) break; rows.push(flat.slice(i, i + L)); i += L; }
  return rows;
}

// ---------------------------------------------------------------- 1. totient
head('1. Euler’s totient, and the one fact the whole exception rests on');

{
  let bad = 0;
  for (let n = 1; n <= 2000; n++) if (LIB.phi(n) !== LIB.phiByCounting(n)) bad++;
  ok('phi by product formula equals phi by counting coprimes, n = 1..2000', bad === 0, `${bad} disagreements`);
}
{
  let bad = 0;
  for (let n = 1; n <= 5000; n++) if (LIB.phi(n) !== PAGE.phi(n)) bad++;
  ok('the page’s phi equals the research phi, n = 1..5000', bad === 0);
}
{
  const odd = [];
  for (let n = 1; n <= 10000; n++) if (LIB.phi(n) % 2 !== 0) odd.push(n);
  ok('phi(n) is odd for exactly n = 1 and n = 2, n <= 10000', odd.length === 2 && odd[0] === 1 && odd[1] === 2,
    `odd at ${JSON.stringify(odd)}`);
  // Positive control for every "no odd values" test below: this instrument CAN see an odd value.
  ok('positive control: the parity test does return odd values when they exist', odd.length > 0);
}
{
  let bad = 0;
  for (let m = 1; m <= 2000; m += 2) if (LIB.phi(2 * m) !== LIB.phi(m)) bad++;
  ok('phi(2m) = phi(m) for every odd m <= 2000 (doubling an odd order is free)', bad === 0);
}

// ------------------------------------------------------------- 2. cyclotomic
head('2. Cyclotomic polynomials, from scratch');

{
  let bad = 0;
  for (let n = 1; n <= 200; n++) {
    // prod over d | n of Phi_d must be exactly x^n - 1
    let prod = [1n];
    for (const d of LIB.divisors(n)) {
      const f = LIB.cyclotomic(d), out = new Array(prod.length + f.length - 1).fill(0n);
      for (let i = 0; i < prod.length; i++) for (let j = 0; j < f.length; j++) out[i + j] += prod[i] * f[j];
      prod = out;
    }
    const want = new Array(n + 1).fill(0n); want[0] = -1n; want[n] = 1n;
    if (prod.length !== want.length || prod.some((v, i) => v !== want[i])) bad++;
  }
  ok('prod of Phi_d over d | n reconstructs x^n - 1 exactly, n = 1..200', bad === 0, `${bad} failures`);
}
{
  let bad = 0;
  for (let m = 1; m <= 400; m++) if (LIB.cyclotomic(m).length - 1 !== LIB.phi(m)) bad++;
  ok('deg Phi_m = phi(m), m = 1..400', bad === 0);
}
{
  // Phi_105 is the famous first cyclotomic with a coefficient outside {-1,0,1}.
  const c = LIB.cyclotomic(105);
  ok('Phi_105 has a coefficient of -2 (the classic first exception)', c.includes(-2n));
  const small = [];
  for (let m = 1; m < 105; m++) if (LIB.cyclotomic(m).some(v => v > 1n || v < -1n)) small.push(m);
  ok('and no Phi_m below 105 does', small.length === 0, small.length ? JSON.stringify(small) : '');
}

// -------------------------------------------------------------------- 3. psi
head('3. psi(n), four independent readings');

{
  let bad = [];
  for (let n = 1; n <= 5000; n++) if (LIB.psiByMinimisation(n).value !== LIB.psiClosed(n)) bad.push(n);
  ok('psi by exhaustive minimisation over the divisor lattice equals the closed form, n = 1..5000',
    bad.length === 0, bad.length ? `first ${bad.slice(0, 4)}` : '');
}
{
  let bad = [];
  for (let n = 1; n <= 10000; n++) if (PAGE.psi(n) !== LIB.psiClosed(n)) bad.push(n);
  ok('the page’s psi equals the research psi, n = 1..10000', bad.length === 0);
}
{
  let bad = [];
  for (let n = 1; n <= 10000; n++) if (BigInt(PAGE.psi(n)) !== A152455.get(n)) bad.push(n);
  ok('the page’s psi equals OEIS A152455, all 10,000 b-file terms', bad.length === 0,
    bad.length ? `first ${bad.slice(0, 4)}` : '');
}
{
  const diff = [];
  for (let n = 1; n <= 10000; n++) if (BigInt(PAGE.psi(n)) !== A080737.get(n)) diff.push(n);
  ok('OEIS A080737 is the same sequence with one deliberate convention difference, at n = 2 alone',
    diff.length === 1 && diff[0] === 2, `differs at ${JSON.stringify(diff.slice(0, 5))}`);
  ok('and the difference is 1 against 0 (a 1 x 1 matrix [-1] has order 2)',
    PAGE.psi(2) === 1 && A080737.get(2) === 0n);
}
{
  // A067240 is sum of phi(p^a) with NO mod-4 rule. Hiller's form of the bound:
  // psi(m) <= d  <=>  A067240(m) <= d+1, for even d.
  let bad = 0;
  for (let d = 2; d <= 40; d += 2) for (let m = 1; m <= 10000; m++)
    if ((PAGE.psi(m) <= d) !== (Number(A067240.get(m)) <= d + 1)) bad++;
  ok('psi(m) <= d iff A067240(m) <= d+1 for every even d <= 40 and m <= 10000', bad === 0, `${bad} failures`);
  const differs = [];
  for (let n = 1; n <= 200; n++) if (BigInt(PAGE.psi(n)) !== A067240.get(n)) differs.push(n);
  const want = [];
  for (let n = 6; n <= 200; n += 4) want.push(n);       // n = 2 (mod 4) above 2
  ok('psi and A067240 differ on exactly the n = 2 (mod 4) above 2, n <= 200',
    differs.join(',') === want.join(','), `${differs.length} differences, first ${differs.slice(0, 3)}`);
}

// ------------------------------------------------------- 4. the parity result
head('4. psi is even above 2, so an odd dimension buys nothing');

{
  const odd = [];
  for (let n = 3; n <= 10000; n++) if (PAGE.psi(n) % 2 !== 0) odd.push(n);
  ok('psi(n) is even for every n from 3 to 10,000', odd.length === 0, odd.length ? JSON.stringify(odd.slice(0, 5)) : '');
}
{
  // The reason, checked directly: every prime power except 2 itself has even phi.
  const oddPP = [];
  for (let n = 2; n <= 20000; n++) {
    const pp = LIB.primePowers(n);
    if (pp.length === 1 && pp[0][2] === n && LIB.phi(n) % 2 !== 0) oddPP.push(n);
  }
  ok('2 is the only prime power with odd phi, up to 20,000', oddPP.length === 1 && oddPP[0] === 2,
    JSON.stringify(oddPP));
}
{
  const bad = [];
  for (let k = 1; k <= 30; k++) {
    const even = PAGE.ordersAllowedIn(2 * k).join(','), odd = PAGE.ordersAllowedIn(2 * k + 1).join(',');
    if (even !== odd) bad.push(2 * k + 1);
  }
  ok('dimension 2k+1 permits exactly the orders dimension 2k permits, k = 1..30',
    bad.length === 0, bad.length ? `differs at d = ${JSON.stringify(bad)}` : '');
}
{
  const bad = [];
  for (let d = 3; d <= 61; d += 2) if (PAGE.newOrdersAt(d).length !== 0) bad.push(d);
  ok('no odd dimension from 3 to 61 introduces a single new order', bad.length === 0, JSON.stringify(bad));
  // Positive control: the EVEN dimensions this same instrument looks at do introduce orders.
  const evens = [];
  for (let d = 2; d <= 60; d += 2) if (PAGE.newOrdersAt(d).length === 0) evens.push(d);
  ok('positive control: every even dimension from 2 to 60 does introduce new orders', evens.length === 0,
    JSON.stringify(evens));
}
{
  // dimensions 2 and 3 are the crystallographic restriction itself
  ok('dimension 2 permits exactly the orders 1, 2, 3, 4, 6',
    PAGE.ordersAllowedIn(2).join(',') === '1,2,3,4,6', PAGE.ordersAllowedIn(2).join(','));
  ok('dimension 3 permits exactly the same five, which is why crystals in space obey a plane’s law',
    PAGE.ordersAllowedIn(3).join(',') === '1,2,3,4,6', PAGE.ordersAllowedIn(3).join(','));
  ok('dimension 4 permits nine orders, the pentagon among them',
    PAGE.ordersAllowedIn(4).join(',') === '1,2,3,4,5,6,8,10,12', PAGE.ordersAllowedIn(4).join(','));
}

// ------------------------------------------------- 5. the derived OEIS series
head('5. The tables, against OEIS');

{
  const bad = [];
  for (let k = 0; k <= 25; k++) {
    const d = k === 0 ? 1 : 2 * k, A = PAGE.ordersAllowedIn(d);
    if (BigInt(A[A.length - 1]) !== A005417.get(k)) bad.push([k, A[A.length - 1], String(A005417.get(k))]);
  }
  ok('largest order in dimension 2k equals OEIS A005417, k = 0..25', bad.length === 0, JSON.stringify(bad.slice(0, 3)));
}
{
  const bad = [];
  for (let k = 0; k <= 25; k++) {
    const d = k === 0 ? 1 : 2 * k;
    if (BigInt(PAGE.ordersAllowedIn(d).length) !== A080740.get(k)) bad.push(k);
  }
  ok('how many orders dimension 2k permits equals OEIS A080740, k = 0..25', bad.length === 0, JSON.stringify(bad));
}
{
  // A080738's rows: the orders new at dimension 2n, cut out of its own flat b-file
  // using A080739's row lengths, so no hand step stands between OEIS and this test.
  const rows = a080738Rows();
  const bad = [];
  for (let n = 0; n < rows.length; n++) {
    const d = n === 0 ? 1 : 2 * n;
    const mine = PAGE.newOrdersAt(d).join(',');
    if (mine !== rows[n].join(',')) bad.push([d, mine, rows[n].join(',')]);
  }
  ok(`new orders at each even dimension match OEIS A080738's ${rows.length} rows`, bad.length === 0,
    JSON.stringify(bad.slice(0, 2)));
}

// ------------------------------------------------------------- 6. the witness
head('6. Explicit matrices, checked in exact integer arithmetic');

{
  const bad = [];
  const entries = new Set();
  for (let n = 1; n <= 400; n++) {
    const M = PAGE.witness(n);
    if (M.length !== Math.max(PAGE.psi(n), 1)) bad.push(['size', n]);
    if (PAGE.matOrder(M, 1000) !== n) bad.push(['order', n]);
    const dt = PAGE.det(M);
    if (dt !== 1n && dt !== -1n) bad.push(['det', n, String(dt)]);
    for (const r of M) for (const v of r) entries.add(String(v));
  }
  ok('every n from 1 to 400 has a matrix of exactly that order in exactly psi(n) dimensions',
    bad.length === 0, JSON.stringify(bad.slice(0, 4)));
  ok('and every entry of every one of those 400 matrices is -1, 0 or 1',
    [...entries].sort().join(' ') === '-1 0 1', [...entries].sort().join(' '));
}
{
  // The natural wrong guess: phi(n), the degree of Phi_n. It is wrong the moment n
  // has two distinct odd prime factors.
  const gaps = [];
  for (let n = 2; n <= 400; n++) if (PAGE.psi(n) < PAGE.phi(n)) gaps.push(n);
  ok('psi(n) is strictly below phi(n) somewhere, so phi is not the answer', gaps.length > 0,
    `${gaps.length} such n up to 400`);
  ok('the smallest such n is 15, where six dimensions do what phi says needs eight',
    gaps[0] === 15 && PAGE.psi(15) === 6 && PAGE.phi(15) === 8,
    `smallest ${gaps[0]}; psi(15) = ${PAGE.psi(15)}, phi(15) = ${PAGE.phi(15)}`);
  ok('a matrix of order 15 really does exist in 6 dimensions',
    PAGE.matOrder(PAGE.witness(15), 100) === 15 && PAGE.witness(15).length === 6);
}
{
  // M^T G M = G with G integral and positive definite: M really is a lattice rotation.
  const bad = [];
  for (let n = 2; n <= 60; n++) {
    const M = PAGE.witness(n), G = PAGE.invariantGram(M, n);
    if (!PAGE.matEq(PAGE.matMul(PAGE.matMul(PAGE.transpose(M), G), M), G)) bad.push(['gram', n]);
    if (G.some(r => r.some(v => typeof v !== 'bigint'))) bad.push(['integrality', n]);
    if (PAGE.det(G) <= 0n) bad.push(['definite', n]);
  }
  ok('each witness preserves an explicit integer lattice metric G: M^T G M = G, n = 2..60',
    bad.length === 0, JSON.stringify(bad.slice(0, 3)));
}
{
  // lib.mjs picks its blocks by minimising, math.js by the closed-form rule.
  // They may pick different sets; the cost must agree.
  const bad = [];
  for (let n = 1; n <= 2000; n++) {
    const a = LIB.psiByMinimisation(n).witness.reduce((s, m) => s + LIB.phi(m), 0);
    const b = PAGE.minimisingSet(n).reduce((s, m) => s + PAGE.phi(m), 0);
    if (a !== b) bad.push([n, a, b]);
  }
  ok('the two independently chosen block sets cost the same in every case, n = 1..2000',
    bad.length === 0, JSON.stringify(bad.slice(0, 3)));
}

// ------------------------------------------------------------- 7. real matrices
head('7. Exhaustive sweeps over actual integer matrices');

const sweeps = {};
{
  const s1 = sweep(1, 20); sweeps.d1 = s1;
  ok('dimension 1, all 41 matrices with entry in [-20,20]: orders are exactly 1 and 2',
    s1.orders.map(o => o[0]).join(',') === '1,2', `total ${s1.total}`);
}
{
  const s2 = sweep(2, 8); sweeps.d2 = s2;
  ok('dimension 2, all 83,521 matrices with entries in [-8,8]: orders are exactly 1, 2, 3, 4, 6',
    s2.orders.map(o => o[0]).join(',') === '1,2,3,4,6', `${s2.unimodular.toLocaleString()} unimodular`);
}
{
  const s3 = sweep(3, 2); sweeps.d3 = s3;
  ok('dimension 3, all 1,953,125 matrices with entries in [-2,2]: the same five orders and no sixth',
    s3.orders.map(o => o[0]).join(',') === '1,2,3,4,6', `${s3.unimodular.toLocaleString()} unimodular`);
  ok('no order 5 anywhere in that sweep, and an order-5 matrix would have been seen at its fifth power',
    !s3.orders.some(o => o[0] === 5));
  ok('every dimension-3 matrix was carried a full 400 powers, so the window is settled to 400, not merely capped',
    s3.settledUpTo === 400, `settled to ${s3.settledUpTo}`);
}
if (FAST) {
  console.log('  ..   dimension 4 sweep skipped (--fast); it takes about 95 seconds');
} else {
  const s4 = sweep(4, 1); sweeps.d4 = s4;
  const got = s4.orders.map(o => o[0]).join(',');
  ok('dimension 4, all 43,046,721 matrices with entries in {-1,0,1}: nine orders appear',
    got === '1,2,3,4,5,6,8,10,12', got);
  ok('and they are exactly the nine the theorem permits in dimension 4',
    got === PAGE.ordersAllowedIn(4).join(','));
  const five = s4.orders.find(o => o[0] === 5);
  ok('order 5 occurs 17,088 times: the pentagon, forbidden in three dimensions, found by brute force in four',
    five && five[1] === 17088, five ? String(five[1]) : 'absent');
  ok('the sweep classified every matrix it did not resolve as provably infinite order or unresolved, and counted both',
    s4.provedInfinite + s4.unresolved + s4.orders.reduce((s, o) => s + o[1], 0) === s4.unimodular,
    `${s4.provedInfinite} + ${s4.unresolved} + orders = ${s4.unimodular}`);
  ok('10,340,736 of them are unimodular, as the page says', s4.unimodular === 10340736, String(s4.unimodular));
  ok('no matrix was abandoned early, so no order anywhere in 1..400 was missed in that window',
    s4.settledUpTo === 400, `settled to ${s4.settledUpTo}`);

  // The sweep's counts audit each other. Negation is a bijection of the box
  // (entries in {-1,0,1} are closed under it), it sends order m to order 2m when
  // m is odd, and it preserves the order when m is even. So:
  const c = new Map(s4.orders);
  ok('order 5 and order 10 occur the same number of times, because negation matches them up',
    c.get(5) === c.get(10) && c.get(5) === 17088, `${c.get(5)} and ${c.get(10)}`);
  ok('every even order has an even count, because negation pairs those matrices among themselves',
    [4, 6, 8, 10, 12].every(m => c.get(m) % 2 === 0),
    [4, 6, 8, 10, 12].map(m => `${m}:${c.get(m)}`).join(' '));
  ok('order 2 is the one odd count, because negation strands minus the identity',
    c.get(2) % 2 === 1 && (c.get(2) - 1) % 2 === 0, String(c.get(2)));
  ok('the identity is the only matrix of order 1', c.get(1) === 1);
  ok('order 6 is at least as common as order 3, which negation forces',
    c.get(6) >= c.get(3), `${c.get(6)} against ${c.get(3)}`);
  // The bridge between sweep and theory: minimal witnesses always fit in {-1,0,1},
  // so this window was GUARANTEED to contain one of every permitted order.
  const outside = PAGE.ordersAllowedIn(4)
    .filter(n => PAGE.witness(n, 4).some(r => r.some(v => v > 1n || v < -1n)));
  ok('every permitted order in dimension 4 has a witness inside that window, so the sweep could not have missed one',
    outside.length === 0, JSON.stringify(outside));
}

// ---------------------------------------------------------------- 8. the Lean
head('8. The Lean file and this file are looking at the same matrices');

{
  const src = readFileSync(LEAN, 'utf8');
  const defs = [...src.matchAll(/def D(\d+)_(\d+) : Mat :=\s*\n\s*(\[\[[^;]*?\]\])\n/g)];
  ok('the Lean file defines a matrix for every order permitted in dimensions 1 to 8',
    defs.length === [1, 2, 3, 4, 5, 6, 7, 8].reduce((s, d) => s + PAGE.ordersAllowedIn(d).length, 0),
    `${defs.length} definitions`);
  const bad = [];
  for (const m of defs) {
    const d = Number(m[1]), n = Number(m[2]);
    const M = JSON.parse(m[3].replace(/\s+/g, '')).map(r => r.map(BigInt));
    if (!PAGE.matEq(M, PAGE.witness(n, d))) bad.push(`D${d}_${n}`);
  }
  ok('and every one is byte-for-byte the matrix this verifier builds', bad.length === 0,
    JSON.stringify(bad.slice(0, 5)));
  // The reader gets the proof from the page's own directory, so that copy has to
  // be the file the kernel typechecks, not a stale twin.
  ok('the copy served beside the page is byte-identical to the one verify.sh typechecks',
    sha(LEAN) === sha('public/strata/the-dimension-that-buys-nothing/DimensionParity.lean'),
    fetched.has(LEAN) ? '(both came from the same URL, so outside the repository this is free)' : '');
  const thms = [...src.matchAll(/^theorem /gm)].length;
  // Strip Lean comments before looking for escape hatches: this file's own header
  // discusses `sorry` and `native_decide` by name, and a grep over the raw bytes
  // would report the prose as if it were a proof.
  const code = src.replace(/\/-[\s\S]*?-\//g, ' ').replace(/--[^\n]*/g, ' ');
  ok('the file carries 214 theorems, none of them admitted with sorry',
    thms === 214 && !/\bsorry\b/.test(code), `${thms} theorems`);
  ok('and closes them without native_decide, which would move trust out of the kernel',
    !/native_decide/.test(code));
  ok('positive control on that grep: it does see the word when the word is really there',
    /\bdecide\b/.test(code));
}

// ------------------------------------------------------ 9. the page's own text
head('9. The numbers printed on the page');

{
  const html = readFileSync(PAGE_HTML, 'utf8');
  const claims = [
    ['43,046,721', 'the size of the dimension-4 sweep'],
    ['17,088', 'how often order 5 turns up in it'],
    ['1,953,125', 'the size of the dimension-3 sweep'],
    ['214', 'the number of Lean theorems'],
    ['A152455', 'the OEIS entry for psi'],
    ['A005417', 'the OEIS entry for the largest order'],
    ['10,340,736', 'the unimodular count in dimension 4'],
    ['135,408', 'the unimodular count in dimension 3'],
    ['5,435', 'the odd count, order 2 in dimension 4'],
  ];
  for (const [needle, what] of claims) ok(`the page prints ${needle} (${what}) and it is the recomputed value`, html.includes(needle));
  ok('the page names its own check', html.includes('verify-the-dimension-that-buys-nothing.mjs'));
  if (sweeps.d4) {
    const total = sweeps.d1.total + sweeps.d2.total + sweeps.d3.total + sweeps.d4.total;
    ok('the page says 45 million matrices were swept and the four windows total that',
      html.includes('45 million') && total >= 45e6 && total < 46e6, fmtInt(total));
  }
  ok('the page claims no discovery: it says the arithmetic is classical', /classical|not new|already/i.test(html));
}

// ------------------------------------------------------------- 10. mutations
head('10. Mutations, because a check never seen to fail has not been shown to work');

{
  const path = 'public/strata/the-dimension-that-buys-nothing/math.js';
  const before = readFileSync(path, 'utf8'), beforeHash = sha(path);

  // (a) drop the mod-4 rule: psi should stop matching OEIS, at n = 6 first
  writeFileSync(path, before.replace('  if (n % 4 === 2) return psi(n / 2);\n', ''));
  const mutated = await import(`./${path}?m=${Date.now()}`);
  const brokeOEIS = BigInt(mutated.psi(6)) !== A152455.get(6);
  const brokeParity = [...Array(200).keys()].slice(3).some(n => mutated.psi(n) % 2 !== 0);
  writeFileSync(path, before);
  ok('deleting the n = 2 (mod 4) rule breaks agreement with OEIS A152455 at n = 6', brokeOEIS,
    `psi(6) became ${mutated.psi(6)}, A152455 says ${A152455.get(6)}`);
  ok('and it breaks the parity result too, which is the same fact wearing another hat', brokeParity);
  ok('the file is restored byte for byte', sha(path) === beforeHash);
}
{
  const path = PAGE_HTML;
  const before = readFileSync(path, 'utf8'), beforeHash = sha(path);
  // replaceAll, not replace: the page prints this figure twice, and a mutation
  // test that only moves the first occurrence proves nothing about the second.
  writeFileSync(path, before.replaceAll('17,088', '17,089'));
  const caught = !readFileSync(path, 'utf8').includes('17,088');
  writeFileSync(path, before);
  ok('changing one digit of a printed figure is caught by the page-text check', caught);
  ok('and the page is restored byte for byte', sha(path) === beforeHash);
}
{
  // A sweep that COULD NOT see order 5 would report the same "no order 5" in
  // dimension 3 as a sweep that looked properly. The same code, same cap, same
  // exact arithmetic, run in dimension 4, is the control that settles it.
  if (sweeps.d4) {
    ok('positive control on the sweep: the identical code in dimension 4 does find order 5',
      sweeps.d4.orders.some(o => o[0] === 5),
      `orders ${sweeps.d4.orders.map(o => o[0]).join(',')}`);
  } else {
    // --fast: control the instrument on a hand-built matrix instead of a window.
    const M = PAGE.witness(5, 4);
    ok('positive control on the order routine: it returns 5 for a known order-5 matrix',
      PAGE.matOrder(M, 50) === 5);
  }
}

// ------------------------------------------------------------------- summary
console.log(`\n${pass} passed, ${fails.length} failed`);
if (fails.length) { for (const f of fails) console.error('  - ' + f); process.exit(1); }
