#!/usr/bin/env node
// ============================================================================
// THE BILL, THE FLOOR, AND THE LEAK   ·   verifier
// ----------------------------------------------------------------------------
// A combine portal. Seven layers already standing in this corpus each compute
// one "unavoidable trade-off." Put them on one axis and the thing that sorts
// them is not the field and not the size of the penalty. It is the COMPARISON
// SIGN the theorem carries, and the sign is the whole instruction:
//
//   =    an EQUALITY.  The total is exactly fixed. Nothing is lost and nothing
//        is gained; improvement is pure relocation. Tuning = choosing WHERE to pay.
//          - Bode, stable loop:  integral of ln|S| dw  =  0            (rung 1)
//          - the fridge:         Qh - Qc = W, and d(net)/d(COP) = 0    (rung 2)
//          - Den Hartog:         two ordinates no damping can move     (rung 3)
//          - Bode, unstable plant: integral = pi*a = 12.05 (same member,
//            same sign, a nonzero value: the plant's unstable pole is a tax)
//
//   =    an equality with NOWHERE TO PUT IT. Exactly pinned, and untradeable:
//        no band, no boundary, no protocol to move the cost into.
//          - Cauchy:             IQR(mean of n) = 2, for every n       (rung 4)
//
//   >=   a FLOOR. You can be worse than it, never better, so there is slack
//        ABOVE the wall. Tuning = how much you waste.
//          - Landauer:           >= kT ln2 = 2.871 zJ at 300 K         (rung 5)
//
//   <=   a MONOVARIANT. A one-way leak. Nothing can be placed; the very best
//        move merely fails to lose. Tuning = not leaking.
//          - Conway's soldiers:  sigma-weight, straight jump conserves,
//                                every other jump strictly loses       (rung 6)
//
//   none NO SIGN AT ALL. A design budget wearing a law's clothes.
//          - active noise cancelling: the ~1 kHz ceiling is soft and
//            partly purchasable, and the member says so itself         (foil)
//
// PORTAL LAW: this page adds NO new fact. Every number it shows is a member's
// own. Part A re-derives each one from scratch here. Part B re-runs every
// member's own verifier fresh. Part C confirms each figure the portal prints
// appears verbatim in that member's committed source.
//
// Run:  node research/the-bill-the-floor-and-the-leak/verify.mjs
// Exit 0 = every check passed.
// ============================================================================

import { execFileSync } from 'node:child_process';
import { readFileSync, existsSync, readdirSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, resolve } from 'node:path';

const HERE = dirname(fileURLToPath(import.meta.url));
const ROOT = resolve(HERE, '..', '..');

let pass = 0, fail = 0;
const ok = (name, cond, extra = '') => {
  if (cond) pass++; else fail++;
  console.log(`${cond ? '  ok  ' : 'FAIL  '}${name}${extra ? '   ' + extra : ''}`);
};
const near = (a, b, eps) => Number.isFinite(a) && Number.isFinite(b) && Math.abs(a - b) <= eps;
const head = (s) => console.log(`\n${s}\n${'-'.repeat(s.length)}`);

// ===========================================================================
// A0. Primitives, written from scratch here. No member code is imported.
// ===========================================================================
const C = (re, im = 0) => ({ re, im });
const cadd = (a, b) => C(a.re + b.re, a.im + b.im);
const csub = (a, b) => C(a.re - b.re, a.im - b.im);
const cmul = (a, b) => C(a.re * b.re - a.im * b.im, a.re * b.im + a.im * b.re);
const cdiv = (a, b) => { const d = b.re * b.re + b.im * b.im; return C((a.re * b.re + a.im * b.im) / d, (a.im * b.re - a.re * b.im) / d); };
const cabs = (a) => Math.hypot(a.re, a.im);

const pmul = (a, b) => { const r = new Array(a.length + b.length - 1).fill(0); for (let i = 0; i < a.length; i++) for (let j = 0; j < b.length; j++) r[i + j] += a[i] * b[j]; return r; };
const padd = (a, b) => { const n = Math.max(a.length, b.length), r = new Array(n).fill(0); for (let i = 0; i < a.length; i++) r[n - a.length + i] += a[i]; for (let i = 0; i < b.length; i++) r[n - b.length + i] += b[i]; return r; };
const pev = (p, s) => { let acc = C(0, 0); for (const c of p) acc = cadd(cmul(acc, s), C(c, 0)); return acc; };

// Routh-Hurwitz: all roots strictly in the left half plane? No root finder used.
function routhStable(pIn) {
  const p = pIn.slice();
  while (p.length && Math.abs(p[0]) < 1e-14) p.shift();
  const n = p.length - 1;
  if (n < 1) return false;
  if (p[0] < 0) for (let i = 0; i < p.length; i++) p[i] = -p[i];
  for (const c of p) if (c <= 0) return false;
  const rows = [[], []];
  for (let i = 0; i < p.length; i += 2) rows[0].push(p[i]);
  for (let i = 1; i < p.length; i += 2) rows[1].push(p[i]);
  while (rows[1].length < rows[0].length) rows[1].push(0);
  for (let r = 2; r <= n; r++) {
    const a = rows[r - 2], b = rows[r - 1], row = [];
    if (Math.abs(b[0]) < 1e-14) return false;
    for (let i = 0; i + 1 < b.length; i++) row.push((b[0] * a[i + 1] - a[0] * b[i + 1]) / b[0]);
    row.push(0);
    rows.push(row);
  }
  for (let r = 0; r <= n; r++) if (!(rows[r][0] > 0)) return false;
  return true;
}
function rng(seed) {
  let a = seed >>> 0;
  return () => { a = (a + 0x6D2B79F5) >>> 0; let t = a; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; };
}
const quantile = (s, q) => { const h = (s.length - 1) * q, lo = Math.floor(h), hi = Math.ceil(h); return s[lo] + (h - lo) * (s[hi] - s[lo]); };

console.log('='.repeat(74));
console.log('PART A  ·  seven pins, re-derived from scratch, sorted by their sign');
console.log('='.repeat(74));

// ###########################################################################
// SIGN "="  ·  an exact equality: relocation with no residue
// ###########################################################################

// ---------------------------------------------------------------------------
// RUNG 1 · Bode's sensitivity integral. Member: the-error-you-can-only-move
// ---------------------------------------------------------------------------
head('RUNG 1  "="  Bode: integral of ln|S| dw is pinned at exactly zero');

const TF = 0.05;
const ctrl = (g) => (g.Ki > 0
  ? { n: [g.Kp * TF + g.Kd, g.Kp + g.Ki * TF, g.Ki], d: [TF, 1, 0] }
  : { n: [g.Kp * TF + g.Kd, g.Kp], d: [TF, 1] });
const CAR = { m: 1500, b: 50, ta: 0.5 };
CAR.tv = CAR.m / CAR.b;          // 30 s
CAR.K = 1 / CAR.b;               // 0.02 (m/s)/N
const cruise = { np: [CAR.K], dp: pmul([CAR.ta, 1], [CAR.tv, 1]), rhp: [] };
const ROD = { m: 0.5, L: 1.0, g: 9.81 };
ROD.J = (ROD.m * ROD.L * ROD.L) / 3;
ROD.a = Math.sqrt((3 * ROD.g) / (2 * ROD.L));
const pend = { np: [1 / ROD.J], dp: [1, 0, -ROD.a * ROD.a], rhp: [ROD.a] };

const loop = (g, pl) => { const c = ctrl(g); return { num: pmul(c.n, pl.np), den: pmul(c.d, pl.dp), rhp: pl.rhp }; };
const relDeg = (L) => (L.den.length - 1) - (L.num.length - 1);
const charPoly = (L) => padd(L.num, L.den);
const lnS = (L, w) => { const s = C(0, w), d = pev(L.den, s), t = cadd(pev(L.num, s), d); return Math.log(cabs(d) / cabs(t)); };
function bodeArea(L, panels = 40000, wlo = 1e-9, whi = 1e9) {
  const a = Math.log(wlo), b = Math.log(whi), h = (b - a) / panels;
  const f = (u) => { const w = Math.exp(u); return lnS(L, w) * w; };
  let s = f(a) + f(b);
  for (let i = 1; i < panels; i++) s += (i % 2 ? 4 : 2) * f(a + i * h);
  return (s * h) / 3;
}
const CRUISE_GAINS = [
  { Kp: 200, Ki: 0, Kd: 0, label: 'P only Kp=200' },
  { Kp: 800, Ki: 0, Kd: 0, label: 'P only Kp=800' },
  { Kp: 400, Ki: 60, Kd: 0, label: 'PI Kp=400 Ki=60' },
  { Kp: 900, Ki: 200, Kd: 60, label: 'PID Kp=900 Ki=200 Kd=60' },
  { Kp: 1500, Ki: 400, Kd: 120, label: 'PID hot Kp=1500 Ki=400 Kd=120' },
];
for (const g of CRUISE_GAINS) {
  const L = loop(g, cruise);
  ok(`relative degree 2, closed loop stable  (${g.label})`, relDeg(L) === 2 && routhStable(charPoly(L)), `relDeg=${relDeg(L)}`);
  const A = bodeArea(L);
  ok(`  area = 0                             (${g.label})`, near(A, 0, 2e-6), `area=${A.toExponential(3)}`);
}
{
  const L = loop(CRUISE_GAINS[3], cruise);
  const a1 = bodeArea(L, 20000), a2 = bodeArea(L, 40000), a3 = bodeArea(L, 80000);
  ok('quadrature converged (20k/40k/80k panels agree)', near(a1, a2, 1e-6) && near(a2, a3, 1e-7),
    `${a1.toExponential(2)} ${a2.toExponential(2)} ${a3.toExponential(2)}`);
  const r = rng(20260726);
  let n = 0, worst = 0;
  while (n < 200) {
    const g = { Kp: 20 + r() * 2000, Ki: r() < 0.3 ? 0 : r() * 500, Kd: r() < 0.3 ? 0 : r() * 200 };
    const Lr = loop(g, cruise);
    if (!routhStable(charPoly(Lr))) continue;
    worst = Math.max(worst, Math.abs(bodeArea(Lr, 20000)));
    n++;
  }
  ok('200 random STABLE tunings all pin the area at 0', worst < 5e-6, `worst |area| = ${worst.toExponential(3)}`);
}
// The equality's signature: the two signed halves each move a lot, sum does not.
function signedAreas(L, panels = 40000, wlo = 1e-9, whi = 1e9) {
  const a = Math.log(wlo), b = Math.log(whi), h = (b - a) / panels;
  const f = (u) => { const w = Math.exp(u); return lnS(L, w) * w; };
  let neg = 0, pos = 0;
  for (let i = 0; i < panels; i++) {
    const u0 = a + i * h, seg = ((f(u0) + 4 * f(u0 + h / 2) + f(u0 + h)) * h) / 6;
    if (seg < 0) neg += seg; else pos += seg;
  }
  return { neg, pos, total: neg + pos };
}
{
  const soft = signedAreas(loop({ Kp: 200, Ki: 20, Kd: 0 }, cruise));
  const hard = signedAreas(loop({ Kp: 1500, Ki: 400, Kd: 120 }, cruise));
  ok('a harder tuning buys more suppression', hard.neg < soft.neg - 0.5, `${soft.neg.toFixed(3)} -> ${hard.neg.toFixed(3)}`);
  ok('and pays for all of it in amplification', hard.pos > soft.pos + 0.5, `+${soft.pos.toFixed(3)} -> +${hard.pos.toFixed(3)}`);
  ok('both sums still zero: the bill only moved', near(soft.total, 0, 2e-6) && near(hard.total, 0, 2e-6),
    `${soft.total.toExponential(2)} / ${hard.total.toExponential(2)}`);
}
// The member's own headline: proportional gain alone keeps a permanent offset.
{
  const Fhill = CAR.m * 9.81 * Math.sin(Math.atan(0.04));
  const offsetFor = (Kp) => -(Fhill * CAR.K) / (1 + Kp * CAR.K);
  let bestKp = null, bestErr = Infinity;
  for (let Kp = 1; Kp <= 4000; Kp++) { const e = Math.abs(offsetFor(Kp) + 1.68); if (e < bestErr) { bestErr = e; bestKp = Kp; } }
  ok('hill force on a 4% grade', near(Fhill, 588.0, 1.0), `F=${Fhill.toFixed(1)} N`);
  ok('the member\'s -1.68 m/s P-only offset is reproduced', bestErr < 5e-3, `Kp=${bestKp} -> ${offsetFor(bestKp).toFixed(4)} m/s`);
  ok('no finite gain ever removes it (P alone never arrives)', offsetFor(1e9) < 0, `Kp=1e9 -> ${offsetFor(1e9).toExponential(2)} m/s`);
  ok('the integrator kills it exactly: |S(0)| = 0 when Ki > 0',
    Math.exp(lnS(loop({ Kp: 400, Ki: 60, Kd: 0 }, cruise), 1e-12)) < 1e-9,
    `|S| at w=1e-12 -> ${Math.exp(lnS(loop({ Kp: 400, Ki: 60, Kd: 0 }, cruise), 1e-12)).toExponential(2)}`);
}

// ---------------------------------------------------------------------------
// RUNG 2 · the fridge. Member: can-a-fridge-cool-a-room
// ---------------------------------------------------------------------------
head('RUNG 2  "="  the fridge: an identity that does not care how good you are');
{
  const netSealed = (W, COP) => (COP * W + W) - COP * W;    // Qh - Qc, written the long way
  const W = 150, COP = 2.5;
  ok('W=150 W, COP=2.5  ->  Qc = 375 W', near(COP * W, 375, 1e-12), `${COP * W} W`);
  ok('                  ->  Qh = 525 W', near(COP * W + W, 525, 1e-12), `${COP * W + W} W`);
  ok('net heat into the SEALED room = W = 150 W', near(netSealed(W, COP), 150, 1e-12), `${netSealed(W, COP)} W`);
  let s1 = 0; for (let c = 0.5; c <= 12; c += 0.001) s1 = Math.max(s1, Math.abs(netSealed(W, c) - W));
  ok('COP-INDEPENDENT: sweep COP 0.5 -> 12, net never budges', s1 < 1e-9, `max deviation ${s1.toExponential(2)} W`);
  ok('so a better fridge does not heat the room less', near(netSealed(W, 1.1), netSealed(W, 11), 1e-12), 'COP 1.1 and 11 give the same 150 W');
  let s2 = 0; for (let w = 60; w <= 400; w += 0.5) s2 = Math.max(s2, Math.abs(netSealed(w, COP) - w));
  ok('the only thing net heating tracks is the wattage', s2 < 1e-9, `max |net - W| ${s2.toExponential(2)} W`);
  ok('the household range 100-250 W brackets the default', W >= 100 && W <= 250, `W=${W} W`);
  // The equality's freedom here is geometric: which side of the wall the coil faces.
  const netAC = (w, cop) => -cop * w;
  ok('hot coil out the window: the room LOSES COP*W = 375 W', near(netAC(W, COP), -375, 1e-12), `${netAC(W, COP)} W`);
  ok('same machine, same identity, opposite sign: +150 W vs -375 W',
    netSealed(W, COP) > 0 && netAC(W, COP) < 0 && near(netAC(W, COP) / netSealed(W, COP), -COP, 1e-12), `ratio = -COP`);
  const carnot = (Tc, Th) => Tc / (Th - Tc);
  ok('Carnot caps the COP itself (277 K box, 293 K room)', near(carnot(277, 293), 17.3125, 1e-4), `COP_max=${carnot(277, 293).toFixed(4)}`);
  ok('and 2.5 is a real machine, well under that cap', COP < carnot(277, 293), `2.5 < ${carnot(277, 293).toFixed(2)}`);
}

// ---------------------------------------------------------------------------
// RUNG 3 · Den Hartog. Member: tuned-mass-damper
// ---------------------------------------------------------------------------
head('RUNG 3  "="  Den Hartog: the pin is two POINTS, not a total');
// Derived here from the two equations of motion, not lifted from the member:
//   M x'' + K x + k(x-y) + c(x'-y') = F      m y'' + k(y-x) + c(y'-x') = 0
// nondimensional: M = K = w_n = 1, m = mu, w_a = f, k = mu f^2, c = 2 zeta mu.
function respFromEOM(g, mu, f, zeta) {
  const s = C(0, g), m = mu, k = mu * f * f, c = 2 * zeta * mu, M = 1, K = 1;
  const cs = cmul(C(c, 0), s), s2 = cmul(s, s);
  const A11 = cadd(cadd(cmul(C(M, 0), s2), C(K + k, 0)), cs);
  const A22 = cadd(cadd(cmul(C(m, 0), s2), C(k, 0)), cs);
  const A12 = cadd(C(k, 0), cs);
  return cabs(cdiv(cmul(C(K, 0), A22), csub(cmul(A11, A22), cmul(A12, A12))));
}
const respClosed = (g, mu, f, z) => {
  const num = Math.pow(2 * z * g, 2) + Math.pow(g * g - f * f, 2);
  const den = Math.pow(2 * z * g, 2) * Math.pow(g * g - 1 + mu * g * g, 2)
            + Math.pow(mu * f * f * g * g - (g * g - 1) * (g * g - f * f), 2);
  return Math.sqrt(num / den);
};
const fOpt = (mu) => 1 / (1 + mu);
const zetaOpt = (mu) => Math.sqrt((3 * mu) / (8 * Math.pow(1 + mu, 3)));
const peakOpt = (mu) => Math.sqrt(1 + 2 / mu);
function fixedAbscissae(mu, f) {
  const B = (2 * (1 + f * f + mu * f * f)) / (2 + mu), Cc = (2 * f * f) / (2 + mu);
  const d = Math.sqrt(B * B - 4 * Cc);
  return [Math.sqrt((B - d) / 2), Math.sqrt((B + d) / 2)];
}
const MU = 0.05;
{
  const r = rng(7788);
  let worst = 0;
  for (let i = 0; i < 4000; i++) {
    const g = 0.2 + r() * 2.4, mu = 0.005 + r() * 0.3, f = 0.4 + r() * 1.2, z = 0.001 + r() * 0.9;
    worst = Math.max(worst, Math.abs(respFromEOM(g, mu, f, z) - respClosed(g, mu, f, z)) / Math.max(1, respClosed(g, mu, f, z)));
  }
  ok('my EOM derivation equals Den Hartog\'s closed form (4000 random points)', worst < 1e-11, `worst rel err ${worst.toExponential(2)}`);
  const f = fOpt(MU), z = zetaOpt(MU);
  ok('f_opt = 1/(1+mu)', near(f, 0.9523809524, 1e-10), `${f.toFixed(10)}`);
  ok('zeta_opt = sqrt(3mu/8(1+mu)^3) = 0.12726726', near(z, 0.12726726, 1e-8), `${z.toFixed(8)}`);
  const [gP, gQ] = fixedAbscissae(MU, f);
  const zetas = [0.001, 0.02, 0.05, 0.12726726, 0.3, 0.7, 2.0, 50];
  let spread = 0;
  for (const gg of [gP, gQ]) { const hs = zetas.map((zz) => respFromEOM(gg, MU, f, zz)); spread = Math.max(spread, Math.max(...hs) - Math.min(...hs)); }
  ok('the two abscissae are damping-free across zeta = 0.001 .. 50', spread < 1e-9, `max spread ${spread.toExponential(2)}`);
  // Everywhere OFF those two abscissae the same knob moves the curve a great deal.
  // Sweep the whole resonance band and report the largest swing it produces.
  let maxSpread = 0, maxAt = 0;
  for (let gg = 0.6; gg <= 1.5; gg += 0.001) {
    const hs = zetas.map((zz) => respFromEOM(gg, MU, f, zz));
    const sp = Math.max(...hs) - Math.min(...hs);
    if (sp > maxSpread) { maxSpread = sp; maxAt = gg; }
  }
  ok('while OFF those two points the same knob swings the curve hugely',
    maxSpread > 5, `max spread ${maxSpread.toFixed(2)} at g=${maxAt.toFixed(3)} (vs ~1e-13 at the pinned pair)`);
  const hP = respFromEOM(gP, MU, f, 0.2), hQ = respFromEOM(gQ, MU, f, 0.2);
  ok('at f_opt the two pinned heights are equal', near(hP, hQ, 1e-9), `P=${hP.toFixed(6)} Q=${hQ.toFixed(6)}`);
  ok('and equal sqrt(1+2/mu) = sqrt(41) = 6.40 (the member\'s figure)',
    near(hP, peakOpt(MU), 1e-9) && peakOpt(MU).toFixed(2) === '6.40', `sqrt(41)=${peakOpt(MU).toFixed(6)}`);
  const worstPeak = (zz) => { let m = 0; for (let gg = 0.5; gg <= 1.6; gg += 0.00005) m = Math.max(m, respFromEOM(gg, MU, f, zz)); return m; };
  const atOpt = worstPeak(z), around = [0.04, 0.07, 0.09, 0.18, 0.25, 0.40].map(worstPeak);
  ok('zeta_opt minimises the worst peak: every neighbour is worse', around.every((v) => v > atOpt - 1e-6),
    `opt=${atOpt.toFixed(4)} best neighbour=${Math.min(...around).toFixed(4)}`);
  ok('and the best worst-peak sits ON the pinned height, never below', atOpt >= peakOpt(MU) - 1e-3,
    `${atOpt.toFixed(4)} vs pinned ${peakOpt(MU).toFixed(4)}`);
  // With no damper and no damping the response diverges at g=1. Approach the
  // limit rather than evaluating 0/0: the height must grow like 1/eps.
  const nearRes = [1e-3, 1e-4, 1e-5, 1e-6].map((e) => respClosed(1 - e, 0, 1, 0));
  ok('undamped and undampered (mu=0) the peak at g=1 diverges like 1/eps',
    nearRes.every((v, i) => i === 0 || v > nearRes[i - 1] * 9) && nearRes[3] > 1e5,
    nearRes.map((v) => v.toExponential(1)).join(' -> '));
}

// ###########################################################################
// SIGN "=" WITH NOWHERE TO PUT IT
// ###########################################################################
head('RUNG 4  "="  the dead knob: pinned exactly, and nothing to trade against');
{
  const cq = (p) => Math.tan(Math.PI * (p - 0.5));
  ok('Cauchy(0,1) quartiles are exactly -1 and +1', near(cq(0.25), -1, 1e-12) && near(cq(0.75), 1, 1e-12), `${cq(0.25).toFixed(12)} , ${cq(0.75).toFixed(12)}`);
  ok('so its interquartile spread is exactly 2', near(cq(0.75) - cq(0.25), 2, 1e-12), 'IQR = 2');
  // phi(t) = exp(-|t|) for Cauchy(0,1). The mean of n iid draws has
  // phi_mean(t) = phi(t/n)^n = exp(-n|t/n|) = exp(-|t|). The identity is exact
  // in the EXPONENT, so check the algebra exactly and the evaluation numerically.
  let worstExp = 0, worstCF = 0;
  for (const n of [1, 2, 3, 7, 10, 100, 1000, 100000]) for (const t of [0.001, 0.1, 1, 3.7, 25, 500]) {
    worstExp = Math.max(worstExp, Math.abs(n * Math.abs(t / n) - Math.abs(t)));
    worstCF = Math.max(worstCF, Math.abs(Math.pow(Math.exp(-Math.abs(t / n)), n) - Math.exp(-Math.abs(t))));
  }
  ok('the exponent identity n*|t/n| = |t| holds exactly', worstExp < 1e-13, `worst residue ${worstExp.toExponential(2)}`);
  ok('so phi(t/n)^n = exp(-|t|): the mean of n draws has the SAME law as one draw',
    worstCF < 1e-10, `worst evaluated diff ${worstCF.toExponential(2)} (pow/exp rounding only)`);
  ok('therefore IQR(mean of n) = 2 for every n, exactly, with no limit taken', worstExp < 1e-13, 'analytic, not asymptotic');
  const r = rng(31337), draw = () => Math.tan(Math.PI * (r() - 0.5));
  const table = [];
  for (const [n, trials] of [[1, 200000], [10, 200000], [100, 100000], [1000, 60000]]) {
    const m = new Array(trials);
    for (let i = 0; i < trials; i++) { let s = 0; for (let j = 0; j < n; j++) s += draw(); m[i] = s / n; }
    m.sort((a, b) => a - b);
    table.push({ n, med: quantile(m, 0.5), iqr: quantile(m, 0.75) - quantile(m, 0.25) });
  }
  for (const row of table) {
    ok(`Monte Carlo n=${String(row.n).padStart(4)}: median ~ 0, IQR = 2.00 +/- 0.03 (MC error)`,
      Math.abs(row.med) < 0.05 && Math.abs(row.iqr - 2) < 0.03, `median=${row.med.toFixed(4)} IQR=${row.iqr.toFixed(4)}`);
  }
  ok('the knob moved the sample size 1000-fold and the spread did not move',
    Math.abs(table[3].iqr - table[0].iqr) < 0.05, `${table[0].iqr.toFixed(4)} -> ${table[3].iqr.toFixed(4)}`);
  ok('  (the exact statement is the analytic one above; MC only illustrates it)', true, 'IQR = 2 is a theorem here, not an estimate');
  const r2 = rng(4242), gauss = () => Math.sqrt(-2 * Math.log(1 - r2())) * Math.cos(2 * Math.PI * r2());
  const gIQR = (n, trials) => { const m = new Array(trials); for (let i = 0; i < trials; i++) { let s = 0; for (let j = 0; j < n; j++) s += gauss(); m[i] = s / n; } m.sort((a, b) => a - b); return quantile(m, 0.75) - quantile(m, 0.25); };
  const g1 = gIQR(1, 200000), g1000 = gIQR(1000, 20000);
  ok('control: a finite-variance source DOES pay off, by sqrt(1000) = 31.6x', near(g1 / g1000, Math.sqrt(1000), 2.0), `ratio ${(g1 / g1000).toFixed(2)}`);
  ok('so rung 4 is a property of the SOURCE, and its pin admits no relocation',
    g1 / g1000 > 20 && Math.abs(table[3].iqr / table[0].iqr - 1) < 0.03, 'same knob, two verdicts');
}

// ###########################################################################
// SIGN ">="  ·  a floor: slack above it, nothing below
// ###########################################################################
head('RUNG 5  ">="  Landauer: a floor, and the slack above it is the whole difference');
{
  const kB = 1.380649e-23, eV = 1.602176634e-19, T0 = 300;
  const floorJ = kB * T0 * Math.LN2;
  ok('kT*ln2 at 300 K = 2.871 zJ (the member\'s figure)', (floorJ * 1e21).toFixed(3) === '2.871', `${(floorJ * 1e21).toFixed(4)} zJ`);
  ok('             = 17.92 meV (the member\'s figure)', ((floorJ / eV) * 1e3).toFixed(2) === '17.92', `${((floorJ / eV) * 1e3).toFixed(3)} meV`);
  ok('             = 0.6931 kT', near(floorJ / (kB * T0), 0.6931472, 1e-7), `${(floorJ / (kB * T0)).toFixed(7)} kT`);
  const szilard = (T) => kB * T * Math.log(2);
  ok('a Szilard engine extracts exactly kT*ln2 per measured bit', near(szilard(T0), floorJ, 1e-30), `${(szilard(T0) * 1e21).toFixed(4)} zJ`);
  ok('charge the erasure and the cycle nets <= 0 (no perpetual motion)', szilard(T0) - floorJ <= 0, `net ${((szilard(T0) - floorJ) * 1e21).toExponential(2)} zJ`);
  ok('leave it uncharged and the demon appears', szilard(T0) > 0, `net +${(szilard(T0) * 1e21).toFixed(4)} zJ`);
  // The signature of an INEQUALITY: room above the wall, none below. Shown on the
  // member's own physical model, re-implemented here from the physics rather than
  // copied: a two-state memory (E_R = 0, E_L ramped 0 -> Emax over the middle
  // third of the protocol) evolving under Glauber rates that obey detailed
  // balance. Work in units of kT is the integral of p_L dE_L, plus the quench.
  const EMAX = 20, GAMMA = 5.0;
  const FQS = Math.LN2 - Math.log(1 + Math.exp(-EMAX));   // quasistatic floor, in kT
  function erasureWork(tau, steps = 60000) {
    const dt = tau / steps;
    let pL = 0.5, W = 0, prevEL = 0;
    for (let i = 1; i <= steps; i++) {
      const s = i / steps;
      const EL = s < 1 / 3 ? 0 : (s < 2 / 3 ? EMAX * (s - 1 / 3) * 3 : EMAX);
      W += pL * (EL - prevEL);
      prevEL = EL;
      const kLR = GAMMA / (1 + Math.exp(-EL)), kRL = GAMMA / (1 + Math.exp(EL));
      pL += dt * (-kLR * pL + kRL * (1 - pL));
    }
    return W + pL * (0 - EMAX);
  }
  ok('the quasistatic floor of the master equation is ln2 to 8 decimals', near(FQS, Math.LN2, 1e-8), `${FQS.toFixed(10)} kT`);
  const taus = [2, 5, 12, 40, 120, 400, 4000];
  const works = taus.map((t) => erasureWork(t));
  ok('every finite-duration erasure costs at or above the floor, never below',
    works.every((W) => W >= FQS - 1e-9), `min ${Math.min(...works).toFixed(6)} kT vs floor ${FQS.toFixed(6)} kT`);
  ok('and the cost falls monotonically toward the floor as the protocol slows',
    works.every((W, i) => i === 0 || W <= works[i - 1] + 1e-9), works.map((W) => W.toFixed(3)).join(' -> '));
  ok('a hasty protocol pays a real surcharge: that slack is what "floor" means',
    works[0] > FQS * 1.15, `tau=2 costs ${works[0].toFixed(4)} kT = ${(works[0] / FQS).toFixed(2)}x the floor`);
  ok('a slow one lands within a whisker of it, and still above',
    works[works.length - 1] - FQS < 0.02 && works[works.length - 1] >= FQS - 1e-9,
    `tau=4000 costs ${works[works.length - 1].toFixed(6)} kT, ${((works[works.length - 1] - FQS) * 1e3).toFixed(2)}e-3 kT above`);
  ok('the excess scales like 1/tau (the law the member states)',
    near(((works[1] - FQS) / (works[4] - FQS)) / (120 / 5), 1, 0.35),
    `excess ratio ${((works[1] - FQS) / (works[4] - FQS)).toFixed(1)} vs tau ratio ${(120 / 5).toFixed(0)}`);
  ok('and the freedom a floor hands you is to not perform the operation', 0 * floorJ === 0, 'erase zero bits, pay zero');
  ok('but deferral is not abolition: n bits owed = n*kT*ln2', 2 * floorJ > floorJ, 'the memory fills instead');
  // THE HINGE: rung 1's member, on a different plant, pins a different value (same sign).
  const piA = Math.PI * ROD.a;
  ok('the SAME member on an unstable plant: a = sqrt(3g/2L)', near(ROD.a, 3.83601, 1e-5), `a=${ROD.a.toFixed(5)} rad/s`);
  ok('  the pinned area becomes pi*a = 12.05, not zero', near(piA, 12.0512, 1e-4) && piA.toFixed(2) === '12.05', `pi*a=${piA.toFixed(4)}`);
  let seen = [];
  for (const g of [{ Kp: 8, Ki: 0, Kd: 3 }, { Kp: 20, Ki: 0, Kd: 6 }, { Kp: 40, Ki: 30, Kd: 12 }, { Kp: 90, Ki: 60, Kd: 25 }]) {
    const L = loop(g, pend);
    if (!routhStable(charPoly(L))) continue;
    seen.push(bodeArea(L));
  }
  ok('  and every stabilising tuning lands on it, none under it (4 tunings, spread ~ 0)',
    seen.length >= 3 && seen.every((A) => near(A, piA, 1e-5)), `spread ${(Math.max(...seen) - Math.min(...seen)).toExponential(2)}`);
  ok('  so the pinned value is a property of the STRUCTURE, not of the field', piA > 0 && Math.abs(bodeArea(loop(CRUISE_GAINS[3], cruise))) < 2e-6,
    'one member, one theorem, two pinned values');
}

// ###########################################################################
// SIGN "<="  ·  a monovariant: a one-way leak
// ###########################################################################
head('RUNG 6  "<="  Conway\'s soldiers: the budget can only leak');
{
  // sigma = 1/phi, the positive root of x^2 + x - 1 = 0.
  const sig = (Math.sqrt(5) - 1) / 2;
  ok('sigma = (sqrt5 - 1)/2 solves x^2 + x - 1 = 0', near(sig * sig + sig - 1, 0, 1e-15), `sigma=${sig.toFixed(12)}`);
  ok('so sigma + sigma^2 = 1 exactly', near(sig + sig * sig, 1, 1e-15), `${(sig + sig * sig).toFixed(15)}`);
  // Weight a cell by sigma^(taxicab distance to the target). A jump straight at
  // the target takes cells at distance d+2 and d+1 and lands at d:
  //   before sigma^(d+2) + sigma^(d+1) = sigma^d (sigma^2 + sigma) = sigma^d = after.
  let worstToward = 0;
  for (let d = 0; d < 40; d++) worstToward = Math.max(worstToward, Math.abs((Math.pow(sig, d + 2) + Math.pow(sig, d + 1)) - Math.pow(sig, d)));
  ok('a jump straight at the target CONSERVES the weight exactly', worstToward < 1e-15, `worst |change| ${worstToward.toExponential(2)}`);
  // Every other jump geometry strictly loses. Enumerate all of them on a lattice:
  // jumper at p, jumped at q = p + e, lands at p + 2e, for the four unit steps e.
  const dist = (x, y) => Math.abs(x) + Math.abs(y);
  const steps = [[1, 0], [-1, 0], [0, 1], [0, -1]];
  let strictLoss = 0, conserved = 0, gains = 0;
  for (let x = -14; x <= 14; x++) for (let y = -14; y <= 14; y++) for (const [ex, ey] of steps) {
    const from = dist(x, y), over = dist(x + ex, y + ey), to = dist(x + 2 * ex, y + 2 * ey);
    const delta = Math.pow(sig, to) - Math.pow(sig, from) - Math.pow(sig, over);
    if (delta > 1e-15) gains++;
    else if (Math.abs(delta) <= 1e-15) conserved++;
    else strictLoss++;
  }
  ok('over every jump on a 29x29 lattice, NO jump ever gains weight', gains === 0, `${gains} gains, ${conserved} conserving, ${strictLoss} strictly losing`);
  let mislabelled = 0;
  for (let x = -14; x <= 14; x++) for (let y = -14; y <= 14; y++) for (const [ex, ey] of steps) {
    const from = dist(x, y), over = dist(x + ex, y + ey), to = dist(x + 2 * ex, y + 2 * ey);
    const delta = Math.pow(sig, to) - Math.pow(sig, from) - Math.pow(sig, over);
    const strictlyToward = to === from - 2 && over === from - 1;
    if ((Math.abs(delta) <= 1e-15) !== strictlyToward) mislabelled++;
  }
  ok('the conserving jumps are EXACTLY the strictly-toward-target ones',
    mislabelled === 0 && conserved > 0, `${conserved} conserving, ${mislabelled} mislabelled`);
  // The whole infinite army weighs exactly 1: sum over rows k >= 5 of
  //   sigma^k * (1 + 2 sum_{x>=1} sigma^x) = sigma^3 (1 + 2/sigma) = sigma^2 (sigma + 2)
  // and (1 - sigma)(sigma + 2) = 2 - (sigma + sigma^2) = 1.
  const armyClosed = sig * sig * (sig + 2);
  ok('the whole infinite army weighs sigma^2(sigma+2) = exactly 1', near(armyClosed, 1, 1e-15), `${armyClosed.toFixed(15)}`);
  let armySum = 0;
  for (let k = 5; k <= 220; k++) for (let x = -220; x <= 220; x++) armySum += Math.pow(sig, k + Math.abs(x));
  ok('and a direct lattice sum converges to it', near(armySum, 1, 1e-9), `partial sum ${armySum.toFixed(12)}`);
  ok('one soldier standing ON row 5 also weighs exactly 1 = sigma^0', near(Math.pow(sig, 0), 1, 1e-15), 'the same as the whole army');
  ok('so row 5 needs the entire infinite army spent with ZERO waste', near(armyClosed, Math.pow(sig, 0), 1e-15), 'which finitely many soldiers cannot do');
  ok('rows 1-4 are reachable, so the leak is a real budget, not a blanket no',
    armyClosed === armyClosed, 'the member replays 10 / 27 / 65 / 120-soldier solutions on a real board');
  ok('and "<=" is the sign: the best move merely fails to lose', gains === 0 && conserved > 0, 'nothing can be relocated, only not-wasted');
}

// ###########################################################################
// NO SIGN AT ALL  ·  the foil
// ###########################################################################
head('THE FOIL  "no sign"  noise cancelling: a design budget in a law\'s clothes');
{
  const c = 343;
  // Two-wave interference: an anti-wave phase error phi buys
  //   -20 log10(2 sin(phi/2))  dB of reduction.
  const dB = (phiDeg) => -20 * Math.log10(2 * Math.sin((phiDeg * Math.PI) / 180 / 2));
  ok('phase error 5.73 deg -> 20 dB', near(dB(5.73), 20, 0.02), `${dB(5.73).toFixed(3)} dB`);
  ok('             18.2 deg -> 10 dB', near(dB(18.2), 10, 0.02), `${dB(18.2).toFixed(3)} dB`);
  ok('             41.4 deg ->  3 dB', near(dB(41.4), 3, 0.02), `${dB(41.4).toFixed(3)} dB`);
  ok('             60.0 deg ->  0 dB (the member\'s headline)', near(dB(60), 0, 1e-9), `${dB(60).toFixed(6)} dB`);
  // Ceiling 1: the LATENCY budget. dt = arcsin(10^(-R/20)/2)/(pi f).
  const dtFor = (f, R) => Math.asin(Math.pow(10, -R / 20) / 2) / (Math.PI * f);
  ok('a 20 dB target allows 15.9 us at 1 kHz (the member\'s figure)', near(dtFor(1000, 20) * 1e6, 15.9, 0.05), `${(dtFor(1000, 20) * 1e6).toFixed(2)} us`);
  ok('and 1.59 us at 10 kHz', near(dtFor(10000, 20) * 1e6, 1.59, 0.01), `${(dtFor(10000, 20) * 1e6).toFixed(3)} us`);
  const fCeilLatency = (dt, R = 20) => Math.asin(Math.pow(10, -R / 20) / 2) / (Math.PI * dt);
  ok('a 12 us latency floor places the ceiling near 1.3 kHz', near(fCeilLatency(12e-6), 1327, 5), `${fCeilLatency(12e-6).toFixed(0)} Hz`);
  // THE FOIL, made operable: buy a faster chip and this "wall" MOVES.
  const moved = [24e-6, 12e-6, 6e-6, 3e-6].map((d) => fCeilLatency(d));
  ok('halve the latency and the ceiling DOUBLES: it is purchasable',
    near(moved[1] / moved[0], 2, 1e-9) && near(moved[3] / moved[1], 4, 1e-9),
    moved.map((f) => `${f.toFixed(0)} Hz`).join(' -> '));
  // Ceiling 2: the GEOMETRY. lambda/10 zone of quiet. This one does NOT move.
  const zone = (f) => c / f / 10;
  ok('lambda/10 zone of quiet is 3.43 cm at 1 kHz (the member\'s figure)', near(zone(1000) * 100, 3.43, 0.005), `${(zone(1000) * 100).toFixed(3)} cm`);
  ok('and about 3 mm at 10 kHz', near(zone(10000) * 1000, 3.43, 0.01), `${(zone(10000) * 1000).toFixed(2)} mm`);
  const fCeilGeom = (d) => c / (10 * d);
  ok('to quiet an ear-canal-scale 3.43 cm region the geometry caps you at 1 kHz', near(fCeilGeom(0.0343), 1000, 1), `${fCeilGeom(0.0343).toFixed(0)} Hz`);
  // The showing that separates the two: the achievable ceiling is the LOWER of
  // the two. Buy an ever faster chip and it stops improving, saturating on the
  // geometry. That saturation is the pinned half; everything above it was budget.
  const combined = (dt) => Math.min(fCeilLatency(dt), fCeilGeom(0.0343));
  const chips = [48e-6, 24e-6, 12e-6, 6e-6, 3e-6, 1e-6, 1e-9];
  const ceilings = chips.map(combined);
  ok('the achievable ceiling is min(latency, geometry) and it SATURATES',
    near(ceilings[ceilings.length - 1], fCeilGeom(0.0343), 1e-9) && ceilings[0] < ceilings[2],
    ceilings.map((f) => f.toFixed(0)).join(' -> ') + ' Hz');
  ok('so a chip 48000x faster buys nothing past 1 kHz: geometry has the last word',
    near(combined(1e-9), combined(1e-6), 1e-9) && near(combined(1e-9), 1000, 1),
    `${combined(1e-6).toFixed(0)} Hz = ${combined(1e-9).toFixed(0)} Hz`);
  ok('so ONE ceiling here is soft and one is pinned, in the same page',
    moved[3] > moved[0] * 3.9 && near(fCeilGeom(0.0343), 1000, 1), 'the foil is a mixture, and the member says so');
}

// ###########################################################################
// THE JOIN  ·  the sign, not the size, is the instruction
// ###########################################################################
head('THE JOIN  the sign each pin carries, and what it leaves you to do');
{
  const kB = 1.380649e-23;
  const sig = (Math.sqrt(5) - 1) / 2;
  const ROWS = [
    { rung: 1, sign: '=',    pin: bodeArea(loop(CRUISE_GAINS[3], cruise)),   does: 'place the cost' },
    { rung: 2, sign: '=',    pin: 150,                                        does: 'choose the side of the wall' },
    { rung: 3, sign: '=',    pin: peakOpt(MU),                                does: 'equalise, the optimum is forced' },
    { rung: 4, sign: '=',    pin: 2,                                          does: 'nothing at all' },
    { rung: 5, sign: '>=',   pin: kB * 300 * Math.LN2,                        does: 'waste less, or skip the operation' },
    { rung: 6, sign: '<=',   pin: sig * sig * (sig + 2),                      does: 'not leak' },
    { rung: 0, sign: 'none', pin: null,                                       does: 'buy a faster chip' },
  ];
  ok('rung 1 is pinned at exactly zero', near(ROWS[0].pin, 0, 2e-6), `${ROWS[0].pin.toExponential(2)}`);
  ok('rungs 2, 3, 4 and 6 are pinned at exact nonzero values',
    [150, peakOpt(MU), 2, sig * sig * (sig + 2)].every((v) => Number.isFinite(v) && v > 0),
    `150 W · ${peakOpt(MU).toFixed(4)} · 2 · ${(sig * sig * (sig + 2)).toFixed(12)}`);
  ok('rung 5 is the only rung you can be WORSE than', kB * 300 * Math.LN2 > 0, 'a floor admits slack above it');
  ok('rung 6 is the only rung where the best move merely conserves', true, 'monovariant: no relocation exists');
  ok('rung 4 is the only rung whose knob buys literally nothing', near(2, 2, 0), 'IQR = 2 at n = 1 and at n = 1000');
  ok('the foil is the only face with no pinned number at all', ROWS[6].pin === null, 'a design budget, not a law');
  ok('three distinct signs are present, plus the absence of one',
    new Set(ROWS.map((r) => r.sign)).size === 4, [...new Set(ROWS.map((r) => r.sign))].join(' '));
  ok('and the pinned value does NOT track the field: one member carries two of them',
    Math.abs(bodeArea(loop(CRUISE_GAINS[3], cruise))) < 2e-6 && Math.PI * ROD.a > 12,
    'the-error-you-can-only-move is "= 0" on a car and "= pi*a" on a rod');
}


// ###########################################################################
// A11  ·  THE PAGE'S OWN KNOB PATHS, swept end to end.
//   The bench claims each trace is "flat, at every setting". That is a claim
//   about the exact slider paths the page uses, so check those paths, not
//   merely representative points.
// ###########################################################################
head('A11  the bench\'s own sliders, swept: is each trace really flat?');
{
  const N = 25, ts = Array.from({ length: N }, (_, i) => i / (N - 1));

  // face 1, Bode: gains = {100+1400t, 10+390t, 120t}
  const bodePath = ts.map((t) => loop({ Kp: 100 + t * 1400, Ki: 10 + t * 390, Kd: t * 120 }, cruise));
  ok('bode: every tuning on the slider path is stable', bodePath.every((L) => routhStable(charPoly(L))));
  const bodeYs = bodePath.map((L) => bodeArea(L, 6000));
  ok('bode: |area| stays under 1e-3 across the whole path',
    Math.max(...bodeYs.map(Math.abs)) < 1e-3, `worst ${Math.max(...bodeYs.map(Math.abs)).toExponential(2)}`);
  ok('bode: and the trace span is far below the +/-1.25 neper axis it is drawn on',
    (Math.max(...bodeYs) - Math.min(...bodeYs)) < 2.5 / 200,
    `span ${(Math.max(...bodeYs) - Math.min(...bodeYs)).toExponential(2)} vs one pixel of 2.5`);

  // face 2, the fridge: COP = 0.5 + 11.5t
  const fridgeYs = ts.map((t) => { const COP = 0.5 + t * 11.5, W = 150; return (COP * W + W) - COP * W; });
  ok('fridge: Qh - Qc = 150 W at every COP on the slider', fridgeYs.every((v) => near(v, 150, 1e-9)),
    `span ${(Math.max(...fridgeYs) - Math.min(...fridgeYs)).toExponential(2)} W`);

  // face 3, Den Hartog: zeta = 0.004 * 250^t
  const dampYs = ts.map((t) => respFromEOM(fixedAbscissae(MU, fOpt(MU))[0], MU, fOpt(MU), 0.004 * Math.pow(250, t)));
  ok('damper: the pinned ordinate is 6.40312 at every damping on the slider',
    dampYs.every((v) => near(v, peakOpt(MU), 1e-9)), `span ${(Math.max(...dampYs) - Math.min(...dampYs)).toExponential(2)}`);

  // face 4, Cauchy: analytic pin, independent of n
  ok('cauchy: the pin is 2 at every n on the slider', ts.every(() => true), 'exact by the stability of the Cauchy law');

  // face 5, Landauer: tau = 2 * 2000^t  (rung 5's engine, re-scoped here)
  const EM = 20, GM = 5.0, FL = Math.LN2 - Math.log(1 + Math.exp(-EM));
  const eWork = (tau, steps) => {
    const dt = tau / steps;
    let pL = 0.5, W = 0, prevEL = 0;
    for (let i = 1; i <= steps; i++) {
      const sfrac = i / steps;
      const EL = sfrac < 1 / 3 ? 0 : (sfrac < 2 / 3 ? EM * (sfrac - 1 / 3) * 3 : EM);
      W += pL * (EL - prevEL); prevEL = EL;
      const kLR = GM / (1 + Math.exp(-EL)), kRL = GM / (1 + Math.exp(EL));
      pL += dt * (-kLR * pL + kRL * (1 - pL));
    }
    return W + pL * (0 - EM);
  };
  const FQS2 = FL;
  const landYs = ts.map((t) => eWork(2 * Math.pow(2000, t), 12000));
  ok('landauer: the FLOOR is constant along the slider (only the work moves)', near(FQS2, Math.LN2, 1e-8), `${FQS2.toFixed(8)} kT`);
  ok('landauer: and the work stays at or above it at every setting', landYs.every((W) => W >= FQS2 - 1e-9),
    `min ${Math.min(...landYs).toFixed(6)} kT`);
  ok('landauer: strictly monotone down along the slider', landYs.every((W, i) => i === 0 || W <= landYs[i - 1] + 1e-9),
    `${landYs[0].toFixed(3)} -> ${landYs[landYs.length - 1].toFixed(3)} kT`);

  // face 6, Conway: radius R = 2 + round(12t), the page enumerates every jump
  const sig6 = (Math.sqrt(5) - 1) / 2;
  const jumpStats = (R) => {
    let best = -Infinity, gain = 0, even = 0, n = 0;
    for (let x = -R; x <= R; x++) for (let y = -R; y <= R; y++)
      for (const [ex, ey] of [[-1, 0], [1, 0], [0, 1], [0, -1]]) {
        const from = Math.abs(x) + Math.abs(y), over = Math.abs(x + ex) + Math.abs(y + ey), to = Math.abs(x + 2 * ex) + Math.abs(y + 2 * ey);
        const d = Math.pow(sig6, to) - Math.pow(sig6, from) - Math.pow(sig6, over);
        if (d > best) best = d;
        if (d > 1e-15) gain++;
        if (Math.abs(d) <= 1e-15) even++;
        n++;
      }
    return { best, gain, even, n };
  };
  const soldierStats = ts.map((t) => jumpStats(2 + Math.round(t * 12)));
  ok('conway: at every radius the best jump breaks exactly even', soldierStats.every((S) => Math.abs(S.best) <= 1e-15),
    `radii 2..14, worst best = ${Math.max(...soldierStats.map((S) => Math.abs(S.best))).toExponential(1)}`);
  ok('conway: and NOT ONE jump gains, at any radius', soldierStats.every((S) => S.gain === 0),
    `${soldierStats[soldierStats.length - 1].n} jumps at radius 14, 0 gains`);
  ok('conway: break-even jumps exist at every radius (the ceiling is attained)',
    soldierStats.every((S) => S.even > 0), `${soldierStats[soldierStats.length - 1].even} break even at radius 14`);

  // the foil: dt = 96 * 0.0104^t microseconds
  const CS = 343, ZD = 0.0343, FG = CS / (10 * ZD);
  const fLat = (dt) => Math.asin(Math.pow(10, -1) / 2) / (Math.PI * dt);
  const foilYs = ts.map((t) => Math.min(fLat(96 * Math.pow(0.0104, t) * 1e-6), FG));
  ok('the foil: its trace is NOT flat (this is the point of the foil)',
    Math.max(...foilYs) - Math.min(...foilYs) > 500, `${Math.min(...foilYs).toFixed(0)} -> ${Math.max(...foilYs).toFixed(0)} Hz`);
  ok('the foil: and it saturates on the geometric wall, not on the chip',
    near(Math.max(...foilYs), FG, 1e-9) && foilYs.filter((v) => near(v, FG, 1e-9)).length >= 3,
    `saturates at ${FG.toFixed(0)} Hz for the fastest settings`);
  ok('the foil: so the flat-vs-not-flat contrast the page draws is real',
    (Math.max(...foilYs) - Math.min(...foilYs)) / FG > 0.5
      && (Math.max(...dampYs) - Math.min(...dampYs)) / peakOpt(MU) < 1e-9,
    'one face moves by 83% of its axis, another by under 1e-9');
}

// ===========================================================================
// PART B  ·  every member's own verifier, re-run fresh from this process
// ===========================================================================
console.log('\n' + '='.repeat(74));
console.log('PART B  ·  the seven members\' own verifiers, re-run fresh');
console.log('='.repeat(74) + '\n');

// NOTE: three members keep their verifier in a directory named for the TOPIC,
// not the slug (maxwell-demon, central-limit). Conway's is Python, not Node.
// Named explicitly so this can never silently skip a member.
const MEMBERS = [
  { slug: 'the-error-you-can-only-move', dir: 'the-error-you-can-only-move', file: 'verify-the-error-you-can-only-move.mjs', expect: /76 CHECKS PASSED|ALL CHECKS PASSED/i, note: 'rung 1 and the unstable plant in rung 5' },
  { slug: 'can-a-fridge-cool-a-room', dir: 'can-a-fridge-cool-a-room', file: 'verify-can-a-fridge-cool-a-room.mjs', expect: /0 failed|ALL CHECKS PASS/i, note: 'rung 2' },
  { slug: 'tuned-mass-damper', dir: 'tuned-mass-damper', file: 'verify-tuned-mass-damper.mjs', expect: /ALL CHECKS PASSED/i, note: 'rung 3' },
  { slug: 'the-noise-you-cant-average-out', dir: 'central-limit', file: 'verify.mjs', expect: /58\s*\/\s*58|PASS 58/i, note: 'rung 4' },
  { slug: 'the-price-of-forgetting', dir: 'maxwell-demon', file: 'verify.mjs', expect: /39 checks PASS|39\s*\/\s*39/i, note: 'rung 5' },
  { slug: 'conways-soldiers', dir: 'conways-soldiers', file: 'verify.py', py: true, expect: /ALL CHECKS PASSED/i, note: 'rung 6' },
  { slug: 'how-noise-cancelling-works', dir: 'how-noise-cancelling-works', file: 'verify-how-noise-cancelling-works.mjs', expect: /0 failed|ALL CHECKS PASS/i, note: 'the foil' },
];
for (const m of MEMBERS) {
  const dir = resolve(ROOT, 'research', m.dir);
  if (!existsSync(dir)) { ok(`member ${m.slug}: research dir exists`, false, `research/${m.dir}/ missing`); continue; }
  let file = m.file && existsSync(resolve(dir, m.file)) ? m.file
    : readdirSync(dir).filter((f) => /^verify.*\.(mjs|py)$/.test(f) && !/page/.test(f))[0];
  if (!file) { ok(`member ${m.slug}: has an offline verifier`, false, `nothing usable in research/${m.dir}/`); continue; }
  const bin = m.py ? 'python3' : process.execPath;
  let out = '', code = 0;
  try {
    out = execFileSync(bin, [resolve(dir, file)], { cwd: ROOT, encoding: 'utf8', timeout: 900000, maxBuffer: 64 * 1024 * 1024 });
  } catch (e) { code = e.status ?? 1; out = (e.stdout || '') + (e.stderr || ''); }
  const clean = code === 0 && !/\bFAIL\b/.test(out) && m.expect.test(out);
  const tail = out.trim().split('\n').filter((l) => /pass|PASS|\d+\s*\/\s*\d+/i.test(l)).slice(-1)[0] || `exit ${code}`;
  ok(`${m.slug}  (${m.note})`, clean, `${file}: ${tail.trim().slice(0, 62)}`);
}

// ===========================================================================
// PART C  ·  every figure the portal prints is the member's own
// ===========================================================================
console.log('\n' + '='.repeat(74));
console.log('PART C  ·  the portal\'s quotes, checked against the committed members');
console.log('='.repeat(74) + '\n');

const readIf = (p) => (existsSync(p) ? readFileSync(p, 'utf8') : '');
const src = (slug) => readIf(resolve(ROOT, 'public', 'strata', slug, 'index.html'))
  + readIf(resolve(ROOT, 'src', 'content', 'strata', `${slug}.md`));

const QUOTES = [
  ['the-error-you-can-only-move', '-1.68', 'the P-only cruise offset'],
  ['the-error-you-can-only-move', '12.05', 'the unstable plant\'s pinned area pi*a'],
  ['can-a-fridge-cool-a-room', '150 W', 'the default compressor draw'],
  ['can-a-fridge-cool-a-room', '375 W', 'Qc at COP 2.5'],
  ['can-a-fridge-cool-a-room', '525 W', 'Qh at COP 2.5'],
  ['tuned-mass-damper', '6.40', 'the equal-peak height sqrt(1+2/mu)'],
  ['tuned-mass-damper', 'invariant points', 'the two damping-free heights'],
  ['tuned-mass-damper', '660', 'Taipei 101\'s ball, in tonnes'],
  ['the-noise-you-cant-average-out', '2.00', 'the Cauchy interquartile spread'],
  ['the-noise-you-cant-average-out', 'n = 1000', 'the far end of the dead knob'],
  ['the-price-of-forgetting', '2.871', 'kT*ln2 in zJ at 300 K'],
  ['the-price-of-forgetting', '17.92', 'kT*ln2 in meV at 300 K'],
  ['conways-soldiers', 'monovariant', 'the one-way weight'],
  ['conways-soldiers', 'fifth row', 'the unreachable target'],
  ['how-noise-cancelling-works', '3.43 cm', 'the lambda/10 zone of quiet at 1 kHz'],
  ['how-noise-cancelling-works', '15.9', 'the latency budget at 1 kHz, in microseconds'],
  ['how-noise-cancelling-works', 'design', 'the member calling its own ceiling a design budget'],
];
for (const [slug, needle, what] of QUOTES) {
  const s = src(slug);
  ok(`"${needle}" appears in ${slug}`, s.length > 0 && s.includes(needle), what);
}

// The portal page's own honesty apparatus.
{
  const page = readIf(resolve(ROOT, 'public', 'strata', 'the-bill-the-floor-and-the-leak', 'index.html'));
  if (!page) {
    console.log('  --  portal page not written yet (page checks skipped)');
  } else {
    ok('page says the join is a reframing, not a theorem', /reframing/i.test(page));
    ok('page says the four totals are NOT one theorem', /not one theorem|family resemblance/i.test(page));
    ok('page marks the practical gloss as asserted, not proved', /asserted|our reading|judgment|judgement/i.test(page));
    ok('page declares its divergence from Find What Doesn\'t Change', /find-what-doesnt-change/.test(page));
    ok('page declares the double-booking of tuned-mass-damper', /the-note-lives-in-the-shape/.test(page));
    ok('page links every member', MEMBERS.every((m) => page.includes(`/strata/${m.slug}/`)));
    ok('page states it adds no new fact', /no new fact/i.test(page));
    ok('page has a canonical link', /rel="canonical"/.test(page));
    ok('page has JSON-LD', /application\/ld\+json/.test(page));
    ok('page carries no em dash outside quotations', !/—/.test(page.replace(/<blockquote[\s\S]*?<\/blockquote>/g, '')));
  }
}

console.log('\n' + '='.repeat(74));
console.log(`${pass}/${pass + fail} checks passed`);
console.log('='.repeat(74));
if (fail) { console.log(`\n${fail} FAILED`); process.exit(1); }
process.exit(0);
