#!/usr/bin/env node
/**
 * verify-one-minute-of-latitude.mjs — the evidence for the page.
 *
 * What this program is: an independent re-derivation of every number the page
 * displays, plus structural proof that the page and this verifier are talking
 * about the same Earth. It reads the SOURCE TREE ONLY (the page's index.html
 * and engine.mjs); it never reads a build directory, so it cannot silently
 * verify a page nobody shipped.
 *
 * Order of operations, deliberately:
 *   1. unit tests of the small pure helpers against hand-worked cases FIRST,
 *      because a wrong primitive under a correct algorithm is the failure that
 *      ships behind a green check;
 *   2. anchors: two independent computations of the same quantity (series vs
 *      Simpson integration), an analytic anchor that needs neither (a sphere
 *      must give quadrant = pi*a/2 exactly), and a published-value anchor;
 *   3. coupling: the page's hard-coded ellipsoid parameters and definitions
 *      are compared against this file's own independent transcription;
 *   4. the reconciliation battery is smoke-run, including its error contracts.
 *
 * Discipline enforced here (each one earned by a real past failure):
 *   - every check RETURNS a boolean (or {ok, detail}) that the harness inspects;
 *     a check that throws, or returns undefined, is scored as a FAILURE;
 *   - the total check count is printed; a run performing zero checks exits
 *     non-zero, so a silent no-op can never look like a pass;
 *   - --mutate corrupts engine.mjs ON DISK, asserts the bytes actually changed,
 *     re-imports it fresh, requires the core checks to FAIL, restores the
 *     original bytes, and asserts the restoration. Under --mutate the process
 *     exits NON-ZERO if the checks still pass, because that would mean the
 *     verifier is blind.
 *
 * Usage:
 *   node verify-one-minute-of-latitude.mjs            # full run
 *   node verify-one-minute-of-latitude.mjs --mutate   # corruption drill
 */

import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';

const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, '..', '..');
const ENGINE_PATH = path.join(HERE, 'engine.mjs');
const PAGE_PATH = path.join(ROOT, 'public', 'strata', 'one-minute-of-latitude', 'index.html');
const BATTERY_PATH = path.join(HERE, 'battery.json');

const MUTATE = process.argv.includes('--mutate');

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

/** Run one check. The predicate must RETURN truth (boolean or {ok,detail}).
 *  A throw or an undefined return is recorded as a failure, never as a pass. */
function check(name, fn) {
  let ok = false;
  let detail = '';
  try {
    const r = fn();
    if (r === undefined) {
      ok = false;
      detail = 'returned undefined; counted as FAIL';
    } else if (typeof r === 'object' && r !== null && 'ok' in r) {
      ok = Boolean(r.ok);
      detail = r.detail || '';
    } else {
      ok = Boolean(r);
    }
  } catch (err) {
    ok = false;
    detail = 'threw: ' + err.message;
  }
  if (ok) {
    passed += 1;
    console.log('  pass  ' + name + (detail ? '  [' + detail + ']' : ''));
  } else {
    failed += 1;
    failureNames.push(name);
    console.log('  FAIL  ' + name + (detail ? '  [' + detail + ']' : ''));
  }
}

const near = (a, b, tol) => Math.abs(a - b) <= tol;
const nearRel = (a, b, tol) => Math.abs(a - b) <= tol * Math.max(1, Math.abs(b));
const throwsRangeError = (fn) => {
  try { fn(); return false; } catch (err) { return err instanceof RangeError; }
};

function loadEngine(tag) {
  return import(pathToFileURL(ENGINE_PATH).href + '?run=' + tag);
}

/* ─────────────────────────────────────────────────────────────────────────── */

async function unitTests(E) {
  console.log('[1] unit tests of pure helpers against hand-worked cases');
  const ta = 4, te2 = 0.5;                      // toy ellipsoid: a = 4, e^2 = 1/2

  check('eccentricitySquared(0.25) === 0.4375 exactly (binary-exact rationals)',
    () => E.eccentricitySquared(0.25) === 0.4375);
  check('eccentricitySquared(0) === 0 (sphere)',
    () => E.eccentricitySquared(0) === 0);

  check('logImpliedUnit(15 m, 30 s) === 1800 m exactly (hand case)',
    () => E.logImpliedUnit(15, 30) === 1800);
  check('spacingForUnit(1852, 28) === 51856/3600 (hand case)',
    () => near(E.spacingForUnit(1852, 28), 51856 / 3600, 1e-12));

  check('meridianRadius(toy, 0°) === 2 exactly (a(1-e²) with a=4, e²=1/2)',
    () => E.meridianRadius(ta, te2, 0) === 2);
  check('meridianRadius(toy, 90°) === 4/sqrt(0.5) = 5.656854249492381 (hand case)',
    () => near(E.meridianRadius(ta, te2, 90), 4 / Math.sqrt(0.5), 1e-12));
  check('meridianRadius(toy, 45°) === 2/0.75^1.5 = 3.0792014356780036 (hand case)',
    () => near(E.meridianRadius(ta, te2, 45), 2 / Math.pow(0.75, 1.5), 1e-12));

  /* HAND CASE, CORRECTED AT THE EXPECTATION: an earlier draft claimed the
     centred-arc minuteLength(toy, 0) equals pi/5400 to 1e-12. That expectation
     was wrong twice over, and the engine was right. First, pi/5400 is the
     LOCAL minute (radius times angle), which the centred finite arc exceeds by
     a real O(delta^3) curvature term of about 3e-12 m even on this toy.
     Second, and decisively, at e^2 = 0.5 the four-term series carries
     neglected e^8-and-higher terms worth a couple of micro-metres over the
     minute span, so no series-based hand case tighter than that is honest at
     this eccentricity. The exact statement the toy supports is asserted first;
     the centred-arc check keeps its coverage of the span-and-clamp plumbing
     with a widened tolerance printed beside its reason. */
  check('LOCAL minute (toy, 0°) === 2 x pi/10800 = pi/5400 (radius times angle, exact hand case)',
    () => near(E.meridianRadius(ta, te2, 0) * E.MINUTE_RAD, Math.PI / 5400, 1e-15));
  check('CENTRED-ARC minute (toy, 0°) within 1e-5 m of pi/5400 [tolerance widened from 1e-12 and printed: at e² = 0.5 the neglected e⁸ series terms are worth ~2e-6 m over the minute span, so the gap is truncation plus real curvature, not engine error]',
    () => {
      const got = E.minuteLength(ta, te2, 0);
      return { ok: Math.abs(got - Math.PI / 5400) < 1e-5,
               detail: 'centred arc ' + got.toFixed(9) + ' m vs pi/5400 = ' +
                       (Math.PI / 5400).toFixed(9) + ' m' };
    });

  const w = E.ELLIPSOIDS.wgs84;
  const e2w = E.eccentricitySquared(1 / w.rf);
  check('minuteLength is even in latitude (37.5° vs -37.5°)',
    () => near(E.minuteLength(w.a, e2w, 37.5), E.minuteLength(w.a, e2w, -37.5), 1e-9));
  check('minuteLength strictly increases with |latitude| (10 < 50 < 89 degrees)',
    () => E.minuteLength(w.a, e2w, 10) < E.minuteLength(w.a, e2w, 50) &&
          E.minuteLength(w.a, e2w, 50) < E.minuteLength(w.a, e2w, 89));

  check('meridianArc(wgs84, 0 rad) === 0 exactly',
    () => E.meridianArc(w.a, e2w, 0) === 0);
  check('meridianArc is odd in phi (+/- pi/2 give exact negatives)',
    () => E.meridianArc(w.a, e2w, -Math.PI / 2) === -E.meridianArc(w.a, e2w, Math.PI / 2));

  check('ANALYTIC ANCHOR: sphere quadrant by integration === pi*a/2 (needs neither series nor published value)',
    () => ({ ok: nearRel(E.quadrantNumeric(6378137, 0), Math.PI * 6378137 / 2, 1e-12),
             detail: 'computed ' + E.quadrantNumeric(6378137, 0).toFixed(6) + ' m' }));
  check('ANALYTIC ANCHOR: sphere quadrant by series === pi*a/2 (series degenerates exactly)',
    () => nearRel(E.quadrantSeries(6378137, 0), Math.PI * 6378137 / 2, 1e-12));

  check('edges: minuteLength beyond 90° throws RangeError',
    () => throwsRangeError(() => E.minuteLength(6378137, 0.0067, 90.5)));
  check('edges: meridianArc beyond pi/2 radians throws RangeError',
    () => throwsRangeError(() => E.meridianArc(6378137, 0.0067, 3.5)));
  check('edges: logImpliedUnit with a zero-second glass throws RangeError',
    () => throwsRangeError(() => E.logImpliedUnit(1, 0)));
  check('edges: logImpliedUnit with negative rope throws RangeError',
    () => throwsRangeError(() => E.logImpliedUnit(-1, 28)));
  check('edges: spacingForUnit with a zero-second glass throws RangeError',
    () => throwsRangeError(() => E.spacingForUnit(100, 0)));

  check('crossingLatitudes above the ceiling returns null (no crossing exists)',
    () => E.crossingLatitudes(w.a, e2w, 1900) === null);
  check('crossingLatitudes is symmetric (positive + negative === 0)',
    () => {
      const c = E.crossingLatitudes(w.a, e2w, 1852);
      return c !== null && Math.abs(c.positive + c.negative) < 1e-12;
    });
}

/* ─────────────────────────────────────────────────────────────────────────── */

async function anchors(E) {
  console.log('');
  console.log('[2] anchors: two independent computations, then the published value');
  console.log('      anchor A (analytic): a sphere of radius a must give quadrant = pi*a/2,');
  console.log('      exactly, by geometry alone. Covered in the unit tests above and here:');
  console.log('      anchor B (published): the WGS 84 meridian quadrant is about');
  console.log('      10,001,965.7 m in the geodesy literature; this verifier carries it');
  console.log('      ROUNDED to 10,001,966 m with a 1 m band. Precise printed provenance is');
  console.log('      flagged SOURCE NEEDED in research/one-minute-of-latitude/README.md');
  console.log('      rather than invented here.');
  console.log('      note on crossings: the centred-arc minute and the local-limit minute are');
  console.log('      related but DISTINCT quantities (a finite one-minute span versus its');
  console.log('      limit). An earlier draft described the two crossing routes as anchors');
  console.log('      for each other; they are not. Each crossing is now cross-checked like');
  console.log('      for like, and the gap between the two definitions is measured and');
  console.log('      printed, never matched and never rounded away.');

  const ids = Object.keys(E.ELLIPSOIDS);
  let worstMinute = 0;
  for (const id of ids) {
    const el = E.ELLIPSOIDS[id];
    const e2 = E.eccentricitySquared(1 / el.rf);
    for (let la = 0; la <= 90; la += 5) {
      const d = Math.abs(E.minuteLength(el.a, e2, la) - E.minuteLengthNumeric(el.a, e2, la));
      if (d > worstMinute) worstMinute = d;
    }
  }
  check('INDEPENDENT METHOD 1: series vs Simpson minute length, all five ellipsoids, 0-90° sweep, within 1 mm',
    () => ({ ok: worstMinute < 1e-3, detail: 'worst gap ' + worstMinute.toExponential(2) + ' m' }));

  let worstQuad = 0;
  for (const id of ids) {
    const el = E.ELLIPSOIDS[id];
    const e2 = E.eccentricitySquared(1 / el.rf);
    const d = Math.abs(E.quadrantSeries(el.a, e2) - E.quadrantNumeric(el.a, e2));
    if (d > worstQuad) worstQuad = d;
  }
  check('INDEPENDENT METHOD 2: series vs Simpson quadrant, all five ellipsoids, within 1 mm',
    () => ({ ok: worstQuad < 1e-3, detail: 'worst gap ' + worstQuad.toExponential(2) + ' m' }));

  const w = E.ELLIPSOIDS.wgs84;
  const e2w = E.eccentricitySquared(1 / w.rf);
  const q = E.quadrantNumeric(w.a, e2w, 16384);
  check('PUBLISHED ANCHOR: WGS 84 quadrant (integration) vs 10,001,966 m (rounded, see above) within 1 m',
    () => ({ ok: near(q, 10001966, 1), detail: 'computed ' + q.toFixed(3) + ' m' }));
  check('PUBLISHED ANCHOR: WGS 84 quadrant (series) vs 10,001,966 m within 1 m',
    () => near(E.quadrantSeries(w.a, e2w), 10001966, 1));

  /* Crossing latitude, done honestly. Two RELATED BUT DISTINCT quantities live
     here, and an earlier draft described their two routes as anchors for each
     other, which they are not:
       - the CENTRED-ARC minute: the finite arc of the one-minute interval
         centred on the latitude. This is what the page plots and bisects.
       - the LOCAL-LIMIT minute: meridianRadius(latitude) x pi/10800, the limit
         of that arc as the span shrinks to zero.
     They differ by micrometres of arc wherever the meridian curves, so their
     crossings of the fixed mile sit apart by a few hundred-thousandths of a
     degree. Each root therefore gets a LIKE-FOR-LIKE cross-method check, and
     the gap between the two definitions is then measured and printed. */
  const D = Math.PI / 10800;

  // Like-for-like, method 1: the exported bisection on series arcs.
  const seriesRoot = E.crossingLatitudes(w.a, e2w, 1852).positive;

  // Like-for-like, method 2: bisection on the Simpson twin of the SAME
  // centred-arc quantity. Shares no code with method 1 beyond the module
  // boundary; the two can only agree if the series and the integrator agree.
  let loN = 0, hiN = 90;
  for (let i = 0; i < 120; i++) {
    const mid = (loN + hiN) / 2;
    if (E.minuteLengthNumeric(w.a, e2w, mid, 512) > 1852) hiN = mid; else loN = mid;
  }
  const simpsonRoot = (loN + hiN) / 2;
  check('CROSS-CHECK, one quantity two methods: centred-arc crossing, series vs Simpson, within 1e-5 deg [tolerance printed: the neglected e⁸ series terms bend the minute by ~0.3 µm near the crossing, worth ~1e-6 deg of root; both bisections themselves converge past 1e-10 deg]',
    () => ({ ok: near(seriesRoot, simpsonRoot, 1e-5),
             detail: seriesRoot.toFixed(9) + ' vs ' + simpsonRoot.toFixed(9) + ' deg' }));

  // The OTHER quantity, computed for what it is: the local-limit crossing.
  // Not an anchor for anything; a neighbouring definition whose separation
  // from the centred-arc crossing is a measured fact.
  let loR = 0, hiR = 90;
  for (let i = 0; i < 120; i++) {
    const mid = (loR + hiR) / 2;
    if (E.meridianRadius(w.a, e2w, mid) * D > 1852) hiR = mid; else loR = mid;
  }
  const radiusRoot = (loR + hiR) / 2;

  check('DIFFERENT QUANTITIES, MEASURED NOT MATCHED: local-limit crossing vs centred-arc crossing, gap under 1e-3 deg, value printed',
    () => {
      const gap = Math.abs(radiusRoot - seriesRoot);
      return { ok: gap < 1e-3,
               detail: 'centred-arc root ' + seriesRoot.toFixed(6) + ' deg; local-limit root ' +
                       radiusRoot.toFixed(6) + ' deg; gap ' + gap.toExponential(2) +
                       ' deg. Different definitions of the minute, not a mismatch.' };
    });

  let allContain = true;
  const parts = [];
  for (const id of ids) {
    const el = E.ELLIPSOIDS[id];
    const e2 = E.eccentricitySquared(1 / el.rf);
    const r = E.minuteRange(el.a, e2);
    const inside = r.min.length < 1852 && 1852 < r.max.length;
    parts.push(id + ':' + (inside ? 'in' : 'OUT'));
    if (!inside) allContain = false;
  }
  check('DEFINITIONAL COHERENCE: 1852 m lies strictly inside [min minute, max minute] for all five ellipsoids',
    () => ({ ok: allContain, detail: parts.join(' ') }));

  const rw = E.minuteRange(w.a, e2w);
  const qm = E.quadrantSeries(w.a, e2w) / 5400;
  check('METRE COHERENCE: quadrant/5400 (the all-latitudes mean minute) lies inside [min, max]',
    () => ({ ok: qm > rw.min.length && qm < rw.max.length,
             detail: 'mean minute ' + qm.toFixed(3) + ' m' }));
}

/* ─────────────────────────────────────────────────────────────────────────── */

async function pageCoupling(E) {
  console.log('');
  console.log('[3] coupling: the page must be describing the same Earth this file computes');

  const src = fs.readFileSync(PAGE_PATH, 'utf8');
  check('page exists at public/strata/one-minute-of-latitude/index.html and is non-trivial',
    () => src.length > 10000);

  const KNOWN = {
    wgs84:      [6378137, 298.257223563],
    grs80:      [6378137, 298.257222101],
    airy1830:   [6377563.396, 299.3249646],
    bessel1841: [6377397.155, 299.1528128],
    clarke1880: [6378249.145, 293.465]
  };

  /* Independent transcription check: the engine's parameters must equal this
     file's own typed literals, so a typo in either place is caught. */
  let transOk = true;
  const transBad = [];
  for (const id of Object.keys(KNOWN)) {
    const el = E.ELLIPSOIDS[id];
    if (!el || el.a !== KNOWN[id][0] || el.rf !== KNOWN[id][1]) {
      transOk = false;
      transBad.push(id);
    }
  }
  check("engine ellipsoid parameters match this file's independent transcription (EPSG-registered values)",
    () => ({ ok: transOk, detail: transBad.length ? 'mismatch: ' + transBad.join(',') : 'all five match' }));

  /* Page coupling: parse the page's ELLIPSOIDS literals and compare. */
  const entryRe = /id:'([a-z0-9]+)', name:'[^']*', a:([0-9.]+), rf:([0-9.]+)/g;
  const pageEntries = {};
  let m2;
  while ((m2 = entryRe.exec(src)) !== null) {
    pageEntries[m2[1]] = [parseFloat(m2[2]), parseFloat(m2[3])];
  }
  const missing = Object.keys(KNOWN).filter((id) => !pageEntries[id]);
  const wrong = Object.keys(pageEntries).filter((id) =>
    !KNOWN[id] ||
    pageEntries[id][0] !== KNOWN[id][0] ||
    pageEntries[id][1] !== KNOWN[id][1]);
  check('page hard-codes the same five ellipsoids with the same defining parameters',
    () => ({ ok: missing.length === 0 && wrong.length === 0,
             detail: (missing.length ? 'missing ' + missing.join(',') + '; ' : '') +
                     (wrong.length ? 'wrong ' + wrong.join(',') : (Object.keys(pageEntries).length + ' entries parsed')) }));

  check('page declares the fixed mile as exactly 1852 (var NM = 1852;)',
    () => /\bvar NM = 1852;/.test(src));
  check('page declares the international foot as exactly 0.3048 (var FT = 0.3048;)',
    () => /\bvar FT = 0\.3048;/.test(src));

  /* House rule (research README, Editor notes): shareable description surfaces
     ship as __DEK__ and the editor fills them at publish time. The source tree
     therefore cannot promise zero placeholders, and an earlier draft of this
     check wrongly demanded exactly that. What the tree CAN promise, and what
     is enforced here, is SCOPE: every __DEK__ must sit on a description
     surface (a meta tag named or propertied "description", or the JSON-LD
     description field), so a placeholder can never leak onto a title, a
     canonical URL or a heading. The count is printed so the editor can see
     how many surfaces remain to fill; when all are filled the check still
     holds, vacuously and visibly. */
  const dekTotal = (src.match(/__DEK__/g) || []).length;
  let dekScoped = (src.match(/"description":"__DEK__"/g) || []).length;
  for (const tag of (src.match(/<meta\b[^>]*>/g) || [])) {
    if (tag.indexOf('__DEK__') === -1) continue;
    const nm = /(?:name|property)="([^"]*)"/.exec(tag);
    if (nm && /description/i.test(nm[1]) && tag.includes('content="__DEK__"')) dekScoped += 1;
  }
  check('__DEK__ placeholders (editor fills at publish) appear only on description surfaces: found ' + dekTotal,
    () => ({ ok: dekScoped === dekTotal,
             detail: dekTotal + ' placeholder(s); ' + dekScoped + ' on description surfaces' }));

  const EM = String.fromCharCode(8212); // em dash
  check('no em dash anywhere in the page (house law; the character is the loudest tell)',
    () => !src.includes(EM));

  check('marker-wrapped way-out footer present (injectors anchor on it)',
    () => src.includes('<!--aw-wayout:start-->') && src.includes('<!--aw-wayout:end-->'));

  check('canonical URL points at this stratum',
    () => src.includes('https://artwaste.land/strata/one-minute-of-latitude/'));

  const bodies = (src.match(/<\/body>/g) || []).length;
  const htmls = (src.match(/<\/html>/g) || []).length;
  check('closing tags occur exactly once each and the file ends with the closing html tag',
    () => bodies === 1 && htmls === 1 && src.replace(/\s+$/, '').endsWith('</html>'));

  check('page prints the verify command and it resolves to this file',
    () => src.includes('research/one-minute-of-latitude/verify-one-minute-of-latitude.mjs') &&
          fs.existsSync(ENGINE_PATH));
}

/* ─────────────────────────────────────────────────────────────────────────── */

async function batteryChecks(E) {
  console.log('');
  console.log('[4] reconciliation battery: parse, coverage, and error-contract smoke run');

  const raw = fs.readFileSync(BATTERY_PATH, 'utf8');
  let bat = null;
  let parseOk = true;
  try { bat = JSON.parse(raw); } catch (err) { parseOk = false; }
  check('battery.json parses and holds a non-empty calls array',
    () => parseOk && bat && Array.isArray(bat.calls) && bat.calls.length > 0);

  const fns = Object.keys(E).filter((k) => typeof E[k] === 'function');
  const called = new Set((bat && bat.calls ? bat.calls : []).map((c) => c.fn));
  const uncovered = fns.filter((f) => !called.has(f));
  check('battery covers every exported FUNCTION of engine.mjs (' + fns.length + ' exports)',
    () => ({ ok: uncovered.length === 0, detail: uncovered.length ? 'uncovered: ' + uncovered.join(',') : 'all covered' }));

  check('every battery call names a function that exists on the engine',
    () => bat.calls.every((c) => typeof E[c.fn] === 'function'));

  check('battery breadth: at least 40 calls, so edge cases survive editing',
    () => bat.calls.length >= 40);

  /* Smoke run: calls whose note promises a RangeError must throw exactly that;
     all other calls must return without throwing. This reconciles the error
     contracts a second implementer must match, without interpreting prose
     beyond the single marker word. */
  const bad = [];
  for (const c of bat.calls) {
    const wantsThrow = /RangeError/.test(c.note || '');
    let threw = null;
    try { E[c.fn](...c.args); } catch (err) { threw = err; }
    if (wantsThrow && !(threw instanceof RangeError)) {
      bad.push(c.fn + '(' + c.args.map((x) => String(x)).join(', ') + '): expected RangeError, got ' +
        (threw ? threw.name : 'a return value'));
    }
    if (!wantsThrow && threw) {
      bad.push(c.fn + '(' + c.args.map((x) => String(x)).join(', ') + '): threw ' + threw.message);
    }
  }
  check('battery smoke-run: every error contract honoured, every plain call returns',
    () => ({ ok: bad.length === 0, detail: bad.slice(0, 3).join(' | ') }));
}

/* ─────────────────────────────────────────────────────────────────────────── */

async function mutateMode() {
  console.log('MUTATION MODE: corrupt engine.mjs on disk, prove the checks notice, restore.');

  const FIND = '- 3 * e4 / 64';
  const REPLACE = '- 3 * e4 / 32';   // doubles a series coefficient: quadrant shifts ~21 m

  const orig = fs.readFileSync(ENGINE_PATH);
  const origStr = orig.toString('utf8');
  if (!origStr.includes(FIND)) {
    console.log('FAIL: mutation target not found in engine.mjs; refusing to proceed blindly.');
    process.exit(2);
  }

  fs.writeFileSync(ENGINE_PATH + '.bak', orig);
  let changed = false;
  let tripped = 0;
  let ran = 0;
  let restored = false;

  try {
    fs.writeFileSync(ENGINE_PATH, origStr.replace(FIND, REPLACE));
    changed = !Buffer.from(fs.readFileSync(ENGINE_PATH)).equals(orig);
    console.log('  corruption applied, bytes actually changed: ' + changed);

    const M = await loadEngine('mut' + Date.now());
    const w = M.ELLIPSOIDS.wgs84;
    const e2 = M.eccentricitySquared(1 / w.rf);

    ran++;
    let worst = 0;
    for (let la = 0; la <= 90; la += 5) {
      worst = Math.max(worst,
        Math.abs(M.minuteLength(w.a, e2, la) - M.minuteLengthNumeric(w.a, e2, la)));
    }
    if (worst >= 1e-3) tripped++;

    ran++;
    if (Math.abs(M.quadrantNumeric(w.a, e2, 16384) - 10001966) > 1) tripped++;

    /* Like-for-like probe: the corrupted series coefficients move the
       series-based crossing but not the Simpson-based one, so the two roots
       of the SAME centred-arc quantity fly apart and the drill trips. */
    ran++;
    let lo = 0, hi = 90;
    for (let i = 0; i < 200; i++) {
      const mid = (lo + hi) / 2;
      if (M.minuteLengthNumeric(w.a, e2, mid, 512) > 1852) hi = mid; else lo = mid;
    }
    const simpsonRoot = (lo + hi) / 2;
    const sr = M.crossingLatitudes(w.a, e2, 1852);
    if (!sr || Math.abs(sr.positive - simpsonRoot) > 1e-5) tripped++;
  } finally {
    fs.writeFileSync(ENGINE_PATH, orig);
    restored = Buffer.from(fs.readFileSync(ENGINE_PATH)).equals(orig);
    fs.rmSync(ENGINE_PATH + '.bak', { force: true });
  }

  console.log('  original bytes restored: ' + restored);
  console.log('  core checks tripped by corruption: ' + tripped + ' of ' + ran);
  if (changed && restored && tripped > 0) {
    console.log('MUTATION DRILL PASSED: the verifier is not blind.');
    process.exit(0);
  }
  console.log('MUTATION DRILL FAILED: ' +
    (!changed ? 'corruption did not land; ' : '') +
    (!restored ? 'restore failed; ' : '') +
    (tripped === 0 ? 'checks still passed under corruption, the verifier is blind.' : ''));
  process.exit(1);
}

/* ─────────────────────────────────────────────────────────────────────────── */

async function main() {
  const E = await loadEngine('main' + Date.now());

  await unitTests(E);
  await anchors(E);
  await pageCoupling(E);
  await batteryChecks(E);

  console.log('');
  console.log('CHECKS RUN: ' + (passed + failed) + '   PASSED: ' + passed + '   FAILED: ' + failed);
  if (failureNames.length) {
    console.log('failures:');
    for (const n of failureNames) console.log('  - ' + n);
  }
  if (passed + failed === 0) {
    console.log('zero checks ran: refusing to report success.');
    process.exit(2);
  }
  process.exit(failed === 0 ? 0 : 1);
}

if (MUTATE) {
  await mutateMode();
} else {
  await main();
}
