// research/any-loop-you-can-draw/verify-hodge.mjs — the MEASUREMENT + RESOLUTION half
// of the "Any Loop You Can Draw" portal (companion to verify.mjs, which covers the
// EXISTENCE/UNIVERSALITY half: McGarvey's machine and Guilbaud's genericity).
//
//   node research/any-loop-you-can-draw/verify-hodge.mjs
//
// The portal shows the loop EXISTS, is UNIVERSAL, and is GENERIC; this file adds the
// two things it originally lacked — how MUCH of each real domain is loop, and what the
// honest ANSWER is — recomputed from first principles:
//   "Better than" is a RELATION, and relations need not order. Across four domains
//   that look unrelated — a fair coin (Penney's game), our votes (Condorcet's
//   paradox), how we rank intelligence (Elo / Arena leaderboards), and the living
//   world (the side-blotched lizard) — the SAME object appears: a tournament whose
//   dominance forms a ring, A beats B beats C beats A. ONE lens reads all four
//   (the Helmholtz–Hodge decomposition: split the pairwise field into a rankable
//   GRADIENT part and a CYCLIC residual no scalar rating can hold), and ONE
//   resolution answers all four (not a fake scalar order but a DISTRIBUTION over the
//   ring — the maximal lottery, the Nash mixed strategy of the tournament game).
//
// This file reproduces every number the page prints and proves the structural
// umbrella claims. The Hodge / maximal-lottery / evolutionary engine is the same one
// verified for "No King of the Hill" (research/nontransitive-eval/) and "Rock,
// Paper, Lizard" (research/rock-paper-lizard/); here it is pointed at all four
// domains at once to show they are one phenomenon, not four curiosities.

// ───────────────────────── the shared engine ─────────────────────────
const sig = (x) => 1 / (1 + Math.exp(-x));
const logit = (p) => Math.log(p / (1 - p));

// Helmholtz–Hodge on the complete graph: an antisymmetric edge field Y_ij splits into
// a gradient flow grad(r)_ij = r_i - r_j (the unique least-squares rating; on K_n
// r is the row-mean of Y) plus a cyclic residual, and the two are orthogonal so
// ||Y||^2 = ||grad||^2 + ||cyc||^2 exactly. cyclicFraction = ||cyc||^2 / ||Y||^2 is
// the share of the comparison NO scalar rating can ever represent.
function hodgeFromY(Y) {
  const n = Y.length;
  const r = Y.map((row) => row.reduce((a, b) => a + b, 0) / n); // row-mean rating
  let eY = 0, eG = 0, eC = 0, cross = 0;
  for (let i = 0; i < n; i++) for (let j = i + 1; j < n; j++) {
    const g = r[i] - r[j], c = Y[i][j] - g;
    eY += Y[i][j] ** 2; eG += g ** 2; eC += c ** 2; cross += g * c;
  }
  return { r, eY, eG, eC, cross, cyclicFraction: eY === 0 ? 0 : eC / eY };
}
// Y from a probability matrix in two natural magnitude conventions.
const Ylogit = (P) => P.map((row, i) => row.map((p, j) => (i === j ? 0 : logit(p))));
const Ymargin = (P) => P.map((row, i) => row.map((p, j) => (i === j ? 0 : 2 * p - 1)));
const hodge = (P) => hodgeFromY(Ylogit(P));

// independent rating check: solve the least-squares normal equations directly (Gaussian
// elimination with a sum-zero gauge), so the row-mean shortcut is cross-checked.
function lsRatingDirect(Y) {
  const n = Y.length;
  const A = Array.from({ length: n }, () => new Array(n).fill(0)), b = new Array(n).fill(0);
  for (let i = 0; i < n; i++) { A[i][i] = n - 1; for (let j = 0; j < n; j++) if (j !== i) { A[i][j] = -1; b[i] += Y[i][j]; } }
  A[n - 1] = new Array(n).fill(1); b[n - 1] = 0;
  for (let c = 0; c < n; c++) {
    let p = c; while (Math.abs(A[p][c]) < 1e-12) p++;
    [A[c], A[p]] = [A[p], A[c]]; [b[c], b[p]] = [b[p], b[c]];
    const pv = A[c][c]; for (let k = 0; k < n; k++) A[c][k] /= pv; b[c] /= pv;
    for (let r = 0; r < n; r++) if (r !== c) { const f = A[r][c]; for (let k = 0; k < n; k++) A[r][k] -= f * A[c][k]; b[r] -= f * b[c]; }
  }
  return b;
}

// maximal lottery: the Nash equilibrium of the symmetric zero-sum "who-beats-whom"
// game with payoff A_ij = 2 P_ij - 1. Time-averaged multiplicative weights -> Nash.
function maximalLottery(P) {
  const n = P.length, A = P.map((row, i) => row.map((p, j) => (i === j ? 0 : 2 * p - 1)));
  let x = new Array(n).fill(1 / n), avg = new Array(n).fill(0); const eta = 0.05, iters = 60000;
  for (let t = 0; t < iters; t++) {
    const payoff = A.map((row) => row.reduce((s, a, j) => s + a * x[j], 0));
    let Z = 0; const nx = x.map((xi, i) => { const v = xi * Math.exp(eta * payoff[i]); Z += v; return v; });
    x = nx.map((v) => v / Z); for (let i = 0; i < n; i++) avg[i] += x[i];
  }
  avg = avg.map((v) => v / iters);
  const colPayoff = A[0].map((_, j) => A.reduce((s, row, i) => s + avg[i] * row[j], 0));
  return { x: avg, value: Math.min(...colPayoff) };
}

// online Elo over a random schedule -> who ends up #1 (champion). Used to show the
// "leaderboard" is schedule-noise when the field is a ring.
function mulberry32(seed) { let a = seed >>> 0; return () => { 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; }; }
function onlineEloChampion(P, rng, games = 3000, K = 32) {
  const n = P.length, R = new Array(n).fill(1500);
  for (let g = 0; g < games; g++) {
    const i = Math.floor(rng() * n); let j = Math.floor(rng() * (n - 1)); if (j >= i) j++;
    const exp = 1 / (1 + 10 ** ((R[j] - R[i]) / 400));
    const win = rng() < P[i][j] ? 1 : 0;
    R[i] += K * (win - exp); R[j] += K * ((1 - win) - (1 - exp));
  }
  let best = 0; for (let i = 1; i < n; i++) if (R[i] > R[best]) best = i; return best;
}
function championSpread(P, shuffles = 300) {
  const n = P.length, cnt = new Array(n).fill(0);
  for (let s = 0; s < shuffles; s++) cnt[onlineEloChampion(P, mulberry32(1000 + s))]++;
  return cnt.map((c) => c / shuffles);
}

// ───────────────────────── the four domains ─────────────────────────
// A · THE COIN — Penney's game. P(i beats j) = P(triple i appears before triple j) in
// a fair stream, by Conway's leading-number formula (exact rationals via BigInt).
function corr(X, Y) { let t = 0n; for (let k = 1; k <= X.length; k++) if (X.slice(-k) === Y.slice(0, k)) t += 2n ** BigInt(k - 1); return t; }
function penneyFirst(A, B) { const AA = corr(A, A), AB = corr(A, B), BA = corr(B, A), BB = corr(B, B); const num = BB - BA, den = AA - AB; return Number(num) / Number(num + den); }
const seqs3 = [...'01234567'].map((_, i) => i.toString(2).padStart(3, '0').replace(/0/g, 'H').replace(/1/g, 'T'));
function penney8() {
  const n = 8, P = Array.from({ length: n }, () => new Array(n).fill(0.5));
  for (let i = 0; i < n; i++) for (let j = 0; j < n; j++) if (i !== j) P[i][j] = penneyFirst(seqs3[i], seqs3[j]);
  return P;
}

// B · THE VOTES — Condorcet's paradox. The classic 3-voter profile, each majority 2–1.
//   voter 1: A>B>C   voter 2: B>C>A   voter 3: C>A>B
// Majorities: A>B {1,3}, B>C {1,2}, C>A {2,3} — a pure intransitive 3-cycle.
const condorcetProfile = [["A", "B", "C"], ["B", "C", "A"], ["C", "A", "B"]];
function condorcetTournament(profile) {
  const cands = ["A", "B", "C"], idx = { A: 0, B: 1, C: 2 };
  const margin = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]; // net votes, x beats y
  for (const x of cands) for (const y of cands) if (x !== y) {
    let pref = 0; for (const ballot of profile) pref += ballot.indexOf(x) < ballot.indexOf(y) ? 1 : -1;
    margin[idx[x]][idx[y]] = pref;
  }
  // probability matrix: 1 if x is the majority winner over y, else 0 (deterministic)
  const P = margin.map((row, i) => row.map((m, j) => (i === j ? 0.5 : m > 0 ? 1 : 0)));
  return { margin, P, cands };
}

// C · THE INTELLIGENCE — Elo / Arena leaderboards. A "spinning top": a real skill
// gradient PLUS a cyclic upset among the middle ranks (a MODEL of a realistic field,
// the same preset 'No King of the Hill' uses; labelled a model on the page).
function fromSkills(s) { const n = s.length, P = Array.from({ length: n }, () => new Array(n).fill(0.5)); for (let i = 0; i < n; i++) for (let j = 0; j < n; j++) if (i !== j) P[i][j] = sig(s[i] - s[j]); return P; }
function spinningTop() {
  const P = fromSkills([2.2, 0.9, 0.0, -0.9, -2.2]); const w = 0.78, mid = [1, 2, 3];
  for (let k = 0; k < 3; k++) { const i = mid[k], j = mid[(k + 1) % 3]; P[i][j] = w; P[j][i] = 1 - w; }
  return P;
}

// D · THE LIFE — the side-blotched lizard (Sinervo & Lively, Nature 1996): orange
// beats blue beats yellow beats orange. The cycle DIRECTION is the sourced biological
// fact; the symmetric strength is a model. A clean symmetric 3-cycle.
const lizardCycle = [["orange", "blue"], ["blue", "yellow"], ["yellow", "orange"]];
function lizardTournament(strength = 0.85) {
  const morphs = ["orange", "blue", "yellow"], idx = { orange: 0, blue: 1, yellow: 2 };
  const P = [[0.5, 0.5, 0.5], [0.5, 0.5, 0.5], [0.5, 0.5, 0.5]];
  const margin = [[0, 0, 0], [0, 0, 0], [0, 0, 0]];
  for (const [w, l] of lizardCycle) { P[idx[w]][idx[l]] = strength; P[idx[l]][idx[w]] = 1 - strength; margin[idx[w]][idx[l]] = 1; margin[idx[l]][idx[w]] = -1; }
  return { P, margin, morphs };
}

// ───────────────────────── helpers ─────────────────────────
let PASS = 0, FAIL = 0; const out = [];
const ok = (name, cond, extra = "") => { if (cond) { PASS++; out.push(`  ok   ${name}`); } else { FAIL++; out.push(`  FAIL ${name}${extra ? "\n         " + extra : ""}`); } };
const near = (a, b, tol = 1e-9) => Math.abs(a - b) <= tol;
const pct = (x) => (100 * x).toFixed(1) + "%";
// is the deterministic ±1 tournament (P in {0,0.5,1}) acyclic? (a real order exists)
function isAcyclic(P) {
  const n = P.length; const beats = (i, j) => P[i][j] > 0.5;
  // a tournament is transitive iff it has no 3-cycle iff sorting by out-degree is a total order with no upsets
  const deg = Array.from({ length: n }, (_, i) => { let d = 0; for (let j = 0; j < n; j++) if (i !== j && beats(i, j)) d++; return d; });
  const order = [...Array(n).keys()].sort((a, b) => deg[b] - deg[a]);
  for (let a = 0; a < n; a++) for (let b = a + 1; b < n; b++) if (beats(order[b], order[a])) return false;
  return true;
}

// ═══════════════════════════ CHECKS ═══════════════════════════
console.log("THE RING WITH NO TOP — portal verifier\n");

// ── 0 · the engine itself: Hodge orthogonality + energy split + independent rating ──
out.push("0. THE LENS — Hodge split is exact and the rating is the genuine least-squares solution");
for (const [name, P] of [["coin/Penney", penney8()], ["AI/spinning-top", spinningTop()]]) {
  const Y = Ylogit(P), H = hodgeFromY(Y);
  ok(`${name}: gradient ⟂ cyclic (cross ≈ 0)`, near(H.cross, 0, 1e-9), `cross=${H.cross}`);
  ok(`${name}: energy splits ‖Y‖²=‖grad‖²+‖cyc‖²`, near(H.eY, H.eG + H.eC, 1e-9));
  const rD = lsRatingDirect(Y), rC = H.r.map((v) => v - H.r.reduce((a, b) => a + b) / H.r.length);
  ok(`${name}: row-mean rating == independent LS solve`, Math.max(...rC.map((v, i) => Math.abs(v - rD[i]))) < 1e-9);
}
// sanity anchors of the ruler
ok("anchor: a pure 3-cycle (RPS) is 100% cyclic", near(hodgeFromY(Ymargin([[0.5, 1, 0], [0, 0.5, 1], [1, 0, 0.5]])).cyclicFraction, 1, 1e-9));
ok("anchor: a clean ladder is 0% cyclic", hodge(fromSkills([2, 1, 0, -1, -2])).cyclicFraction < 1e-9);

// ── 1 · THE COIN — Penney's eight triples ──
out.push("");
out.push("1. THE COIN — Penney's game: a fair coin hides a ring (Conway leading numbers)");
const coin = penney8(), coinH = hodge(coin), coinL = maximalLottery(coin);
ok("coin: Penney win-matrix is a valid tournament (P_ij+P_ji=1)", coin.every((r, i) => r.every((p, j) => i === j || near(p + coin[j][i], 1))));
// the canonical famous fact: HHH (idx0) beats nothing universally; THH beats HHH 7:1
ok("coin: THH beats HHH with probability 7/8 (Conway)", near(coin[seqs3.indexOf("THH")][seqs3.indexOf("HHH")], 7 / 8, 1e-12), `got ${coin[seqs3.indexOf("THH")][seqs3.indexOf("HHH")]}`);
ok("coin: no triple beats all others (no Condorcet winner)", !coin.some((row, i) => row.every((p, j) => i === j || p > 0.5)));
ok("coin: cyclic fraction = 55.8% (log-odds convention, matches No King of the Hill)", coinH.cyclicFraction.toFixed(3) === "0.558", `got ${coinH.cyclicFraction.toFixed(3)}`);
ok("coin: maximal lottery value ≈ 0 (a valid symmetric-game Nash)", near(coinL.value, 0, 5e-3));
console.log(`COIN  cyclic=${pct(coinH.cyclicFraction)}  lottery spreads over the ring: [${coinL.x.map((v) => pct(v)).join(", ")}]`);

// ── 2 · THE VOTES — Condorcet's paradox ──
out.push("");
out.push("2. THE VOTES — Condorcet's paradox: majority rule chases its own tail");
const { margin: cMargin, P: cP } = condorcetTournament(condorcetProfile);
ok("votes: A>B, B>C, C>A each by a 2–1 majority", cMargin[0][1] === 1 && cMargin[1][2] === 1 && cMargin[2][0] === 1);
ok("votes: it is a genuine 3-cycle (no Condorcet winner)", !isAcyclic(cP) && !cP.some((row, i) => row.every((p, j) => i === j || p > 0.5)));
const cH = hodgeFromY(cMargin);
ok("votes: cyclic fraction = 100% (gradient zero by symmetry, convention-free)", near(cH.cyclicFraction, 1, 1e-12), `got ${cH.cyclicFraction}`);
const cL = maximalLottery(cP);
ok("votes: maximal lottery is the uniform 1/3 over the cycle", cL.x.every((v) => near(v, 1 / 3, 2e-3)));
// the live count the member page reports: exactly 12 of the 216 three-voter profiles cycle
function countCondorcetCycles() {
  const perms = []; const cands = [0, 1, 2];
  const permute = (a, m = []) => { if (!a.length) perms.push(m); else a.forEach((x, i) => permute(a.slice(0, i).concat(a.slice(i + 1)), m.concat(x))); };
  permute(cands);
  let cyc = 0;
  for (const b1 of perms) for (const b2 of perms) for (const b3 of perms) {
    const prof = [b1, b2, b3];
    const beats = (x, y) => { let s = 0; for (const b of prof) s += b.indexOf(x) < b.indexOf(y) ? 1 : -1; return s > 0; };
    const ab = beats(0, 1), bc = beats(1, 2), ca = beats(2, 0), ba = beats(1, 0), cb = beats(2, 1), ac = beats(0, 2);
    if ((ab && bc && ca) || (ba && cb && ac)) cyc++;
  }
  return cyc;
}
ok("votes: exactly 12 of the 216 three-voter profiles cycle (matches The Only Fair Vote)", countCondorcetCycles() === 12, `got ${countCondorcetCycles()}`);
console.log(`VOTES cyclic=${pct(cH.cyclicFraction)}  lottery: [${cL.x.map((v) => pct(v)).join(", ")}]   (12/216 profiles cycle)`);

// ── 3 · THE INTELLIGENCE — Elo / Arena leaderboards ──
out.push("");
out.push("3. THE INTELLIGENCE — Elo leaderboards: a ring in the middle ranks, unreported");
const top = spinningTop(), topH = hodge(top), topL = maximalLottery(top), topSpread = championSpread(top, 200);
ok("AI: cyclic fraction = 12.0% (real but small; lives in the middle ranks)", topH.cyclicFraction.toFixed(3) === "0.120", `got ${topH.cyclicFraction.toFixed(3)}`);
ok("AI: the genuine top wins the lottery ~100% (the lens does not cry wolf)", topL.x[0] > 0.99);
ok("AI: but the middle three are an intransitive ring (1>2>3>1)", top[1][2] > 0.5 && top[2][3] > 0.5 && top[3][1] > 0.5);
ok("AI: Elo champion is stable here (the top is real) — schedule does not move #1", Math.max(...topSpread) > 0.98);
// contrast: a PURE ring's Elo champion is pure schedule noise
const rps = [[0.5, 0.85, 0.15], [0.15, 0.5, 0.85], [0.85, 0.15, 0.5]];
ok("AI-contrast: a pure ring's Elo #1 is schedule-noise (no stable champion)", Math.max(...championSpread(rps, 300)) < 0.55);
console.log(`AI    cyclic=${pct(topH.cyclicFraction)}  lottery: [${topL.x.map((v) => pct(v)).join(", ")}]  (champion stable: ${pct(Math.max(...topSpread))})`);

// ── 4 · THE LIFE — the side-blotched lizard ──
out.push("");
out.push("4. THE LIFE — the side-blotched lizard: rock-paper-scissors made of animals");
const { P: lP, margin: lMargin, morphs } = lizardTournament(0.85);
ok("life: orange→blue→yellow→orange is a true 3-cycle (each wins once, loses once)", (() => { const w = [0, 0, 0], l = [0, 0, 0]; for (const [a, b] of lizardCycle) { w[["orange", "blue", "yellow"].indexOf(a)]++; l[["orange", "blue", "yellow"].indexOf(b)]++; } return w.every((x) => x === 1) && l.every((x) => x === 1); })());
ok("life: no morph beats both others (no champion)", !lP.some((row, i) => row.every((p, j) => i === j || p > 0.5)));
const lH = hodgeFromY(lMargin);
ok("life: cyclic fraction = 100% (a pure symmetric ring, convention-free)", near(lH.cyclicFraction, 1, 1e-12));
const lL = maximalLottery(lP);
ok("life: maximal lottery is uniform 1/3 — the cycle keeps all three alive", lL.x.every((v) => near(v, 1 / 3, 2e-3)));
// same abstract object as the coin's ring and the votes' ring (a 3-cycle up to relabelling)
ok("life: the lizard ring == the votes ring up to relabelling (one shape)", JSON.stringify(lMargin) === JSON.stringify(cMargin) || JSON.stringify(lMargin) === JSON.stringify(cMargin.map((r) => r.map((v) => -v))));
console.log(`LIFE  cyclic=${pct(lH.cyclicFraction)}  lottery: [${lL.x.map((v) => pct(v)).join(", ")}]`);

// ── 5 · THE UMBRELLA — one lens, one spectrum, one resolution ──
out.push("");
out.push("5. THE UMBRELLA — the four domains are one phenomenon on a single ruler");
// the spectrum the page prints, low to high
const spectrum = [["AI / leaderboards", topH.cyclicFraction], ["the coin / Penney", coinH.cyclicFraction], ["the votes / Condorcet", cH.cyclicFraction], ["life / the lizard", lH.cyclicFraction]];
const sorted = [...spectrum].sort((a, b) => a[1] - b[1]);
ok("umbrella: the spectrum runs AI(12%) < coin(56%) < votes=life(100%)", sorted[0][0] === "AI / leaderboards" && sorted[3][1] >= sorted[0][1] && near(sorted[2][1], 1) && near(sorted[3][1], 1));
ok("umbrella: every domain has a NONZERO cyclic part (none is a clean ladder)", spectrum.every(([, f]) => f > 0.1));
// the generic-case claim: among the 4 distinct 3-node tournaments (up to relabelling),
// one of the 2 strongly-connected ones is the 3-cycle — cyclicity is not a rare accident.
function tournamentsOn3() {
  // 3 unordered pairs, each oriented 2 ways -> 8 labelled tournaments; classify by #cycles
  let cyclic = 0, total = 0;
  for (let m = 0; m < 8; m++) {
    const ab = (m & 1) ? 1 : -1, bc = (m & 2) ? 1 : -1, ca = (m & 4) ? 1 : -1;
    total++;
    // a 3-node tournament is cyclic iff all three edges agree around the loop
    if ((ab > 0 && bc > 0 && ca > 0) || (ab < 0 && bc < 0 && ca < 0)) cyclic++;
  }
  return { cyclic, total };
}
const t3 = tournamentsOn3();
ok("umbrella: 2 of the 8 labelled 3-tournaments are full rings (25% — not vanishing)", t3.cyclic === 2 && t3.total === 8);
ok("umbrella: the honest answer everywhere is a DISTRIBUTION that is a valid Nash (value ≈ 0)", [coinL, cL, topL, lL].every((L) => near(L.value, 0, 5e-3)));

console.log("\nTHE SPECTRUM (cyclic share — what no single number can hold):");
for (const [name, f] of spectrum) console.log(`  ${name.padEnd(24)} ${pct(f).padStart(7)}`);

// ───────────────────────── report ─────────────────────────
console.log("\n" + out.join("\n"));
console.log(`\n${FAIL === 0 ? "✓ ALL" : "✗ " + PASS + "/"} ${PASS + FAIL} checks ${FAIL === 0 ? "PASS" : "FAIL (" + FAIL + ")"}`);
process.exit(FAIL === 0 ? 0 : 1);
