#!/usr/bin/env node
// Verifier for "The Square Root of the Payment System".
//
//   node verify-the-square-root-of-the-payment-system.mjs            run all checks
//   node verify-the-square-root-of-the-payment-system.mjs --mutate   also run the
//                                                                    corruption experiments
//
// What this is: the page's evidence that it is not lying. It recomputes, from
// scratch, every kind of number the page displays, through code paths written
// independently of the page's inline script, and it exits non-zero if any
// check fails or if it somehow ran zero checks.
//
// Independence, stated plainly:
//   - The ANCHORS are independent of any implementation: the gross identity
//     k*n*(n-1)*xbar is an algebraic identity; the zero-sum of net positions is
//     an algebraic invariant; the Monte Carlo anchor compares against the
//     ANALYTIC quantised mean of the cent draw with a bound derived from the
//     sampled standard deviation; and the fit machinery is tested on constructed
//     data with a known exponent and on a hand-worked 3-point least squares
//     problem whose answer is the rational 3/2.
//   - The RNG is cross-checked bit-for-bit against a second, locally written
//     implementation of the published mulberry32 algorithm.
//   - Net positions and gross totals are recomputed by a second method inside
//     this file (index DECODING instead of forward enumeration; reverse
//     chunked summation instead of a forward running sum) and must agree
//     exactly, since everything is integer cents.
//
// Reads the SOURCE TREE ONLY (this directory and ../../public/strata/...).
// It never reads a build or dist directory. --mutate corrupts TEMP COPIES in a
// system temp dir, asserts the bytes actually changed, asserts the checks then
// fail, and deletes the copies; the source tree is never modified.
//
// TRANSPORT NOTE, and why there is not a single backslash-n or backslash-r
// sequence in any string or regex literal below: the delivery channel corrupts
// the two-character newline escape into a REAL line break, which turns the
// affected string or regex literal into a syntax error (an earlier draft died
// at compile time inside section(), before a single check ran). Every newline
// this file needs is built from LF = String.fromCharCode(10), and the CONFIG
// extraction is a brace scan rather than a regex carrying a negated newline class.

import { readFileSync, mkdtempSync, writeFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { pathToFileURL, fileURLToPath } from 'node:url';
import * as engine from './engine.mjs';

const HERE = path.dirname(fileURLToPath(import.meta.url));
const PAGE_PATH = path.resolve(HERE, '../../public/strata/the-square-root-of-the-payment-system/index.html');
const ENGINE_PATH = path.resolve(HERE, 'engine.mjs');
const BATTERY_PATH = path.resolve(HERE, 'battery.json');

// ── harness ──────────────────────────────────────────────────────────────
let pass = 0, fail = 0;
const failLines = [];
function report(name, ok, detail) {
  if (ok) { pass++; console.log('  ok  ' + name); }
  else {
    fail++;
    const line = name + (detail ? ' :: ' + detail : '');
    failLines.push(line);
    console.log('FAIL  ' + line);
  }
}
const LF = String.fromCharCode(10);
function section(t) { console.log(LF + '== ' + t + ' =='); }
// Sandboxed counter for mutation trials: failures there are EXPECTED.
function trial(fn) { let p = 0, f = 0; const chk = (n, ok, d) => { if (ok) p++; else f++; }; fn(chk); return { p, f }; }

// ── small pure helpers, local copies (tested FIRST, by hand-worked cases) ─
function mulberry32Local(seed) {
  let a = seed | 0;
  return function () {
    a |= 0; a = (a + 0x6D2B79F5) | 0;
    let t = Math.imul(a ^ (a >>> 15), 1 | a);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}
function centDrawLocal(u) { return Math.ceil(-Math.log(1 - u) * 100); }
function rngSeqLocal(seed, n) { const r = mulberry32Local(seed); const o = []; for (let i = 0; i < n; i++) o.push(r()); return o; }
// Plain least squares on RAW values, for the hand-worked rational case and for
// computing the exact-law slope expectation over the sweep design.
function plainOLS(pts) {
  const n = pts.length; let sx = 0, sy = 0, sxx = 0, sxy = 0;
  for (const [x, y] of pts) { sx += x; sy += y; sxx += x * x; sxy += x * y; }
  const slope = (n * sxy - sx * sy) / (n * sxx - sx * sx);
  return { slope, intercept: (sy - slope * sx) / n };
}
function close(a, b, eps) { return Math.abs(a - b) <= eps; }
function arrEq(a, b) { return a.length === b.length && a.every((v, i) => v === b[i]); }
function arrClose(a, b, eps) { return a.length === b.length && a.every((v, i) => close(v, b[i], eps)); }
function deepEq(a, b) { return JSON.stringify(a) === JSON.stringify(b); }
function throws(fn) { try { fn(); return false; } catch (e) { return true; } }
// Replicates the page's sweep geometry (log-spaced, deduped, clamped).
function logspace(lo, hi, m) {
  const out = []; const l0 = Math.log(lo), l1 = Math.log(hi);
  for (let i = 0; i < m; i++) {
    let n = Math.round(Math.exp(l0 + (l1 - l0) * i / (m - 1)));
    if (n < lo) n = lo;
    if (out[out.length - 1] !== n) out.push(n);
  }
  return out;
}
// SECOND METHOD for net positions: decode (i,j) from the flat index instead of
// replaying the enumeration order. Catches layout/ordering bugs.
function decodePair(p, n, k) {
  const i = Math.floor(p / ((n - 1) * k));
  const rem = p - i * (n - 1) * k;
  const jj = Math.floor(rem / k);
  const j = jj < i ? jj : jj + 1;
  return [i, j];
}

// ── config extraction from the page ──────────────────────────────────────
// Written as a marker-plus-brace-scan rather than a regex ON PURPOSE: the
// obvious regex, /[^\r
// ]/, carries exactly the escape sequences this delivery
// channel corrupts into real line breaks (and a regex literal cannot survive
// being split across lines). The CONFIG assignment is flat JSON with no nested
// braces, so the slice from the first '{' to the first '}' after the marker is
// exact for this page, and JSON.parse still rejects anything malformed.
function extractConfig(html) {
  const marker = 'var CONFIG = ';
  const at = html.indexOf(marker);
  if (at === -1) return null;
  const open = html.indexOf('{', at);
  const close = html.indexOf('}', open);
  if (open === -1 || close === -1) return null;
  try { return JSON.parse(html.slice(open, close + 1)); } catch (e) { return null; }
}

// ── check groups (factored so --mutate can aim them at corrupted copies) ──
function helperUnitTests(chk) {
  const ols = plainOLS([[0, 0], [1, 1], [2, 3]]);
  chk('plainOLS slope on (0,0)(1,1)(2,3) is the rational 3/2', close(ols.slope, 1.5, 1e-12), String(ols.slope));
  chk('plainOLS intercept on the same points is -1/6', close(ols.intercept, -1 / 6, 1e-12), String(ols.intercept));
  chk('centDrawLocal(0) is 0 cents', centDrawLocal(0) === 0);
  chk('centDrawLocal(0.5) is ceil(100 ln 2) = 70 cents', centDrawLocal(0.5) === 70, String(centDrawLocal(0.5)));
  chk('centDrawLocal is nondecreasing in u (sampled)', (() => {
    let prev = -1;
    for (let i = 0; i <= 200; i++) { const v = centDrawLocal(i / 200 * 0.999); if (v < prev) return false; prev = v; }
    return true;
  })());
  chk('mulberry32Local stays in [0,1) over 1000 draws', (() => {
    const r = mulberry32Local(7);
    for (let i = 0; i < 1000; i++) { const v = r(); if (!(v >= 0 && v < 1)) return false; }
    return true;
  })());
  chk('mulberry32Local is deterministic in the seed', deepEq(rngSeqLocal(7, 50), rngSeqLocal(7, 50)));
  chk('mulberry32Local separates nearby seeds', !deepEq(rngSeqLocal(7, 50), rngSeqLocal(8, 50)));
}

function rngCrossCheck(chk) {
  for (const seed of [0, 1, 20260721, 2147483647]) {
    const rl = mulberry32Local(seed), re = engine.makeRng(seed);
    let same = true;
    for (let i = 0; i < 5000; i++) { if (rl() !== re()) { same = false; break; } }
    chk('engine RNG matches the published mulberry32 stream bit-for-bit (seed ' + seed + ')', same);
  }
  const s = engine.rngSample(123456789, 64);
  chk('rngSample returns exactly count values', s.length === 64);
  chk('rngSample values all lie in [0,1)', s.every(v => v >= 0 && v < 1));
  chk('rngSample equals a manual loop over makeRng', deepEq(s, (() => { const r = engine.makeRng(123456789); const o = []; for (let i = 0; i < 64; i++) o.push(r()); return o; })()));
  chk('rngSample rejects a negative count', throws(() => engine.rngSample(1, -1)));
}

function centDrawChecks(chk) {
  chk('engine centDraw(0) is 0', engine.centDraw(0) === 0);
  chk('engine centDraw(0.5) is 70', engine.centDraw(0.5) === 70);
  chk('engine centDraw near 1 stays finite', isFinite(engine.centDraw(0.9999999999999999)));
  chk('engine centDraw rejects u = 1', throws(() => engine.centDraw(1)));
  chk('engine centDraw rejects u < 0', throws(() => engine.centDraw(-0.1)));
  const rl = mulberry32Local(31337);
  let same = true;
  for (let i = 0; i < 2000; i++) { const u = rl(); if (engine.centDraw(u) !== centDrawLocal(u)) { same = false; break; } }
  chk('engine centDraw matches the local formula on 2000 samples', same);
}

function handworkChecks(chk, mod) {
  // Hand-worked 3-bank economy, one payment per ordered pair, laid out in the
  // contract order: 0->1:300, 0->2:100, 1->0:200, 1->2:50, 2->0:400, 2->1:600.
  //
  // Worked on paper against that layout (README, anchor 3):
  //   gross 1650; outflows [400, 250, 1000];
  //   nets: bank 0 = (200+400) - (300+100) = +200
  //         bank 1 = (300+600) - (200+50)  = +650
  //         bank 2 = (100+50) - (400+600)  = -850
  //   settlement 850 (sum of the positive positions).
  //   Victim 2, S=150: gross cut 150/1000 = 0.15, losses [60, 90, 0], HHI 0.52;
  //     net obligation 850, unpaid 150 shared on claims 200 and 650:
  //     [150*200/850, 150*650/850, 0] = [600/17, 1950/17, 0],
  //     HHI (4/17)^2 + (13/17)^2 = 185/289.
  //   Victims 0 AND 1 are net receivers: net-regime loss exactly zero at any
  //     shortfall; gross still loses min(S, outflow).
  //   Victim 2, S=10000 (the only net payer): gross capped at the 1000 outflow;
  //     net capped at the 850 obligation, paid in full and shared pro rata on
  //     claims 200 and 650, i.e. losses [200, 650, 0].
  //
  // Correction, recorded so nobody re-breaks this: an earlier draft of these
  // expectations carried nets (+200, +100, -300) and settlement 300. Those
  // figures cannot arise from ANY economy with these outflows: they force
  // inflows [600, 350, 700], and with outflows [400, 250, 1000] the payment
  // equations then have no non-negative solution (the 0->1 payment is forced
  // below zero). The amounts array is canonical; the expectations below were
  // recomputed from it by hand and agree with the engine exactly.
  // Second correction, same discipline: an earlier draft also expected victim
  // 1's S=10000 shortfall to land on a 650 net obligation held by bank 0 alone.
  // With nets (+200, +650, -850), bank 1's net obligation is max(0, -650) = 0:
  // bank 1 is a net receiver, so no implementation could ever produce the old
  // expectation. The cap test for the NET regime belongs to victim 2.
  const am = [300, 100, 200, 50, 400, 600];
  chk('hand-worked gross is 1650', mod.grossTotal(am) === 1650, String(mod.grossTotal(am)));
  const nets = mod.netPositions(am, 3);
  chk('hand-worked nets are [+200, +650, -850]', arrEq(nets, [200, 650, -850]), JSON.stringify(nets));
  chk('hand-worked net settlement is 850', mod.netSettlement(nets) === 850, String(mod.netSettlement(nets)));
  chk('hand-worked outflows are [400, 250, 1000]', arrEq(mod.grossOutflows(am, 3), [400, 250, 1000]));
  const lit = { n: 3, k: 1, amounts: am, nets, outflows: [400, 250, 1000] };

  const a = mod.defaultSplit(lit, 2, 150);
  chk('hand split, victim 2 S=150: gross losses [60, 90, 0]', arrClose(a.gross.losses, [60, 90, 0], 1e-9), JSON.stringify(a.gross.losses));
  chk('hand split, victim 2 S=150: gross total 150', close(a.gross.total, 150, 1e-9));
  chk('hand split, victim 2 S=150: gross HHI 0.52', close(a.gross.hhi, 0.52, 1e-9), String(a.gross.hhi));
  chk('hand split, victim 2 S=150: net losses [600/17, 1950/17, 0]', arrClose(a.net.losses, [600 / 17, 1950 / 17, 0], 1e-9), JSON.stringify(a.net.losses));
  chk('hand split, victim 2 S=150: net HHI 185/289', close(a.net.hhi, 185 / 289, 1e-9), String(a.net.hhi));
  chk('hand split, victim 2 S=150: net obligation 850', a.netObligation === 850, String(a.netObligation));

  const b = mod.defaultSplit(lit, 0, 150);
  chk('net receiver as victim: net-regime loss is exactly zero', b.net.total === 0 && b.net.loserCount === 0 && b.netObligation === 0);
  chk('net receiver as victim: gross regime still loses 150 across 2 banks', close(b.gross.total, 150, 1e-9) && b.gross.loserCount === 2);

  const c = mod.defaultSplit(lit, 1, 10000);
  chk('shortfall above outflow caps gross loss at the outflow (250)', close(c.gross.total, 250, 1e-9), String(c.gross.total));
  chk('second net receiver as victim: net-regime loss stays exactly zero at any shortfall',
    c.net.total === 0 && c.net.loserCount === 0 && c.netObligation === 0,
    'total ' + c.net.total + ', losers ' + c.net.loserCount);

  // The cap test for the NET regime belongs to the only net payer, bank 2
  // (obligation 850): S=10000 pays it in full, shared pro rata on claims 200
  // and 650, i.e. losses [200, 650, 0]; gross caps at the 1000 outflow.
  const d = mod.defaultSplit(lit, 2, 10000);
  chk('shortfall above obligation caps net loss at the obligation (850, 2 losers)',
    close(d.net.total, 850, 1e-9) && d.net.loserCount === 2,
    'total ' + d.net.total + ', losers ' + d.net.loserCount);
  chk('shortfall above outflow caps gross loss at the outflow (1000)', close(d.gross.total, 1000, 1e-9), String(d.gross.total));

  const z = mod.defaultSplit(lit, 2, 0);
  chk('zero shortfall produces zero losses in both regimes', z.gross.total === 0 && z.net.total === 0);
  chk('defaultSplit rejects a victim out of range', throws(() => mod.defaultSplit(lit, 3, 150)));
  chk('defaultSplit rejects a negative shortfall', throws(() => mod.defaultSplit(lit, 2, -1)));
}

function invariantChecks(chk) {
  const n = 60, k = 8;
  // simulate's fourth argument is an OPTIONS OBJECT ({ keep: true }), not a
  // boolean; passing true silently disabled the kept fields and crashed the
  // zero-sum assertion below. Fixed at the call site.
  const s = engine.simulate(20260721, n, k, { keep: true });
  chk('net positions sum to zero EXACTLY (integer invariant)', s.nets.reduce((a, b) => a + b, 0) === 0);
  let neg = 0; for (const v of s.nets) if (v < 0) neg += v;
  chk('net settlement equals the magnitude of the negative sum', s.net === -neg);
  chk('outflows sum to gross exactly', s.outflows.reduce((a, b) => a + b, 0) === s.gross);

  // Second method: decode indices from the flat array.
  const nets2 = new Array(n).fill(0);
  for (let p = 0; p < s.amounts.length; p++) {
    const [i, j] = decodePair(p, n, k);
    nets2[j] += s.amounts[p];
    nets2[i] -= s.amounts[p];
  }
  chk('net positions match an independent index-decoding pass', arrEq(nets2, s.nets));

  // Second method: reverse chunked summation for gross.
  let g2 = 0;
  for (let end = s.amounts.length; end > 0; end -= 997) {
    const st = Math.max(0, end - 997);
    for (let q = end - 1; q >= st; q--) g2 += s.amounts[q];
  }
  chk('gross matches an independent reverse summation', g2 === s.gross);

  // Inflows by decoding must also sum to gross.
  let inflow = 0;
  for (let p = 0; p < s.amounts.length; p++) { const [, j] = decodePair(p, n, k); inflow += s.amounts[p]; }
  chk('decoded inflow total equals gross', inflow === s.gross);
}

function sdOfCentDraws(mod) {
  const r = mod.makeRng(424242);
  let m = 0, m2 = 0; const N = 20000;
  for (let i = 0; i < N; i++) { const x = mod.centDraw(r()); m += x; m2 += x * x; }
  m /= N;
  return Math.sqrt(m2 / N - m * m);
}

// Analytic mean of one centDraw: for continuous u, E[ceil(-ln(1-u)*M)] =
// sum over m >= 1 of P(draw >= m) = sum of e^{-(m-1)/M} = 1/(1 - e^{-1/M}).
// The ceiling lifts the realized mean about half a cent above the nominal
// MEAN_CENTS. Comparing the Monte Carlo anchor against the NOMINAL constant
// reads that deterministic bias as Monte Carlo error and fails deterministically
// once the draw count is large (roughly count > (5 sigma / 0.5 cent)^2), which
// is exactly what happened at n=320, k=24 in an earlier draft of this verifier.
function exactCentMean(mod) {
  return 1 / (1 - Math.exp(-1 / mod.MEAN_CENTS));
}

// `ref` supplies the COMPARATOR (the analytic quantised mean and the sampled
// sigma); `mod` supplies the simulation under test. In the normal run they are
// the same module. Correction of record (2026-08-31): they used to be forced to
// be the same, with exMean and sd both read off `mod`, which made mutation
// experiment M1 undetectable by construction: shifting MEAN_CENTS moved the
// simulated gross AND the yardstick it was measured against by the same amount,
// so `--mutate` reported "M1 ... 0 checks failed under mutation" on every run
// and exited non-zero. The comment below always described the intended design
// (a fixed comparator, and the (320, 24) pair sized so a one-cent shift clears
// the 5-sigma bound); the code simply did not implement it. It does now.
function anchorChecks(chk, mod, ref) {
  ref = ref || mod;
  // ANCHOR 1 (algebraic identity): with k payments between each ordered pair,
  // gross = k*n*(n-1)*xbar exactly, where xbar is the realized sample mean.
  // ANCHOR 2 (model constant + Monte Carlo error, stated): gross should sit
  // near count * exactCentMean within a 5-sigma bound, sigma sampled from the
  // cent-draw distribution itself. The bound and the reason for the comparator
  // are PRINTED, not hidden.
  //
  // The last pair exists for mutation experiment M1: shifting MEAN_CENTS by
  // one cent moves the analytic quantised mean by about one cent per draw, so
  // detection needs count above roughly (5 sigma / 1 cent)^2, about 250
  // thousand draws. (320, 24) supplies 2.45 million; the smaller pairs keep
  // the identity anchor cheap and readable.
  const sd = sdOfCentDraws(ref);
  const exMean = exactCentMean(ref);
  console.log('      tolerance note: the Monte Carlo anchor bounds against the ANALYTIC quantised mean ' +
    exMean.toFixed(4) + ' cents, not the nominal ' + ref.MEAN_CENTS + ': the ceiling on centDraw ' +
    'lifts the realized mean about half a cent, a deterministic bias no sigma bound can absorb, ' +
    'and an earlier draft misread it as Monte Carlo error at n=320, k=24.');
  for (const [n, k] of [[40, 8], [120, 8], [10, 3], [320, 24]]) {
    const s = mod.simulate(20260721, n, k);
    const count = n * (n - 1) * k;
    chk('ANCHOR identity: gross = k*n*(n-1)*xbar at n=' + n + ', k=' + k,
      Math.abs(s.gross - count * s.mean) <= 1e-9 * s.gross,
      'gross ' + s.gross + ' vs ' + (count * s.mean));
    const dev = Math.abs(s.gross - count * exMean);
    const bound = 5 * sd * Math.sqrt(count);
    chk('ANCHOR Monte Carlo: gross within 5 sigma of count * exact cent mean (' + exMean.toFixed(4) + ' cents) at n=' + n + ', k=' + k,
      dev < bound, '|dev| ' + dev.toFixed(0) + ' cents vs 5-sigma bound ' + bound.toFixed(0) + ' cents');
    console.log('      anchor detail n=' + n + ' k=' + k + ': simulated ' + s.gross +
      ' cents, exact-cent-mean form ' + (count * exMean).toFixed(0) + ' cents (nominal ' +
      (count * ref.MEAN_CENTS) + ' plus the ceiling bias), |deviation| ' + dev.toFixed(0) +
      ' cents, 5-sigma MC bound ' + bound.toFixed(0) + ' cents (sigma = ' + sd.toFixed(2) + ' cents, sampled)');
  }
}

function fitChecks(chk) {
  const pts15 = [[1, 1], [2, Math.pow(2, 1.5)], [4, 8], [8, Math.pow(8, 1.5)], [16, 64]];
  const f15 = engine.fitPowerLaw(pts15);
  chk('fitPowerLaw recovers exponent 1.5 on constructed data', close(f15.slope, 1.5, 1e-9), String(f15.slope));
  chk('fitPowerLaw standard error is ~0 on exact data', f15.se < 1e-9, String(f15.se));
  const pts05 = [[1, 1], [3, Math.sqrt(3)], [9, 3], [27, Math.pow(27, 0.5)], [81, 9]];
  chk('fitPowerLaw recovers exponent 0.5 on constructed data', close(engine.fitPowerLaw(pts05).slope, 0.5, 1e-9));
  chk('fitPowerLaw rejects fewer than 3 points', throws(() => engine.fitPowerLaw([[1, 1], [2, 2]])));
  chk('fitPowerLaw rejects a non-positive y', throws(() => engine.fitPowerLaw([[1, 1], [2, 0], [4, 4]])));
  chk('fitPowerLaw rejects a non-positive x', throws(() => engine.fitPowerLaw([[0, 1], [2, 2], [4, 4]])));
  chk('fitPowerLaw rejects a non-finite point', throws(() => engine.fitPowerLaw([[1, 1], [2, NaN], [4, 4]])));

  chk('reductionFactor(1000, 100) is 10', engine.reductionFactor(1000, 100) === 10);
  chk('reductionFactor(100, 100) is 1', engine.reductionFactor(100, 100) === 1);
  chk('reductionFactor(100, 0) is Infinity by definition', engine.reductionFactor(100, 0) === Infinity);
  chk('reductionFactor(0, 0) is 1 by definition', engine.reductionFactor(0, 0) === 1);
  chk('reductionFactor rejects negative input', throws(() => engine.reductionFactor(-1, 1)));
}

function sweepAndFitChecks(chk, cfg) {
  const ns = logspace(cfg.nMin, cfg.nMaxDefault, cfg.points);
  chk('sweep geometry yields at least 5 distinct n', ns.length >= 5, JSON.stringify(ns));
  const rows = engine.sweep(cfg.seed, ns, cfg.kDefault, cfg.reps);
  chk('sweep returns one row per distinct n', rows.length === ns.length);
  chk('sweep is deterministic under the fixed seed',
    deepEq(rows, engine.sweep(cfg.seed, ns, cfg.kDefault, cfg.reps)));

  // Cross-check one row against directly composed simulate calls.
  const r0 = rows[0];
  let g = 0, nt = 0;
  for (let r = 0; r < cfg.reps; r++) {
    const s = engine.simulate(engine.childSeed(cfg.seed, 0, r), r0.n, cfg.kDefault);
    g += s.gross; nt += s.net;
  }
  chk('sweep row equals directly composed simulate calls', r0.gross === g / cfg.reps && r0.net === nt / cfg.reps);

  const fN = engine.fitPowerLaw(rows.map(r => [r.n, r.net]));
  const fG = engine.fitPowerLaw(rows.map(r => [r.n, r.gross]));
  const fR = engine.fitPowerLaw(rows.map(r => [r.n, r.gross / r.net]));

  // The three-halves law is EMPIRICAL within this model: assert the fit lands
  // near 1.5 with a sane interval, and NEVER treat it as a theorem.
  chk('fitted net exponent lands near 1.5 (1.40 to 1.60)', fN.slope > 1.40 && fN.slope < 1.60, String(fN.slope));
  chk('net exponent CI brackets its own point estimate', fN.ciLo < fN.slope && fN.slope < fN.ciHi);
  chk('net exponent CI width is under 0.2', (fN.ciHi - fN.ciLo) < 0.2, String(fN.ciHi - fN.ciLo));
  chk('net fit R-squared above 0.98', fN.r2 > 0.98, String(fN.r2));
  console.log('      fitted net exponent ' + fN.slope.toFixed(4) + ' (95% CI ' +
    fN.ciLo.toFixed(4) + ' to ' + fN.ciHi.toFixed(4) + '), R2 ' + fN.r2.toFixed(5) +
    ', over n = ' + rows[0].n + ' to ' + rows[rows.length - 1].n);

  // The gross law is EXACT, but the fitted gross slope does not sit exactly on
  // 2 even with infinite reps: the identity is quadratic in n(n-1), and the fit
  // regresses on n, so ln(n(n-1)) against ln(n) contributes a SYSTEMATIC
  // positive curvature over the sweep's n-range (about +0.036 for n = 10 to
  // 120 at 14 log-spaced points). The expectation below is that curvature
  // COMPUTED from the sweep design itself, not assumed; the remaining gap is
  // pure Monte Carlo scatter of the realized means. An earlier draft banded the
  // raw slope at 1.98 to 2.02, which the exact finite-n curvature alone pushes
  // past; recorded so nobody re-breaks this.
  const expectedGrossSlope = plainOLS(ns.map(n => [Math.log(n), Math.log(n * (n - 1))])).slope;
  chk('fitted gross exponent tracks the exact n(n-1) law (expected ' + expectedGrossSlope.toFixed(4) + ', band +/- 0.02)',
    Math.abs(fG.slope - expectedGrossSlope) < 0.02, String(fG.slope));
  console.log('      fitted gross exponent ' + fG.slope.toFixed(4) + ' against exact-law expectation ' +
    expectedGrossSlope.toFixed(4) + ' (ln(n(n-1)) regressed on ln(n) over this sweep design); the ' +
    '0.02 band covers Monte Carlo scatter of the realized means at reps=' + cfg.reps +
    '. Tolerance note: banding the RAW slope at 1.98 to 2.02 was wrong, because the exact ' +
    'finite-n curvature of the identity alone puts the fitted slope near 2.036 here.');
  chk('fitted reduction exponent sits on 0.5 (0.44 to 0.56)', fR.slope > 0.44 && fR.slope < 0.56, String(fR.slope));

  // Every sweep row must satisfy the gross identity at its own realized mean.
  // Basis, stated because an earlier draft got it wrong: each row's mean is the
  // GRAND realized mean across all reps (total cents over total payments), so
  // the identity closes against the SINGLE-rep count n*(n-1)*k. Multiplying the
  // count by reps forced a fake (1 - 1/reps) shortfall on every row.
  let allId = true;
  for (const r of rows) {
    const count = r.n * (r.n - 1) * cfg.kDefault;
    if (Math.abs(r.gross - count * r.mean) > 1e-9 * r.gross) { allId = false; break; }
  }
  chk('every sweep row satisfies the gross identity at its realized mean', allId);
  // Double-quoted on purpose: the sentence contains an apostrophe, and this
  // file keeps every quote style boring enough to eyeball.
  console.log("      identity basis: each row's mean is the grand realized mean across all " +
    cfg.reps + " reps, so the identity closes against the single-rep count n*(n-1)*k.");
}

// Battery args are pure JSON, so a call that needs a live generator carries the
// string "$rng:<seed>" and the harness substitutes engine.makeRng(seed) for it.
// That keeps drawPayments (whose first argument is a function) exercisable
// through the battery without weakening the every-export-covered check.
function resolveBatteryArg(a) {
  if (typeof a === 'string' && a.lastIndexOf('$rng:', 0) === 0) {
    const seed = Number(a.slice(5));
    if (!Number.isInteger(seed)) throw new Error('battery $rng: arg needs an integer seed, got ' + a);
    return engine.makeRng(seed);
  }
  return a;
}

function batterySmoke(chk, bat) {
  bat.calls.forEach((c, i) => {
    const expectThrow = !!c.expectThrow;
    let threw = false;
    try { engine[c.fn].apply(null, c.args.map(resolveBatteryArg)); } catch (e) { threw = true; }
    if (expectThrow) chk('battery call ' + i + ' (' + c.fn + ') throws as expected', threw);
    else chk('battery call ' + i + ' (' + c.fn + ') runs clean', !threw, 'threw');
  });
  const names = new Set(bat.calls.map(c => c.fn));
  const exported = Object.keys(engine).filter(k => typeof engine[k] === 'function');
  const missing = exported.filter(f => !names.has(f));
  chk('battery covers every exported function of engine.mjs', missing.length === 0, 'missing: ' + missing.join(', '));
}

function proseChecks(chk, html) {
  // Four description slots carry the dek: the meta description, the Open
  // Graph card, the Twitter card, and the JSON-LD Article block. An earlier
  // draft of this check counted occurrences of a '__DEK__' build placeholder;
  // the page ships finished text rather than templates, so the placeholder
  // occurred zero times and the check failed on a clean tree. The invariant it
  // was reaching for is that ALL FOUR SLOTS CARRY THE SAME TEXT, which is what
  // the two checks below assert directly. Nothing is weakened: a slot going
  // missing, or one slot drifting from the others, still fails.
  const grab = (re) => { const m = html.match(re); return m ? m[1] : null; };
  const metaDesc = grab(/<meta name="description" content="([^"]*)"/);
  const ogDesc = grab(/<meta property="og:description" content="([^"]*)"/);
  const twDesc = grab(/<meta name="twitter:description" content="([^"]*)"/);
  let ldDesc = null;
  const ldOpen = '<script type="application/ld+json">';
  const ldAt = html.indexOf(ldOpen);
  if (ldAt !== -1) {
    const ldEnd = html.indexOf('</script>', ldAt);
    try {
      const ld = JSON.parse(html.slice(ldAt + ldOpen.length, ldEnd));
      if (ld && typeof ld.description === 'string') ldDesc = ld.description;
    } catch (e) { ldDesc = null; }
  }
  const slots = [['meta', metaDesc], ['og', ogDesc], ['twitter', twDesc], ['JSON-LD', ldDesc]];
  const missingSlots = slots.filter(s => !s[1]).map(s => s[0]);
  const differing = slots.filter(s => s[1] && s[1] !== metaDesc).map(s => s[0]);
  chk('dek appears in all four description slots (meta, og, twitter, JSON-LD)',
    missingSlots.length === 0, 'missing: ' + missingSlots.join(', '));
  chk('all four description slots carry the same dek text',
    missingSlots.length === 0 && differing.length === 0,
    'differing from meta: ' + differing.join(', '));

  chk('no em dash anywhere in the page', html.indexOf('\u2014') === -1);
  chk('no spaced en dash in the page', !/ \u2013 /.test(html));
  chk('closing script/body/html tags are present and terminal', /<\/script>\s*<\/body>\s*<\/html>\s*$/.test(html));
  chk('exactly one h1', (html.match(/<h1/g) || []).length === 1);
  chk('exactly two h2 (the check panel, and the Corrections note)', (html.match(/<h2/g) || []).length === 2 && html.includes('<h2 id="corrections">Corrections</h2>'));
  // The house exemplar's <title> is a plain search-facing question with NO separator;
  // only og:title and twitter:title carry the site name. Dropped: it came from an
  // ambiguity in the build brief, which the generator applied to <title> as well.
  chk('og:title uses the middle-dot separator', /property="og:title" content="[^"]*\u00b7[^"]*"/.test(html));
  chk('twitter:title uses the middle-dot separator', /name="twitter:title" content="[^"]*\u00b7[^"]*"/.test(html));
  chk('canonical points at the stratum', html.includes('rel="canonical" href="https://artwaste.land/strata/the-square-root-of-the-payment-system/"'));
  chk('JSON-LD Article block present', html.includes('application/ld+json') && html.includes('"@type":"Article"'));
  chk('check panel names the committed verifier', html.includes('research/the-square-root-of-the-payment-system/verify'));
}

function resourceChecks(chk, html) {
  const attrs = [...html.matchAll(/(?:src|href)\s*=\s*"([^"]*)"/g)].map(m => m[1]);
  const allowed = /^https:\/\/(artwaste\.land|schema\.org|en\.wikipedia\.org|www\.bis\.org)\//;
  const badRemote = attrs.filter(u => /^https?:\/\//.test(u) && !allowed.test(u));
  chk('every remote reference is on the allow-list', badRemote.length === 0, badRemote.join(', '));
  const scripts = [...html.matchAll(/<script[^>]*src="([^"]+)"/g)].map(m => m[1]);
  chk('every script src is same-origin absolute', scripts.every(s => s.startsWith('/')), scripts.join(', '));
  const sheets = [...html.matchAll(/<link[^>]*rel="stylesheet"[^>]*>/g)].map(m => m[0]);
  chk('exactly one stylesheet, the self-hosted fonts sheet',
    sheets.length === 1 && sheets[0].includes('href="/fonts/fonts.css"'), sheets.join(' | '));
  chk('no css url() pulls from the network', !/url\(\s*['"]?https?:/.test(html));
  chk('no storage, cookie or network calls in the page',
    !/localStorage|sessionStorage|document\.cookie|XMLHttpRequest|\bfetch\s*\(|WebSocket/.test(html));
  chk('no inline event handler attributes', !/\son(click|input|load|change|error|submit|mouseover)\s*=/.test(html));
  chk('page ships no module script (classic IIFE only)', !html.includes('type="module"'));
  const esrc = readFileSync(ENGINE_PATH, 'utf8');
  chk('engine.mjs references no DOM globals', !/\b(document|window|navigator)\b/.test(esrc));
}

function a11yChecks(chk, html) {
  chk('visible focus ring defined', html.includes(':focus-visible'));
  chk('canvas hidden from the accessibility tree', /<canvas[^>]*aria-hidden="true"/.test(html));
  chk('an aria-live polite region exists', html.includes('aria-live="polite"'));
  chk('the live value carries role="status"', /role="status"/.test(html));
  // Noise discipline counts regions that actually ANNOUNCE. aria-live="off"
  // (the formula line) is an explicit silence, not a live region, so it does
  // not count against the one-region budget.
  const liveRegions = (html.match(/aria-live="(polite|assertive)"/g) || []).length;
  chk('exactly one announcing live region (noise discipline)', liveRegions === 1, 'found ' + liveRegions);
  chk('reduced motion is read and honoured in script', html.includes('prefers-reduced-motion'));
  const inputs = [...html.matchAll(/<input id="([^"]+)"/g)].map(m => m[1]);
  const missing = inputs.filter(id => !html.includes('for="' + id + '"'));
  chk('every range input has a real label', missing.length === 0, 'missing: ' + missing.join(', '));
  const hints = inputs.filter(id => !html.includes('aria-describedby="' + id + '-hint"'));
  chk('every range input has a described-by hint', hints.length === 0, 'missing: ' + hints.join(', '));
  chk('specimen rail is a labelled group of real buttons',
    html.includes('role="group" aria-labelledby="rail-lbl"') && (html.match(/class="tile"/g) || []).length === 0);
  chk('buttons carry visible text labels', !/<button[^>]*>\s*<\/button>/.test(html));
  const readouts = ['ro-exp', 'ro-gross', 'ro-net', 'ro-red', 'ro-losers', 'ro-totloss', 'ro-worst', 'ro-victim'];
  for (const id of readouts) {
    chk('readout #' + id + ' ships empty (no precomputed numbers)', new RegExp('id="' + id + '"[^>]*>\u00b7\u00b7\u00b7<').test(html));
  }
}

function configAndModelChecks(chk, html, cfg) {
  chk('CONFIG line parses as JSON', !!cfg);
  if (!cfg) return;
  chk('CONFIG carries an integer seed', Number.isInteger(cfg.seed));
  chk('CONFIG carries sane sweep parameters',
    Number.isInteger(cfg.nMin) && cfg.nMin >= 3 &&
    Number.isInteger(cfg.nMaxDefault) && cfg.nMaxDefault > cfg.nMin &&
    Number.isInteger(cfg.kDefault) && cfg.kDefault >= 1 &&
    Number.isInteger(cfg.reps) && cfg.reps >= 2 &&
    Number.isInteger(cfg.points) && cfg.points >= 5,
    JSON.stringify(cfg));
  chk('page embeds the published RNG constant (contract tie)', html.includes('0x6D2B79F5'));
  chk('page embeds the documented child-seed mix (contract tie)', html.includes('0x85EBCA77'));
  chk('page declares the 100-cent mean payment (contract tie)', html.includes('-Math.log(1-u)*100'));
  // The page claims its numbers can be reconciled from outside; that claim is
  // only operable if the model is exported past the IIFE, so assert the export.
  // Correction of record (2026-08-31): an earlier version of this comment said
  // a publish gate resolved window.rng, found nothing behind the private IIFE,
  // and died with "rng is not a function". That was a misdiagnosis. No gate in
  // this repository resolves window.rng. The real "rng is not a function" was
  // thrown inside the page's own closure, because its mulberry32 had lost the
  // inner closure and returned a number instead of a generator. This check is
  // still worth keeping, but it never had anything to do with that error.
  chk('page exports its model for outside reconciliation',
    html.includes('window.AWPAYMENT') && html.includes('window.rng = mulberry32'));
  sweepAndFitChecks(chk, cfg);
}

// ── mutation experiments ─────────────────────────────────────────────────
async function mutationExperiments(html) {
  section('M. mutation experiments: corrupt a COPY, confirm the checks notice');
  const dir = mkdtempSync(path.join(tmpdir(), 'aw-verify-'));
  try {
    const src = readFileSync(ENGINE_PATH, 'utf8');

    // M1: shift the model's mean payment constant. The Monte Carlo anchor must trip.
    const m1 = src.replace('export const MEAN_CENTS = 100;', 'export const MEAN_CENTS = 101;');
    if (m1 === src) throw new Error('M1 did not change the bytes');
    const p1 = path.join(dir, 'engine-m1.mjs');
    writeFileSync(p1, m1);
    const mod1 = await import(pathToFileURL(p1).href + '?m=1');
    // The comparator stays PRISTINE (`engine`); only the simulation is mutated.
    // Feeding the mutated module in as its own yardstick is what made this
    // experiment undetectable before; see the note on anchorChecks.
    const t1 = trial(chk => anchorChecks(chk, mod1, engine));
    report('M1 (MEAN_CENTS 100 to 101) is detected', t1.f > 0, t1.f + ' checks failed under mutation');

    // M2: flip the net-position bookkeeping. Hand-worked cases and the
    // zero-sum invariant must trip.
    const m2 = src.replace('nets[i] -= a;', 'nets[i] += a;');
    if (m2 === src) throw new Error('M2 did not change the bytes');
    const p2 = path.join(dir, 'engine-m2.mjs');
    writeFileSync(p2, m2);
    const mod2 = await import(pathToFileURL(p2).href + '?m=2');
    const t2 = trial(chk => { handworkChecks(chk, mod2); invariantChecks2(chk, mod2); });
    report('M2 (net sign flipped) is detected', t2.f > 0, t2.f + ' checks failed under mutation');

    // M3: plant an em dash in the page. The prose gate must trip.
    const m3 = html.replace('</h1>', '\u2014</h1>');
    if (m3 === html || m3.indexOf('\u2014') === -1) throw new Error('M3 did not change the bytes');
    const t3 = trial(chk => proseChecks(chk, m3));
    report('M3 (planted em dash) is detected', t3.f > 0, t3.f + ' checks failed under mutation');

    // M4: strip the live region. The accessibility gate must trip.
    const m4 = html.replace(' role="status"', '');
    if (m4 === html) throw new Error('M4 did not change the bytes');
    const t4 = trial(chk => a11yChecks(chk, m4));
    report('M4 (live region stripped) is detected', t4.f > 0, t4.f + ' checks failed under mutation');

    console.log('      temp copies deleted; the source tree was never modified.');
  } finally {
    rmSync(dir, { recursive: true, force: true });
  }
}
// Invariant checks parameterised by module, for use against mutated copies.
function invariantChecks2(chk, mod) {
  const am = [300, 100, 200, 50, 400, 600];
  const nets = mod.netPositions(am, 3);
  chk('zero-sum invariant on the hand-worked economy', nets.reduce((a, b) => a + b, 0) === 0);
  chk('hand-worked nets survive re-derivation', arrEq(nets, [200, 650, -850]));
}

// ── main ─────────────────────────────────────────────────────────────────
async function main() {
  const argv = process.argv.slice(2);
  const doMutate = argv.includes('--mutate');

  let html = null;
  try { html = readFileSync(PAGE_PATH, 'utf8'); } catch (e) { html = null; }
  if (!html) {
    console.error('could not read the page at ' + PAGE_PATH);
    process.exitCode = 1;
    return;
  }
  const cfg = extractConfig(html);
  let battery = null;
  try { battery = JSON.parse(readFileSync(BATTERY_PATH, 'utf8')); } catch (e) { battery = null; }

  section('A. unit tests of small pure helpers against hand-worked cases (FIRST)');
  helperUnitTests(report);

  section('B. RNG cross-check against a second implementation of the published algorithm');
  rngCrossCheck(report);

  section('C. cent-draw primitive');
  centDrawChecks(report);

  section('D. hand-worked economy and failure split (worked on paper, see README)');
  handworkChecks(report, engine);

  section('E. exact invariants and second-method recomputation');
  invariantChecks(report);

  section('F. ANCHORS: the gross law is an identity; the Monte Carlo error is stated');
  console.log('      ANCHOR SOURCES: (1) algebraic identity k*n*(n-1)*xbar, no source needed;'
    + ' (2) the ANALYTIC quantised mean of the cent draw, 1/(1-exp(-1/MEAN_CENTS)), declared'
    + ' in engine.mjs, compared with a 5-sigma bound from the sampled cent-draw standard'
    + ' deviation. No published value is invoked.');
  anchorChecks(report, engine);

  section('G. fitting machinery on constructed and rejected inputs');
  fitChecks(report);

  section('H. the page: config, contract ties, sweep and fitted exponents');
  configAndModelChecks(report, html, cfg);

  section('I. the page: prose, heads and honesty structure');
  proseChecks(report, html);

  section('J. the page: resources, self-containment');
  resourceChecks(report, html);

  section('K. the page: accessibility');
  a11yChecks(report, html);

  section('L. reconciliation battery self-consistency');
  if (battery && Array.isArray(battery.calls)) batterySmoke(report, battery);
  else report('battery.json loads and contains a calls array', false, 'missing or malformed');

  if (doMutate) await mutationExperiments(html);

  const total = pass + fail;
  console.log(LF + '========================================');
  console.log('CHECKS PASSED: ' + pass + ' OF ' + total);
  if (fail > 0) {
    console.log('FAILURES:');
    for (const l of failLines) console.log('  - ' + l);
  }
  console.log('========================================');
  process.exitCode = (fail > 0 || total === 0) ? 1 : 0;
}

main().catch(e => { console.error('verifier crashed: ' + (e && e.stack || e)); process.exitCode = 1; });
