// verify-finite-gap.mjs — the bridge between a Lean theorem and the pages it deepens.
//
//   node research/finite-gap/verify-finite-gap.mjs
//
// lean/FiniteGap.lean proves one identity, `d * geom (T+d) T n + T^n = (T+d)^n`, and
// reads it five ways to settle five claims that two live layers currently only sample.
// A proof is worth nothing to those layers unless it is a proof ABOUT them, so this
// script never asserts the theorem (Lean's kernel does that). It asserts the two things
// the kernel cannot:
//
//   1. FIDELITY. The Lean definitions, transcribed here from the .lean source, compute
//      the same numbers the pages' own engines compute — the exact BigInt rationals in
//      research/does-point-nine-equal-one/verify.mjs and research/zeno-paradox/verify.mjs
//      and in the two immersive pages' in-browser arithmetic. If they ever diverge, the
//      proof is about something else and this goes red.
//   2. THE BOUNDS ARE REAL. The five loops the proof replaces stop where the prose says
//      they stop. Read out of the source, not transcribed, so the sentence "stops at 60"
//      cannot rot.
//
// And, because a fidelity check that cannot fail is worse than none, §F re-runs every
// fidelity assertion against DELIBERATELY WRONG transcriptions of the Lean model and
// requires each one to be caught.
//
// §G typechecks the proof live when `lean` is on PATH and audits its axiom footprint.

'use strict';

import fs from 'node:fs';
import path from 'node:path';
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 LEAN_FILE = path.join(HERE, 'lean', 'FiniteGap.lean');

let fails = 0, checks = 0;
const ok = (name, cond, extra = '') => {
  checks++;
  if (!cond) fails++;
  console.log(`${cond ? '  ok  ' : 'FAIL  '}${name}${extra ? '   ' + extra : ''}`);
};
const section = (s) => console.log(`\n${s}`);

// ---------------------------------------------------------------------------
// Exact rationals on BigInt — the same shape both page verifiers use, written
// independently here so agreement is agreement and not a shared bug.
// ---------------------------------------------------------------------------
function gcd(a, b) { a = a < 0n ? -a : a; b = b < 0n ? -b : b; while (b) { [a, b] = [b, a % b]; } return a; }
function R(n, d = 1n) {
  n = BigInt(n); d = BigInt(d);
  if (d === 0n) throw new Error('zero denominator');
  if (d < 0n) { n = -n; d = -d; }
  const g = gcd(n, d) || 1n;
  return { n: n / g, d: d / g };
}
const add = (a, b) => R(a.n * b.d + b.n * a.d, a.d * b.d);
const rsub = (a, b) => R(a.n * b.d - b.n * a.d, a.d * b.d);
const mul = (a, b) => R(a.n * b.n, a.d * b.d);
const div = (a, b) => R(a.n * b.d, a.d * b.n);
const eq = (a, b) => a.n * b.d === b.n * a.d;
const lt = (a, b) => a.n * b.d < b.n * a.d;
const ONE = R(1n), ZERO = R(0n);
const bpow = (b, k) => { let r = 1n, x = BigInt(b), e = BigInt(k); while (e > 0n) { if (e & 1n) r *= x; x *= x; e >>= 1n; } return r; };

// ---------------------------------------------------------------------------
// §A. THE LEAN MODEL, transcribed. Every line below has its .lean counterpart
//     quoted beside it; §F proves the transcription is load-bearing.
// ---------------------------------------------------------------------------
//   def geom (A T : Nat) : Nat → Nat
//     | 0 => 0
//     | n + 1 => A ^ n + T * geom A T n
function geom(A, T, n) {
  let acc = 0n;                                   // geom A T 0 = 0
  for (let j = 1; j <= n; j++) acc = bpow(A, j - 1) + BigInt(T) * acc;
  return acc;
}
//   def repunit (b : Nat) (n : Nat) : Nat := geom b 1 n
const repunit = (b, n) => geom(b, 1, n);

console.log('The gap at every finite stage — Lean proof vs the layers it deepens\n');

section('[A] the transcription computes what the recursion says it computes');
{
  // geom A T n unrolled by hand for small n, against the loop above.
  const byHand = (A, T, n) => {
    let s = 0n;
    for (let i = 0; i < n; i++) s += bpow(A, n - 1 - i) * bpow(T, i);   // A^(n-1) + A^(n-2)T + …
    return s;
  };
  let agree = true;
  for (let A = 1; A <= 12; A++) for (let T = 0; T <= 12; T++) for (let n = 0; n <= 14; n++) {
    if (geom(A, T, n) !== byHand(A, T, n)) agree = false;
  }
  ok('the recursion and the closed sum A^(n-1)+A^(n-2)T+…+T^(n-1) agree (13×13×15 cases)', agree);
  ok('geom A T 0 = 0 and geom A T 1 = 1', geom(7, 3, 0) === 0n && geom(7, 3, 1) === 1n);
  ok('geom A T 2 = A + T', geom(7, 3, 2) === 10n);

  // The identity itself, numerically. This CORROBORATES the transcription; the
  // theorem is proved in Lean, not here.
  let idHolds = true;
  for (let T = 0; T <= 12; T++) for (let d = 0; d <= 12; d++) for (let n = 0; n <= 20; n++) {
    const A = BigInt(T + d);
    if (BigInt(d) * geom(T + d, T, n) + bpow(T, n) !== bpow(A, n)) idHolds = false;
  }
  ok('d·geom(T+d,T,n) + T^n = (T+d)^n over 13×13×21 = 3,549 cases (corroboration; Lean has the proof)', idHolds);
}

// ---------------------------------------------------------------------------
// §B. FIDELITY — 0.999… . The page's S_n is Σ_{k=1}^n 9/10^k, built the way the
//     page builds it. The theorem's reading is: numerator 9·repunit over 10^n.
// ---------------------------------------------------------------------------
section('[B] fidelity: the 0.999… layer computes what nines_gap is about');
{
  const NMAX = 60;                                     // the layer's own stopping point
  let S = ZERO, sumMatches = true, gapMatches = true, belowOne = true;
  for (let n = 1; n <= NMAX; n++) {
    S = add(S, R(9n, bpow(10, n)));                    // exactly the page's construction
    const leanS = R(9n * repunit(10, n), bpow(10, n)); // exactly the theorem's reading
    if (!eq(S, leanS)) sumMatches = false;
    if (!eq(rsub(ONE, S), R(1n, bpow(10, n)))) gapMatches = false;
    if (!lt(S, ONE)) belowOne = false;
  }
  ok(`S_n built term-by-term equals 9·repunit(10,n)/10^n for every n ≤ ${NMAX}`, sumMatches);
  ok('the gap 1 − S_n is exactly 1/10^n — the theorem\'s "+ 1", divided through', gapMatches);
  ok('and S_n < 1 at every stage (trunc_lt_one)', belowOne);

  // The thirds. 1/3 − T_n = 1/(3·10^n) is the SAME numerator identity regrouped,
  // which is what thirds_gap says; check the regrouping is real.
  let T3 = ZERO, thirdsMatch = true;
  for (let n = 1; n <= NMAX; n++) {
    T3 = add(T3, R(3n, bpow(10, n)));
    if (!eq(rsub(R(1n, 3n), T3), R(1n, 3n * bpow(10, n)))) thirdsMatch = false;
    if (3n * (3n * repunit(10, n)) + 1n !== bpow(10, n)) thirdsMatch = false;
  }
  ok(`1/3 − 0.33…3 is exactly 1/(3·10^n) for every n ≤ ${NMAX}, and it is nines_gap regrouped`, thirdsMatch);
}

// ---------------------------------------------------------------------------
// §C. FIDELITY — Zeno, in the research verifier's GENERAL (A,T,H) form.
//
//     This section exists in two halves for a reason that only showed up when the
//     controls in §F were written. The immersive page parameterises the race by a
//     single speed ratio k, which is the T = 1 case — and at T = 1 the Lean model's
//     `T * geom` is indistinguishable from `geom`, and swapping A for T changes
//     nothing. A fidelity check run only against the page therefore cannot see two
//     of the four plausible mis-transcriptions. The research verifier races with
//     T = 2, 3, 99, so this half runs first and the T-dependence is exercised.
// ---------------------------------------------------------------------------
section('[C] fidelity: the Zeno layer computes what achilles_lead is about — general (A,T,H)');
{
  // the research verifier's own races (research/zeno-paradox/verify.mjs §6), T > 1 among them
  const races = [[2, 1, 10], [3, 2, 30], [7, 3, 12], [100, 99, 1], [5, 1, 200], [10, 1, 100]];
  let leadMatch = true, runMatch = true, gapMatch = true, timesMatch = true, tGuard = false;
  for (const [A, T, H] of races) {
    if (T > 1) tGuard = true;
    const d = A - T, r = R(BigInt(T), BigInt(A));
    const L = div(R(BigInt(H)), rsub(ONE, r));                   // H/(1−r)
    const tau = div(R(BigInt(H)), R(BigInt(d)));                 // H/(A−T)
    for (let n = 0; n <= 40; n++) {
      const rn = R(bpow(T, n), bpow(A, n));
      const Sn = div(mul(R(BigInt(H)), rsub(ONE, rn)), rsub(ONE, r));   // the verifier's S_n
      const lead = mul(R(BigInt(H)), rn);                              // the verifier's g_n
      const den = BigInt(d) * bpow(A, n);                              // the theorem's common denominator
      if (!eq(lead, R(BigInt(H) * bpow(T, n), bpow(A, n)))) leadMatch = false;
      if (!eq(Sn, R(BigInt(H) * BigInt(A) * (BigInt(d) * geom(A, T, n)), den))) runMatch = false;
      if (!eq(rsub(L, Sn), R(BigInt(H) * BigInt(A) * bpow(T, n), den))) gapMatch = false;
      if (n > 0 && !lt(Sn, L)) gapMatch = false;
      let tSum = ZERO;
      for (let j = 1; j <= n; j++) tSum = add(tSum, div(mul(R(BigInt(H)), R(bpow(T, j - 1), bpow(A, j - 1))), R(BigInt(A))));
      if (!eq(tSum, R(BigInt(H) * (BigInt(d) * geom(A, T, n)), den))) timesMatch = false;
      if (n > 0 && !lt(tSum, tau)) timesMatch = false;
    }
  }
  ok('SIX races, the number the Zeno page states in its own prose', races.length === 6, `${races.length} races`);
  ok('the race set exercises T > 1 (so the model\'s T-dependence is actually tested)', tGuard);
  ok('the verifier\'s lead g_n = H·r^n is H·T^n/A^n — the theorem\'s second summand (6 races × 41 stages)', leadMatch);
  ok('the verifier\'s S_n is H·A·(d·geom(A,T,n))/(d·A^n) — the theorem\'s first summand', runMatch);
  ok('L − S_n is exactly H·A·T^n/(d·A^n) and S_n < L at every stage (position_below_catch)', gapMatch);
  ok('the stage TIMES sum to H·(d·geom)/(d·A^n) and stay below τ (times_below_total)', timesMatch);
}

section('[C2] …and the immersive page\'s single-ratio (k,H) form, which is the T = 1 case');
{
  // the page's own engine, transcribed from public/strata/zeno-paradox/index.html
  const pageCatch = (k, H) => div(R(BigInt(H) * BigInt(k)), R(BigInt(k) - 1n));      // H·k/(k−1)
  const pageTau = (k, H) => div(R(BigInt(H)), R(BigInt(k) - 1n));                    // H/(k−1)
  const pageRun = (k, H, n) => n === 0 ? ZERO
    : R(BigInt(H) * (bpow(k, n) - 1n) * BigInt(k), (BigInt(k) - 1n) * bpow(k, n));   // S_n
  const pageLead = (k, H, n) => R(BigInt(H), bpow(k, n));                            // H/k^n

  let leadMatch = true, runMatch = true, belowCatch = true, sumMatch = true, neverZero = true;
  const races = [[10, 100], [2, 10], [3, 30], [7, 12], [100, 1], [5, 200]];
  for (const [k, H] of races) {
    const T = 1, A = k, d = k - 1;
    for (let n = 0; n <= 60; n++) {
      // the tortoise's lead, page-side vs theorem-side (H·T^n over A^n)
      if (!eq(pageLead(k, H, n), R(BigInt(H) * bpow(T, n), bpow(A, n)))) leadMatch = false;
      // Achilles' position, over the theorem's common denominator d·A^n
      const leanRun = R(BigInt(H) * BigInt(A) * (BigInt(d) * geom(A, T, n)), BigInt(d) * bpow(A, n));
      if (!eq(pageRun(k, H, n), leanRun)) runMatch = false;
      // position_below_catch, and the gap is exactly the lead scaled by A/d
      const L = pageCatch(k, H);
      if (n > 0 && !lt(pageRun(k, H, n), L)) belowCatch = false;
      const gapToCatch = rsub(L, pageRun(k, H, n));
      if (!eq(gapToCatch, R(BigInt(H) * BigInt(A) * bpow(T, n), BigInt(d) * bpow(A, n)))) belowCatch = false;
      if (n > 0 && !lt(ZERO, pageLead(k, H, n))) neverZero = false;
      // times_below_total: Σ stage times = H·(d·geom)/(d·A^n), total τ = H/d
      let tSum = ZERO;
      for (let j = 1; j <= n; j++) tSum = add(tSum, div(mul(R(BigInt(H)), R(bpow(T, j - 1), bpow(A, j - 1))), R(BigInt(A))));
      const leanTimes = R(BigInt(H) * (BigInt(d) * geom(A, T, n)), BigInt(d) * bpow(A, n));
      if (!eq(tSum, leanTimes)) sumMatch = false;
      if (n > 0 && !lt(tSum, pageTau(k, H))) sumMatch = false;
    }
  }
  ok('the tortoise\'s lead H/k^n is H·T^n/A^n — the theorem\'s second summand (6 races × 61 stages)', leadMatch);
  ok('Achilles\' position S_n is H·A·(d·geom)/(d·A^n) — the theorem\'s first summand', runMatch);
  ok('S_n < L at every stage, and L − S_n is exactly H·A·T^n/(d·A^n) (position_below_catch)', belowCatch);
  ok('the stage TIMES sum to H·(d·geom)/(d·A^n) and stay below τ = H/d (times_below_total)', sumMatch);
  ok('the lead is strictly positive at every finite stage (lead_pos)', neverZero);

  // The Dichotomy — the same theorem at base 2, which is the layer's §5.
  let dSum = ZERO, dichMatch = true;
  for (let n = 1; n <= 64; n++) {
    dSum = add(dSum, R(1n, bpow(2, n)));
    if (!eq(dSum, R(repunit(2, n), bpow(2, n)))) dichMatch = false;
    if (!eq(rsub(ONE, dSum), R(1n, bpow(2, n)))) dichMatch = false;
  }
  ok('Σ_{k≤n} 1/2^k = repunit(2,n)/2^n and the gap is exactly 1/2^n, n ≤ 64 (halves_gap)', dichMatch);
  ok('repunit(2,10) = 1023, the kernel\'s own `decide` (dichotomy_at_ten)', repunit(2, 10) === 1023n);
}

// ---------------------------------------------------------------------------
// §D. FIDELITY — the other half. `overtaken` says every rational below 1 is
//     passed by some truncation; the page's nThatBeats finds the SMALLEST such n
//     for four hand-picked decimals. Check the theorem's witness against it.
// ---------------------------------------------------------------------------
section('[D] fidelity: overtaken / only_one_limit vs the page\'s "find a number in between"');
{
  // transcribed from public/strata/does-point-nine-equal-one/index.html
  const nThatBeats = (num, den) => {
    const diff = den - num; if (diff <= 0n) return null;
    let n = 1n, guard = 0;
    while (bpow(10, Number(n)) * diff <= den) { n++; if (++guard > 4000) return null; }
    return Number(n);
  };
  const cands = [[9n, 10n], [99n, 100n], [9995n, 10000n], [99999999n, 100000000n],
                 [1n, 2n], [2n, 3n], [999999999999n, 1000000000000n], [1n, 1000000n]];
  let smallestWorks = true, leanWitnessWorks = true, witnessNotSmaller = true, witnessed = 0;
  for (const [p, q] of cands) {
    const nSmall = nThatBeats(p, q);
    if (nSmall === null) { smallestWorks = false; continue; }
    // the page's n really does overtake
    if (!lt(R(p, q), R(9n * repunit(10, nSmall), bpow(10, nSmall)))) smallestWorks = false;
    // the theorem's witness is n = q, crude on purpose; run it wherever q is affordable
    if (q <= 300n) {
      const witness = Number(q);
      if (!(p * bpow(10, witness) < q * (9n * repunit(10, witness)))) leanWitnessWorks = false;
      if (nSmall > witness) witnessNotSmaller = false; // the proof's witness is never tighter
      witnessed++;
    }
  }
  ok('the witness n = q was actually run on some candidate (the check is not vacuous)', witnessed >= 3,
     `${witnessed} of ${cands.length} candidates had q ≤ 300`);
  ok('every candidate strictly below 1 is overtaken by some finite run of nines (8 candidates)', smallestWorks);
  ok('the theorem\'s witness n = q overtakes too — the existence claim, at its stated witness', leanWitnessWorks);
  ok('and the page\'s n is never larger than the proof\'s witness (the proof is loose, not wrong)', witnessNotSmaller);
  ok('a candidate at or above 1 has no overtaking n (one_not_overtaken)',
     nThatBeats(1n, 1n) === null && nThatBeats(3n, 2n) === null);

  // only_one_limit, instantiated: nothing at-or-above every truncation and below 1.
  let noneInside = true;
  for (const [p, q] of cands) {
    let aboveAll = true;
    for (let n = 1; n <= 40; n++) if (lt(R(p, q), R(9n * repunit(10, n), bpow(10, n)))) { aboveAll = false; break; }
    if (aboveAll && p < q) noneInside = false;         // would be a number strictly between
  }
  ok('no candidate sits at-or-above every truncation while staying below 1 (only_one_limit)', noneInside);
}

// ---------------------------------------------------------------------------
// §E. THE BOUNDS ARE REAL — read out of the two layers' sources, not transcribed.
// ---------------------------------------------------------------------------
section('[E] the five windows this proof replaces, read out of their own sources');
{
  const WINDOWS = [
    ['research/does-point-nine-equal-one/verify.mjs', 49, 60, 'every truncation S_n of 0.999… is < 1 and the gap is exactly 1/10^n', 'nines_gap'],
    ['research/does-point-nine-equal-one/verify.mjs', 77, 60, 'the truncated 0.33…3 sits below 1/3 by exactly 1/(3·10^n)', 'thirds_gap'],
    ['research/zeno-paradox/verify.mjs', 73, 50, 'at every finite stage Achilles is behind the catch point; the lead is exactly H·r^n', 'position_below_catch'],
    ['research/zeno-paradox/verify.mjs', 92, 60, 'every finite partial sum of the stage TIMES stays below the total catch time', 'times_below_total'],
    ['research/zeno-paradox/verify.mjs', 116, 64, 'the partial sum of 1/2^n equals 1 − 1/2^n, below 1 at every finite step', 'halves_gap'],
  ];
  const leanSrc = fs.readFileSync(LEAN_FILE, 'utf8');
  for (const [file, line, bound, claim, thm] of WINDOWS) {
    const src = fs.readFileSync(path.join(ROOT, file), 'utf8').split('\n');
    const text = (src[line - 1] || '');
    const m = text.match(/<=\s*(\d+)\s*;/);
    ok(`${file}:${line} is a counted loop stopping at ${bound}`, !!m && Number(m[1]) === bound,
       m ? `“${text.trim().slice(0, 58)}…”` : `line reads: ${text.trim().slice(0, 58)}`);
    ok(`  …and lean/FiniteGap.lean carries a theorem \`${thm}\` for it`,
       new RegExp(`theorem\\s+${thm}\\b`).test(leanSrc), claim.slice(0, 52) + '…');
  }
}

// ---------------------------------------------------------------------------
// §F. THE CONTROLS — every fidelity check above must be able to go red. Each
//     mutation is a plausible mis-transcription of the Lean model; if any one of
//     them slips through, the fidelity section is decoration.
// ---------------------------------------------------------------------------
section('[F] controls: deliberately wrong transcriptions of the Lean model, each must be caught');
{
  const mutants = {
    'geom off by one stage (A^n instead of A^(n-1))': (A, T, n) => {
      let acc = 0n; for (let i = 0; i < n; i++) acc = bpow(A, n - i) + BigInt(T) * acc; return acc;
    },
    'geom drops the T factor (T*geom → geom)': (A, T, n) => {
      let acc = 0n; for (let i = 0; i < n; i++) acc = bpow(A, n - 1 - i) + acc; return acc;
    },
    'geom starts at 1 instead of 0': (A, T, n) => {
      let acc = 1n; for (let i = 0; i < n; i++) acc = bpow(A, n - 1 - i) + BigInt(T) * acc; return acc;
    },
    'geom swaps A and T': (A, T, n) => {
      let acc = 0n; for (let i = 0; i < n; i++) acc = bpow(T, n - 1 - i) + BigInt(A) * acc; return acc;
    },
  };
  // The two fidelity predicates, re-run against a supplied geom.
  const ninesFidelity = (g) => {
    for (let n = 1; n <= 30; n++) {
      let S = ZERO; for (let j = 1; j <= n; j++) S = add(S, R(9n, bpow(10, j)));
      if (!eq(S, R(9n * g(10, 1, n), bpow(10, n)))) return false;
    }
    return true;
  };
  // NOTE the T = 3 race. Run this predicate at T = 1 (the immersive page's form) and
  // two of the four mutations below become invisible, because `T * geom` collapses to
  // `geom` and swapping A for T changes nothing. That is why §C leads with the general
  // races and this control follows it.
  const zenoFidelity = (g) => {
    const A = 7, T = 3, H = 12, d = A - T;
    const r = R(BigInt(T), BigInt(A));
    for (let n = 1; n <= 20; n++) {
      const rn = R(bpow(T, n), bpow(A, n));
      const Sn = div(mul(R(BigInt(H)), rsub(ONE, rn)), rsub(ONE, r));
      const leanRun = R(BigInt(H) * BigInt(A) * (BigInt(d) * g(A, T, n)), BigInt(d) * bpow(A, n));
      if (!eq(Sn, leanRun)) return false;
    }
    return true;
  };
  // The two pages say "four deliberately wrong transcriptions" and "six races" in their own
  // prose. Tie those numbers to the code so the sentences cannot drift away from the check.
  ok('the control set is exactly the FOUR mutations the two pages name', Object.keys(mutants).length === 4,
     `${Object.keys(mutants).length} mutations`);
  ok('positive control: the real transcription passes both fidelity predicates',
     ninesFidelity(geom) && zenoFidelity(geom));
  let allCaught = true;
  for (const [label, g] of Object.entries(mutants)) {
    const caught = !ninesFidelity(g) || !zenoFidelity(g);
    if (!caught) allCaught = false;
    ok(`  mutation caught: ${label}`, caught);
  }
  ok('every mutation of the Lean model is caught by the fidelity checks', allCaught);

  // And a control on §E: a bound that is NOT what the source says must be rejected.
  const src = fs.readFileSync(path.join(ROOT, 'research/zeno-paradox/verify.mjs'), 'utf8').split('\n');
  const m = (src[115] || '').match(/<=\s*(\d+)\s*;/);
  ok('control: the bound reader rejects a wrong bound (claiming zeno:116 stops at 63)',
     !!m && Number(m[1]) !== 63);
}

// ---------------------------------------------------------------------------
// §G. THE KERNEL — typecheck live and audit the axiom footprint.
// ---------------------------------------------------------------------------
section('[G] the kernel: zero imports, live typecheck, axiom footprint');
{
  const leanSrc = fs.readFileSync(LEAN_FILE, 'utf8');
  const importLines = leanSrc.split('\n').filter(l => /^\s*import\s/.test(l));
  ok('lean/FiniteGap.lean has ZERO import lines (no Mathlib, no Std) — read, not asserted',
     importLines.length === 0, `${importLines.length} imports`);
  // Strip comments before hunting for `sorry`: this file's own header discusses the word,
  // and a scan that cannot tell prose from a tactic would fail on its own honesty note.
  const code = leanSrc.replace(/\/-[\s\S]*?-\//g, ' ').replace(/--[^\n]*/g, ' ');
  ok('and no `sorry` tactic in the code (comments stripped first)', !/\bsorry\b/.test(code));
  ok('control: the comment-stripped scan still sees a planted `sorry`',
     /\bsorry\b/.test((code + '\n  exact sorry\n')));
  const theorems = [...leanSrc.matchAll(/^theorem\s+([A-Za-z0-9_']+)/gm)].map(m => m[1]);
  const audited = [...leanSrc.matchAll(/^#print axioms\s+([A-Za-z0-9_']+)/gm)].map(m => m[1]);
  ok(`every theorem in the file is in the axiom audit (${theorems.length} theorems)`,
     theorems.every(t => audited.includes(t)),
     theorems.filter(t => !audited.includes(t)).join(' ') || 'all audited');

  let lean = null;
  for (const c of [process.env.LEAN_BIN, 'lean', path.join(process.env.HOME || '', '.elan/bin/lean'),
                   path.join(process.env.HOME || '', '.nix-profile/bin/lean')]) {
    if (!c) continue;
    try { execFileSync(c, ['--version'], { stdio: 'pipe' }); lean = c; break; } catch { /* keep looking */ }
  }
  if (!lean) {
    console.log('  --   lean not on PATH; skipping the live typecheck.');
    console.log('       install: bash research/finite-gap/lean/install-lean.sh   (then re-run)');
  } else {
    let out = '', code = 0;
    try {
      out = execFileSync(lean, [LEAN_FILE], { encoding: 'utf8', maxBuffer: 1 << 26, timeout: 600000 });
    } catch (e) { code = e.status ?? 1; out = String(e.stdout || '') + String(e.stderr || ''); }
    ok('lean typechecks lean/FiniteGap.lean with no errors (exit 0)', code === 0,
       code === 0 ? '' : out.split('\n').slice(0, 3).join(' | '));
    const axLines = out.split('\n').filter(l => /depends on axioms|does not depend on any axioms/.test(l));
    ok(`the axiom audit printed a footprint for every audited theorem (${audited.length})`,
       axLines.length === audited.length, `${axLines.length} lines`);
    const bad = axLines.filter(l => /sorryAx|Classical\.choice/.test(l));
    ok('no theorem depends on sorryAx or Classical.choice', bad.length === 0, bad.join(' | '));
    const clean = axLines.every(l => /\[propext(, Quot\.sound)?\]/.test(l) || /does not depend on any axioms/.test(l));
    ok('every footprint is [propext, Quot.sound] or narrower', clean);
  }
}

// ---------------------------------------------------------------------------
console.log(`\n${fails === 0 ? '✓ ALL PASS' : '✗ FAILURES'} — ${checks} checks, ${fails} failed.`);
// What is established: the Lean file's five theorems are about the same quantities the
// two layers compute and display, and the loops they replace stop where the prose says.
// What is NOT established here or there: that 0.999… = 1 as a statement about the REAL
// numbers. That needs a construction of ℝ to take a supremum in, which a zero-import
// file cannot have. See the header of lean/FiniteGap.lean.
process.exit(fails === 0 ? 0 : 1);
