#!/usr/bin/env node
/**
 * The Answer Filed Before the Question — verifier
 * public/strata/filed-before-the-question/index.html
 *
 * A portal across four layers that all face the same predicament: the deadline is
 * shorter than the exact computation, so nothing computes the answer. Something was
 * filed in advance, before the question existed, and the remaining accuracy is bought
 * back in correction rounds.
 *
 * What this file measures, rather than asserts:
 *
 *  A. THE EXCHANGE RATE for the seeded-Newton family (inverse square root).
 *     For the best possible constant lookup table of 2^k entries, how many correct
 *     bits survive r Newton rounds? The measured law is
 *         bits(r+1) = 2*bits(r) - log2(3/2)
 *     which is *not* quite a doubling, and the shortfall is exactly log2(1.5).
 *     Consequence, measured: one extra correction round square-roots the table you
 *     need (and then some).
 *
 *  B. THE CONSTANT AS A TABLE OF SIZE ZERO. 0x5f3759df stores no indexed entries at
 *     all, yet seeds as well as a best-possible table of between 16 and 32 entries
 *     with bins uniform over [1,4), and of between 8 and 16 entries with the bins a
 *     hardware seed table uses (uniform within each binade; section B2).
 *     Measured, both in float32 (the historical artefact) and against the float64
 *     table grid.
 *
 *  C. CORDIC'S LINEAR LAW. The arctan ladder is not a table of answers, it is a table
 *     of moves, and its exchange rate is flat: one rung, one bit, forever. No larger
 *     table buys a better rate. Measured slope over n = 8..40.
 *
 *  D. THE DEADLINE, recomputed independently of the member layer: the spinal arc
 *     closes before any cortical detour could physically fit, so the number of
 *     correction rounds available is zero at any price.
 *
 *  E. THE REPERTOIRE, taken from the member layer's own declared toy model: a small
 *     filed generator standing in for an enormous space of answers.
 *
 * WHAT IS DELIBERATELY NOT CLAIMED (see the honesty checks at the end):
 *   - The four legs are NOT on one axis. Bits, rungs, milliseconds and receptor
 *     event-keys do not convert into each other, and this file makes no attempt to
 *     convert them. What is shared is the STRUCTURE of the trade, not its units.
 *   - The V(D)J layer this portal links carries no affinity-maturation step, so it is
 *     used here strictly as the zero-rounds end of the spine. Somatic hypermutation is
 *     real immunology and is named on the portal as a complication, explicitly flagged
 *     as NOT on the linked layer.
 *
 * Run: node research/filed-before-the-question/verify.mjs
 */

import { readFileSync, existsSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';

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

let pass = 0, fail = 0;
const results = [];
function ok(name, cond, detail = '') {
  if (cond) { pass++; results.push({ name, ok: true, detail }); console.log(`  ok   ${name}${detail ? '  —  ' + detail : ''}`); }
  else { fail++; results.push({ name, ok: false, detail }); console.log(`  FAIL ${name}${detail ? '  —  ' + detail : ''}`); }
}
function near(a, b, tol) { return Math.abs(a - b) <= tol; }
function head(s) { console.log(`\n— ${s} —`); }

/* ============================================================================
   A. The exchange rate: best-possible seed tables, then Newton rounds
   ========================================================================= */

// The reduction range. For x = m * 4^e with m in [1,4), 1/sqrt(x) = (1/sqrt(m)) * 2^-e,
// and the exponent factor is exact in binary floating point. So a seed table over
// [1,4) is a seed table for every positive float, which is exactly how a hardware
// rsqrt seed table is built. All accuracy figures below are for the mantissa leg.
const LO = 1, HI = 4;

/** Best possible constant table of 2^k entries over [1,4).
 *  Within a bin, the constant minimising MAX RELATIVE error of a monotone function is
 *  the harmonic mean of the endpoint values: it equalises the relative error at the two
 *  ends. So these figures are the best any 2^k-entry constant table can do with THIS
 *  binning (uniform over [1,4)). Other binnings do better: see section B2 (corrected
 *  2026-11-01 by the assay line; it used to say "an upper bound on what any 2^k-entry
 *  constant table can do"). */
function bestTable(k) {
  const n = 1 << k, t = new Float64Array(n);
  for (let i = 0; i < n; i++) {
    const a = LO + (HI - LO) * i / n, b = LO + (HI - LO) * (i + 1) / n;
    const fa = 1 / Math.sqrt(a), fb = 1 / Math.sqrt(b);
    t[i] = 2 / (1 / fa + 1 / fb);
  }
  return t;
}

/** One Newton round for y ~ 1/sqrt(x): the Quake line, y*(1.5 - 0.5*x*y*y). */
const newton = (y, x) => y * (1.5 - 0.5 * x * y * y);

/** Worst relative seed error of the best 2^k table, computed EXACTLY.
 *  Within a bin the relative error c/f(x) - 1 is monotone in x (f monotone, c constant),
 *  so the maximum sits at a bin endpoint and no sampling is needed. */
function seedWorstExact(k) {
  const t = bestTable(k), n = 1 << k;
  let worst = 0;
  for (let i = 0; i < n; i++) {
    const a = LO + (HI - LO) * i / n, b = LO + (HI - LO) * (i + 1) / n;
    worst = Math.max(worst, Math.abs(t[i] * Math.sqrt(a) - 1), Math.abs(t[i] * Math.sqrt(b) - 1));
  }
  return worst;
}

/** Correct bits = -log2(max relative error) over a dense sweep of [1,4). */
function tableBits(k, r, S = 300000) {
  const t = bestTable(k), n = 1 << k;
  let worst = 0;
  for (let s = 0; s < S; s++) {
    const x = LO + (HI - LO) * (s + 0.5) / S;
    let idx = Math.floor((x - LO) / (HI - LO) * n); if (idx >= n) idx = n - 1;
    let y = t[idx];
    for (let j = 0; j < r; j++) y = newton(y, x);
    const e = Math.abs(y * Math.sqrt(x) - 1);
    if (e > worst) worst = e;
  }
  return worst === 0 ? Infinity : -Math.log2(worst);
}

head('A1. the seed table is minimax by construction');
{
  const t = bestTable(3), n = 8;
  let worstAsym = 0;
  for (let i = 0; i < n; i++) {
    const a = LO + 3 * i / n, b = LO + 3 * (i + 1) / n;
    const ea = Math.abs(t[i] * Math.sqrt(a) - 1), eb = Math.abs(t[i] * Math.sqrt(b) - 1);
    worstAsym = Math.max(worstAsym, Math.abs(ea - eb));
  }
  ok('harmonic-mean entry equalises relative error at both bin ends', worstAsym < 1e-15,
     `max end-to-end asymmetry = ${worstAsym.toExponential(2)}`);
  // and it really is optimal: perturbing an entry cannot lower that bin's max error
  const i = 3, a = LO + 3 * i / 8, b = LO + 3 * (i + 1) / 8;
  const base = Math.abs(t[i] * Math.sqrt(a) - 1);
  const worse = [0.999, 1.001].map(f => Math.max(
    Math.abs(t[i] * f * Math.sqrt(a) - 1), Math.abs(t[i] * f * Math.sqrt(b) - 1)));
  ok('perturbing an entry only raises that bin\'s max relative error', worse.every(w => w > base),
     `base ${base.toExponential(3)} vs ${worse.map(w => w.toExponential(3)).join(' / ')}`);
}

head('A2. a 2^k-entry table buys k + log2(4/3) bits: one bit per doubling, plus a constant');
const SEED_BITS = {};
for (let k = 0; k <= 20; k++) SEED_BITS[k] = -Math.log2(seedWorstExact(k));
{
  // The asymptotic constant is exact and comes from the leftmost bin, where 1/√x is steepest:
  // a bin of relative width w costs about w/4 in relative error, w → 3/2^k at x = 1, so the
  // worst relative error tends to (3/4)·2^-k and the bit count to k + log2(4/3).
  const LOG43 = Math.log2(4 / 3);
  ok('log2(4/3) = 0.4150375…', near(LOG43, 0.41503749928, 1e-10), `${LOG43.toFixed(10)}`);
  for (const k of [4, 8, 12, 16, 20]) {
    ok(`2^${k} entries seeds ${SEED_BITS[k].toFixed(4)} bits (k + ${(SEED_BITS[k] - k).toFixed(4)})`,
       SEED_BITS[k] - k > LOG43 && SEED_BITS[k] - k < LOG43 + 0.2,
       `${(1 << k).toLocaleString()} entries → ${SEED_BITS[k].toFixed(4)} bits; the offset falls toward log2(4/3) from above`);
  }
  ok('the offset converges to log2(4/3) as the bins shrink',
     near(SEED_BITS[20] - 20, LOG43, 5e-5),
     `k=20 offset ${(SEED_BITS[20] - 20).toFixed(6)} vs ${LOG43.toFixed(6)}`);
  const slopes = [];
  for (let k = 9; k <= 20; k++) slopes.push(SEED_BITS[k] - SEED_BITS[k - 1]);
  const meanSlope = slopes.reduce((a, b) => a + b) / slopes.length;
  ok('one extra bit of index buys exactly one extra bit of answer (slope 1.000 over k=8..20)',
     near(meanSlope, 1, 0.002), `mean slope = ${meanSlope.toFixed(5)} bits/doubling`);
  ok('and the rule of thumb breaks at tiny tables, honestly',
     SEED_BITS[0] - 0 > 1.5, `a 1-entry table gets ${SEED_BITS[0].toFixed(3)} bits, not 0.415: with one bin there is no "leftmost bin" to be worst`);
  // the sampled sweep must agree with the exact endpoint computation
  const sampled = tableBits(6, 0);
  ok('the dense sweep agrees with the exact endpoint computation', near(sampled, SEED_BITS[6], 0.01),
     `sweep ${sampled.toFixed(4)} vs exact ${SEED_BITS[6].toFixed(4)} bits`);

  // And there is a closed form, because the worst bin is always the leftmost one: bins are
  // uniform in x, the relative swing of 1/√x across a bin is (1/2)·ln(b/a), and ln(b/a) is
  // largest at the left. With c the harmonic mean of the endpoint values, the worst relative
  // error is exactly (√b − 1)/(√b + 1) with b = 1 + 3·2^-k. This is what the page computes.
  const closed = (k) => { const b = 1 + 3 * Math.pow(2, -k); const s = Math.sqrt(b); return -Math.log2((s - 1) / (s + 1)); };
  let worstGap = 0;
  for (let k = 0; k <= 20; k++) worstGap = Math.max(worstGap, Math.abs(closed(k) - SEED_BITS[k]));
  ok('closed form: worst relative seed error = (√b − 1)/(√b + 1), b = 1 + 3·2^-k',
     worstGap < 1e-9, `max disagreement with the brute-force endpoint sweep over k=0..20: ${worstGap.toExponential(2)} bits`);
  ok('and the leftmost bin really is the worst one', (() => {
    const t = bestTable(8), n = 256; let argmax = -1, best = -1;
    for (let i = 0; i < n; i++) {
      const a = LO + 3 * i / n, e = Math.abs(t[i] * Math.sqrt(a) - 1);
      if (e > best) { best = e; argmax = i; }
    }
    return argmax === 0;
  })(), 'checked over all 256 bins of a 2^8 table: the maximum is in bin 0, where 1/√x is steepest');
}

head('A3. Newton does not quite double: the shortfall is exactly log2(3/2)');
{
  // Analytic: with y = (1+e)/sqrt(x), one round gives e' = -1.5 e^2 - 0.5 e^3.
  let worstRes = 0;
  for (const e of [1e-2, 1e-3, 1e-4, 3e-3, -2e-3]) {
    const x = 2.7, y = (1 + e) / Math.sqrt(x);
    const ePrime = newton(y, x) * Math.sqrt(x) - 1;
    const predicted = -1.5 * e * e - 0.5 * e * e * e;
    worstRes = Math.max(worstRes, Math.abs(ePrime - predicted) / Math.abs(predicted));
  }
  ok('the Newton line is exactly e → -1.5e² - 0.5e³', worstRes < 1e-8,
     `worst relative residual = ${worstRes.toExponential(2)}`);

  const LOG15 = Math.log2(1.5);
  ok('log2(3/2) = 0.5849625…', near(LOG15, 0.5849625007, 1e-9), `${LOG15.toFixed(10)}`);

  // Measured across the grid, away from the arithmetic floor.
  const shortfalls = [];
  for (let k = 0; k <= 10; k++) {
    for (let r = 0; r <= 2; r++) {
      const b0 = tableBits(k, r), b1 = tableBits(k, r + 1);
      if (b1 > 49) continue;                 // float64 measurement floor: excluded
      shortfalls.push(2 * b0 - b1);
    }
  }
  const meanShort = shortfalls.reduce((a, b) => a + b) / shortfalls.length;
  const maxDev = Math.max(...shortfalls.map(s => Math.abs(s - LOG15)));
  ok('measured: bits(r+1) = 2·bits(r) − log2(3/2), across the whole grid',
     near(meanShort, LOG15, 0.05) && maxDev < 0.35,
     `${shortfalls.length} grid transitions, mean shortfall ${meanShort.toFixed(4)} bits vs log2(1.5)=${LOG15.toFixed(4)}, max deviation ${maxDev.toFixed(3)}`);
}

head('A4. the exchange rate: one extra round square-roots the table');
/** Entries needed to reach B bits after r rounds, by inverting the measured seed curve. */
function entriesFor(B, r) {
  const need = (B + Math.log2(1.5) * (Math.pow(2, r) - 1)) / Math.pow(2, r); // seed bits required
  // Invert the MEASURED seed curve. Past k = 20 the measured offset has converged to
  // log2(4/3) to five decimals, so the law is used there rather than a 16-million-bin sweep.
  const bitsAt = (k) => SEED_BITS[k] ?? (k + Math.log2(4 / 3));
  let k = 0;
  while (k < 40 && bitsAt(k) < need) k++;
  return { seedBitsNeeded: need, k, entries: Math.pow(2, k) };
}
const TARGET = 24;   // a float32 significand
const LADDER = [0, 1, 2, 3, 4].map(r => ({ r, ...entriesFor(TARGET, r) }));
{
  for (const row of LADDER) {
    console.log(`     ${row.r} round(s): seed must supply ${row.seedBitsNeeded.toFixed(2)} bits → 2^${row.k} = ${row.entries.toLocaleString()} entries`);
  }
  ok('0 rounds to 24 bits needs a table of millions of entries', LADDER[0].entries >= 1 << 23,
     `2^${LADDER[0].k} = ${LADDER[0].entries.toLocaleString()} entries`);
  ok('1 round drops it to thousands', LADDER[1].entries >= 1024 && LADDER[1].entries <= 8192,
     `2^${LADDER[1].k} = ${LADDER[1].entries.toLocaleString()} entries`);
  ok('2 rounds drops it to dozens', LADDER[2].entries >= 16 && LADDER[2].entries <= 128,
     `2^${LADDER[2].k} = ${LADDER[2].entries} entries`);
  ok('3 rounds drops it to a handful', LADDER[3].entries <= 8,
     `2^${LADDER[3].k} = ${LADDER[3].entries} entries`);
  ok('4 rounds drops it to almost nothing', LADDER[4].entries <= 4,
     `2^${LADDER[4].k} = ${LADDER[4].entries} entries`);
  // the square-root law, measured on the ladder itself
  const devs = [];
  for (let i = 0; i + 1 < LADDER.length; i++) {
    if (LADDER[i].k === 0) break;
    devs.push(LADDER[i + 1].k - LADDER[i].k / 2);   // 0 would be an exact square root
  }
  // The closed form's own prediction, with k left continuous (corrected 2026-11-01 by the
  // assay line: this line used to print a typed "predicted −0.21", which is log2(4/3)/2 with
  // the Newton tax left out). Bisect the page's closed form for the k that supplies `need`.
  const closedBits = (k) => { const b = 1 + 3 * Math.pow(2, -k); const s = Math.sqrt(b); return -Math.log2((s - 1) / (s + 1)); };
  const kCont = (need) => { let lo = 0, hi = 60; for (let i = 0; i < 200; i++) { const m = (lo + hi) / 2; if (closedBits(m) < need) lo = m; else hi = m; } return lo; };
  const ks = LADDER.map(row => kCont(row.seedBitsNeeded));
  const predDevs = ks.slice(1).map((k, i) => k - ks[i] / 2);
  const asym = (Math.log2(1.5) - Math.log2(4 / 3)) / 2;
  ok('each round roughly halves log2(table), i.e. square-roots the table',
     devs.every(d => d <= 0.5 + 1e-9 && d >= -1.2),
     `log2 deviations from an exact square root: ${devs.map(d => d.toFixed(2)).join(', ')} (the closed form with k unrounded predicts ${predDevs.map(d => (d >= 0 ? '+' : '') + d.toFixed(2)).join(', ')}; integer k rounds them)`);
  ok('the closed form\'s predicted deviation tends to (log2(3/2) − log2(4/3))/2 = +0.085 for large tables',
     near(predDevs[0], asym, 0.005) && near(asym, 0.0850, 0.0001),
     `first transition (2^24 → 2^12 scale) ${predDevs[0].toFixed(4)} vs limit ${asym.toFixed(4)}; the page prints +0.08, +0.05, −0.16, −0.58`);
  ok('the page\'s printed predictions match the closed form',
     [0.08, 0.05, -0.16, -0.58].every((v, i) => near(predDevs[i], v, 0.006)),
     predDevs.map(d => d.toFixed(3)).join(', '));
}

head('A5. the floors are real, and the page shows them');
{
  ok('float64 error measurement floors near 51 bits', tableBits(12, 3) > 45 && tableBits(12, 3) < 53,
     `2^12 table + 3 rounds → ${tableBits(12, 3).toFixed(2)} bits (the sweep\'s own arithmetic floor, not the method\'s limit)`);
  // float32 pipeline: the historical case
  const f32 = Math.fround;
  function f32Bits(k, r, S = 200000) {
    const t = bestTable(k), n = 1 << k; let worst = 0;
    for (let s = 0; s < S; s++) {
      const x = f32(LO + (HI - LO) * (s + 0.5) / S);
      let idx = Math.floor((x - LO) / (HI - LO) * n); if (idx >= n) idx = n - 1;
      let y = f32(t[idx]);
      for (let j = 0; j < r; j++) y = f32(f32(y) * f32(1.5 - f32(0.5 * f32(x * f32(y * y)))));
      const e = Math.abs(y * Math.sqrt(x) - 1);
      if (e > worst) worst = e;
    }
    return -Math.log2(worst);
  }
  const b = f32Bits(8, 3);
  ok('in float32 the same pipeline ceilings near the 24-bit significand', b > 20 && b < 25,
     `2^8 table + 3 rounds in float32 → ${b.toFixed(2)} bits`);
}

/* ============================================================================
   B. 0x5f3759df: a lookup table with no entries
   ========================================================================= */

head('B. the magic constant is a table of size zero');
const MAGIC = 0x5f3759df;
const _b = new ArrayBuffer(4), _f = new Float32Array(_b), _i = new Uint32Array(_b);
function magicSeed(x) { _f[0] = x; _i[0] = MAGIC - (_i[0] >> 1); return _f[0]; }
let MAGIC_SEED_BITS = 0, MAGIC_R1_BITS = 0, MAGIC_MAXERR = 0;
{
  ok('0x5f3759df = 1597463007', MAGIC === 1597463007, `${MAGIC}`);
  let worst0 = 0, worst1 = 0;
  for (let s = 0; s < 400000; s++) {
    const x = Math.fround(LO + (HI - LO) * (s + 0.5) / 400000);
    const y0 = magicSeed(x);
    const y1 = Math.fround(y0 * (1.5 - 0.5 * x * y0 * y0));
    worst0 = Math.max(worst0, Math.abs(y0 * Math.sqrt(x) - 1));
    worst1 = Math.max(worst1, Math.abs(y1 * Math.sqrt(x) - 1));
  }
  MAGIC_MAXERR = worst0;
  MAGIC_SEED_BITS = -Math.log2(worst0);
  MAGIC_R1_BITS = -Math.log2(worst1);
  ok('seed max relative error ≈ 3.44% (agrees with the member layer\'s verifier)',
     near(worst0 * 100, 3.4376, 0.02), `${(worst0 * 100).toFixed(4)}% over [1,4)`);
  ok('after one Newton round ≈ 0.175% (agrees with the member layer\'s verifier)',
     near(worst1 * 100, 0.17522, 0.01), `${(worst1 * 100).toFixed(5)}%`);
  ok('so the constant seeds 4.86 bits from zero stored entries',
     near(MAGIC_SEED_BITS, 4.862, 0.03), `${MAGIC_SEED_BITS.toFixed(3)} bits`);

  // The table-equivalence: which best-possible table matches it?
  let kLower = -1, kUpper = -1;
  for (let k = 0; k <= 14; k++) {
    if (SEED_BITS[k] <= MAGIC_SEED_BITS) kLower = k;
    if (kUpper < 0 && SEED_BITS[k] >= MAGIC_SEED_BITS) kUpper = k;
  }
  ok('it seeds better than the best possible 16-entry table',
     MAGIC_SEED_BITS > SEED_BITS[4], `${MAGIC_SEED_BITS.toFixed(3)} > ${SEED_BITS[4].toFixed(3)} bits`);
  ok('and not as well as the best possible 32-entry table',
     MAGIC_SEED_BITS < SEED_BITS[5], `${MAGIC_SEED_BITS.toFixed(3)} < ${SEED_BITS[5].toFixed(3)} bits`);
  ok('so its table-equivalent is between 2^4 and 2^5 entries', kLower === 4 && kUpper === 5,
     `bracketed by k=${kLower} and k=${kUpper}`);
  // storage comparison, stated in bits actually filed
  const constantBits = 32;                       // the constant itself
  const tableBitsStored = (1 << 5) * 32;         // 32 float32 entries
  ok('the constant files 32 bits where the equivalent table files 1,024',
     constantBits === 32 && tableBitsStored === 1024,
     `${tableBitsStored / constantBits}× less filed, for the same seed accuracy`);
  ok('it beats a 1-entry table by more than 3 bits (a table cannot exploit the exponent)',
     MAGIC_SEED_BITS - SEED_BITS[0] > 3,
     `${MAGIC_SEED_BITS.toFixed(3)} vs ${SEED_BITS[0].toFixed(3)} bits; the constant reads the float\'s exponent as a logarithm, a table only indexes it`);
}

/* ============================================================================
   B2. The binning is a choice, and hardware makes a different one (added 2026-11-01)
   ========================================================================= */

// Added by the assay line on 2026-11-01, when the page's claim that bins uniform over
// [1,4) are "what a hardware seed table indexed by leading mantissa bits actually does"
// was found false. Arm's FRSQRTE (as QEMU's vfp_helper.c implements the Arm ARM) indexes
// by the exponent's parity plus leading fraction bits, so its bins are uniform WITHIN each
// binade: n/2 bins over [1,2) and n/2 twice as wide over [2,4). Bins uniform in log x are
// the other natural choice. Both beat the page's binning, and both move the constant's
// table equivalent from 16-32 entries down to 8-16.
head('B2. the same constant against other binnings of the same size');
let B2 = {};
{
  // Closed forms: with the harmonic-mean entry the worst relative error of a bin [a,b] is
  // (√(b/a) − 1)/(√(b/a) + 1), so the worst bin is the one with the largest ratio b/a.
  const bitsRatio = (ratio) => { const s = Math.sqrt(ratio); return -Math.log2((s - 1) / (s + 1)); };
  const perBinade = (k) => bitsRatio(1 + Math.pow(2, 1 - k));       // leftmost bin [1, 1 + 2/n]
  const logUniform = (k) => bitsRatio(Math.pow(4, Math.pow(2, -k))); // every bin has ratio 4^(1/n)
  // A dense float32 sweep of a per-binade table, so the closed form is not trusted alone.
  function perBinadeSweep(k, S = 400000) {
    const n = 1 << k, h = n / 2, t = [];
    for (let i = 0; i < h; i++) { const a = 1 + i / h, b = 1 + (i + 1) / h; t.push(2 / (Math.sqrt(a) + Math.sqrt(b))); }
    for (let i = 0; i < h; i++) { const a = 2 + 2 * i / h, b = 2 + 2 * (i + 1) / h; t.push(2 / (Math.sqrt(a) + Math.sqrt(b))); }
    let worst = 0;
    for (let s = 0; s < S; s++) {
      const x = Math.fround(LO + (HI - LO) * (s + 0.5) / S);
      const idx = x < 2 ? Math.min(h - 1, Math.floor((x - 1) * h)) : h + Math.min(h - 1, Math.floor((x - 2) / 2 * h));
      worst = Math.max(worst, Math.abs(t[idx] * Math.sqrt(x) - 1));
    }
    return -Math.log2(worst);
  }
  const sw3 = perBinadeSweep(3), sw4 = perBinadeSweep(4);
  ok('per-binade closed form agrees with a 400,000-point float32 sweep (8 and 16 entries)',
     near(sw3, perBinade(3), 0.001) && near(sw4, perBinade(4), 0.001),
     `8: ${sw3.toFixed(4)} vs ${perBinade(3).toFixed(4)}, 16: ${sw4.toFixed(4)} vs ${perBinade(4).toFixed(4)} bits`);
  ok('binned per binade, as hardware does, 0x5f3759df sits between 8 and 16 entries',
     perBinade(3) < MAGIC_SEED_BITS && MAGIC_SEED_BITS < perBinade(4),
     `${perBinade(3).toFixed(3)} < ${MAGIC_SEED_BITS.toFixed(3)} < ${perBinade(4).toFixed(3)} bits`);
  ok('binned uniformly in log x, it also sits between 8 and 16 entries',
     logUniform(3) < MAGIC_SEED_BITS && MAGIC_SEED_BITS < logUniform(4),
     `${logUniform(3).toFixed(3)} < ${MAGIC_SEED_BITS.toFixed(3)} < ${logUniform(4).toFixed(3)} bits`);
  ok('per-binade bins gain on the page\'s binning, tending to log2(3/2) = 0.585 bits',
     near(perBinade(20) - SEED_BITS[20], Math.log2(1.5), 0.001) && perBinade(4) - SEED_BITS[4] > 0.5,
     `k=4: +${(perBinade(4) - SEED_BITS[4]).toFixed(3)}, k=20: +${(perBinade(20) - SEED_BITS[20]).toFixed(4)} bits`);
  ok('log-uniform bins gain about 1.11 bits, worth a doubling of the table',
     near(logUniform(20) - SEED_BITS[20], 1.11, 0.01) && logUniform(4) - SEED_BITS[4] > 0.95,
     `k=4: +${(logUniform(4) - SEED_BITS[4]).toFixed(3)}, k=20: +${(logUniform(20) - SEED_BITS[20]).toFixed(4)} bits`);
  B2 = { perBinade8: perBinade(3), perBinade16: perBinade(4), log8: logUniform(3), log16: logUniform(4) };
}

/* ============================================================================
   C. CORDIC: a table of moves, and a flat exchange rate
   ========================================================================= */

head('C. CORDIC\'s ladder: one rung, one bit, and no trade available');
const ATAN = []; for (let i = 0; i < 60; i++) ATAN.push(Math.atan(Math.pow(2, -i)));
const K_CORDIC = (() => { let k = 1; for (let i = 0; i < 60; i++) k /= Math.sqrt(1 + Math.pow(4, -i)); return k; })();
function cordicSinCos(theta, n) {
  let x = K_CORDIC, y = 0, z = theta;
  for (let i = 0; i < n; i++) {
    const d = z >= 0 ? 1 : -1, p = Math.pow(2, -i);
    const xn = x - d * y * p, yn = y + d * x * p;
    x = xn; y = yn; z -= d * ATAN[i];
  }
  return { cos: x, sin: y };
}
function cordicBits(n, S = 2000) {
  const RANGE = 1.0; let worst = 0;
  for (let s = 0; s < S; s++) {
    const th = -RANGE + 2 * RANGE * (s + 0.5) / S;
    const { sin } = cordicSinCos(th, n);
    worst = Math.max(worst, Math.abs(sin - Math.sin(th)));   // absolute; sin is O(1) here
  }
  return -Math.log2(worst);
}
const CORDIC_BITS = {};
for (let n = 4; n <= 44; n++) CORDIC_BITS[n] = cordicBits(n);
{
  ok('K = 0.6072529350088813 (agrees with the member layer\'s verifier)',
     near(K_CORDIC, 0.6072529350088813, 1e-15), `${K_CORDIC.toFixed(16)}`);
  const slopes = [];
  for (let n = 9; n <= 40; n++) slopes.push(CORDIC_BITS[n] - CORDIC_BITS[n - 1]);
  const mean = slopes.reduce((a, b) => a + b) / slopes.length;
  ok('one rung buys one bit, flat, over n = 8..40', near(mean, 1, 0.06),
     `mean slope ${mean.toFixed(4)} bits/rung`);
  ok('and the rate never improves: no rung ever buys two bits',
     slopes.every(s => s < 1.5), `max single-rung gain ${Math.max(...slopes).toFixed(3)} bits`);
  ok('so CORDIC needs one filed constant per bit of answer',
     Math.abs(CORDIC_BITS[24] - 24) < 3, `24 rungs → ${CORDIC_BITS[24].toFixed(2)} bits`);
  // the contrast, in the one currency both share: entries filed
  const cordicEntries24 = 24;
  const newtonEntries24_r0 = LADDER[0].entries;
  ok('at 24 bits and zero correction rounds, the ladder files 24 constants and the table files millions',
     cordicEntries24 < newtonEntries24_r0 / 100000,
     `${cordicEntries24} vs ${newtonEntries24_r0.toLocaleString()} — but the ladder pays 24 rounds and the table pays none`);
}

head('C2. what actually separates them: whether the filed thing is indexed by the question');
{
  // A seed table IS indexed by the question: a different x reads a different entry.
  const t = bestTable(6);
  const idxOf = (x) => Math.min(63, Math.floor((x - LO) / 3 * 64));
  const i1 = idxOf(1.2), i2 = idxOf(3.7);
  ok('the seed table is indexed by the question: a different x reads a different entry',
     i1 !== i2 && t[i1] !== t[i2],
     `x=1.2 → entry ${i1} (${t[i1].toFixed(6)}), x=3.7 → entry ${i2} (${t[i2].toFixed(6)})`);
  ok('and each entry is already an answer: read it and you hold 1/√x to about 6 bits',
     Math.abs(t[i2] * Math.sqrt(3.7) - 1) < 0.02,
     `table[${i2}] = ${t[i2].toFixed(6)} vs true 1/√3.7 = ${(1 / Math.sqrt(3.7)).toFixed(6)}`);

  // CORDIC's table is NOT indexed by anything: every angle consumes the same constants,
  // in the same order. Only the SIGN sequence carries the question. Instrument and check.
  function trace(theta, n) {
    let x = K_CORDIC, y = 0, z = theta; const used = [], signs = [];
    for (let i = 0; i < n; i++) {
      const d = z >= 0 ? 1 : -1, p = Math.pow(2, -i);
      used.push(ATAN[i]); signs.push(d);
      const xn = x - d * y * p, yn = y + d * x * p;
      x = xn; y = yn; z -= d * ATAN[i];
    }
    return { used, signs };
  }
  const A = trace(0.31, 20), B = trace(-1.42, 20);
  ok('CORDIC reads the identical constants in the identical order for two unrelated angles',
     A.used.every((v, i) => v === B.used[i]),
     `20 rungs, all 20 table entries identical for θ=0.31 and θ=-1.42`);
  ok('only the sign sequence differs, so the question lives in the signs, not the table',
     A.signs.some((s, i) => s !== B.signs[i]),
     `sign words differ in ${A.signs.filter((s, i) => s !== B.signs[i]).length} of 20 positions`);
  ok('so the arctan ladder is not a filed answer at all: it is a filed alphabet',
     true, 'the answer is the signed-digit word the machine writes at run time; the table only supplies the digits it may write');
  ok('which is why the exchange rates differ: squaring an error needs an error to square',
     true, 'Newton refines an estimate the seed already supplied (quadratic); CORDIC has no estimate to refine and must construct one digit at a time (linear)');
}

/* ============================================================================
   D. The deadline: zero rounds available, at any price
   ========================================================================= */

head('D. the deadline leg, recomputed independently of the member layer');
const K_PATH = 0.8817;               // round-trip nerve path as a fraction of height
const HEIGHT = 1.70, CV = 85, SYN = 0.7;
{
  const L = K_PATH * HEIGHT;
  const loop = (L / CV) * 1000 + SYN;
  ok('spinal loop at 1.70 m, 85 m/s ≈ 18.3 ms', near(loop, 18.34, 0.05),
     `L = ${L.toFixed(3)} m, t = L/CV + synapse = ${loop.toFixed(2)} ms`);
  // a cortical detour: cord conduction up and down, plus minimum cortical processing
  const cordUpDown = (2 * 0.45 / CV) * 1000;     // ~0.45 m of cord each way
  const detour = loop + cordUpDown + 20;
  ok('any cortical detour costs at least ~49 ms, more than twice the reflex',
     detour > 45 && detour < 55, `${detour.toFixed(1)} ms vs an 18–30 ms measured reflex window`);
  ok('so the correction rounds available inside the reflex window is exactly zero',
     detour > 30, `${detour.toFixed(1)} ms > 30 ms: there is no time for even one consultation`);
  ok('a fast voluntary response is far outside the window', 90 > 30,
     'about 90 ms, a voluntary response to a go signal in biceps brachii. NOTE: the member layer ' +
     'corrected an earlier, larger version of this claim on 2026-08-01 (it had called the figure a ' +
     'record for deliberate movement, which the source does not support), and this portal carries ' +
     'only the corrected size.');
  ok('what is filed here is one answer, with no index at all',
     true, 'the monosynaptic arc has no question to look up: a stretch triggers the contraction directly, though its size can be damped, exaggerated or enlarged (Jendrassik manoeuvre)');
}

/* ============================================================================
   E. The repertoire: a small filed generator standing for an enormous space
   ========================================================================= */

head('E. the repertoire leg, from the member layer\'s declared toy model');
{
  const V = 48, D = 2, J = 13;
  const combos = V * D * J;
  ok('the filed segment inventory is 48 × 2 × 13 = 1,248 combinations',
     combos === 1248, `${combos} segment combinations (the member layer\'s declared toy model)`);
  const segEntropy = 9.048440, keyEntropy = 43.712331, diversity = 1.4412e13;
  ok('segment choice carries 9.048 bits of entropy', near(segEntropy, 9.048440, 1e-5), `${segEntropy} bits`);
  ok('the assembled event-key entropy is 43.712 bits', near(keyEntropy, 43.712331, 1e-5), `${keyEntropy} bits`);
  ok('so the assembly manufactures ~34.7 bits the inventory never stored',
     near(keyEntropy - segEntropy, 34.66, 0.01),
     `${(keyEntropy - segEntropy).toFixed(3)} bits from junctional deletion and insertion, generated at assembly time, not filed`);
  const ratio = diversity / combos;
  ok('1,248 filed combinations stand behind a Shannon diversity of 1.44e13',
     ratio > 1e9, `a factor of ${ratio.toExponential(2)}`);
  ok('and the rounds paid on first contact are zero',
     true, 'the receptor that meets the pathogen was assembled before the pathogen existed');
}

/* ============================================================================
   F. Honesty: the claims this portal refuses to make
   ========================================================================= */

head('F. the claims this portal refuses to make');
{
  ok('no unit conversion is attempted across the seam', true,
     'bits, rungs, milliseconds and event-keys are reported in their own units and never combined into one number');
  ok('the shared quantity is named as structural, not numerical', true,
     'what is shared is: something was filed before the question, and the rest is bought back in rounds');
  const vdjPage = join(ROOT, 'public/strata/vdj-repertoire/index.html');
  if (existsSync(vdjPage)) {
    const src = readFileSync(vdjPage, 'utf8');
    const mentionsMaturation = /hypermutation|affinity matur/i.test(src);
    ok('the linked V(D)J layer carries no affinity-maturation step (checked on disk)',
       !mentionsMaturation,
       mentionsMaturation ? 'FOUND a maturation mention — the portal\'s disclosure needs updating' :
       'confirmed absent, so the portal names somatic hypermutation as a complication NOT on that layer');
  } else {
    ok('member page present for the disclosure check', false, `missing ${vdjPage}`);
  }
  // the four member pages exist and are linked
  for (const slug of ['cordic', 'fast-inverse-sqrt', 'vdj-repertoire', 'the-jerk-that-skips-your-brain']) {
    ok(`member layer on disk: ${slug}`, existsSync(join(ROOT, 'src/content/strata', `${slug}.md`)));
  }
  // the one pair already published as a relation, which the portal must not claim as new
  const cordicMd = readFileSync(join(ROOT, 'src/content/strata/cordic.md'), 'utf8');
  ok('cordic already relates: to fast-inverse-sqrt, so the portal does not claim that pair',
     /to:\s*fast-inverse-sqrt/.test(cordicMd),
     'published as "kin in spirit, opposite in method"; the portal states the exchange rate instead, which neither page carries');
}

/* ============================================================================
   G. The page states what this file measured
   ========================================================================= */

head('G. the page and this verifier agree');
const PAGE = join(ROOT, 'public/strata/filed-before-the-question/index.html');
if (existsSync(PAGE)) {
  const src = readFileSync(PAGE, 'utf8');
  const mustSay = [
    ['0x5f3759df', /0x5f3759df/],
    ['the log2(3/2) shortfall', /0\.585|log₂\(3\/2\)|log2\(3\/2\)/],
    ['the seed accuracy of the constant, 4.86 bits', /4\.86/],
    ['the 16-to-32 entry table equivalence', /16 and 32|16-to-32|between 16 and 32/],
    ['the 8-to-16 entry equivalence with hardware binning', /between 8 and 16/],
    ['the closed form\'s unrounded deviations, +0.08, +0.05, −0.16, −0.58', /\+0\.08, \+0\.05, &minus;0\.16 and &minus;0\.58/],
    ['the 18 ms reflex', /18\.3|18 ms|18 milliseconds/],
    ['the 1,248 filed combinations', /1,248|1248/],
    ['one rung, one bit', /one rung|per rung/i],
    ['the closed form for the seed error', /\(&radic;b &minus; 1\)\/\(&radic;b \+ 1\)/],
    ['the log2(4/3) offset', /log&#8322;\(4\/3\)|0\.4150/],
    ['that no four-way axis is claimed', /no four-way axis|not an axis|never combined/i],
  ];
  for (const [what, re] of mustSay) ok(`page states ${what}`, re.test(src));

  // The page's four station blocks carry their figures as data attributes. Parse them out
  // and re-derive each one here, so the page cannot drift away from this file silently.
  const stations = {};
  for (const m of src.matchAll(/<div class="station"([^>]*)>/g)) {
    const attrs = {};
    for (const a of m[1].matchAll(/([a-z0-9-]+)="([^"]*)"/g)) attrs[a[1]] = a[2];
    if (attrs['data-slug']) stations[attrs['data-slug']] = attrs;
  }
  ok('the page carries all four station blocks', Object.keys(stations).length === 4,
     `found: ${Object.keys(stations).join(', ')}`);

  const S = (slug, key) => stations[slug]?.[key];
  ok('station: the reflex loop time on the page matches the recomputation here',
     near(+S('the-jerk-that-skips-your-brain', 'data-loop-ms'), (K_PATH * HEIGHT / CV) * 1000 + SYN, 0.02),
     `page says ${S('the-jerk-that-skips-your-brain', 'data-loop-ms')} ms`);
  ok('station: the reflex rounds available is zero',
     S('the-jerk-that-skips-your-brain', 'data-rounds') === '0');
  ok('station: the CORDIC rate on the page matches the measured slope',
     near(+S('cordic', 'data-rate'), 1.0001, 0.01), `page says ${S('cordic', 'data-rate')} bits/rung`);
  ok('station: the CORDIC gain on the page matches the recomputed K',
     +S('cordic', 'data-k') === K_CORDIC, `page says ${S('cordic', 'data-k')}`);
  ok('station: the magic constant seed accuracy on the page matches the measurement',
     near(+S('fast-inverse-sqrt', 'data-seed-bits'), MAGIC_SEED_BITS, 0.002),
     `page says ${S('fast-inverse-sqrt', 'data-seed-bits')} bits, measured ${MAGIC_SEED_BITS.toFixed(4)}`);
  ok('station: the magic constant seed error on the page matches the measurement',
     near(+S('fast-inverse-sqrt', 'data-seed-err-pct'), MAGIC_MAXERR * 100, 0.002),
     `page says ${S('fast-inverse-sqrt', 'data-seed-err-pct')}%`);
  ok('station: the V(D)J filed count on the page is the product of its own segment counts',
     +S('vdj-repertoire', 'data-filed-count') === 48 * 2 * 13, `page says ${S('vdj-repertoire', 'data-filed-count')}`);
  ok('station: the V(D)J entropies on the page match the member layer\'s verifier',
     +S('vdj-repertoire', 'data-seg-entropy') === 9.048440 && +S('vdj-repertoire', 'data-key-entropy') === 43.712331,
     `page says ${S('vdj-repertoire', 'data-seg-entropy')} and ${S('vdj-repertoire', 'data-key-entropy')} bits`);

  // Every station must link to its own layer as real markup, not JS-rendered.
  for (const slug of Object.keys(stations)) {
    ok(`station links out to /strata/${slug}/ as real markup`,
       src.includes(`href="/strata/${slug}/"`));
  }

  // The browser and this file must agree on the frontier. Re-derive the page's own
  // closed form the way its script does, and confirm it reproduces the ladder above.
  const pageClosed = (k) => { const b = 1 + 3 * Math.pow(2, -k); const s = Math.sqrt(b); return -Math.log2((s - 1) / (s + 1)); };
  const pageLadder = [0, 1, 2, 3].map((r) => {
    const p = Math.pow(2, r), need = (24 + Math.log2(1.5) * (p - 1)) / p;
    let k = 0; while (pageClosed(k) < need) k++;
    return Math.pow(2, k);
  });
  ok('the browser\'s frontier for 24 bits reproduces this file\'s ladder',
     pageLadder.every((e, i) => e === LADDER[i].entries),
     `browser: ${pageLadder.map((e) => e.toLocaleString()).join(' → ')}`);
} else {
  console.log('  (page not built yet — the coupling checks above will run once it is)');
}

/* ========================================================================= */
console.log(`\n${pass}/${pass + fail} checks green${fail ? `  (${fail} FAILED)` : ''}`);

// Machine-readable summary the page is built from.
const summary = {
  seedBits: Object.fromEntries(Object.entries(SEED_BITS).map(([k, v]) => [k, +v.toFixed(4)])),
  cordicBits: Object.fromEntries(Object.entries(CORDIC_BITS).map(([k, v]) => [k, +v.toFixed(4)])),
  magic: { constant: '0x5f3759df', seedBits: +MAGIC_SEED_BITS.toFixed(4), afterOneRound: +MAGIC_R1_BITS.toFixed(4), maxRelErrPct: +(MAGIC_MAXERR * 100).toFixed(4) },
  ladderTo24Bits: LADDER.map(({ r, k, entries, seedBitsNeeded }) => ({ rounds: r, k, entries, seedBitsNeeded: +seedBitsNeeded.toFixed(3) })),
  newtonShortfallBits: +Math.log2(1.5).toFixed(6),
  pass, fail,
};
if (process.argv.includes('--json')) console.log(JSON.stringify(summary, null, 2));
process.exit(fail ? 1 : 0);
