#!/usr/bin/env node
/*
 * Offline gate for "Six Contacts at the Jamming Point".
 * Run:  node research/six-contacts-at-the-jamming-point/verify-six-contacts-at-the-jamming-point.mjs
 * Node 22, no dependencies, no network. Exits non-zero on any FAIL.
 * The full-size sweep runs for real here: 39 packings, seven sizes to 3072 grains, each
 * carried through its whole compression ladder and relaxed at every rung. Expect roughly
 * fifteen to twenty-five minutes on one core, most of it the two largest sizes.
 */

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

const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, '../..');
const SLUG = 'six-contacts-at-the-jamming-point';
const DIR = path.join(ROOT, 'public', 'strata', SLUG);

let pass = 0, fail = 0;
const t0 = Date.now();
const ok = (n, msg) => { pass++; console.log(`PASS ${String(n).padStart(3, ' ')}  ${msg}`); };
const bad = (n, msg) => { fail++; console.log(`FAIL ${String(n).padStart(3, ' ')}  ${msg}`); };
const skip = (msg) => console.log(`SKIP   ${msg}`);
const ctrl = (n, good, msg) => {
  if (good) { pass++; console.log(`CONTROL ${String(n).padStart(3, ' ')}  caught: ${msg}`); }
  else { fail++; console.log(`FAIL ${String(n).padStart(3, ' ')}  CONTROL DID NOT CATCH: ${msg}`); }
};

const plan = await import(pathToFileURL(path.join(DIR, 'plan.js')));
const ref = await import(pathToFileURL(path.join(DIR, 'reference.js')));
// The kit is not an ES module with named exports: deep.js is an IIFE that hangs its API off
// self.AW.deep, because the page and the worker both load it with a plain <script>. Importing
// it RUNS it and populates the global; the module namespace it returns is empty. Binding the
// namespace instead gave 'deep.selftest is not a function' with no hint of why.
await import(pathToFileURL(path.join(ROOT, 'public', '_kit', 'deep.js')));
const deep = globalThis.AW && globalThis.AW.deep;
if (!deep) { console.log('FAIL 000  the kit at public/_kit/deep.js did not populate globalThis.AW.deep'); process.exit(1); }
let manifest = null;
try { manifest = await import(pathToFileURL(path.join(DIR, 'manifest.js'))); }
catch (e) { console.log('note: manifest.js not importable: ' + e.message); }

/* ---- 001 ABI --------------------------------------------------------------- */
let mod = null, inst = null;
{
  const wp = path.join(DIR, 'engine.wasm');
  if (!fs.existsSync(wp)) bad(1, 'engine.wasm missing from ' + DIR);
  else {
    const bytes = new Uint8Array(fs.readFileSync(wp));
    try {
      mod = await WebAssembly.compile(bytes);
      inst = deep.instantiate(mod);
      const need = ['aw_init', 'aw_chunk', 'aw_out', 'aw_out_len', 'memory'];
      const missing = need.filter((k) => !(k in inst.exports));
      if (missing.length) bad(1, 'missing exports: ' + missing.join(','));
      else ok(1, `ABI exports present (${bytes.length} bytes)`);
    } catch (e) { bad(1, 'instantiation failed: ' + e.message); }
  }
}

/* ---- 002 hash -------------------------------------------------------------- */
{
  const wp = path.join(DIR, 'engine.wasm');
  if (mod && manifest && manifest.WASM_SHA256) {
    const h = crypto.createHash('sha256').update(fs.readFileSync(wp)).digest('hex');
    if (h === manifest.WASM_SHA256.toLowerCase()) ok(2, 'sha256(engine.wasm) == manifest.WASM_SHA256');
    else bad(2, `hash mismatch: got ${h}, manifest names ${manifest.WASM_SHA256}`);
  } else if (!manifest) bad(2, 'manifest.js missing or has no WASM_SHA256');
}

/* ---- 003 reproducible build ------------------------------------------------- */
{
  let clangV = null;
  try {
    const r = spawnSync('clang', ['--version'], { encoding: 'utf8' });
    if (r.status === 0) { const m = /version\s+(\d+\.\d+\.\d+)/.exec(r.stdout); if (m) clangV = m[1]; }
  } catch (_) {}
  const pinned = manifest && manifest.CLANG ? String(manifest.CLANG) : null;
  const match = clangV && pinned && (pinned.includes(clangV) || clangV.includes(pinned));
  if (!match) skip(`reproducible build (clang ${clangV ?? 'absent'} vs pinned ${pinned ?? 'none'})`);
  else {
    try {
      const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'awbuild-'));
      const dst = path.join(tmp, 'engine.wasm');
      const r = spawnSync('bash', [path.join(ROOT, 'research/_ox3/lib/build-wasm.sh'),
        path.join(DIR, 'engine.c'), dst], { encoding: 'utf8' });
      if (r.status !== 0 || !fs.existsSync(dst)) {
        bad(3, 'build script failed: ' + (r.stderr || r.stdout || 'no output').slice(0, 300));
      } else {
        const a = crypto.createHash('sha256').update(fs.readFileSync(path.join(DIR, 'engine.wasm'))).digest('hex');
        const b = crypto.createHash('sha256').update(fs.readFileSync(dst)).digest('hex');
        if (a === b) ok(3, 'rebuilt engine.c under the pinned clang: bytes identical');
        else bad(3, `rebuild differs: ${a} vs ${b}`);
      }
      fs.rmSync(tmp, { recursive: true, force: true });
    } catch (e) { bad(3, 'reproducible-build check threw: ' + e.message); }
  }
}

/* ---- battery plumbing -------------------------------------------------------- */
const basePlan = {
  chunks: 1, rounds: 1, p0: 0, p1: 0,
  initial: plan.initial, reduce: plan.reduce, fingerprint: plan.fingerprint,
  battery: plan.battery, breakReference: plan.breakReference, reference: ref,
};

/* ---- 004/005 battery, 006 control -------------------------------------------- */
let st = null, ct = null;
if (mod) {
  try {
    st = await deep.selftest({ ...basePlan, engine: { module: mod } });
    if (st.agree) ok(4, `battery: engine and reference agree on all ${st.rows.length} rows`);
    else {
      const r0 = st.rows.find((r) => !r.agree);
      bad(4, `battery disagreement on "${r0.label}": wasm ${r0.wasm} vs ref ${r0.ref}`);
    }
    const distinct = new Set(st.rows.map((r) => r.wasm)).size;
    if (distinct >= 6) ok(5, `battery rows are not trivially identical (${distinct}/${st.rows.length} distinct fingerprints)`);
    else bad(5, `battery rows suspiciously alike (${distinct}/${st.rows.length} distinct)`);
  } catch (e) { bad(4, 'selftest threw: ' + e.message); }
  try {
    ct = await deep.control({ ...basePlan, engine: { module: mod } });
    // Stronger than deep.control's own bar of "caught at least one". The break shifts the
    // contact threshold by 2% of a mean diameter, so it must change the answer on EVERY
    // battery row that has a contact at all. Exactly one row, the planted dilute gas, has
    // none and cannot be caught by it; anything under 7 means the break is going soft.
    if (ct.passed && ct.caught >= 7) ok(6, `control: broken reference caught on ${ct.caught}/${ct.of} rows (the one it misses is the dilute plant, which has no contacts to miscount)`);
    else bad(6, `control caught only ${ct.caught}/${ct.of} rows` + (ct.note ? ' (' + ct.note + ')' : ''));
  } catch (e) { bad(6, 'control threw: ' + e.message); }
}

/* ---- 007/008 planted objects, through the unmodified pipeline ----------------- */
function runOne(p0, p1) {
  inst.init(p0 >>> 0, p1 >>> 0);
  const c = inst.chunk(0, 0, 1);
  const acc = plan.initial();
  plan.reduce(acc, new DataView(c.out.buffer, c.out.byteOffset, c.out.byteLength));
  return acc.jobs[0] ?? null;
}
{
  const lat = runOne(5, plan.M_LATTICE | 36);
  if (lat) {
    const last = lat.rungs[lat.rungs.length - 1];
    const z = 2 * last.clean / (36 - last.ratt);
    // F_BADPLANT (32) fires when the row count is odd, where the half-row offset is not
    // periodic in y and the plant is not the lattice it claims to be. 6x6 is fine; the
    // flag is asserted so a later N cannot answer wrongly in silence.
    if (last.clean === 108 && last.ratt === 0 && Math.abs(z - 6) < 1e-12 && lat.spec.zmFin === 2
        && (lat.flags & 32) === 0 && lat.spec.tnFin < 1e-12)
      ok(7, 'planted triangular lattice: 108 contacts, 0 rattlers, z = 6 exactly, 2 zero modes, translations exactly null');
    else bad(7, `planted lattice wrong: clean=${last.clean} ratt=${last.ratt} z=${z} zm=${lat.spec.zmFin} flags=${lat.flags} tn=${lat.spec.tnFin}`);
  } else bad(7, 'planted lattice produced no job');
  const dil = runOne(6, plan.M_DILUTE | 32);
  if (dil) {
    const last = dil.rungs[dil.rungs.length - 1];
    if (last.clean === 0 && last.raw === 0) ok(8, 'planted dilute config: zero contacts, z = 0');
    else bad(8, `planted dilute config wrong: raw=${last.raw} clean=${last.clean}`);
  } else bad(8, 'planted dilute config produced no job');
}

/* ---- full-size sweep, run for real ------------------------------------------- */
let accA = null;
if (mod) {
  accA = plan.initial();
  const tS = Date.now();
  for (let idx = 0; idx < plan.CONST.nchunks; idx++) {
    inst.init(((0 << 30) | plan.BASE_SEED) >>> 0, 0);
    const c = inst.chunk(0, idx, plan.CONST.nchunks);
    plan.reduce(accA, new DataView(c.out.buffer, c.out.byteOffset, c.out.byteLength));
  }
  console.log(`note: full sweep (${accA.jobs.length} packings) took ${((Date.now() - tS) / 1000).toFixed(1)}s`);
  // The headline numbers, printed rather than asserted: they are this page's measurement
  // on this protocol, and the page prints its own window, point count and scatter beside
  // them. A reader comparing two runs needs to see them in the gate's own output.
  {
    const pts = plan.poolPoints(accA, 768);
    const fe = plan.fitExponent(pts), fi = plan.fitIntercept(pts);
    console.log(`note: fit pool N>=768: ${pts.length} points within dphi <= ${plan.CONST.window} of each realisation's own phi_J`);
    console.log(`note: sqrt fit  z = z0 + A*sqrt(dphi):  z0 = ${fi ? fi.z0.toFixed(4) : 'n/a'}, A = ${fi ? fi.A.toFixed(4) : 'n/a'}, n = ${fi ? fi.n : 0}, rms = ${fi ? fi.rms.toFixed(4) : 'n/a'}   (isostatic value is ${plan.CONST.zIso})`);
    console.log(`note: power fit z - 4 = A*dphi^alpha:  alpha = ${fe ? fe.alpha.toFixed(4) : 'n/a'}, A = ${fe ? fe.A.toFixed(4) : 'n/a'}, n = ${fe ? fe.n : 0}, rms = ${fe ? fe.rms.toFixed(4) : 'n/a'}`);
    for (const r of plan.levelSummary(accA)) {
      console.log(`note:   N=${String(r.N).padStart(5)} reals=${r.reals} jammed=${r.jammed} phiJ(med)=${r.phiJmed ? r.phiJmed.toFixed(4) : '-'} points=${r.points} meanZ=${r.meanZ ? r.meanZ.toFixed(3) : '-'} sdZ=${r.sdZ ? r.sdZ.toFixed(3) : '-'}`);
    }
  }
}

/* ---- 009 decomposition: different packing-to-chunk assignment ----------------- */
if (mod && accA) {
  const sub = [...Array(16).keys()];               // jobIds 0..15 (levels 0 and 1)
  const runMap = async (mapId) => {
    const acc = plan.initial();
    for (const job of sub) {
      const idx = mapId === 1 ? plan.bitrev6(job) : job;
      inst.init(((mapId << 30) | plan.BASE_SEED) >>> 0, 0);
      const c = inst.chunk(0, idx, plan.CONST.nchunks);
      plan.reduce(acc, new DataView(c.out.buffer, c.out.byteOffset, c.out.byteLength));
    }
    return acc;
  };
  const a = await runMap(0), b = await runMap(1);
  const ca = JSON.stringify(plan.canon(a)), cb = JSON.stringify(plan.canon(b));
  const full = JSON.stringify(plan.canon({ jobs: accA.jobs.filter((j) => j.jobId < 16) }));
  if (ca === cb && ca === full && ca !== '[]')
    ok(9, 'decomposition: bit-reversed chunk assignment reproduces every per-packing record exactly');
  else bad(9, 'decomposition mismatch between chunk assignments');
}

/* ---- 010-013 invariants on the full sweep ------------------------------------- */
if (accA && accA.jobs.length) {
  let maxRes = 0, unconvChecked = 0, resBad = 0;
  for (const j of accA.jobs) for (const r of j.rungs) {
    if (!r.conv) continue;
    unconvChecked++;
    if (r.resid > maxRes) maxRes = r.resid;
    if (!(r.resid <= plan.CONST.ftol * 1.000001)) resBad++;
  }
  if (resBad === 0 && unconvChecked > 0)
    ok(10, `force balance: ${unconvChecked} converged rungs, max residual ${maxRes.toExponential(2)} <= ${plan.CONST.ftol}`);
  else bad(10, `${resBad} converged rungs exceed the force tolerance`);

  // cgViol counts accepted CG steps whose energy, RE-EVALUATED through the gradient
  // branch of the pair pass at the copied coordinates, is not bit-identical to the value
  // the line search accepted or is not below the pre-step energy. Until this repair
  // nothing anywhere incremented it and this line could not fail; it is a consistency
  // check on the two energy evaluations, not an independent test of the optimiser, and
  // the README says so.
  const viol = accA.jobs.reduce((s, j) => s + j.cgViol, 0);
  const steps = accA.jobs.reduce((s, j) => s + j.cgSteps, 0);
  if (viol === 0 && steps > 0)
    ok(11, `energy re-evaluation: over ${steps} accepted CG steps, every one re-evaluated to the exact energy the line search accepted, and below the pre-step energy`);
  else bad(11, `${viol} energy re-evaluation mismatches over ${steps} accepted steps`);

  /* The stiffness matrix is built over EVERY particle, rattlers included, so "exactly two
   * zero modes" is only the right statement when no rattler survives. A rattler is a
   * particle with fewer than three contacts; in two dimensions its own free directions
   * number at most two, and they are genuine zero modes of this matrix. So the exact
   * invariant is: zm = 2 when the final rung has no rattlers, and 2 < zm <= 2 + 2*ratt
   * when it has some. Measured on this sweep: 13 of the 16 spectral jobs end rattler-free
   * and give exactly 2; the three that keep one rattler give 3, 4 and 4. The earlier
   * blanket "zm === 2" was wrong about what the matrix contains, not about the physics. */
  const specJobs = accA.jobs.filter((j) => (j.flags & 4) && j.jammed);
  let zmBad = 0, psdBad = 0, tnBad = 0, clean2 = 0, withRatt = 0;
  for (const j of specJobs) {
    const fr = j.rungs[j.spec.finRung];
    const ratt = fr ? fr.ratt : 0;
    if (ratt === 0) {
      if (j.spec.zmFin !== 2) zmBad++; else clean2++;
    } else {
      if (!(j.spec.zmFin > 2 && j.spec.zmFin <= 2 + 2 * ratt)) zmBad++; else withRatt++;
    }
    if (j.spec.psdFin !== 1) psdBad++;
    if (!(j.spec.tnFin < 1e-6)) tnBad++;
    if (j.spec.psdNear !== 1) psdBad++;
  }
  if (specJobs.length && zmBad === 0 && psdBad === 0 && tnBad === 0 && clean2 > 0)
    ok(12, `spectral invariants on ${specJobs.length} jammed packings: ${clean2} rattler-free ones have exactly 2 zero modes (the two translations), ${withRatt} with rattlers sit inside 2 < zm <= 2 + 2*ratt, all positive semidefinite, translation null norm < 1e-6 throughout`);
  else bad(12, `spectral invariants: ${specJobs.length} jobs, zmBad=${zmBad} psdBad=${psdBad} tnBad=${tnBad} rattlerFreeWith2=${clean2}`);

  let near = 0, far = 0;
  for (const j of accA.jobs) {
    if (!(j.flags & 4) || !j.jammed) continue;
    const nr = j.rungs[j.spec.nearRung];
    const nf = j.rungs[j.spec.finRung];
    if (nr && nr.phi - j.phiJ < 0.02) near += j.spec.lbNear;
    if (nf && nf.phi - j.phiJ > 0.04) far += j.spec.lbFin;
  }
  if (near >= far) ok(13, `low-frequency direction: ${near} modes below 1e-4 near jamming vs ${far} far above (weak, directional)`);
  else bad(13, `low-frequency modes DECREASED toward jamming (${near} near vs ${far} far)`);
}

/* ---- 014 the page's fixed facts ------------------------------------------------ */
{
  const hp = path.join(DIR, 'index.html');
  if (!fs.existsSync(hp)) bad(14, 'index.html missing');
  else {
    const html = fs.readFileSync(hp, 'utf8');
    const m = /<script type="application\/json" id="aw-constants">([\s\S]*?)<\/script>/.exec(html);
    if (!m) bad(14, 'aw-constants JSON block missing from the page');
    else {
      let page;
      try { page = JSON.parse(m[1]); } catch (e) { page = null; }
      if (!page) bad(14, 'aw-constants block does not parse');
      else {
        const diffs = [];
        for (const k of Object.keys(plan.CONST)) {
          const a = JSON.stringify(page[k]), b = JSON.stringify(plan.CONST[k]);
          if (a !== b) diffs.push(`${k}: page ${a} vs plan ${b}`);
        }
        if (diffs.length === 0) ok(14, 'every protocol constant printed on the page matches the committed plan');
        else bad(14, 'constant mismatches: ' + diffs.join('; '));
      }
    }
    const needIds = ['stage', 'runSweep', 'batTable', 'costOps', 'modeCanvas', 'plotDos', 'aw-constants'];
    const miss = needIds.filter((id) => !html.includes(`id="${id}"`));
    if (miss.length) bad(14, 'page missing required elements: ' + miss.join(','));
    else ok(14, 'page carries the instrument, run, check and cost panels');

    /* 015: the page's own script has to PARSE. Everything above this check reads the page
     * as text, and a page whose module never parses shows a dead panel while every
     * text-level assertion stays green. This one found two real ones: an unescaped
     * apostrophe inside a single-quoted string, and a raw newline inside another. */
    const mods = [...html.matchAll(/<script type="module">([\s\S]*?)<\/script>/g)].map((m) => m[1]);
    if (!mods.length) bad(15, 'page has no module script');
    else {
      const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'awpage-'));
      const bads = [];
      mods.forEach((src, i) => {
        const f = path.join(tmp, `mod${i}.mjs`);
        fs.writeFileSync(f, src);
        const r = spawnSync(process.execPath, ['--check', f], { encoding: 'utf8' });
        if (r.status !== 0) bads.push(`block ${i}: ` + String(r.stderr || '').split('\n').slice(0, 3).join(' '));
      });
      fs.rmSync(tmp, { recursive: true, force: true });
      if (bads.length) bad(15, "the page's module script does not parse: " + bads.join(' | '));
      else ok(15, `the page's ${mods.length} module script(s) parse under node --check`);
    }
  }
}

/* ---- 016 the intercept as printed, with its error bar ------------------------------
 * Added 2026-09-26. The dek used to quote the intercept as 3.9995, a digit string the page
 * never rendered, to a precision nine packings cannot support. The error bar is the
 * delete-one-packing jackknife in plan.js; the printed pair is plan.roundedPair, which
 * rounds the error to one significant figure and the value to match. This checks that the
 * dek, the page's rendering code and its dated note all carry the pair the sweep gives. */
if (accA && accA.jobs.length) {
  const mdPath = path.join(ROOT, 'src', 'content', 'strata', SLUG + '.md');
  const md = fs.existsSync(mdPath) ? fs.readFileSync(mdPath, 'utf8') : '';
  const html = fs.readFileSync(path.join(DIR, 'index.html'), 'utf8');
  const dek = (/^dek:\s*"(.*)"\s*$/m.exec(md) || [])[1] || '';
  const pts = plan.poolPoints(accA, 768);
  const fi = plan.fitIntercept(pts), jk = fi && plan.jackknifeIntercept(pts);
  const hv = fi && plan.interceptWithoutRattlerHeavy(pts);
  const ols = fi && plan.olsInterceptSE(pts, fi);
  if (!fi || !jk || !hv || !hv.jk) bad(16, 'intercept, jackknife or sensitivity fit could not be computed');
  else {
    const head = plan.roundedPair(fi.z0, jk.se), alt = plan.roundedPair(hv.fi.z0, hv.jk.se);
    const miss = [];
    if (!dek.includes(`prints ${head},`)) miss.push(`dek lacks "prints ${head},"`);
    if (!dek.includes(`gives ${alt},`)) miss.push(`dek lacks "gives ${alt},"`);
    if (!dek.includes(`${hv.dropped} of its ${fi.n} points`) && !dek.includes(`${['Zero','One','Two','Three','Four','Five','Six'][hv.dropped] ?? hv.dropped} of its ${fi.n} points`))
      miss.push(`dek does not say ${hv.dropped} of ${fi.n} points`);
    if (/3\.9995/.test(md) && !/used to say the intercept "prints 3\.9995"/.test(md.replace(/\\"/g, '"'))) miss.push('md still quotes 3.9995 as current');
    if (!md.includes(`standard error of ${jk.se.toFixed(3)}`)) miss.push(`md note lacks jackknife SE ${jk.se.toFixed(3)}`);
    if (!md.includes(`figure, ${ols.toFixed(3)},`)) miss.push(`md note lacks OLS SE ${ols.toFixed(3)}`);
    if (!md.includes(`(${alt})`)) miss.push(`md note lacks (${alt})`);
    if (!html.includes('z0 = ${plan.roundedPair(fi.z0, jk.se)}')) miss.push('page does not render z0 through roundedPair with the jackknife SE');
    if (/fi\.z0\.toFixed\(/.test(html)) miss.push('page still renders a bare fi.z0.toFixed');
    if (!html.includes(`<span class="mono">z0 = ${head}</span>`)) miss.push(`page note lacks z0 = ${head}`);
    if (!html.includes(`<span class="mono">${alt}</span>`)) miss.push(`page note lacks ${alt}`);
    if (!html.includes(`pools ${fi.n} rungs`)) miss.push(`page note does not say ${fi.n} rungs`);
    /* Like for like. The exponent fit keeps points with z above four; on this sweep those are
     * exactly the points that are not rattler-dominated, so both fits can be compared on one
     * set. The dek used to call the exponent fit "three times closer", comparing its scatter
     * on 61 points with the square root's on 65. */
    const fe = plan.fitExponent(pts);
    const gt4 = pts.filter((p) => p.z > 4.0005);
    const noH = pts.filter((p) => !(p.rattFrac > plan.HEAVY_RATTLER_FRACTION));
    const sameSet = gt4.length === noH.length && gt4.every((p, i) => p === noH[i]);
    const powRms = (set) => Math.sqrt(set.reduce((s, p) => s + (p.z - 4 - fe.A * p.dphi ** fe.alpha) ** 2, 0) / set.length);
    if (!fe || !sameSet) miss.push('exponent-fit points and non-rattler-heavy points are no longer the same set');
    else {
      const rP = fe.rms.toFixed(3), rS = hv.fi.rms.toFixed(3);
      if (!(fe.rms / hv.fi.rms < 1.5 && hv.fi.rms / fe.rms < 1.5)) miss.push(`fits no longer equally close: ${rP} vs ${rS}`);
      if (!dek.includes(`same ${fe.n} points the two sit equally close (rms ${rP} against ${rS})`)) miss.push(`dek lacks like-for-like rms ${rP} against ${rS}`);
      if (!dek.includes(`prefers ${fe.alpha.toFixed(2)};`) || !dek.includes(`ending near ${hv.fi.z0.toFixed(2)}`)) miss.push('dek exponent or alternative intercept wrong');
      if (/three times closer/.test(dek)) miss.push('dek still says three times closer');
      if (!md.includes(`(rms ${rS} and ${rP})`) || !md.includes(`(${powRms(pts).toFixed(3)} against ${fi.rms.toFixed(3)})`)) miss.push('md note like-for-like numbers wrong');
      if (!(powRms(pts) > fi.rms)) miss.push('on all points the fixed-at-four fit is no longer the worse one');
      if (!html.includes(`rms <span class="mono">${rS}</span> for the square root against <span class="mono">${rP}</span>`)) miss.push('page note like-for-like numbers wrong');
    }
    /* The opening paragraph's numbers: first load-bearing rung per packing at N = 48, the
     * scatter of that first-rung z across packings by size, and the per-size intercepts. */
    const firstZ = (N) => accA.jobs.filter((j) => j.N === N && j.jammed)
      .map((j) => plan.poolPoints({ jobs: [j] }, N)[0]).filter(Boolean).map((p) => p.z);
    const sdv = (a) => { const m = a.reduce((x, y) => x + y, 0) / a.length; return Math.sqrt(a.reduce((s, x) => s + (x - m) ** 2, 0) / (a.length - 1)); };
    const z48 = firstZ(48), mean48 = z48.reduce((a, b) => a + b, 0) / z48.length;
    const sds = Object.fromEntries(plan.CONST.sizes.map((N) => [N, sdv(firstZ(N))]));
    if (!html.includes(`reads anywhere from ${Math.min(...z48).toFixed(1)} to ${Math.max(...z48).toFixed(1)},`) || !(mean48 < 4))
      miss.push(`page N=48 range/mean wrong (${Math.min(...z48).toFixed(3)}..${Math.max(...z48).toFixed(3)}, mean ${mean48.toFixed(3)})`);
    if (!html.includes(`from ${sds[48].toFixed(2)} at 48 grains to ${sds[768].toFixed(2)} at 768`) || !(sds[1536] > sds[768] && sds[3072] > sds[768]))
      miss.push('page scatter-by-size numbers wrong');
    const perSize = plan.CONST.sizes.slice(0, 5).map((N) => plan.fitIntercept(plan.poolPoints({ jobs: accA.jobs.filter((j) => j.N === N) }, N)).z0.toFixed(2)).join(', ');
    if (!html.replace(/\s+/g, ' ').includes(`per-size intercepts run ${perSize} from 48`)) miss.push(`page per-size intercepts should read ${perSize}`);
    // search and sharing descriptions carry the error bar, and no longer put the onset AT four
    const heads = [/<meta name="description" content="([^"]*)"/, /<meta property="og:description" content="([^"]*)"/,
      /<meta name="twitter:description" content="([^"]*)"/, /"@type":"Article".*?"description":"([^"]*)"/]
      .map((re) => (re.exec(html) || [])[1] || '');
    heads.forEach((t, i) => {
      if (!(t.includes(head) && !/\d/.test(t[t.indexOf(head) + head.length] || ''))) miss.push(`head description ${i} lacks ${head}`);
      if (/at the isostatic contact number|intercept near 4|isostatic value emerge/.test(t)) miss.push(`head description ${i} keeps an unqualified claim`);
    });
    if (miss.length === 0)
      ok(16, `like-for-like on ${fe.n} points: rms ${hv.fi.rms.toFixed(3)} (square root) vs ${fe.rms.toFixed(3)} (exponent fit); opening-paragraph and head descriptions match; intercept printed as ${head} (jackknife over ${jk.G} packings, SE ${jk.se.toFixed(3)}; OLS SE ${ols.toFixed(3)}), without the ${hv.dropped} rattler-heavy rungs ${alt}; dek, page code and page note agree`);
    else bad(16, 'intercept text disagrees with the computation: ' + miss.join('; '));
  }
}
/* ---- end 016 */

/* ---- negative controls on the verifier itself ----------------------------------- */
if (mod && st) {
  // C1: corrupt one record field; the fingerprint comparator must notice.
  inst.init(2, (plan.M_SINGLE | 48) >>> 0);
  const c = inst.chunk(0, 0, 1);
  const bytes = c.out.slice();
  const dv = new DataView(bytes.buffer);
  dv.setUint32(20 + 20, dv.getUint32(20 + 20, true) + 1, true);   // first rung's clean count
  const accGood = plan.initial(), accBad = plan.initial();
  plan.reduce(accGood, new DataView(c.out.buffer, c.out.byteOffset, c.out.byteLength));
  plan.reduce(accBad, new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength));
  ctrl(1, plan.fingerprint(accGood) !== plan.fingerprint(accBad), 'single mutated contact count changes the fingerprint');
  // C2: mutate the seed; the decomposition comparison must notice.
  const run3 = (base) => {
    const acc = plan.initial();
    for (let idx = 0; idx < 3; idx++) {
      inst.init(base >>> 0, 0);
      const cc = inst.chunk(0, idx, plan.CONST.nchunks);
      plan.reduce(acc, new DataView(cc.out.buffer, cc.out.byteOffset, cc.out.byteLength));
    }
    return JSON.stringify(plan.canon(acc));
  };
  ctrl(2, run3(((0 << 30) | plan.BASE_SEED) >>> 0) !== run3(((0 << 30) | (plan.BASE_SEED ^ 0xF)) >>> 0),
    'changed base seed changes the aggregated records');
}

/* ---- summary --------------------------------------------------------------------- */
console.log(`
${pass} passed, ${fail} failed, ${(Date.now() - t0) / 1000 | 0}s total`);
process.exit(fail ? 1 : 0);
