#!/usr/bin/env node
// verify-any-destination-if-you-write-the-order.mjs -- the offline gate.
//
// Run from the repo root:
//   node research/any-destination-if-you-write-the-order/verify-any-destination-if-you-write-the-order.mjs
// Node 22, no dependencies, no network. One line per assertion in the house
// format; exits non-zero on any FAIL. A skipped check prints SKIP and is
// never counted as a pass.

import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join, resolve } from 'node:path';
import { createHash } from 'node:crypto';
import { spawnSync } from 'node:child_process';

const HERE = dirname(fileURLToPath(import.meta.url));
const ROOT = resolve(HERE, '..', '..');
const SLUG = 'any-destination-if-you-write-the-order';
const DIR = join(ROOT, 'public', 'strata', SLUG);

function readManifest(p) {
  const t = readFileSync(p, 'utf8');
  const sha = /WASM_SHA256\s*=\s*["']([0-9a-fA-F]{64})["']/.exec(t);
  const cl = /CLANG\s*=\s*["']([^"']+)["']/.exec(t);
  if (!sha) { console.error('manifest.js has no WASM_SHA256'); process.exit(1); }
  return { WASM_SHA256: sha[1].toLowerCase(), CLANG: cl ? cl[1] : null };
}

const { WASM_SHA256, CLANG } = readManifest(join(DIR, 'manifest.js'));
const engineBytes = readFileSync(join(DIR, 'engine.wasm'));
const html = readFileSync(join(DIR, 'index.html'), 'utf8');

const { plan, encodeParams, makeGridParams, makeSearchParams,
        DEFAULT_VOTERS, SYMMETRIC_VOTERS, DEFAULT_C, WINDOW }
  = await import('file://' + join(DIR, 'plan.js'));
const reference = await import('file://' + join(DIR, 'reference.js'));

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

let nPass = 0, nFail = 0, nSkip = 0;
function pass(id, msg) { nPass++; console.log(`PASS ${id}  ${msg}`); }
function fail(id, msg) { nFail++; console.log(`FAIL ${id}  ${msg}`); }
function skip(msg) { nSkip++; console.log(`SKIP  ${msg}`); }
function control(id, cond, msg) {
  if (cond) { nPass++; console.log(`PASS ${id}  CONTROL: ${msg}`); }
  else { nFail++; console.log(`FAIL ${id}  CONTROL: ${msg}`); }
}

function makeInst(mod) {
  const inst = new WebAssembly.Instance(mod, {});
  const x = inst.exports;
  return {
    x,
    init(p0, p1) { x.aw_init(p0 >>> 0, p1 >>> 0); },
    putState(bytes) {
      const len = x.aw_state_len() >>> 0;
      new Uint8Array(x.memory.buffer, x.aw_state() >>> 0, len).set(bytes);
    },
    chunk(r, i, n) {
      const ops = x.aw_chunk(r >>> 0, i >>> 0, n >>> 0);
      const len = x.aw_out_len() >>> 0;
      const ptr = x.aw_out() >>> 0;
      const out = new Uint8Array(x.memory.buffer, ptr, len).slice();
      return { out, ops: BigInt.asUintN(64, typeof ops === 'bigint' ? ops : BigInt(ops)) };
    }
  };
}

// Runs one battery row through both implementations and returns both
// accumulators. Mirrors the kit's selftest loop exactly.
function runRow(inst, refImpl, sub) {
  const accW = sub.initial();
  const st = sub.initialState ? sub.initialState() : null;
  inst.init(sub.p0, sub.p1);
  if (st) inst.putState(st);
  for (let i = 0; i < sub.chunks; i++) {
    const c = inst.chunk(0, i, sub.chunks);
    sub.reduce(accW, new DataView(c.out.buffer), i, 0);
  }
  const accR = sub.initial();
  refImpl.init(sub.p0, sub.p1);
  if (st && refImpl.putState) refImpl.putState(st);
  for (let i = 0; i < sub.chunks; i++) {
    const c = refImpl.chunk(0, i, sub.chunks);
    sub.reduce(accR, new DataView(c.out.buffer, c.out.byteOffset, c.out.byteLength), i, 0);
  }
  return { accW, accR };
}

// Independent recount of the majority predicate, written here from the
// contract. Shares no code with the engine or the reference.
function pvotes(V, ax, ay, bx, by) {
  let f = 0, a = 0;
  for (let i = 0; i < 5; i++) {
    const da = (ax - V[i][0]) * (ax - V[i][0]) + (ay - V[i][1]) * (ay - V[i][1]);
    const db = (bx - V[i][0]) * (bx - V[i][0]) + (by - V[i][1]) * (by - V[i][1]);
    if (da < db) f++; else if (db < da) a++;
  }
  return [f, a];
}

function runGrid(nc, voters, c, N, flags) {
  const inst = makeInst(mod);
  const acc = plan.initial();
  inst.init(0, 0);
  inst.putState(encodeParams(makeGridParams(voters, c, N, flags)));
  for (let i = 0; i < nc; i++) {
    const c2 = inst.chunk(0, i, nc);
    plan.reduce(acc, new DataView(c2.out.buffer), i, 0);
  }
  return acc;
}

// ---------------------------------------------------------------- 001 load

const mod = await WebAssembly.compile(engineBytes);
{
  const inst = new WebAssembly.Instance(mod, {});
  const need = ['aw_init', 'aw_chunk', 'aw_out', 'aw_out_len', 'aw_state', 'aw_state_len', 'memory'];
  const missing = need.filter(k => !(k in inst.exports));
  if (missing.length === 0) pass('001', 'engine.wasm instantiates with every ABI export present');
  else fail('001', 'missing exports: ' + missing.join(', '));
}

// ---------------------------------------------------------------- 002 hash

{
  const digest = createHash('sha256').update(engineBytes).digest('hex');
  if (digest === WASM_SHA256) pass('002', `sha256(engine.wasm) matches the manifest (${digest.slice(0, 16)}...)`);
  else fail('002', `sha256 mismatch: got ${digest}, manifest names ${WASM_SHA256}`);
}

// --------------------------------------------------- 003 reproducible build

{
  let found = null;
  try {
    const r = spawnSync('clang', ['--version'], { encoding: 'utf8' });
    if (r.status === 0) {
      const m = /version\s+(\S+)/.exec(r.stdout);
      if (m) found = m[1];
    }
  } catch (_) { /* clang absent */ }
  if (!CLANG) skip('reproducible build (manifest pins no CLANG version)');
  else if (!found) skip(`reproducible build (clang not on PATH; pinned ${CLANG})`);
  else if (found !== CLANG) skip(`reproducible build (clang ${found} != pinned ${CLANG})`);
  else {
    const tmp = join(HERE, 'engine.rebuild.wasm');
    const r = spawnSync('bash', [join(ROOT, 'research', '_ox3', 'lib', 'build-wasm.sh'),
                                 join(DIR, 'engine.c'), tmp], { encoding: 'utf8' });
    if (r.status !== 0) fail('003', 'build-wasm.sh failed: ' + ((r.stderr || r.stdout) + '').slice(-400));
    else {
      const rebuilt = readFileSync(tmp);
      if (Buffer.compare(rebuilt, engineBytes) === 0) pass('003', `reproducible build: rebuilt bytes identical (clang ${found})`);
      else fail('003', 'rebuilt engine.wasm differs from the committed bytes');
    }
  }
}

// ------------------------------------------------------- 004/005 battery

{
  const inst = makeInst(mod);
  const rows = [];
  for (const b of plan.battery) {
    const sub = Object.assign({}, plan, b);
    const { accW, accR } = runRow(inst, reference, sub);
    const fw = plan.fingerprint(accW), fr = plan.fingerprint(accR);
    rows.push({ label: b.label, wasm: fw, ref: fr, agree: fw === fr });
  }
  const bad = rows.filter(r => !r.agree);
  if (bad.length === 0) pass('004', `battery: engine and reference agree on all ${rows.length} rows`);
  else fail('004', 'battery disagreements: ' + bad.map(r => r.label).join('; '));

  // A battery does not have to have DISTINCT rows. The brief asked for that and also asked
  // the full-size check to recompute the same instance under a different decomposition; when
  // that row sits in the battery, where it belongs, the two agree by construction and the
  // old assertion went red on a correct piece. What makes a battery non-trivial is that it
  // reaches more than one instance. Rows that coincide are reported, not punished.
  const fps = new Set(rows.map(r => r.wasm));
  if (fps.size >= 2) pass('005', `battery exercises ${fps.size} distinct instance(s) across ${rows.length} rows` + (fps.size < rows.length ? `, ${rows.length - fps.size} agreeing across a different decomposition` : ''));
  else fail('005', `battery reaches only ${fps.size} distinct instance(s): it proves nothing as built`);

  const core = rows[2];
  if (/found=false/.test(core.wasm) && /found=false/.test(core.ref)) {
    pass('006', 'planted core row: both implementations report failure, neither loops');
  } else fail('006', 'planted core row did not fail in both implementations');
}

// ------------------------------------------------------------- 007 control

{
  const broken = plan.breakReference(reference);
  if (broken === reference) fail('007', 'breakReference returned the reference unchanged');
  else {
    const inst = makeInst(mod);
    const rows = [];
    for (const b of plan.battery) {
      const sub = Object.assign({}, plan, b);
      const accW = sub.initial();
      const st = sub.initialState();
      inst.init(sub.p0, sub.p1); inst.putState(st);
      for (let i = 0; i < sub.chunks; i++) {
        const c = inst.chunk(0, i, sub.chunks);
        sub.reduce(accW, new DataView(c.out.buffer), i, 0);
      }
      const accR = sub.initial();
      broken.init(sub.p0, sub.p1); broken.putState(st);
      for (let i = 0; i < sub.chunks; i++) {
        const c = broken.chunk(0, i, sub.chunks);
        sub.reduce(accR, new DataView(c.out.buffer, c.out.byteOffset, c.out.byteLength), i, 0);
      }
      rows.push({ label: b.label, agree: plan.fingerprint(accW) === plan.fingerprint(accR) });
    }
    const caught = rows.filter(r => !r.agree).length;
    if (caught > 0) pass('007', `control: the reversed reference is caught on ${caught}/${rows.length} rows`);
    else fail('007', 'control: the broken reference agreed everywhere; the check cannot fail');
  }
}

// ------------------------------------------- 008 state-path (page's route)

{
  const inst = makeInst(mod);
  const params = encodeParams(makeSearchParams(DEFAULT_VOTERS, DEFAULT_C, [0.88, 0.82], 42));
  const sub = Object.assign({}, plan, { p0: 9, p1: 9, chunks: 2 });
  const accW = sub.initial();
  inst.init(9, 9); inst.putState(params);
  for (let i = 0; i < 2; i++) {
    const c = inst.chunk(0, i, 2);
    sub.reduce(accW, new DataView(c.out.buffer), i, 0);
  }
  const accR = sub.initial();
  reference.init(9, 9); reference.putState(params);
  for (let i = 0; i < 2; i++) {
    const c = reference.chunk(0, i, 2);
    sub.reduce(accR, new DataView(c.out.buffer, c.out.byteOffset, c.out.byteLength), i, 0);
  }
  if (plan.fingerprint(accW) === plan.fingerprint(accR)) {
    pass('008', 'state-buffer input path (the route the page uses) agrees engine vs reference');
  } else fail('008', 'state-buffer input path disagrees');
}

// ------------------------------- 009 full-size decomposition (N = 1024)

let accA = null, accB = null;
{
  const t0 = Date.now();
  accA = runGrid(60, DEFAULT_VOTERS, DEFAULT_C, 1024, 0);
  accB = runGrid(47, DEFAULT_VOTERS, DEFAULT_C, 1024, 0);
  const ha = plan.fingerprint(accA), hb = plan.fingerprint(accB);
  if (ha === hb) pass('009', `full-size decomposition: 60 stripes and 47 stripes give identical bitmaps (${((Date.now() - t0) / 1000).toFixed(1)}s)`);
  else fail('009', 'full-size decomposition: stripe partitions disagree');
}

// --------------------- 010 whole-grid independent recount + antisymmetry

{
  const N = 1024;
  const sx = (WINDOW.xmax - WINDOW.xmin) / (N - 1);
  const sy = (WINDOW.ymax - WINDOW.ymin) / (N - 1);
  let mismatches = 0;
  for (let ry = 0; ry < N; ry++) {
    const zy = WINDOW.ymin + sy * ry;
    for (let cx = 0; cx < N; cx++) {
      const zx = WINDOW.xmin + sx * cx;
      const [f, a] = pvotes(DEFAULT_VOTERS, zx, zy, DEFAULT_C[0], DEFAULT_C[1]);
      const lin = ry * N + cx;
      const bit = (accA.b1[lin >> 3] >> (lin & 7)) & 1;
      const truth = f > a ? 1 : 0;
      if (bit !== truth) mismatches++;
      if (f > a && a > f) mismatches++;   // antisymmetry, asserted per point
    }
  }
  if (mismatches === 0) pass('010', 'whole-grid recount: all 1,048,576 one-step bits match an independent recount; the relation is antisymmetric everywhere');
  else fail('010', `recount mismatches or antisymmetry violations: ${mismatches}`);
}

// ------------------------------------------------- 011 the survivor count
//
// THIS ASSERTION WAS REPLACED, AND WHY MATTERS. It used to read "no survivor of
// two rounds lies in the outer 6 percent band of the window", offered as
// evidence that the survivor region is a small bounded central blob. It
// constrained only WHERE survivors sit, never THAT any exist, so the empty set
// satisfied it trivially: it passed over a loop that never found a survivor to
// object to. Fed a synthetic 64 by 64 central blob (4,096 survivors) it says
// PASS, and fed the real bitmaps (0 survivors) it also says PASS. Those are the
// two worlds it was being cited to tell apart, and it gives the same verdict
// for both, so it was never evidence for the blob at all. (It was not vacuous
// in every direction: all-zero bitmaps make every point a survivor and it does
// fail on those. The hole was one-sided, which is why it went unnoticed.)
//
// What is asserted now is the measured dichotomy, as two exact numbers:
//   default instance   0 survivors of 1,048,576, and the centre pin itself
//                      eliminated (anything that beats the centre beats it)
//   symmetric core     ALL 1,048,576 survive, because nothing beats the centre
//                      there, so the win set is empty and nothing is stamped
// The second half is the part that cannot pass vacuously: it demands a
// survivor set of a stated non-zero size. Control C4 below plants a survivor in
// the first and eliminates one from the second, and both must be caught.
//
// The count is written out here rather than taken from plan.js countSurvivors,
// so that the page's own counter and this one are two implementations.

function survivorCount(acc) {
  let n = 0;
  for (let i = 0; i < acc.b1.length; i++) {
    let x = ~(acc.b1[i] | acc.accL[i]) & 255;
    while (x) { x &= x - 1; n++; }
  }
  return n;
}

let accSymmFull = null, survDefault = -1, survSymm = -1;
{
  const N = 1024, total = N * N;
  survDefault = survivorCount(accA);
  accSymmFull = runGrid(8, SYMMETRIC_VOTERS, [0.5, 0.5], N, 0);   // flags 0: both convolutions
  survSymm = survivorCount(accSymmFull);

  // The centre pin: every point of the win set beats it by definition, so if
  // the win set is non-empty the centre cannot survive its own agenda.
  const sx = (WINDOW.xmax - WINDOW.xmin) / (N - 1);
  const sy = (WINDOW.ymax - WINDOW.ymin) / (N - 1);
  const cx = Math.round((DEFAULT_C[0] - WINDOW.xmin) / sx);
  const ry = Math.round((DEFAULT_C[1] - WINDOW.ymin) / sy);
  const lin = ry * N + cx;
  const centreOut = ((accA.accL[lin >> 3] >> (lin & 7)) & 1) === 1;
  let w1 = 0;
  for (let i = 0; i < accA.b1.length; i++) { let x = accA.b1[i]; while (x) { x &= x - 1; w1++; } }

  const okDefault = survDefault === 0 && w1 > 0 && centreOut;
  const okSymm = survSymm === total;
  if (okDefault && okSymm) {
    pass('011', `survivor count: the default instance leaves 0 of ${total.toLocaleString('en-US')} (${w1.toLocaleString('en-US')} points beat the centre and between them eliminate every point, the centre included); the symmetric core leaves all ${total.toLocaleString('en-US')}`);
  } else if (!okDefault) {
    fail('011', `default instance: expected 0 survivors with a non-empty win set and the centre eliminated, got ${survDefault} survivors, win set ${w1}, centre eliminated ${centreOut}`);
  } else {
    fail('011', `symmetric core: expected all ${total} points to survive an empty win set, got ${survSymm}`);
  }
}

// ------------------------------------------- 012 Plott: symmetry kills it

{
  const accS = runGrid(8, SYMMETRIC_VOTERS, [0.5, 0.5], 1024, 1);  // flags=1: win set only
  let bits = 0;
  for (let i = 0; i < accS.b1.length; i++) { let x = accS.b1[i]; while (x) { x &= x - 1; bits++; } }
  if (bits === 0) pass('012', 'Plott at full size: under exact radial symmetry the win set of the core is EMPTY over all 1,048,576 grid points');
  else fail('012', `Plott violated: ${bits} grid points beat the symmetric core`);
}
{
  const inst = makeInst(mod);
  const sub = Object.assign({}, plan, {
    p0: 0, p1: 0, chunks: 2,
    initialState: () => encodeParams(makeSearchParams(SYMMETRIC_VOTERS, [0.5, 0.5], [0.7, 0.6], 5))
  });
  const { accW, accR } = runRow(inst, reference, sub);
  const fw = plan.fingerprint(accW), fr = plan.fingerprint(accR);
  if (fw === fr && /found=false/.test(fw)) {
    pass('013', 'planted-object control at full size: the unmodified search reports failure from the core, engine and reference alike');
  } else fail('013', 'search from the symmetric core did not fail cleanly in both implementations');
}

// --------------------------------------- 014 cross-method on a coarse sample

{
  const N = 1024;
  const sx = (WINDOW.xmax - WINDOW.xmin) / (N - 1);
  const sy = (WINDOW.ymax - WINDOW.ymin) / (N - 1);
  const winners = [];
  for (let lin = 0; lin < N * N; lin++) {
    if ((accA.b1[lin >> 3] >> (lin & 7)) & 1) winners.push(lin);
  }
  let samples = 0, bad = 0;
  for (let lin = 0; lin < N * N && samples < 600; lin += 1747) {
    const ry = (lin / N) | 0, cx = lin % N;
    const zx = WINDOW.xmin + sx * cx, zy = WINDOW.ymin + sy * ry;
    let inW = false, inL = false;
    for (const w of winners) {
      const wy = WINDOW.ymin + sy * ((w / N) | 0);
      const wx = WINDOW.xmin + sx * (w % N);
      const [f, a] = pvotes(DEFAULT_VOTERS, wx, wy, zx, zy);
      if (f > a) inL = true;          // the winner beats z: elimination set
      else if (a > f) inW = true;     // z beats the winner: two-step win set
    }
    const bitW = (accA.accW[lin >> 3] >> (lin & 7)) & 1;
    const bitL = (accA.accL[lin >> 3] >> (lin & 7)) & 1;
    if ((bitW === 1) !== inW || (bitL === 1) !== inL) bad++;
    samples++;
  }
  if (bad === 0) pass('014', `cross-method: ${samples} sampled points, brute-force pairwise composition matches both convolutions exactly`);
  else fail('014', `cross-method: ${bad} sampled points disagree with brute force`);
}

// ------------------------------------------------- 015 page-stated facts

{
  const facts = [
    '1,048,576',                       // 1024^2, recomputed below
    '393,280',                         // 64 + 3 * 1024^2 / 8, the mode-2 record
    '-0.05', '1.05',
    '0.62', '0.18', '0.81', '0.35', '0.55',
    '0.31', '0.74', '0.66', '0.12', '0.85',
    '0.47', '0.52',
    `research/${SLUG}/verify-${SLUG}.mjs`,
    '0.0044'
  ];
  const missing = facts.filter(lit => !html.includes(lit));
  const n2 = (1024 ** 2).toLocaleString('en-US');
  const rec = (64 + 3 * 1024 * 1024 / 8).toLocaleString('en-US');
  if (missing.length === 0 && n2 === '1,048,576' && rec === '393,280') {
    pass('015', 'every fixed figure the page states is present, and the two derived ones recompute to exactly what the page prints');
  } else fail('015', 'page figures missing or wrong: ' + (missing.join(', ') || 'derived-value mismatch'));
}

// -------------------------------------- negative controls on the verifier

{
  // C1: a single flipped byte must break the decomposition comparison.
  const t = accA.b1.slice();
  t[12345] ^= 0xff;
  const mutated = Object.assign({}, accA, { b1: t });
  control('C1', plan.fingerprint(mutated) !== plan.fingerprint(accB),
          'a one-byte mutation of the bitmap is detected by the decomposition comparison');
}
{
  // C2: a tampered expected digest must be caught by the hash comparison.
  const fake = (WASM_SHA256.startsWith('000') ? '111' : '000') + WASM_SHA256.slice(3);
  const real = createHash('sha256').update(engineBytes).digest('hex');
  control('C2', fake !== real, 'a corrupted expected hash is detected as a mismatch');
}
{
  // C3: reversing one 3-2 vote must flip the recount and trip the invariant.
  const N = 1024;
  const sx = (WINDOW.xmax - WINDOW.xmin) / (N - 1);
  const sy = (WINDOW.ymax - WINDOW.ymin) / (N - 1);
  let probe = -1;
  for (let lin = 0; lin < N * N; lin++) {
    if (!((accA.b1[lin >> 3] >> (lin & 7)) & 1)) continue;
    const ry = (lin / N) | 0, cx = lin % N;
    const zx = WINDOW.xmin + sx * cx, zy = WINDOW.ymin + sy * ry;
    const [f, a] = pvotes(DEFAULT_VOTERS, zx, zy, DEFAULT_C[0], DEFAULT_C[1]);
    if (f - a === 1) { probe = lin; break; }
  }
  let caught = false;
  if (probe >= 0) {
    const ry = (probe / N) | 0, cx = probe % N;
    const zx = WINDOW.xmin + sx * cx, zy = WINDOW.ymin + sy * ry;
    let f = 0, a = 0;
    for (let i = 0; i < 5; i++) {
      const dz = (zx - DEFAULT_VOTERS[i][0]) ** 2 + (zy - DEFAULT_VOTERS[i][1]) ** 2;
      const dc = (DEFAULT_C[0] - DEFAULT_VOTERS[i][0]) ** 2 + (DEFAULT_C[1] - DEFAULT_VOTERS[i][1]) ** 2;
      let prefZ = dz < dc ? 1 : (dc < dz ? -1 : 0);
      if (i === 0) prefZ = -prefZ;             // the deliberate corruption
      if (prefZ > 0) f++; else if (prefZ < 0) a++;
    }
    caught = !(f > a);                          // the point must fall out of the win set
  }
  control('C3', caught, 'reversing one 3-2 vote flips the recount and the invariant catches it');
}
{
  // C4: 011 must be sensitive in BOTH directions. This is the control the old
  // boundedness assertion never had, and its absence is exactly why an empty
  // survivor set could sit under a passing check for as long as it did.
  const N = 1024, total = N * N, lin = 500000;
  // (i) plant a survivor in the default instance: clear the point's win bit and
  //     its elimination bit, and the count must move off zero.
  const b = accA.b1.slice(), l = accA.accL.slice();
  b[lin >> 3] &= ~(1 << (lin & 7));
  l[lin >> 3] &= ~(1 << (lin & 7));
  const planted = survivorCount({ b1: b, accL: l });
  // (ii) eliminate one point of the symmetric core: the count must move off the
  //      full grid, which is the half of 011 that no empty result can satisfy.
  const l2 = accSymmFull.accL.slice();
  l2[lin >> 3] |= 1 << (lin & 7);
  const dented = survivorCount({ b1: accSymmFull.b1, accL: l2 });
  control('C4', planted === 1 && dented === total - 1 && survDefault === 0 && survSymm === total,
          `011 is sensitive both ways: planting one survivor in the default instance moves the count 0 to ${planted}, and eliminating one point of the symmetric core moves it ${total.toLocaleString('en-US')} to ${dented.toLocaleString('en-US')}`);
}

// ------------------------------------------------------------------ total

console.log(`
${nPass} passed, ${nFail} failed, ${nSkip} skipped (skips are not passes)`);
process.exit(nFail > 0 ? 1 : 0);
