#!/usr/bin/env node
// verify-sixty-five-thousand-contestants.mjs — the offline gate.
//
// Run from a fresh checkout with:  node research/sixty-five-thousand-contestants/verify-sixty-five-thousand-contestants.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 checks run the REAL tournament (all 65,536 strategies,
// all 2,147,516,416 matches) through the committed wasm engine across
// every core this machine has, via node:worker_threads. On an 8-core
// machine the whole gate takes roughly two to four minutes; most of that
// is the two full play-out passes, which are the point.

import { readFileSync, existsSync, mkdtempSync, writeFileSync } from 'node:fs';
import { createHash } from 'node:crypto';
import { tmpdir } from 'node:os';
import path from 'node:path';
import os from 'node:os';
import { fileURLToPath } from 'node:url';
import { execFileSync, spawnSync } from 'node:child_process';
import { Worker } from 'node:worker_threads';

const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, '..', '..');
const SLUG = 'sixty-five-thousand-contestants';
const DIR = path.join(ROOT, 'public', 'strata', SLUG);

const N = 65536, H = 100;
const PAY = { T: 5, R: 3, P: 1, S: 0 };
const NMATCHES = N * (N + 1) / 2;          // 2,147,516,416

// The repo's .js modules are ES modules but the root package.json may not
// say type:module, so load them through data: URLs, which node always
// parses as ESM. None of them has relative imports.
async function loadESM(p) {
  const src = readFileSync(p, 'utf8');
  return import('data:text/javascript;charset=utf-8;base64,' + Buffer.from(src).toString('base64'));
}

const plan = await loadESM(path.join(DIR, 'plan.js'));
const refImpl = await loadESM(path.join(DIR, 'reference.js'));
const manifest = await loadESM(path.join(DIR, 'manifest.js'));

const wasmBytes = readFileSync(path.join(DIR, 'engine.wasm'));

// ------------------------------------------------------------------ harness

let n = 0, passes = 0, fails = 0;
function check(desc, ok, extra) {
  n++;
  const tag = 'PASS ' + String(n).padStart(3, '0');
  if (ok) { passes++; console.log(tag + '  ' + desc); }
  else { fails++; console.log('FAIL ' + String(n).padStart(3, '0') + '  ' + desc + (extra ? ' :: ' + extra : '')); }
}
function skip(desc, why) {
  console.log('SKIP  ' + desc + ' (' + why + ')');
}
function ctl(desc, ok) {
  if (ok) console.log('CONTROL  ' + desc);
  else { fails++; console.log('FAIL     ' + desc + ' :: the mutation was NOT caught'); }
}
function log(msg) { console.log('  .. ' + msg); }

// ------------------------------------------------------------ small runner

function makeWasmInstance() {
  const mod = new WebAssembly.Module(wasmBytes);
  const ex = new WebAssembly.Instance(mod, {}).exports;
  return {
    exports: ex,
    init(p0, p1) {
      if (ex.aw_reset) ex.aw_reset();
      ex.aw_init(p0 >>> 0, p1 >>> 0);
    },
    chunk(round, idx, nch) {
      const ops = ex.aw_chunk(round >>> 0, idx >>> 0, nch >>> 0);
      const len = ex.aw_out_len() >>> 0;
      const ptr = ex.aw_out() >>> 0;
      const out = new Uint8Array(ex.memory.buffer, ptr, len).slice();
      return { out, ops: BigInt.asUintN(64, typeof ops === 'bigint' ? ops : BigInt(ops)) };
    },
  };
}

function runSmall(impl, p0v, p1v, nch) {
  const acc = plan.initial();
  impl.init(p0v, p1v);
  let ops = 0n;
  for (let i = 0; i < nch; i++) {
    const c = impl.chunk(0, i, nch);
    ops += BigInt(c.ops);
    plan.reduce(acc, new DataView(c.out.buffer, c.out.byteOffset, c.out.byteLength));
  }
  return { acc, ops };
}

// ------------------------------------------------------- full-size runner
//
// One wasm instance per worker thread; chunk indices split contiguously.
// Chunk records are summed per worker into f64 (exact: every value is an
// integer below 2^53) and merged on the main thread.

const workerSrc = `
const { parentPort } = require('node:worker_threads');
let ex = null;
parentPort.on('message', (m) => {
  if (m.t === 'bytes') {
    const mod = new WebAssembly.Module(m.bytes);
    ex = new WebAssembly.Instance(mod, {}).exports;
    parentPort.postMessage({ t: 'ready' });
    return;
  }
  if (m.t === 'job') {
    if (ex.aw_reset) ex.aw_reset();
    ex.aw_init(m.p0 >>> 0, m.p1 >>> 0);
    if (m.state) new Uint8Array(ex.memory.buffer, ex.aw_state() >>> 0, ex.aw_state_len() >>> 0).set(m.state);
    const len = ex.aw_out_len() >>> 0;
    const evo = m.evo;
    const tot = new Float64Array(65536);
    let c0 = 0, c1 = 0, c2 = 0, ops = 0n;
    for (let idx = m.lo; idx < m.hi; idx++) {
      const o = ex.aw_chunk(0, idx, m.chunks);
      ops += BigInt.asUintN(64, o);
      const ptr = ex.aw_out() >>> 0;
      const buf = ex.memory.buffer;
      if (evo) {
        const f = new Float64Array(buf, ptr, 65536);
        for (let k = 0; k < 65536; k++) tot[k] += f[k];
      } else {
        const dv = new DataView(buf, ptr, len);
        for (let k = 0; k < 65536; k++) tot[k] += dv.getUint32(k * 8, true) + dv.getUint32(k * 8 + 4, true) * 4294967296;
      }
      const dv2 = new DataView(buf, ptr, len);
      c0 += dv2.getUint32(65536 * 8, true) + dv2.getUint32(65536 * 8 + 4, true) * 4294967296;
      c1 += dv2.getUint32(65536 * 8 + 8, true) + dv2.getUint32(65536 * 8 + 12, true) * 4294967296;
      c2 += dv2.getUint32(65536 * 8 + 16, true) + dv2.getUint32(65536 * 8 + 20, true) * 4294967296;
    }
    parentPort.postMessage({ t: 'done', tot: tot.buffer, c0, c1, c2, ops }, [tot.buffer]);
  }
});
`;

async function runFull(opts) {
  const p0v = opts.p0 >>> 0, p1v = opts.p1 >>> 0, nch = opts.chunks;
  const nW = Math.max(1, Math.min(os.cpus().length || 1, 16));
  const per = Math.ceil(nch / nW);
  const jobs = [];
  for (let w = 0; w < nW; w++) {
    const lo = w * per, hi = Math.min(nch, lo + per);
    if (lo < hi) jobs.push({ lo, hi });
  }
  const acc = plan.initial();
  let ops = 0n;
  const t0 = Date.now();
  await Promise.all(jobs.map((job) => new Promise((res, rej) => {
    const wk = new Worker(workerFile);
    wk.on('message', (m) => {
      if (m.t === 'ready') {
        wk.postMessage({
          t: 'job', p0: p0v, p1: p1v, chunks: nch, lo: job.lo, hi: job.hi,
          evo: !!opts.evo,
          state: opts.state ? Buffer.from(opts.state.buffer, opts.state.byteOffset, opts.state.byteLength) : null,
        });
      } else if (m.t === 'done') {
        const tot = new Float64Array(m.tot);
        for (let k = 0; k < N; k++) acc.tot[k] += tot[k];
        acc.nCC += m.c0; acc.nSplit += m.c1; acc.nDD += m.c2;
        ops += BigInt(m.ops);
        wk.terminate();
        res();
      }
    });
    wk.on('error', rej);
    wk.postMessage({ t: 'bytes', bytes: wasmBytes });
  })));
  return { acc, ops, ms: Date.now() - t0, workers: jobs.length };
}

// the worker source goes through a temp .cjs file so node cannot mistake
// it for an ES module no matter what the repo's package.json says
const tmpDir = mkdtempSync(path.join(tmpdir(), 'aw-verify-'));
const workerFile = path.join(tmpDir, 'deep-worker.cjs');
writeFileSync(workerFile, workerSrc);

// ================================================================ assertions

// 1. compile-free load and ABI exports
{
  const ex = new WebAssembly.Instance(new WebAssembly.Module(wasmBytes), {}).exports;
  const need = ['aw_init', 'aw_chunk', 'aw_out', 'aw_out_len', 'aw_state', 'aw_state_len', 'memory'];
  const missing = need.filter((k) => !(k in ex));
  check('engine.wasm instantiates and exports the ABI (' + need.join(', ') + ')', missing.length === 0,
    missing.length ? 'missing: ' + missing.join(', ') : '');
}

// 2. hash
{
  const digest = createHash('sha256').update(wasmBytes).digest('hex');
  check('sha256(engine.wasm) equals WASM_SHA256 in manifest.js (' + digest.slice(0, 16) + '...)',
    digest === String(manifest.WASM_SHA256).toLowerCase());
}

// 3. reproducible build, with an honest skip
{
  let found = '';
  try { found = execFileSync('clang', ['--version'], { encoding: 'utf8' }).split('\n')[0].trim(); } catch (_) { /* absent */ }
  const pinned = String(manifest.CLANG || '');
  const ver = (s) => (s.match(/\b\d+\.\d+\.\d+\b/) || [null])[0];
  const buildScript = path.join(ROOT, 'research', '_ox3', 'lib', 'build-wasm.sh');
  if (!found || !pinned || ver(found) !== ver(pinned)) {
    skip('reproducible build', 'clang ' + (found || 'absent') + ' != pinned ' + (pinned || 'none'));
  } else if (!existsSync(buildScript)) {
    // 2026-09-27: a copy run outside the repository has the pinned clang but no build
    // script; that is the documented SKIP, not a failed build.
    skip('reproducible build', 'build script ' + path.relative(ROOT, buildScript) + ' absent (run outside the repository)');
  } else {
    const out = path.join(tmpDir, 'rebuilt.wasm');
    const r = spawnSync('bash',
      [buildScript, path.join(DIR, 'engine.c'), out],
      { encoding: 'utf8' });
    if (r.status !== 0 || !existsSync(out)) {
      check('reproducible build: rebuilt bytes identical to committed engine.wasm', false,
        'build-wasm.sh failed: ' + (r.stderr || r.stdout || 'status ' + r.status));
    } else {
      const rd = createHash('sha256').update(readFileSync(out)).digest('hex');
      check('reproducible build: rebuilt bytes identical to committed engine.wasm', rd === createHash('sha256').update(wasmBytes).digest('hex'));
    }
  }
}

// 4. battery: both implementations, identical fingerprints, and the row
//    pattern that makes the battery mean something
const batRows = [];
{
  let allAgree = true;
  const badRows = [];
  for (const b of plan.battery) {
    const w = runSmall(makeWasmInstance(), b.p0, b.p1, b.chunks);
    const r = runSmall(refImpl, b.p0, b.p1, b.chunks);
    const fw = plan.fingerprint(w.acc), fr = plan.fingerprint(r.acc);
    batRows.push({ label: b.label, role: b.role || 'semantic', wasm: fw, ref: fr, agree: fw === fr });
    if (fw !== fr) { allAgree = false; badRows.push(b.label + ' (wasm ' + fw.slice(0, 10) + '... vs ref ' + fr.slice(0, 10) + '...)'); }
  }
  check('battery: wasm and reference fingerprints identical on all ' + plan.battery.length + ' rows',
    allAgree, badRows.length ? 'disagreeing rows: ' + badRows.join('; ') : '');

  // Rows carry roles, pinned in plan.js:
  //   baseline    the forward play-out every other row is measured against
  //   traversal   changes ONLY the walk direction; must EQUAL the baseline,
  //               because order is traversal, not semantics
  //   crossmethod changes ONLY the scoring algorithm (cycle detection); must
  //               EQUAL the baseline, because it implements the same
  //               contract: this row is the battery-scale form of the
  //               full-size cross-method check (c)
  //   semantic    changes the semantics (horizon, payoffs, field size,
  //               planted or flat field); must DIFFER from the baseline, or
  //               the engine is ignoring its parameters
  // The previous single assertion demanded that every row except the
  // reversed one differ from the baseline. That mislabelled the cycle
  // method as a semantics change: satisfying it would have REQUIRED the
  // cycle method to disagree with round-by-round play, i.e. required the
  // cross-method property to fail. The row was mislabelled by the
  // assertion, not inert in the engine; see FIX-NOTE.md.
  const bases = batRows.filter((r) => r.role === 'baseline');
  check('battery: exactly one forward baseline row', bases.length === 1,
    bases.length === 1 ? '' : 'found ' + bases.length + ' baseline rows');
  const base = bases[0];

  const travBad = batRows.filter((r) => r.role === 'traversal' && r.wasm !== base.wasm);
  check('battery: reversed pair order equals forward order exactly (order is traversal, not semantics)',
    batRows.some((r) => r.role === 'traversal') && travBad.length === 0,
    travBad.length ? 'offender: ' + travBad.map((r) => r.label).join('; ') : '');

  const crossBad = batRows.filter((r) => r.role === 'crossmethod' && r.wasm !== base.wasm);
  check('battery: cycle-method row reproduces the play-out baseline exactly (same contract, different algorithm)',
    batRows.some((r) => r.role === 'crossmethod') && crossBad.length === 0,
    crossBad.length ? 'offender: ' + crossBad.map((r) => r.label).join('; ') : '');

  const semBad = batRows.filter((r) => r.role === 'semantic' && r.wasm === base.wasm);
  check('battery: every semantics-changing row differs from the forward baseline',
    batRows.some((r) => r.role === 'semantic') && semBad.length === 0,
    semBad.length ? 'offender: ' + semBad.map((r) => r.label).join('; ') : '');
}
// 4b. the step counter is a real count, not an estimate; and the corrected
//     payoff identity at a scale the reference also ran
{
  const b = plan.battery[0];                       // 16 strategies, play-out, horizon 100
  const w = runSmall(makeWasmInstance(), b.p0, b.p1, b.chunks);
  const expect = BigInt(100 * (16 * 17 / 2));      // rounds played, exactly
  check('step-counter honesty: play-out ops == matches x horizon (' + expect + ')', w.ops === expect, 'got ' + w.ops);
  const c = plan.battery[4];                       // cycle method row
  const wc = runSmall(makeWasmInstance(), c.p0, c.p1, c.chunks);
  check('step-counter honesty: cycle-mode ops >= one iteration per match and < play-out ops',
    wc.ops >= BigInt(16 * 17 / 2) && wc.ops < w.ops);

  // The gross identity 2R*nCC + (T+S)*nSplit + 2P*nDD prices every round for
  // two players; the contract counts self-play once, so the self-play rounds
  // must be charged for one player only. Row 0 is 16 strategies, horizon 100,
  // standard payoffs, self-play included, so the corrected theorem applies
  // with n = 16. See FIX-NOTE.md for why the gross form is not a theorem.
  const sp0 = plan.selfPlayOutcomeCounts(H, PAY, 16);
  const gt0 = plan.grandTotal(w.acc);
  const gross0 = 2 * PAY.R * w.acc.nCC + (PAY.T + PAY.S) * w.acc.nSplit + 2 * PAY.P * w.acc.nDD;
  const corr0 = PAY.R * sp0.sCC + PAY.P * sp0.sDD;
  check('small-scale identity with the self-play correction (battery row 0): ' + gt0 + ' == ' +
      gross0 + ' - ' + corr0,
    gt0 === gross0 - corr0, 'sSplit was ' + sp0.sSplit + ' (must be 0)');
}

// 5. control: the deliberately broken reference must go red
{
  const broken = plan.breakReference(refImpl);
  check('breakReference returns a different object with a chunk()', broken !== refImpl && typeof broken.chunk === 'function');
  let disagreed = 0;
  for (const b of plan.battery) {
    const w = runSmall(makeWasmInstance(), b.p0, b.p1, b.chunks);
    const r = runSmall(broken, b.p0, b.p1, b.chunks);
    if (plan.fingerprint(w.acc) !== plan.fingerprint(r.acc)) disagreed++;
  }
  check('broken reference DISAGREES on at least one battery row (' + disagreed + '/' + plan.battery.length + ')', disagreed >= 1);
}

// 6. THE FULL-SIZE CHECKS, run for real
log('full-size run A: every match played out, 256 chunks, forward order');
const A = await runFull({ p0: plan.encodeP0({}), p1: plan.encodeP1(), chunks: 256 });
log('  done in ' + (A.ms / 1000).toFixed(1) + 's on ' + A.workers + ' workers, ' + A.ops + ' inner-loop iterations');

log('full-size run B: decomposition, 197 chunks, REVERSED pair order');
const B = await runFull({ p0: plan.encodeP0({ order: 1 }), p1: plan.encodeP1(), chunks: 197 });
log('  done in ' + (B.ms / 1000).toFixed(1) + 's');

log('full-size run C: cross-method, cycle detection, 256 chunks');
const C = await runFull({ p0: plan.encodeP0({ mode: 1 }), p1: plan.encodeP1(), chunks: 256 });
log('  done in ' + (C.ms / 1000).toFixed(1) + 's');

check('(a) decomposition: different chunk count AND reversed pair order give IDENTICAL per-strategy totals and counts',
  plan.sameAcc(A.acc, B.acc));
check('(c) cross-method: cycle detection agrees with round-by-round play-out on EVERY match of the full tournament',
  plan.sameAcc(A.acc, C.acc));

// (b) invariants, on run A
{
  const gt = plan.grandTotal(A.acc);
  // The correction term is DERIVED FROM THE CONTRACT, not taken from the
  // engine: selfPlayOutcomeCounts walks all 65,536 self-play matches round
  // by round in plain JavaScript. The gross identity overcharges each
  // self-play round by one player's payoff, because the contract counts
  // self-play once. Mirror symmetry further forces sSplit = 0, asserted
  // separately below. See FIX-NOTE.md for the full derivation and the
  // arithmetic that closes the old 15,687,680 gap to the digit.
  const sp = plan.selfPlayOutcomeCounts(H, PAY, N);
  const gross = 2 * PAY.R * A.acc.nCC + (PAY.T + PAY.S) * A.acc.nSplit + 2 * PAY.P * A.acc.nDD;
  const corr = PAY.R * sp.sCC + PAY.P * sp.sDD;
  check('(b) self-play never splits: the ' + N + ' self-play matches contain no split round',
    sp.sSplit === 0, 'got sSplit=' + sp.sSplit);
  check('(b) identity: grand total == 2R*nCC + (T+S)*nSplit + 2P*nDD - (R*sCC + P*sDD) (' + gt + ')' +
      '  [nCC=' + A.acc.nCC + ', nSplit=' + A.acc.nSplit + ', nDD=' + A.acc.nDD +
      ', rounds=' + (H * NMATCHES) + ', sCC=' + sp.sCC + ', sDD=' + sp.sDD + ', correction=' + corr + ']',
    gt === gross - corr,
    'gross identity ' + gross + '; the gross form prices every round for two players but a self-play round pays one');
  check('(b) outcome counts sum to rounds played: nCC+nSplit+nDD == ' + (H * NMATCHES),
    A.acc.nCC + A.acc.nSplit + A.acc.nDD === H * NMATCHES);
  const lo = H * Math.min(PAY.P, PAY.S) * N, hi = H * Math.max(PAY.T, PAY.R) * N;
  let rowOK = true;
  for (let k = 0; k < N; k++) if (!(A.acc.tot[k] >= lo && A.acc.tot[k] <= hi)) { rowOK = false; break; }
  check('(b) every strategy total lies in [' + lo + ', ' + hi + '] (payoff bounds x rounds played)', rowOK);
}

// the planted field, at full size, through the UNMODIFIED engine
{
  log('full-size planted field: one all-defect inserted into an all-cooperate field (cycle method)');
  const P = await runFull({ p0: plan.encodeP0({ variant: 1, mode: 1 }), p1: plan.encodeP1(), chunks: 64 });
  const exp = plan.expectedPlanted(N, H, PAY);
  let ok = P.acc.tot[0] === exp.defector;
  for (let k = 1; k < N && ok; k++) if (P.acc.tot[k] !== exp.cooperator) ok = false;
  check('planted field: the same engine reports the closed-form scores exactly (defector ' + exp.defector + ', cooperators ' + exp.cooperator + ')', ok);
  check('planted field: outcome counts match the closed form too',
    P.acc.nCC === exp.nCC && P.acc.nSplit === exp.nSplit && P.acc.nDD === exp.nDD);
}

// the flat field, at full size: the ranking must be a single tie
{
  log('full-size flat field: T=R=P=S, every strategy must tie (cycle method)');
  const F = await runFull({ p0: plan.encodeP0({ variant: 2, mode: 1 }), p1: plan.encodeP1(), chunks: 64 });
  const expect = plan.expectedFlatTotal(N, H, 3);
  let ok = true;
  for (let k = 0; k < N; k++) if (F.acc.tot[k] !== expect) { ok = false; break; }
  check('flat field: all 65,536 totals equal ' + expect + ' (the ranking is one tie, so it comes from the play)', ok);
}

// 7. every fixed fact the PAGE states, recomputed and matched to the HTML
{
  const html = readFileSync(path.join(DIR, 'index.html'), 'utf8');
  const has = (s) => html.includes(s);
  check('page states 65,536 strategies and 2^16 is 65,536', has('65,536') && 2 ** 16 === 65536);
  check('page states 2,147,516,416 matches and 65536*65537/2 is 2,147,516,416',
    has('2,147,516,416') && N * (N + 1) / 2 === 2147516416);
  check('page states the payoffs T=5, R=3, P=1, S=0 that every run here used',
    has('T=5') && has('R=3') && has('P=1') && has('S=0'));
  check('page states the 100-round horizon used here', has('100 rounds'));
  const vpath = 'research/' + SLUG + '/verify-' + SLUG + '.mjs';
  check('page names its offline verifier and that file exists', has(vpath) && existsSync(path.join(HERE, 'verify-' + SLUG + '.mjs')));
}

// 8. negative controls on the verifier itself
{
  const a2 = { tot: A.acc.tot.slice(), nCC: A.acc.nCC, nSplit: A.acc.nSplit, nDD: A.acc.nDD };
  a2.tot[12345] += 1;
  ctl('mutating one strategy total by +1 makes the decomposition comparator report a difference', !plan.sameAcc(a2, B.acc));

  const gt = plan.grandTotal(A.acc);
  const spC = plan.selfPlayOutcomeCounts(H, PAY, N);
  const badIdent = 2 * PAY.R * (A.acc.nCC + 1) + (PAY.T + PAY.S) * A.acc.nSplit + 2 * PAY.P * A.acc.nDD
    - (PAY.R * spC.sCC + PAY.P * spC.sDD);
  ctl('adding 1 to nCC breaks the corrected payoff identity (comparator returns unequal)', gt !== badIdent);

  const tampered = batRows[0].ref.slice(0, -1) + (batRows[0].ref.endsWith('0') ? '1' : '0');
  ctl('flipping the last character of a battery fingerprint is caught by the equality test', batRows[0].wasm !== tampered);
}

// -------------------------------------------------------------------- total
console.log('');
console.log(passes + ' passed, ' + fails + ' failed' + '  (full-size runs: ' +
  ((A.ms + B.ms + C.ms) / 1000).toFixed(1) + 's across ' + A.workers + ' workers)');
process.exit(fails ? 1 : 0);
