// verify.mjs: the check for "Every Plus-or-Minus Is a Decision".
//
//   node research/every-plus-or-minus/verify.mjs
//
// Order of business, and the reason for it:
//   1. Recompute every statistic from the raw member data with arithmetic written here,
//      importing none of the layer's own engine. If the two agree the engine is not
//      merely self-consistent.
//   2. Re-run the data assembly and require the committed data.mjs to come back
//      byte-identical, and the page's engine copies to be byte-identical to the lab's.
//   3. Check the page's shipped bytes against the numbers, including its own check count.
//   4. Mutate, and require the checks to turn red.

import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, '../..');
const R = p => fs.readFileSync(path.join(ROOT, p), 'utf8');

let pass = 0, fail = 0;
const problems = [];
function ok(cond, label) {
  if (cond) { pass++; } else { fail++; problems.push(label); console.log('  FAIL  ' + label); }
}
function near(a, b, tol, label) { ok(Number.isFinite(a) && Math.abs(a - b) <= tol, label + ' (got ' + a + ', want ' + b + ' ±' + tol + ')'); }

// ─────────────────────────────────────────────────────────────────────────────
// 0. Independent arithmetic. Nothing below imports decide.mjs.
// ─────────────────────────────────────────────────────────────────────────────

function ownWeighted(pts) {
  const w = pts.map(p => 1 / p.sigma ** 2);
  const sw = w.reduce((a, b) => a + b, 0);
  const mean = pts.reduce((s, p, i) => s + w[i] * p.value, 0) / sw;
  const chi2 = pts.reduce((s, p) => s + ((p.value - mean) / p.sigma) ** 2, 0);
  return { n: pts.length, mean, chi2, internal: Math.sqrt(1 / sw),
    birge: pts.length > 1 ? Math.sqrt(chi2 / (pts.length - 1)) : null };
}

// The inverse standard normal CDF by bisection on an independently written erf, so the
// probable-error factor is derived here and not copied from either the engine or a table.
function ownErf(x) {
  // Maclaurin series, which converges quickly for the |x| < 1 we need.
  let term = x, sum = x;
  for (let n = 1; n < 200; n++) {
    term *= -x * x / n;
    sum += term / (2 * n + 1);
  }
  return 2 / Math.sqrt(Math.PI) * sum;
}
function ownPhi(z) { return 0.5 * (1 + ownErf(z / Math.SQRT2)); }
function ownProbit(p) {
  let lo = 0, hi = 3;
  for (let i = 0; i < 200; i++) { const m = (lo + hi) / 2; if (ownPhi(m) < p) lo = m; else hi = m; }
  return (lo + hi) / 2;
}

console.log('\n§0  independent arithmetic');
const ownPE = ownProbit(0.75);
near(ownPE, 0.6744897501960817, 1e-12, 'the probable-error factor is z(0.75), derived by bisection on a series erf');
near(ownPhi(0), 0.5, 1e-12, 'the independent normal CDF is 0.5 at zero');
near(2 * (1 - ownPhi(2.33)) * 100, 1.9806, 2e-3, 'the two-sided normal tail at 2.33 sigma is about 1.98 percent');

// ─────────────────────────────────────────────────────────────────────────────
// 1. The data is assembled, not transcribed.
// ─────────────────────────────────────────────────────────────────────────────

console.log('\n§1  the data is assembled from the members, and cannot drift');
const { assemble, render } = await import('./build-data.mjs');
const fresh = render(await assemble());
const committed = R('research/every-plus-or-minus/data.mjs');
ok(fresh === committed, 'data.mjs is byte-identical to a fresh assembly from the members\' own files');

for (const mod of ['decide.mjs', 'data.mjs', 'findings.mjs']) {
  ok(R('research/every-plus-or-minus/' + mod) === R('public/strata/every-plus-or-minus/engine/' + mod),
    'the page\'s copy of ' + mod + ' is byte-identical to the lab\'s');
}

// The build script quotes the five NIST lines it used. Re-parse them out of that comment
// block and require the parsed numbers to be the ones the module actually exports.
// The quoted lines carry a mantissa with NIST's digit grouping and a separate power of
// ten. Compare mantissas: the powers of ten are the unit bridges, checked on their own
// below, and mixing the two would let an error in one hide an error in the other.
const build = R('research/every-plus-or-minus/build-data.mjs');
const quoted = {};
for (const m of build.matchAll(/^\/\/ {3}([A-Za-z][A-Za-z -]*?) {2,}([\d][\d ]*\.[\d ]*?)(?: (e-?\d+))? {2,}/gm)) {
  quoted[m[1].trim()] = { mantissa: Number(m[2].replace(/ /g, '')), exponent: m[3] || null };
}
ok(Object.keys(quoted).length === 5,
  'five NIST lines are quoted verbatim in the build script (found ' + Object.keys(quoted).length +
  ': ' + Object.keys(quoted).join(', ') + ')');
const { MODERN_REFERENCE, BRIDGES, DATASETS } = await import('./data.mjs');
const mant = (name, exp) => { ok(quoted[name] && quoted[name].exponent === exp,
  'the quoted ' + name + ' line carries the power of ten ' + exp); return quoted[name] ? quoted[name].mantissa : NaN; };
near(mant('Avogadro constant', 'e23'), MODERN_REFERENCE.avogadroConstant.value, 1e-12,
  'the quoted Avogadro mantissa is the value used');
near(mant('inverse fine-structure constant', null), MODERN_REFERENCE.alphaInverse.value, 1e-12,
  'the quoted fine-structure line is the value used, no bridge needed');
near(mant('Planck constant', 'e-34'), MODERN_REFERENCE.planckConstant.value, 1e-12,
  'the quoted Planck mantissa is the value used, since 1 J = 1e7 erg moves only the exponent');
near(mant('electron mass', 'e-31'), MODERN_REFERENCE.electronMass.value, 1e-12,
  'the quoted electron-mass mantissa is the value used, since 1 kg = 1e3 g moves only the exponent');
near(mant('elementary charge', 'e-19') * BRIDGES.statcoulombPerCoulomb * 1e-9,
  MODERN_REFERENCE.elementaryCharge.value, 1e-12,
  'the quoted charge mantissa becomes the value used through the exact statcoulomb bridge');

// The bridges themselves, derived rather than asserted.
near(BRIDGES.statcoulombPerCoulomb, 10 * 299792458, 0, 'the statcoulomb bridge is exactly ten times the numeric speed of light');
near(MODERN_REFERENCE.elementaryCharge.value, 4.803204712570263, 1e-14, 'e in 1e-10 esu, computed from two exact numbers');
near(MODERN_REFERENCE.elementaryCharge.value, 4.80320471, 5e-9,
  'that agrees with the independent value the-charge-that-crept carries to every digit it prints');

// ─────────────────────────────────────────────────────────────────────────────
// 2. The opening row.
// ─────────────────────────────────────────────────────────────────────────────

console.log('\n§2  one row, two documents');
const F = await import('./findings.mjs');
const anchorRow = DATASETS.anchor.rows.find(r => r.review === '1963' && r.quantity === 'elementaryCharge');
ok(anchorRow.value === 4.80298 && anchorRow.uncertainty === 6e-5,
  'error-bar-coverage still ships the 1963 charge row as 4.80298 ± 0.00006');
const creptRow = DATASETS.charge.rows.find(r => r.year === 1963);
ok(creptRow.value === 4.80298 && creptRow.uncertainty === 0.00020 && creptRow.errType === '3sd',
  'the-charge-that-crept still ships it as 4.80298 ± 0.00020, tagged 3sd');
const modernE = MODERN_REFERENCE.elementaryCharge.value;
const zA = (4.80298 - modernE) / 6e-5, zB = (4.80298 - modernE) / 0.00020, zC = (4.80298 - modernE) / (0.00020 / 3);
near(zA, -3.7449, 1e-3, 'read as the review prints it, the 1963 row is 3.74 sigma from the exact value');
near(zB, -1.1235, 1e-3, 'read as the card prints it and taken at face value, it is 1.12 sigma');
near(zC, -3.3704, 1e-3, 'read as the card prints it and divided by three, it is 3.37 sigma');
ok(Math.abs(zA) > 3 && Math.abs(zB) < 2, 'the two readings land on opposite sides of any usual verdict boundary');
// the reconciliation
near(F.RECONCILIATION.sigma, 12e-6 * 4.80298, 1e-12, 'the 1963 adjustment\'s own sigma is 12 ppm of the value');
ok(F.RECONCILIATION.sigmaRoundsToShipped, 'that sigma rounds to the 0.00006 error-bar-coverage ships');
ok(F.RECONCILIATION.threeSigmaRoundsToLimit, 'three of those sigmas round to the 0.00020 the card prints');
near(F.RECONCILIATION.limitOverSigma, 3.4703, 1e-3, 'against the adjustment\'s printed 12 ppm the card\'s limit is 3.47 sigma; the page does not claim this multiple is exact');
near(0.00020 / 0.00006, 3.3333, 1e-3, 'and against the 0.00006 the anchor layer ships it is 3.33, which is why the page says about three and a half rather than a number');

// ─────────────────────────────────────────────────────────────────────────────
// 3. The reference put through its own test.
// ─────────────────────────────────────────────────────────────────────────────

console.log('\n§3  the reference is also a measurement');
const expectedZ = { alphaInverse: 0.371, elementaryCharge: 2.663, planckConstant: 2.940,
  electronMass: 3.198, avogadroConstant: -3.089 };
let surprises = 0;
const seen = new Set();
for (const r of DATASETS.anchor.rows) {
  if (seen.has(r.quantity)) continue;
  seen.add(r.quantity);
  const z = (r.target1973 - r.targetModern) / r.target1973Sigma;
  near(z, expectedZ[r.quantity], 5e-3, 'the 1973 ' + r.symbol + ' sits ' + expectedZ[r.quantity] + ' of its own sigma from today\'s value');
  if (Math.abs(z) > 2.33) surprises++;
}
ok(surprises === 4, 'four of the five 1973 reference values fail the 2.33 sigma test they are the reference for');
ok(F.REFERENCE_RECURSION.surprises === surprises, 'the layer reports the same count');
near(Math.sqrt(14.50 / 21), 0.83, 5e-3, 'the Birge ratio printed in the caption of Table 33.1 follows from its own chi-squared');
ok(F.SELF_DIAGNOSTIC.belowUnity, 'that Birge ratio is below unity, the best verdict the diagnostic can return');

// ─────────────────────────────────────────────────────────────────────────────
// 4. The cube, recomputed here from the raw rows.
// ─────────────────────────────────────────────────────────────────────────────

console.log('\n§4  the anchor cube');
const C2P = 1.000275, P2U = 16 / 15.9949146196;
near(P2U, 1.000318, 1e-6, 'the physical-to-unified mass-scale factor follows from the mass of oxygen-16');
function ownRun(rule) {
  const zs = [];
  for (const r of DATASETS.anchor.rows) {
    if (rule.include === 'only the reviews both layers could verify' && r.review === '1941') continue;
    let u = r.uncertainty;
    if (rule.convention === 'probable errors converted' && r.errType === 'pe') u = u / ownPE;
    if (r.review === '1963' && r.quantity === 'elementaryCharge') {
      if (rule.charge1963 === 'the 1963 sheet') u = 0.00020;
      else if (rule.charge1963 === 'the sheet divided by three') u = 0.00020 / 3;
    }
    let v = r.value;
    if (rule.massScale === 'brought to the unified scale' && r.massScale) {
      v = r.massScale === 'chemical' ? v * C2P / P2U : r.massScale === 'physical' ? v / P2U : v;
    }
    const t = rule.reference === 'the modern value' ? r.targetModern : r.target1973;
    zs.push((v - t) / u);
  }
  const k = zs.filter(z => Math.abs(z) > rule.threshold).length;
  return { n: zs.length, k, percent: 100 * k / zs.length };
}
// the rule the member layer actually ships
const shipped = { convention: 'as printed', charge1963: 'the 1965 review', massScale: 'as printed',
  include: 'all eight reviews', reference: 'the 1973 recommendation', threshold: 2.33 };
const base = ownRun(shipped);
ok(base.k === 23 && base.n === 40, 'the naive rule reproduces error-bar-coverage\'s own 23 of 40');
near(base.percent, 57.5, 1e-9, 'which is 57.5 percent, within a point of the published 57');
// the member's README states three one-at-a-time sensitivities; each is re-derived here
ok(ownRun({ ...shipped, massScale: 'brought to the unified scale' }).k === 22,
  'the README\'s mass-scale sensitivity reproduces: 22 of 40');
ok(ownRun({ ...shipped, convention: 'probable errors converted' }).k === 21,
  'the README\'s probable-error sensitivity reproduces: 21 of 40');
// the full grid, crossed
let lo = Infinity, hi = -Infinity, worstRatio = Infinity, count = 0, repro = 0, reproAt = 0, atThr = 0;
const axes = F.ANCHOR_AXES, names = Object.keys(axes);
(function rec(i, acc) {
  if (i === names.length) {
    const run = ownRun(acc);
    const cal = 2 * (1 - ownPhi(acc.threshold)) * 100;
    lo = Math.min(lo, run.percent); hi = Math.max(hi, run.percent);
    worstRatio = Math.min(worstRatio, run.percent / cal);
    count++;
    if (Math.abs(run.percent - 57) <= 1) repro++;
    if (acc.threshold === 2.33) { atThr++; if (Math.abs(run.percent - 57) <= 1) reproAt++; }
    return;
  }
  for (const level of axes[names[i]]) rec(i + 1, { ...acc, [names[i]]: level });
})(0, {});
ok(count === 144, 'the grid is 144 rules (got ' + count + ')');
near(lo, 42.5, 1e-9, 'the lowest surprise rate on the grid is 42.5 percent');
near(hi, 80.0, 1e-9, 'the highest is 80.0 percent');
ok(reproAt === 8 && atThr === 48, 'at the published threshold, 8 of 48 rules land within a point of 57 percent');
ok(worstRatio >= 11.5, 'every rule exceeds its own calibrated expectation by at least 11.5 times');
ok(lo > 0 && worstRatio > 1, 'no rule on the grid returns a rate at or below what a calibrated set would give');
// agreement with the layer's own engine
near(F.ANCHOR_CUBE.range.min, lo, 1e-9, 'the layer agrees with this independent recomputation on the minimum');
near(F.ANCHOR_CUBE.range.max, hi, 1e-9, 'and on the maximum');
ok(F.ANCHOR_CUBE.atPublishedThreshold.reproducing === reproAt, 'and on the reproducing count');
near(F.ANCHOR_CUBE.minRatio, worstRatio, 1e-4, 'and on the smallest ratio to the calibrated expectation, two independent normal tails agreeing to four decimals');
// the ordering of the main effects, which the page states in words
const eff = F.ANCHOR_CUBE.effects;
ok(eff[0].axis === 'threshold', 'the threshold is the largest single lever');
ok(eff[1].axis === 'include', 'which rows are admitted is the largest substantive one');
ok(eff.findIndex(e => e.axis === 'include') < eff.findIndex(e => e.axis === 'convention'),
  'inclusion outranks the error convention, as the page says');
ok(eff.findIndex(e => e.axis === 'convention') < eff.findIndex(e => e.axis === 'reference'),
  'and the error convention outranks the choice of reference');

// The anchor paper's own claim about the 1963 to 1969 shift, checked from the same rows.
console.log('\n§4b the anchor paper\'s other claim, tested');
let allInBand = true;
for (const q of ['alphaInverse', 'elementaryCharge', 'planckConstant', 'electronMass', 'avogadroConstant']) {
  const a = DATASETS.anchor.rows.find(r => r.review === '1963' && r.quantity === q);
  const b = DATASETS.anchor.rows.find(r => r.review === '1969' && r.quantity === q);
  const n = Math.abs(b.value - a.value) / a.uncertainty;
  if (!(n >= 3 && n <= 5)) allInBand = false;
}
ok(allInBand, 'Henrion and Fischhoff\'s "three to five 1963 standard deviations" for all five constants reproduces');

// The 1952 convention disagreement inside the member layer, and its (nil) effect.
console.log('\n§4c the 1952 convention, recorded twice');
const py = R('research/error-bar-coverage/anchor_reproduction.py');
ok(/Datum\(1952, "e_esu", 4\.80288, 0\.00021, "pe"\)/.test(py),
  'anchor_reproduction.py still tags the 1952 rows as probable errors');
const json = JSON.parse(R('research/error-bar-coverage/data/anchor-rows.json'));
ok(json.reviews[4].key === '1952' && json.reviews[4].errorMeasure === 'standard error',
  'anchor-rows.json still records the 1952 review as standard error');
function countWith1952AsPE(as1952PE) {
  let k = 0;
  for (const r of DATASETS.anchor.rows) {
    let u = r.uncertainty;
    if (r.errType === 'pe' || (as1952PE && r.review === '1952')) u = u / ownPE;
    if (Math.abs((r.value - r.target1973) / u) > 2.33) k++;
  }
  return k;
}
ok(countWith1952AsPE(false) === 21 && countWith1952AsPE(true) === 21,
  'the two labellings give the same count under conversion, so this disagreement moves nothing this layer reports');

// ─────────────────────────────────────────────────────────────────────────────
// 5. The half-life census.
// ─────────────────────────────────────────────────────────────────────────────

console.log('\n§5  the half-life census');
const gold = DATASETS.halflife.entries.find(e => e.slug === '196Au');
const gw = ownWeighted(gold.inputs);
near(gw.birge, 10.86, 5e-3, 'gold-196\'s Birge ratio reproduces the 10.86 the evaluation prints');
near(gw.mean, 6.163131, 1e-6, 'and its weighted mean');
ok(DATASETS.halflife.entries.length === 45, 'the census contributes 45 entries with two or more measurements');
ok(DATASETS.halflife.entries.reduce((s, e) => s + e.inputs.length, 0) === 140, 'carrying 140 measurements in all');
// the PDG rule, written out here rather than imported
const ceiling = 3 * Math.sqrt(gw.n) * gw.internal;
const kept = gold.inputs.filter(p => p.sigma <= ceiling);
ok(kept.length === 2, 'PDG\'s own ceiling of three root-N times the error of the mean excludes one of the three');
const S = Math.sqrt(kept.reduce((s, p) => s + ((p.value - gw.mean) / p.sigma) ** 2, 0) / (kept.length - 1));
near(S, F.HALFLIFE.gold.pdg.S, 1e-9, 'the PDG scale factor reproduces independently');
ok(S > gw.birge, 'and it is larger than the evaluation\'s own ratio on the same three numbers');
ok(F.HALFLIFE.driftOverOne === 40, '40 of the 45 entries travel further across the rule grid than the internal sigma of their own weighted mean');
ok(F.HALFLIFE.thresholds.disagree.length === 0,
  'the NUBASE and CODATA inconsistency thresholds disagree on none of the 45, a null the page states');
ok(F.HALFLIFE.zeroSigmaEntries === 1, 'exactly one entry has a rule that returns an uncertainty of zero');

// ─────────────────────────────────────────────────────────────────────────────
// 6. The two-number cases, and the two members with no sigma.
// ─────────────────────────────────────────────────────────────────────────────

console.log('\n§6  the two-number cases, and the boundary');
const muonHtml = R('public/strata/the-gap-that-changed-sides/index.html');
ok(/wp20:\s*\{\s*value:116591810,\s*sigma:43/.test(muonHtml), 'the muon layer still ships the 2020 reference as 116591810 ± 43');
ok(/ti25:\s*\{\s*value:116592033,\s*sigma:62/.test(muonHtml), 'and the 2025 lattice as 116592033 ± 62');
const mb = F.MUON.byTheory;
ok(mb.find(t => t.theory === 'wp20').stability.verdicts.every(v => v.name === 'discrepant'),
  'against the 2020 reference every cell is discrepant');
ok(mb.find(t => t.theory === 'ti25').stability.verdicts.every(v => v.name === 'consistent'),
  'against the 2025 lattice every cell is consistent');
ok(F.HUBBLE.stability.verdicts.length === 3, 'the Hubble grid returns all three verdicts');
// the boundary layers are named, and are NOT run through anything
ok(!/the-room-inside-a-number/.test(R('research/every-plus-or-minus/build-data.mjs')) ||
   !Object.keys(DATASETS).includes('room'),
  'the-room-inside-a-number is not assembled as a dataset, because it has no sigma to assemble');
ok(!Object.keys(DATASETS).includes('answer'),
  'the-answer-that-cant-be-wrong is not assembled as a dataset either');
ok(Object.keys(DATASETS).length === 5, 'exactly five of the seven members carry data this instrument can eat');

// ─────────────────────────────────────────────────────────────────────────────
// 7. The page's shipped bytes.
// ─────────────────────────────────────────────────────────────────────────────

console.log('\n§7  the page says what the numbers say');
const html = R('public/strata/every-plus-or-minus/index.html');
ok(html.includes('Based on 3 std. dev., applies to last digits in preceding col.'),
  'the page quotes the 1963 card\'s footnote verbatim');
ok(html.includes('it would be prudent to multiply the above uncertainties by 3'),
  'and the 1971 card\'s footnote verbatim');
ok(html.includes('R<sub>B</sub> = 0.83'), 'and the Birge ratio from the caption of Table 33.1');
ok(html.includes('Wherever applicable, we shall quote the larger uncertainty'),
  'and the 1973 paper\'s stated policy on which uncertainty to print');
ok(/Cohen and Taylor, J\. Phys\. Chem\. Ref\. Data 2, 663 \(1973\)/.test(html), 'attributing them to the right paper');
ok(html.includes('<canvas'), 'the page ships the grid as a canvas rather than a picture of one');
ok(!/cdn|googleapis|unpkg|jsdelivr|fonts\.google/i.test(html), 'no third-party host is contacted');
ok(/role="status"/.test(html) && /aria-live/.test(html), 'the live readout announces itself');
ok(/prefers-reduced-motion/.test(html), 'reduced motion is respected');
ok(/:focus-visible/.test(html), 'focus is visible');
ok(/class="aw-wayout"/.test(html), 'the way-out footer is present');
// The page must not claim a join a member's own card already publishes.
ok(!/we are the first to connect|nobody has noticed|no one has linked/i.test(html),
  'the page claims no priority it did not check');
ok(html.includes('The Anatomy of Error'), 'the one portal hit found by the sweep is disclosed on the page');
ok(html.includes('What the Average Throws Away'), 'and the nearest adjacency is credited');

// the em-dash rule, on this layer's own new prose
const bodyOnly = html.replace(/<blockquote[\s\S]*?<\/blockquote>/g, '');
ok(!bodyOnly.includes('—'), 'no em dash in this layer\'s own prose');

// ─────────────────────────────────────────────────────────────────────────────
// 8. Mutations: the checks must be able to go red.
// ─────────────────────────────────────────────────────────────────────────────

console.log('\n§8  mutations');
let caught = 0;
function mutation(label, fn) {
  let red = false;
  try { red = fn() === false; } catch { red = true; }
  if (red) { caught++; console.log('  caught: ' + label); }
  else { fail++; problems.push('MUTATION NOT CAUGHT: ' + label); console.log('  MISSED: ' + label); }
}
mutation('the 1963 row read as one sigma is no longer consistent', () => {
  const z = (4.80298 - modernE) / 0.00020;
  return Math.abs(z) > 2;              // the real value is 1.12, so this is false
});
mutation('a wrong statcoulomb bridge changes e in esu', () => {
  const bad = 1.602176634e-19 * 299792458 * 1e10;
  return Math.abs(bad - 4.803204712570263) < 1e-9;
});
mutation('the mass-scale factors applied in the same direction stop reproducing the README', () => {
  let k = 0;
  for (const r of DATASETS.anchor.rows) {
    let v = r.value;
    if (r.massScale === 'chemical') v = v * C2P * P2U;
    else if (r.massScale === 'physical') v = v * P2U;
    if (Math.abs((v - r.target1973) / r.uncertainty) > 2.33) k++;
  }
  return k === 22;
});
mutation('dropping the probable-error conversion changes the converted count', () => {
  let k = 0;
  for (const r of DATASETS.anchor.rows) {
    if (Math.abs((r.value - r.target1973) / r.uncertainty) > 2.33) k++;
  }
  return k === 21;
});
mutation('the 1973 reference passes its own test', () => {
  let s = 0;
  const seen2 = new Set();
  for (const r of DATASETS.anchor.rows) {
    if (seen2.has(r.quantity)) continue;
    seen2.add(r.quantity);
    if (Math.abs((r.target1973 - r.targetModern) / r.target1973Sigma) > 2.33) s++;
  }
  return s === 0;
});
mutation('gold-196 agrees with itself', () => ownWeighted(gold.inputs).birge < 2.5);
mutation('the grid is smaller than it is', () => {
  let n = 1;
  for (const a of Object.keys(F.ANCHOR_AXES)) n *= F.ANCHOR_AXES[a].length;
  return n === 72;
});

// ─────────────────────────────────────────────────────────────────────────────
// 8b. The claims the page prints that nothing above was testing.
//
// An adversarial pass found this section missing and proved it: changing
// MEDIAN_SE_FACTOR in decide.mjs, and falsifying four numbers directly in the HTML,
// both left the verifier green. Everything below exists because of that.
// ─────────────────────────────────────────────────────────────────────────────

console.log('\n§8b the numbers the page prints');

// the opening table
ok(F.TWO_DOCUMENTS.readings.length === 3, 'the opening table has three readings');
ok(F.TWO_DOCUMENTS.verdictsSeen.includes('discrepant') && F.TWO_DOCUMENTS.verdictsSeen.includes('consistent'),
  'and they do not all land on the same verdict');
near(F.TWO_DOCUMENTS.readings[0].z, zA, 1e-9, 'its first row is the review reading recomputed above');
near(F.TWO_DOCUMENTS.readings[1].z, zC, 1e-9, 'its second row divides the card limit by three');
near(F.TWO_DOCUMENTS.readings[2].z, zB, 1e-9, 'its third row takes the card limit at face value');

// the charge series
ok(F.CHARGE.n === 23 && F.CHARGE.convertible === 14 && F.CHARGE.unconvertible === 9,
  'the charge series is 23 rows, 14 with a convertible convention and 9 without');
ok(F.CHARGE.asPrinted.misses === 10 && F.CHARGE.converted.misses === 11,
  'ten rows miss by more than 2.33 as printed, eleven when the conventions are honoured');
ok(F.CHARGE.moved.length === 1 && F.CHARGE.moved[0].year === 1963,
  'exactly one row crosses the line, and it is 1963');
ok(F.CHARGE.everyReviewTo1963BelowModern,
  'every recommendation to 1963 sits below the exact value, the invariance the page claims');

// the half-life spreads, and the estimator constant an adversary was able to change silently
const goldRules = F.HALFLIFE.rules.length;
ok(goldRules === 54, 'the half-life grid is 54 settings');
near(F.HALFLIFE.gold.sigmaSpread.max / F.HALFLIFE.gold.sigmaSpread.min, 31.75, 0.05,
  'gold-196\'s printed uncertainty spans a factor of 31.8 across them');
near(F.HALFLIFE.driftMedian, 3.83, 0.01, 'the median entry travels 3.83 of its own sigma');
near(F.HALFLIFE.driftMax, 17.52, 0.01, 'and the worst travels 17.5');
ok(F.HALFLIFE.driftOverOne === 40, 'forty of the 45 travel further than the internal sigma of their own weighted mean');
// the median estimator's efficiency factor, which nothing was pinning
const D = await import('./decide.mjs');
near(D.MEDIAN_SE_FACTOR, Math.sqrt(Math.PI / 2), 1e-12,
  'the median estimator carries the sqrt(pi/2) efficiency factor the halflife layer omits');
// no two of the three gold-196 measurements overlap: the invariance the page now claims
const gi = F.HALFLIFE.gold.inputs;
let disjoint = true;
for (let i = 0; i < gi.length; i++) for (let j = i + 1; j < gi.length; j++) {
  if (Math.abs(gi[i].value - gi[j].value) <= gi[i].sigma + gi[j].sigma) disjoint = false;
}
ok(disjoint, 'no two of gold-196\'s three measurements overlap within their own quoted errors');

// the summary table, which drives five rows of prose
ok(F.SUMMARY.length === 5, 'the summary table has one row per dataset that carries a sigma');
ok(F.SUMMARY.every(r => r.moves && r.holds && r.movesDetail && r.holdsDetail),
  'and every row states both what moves and what holds');

// the mass-scale conversion carries the uncertainty with the value, and it changes nothing
const scaledCount = ownRun({ ...shipped, massScale: 'brought to the unified scale' }).k;
ok(scaledCount === 22, 'the mass-scale count is 22 whether or not the uncertainty rides the factor');

console.log('\n§8c the literals in the page\'s own prose');
const lit = (needle, why) => ok(html.includes(needle), why);
lit('2,842', 'the page states the Ames II comparison count');
ok(/0\.70%, 2\.04%, 0\.70% and 66\.19%/.test(html), 'and the four forensic rates in the published order');
lit('59 portal layers that existed before this one', 'the page states the portal count the sweep covered, and that it excludes itself');
lit('125 files', 'and the file count');
lit('<span class="num">57%</span>', 'and the published surprise rate it is testing');
lit('They never printed the rows.', 'and that the anchor paper never printed the forty rows');
// gate those against the sources rather than against the page itself
const studies = R('public/strata/the-answer-that-cant-be-wrong/studies.js');
ok(/1076/.test(studies) && /961/.test(studies),
  'the forensic layer still ships the counts those rates are computed from');
// This block used to assert `portalSlugs.length === 60`, described as "the 59 that
// were swept plus this one". It was true on 2026-08-09 and false by 2026-08-21,
// when there were 65, and it had failed for every reader of the sweep in between.
// Nothing about the page was wrong: the assertion was, because it pinned a live
// count of a growing archive to a constant. The page's own sentence is careful and
// dated by construction ("59 portal layers that existed BEFORE this one"), so the
// check now tests exactly that sentence and nothing else, by counting the portals
// whose frontmatter date precedes this page's. That number can never change again,
// because the past does not grow. Today's total is printed as context, not asserted.
const strataDir = path.join(ROOT, 'src/content/strata');
const frontmatterDate = (f) => (R('src/content/strata/' + f).match(/^date:\s*(\S+)/m) || [])[1] || '';
const portalSlugs = fs.readdirSync(strataDir)
  .filter(f => f.endsWith('.md'))
  .filter(f => /^tags:.*\bportal\b/m.test(R('src/content/strata/' + f)));
const SELF = 'every-plus-or-minus.md';
const selfDate = frontmatterDate(SELF);
ok(portalSlugs.includes(SELF), 'this layer is itself tagged a portal, so it is one of the ones it counts');
const portalsBefore = portalSlugs.filter(f => f !== SELF && frontmatterDate(f) < selfDate);
ok(portalsBefore.length === 59,
  'and 59 portal layers are dated before this one (' + selfDate + '), which is the sentence the page prints'
  + ' · found ' + portalsBefore.length + ' before, ' + portalSlugs.length + ' in total today');
ok(html.includes('59 portal layers that existed before this one'),
  'the page says 59 that existed before this one, not 59 today, because this page is now the sixtieth');
ok(String(DATASETS.anchor.published.surprisePercent) === '57',
  'and the anchor layer really does record the published rate as 57');

console.log('\n§8d the correlation, and what it will not support');
const CO = F.CORRELATION;
ok(CO.strongPairs.length === 6, 'six of the ten published correlation pairs exceed 0.9 in magnitude');
near(CO.R[1][4], -0.997, 1e-9, 'including N_A against m_e at -0.997');
near(CO.R[2][3], 0.991, 1e-9, 'and e against h at 0.991');
ok(CO.alphaMaxCorrelation < 0.5, 'the one constant that passes is the one whose largest correlation is below 0.5');
ok(CO.effDim > 1 && CO.effDim < 2, 'the five carry between one and two independent quantities (' + CO.effDim.toFixed(2) + ')');
ok(CO.condition > 1e5, 'the matrix condition number exceeds 1e5');
ok(CO.signsAgree, 'the deviation signs are the pattern a single shared shift would produce');
// Count the valid corners here with a Cholesky factorisation written for this check, not
// the engine's eigenvalues, and require the engine to keep exactly those. This assertion
// used to be probeCorners < 1024, which passed while the engine kept 988 corners when only
// 187 are positive definite (found by the assay line, 2026-10-18).
const ownPD = M => {
  const n = M.length, L = M.map(() => new Array(n).fill(0));
  for (let i = 0; i < n; i++) for (let j = 0; j <= i; j++) {
    let s = M[i][j];
    for (let k = 0; k < j; k++) s -= L[i][k] * L[j][k];
    if (i === j) { if (!(s > 0)) return false; L[i][i] = Math.sqrt(s); }
    else L[i][j] = s / L[j][j];
  }
  return true;
};
let ownValid = 0;
const pairs = [];
for (let i = 0; i < 5; i++) for (let j = i + 1; j < 5; j++) pairs.push([i, j]);
for (let mask = 0; mask < 1024; mask++) {
  const M = CO.R.map(r => [...r]);
  pairs.forEach(([i, j], b) => {
    const v = Math.max(-0.9999, Math.min(0.9999, CO.R[i][j] + ((mask >> b) & 1 ? 1 : -1) * 0.0005));
    M[i][j] = M[j][i] = v;
  });
  if (ownPD(M)) ownValid++;
}
ok(ownValid === 187 && CO.probeCorners === ownValid,
  'only ' + ownValid + ' of the 1024 corners of the printed precision are a valid correlation matrix, and the engine keeps exactly those (it keeps ' + CO.probeCorners + ')');
ok(CO.probeRatio > 100, 'the joint statistic moves by more than a factor of 100 within the last printed digit');
ok(CO.computable === false, 'so this layer does not publish a joint significance, and says why');
ok(!/joint (significance|sigma) of \d/.test(html), 'and the page prints no joint sigma');
ok(html.includes('one failure, counted four times'), 'the page states the correction rather than the first draft');
// The count is stated in prose now, so gate the words against the computed number.
const words5 = ['None', 'One', 'Two', 'Three', 'Four', 'Five'];
ok(html.includes(words5[F.REFERENCE_RECURSION.surprises] + ' of the five are more than 2.33'),
  'the page writes the surprise count in words, and the words match the computed count');
ok(CO.effDim < F.REFERENCE_RECURSION.surprises,
  'and the effective number of independent quantities is smaller than that count, which is the whole correction');

// ─────────────────────────────────────────────────────────────────────────────
// 9. The second implementation, in a second language.
// ─────────────────────────────────────────────────────────────────────────────

console.log('\n§9  the python cross-check');
import { execFileSync } from 'node:child_process';
let pyOut = '';
try {
  pyOut = execFileSync('python3', [path.join(ROOT, 'research/every-plus-or-minus/cross-check.py')],
    { cwd: ROOT, encoding: 'utf8' });
} catch (e) { pyOut = String(e.stdout || '') + String(e.stderr || ''); }
ok(/the second implementation agrees with the first on every number/.test(pyOut),
  'cross-check.py, which reads only the raw member data and uses python\'s own erf, agrees on every number');
ok(!/FAIL/.test(pyOut), 'and reports no disagreements');

// ─────────────────────────────────────────────────────────────────────────────
// 10. The printed check count.
// ─────────────────────────────────────────────────────────────────────────────

const total = pass;
console.log('\n' + '─'.repeat(60));
console.log('ASSERTIONS ' + pass + '   FAILURES ' + fail + '   MUTATIONS CAUGHT ' + caught + '/7');
if (problems.length) { console.log('\nproblems:'); problems.forEach(p => console.log('  - ' + p)); }

// The page prints its own check count. Gate it against this run's tally, so the sentence
// cannot drift from the thing it describes.
const claimed = html.match(/Offline: (\d+) checks/);
if (!claimed) { console.log('\nthe page does not print a check count'); process.exitCode = 1; }
else if (Number(claimed[1]) !== total) {
  console.log('\nthe page says "Offline: ' + claimed[1] + ' checks" and this run made ' + total + '.');
  console.log('Update public/strata/every-plus-or-minus/index.html to say ' + total + '.');
  process.exitCode = 1;
} else {
  console.log('the page\'s printed count of ' + total + ' checks matches this run.');
}
if (fail > 0) process.exitCode = 1;
