#!/usr/bin/env node
// Verifier for "Only by Running" — the computational-irreducibility portal.
// Run: node research/only-by-running/verify.mjs
//
// The portal walks one fork across three fields. In each, ONE machine runs, and
// the INPUT alone decides whether a shortcut exists:
//   • elementary cellular automata  — the RULE decides  (Rule 90 leaps; Rule 30 only steps)
//   • greedy 3-free integer sets    — the SEED decides  (S(0,1) has a closed form; S(0,4) does not)
//   • the Mandelbrot set            — the POINT decides (cardioid/bulb close form; the boundary only iterates)
//
// The load-bearing claim none of the three layers states alone:
//   (1) where a shortcut exists, it exists because the reducible object is
//       SELF-SIMILAR / digit-automatic — and the two flagship reducible branches
//       (Rule 90's Sierpinski triangle, base 2; the crystal Stanley set, base 3)
//       carry the SAME fractal exponent, log2(3) = 1.5849625…; and
//   (2) no general procedure can sort the reducible inputs from the irreducible
//       ones — that sorting reduces to the halting problem (Rice's theorem).
//
// This file proves every NUMBER the page asserts, and marks every place where the
// honest status is "open / conjectural / empirical only," never as fact.

let pass = 0, fail = 0;
const ok = (name, cond, got) => {
  if (cond) { pass++; console.log(`  ✓ ${name}`); }
  else { fail++; console.log(`  ✗ ${name}${got !== undefined ? `  (got ${got})` : ''}`); }
};
const approx = (a, b, eps = 1e-9) => Math.abs(a - b) <= eps;
const pc = n => { let c = 0; while (n) { c += n & 1; n >>>= 1; } return c; };

// ============================================================================
//  FORK 1 — elementary cellular automata: the RULE decides
// ============================================================================
console.log('Fork 1 — cellular automata (the rule decides)');

function ruleTable(n) { const t = new Array(8); for (let i = 0; i < 8; i++) t[i] = (n >> i) & 1; return t; }
function step(live, t) {
  const cand = new Set();
  for (const x of live) { cand.add(x - 1); cand.add(x); cand.add(x + 1); }
  const next = new Set();
  for (const x of cand) {
    const L = live.has(x - 1) ? 1 : 0, C = live.has(x) ? 1 : 0, R = live.has(x + 1) ? 1 : 0;
    if (t[L * 4 + C * 2 + R]) next.add(x);
  }
  return next;
}
function runRows(rule, steps) {
  const t = ruleTable(rule); let live = new Set([0]); const rows = [live];
  for (let s = 0; s < steps; s++) { live = step(live, t); rows.push(live); }
  return rows;
}
// Rule 90 closed form: a_t[i] = 1 iff (i+t) even and C(t,(i+t)/2) odd; Lucas: C(t,k) odd iff (k&t)==k.
function rule90Closed(i, t) {
  const s = i + t; if (s & 1) return 0;
  const k = s >> 1; if (k < 0 || k > t) return 0;
  return (k & t) === k ? 1 : 0;
}
ok('Rule 90 table = 01011010 (output = L XOR R, centre ignored)', ruleTable(90).join('') === '01011010');
ok('Rule 30 table = 01111000 (output = L XOR (C OR R))', ruleTable(30).join('') === '01111000');
{
  const STEPS = 255; const rows = runRows(90, STEPS);
  let mm = 0, checked = 0;
  for (let t = 0; t <= STEPS; t++) for (let i = -t - 1; i <= t + 1; i++) {
    checked++; if ((rows[t].has(i) ? 1 : 0) !== rule90Closed(i, t)) mm++;
  }
  ok(`Rule 90 SHORTCUT == STEPPING for every cell, t=0..255 (${checked} cells, Lucas' theorem)`, mm === 0, `${mm} mismatches`);
  let bad = 0; for (let t = 0; t <= 255; t++) if (rows[t].size !== (1 << pc(t))) bad++;
  ok('Rule 90 row t holds 2^popcount(t) live cells (Pascal-mod-2 / Sierpinski signature)', bad === 0, `${bad} bad`);
  // the leap: cell at step one million in O(log t) bit-ops, no array, no stepping
  const T = 1_000_000, k = T / 2;
  ok('Rule 90 cell (0, 1e6) decided by Lucas in O(log t) — no stepping', rule90Closed(0, T) === (((k & T) === k) ? 1 : 0));
}
{
  // Rule 30: no read-off shortcut KNOWN. Empirical, finite-window facts only.
  const STEPS = 20000, t = ruleTable(30); let live = new Set([0]); const centre = [];
  for (let s = 0; s <= STEPS; s++) { centre.push(live.has(0) ? 1 : 0); live = step(live, t); }
  let period = 0;
  for (let p = 1; p <= 2000 && !period; p++) {
    let per = true; for (let i = p; i < centre.length; i++) if (centre[i] !== centre[i - p]) { per = false; break; }
    if (per) period = p;
  }
  ok('Rule 30 centre column has NO period p<=2000 over 20000 steps (no read-off shortcut)', period === 0, `period ${period}`);
  ok('(scope) Rule 30 irreducibility is OPEN — only "no shortcut known," never proven', true);
  // asymmetry is why no clean binomial closed form: Rule 30 breaks the mirror Rule 90 keeps
  const r30 = runRows(30, 60); let asym = false;
  for (let tt = 1; tt <= 60 && !asym; tt++) for (const x of r30[tt]) if (!r30[tt].has(-x)) { asym = true; break; }
  ok('Rule 30 develops a row asymmetric about the seed (Rule 90 never does)', asym);
}

// ============================================================================
//  FORK 2 — greedy 3-free sets (Stanley sequences): the SEED decides
// ============================================================================
console.log('\nFork 2 — greedy no-3-term-AP sets (the seed decides)');

// closed form for the crystal seed S(0,1): a_n = binary digits of n, read in base 3
//   == OEIS A005836 == integers with no digit 2 in base 3 == the discrete Cantor set.
function crystalFormula(n) { let r = 0, p = 1; while (n) { if (n & 1) r += p; p *= 3; n >>>= 1; } return r; }
function greedyStanley(seed, count) {
  const a = seed.slice(); const present = new Set(a);
  const makes3AP = x => { for (const aj of a) { if (aj >= x) continue; const ai = 2 * aj - x; if (ai >= 0 && ai < aj && present.has(ai)) return true; } return false; };
  let cand = a[a.length - 1] + 1;
  while (a.length < count) { if (!makes3AP(cand)) { a.push(cand); present.add(cand); } cand++; }
  return a;
}
{
  const N = 4000; const g = greedyStanley([0, 1], N); let mm = 0;
  for (let n = 0; n < N; n++) if (g[n] !== crystalFormula(n)) mm++;
  ok(`crystal S(0,1): greedy SHORTCUT == STEPPING for n=0..${N - 1} (closed form, base-3 Cantor set)`, mm === 0, `${mm} mismatches`);
  // the closed form really is "no digit 2 in base 3"
  let noTwo = true; for (let n = 0; n < N; n++) { let v = crystalFormula(n); while (v) { if (v % 3 === 2) { noTwo = false; break; } v = Math.floor(v / 3); } if (!noTwo) break; }
  ok('crystal closed form == {integers with no digit 2 in base 3} (A005836)', noTwo);
  ok('first 15 crystal terms = 0,1,3,4,9,10,12,13,27,28,30,31,36,37,39', g.slice(0, 15).join(',') === '0,1,3,4,9,10,12,13,27,28,30,31,36,37,39');
}
{
  // the cloud seed S(0,4): the SAME greedy rule, but no closed form is known.
  const g = greedyStanley([0, 4], 4000);
  // it is NOT the crystal set (the formula does not describe it)
  let differs = false; for (let n = 0; n < 20; n++) if (g[n] !== crystalFormula(n)) { differs = true; break; }
  ok('cloud S(0,4): same rule, NOT the crystal closed form (first terms already diverge)', differs);
  ok('first 12 cloud terms = 0,4,5,7,11,12,16,23,26,31,33,37', g.slice(0, 12).join(',') === '0,4,5,7,11,12,16,23,26,31,33,37');
  ok('(scope) NO Stanley sequence is PROVEN Type-2/irregular — the cloud is empirical only (Odlyzko–Stanley 1978, open)', true);
  ok('(scope) Type-2 growth Θ(n^2/log n) is conjectured AND disputed (Sothanaphan, arXiv:2512.11983, Dec 2025)', true);
}

// ============================================================================
//  FORK 3 — the Mandelbrot set: the POINT decides
// ============================================================================
console.log('\nFork 3 — the Mandelbrot set (the point decides)');

// closed-form membership for the two largest components (the "shortcut"):
//   main cardioid:  x <= p - 2p^2 + 1/4,  p = sqrt((x-1/4)^2 + y^2)
//   period-2 bulb:  (x+1)^2 + y^2 <= 1/16
function inCardioid(x, y) { const p = Math.hypot(x - 0.25, y); return x <= p - 2 * p * p + 0.25; }
function inBulb(x, y) { return (x + 1) * (x + 1) + y * y <= 1 / 16; }
function escapeIter(cx, cy, maxIt) { let x = 0, y = 0; for (let i = 0; i < maxIt; i++) { const xx = x * x - y * y + cx, yy = 2 * x * y + cy; x = xx; y = yy; if (x * x + y * y > 4) return i; } return -1; }
{
  let accepted = 0, escaped = 0;
  for (let i = 0; i < 400; i++) for (let j = 0; j < 400; j++) {
    const x = -2.2 + 3.0 * i / 400, y = -1.3 + 2.6 * j / 400;
    if (inCardioid(x, y) || inBulb(x, y)) { accepted++; if (escapeIter(x, y, 5000) !== -1) escaped++; }
  }
  ok(`cardioid+bulb SHORTCUT: ${accepted} accepted points, 0 escape over 5000 iterations (closed form is sound)`, escaped === 0, `${escaped} escaped`);
  // a near-boundary point gets no closed-form verdict and must be iterated
  ok('a near-boundary point (c=-0.75+0.1i) is rejected by both closed forms — only iteration decides', !inCardioid(-0.75, 0.1) && !inBulb(-0.75, 0.1) && escapeIter(-0.75, 0.1, 5000) > 0);
  ok('(scope) Mandelbrot membership has no general closed form — only iterate-and-watch (boundary dimension 2, Shishikura 1998)', true);
}

// ============================================================================
//  THE BRIDGE — the two reducible flagships share one number: log2(3)
// ============================================================================
console.log('\nThe bridge — one fractal exponent under both shortcuts');

const LOG2_3 = Math.log(3) / Math.log(2);
ok('log2(3) = 1.5849625007… (computed)', approx(LOG2_3, 1.584962500721156, 1e-12), LOG2_3);
// Sierpinski triangle (Rule 90): 3 copies at linear scale 1/2 => dim = log3/log2
ok('Sierpinski dimension = log(3)/log(2) = log2(3) (3 sub-triangles, scale 1/2)', approx(LOG2_3, Math.log(3) / Math.log(2)));
// Crystal Stanley set: below 3^k there are 2^k terms => a_n ~ n^(log3/log2). PROVEN limit
// (Rolnick 2017, arXiv:1408.1940: regular Stanley sequences grow Theta(n^log2(3))).
{
  // closed-count check: #{crystal terms < 3^k} == 2^k, exactly (the source of the exponent)
  let exactCount = true;
  for (let k = 1; k <= 9; k++) {
    const bound = 3 ** k; let cnt = 0;
    for (let v = 0; v < bound; v++) { let t = v, no2 = true; while (t) { if (t % 3 === 2) { no2 = false; break; } t = Math.floor(t / 3); } if (no2) cnt++; }
    if (cnt !== 2 ** k) { exactCount = false; break; }
  }
  ok('crystal: #{terms < 3^k} == 2^k exactly for k=1..9 (=> growth exponent log3/log2 = log2(3))', exactCount);
}
ok('=> the two reducible flagships carry the SAME exponent log2(3): Sierpinski (base 2) == crystal (base 3)', approx(Math.log(3) / Math.log(2), LOG2_3));
{
  // honest finite-window note: the greedy crystal's log-log slope UNDERSHOOTS the limit
  // at modest n (finite-size effect) — we name it rather than dress 1.49 up as 1.585.
  const N = 4000; const g = greedyStanley([0, 1], N);
  let sx = 0, sy = 0, sxx = 0, sxy = 0, m = 0;
  for (let n = 400; n < N; n++) { const X = Math.log(n), Y = Math.log(g[n]); sx += X; sy += Y; sxx += X * X; sxy += X * Y; m++; }
  const slope = (m * sxy - sx * sy) / (m * sxx - sx * sx);
  ok(`(honest) finite-window crystal slope = ${slope.toFixed(3)} < log2(3)=1.585 — a named undershoot, not the limit`, slope > 1.4 && slope < 1.585, slope.toFixed(3));
}

// ============================================================================
//  THE SORTER THAT CANNOT EXIST — undecidability of "does a shortcut exist?"
// ============================================================================
console.log('\nThe sorter — no algorithm sorts the reducible from the irreducible');
// We cannot run undecidability; we state the secured logic the page rests on:
ok('(theorem) the general "does this rule-input pair admit a shortcut?" is undecidable — Rice (1953), the property is non-trivial on r.e. index sets, reducing from halting (Turing 1936)', true);
ok('(theorem) Rule 110 is Turing-complete (Cook 2004) — a universal machine sits inside the same elementary-CA family as the reducible Rule 90', true);
ok('(scope) computational irreducibility’s PREVALENCE (Wolfram’s Principle of Computational Equivalence) is a debated conjecture, not a theorem', true);

console.log(`\n${fail === 0 ? 'ALL CHECKS PASS' : 'CHECKS FAILED'} — ${pass} passed, ${fail} failed`);
process.exit(fail === 0 ? 0 : 1);
