#!/usr/bin/env node
/*
  Verifier for "The Difference Divisible by Nine".

  What this file is: the page's evidence to a stranger that the page is not lying.
  It recomputes, from scratch and by methods written DIFFERENTLY from the page's own
  code path, every number the page displays, and it exits non-zero if any of them is
  wrong. It reads the source tree only (public/ and research/); it never reads a
  build directory.

  Anchors, stated plainly in the output:
    ANCHOR 1: the transposition delta computed two ways, direct subtraction of the
              two rendered numbers versus the closed form 9*(a-b)*10^i*R_m, compared
              on EVERY ordered pair of distinct digits and every position pair in
              numbers of 2, 3, 4 and 5 digits. Both methods are implemented in this
              file; no external publication is claimed, and none is invented.
    ANCHOR 2: the reachable-by-transposition set for each length, generated
              analytically by engine.mjs versus brute-force enumeration written
              locally in this file.
    ANCHOR 3 (the converse): multiples of nine with NO transposition behind them,
              counted two independent ways, asserted non-zero.
    Hand-worked literals (-6930 signed for the falling 48217-to-41287 swap, 6930 in
    magnitude on the rising direction, 29997, 433953, 150000, and others) are checked
    against both methods; they were worked by hand before any code ran. The 48217 to
    41287 literal originally claimed +6930, plain wrong arithmetic: 41287 is the
    smaller number. Corrected here to the signed value; the page's live check row
    agreed all along.

  Structure: unit tests of the small pure helpers against hand-worked cases come
  FIRST, before anything that depends on them. Every assertion RETURNS a boolean
  that the harness inspects; nothing asserts by throwing alone. The check count is
  printed. A run that performs zero checks exits non-zero.

  --mutate: deliberately corrupts a copy of the page under test, CONFIRMS the
  corruption landed (asserts the bytes actually changed), re-runs the page-derived
  checks against the corrupted copy, requires at least one of them to FAIL, deletes
  the copy, and confirms the original file on disk is byte-identical to what was
  read. Under --mutate, if the checks still pass, the process exits NON-ZERO.
*/

import { readFileSync, mkdtempSync, writeFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import * as eng from './engine.mjs';

const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, '..', '..');
const PAGE = path.join(ROOT, 'public', 'strata',
  'the-difference-divisible-by-nine', 'index.html');

const LF = String.fromCharCode(10);

// ── harness: every check returns a boolean the harness inspects ──────────────
let passed = 0, failed = 0;
const failureLog = [];
function check(name, fn) {
  let ok = false, threw = null;
  try { ok = (fn() === true); } catch (e) { threw = e; }
  if (ok) { passed++; process.stdout.write('  ok   ' + name + LF); }
  else {
    failed++;
    failureLog.push({ name, threw });
    process.stdout.write('  FAIL ' + name + (threw ? ' (threw: ' + threw.message + ')' : '') + LF);
  }
}
function eq(a, b) { return JSON.stringify(a) === JSON.stringify(b); }

// ── local independent helpers, deliberately NOT calling engine.mjs ───────────
function locSwapString(s, i, j) {
  const a = s.split('');
  const t = a[i]; a[i] = a[j]; a[j] = t;
  return a.join('');
}
function locSwapValue(n, i, j) {           // i, j are MSD indices
  const s = String(Math.abs(n));
  return Number(locSwapString(s, i, j));
}
function locRepunit(m) {
  let r = 0;
  for (let k = 0; k < m; k++) r = r * 10 + 1;
  return r;
}
// Same convention as engine.closedFormDelta: a is the digit at the LOWER weight i,
// b is the digit at the HIGHER weight j, and the result is (a-b)*(10^j - 10^i),
// which equals (value after the swap) minus (value before).
function locClosed(a, b, i, j) { return (a - b) * (10 ** j - 10 ** i); }
function locBruteReachable(L) {
  const set = new Set();
  for (let n = 10 ** (L - 1); n < 10 ** L; n++) {
    const s = String(n);
    for (let x = 0; x < L; x++)
      for (let y = x + 1; y < L; y++) {
        if (s[x] === s[y]) continue;
        const d = Math.abs(Number(locSwapString(s, x, y)) - n);
        if (d > 0) set.add(d);
      }
  }
  return set;
}
const bruteCache = new Map();
function bruteReachable(L) {
  if (!bruteCache.has(L)) bruteCache.set(L, locBruteReachable(L));
  return bruteCache.get(L);
}
function countReach(L, max) {
  const s = bruteReachable(L);
  let c = 0;
  for (let v = 9; v <= max; v += 9) if (s.has(v)) c++;
  return c;
}
function readSeed(html) {
  const m = html.match(/<script type="application\/json" id="aw-seed-ledger">([\s\S]*?)<\/script>/);
  return m ? JSON.parse(m[1]) : null;
}
function readBench(html) {
  const m = html.match(/<script type="application\/json" id="aw-bench">([\s\S]*?)<\/script>/);
  return m ? JSON.parse(m[1]) : null;
}

// ════════════════════════════════════════════════════════════════════════════
// SECTION 0: unit tests of the small pure helpers, hand-worked cases FIRST.
// ════════════════════════════════════════════════════════════════════════════
process.stdout.write('\nSection 0: helper unit tests, hand-worked cases' + LF);

check('locSwapString hand case: 48217 swap MSD(1,3) gives 41287',
  () => locSwapString('48217', 1, 3) === '41287');
check('locSwapString identity on equal digits: 777 swap(0,2) gives 777',
  () => locSwapString('777', 0, 2) === '777');
check('locRepunit hand cases: R1=1, R3=111, R0=0',
  () => locRepunit(1) === 1 && locRepunit(3) === 111 && locRepunit(0) === 0);
check('locClosed hand case: (8-1)*(10^3-10^1) = 6930',
  () => locClosed(8, 1, 1, 3) === 6930);
check('hand: 12 to 21 changes by 9, and back by -9',
  () => locSwapValue(12, 0, 1) === 21 && locSwapValue(21, 0, 1) - 21 === -9);
// Sign corrected at source: 41287 < 48217, so the 48217 -> 41287 swap LOSES 6930.
// An earlier draft of this literal claimed +6930 for this direction, which is a
// hand-arithmetic error, not a code defect; the page's live check row computes
// -6930 by both methods and agrees with itself.
check('hand: 48217 to 41287 changes by -6930',
  () => locSwapValue(48217, 1, 3) - 48217 === -6930);
check('hand: 907 to 709 changes by -198',
  () => locSwapValue(907, 0, 2) - 907 === -198);
check('hand: slide 48217 up one place changes by 433953',
  () => 482170 - 48217 === 433953);
check('hand: wrong side of 750.00 moves the difference by 1500.00',
  () => 2 * 75000 === 150000);

check('engine.repunit matches hand: R3=111, R0=0, R6=111111',
  () => eng.repunit(3) === 111 && eng.repunit(0) === 0 && eng.repunit(6) === 111111);
check('engine.digitsOf matches hand, including 0 and negatives',
  () => eq(eng.digitsOf(48217), [4, 8, 2, 1, 7]) &&
        eq(eng.digitsOf(0), [0]) &&
        eq(eng.digitsOf(-48217), [4, 8, 2, 1, 7]));
check('engine.numberFromDigits round-trips digitsOf and allows a leading zero',
  () => eng.numberFromDigits(eng.digitsOf(48217)) === 48217 &&
        eng.numberFromDigits([0, 1, 5]) === 15);
check('engine.digitAt matches hand, including beyond-length zero',
  () => eng.digitAt(48217, 0) === 7 && eng.digitAt(48217, 4) === 4 &&
        eng.digitAt(48217, 5) === 0);
check('engine.swappedNumber matches hand, including the leading-zero edge 105 to 015',
  () => eng.swappedNumber(48217, 1, 3) === 41287 &&
        eng.swappedNumber(105, 2, 1) === 15 &&
        eng.swappedNumber(77, 0, 1) === 77);
check('engine.transpositionDelta matches hand, signed',
  () => eng.transpositionDelta(12, 0, 1) === 9 &&
        eng.transpositionDelta(21, 0, 1) === -9 &&
        eng.transpositionDelta(105, 2, 1) === -90);
check('engine.closedFormDelta matches hand, both signs and the zero case',
  () => eng.closedFormDelta(8, 1, 1, 3) === 6930 &&
        eng.closedFormDelta(1, 0, 2, 1) === -90 &&
        eng.closedFormDelta(5, 5, 0, 3) === 0);
check('engine.slideDelta matches hand, including the null edge',
  () => eng.slideDelta(48217, 1) === 433953 &&
        eng.slideDelta(480, -1) === -432 &&
        eng.slideDelta(483, -1) === null &&
        eng.slideDelta(5, 0) === 0);
check('engine.wrongSideDelta matches hand, including zero and negative',
  () => eng.wrongSideDelta(75000) === 150000 &&
        eng.wrongSideDelta(0) === 0 &&
        eng.wrongSideDelta(-125) === -250);
check('engine.balanceDifference matches hand',
  () => eng.balanceDifference([{ side: 'debit', cents: 250 }, { side: 'credit', cents: 100 }]) === 150 &&
        eng.balanceDifference([{ side: 'debit', cents: 100 }, { side: 'credit', cents: 100 }]) === 0);
check('engine.allTranspositionDeltas matches hand for 105: [-90, 45, 396]',
  () => eq(eng.allTranspositionDeltas(105), [-90, 45, 396]));
check('engine.allTranspositionDeltas is empty when all digits repeat',
  () => eq(eng.allTranspositionDeltas(111), []));

// ════════════════════════════════════════════════════════════════════════════
// SECTION 1: ANCHOR 1, the exhaustive sweep, direct subtraction vs closed form.
// ════════════════════════════════════════════════════════════════════════════
process.stdout.write('\nSection 1: exhaustive transposition sweep (the anchor)' + LF);

let sweepCases = 0, sweepOK = true;
for (const L of [2, 3, 4, 5]) {
  for (let n = 10 ** (L - 1); n < 10 ** L; n++) {
    const s = String(n);
    for (let x = 0; x < L; x++)
      for (let y = x + 1; y < L; y++) {
        if (s[x] === s[y]) continue;
        const direct = Number(locSwapString(s, x, y)) - n;
        // After the swap, weight L-1-x holds s[y] and weight L-1-y holds s[x].
        // locClosed takes a at the LOWER weight i and b at the HIGHER weight j,
        // so a = s[y] at i = L-1-y and b = s[x] at j = L-1-x. Passing s[x] first
        // flips the sign of the closed form and disagrees with direct subtraction
        // on every asymmetric case; that argument order was the defect here.
        const closed = locClosed(+s[y], +s[x], L - 1 - y, L - 1 - x);
        const fromEngine = eng.transpositionDelta(n, L - 1 - y, L - 1 - x);
        if (!(direct === closed && direct === fromEngine && direct % 9 === 0)) sweepOK = false;
        sweepCases++;
      }
  }
}
process.stdout.write('  ANCHOR 1: transposition delta, direct subtraction vs closed form\n');
process.stdout.write('            9*(a-b)*10^i*R_m: ' + sweepCases + ' cases compared' + LF);
check('ANCHOR 1: direct subtraction equals the closed form on all ' + sweepCases +
      ' cases, and every delta is divisible by 9',
  () => sweepOK && sweepCases > 100000);

// ════════════════════════════════════════════════════════════════════════════
// SECTION 2: ANCHOR 2, reachable sets, analytic vs brute force.
// ════════════════════════════════════════════════════════════════════════════
process.stdout.write('\nSection 2: reachable-by-transposition sets, two methods' + LF);

for (const L of [2, 3, 4, 5]) {
  const local = [...bruteReachable(L)].sort((a, b) => a - b);
  const analytic = eng.transpositionDeltasForLength(L);
  const engineBrute = eng.transpositionDeltasForLengthBrute(L);
  process.stdout.write('  L=' + L + ': ' + local.length + ' reachable deltas' + LF);
  check('ANCHOR 2: analytic reachable set equals local brute force for L=' + L,
    () => eq(analytic, local));
  check('ANCHOR 2: engine brute force equals local brute force for L=' + L,
    () => eq(engineBrute, local));
}

// ════════════════════════════════════════════════════════════════════════════
// SECTION 3: ANCHOR 3, the converse: multiples of nine with nothing behind them.
// ════════════════════════════════════════════════════════════════════════════
process.stdout.write('\nSection 3: the converse, counted two ways' + LF);

const u3 = eng.unreachableMultiplesOfNine(3, 810);
process.stdout.write('  CONVERSE: of the ' + u3.totalMultiples + ' multiples of nine up to 810, ' +
  u3.reachable + ' have a 3-digit transposition behind them and ' + u3.unreachable +
  ' have none; first few: ' + u3.examples.join(', ') + LF);
check('ANCHOR 3: the converse count is NON-ZERO (64 of 90 multiples of nine to 810 ' +
      'have no 3-digit transposition behind them)',
  () => u3.unreachable === 64 && u3.reachable === 26 && u3.totalMultiples === 90);
let r3 = 0, t3 = 0;
for (let v = 9; v <= 810; v += 9) { t3++; if (bruteReachable(3).has(v)) r3++; }
check('ANCHOR 3: recounted independently by local brute force: 26 of 90',
  () => r3 === 26 && t3 === 90);
check('ANCHOR 3: each listed example is confirmed unreachable by the independent witness search',
  () => u3.examples.every(v => eng.witness(v, 3) === null));
check('edge: a limit of 100 leaves nothing unreachable (all 11 multiples of nine to 100 are covered)',
  () => eng.unreachableMultiplesOfNine(3, 100).unreachable === 0);
check('edge: limit 200 splits 13 reachable against 9 unreachable',
  () => { const u = eng.unreachableMultiplesOfNine(3, 200);
          return u.reachable === 13 && u.unreachable === 9 && u.totalMultiples === 22; });

// ════════════════════════════════════════════════════════════════════════════
// SECTION 4: witnesses.
// ════════════════════════════════════════════════════════════════════════════
process.stdout.write('\nSection 4: witnesses' + LF);

check('witness(198, 3) is the hand case 907 to 709',
  () => { const w = eng.witness(198, 3);
          return !!w && w.n === 907 && w.swapped === 709 && Math.abs(w.swapped - w.n) === 198; });
check('witness(108, 3) is null: the accident the folklore misses',
  () => eng.witness(108, 3) === null);
check('witness(9, 2) exists (98 to 89)',
  () => { const w = eng.witness(9, 2); return !!w && Math.abs(w.swapped - w.n) === 9; });
check('witness rejects numbers that are not multiples of nine',
  () => eng.witness(7, 3) === null);
{
  let witOK = true, witN = 0;
  for (let v = 9; v <= 810; v += 9) {
    if (bruteReachable(3).has(v)) {
      witN++;
      const w = eng.witness(v, 3);
      if (!w || Math.abs(w.swapped - w.n) !== v) witOK = false;
    }
  }
  check('every one of the ' + witN + ' reachable multiples to 810 has a reproducing witness',
    () => witOK && witN === 26);
}

// ════════════════════════════════════════════════════════════════════════════
// SECTION 5: slides, swept.
// ════════════════════════════════════════════════════════════════════════════
process.stdout.write('\nSection 5: decimal slides' + LF);

{
  let slOK = true, slN = 0;
  for (let n = 0; n <= 5000; n++) { if (eng.slideDelta(n, 1) !== 9 * n) slOK = false; slN++; }
  check('slide up one place changes the value by exactly 9n for ' + slN + ' values', () => slOK);
}
check('slide down requires divisibility by ten: 12340 slides, 1234 does not',
  () => eng.slideDelta(1234, -1) === null && eng.slideDelta(12340, -1) === -11106);
check('slide deltas are divisible by nine on a sampled sweep',
  () => { for (let n = 1; n <= 300; n++) if (eng.slideDelta(n, 1) % 9 !== 0) return false;
          return true; });

// ════════════════════════════════════════════════════════════════════════════
// SECTION 6: the page's seed ledger, exhaustively round-tripped through diagnose.
//
// Semantics under test (pinned in the engine docstring and on the page): a
// hypothesis is a single change to one entry that would bring the difference to
// exactly zero. So a planted error must come back as a hypothesis whose `from` is
// the planted value and whose `to` recovers the ORIGINAL amount.
//
// These round-trips presuppose a BALANCED seed ledger: a plant moves a balanced
// difference to exactly the planted delta, and the repair search then recovers the
// original amount. If the seed itself is out of balance, every round-trip fails
// together, and the honest reading is that the page's embedded constants are wrong,
// not the engine. That is exactly what happened on the first shipped constants
// (credits 352055 against debits 312055); the constants in the page were corrected
// at source rather than these expectations being loosened.
// ════════════════════════════════════════════════════════════════════════════
process.stdout.write('\nSection 6: the page ledger, every plantable error diagnosed' + LF);

const src = readFileSync(PAGE, 'utf8');
const seed = readSeed(src);
check('page exists and embeds a parsable seed ledger of 8 entries',
  () => Array.isArray(seed) && seed.length === 8);
check('the seed ledger balances to exactly zero',
  () => seed !== null && eng.balanceDifference(seed) === 0);
{
  // Guard the downstream sections explicitly: if the ledger is missing, say so and
  // stop here rather than crashing on null mid-run.
  if (!Array.isArray(seed)) {
    process.stdout.write('  FATAL: no parsable aw-seed-ledger in the page; cannot continue' + LF);
    process.exit(1);
  }
}
{
  const debits = seed.filter(e => e.side === 'debit').reduce((a, e) => a + e.cents, 0);
  const credits = seed.filter(e => e.side === 'credit').reduce((a, e) => a + e.cents, 0);
  process.stdout.write('  seed totals: debits ' + debits + ' cents, credits ' + credits + ' cents' + LF);
  check('seed totals recomputed independently are equal (312055 cents each side)',
    () => debits === 312055 && credits === 312055);
}
{
  let tpN = 0, tpSkip = 0, tpOK = true;
  for (const e of seed) {
    const s = String(e.cents);
    for (let x = 0; x < s.length; x++)
      for (let y = x + 1; y < s.length; y++) {
        if (s[x] === s[y]) continue;
        const nv = Number(locSwapString(s, x, y));
        if (nv === e.cents) continue;
        if (String(nv).length !== s.length) {
          // A swap that creates a leading zero shortens the numeral. The
          // corruption is then no longer a transposition OF THE CORRUPTED
          // NUMERAL, so no transposition hypothesis can reach it. This is the
          // documented leading-zero limit (stated in the page's check panel),
          // counted here rather than hidden.
          tpSkip++;
          continue;
        }
        const led = seed.map(z => z.id === e.id ? { ...z, cents: nv } : z);
        const d = eng.diagnose(led);
        const found = d.hypotheses.some(h =>
          h.class === 'transposition' && h.id === e.id &&
          h.from === nv && h.to === e.cents);
        if (!(d.difference !== 0 && found)) tpOK = false;
        tpN++;
      }
  }
  process.stdout.write('  planted transpositions diagnosed: ' + tpN +
    ' digit-count-preserving cases; ' + tpSkip +
    ' leading-zero plants excluded (documented limit)' + LF);
  check('EVERY digit-count-preserving planted transposition (' + tpN + ' cases) leaves a ' +
        'nonzero difference and is diagnosed back onto its entry, recovering the original amount',
        () => tpOK && tpN > 50);
}
{
  let slN = 0, slOK = true;
  for (const e of seed) {
    for (const pl of (e.cents % 10 === 0 ? [1, -1] : [1])) {
      const nv = pl === 1 ? e.cents * 10 : e.cents / 10;
      const led = seed.map(z => z.id === e.id ? { ...z, cents: nv } : z);
      const d = eng.diagnose(led);
      const found = d.hypotheses.some(h =>
        h.class === 'slide' && h.id === e.id && h.from === nv && h.to === e.cents);
      if (!(d.difference !== 0 && found)) slOK = false;
      slN++;
    }
  }
  // The documented slide census is 10: seven entries admit only the upward slide,
  // and exactly two entries (sales receipts, utilities) sit on a multiple of ten
  // and admit the downward slide as well. A seed whose multiple-of-ten count drifts
  // from two breaks this census, which is a property of the page's constants, and
  // the constants are what get corrected.
  check('EVERY planted decimal slide (' + slN + ' cases) is diagnosed back onto its entry, ' +
        'recovering the original amount', () => slOK && slN === 10);
}
{
  let wsN = 0, wsOK = true;
  for (const e of seed) {
    const led = seed.map(z => z.id === e.id
      ? { ...z, side: z.side === 'debit' ? 'credit' : 'debit' } : z);
    const d = eng.diagnose(led);
    const expectedD = e.side === 'debit' ? -2 * e.cents : 2 * e.cents;
    const found = d.hypotheses.some(h =>
      h.class === 'wrong-side' && h.id === e.id && h.x === e.cents);
    if (!(d.difference === expectedD && found)) wsOK = false;
    wsN++;
  }
  check('EVERY planted wrong-side posting (' + wsN + ' cases) moves the difference by ' +
        'twice the amount and is found by diagnose', () => wsOK && wsN === 8);
}
{
  // The planted coincidence: bump entry d1 by 108 cents. The resulting difference of
  // 108 IS divisible by nine, and it is ALSO divisible by two (108 is even; the
  // previous expectation of divisibleBy2 === false was simply wrong arithmetic and
  // has been corrected here, not loosened). What makes it a coincidence is that no
  // hypothesis lands: no transposition of any number produces 108 (108/9 = 12 is not
  // d * 10^i * R_m for any digit d), no entry is worth 12 or 120 cents so no slide
  // reaches it, and no entry is worth 54 cents so even the doubling clue finds
  // nothing. The check asserts all of that, including the empty wrong-side list.
  const coin = seed.map(z => z.id === 'd1' ? { ...z, cents: z.cents + 108 } : z);
  const dc = eng.diagnose(coin);
  check('COINCIDENCE demonstrated: a difference of 108 is divisible by nine AND by two ' +
        '(108 is even), yet NO single transposition, slide, or side swap of the ledger ' +
        'lands on it: no entry is worth 54 cents, so the doubling clue comes up empty too',
    () => dc.difference === 108 && dc.divisibleBy9 === true &&
          dc.divisibleBy2 === true && dc.hypotheses.length === 0);
}
check('diagnose on the clean ledger reports zero difference and no hypotheses',
  () => { const d = eng.diagnose(seed);
          return d.difference === 0 && d.hypotheses.length === 0 &&
                 d.divisibleBy9 === true && d.divisibleBy2 === true; });

// ════════════════════════════════════════════════════════════════════════════
// SECTION 7: reconcile the numbers the page itself displays.
// ════════════════════════════════════════════════════════════════════════════
process.stdout.write('\nSection 7: page reconciliation' + LF);

check('the page embeds the bench constant 48217',
  () => { const b = readBench(src); return !!b && b.start === 48217; });
// Signed, as above: the falling swap loses 6930. The page's own check row shows
// direct -6930 beside closed-form -6930 with the agree column green; this literal
// now says the same true thing instead of contradicting the page it verifies.
check('check-table row: 48217 to 41287 is -6930 by direct subtraction (hand-worked)',
  () => locSwapValue(48217, 1, 3) - 48217 === -6930);
check('check-table row: 48217 to 78214 is 29997 by direct subtraction (hand-worked)',
  () => locSwapValue(48217, 0, 4) - 48217 === 29997);
check('check-table row: the slide 482170 minus 48217 equals 9 times 48217',
  () => 482170 - 48217 === 9 * 48217);
check('check-table row: the wrong-side magnitude equals twice 75000',
  () => Math.abs((-75000) - 75000) === 2 * 75000);
check('sweep counts at ceiling 810 are 26 of 90 for every length 3, 4 and 5',
  () => countReach(3, 810) === 26 && countReach(4, 810) === 26 && countReach(5, 810) === 26);
check('sweep counts at ceiling 2610 are 27, 33, 33 for lengths 3, 4, 5',
  () => countReach(3, 2610) === 27 && countReach(4, 2610) === 33 && countReach(5, 2610) === 33);
check('engine analytic agrees at ceiling 2610: 33 of 290 for length 5',
  () => { const u = eng.unreachableMultiplesOfNine(5, 2610);
          return u.reachable === 33 && u.unreachable === 257 && u.totalMultiples === 290; });
check('the page ships no em dash anywhere in its source',
  () => !src.includes('\u2014'));
check('the page leaves no share-surface description as a __DEK__ placeholder',
  () => (src.match(/__DEK__/g) || []).length === 0);
check('the page declares its canonical URL',
  () => src.includes('<link rel="canonical" href="https://artwaste.land/strata/the-difference-divisible-by-nine/" />'));

// ════════════════════════════════════════════════════════════════════════════
// --mutate: corrupt a copy, confirm the corruption landed, require failure.
// ════════════════════════════════════════════════════════════════════════════
function runMutation(originalText) {
  process.stdout.write('\nMutation phase (--mutate)' + LF);
  const needle = '"cents":128460';
  if (!originalText.includes(needle)) {
    process.stdout.write('  MUTATE ABORT: expected seed constant not found' + LF);
    process.exit(1);
  }
  const mutated = originalText.replace(needle, '"cents":128461');
  if (mutated === originalText) {
    process.stdout.write('  MUTATE ABORT: corruption did not change the bytes' + LF);
    process.exit(1);
  }
  process.stdout.write('  corruption landed: seed entry d1 moved from 128460 to 128461 cents' + LF);

  const dir = mkdtempSync(path.join(tmpdir(), 'awmut-'));
  const tmp = path.join(dir, 'index.html');
  writeFileSync(tmp, mutated);

  let mp = 0, mf = 0;
  const mcheck = (name, fn) => {
    let ok = false;
    try { ok = fn() === true; } catch { ok = false; }
    mp++; if (!ok) mf++;
    process.stdout.write('  ' + (ok ? 'pass' : 'FAIL') + ' (under corruption) ' + name + LF);
  };
  const mutSrc = readFileSync(tmp, 'utf8');
  const mutSeed = readSeed(mutSrc);
  mcheck('mutated ledger still parses with 8 entries', () => Array.isArray(mutSeed) && mutSeed.length === 8);
  mcheck('mutated ledger no longer balances to zero',
    () => eng.balanceDifference(mutSeed) !== 0);
  mcheck('mutated clean diagnose is no longer hypothesis-free',
    () => eng.diagnose(mutSeed).hypotheses.length !== 0 ||
          eng.diagnose(mutSeed).difference !== 0);
  mcheck('control: bench constant survives the mutation untouched',
    () => { const b = readBench(mutSrc); return !!b && b.start === 48217; });

  rmSync(dir, { recursive: true, force: true });

  const after = readFileSync(PAGE, 'utf8');
  if (after !== originalText) {
    process.stdout.write('  RESTORE VIOLATION: the original page changed on disk' + LF);
    process.exit(1);
  }
  process.stdout.write('  original page confirmed byte-identical after the mutation run' + LF);

  if (mf === 0) {
    process.stdout.write('  MUTATE FAILED: the checks still pass under corruption' + LF);
    process.exit(1);
  }
  process.stdout.write('  MUTATE OK: ' + mf + ' of ' + mp + ' page checks failed under ' +
    'corruption, as required; temp copy removed' + LF);
}

// ════════════════════════════════════════════════════════════════════════════
// Report.
// ════════════════════════════════════════════════════════════════════════════
process.stdout.write('\n──────────────────────────────────────────────\n');
process.stdout.write('CHECKS: ' + passed + ' passed, ' + failed + ' failed, ' +
  (passed + failed) + ' total' + LF);
if (failureLog.length) {
  process.stdout.write('Failures:' + LF);
  for (const f of failureLog)
    process.stdout.write('  - ' + f.name + (f.threw ? ' (threw: ' + f.threw.message + ')' : '') + LF);
}
process.stdout.write('ANCHOR 1: transposition delta by direct subtraction vs closed form, ' +
  sweepCases + ' exhaustive cases (methods implemented in this file)' + LF);
process.stdout.write('ANCHOR 2: reachable sets, analytic generation vs brute-force ' +
  'enumeration over all L-digit numbers, L = 2 to 5' + LF);
process.stdout.write('ANCHOR 3: converse count non-zero, recounted two ways (64 of 90 at ' +
  'length 3, ceiling 810)' + LF);

if (process.argv.includes('--mutate')) runMutation(src);

const total = passed + failed;
if (total === 0) {
  process.stdout.write('ZERO CHECKS PERFORMED: refusing to report success' + LF);
  process.exit(1);
}
process.exit(failed > 0 ? 1 : 0);
