#!/usr/bin/env node
/* verify-the-gap-that-carves-itself.mjs -- the offline gate.
 *
 *   node research/the-gap-that-carves-itself/verify-the-gap-that-carves-itself.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 two
 * full-size decomposition runs dominate the runtime (expect a few minutes
 * total depending on the machine); everything else is seconds.
 */

import fs from 'node:fs';
import path from 'node:path';
import vm from 'node:vm';
import { createHash } from 'node:crypto';
import { execFileSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';

const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, '..', '..');
const SLUG = 'the-gap-that-carves-itself';
const DIR = path.join(ROOT, 'public', 'strata', SLUG);

let nPass = 0, nFail = 0, nSkip = 0, nCtrl = 0, nCtrlBad = 0, seq = 0;
function ok(name, cond, extra) {
  seq++;
  if (cond) { nPass++; console.log(`PASS ${String(seq).padStart(3, '0')}  ${name}`); }
  else { nFail++; console.log(`FAIL ${String(seq).padStart(3, '0')}  ${name}${extra ? '  :: ' + extra : ''}`); }
}
function skip(name, why) { nSkip++; console.log(`SKIP  ${name} (${why})`); }
function control(name, cond) {
  nCtrl++;
  if (cond) console.log(`CONTROL  ok    ${name}`);
  else { nCtrlBad++; console.log(`CONTROL  BAD   ${name}`); }
}
const t0 = Date.now();
const stamp = () => `[${((Date.now() - t0) / 1000).toFixed(1)}s]`;

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

const kitSrc = fs.readFileSync(path.join(ROOT, 'public', '_kit', 'deep.js'), 'utf8');
vm.runInThisContext(kitSrc, { filename: 'deep.js' });
const deep = globalThis.AW.deep;

const plan = await import(`file://${path.join(DIR, 'plan.js')}`);
const ref = await import(`file://${path.join(DIR, 'reference.js')}`);

const wasmPath = path.join(DIR, 'engine.wasm');
const wasmBytes = fs.readFileSync(wasmPath);
const mod = await WebAssembly.compile(wasmBytes);
const probe = new WebAssembly.Instance(mod, {});
const NEED = ['aw_init', 'aw_chunk', 'aw_out', 'aw_out_len', 'aw_alloc', 'aw_reset', 'memory'];
ok('engine.wasm instantiates and exports the full ABI', NEED.every((k) => k in probe.exports));

const manSrc = fs.readFileSync(path.join(DIR, 'manifest.js'), 'utf8');
const mSha = (/WASM_SHA256\s*=\s*["']([0-9a-f]{64})["']/.exec(manSrc) || [])[1];
const mClang = (/CLANG\s*=\s*["']([^"']+)["']/.exec(manSrc) || [])[1];
const digest = createHash('sha256').update(wasmBytes).digest('hex');
ok('sha256(engine.wasm) equals WASM_SHA256 from manifest.js',
  !!mSha && digest === mSha, `file ${digest} vs manifest ${mSha}`);

/* ------------------------------------------------- constants cross-read */

const engSrc = fs.readFileSync(path.join(DIR, 'engine.c'), 'utf8');
const defines = {};
for (const m of engSrc.matchAll(/#define\s+AW_(\w+)\s+([-+0-9.eExXA-Fa-f]+)/g)) defines[m[1]] = m[2];
const P = plan.PARAMS;
const pairs = [
  ['MU', P.MU], ['H', P.H], ['REC', P.REC], ['RENORM', P.RENORM], ['D0', P.D0],
  ['ETHR', P.ETHR], ['E0', P.E0], ['NSIG', P.NSIG], ['NPLANT', P.NPLANT],
  ['ACIRC', P.ACIRC], ['ACHAOS', P.ACHAOS], ['EPLANT', P.EPLANT], ['ARES', P.ARES],
  ['AMIN', P.AMIN], ['AMAX', P.AMAX],
];
ok('engine.c #define constants match plan.PARAMS exactly',
  pairs.every(([k, v]) => k in defines && Number(defines[k]) === v),
  JSON.stringify(pairs.filter(([k, v]) => !(k in defines && Number(defines[k]) === v))));
ok('ARES is 3^(-2/3) to within 1e-15',
  Math.abs(P.ARES - Math.pow(3, -2 / 3)) < 1e-15);

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

{
  let clangOk = false, found = 'absent';
  try {
    const v = execFileSync('clang', ['--version'], { encoding: 'utf8' });
    found = v.split('\n')[0].trim();
    clangOk = !!mClang && v.includes(mClang);
  } catch (_) { /* clang not on PATH */ }
  if (!clangOk) {
    skip('reproducible build', `clang ${found} != pinned ${mClang || '(none)'}`);
  } else {
    const script = path.join(ROOT, 'research', '_ox3', 'lib', 'build-wasm.sh');
    const tmp = path.join(HERE, '.rebuild.wasm');
    try {
      execFileSync('bash', [script, path.join(DIR, 'engine.c'), tmp], { stdio: ['ignore', 'pipe', 'pipe'] });
      const rb = fs.readFileSync(tmp);
      ok('reproducible build: rebuilt engine.c is byte-identical to engine.wasm',
        rb.length === wasmBytes.length && rb.equals(wasmBytes));
    } catch (err) {
      ok('reproducible build: rebuilt engine.c is byte-identical to engine.wasm', false, String(err.message).slice(0, 200));
    } finally { try { fs.unlinkSync(tmp); } catch (_) {} }
  }
}

/* -------------------------------------------------------------- battery */

const PL = plan.asPlan({ module: mod });
PL.reference = ref;

console.log(`${stamp()} running the ${PL.battery.length}-row battery (engine vs reference)...`);
const st = await deep.selftest(PL);
for (const r of st.rows)
  console.log(`   battery  ${r.label.padEnd(28)} wasm=${r.wasm.slice(0, 12)} ref=${r.ref.slice(0, 12)} ${r.agree ? 'agree' : 'DISAGREE'}`);
ok('battery: engine and reference fingerprints agree on every row', st.agree);
ok('battery: honest step counters match (opsW == opsR on every row)',
  st.rows.every((r) => r.opsW === r.opsR));
// ⚠ NOT "every row differs". A row that recomputes the same instance under a different
// decomposition SHOULD agree with its twin, and requiring them to differ requires that check to
// fail. What would be worthless is a battery whose rows ALL coincide, so that is what is tested:
// the battery must exercise more than one instance, and any rows that do coincide are reported
// so a reader can see how much of it is decomposition rather than coverage.
{
  const prints = st.rows.map((r) => r.wasm);
  const distinct = new Set(prints).size;
  const shared = st.rows.length - distinct;
  ok(`battery exercises ${distinct} distinct instance(s) across ${st.rows.length} rows` +
     (shared ? `, with ${shared} row(s) agreeing across a different decomposition` : ''),
     distinct >= 2);
}

/* -------------------------------------------------------------- control */

const brk = plan.breakReference(ref);
ok('breakReference returns a different object from the reference', brk !== ref);
console.log(`${stamp()} running the control (mass ratio broken by one part in a thousand)...`);
const ct = await deep.control(PL);
ok('control: the broken reference is caught on at least one battery row',
  ct.passed && ct.caught >= 1, `caught ${ct.caught}/${ct.of}`);
// The control does not undo itself.  breakReference.init() sets the flag, calls init()
// (which LATCHES mu*1.001 into the module's frame constants) and then clears the FLAG only;
// nothing restores the constants but another init().  Without this line every reference-driven
// check below - the step-halving order test and the whole cross-method comparison - ran a mass
// ratio of 0.001001 against diagnostics and an RK4 written for 0.001.  Measured: it turned the
// halving ratios 4.00/4.01/4.00 into 1.21/4.20/4.34 and failed the order assertion.
ref._setBroken(false);
ref.init(plan.N_TOTAL, P.STEPS);
{
  // Note WHERE the break shows: ref.diag() and ref.icForIndex() are written against the module
  // constant MU and do not move when the mass ratio is broken; only the force law does.  That
  // asymmetry is exactly why the leak was invisible - a broken run kept reporting its Jacobi
  // constant in the unbroken frame - so the probe below steps the map rather than reading it.
  const step100 = () => {
    const st = [ref.icForIndex(0, plan.N_TOTAL)];
    ref.stepBatch(st, 100, P.H);
    return st[0].x;
  };
  const xClean = step100();
  ref._setBroken(true); ref.init(plan.N_TOTAL, P.STEPS);
  const xBroken = step100();
  ref._setBroken(false); ref.init(plan.N_TOTAL, P.STEPS);
  const xAgain = step100();
  control('the reference really is restored after the control (breaking the mass ratio moves the trajectory, and un-breaking it moves it back exactly)',
    xClean !== xBroken && xAgain === xClean);
}

/* ------------------------------------------------- full size, twice over */

async function runFull(chunks) {
  const inst = deep.instantiate(mod);
  inst.init(plan.N_TOTAL, P.STEPS);
  const acc = plan.initial();
  let ops = 0n;
  const t = Date.now();
  for (let i = 0; i < chunks; i++) {
    const c = inst.chunk(0, i, chunks);
    ops += BigInt(c.ops);
    plan.reduce(acc, new DataView(c.out.buffer, c.out.byteOffset, c.out.byteLength), i);
    if (i % 32 === 0) console.log(`${stamp()}   decomposition chunks=${chunks}: ${i + 1}/${chunks}`);
  }
  console.log(`${stamp()}   decomposition chunks=${chunks} done in ${((Date.now() - t) / 1000).toFixed(1)}s`);
  return { acc, ops };
}

console.log(`${stamp()} FULL-SIZE RUN A (chunks=${plan.CHUNKS_A})...`);
const A = await runFull(plan.CHUNKS_A);
console.log(`${stamp()} FULL-SIZE RUN B (chunks=${plan.CHUNKS_B}, different decomposition)...`);
const B = await runFull(plan.CHUNKS_B);

const expectedOps = BigInt(plan.N_TOTAL * P.STEPS);
ok(`run A executed exactly ${plan.N_TOTAL.toLocaleString('en-US')} x ${P.STEPS.toLocaleString('en-US')} counted particle-steps`, A.ops === expectedOps, String(A.ops));
ok('run B executed the same counted steps under the second decomposition', B.ops === expectedOps, String(B.ops));

function bytesEqual(a, b) {
  return a.length === b.length && a.every((v, i) => v === b[i]);
}
ok('FULL-SIZE CHECK (a): all per-particle records byte-identical across 257-chunk and 97-chunk decompositions',
  bytesEqual(A.acc.buf, B.acc.buf));

/* ------------------------------------------------------------ invariants */

const S = plan.summarize(A.acc.buf);
const BF = plan.bandFractions(A.acc.buf);
const gammaOf = (r) => r.lyap / (P.STEPS * P.H);
const binW = (P.AMAX - P.AMIN) / plan.NBINS;
console.log(`${stamp()} measured: crossed ${S.crossedTotal}/${S.n} sweep particles ` +
  `(inner band n=${BF.inner.n}: ${BF.inner.c}; outer bands n=${BF.outer.n}: ${BF.outer.c}); ` +
  `median gamma inner ${S.gammaInMed.toExponential(2)}, outer ${S.gammaOutMed.toExponential(2)}, ` +
  `largest anywhere in the sweep ${S.maxGamma.toExponential(2)}; ` +
  `max-e profile peaks at a=${S.peak.a.toFixed(6)} (mean ${S.peak.mxMean.toFixed(4)}) over a baseline of ${S.baseMaxE.toFixed(4)}; ` +
  `max Jacobi drift ${S.maxDrift.toExponential(2)}`);
console.log(`${stamp()} controls: circular a=${P.ACIRC} maxE=${S.circ.maxE.toFixed(5)} gamma=${gammaOf(S.circ).toExponential(2)}; ` +
  `chaotic a=${P.ACHAOS} maxE=${S.chaos.maxE.toFixed(3)} gamma=${gammaOf(S.chaos).toExponential(2)} ` +
  `crossed at t=${S.chaos.crossT} drift=${S.chaos.drift.toExponential(2)}; ` +
  `plants ${S.plants.map((r) => r.maxE.toFixed(4)).join(', ')}`);

const driftAll = Math.max(S.maxDrift, S.circ.drift, ...S.plants.map((r) => r.drift));
ok(`invariant (b): max Jacobi drift ${driftAll.toExponential(2)} over the sweep and the planted bound orbits stays under the ceiling ${plan.DRIFT_BOUND}`,
  driftAll < plan.DRIFT_BOUND);
ok('invariant (b): the planted circular control does not pump (maxE < 0.01) and has gamma below the chaotic classifier',
  !plan.isEmptyRec(S.circ) && S.circ.maxE < 0.01 && gammaOf(S.circ) < plan.GAMMA_CHAOTIC,
  `maxE=${S.circ.maxE}`);
// THE POSITIVE CONTROL ON THE NULL.  This run's headline is that nothing escapes, and a
// detector that never fires would report exactly the same thing.  So one particle is planted
// where the model IS violently chaotic (a = 0.9, which is 0.1 in semi-major axis from the
// perturber, about 1.4 Hill radii at this mass ratio): the
// escape detector must fire on it and the Lyapunov estimator must lift above every sweep
// particle.  If this goes red, the zero below means nothing and must not be published.
ok(`positive control (planted chaotic object at a = ${P.ACHAOS}): the escape detector fires (crossed at t = ${S.chaos.crossT}) and its gamma ${gammaOf(S.chaos).toExponential(2)} clears both the classifier and every sweep particle`,
  !plan.isEmptyRec(S.chaos) && S.chaos.crossStep >= 0 &&
  gammaOf(S.chaos) > plan.GAMMA_CHAOTIC && gammaOf(S.chaos) > S.maxGamma,
  `cross=${S.chaos.crossStep} gamma=${gammaOf(S.chaos).toExponential(3)} vs sweep max ${S.maxGamma.toExponential(3)}`);
const plantBest = Math.max(...S.plants.map((r) => r.maxE));
// 0.23, not the 0.25 of revision 3: that threshold was met only by the desynchronised
// diagnostic, which biased every recorded eccentricity upward by about 0.018.  The same orbits
// deliver 0.2388 and 0.2356 read at the synchronised state, and RK4 gives 0.2355 for the second.
ok('control (planted object): the deep-resonance starts pump by libration (best maxE >= 0.23, well above their own start and far above the circular control)',
  plantBest >= 0.23 && plantBest > P.E0 + 0.03 && plantBest > S.circ.maxE + 0.1,
  `best=${plantBest.toFixed(4)} circ=${S.circ.maxE.toFixed(4)}`);
// THE MEASURED RESULT, and it is a null.  The page states it as one.
ok(`the measured result: 0 of ${plan.NSWEEP.toLocaleString('en-US')} sweep particles cross e = ${P.ETHR} in ${(P.STEPS * P.H).toLocaleString('en-US')} time units, on a detector proved above to be capable of firing`,
  S.crossedTotal === 0 && BF.inner.c === 0 && BF.outer.c === 0,
  `crossed=${S.crossedTotal}`);
// The resonance is nonetheless FOUND, and found by location rather than by assumption: the
// argmax over 40 bins of the mean recorded max eccentricity is computed without reference to
// a_res and then compared against 3^(-2/3).
ok(`the resonance is located: the max-e profile peaks at a = ${S.peak.a.toFixed(6)}, within one ${binW.toFixed(5)} bin of 3^(-2/3) = ${P.ARES}, and lifts ${((S.peak.mxMean / S.baseMaxE - 1) * 100).toFixed(1)}% above the outer-band baseline`,
  Math.abs(S.peak.a - P.ARES) <= binW && S.peak.mxMean >= 1.1 * S.baseMaxE,
  `peak=${S.peak.a} base=${S.baseMaxE}`);
// The second null, also positive-controlled: no Lyapunov structure across the resonance.
ok(`layer 2: the Lyapunov profile across the resonance is FLAT (inner ${S.gammaInMed.toExponential(2)} vs outer ${S.gammaOutMed.toExponential(2)}, within 20%), while the same estimator returns ${gammaOf(S.chaos).toExponential(2)} on the planted chaotic control`,
  Math.abs(S.gammaInMed / S.gammaOutMed - 1) <= 0.2 && gammaOf(S.chaos) > S.maxGamma,
  `ratio=${(S.gammaInMed / S.gammaOutMed).toFixed(3)}`);

/* --------------------------------------------------- step-halving (order) */
// RMS statistic, not sampled max.  The max of |C - C0| over a grid that
// undersamples the C-error oscillation has large variance when the signal is
// small and near-monochromatic (the clean circular control): a ratio below 4
// is impossible for a pure polynomial error, so the shipped 1.61 on the
// control was a property of the statistic, not of the map (the same step gave
// 3.96 and 4.11 on busier orbits).  The RMS of the same samples estimates the
// oscillation amplitude with far less variance.  The asserted law (divide by
// ~4) and the acceptance window [2, 8] are unchanged.
function driftRms(i, Ssteps, h) {
  const states = [ref.icForIndex(i, plan.N_TOTAL)];
  const C0 = ref.diag(states[0]).C;
  let sum = 0, n = 0;
  for (let n0 = 0; n0 < Ssteps; n0 += 100) {
    ref.stepBatch(states, Math.min(100, Ssteps - n0), h);
    const d = ref.diag(states[0]).C - C0;
    sum += d * d;
    n++;
  }
  return Math.sqrt(sum / Math.max(1, n));
}
console.log(`${stamp()} step-halving order check (reference implementation, T=2,000, RMS drift statistic)...`);
const ratios = [1024, 100, 900].map((i) => {
  const d1 = driftRms(i, plan.HALVE.S, P.H);
  const d2 = driftRms(i, plan.HALVE.S, P.H / 2);
  const r = d1 / d2;
  console.log(`   particle ${i}: rms drift(h)=${d1.toExponential(2)} rms drift(h/2)=${d2.toExponential(2)} ratio=${r.toFixed(2)}`);
  return r;
});
ok('invariant (b): halving the step divides the RMS Jacobi drift by ~4 (second order), all ratios in [2, 8]',
  ratios.every((r) => r >= plan.HALVE.LO && r <= plan.HALVE.HI), ratios.map((r) => r.toFixed(2)).join(','));

/* --------------------------------------------------- cross-method (RK4) */

console.log(`${stamp()} cross-method: RK4 on the ${plan.SUBSET_RK.length}-particle subset...`);
const sched = (n) => n === 0 || (n <= plan.RK_CMP_STEPS ? n % 10 === 0 : n % 100 === 0);
const CHAOS_IDX = plan.N_TOTAL - 3;
let worstShort = 0, worstShortAt = -1, agreeOutcome = 0, rkCrossed = 0, engCrossed = 0;
let maxEWorst = 0, maxEWorstAt = -1;
const maxERows = [];
for (const i of plan.SUBSET_RK) {
  const lf = ref.traceParticle(i, plan.N_TOTAL, P.STEPS, sched);
  const rec = plan.decode(A.acc.buf, i);
  const rkE = [];
  let rkCross = -1;
  const rk = plan.rk4Run(ref.icForIndex(i, plan.N_TOTAL), P.STEPS, P.H, (n, e) => {
    if (sched(n)) rkE.push(e);
    if (rkCross < 0 && e >= P.ETHR) rkCross = n;
  });
  if (lf.e.length !== rkE.length) { ok('cross-method sample schedules align', false, `${lf.e.length} vs ${rkE.length}`); break; }
  // Pointwise, over the opening window, for every particle EXCEPT the planted chaotic control:
  // that one has close encounters with the perturber, and no two integrators track a close
  // encounter step for step.  It is compared by its outcome instead, two lines down.
  if (i !== CHAOS_IDX) {
    const nShort = Math.floor(plan.RK_CMP_STEPS / 10) + 1;
    for (let k = 0; k < nShort && k < lf.e.length; k++) {
      const d = Math.abs(lf.e[k] - rkE[k]);
      if (d > worstShort) { worstShort = d; worstShortAt = i; }
    }
  }
  if ((rec.crossStep >= 0) === (rkCross >= 0)) agreeOutcome++;
  if (rkCross >= 0) rkCrossed++;
  if (rec.crossStep >= 0) engCrossed++;
  const dm = Math.abs(rec.maxE - rk.maxE);
  maxERows.push([i, rec.maxE, rk.maxE, dm]);
  if (i !== CHAOS_IDX && dm > maxEWorst) { maxEWorst = dm; maxEWorstAt = i; }
}
ok(`cross-method (c): pointwise eccentricity over the first ${plan.RK_CMP_STEPS.toLocaleString('en-US')} steps agrees within ${plan.RK_TOL} for the ${plan.SUBSET_RK.length - 1} bound subset particles (worst ${worstShort.toExponential(2)}, particle ${worstShortAt})`,
  worstShort < plan.RK_TOL);
// The full-run OUTCOME, which is the page's actual claim, checked by the independent method.
ok(`cross-method (c): the independent integrator agrees on the escape outcome for all ${plan.SUBSET_RK.length} subset particles (${engCrossed} escape under the engine, ${rkCrossed} under RK4, and they are the same particle)`,
  agreeOutcome === plan.SUBSET_RK.length && rkCrossed === engCrossed && engCrossed === 1);
// REPORTED, NOT ASSERTED, and here is why.  The maximum of a librating eccentricity over 4,774
// perturber orbits is not a method-independent quantity: near the resonance a difference of one
// part in 10^13 in the opening step decides which peak of the libration envelope is the largest
// one in the window.  Measured, the subset splits cleanly - particles away from the separatrix
// agree to 1e-4, particle 512 (the closest start to a_res) differs by 4.4e-2 - and asserting a
// tolerance over both would be asserting a coincidence.  The pointwise window above and the
// escape outcome are what two integrators can be held to over this length.
console.log(`${stamp()} cross-method, full-run max eccentricity (reported, not asserted): worst |engine - RK4| = ` +
  `${maxEWorst.toExponential(2)} on particle ${maxEWorstAt}; ` +
  maxERows.filter((r) => r[3] > 1e-3).map((r) => `p${r[0]} ${r[1].toFixed(4)}/${r[2].toFixed(4)}`).join(', ') +
  `. A librating maximum over 4,774 orbits is not method-independent; the outcome above is.`);

/* ------------------------------------------------------ the shipped HTML */

const html = fs.readFileSync(path.join(DIR, 'index.html'), 'utf8');
const fmtInt = (n) => n.toLocaleString('en-US');
const fmtNum = (v) => String(Number(v));
const facts = [
  ['MU', fmtNum(P.MU)], ['H', fmtNum(P.H)], ['STEPS', fmtInt(P.STEPS)],
  ['TIME', fmtInt(P.STEPS * P.H)], ['NTOT', fmtInt(plan.N_TOTAL)], ['NSWEEP', fmtInt(plan.NSWEEP)],
  ['E0', fmtNum(P.E0)], ['ETHR', fmtNum(P.ETHR)], ['D0', fmtNum(P.D0)],
  ['RENORM', fmtInt(P.RENORM)], ['REC', fmtInt(P.REC)], ['NSIG', fmtInt(P.NSIG)],
  ['ARES', fmtNum(P.ARES)], ['AMIN', fmtNum(P.AMIN)], ['AMAX', fmtNum(P.AMAX)],
  ['ACIRC', fmtNum(P.ACIRC)], ['ACHAOS', fmtNum(P.ACHAOS)],
  ['EPLANT', fmtNum(P.EPLANT)], ['NPLANT', fmtInt(P.NPLANT)],
  ['CHUNKSA', fmtInt(plan.CHUNKS_A)], ['CHUNKSB', fmtInt(plan.CHUNKS_B)],
  ['DRIFTBOUND', fmtNum(plan.DRIFT_BOUND)], ['GAMMA', fmtNum(plan.GAMMA_CHAOTIC)],
  ['RKTOL', fmtNum(plan.RK_TOL)], ['BANDIN', fmtNum(plan.BAND_IN)],
  ['BANDOUT0', fmtNum(plan.BAND_OUT0)], ['BANDOUT1', fmtNum(plan.BAND_OUT1)],
  ['TCMP', fmtInt(plan.RK_CMP_STEPS)], ['HALVET', fmtInt(plan.HALVE.S / 100)],
];
const missing = facts.filter(([k, v]) => !html.includes(`data-p="${k}">${v}<`));
ok('every fixed number the page states is present in the shipped HTML and equals the recomputed value',
  missing.length === 0, missing.map(([k, v]) => `${k}!=${v}`).join(', '));
ok('the page names its offline verifier by path',
  html.includes(`research/${SLUG}/verify-${SLUG}.mjs`));

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

{
  const bad = Uint8Array.from(B.acc.buf);
  bad[bad.length - 1] ^= 0xff;
  control('flipping one byte of decomposition B makes the byte comparator report inequality', !bytesEqual(A.acc.buf, bad));
  control('tightening the drift bound to 1e-12 makes the drift assertion fail', !(S.maxDrift < 1e-12));
  const fpA = plan.fnv64(A.acc.buf), fpBad = plan.fnv64(bad);
  control('tampering with the buffer changes the fingerprint', fpA !== fpBad);
  control('a wrong parameter value (MU as 0.002) is absent from the HTML, so the inclusion check can fail',
    !html.includes('data-p="MU">0.002<'));
  // The peak-finder is new, and a peak-finder that always answers "at the resonance" would
  // pass the location assertion on any data at all.  Feed it a profile planted at the far edge
  // of the sweep and require it to follow the data there.
  {
    const fake = Uint8Array.from(A.acc.buf);
    const dv = new DataView(fake.buffer);
    const aFake = P.AMIN + 0.9 * (P.AMAX - P.AMIN);
    for (let i = 0; i < plan.NSWEEP; i++) {
      const a = plan.aOfIndex(i);
      dv.setFloat64(i * P.RECSZ, 0.2 + 0.05 / (1 + 4e4 * (a - aFake) * (a - aFake)), true);
    }
    const F = plan.summarize(fake);
    control(`the peak-finder follows the data: a profile planted at a=${aFake.toFixed(4)} is located at a=${F.peak.a.toFixed(4)}, not at the resonance`,
      Math.abs(F.peak.a - aFake) <= (P.AMAX - P.AMIN) / plan.NBINS && Math.abs(F.peak.a - P.ARES) > 0.01);
  }
}

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

console.log('');
console.log(`TOTAL  ${nPass} passed, ${nFail} failed, ${nSkip} skipped, controls ${nCtrl - nCtrlBad}/${nCtrl} behaved`);
process.exit(nFail > 0 || nCtrlBad > 0 ? 1 : 0);
