// verify-someone-always-crosses.mjs: the arithmetic behind the stratum
// "Someone Always Crosses" (/strata/someone-always-crosses/).
//
// THE CLAIMS THE PAGE MAKES, AND WHAT THIS SCRIPT DOES ABOUT THEM
//
//  1. THE HEX THEOREM. Every complete two-colouring of an n x n Hex board contains
//     exactly one winning chain: never zero, never two. Checked here two ways.
//     (a) By exhaustion: all 2^(n*n) colourings for n = 1..4, i.e. 66,066 boards,
//         each searched in both directions. Under --full, also all 2^25 =
//         33,554,432 colourings of the 5x5 board. That loop is minutes, not
//         seconds: two timed runs under node v22 gave 191 s and 215 s total wall
//         clock, nearly all of it here. Hardware-dependent, so treat it as an
//         order of magnitude rather than a figure.
//     (b) By seeded census: 1,000 random fills of the 11x11 board (the size Piet
//         Hein introduced in 1942), reproducing the page's numbers exactly,
//         because the page and this file use the same mulberry32 stream.
//
//  2. NASH'S STRATEGY STEALING. The argument is nonconstructive: it proves the
//     FIRST player wins and names no move. Its load-bearing step is that in Hex
//     an extra stone of your own colour is never a liability. That step is
//     checked here by exhaustion over every 3x3 position, in both directions.
//     The conclusion is checked by full game-tree search on 3x3 and 4x4, which
//     also reports exactly which openings win. (Both are things the page runs in
//     the browser; the search code is byte-identical, so node counts agree.)
//
//  3. GALE 1979. The Hex theorem is equivalent to the two-dimensional Brouwer
//     fixed-point theorem. The page runs the Hex -> Brouwer direction as an
//     algorithm: colour each cell of a fine Hex board by whether the map pushes
//     it more sideways than up-down, take the forced winning chain, and find the
//     neighbouring pair on it where the relevant displacement coordinate changes
//     sign. That cell has |f(x) - x| <= omega*sqrt(2), where omega is the largest
//     change in either displacement coordinate between neighbouring cells.
//     Verified here:
//       - the guarantee holds at every board size on the page's ladder;
//       - it holds in 1,600 randomly drawn cases (400 maps x 4 board sizes);
//       - every one of those 1,600 boards has exactly one winner;
//       - the Lipschitz bound, the Banach reference x*, and, at swirl = 0, the
//         closed-form fixed point x* = c + (I - sR)^-1 t, all agree.
//
//   run:  node research/someone-always-crosses/verify-someone-always-crosses.mjs
//         node research/someone-always-crosses/verify-someone-always-crosses.mjs --full
//
// No dependencies. Every number the page displays is recomputed here from scratch.

const FULL = process.argv.includes('--full');

let fails = 0;
const ok = (name, cond, extra = '') => {
  if (!cond) fails++;
  console.log(`${cond ? '  ok' : 'FAIL'}  ${name}${extra ? '   ' + extra : ''}`);
};
const near = (a, b, eps) => Math.abs(a - b) <= eps;
const commas = (n) => Number(n).toLocaleString('en-US');

// ── shared Hex machinery (identical to the page's) ──────────────────────────
const NB = [[0, -1], [0, 1], [-1, 0], [1, 0], [-1, 1], [1, -1]];
const AMB = 1;   // amber joins row 0 to row n-1
const TEA = 2;   // teal  joins col 0 to col n-1

function connected(board, n, player) {
  const seen = new Uint8Array(n * n), stack = [];
  if (player === AMB) { for (let c = 0; c < n; c++) if (board[c] === AMB) { seen[c] = 1; stack.push(c); } }
  else { for (let r = 0; r < n; r++) { const i = r * n; if (board[i] === TEA) { seen[i] = 1; stack.push(i); } } }
  while (stack.length) {
    const i = stack.pop(), r = (i / n) | 0, c = i % n;
    if (player === AMB && r === n - 1) return true;
    if (player === TEA && c === n - 1) return true;
    for (const [dr, dc] of NB) {
      const rr = r + dr, cc = c + dc;
      if (rr < 0 || cc < 0 || rr >= n || cc >= n) continue;
      const j = rr * n + cc;
      if (!seen[j] && board[j] === player) { seen[j] = 1; stack.push(j); }
    }
  }
  return false;
}

function winningChain(board, n, player) {
  const par = new Int32Array(n * n).fill(-1), seen = new Uint8Array(n * n), q = [];
  if (player === AMB) { for (let c = 0; c < n; c++) if (board[c] === AMB) { seen[c] = 1; q.push(c); } }
  else { for (let r = 0; r < n; r++) { const i = r * n; if (board[i] === TEA) { seen[i] = 1; q.push(i); } } }
  let head = 0;
  while (head < q.length) {
    const i = q[head++], r = (i / n) | 0, c = i % n;
    if ((player === AMB && r === n - 1) || (player === TEA && c === n - 1)) {
      const path = []; let t = i;
      while (t !== -1) { path.push(t); t = par[t]; }
      return path.reverse();
    }
    for (const [dr, dc] of NB) {
      const rr = r + dr, cc = c + dc;
      if (rr < 0 || cc < 0 || rr >= n || cc >= n) continue;
      const j = rr * n + cc;
      if (!seen[j] && board[j] === player) { seen[j] = 1; par[j] = i; q.push(j); }
    }
  }
  return null;
}

function mulberry32(a) {
  return function () {
    a |= 0; a = a + 0x6D2B79F5 | 0;
    let t = Math.imul(a ^ a >>> 15, 1 | a);
    t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t;
    return ((t ^ t >>> 14) >>> 0) / 4294967296;
  };
}

// ── 1a. exhaustion: every complete colouring, n = 1..4 ──────────────────────
console.log('\n·· the Hex theorem by exhaustion: every complete colouring ··');
function exhaust(n) {
  const N = n * n, total = 2 ** N, b = new Int8Array(N);
  let one = 0, none = 0, both = 0, amber = 0;
  for (let m = 0; m < total; m++) {
    for (let i = 0; i < N; i++) b[i] = (m >>> i) & 1 ? AMB : TEA;
    const ca = connected(b, n, AMB), ct = connected(b, n, TEA);
    if (ca && ct) both++;
    else if (!ca && !ct) none++;
    else { one++; if (ca) amber++; }
  }
  return { n, total, one, none, both, amber };
}
{
  const expect = { 1: 2, 2: 16, 3: 512, 4: 65536 };
  let tot = 0, one = 0, none = 0, both = 0, amber = 0;
  for (let n = 1; n <= 4; n++) {
    const R = exhaust(n);
    tot += R.total; one += R.one; none += R.none; both += R.both; amber += R.amber;
    ok(`${n}x${n}: ${commas(R.total)} colourings, all with exactly one winner`,
       R.total === expect[n] && R.one === R.total && R.none === 0 && R.both === 0,
       `draws=${R.none} both=${R.both} amber=${commas(R.amber)}`);
    ok(`${n}x${n}: amber takes exactly half (transposing a board swaps the players)`,
       R.amber * 2 === R.total, `${commas(R.amber)} of ${commas(R.total)}`);
  }
  ok('page total: 66,066 complete boards, 0 draws, 0 double wins',
     tot === 66066 && one === 66066 && none === 0 && both === 0,
     `${commas(tot)} boards`);
  ok('page total: amber wins 33,033 of them', amber === 33033, `${commas(amber)}`);
}

// ── 1a'. the 5x5 exhaustion (opt-in; the page states this figure as offline) ─
if (FULL) {
  console.log('\n·· all 2^25 = 33,554,432 colourings of the 5x5 board (this takes a while) ··');
  const n = 5, N = 25, total = 2 ** 25, b = new Int8Array(N);
  let one = 0, none = 0, both = 0, amber = 0;
  for (let m = 0; m < total; m++) {
    for (let i = 0; i < N; i++) b[i] = (m >>> i) & 1 ? AMB : TEA;
    const ca = connected(b, n, AMB), ct = connected(b, n, TEA);
    if (ca && ct) both++;
    else if (!ca && !ct) none++;
    else { one++; if (ca) amber++; }
  }
  ok('5x5: all 33,554,432 colourings have exactly one winner',
     one === total && none === 0 && both === 0, `draws=${none} both=${both}`);
  ok('5x5: amber wins exactly half (16,777,216)', amber === total / 2, `${commas(amber)}`);
} else {
  console.log('\n·· 5x5 exhaustion skipped (pass --full to run all 33,554,432 boards) ··');
}

// ── 1b. the seeded census the page runs on load ─────────────────────────────
console.log('\n·· the census: 1,000 random 11x11 fills, seed 20260720 ··');
function census(seed, trials, n) {
  const N = n * n, b = new Int8Array(N), rnd = mulberry32(seed | 0);
  let one = 0, none = 0, both = 0, amber = 0, teal = 0;
  for (let t = 0; t < trials; t++) {
    for (let i = 0; i < N; i++) b[i] = rnd() < 0.5 ? AMB : TEA;
    const ca = connected(b, n, AMB), ct = connected(b, n, TEA);
    if (ca && ct) both++;
    else if (!ca && !ct) none++;
    else { one++; if (ca) amber++; else teal++; }
  }
  return { one, none, both, amber, teal, trials };
}
{
  const R = census(20260720, 1000, 11);
  console.log(`  one=${R.one} draws=${R.none} both=${R.both} amber=${R.amber} teal=${R.teal}`);
  ok('1,000 of 1,000 boards had exactly one winner', R.one === 1000);
  ok('0 draws, 0 double wins', R.none === 0 && R.both === 0);
  ok('the page shows amber 498 / teal 502 at this seed',
     R.amber === 498 && R.teal === 502, `${R.amber}/${R.teal}`);
  // three other seeds, to show the result is not a property of the seed
  for (const s of [1, 42, 987654321]) {
    const Q = census(s, 1000, 11);
    ok(`seed ${s}: 1000/1000 exactly one winner`, Q.one === 1000 && Q.none === 0 && Q.both === 0,
       `amber=${Q.amber} teal=${Q.teal}`);
  }
  ok('the board Piet Hein published in 1942 is 11x11 = 121 cells', 11 * 11 === 121);
}

// ── 2. the small-board solver (byte-identical to the page's) ────────────────
console.log('\n·· full game-tree search on small boards ··');
function mkAdj(n) {
  const A = new Array(n * n).fill(0);
  for (let r = 0; r < n; r++) for (let c = 0; c < n; c++) {
    let m = 0;
    for (const [dr, dc] of NB) {
      const rr = r + dr, cc = c + dc;
      if (rr >= 0 && cc >= 0 && rr < n && cc < n) m |= 1 << (rr * n + cc);
    }
    A[r * n + c] = m;
  }
  return A;
}
function winsMask(mask, n, A, player) {
  let front = 0;
  if (player === AMB) { for (let c = 0; c < n; c++) if (mask >>> c & 1) front |= 1 << c; }
  else { for (let r = 0; r < n; r++) if (mask >>> (r * n) & 1) front |= 1 << (r * n); }
  let seen = front;
  while (front) {
    let nf = 0, f = front;
    while (f) {
      const b = f & -f, i = 31 - Math.clz32(b); f ^= b;
      const rr = (i / n) | 0, cc = i % n;
      if (player === AMB && rr === n - 1) return true;
      if (player === TEA && cc === n - 1) return true;
      nf |= A[i] & mask & ~seen;
    }
    seen |= nf; front = nf;
  }
  return false;
}
function makeSolver(n) {
  const A = mkAdj(n), MASK = (1 << (n * n)) - 1, SH = 2 ** (n * n);
  const order = [];
  for (let i = 0; i < n * n; i++) order.push(i);
  const key = (j) => { const r = (j / n) | 0, c = j % n; return Math.abs(r + c - (n - 1)) * 10 + Math.abs(r - c); };
  order.sort((a, b) => key(a) - key(b));
  const memo = new Map();
  let nodes = 0;
  function rec(ma, mt, toMove) {
    nodes++;
    const k = (ma * SH + mt) * 2 + (toMove - 1), g = memo.get(k);
    if (g !== undefined) return g;
    const empty = MASK & ~ma & ~mt;
    let res = false;
    for (const idx of order) {
      const b = 1 << idx;
      if (!(empty & b)) continue;
      if (toMove === AMB) {
        const nma = ma | b;
        if (winsMask(nma, n, A, AMB)) { res = true; break; }
        if (!rec(nma, mt, TEA)) { res = true; break; }
      } else {
        const nmt = mt | b;
        if (winsMask(nmt, n, A, TEA)) { res = true; break; }
        if (!rec(ma, nmt, AMB)) { res = true; break; }
      }
    }
    memo.set(k, res); return res;
  }
  return {
    n, A, order,
    toMoveWins(ma, mt, toMove) {
      if (winsMask(ma, n, A, AMB)) return toMove === AMB;
      if (winsMask(mt, n, A, TEA)) return toMove === TEA;
      return rec(ma, mt, toMove);
    },
    solveOpenings() {
      const wins = [];
      for (const idx of order) {
        const b = 1 << idx;
        if (winsMask(b, n, A, AMB) || !rec(b, 0, TEA)) wins.push(idx);
      }
      wins.sort((x, y) => x - y);
      return { wins, nodes, memo: memo.size };
    },
  };
}
{
  const S3 = makeSolver(3).solveOpenings();
  console.log(`  3x3 winning openings: ${JSON.stringify(S3.wins)}  nodes=${commas(S3.nodes)} memo=${commas(S3.memo)}`);
  ok('3x3: the first player wins', S3.wins.length > 0);
  ok('3x3: exactly 5 of the 9 openings win, and they are [2,3,4,5,6]',
     S3.wins.length === 5 && S3.wins.join(',') === '2,3,4,5,6');
  ok('3x3: the page shows 1,540 search nodes and 998 memoised positions',
     S3.nodes === 1540 && S3.memo === 998, `${commas(S3.nodes)} / ${commas(S3.memo)}`);

  const S4 = makeSolver(4).solveOpenings();
  console.log(`  4x4 winning openings: ${JSON.stringify(S4.wins)}  nodes=${commas(S4.nodes)} memo=${commas(S4.memo)}`);
  ok('4x4: the first player wins', S4.wins.length > 0);
  ok('4x4: exactly 4 openings win, and they are precisely the short diagonal',
     S4.wins.length === 4 && S4.wins.every((i) => ((i / 4) | 0) + (i % 4) === 3),
     JSON.stringify(S4.wins));
  ok('4x4: the page shows 749,217 search nodes and 337,356 memoised positions',
     S4.nodes === 749217 && S4.memo === 337356, `${commas(S4.nodes)} / ${commas(S4.memo)}`);
}

// ── 2'. an extra stone never hurts (the load-bearing step of strategy stealing) ─
console.log('\n·· monotonicity: adding a friendly stone never loses a won 3x3 position ··');
{
  const n = 3, N = 9, MASK = (1 << N) - 1, S = makeSolver(n);
  const winnerOf = (ma, mt, tm) => (S.toMoveWins(ma, mt, tm) ? tm : (tm === AMB ? TEA : AMB));
  let testedA = 0, violA = 0, testedT = 0, violT = 0;
  for (let ma = 0; ma <= MASK; ma++) for (let mt = 0; mt <= MASK; mt++) {
    if (ma & mt) continue;
    for (const tm of [AMB, TEA]) {
      const empty = MASK & ~ma & ~mt;
      if (winnerOf(ma, mt, tm) === AMB) {
        for (let i = 0; i < N; i++) { const b = 1 << i; if (!(empty & b)) continue; testedA++;
          if (winnerOf(ma | b, mt, tm) !== AMB) violA++; }
      }
      if (winnerOf(ma, mt, tm) === TEA) {
        for (let i = 0; i < N; i++) { const b = 1 << i; if (!(empty & b)) continue; testedT++;
          if (winnerOf(ma, mt | b, tm) !== TEA) violT++; }
      }
    }
  }
  ok('the page shows 59,049 amber tests and 59,049 teal tests',
     testedA === 59049 && testedT === 59049, `${commas(testedA)} / ${commas(testedT)}`);
  ok('violations: 0 in both directions', violA === 0 && violT === 0, `${violA} / ${violT}`);
}

// ── 3. Gale: the Hex board as a fixed-point finder ──────────────────────────
console.log('\n·· Gale 1979: the Hex theorem run as an approximate-fixed-point algorithm ··');
const CX = 0.5, CY = 0.5;
function makeMap(p) {
  return function (x, y) {
    const ux = x - CX, uy = y - CY, r = Math.hypot(ux, uy);
    const a = p.th + p.w * r, ca = Math.cos(a), sa = Math.sin(a);
    const gx = CX + p.s * (ca * ux - sa * uy) + p.tx;
    const gy = CY + p.s * (sa * ux + ca * uy) + p.ty;
    return [Math.min(1, Math.max(0, gx)), Math.min(1, Math.max(0, gy))];
  };
}
// Lipschitz bound. In polar coordinates about the centre, the swirl part sends
// r*e^(i phi) to r*e^(i(phi + th + w r)); in the orthonormal (e_r, e_phi) frame its
// derivative is [[1,0],[a,1]] with a = w*r, and |x - c| <= sqrt(2)/2 on the square.
// The operator norm of [[1,0],[a,1]] is sqrt of the larger eigenvalue of M^T M,
// whose trace is 2 + a^2 and determinant 1.
function lipschitz(p) {
  const a = Math.abs(p.w) * Math.SQRT1_2, q = 2 + a * a;
  return Math.abs(p.s) * Math.sqrt((q + Math.sqrt(q * q - 4)) / 2);
}
function banach(p) {
  const f = makeMap(p);
  let x = CX, y = CY, q;
  for (let k = 0; k < 500; k++) { q = f(x, y); x = q[0]; y = q[1]; }
  q = f(x, y);
  const step = Math.hypot(q[0] - x, q[1] - y), L = lipschitz(p);
  return { x, y, step, bound: L < 1 ? L / (1 - L) * step : NaN, L, certified: L < 1 };
}
function galeRun(p, n) {
  const f = makeMap(p), color = new Int8Array(n * n), D = new Float64Array(n * n * 2);
  for (let r = 0; r < n; r++) for (let c = 0; c < n; c++) {
    const x = c / (n - 1), y = 1 - r / (n - 1), q = f(x, y), i = r * n + c;
    D[2 * i] = q[0] - x; D[2 * i + 1] = q[1] - y;
    color[i] = Math.abs(D[2 * i]) >= Math.abs(D[2 * i + 1]) ? TEA : AMB;   // ties -> teal
  }
  const pa = winningChain(color, n, AMB), pt = winningChain(color, n, TEA);
  const winners = (pa ? 1 : 0) + (pt ? 1 : 0);
  const path = pa || pt, ci = pa ? 1 : 0, win = pa ? AMB : TEA;
  let hit = null;
  for (let k = 0; k + 1 < path.length; k++) {
    const u = path[k], v = path[k + 1], du = D[2 * u + ci], dv = D[2 * v + ci];
    if ((du >= 0 && dv <= 0) || (du <= 0 && dv >= 0)) {
      const mu = Math.hypot(D[2 * u], D[2 * u + 1]), mv = Math.hypot(D[2 * v], D[2 * v + 1]);
      hit = mu <= mv ? { i: u, m: mu } : { i: v, m: mv };
      break;
    }
  }
  if (!hit) {
    hit = { i: path[0], m: Math.hypot(D[2 * path[0]], D[2 * path[0] + 1]) };
    for (let k = 1; k < path.length; k++) {
      const mk = Math.hypot(D[2 * path[k]], D[2 * path[k] + 1]);
      if (mk < hit.m) hit = { i: path[k], m: mk };
    }
  }
  let om = 0;
  for (let r = 0; r < n; r++) for (let c = 0; c < n; c++) {
    const i = r * n + c;
    for (const [dr, dc] of NB) {
      const rr = r + dr, cc = c + dc;
      if (rr < 0 || cc < 0 || rr >= n || cc >= n) continue;
      const j = rr * n + cc;
      om = Math.max(om, Math.abs(D[2 * i] - D[2 * j]), Math.abs(D[2 * i + 1] - D[2 * j + 1]));
    }
  }
  return { n, winners, win, hit, hx: (hit.i % n) / (n - 1), hy: 1 - (((hit.i / n) | 0) / (n - 1)),
           resid: hit.m, omega: om, bound: om * Math.SQRT2 };
}

const P_DEFAULT = { th: 2.20, s: 0.55, w: 0.90, tx: 0.12, ty: -0.07 };
const LADDER = [5, 9, 17, 33, 61, 101, 151, 201];
{
  const ref = banach(P_DEFAULT);
  ok('default map: Lipschitz bound L = 0.752181 (< 1, so the fixed point is unique)',
     near(ref.L, 0.752181454543593, 1e-12) && ref.certified, `L=${ref.L}`);
  ok('default map: certified reference x* = (0.594990369, 0.477508451)',
     near(ref.x, 0.5949903688620901, 1e-12) && near(ref.y, 0.47750845118137136, 1e-12),
     `(${ref.x.toFixed(9)}, ${ref.y.toFixed(9)})`);
  const f = makeMap(P_DEFAULT), q = f(ref.x, ref.y);
  ok('x* really is fixed: |f(x*) - x*| below 1e-12',
     Math.hypot(q[0] - ref.x, q[1] - ref.y) < 1e-12,
     `${Math.hypot(q[0] - ref.x, q[1] - ref.y).toExponential(2)}`);

  console.log('\n  n   winner  cornered point            residual     guarantee    dist to x*');
  const rows = LADDER.map((n) => {
    const R = galeRun(P_DEFAULT, n);
    const dist = Math.hypot(R.hx - ref.x, R.hy - ref.y);
    console.log(`  ${String(n).padStart(3)}  ${R.win === AMB ? 'amber' : 'teal '}   ` +
      `(${R.hx.toFixed(6)}, ${R.hy.toFixed(6)})   ${R.resid.toExponential(3)}   ` +
      `${R.bound.toExponential(3)}   ${dist.toExponential(3)}`);
    return { ...R, dist };
  });
  ok('every board on the ladder has exactly one winner', rows.every((r) => r.winners === 1));
  ok('the residual is at or below the guarantee omega*sqrt(2) at every board size',
     rows.every((r) => r.resid <= r.bound + 1e-12));
  ok('the guarantee shrinks monotonically as the board is refined',
     rows.every((r, i) => i === 0 || r.bound < rows[i - 1].bound));
  ok('the guarantee at n=201 is below 1.4e-2', rows[7].bound < 1.4e-2, rows[7].bound.toExponential(3));

  // the page claims the guarantee halves across the mesh doublings, and prints the
  // measured ratios. Only four ladder pairs are doublings; check exactly those.
  const dbl = [];
  for (let a = 0; a < rows.length; a++) for (let b = a + 1; b < rows.length; b++)
    if (rows[b].n - 1 === 2 * (rows[a].n - 1)) dbl.push([rows[a].n, rows[b].n, rows[a].bound / rows[b].bound]);
  ok('exactly four ladder pairs are mesh doublings (5->9, 9->17, 17->33, 101->201)',
     dbl.length === 4 && dbl.map((d) => d[0] + '->' + d[1]).join(',') === '5->9,9->17,17->33,101->201',
     dbl.map((d) => d[0] + '->' + d[1]).join(', '));
  ok('the guarantee halves across every mesh doubling (ratio within 1.9 to 2.1)',
     dbl.every((d) => d[2] > 1.9 && d[2] < 2.1),
     dbl.map((d) => `${d[0]}->${d[1]}: ${d[2].toFixed(3)}`).join(', '));

  // the two numbers the page prints for its default board size, n = 61
  const R61 = rows[LADDER.indexOf(61)];
  ok('page default n=61: winner is teal, residual 1.1123e-2',
     R61.win === TEA && near(R61.resid, 1.1122689e-2, 1e-8), R61.resid.toExponential(4));
  ok('page default n=61: guarantee 4.4156e-2', near(R61.bound, 4.4156217e-2, 1e-8), R61.bound.toExponential(4));
  ok('page default n=61: distance from the Hex point to x* is 7.6828e-3',
     near(R61.dist, 7.682816e-3, 1e-8), R61.dist.toExponential(4));
  ok('page default n=61: the cornered point is (0.600000, 0.483333)',
     near(R61.hx, 0.6, 1e-12) && near(R61.hy, 29 / 60, 1e-12),
     `(${R61.hx.toFixed(6)}, ${R61.hy.toFixed(6)})`);
}

// ── 3'. the swirl = 0 preset, where the fixed point has a closed form ───────
console.log('\n·· the pure-rotation preset: Banach iterate vs closed-form algebra ··');
{
  const P = { th: 2.20, s: 0.55, w: 0, tx: 0.12, ty: -0.07 };
  // f(x) = c + sR(x - c) + t  =>  x* = c + (I - sR)^-1 t
  const s = P.s, th = P.th, a = 1 - s * Math.cos(th), b = s * Math.sin(th), det = a * a + b * b;
  const fx = CX + (a * P.tx - b * P.ty) / det, fy = CY + (b * P.tx + a * P.ty) / det;
  const ref = banach(P);
  const d = Math.hypot(fx - ref.x, fy - ref.y);
  console.log(`  closed form (${fx.toFixed(12)}, ${fy.toFixed(12)})`);
  console.log(`  Banach      (${ref.x.toFixed(12)}, ${ref.y.toFixed(12)})`);
  ok('closed form and Banach iterate agree to 1e-15', d <= 1e-15, `diff=${d.toExponential(2)}`);
  ok('the closed-form fixed point lies inside the square (so clamping does not move it)',
     fx > 0 && fx < 1 && fy > 0 && fy < 1, `(${fx.toFixed(6)}, ${fy.toFixed(6)})`);
  const R = galeRun(P, 61);
  ok('the Hex construction finds it too, within the guarantee',
     R.resid <= R.bound + 1e-12 && Math.hypot(R.hx - fx, R.hy - fy) < R.bound,
     `resid=${R.resid.toExponential(3)} dist=${Math.hypot(R.hx - fx, R.hy - fy).toExponential(3)}`);
}

// ── 3''. the 1,600-case stress test the page runs on request ────────────────
console.log('\n·· stress: 400 randomly drawn maps x 4 board sizes ··');
{
  let s = 7 >>> 0;
  const rng = () => { s = (Math.imul(s, 1664525) + 1013904223) >>> 0; return s / 4294967296; };
  let cases = 0, winnerFail = 0, boundFail = 0, worstSlack = Infinity;
  for (let t = 0; t < 400; t++) {
    const p = { th: rng() * 6.283185307179586, s: 0.2 + rng() * 0.75, w: rng() * 4 - 2,
                tx: (rng() - 0.5) * 0.5, ty: (rng() - 0.5) * 0.5 };
    for (const n of [7, 13, 29, 61]) {
      const R = galeRun(p, n); cases++;
      if (R.winners !== 1) winnerFail++;
      if (!(R.resid <= R.bound + 1e-12)) boundFail++;
      worstSlack = Math.min(worstSlack, R.bound - R.resid);
    }
  }
  ok('the page shows 1,600 cases', cases === 1600, `${commas(cases)}`);
  ok('every one of them has exactly one winning chain', winnerFail === 0, `${winnerFail} failures`);
  ok('every residual sits at or below its guarantee', boundFail === 0,
     `tightest slack observed ${worstSlack.toExponential(2)}`);
}

// ── 3'''. the construction's colouring rule is a genuine 2-colouring ────────
console.log('\n·· the colouring rule assigns every cell exactly one colour ··');
{
  const R = galeRun(P_DEFAULT, 61);
  ok('a cell is teal iff |d1| >= |d2|, so the tie case is decided and no cell is left blank',
     R.winners === 1);
  // a map with a genuine tie region: the identity's displacement is exactly (0,0) everywhere
  const ident = { th: 0, s: 1, w: 0, tx: 0, ty: 0 };
  const I = galeRun(ident, 21);
  ok('the identity map (all displacements exactly zero) still yields exactly one winner',
     I.winners === 1, `winner=${I.win === AMB ? 'amber' : 'teal'} resid=${I.resid}`);
  ok('and its residual is exactly 0 (every point is fixed)', I.resid === 0);
}

console.log(`\n${fails === 0 ? 'ALL CHECKS PASSED' : fails + ' CHECK(S) FAILED'}`);
console.log(FULL ? '' : '(run with --full to add the 33,554,432-board 5x5 exhaustion)\n');
process.exit(fails === 0 ? 0 : 1);
