#!/usr/bin/env node
// Verifier for the stratum "The Most Irrational Number"
//   page: public/strata/most-irrational/index.html
//   live: https://artwaste.land/strata/most-irrational/
//
// Checks every numerical claim the page makes — the continued fractions on the
// picker, the Hurwitz/√5 sense in which φ is "the most irrational number", the
// golden angle, the spoke counts, and the Fibonacci parastichy numbers — so the
// page's promise ("every figure exact and checkable") is something you can run.
//
// This verifier was added by a later instance (2026-06-18) as an honesty pass on
// an early stratum that shipped before the show-the-check discipline was routine.
// It also caught one real error in the prose, fixed in the same pass: 355/113
// matches π to SIX decimal places (seven significant figures), not seven decimal
// places as the page originally said.
//
// Run:  node research/most-irrational/verify.mjs
// Exit: 0 if every check passes, 1 otherwise.  No dependencies (Node 18+).

let pass = 0, fail = 0;
function check(label, cond, got) {
  if (cond) { pass++; console.log(`  ok   ${label}`); }
  else { fail++; console.log(`  FAIL ${label}` + (got !== undefined ? `  (got: ${got})` : "")); }
}
function approx(a, b, tol) { return Math.abs(a - b) <= tol; }

const sqrt5 = Math.sqrt(5);
const PHI = (1 + sqrt5) / 2;

// --- continued-fraction machinery --------------------------------------------
// CF of a real value (Euclidean / Gauss map), good for as many terms as double
// precision supports — comfortably past every entry the page displays.
function cfOf(x, n) {
  const a = [];
  for (let i = 0; i < n; i++) {
    const ai = Math.floor(x);
    a.push(ai);
    const frac = x - ai;
    if (frac < 1e-12) break;
    x = 1 / frac;
  }
  return a;
}
// Convergents p_k/q_k of a CF as exact BigInt pairs.
function convergents(a) {
  let hm1 = 1n, hm2 = 0n, km1 = 0n, km2 = 1n;
  const out = [];
  for (const ai of a) {
    const A = BigInt(ai);
    const h = A * hm1 + hm2, k = A * km1 + km2;
    out.push([h, k]);
    hm2 = hm1; hm1 = h; km2 = km1; km1 = k;
  }
  return out;
}

console.log("\nI · A number's true name — the continued fractions on the picker");

// φ = [1; 1, 1, 1, …], solves x = 1 + 1/x, equals (1+√5)/2
{
  const cf = cfOf(PHI, 16);
  check("φ's continued fraction is all 1s", cf.length >= 12 && cf.slice(0, 12).every(t => t === 1), cf.slice(0, 6).join(","));
  // x = 1 + 1/x  ⇒  x² − x − 1 = 0  ⇒  PHI satisfies it
  check("φ solves x = 1 + 1/x", approx(PHI, 1 + 1 / PHI, 1e-15));
  check("φ = (1+√5)/2 ≈ 1.6180339887", approx(PHI, 1.6180339887, 1e-9), PHI.toFixed(10));
}

// φ's convergents are ratios of consecutive Fibonacci numbers
{
  const cv = convergents(Array(12).fill(1));
  const fib = [1n, 1n, 2n, 3n, 5n, 8n, 13n, 21n, 34n, 55n, 89n, 144n, 233n];
  // convergent k is F_{k+2}/F_{k+1}: 1/1, 2/1, 3/2, 5/3, 8/5, 13/8, …
  const want = [[1n, 1n], [2n, 1n], [3n, 2n], [5n, 3n], [8n, 5n], [13n, 8n]];
  let okFib = true;
  for (let i = 0; i < want.length; i++) if (cv[i][0] !== want[i][0] || cv[i][1] !== want[i][1]) okFib = false;
  check("φ's convergents are consecutive Fibonacci ratios (1/1,2/1,3/2,5/3,8/5,13/8)", okFib,
        cv.slice(0, 6).map(([h, k]) => `${h}/${k}`).join(" "));
}

// π = [3; 7, 15, 1, 292, …]; 355/113 is the convergent right before the big entry
{
  const cf = cfOf(Math.PI, 6);
  check("π's continued fraction begins [3; 7, 15, 1, 292]", cf.slice(0, 5).join(",") === "3,7,15,1,292", cf.slice(0, 5).join(","));
  const cv = convergents([3, 7, 15, 1]); // last convergent before the 292 entry
  const [h, k] = cv[cv.length - 1];
  check("the convergent before π's big entry (292) is 355/113", h === 355n && k === 113n, `${h}/${k}`);
}

console.log("\n  · the correction: how good is 355/113, exactly?");
{
  const a = 355 / 113;
  const err = Math.abs(Math.PI - a);
  check("355/113 − π error ≈ 2.67e-7", approx(err, 2.6676e-7, 1e-10), err.toExponential(4));
  // rounding to N decimals: do they agree?
  check("355/113 matches π to SIX decimal places", Math.PI.toFixed(6) === a.toFixed(6),
        `π=${Math.PI.toFixed(6)} vs ${a.toFixed(6)}`);
  check("355/113 does NOT match π to seven decimal places (page originally said it did)",
        Math.PI.toFixed(7) !== a.toFixed(7), `π=${Math.PI.toFixed(7)} vs ${a.toFixed(7)}`);
  // seven significant figures: 3.141592 (both); the 8th differs (6 vs 9)
  const sig7 = x => x.toPrecision(7);
  check("355/113 agrees with π to seven significant figures (3.141592)", sig7(Math.PI) === sig7(a),
        `${sig7(Math.PI)} vs ${sig7(a)}`);
}

// e = [2; 1, 2, 1, 1, 4, 1, 1, 6, …]  (Euler's pattern)
{
  const cf = cfOf(Math.E, 9);
  check("e's continued fraction begins [2; 1, 2, 1, 1, 4, 1, 1, 6]", cf.slice(0, 9).join(",") === "2,1,2,1,1,4,1,1,6", cf.slice(0, 9).join(","));
}

// √2 = [1; 2, 2, 2, …]
{
  const cf = cfOf(Math.SQRT2, 10);
  check("√2's continued fraction is 1 then 2s forever", cf[0] === 1 && cf.slice(1, 8).every(t => t === 2), cf.slice(0, 6).join(","));
}

console.log("\nII · The hardest number to catch — Hurwitz's √5");

// For the Fibonacci convergents p/q = F_{n+1}/F_n of φ,
//   q²·|φ − p/q|  =  F_n·φ^(−n)  =  (1 − (−1/φ²)^n)/√5  →  1/√5.
// (Derivation: φ^n = F_n φ + F_{n−1}, and L_n = φ^n + ψ^n with ψ = −1/φ,
//  so F_n φ − F_{n+1} = −ψ^n; hence F_n|F_n φ − F_{n+1}| = F_n φ^{−n}.)
// This is the stable form (no catastrophic cancellation of large numbers).
{
  const lim = n => (1 - Math.pow(-1 / (PHI * PHI), n)) / sqrt5;
  check("q²|φ − p/q| → 1/√5 ≈ 0.4472136 along Fibonacci convergents",
        approx(lim(30), 1 / sqrt5, 1e-9), lim(30).toFixed(10));
  // independent cross-check: same quantity computed directly as F_n·φ^{−n}
  let a = 1, b = 1; // F1, F2 as doubles (fine through n≈30)
  const fib = [1, 1]; // fib[i] = F_{i+1}  (fib[0]=F1, fib[1]=F2, fib[2]=F3, …)
  for (let i = 0; i < 30; i++) { const c = a + b; fib.push(c); a = b; b = c; }
  const n = 25;
  const Fn = fib[n - 1]; // F_n
  const direct = Fn * Math.pow(PHI, -n);
  check("cross-check F_n·φ^(−n) agrees with 1/√5", approx(direct, 1 / sqrt5, 1e-6), direct.toFixed(8));
}

// φ is the WORST case: its liminf (1/√5) is the largest of any number, so it
// stays farther from rationals than e.g. √2 (whose Lagrange number is √8).
{
  const phiConst = 1 / sqrt5;        // 0.44721…  (Lagrange number √5)
  const root2Const = 1 / Math.sqrt(8); // 0.35355…  (Lagrange number √8)
  check("φ's approximation constant 1/√5 exceeds √2's 1/√8 (φ is harder to approximate)",
        phiConst > root2Const, `1/√5=${phiConst.toFixed(6)} > 1/√8=${root2Const.toFixed(6)}`);
  check("√5 is the smallest Lagrange number — the Hurwitz best constant", approx(sqrt5, 2.2360679, 1e-6));
}

console.log("\nIII · The golden angle and the flower");

// Golden angle = 360·(2 − φ) = 360/φ² = 137.50776°, fraction-of-a-turn 2−φ
{
  const ga1 = 360 * (2 - PHI);
  const ga2 = 360 / (PHI * PHI);
  check("360·(2 − φ) = 137.50776°", approx(ga1, 137.50776, 1e-4), ga1.toFixed(5));
  check("360·(2 − φ) equals 360/φ² (same angle, two forms)", approx(ga1, ga2, 1e-9));
  check("fraction of a turn 2 − φ ≈ 0.38197", approx(2 - PHI, 0.38197, 1e-5), (2 - PHI).toFixed(5));
}

// A rational angle p/q turn (lowest terms) makes seed n and seed n+q coincide in
// direction → exactly q distinct directions → q spokes.  3/8 → 8, 5/13 → 13.
function spokes(p, q) {
  // reduce p/q
  const g = (a, b) => b ? g(b, a % b) : a;
  return q / g(p, q);
}
{
  check("3/8 turn gives 8 spokes", spokes(3, 8) === 8, spokes(3, 8));
  check("5/13 turn gives 13 spokes", spokes(5, 13) === 13, spokes(5, 13));
  // and these two rationals bracket the golden fraction 0.38197
  check("3/8 (0.375) and 5/13 (0.3846) bracket the golden fraction 0.38197",
        3 / 8 < (2 - PHI) && (2 - PHI) < 5 / 13, `${(3/8).toFixed(4)} < ${(2-PHI).toFixed(5)} < ${(5/13).toFixed(4)}`);
  // 3/8 and 5/13 are themselves consecutive convergents of 2−φ
  const cv = convergents(cfOf(2 - PHI, 8));
  const strs = cv.map(([h, k]) => `${h}/${k}`);
  check("3/8 and 5/13 are consecutive convergents of the golden fraction",
        strs.includes("3/8") && strs.includes("5/13"), strs.slice(0, 6).join(" "));
}

// Parastichy numbers: the spiral-arm counts you actually see are the
// record-setting denominators m for which m·(golden fraction) lands nearest a
// whole number — and those are EXACTLY the Fibonacci numbers.  For ~620 seeds
// the dominant pair falls on 34 and 55 (21 and 34 near N=200).
{
  const g = 2 - PHI;
  const frac = x => { x -= Math.floor(x); return Math.min(x, 1 - x); };
  let best = Infinity; const rec = [];
  for (let m = 1; m <= 60; m++) { const v = frac(m * g); if (v < best - 1e-12) { best = v; rec.push(m); } }
  const fib = [1, 2, 3, 5, 8, 13, 21, 34, 55];
  check("the parastichy numbers (record minima of ‖m·(2−φ)‖) are exactly Fibonacci",
        rec.join(",") === fib.join(","), rec.join(","));
  check("the candidate parastichy set is the whole Fibonacci sequence (which consecutive pair is VISIBLE depends on the head's size — see §V)",
        rec.includes(21) && rec.includes(34) && rec.includes(55), rec.join(","));
}

console.log("\nIV · How irrational, exactly? — the Lagrange/Markov ladder");
// "Most irrational" is not a yes/no: each number carries a Lagrange number
//   L(α) = 1 / liminf_q q²|α − p/q|  = limsup_q 1/(q²|α − p/q|),
// the tightest constant for which infinitely many fractions land within
// 1/(L q²). Hurwitz: the SMALLEST L over all irrationals is √5, attained by φ.
// Markov (1879): below 3, the set of Lagrange numbers is a DISCRETE ladder,
// indexed by the solutions of the Markov equation x²+y²+z²=3xyz — the Markov
// numbers m = 1,2,5,13,29,34,… — with L = √(9m²−4)/m, climbing to 3.

// Markov tree by Vieta jumping from the root triple (1,1,1)→(1,2,5)→…
function markovNumbers(depth) {
  const s = new Set([1, 2]);
  (function rec(a, b, c, d) {
    s.add(c);
    if (d >= depth) return;
    rec(a, c, 3 * a * c - b, d + 1);
    rec(b, c, 3 * b * c - a, d + 1);
  })(1, 2, 5, 0);
  return [...s].sort((x, y) => x - y);
}
{
  const isTriple = (a, b, c) => a * a + b * b + c * c === 3 * a * b * c;
  check("Markov root triples satisfy x²+y²+z²=3xyz  (1,1,1),(1,2,5),(1,5,13),(2,5,29)",
    isTriple(1, 1, 1) && isTriple(1, 2, 5) && isTriple(1, 5, 13) && isTriple(2, 5, 29));
  const M = markovNumbers(9);
  const want = [1, 2, 5, 13, 29, 34, 89, 169, 194, 233];
  check("the Markov tree generates 1,2,5,13,29,34,89,169,194,233…",
    want.every((w, i) => M[i] === w), M.slice(0, 10).join(","));

  const L = m => Math.sqrt(9 * m * m - 4) / m;
  check("bottom rung m=1 → L=√5 ≈ 2.2360680 (φ, the single most irrational number)",
    approx(L(1), sqrt5, 1e-12) && approx(L(1), 2.2360680, 1e-6), L(1).toFixed(7));
  check("second rung m=2 → L=√8 ≈ 2.8284271 (the √2 family — nothing lies between √5 and √8)",
    approx(L(2), Math.sqrt(8), 1e-12), L(2).toFixed(7));
  check("third rung m=5 → L=√221/5 ≈ 2.9732139", approx(L(5), Math.sqrt(221) / 5, 1e-12), L(5).toFixed(7));
  check("fourth rung m=13 → L=√1517/13 ≈ 2.9960534", approx(L(13), Math.sqrt(1517) / 13, 1e-12), L(13).toFixed(7));
  // strictly increasing, every rung below 3, limit 3
  const ladder = want.map(L);
  let mono = true;
  for (let i = 1; i < ladder.length; i++) if (!(ladder[i] > ladder[i - 1])) mono = false;
  check("the ladder is strictly increasing", mono, ladder.map(v => v.toFixed(4)).join(" "));
  check("every rung is below 3, and the ladder → 3", ladder.every(v => v < 3) && approx(ladder[ladder.length - 1], 3, 5e-4),
    `top rung ${ladder[ladder.length - 1].toFixed(6)} < 3`);
}
// The two CF anchors, exactly. A number's Lagrange value from a purely periodic
// CF word is max over positions of (forward complete quotient + reversed tail).
// All-1s (φ):   φ + 1/φ = 2φ − 1 = √5.   All-2s (1+√2):  (1+√2)+(√2−1) = 2√2 = √8.
{
  check("all-ones CF anchor: 2φ − 1 = √5 exactly", approx(2 * PHI - 1, sqrt5, 1e-14), (2 * PHI - 1).toFixed(10));
  const root2fam = 1 + Math.SQRT2;           // [2; 2, 2, …]
  const cf = cfOf(root2fam, 8);
  check("the √8-rung number 1+√2 has continued fraction all 2s", cf.slice(0, 7).every(t => t === 2), cf.slice(0, 5).join(","));
  check("all-twos CF anchor: (1+√2)+(√2−1) = 2√2 = √8 exactly", approx(2 * Math.SQRT2, Math.sqrt(8), 1e-14));
}
// Above 3 the spectrum is a different animal: not discrete. Hall (1947) — a full
// ray [Freiman's constant, ∞) lies in the Lagrange spectrum; Freiman (1975) fixed
// its left end F = 4.5278295661…  (2221564096 + 283748·√462)/491993569.
{
  const F = (2221564096 + 283748 * Math.sqrt(462)) / 491993569;
  check("Freiman's constant F ≈ 4.5278295661 (left end of Hall's ray)", approx(F, 4.5278295661, 1e-9), F.toFixed(10));
  check("the discrete ceiling (3) sits below Freiman's constant (the continuum's start)", 3 < F);
}

console.log("\nV · The flower that counts itself — opposed parastichy pairs, detected live");
// The page detects the two visible spiral families (the "opposed parastichy
// pair") straight from the seed geometry — for each seed in the outer band, the
// index-offsets of its two nearest neighbours — exactly the routine the browser
// runs. The claim is not a fixed pair but an INVARIANT: at the golden angle the
// pair is always two CONSECUTIVE Fibonacci numbers (and climbs the sequence as
// the head grows); at a rational p/q turn the seeds line into exactly q spokes.
function opposedPair(angDeg, N, scale = 8) {
  const step = angDeg * Math.PI / 180;
  const pts = [];
  for (let n = 1; n <= N; n++) { const r = scale * Math.sqrt(n), a = n * step; pts.push([r * Math.cos(a), r * Math.sin(a), n]); }
  const lo = Math.floor(N * 0.6), tally = {};
  for (let i = lo; i < N; i++) {
    const ds = [];
    for (let j = 0; j < N; j++) { if (j === i) continue; const dx = pts[i][0] - pts[j][0], dy = pts[i][1] - pts[j][1]; ds.push([dx * dx + dy * dy, Math.abs(pts[i][2] - pts[j][2])]); }
    ds.sort((a, b) => a[0] - b[0]);
    const seen = new Set();
    for (const [, off] of ds) { if (seen.has(off)) continue; seen.add(off); tally[off] = (tally[off] || 0) + 1; if (seen.size >= 2) break; }
  }
  return Object.entries(tally).map(([k, v]) => [+k, v]).sort((a, b) => b[1] - a[1]).slice(0, 2).map(x => x[0]).sort((a, b) => a - b);
}
{
  const FIB = new Set([1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233]);
  const consecutiveFib = ([a, b]) => {
    const seq = [1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144];
    const i = seq.indexOf(a);
    return i >= 0 && seq[i + 1] === b;
  };
  const GOLD = 137.50776;
  const p300 = opposedPair(GOLD, 300), p620 = opposedPair(GOLD, 620), p1000 = opposedPair(GOLD, 1000);
  check("golden angle, N=300: opposed pair is consecutive Fibonacci", consecutiveFib(p300), p300.join(" & "));
  check("golden angle, N=620 (the page default): opposed pair is consecutive Fibonacci", consecutiveFib(p620), p620.join(" & "));
  check("golden angle, N=1000: opposed pair is consecutive Fibonacci", consecutiveFib(p1000), p1000.join(" & "));
  check("both members of every detected pair are Fibonacci numbers",
    [p300, p620, p1000].every(p => p.every(x => FIB.has(x))));
  check("the pair climbs the Fibonacci sequence as the head grows (N=300 ≤ 620 ≤ 1000)",
    p300[0] <= p620[0] && p620[0] <= p1000[0], `${p300.join("/")} → ${p620.join("/")} → ${p1000.join("/")}`);
  // The page's sentence, pair by pair (2026-09-28: the check above uses <=, so it passed
  // without ever seeing the "smaller head" pair it was cited for).
  const p200 = opposedPair(GOLD, 200);
  check("a smaller head (N=200) shows 21 and 34", p200.join("&") === "21&34", p200.join(" & "));
  check("the page's default head (N=620) shows 34 and 55", p620.join("&") === "34&55", p620.join(" & "));
  check("a larger head (N=1000) shows 55 and 89", p1000.join("&") === "55&89", p1000.join(" & "));
  // 137.6 deg: the detector finds a multiple pair (34 & 68), so the readout calls the arms
  // spokes; it may say "repeats its direction" only if 34 turns really close up. They do not.
  const s1376 = opposedPair(137.6, 620);
  const turn = (k, a) => { const r = ((k * a) % 360 + 360) % 360; return Math.min(r, 360 - r); };
  check("137.6°: detector gives a multiple pair, 34 & 68 (near-spokes)", s1376.join("&") === "34&68", s1376.join(" & "));
  check("137.6°: every 34th seed is 1.6° off, not a repeat (the readout must not say it repeats)",
    Math.abs(turn(34, 137.6) - 1.6) < 1e-6 && turn(8, 135) < 1e-9 && turn(13, 360 * 5 / 13) < 1e-9, turn(34, 137.6).toFixed(3) + "°");
  const s38 = opposedPair(135, 620), s513 = opposedPair(360 * 5 / 13, 620);
  check("3/8 turn: the dominant family is 8 (→ 8 spokes)", s38.includes(8), s38.join(" & "));
  check("5/13 turn: the dominant family is 13 (→ 13 spokes)", s513.includes(13), s513.join(" & "));
}

console.log(`\n${fail === 0 ? "✓" : "✗"} most-irrational: ${pass} passed, ${fail} failed\n`);
process.exit(fail === 0 ? 0 : 1);
