// research/check-digits/verify.mjs
// Locks every claim the stratum "The Digit That Guards the Rest" makes about the
// five check-digit schemes, each way twice: an ALGEBRAIC argument over the
// weight/group/quasigroup structure, and an EXHAUSTIVE enumeration over all valid
// numbers of a small length. The general "for all lengths" statements are then
// handed to Lean's kernel (§6, lean/CheckDigits.lean) — all five schemes now
// machine-checked, Verhoeff's D5 group fold and Damm's quasigroup fold included —
// so nothing load-bearing is merely sampled.
//
// The two human-error types under test are the ones Verhoeff (1969) measured as
// far and away the most common: a single mistyped digit, and a swap of two
// adjacent digits.
//
// Run:  node research/check-digits/verify.mjs

import {
  luhnF, luhnValid, luhnCheck,
  isbn10Valid, isbn10Check, isbn10Sum,
  ean13Valid, ean13Check,
  verhoeffValid, verhoeffCheck, D5, VP, VINV,
  dammValid, dammCheck, dammSum, DAMM,
  SCHEMES, toDigits, undetectedSingles, undetectedAdjacent, transpositionBlindPairs,
} from './engine.mjs';
import { execSync } from 'node:child_process';
import { existsSync, readFileSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { homedir } from 'node:os';

const HERE = dirname(fileURLToPath(import.meta.url));

let checks = 0, fails = 0;
const ok = (cond, msg) => { checks++; if (!cond) { fails++; console.log('  ✗ ' + msg); } };
const eqSet = (a, b) => a.length === b.length && a.every((x, i) => x === b[i]);
const digits = (s) => toDigits(s);

// Enumerate every valid number of length `len` for a scheme, calling fn(fullDigits).
function forEachValid(scheme, len, fn) {
  const payLen = len - 1;
  const total = 10 ** payLen;
  const pay = new Array(payLen).fill(0);
  for (let n = 0; n < total; n++) {
    let x = n;
    for (let i = payLen - 1; i >= 0; i--) { pay[i] = x % 10; x = (x / 10) | 0; }
    fn([...pay, scheme.check(pay)]);
  }
}

// A deterministic pseudo-random stream (no Math.random — reproducible).
function* lcg(seed) { let s = seed >>> 0; for (;;) { s = (1103515245 * s + 12345) >>> 0; yield s; } }

// ===========================================================================
console.log('0. Table & structure sanity');
// ---------------------------------------------------------------------------
// luhnF is a bijection of {0..9} — the reason a doubled digit can never collide.
{
  const img = [...Array(10)].map((_, d) => luhnF(d)).sort((a, b) => a - b);
  ok(eqSet(img, [...Array(10)].map((_, i) => i)), 'luhnF is a bijection of {0..9}');
}
// D5 is a Latin square, has identity 0, is associative, every element invertible.
{
  let latin = true;
  for (let r = 0; r < 10; r++) {
    const row = new Set(D5[r]), col = new Set(D5.map((x) => x[r]));
    if (row.size !== 10 || col.size !== 10) latin = false;
  }
  ok(latin, 'D5 is a Latin square (rows & columns are permutations)');
  ok(D5[0].every((v, i) => v === i) && D5.every((row, i) => row[0] === i), 'D5 identity is 0');
  let assoc = true;
  for (let a = 0; a < 10 && assoc; a++) for (let b = 0; b < 10 && assoc; b++) for (let c = 0; c < 10; c++)
    if (D5[D5[a][b]][c] !== D5[a][D5[b][c]]) { assoc = false; break; }
  ok(assoc, 'D5 is associative (a genuine group — the dihedral group of order 10)');
  ok([...Array(10)].every((_, a) => D5[a][VINV[a]] === 0), 'VINV inverts every element of D5');
  // D5 is NON-abelian: that non-commutativity is what defeats adjacent swaps.
  let nonAbelian = false;
  for (let a = 0; a < 10 && !nonAbelian; a++) for (let b = 0; b < 10; b++)
    if (D5[a][b] !== D5[b][a]) { nonAbelian = true; break; }
  ok(nonAbelian, 'D5 does NOT commute (the property mod-10 arithmetic lacks)');
  // VP is 8 genuine permutations, and VP[0] is the identity.
  ok(VP.length === 8 && VP.every((p) => new Set(p).size === 10), 'VP is 8 permutations of {0..9}');
  ok(VP[0].every((v, i) => v === i), 'VP[0] is the identity permutation');
}
// DAMM is a Latin square with a ZERO diagonal, TOTALLY ANTI-SYMMETRIC but NOT
// associative — a quasigroup, not a group. That anti-symmetry (not a group
// structure, not a modulus) is the whole engine of the transposition guarantee.
{
  let latin = true;
  for (let r = 0; r < 10; r++) {
    const row = new Set(DAMM[r]), col = new Set(DAMM.map((x) => x[r]));
    if (row.size !== 10 || col.size !== 10) latin = false;
  }
  ok(latin, 'DAMM is a Latin square (a quasigroup: rows & columns are permutations)');
  ok([...Array(10)].every((_, i) => DAMM[i][i] === 0), 'DAMM has an all-zero diagonal (x⋆x = 0)');
  // totally anti-symmetric: (c⋆a)⋆b ≠ (c⋆b)⋆a for every carry c and every a≠b.
  let ta = true;
  for (let c = 0; c < 10 && ta; c++) for (let a = 0; a < 10 && ta; a++) for (let b = 0; b < 10; b++)
    if (a !== b && DAMM[DAMM[c][a]][b] === DAMM[DAMM[c][b]][a]) { ta = false; break; }
  ok(ta, 'DAMM is totally anti-symmetric ((c⋆a)⋆b ≠ (c⋆b)⋆a for a≠b) — the transposition guarantee');
  // NOT associative — so Verhoeff's factor-out-the-accumulator reduction cannot
  // apply; the Lean proof rests on the suffix fold being a bijection instead.
  let assoc = true;
  for (let a = 0; a < 10 && assoc; a++) for (let b = 0; b < 10 && assoc; b++) for (let c = 0; c < 10; c++)
    if (DAMM[DAMM[a][b]][c] !== DAMM[a][DAMM[b][c]]) { assoc = false; break; }
  ok(!assoc, 'DAMM is NOT associative (a quasigroup, not a group — unlike D5)');
}

// ===========================================================================
console.log('\n1. LUHN (mod 10, double every 2nd) — credit cards, IMEI');
// ---------------------------------------------------------------------------
// Real published test PANs are Luhn-valid; a real IMEI check digit reproduces.
ok(luhnValid(digits('4111 1111 1111 1111')), 'Visa test PAN 4111 1111 1111 1111 passes Luhn');
ok(luhnValid(digits('4242 4242 4242 4242')), 'Stripe test PAN 4242 4242 4242 4242 passes Luhn');
ok(luhnValid(digits('5500 0000 0000 0004')), 'Mastercard test PAN passes Luhn');
ok(luhnCheck(digits('7992739871')) === 3, 'Wikipedia Luhn example 7992739871 -> check 3');

// (a) ALGEBRAIC: every single-digit substitution is caught, because both the
// identity (undoubled) and luhnF (doubled) are injective mod 10.
ok([...Array(10)].every((_, d) => [...Array(10)].every((_, e) =>
  d === e || ((luhnF(d) - luhnF(e)) % 10 !== 0 && (d - e) % 10 !== 0))),
  'ALGEBRAIC: no two distinct digits share a Luhn contribution (all single errors caught)');

// (b) ALGEBRAIC: an adjacent swap {a,b} slips through iff g(a)=g(b) where
// g(d) = (luhnF(d) - d) mod 10. The ONLY collision is g(0)=g(9)=0.
{
  const g = (d) => ((luhnF(d) - d) % 10 + 10) % 10;
  const blind = [];
  for (let a = 0; a <= 9; a++) for (let b = a + 1; b <= 9; b++) if (g(a) === g(b)) blind.push(`${a}${b}`);
  ok(eqSet(blind, ['09']), `ALGEBRAIC: Luhn's only transposition blind spot is {0,9} (got ${blind.join(',') || 'none'})`);
}

// (c) EXHAUSTIVE: over every valid 6-digit Luhn number, collect the single-error
// misses (must be zero) and the adjacent-swap blind pairs (must be exactly 09).
{
  let singleMiss = 0; const adjBlind = new Set();
  forEachValid(SCHEMES.luhn, 6, (full) => {
    singleMiss += undetectedSingles(full, luhnValid).length;
    for (const m of undetectedAdjacent(full, luhnValid)) adjBlind.add(`${Math.min(m.a, m.b)}${Math.max(m.a, m.b)}`);
  });
  ok(singleMiss === 0, 'EXHAUSTIVE (all valid 6-digit): Luhn misses no single-digit error');
  ok(eqSet([...adjBlind].sort(), ['09']), `EXHAUSTIVE: Luhn's adjacent blind pairs are exactly {09} (got ${[...adjBlind].sort().join(',')})`);
}

// (d) The headline gap, made concrete: build a valid card-length number holding
// an adjacent 0,9 and show the swap is invisible to Luhn.
{
  const pay = digits('123456789009876');            // 15 digits; contains "09"
  const full = [...pay, luhnCheck(pay)];
  const i = full.findIndex((d, k) => full[k] === 0 && full[k + 1] === 9);
  ok(i >= 0, 'demo Luhn number contains an adjacent 0 then 9');
  const swapped = full.slice(); [swapped[i], swapped[i + 1]] = [swapped[i + 1], swapped[i]];
  ok(luhnValid(full) && luhnValid(swapped), 'CONCRETE: swapping that 0<->9 leaves Luhn still valid (undetected)');
}

// ===========================================================================
console.log('\n2. ISBN-10 (mod 11, weights 10..1, X) — books');
// ---------------------------------------------------------------------------
ok(isbn10Valid(digits('0-306-40615-2')), 'real ISBN-10 0-306-40615-2 is valid');
ok(isbn10Check(digits('013468599')) === 7 && isbn10Valid(digits('0-13-468599-7')),
  'ISBN-10 0-13-468599-7 is valid (check digit computed, not recalled)');
// The X: a valid ISBN-10 whose check digit is 10, written X (the whole reason X exists).
ok(isbn10Check(digits('080442957')) === 10, 'payload 080442957 -> check digit 10 = X');
ok(isbn10Valid(digits('0-8044-2957-X')), 'CONCRETE: 0-8044-2957-X is a valid ISBN-10 ending in X');

// (a) ALGEBRAIC: single-digit errors all caught. A change at position k alters
// the weighted sum by w_k*(d'-d) mod 11; w_k in {1..10} is coprime to 11 and
// (d'-d) with digits 0..9 is never 0 mod 11 -> never zero.
ok([...Array(10)].every((_, k) => {                       // position weights 10..1
  const w = 10 - k;
  return [...Array(10)].every((_, d) => [...Array(10)].every((_, e) =>
    d === e || (w * (d - e)) % 11 !== 0));
}), 'ALGEBRAIC: every single-digit error changes the mod-11 sum (all caught)');

// (b) ALGEBRAIC: EVERY transposition is caught — not just adjacent ones —
// because 11 is prime. Swapping positions i,j (values a,b) changes the sum by
// (w_i - w_j)(a - b); distinct weights and prime modulus make it never 0.
{
  let allCaught = true;
  for (let i = 0; i < 10 && allCaught; i++) for (let j = i + 1; j < 10; j++) {
    const dw = (10 - i) - (10 - j);                        // = j - i, in 1..9
    for (let a = 0; a <= 9 && allCaught; a++) for (let b = a + 1; b <= 9; b++)
      if ((dw * (a - b)) % 11 === 0) { allCaught = false; break; }
  }
  ok(allCaught, 'ALGEBRAIC: ISBN-10 catches EVERY transposition of two distinct digits (prime modulus)');
}

// (c) RANDOM sweep at the real length 10: no single error and no adjacent swap
// (of distinct digits) slips through. 60k valid ISBN-10s, all probed.
{
  let sMiss = 0, aMiss = 0; const rng = lcg(2108);
  for (let n = 0; n < 60000; n++) {
    const p = [...Array(9)].map(() => rng.next().value % 10);
    const full = [...p, isbn10Check(p)];
    sMiss += undetectedSingles(full, isbn10Valid).length;
    aMiss += undetectedAdjacent(full, isbn10Valid).length;
  }
  ok(sMiss === 0 && aMiss === 0, 'RANDOM (60k valid ISBN-10s): misses no single error and no adjacent swap');
}

// (d) About 1 in 11 ISBN-10s ends in X — computed EXACTLY by DP over residues
// mod 11 (each of the 9 payload digits uniform on 0..9). It is NOT exactly 1/11:
// the digits run 0..9, not 0..10, so the check digit is only *nearly* uniform.
{
  const W = [10, 9, 8, 7, 6, 5, 4, 3, 2];                   // payload weights
  let dp = [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];              // counts of S mod 11
  for (const w of W) {
    const nx = new Array(11).fill(0);
    for (let r = 0; r < 11; r++) if (dp[r]) for (let d = 0; d <= 9; d++) nx[(r + w * d) % 11] += dp[r];
    dp = nx;
  }
  const total = 10 ** 9;                                    // exact integer (< 2^53)
  const xCount = dp[1];                                     // check=10 <=> S ≡ 1 (mod 11)
  // Exactly 90,909,090 of the billion 9-digit payloads need an X — one shy of a
  // perfect eleventh (residue 1 is the single short class; all others hold 90,909,091).
  ok(xCount === 90909090, `EXACT DP: exactly ${xCount.toLocaleString()} of ${total.toLocaleString()} ISBN-10s end in X`);
  ok(dp.filter((c) => c === 90909091).length === 10 && Math.abs(xCount / total - 1 / 11) < 1e-8,
    `EXACT DP: that is ${(xCount / total * 100).toFixed(6)}% — one shy of a perfect 1/11 (${(100 / 11).toFixed(6)}%)`);
}

// ===========================================================================
console.log('\n3. EAN-13 / UPC-A (mod 10, weights 1,3) — retail barcodes');
// ---------------------------------------------------------------------------
ok(ean13Valid(digits('5901234123457')), 'EAN-13 5901234123457 is valid');
ok(ean13Valid(digits('4006381333931')), 'EAN-13 4006381333931 is valid');
ok(ean13Check(digits('978030640615')) === 7, 'EAN-13 payload 978030640615 -> check 7 (ISBN-13 of the book above)');

// (a) ALGEBRAIC: all single-digit errors caught. Weight-1 positions change the
// sum by (d'-d); weight-3 positions by 3(d'-d); gcd(3,10)=1 so 3k=0 mod 10 only
// when k=0 -> never zero for d'!=d.
ok([1, 3].every((w) => [...Array(10)].every((_, d) => [...Array(10)].every((_, e) =>
  d === e || (w * (d - e)) % 10 !== 0))),
  'ALGEBRAIC: every single-digit error changes the mod-10 sum (all caught)');

// (b) ALGEBRAIC: an adjacent swap {a,b} slips through iff 2(a-b)=0 mod 10, i.e.
// |a-b| = 5. Blind pairs: {0,5},{1,6},{2,7},{3,8},{4,9}.
{
  const blind = [];
  for (let a = 0; a <= 9; a++) for (let b = a + 1; b <= 9; b++) if ((2 * (a - b)) % 10 === 0) blind.push(`${a}${b}`);
  ok(eqSet(blind, ['05', '16', '27', '38', '49']),
    `ALGEBRAIC: EAN-13's transposition blind spots are the five |a-b|=5 pairs (got ${blind.join(',')})`);
}

// (c) RANDOM sweep at the real length 13: no single error slips; the adjacent
// blind pairs collected across 60k valid barcodes are EXACTLY the five |a-b|=5.
{
  let sMiss = 0; const adjBlind = new Set(); const rng = lcg(13013);
  for (let n = 0; n < 60000; n++) {
    const p = [...Array(12)].map(() => rng.next().value % 10);
    const full = [...p, ean13Check(p)];
    sMiss += undetectedSingles(full, ean13Valid).length;
    for (const m of undetectedAdjacent(full, ean13Valid)) adjBlind.add(`${Math.min(m.a, m.b)}${Math.max(m.a, m.b)}`);
  }
  ok(sMiss === 0, 'RANDOM (60k valid EAN-13s): misses no single-digit error');
  ok(eqSet([...adjBlind].sort(), ['05', '16', '27', '38', '49']),
    `RANDOM: EAN-13's adjacent blind pairs are exactly the five |a-b|=5 pairs (got ${[...adjBlind].sort().join(',')})`);
}

// (d) CONCRETE: a ±5 adjacent swap that slides straight past a real barcode.
{
  const pay = digits('050505050505');                      // adjacent 0,5 differ by 5
  const full = [...pay, ean13Check(pay)];
  let i = -1;
  for (let k = 0; k + 1 < full.length; k++) if (Math.abs(full[k] - full[k + 1]) === 5) { i = k; break; }
  ok(i >= 0, 'demo EAN-13 contains an adjacent pair differing by 5');
  const sw = full.slice(); [sw[i], sw[i + 1]] = [sw[i + 1], sw[i]];
  ok(ean13Valid(full) && ean13Valid(sw), 'CONCRETE: swapping that ±5 pair leaves EAN-13 still valid (undetected)');
}

// ===========================================================================
console.log('\n4. VERHOEFF (dihedral D5) — the fix mod-10 cannot reach');
// ---------------------------------------------------------------------------
ok(verhoeffCheck(digits('236')) === 3, 'Verhoeff check of 236 is 3 (Wikipedia example)');
ok(verhoeffValid(digits('2363')), '2363 passes Verhoeff');
ok(!verhoeffValid(digits('2364')), 'a wrong Verhoeff check digit fails');

// (a) EXHAUSTIVE, all lengths 2..7: Verhoeff catches EVERY single-digit error and
// EVERY adjacent transposition of distinct digits — zero misses of either kind.
{
  let sMiss = 0, aMiss = 0, tested = 0;
  for (let len = 2; len <= 7; len++) {
    forEachValid({ check: verhoeffCheck, validate: verhoeffValid }, len, (full) => {
      sMiss += undetectedSingles(full, verhoeffValid).length;
      aMiss += undetectedAdjacent(full, verhoeffValid).length;
      tested++;
    });
  }
  ok(sMiss === 0, `EXHAUSTIVE (all valid numbers, len 2..7; ${tested.toLocaleString()} of them): Verhoeff misses NO single-digit error`);
  ok(aMiss === 0, 'EXHAUSTIVE (len 2..7): Verhoeff misses NO adjacent transposition');
}

// (b) RANDOM sweep at card length (16 digits): still zero misses of either kind.
{
  let sMiss = 0, aMiss = 0; const rng = lcg(424242);
  for (let n = 0; n < 40000; n++) {
    const pay = [...Array(15)].map(() => rng.next().value % 10);
    const full = [...pay, verhoeffCheck(pay)];
    sMiss += undetectedSingles(full, verhoeffValid).length;
    aMiss += undetectedAdjacent(full, verhoeffValid).length;
  }
  ok(sMiss === 0 && aMiss === 0, 'RANDOM (40k numbers, len 16): Verhoeff misses no single error and no adjacent swap');
}

// (c) THE HEADLINE, side by side: the same 0<->9 adjacent swap that Luhn cannot
// see, Verhoeff catches.
{
  const pay = digits('123456789009876');
  const luhnFull = [...pay, luhnCheck(pay)];
  const verFull = [...pay, verhoeffCheck(pay)];
  const iL = luhnFull.findIndex((d, k) => luhnFull[k] === 0 && luhnFull[k + 1] === 9);
  const iV = verFull.findIndex((d, k) => verFull[k] === 0 && verFull[k + 1] === 9);
  const sL = luhnFull.slice(); [sL[iL], sL[iL + 1]] = [sL[iL + 1], sL[iL]];
  const sV = verFull.slice(); [sV[iV], sV[iV + 1]] = [sV[iV + 1], sV[iV]];
  ok(luhnValid(sL), 'Luhn:     the 0<->9 swap stays valid  (miss)');
  ok(!verhoeffValid(sV), 'Verhoeff: the 0<->9 swap is rejected  (catch) — the headline');
}

// (d) HONEST LIMIT: Verhoeff is NOT perfect on every error type. It does not
// catch all "twin" errors (aa -> bb) or all jump transpositions. Show one real
// twin miss so the page can state the boundary truthfully.
{
  let twinMiss = 0, twinTested = 0; const rng = lcg(9001);
  for (let n = 0; n < 5000; n++) {
    const pay = [...Array(9)].map(() => rng.next().value % 10);
    const full = [...pay, verhoeffCheck(pay)];
    for (let i = 0; i + 1 < full.length; i++) {
      if (full[i] !== full[i + 1]) continue;               // need a twin aa
      for (let b = 0; b <= 9; b++) {
        if (b === full[i]) continue;
        const t = full.slice(); t[i] = b; t[i + 1] = b;    // aa -> bb
        twinTested++; if (verhoeffValid(t)) twinMiss++;
      }
    }
  }
  ok(twinMiss > 0, `HONEST LIMIT: Verhoeff lets some twin errors (aa->bb) through (${twinMiss} of ${twinTested} sampled) — single & adjacent are its guarantee, not everything`);
}

// ===========================================================================
console.log('\n4b. DAMM (2004, a totally anti-symmetric quasigroup) — Verhoeff\'s guarantee, ONE 10×10 table');
// ---------------------------------------------------------------------------
ok(dammCheck(digits('572')) === 4 && dammValid(digits('5724')), 'Damm check of 572 is 4 -> 5724 valid (Wikipedia example)');
ok(!dammValid(digits('5720')), 'a wrong Damm check digit fails');

// (a) THE ZERO-DIAGONAL PAYOFF: the check digit is literally the payload's running
// interim (dm r r = 0), so appending it always validates — no inverse lookup.
{
  const rng = lcg(2004); let mismatch = 0, badAppend = 0, tested = 0;
  for (let n = 0; n < 20000; n++) {
    const p = [...Array(1 + rng.next().value % 12)].map(() => rng.next().value % 10);
    if (dammCheck(p) !== dammSum(p)) mismatch++;         // the check IS the interim
    if (!dammValid([...p, dammCheck(p)])) badAppend++;   // appending it validates
    tested++;
  }
  ok(mismatch === 0, `GENERATION: Damm's check digit equals the payload's running interim over ${tested.toLocaleString()} numbers`);
  ok(badAppend === 0, 'GENERATION: appending that interim always validates (the zero-diagonal buys check-digit generation free)');
}

// (b) EXHAUSTIVE, all lengths 2..7: Damm catches EVERY single-digit error and
// EVERY adjacent transposition of distinct digits — zero misses of either kind,
// exactly like Verhoeff, but with no permutation power.
{
  let sMiss = 0, aMiss = 0, tested = 0;
  for (let len = 2; len <= 7; len++) {
    forEachValid({ check: dammCheck, validate: dammValid }, len, (full) => {
      sMiss += undetectedSingles(full, dammValid).length;
      aMiss += undetectedAdjacent(full, dammValid).length;
      tested++;
    });
  }
  ok(sMiss === 0, `EXHAUSTIVE (all valid numbers, len 2..7; ${tested.toLocaleString()} of them): Damm misses NO single-digit error`);
  ok(aMiss === 0, 'EXHAUSTIVE (len 2..7): Damm misses NO adjacent transposition — no blind pair at all');
}

// (c) RANDOM sweep at card length (16 digits): still zero misses of either kind.
{
  let sMiss = 0, aMiss = 0; const rng = lcg(20042004);
  for (let n = 0; n < 40000; n++) {
    const pay = [...Array(15)].map(() => rng.next().value % 10);
    const full = [...pay, dammCheck(pay)];
    sMiss += undetectedSingles(full, dammValid).length;
    aMiss += undetectedAdjacent(full, dammValid).length;
  }
  ok(sMiss === 0 && aMiss === 0, 'RANDOM (40k numbers, len 16): Damm misses no single error and no adjacent swap');
}

// (d) NO blind pairs at all, over the structural search (unlike Luhn's {0,9} and
// EAN-13's five |a-b|=5 pairs, and matching Verhoeff).
ok(transpositionBlindPairs(SCHEMES.damm).length === 0, 'STRUCTURAL: Damm has NO transposition blind pairs (matching Verhoeff, beating both mod-10 sums)');

// (e) THE HEADLINE, side by side: the same 0<->9 adjacent swap Luhn cannot see,
// Damm catches — with a single table where Verhoeff spent a group + 8 permutations.
{
  const pay = digits('123456789009876');
  const dFull = [...pay, dammCheck(pay)];
  const iD = dFull.findIndex((d, k) => dFull[k] === 0 && dFull[k + 1] === 9);
  ok(iD >= 0, 'demo Damm number contains an adjacent 0 then 9');
  const sD = dFull.slice(); [sD[iD], sD[iD + 1]] = [sD[iD + 1], sD[iD]];
  ok(!dammValid(sD), 'CONCRETE: Damm rejects the 0<->9 swap (catch) — the guarantee, from one 10×10 table');
}

// ===========================================================================
console.log('\n5. Cross-scheme blind-spot summary (the table the page quotes)');
// ---------------------------------------------------------------------------
const SUMMARY = {
  luhn:     { single: 'all caught', adjacent: 'all but 0↔9' },
  isbn10:   { single: 'all caught', adjacent: 'all caught (any distance)' },
  ean13:    { single: 'all caught', adjacent: 'misses the five |a-b|=5 swaps' },
  verhoeff: { single: 'all caught', adjacent: 'all caught (incl. 0↔9)' },
  damm:     { single: 'all caught', adjacent: 'all caught (incl. 0↔9), one table' },
};
ok(Object.keys(SUMMARY).length === 5, 'summary covers all five schemes');
console.log('   ' + JSON.stringify(SUMMARY));

// ===========================================================================
console.log('\n6. The kernel proof (Lean) — the guarantees, for EVERY length');
// ---------------------------------------------------------------------------
// The checks above pin each claim, but for the "all lengths" statements they can
// only SAMPLE: exhaustive over short numbers, a 60k sweep at real length, a named
// theorem for the rest. lean/CheckDigits.lean hands Lean's kernel the universal
// statement (zero imports). Here we (a) re-implement the Lean model in JS and
// prove it is the SAME scheme engine.mjs operates — model fidelity, never one
// path — and (b) when `lean` is on PATH, typecheck the file live and assert the
// [propext, Quot.sound] axiom footprint.

// (a) The Lean model, in JS: a checksum = sum of per-INDEX contributions g(i,d)
// over the digits held units-first (rightmost first). Validity = sum % m === 0.
// These g's mirror luhnG / isbnG / eanG in CheckDigits.lean exactly.
const gLuhn = (i, d) => (i % 2 === 1) ? luhnF(d) : d;
const gIsbn = (i, d) => (i + 1) * d;
const gEan  = (i, d) => (i % 2 === 1 ? 3 : 1) * d;
const modelValid = (g, m) => (ds) => {
  let s = 0;
  const uf = [...ds].reverse();                 // units-first
  for (let i = 0; i < uf.length; i++) s += g(i, uf[i]);
  return s % m === 0;
};
const luhnModel = modelValid(gLuhn, 10);
const isbnModel = modelValid(gIsbn, 11);
const eanModel  = modelValid(gEan, 10);

// Verhoeff's Lean model is NOT a sum mod m — it is the D5 group fold `vsum`
// (CheckDigits.lean section 4), digits held units-first: c starts at the identity
// 0 and c := D5[c][VP[i%8][digit]] at each position. Validity = the product is 0.
// Reimplemented here independently of engine.mjs's verhoeffSum, then proven equal.
const verhoeffModel = (ds) => {
  const uf = [...ds].reverse();                 // MSB-first -> units-first (Lean's List)
  let c = 0;
  for (let i = 0; i < uf.length; i++) c = D5[c][VP[i % 8][uf[i]]];
  return c === 0;
};

// Damm's Lean model is the fold `dsum` over the DAMM quasigroup (CheckDigits.lean
// section 5), digits in reading order (MSB first — no positional weighting, so no
// reversal). Reimplemented here independently of engine.mjs's dammSum, then proven
// equal over the sweep below.
const dammModel = (ds) => {
  let c = 0;
  for (let i = 0; i < ds.length; i++) c = DAMM[c][ds[i]];
  return c === 0;
};

// Fidelity on the page's own published test vectors.
ok(luhnModel(digits('4111 1111 1111 1111')) === luhnValid(digits('4111 1111 1111 1111'))
   && luhnModel(digits('4111 1111 1111 1111')),
   'MODEL=ENGINE: Lean Luhn model agrees on the Visa test PAN (and validates it)');
ok(isbnModel(digits('0-8044-2957-X')) === isbn10Valid(digits('0-8044-2957-X'))
   && isbnModel(digits('0-8044-2957-X')),
   'MODEL=ENGINE: Lean ISBN model agrees on 0-8044-2957-X (ending in X)');
ok(eanModel(digits('5901234123457')) === ean13Valid(digits('5901234123457'))
   && eanModel(digits('5901234123457')),
   'MODEL=ENGINE: Lean EAN-13 model agrees on 5901234123457');
ok(verhoeffModel(digits('2363')) === verhoeffValid(digits('2363')) && verhoeffModel(digits('2363')),
   'MODEL=ENGINE: Lean Verhoeff (D5) model agrees on 2363 (and validates it)');
ok(dammModel(digits('5724')) === dammValid(digits('5724')) && dammModel(digits('5724')),
   'MODEL=ENGINE: Lean Damm (quasigroup) model agrees on 5724 (and validates it)');

// Fidelity over a sweep: for each scheme, build valid numbers of many lengths and
// also corrupt them, and confirm the Lean model's verdict matches the engine's on
// EVERY number — valid and invalid alike. If the two ever disagreed, the proof
// would be about a different scheme than the page operates.
function* lcg2(seed) { let s = seed >>> 0; for (;;) { s = (1103515245 * s + 12345) >>> 0; yield s; } }
{
  let disagree = 0, tested = 0;
  const rng = lcg2(70719);
  const cases = [
    { model: luhnModel, valid: luhnValid, check: luhnCheck, lens: [2, 6, 10, 15, 16, 19] },
    { model: eanModel,  valid: ean13Valid, check: ean13Check, lens: [13] },
    { model: isbnModel, valid: isbn10Valid, check: isbn10Check, lens: [10] },
    { model: verhoeffModel, valid: verhoeffValid, check: verhoeffCheck, lens: [2, 6, 10, 16, 19] },
    { model: dammModel, valid: dammValid, check: dammCheck, lens: [2, 6, 10, 16, 19] },
  ];
  for (const c of cases) {
    for (const len of c.lens) {
      for (let n = 0; n < 4000; n++) {
        const pay = [...Array(len - 1)].map(() => rng.next().value % 10);
        const full = [...pay, c.check(pay)];
        // test the valid number and a random single corruption
        for (const num of [full, (() => { const t = full.slice(); t[rng.next().value % t.length] = rng.next().value % 10; return t; })()]) {
          tested++;
          if (c.model(num) !== c.valid(num)) disagree++;
        }
      }
    }
  }
  ok(disagree === 0, `MODEL=ENGINE: Lean model matches engine on all ${tested.toLocaleString()} swept numbers (valid & corrupted), 0 disagreements`);
}

// (b) The Lean file itself: present, states the theorems, no sorry / native_decide.
const leanFile = join(HERE, 'lean', 'CheckDigits.lean');
ok(existsSync(leanFile), 'Lean proof file present (lean/CheckDigits.lean)');
if (existsSync(leanFile)) {
  const src = readFileSync(leanFile, 'utf8');
  const wanted = [
    'csumFrom_split', 'luhn_single_detects', 'luhn_swap_detects', 'luhn_swap_blind',
    'isbn_single_detects', 'isbn_transposition_detects',
    'ean_single_detects', 'ean_swap_detects', 'ean_swap_blind',
    'vfold_append', 'vfold_factor', 'verhoeff_single_detects', 'verhoeff_transposition_detects',
    'dm_antisym', 'dfold_inj', 'damm_single_detects', 'damm_transposition_detects', 'damm_check_digit',
  ];
  for (const t of wanted) ok(new RegExp(`theorem ${t}\\b`).test(src), `Lean states theorem ${t}`);
  // strip prose (comments/strings) before scanning for a real sorry / native_decide
  const code = src.replace(/\/-[\s\S]*?-\//g, '').replace(/--[^\n]*/g, '');
  ok(!/\bsorry\b/.test(code) && !/native_decide/.test(code), 'Lean source has no sorry / native_decide');

  // The Damm table is maintained in TWO files (engine.mjs and CheckDigits.lean);
  // assert they are the SAME table, so the kernel proof is about the operated
  // scheme and not a differently-typed quasigroup.
  {
    const m = code.match(/def Drows[\s\S]*?:=\s*(\[[\s\S]*?\]\])/);
    ok(!!m, 'Lean Damm table (Drows) is present and parseable');
    if (m) {
      const leanTable = JSON.parse(m[1].replace(/\s+/g, ''));
      const same = leanTable.length === 10 && leanTable.every((row, i) =>
        row.length === 10 && row.every((v, j) => v === DAMM[i][j]));
      ok(same, 'Lean Drows table is byte-for-byte the engine.mjs DAMM table (proof matches the operated scheme)');
    }
  }

  const candidates = ['lean', join(homedir(), '.elan', 'bin', 'lean'), join(homedir(), '.nix-profile', 'bin', 'lean')];
  let leanBin = null;
  for (const c of candidates) {
    try { execSync(`${c} --version`, { stdio: 'ignore' }); leanBin = c; break; } catch { /* keep trying */ }
  }
  if (leanBin) {
    let out = '', typechecked = true;
    try {
      out = execSync(`${leanBin} ${JSON.stringify(leanFile)}`, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
    } catch (e) {
      out = (e.stdout || '') + (e.stderr || '');
      typechecked = false;
    }
    ok(typechecked, 'Lean typechecks with no errors' + (typechecked ? '' : ' — ' + out.split('\n').slice(0, 4).join(' | ')));
    const axiomLines = out.split('\n').filter((l) => /depends on axioms|does not depend on any axioms/.test(l));
    ok(axiomLines.length >= 10, `Lean emitted axiom footprints (${axiomLines.length} lines)`);
    const badAxiom = axiomLines.find((l) => /sorryAx|Classical\.choice/.test(l));
    ok(!badAxiom, 'every kernel theorem is [propext, Quot.sound] or tighter (no sorryAx, no Classical.choice)' + (badAxiom ? ' — ' + badAxiom : ''));
    for (const l of axiomLines) console.log('   ', l.trim());
  } else {
    console.log('  ..  lean not on PATH — model-fidelity + static checks only');
    console.log('      (run research/check-digits/lean/install-lean-nix.sh to typecheck the kernel proof)');
  }
}

// ---------------------------------------------------------------------------
console.log(`\n${fails === 0 ? '✓' : '✗'} ${checks - fails}/${checks} checks green`);
if (fails) { console.log(`${fails} FAILED`); process.exit(1); }
