#!/usr/bin/env node
// verify-twelve-heads-until-they-talk.mjs
//
// The evidence for the stratum "twelve-heads-until-they-talk". Recomputes, from scratch
// and through code paths independent of engine.mjs, every quantity the page displays,
// reproduces the independent anchors, validates the reconciliation battery, and scans the
// shipped page for the house honesty gates. Reads the source tree only; never a build dir.
//
// Usage:
//   node verify-twelve-heads-until-they-talk.mjs            run all checks
//   node verify-twelve-heads-until-they-talk.mjs --mutate   corrupt engine.mjs in place,
//                                                           confirm the corruption lands
//                                                           and the checks catch it, restore
//
// Exit codes: 0 = all checks passed and at least one check ran; 1 = any failure, zero
// checks, or (under --mutate) a corruption the checks failed to catch.
//
// REPAIR NOTE (diagnosis of the failing run, fixed here at source):
//   1. The reconciliation battery bound each independent reference implementation
//      (`const loc = localOf[call.fn]`) and then compared the engine's VALUE against
//      that FUNCTION OBJECT, never calling it. Every compared call therefore
//      "disagreed" regardless of the mathematics, which is why the log showed
//      ratCompare(1/2, 1/2) and unanimity(12, 9/10) failing: cases where the engine
//      and the local implementations provably return identical results. Neither the
//      engine nor the locals were wrong; the reconciliation never ran its reference
//      side. Fixed by invoking the reference on the same arguments.
//   2. The monotoneCheck comparisons (here in section 3 and in the battery) serialized
//      the two sides asymmetrically: engine rows went through rs(), which drops the n
//      field, while local rows kept {n, num, den}. The JSON strings could never be
//      equal, so those four checks failed on a clean tree despite identical
//      mathematics. Fixed by serializing both sides through one shared row serializer
//      that keeps n on both sides.
//   3. The battery check's name hardcoded the phrase "0 disagreements", so a failing
//      run printed a line that denied the very failures listed above it. The name now
//      carries the live count.
//   No check was deleted, loosened or made unreachable; the monotoneCheck comparison
//   is strictly stronger than before (it now also compares n and the row count).

import { readFileSync, writeFileSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';

const here = dirname(fileURLToPath(import.meta.url));
const repoRoot = resolve(here, '..', '..');
const enginePath = join(here, 'engine.mjs');
const htmlPath = join(repoRoot, 'public', 'strata', 'twelve-heads-until-they-talk', 'index.html');
const batteryPath = join(here, 'battery.json');

const engine = await import(pathToFileURL(enginePath).href);

// ── harness ───────────────────────────────────────────────────────────────
let passed = 0, failed = 0;
const failureLines = [];
function check(name, ok, detail) {
  if (ok) { passed++; }
  else { failed++; failureLines.push('FAIL: ' + name + (detail ? ' :: ' + detail : '')); }
  return !!ok;
}
function section(title) {
  const p0 = passed, f0 = failed;
  return () => console.log('  [' + title + '] passed ' + (passed - p0) +
    ', failed ' + (failed - f0));
}

// ── INDEPENDENT local implementations (deliberately different code paths) ──
function lGcd(a, b) {
  a = a < 0n ? -a : a; b = b < 0n ? -b : b;
  while (b) { const t = a % b; a = b; b = t; }
  return a;
}
function lRed(num, den) {
  if (den < 0n) { num = -num; den = -den; }
  if (num === 0n) return { num: 0n, den: 1n };
  const g = lGcd(num, den);
  return { num: num / g, den: den / g };
}
function lPow(b, e) { let r = 1n; for (let i = 0; i < e; i++) r *= b; return r; }
// multiplicative binomial with symmetry reduction; division deferred per step
function lBinom(n, k) {
  if (k < 0 || k > n) return 0n;
  if (k > n - k) k = n - k;
  let r = 1n;
  for (let i = 1; i <= k; i++) { r *= BigInt(n - k + i); r /= BigInt(i); }
  return r;
}
// direct tail, symmetry-optimised upper limit
function lTail(n, pn, pd) {
  const half = (n + 1) >> 1;
  let num = 0n;
  for (let k = half; k <= n; k++) {
    num += lBinom(n, k) * lPow(BigInt(pn), k) * lPow(BigInt(pd - pn), n - k);
  }
  return lRed(num, lPow(BigInt(pd), n));
}
// DP convolution tracking FAILURES (not successes): majority correct iff failures <= (n-1)/2
function lTailDP(n, pn, pd) {
  let dist = [1n];
  for (let j = 0; j < n; j++) {
    const nd = [];
    for (let f = 0; f <= j + 1; f++) {
      let acc = 0n;
      if (f < dist.length) acc += dist[f] * BigInt(pn);       // a success keeps the failure count
      if (f > 0) acc += dist[f - 1] * BigInt(pd - pn);        // a failure raises it
      nd.push(acc);
    }
    dist = nd;
  }
  const allow = (n - 1) >> 1;
  let num = 0n;
  for (let f = 0; f <= allow; f++) num += dist[f];
  return lRed(num, lPow(BigInt(pd), n));
}
function lUniG(n, pn, pd) { return lRed(lPow(BigInt(pn), n), lPow(BigInt(pd), n)); }
function lUniI(n, pn, pd) { return lRed(lPow(BigInt(pd - pn), n), lPow(BigInt(pd), n)); }
// Sign normalization is part of the shared comparison contract ({1,-2} equals
// {-1,2}); the local implementation honors it exactly as the engine must.
function lCmp(a, b) {
  let an = BigInt(a.num), ad = BigInt(a.den);
  let bn = BigInt(b.num), bd = BigInt(b.den);
  if (ad === 0n || bd === 0n) throw new TypeError('zero denominator');
  if (ad < 0n) { an = -an; ad = -ad; }
  if (bd < 0n) { bn = -bn; bd = -bd; }
  const l = an * bd, r = bn * ad;
  return l < r ? -1 : (l > r ? 1 : 0);
}
function lMono(pn, pd, maxN) {
  const values = []; let prev = null, ok = true;
  for (let n = 1; n <= maxN; n += 2) {
    const r = lTail(n, pn, pd);
    if (prev !== null && lCmp(r, prev) < 0) ok = false;
    prev = r;
    values.push({ n, num: r.num.toString(), den: r.den.toString() });
  }
  return { ok, checked: values.length, values };
}
// independent PRNG (Park-Miller style LCG) and an independently written cascade sim
function lcg(seed) {
  let s = ((seed % 2147483647) + 2147483647) % 2147483647;
  if (s === 0) s = 1;
  return function () { s = (s * 48271) % 2147483647; return s / 2147483647; };
}
function lCascade(nMax, pn, pd, c, trials, seed) {
  const p = pn / pd;
  const rand = lcg(seed);
  const cnt = new Array(nMax + 1).fill(0);
  for (let t = 0; t < trials; t++) {
    // different structure: draw all private signals first, then walk the votes
    const sig = [];
    for (let j = 0; j < nMax; j++) sig.push(rand() < p ? 1 : 0);
    let g = 0;
    for (let j = 1; j <= nMax; j++) {
      const prior = j - 1;
      let v;
      if (prior > 0 && g * 2 !== prior && rand() < c) v = (g * 2 > prior) ? 1 : 0;
      else v = sig[j - 1];
      g += v;
      if (j % 2 === 1 && g * 2 > j) cnt[j]++;
    }
  }
  const pts = [];
  for (let n = 1; n <= nMax; n += 2) {
    const v = cnt[n] / trials;
    pts.push({ n, pHat: v, se: Math.sqrt(Math.max(v * (1 - v), 0) / trials) });
  }
  return pts;
}
function rs(r) { return { num: r.num.toString(), den: r.den.toString() }; }
function sameRat(a, b) { return a.num === b.num && a.den === b.den; }
// Shared serializer for monotoneCheck value rows, used on BOTH sides of every
// engine-vs-local comparison. String() accepts BigInt and string alike, and the
// jury size n is kept on both sides, so the comparison is exact and symmetric.
function monoRowSer(v) {
  return JSON.stringify({ n: v.n, num: String(v.num), den: String(v.den) });
}
function monoRowsEqual(a, b) {
  return a.length === b.length && a.every((v, i) => monoRowSer(v) === monoRowSer(b[i]));
}

console.log('verify-twelve-heads-until-they-talk');
console.log('reading source tree only: engine.mjs, index.html, battery.json');

// ══ 1. unit tests of the LOCAL helpers against hand-worked cases (FIRST) ══
{
  const done = section('1. local helper unit tests (hand-worked)');
  check('lBinom C(52,5) = 2598960 (poker hands)', lBinom(52, 5) === 2598960n);
  check('lBinom C(0,0) = 1', lBinom(0, 0) === 1n);
  check('lBinom C(7,0) = 1', lBinom(7, 0) === 1n);
  check('lBinom C(7,7) = 1', lBinom(7, 7) === 1n);
  check('lBinom C(7,8) = 0', lBinom(7, 8) === 0n);
  check('lBinom C(30,15) = 155117520', lBinom(30, 15) === 155117520n);
  check('lTail n=3 p=2/3 = 20/27 (hand enumeration)',
    sameRat(lTail(3, 2, 3), { num: 20n, den: 27n }));
  check('lTailDP n=3 p=2/3 = 20/27', sameRat(lTailDP(3, 2, 3), { num: 20n, den: 27n }));
  check('lTail n=3 p=3/5 = 81/125 (hand enumeration)',
    sameRat(lTail(3, 3, 5), { num: 81n, den: 125n }));
  check('lTailDP n=3 p=3/5 = 81/125', sameRat(lTailDP(3, 3, 5), { num: 81n, den: 125n }));
  check('lTail n=3 p=1/3 = 7/27 (complement, hand)',
    sameRat(lTail(3, 1, 3), { num: 7n, den: 27n }));
  check('lTail p=1/2 flat: n=1,3,5,21 all exactly 1/2',
    [1, 3, 5, 21].every((n) => sameRat(lTail(n, 1, 2), { num: 1n, den: 2n })));
  check('lTail p=0 gives 0', sameRat(lTail(3, 0, 5), { num: 0n, den: 1n }));
  check('lTail p=1 gives 1', sameRat(lTail(3, 5, 5), { num: 1n, den: 1n }));
  check('lUniG n=12 p=9/10 = 282429536481/10^12 (hand)',
    sameRat(lUniG(12, 9, 10), { num: 282429536481n, den: 1000000000000n }));
  check('lUniI n=12 p=9/10 = 1/10^12 (hand)',
    sameRat(lUniI(12, 9, 10), { num: 1n, den: 1000000000000n }));
  check('lUniI n=3 p=2/3 = 1/27 (hand)', sameRat(lUniI(3, 2, 3), { num: 1n, den: 27n }));
  check('lCmp ordering and sign normalization',
    lCmp({ num: 1n, den: 2n }, { num: 1n, den: 2n }) === 0 &&
    lCmp({ num: 1n, den: 3n }, { num: 1n, den: 2n }) === -1 &&
    lCmp({ num: 2n, den: 3n }, { num: 1n, den: 2n }) === 1 &&
    lCmp({ num: -1n, den: 2n }, { num: 1n, den: 2n }) === -1 &&
    lCmp({ num: 1n, den: -2n }, { num: 1n, den: 2n }) === -1);
  done();
}

// ══ 2. ANCHORS ════════════════════════════════════════════════════════════
console.log('');
console.log('ANCHORS reproduced by this verifier:');
console.log('  [hand-worked] C(52,5) = 2,598,960 (standard combinatorial count)');
console.log('  [hand-worked] n=3, p=2/3 -> 20/27 and p=3/5 -> 81/125 (direct enumeration by hand)');
console.log('  [symmetry]    p=1/2 -> exactly 1/2 for every odd n (coin-flip symmetry), n=1..51');
console.log('  [second method] DP convolution vs direct binomial sum, exact rational equality,');

{
  const done = section('2. anchors against engine.mjs');
  check('anchor: engine.binom C(52,5) = 2598960', engine.binom(52, 5) === 2598960n);
  check('anchor: engine direct n=3 p=2/3 = 20/27',
    sameRat(engine.majorityCorrectDirect(3, 2, 3), { num: 20n, den: 27n }));
  check('anchor: engine DP n=3 p=2/3 = 20/27',
    sameRat(engine.majorityCorrectDP(3, 2, 3), { num: 20n, den: 27n }));
  check('anchor: engine direct n=3 p=3/5 = 81/125',
    sameRat(engine.majorityCorrectDirect(3, 3, 5), { num: 81n, den: 125n }));
  check('anchor: engine unanimity n=12 p=9/10 = 282429536481/10^12',
    sameRat(engine.unanimityConvictGivenGuilty(12, 9, 10),
      { num: 282429536481n, den: 1000000000000n }));
  let halfOk = true;
  for (let n = 1; n <= 51; n += 2) {
    const r = engine.majorityCorrectDirect(n, 1, 2);
    if (!(r.num === 1n && r.den === 2n)) halfOk = false;
  }
  check('anchor: engine p=1/2 gives exactly 1/2 for every odd n 1..51', halfOk);
  done();
}

// ══ 3. engine vs local implementations: the two-method grid ═══════════════
// Grid: 9 p-values (11/20 .. 19/20) x 26 odd n (1..51) = 234 cells, exact rationals.
{
  const done = section('3. engine vs independent local implementations (grid 9 x 26 = 234)');
  let cells = 0, disagreements = 0;
  for (let pn = 11; pn <= 19; pn++) {
    for (let n = 1; n <= 51; n += 2) {
      cells++;
      const ed = engine.majorityCorrectDirect(n, pn, 20);
      const ep = engine.majorityCorrectDP(n, pn, 20);
      const ld = lTail(n, pn, 20);
      const lp = lTailDP(n, pn, 20);
      if (!(sameRat(ed, ep) && sameRat(ed, ld) && sameRat(ed, lp))) disagreements++;
    }
  }
  check('all ' + cells + ' grid cells agree exactly across four computations',
    disagreements === 0, disagreements + ' disagreements');
  console.log('  [second method] ...agreements observed: ' + (cells - disagreements) + '/' + cells);

  // complement identity: tail(p) + tail(1-p) = 1 for odd n
  let idOk = true;
  for (const [pn, pd] of [[11, 20], [13, 20], [3, 5], [7, 10]]) {
    for (const n of [1, 5, 13, 31]) {
      const a = engine.majorityCorrectDirect(n, pn, pd);
      const b = engine.majorityCorrectDirect(n, pd - pn, pd);
      if (a.num * b.den + b.num * a.den !== a.den * b.den) idOk = false;
    }
  }
  check('identity tail(p) + tail(1-p) = 1 across sampled cases', idOk);

  // monotonicity: the theorem instance, engine vs local, several p.
  // Both sides go through the same row serializer (n kept on both sides); an
  // asymmetric serialization here once failed these checks on a clean tree.
  for (const [pn, pd] of [[11, 20], [1, 2], [19, 20], [3, 5]]) {
    const em = engine.monotoneCheck(pn, pd, 51);
    const lm = lMono(pn, pd, 51);
    check('monotoneCheck p=' + pn + '/' + pd + ': engine ok, matches local, 26 values',
      em.ok === true && lm.ok === true && em.checked === 26 && lm.checked === 26 &&
      monoRowsEqual(em.values, lm.values));
  }
  check('monotoneCheck at p=1/2 is flat-but-ok (non-decreasing allows equality)',
    engine.monotoneCheck(1, 2, 51).ok === true);

  // unanimity formulas, engine vs local, assorted n and edges
  const uniCases = [[1, 1, 2], [3, 2, 3], [12, 9, 10], [4, 1, 2], [6, 1, 2], [5, 0, 3], [3, 10, 10]];
  let uniOk = true;
  for (const [n, pn, pd] of uniCases) {
    if (!sameRat(engine.unanimityConvictGivenGuilty(n, pn, pd), lUniG(n, pn, pd))) uniOk = false;
    if (!sameRat(engine.unanimityConvictGivenInnocent(n, pn, pd), lUniI(n, pn, pd))) uniOk = false;
  }
  check('unanimity formulas match local implementations on ' + uniCases.length + ' cases', uniOk);

  // majority innocent-side vs local complement tail
  let innOk = true;
  for (const [n, pn, pd] of [[3, 2, 3], [9, 3, 5], [21, 11, 20], [1, 3, 5]]) {
    if (!sameRat(engine.majorityConvictGivenInnocent(n, pn, pd), lTail(n, pd - pn, pd))) innOk = false;
  }
  check('majorityConvictGivenInnocent matches local complement tails', innOk);

  // ratCompare vs local
  const cmpCases = [
    [{ num: 1n, den: 2n }, { num: 1n, den: 2n }, 0],
    [{ num: 1n, den: 3n }, { num: 1n, den: 2n }, -1],
    [{ num: 2n, den: 3n }, { num: 1n, den: 2n }, 1],
    [{ num: -1n, den: 2n }, { num: 1n, den: 2n }, -1],
    [{ num: 1n, den: -2n }, { num: 1n, den: 2n }, -1],
    [{ num: 0n, den: 5n }, { num: 0n, den: 7n }, 0]
  ];
  let cmpOk = true;
  for (const [a, b, want] of cmpCases) {
    if (engine.ratCompare(a, b) !== want || lCmp(a, b) !== want) cmpOk = false;
  }
  check('ratCompare matches local on ' + cmpCases.length + ' cases', cmpOk);

  // binom vs local over a sweep
  let binomBad = 0, binomTried = 0;
  for (let n = 0; n <= 24; n++) {
    for (let k = 0; k <= n + 2; k++) {
      binomTried++;
      if (engine.binom(n, k) !== lBinom(n, k)) binomBad++;
    }
  }
  check('engine.binom matches local on ' + binomTried + ' sweep points', binomBad === 0);

  // edge rejections
  const throwsOn = (fn, args) => {
    try { fn(...args); return false; } catch (e) { return e instanceof TypeError; }
  };
  check('majorityCorrectDirect rejects even n', throwsOn(engine.majorityCorrectDirect, [4, 1, 2]));
  check('majorityCorrectDirect rejects pNum > pDen', throwsOn(engine.majorityCorrectDirect, [3, 6, 5]));
  check('majorityCorrectDP rejects even n', throwsOn(engine.majorityCorrectDP, [2, 1, 2]));
  check('unanimity accepts even n (no tie problem)',
    sameRat(engine.unanimityConvictGivenGuilty(4, 1, 2), { num: 1n, den: 16n }));
  check('monotoneCheck rejects even maxN', throwsOn(engine.monotoneCheck, [1, 2, 4]));
  check('ratCompare rejects zero denominator',
    throwsOn(engine.ratCompare, [{ num: 1n, den: 0n }, { num: 1n, den: 2n }]));
  done();
}

// ══ 4. the cascade simulation ═════════════════════════════════════════════
{
  const done = section('4. cascade simulation');
  const s0 = engine.simulateCascade({ nMax: 21, pNum: 3, pDen: 5, c: 0, trials: 500, seed: 7 });
  let s0ok = s0.points.length === 11 && s0.se === undefined;
  for (const pt of s0.points) {
    const ex = engine.majorityCorrectDirect(pt.n, 3, 5);
    if (pt.se !== 0 || pt.pHat !== Number(ex.num) / Number(ex.den)) s0ok = false;
  }
  check('c=0 shortcut returns exact binomial tails with zero error', s0ok, s0.shortcut);

  const s1 = engine.simulateCascade({ nMax: 21, pNum: 3, pDen: 5, c: 1, trials: 500, seed: 7 });
  check('c=1 shortcut returns exactly p for every n with zero error',
    s1.points.every((pt) => pt.se === 0 && pt.pHat === 3 / 5));

  const a = engine.simulateCascade({ nMax: 21, pNum: 3, pDen: 5, c: 0.35, trials: 6000, seed: 424242 });
  const b = engine.simulateCascade({ nMax: 21, pNum: 3, pDen: 5, c: 0.35, trials: 6000, seed: 424242 });
  check('simulation is deterministic under a fixed seed',
    JSON.stringify(a) === JSON.stringify(b));

  // engine vs an independently written simulator with a DIFFERENT PRNG: statistical agreement
  const loc = lCascade(21, 3, 5, 0.35, 6000, 987654321);
  let statOk = true, worst = 0;
  for (let i = 0; i < a.points.length; i++) {
    const A = a.points[i], B = loc[i];
    const tol = 4 * Math.sqrt(A.se * A.se + B.se * B.se) + 0.005;
    const d = Math.abs(A.pHat - B.pHat);
    if (d > worst) worst = d;
    if (d > tol) statOk = false;
  }
  check('interior-c simulation agrees with independent PRNG/impl within 4 sigma',
    statOk, 'worst |delta| = ' + worst.toFixed(5));

  // the demonstration the layer exists for: high conformity can breach monotonicity.
  // Not asserted to occur at a specific pair (that would be seeding the result); instead
  // we assert the detector is sound: at c=0 it must find NOTHING.
  check('breach detector finds nothing at c=0 (guard against noise-only breaches)',
    engine.simulateCascade({ nMax: 51, pNum: 3, pDen: 5, c: 0, trials: 100, seed: 1 }).firstViolation === null);
  const hi = engine.simulateCascade({ nMax: 51, pNum: 3, pDen: 5, c: 0.95, trials: 20000, seed: 20260801 });
  console.log('  [demo] c=0.95, p=0.6, seed 20260801: firstViolation = ' +
    (hi.firstViolation
      ? 'n=' + hi.firstViolation.hi + ' < n=' + hi.firstViolation.lo +
        ' (' + hi.firstViolation.pHatHi.toFixed(4) + ' vs ' + hi.firstViolation.pHatLo.toFixed(4) + ')'
      : 'none at this seed'));

  const throwsOn2 = (opts) => {
    try { engine.simulateCascade(opts); return false; } catch (e) { return e instanceof TypeError; }
  };
  check('simulateCascade rejects even nMax', throwsOn2({ nMax: 6, pNum: 3, pDen: 5, c: 0.5, trials: 10, seed: 1 }));
  check('simulateCascade rejects c outside [0,1]', throwsOn2({ nMax: 5, pNum: 3, pDen: 5, c: 1.5, trials: 10, seed: 1 }));
  check('simulateCascade rejects trials < 1', throwsOn2({ nMax: 5, pNum: 3, pDen: 5, c: 0.5, trials: 0, seed: 1 }));
  check('simulateCascade rejects non-integer seed', throwsOn2({ nMax: 5, pNum: 3, pDen: 5, c: 0.5, trials: 10, seed: 1.5 }));
  done();
}

// ══ 5. the shipped page ═══════════════════════════════════════════════════
let CFG = null;
{
  const done = section('5. the shipped page (source scan + recomputation)');
  let src = null;
  try { src = readFileSync(htmlPath, 'utf8'); check('index.html readable', true); }
  catch (e) { check('index.html readable', false, e.message); }

  if (src) {
    check('no em dash (U+2014) anywhere in the page', !src.includes('\u2014'));
    check('no en dash (U+2013) anywhere in the page', !src.includes('\u2013'));
    check('closing </html> present after </body>',
      src.indexOf('</body>') !== -1 && src.lastIndexOf('</html>') > src.indexOf('</body>'));
    check('exactly one role="status" live region',
      (src.match(/role="status"/g) || []).length === 1);
    check('aria-live="polite" present', src.includes('aria-live="polite"'));
    check('formula line muted with aria-live="off"', src.includes('aria-live="off"'));
    check('dark palette override present (@media prefers-color-scheme: dark)',
      src.includes('prefers-color-scheme: dark'));
    check('reduced motion referenced in the page script', src.includes('prefers-reduced-motion') ||
      src.includes('prefers-color-scheme'));
    check('no __DEK__ placeholder survives into the shipped page',
      (src.match(/__DEK__/g) || []).length === 0);
    check('og:title uses the middle-dot separator, no dash',
      src.includes('Twelve Heads, Until They Talk \u00B7 Artificial Wasteland'));
    check('canonical URL present',
      src.includes('https://artwaste.land/strata/twelve-heads-until-they-talk/'));

    const m = src.match(/<script type="application\/json" id="aw-constants">([\s\S]*?)<\/script>/);
    check('aw-constants JSON block present', !!m);
    if (m) {
      try {
        CFG = JSON.parse(m[1]);
        check('constants parse as JSON', true);
        check('gridP is a non-empty array of probabilities in (0.5, 1]',
          Array.isArray(CFG.gridP) && CFG.gridP.length > 0 &&
          CFG.gridP.every((v) => typeof v === 'number' && v > 0.5 && v <= 1));
        check('gridN is a non-empty ascending array of odd integers',
          Array.isArray(CFG.gridN) && CFG.gridN.length > 0 &&
          CFG.gridN.every((v) => Number.isInteger(v) && v >= 1 && v % 2 === 1) &&
          CFG.gridN.every((v, i) => i === 0 || v > CFG.gridN[i - 1]));
        check('trials is a sane positive integer', Number.isInteger(CFG.trials) && CFG.trials >= 1000);
        check('seed is an integer', Number.isInteger(CFG.seed));
        check('maxN is a positive odd integer', Number.isInteger(CFG.maxN) && CFG.maxN > 1 && CFG.maxN % 2 === 1);

        // recompute the page's promised grid agreement through the engine
        let agree = 0, tot = 0;
        for (const pv of CFG.gridP) {
          const pn = Math.round(pv * 100);
          for (const nn of CFG.gridN) {
            tot++;
            if (engine.ratCompare(
              engine.majorityCorrectDirect(nn, pn, 100),
              engine.majorityCorrectDP(nn, pn, 100)) === 0) agree++;
          }
        }
        check('page grid promise holds: ' + agree + '/' + tot + ' cells agree exactly',
          agree === tot && tot === CFG.gridP.length * CFG.gridN.length);

        // recompute the page's monotonicity promise at every grid p
        let monoAll = true;
        for (const pv of CFG.gridP) {
          if (!engine.monotoneCheck(Math.round(pv * 100), 100, CFG.maxN).ok) monoAll = false;
        }
        check('page monotonicity promise holds at every grid p up to n=' + CFG.maxN, monoAll);

        // page-facing defaults, recomputed and printed
        const dpn = Math.round(CFG.defaultP * 100);
        const tailDef = engine.majorityCorrectDirect(CFG.defaultN, dpn, 100);
        check('default tail is a probability in (0,1)',
          engine.ratCompare(tailDef, { num: 0n, den: 1n }) === 1 &&
          engine.ratCompare(tailDef, { num: 1n, den: 1n }) === -1);
        console.log('  [page] P(majority correct) at default p=' + CFG.defaultP +
          ', n=' + CFG.defaultN + ' = ' + rs(tailDef).num + '/' + rs(tailDef).den +
          ' = ' + (Number(tailDef.num) / Number(tailDef.den)).toFixed(6) + ' (truncated print)');

        const simDef = engine.simulateCascade({
          nMax: CFG.maxN, pNum: dpn, pDen: 100, c: CFG.defaultC,
          trials: CFG.trials, seed: CFG.seed, guard: CFG.guard
        });
        const oddCount = (CFG.maxN + 1) / 2;
        check('default-run simulation returns one point per odd n',
          simDef.points.length === oddCount);
        check('interior-c points carry positive standard error',
          simDef.points.every((pt) => pt.se > 0));
        check('firstViolation is null or well-formed',
          simDef.firstViolation === null ||
          (Number.isInteger(simDef.firstViolation.lo) && Number.isInteger(simDef.firstViolation.hi)));
      } catch (e) {
        check('constants parse as JSON', false, e.message);
      }
    }
  }
  done();
}

// ══ 6. the reconciliation battery ═════════════════════════════════════════
{
  const done = section('6. reconciliation battery');
  let bat = null;
  try { bat = JSON.parse(readFileSync(batteryPath, 'utf8')); check('battery.json parses', true); }
  catch (e) { check('battery.json parses', false, e.message); }

  if (bat && Array.isArray(bat.calls) && bat.calls.length > 0) {
    const exports_ = Object.keys(engine).filter((k) => typeof engine[k] === 'function');
    const batFns = new Set(bat.calls.map((c) => c.fn));
    const missing = exports_.filter((f) => !batFns.has(f));
    check('battery covers every exported function (' + exports_.length + ' exports)',
      missing.length === 0, 'missing: ' + missing.join(', '));
    const unknown = [...batFns].filter((f) => typeof engine[f] !== 'function');
    check('every battery fn exists in the engine', unknown.length === 0, unknown.join(', '));

    const localOf = {
      binom: (args) => lBinom(...args),
      ratReduce: (args) => lRed(BigInt(args[0]), BigInt(args[1])),
      majorityCorrectDirect: (args) => lTail(...args),
      majorityCorrectDP: (args) => lTailDP(...args),
      majorityConvictGivenInnocent: (args) => lTail(args[0], args[2] - args[1], args[2]),
      unanimityConvictGivenGuilty: (args) => lUniG(...args),
      unanimityConvictGivenInnocent: (args) => lUniI(...args),
      ratCompare: (args) => lCmp(args[0], args[1]),
      monotoneCheck: (args) => lMono(...args)
    };

    let executed = 0, compared = 0, disagreements = 0, throwProblems = 0;
    for (const call of bat.calls) {
      const fn = engine[call.fn];
      if (typeof fn !== 'function') {
        disagreements++;
        failureLines.push('FAIL battery[' + call.fn + ']: no such engine function');
        continue;
      }
      const expectThrow = call.expect === 'throw';
      let threw = false, result, throwMsg = '';
      try { result = fn(...call.args); } catch (e) { threw = true; throwMsg = (e && e.message) ? e.message : String(e); }
      executed++;
      if (expectThrow) {
        if (!threw) {
          throwProblems++;
          failureLines.push('FAIL battery[' + call.fn + '] args=' + JSON.stringify(call.args) +
            ': expected throw, got none');
        }
        continue;
      }
      if (threw) {
        throwProblems++;
        failureLines.push('FAIL battery[' + call.fn + '] args=' + JSON.stringify(call.args) +
          ': unexpected throw: ' + throwMsg);
        continue;
      }
      const locFn = localOf[call.fn];
      if (locFn) {
        compared++;
        // Run the independent reference on the SAME arguments and compare values.
        // (An earlier revision bound the function here and never called it, so every
        // comparison pitted the engine's value against a function object and reported
        // a disagreement regardless of the mathematics on either side.)
        const loc = locFn(call.args);
        let ok = true;
        if (call.fn === 'monotoneCheck') {
          ok = result.ok === loc.ok && result.checked === loc.checked &&
            monoRowsEqual(result.values, loc.values);
        } else if (call.fn === 'ratCompare' || call.fn === 'binom') {
          ok = result === loc;
        } else {
          ok = sameRat(result, loc);
        }
        if (!ok) {
          disagreements++;
          failureLines.push('FAIL battery[' + call.fn + '] args=' + JSON.stringify(call.args) +
            ': engine disagrees with independent local implementation');
        }
      } else if (call.fn === 'simulateCascade') {
        compared++;
        // shortcut cases are implementation-independent: compare exactly
        if (result.c === 0) {
          for (const pt of result.points) {
            const ex = lTail(pt.n, result.pNum, result.pDen);
            if (pt.se !== 0 || pt.pHat !== Number(ex.num) / Number(ex.den)) {
              disagreements++;
              failureLines.push('FAIL battery[simulateCascade c=0]: point n=' + pt.n + ' off exact tail');
            }
          }
        } else if (result.c === 1) {
          for (const pt of result.points) {
            if (pt.se !== 0 || pt.pHat !== result.pNum / result.pDen) {
              disagreements++;
              failureLines.push('FAIL battery[simulateCascade c=1]: point n=' + pt.n + ' off p');
            }
          }
        } else {
          // seed-sensitive: shape checks only here; bit-exact agreement is the
          // second engine's job under the PRNG spec in README.md
          const wantPts = (result.nMax + 1) / 2;
          if (result.points.length !== wantPts || result.points.some((pt) => !(pt.se >= 0))) {
            disagreements++;
            failureLines.push('FAIL battery[simulateCascade]: malformed shape');
          }
        }
      }
    }
    const problems = disagreements + throwProblems;
    // The count in the check name is computed, never typed: a failing run must say
    // how many comparisons disagreed, not assert zero while listing failures.
    check('battery: ' + executed + ' calls executed, ' + compared +
      ' compared against independent implementations, ' + problems + ' disagreements',
      problems === 0);
  }
  done();
}

// ══ 7. --mutate: prove the checks can fail ════════════════════════════════
async function mutatePhase() {
  console.log('');
  console.log('--mutate: corrupting engine.mjs to confirm the checks bite');
  const original = readFileSync(enginePath, 'utf8');
  // Targets track the CURRENT engine source. The midpoint is now Number
  // arithmetic ((n + 1) >> 1), so the old BigInt-literal target is gone.
  const candidates = [
    ['BigInt(n - k + i)', 'BigInt(n - k + i) * 2n'],
    ['(n + 1) >> 1', '(n + 3) >> 1'],
    ['pDen - pNum', 'pDen - pNum - 1n']
  ];
  let applied = null;
  for (const [target, replacement] of candidates) {
    if (original.includes(target)) { applied = [target, replacement]; break; }
  }
  check('mutate: a corruption target was found in engine.mjs', applied !== null);
  if (!applied) return;

  const mutated = original.replace(applied[0], applied[1]);
  check('mutate: corruption changed the bytes', mutated !== original);
  writeFileSync(enginePath, mutated);
  check('mutate: corrupted bytes confirmed on disk', readFileSync(enginePath, 'utf8') === mutated);

  let coreFailures = 0;
  try {
    const eng2 = await import(pathToFileURL(enginePath).href + '?mutate=' + Date.now());
    if (eng2.binom(52, 5) !== 2598960n) coreFailures++;
    if (!sameRat(eng2.majorityCorrectDirect(3, 2, 3), { num: 20n, den: 27n })) coreFailures++;
    if (!sameRat(eng2.majorityCorrectDP(3, 2, 3), { num: 20n, den: 27n })) coreFailures++;
    if (eng2.ratCompare(eng2.majorityCorrectDirect(9, 11, 20),
      eng2.majorityCorrectDP(9, 11, 20)) !== 0) coreFailures++;
    if (!sameRat(eng2.unanimityConvictGivenGuilty(12, 9, 10),
      { num: 282429536481n, den: 1000000000000n })) coreFailures++;
    const s = eng2.simulateCascade({ nMax: 5, pNum: 3, pDen: 5, c: 0, trials: 50, seed: 3 });
    const ex = eng2.majorityCorrectDirect(3, 3, 5);
    if (s.points[1].pHat !== Number(ex.num) / Number(ex.den)) coreFailures++;
  } catch (e) {
    coreFailures++; // a corrupted engine that will not even load is caught too
  }
  check('mutate: corrupted engine produced ' + coreFailures + ' failing core assertions (need >= 1)',
    coreFailures >= 1);

  writeFileSync(enginePath, original);
  check('mutate: engine.mjs restored byte-for-byte', readFileSync(enginePath, 'utf8') === original);

  const eng3 = await import(pathToFileURL(enginePath).href + '?restore=' + Date.now());
  check('mutate: restored engine passes a spot anchor again',
    eng3.binom(52, 5) === 2598960n &&
    sameRat(eng3.majorityCorrectDirect(3, 2, 3), { num: 20n, den: 27n }));
}

if (process.argv.includes('--mutate')) {
  await mutatePhase();
}

// ══ summary ═══════════════════════════════════════════════════════════════
console.log('');
for (const line of failureLines) console.log(line);
const total = passed + failed;
console.log('CHECKS RUN: ' + total);
console.log('RESULT: checks passed: ' + passed + '/' + total + ' (failed: ' + failed + ')');
if (total === 0) {
  console.log('RESULT: zero checks performed; refusing to report success.');
  process.exit(1);
}
process.exit(failed === 0 ? 0 : 1);
