#!/usr/bin/env node
/* Offline gate for the-walk-that-never-stops-crossing.
 *
 *   node research/the-walk-that-never-stops-crossing/verify-the-walk-that-never-stops-crossing.mjs
 *
 * Node 22, no dependencies, no network. Prints one line per assertion,
 * then a total, and exits non-zero on any FAIL. The full-size section runs
 * the real 10^11-step walk twice under two different chunk counts on a pool
 * of worker threads; on an 8-core machine the whole file takes about two
 * minutes, most of it that section.
 */

import fs from 'node:fs';
import path from 'node:path';
import os from 'node:os';
import crypto from 'node:crypto';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { Worker } from 'node:worker_threads';

const SLUG = 'the-walk-that-never-stops-crossing';
const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, '..', '..');
const PUB = path.join(ROOT, 'public', 'strata', SLUG);
const RESDIR = path.join(ROOT, 'research', '_ox3', 'lib');

let n = 0, npass = 0, nfail = 0, nskip = 0;
function P(ok, msg) {
  n++;
  if (ok) { npass++; console.log('PASS ' + String(n).padStart(3, '0') + '  ' + msg); }
  else { nfail++; console.log('FAIL ' + String(n).padStart(3, '0') + '  ' + msg); }
}
function S(msg) { nskip++; console.log('SKIP  ' + msg); }
function C(ok, msg) {
  console.log((ok ? 'CONTROL ' : 'CTRL-FAIL ') + msg);
  if (!ok) { nfail++; n++; }
}

const t0 = Date.now();

/* ---------------------------------------------------------------- load code */

const wasmPath = path.join(PUB, 'engine.wasm');
if (!fs.existsSync(wasmPath)) {
  console.log('FAIL 000  engine.wasm not found at ' + wasmPath + ' (run the pipeline build first)');
  process.exit(1);
}
const wasmBytes = fs.readFileSync(wasmPath);
const wasmMod = new WebAssembly.Module(wasmBytes);
const x = new WebAssembly.Instance(wasmMod, {}).exports;

const need = ['aw_init', 'aw_chunk', 'aw_out', 'aw_out_len', 'aw_state', 'aw_state_len', 'aw_alloc', 'aw_reset', 'memory'];
P(need.every((k) => k in x), 'engine.wasm instantiates and exports the full ABI (' + need.join(', ') + ')');

const manifest = await import(pathToFileURL(path.join(PUB, 'manifest.js')).href).catch(() => null);
if (!manifest) {
  P(false, 'manifest.js imports (pipeline artifact missing)');
} else {
  const dig = crypto.createHash('sha256').update(wasmBytes).digest('hex');
  P(dig === manifest.WASM_SHA256.toLowerCase(),
    'sha256(engine.wasm) equals manifest.WASM_SHA256 (' + dig.slice(0, 16) + '...)');
}

/* --------------------------------------------------- reproducible build */

try {
  const clangOnPath = (() => {
    try { require('node:child_process'); } catch (_) {}
    return null;
  })();
} catch (_) {}
{
  const { execFileSync } = await import('node:child_process');
  let clangV = null;
  try { clangV = execFileSync('clang', ['--version'], { encoding: 'utf8' }); } catch (_) { clangV = null; }
  const script = path.join(RESDIR, 'build-wasm.sh');
  if (!clangV) {
    S('reproducible build (clang not on PATH)');
  } else if (!manifest || !manifest.CLANG || !clangV.includes(manifest.CLANG)) {
    S('reproducible build (clang ' + (clangV.split('\n')[0] || 'unknown').trim() + ' != pinned ' + (manifest ? manifest.CLANG : 'n/a') + ')');
  } else if (!fs.existsSync(script)) {
    S('reproducible build (research/_ox3/lib/build-wasm.sh not found)');
  } else {
    const tmp = path.join(os.tmpdir(), 'aw-walk-rebuild-' + process.pid + '.wasm');
    try {
      execFileSync('bash', [script, path.join(PUB, 'engine.c'), tmp], { stdio: 'pipe' });
      const rebuilt = fs.readFileSync(tmp);
      P(rebuilt.equals(wasmBytes), 'rebuilt engine.c under the pinned clang is byte-identical to engine.wasm');
    } catch (e) {
      P(false, 'reproducible build failed to run: ' + String(e.message).split('\n')[0]);
    } finally {
      try { fs.unlinkSync(tmp); } catch (_) {}
    }
  }
}

/* ------------------------------------------------------------ the drivers */

// plan.js exports FACTS, SLUG, hdr and `plan`, and everything the battery needs hangs off
// that last one. Binding the module NAMESPACE gave 'plan.battery is not iterable' at the
// first row. Resolved the same way lib/resolve-plan.mjs does, so the four module shapes the
// brief left open all work here.
const planUrl = pathToFileURL(path.join(PUB, 'plan.js')).href;
const planMod = await import(planUrl);
const plan = planMod.plan ?? planMod.default ?? planMod;
const reference = await import(pathToFileURL(path.join(PUB, 'reference.js')).href);
const FACTS = planMod.FACTS ?? plan.FACTS;
const hdr = planMod.hdr;

/* The page does `import { plan, FACTS, hdr, stitch } from './plan.js'`. A named import of an
 * export the module does not have is a link-time error that kills the entire page module and
 * nothing else in this file would notice, so it is asserted here, first. */
{
  const want = ['plan', 'FACTS', 'hdr', 'stitch'];
  const missing = want.filter((k) => !(k in planMod));
  P(missing.length === 0, 'plan.js provides every top-level export the page imports by name ('
    + want.join(', ') + (missing.length ? '; MISSING: ' + missing.join(', ') : '') + ')');
  P(Array.isArray(plan.battery) && plan.battery.length === FACTS.batteryRows,
    'plan.battery is an array of the ' + FACTS.batteryRows + ' rows FACTS declares');
}

/* A row is assembled exactly the way /_kit/deep.js selftest() assembles it: the row's own
 * fields override the plan's, so initial(), nextState(), stitch() and fingerprint() all see
 * the ROW's parameters and the ROW's chunk count rather than the flagship's. Anything that
 * runs here therefore runs the way the reader's browser runs it. */
function mkSub(row) {
  const sub = Object.assign({}, plan, row);
  if (!sub.initialState) {
    const c = sub.current;
    sub.initialState = () => hdr(c.seed, c.N, c.cfix, c.drift || 0);
  }
  sub.rounds = sub.rounds || 2;
  return sub;
}

/* The header a row hands the two implementations is the ONLY thing that tells them which walk
 * to run, and it is built twice: once for round 0 (initialState) and once for round 1
 * (nextState, out of the accumulator's params). If those two disagree, round 1 silently runs a
 * different walk from round 0 -- which is exactly the defect that stalled this piece, and it
 * presents as an implausible speed ratio rather than as a wrong answer. Checked, not assumed. */
function rowHeaders(row) {
  const sub = mkSub(row);
  const s0 = sub.initialState();
  const s1 = sub.nextState(sub.initial(), 0);
  const rd = (b) => {
    const d = new DataView(b.buffer, b.byteOffset, b.byteLength);
    return { seed: d.getBigUint64(0, true), N: d.getBigUint64(8, true),
             cfix: d.getUint32(16, true), drift: d.getUint32(20, true), magic: d.getUint32(28, true) };
  };
  return { sub, r0: rd(s0), r1: rd(s1) };
}

/* One row through the compiled engine, and one through whichever JavaScript implementation is
 * handed in (the honest reference, or the biased twin). Deliberately the same shape. */
function runEngineRow(row) {
  const sub = mkSub(row);
  let acc = sub.initial();
  let state = sub.initialState();
  for (let r = 0; r < sub.rounds; r++) {
    x.aw_reset();
    x.aw_init(sub.p0 >>> 0, sub.p1 >>> 0);
    if (state) new Uint8Array(x.memory.buffer, x.aw_state(), x.aw_state_len()).set(state);
    for (let i = 0; i < sub.chunks; i++) {
      x.aw_chunk(r, i, sub.chunks);
      const out = new Uint8Array(x.memory.buffer, x.aw_out(), x.aw_out_len()).slice();
      sub.reduce(acc, new DataView(out.buffer), i, r);
    }
    if (r + 1 < sub.rounds) {
      state = sub.nextState(acc, r);
      if (sub.resetEachRound !== false) acc = sub.initial(acc, r + 1);
    }
  }
  return acc;
}

function runJsRow(row, impl) {
  const sub = mkSub(row);
  let acc = sub.initial();
  let state = sub.initialState();
  for (let r = 0; r < sub.rounds; r++) {
    impl.init(sub.p0 >>> 0, sub.p1 >>> 0);
    if (state) impl.putState(state);
    for (let i = 0; i < sub.chunks; i++) {
      const c = impl.chunk(r, i, sub.chunks);
      sub.reduce(acc, new DataView(c.out.buffer, c.out.byteOffset, c.out.byteLength), i, r);
    }
    if (r + 1 < sub.rounds) {
      state = sub.nextState(acc, r);
      if (sub.resetEachRound !== false) acc = sub.initial(acc, r + 1);
    }
  }
  return acc;
}

const runRefRow = (row) => runJsRow(row, reference);
const fpOf = (row, acc) => mkSub(row).fingerprint(acc);
const rowSpec = (b) => b;

/* ------------------------------------------------------------- 4. battery */

/* Before running a step of it: does every row actually ask for its own walk in BOTH rounds? */
{
  let ok = true;
  for (const b of plan.battery) {
    const h = rowHeaders(b);
    const same = h.r0.seed === h.r1.seed && h.r0.N === h.r1.N && h.r0.cfix === h.r1.cfix
      && h.r0.drift === h.r1.drift && h.r0.magic === 0x57414C53 && h.r1.magic === 0x57414C53;
    if (!same) {
      ok = false;
      console.log('  row "' + b.label + '": round-0 header asks for N=' + h.r0.N + ' seed=' + h.r0.seed
        + ' c=' + h.r0.cfix + ', round-1 header asks for N=' + h.r1.N + ' seed=' + h.r1.seed + ' c=' + h.r1.cfix);
    }
  }
  P(ok, 'every battery row hands both rounds the same walk (round-0 and round-1 state headers agree)');
}

const fps = [];
let batteryOk = true;
const tbat = Date.now();
let refMs = 0, engMs = 0;
for (const b of plan.battery) {
  const spec = rowSpec(b);
  let t = Date.now();
  const fw = fpOf(spec, runEngineRow(spec));
  engMs += Date.now() - t;
  t = Date.now();
  const fr = fpOf(spec, runRefRow(spec));
  refMs += Date.now() - t;
  if (fw !== fr) { batteryOk = false; console.log('  row "' + b.label + '": wasm ' + fw + ' vs ref ' + fr); }
  fps.push(fw);
}
console.log('# battery cost: engine ' + engMs + ' ms, JavaScript reference ' + refMs + ' ms over the same '
  + plan.battery.length + ' rows (ratio ' + (refMs / Math.max(engMs, 1)).toFixed(0) + 'x)');
P(batteryOk, 'battery: wasm and reference fingerprints agree on all ' + plan.battery.length + ' rows');
// The battery must reach more than one instance, NOT have pairwise-distinct rows: the
// full-size check recomputes the same instance under a different decomposition, so where
// that row sits in the battery it agrees by construction. Coinciding rows are reported.
P(new Set(fps).size >= 2, `battery exercises ${new Set(fps).size} distinct instance(s) across ${fps.length} rows` + (new Set(fps).size < fps.length ? `, ${fps.length - new Set(fps).size} agreeing across a different decomposition` : ''));

/* --------------------------------------------------------- 5. the control */

const broken = plan.breakReference(reference);
P(broken !== reference, 'breakReference returns a different object (it mutates something)');
let caught = 0;
for (const b of plan.battery) {
  const spec = rowSpec(b);
  const fw = fpOf(spec, runEngineRow(spec));
  const fb = fpOf(spec, runJsRow(spec, broken));
  if (fw !== fb) caught++;
}
P(caught >= 1, 'control: the biased reference disagrees on ' + caught + ' of ' + plan.battery.length + ' battery rows');

/* ------------------------------------------- planted-data positive control */

{
  const spec = { p0: FACTS.seed, p1: 65536, chunks: FACTS.driftChunks,
    current: { seed: FACTS.seed, N: FACTS.driftN, cfix: 65536, drift: FACTS.driftPeriod } };
  const ae = runEngineRow(spec);
  const ar = runRefRow(spec);
  const fe = fpOf(spec, ae);
  const fr = fpOf(spec, ar);
  const cr = planMod.stitch(ae);
  const last = cr[cr.length - 1];
  P(fe === fr, 'planted drift: unmodified engine and reference agree on the doctored input');

  /* The old threshold here was `cr.length >= 3`, and it is arithmetically at odds with the
   * drift it plants. A +1 every 64th step carries the position to about n/64, which is 31,250
   * by step 2,000,000, while the boundary there is only about 3,271. Past the crossover the
   * walk is above the curve at every single step, and a crossing is by definition a MAXIMAL
   * run of such steps, so the doctored walk can only ever report ONE. Demanding three demands
   * that the drift let go three times, which is what planting it prevents. What the control is
   * actually for is that the detector fires at all and stays fired to the horizon, which is
   * what the piece's own README claims for it. Both halves are asserted, and the fair walk on
   * the same seed and horizon is run as the negative half so that "fires" is not vacuous. */
  const covered = cr.filter((c) => c.end >= 0.9 * FACTS.driftN).length;
  P(cr.length >= 1 && covered >= 1,
    'planted drift: detector fires (' + cr.length + ' excursion(s), ' + covered + ' reaching the horizon)');
  P(last && last.end >= 0.9 * FACTS.driftN,
    'planted drift: the final excursion runs to the horizon (end=' + (last ? last.end : -1) + ' of ' + FACTS.driftN + ')');

  const fairSpec = { p0: FACTS.seed, p1: 65536, chunks: FACTS.driftChunks,
    current: { seed: FACTS.seed, N: FACTS.driftN, cfix: 65536, drift: 0 } };
  const fair = planMod.stitch(runEngineRow(fairSpec));
  const fairCovered = fair.filter((c) => c.end >= 0.9 * FACTS.driftN).length;
  C(fairCovered === 0, 'negative control: the SAME detector on the SAME seed and horizon with the drift '
    + 'removed reports ' + fair.length + ' excursion(s) and ' + fairCovered + ' reaching the horizon, '
    + 'so the planted-drift result is a response to the doctored input and not to the detector');
}

/* ------------------------------------------- exact binomial machinery */

function lnFact(n) {
  if (n < 32) { let s = 0; for (let i = 2; i <= n; i++) s += Math.log(i); return s; }
  const z = n + 1;
  return 0.5 * Math.log(2 * Math.PI) + (z - 0.5) * Math.log(z) - z
    + 1 / (12 * z) - 1 / (360 * z * z * z) + 1 / (1260 * z * z * z * z * z);
}
const LN2 = Math.log(2);
function lnBinom(n, k) { return lnFact(n) - lnFact(k) - lnFact(n - k); }
function upperTail(n, a) {           // P(S_n >= a) for the fair walk, a >= 1
  const k0 = Math.ceil((n + a) / 2);
  let p = 0;
  for (let k = k0; k <= n; k++) {
    const t = Math.exp(lnBinom(n, k) - n * LN2);
    p += t;
    if (t < 1e-24 && k > k0 + 10) break;
  }
  return p;
}
function twoSidedP(n, h) {           // P(|S_n| >= |2h - n|)
  const dev = Math.abs(2 * h - n);
  if (dev === 0) return 1;
  const up = upperTail(n, dev);
  let p = 2 * up;
  if (Number.isInteger((n + dev) / 2)) p -= Math.exp(lnBinom(n, (n + dev) / 2) - n * LN2);
  return p;
}
{ // validate the Stirling log-factorial before it is trusted anywhere
  let exact = 0; for (let i = 2; i <= 2000; i++) exact += Math.log(i);
  P(Math.abs(lnFact(2000) - exact) < 1e-6, 'Stirling ln-factorial matches exact summation at n=2000 to 1e-6');
  let mass = 0; for (let k = 0; k <= 100; k++) mass += Math.exp(lnBinom(100, k) - 100 * LN2);
  P(Math.abs(mass - 1) < 1e-9, 'binomial pmf from the same machinery sums to 1 over k=0..100 (mass=' + mass.toFixed(12) + ')');
}

/* ------------------- the shared contract, against something outside both sides */

/* The hash and the log series are shared between engine.c and reference.js on purpose, and
 * that is precisely where the battery is blind: if the 18-term series were wrong, both
 * implementations would compute the same wrong boundary and every row would still agree. The
 * platform's own Math.log has no part in either implementation, so it is an outside witness.
 * Same for the quantised boundary, recomputed here from Math.log and Math.sqrt. */
{
  let worst = 0, worstX = 0, cnt = 0;
  const crippled = (v) => {          // the same series truncated to 2 terms: the control
    const buf = new ArrayBuffer(8);
    const f = new Float64Array(buf), u = new BigUint64Array(buf);
    f[0] = v;
    let b = u[0];
    const E = Number((b >> 52n) & 2047n) - 1023;
    u[0] = (b & 0x000FFFFFFFFFFFFFn) | 0x3FF0000000000000n;
    const m = f[0], z = (m - 1.0) / (m + 1.0), z2 = z * z;
    let term = 1.0, s = 1.0;
    for (let i = 1; i <= 2; i++) { term *= z2; s += term / (2 * i + 1); }
    return E * 0.6931471805599453 + 2.0 * z * s;
  };
  let worstCrip = 0;
  for (let e = -20; e <= 40; e++) {
    for (let f = 1; f < 64; f++) {
      const xv = Math.pow(2, e) * (1 + f / 64);
      const truth = Math.log(xv);
      const den = Math.max(Math.abs(truth), 1e-300);
      const rel = Math.abs(reference.lnPos(xv) - truth) / den;
      if (rel > worst) { worst = rel; worstX = xv; }
      worstCrip = Math.max(worstCrip, Math.abs(crippled(xv) - truth) / den);
      cnt++;
    }
  }
  P(worst < 1e-12, 'shared log series agrees with the platform Math.log on ' + cnt
    + ' arguments (worst relative ' + worst.toExponential(2) + ' at x=' + worstX + ')');
  C(worstCrip >= 1e-12, 'negative control: the same comparison rejects the series truncated to two '
    + 'terms (worst relative ' + worstCrip.toExponential(2) + '), so it is not measuring nothing');

  let checked = 0, mism = 0, skipped = 0;
  for (const cfix of [65536, 32768, 72090]) {
    const c = cfix / 65536;
    for (let k = 1; k <= 400; k++) {
      const nn = Math.round(Math.pow(10, 4.9 + (k / 400) * 6.1));
      const nb = Math.floor(nn / 65536) * 65536;
      if (nb < 65536) continue;
      const l2 = Math.log(Math.log(nb));
      if (!(l2 > 0)) continue;
      const bm = Math.sqrt(2 * c * nb * l2);
      const frac = bm / 64 - Math.floor(bm / 64);
      // A sample sitting on a quantisation edge would be decided by the last bit of two
      // different computations, which is not what is under test. Counted and reported.
      if (frac < 1e-9 || frac > 1 - 1e-9) { skipped++; continue; }
      checked++;
      if (reference.boundaryAt(cfix, nn) !== Math.floor(bm / 64) * 64) mism++;
    }
  }
  P(checked > 1000 && mism === 0, 'quantised boundary Q(n) matches an independent Math.log/Math.sqrt '
    + 'recomputation on ' + checked + ' samples across three c (' + mism + ' mismatches, '
    + skipped + ' skipped on a quantisation edge)');
}

/* ------------------------------- 6. full size: two decompositions, invariants */

const WORKER_SRC = `
import { parentPort } from 'node:worker_threads';
let mod = null, inst = null, acc = null, planP = null;
parentPort.on('message', async (m) => {
  try {
    if (m.t === 'module') {
      // WebAssembly.Module is a constructor: calling it without new throws, the catch below
      // turns that into an 'error' message, and the pool never boots.
      mod = new WebAssembly.Module(new Uint8Array(m.bytes));
      inst = new WebAssembly.Instance(mod, {});
      parentPort.postMessage({ t: 'ready' });
      return;
    }
    if (m.t === 'round0') {
      // The module NAMESPACE is sealed; assigning .current to it throws in strict mode. The
      // plan object is what carries current/chunks, and both must be set before initial().
      const pm = await import(m.planUrl);
      planP = pm.plan;
      planP.chunks = m.chunks;
      planP.current = m.current;
      acc = planP.initial();
      const xx = inst.exports;
      xx.aw_reset(); xx.aw_init(m.p0 >>> 0, m.p1 >>> 0);
      new Uint8Array(xx.memory.buffer, xx.aw_state(), xx.aw_state_len()).set(planP.initialState());
      for (const i of m.idxList) {
        xx.aw_chunk(0, i, m.chunks);
        const out = new Uint8Array(xx.memory.buffer, xx.aw_out(), xx.aw_out_len()).slice();
        planP.reduce(acc, new DataView(out.buffer), i, 0);
      }
      // ONLY this worker's own chunks. Reporting the whole array meant every worker also
      // reported 0n for the chunks it never ran, and the parent assigns every pair it is sent,
      // so the last pool member to answer zeroed all the others' sums. The events reply below
      // already filters this way (untouched entries are null); this one did not.
      const sums = [], heads = [];
      for (const i of m.idxList) { sums.push([i, acc.sums[i]]); heads.push([i, acc.heads[i]]); }
      parentPort.postMessage({ t: 'sums', sums, heads });
      return;
    }
    if (m.t === 'round1') {
      const xx = inst.exports;
      xx.aw_reset(); xx.aw_init(m.p0 >>> 0, m.p1 >>> 0);
      new Uint8Array(xx.memory.buffer, xx.aw_state(), xx.aw_state_len()).set(m.state);
      for (const i of m.idxList) {
        xx.aw_chunk(1, i, m.chunks);
        const out = new Uint8Array(xx.memory.buffer, xx.aw_out(), xx.aw_out_len()).slice();
        planP.reduce(acc, new DataView(out.buffer), i, 1);
      }
      const events = [];
      for (let i = 0; i < m.chunks; i++) { if (acc.events[i]) events.push([i, acc.events[i]]); }
      parentPort.postMessage({ t: 'done', events, ext: acc.ext, overflow: acc.overflow });
      return;
    }
  } catch (e) {
    parentPort.postMessage({ t: 'error', message: String((e && e.stack) || e) });
  }
});
`;

const fullSub = (chunks) => Object.assign({}, plan, {
  chunks, current: { seed: FACTS.seed, N: FACTS.N, cfix: 65536, drift: 0 },
});

async function runFullSize(chunks) {
  const N = FACTS.N, seed = FACTS.seed, cfix = 65536;
  const nW = Math.max(2, Math.min(os.cpus() ? os.cpus().length : 4, 8));
  const wpath = path.join(os.tmpdir(), 'aw-walk-worker-' + process.pid + '.mjs');
  fs.writeFileSync(wpath, WORKER_SRC);
  const workers = [];
  try {
    for (let i = 0; i < nW; i++) workers.push(new Worker(wpath));
    await Promise.all(workers.map((w) => new Promise((res, rej) => {
      w.once('message', (m) => (m.t === 'ready' ? res() : rej(new Error('worker boot'))));
      w.postMessage({ t: 'module', bytes: wasmBytes });
    })));
    const idxLists = Array.from({ length: nW }, () => []);
    for (let i = 0; i < chunks; i++) idxLists[i % nW].push(i);
    const sums = new Array(chunks).fill(0n);
    const heads = new Array(chunks).fill(0n);
    await Promise.all(workers.map((w, i) => new Promise((res, rej) => {
      w.once('message', (m) => {
        if (m.t === 'error') return rej(new Error(m.message));
        for (const [j, v] of m.sums) sums[j] = v;
        for (const [j, v] of m.heads) heads[j] = v;
        res();
      });
      w.postMessage({ t: 'round0', idxList: idxLists[i], chunks, p0: seed, p1: cfix,
        current: { seed, N, cfix, drift: 0 }, planUrl: pathToFileURL(path.join(PUB, 'plan.js')).href });
    })));
    const acc0 = { sums, heads, events: new Array(chunks).fill(null), ext: null, overflow: false,
      params: { seed, N, cfix, drift: 0 } };
    // nextState() prefix-sums `chunks` entries and states the count in the header, so it has to
    // be called on a plan whose chunk count is THIS decomposition's, not the default 2048.
    const state = fullSub(chunks).nextState(acc0, 0);
    const events = new Array(chunks).fill(null);
    let ext = null, overflow = false;
    await Promise.all(workers.map((w, i) => new Promise((res, rej) => {
      w.once('message', (m) => {
        if (m.t === 'error') return rej(new Error(m.message));
        for (const [j, e] of m.events) events[j] = e;
        if (m.ext) {
          if (!ext) ext = m.ext;
          else {
            if (m.ext.max > ext.max || (m.ext.max === ext.max && m.ext.maxAt < ext.maxAt)) ext = { ...ext, max: m.ext.max, maxAt: m.ext.maxAt };
            if (m.ext.min < ext.min || (m.ext.min === ext.min && m.ext.minAt < ext.minAt)) ext = { ...ext, min: m.ext.min, minAt: m.ext.minAt };
          }
        }
        overflow = overflow || m.overflow;
        res();
      });
      w.postMessage({ t: 'round1', idxList: idxLists[i], chunks, state, p0: seed, p1: cfix });
    })));
    return { sums, heads, events, ext, overflow, params: { seed, N, cfix, drift: 0 } };
  } finally {
    for (const w of workers) { try { await w.terminate(); } catch (_) {} }
    try { fs.unlinkSync(wpath); } catch (_) {}
  }
}

console.log('# full size: ' + FACTS.N.toExponential() + ' steps, chunkings ' + FACTS.chunksA + ' and ' + FACTS.chunksB + ', on ' + Math.min(os.cpus() ? os.cpus().length : 4, 8) + ' workers');
const tfs = Date.now();
const A = await runFullSize(FACTS.chunksA);
const B = await runFullSize(FACTS.chunksB);
console.log('# full-size section took ' + ((Date.now() - tfs) / 1000).toFixed(1) + ' s');

const fpA = fullSub(FACTS.chunksA).fingerprint(A);
const fpB = fullSub(FACTS.chunksB).fingerprint(B);
P(fpA === fpB, 'full size: both decompositions produce the identical fingerprint (' + fpA.slice(0, 40) + '...)');
P(!A.overflow && !B.overflow, 'full size: no chunk exceeded its event-record capacity');

const endA = A.sums.reduce((a, b) => a + b, 0n);
const headsA = A.heads.reduce((a, b) => a + b, 0n);
P(endA === 2n * headsA - BigInt(FACTS.N),
  'invariant: endpoint equals 2H - N exactly (S=' + endA + ', H=' + headsA + ')');
{
  // "Inside the two-sided interval at alpha" is p >= alpha: a SMALL p is a head count so far
  // from N/2 that a fair coin is rejected. The assertion read `p <= alpha`, which demanded the
  // opposite and would have passed only on a walk that failed the test. Direction corrected,
  // and positive-controlled immediately below so the check is known to be able to go red.
  // twoSidedP does Number arithmetic; H is about 5e10, well inside exact double integers, but
  // it arrives as a BigInt and `2 * h` would throw on the mix.
  const H = Number(headsA);
  P(Number.isSafeInteger(H) && BigInt(H) === headsA, 'head count converts to an exact double (H=' + H + ')');
  const p = twoSidedP(FACTS.N, H);
  P(p >= FACTS.ciAlpha, 'invariant: head count inside the exact two-sided binomial interval at alpha='
    + FACTS.ciAlpha + ' (p=' + p.toExponential(2) + ')');
  const pBad = twoSidedP(FACTS.N, H + Math.round(3 * Math.sqrt(FACTS.N)));
  C(pBad < FACTS.ciAlpha, 'negative control: the same test rejects a head count moved by 6 sigma (p='
    + pBad.toExponential(2) + ' < ' + FACTS.ciAlpha + '), so the interval check can fail');
}
{
  const cr = planMod.stitch(A);
  const crB = planMod.stitch(B);
  P(JSON.stringify(cr) === JSON.stringify(crB), 'full size: stitched crossing lists identical under both chunkings (' + cr.length + ' crossings)');
}

/* ------------------------------------------ reflection principle, aggregate */

/* What a seed IS, checked rather than assumed. Step k is drawn from splitmix64(k + seed), so
 * the seed is an offset into one stream: the walk with seed s+d is the walk with seed s
 * translated by d steps, exactly. Every ensemble here therefore has to space its seeds by more
 * than the walk it runs, or it is one walk counted many times. Both halves are asserted. */
{
  let shiftOk = true, sample = 0;
  for (const s of [0n, 7n, 20260825n, 1000000000n]) {
    for (const d of [1n, 3n, 65536n]) {
      for (const k of [1n, 2n, 999n, 123456n]) {
        sample++;
        if (reference.hashStep(k + d, s) !== reference.hashStep(k, s + d)) shiftOk = false;
      }
    }
  }
  P(shiftOk, 'the seed is an offset into one stream: increment(k+d, seed s) equals increment(k, seed s+d) '
    + 'on all ' + sample + ' sampled (s, d, k), which is why every ensemble strides its seeds');
  P(FACTS.reflStride > FACTS.reflN && FACTS.ensStride > FACTS.ensN && FACTS.traceStride > FACTS.traceSteps,
    'every ensemble stride exceeds its own horizon, so the windows are disjoint (refl '
    + FACTS.reflStride + '>' + FACTS.reflN + ', ens ' + FACTS.ensStride + '>' + FACTS.ensN
    + ', trace ' + FACTS.traceStride + '>' + FACTS.traceSteps + ')');
}

{
  const NN = FACTS.reflN, AA = FACTS.reflA;
  const runEnsemble = (stride) => {
    let ge = 0;
    const maxes = [];
    for (let s = 1; s <= FACTS.reflWalks; s++) {
      const seed = s * stride;
      const acc = runEngineRow({ p0: 1, p1: 65536, chunks: 1, current: { seed, N: NN, cfix: 65536, drift: 0 } });
      if (acc.ext) { maxes.push(Number(acc.ext.max)); if (acc.ext.max >= BigInt(AA)) ge++; }
    }
    maxes.sort((a, b) => a - b);
    return { emp: ge / FACTS.reflWalks, lo: maxes[0], hi: maxes[maxes.length - 1] };
  };
  const theory = 2 * upperTail(NN, AA) - Math.exp(lnBinom(NN, (NN + AA) / 2) - NN * LN2);
  const se = Math.sqrt(theory * (1 - theory) / FACTS.reflWalks);
  P(theory > 0.05 && theory < 0.6, 'reflection principle: exact formula gives a sane probability (P(M>='
    + AA + ')=' + theory.toFixed(4) + ')');

  const r = runEnsemble(FACTS.reflStride);
  P(Math.abs(r.emp - theory) <= 4 * se, 'reflection principle over ' + FACTS.reflWalks
    + ' disjoint-window walks: empirical ' + r.emp.toFixed(4) + ' vs exact ' + theory.toFixed(4)
    + ' (4se=' + (4 * se).toFixed(4) + '; walk maxima span ' + r.lo + ' to ' + r.hi + ')');

  /* The control on that check, and the reason this piece was wrong: run the SAME ensemble with
   * consecutive seeds, which is what it used to do, and require the comparison to go red. If
   * this came back green the reflection check could not tell an ensemble from one walk. */
  const bad = runEnsemble(1);
  C(Math.abs(bad.emp - theory) > 4 * se, 'negative control: the same test on ' + FACTS.reflWalks
    + ' CONSECUTIVE seeds reports empirical ' + bad.emp.toFixed(4) + ' against exact '
    + theory.toFixed(4) + ' (their maxima span only ' + bad.lo + ' to ' + bad.hi
    + '), so the check can tell one walk from an ensemble');
}

/* ------------------------------------- 7. the page's stated fixed facts */

{
  const html = fs.readFileSync(path.join(PUB, 'index.html'), 'utf8');
  const m = html.match(/<script type="application\/json" id="stated-facts">([\s\S]*?)<\/script>/);
  P(!!m, 'page ships a machine-readable stated-facts block');
  if (m) {
    let stated = null;
    try { stated = JSON.parse(m[1]); } catch (_) {}
    P(!!stated && JSON.stringify(stated) === JSON.stringify(FACTS),
      'every fixed fact stated by the page equals the values these runs actually used');
    P(html.includes('research/' + SLUG + '/verify-' + SLUG + '.mjs'),
      'page names this verifier and the path resolves');
  }
}

/* ------------------------------- 8. negative controls on the verifier itself */

{
  const bad = Uint8Array.from(wasmBytes);
  bad[bad.length - 1] ^= 0xff;
  const dig = crypto.createHash('sha256').update(bad).digest('hex');
  C(dig !== manifest.WASM_SHA256.toLowerCase(), 'negative control: flipping one wasm byte changes the digest, so assertion 2 would fail');
}
{
  const row = rowSpec(plan.battery[0]);
  const acc = runEngineRow(row);
  const fp1 = fpOf(row, acc);
  const acc2 = { ...acc, sums: [...acc.sums] };
  acc2.sums[acc2.sums.length - 1] += 2n;
  const fp2 = fpOf(row, acc2);
  C(fp1 !== fp2, 'negative control: moving the endpoint by 2 changes the fingerprint, so the battery comparison would fail');
}

/* ------------------------------------------------------------------- total */

console.log('');
console.log('TOTAL ' + npass + ' pass, ' + nfail + ' fail, ' + nskip + ' skip  (' + ((Date.now() - t0) / 1000).toFixed(1) + ' s)');
process.exit(nfail > 0 ? 1 : 0);
