#!/usr/bin/env node
// verify-the-anomaly-outlived-its-planet.mjs: recomputes every number the page shows from the three frozen
// files, checks the shipped page, head tags, JSON-LD, frontmatter and record.json against the recomputation,
// and exits non-zero on any disagreement.
//
//   node research/the-anomaly-outlived-its-planet/verify-the-anomaly-outlived-its-planet.mjs            # every assertion
//   node research/the-anomaly-outlived-its-planet/verify-the-anomaly-outlived-its-planet.mjs --ledger   # the nine ledger cells
//   node research/the-anomaly-outlived-its-planet/verify-the-anomaly-outlived-its-planet.mjs --regen    # rewrite record.json and
//        the literal inventory, only if every other assertion passes. It never rewrites a data file or a pin.
//
// Two kinds of check are kept apart. The page's own functions are run on the frozen records and on doctored
// copies of them. And the central results are recomputed a second time here by independent code that shares
// nothing with engine.js (its own Cauchy elimination, a Cholesky least squares, a series for the Laplace
// coefficient), so an error in the engine cannot be confirmed by the engine.

import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import assert from 'node:assert/strict';
import { fileURLToPath } from 'node:url';
import * as E from '../../public/strata/the-anomaly-outlived-its-planet/engine.js';
import { figures, nullFigures, NULL_DRAWS, NULL_SEED, SIG_MARKS, num, sgn } from '../../public/strata/the-anomaly-outlived-its-planet/figures.js';
import { VERDICT, NOVELTY, CHOICES, ANCHOR_TOL, CONTROL_TOL } from '../../public/strata/the-anomaly-outlived-its-planet/readings.js';
import { FILES, SHA256 } from '../../public/strata/the-anomaly-outlived-its-planet/data.js';
import * as S from './surface.mjs';
import { fillHtml, mdText } from './fill.mjs';

// The site's chrome writers inject marked blocks and a banner script at landing; this verifier checks the
// page's OWN content, so it reads the page with exactly those blocks removed.
const stripChrome = (s) => s.replace(/\s*<!--aw-([a-z-]+):start-->[\s\S]*?<!--aw-\1:end-->/g, '')
  .replace(/\s*<script src="\/media\/home-banner\.js"[^>]*><\/script>/g, '');

const here = path.dirname(fileURLToPath(import.meta.url));
const root = path.resolve(here, '../..');
const dir = path.join(root, 'public/strata', S.SLUG);
const mdPath = path.join(root, 'src/content/strata', S.SLUG + '.md');
const read = (f) => fs.readFileSync(path.join(dir, f), 'utf8');
const html = stripChrome(read('index.html'));
const md = fs.readFileSync(mdPath, 'utf8');
const LV = JSON.parse(read(FILES.claimant));
const NC = JSON.parse(read(FILES.control));
const REF = JSON.parse(read(FILES.reference));
const readme = fs.readFileSync(path.join(here, 'README.md'), 'utf8');
const notice = read('NOTICE.txt');
const recordPath = path.join(dir, 'record.json');
const record = fs.existsSync(recordPath) ? JSON.parse(fs.readFileSync(recordPath, 'utf8')) : null;
const literalsPath = path.join(here, 'surface-literals.json');
const REGEN = process.argv.includes('--regen');
const LEDGER = process.argv.includes('--ledger');

const results = [];
function test(group, name, fn) {
  try { fn(); results.push({ group, name, pass: true }); }
  catch (error) { results.push({ group, name, pass: false, error: error.message }); }
}
const near = (a, b, tol, msg = '') => assert.ok(Number.isFinite(a) && Math.abs(a - b) <= tol, `${msg} ${a} differs from ${b} beyond ${tol}`);
const clone = structuredClone;
const EM_DASH = String.fromCharCode(0x2014);
const qnorm = (t) => t.replace(/[‘’]/g, "'").replace(/[“”]/g, '"');

// ------------------------------------------------------------------ independent arithmetic
// Cauchy's elimination written again from the description on Annales p. 81, with plain loops.
function indepCauchy(rec, reversed = { w1: ['1769E'] }) {
  const cols = rec.columns, K = cols.length;
  let eqs = rec.equations.map((e) => ({ id: e.id, a: [...e.coef, e.const] }));
  const exprs = {};
  for (const u of ['deps', 'dn', 'dw', 'w1']) {
    const j = cols.indexOf(u);
    const P = new Array(K + 1).fill(0);
    for (const e of eqs) {
      let m = e.a[j] < 0 ? -1 : 1;
      if ((reversed[u] || []).includes(e.id)) m = -m;
      for (let k = 0; k <= K; k++) P[k] += m * e.a[k];
    }
    exprs[u] = P.map((v, k) => (k === j ? 0 : -v / P[j]));
    for (const e of eqs) { const f = e.a[j] / P[j]; for (let k = 0; k <= K; k++) e.a[k] -= f * P[k]; e.a[j] = 0; }
  }
  const x = new Array(K).fill(0);
  const ad = rec.printed.adopted_p96;
  x[cols.indexOf('dth')] = ad.dth; x[cols.indexOf('kap')] = ad.kap; x[cols.indexOf('kapp')] = ad.kapp;
  const ev = (u) => { const ex = exprs[u]; let s = ex[K]; for (let k = 0; k < K; k++) s += ex[k] * x[k]; return s; };
  x[cols.indexOf('w1')] = ev('w1');
  return 100 * x[cols.indexOf('w1')];
}
// Least squares by Cholesky, for Newcomb's control at k = 0 with his rejections.
function indepNewcomb(rec) {
  const rows = rec.equations.filter((e) => !e.rejected);
  const m = 10;
  const A = Array.from({ length: m }, () => new Array(m).fill(0)), b = new Array(m).fill(0);
  for (const r of rows) for (let i = 0; i < m; i++) { b[i] -= r.weight * r.coef[i] * r.abs; for (let j = 0; j < m; j++) A[i][j] += r.weight * r.coef[i] * r.coef[j]; }
  const Lm = Array.from({ length: m }, () => new Array(m).fill(0));
  for (let i = 0; i < m; i++) for (let j = 0; j <= i; j++) {
    let s = A[i][j];
    for (let k = 0; k < j; k++) s -= Lm[i][k] * Lm[j][k];
    Lm[i][j] = i === j ? Math.sqrt(s) : s / Lm[j][j];
  }
  const y = new Array(m).fill(0), x = new Array(m).fill(0);
  for (let i = 0; i < m; i++) { let s = b[i]; for (let k = 0; k < i; k++) s -= Lm[i][k] * y[k]; y[i] = s / Lm[i][i]; }
  for (let i = m - 1; i >= 0; i--) { let s = y[i]; for (let k = i + 1; k < m; k++) s -= Lm[k][i] * x[k]; x[i] = s / Lm[i][i]; }
  const U = rec.unknowns;
  return { V1: x[U.indexOf('V1')], W1: x[U.indexOf('W1')] };
}
// b^(1)_{3/2}(alpha) by its hypergeometric series, 3 alpha F(3/2, 5/2; 2; alpha^2), summed to convergence.
function laplaceSeries(alpha) {
  let term = 1, sum = 1;
  for (let n = 0; n < 4000; n++) {
    term *= ((1.5 + n) * (2.5 + n)) / ((2 + n) * (n + 1)) * alpha * alpha;
    sum += term;
    if (term < 1e-15) break;
  }
  return 3 * alpha * sum;
}

// ------------------------------------------------------------------ fixtures
const F = figures(LV, NC, REF);
const NULL = E.lvNullSweep(LV, { draws: NULL_DRAWS, seed: NULL_SEED });
Object.assign(F, nullFigures(NULL, NULL_SEED, NULL.fitRms));
const X = S.texts(F);
const claim = E.printedClaim(LV);
const head = E.lvSolve(LV);
const ctl = E.newcombControl(NC, { k: 0 });
const pw = E.powerTest(NC, LV);
const fm = (md.match(/^---\n([\s\S]*?)\n---/) || [])[1] || '';
const fmField = (k) => { const m = fm.match(new RegExp('^' + k + ':\\s*"(.*)"\\s*$', 'm')); return m ? m[1] : null; };
const meta = (attr, name) => { const m = html.match(new RegExp('<meta ' + attr + '="' + name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '" content="([^"]*)"')); return m ? S.decodeEntities(m[1]) : null; };
const fullVisible = S.decodeEntities(html.slice(html.indexOf('<body')).replace(/<script[\s\S]*?<\/script>/g, ' ').replace(/<style[\s\S]*?<\/style>/g, ' ').replace(/<!--[\s\S]*?-->/g, ' ').replace(/<[^>]+>/g, ' ')).replace(/\s+/g, ' ');
const has = (s) => qnorm(fullVisible).includes(qnorm(s.replace(/\s+/g, ' ')));
function surfaceDisagreements(h, figs) {
  const out = [];
  for (const d of S.dataFigs(h)) if (!(d.key in figs) || S.decodeEntities(d.inner.trim()) !== figs[d.key]) out.push(d.key);
  return out;
}
const date = (fm.match(/^date:\s*(\S+)/m) || [])[1] || '2026-09-23';

// ================================================================== anchor: the claim at full strength
test('anchor', 'the transcription: every coefficient of Le Verrier’s printed (I), a column sum of the record, reproduced to its last digit', () => {
  const I = E.lvChecksums(LV).find((c) => c.eq === 'I');
  assert.equal(I.rows.length, 14);
  for (const r of I.rows) assert.ok(E.agreesPrinted(r.printed, r.engine, 'I', r.dec), 'I ' + r.key + ': printed ' + r.printed + ' engine ' + r.engine);
  // and (I) is exactly the column sums over the delta-epsilon sum, independently
  const j = LV.columns.indexOf('deps');
  const sumDeps = LV.equations.reduce((s, e) => s + e.coef[j], 0);
  const sumConst = LV.equations.reduce((s, e) => s + e.const, 0);
  near(-sumConst / sumDeps, LV.printed.I.const, 0.005, '(I) constant by hand');
  assert.equal(LV.equations.length, 21);
  assert.deepEqual([LV.equations.filter((e) => e.month === 'November').length, LV.equations.filter((e) => e.month === 'May').length], [13, 8]);
  for (const e of LV.equations) assert.equal(e.coef.length, 15);
});
test('anchor', 'the page’s engine reproduces the printed claim within the stated tolerance, through the same function the page calls', () => {
  assert.equal(claim, 38.3);
  assert.equal(LV.printed.headline.cras_p380_value, 38);
  near(head.perCentury, claim, ANCHOR_TOL, 'headline');
  near(head.perCentury, 38.44, 0.005, 'the recorded engine value');
  near(indepCauchy(LV), head.perCentury, 1e-9, 'independent Cauchy elimination');
  near(E.printedIVHeadline(LV), 38.34, 0.005, 'his own printed (IV) at his adopted values');
  assert.equal(E.printedIVHeadline(LV).toFixed(1), claim.toFixed(1), 'his printed (IV) rounds to his printed 38.3');
  near(E.roundingBudget(LV).sd, 0.16, 0.03, 'rounding budget');
  assert.ok(E.roundingBudget(LV).sd * 3 < ANCHOR_TOL, 'the tolerance exceeds three rounding standard deviations');
});
test('anchor', 'his (IV) needs his multiplier set: the plain sign rule misses three printed values, one reversal on the 1769 ingress reproduces all eight, and no other single or paired reversal does', () => {
  const lv = E.lvChecksums(LV, { rule: 'leverrier' }), sg = E.lvChecksums(LV, { rule: 'sign' });
  const count = (ck, eq) => ck.find((c) => c.eq === eq).rows.filter((r) => E.agreesPrinted(r.printed, r.engine, eq, r.dec)).length;
  assert.deepEqual([count(lv, 'I'), count(lv, 'II'), count(lv, 'III'), count(lv, 'IV')], [14, 12, 12, 8]);
  assert.equal(count(sg, 'IV'), 5);
  const rs = E.reversalSearch(LV);
  assert.equal(rs.tried, 1 + 21 + 210);
  assert.deepEqual(rs.full, [['1769E']]);
  assert.deepEqual(E.LEVERRIER_SET, { step: 'w1', reversed: ['1769E'] });
  near(E.lvSolve(LV, { estimator: 'sign' }).perCentury, 38.01, 0.005);
});
test('anchor', 'the residual claim: under one second at his values, over six with no excess, and his p. 82 table reproduced', () => {
  assert.ok(head.max < 1, 'max ' + head.max);
  near(head.rms, 0.592, 0.001);
  const f0 = E.lvSolve(LV, { w1: 0 });
  assert.equal(f0.worst, '1753S'); near(f0.max, 6.295, 0.001); near(f0.rms, 2.425, 0.001);
  const rc = E.lvResidualCheck(LV);
  assert.ok(rc.maxDiff < 0.11, 'p. 82 table reproduced within ' + rc.maxDiff);
  assert.equal(rc.pairs.find((p) => p.id === '1782E').printed, -1.16);
});
test('anchor', 'a corrupted claimant record fails the anchor', () => {
  const bad = clone(LV); bad.equations.find((e) => e.id === '1753S').const *= -1;
  const hb = E.lvSolve(bad).perCentury;
  assert.ok(Math.abs(hb - claim) > ANCHOR_TOL, 'flipped 1753 constant gives ' + hb);
  near(hb, 4.5, 0.5, 'as the spec’s pilot found');
  const bad2 = clone(LV); for (const e of bad2.equations) if (e.month === 'May') e.const = 0;
  assert.ok(Math.abs(E.lvSolve(bad2).perCentury - claim) > ANCHOR_TOL, 'May constants zeroed');
  const bad3 = clone(LV); bad3.equations[0].coef[0] += 0.1;
  assert.ok(!E.lvChecksums(bad3).find((c) => c.eq === 'I').rows.every((r) => E.agreesPrinted(r.printed, r.engine, 'I', r.dec)), 'a mistyped coefficient breaks the (I) checksum');
});

// ================================================================== control: the deciding control
test('control', 'Newcomb’s control from his equations of condition: V′, W′ and p within the stated acceptance', () => {
  const P = NC.printed_solution_p460.k0;
  near(ctl.V1, P.V1, CONTROL_TOL.V1, 'V1'); near(ctl.W1, P.W1, CONTROL_TOL.W1, 'W1'); near(ctl.p, NC.chain.adopted_p473.p, CONTROL_TOL.p, 'p');
  const ind = indepNewcomb(NC);
  near(ind.V1, ctl.V1, 1e-9, 'Cholesky V1'); near(ind.W1, ctl.W1, 1e-9, 'Cholesky W1');
  assert.equal(ctl.n, 54); assert.equal(ctl.m, 10);
  near(ctl.sumWvv, NC.sum_wvv_p463.k0, 0.2, 'sum of weighted squares against p. 463');
  near(ctl.sigmaFormal, 1.21, 0.01); near(ctl.sigmaJackknife, 2.94, 0.01);
  assert.equal(ctl.jackknife.length, 21);
});
test('control', 'the normal equations: every entry without k reproduced except the two in (8), and the two readings of the asymmetry tested', () => {
  const ck = E.normalChecksum(NC);
  assert.deepEqual(ck.bad.map((q) => [q.eq, q.col]), [[8, 'W1'], [8, 'constant']]);
  const w = ck.bad[0];
  near(w.engine, -w.printed, 0.002, 'the W1 entry differs only in sign');
  assert.equal(NC.printed_normal_p459[5][7], -NC.printed_normal_p459[7][5], 'printed (6) S and (8) W1 are opposite');
  near(ck.bad[1].engine - ck.bad[1].printed, -1.0, 0.0015, 'constant of (8)');
  const asIs = E.solvePrintedNormals(NC);
  near(asIs.V1, -2.567, 0.001); near(asIs.W1, 1.746, 0.001);
  const fix8 = E.solvePrintedNormals(NC, { fix: [[7, 5, 6.156]] });
  for (const [u, v] of Object.entries(NC.printed_solution_p460.k0)) near(fix8[u], v, 0.0065, 'fix (8) ' + u);
  const fix6 = E.solvePrintedNormals(NC, { fix: [[5, 7, -6.156]] });
  assert.ok(Math.abs(fix6.W1 - NC.printed_solution_p460.k0.W1) > 0.02, 'fixing (6) instead does not match');
  assert.ok(ck.maxK > 1 && ck.maxK < 2, 'the k column differs by up to ' + ck.maxK);
  assert.ok(!NC.corrigenda_p484.some((c) => /459|473|normal/i.test(c)), 'none in the corrigenda');
});
test('control', 'Newcomb’s closing pair gives dn +0.295, not the printed +0.37, and p is unaffected; the Venus arithmetic of p. 470', () => {
  const pp = E.printedPair(NC);
  near(pp.p, 42.954, 0.001); near(pp.dn, 0.2949, 0.0005);
  assert.equal(NC.chain.adopted_p473.dn, 0.37);
  near(E.chainP(NC, -2.63, 1.84, -0.008).p, NC.chain.adopted_p473.p, 0.01, 'the chain from the printed V′, W′');
  const vz = E.venusForZero(NC, NC.printed_solution_p460.k0.V1, NC.printed_solution_p460.k0.W1);
  assert.equal(vz.nu1.toFixed(4), NC.chain.venus_p470.nu1.toFixed(4));
  near(vz.denominator, NC.chain.venus_p470.mass_denominator, 50);
  near(E.chainP(NC, ctl.V1, ctl.W1, vz.nu1).p, 0, 0.1, 'near zero at the p. 470 mass');
});
test('control', 'choices of the control move p: k and the rejections', () => {
  near(E.newcombControl(NC, { k: 0.295, jackknife: false }).p, 44.01, 0.01);
  near(E.newcombControl(NC, { k: 'free', jackknife: false }).x.k, 0.292, 0.001);
  const r = E.newcombControl(NC, { rejections: 'restore', jackknife: false });
  assert.equal(r.n, 57); near(r.p, 42.92, 0.01);
});

// ================================================================== power: the control on the control
test('power', 'grade A: the claimed excess, read from the claimant file, planted into a copy of Newcomb’s own equations of condition and run through the unmodified control', () => {
  const empty = E.plantPerihelionExcess(clone(NC), -NC.chain.adopted_p473.p);
  const r0 = E.newcombControl(empty, { k: 0 });
  assert.ok(Math.abs(r0.p) / r0.sigmaFormal < 2, 'the control can come back empty: ' + r0.p);
  const planted = E.plantPerihelionExcess(clone(empty), claim);
  assert.equal(planted.meta.plantedDp, claim, 'plant used the printed claim');
  assert.equal(planted.meta.plantedDp, LV.printed.headline.annales_p100_value);
  const r1 = E.newcombControl(planted, { k: 0 });
  near(r1.p, claim, E.POWER_RULE.tol, 'recovered');
  assert.ok(r1.p / r1.sigmaFormal >= E.POWER_RULE.z && r1.p / r1.sigmaJackknife >= E.POWER_RULE.z, 'z ' + r1.p / r1.sigmaFormal + ' ' + r1.p / r1.sigmaJackknife);
  // the plant went into the absolute terms only, and moved V′ and W′ by exactly Newcomb’s first-order amounts
  assert.deepEqual(planted.equations.map((e) => e.coef), NC.equations.map((e) => e.coef));
  near(r1.V1 - r0.V1, -0.487 * claim, 1e-9, 'V′ moved by -0.487 dp'); near(r1.W1 - r0.W1, 0.284 * claim, 1e-9, 'W′ moved by +0.284 dp');
  // the page's powerTest is this same computation
  assert.equal(pw.planted.p, r1.p); assert.equal(pw.empty.p, r0.p);
  assert.equal(pw.couldConfirm, true); assert.equal(pw.couldComeBackEmpty, true);
  assert.ok(ctl.p / ctl.sigmaJackknife >= 3, 'the real data show the effect');
});
test('power', 'the test can fail: a plant below the control’s noise, and the claim planted into a noisier copy of the same equations, are both called inconclusive by the same rule', () => {
  // a small plant goes in and comes back, but stands too few jackknife errors from zero
  const small = E.powerTest(NC, LV, { size: 5 });
  assert.equal(small.recovered, true);
  assert.equal(small.couldConfirm, false, 'a plant of 5 is inconclusive: jackknife z ' + small.zJack);
  assert.ok(small.zJack < E.POWER_RULE.z && small.zFormal >= E.POWER_RULE.z, 'it fails on the jackknife error, not the formal one');
  // the smallest size the rule accepts, found by bisection through powerTest, equals the rule solved by hand
  const min = E.smallestConfirmable(NC, LV).size;
  near(min, E.POWER_RULE.z * pw.planted.sigmaJackknife - pw.recoveredGap, 1e-6, 'smallest confirmable excess');
  assert.equal(E.powerTest(NC, LV, { size: min - 0.01 }).couldConfirm, false);
  assert.equal(E.powerTest(NC, LV, { size: min + 0.01 }).couldConfirm, true);
  assert.equal(figures(LV, NC, REF)['pw.min'], min.toFixed(2));
  // a noisier copy of Newcomb's own equations: every accepted row's residual at the k = 0 solution made five
  // times larger. The solution is unchanged, so the plant is still recovered, but the rule now says inconclusive.
  const noisy = clone(NC);
  for (const e of noisy.equations) {
    if (e.rejected) continue;
    let r = e.abs;
    NC.unknowns.slice(0, 10).forEach((u, i) => { r += e.coef[i] * ctl.x[u]; });
    e.abs += 4 * r;
  }
  near(E.newcombControl(noisy, { k: 0, jackknife: false }).p, ctl.p, 1e-9, 'the noisier copy has the same solution');
  const pn = E.powerTest(noisy, LV);
  assert.equal(pn.recovered, true);
  assert.equal(pn.couldConfirm, false, 'noisier data: z ' + pn.zFormal + ' ' + pn.zJack);
  assert.ok(pn.zJack < E.POWER_RULE.z);
  const src = read('engine.js');
  assert.ok(/e\.abs -= d/.test(src) && !/\.p \+= dp|p: .*\+ dp/.test(src), 'the plant is written into the absolute terms, never added to a result');
});
test('power', 'power at other sizes goes through the same function, and zero planted returns the emptied value', () => {
  const empty = E.plantPerihelionExcess(clone(NC), -NC.chain.adopted_p473.p);
  const base = E.newcombControl(empty, { k: 0, jackknife: false }).p;
  for (const d of [0, 10, 42.95, -20]) near(E.newcombControl(E.plantPerihelionExcess(clone(empty), d), { k: 0, jackknife: false }).p, base + d, 1e-9, 'plant ' + d);
});

// ================================================================== null: the claimant's method on nothing
test('null', 'the null records keep Le Verrier’s rows and carry no excess, and his procedure run on them never reaches the claim', () => {
  const fit = E.lvSolve(LV);
  const rec0 = E.nullRecord(LV, fit, E.mulberry32(3), { noise: 'gaussian', sigmaSys: 0 });
  assert.deepEqual(rec0.equations.map((e) => e.coef), LV.equations.map((e) => e.coef));
  const clean = { ...LV, equations: LV.equations.map((e) => { let m = 0; LV.columns.forEach((c, k) => { if (c !== 'w1' && fit.x[c]) m -= e.coef[k] * fit.x[c]; }); return { ...e, const: m }; }) };
  near(E.lvSolve(clean).perCentury, 0, 1e-9, 'the model alone carries no excess');
  assert.equal(NULL.draws, 10000); assert.equal(NULL.countGE, 0);
  near(NULL.sd, 2.88, 0.02); near(NULL.max, 10.05, 0.02);
  // the residuals are scaled up by sqrt(21/17) for the four unknowns fitted, and the null's spread then agrees
  // with the page's formal standard error of the headline, computed a different way
  near(E.residualInflation(fit), Math.sqrt(21 / 17), 1e-12);
  near(NULL.sd, E.lvFormalError(LV).se, 0.06, 'null spread against formal error');
  // a null record with the claim planted into it is seen: the procedure can see the effect in this structure
  const withClaim = { ...clean, equations: clean.equations.map((e) => ({ ...e, const: e.const - e.coef[LV.columns.indexOf('w1')] * claim / 100 })) };
  near(E.lvSolve(withClaim).perCentury, claim, 1e-9, 'planted into the null structure');
});
test('null', 'the systematic-error sweep: the linear decomposition equals the procedure run directly, draw by draw', () => {
  const d = E.lvNullDraws(LV, { from: 0, to: 300 });
  const direct = E.lvNullAt(LV, { sigmaSys: 5, draws: 300 });
  for (let i = 0; i < 300; i++) near(d.A[i] + 5 * d.B[i], direct.values[i], 1e-8, 'draw ' + i);
  near(NULL.rateAt(5), 0.0857, 0.001); near(NULL.rateAt(10), 0.2527, 0.001); near(NULL.rateAt(2), 0.0007, 0.0002);
  near(NULL.sigmaFor5, 4.17, 0.02);
  // a draw already at or above the claim needs no systematic error at all, and is counted so
  assert.equal(E.summarizeNull([40, 30, 0], [1, 1, -1], claim).sigmaFor5, 0);
  near(E.summarizeNull([30, 20], [1, 1], claim).sigmaFor5, 8.3, 1e-9);
  assert.ok(NULL.rateAt(NULL.sigmaFor5) >= 0.05 && NULL.rateAt(NULL.sigmaFor5 - 0.01) < 0.05);
  const inf = E.lvInfluence(LV);
  assert.equal(inf.cheapest.year, 1832); near(inf.cheapest.needed, 11.7, 0.05);
  near(E.lvFormalError(LV).se, 2.88, 0.01);
});

// ================================================================== the page's own physics (asserted under surface: they are printed figures)
test('surface', 'Einstein’s formula (14) and the inner-planet sums, recomputed independently', () => {
  const g = E.einsteinAdvance(REF);
  const a = REF.mercury.semimajor_axis_km * 1e3, T = REF.mercury.sidereal_period_days * 86400, e = REF.mercury.eccentricity, c = REF.c_m_s;
  // the same formula rearranged (GM from Kepler's third law with the same a and T): an arithmetic check only
  const GM = (4 * Math.PI ** 2 * a ** 3) / T ** 2;
  const alt = ((6 * Math.PI * GM) / (c * c * a * (1 - e * e))) * (36525 / REF.mercury.sidereal_period_days) * (180 * 3600 / Math.PI);
  near(g.perCentury, alt, 1e-9); near(g.perCentury, 42.98, 0.005);
  // a second route: the Sun's gravitational parameter itself, the IAU 2015 nominal value (Resolution B3),
  // 1.3271244e20 m^3 s^-2, in place of the period
  const GMsun = 1.3271244e20;
  const alt2 = ((6 * Math.PI * GMsun) / (c * c * a * (1 - e * e))) * (36525 / REF.mercury.sidereal_period_days) * (180 * 3600 / Math.PI);
  near(g.perCentury, alt2, 0.005, 'Einstein’s advance from the IAU solar GM');
  for (const al of [0.2, 0.3686, 0.437, 0.8]) near(E.laplaceB32(al), laplaceSeries(al), 1e-8, 'b(' + al + ')');
  const lvm = 1 / REF.leverrier_mercury_mass.denominator;
  const d = E.distanceFor(REF, lvm, claim);
  near(d.alpha, 0.437, 0.0005, 'his relation: a body of Mercury’s mass a little inside half Mercury’s distance');
  assert.ok(d.alpha < 0.5);
  const rq = E.requiredMass(REF, REF.leverrier_1860.semimajor_axis_au, claim);
  near(rq.m / lvm, 1.59, 0.005);
  near(E.vulcanRate(REF, REF.leverrier_1860.semimajor_axis_au, lvm / 17).rate, 1.42, 0.005);
});

// ================================================================== surface: what the reader sees
test('surface', 'every bound figure on the page equals the recomputation', () => {
  const figs = S.dataFigs(html);
  assert.ok(figs.length > 180, 'bound figures ' + figs.length);
  assert.deepEqual(surfaceDisagreements(html, F), []);
  for (const k of Object.keys(F)) assert.ok(figs.some((d) => d.key === k) || /^(lv\.contPlain|lv\.contSub|pr\.contPrinted|lv\.max0r|nc\.dn|nc\.peV1|nc\.peW1|pr\.peV1|pr\.peW1|nc\.denZero|vd\.revs|lv\.first|lv\.last)$/.test(k) || k.startsWith('rd.s'), 'figure ' + k + ' is printed somewhere');
});
test('surface', 'the page is exactly what the fill script writes from the recomputation: dek, headline, verdict text, head tags and JSON-LD', () => {
  const filled = fillHtml(html, F, date);
  assert.equal(filled, html, 'the shipped page differs from the one the recomputation writes');
  assert.equal(S.decodeEntities((html.match(/<title>([\s\S]*?)<\/title>/) || [])[1]), X.SEO);
  assert.equal(meta('name', 'description'), X.DEK);
  assert.equal(meta('property', 'og:description'), X.OG);
  assert.equal(meta('name', 'twitter:description'), X.TW);
  assert.equal(meta('property', 'og:image:alt'), X.OG_ALT);
  assert.equal(meta('property', 'og:title'), S.TITLE + ' · Artificial Wasteland');
  assert.equal(meta('property', 'og:url'), S.URL); assert.equal(meta('property', 'og:image'), S.OG_IMAGE); assert.equal(meta('name', 'twitter:image'), S.OG_IMAGE);
  assert.ok(html.includes('<link rel="canonical" href="' + S.URL + '" />'));
  const ld = JSON.parse((html.match(/<script type="application\/ld\+json">([\s\S]*?)<\/script>/) || [])[1]);
  assert.deepEqual([ld['@type'], ld.name, ld.headline, ld.description, ld.url], ['Article', X.SEO, S.TITLE, X.DEK, S.URL]);
  assert.equal(S.decodeEntities((html.match(/<p class="dek" data-dek>([\s\S]*?)<\/p>/) || [])[1]), X.DEK);
  assert.equal(S.decodeEntities((html.match(/<p id="headline" data-headline>([\s\S]*?)<\/p>/) || [])[1]), X.HEADLINE);
  assert.equal((html.match(/<h1>([^<]*)<\/h1>/) || [])[1], S.TITLE);
});
test('surface', 'the frontmatter and body are exactly what the recomputation writes, and the placard obeys its rules', () => {
  assert.equal(md, mdText(X, F, date));
  assert.equal(fmField('title'), S.TITLE); assert.equal(fmField('dek'), X.DEK); assert.equal(fmField('seoTitle'), X.SEO); assert.equal(fmField('plain'), X.PLAIN);
  assert.equal(fmField('seam'), 'physical'); assert.equal(fmField('href'), '/strata/' + S.SLUG + '/');
  const plain = X.PLAIN;
  assert.ok(plain.length >= 90 && plain.length <= 420, 'plain length ' + plain.length);
  assert.ok((plain.match(/[.!?](\s|$)/g) || []).length <= 3 && !plain.includes(EM_DASH) && !plain.includes('"'));
  const rel = [...fm.matchAll(/^ {2}- to: ([a-z0-9-]+)$/gm)].map((m) => m[1]);
  assert.ok(rel.length >= 3 && rel.length <= 5 && rel.every((s) => fs.existsSync(path.join(root, 'src/content/strata', s + '.md'))), 'relates');
  assert.ok(/^tags: \[.*"extraordinary-claims".*\]$/m.test(fm));
});
test('surface', 'every numeral outside the bound figures is a year, a page, a citation or a stated label, and none has changed', () => {
  const lits = S.literalNumbers(html);
  const ALLOWED = {
    '38': 'Le Verrier’s own rounded figure, quoted from CRAS p. 380 and on the button',
    '43': 'the rounded figure in Newcomb’s and Einstein’s quoted sentences',
    '45': 'Einstein’s quoted 45 ± 5',
    '575': 'the scan resolution in dots per inch',
    '150': 'the refusal demonstration button',
    '0.5': 'the refusal demonstration button, in AU',
    '4.0': 'the CC BY 4.0 licence',
  };
  const bad = lits.filter(({ n, before }) => {
    if (/^(1[6-9]\d\d|20[0-2]\d)$/.test(n)) return false;
    if (/(pp?\.|page|pp\. \d+-)\s*$/.test(before)) return false;
    if (/(doi:\s*[\d./a-z-]*|Comptes rendus|Comptes rendus volumes|volumes \d+ and|CRAS|Relativity|Journal|vol\.|153\(|\d+\(|\d+\),|, 1,|s41114-|3881|1538-|23-|BY)\s*$/i.test(before)) return false;
    if (/^\d+$/.test(n) && Number(n) <= 31) return false;
    return !(n in ALLOWED);
  });
  assert.deepEqual(bad.map((b) => b.n + ' after "' + b.before + '"'), []);
  const inv = lits.map((l) => l.n);
  if (!REGEN) assert.deepEqual(inv, JSON.parse(fs.readFileSync(literalsPath, 'utf8')), 'the unbound numerals differ from the inventory');
});
test('surface', 'structure, accessibility and conduct', () => {
  assert.match(html, /<script type="module" src="page\.js"><\/script>\s*<\/body>\s*<\/html>\s*$/);
  const inline = [...html.matchAll(/<script(?![^>]*\bsrc=)[^>]*>([\s\S]*?)<\/script>/g)];
  assert.equal(inline.length, 1); assert.match(inline[0][0], /application\/ld\+json/);
  const js = ['engine.js', 'figures.js', 'readings.js', 'data.js', 'render.js', 'page.js'].map((f) => read(f)).join('\n');
  assert.ok(!/https?:\/\/(?!www\.w3\.org\/2000\/svg)/.test(js), 'no absolute URL in any shipped script');
  assert.ok(!/fetch\(\s*['"`]https?:|import\(\s*['"`]https?:|from\s+['"]https?:|WebSocket|XMLHttpRequest|sendBeacon|EventSource/.test(js));
  assert.ok(html.includes('<link rel="stylesheet" href="/fonts/fonts.css" />') && !/googleapis|gstatic/.test(html));
  assert.ok(html.includes('prefers-reduced-motion') && html.includes(':focus-visible'));
  assert.ok((html.match(/role="status" aria-live="polite"/g) || []).length >= 12);
  for (const id of ['heroToggle', 'nuSlider', 'plantSlider', 'plantNum', 'sigSlider', 'w1Slider', 'aSlider', 'aNum']) assert.ok(new RegExp('id="' + id + '"').test(html), id);
  for (const m of html.matchAll(/<input type="range" id="([^"]+)"/g)) assert.ok(html.includes('for="' + m[1] + '"'), 'label for ' + m[1]);
  assert.ok(!/<span[^>]*onclick|<div[^>]*onclick/.test(html), 'no clickable span or div');
  const files = fs.readdirSync(dir).map((f) => path.join(dir, f)).concat([mdPath]);
  for (const f of fs.readdirSync(here).filter((x) => /\.(mjs|md|json|py)$/.test(x))) files.push(path.join(here, f));
  for (const f of fs.readdirSync(path.join(here, 'src'))) files.push(path.join(here, 'src', f));
  for (const f of files) assert.ok(fs.readFileSync(f, 'utf8').split('\n').every((l) => !l.includes(EM_DASH) || l.includes('em-dash-ok')), 'em dash in ' + f);
  const words = /\b(debunk\w*|refuted|disproved|myth|hoax\w*|fraud\w*|delusion\w*|crank\w*|misconduct|fabricat\w*)\b/i;
  assert.ok(!words.test(fullVisible) && !words.test(md), 'a word the fairness rules forbid');
  assert.ok(!/github\.com\/[^/]+\/Artificial-Wasteland/i.test(html));
  // a value that rounds to zero is printed without a sign; a check that could not run is not counted as agreeing
  assert.deepEqual([num(-0.004, 2), sgn(-0.004, 2), num(-0.006, 2), sgn(0.006, 2), sgn(-0.02, 2)], ['0.00', '0.00', '−0.01', '+0.01', '−0.02']);
  const pageJs = read('page.js');
  assert.ok(pageJs.includes("c.ok === null ? 'not run '") && pageJs.includes('ok === null ? null : ok === true'), 'an unrun hash check is shown as not run');
  assert.ok(!/nullStatus'\)\.textContent = 'Running null records: '/.test(pageJs), 'the null run does not chatter in its live region');
});

// ================================================================== choices
test('choices', 'every choice is well formed, declared on the page, and moves its named output', () => {
  for (const c of CHOICES) {
    assert.ok(c.id && Array.isArray(c.options) && c.options.length >= 2 && c.options.includes(c.default) && Array.isArray(c.affects) && c.inert === false, c.id);
    assert.equal(new Set(c.options.map(String)).size, c.options.length, c.id + ' distinct');
  }
  const outs = {
    estimator: (v) => E.lvSolve(LV, { estimator: v }).perCentury,
    nuisance: (v) => E.lvSolve(LV, { nuisance: v }).perCentury,
    k: (v) => E.newcombControl(NC, { k: v, jackknife: false }).p,
    rejections: (v) => E.newcombControl(NC, { rejections: v, jackknife: false }).p,
    nu1: (v) => E.chainP(NC, ctl.V1, ctl.W1, v).p,
    plant: (v) => E.newcombControl(E.plantPerihelionExcess(E.plantPerihelionExcess(clone(NC), -NC.chain.adopted_p473.p), v), { jackknife: false }).p,
    noise: (v) => E.lvNullSweep(LV, { draws: 400, noise: v }).max,
    sigmaSys: (v) => NULL.rateAt(v),
    w1: (v) => E.lvSolve(LV, { w1: v / 100 }).rms,
    vulcanA: (v) => E.requiredMass(REF, v, claim).m,
    transits: (v) => E.lvSolve(LV, { exclude: v === 'all' ? [] : LV.equations.filter((e) => String(e.year) === v.split(' ')[1]).map((e) => e.id) }).perCentury,
  };
  for (const c of CHOICES) {
    assert.ok(outs[c.id], 'an output for ' + c.id);
    const vals = c.options.map((o) => outs[c.id](o));
    assert.equal(new Set(vals.map((v) => v.toPrecision(6))).size, vals.length, c.id + ' moves: ' + vals.join(' '));
  }
  const controls = { estimator: 'data-state="estimator"', nuisance: 'data-state="nuisance"', k: 'data-state="k"', rejections: 'data-state="rejections"', noise: 'data-state="noise"', nu1: 'id="nuSlider"', plant: 'id="plantSlider"', sigmaSys: 'id="sigSlider"', w1: 'id="w1Slider"', vulcanA: 'id="aSlider"', transits: 'id="lvYears"' };
  for (const c of CHOICES) assert.ok(html.includes(controls[c.id]), 'control for ' + c.id);
  if (record && !REGEN) assert.deepEqual(record.choices, CHOICES);
});

// ================================================================== fault: planted into copies of the data
test('fault', 'faults planted into copies of the frozen records move the results the page prints', () => {
  const nc = clone(NC); nc.equations.find((e) => e.year === 1878 && e.contact === 'II').abs += 3;
  const r = E.newcombControl(nc, { k: 0, jackknife: false });
  assert.ok(Math.abs(r.p - ctl.p) > 0.5, 'a changed 1878 contact moves p: ' + r.p);
  assert.notEqual(figures(LV, nc, REF)['nc.p'], F['nc.p']);
  const lv = clone(LV); lv.equations.find((e) => e.id === '1769E').coef[5] = -lv.equations.find((e) => e.id === '1769E').coef[5];
  assert.notEqual(E.lvSolve(lv).perCentury.toFixed(2), F['lv.head']);
  const ref = clone(REF); ref.mercury.sidereal_period_days = 88.969;
  assert.notEqual(E.einsteinAdvance(ref).perCentury.toFixed(2), F['vd.gr']);
});
test('fault', 'the surface check goes red on a corrupted displayed figure, a corrupted dek and a corrupted literal', () => {
  const first = S.dataFigs(html).find((d) => d.key === 'nc.p');
  const corrupted = html.slice(0, first.index) + first.full.replace(F['nc.p'], '42.94') + html.slice(first.index + first.full.length);
  assert.deepEqual(surfaceDisagreements(corrupted, F), ['nc.p']);
  assert.notEqual(fillHtml(corrupted, F, date), corrupted);
  const badDek = html.replace(S.escText(X.DEK), S.escText(X.DEK.replace(F['lv.head'], '38.45')));
  assert.notEqual(badDek, html); assert.notEqual(fillHtml(badDek, F, date), badDek);
  const lit = html.replace('(p. 367)', '(p. 368)').replace('p. 367<', 'p. 368<');
  assert.notDeepEqual(S.literalNumbers(lit).map((l) => l.n), S.literalNumbers(html).map((l) => l.n));
});
function pinMismatches(bufs) {
  return Object.entries(bufs).filter(([f, b]) => crypto.createHash('sha256').update(b).digest('hex') !== SHA256[f]).map(([f]) => f).sort();
}
test('fault', 'a changed byte in a frozen file is caught by the same pin check the provenance group runs', () => {
  const real = Object.fromEntries(Object.values(FILES).map((f) => [f, fs.readFileSync(path.join(dir, f))]));
  assert.deepEqual(pinMismatches(real), []);
  const bad = { ...real, [FILES.control]: Buffer.from(real[FILES.control]) };
  const i = bad[FILES.control].indexOf('109.4');
  bad[FILES.control][i + 4] = 0x35;
  assert.deepEqual(pinMismatches(bad), [FILES.control]);
});

// ================================================================== refusal
test('refusal', 'the instrument refuses what its record does not support, and the page offers each refusal', () => {
  const r1 = E.plantPerihelionExcess(clone(NC), 150);
  assert.equal(r1.refused, true); assert.equal(r1.reason, E.REASONS.plantRange);
  for (const v of [NaN, -101, '38.3']) assert.equal(E.plantPerihelionExcess(clone(NC), v).refused, true, 'plant ' + v);
  assert.equal(E.plantPerihelionExcess(clone(NC), 100).refused, undefined);
  const out = E.vulcanRate(REF, 0.5, 1e-7);
  assert.equal(out.code, 'outside'); assert.equal(E.vulcanRate(REF, REF.mercury.semimajor_axis_au, 1e-7).code, 'outside');
  assert.equal(E.vulcanRate(REF, 0.004, 1e-7).code, 'inside-sun');
  assert.equal(E.requiredMass(REF, 0.545, claim).refused, true);
  const few = LV.equations.slice(0, 17).map((e) => e.id);
  assert.equal(E.lvSolve(LV, { exclude: few }).refused, true, 'four equations cannot fix four unknowns and a check');
  assert.equal(E.lvSolve(LV, { exclude: few }).code, 'too-few');
  // one season only is refused, and the page's own formal error shows why: it is several times the claim
  for (const m of ['November', 'May']) {
    const ex = LV.equations.filter((e) => e.month !== m).map((e) => e.id);
    const r = E.lvSolve(LV, { exclude: ex });
    assert.equal(r.code, 'one-season', m + ' only');
    assert.ok(E.lvFormalError(LV, { exclude: ex, oneSeason: true }).se > 5 * claim, m + ' only: formal error');
  }
  const threeMay = LV.equations.filter((e) => ![1753, 1786, 1799].includes(e.year)).map((e) => e.id);
  assert.equal(E.lvSolve(LV, { exclude: threeMay }).code, 'one-season', 'three May transits');
  // a two-season selection too weak to tell the claim from zero is computed and marked undetermined
  const keepOf = (ys) => LV.equations.filter((e) => !ys.includes(e.year)).map((e) => e.id);
  for (const ys of [[1736, 1782, 1832, 1845], [1697, 1769, 1789, 1832]]) {
    const d = E.lvDetermined(LV, { exclude: keepOf(ys) });
    assert.equal(d.determined, false, ys.join(' ') + ': formal error ' + d.se);
  }
  assert.equal(E.lvDetermined(LV).determined, true);
  assert.equal(E.lvDetermined(LV, { exclude: ['1753S'] }).determined, true);
  // the inner planet stops at Mercury's perihelion distance, where a circular orbit would cross Mercury's
  const q = E.mercuryPerihelionAU(REF);
  near(q, REF.mercury.semimajor_axis_au * (1 - REF.mercury.eccentricity), 1e-12);
  assert.equal(E.vulcanRate(REF, q + 0.001, 1e-7).code, 'outside');
  assert.equal(E.vulcanRate(REF, q - 0.001, 1e-7).refused, undefined);
  assert.equal(E.vulcanRate(REF, NaN, 1e-7).code, 'not-number');
  assert.equal(E.plantPerihelionExcess(clone(NC), NaN).code, 'not-number');
  const aMax = Number((html.match(/<input type="range" id="aSlider" min="[^"]*" max="([^"]*)"/) || [])[1]);
  assert.ok(aMax > 0 && aMax < q, 'the distance slider stops inside the perihelion distance: ' + aMax);
  assert.equal(E.lvNullAt(LV, { sigmaSys: 25 }).refused, true);
  const pageJs = read('page.js');
  for (const id of ['try150', 'try545', 'plantRefusal', 'aRefusal', 'claimRefusal']) { assert.ok(html.includes('id="' + id + '"'), id); assert.ok(pageJs.includes("$('" + id + "')"), 'page.js wires ' + id); }
  assert.ok(has('What it refuses.') && has('a significance for 38 against 43'));
  assert.match(pageJs, /value\.trim\(\) === '' \? NaN/, 'an empty box is refused, not read as zero');
  assert.ok(pageJs.includes('E.lvDetermined(') && pageJs.includes("'undetermined'"), 'the claim panel marks a weak selection undetermined');
  assert.ok(pageJs.includes('E.powerTest(NC, LV, { size: v })'), 'the plant slider applies the page’s rule through powerTest');
});

// ================================================================== provenance
const hashes = Object.fromEntries(Object.values(FILES).map((f) => [f, crypto.createHash('sha256').update(fs.readFileSync(path.join(dir, f))).digest('hex')]));
test('provenance', 'every frozen file is pinned in data.js, the README and record.json, copied byte for byte, and its sources named', () => {
  for (const [f, h] of Object.entries(hashes)) {
    assert.equal(SHA256[f], h, 'data.js pin for ' + f);
    assert.ok(readme.includes(h), 'README hash for ' + f);
    assert.deepEqual(fs.readFileSync(path.join(dir, f)), fs.readFileSync(path.join(here, 'data', f)), 'research copy of ' + f);
    assert.ok(fs.statSync(path.join(dir, f)).size < 2_000_000);
  }
  const shipped = fs.readdirSync(dir).filter((f) => f.endsWith('.json') && f !== 'record.json').sort();
  assert.deepEqual(shipped, Object.values(FILES).sort());
  for (const u of ['https://articles.adsabs.harvard.edu/pdf/1859AnPar...5....1L', 'https://archive.org/details/comptesrendusheb49acad', 'https://archive.org/details/comptesrendusheb50acad', 'https://archive.org/details/astronomicalpap00newcgoog', 'https://nssdc.gsfc.nasa.gov/planetary/factsheet/mercuryfact.html', 'https://doi.org/10.3847/1538-3881/aa5be2', 'https://doi.org/10.1007/s41114-023-00047-0', 'https://articles.adsabs.harvard.edu/pdf/1915SPAW.......831E']) {
    assert.ok(readme.includes(u), 'README names ' + u);
    assert.ok(notice.includes(u), 'NOTICE names ' + u);
  }
  assert.equal(LV.source.scan_sha256_read, '9668f9a6e5d984ab35efd1a3cec76d2fab40b1e968e268d3d564729e020db3f4');
  if (record && !REGEN) for (const r of record.records) assert.equal(r.sha256, hashes[r.file], 'record.json pin for ' + r.file);
});

// ================================================================== verdict
test('verdict', 'category, date, scope, sources and what would change it are printed and match record.json', () => {
  assert.match(html, /<p class="cat" id="verdictCat">VINDICATED<\/p>/);
  assert.equal(VERDICT.category, 'VINDICATED'); assert.equal(VERDICT.as_of, '2026-09-23');
  assert.match(html, /<time datetime="2026-09-23" id="verdictDate">23 September 2026<\/time>/);
  assert.equal(S.decodeEntities((html.match(/<span id="verdictScope">([\s\S]*?)<\/span>/) || [])[1]), VERDICT.scope);
  assert.equal(S.decodeEntities((html.match(/<span id="verdictChange">([\s\S]*?)<\/span>/) || [])[1]), VERDICT.would_change);
  assert.equal(S.decodeEntities((html.match(/<span id="novelty">([\s\S]*?)<\/span>/) || [])[1]), NOVELTY);
  const lis = [...html.matchAll(/<li id="src-[a-z]+">([\s\S]*?)<\/li>/g)];
  assert.equal(lis.length, VERDICT.sources.length); assert.ok(lis.length >= 2);
  for (let i = 0; i < lis.length; i++) {
    const shown = S.decodeEntities(lis[i][1].replace(/<[^>]+>/g, '')).replace(/\s+/g, ' ');
    assert.ok(shown.startsWith(VERDICT.sources[i].replace(/\.$/, '').replace(/doi:10\.\S+$/, '').slice(0, 80)), 'source ' + i + ' printed as recorded');
  }
  assert.ok(has('Die Rechnung liefert für den Planeten Merkur ein Vorschreiten des Perihels um 43″ in hundert Jahren'));
  assert.ok(has('really exists, and is indeed larger than he supposed'));
  assert.ok(has('The page does not compare') && has('as two measurements of one number'));
  assert.ok(has('later called Vulcan') && has('The name Vulcan appears in neither this letter nor his 1860 reply below'));
  assert.equal(VERDICT.decision_year - VERDICT.claim_year, 23);
  if (record && !REGEN) {
    assert.deepEqual(record.verdict, { category: VERDICT.category, as_of: VERDICT.as_of, sources: [...VERDICT.sources], would_change: VERDICT.would_change });
    assert.equal(record.decided_by, VERDICT.decided_by); assert.equal(record.years_to_decision, 23);
  }
});
test('verdict', 'the quotations the page prints are in the page’s record of its sources', () => {
  for (const q of ['il a suffi d’augmenter de 38 secondes le mouvement séculaire du périhélie', 'Je n’ai nullement l’intention de décider d’une manière absolue entre ces hypothèses',
    'la masse cherchée serait égale à celle de Mercure', 'The existence of this discrepancy, at least when the mass of Venus determined in other ways is employed, has been placed beyond doubt',
    'It follows that the observed centennial motion of the perihelion of Mercury is greater by 43″', 'we should regard this probable error as quite illusory',
    'masse beaucoup trop petite, à la distance où elle est placée, pour produire la totalité de l’anomalie', 'doit être admise dans la science']) assert.ok(has(q), 'quoted: ' + q);
  assert.ok(NC.illusory_p464.includes('quite illusory')); assert.ok(NC.verdict_p472.includes('really exists'));
  assert.ok(REF.leverrier_1860.words.includes('masse beaucoup trop petite'));
});

// ================================================================== record.json
function makeRecord(ledger) {
  const nf = NULL;
  return {
    slug: S.SLUG, title: S.TITLE, href: '/strata/' + S.SLUG + '/', field: 'celestial mechanics',
    claim: {
      statement: 'Mais, ce qui est remarquable, c’est qu’il a suffi d’augmenter de 38 secondes le mouvement séculaire du périhélie pour représenter toutes les observations des passages à moins d’une seconde près, et même la plupart d’entre elles à moins d’une demi-seconde.',
      claimants: 'U.-J. Le Verrier',
      citation: 'U.-J. Le Verrier, Lettre de M. Le Verrier à M. Faye sur la théorie de Mercure et sur le mouvement du périhélie de cette planète, Comptes rendus hebdomadaires des séances de l’Académie des sciences 49 (séance du 12 septembre 1859), pp. 379-383 (p. 380); full reduction: Théorie du mouvement de Mercure, Annales de l’Observatoire impérial de Paris, Mémoires, t. V (1859), pp. 1-196, ADS 1859AnPar...5....1L (pp. 79-100)',
      year: 1859,
      headline_as_printed: 'CRAS 49, p. 380: augmenter de 38 secondes le mouvement séculaire du périhélie; Annales t. V, p. 96: π′ = +0″,383 − 2,72 e′ − 0,001 67 τ − 0″,033 ν + 0,87 δn″; p. 100: (A) 288″ ν′ + 87″ ν″ = 38″,3',
    },
    records: [
      { file: FILES.claimant, role: 'claimant-data', name: 'Le Verrier’s 21 equations of condition from the transits of Mercury (Annales t. V, p. 80), his printed eliminations (I) to (VII), residual table and adopted values (pp. 79-100), typed from the ADS scan', url: 'https://articles.adsabs.harvard.edu/pdf/1859AnPar...5....1L', licence: 'Transcribed numbers and short quotations of an 1859 work whose author died in 1877; the ADS scan itself is not redistributed (ADS terms)', licence_url: 'https://adsabs.harvard.edu/use.html', retrieved: '2026-09-23', sha256: hashes[FILES.claimant], units: LV.equations.length },
      { file: FILES.control, role: 'control-data', name: 'Newcomb’s 58 equations of condition (pp. 457-458) with weights and rejections, his printed normal equations (p. 459), solution (p. 460) and chain to the excess (pp. 463-473), typed from the page images', url: 'https://archive.org/details/astronomicalpap00newcgoog', licence: 'Transcribed numbers and short quotations; the 1882 volume is marked NOT_IN_COPYRIGHT at the Internet Archive', licence_url: 'https://archive.org/metadata/astronomicalpap00newcgoog', retrieved: '2026-09-23', sha256: hashes[FILES.control], units: NC.equations.length },
      { file: FILES.reference, role: 'reference', name: 'Modern constants for the page’s own arithmetic (NASA planetary fact sheets, the SI value of c), Le Verrier’s 1860 figures for Lescarbault’s body, and the published numbers the verdict cites', url: 'https://nssdc.gsfc.nasa.gov/planetary/factsheet/mercuryfact.html', licence: 'Facts from a NASA page (US government work) and short citations of published numbers', licence_url: 'https://www.nasa.gov/nasa-brand-center/images-and-media/', retrieved: '2026-09-23', sha256: hashes[FILES.reference], units: 1 },
    ],
    anchor: {
      what: 'Le Verrier’s own claim, rebuilt: his 21 equations of condition solved by Cauchy’s elimination as he did it (his multiplier set, a reconstruction that reproduces all 8 printed values of his step IV), then his p. 96 adopted values substituted, through the page’s lvSolve',
      expected: 'as printed: 38.3 arcseconds a century (Annales p. 100, equation A; +0″.383 a year, p. 96); 38 in the letter (CRAS 49, p. 380)',
      computed: F['lv.head'] + ' arcseconds a century (his own printed step IV at the same values gives ' + F['lv.printedIV'] + '; the 21 contacts then miss by at most ' + F['lv.max1'] + '″, rms ' + F['lv.rms1'] + '″)',
      agrees: Math.abs(head.perCentury - claim) <= ANCHOR_TOL,
      tolerance: ANCHOR_TOL + ' arcseconds a century: his intermediate equations carry his own rounding, the letter prints the integer 38, and perturbing every coefficient of the record within half a unit of its last printed digit moves the page’s value by ' + F['lv.roundSd'] + ' (one standard deviation)',
    },
    control: {
      name: 'Newcomb’s 1882 re-reduction of every observed transit of Mercury to 1881, including four transits after Le Verrier’s (1861, 1868, 1878, 1881), by least squares on his 54 accepted equations of condition, then his chain from V′ and W′ to the excess p with the mass of Venus at 1/405,000',
      citation: 'Simon Newcomb, Discussion of Observed Transits of Mercury, 1677-1881, Astronomical Papers prepared for the use of the American Ephemeris and Nautical Almanac, vol. 1, part VI, pp. 363-487, Washington: Bureau of Navigation, 1882',
      computed: 'p = ' + F['nc.p'] + ' arcseconds a century (V′ ' + F['nc.V1'] + ', W′ ' + F['nc.W1'] + ' at k = 0; formal standard error ' + F['nc.sig'] + ', jackknife over transits ' + F['nc.jack'] + '); with k = 0.295, ' + F['nc.pk'],
      as_printed: 'δn = + 0″.37, p = + 42.95 (p. 473): the observed centennial motion of the perihelion of Mercury is greater by 43″ than the theoretical motion; V′ = −2.63, W′ = +1.84 at k = 0 (p. 460)',
    },
    power: {
      grade: 'A-injection',
      planted: 'Into a copy of Newcomb’s 58 equations of condition: first −42.95 (his printed excess) to empty it, then +' + claim + ' (Le Verrier’s printed claim, read from the claimant file), each through the absolute terms of every November row by its V′ coefficient times −0.487 dp and every May row by its W′ coefficient times +0.284 dp (his equations a and b, p. 467), then the unmodified newcombControl',
      recovered: 'emptied: ' + F['pw.empty'] + ' (' + F['pw.zEmpty'] + ' formal errors from zero); planted: ' + F['pw.recovered'] + ', ' + F['pw.zF'] + ' formal and ' + F['pw.zJ'] + ' jackknife standard errors from zero. The control is linear in its absolute terms, so the recovery itself is guaranteed once the plant is wired correctly; the information is in the two distances from zero. By the same rule the smallest excess the control could have confirmed is ' + F['pw.min'] + ' arcseconds a century',
      verdict: pw.couldConfirm ? 'the control COULD have confirmed the claim: recovered within ' + E.POWER_RULE.tol + ' of the planted size and at least ' + E.POWER_RULE.z + ' standard errors from zero by both the formal and the jackknife error' : 'the control could NOT have confirmed it, and the page says inconclusive',
    },
    null_through_claimant_method: {
      applicable: true,
      what: 'Le Verrier’s own 21 coefficient rows unchanged, constants replaced by his fitted model with the perihelion excess set to zero plus noise resampled from his own 21 residuals (random signs, scaled up by ' + F['nl.infl'] + ', the square root of 21/17, for the four unknowns fitted, and multiplied by 13/8 in May rows), through the same lvSolve and p. 96 values as the anchor; then a systematic error per transit (the same for both contacts of a transit) added to find the size at which his procedure manufactures the claim',
      result: 'in ' + F['nl.draws'] + ' null records (seed ' + NULL_SEED + ') the procedure reported a standard deviation of ' + F['nl.sd'] + ' and at most ' + F['nl.max'] + ' arcseconds a century; ' + nf.countGE + ' reached ' + claim + '. With a systematic error per transit it reaches the claim in ' + F['nl.r2'] + ' at 2″, ' + F['nl.r5'] + ' at 5″ and ' + F['nl.r10'] + ' at 10″, and one time in twenty at ' + F['nl.sigma5'] + '″; the cheapest single transit, ' + F['nl.cheapYear'] + ', would have to be wrong by ' + F['nl.cheapNeed'] + '″',
    },
    verdict: { category: VERDICT.category, as_of: VERDICT.as_of, sources: [...VERDICT.sources], would_change: VERDICT.would_change },
    decided_by: VERDICT.decided_by,
    years_to_decision: VERDICT.decision_year - VERDICT.claim_year,
    choices: CHOICES,
    headline: X.HEADLINE,
    novelty: NOVELTY,
    ledger,
  };
}
const ASSERTIONS = {
  claim_reproduced: 'anchor:leverrier-21-equations-cauchy-lvSolve-38.44-vs-38.3',
  control_computed: 'control:newcomb-54-equations-least-squares-p-42.93-vs-42.95',
  control_can_confirm: 'power:claim-planted-into-newcomb-equations-of-condition-recovered',
  rendered_figures_asserted: 'surface:data-fig-spans-head-frontmatter-and-literal-inventory',
  choices_are_live: 'choices:eleven-each-moves-a-named-output',
  planted_fault_caught: 'fault:doctored-records-figures-literals-and-bytes',
  refusal_asserted: 'refuse:plant-beyond-100-inner-planet-outside-mercury-no-pivot',
  provenance_pinned: 'provenance:sha256-in-data-readme-record',
  verdict_dated: 'verdict:category-date-scope-sources-printed-and-null-asserted',
};
const group = (name) => results.some((t) => t.group === name) && results.filter((t) => t.group === name).every((t) => t.pass);
const ledger = {
  claim_reproduced: group('anchor'),
  control_computed: group('control'),
  control_can_confirm: group('power'),
  rendered_figures_asserted: group('surface'),
  choices_are_live: group('choices'),
  planted_fault_caught: group('fault'),
  refusal_asserted: group('refusal'),
  provenance_pinned: group('provenance'),
  verdict_dated: group('verdict') && group('null'),
};
const expected = makeRecord(Object.fromEntries(Object.entries(ledger).map(([k, v]) => [k, { value: v, assertion: ASSERTIONS[k] }])));
if (REGEN) {
  const failing = results.filter((t) => !t.pass);
  if (failing.length) { for (const f of failing) console.error('FAIL ' + f.group + ': ' + f.name + '\n  ' + f.error); throw new Error('Refusing to write record.json while assertions fail.'); }
  fs.writeFileSync(recordPath, JSON.stringify(expected, null, 2) + '\n');
  fs.writeFileSync(literalsPath, JSON.stringify(S.literalNumbers(html).map((l) => l.n)) + '\n');
  console.log('wrote record.json and surface-literals.json');
}
test('manifest', 'record.json equals the manifest built from this run’s own results', () => {
  assert.ok(fs.existsSync(recordPath), 'record.json missing');
  assert.deepEqual(JSON.parse(fs.readFileSync(recordPath, 'utf8')), expected);
});

const failures = results.filter((t) => !t.pass);
for (const f of failures) console.error('FAIL ' + f.group + ': ' + f.name + '\n  ' + f.error);
if (LEDGER) for (const [k, v] of Object.entries(ledger)) console.log(k + '=' + v);
else console.log((results.length - failures.length) + '/' + results.length + ' assertions passed.');
if (failures.length) process.exitCode = 1;
