#!/usr/bin/env node
// verify-a-hundred-billion-walks.mjs - the offline gate.
//
//   node research/a-hundred-billion-walks/verify-a-hundred-billion-walks.mjs
//
// Node 22, no dependencies, no network.  Prints one line per assertion in the
// house format, then a total, and exits non-zero on any FAIL.  The full-size
// census runs for real here, on every core, twice (two decompositions).

import { readFileSync, writeFileSync, existsSync, mkdtempSync, rmSync } from 'node:fs';
import { createHash } from 'node:crypto';
import { execFileSync } from 'node:child_process';
import { fileURLToPath, pathToFileURL } from 'node:url';
import path from 'node:path';
import os from 'node:os';

const SLUG = 'a-hundred-billion-walks';
const HERE = path.dirname(fileURLToPath(import.meta.url));
const REPO = path.resolve(HERE, '..', '..');
const DIR = path.join(REPO, 'public', 'strata', SLUG);
const WASM_PATH = path.join(DIR, 'engine.wasm');
const ENGINE_C = path.join(DIR, 'engine.c');
const PLAN_JS = path.join(DIR, 'plan.js');
const REF_JS = path.join(DIR, 'reference.js');
const PAGE_HTML = path.join(DIR, 'index.html');

let pass = 0, fail = 0, skip = 0;
const P = (id, m) => { pass++; console.log(`PASS ${id}  ${m}`); };
const F = (id, m) => { fail++; console.log(`FAIL ${id}  ${m}`); };
const S = (m) => { skip++; console.log(`SKIP  ${m}`); };
const CTL = (id, m) => console.log(`CONTROL ${id}  ${m}`);
const sha = (buf) => createHash('sha256').update(buf).digest('hex');
const secs = (ms) => (ms / 1000).toFixed(1) + 's';

// ---------------------------------------------------------------- module loading
// plan.js and reference.js are ES modules with .js extensions.  If this repo's
// nearest package.json does not say "type": "module", node would parse them as
// CommonJS and die on the export syntax.  Fall back to a .mjs copy in a temp dir.
async function loadStrataModules() {
  try {
    const [p, r] = await Promise.all([
      import(pathToFileURL(PLAN_JS)), import(pathToFileURL(REF_JS)),
    ]);
    return { plan: p, ref: r };
  } catch (_) {
    const tmp = mkdtempSync(path.join(os.tmpdir(), 'awmod-'));
    writeFileSync(path.join(tmp, 'reference.mjs'), readFileSync(REF_JS, 'utf8'));
    const pTxt = readFileSync(PLAN_JS, 'utf8')
      .replace(/(['"])\.\/reference\.js\1/g, '$1./reference.mjs$1');
    writeFileSync(path.join(tmp, 'plan.mjs'), pTxt);
    const [p, r] = await Promise.all([
      import(pathToFileURL(path.join(tmp, 'plan.mjs'))),
      import(pathToFileURL(path.join(tmp, 'reference.mjs'))),
    ]);
    return { plan: p, ref: r, tmp };
  }
}

// `ref` was loaded and then never bound, so every use of the reference read
// ref, which plan.js does not export. Bind it.
const { plan, ref } = await loadStrataModules();
const { SQ_N, HC_N, DEPTH_MAIN, CHUNKS_MAIN, DEPTH_ALT, CHUNKS_ALT,
        packP0, initial, reduce, fingerprint, battery, breakReference,
        estimates, toNumbers, MU_HONEYCOMB_EXACT } = plan;

let manifest = null;
try { manifest = await import(pathToFileURL(path.join(DIR, 'manifest.js'))); }
catch (_) { manifest = null; }

// ---------------------------------------------------------------- engine helpers
function newInstance(bytes) {
  const inst = new WebAssembly.Instance(new WebAssembly.Module(bytes), {});
  return inst.exports;
}

function runWasm(x, p0, p1, chunks, rounds) {
  if (x.aw_reset) x.aw_reset();
  x.aw_init(p0 >>> 0, p1 >>> 0);
  const outLen = x.aw_out_len() >>> 0;
  const acc = initial();
  let ops = 0n;
  for (let r = 0; r < rounds; r++) {
    for (let i = 0; i < chunks; i++) {
      const o = x.aw_chunk(r >>> 0, i >>> 0, chunks >>> 0);
      ops += BigInt.asUintN(64, o);
      const dv = new DataView(x.memory.buffer, x.aw_out() >>> 0, outLen);
      reduce(acc, dv, i, r);
    }
  }
  return { acc, ops };
}

function runReference(ref, p0, p1, chunks, rounds) {
  ref.init(p0 >>> 0, p1 >>> 0);
  const acc = initial();
  let ops = 0n;
  for (let r = 0; r < rounds; r++) {
    for (let i = 0; i < chunks; i++) {
      const c = ref.chunk(r, i, chunks);
      ops += typeof c.ops === 'bigint' ? c.ops : BigInt(c.ops || 0);
      reduce(acc, new DataView(c.out.buffer, c.out.byteOffset || 0, c.out.byteLength), i, r);
    }
  }
  return { acc, ops };
}

// Full-size census across every core, via worker_threads.  Falls back to one
// thread if workers are unavailable (slower, equally correct).
const WORKER_SRC = [
  "const { parentPort, workerData } = require('node:worker_threads');",
  "const { readFileSync } = require('node:fs');",
  '(async () => {',
  '  const bytes = readFileSync(workerData.wasmPath);',
  '  const x = new WebAssembly.Instance(new WebAssembly.Module(bytes), {}).exports;',
  '  const { p0, p1, chunks, rounds, wid, nw } = workerData;',
  '  if (x.aw_reset) x.aw_reset();',
  '  x.aw_init(p0 >>> 0, p1 >>> 0);',
  '  const outLen = x.aw_out_len() >>> 0;',
  '  const nLens = outLen / 8 - 1;',
  '  const acc = [];',
  '  for (let r = 0; r < rounds; r++) acc.push(new Array(nLens + 1).fill(0n));',
  '  let ops = 0n;',
  "  for (let idx = wid; idx < chunks; idx += nw) {",
  '    for (let r = 0; r < rounds; r++) {',
  '      const o = x.aw_chunk(r >>> 0, idx >>> 0, chunks >>> 0);',
  '      ops += BigInt.asUintN(64, o);',
  '      const dv = new DataView(x.memory.buffer, x.aw_out() >>> 0, outLen);',
  '      for (let k = 0; k <= nLens; k++) acc[r][k] += BigInt.asUintN(64, dv.getBigUint64(8 * k, true));',
  '    }',
  '  }',
  '  parentPort.postMessage({ acc, ops });',
  '})().catch(e => parentPort.postMessage({ error: String((e && e.stack) || e) }));',
].join('\n');

async function runFull(bytes, p0, p1, chunks, rounds, nw) {
  const { Worker } = await import('node:worker_threads');
  const parts = await Promise.all(
    Array.from({ length: nw }, (_, wid) => new Promise((resolve, reject) => {
      let w;
      try {
        w = new Worker(WORKER_SRC, { eval: true, workerData: { wasmPath: WASM_PATH, p0, p1, chunks, rounds, wid, nw } });
      } catch (e) { reject(e); return; }
      w.on('message', (m) => (m.error ? reject(new Error(m.error)) : resolve(m)));
      w.on('error', reject);
    }))
  );
  const sq = new Array(SQ_N + 1).fill(0n);
  const hc = new Array(HC_N + 1).fill(0n);
  let ops = 0n;
  for (const pt of parts) {
    ops += BigInt(pt.ops);
    for (let k = 0; k <= SQ_N; k++) sq[k] += pt.acc[0][k];
    if (rounds > 1) for (let k = 0; k <= HC_N; k++) hc[k] += pt.acc[1][k];
  }
  return { acc: { sq, hc }, ops };
}

// ------------------------------------------------- independent cross-method BFS
// Breadth-first, holding EVERY walk of the current length as an explicit path,
// rebuilding occupancy by walking the path.  No DFS, no bitset, no prefix
// partition, no symmetry fixing: it counts all walks directly.  Shares nothing
// with the engine's algorithm except the definition of a walk.  The origin is
// occupied from the start (it is in `seen` before any step).
function bfsCounts(geo, N, blocked) {
  const step = (d, x, y) => {
    if (geo === 'honey') {
      if (d === 0) return [x + 1, y];
      if (d === 1) return [x - 1, y];
      if (d === 2) return [x, y + (((x + y) & 1) ? -1 : 1)];
      return null;
    }
    if (geo === 'line') {
      if (d === 0) return [x + 1, y];
      if (d === 2) return [x - 1, y];
      return null;
    }
    if (d > 3) return null;
    return [x + [1, 0, -1, 0][d], y + [0, 1, 0, -1][d]];
  };
  const K = (x, y) => (x + 64) * 4096 + (y + 64);
  let walks = [[]];
  const counts = [1];
  for (let n = 1; n <= N; n++) {
    const next = [];
    for (const w of walks) {
      let x = 0, y = 0;
      const seen = new Set([K(0, 0)]);
      for (const d of w) { const s = step(d, x, y); x = s[0]; y = s[1]; seen.add(K(x, y)); }
      for (let d = 0; d < 4; d++) {
        const s = step(d, x, y);
        if (!s) continue;
        const k = K(s[0], s[1]);
        if (seen.has(k)) continue;
        if (blocked && blocked.has(k)) continue;
        next.push(w.concat(d));
      }
    }
    walks = next;
    counts.push(walks.length);
  }
  return counts;
}

// ------------------------------------------------------------------- invariants
function squareViolations(cs) {
  const v = [];
  if (cs[0] !== 1n) v.push('c(0) != 1');
  if (cs[1] !== 4n) v.push('c(1) != 4');
  for (let n = 1; n < cs.length; n++) {
    if (cs[n] % 8n !== 4n) v.push(`c(${n}) % 8 != 4`);
    if (n > 1) {
      if (!(cs[n] > cs[n - 1])) v.push(`c(${n}) <= c(${n - 1})`);
      if (cs[n] > 3n * cs[n - 1]) v.push(`c(${n}) > 3*c(${n - 1})`);
    }
  }
  return v;
}
function honeyViolations(cs) {
  const v = [];
  if (cs[0] !== 1n) v.push('h(0) != 1');
  if (cs[1] !== 3n) v.push('h(1) != 3');
  for (let n = 1; n < cs.length; n++) {
    if (cs[n] % 3n !== 0n) v.push(`h(${n}) % 3 != 0`);
    if (n > 1) {
      if (!(cs[n] > cs[n - 1])) v.push(`h(${n}) <= h(${n - 1})`);
      if (cs[n] > 2n * cs[n - 1]) v.push(`h(${n}) > 2*h(${n - 1})`);
    }
  }
  return v;
}
function diffCounts(a, b, tag) {
  const out = [];
  const n = Math.min(a.length, b.length);
  for (let k = 0; k < n; k++) if (a[k] !== b[k]) out.push(`${tag}[${k}] ${a[k]} != ${b[k]}`);
  return out;
}

// ================================================================== assertions
const t0 = Date.now();
console.log(`verify-${SLUG}: full-size census runs for real in this process`);

let bytes = null, x = null;
try {
  bytes = readFileSync(WASM_PATH);
  x = newInstance(bytes);
} catch (e) {
  F('001', `engine.wasm could not be loaded/instantiated: ${e.message}`);
  console.log(`
${pass} passed, ${fail} failed, ${skip} skipped`);
  process.exit(1);
}

// 001 - ABI exports
{
  const need = ['aw_init', 'aw_chunk', 'aw_out', 'aw_out_len', 'aw_alloc', 'aw_reset', 'memory'];
  const missing = need.filter((k) => !(k in x));
  if (missing.length === 0) {
    P('001', `all ABI exports present (${need.join(', ')}); aw_state legitimately absent: this run has no round state`);
  } else {
    F('001', `missing exports: ${missing.join(', ')}`);
  }
}

// 002 - hash against the manifest the page ships
let pinnedClang = '';
if (!manifest || !manifest.WASM_SHA256) {
  F('002', 'manifest.js missing or exports no WASM_SHA256: the page cannot pin its binary');
} else {
  const got = sha(bytes);
  if (got === String(manifest.WASM_SHA256).toLowerCase()) {
    P('002', `sha256(engine.wasm) = ${got.slice(0, 16)}... matches manifest`);
  } else {
    F('002', `sha256(engine.wasm) = ${got} but manifest names ${manifest.WASM_SHA256}`);
  }
  pinnedClang = manifest.CLANG ? String(manifest.CLANG) : '';
}

// 003 - reproducible build, with an honest skip
{
  let clangVer = '';
  try { clangVer = execFileSync('clang', ['--version'], { encoding: 'utf8' }).split('\n')[0].trim(); } catch (_) {}
  const buildScript = path.join(REPO, 'research', '_ox3', 'lib', 'build-wasm.sh');
  if (!clangVer) {
    S('reproducible build (clang not found on PATH)');
  } else if (pinnedClang && !clangVer.includes(pinnedClang) && !pinnedClang.includes(clangVer)) {
    S(`reproducible build (clang "${clangVer}" != pinned "${pinnedClang}")`);
  } else if (!existsSync(buildScript)) {
    F('003', `clang ${clangVer} is available but the build script is missing: ${buildScript}`);
  } else {
    const tmp = path.join(os.tmpdir(), `aw-${SLUG}-rebuild-${process.pid}.wasm`);
    try {
      execFileSync('bash', [buildScript, ENGINE_C, tmp], { stdio: ['ignore', 'pipe', 'pipe'] });
      const a = sha(bytes), b = sha(readFileSync(tmp));
      if (a === b) P('003', `rebuild from engine.c is byte-identical (${a.slice(0, 16)}...)`);
      else F('003', `rebuilt bytes differ: ${a} vs ${b}`);
    } catch (e) {
      F('003', `rebuild failed: ${String(e.message).split('\n')[0]}`);
    } finally {
      try { rmSync(tmp, { force: true }); } catch (_) {}
    }
  }
}

// 004 - battery: wasm and reference agree on every row
// 005 - and the rows are not trivially identical to each other
{
  let allAgree = true;
  const fps = new Set();
  const rowFps = [];
  for (const row of battery) {
    const w = runWasm(x, row.p0, row.p1, row.chunks, row.rounds);
    const r = runReference(ref, row.p0, row.p1, row.chunks, row.rounds);
    const fw = fingerprint(w.acc), fr = fingerprint(r.acc);
    fps.add(fw);
    rowFps.push(fw);
    if (fw !== fr) { allAgree = false; console.log(`      row "${row.label}" DISAGREES`); }
  }
  if (allAgree) P('004', `wasm and reference fingerprints identical on all ${battery.length} battery rows`);
  else F('004', 'battery disagreement: the page must not display a result');
  // ⚠ The right property is NOT "every row differs". Two rows here deliberately compute the
  // SAME counts under a different depth and a different chunk count, and their agreeing is a
  // decomposition check rather than a redundancy: requiring them to differ would be requiring
  // the check to fail. What must hold is that rows with DIFFERENT PARAMETERS (a different p0,
  // so a different lattice or a different maximum length) give different answers, since a
  // battery whose instances all coincide proves only one of them.
  {
    const byParam = new Map();
    let bad = null, decomp = 0;
    battery.forEach((row, i) => {
      const key = String(row.p0);
      if (!byParam.has(key)) byParam.set(key, []);
      byParam.get(key).push({ i, fp: rowFps[i], label: row.label });
    });
    const distinctParams = new Set();
    for (const [key, rows] of byParam) {
      for (const r of rows.slice(1)) {
        if (r.fp === rows[0].fp) decomp++;
        else bad = `rows "${rows[0].label}" and "${r.label}" share p0 but DISAGREE`;
      }
      distinctParams.add(rows[0].fp);
    }
    if (!bad && distinctParams.size === byParam.size && byParam.size >= 3) {
      P('005', `battery: ${byParam.size} distinct instances give ${distinctParams.size} distinct answers, and ${decomp} same-instance row(s) agree across a different decomposition, which is the point of including them`);
    } else if (bad) {
      F('005', bad);
    } else {
      F('005', `battery: ${byParam.size} distinct instances give only ${distinctParams.size} distinct answers`);
    }
  }
}

// 006/007 - the control on the control
{
  const brk = breakReference(ref);
  if (brk !== ref) {
    P('006', 'breakReference returns a different object running different code');
  } else {
    F('006', 'breakReference returned the reference unchanged: it mutated nothing');
  }
  let disagreements = 0;
  for (const row of battery) {
    const w = runWasm(x, row.p0, row.p1, row.chunks, row.rounds);
    const b = runReference(brk, row.p0, row.p1, row.chunks, row.rounds);
    if (fingerprint(w.acc) !== fingerprint(b.acc)) disagreements++;
  }
  if (disagreements === battery.length) {
    P('007', `the broken reference disagrees on all ${battery.length} rows (West occupancy check removed inflates every count)`);
  } else {
    F('007', `broken reference caught on only ${disagreements}/${battery.length} rows`);
  }
}

// 008 - planted object, trivial lattice: the line, where the answer is provably 2
{
  const { acc } = runWasm(x, packP0(8, 8, 1), 2, 3, 1);
  const want = [1n, 2n, 2n, 2n, 2n, 2n, 2n, 2n, 2n];
  const bad = diffCounts(acc.sq.slice(0, 9), want, 'line');
  if (bad.length === 0) P('008', 'one-dimensional lattice: c(0)=1 and exactly 2 walks at every length 1..8, as the contract proves');
  else F('008', `line lattice wrong: ${bad.join('; ')}`);
}

// 009 - planted object, doctored DATA: site (0,1) blocked, same unmodified engine.
// Hand derivation for n <= 2 (first step NOT fixed, factor 1, site (0,1) blocked,
// and (0,1) is DIRECTLY NORTH of the origin, so the first step North is itself the
// blocked move):
//   n=0: the empty walk -> 1.
//   n=1: East, South, West are free; North lands on the blocked site -> 3.
//   n=2: twelve two-step walks on the open lattice.  A two-step walk visits (0,1)
//        iff its SECOND site or its first is (0,1).  The neighbours of (0,1) are
//        (1,1), (-1,1), (0,2) and the origin, so the only first step adjacent to
//        (0,1) is North itself: the visiting walks are exactly NE, NW, NN.
//        12 - 3 = 9.  (An earlier draft of this check claimed (1, 4, 7) and listed
//        EN and WN among the visitors; EN ends at (1,1) and WN at (-1,1) and
//        neither touches (0,1).  The draft was wrong; the BFS below agrees with 9.)
{
  const { acc } = runWasm(x, packP0(7, 7, 2), 2, 3, 1);
  const hand = [1n, 3n, 9n];
  const badHand = diffCounts(acc.sq.slice(0, 3), hand, 'blocked');
  const bfs = bfsCounts('square', 7, new Set([(0 + 64) * 4096 + (1 + 64)]));
  const bfsBig = bfs.map((v) => BigInt(v));
  const badBfs = diffCounts(acc.sq.slice(0, 8), bfsBig, 'blocked');
  if (badHand.length === 0 && badBfs.length === 0) {
    P('009', 'blocked-site lattice: hand values (1, 3, 9) and independent BFS to n=7 all match');
  } else {
    F('009', `blocked-site lattice wrong: ${badHand.concat(badBfs).join('; ')}`);
  }
}

// 010/011/012/017 - THE FULL-SIZE CHECK, run for real, twice (two decompositions)
let full = null;
{
  const nw = Math.max(1, Math.min(8, typeof os.availableParallelism === 'function' ? os.availableParallelism() : os.cpus().length));
  const p0 = packP0(SQ_N, HC_N, 0);
  let A, B, useWorkers = true;
  try {
    const ta = Date.now();
    A = await runFull(bytes, p0, DEPTH_MAIN, CHUNKS_MAIN, 2, nw);
    console.log(`      decomposition A (depth ${DEPTH_MAIN}, ${CHUNKS_MAIN} chunks, ${nw} workers): ${secs(Date.now() - ta)}`);
    const tb = Date.now();
    B = await runFull(bytes, p0, DEPTH_ALT, CHUNKS_ALT, 2, nw);
    console.log(`      decomposition B (depth ${DEPTH_ALT}, ${CHUNKS_ALT} chunks): ${secs(Date.now() - tb)}`);
  } catch (e) {
    useWorkers = false;
    console.log(`      worker pool unavailable (${String(e.message).split('\n')[0]}); falling back to one thread`);
    A = runWasm(x, p0, DEPTH_MAIN, CHUNKS_MAIN, 2);
    B = runWasm(x, p0, DEPTH_ALT, CHUNKS_ALT, 2);
  }
  full = A;
  const bad = diffCounts(A.acc.sq, B.acc.sq, 'sq').concat(diffCounts(A.acc.hc, B.acc.hc, 'hc'));
  if (bad.length === 0) {
    P('010', `two decompositions agree at every length: depth ${DEPTH_MAIN}/${CHUNKS_MAIN} chunks vs depth ${DEPTH_ALT}/${CHUNKS_ALT} chunks, square 0..${SQ_N}, honeycomb 0..${HC_N}${useWorkers ? '' : ' (single-threaded)'}`);
  } else {
    F('010', `decompositions disagree: ${bad.slice(0, 4).join('; ')}`);
  }

  const vs = squareViolations(A.acc.sq);
  if (vs.length === 0) {
    P('011', `square invariants hold at full size: c(0)=1, c(1)=4, c(n)%8=4 for all n>=1 (4 rotations act freely, exactly one reflection-fixed walk per length), c(n-1)<c(n)<=3c(n-1)`);
  } else F('011', `square invariants violated: ${vs.slice(0, 4).join('; ')}`);

  const vh = honeyViolations(A.acc.hc);
  if (vh.length === 0) {
    P('012', `honeycomb invariants hold at full size: h(0)=1, h(1)=3, 3|h(n) for all n>=1, h(n-1)<h(n)<=2h(n-1)`);
  } else F('012', `honeycomb invariants violated: ${vh.slice(0, 4).join('; ')}`);

  const eh = estimates(toNumbers(A.acc.hc));
  if (Math.abs(eh.fitted - MU_HONEYCOMB_EXACT) < 0.05) {
    P('017', `estimator machinery sane: honeycomb fit ${eh.fitted.toFixed(6)} vs exact ${MU_HONEYCOMB_EXACT.toFixed(6)} (tests the estimator, not the constant)`);
  } else F('017', `honeycomb fit ${eh.fitted} is far from exact ${MU_HONEYCOMB_EXACT}: estimator code is suspect`);
}

// 013/014 - cross-method: a genuinely different algorithm, exact to n=12
{
  const { acc } = runWasm(x, packP0(12, 12, 0), 3, 4, 2);
  const sqBfs = bfsCounts('square', 12, null).map(BigInt);
  const hcBfs = bfsCounts('honey', 12, null).map(BigInt);
  const bs = diffCounts(acc.sq.slice(0, 13), sqBfs, 'sq');
  const bh = diffCounts(acc.hc.slice(0, 13), hcBfs, 'hc');
  if (bs.length === 0 && bh.length === 0) {
    P('013', 'cross-method, square: breadth-full-path enumeration matches the engine exactly for every length 0..12');
    P('014', 'cross-method, honeycomb: breadth-full-path enumeration matches the engine exactly for every length 0..12');
  } else {
    if (bs.length) F('013', `square cross-method mismatch: ${bs.slice(0, 3).join('; ')}`);
    else P('013', 'cross-method, square: exact agreement to n=12');
    if (bh.length) F('014', `honeycomb cross-method mismatch: ${bh.slice(0, 3).join('; ')}`);
    else P('014', 'cross-method, honeycomb: exact agreement to n=12');
  }
}

// 015/016 - every fixed fact the PAGE states, recomputed and matched on disk
{
  if (!existsSync(PAGE_HTML)) {
    F('015', 'index.html not found');
    F('016', 'page citation check impossible');
  } else {
    const html = readFileSync(PAGE_HTML, 'utf8');
    const attr = (name) => {
      const m = html.match(new RegExp(`data-${name}="([^"]*)"`));
      return m ? m[1] : null;
    };
    const problems = [];
    const eq = (name, want) => { if (attr(name) !== String(want)) problems.push(`data-${name}="${attr(name)}" != ${want}`); };
    eq('sq-n', SQ_N); eq('hc-n', HC_N);
    eq('depth-main', DEPTH_MAIN); eq('chunks-main', CHUNKS_MAIN);
    eq('depth-alt', DEPTH_ALT); eq('chunks-alt', CHUNKS_ALT);
    eq('mu-hc', MU_HONEYCOMB_EXACT.toFixed(16));

    // symmetry factors and the trivial counts, recomputed from the engine itself
    const one = runWasm(x, packP0(1, 1, 0), 1, 1, 2);
    if (one.acc.sq[0] !== 1n) problems.push('engine c(0) != 1');
    if (one.acc.sq[1] !== 4n) problems.push('engine c(1) != 4');
    if (one.acc.hc[0] !== 1n) problems.push('engine h(0) != 1');
    if (one.acc.hc[1] !== 3n) problems.push('engine h(1) != 3');
    eq('sym-square', '4'); eq('sym-honeycomb', '3'); eq('c1', '4');
    const line = runWasm(x, packP0(3, 3, 1), 2, 2, 1);
    if (line.acc.sq[1] !== 2n || line.acc.sq[3] !== 2n) problems.push('engine line count != 2');
    eq('line-count', '2');

    // no hardcoded big counts in the shipped HTML (strip the exact mu decimal first)
    const stripped = html.split(MU_HONEYCOMB_EXACT.toFixed(16)).join('');
    if (/\d{10,}/.test(stripped)) problems.push('shipped HTML contains a 10+ digit run: a hardcoded count?');

    if (problems.length === 0) {
      P('015', 'every fixed fact the page states (sizes, depths, chunks, factors, c(0), c(1), line count, exact honeycomb decimal) recomputed here and found in the shipped HTML; no hardcoded census numbers');
    } else F('015', `page facts wrong: ${problems.join('; ')}`);

    const cite = html.match(/research\/a-hundred-billion-walks\/verify-[A-Za-z0-9_.-]*\.mjs/);
    if (cite && existsSync(path.join(REPO, cite[0]))) {
      P('016', `page cites ${cite[0]} and that file exists (it is this one)`);
    } else F('016', 'page does not cite an existing verifier path');
  }
}

// ------------------------------------------------------------ negative controls
// Each one mutates an input and asserts the corresponding assertion WOULD fail.
{
  const doctored = full.acc.sq.slice();
  doctored[7] += 1n;
  const v = squareViolations(doctored);
  if (v.length > 0) CTL('001', `a count perturbed by +1 trips the invariant check (${v[0]})`);
  else { CTL('001', 'perturbation NOT caught by invariant check'); F('C1', 'negative control failed to fire'); }

  const fpA = fingerprint(full.acc);
  const acc2 = { sq: full.acc.sq.slice(), hc: full.acc.hc.slice() };
  acc2.hc[20] += 2n;
  if (fingerprint(acc2) !== fpA) CTL('002', 'a single altered honeycomb count changes the fingerprint (decomposition comparison would go red)');
  else { CTL('002', 'fingerprint insensitive to alteration'); F('C2', 'negative control failed to fire'); }

  const bfsTrue = bfsCounts('square', 6, null).map(BigInt);
  const bfsBad = bfsTrue.slice(); bfsBad[5] -= 1n;
  const d = diffCounts(bfsTrue, bfsBad, 'bfs');
  if (d.length > 0) CTL('003', 'a dropped walk in the cross-method BFS trips the exact-match comparator');
  else { CTL('003', 'cross-method comparator blind'); F('C3', 'negative control failed to fire'); }
}

// ------------------------------------------------------------------------ total
const totalMs = Date.now() - t0;
console.log(`
${pass} passed, ${fail} failed, ${skip} skipped in ${secs(totalMs)}`);
process.exit(fail > 0 ? 1 : 0);
