// verify-half-of-what-is-contested.mjs
// Offline recomputation of every number shown by /strata/half-of-what-is-contested/.
//
// The subject: Mishnah Ketubot 93a records three divisions of an estate among
// three creditors (in the text: three wives holding ketubah claims of 100, 200
// and 300 zuz against the estate of a man who died leaving less than the sum).
//
//     estate 100  ->  (33 1/3, 33 1/3, 33 1/3)   equal shares
//     estate 200  ->  (50,     75,     75    )   neither equal nor proportional
//     estate 300  ->  (50,    100,    150    )   proportional
//
// The middle row is what made the passage famous as a puzzle: it is neither
// equal division nor proportional division, and the Mishnah states no general
// rule. Aumann and Maschler (Journal of Economic Theory 36(2), 1985, 195-213)
// showed that all three rows are the NUCLEOLUS of the coalitional game
//
//     v(S) = max(E - sum of claims outside S, 0)
//
// and that the unique division rule which is pairwise consistent with the
// two-claimant contested-garment rule of Bava Metzia 2a coincides with the
// nucleolus for every estate and every claims vector.
//
// This script proves, from scratch and with no dependencies:
//   1. the contested-garment base case (claims "all" and "half" -> 3/4, 1/4);
//   2. the CG-consistent (Talmud) rule reproduces the three Mishnah rows exactly;
//   3. the nucleolus, computed by an honest lexicographic-minimax LP solved by
//      vertex enumeration (nothing hardcoded), equals the CG rule at those rows;
//   4. they agree not at three points but across the whole estate range, and for
//      randomly drawn claims vectors with 3, 4 and 5 claimants;
//   5. the self-duality phase change: below half the total debt the rule is
//      constrained equal awards on half-claims; above it, the mirror in losses;
//   6. pairwise consistency holds at every estate value (the property that
//      defines the rule);
//   7. the nucleolus differs from the Shapley value and from proportional
//      division, so the coincidence is not trivial.
//
//   run:  node research/half-of-what-is-contested/verify-half-of-what-is-contested.mjs

let fails = 0;
const ok = (name, cond, extra = '') => {
  if (!cond) fails++;
  console.log(`${cond ? '  ok' : 'FAIL'}  ${name}${extra ? '   ' + extra : ''}`);
};
const near = (a, b, eps = 1e-9) => Math.abs(a - b) <= eps;
const vnear = (a, b, eps = 1e-9) => a.length === b.length && a.every((x, i) => near(x, b[i], eps));
const sum = (a) => a.reduce((p, q) => p + q, 0);
const fmt = (a, k = 4) => '(' + a.map((x) => Number(x.toFixed(k))).join(', ') + ')';

// ═══════════════════════════════════════════════════════════════════════════
// 1. The contested garment rule (Bava Metzia 2a), two claimants.
//    Each claimant concedes to the other whatever they do not themselves claim;
//    the conceded part is handed over outright, and only the remainder (the
//    genuinely contested amount) is split down the middle.
// ═══════════════════════════════════════════════════════════════════════════
function cg2(E, d1, d2) {
  const u1 = Math.max(E - d2, 0);        // conceded to claimant 1
  const u2 = Math.max(E - d1, 0);        // conceded to claimant 2
  const contested = E - u1 - u2;         // what both claim
  return [u1 + contested / 2, u2 + contested / 2];
}

// ═══════════════════════════════════════════════════════════════════════════
// 2. The CG-consistent rule for n claimants (Aumann-Maschler's "Talmud rule").
//    Below half the total debt: constrained equal awards on HALF-claims,
//    x_i = min(d_i/2, lambda), with lambda set so the awards sum to E.
//    Above half: the mirror image in losses,
//    x_i = d_i - min(d_i/2, mu), with the losses summing to D - E.
//    Nothing about this construction mentions coalitions or the nucleolus.
// ═══════════════════════════════════════════════════════════════════════════
function levelFor(A, halves) {
  // solve sum_i min(h_i, lambda) = A exactly, for 0 <= A <= sum(halves)
  const h = halves.slice().sort((a, b) => a - b);
  const n = h.length;
  let used = 0;
  for (let k = 0; k < n; k++) {
    const lam = (A - used) / (n - k);
    if (lam <= h[k] + 1e-12) return Math.max(lam, 0);
    used += h[k];
  }
  return h[n - 1];
}
function talmud(E, d) {
  const D = sum(d), halves = d.map((x) => x / 2);
  if (E <= D / 2) {
    const lam = levelFor(E, halves);
    return halves.map((h) => Math.min(h, lam));
  }
  const mu = levelFor(D - E, halves);
  return d.map((di, i) => di - Math.min(halves[i], mu));
}

// ═══════════════════════════════════════════════════════════════════════════
// 3. The nucleolus, computed. No lookup tables.
//    Lexicographic minimax of the excess vector e(S,x) = v(S) - sum_{i in S} x_i
//    over the imputation set, by the Maschler-Peleg-Shapley round scheme. Each
//    round is a small linear program, and each LP is solved EXACTLY by
//    enumerating the vertices of its feasible polyhedron (an optimum of a
//    bounded LP is attained at a vertex; a vertex is where n linearly
//    independent constraints hold with equality).
// ═══════════════════════════════════════════════════════════════════════════
function zeros(n) { return new Array(n).fill(0); }
function dot(a, b) { let s = 0; for (let i = 0; i < a.length; i++) s += a[i] * b[i]; return s; }

function solveSquare(A, b, n) {         // Gaussian elimination, partial pivoting
  const M = A.map((r, i) => r.slice(0, n).concat([b[i]]));
  for (let c = 0; c < n; c++) {
    let p = c;
    for (let r = c + 1; r < n; r++) if (Math.abs(M[r][c]) > Math.abs(M[p][c])) p = r;
    if (Math.abs(M[p][c]) < 1e-10) return null;   // singular: not a vertex
    const t = M[c]; M[c] = M[p]; M[p] = t;
    for (let r = 0; r < n; r++) {
      if (r === c) continue;
      const f = M[r][c] / M[c][c];
      if (f === 0) continue;
      for (let k = c; k <= n; k++) M[r][k] -= f * M[c][k];
    }
  }
  return M.map((r, i) => r[n] / r[i]);
}

function matRank(rows, n) {
  const M = rows.map((r) => r.slice(0, n));
  let rank = 0;
  for (let c = 0; c < n && rank < M.length; c++) {
    let p = -1;
    for (let r = rank; r < M.length; r++) if (Math.abs(M[r][c]) > 1e-9) { p = r; break; }
    if (p < 0) continue;
    const t = M[rank]; M[rank] = M[p]; M[p] = t;
    for (let r = 0; r < M.length; r++) {
      if (r === rank) continue;
      const f = M[r][c] / M[rank][c];
      for (let k = c; k < n; k++) M[r][k] -= f * M[rank][k];
    }
    rank++;
  }
  return rank;
}

// Drop linearly dependent equality rows (they are consistent by construction here,
// but a dependent row makes every candidate vertex system singular).
function pruneEq(A, b, n) {
  const keepA = [], keepB = [];
  for (let i = 0; i < A.length; i++) {
    const trial = keepA.concat([A[i]]);
    if (matRank(trial, n) === trial.length) { keepA.push(A[i]); keepB.push(b[i]); }
  }
  return [keepA, keepB];
}

// minimize c.z subject to Aeq z = beq, Ale z <= ble, by vertex enumeration
function lpMin(n, c, Aeq, beq, Ale, ble) {
  const need = n - Aeq.length;
  if (need < 0) return null;
  const m = Ale.length;
  let best = null;
  const pick = [];
  (function rec(start) {
    if (pick.length === need) {
      const A = Aeq.concat(pick.map((i) => Ale[i]));
      const b = beq.concat(pick.map((i) => ble[i]));
      const z = solveSquare(A, b, n);
      if (!z) return;
      for (let i = 0; i < Aeq.length; i++) if (Math.abs(dot(Aeq[i], z) - beq[i]) > 1e-7) return;
      for (let i = 0; i < m; i++) if (dot(Ale[i], z) - ble[i] > 1e-7) return;
      const val = dot(c, z);
      if (!best || val < best.val - 1e-13) best = { val, z };
      return;
    }
    for (let i = start; i < m; i++) { pick.push(i); rec(i + 1); pick.pop(); }
  })(0);
  return best;
}

function worths(d, E) {
  const n = d.length, M = (1 << n) - 1, v = new Array(1 << n).fill(0);
  for (let S = 1; S <= M; S++) {
    let outside = 0;
    for (let i = 0; i < n; i++) if (!((S >> i) & 1)) outside += d[i];
    v[S] = Math.max(E - outside, 0);
  }
  v[M] = E;
  return v;
}

function nucleolus(d, E) {
  const n = d.length, M = (1 << n) - 1, v = worths(d, E), N1 = n + 1;
  const effRow = zeros(N1); for (let i = 0; i < n; i++) effRow[i] = 1;
  const irA = [], irB = [];
  for (let i = 0; i < n; i++) { const r = zeros(N1); r[i] = -1; irA.push(r); irB.push(-v[1 << i]); }
  let active = []; for (let S = 1; S < M; S++) active.push(S);
  const fixed = [];
  let x = null;

  for (let round = 0; round < n + 4; round++) {
    const Aeq = [effRow], beq = [E];
    for (const f of fixed) {
      const r = zeros(N1); for (let i = 0; i < n; i++) if ((f.S >> i) & 1) r[i] = 1;
      Aeq.push(r); beq.push(v[f.S] - f.t);
    }
    if (matRank(Aeq, n) >= n) { break; }
    const [Aeq2, beq2] = pruneEq(Aeq, beq, N1);
    const Ale = irA.slice(), ble = irB.slice();
    for (const S of active) {
      const r = zeros(N1); for (let i = 0; i < n; i++) if ((S >> i) & 1) r[i] = -1;
      r[n] = -1; Ale.push(r); ble.push(-v[S]);
    }
    const cT = zeros(N1); cT[n] = 1;
    const res = lpMin(N1, cT, Aeq2, beq2, Ale, ble);
    if (!res) return null;
    const tStar = res.val;
    x = res.z.slice(0, n);

    // which active coalitions are pinned at tStar in EVERY optimal solution?
    const AeqX = Aeq2.map((r) => r.slice(0, n)), beqX = beq2.slice();
    const AleX = [], bleX = [];
    for (let i = 0; i < n; i++) { const r = zeros(n); r[i] = -1; AleX.push(r); bleX.push(-v[1 << i]); }
    for (const S of active) {
      const r = zeros(n); for (let i = 0; i < n; i++) if ((S >> i) & 1) r[i] = -1;
      AleX.push(r); bleX.push(tStar - v[S]);
    }
    const newly = [];
    for (const S of active) {
      const cc = zeros(n); for (let i = 0; i < n; i++) if ((S >> i) & 1) cc[i] = -1;
      const r2 = lpMin(n, cc, AeqX, beqX, AleX, bleX);
      if (!r2) continue;
      const minExcess = v[S] + r2.val;          // r2.val = -sum_{i in S} x_i
      if (minExcess > tStar - 1e-7) newly.push(S);
    }
    if (!newly.length) break;
    for (const S of newly) fixed.push({ S, t: tStar });
    active = active.filter((S) => newly.indexOf(S) < 0);

    const rows = [effRow.slice(0, n)];
    for (const f of fixed) { const r = zeros(n); for (let i = 0; i < n; i++) if ((f.S >> i) & 1) r[i] = 1; rows.push(r); }
    if (matRank(rows, n) >= n) {
      // equalities now determine x uniquely; solve them
      const sq = [], sb = [];
      const chosen = [];
      for (let i = 0; i < rows.length && chosen.length < n; i++) {
        const trial = chosen.concat([i]);
        if (matRank(trial.map((j) => rows[j]), n) === trial.length) chosen.push(i);
      }
      for (const i of chosen) { sq.push(rows[i]); sb.push(i === 0 ? E : v[fixed[i - 1].S] - fixed[i - 1].t); }
      const zz = solveSquare(sq, sb, n);
      if (zz) x = zz;
      break;
    }
  }
  return x;
}

// The Shapley value, for the contrast check (it is NOT the Mishnah's answer).
function shapley(d, E) {
  const n = d.length, v = worths(d, E), phi = zeros(n);
  const perm = [];
  (function go(rest) {
    if (!rest.length) {
      let S = 0;
      for (const i of perm) { const S2 = S | (1 << i); phi[i] += v[S2] - v[S]; S = S2; }
      return;
    }
    for (let k = 0; k < rest.length; k++) {
      perm.push(rest[k]);
      go(rest.slice(0, k).concat(rest.slice(k + 1)));
      perm.pop();
    }
  })([...Array(n).keys()]);
  let f = 1; for (let i = 2; i <= n; i++) f *= i;
  return phi.map((p) => p / f);
}

// ═══════════════════════════════════════════════════════════════════════════
//   CHECK 1 — the contested garment base case, Bava Metzia 2a
// ═══════════════════════════════════════════════════════════════════════════
console.log('\n— the contested garment (Bava Metzia 2a): one claims all, one claims half —');
{
  const g = cg2(1, 1, 0.5);
  console.log(`  garment worth 1, claims (1, 1/2)  ->  (${g[0]}, ${g[1]})`);
  ok('claimant of the whole receives 3/4', near(g[0], 0.75));
  ok('claimant of the half receives 1/4', near(g[1], 0.25));
  ok('the split is not proportional (2/3, 1/3)', !near(g[0], 2 / 3, 1e-6));
  ok('the split is not equal (1/2, 1/2)', !near(g[0], 0.5, 1e-6));
  // the two-claimant Talmud rule IS the contested garment rule
  let worst = 0;
  for (let d1 = 1; d1 <= 40; d1++) for (let d2 = 1; d2 <= 40; d2++)
    for (let E = 0; E <= d1 + d2; E += 0.5) {
      const a = cg2(E, d1, d2), b = talmud(E, [d1, d2]);
      worst = Math.max(worst, Math.abs(a[0] - b[0]), Math.abs(a[1] - b[1]));
    }
  ok('two-claimant Talmud rule = contested garment rule everywhere',
     worst < 1e-9, `max |diff| = ${worst.toExponential(2)} over 1600 claim pairs`);
}

// ═══════════════════════════════════════════════════════════════════════════
//   CHECK 2 — the three Mishnah rows, from the rule
// ═══════════════════════════════════════════════════════════════════════════
console.log('\n— Mishnah Ketubot 93a, claims (100, 200, 300) —');
const CLAIMS = [100, 200, 300];
const MISHNAH = [
  { E: 100, x: [100 / 3, 100 / 3, 100 / 3], label: 'equal thirds' },
  { E: 200, x: [50, 75, 75], label: 'neither equal nor proportional' },
  { E: 300, x: [50, 100, 150], label: 'proportional' },
];
for (const row of MISHNAH) {
  const t = talmud(row.E, CLAIMS);
  console.log(`  estate ${String(row.E).padStart(3)}  rule -> ${fmt(t)}   [${row.label}]`);
  ok(`estate ${row.E}: CG-consistent rule reproduces the Mishnah`, vnear(t, row.x, 1e-9));
  ok(`estate ${row.E}: shares sum to the estate`, near(sum(t), row.E, 1e-9));
}
ok('estate 100 is EQUAL division, not proportional',
   near(talmud(100, CLAIMS)[0], talmud(100, CLAIMS)[2], 1e-9));
ok('estate 300 is PROPORTIONAL division (50, 100, 150)',
   vnear(talmud(300, CLAIMS), [50, 100, 150], 1e-9));
ok('estate 200 is neither: not equal',
   !near(talmud(200, CLAIMS)[0], talmud(200, CLAIMS)[1], 1e-6));
ok('estate 200 is neither: not proportional (would be 33.33, 66.67, 100)',
   !vnear(talmud(200, CLAIMS), [100 / 3, 200 / 3, 100], 1e-6));

// ═══════════════════════════════════════════════════════════════════════════
//   CHECK 3 — the nucleolus, computed, equals the rule at those rows
// ═══════════════════════════════════════════════════════════════════════════
console.log('\n— the nucleolus of v(S) = max(E - claims outside S, 0), computed —');
for (const row of MISHNAH) {
  const nu = nucleolus(CLAIMS, row.E);
  console.log(`  estate ${String(row.E).padStart(3)}  nucleolus -> ${fmt(nu)}`);
  ok(`estate ${row.E}: nucleolus = Mishnah division`, vnear(nu, row.x, 1e-7));
}
{
  // the coalition worths at E = 200, printed so the reader can audit the game
  const v = worths(CLAIMS, 200);
  const names = ['{1}', '{2}', '{1,2}', '{3}', '{1,3}', '{2,3}', '{1,2,3}'];
  const order = [1, 2, 3, 4, 5, 6, 7];
  console.log('  worths at E=200: ' + order.map((S, i) => `v${names[i]}=${v[S]}`).join('  '));
  ok('v({2,3}) = 100 at E = 200 (the only coalition worth anything)',
     near(v[6], 100) && near(v[1], 0) && near(v[2], 0) && near(v[4], 0) &&
     near(v[3], 0) && near(v[5], 0));
  // the excess vector at (50,75,75), sorted descending
  const x = [50, 75, 75];
  const exc = [];
  for (let S = 1; S < 7; S++) {
    let s = 0; for (let i = 0; i < 3; i++) if ((S >> i) & 1) s += x[i];
    exc.push(v[S] - s);
  }
  exc.sort((a, b) => b - a);
  console.log('  excesses at (50,75,75), sorted: [' + exc.join(', ') + ']');
  ok('largest excess at (50,75,75) is -50, attained twice ({1} and {2,3})',
     near(exc[0], -50) && near(exc[1], -50) && exc[2] < -50 + 1e-9);
}

// ═══════════════════════════════════════════════════════════════════════════
//   CHECK 4 — not three points: they agree across the whole range,
//             and for random claims vectors with 3, 4 and 5 claimants
// ═══════════════════════════════════════════════════════════════════════════
console.log('\n— the coincidence is not a curve fit —');
{
  let worst = 0, worstE = 0;
  for (let E = 0; E <= 600; E += 2) {
    const a = talmud(E, CLAIMS), b = nucleolus(CLAIMS, E);
    const dd = Math.max(...a.map((q, i) => Math.abs(q - b[i])));
    if (dd > worst) { worst = dd; worstE = E; }
  }
  ok('rule = nucleolus at all 301 estate values 0,2,...,600',
     worst < 1e-7, `max |diff| = ${worst.toExponential(2)} (at E=${worstE})`);
}
{
  // deterministic pseudo-random claims vectors (mulberry32) so the run is reproducible
  let s = 0x9e3779b9;
  const rnd = () => { s |= 0; s = (s + 0x6D2B79F5) | 0;
    let t = Math.imul(s ^ (s >>> 15), 1 | s);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296; };
  for (const [n, trials] of [[3, 200], [4, 12]]) {
    let worst = 0;
    for (let k = 0; k < trials; k++) {
      const d = Array.from({ length: n }, () => 1 + Math.floor(rnd() * 400));
      const D = sum(d), E = rnd() * D;
      const a = talmud(E, d), b = nucleolus(d, E);
      if (!b) { worst = Infinity; break; }
      worst = Math.max(worst, ...a.map((q, i) => Math.abs(q - b[i])));
    }
    ok(`${n} claimants: rule = nucleolus on ${trials} random (claims, estate) draws`,
       worst < 1e-6, `max |diff| = ${worst.toExponential(2)}`);
  }
  // For 5 and 6 claimants the exact LP enumeration gets expensive, so instead we
  // ATTACK the rule's output: search hard for any other allocation whose sorted
  // excess vector is lexicographically smaller. Finding one would refute the
  // identity. This is falsification, not proof, and the page says so.
  const lexSmaller = (a, b, eps = 1e-9) => {         // is sorted-desc a < b ?
    for (let i = 0; i < a.length; i++) {
      if (a[i] < b[i] - eps) return true;
      if (a[i] > b[i] + eps) return false;
    }
    return false;
  };
  const excSorted = (d, E, x) => {
    const n = d.length, v = worths(d, E), out = [];
    for (let S = 1; S < (1 << n) - 1; S++) {
      let s = 0; for (let i = 0; i < n; i++) if ((S >> i) & 1) s += x[i];
      out.push(v[S] - s);
    }
    return out.sort((p, q) => q - p);
  };
  for (const n of [5, 6]) {
    let beaten = 0, cases = 40, probes = 4000;
    for (let k = 0; k < cases; k++) {
      const d = Array.from({ length: n }, () => 1 + Math.floor(rnd() * 400));
      const D = sum(d), E = rnd() * D;
      const x = talmud(E, d), ex = excSorted(d, E, x);
      for (let p = 0; p < probes; p++) {
        const y = x.slice();
        // random zero-sum perturbation of shrinking size, kept feasible
        const step = Math.pow(10, -1 - 4 * rnd()) * (D || 1);
        const i = Math.floor(rnd() * n); let j = Math.floor(rnd() * n);
        if (j === i) j = (j + 1) % n;
        const dlt = step * (rnd() < 0.5 ? -1 : 1);
        y[i] += dlt; y[j] -= dlt;
        if (y[i] < -1e-12 || y[j] < -1e-12 || y[i] > d[i] + 1e-12 || y[j] > d[j] + 1e-12) continue;
        if (lexSmaller(excSorted(d, E, y), ex)) beaten++;
      }
    }
    ok(`${n} claimants: ${cases * probes} probes found nothing lexicographically better`,
       beaten === 0, `${beaten} improvements found`);
  }
}

// ═══════════════════════════════════════════════════════════════════════════
//   CHECK 5 — the self-duality phase change at E = D/2
// ═══════════════════════════════════════════════════════════════════════════
console.log('\n— the half-debt hinge: gains below, losses above —');
{
  const D = sum(CLAIMS);
  ok('at E = D/2 = 300 every claimant has exactly half their claim',
     vnear(talmud(300, CLAIMS), CLAIMS.map((c) => c / 2), 1e-9), fmt(talmud(300, CLAIMS)));
  // self-duality: awards at E mirror losses at D-E
  let worst = 0;
  for (let E = 0; E <= D; E += 1) {
    const a = talmud(E, CLAIMS), b = talmud(D - E, CLAIMS);
    for (let i = 0; i < 3; i++) worst = Math.max(worst, Math.abs(a[i] - (CLAIMS[i] - b[i])));
  }
  ok('self-dual: award(E) = claim - award(D-E), for every E', worst < 1e-9,
     `max |diff| = ${worst.toExponential(2)}`);
  console.log(`  award(200) = ${fmt(talmud(200, CLAIMS), 2)}   loss(400) = ${fmt(talmud(400, CLAIMS).map((x, i) => CLAIMS[i] - x), 2)}`);
  ok('losses at E=400 equal awards at E=200: (50, 75, 75)',
     vnear(talmud(400, CLAIMS).map((x, i) => CLAIMS[i] - x), [50, 75, 75], 1e-9));
  // below the hinge nobody exceeds half their claim; above it nobody falls short
  let below = true, above = true;
  for (let E = 0; E <= D; E += 1) {
    const a = talmud(E, CLAIMS);
    for (let i = 0; i < 3; i++) {
      if (E < D / 2 && a[i] > CLAIMS[i] / 2 + 1e-9) below = false;
      if (E > D / 2 && a[i] < CLAIMS[i] / 2 - 1e-9) above = false;
    }
  }
  ok('below the hinge no one gets more than half their claim', below);
  ok('above the hinge no one gets less than half their claim', above);
}

// ═══════════════════════════════════════════════════════════════════════════
//   CHECK 6 — pairwise consistency (the property that DEFINES the rule)
// ═══════════════════════════════════════════════════════════════════════════
console.log('\n— pairwise consistency: hand any two claimants their joint total —');
{
  let worst = 0;
  const d = CLAIMS;
  for (let E = 0; E <= 600; E += 0.5) {
    const x = talmud(E, d);
    for (let i = 0; i < 3; i++) for (let j = i + 1; j < 3; j++) {
      const pair = cg2(x[i] + x[j], d[i], d[j]);
      worst = Math.max(worst, Math.abs(pair[0] - x[i]), Math.abs(pair[1] - x[j]));
    }
  }
  ok('every pair re-divides its own total back to the same two numbers',
     worst < 1e-9, `max |diff| = ${worst.toExponential(2)} over 1201 estates x 3 pairs`);
  const x2 = talmud(200, CLAIMS);
  console.log(`  E=200: claimants 2 and 3 hold ${x2[1] + x2[2]} between them; ` +
              `CG(${x2[1] + x2[2]}; 200, 300) = ${fmt(cg2(x2[1] + x2[2], 200, 300), 2)}`);
  // a counterexample hunt: proportional division is NOT pairwise CG-consistent
  const prop = CLAIMS.map((c) => 200 * c / sum(CLAIMS));
  const p23 = cg2(prop[1] + prop[2], 200, 300);
  ok('proportional division FAILS the same test (so the test has teeth)',
     Math.abs(p23[0] - prop[1]) > 1, `proportional gives ${fmt(prop, 2)}, pair re-divide ${fmt(p23, 2)}`);
}

// ═══════════════════════════════════════════════════════════════════════════
//   CHECK 7 — the nucleolus is not the Shapley value, nor proportional
// ═══════════════════════════════════════════════════════════════════════════
console.log('\n— what the nucleolus is NOT —');
{
  const sh = shapley(CLAIMS, 200);
  console.log(`  E=200  nucleolus ${fmt(talmud(200, CLAIMS), 3)}   Shapley ${fmt(sh, 3)}`);
  ok('Shapley value is efficient (sums to 200)', near(sum(sh), 200, 1e-7));
  ok('Shapley value differs from the Mishnah division at E = 200',
     !vnear(sh, [50, 75, 75], 1e-3), `Shapley = ${fmt(sh, 3)}`);
  const prop = CLAIMS.map((c) => 200 * c / 600);
  ok('proportional division differs from the Mishnah division at E = 200',
     !vnear(prop, [50, 75, 75], 1e-3), `proportional = ${fmt(prop, 3)}`);
  const eq = [200 / 3, 200 / 3, 200 / 3];
  ok('equal division differs from the Mishnah division at E = 200', !vnear(eq, [50, 75, 75], 1e-3));
}

// ═══════════════════════════════════════════════════════════════════════════
//   CHECK 8 — numbers the page prints verbatim
// ═══════════════════════════════════════════════════════════════════════════
console.log('\n— page constants —');
{
  ok('total debt D = 600', near(sum(CLAIMS), 600));
  ok('hinge D/2 = 300', near(sum(CLAIMS) / 2, 300));
  ok('33 1/3 rendered as 33.33 to two places', talmud(100, CLAIMS)[0].toFixed(2) === '33.33');
  ok('at E = 600 everyone is paid in full', vnear(talmud(600, CLAIMS), CLAIMS, 1e-9));
  ok('at E = 0 nobody gets anything', vnear(talmud(0, CLAIMS), [0, 0, 0], 1e-12));
  // the level lambda at the three rows
  ok('lambda at E=100 is 100/3', near(levelFor(100, CLAIMS.map((c) => c / 2)), 100 / 3, 1e-9));
  ok('lambda at E=200 is 75', near(levelFor(200, CLAIMS.map((c) => c / 2)), 75, 1e-9));
  ok('lambda at E=300 is 150', near(levelFor(300, CLAIMS.map((c) => c / 2)), 150, 1e-9));
  // continuity / monotonicity of the rule in the estate
  let mono = true;
  let prev = talmud(0, CLAIMS);
  for (let E = 0.5; E <= 600; E += 0.5) {
    const cur = talmud(E, CLAIMS);
    for (let i = 0; i < 3; i++) if (cur[i] < prev[i] - 1e-12) mono = false;
    prev = cur;
  }
  ok('every claimant is weakly better off as the estate grows (monotone)', mono);
}

// ═══════════════════════════════════════════════════════════════════════════
//   CHECK 9 — the rival rules the page overlays, and the two estates it names
// ═══════════════════════════════════════════════════════════════════════════
console.log('\n— rival rules the page draws —');
{
  const cea = (E, d) => { const lam = levelFor(E, d.slice()); return d.map((c) => Math.min(c, lam)); };
  const prop = (E, d) => d.map((c) => E * c / sum(d));
  ok('constrained equal awards on FULL claims at E=200 is (66.67, 66.67, 66.67)',
     vnear(cea(200, CLAIMS), [200 / 3, 200 / 3, 200 / 3], 1e-9), fmt(cea(200, CLAIMS), 2));
  ok('Shapley value at E=200 is (33.333, 83.333, 83.333)',
     vnear(shapley(CLAIMS, 200), [100 / 3, 250 / 3, 250 / 3], 1e-7), fmt(shapley(CLAIMS, 200), 3));
  const p = prop(200, CLAIMS);
  ok('proportional hands claimants 2 and 3 a joint 166.67 at E=200',
     near(p[1] + p[2], 500 / 3, 1e-9), `${(p[1] + p[2]).toFixed(2)}`);
  ok('the garment rule splits that joint pot 83.33 / 83.33, not 66.67 / 100',
     vnear(cg2(p[1] + p[2], 200, 300), [250 / 3, 250 / 3], 1e-9), fmt(cg2(p[1] + p[2], 200, 300), 2));
  // the two off-table estates the prose names
  for (const E of [137, 412.5]) {
    const a = talmud(E, CLAIMS), b = nucleolus(CLAIMS, E);
    ok(`estate ${E}: rule ${fmt(a, 4)} = nucleolus ${fmt(b, 4)}`,
       vnear(a, b, 1e-6), `gap ${Math.max(...a.map((q, i) => Math.abs(q - b[i]))).toExponential(1)}`);
  }
  // the vessel levels the canvas labels
  const halves = CLAIMS.map((c) => c / 2);
  ok('at E=200 the floor-basin level is lambda = 75 and the ceiling basin is all shortfall',
     near(levelFor(200, halves), 75, 1e-9) && 200 <= sum(CLAIMS) / 2);
  ok('at E=400 the floor basin is full and the shortfall level is mu = 75',
     near(levelFor(sum(CLAIMS) - 400, halves), 75, 1e-9));
  ok('water in the two basins reconstructs the award at E=400',
     vnear(halves.map((h) => h + (h - Math.min(h, levelFor(200, halves)))),
           talmud(400, CLAIMS), 1e-9), fmt(talmud(400, CLAIMS), 2));
}

console.log(`\n${fails === 0 ? 'ALL CHECKS PASSED' : fails + ' CHECK(S) FAILED'}\n`);
process.exit(fails === 0 ? 0 : 1);
