#!/usr/bin/env node
/**
 * Verifier for the-dial-that-picks-your-instrument.
 *
 * Run:            node research/the-dial-that-picks-your-instrument/verify-the-dial-that-picks-your-instrument.mjs
 * Corruption test: node research/the-dial-that-picks-your-instrument/verify-the-dial-that-picks-your-instrument.mjs --mutate
 *
 * What this is: the page's evidence that it is not lying. It recomputes every
 * number the page displays, independently of the page's own code path, and
 * exits non-zero on any failure or on zero checks performed. It always prints
 * a line stating how many checks it ran, including on the crash path.
 *
 * Anchors, named as the run prints them:
 *   ANCHOR A (second method, no algebra): the closed-form gap vs density-
 *     weighted composite Simpson quadrature of the same quadratic loss
 *     against a Gaussian shock.
 *   ANCHOR B (second distribution, exact): the same closed form vs a two-point
 *     shock (+/- sigma with probability 1/2 each) summed by hand. Valid because
 *     the theorem is distribution-free: only the first two moments enter.
 *   ANCHOR C (published, qualitative): Weitzman (1974), Prices vs. Quantities,
 *     The Review of Economic Studies 41(4): the price instrument is preferred when
 *     the marginal benefit curve is flatter than the marginal cost curve. This
 *     is checked DIRECTIONALLY (the sign condition), not numerically: no
 *     published welfare MAGNITUDE is reproduced, because magnitudes are
 *     normalization-dependent across the literature and inventing one would be
 *     the worst thing this file could do.
 *
 * Reads the source tree only. Never reads dist/ or any build output.
 */

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

const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, '..', '..');
const SLUG = 'the-dial-that-picks-your-instrument';
const ENGINE_PATH = path.join(HERE, 'engine.mjs');
const BATTERY_PATH = path.join(HERE, 'battery.json');
const PAGE_PATH = path.join(ROOT, 'public', 'strata', SLUG, 'index.html');

// Intervals for the density-weighted quadrature anchors. 4000 keeps the
// O(h^4) composite-Simpson error orders of magnitude below the stated 1e-6
// relative tolerance even at the sweep's harshest corner (b1=3, c1=0.25,
// sigma=2), where 800 intervals leave less than a factor of two of margin.
const QUAD_INTERVALS = 4000;

let passed = 0;
let failed = 0;
const failures = [];

function chk(cond, label) {
  if (cond) { passed++; }
  else { failed++; failures.push(label); console.error('  FAIL: ' + label); }
  return !!cond;
}
function closeTo(a, b, tol) {
  return Math.abs(a - b) <= tol * Math.max(1, Math.abs(b));
}
function throwsRangeError(fn) {
  try { fn(); return false; }
  catch (e) { return e instanceof RangeError || e.name === 'RangeError'; }
}
function sha(s) { return createHash('sha256').update(s).digest('hex'); }

// ─────────────────────────────────────────────────────────────────────────
// Independent local implementations, written fresh for this file. They share
// no code with engine.mjs; agreement between the two paths is the point.
// ─────────────────────────────────────────────────────────────────────────

// Generic composite Simpson on [a, b] with n even subintervals.
function simpson(f, a, b, n) {
  const h = (b - a) / n;
  let s = f(a) + f(b);
  for (let i = 1; i < n; i++) s += f(a + i * h) * (i % 2 ? 4 : 2);
  return s * h / 3;
}
// Gaussian pdf, mean 0, sd s.
function pdf(u, s) { return Math.exp(-u * u / (2 * s * s)) / (s * Math.sqrt(2 * Math.PI)); }
// E[f(U)], U ~ N(0, s^2): composite Simpson applied to f times the Gaussian
// pdf over +/- 8s. The density and its normalization are part of the
// estimator; omitting either computes a bare integral over the line, not an
// expectation, and every downstream anchor would then be measuring the
// wrong functional.
function simpsonGauss(f, s, n) {
  if (s === 0) return f(0);
  return simpson((u) => f(u) * pdf(u, s), -8 * s, 8 * s, n);
}
// Closed forms, local versions.
const wCapLoc = (m, b1, c1) => m * m / (2 * (b1 + c1));
const gapLoc = (m, b1, c1, s) => s * s * (c1 - b1) / (2 * c1 * c1);
const wTaxLoc = (m, b1, c1, s) => wCapLoc(m, b1, c1) + gapLoc(m, b1, c1, s);
const tauLoc = (m, b1, c1) => c1 * m / (b1 + c1);
// Welfare under the optimal tax with a TWO-POINT shock: u = +s or -s, each
// with probability 1/2. Direct summation, no quadrature, no algebra reused.
function wTaxTwoPoint(m, b1, c1, s) {
  const tau = tauLoc(m, b1, c1);
  const nb = (u) => {
    const x = (tau - u) / c1;
    return m * x - 0.5 * (b1 + c1) * x * x - u * x;
  };
  return 0.5 * (nb(s) + nb(-s));
}
const recommendLoc = (b1, c1, s) => {
  const g = gapLoc(10, b1, c1, s);
  return g > 0 ? 'tax' : g < 0 ? 'cap' : 'tie';
};

async function main() {
  console.log('verify-the-dial-that-picks-your-instrument');
  console.log('reading source tree only; root = ' + ROOT);

  // ════════════════════════════════════════════════════════════════════
  // SECTION 1. Unit tests of the small pure helpers, hand-worked FIRST,
  // before anything that depends on them.
  // ════════════════════════════════════════════════════════════════════
  console.log('');
  console.log('SECTION 1: helper unit tests against hand-worked cases');

  chk(closeTo(simpson((x) => x * x, 0, 1, 1000), 1 / 3, 1e-10),
    'simpson integrates x^2 on [0,1] to 1/3');
  chk(closeTo(simpson((x) => x ** 3, 0, 2, 1000), 4, 1e-10),
    'simpson integrates x^3 on [0,2] to 4');
  chk(closeTo(simpson((x) => x ** 4, -1, 1, 1000), 0.4, 1e-10),
    'simpson integrates x^4 on [-1,1] to 2/5');

  // Tolerance statement for the Gaussian-weighted quadrature tests below.
  // Composite Simpson over +/-8 sigma with 800 intervals carries O(h^4)
  // error; on these integrands that is up to ~1e-7 absolute. Demanding 1e-9
  // here would be a claim about the method this file does not make, so the
  // tolerance is 1e-6, roughly two orders of magnitude above the worst case.
  console.log('  tolerance note: Gaussian-weighted Simpson checks use 1e-6.');
  console.log('    Reason: 800-interval composite Simpson over +/-8 sigma has');
  console.log('    O(h^4) error up to ~1e-7 absolute on these integrands; 1e-6');
  console.log('    leaves two orders of magnitude of margin.');

  chk(closeTo(simpsonGauss(() => 1, 1, 800), 1, 1e-6),
    'simpsonGauss of a constant is the constant (mass preserved)');
  // E[phi(U)] for phi the N(0,1) density is the known overlap integral
  // integral of phi^2 = 1/(2 sqrt(pi)), hand-derived, no quadrature involved.
  chk(closeTo(simpsonGauss((u) => pdf(u, 1), 1, 800), 0.5 / Math.sqrt(Math.PI), 1e-6),
    'simpsonGauss of the N(0,1) pdf equals the known overlap integral 1/(2 sqrt(pi))');
  chk(closeTo(simpsonGauss((u) => u * u, 1, 800), 1, 1e-6),
    'E[U^2] for U ~ N(0,1) is 1 under simpsonGauss');

  // Hand-worked welfare values (worked by hand from the closed forms).
  chk(wCapLoc(10, 0, 1) === 50, 'hand: wCap(10,0,1) = 50');
  chk(wCapLoc(6, 2, 2) === 4.5, 'hand: wCap(6,2,2) = 4.5');
  chk(wTaxLoc(10, 0, 1, 1) === 50.5, 'hand: wTax(10,0,1,1) = 50.5');
  chk(wTaxLoc(10, 0.5, 2, 3) === 21.6875, 'hand: wTax(10,0.5,2,3) = 21.6875');
  chk(gapLoc(10, 0.5, 2, 3) === 1.6875, 'hand: gap(10,0.5,2,3) = 1.6875');
  chk(gapLoc(10, 1, 1, 5) === 0, 'hand: equal slopes give gap 0 at any sigma');
  chk(gapLoc(10, 0, 1, 0) === 0, 'hand: zero sigma gives gap 0');
  chk(recommendLoc(0.5, 1, 1) === 'tax', 'hand: flatter MB recommends tax');
  chk(recommendLoc(2, 1, 1) === 'cap', 'hand: steeper MB recommends cap');
  chk(recommendLoc(1, 1, 1) === 'tie', 'hand: equal slopes recommend tie');
  chk(recommendLoc(0.5, 1, 0) === 'tie', 'hand: zero sigma recommends tie even with unequal slopes');
  // Two-point anchor sanity, hand-worked at one point:
  // m=10, b1=0.8, c1=1, s=1: tau=5.5556, nb(+1)=22.3222, nb(-1)=33.4334, mean 27.8778.
  chk(closeTo(wTaxTwoPoint(10, 0.8, 1, 1), 27.87777777777778, 1e-9),
    'hand: two-point welfare at (10,0.8,1,1) = 27.8778');

  console.log('  section 1 done, running total: ' + (passed + failed) +
    ' checks, ' + failed + ' failed');

  // ════════════════════════════════════════════════════════════════════
  // SECTION 2. Engine agreement: every exported function against the local
  // implementations, over a swept grid, plus domain-edge behaviour.
  // ════════════════════════════════════════════════════════════════════
  console.log('');
  console.log('SECTION 2: engine.mjs agreement and domain edges');

  const eng = await import('./engine.mjs');

  // No DOM, no side effects: a pure module must not touch browser globals.
  const engSrc = readFileSync(ENGINE_PATH, 'utf8');
  chk(!/\b(document|window|fetch|localStorage)\b/.test(engSrc),
    'engine.mjs contains no DOM or network references');

  const B1S = [0, 0.4, 0.8, 1, 1.2, 1.6, 2, 2.5, 3];
  const C1S = [0.25, 0.5, 1, 2, 3];
  const SGS = [0.5, 1, 2];
  let gridPoints = 0;

  for (const b1 of B1S) {
    for (const c1 of C1S) {
      for (const sg of SGS) {
        gridPoints++;
        chk(closeTo(eng.welfareGap({ m: 10, b1, c1, sigma: sg }), gapLoc(10, b1, c1, sg), 1e-12),
          'engine gap matches local closed form at b1=' + b1 + ' c1=' + c1 + ' s=' + sg);
        chk(closeTo(
          eng.welfareTaxNumeric({ m: 10, b1, c1, sigma: sg, intervals: QUAD_INTERVALS }),
          wTaxLoc(10, b1, c1, sg), 1e-6),
          'engine quadrature matches closed form at b1=' + b1 + ' c1=' + c1 + ' s=' + sg);
        chk(eng.recommend({ b1, c1, sigma: sg }) === recommendLoc(b1, c1, sg),
          'engine recommend matches local at b1=' + b1 + ' c1=' + c1 + ' s=' + sg);
      }
    }
  }
  console.log('  grid: ' + gridPoints + ' points x 3 checks');

  // Domain edges: exact values and rejections.
  chk(eng.optimalCap({ m: 10, b1: 0.8, c1: 1 }) === 10 / 1.8, 'edge: optimalCap(10,0.8,1) = 10/1.8');
  chk(eng.optimalTax({ m: 10, b1: 0.8, c1: 1 }) === 10 / 1.8,
    'edge: optimalTax equals c1 times optimalCap here (both 10/1.8)');
  chk(eng.welfareCap({ m: 10, b1: 0, c1: 1 }) === 50, 'edge: welfareCap(10,0,1) = 50');
  chk(eng.welfareTax({ m: 10, b1: 0, c1: 1, sigma: 1 }) === 50.5, 'edge: welfareTax(10,0,1,1) = 50.5');
  chk(eng.welfareTax({ m: 10, b1: 0.5, c1: 2, sigma: 3 }) === 21.6875,
    'edge: welfareTax(10,0.5,2,3) = 21.6875');
  chk(eng.welfareGap({ m: 10, b1: 2.5, c1: 1, sigma: 1 }) === -0.75,
    'edge: welfareGap(10,2.5,1,1) = -0.75');
  chk(eng.gapPerVariance({ b1: 3, c1: 0.25 }) === -22, 'edge: gapPerVariance(3,0.25) = -22');
  chk(eng.gapPerVariance({ b1: 1, c1: 1 }) === 0, 'edge: gapPerVariance(1,1) = 0');
  // Hand-worked from NB = m x - (b1 + c1) x^2 / 2 - u x. The shock enters PER
  // UNIT abated, so at x=5 a shock u=1 costs u*x = 5, not u: 50 - 22.5 - 5 =
  // 22.5. An earlier round of this file expected 26.5 here, which is the
  // value you get if the shock enters as a level shift (subtracting u alone);
  // that reading contradicts MC = c0 + c1 x + u, and the engine was right.
  chk(eng.nbAbatement({ m: 10, b1: 0.8, c1: 1, x: 5, u: 0 }) === 27.5,
    'edge: nbAbatement(10,0.8,1,x=5,u=0) = 27.5');
  chk(eng.nbAbatement({ m: 10, b1: 0.8, c1: 1, x: 5, u: 1 }) === 22.5,
    'edge: nbAbatement(10,0.8,1,x=5,u=1) = 22.5');
  chk(closeTo(eng.abateUnderTax({ c1: 1, tau: 10 / 1.8, u: 1 }), 10 / 1.8 - 1, 1e-12),
    'edge: abateUnderTax responds one-for-one to the shock at c1=1');
  // Tolerance 1e-6 per the section 1 tolerance note: this is a density-
  // weighted Simpson estimate at 800 intervals, not an exact quantity.
  chk(closeTo(eng.simpsonMean((u) => u * u, 1, 800), 1, 1e-6),
    'edge: simpsonMean of u^2 under N(0,1) is 1 (tolerance 1e-6, see section 1 note)');
  chk(eng.simpsonMean((u) => 7, 0, 8) === 7, 'edge: simpsonMean at sigma=0 returns f(0)');
  chk(throwsRangeError(() => eng.simpsonMean((u) => u, 1, 1)),
    'edge: simpsonMean rejects intervals = 1');
  chk(throwsRangeError(() => eng.simpsonMean((u) => u, 1, 3)),
    'edge: simpsonMean rejects odd intervals');
  chk(throwsRangeError(() => eng.welfareCap({ m: 10, b1: -1, c1: 1 })),
    'edge: welfareCap rejects negative b1');
  chk(throwsRangeError(() => eng.welfareTax({ m: 10, b1: 0.8, c1: 0 })),
    'edge: welfareTax rejects c1 = 0');
  chk(throwsRangeError(() => eng.welfareGap({ m: 10, b1: 0.8, c1: 1, sigma: -1 })),
    'edge: welfareGap rejects negative sigma');
  chk(throwsRangeError(() => eng.recommend({ b1: 0.8, c1: NaN })),
    'edge: recommend rejects NaN c1');
  chk(throwsRangeError(() => eng.mbSlopeThreshold(-1, 5, 2)),
    'edge: mbSlopeThreshold rejects negative dt');
  chk(eng.mbSlopeThreshold(2.5, 25, 20) === 2.5, 'edge: threshold slope above T is dt');
  chk(eng.mbSlopeThreshold(2.5, 20, 20) === 0, 'edge: AT the threshold the left-continuous 0 is returned');
  chk(eng.mbSlopeThreshold(2.5, 19.999, 20) === 0, 'edge: threshold slope below T is 0');
  chk(eng.mbSlopeStock() === 0, 'edge: stock structure slope is exactly 0');
  chk(closeTo(eng.pvStockFactor(0.03, 0.005), 1.03077, 1e-4),
    'edge: pvStockFactor(0.03,0.005) = 1.03077 (hand-divided)');
  chk(eng.pvStockFactor(0.5, 0) === 2, 'edge: pvStockFactor(0.5,0) = 2');
  chk(throwsRangeError(() => eng.pvStockFactor(1, 0)),
    'edge: pvStockFactor rejects a non-convergent series');

  console.log('  section 2 done, running total: ' + (passed + failed) +
    ' checks, ' + failed + ' failed');

  // ════════════════════════════════════════════════════════════════════
  // SECTION 3. The anchors.
  // ════════════════════════════════════════════════════════════════════
  console.log('');
  console.log('SECTION 3: anchors');

  // ANCHOR A: closed form vs quadrature, no algebra. Already exercised per
  // grid point in section 2; counted and reported here as a named anchor.
  console.log('  ANCHOR A (second method, no algebra): closed-form gap vs density-weighted');
  console.log('    Simpson quadrature of the same loss over a Gaussian shock, ' +
    gridPoints + ' grid points, ' + QUAD_INTERVALS + ' intervals, tolerance 1e-6 relative.');
  console.log('    (Tolerance rationale: see the section 1 tolerance note; the wider');
  console.log('    interval count keeps the O(h^4) error far below it at every corner.)');

  // ANCHOR B: two-point shock distribution, exact summation.
  console.log('  ANCHOR B (second distribution, exact): two-point shock +/- sigma,');
  console.log('    summed by hand. Valid because the theorem is distribution-free.');
  for (const b1 of B1S) {
    for (const c1 of C1S) {
      for (const sg of SGS) {
        chk(closeTo(eng.welfareTax({ m: 10, b1, c1, sigma: sg }), wTaxTwoPoint(10, b1, c1, sg), 1e-9),
          'ANCHOR B: two-point welfare matches closed form at b1=' + b1 + ' c1=' + c1 + ' s=' + sg);
      }
    }
  }

  // ANCHOR C: the published sign condition, checked directionally.
  console.log('  ANCHOR C (published, qualitative): Weitzman (1974) sign condition:');
  console.log('    price preferred iff the marginal benefit curve is flatter than');
  console.log('    the marginal cost curve. Checked directionally, not numerically.');

  // THE SIGN CHECK. This is the check that matters: sign(gap) must equal
  // sign(c1 - b1) on EVERY grid point. A gap that agreed in magnitude but
  // flipped sign anywhere would look green and be worthless.
  let signViolations = 0;
  let anchorCViolations = 0;
  for (const b1 of B1S) {
    for (const c1 of C1S) {
      for (const sg of SGS) {
        const g = eng.welfareGap({ m: 10, b1, c1, sigma: sg });
        if (Math.sign(g) !== Math.sign(c1 - b1)) signViolations++;
        const want = b1 < c1 ? 'tax' : b1 > c1 ? 'cap' : 'tie';
        if (eng.recommend({ b1, c1, sigma: sg }) !== want) anchorCViolations++;
      }
    }
  }
  chk(signViolations === 0,
    'SIGN CHECK: sign(gap) = sign(c1 - b1) on all ' + gridPoints + ' grid points (violations: ' +
    signViolations + ')');
  chk(anchorCViolations === 0,
    'ANCHOR C: recommendation matches the published flatness condition on all ' +
    gridPoints + ' grid points (violations: ' + anchorCViolations + ')');
  console.log(signViolations === 0
    ? '  SIGN CHECK PASS: 0 violations across ' + gridPoints + ' points.'
    : '  SIGN CHECK FAIL: ' + signViolations + ' violations.');

  // Intercept cancellation: the gap must not depend on m, exactly.
  for (const [b1, c1, sg] of [[0, 1, 1], [0.8, 1, 1], [2.5, 1, 1], [0.4, 3, 2]]) {
    chk(eng.welfareGap({ m: 10, b1, c1, sigma: sg }) === eng.welfareGap({ m: 987.65, b1, c1, sigma: sg }),
      'cancellation: gap identical for m=10 and m=987.65 at b1=' + b1 + ' c1=' + c1 + ' s=' + sg);
  }

  console.log('  section 3 done, running total: ' + (passed + failed) +
    ' checks, ' + failed + ' failed');

  // ════════════════════════════════════════════════════════════════════
  // SECTION 4. Page coupling: the HTML's declared constants, the battery,
  // and the printed verify command must all resolve and agree.
  // ════════════════════════════════════════════════════════════════════
  console.log('');
  console.log('SECTION 4: page, battery and command coupling');

  chk(existsSync(PAGE_PATH), 'page exists at public/strata/' + SLUG + '/index.html');
  const html = readFileSync(PAGE_PATH, 'utf8');

  chk(!html.includes('\u2014'), 'page prose contains no em dash character');

  // The page's side of the coupling contract: every model constant appears
  // as its own `var NAME = <number>;` line, which is what lets this dumb
  // matcher find it. An earlier draft packed several declarations onto
  // shared `var a = 1, b = 2;` lines, so the matcher saw only the first
  // name on each line and half the page's constants were invisible to this
  // check. The page was reformatted to the strict one-per-line form rather
  // than the matcher widened: the strict form is easier for a stranger to
  // audit, and the downstream checks that consume the extracted values were
  // never touched.
  function grabConst(name) {
    const m = html.match(new RegExp('var ' + name + '\\s*=\\s*(-?[0-9.]+)'));
    return m ? parseFloat(m[1]) : null;
  }
  const pgB1 = grabConst('B1_DEF'), pgC1 = grabConst('C1_DEF'), pgSG = grabConst('SG_DEF');
  const pgM = grabConst('M_HEAD'), pgRHO = grabConst('RHO'), pgDELTA = grabConst('DELTA');
  const pgDS = grabConst('DS'), pgDT = grabConst('DT'), pgTHRESH = grabConst('THRESH');
  chk(pgB1 !== null && pgC1 !== null && pgSG !== null && pgM !== null,
    'page declares its model defaults where the verifier can find them');
  chk(pgRHO !== null && pgDELTA !== null && pgDS !== null && pgDT !== null && pgTHRESH !== null,
    'page declares its damage-structure constants where the verifier can find them');

  if (pgB1 !== null && pgC1 !== null && pgSG !== null && pgM !== null) {
    chk(closeTo(eng.welfareGap({ m: pgM, b1: pgB1, c1: pgC1, sigma: pgSG }),
      gapLoc(pgM, pgB1, pgC1, pgSG), 1e-12),
      'page defaults: engine gap agrees with the independent closed form');
    chk(closeTo(
      eng.welfareTaxNumeric({ m: pgM, b1: pgB1, c1: pgC1, sigma: pgSG, intervals: QUAD_INTERVALS }),
      wTaxLoc(pgM, pgB1, pgC1, pgSG), 1e-6),
      'page defaults: engine quadrature agrees with the independent closed form');
    chk(eng.recommend({ b1: pgB1, c1: pgC1, sigma: pgSG }) ===
      recommendLoc(pgB1, pgC1, pgSG),
      'page defaults: engine recommendation agrees with the independent one');
  }
  if (pgRHO !== null && pgDELTA !== null) {
    chk(closeTo(eng.pvStockFactor(pgRHO, pgDELTA),
      1 / (1 - pgRHO * (1 - pgDELTA)), 1e-12),
      'page constants: present-value factor agrees with the geometric series');
  }
  if (pgM !== null && pgDT !== null && pgTHRESH !== null) {
    chk(closeTo(pgTHRESH, pgM / pgDT, 1e-12),
      'page constants: the threshold zero-benefit point equals m / dt, the straight curve the page draws');
  }
  if (pgDT !== null && pgC1 !== null) {
    // The page claims its two damage structures invert the verdict. With the
    // declared constants that claim is checkable outright: slope 0 must
    // recommend the tax, and the declared threshold slope must flip it to
    // cap, at the page's default cost slope. (This replaces an earlier check
    // that probed mbSlopeThreshold against a kinked threshold curve the page
    // no longer draws. That curve had a RISING marginal benefit of
    // abatement, an effective b1 of -dt outside the model's domain b1 >= 0,
    // and an unbounded welfare maximum, so no verdict existed for it; the
    // CAP verdict once shown beside it came from substituting b1 = +dt into
    // the gap formula, which describes a different, straight curve.)
    chk(eng.recommend({ b1: 0, c1: pgC1, sigma: 1 }) === 'tax' &&
        eng.recommend({ b1: pgDT, c1: pgC1, sigma: 1 }) === 'cap',
      'page constants: the declared slopes straddle the default cost slope, so the inversion the page claims is real');
  }

  // Every verify command the page prints must resolve to a real file.
  const cmdRe = /research\/[A-Za-z0-9\-]+\/verify[A-Za-z0-9\-\.]*\.mjs/g;
  const cmds = [...new Set(html.match(cmdRe) || [])];
  chk(cmds.length > 0, 'page prints at least one runnable verify command');
  for (const c of cmds) {
    chk(existsSync(path.join(ROOT, c)), 'printed command resolves: ' + c);
  }

  // The battery must exist, parse, cover every exported function, and only
  // name functions the engine actually exports.
  chk(existsSync(BATTERY_PATH), 'battery.json exists beside the engine');
  const battery = JSON.parse(readFileSync(BATTERY_PATH, 'utf8'));
  chk(Array.isArray(battery.calls) && battery.calls.length > 0,
    'battery.json has a non-empty calls array');
  const exportFns = Object.entries(eng).filter(([, v]) => typeof v === 'function').map(([k]) => k);
  for (const fn of exportFns) {
    chk(battery.calls.some((c) => c.fn === fn),
      'battery covers exported function: ' + fn);
  }
  for (const call of battery.calls) {
    chk(typeof eng[call.fn] === 'function',
      'battery call targets a real export: ' + call.fn);
    chk(typeof call.note === 'string' && call.note.length > 0,
      'battery call carries an explanatory note: ' + call.fn);
  }

  console.log('  section 4 done, running total: ' + (passed + failed) +
    ' checks, ' + failed + ' failed');

  // ════════════════════════════════════════════════════════════════════
  // SECTION 5. --mutate: corrupt the engine, CONFIRM the corruption landed,
  // confirm the checks catch it, restore, confirm the original is untouched.
  // ════════════════════════════════════════════════════════════════════
  if (process.argv.includes('--mutate')) {
    console.log('');
    console.log('SECTION 5: mutation test (--mutate)');

    const original = readFileSync(ENGINE_PATH, 'utf8');
    const beforeHash = sha(original);

    const patterns = [
      ['(c1 - b1)', '(b1 - c1)'],
      ['2 * c1 * c1', '2 * c1'],
      ['m / (b1 + c1)', 'm / (b1 + c1 + 1)']
    ];
    let mutated = null;
    for (const [from, to] of patterns) {
      if (original.includes(from)) { mutated = original.split(from).join(to); break; }
    }
    chk(mutated !== null && mutated !== original, 'mutation changed the engine bytes');

    const tmp = path.join(os.tmpdir(), 'engine-mutated-' + Date.now() + '.mjs');
    let detected = false;
    try {
      writeFileSync(tmp, mutated);
      const bad = await import(pathToFileURL(tmp).href);
      // Run anchor-A-style comparisons against the corrupted engine.
      for (const [b1, c1, sg] of [[0, 1, 1], [0.8, 1, 1], [2, 1, 1], [2.5, 0.5, 2]]) {
        if (!closeTo(bad.welfareGap({ m: 10, b1, c1, sigma: sg }), gapLoc(10, b1, c1, sg), 1e-9)) {
          detected = true;
        }
        if (!closeTo(
          bad.welfareTaxNumeric({ m: 10, b1, c1, sigma: sg, intervals: QUAD_INTERVALS }),
          wTaxLoc(10, b1, c1, sg), 1e-6)) {
          detected = true;
        }
      }
    } catch {
      detected = true; // a corrupted engine that crashes is also caught
    } finally {
      if (existsSync(tmp)) unlinkSync(tmp);
    }
    chk(detected, 'corrupted engine is DETECTED by the checks (checks fail or crash)');
    chk(!existsSync(tmp), 'temporary mutated engine removed after the test');
    chk(sha(readFileSync(ENGINE_PATH, 'utf8')) === beforeHash,
      'original engine.mjs untouched by the mutation test');

    console.log('  section 5 done, running total: ' + (passed + failed) +
      ' checks, ' + failed + ' failed');
  }

  // ════════════════════════════════════════════════════════════════════
  // VERDICT
  // ════════════════════════════════════════════════════════════════════
  const total = passed + failed;
  console.log('');
  console.log('TOTAL CHECKS: ' + total + '  (passed ' + passed + ', failed ' + failed + ')');
  if (failures.length > 0) {
    console.error('Failed checks:');
    for (const f of failures) console.error('  - ' + f);
  }
  if (total === 0) {
    console.error('ZERO CHECKS PERFORMED: this run proves nothing, exiting non-zero.');
    process.exit(1);
  }
  if (failed > 0) {
    console.error('RESULT: FAIL');
    process.exit(1);
  }
  console.log('RESULT: ALL CHECKS PASS');
  process.exit(0);
}

main().catch((e) => {
  // Even a crash must leave behind the count of checks actually performed.
  console.error('VERIFIER CRASHED: ' + (e && e.stack ? e.stack : e));
  console.error('TOTAL CHECKS before the crash: ' + (passed + failed) +
    '  (passed ' + passed + ', failed ' + failed + ')');
  process.exit(1);
});
