#!/usr/bin/env node
// verify-the-dimming-that-turned-around.mjs: recomputes every number the page shows from the two frozen
// files, checks the shipped page, frontmatter, head tags, JSON-LD and record.json against the
// recomputation, and exits non-zero on any disagreement.
//
//   node research/the-dimming-that-turned-around/verify-the-dimming-that-turned-around.mjs            # every assertion
//   node research/the-dimming-that-turned-around/verify-the-dimming-that-turned-around.mjs --ledger   # the nine ledger cells
//   node research/the-dimming-that-turned-around/verify-the-dimming-that-turned-around.mjs --regen    # rewrite record.json and
//        the literal inventory, only if every other assertion passes. It never rewrites a data file.
//
// Two kinds of check are kept apart. The page's own functions are run on the frozen data and on doctored
// copies of it. And the headline quantities are recomputed a second time here, by independent code that
// shares nothing with engine.js (its own distance integral, its own offset fit, its own grid), 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 { spawnSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import * as E from '../../public/strata/the-dimming-that-turned-around/engine.js';
import * as FG from '../../public/strata/the-dimming-that-turned-around/figures.js';
import { VERDICT, EXCHANGE, DESI, PREPRINT_NOTE, NOVELTY, FORBIDDEN } from '../../public/strata/the-dimming-that-turned-around/readings.js';
import { FILES, SHA256, load as loadPinned } from '../../public/strata/the-dimming-that-turned-around/data.js';
import { pathToFileURL } from 'node:url';
import * as S from './surface.mjs';
import * as H from './html-parts.mjs';

// The site's chrome writers inject marked blocks and a banner script into every shipped page after the
// build; this verifier checks the page's own content, so it reads the page with those 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 D98 = JSON.parse(read(FILES.d98));
const D04 = JSON.parse(read(FILES.d04));
const readme = fs.readFileSync(path.join(here, 'README.md'), 'utf8');
const recordPath = path.join(dir, 'record.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 sha = buf => crypto.createHash('sha256').update(buf).digest('hex');

// ------------------------------------------------------------------ the computation, once
const ctx = FG.computeAll(D98, D04);
const F = FG.figures(ctx);
const X = S.texts(F);
const res = ctx.res;
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 mdBody = md.slice(md.indexOf('\n---', 4) + 4).trim();
const meta = (attr, name) => { const m = html.match(new RegExp('<meta ' + attr + '="' + name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '" content="([^"]*)"')); return m ? 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 qn = t => t.replace(/[‘’]/g, "'").replace(/[“”]/g, '"').replace(/\s+/g, ' ');
const has = s => qn(fullVisible).includes(qn(s));
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;
}

// ------------------------------------------------------------------ independent arithmetic
// A second distance function: composite Simpson on a fine uniform grid, its own curvature handling.
function indepMu(z, Om, OL, steps = 2000) {
  const Ok = 1 - Om - OL, h = z / steps;
  const f = x => 1 / Math.sqrt(Om * (1 + x) ** 3 + Ok * (1 + x) ** 2 + OL);
  let s = f(0) + f(z);
  for (let i = 1; i < steps; i++) s += (i % 2 ? 4 : 2) * f(i * h);
  const I = s * h / 3;
  const d = Math.abs(Ok) < 1e-12 ? I : Ok > 0 ? Math.sinh(Math.sqrt(Ok) * I) / Math.sqrt(Ok) : Math.sin(Math.sqrt(-Ok) * I) / Math.sqrt(-Ok);
  return 5 * Math.log10((1 + z) * d);
}
function indepOffsetChi2(ys, ws, ms) {
  let a = 0, b = 0; for (let i = 0; i < ys.length; i++) { a += ws[i] * (ys[i] - ms[i]); b += ws[i]; }
  const o = a / b; let c = 0; for (let i = 0; i < ys.length; i++) c += ws[i] * (ys[i] - ms[i] - o) ** 2;
  return { chi2: c, off: o };
}
const C = 299792.458;
// the 1998 light-curve rows, built directly from the frozen tables
function indepRows98(method, withCk) {
  const T = D98.tables, b = new Set(T.t1.rows.filter(r => r.zsrc === 'b').map(r => r.sn)), a = new Set(T.t1.rows.filter(r => r.zsrc === 'a').map(r => r.sn));
  const vel = (sn, z) => (5 / Math.log(10)) * Math.sqrt(200 ** 2 + (b.has(sn) && !a.has(sn) ? 2500 ** 2 : 0)) / (C * z);
  const near = T.t10.rows.map(r => { const z = 10 ** r.logcz / C, v = r[method]; return { sn: r.sn, z, mu: v[0], w: 1 / (v[1] ** 2 + vel(r.sn, z) ** 2) }; });
  const high = (method === 'mlcs' ? T.t5 : T.t6).rows.filter(r => withCk || r.sn !== '1997ck').map(r => ({ sn: r.sn, z: r.z, mu: r.mu0, w: 1 / (r.sig ** 2 + vel(r.sn, r.z) ** 2) }));
  const snap = [...T.t9.rows.map(r => ({ sn: r.sn, z: 10 ** r.logcz / C, mu: r.mu0, sig: r.sig })), ...T.t7.rows.map(r => ({ sn: r.sn, z: r.z, mu: r.mu0, sig: r.sig }))].map(r => ({ ...r, w: 1 / (r.sig ** 2 + vel(r.sn, r.z) ** 2) }));
  return { lc: [...near, ...high], snap };
}
// an independent 1998 posterior on its own coarser grid (0.025), cell centres, own big-bang test
function indepP98() {
  const { lc, snap } = indepRows98('mlcs', false);
  const zsl = [...new Set([...lc, ...snap].map(r => r.z))].sort((x, y) => x - y);
  const grid = [];
  for (let Om = 0.0125; Om < 2.5; Om += 0.025) for (let OL = -0.9875; OL < 3; OL += 0.025) grid.push([Om, OL]);
  const bb = (Om, OL) => { for (let a = 1; a < 60; a *= 1.02) if (Om * a ** 3 + (1 - Om - OL) * a * a + OL <= 0) return false; return true; };
  let Z = 0, Zq = 0, ZL = 0; const dens = [];
  let best = Infinity;
  for (const [Om, OL] of grid) {
    if (!bb(Om, OL)) continue;
    const mu = new Map(); let ok = true;
    // cumulative trapezoid on dz = 0.0005
    let I = 0, zc = 0; const Ok = 1 - Om - OL;
    const f = x => { const e = Om * (1 + x) ** 3 + Ok * (1 + x) ** 2 + OL; if (e <= 0) ok = false; return 1 / Math.sqrt(Math.max(e, 1e-300)); };
    for (const z of zsl) {
      const n = Math.max(1, Math.ceil((z - zc) / 0.0005)), h = (z - zc) / n;
      for (let i = 0; i < n; i++) I += h * (f(zc + i * h) + f(zc + (i + 1) * h)) / 2;
      zc = z;
      const d = Math.abs(Ok) < 1e-12 ? I : Ok > 0 ? Math.sinh(Math.sqrt(Ok) * I) / Math.sqrt(Ok) : Math.sin(Math.sqrt(-Ok) * I) / Math.sqrt(-Ok);
      if (!(d > 0)) ok = false;
      mu.set(z, 5 * Math.log10((1 + z) * d));
    }
    if (!ok) continue;
    const A = indepOffsetChi2(lc.map(r => r.mu), lc.map(r => r.w), lc.map(r => mu.get(r.z)));
    const B = indepOffsetChi2(snap.map(r => r.mu), snap.map(r => r.w), snap.map(r => mu.get(r.z)));
    const chi = A.chi2 + B.chi2, lj = -(Math.log(10) / 5) * (A.off + B.off);
    dens.push([Om, OL, chi, lj]); if (chi < best) best = chi;
  }
  const lj0 = Math.max(...dens.map(d => d[3]));
  for (const [Om, OL, chi, lj] of dens) { const d = Math.exp(-(chi - best) / 2 + lj - lj0); Z += d; if (OL >= Om / 2) Zq += d; if (OL >= 0) ZL += d; }
  return { pq: Zq / Z, pL: ZL / Z };
}

// An independent kinematic posterior: q(z) = q0 + z dq/dz in a flat universe, H = H0 (1+z)^(1+q0-dq/dz)
// exp(z dq/dz), its own composite Simpson distance integral, its own grid (cells 0.05 by 0.1 over the same
// box), the offset profiled out and flat in the offset. It shares no code with engine.js's prepareKin or
// kinematic, which produce every quadrant probability on the page.
function indepKinQuadrant(rows) {
  const zs = [...new Set(rows.map(r => r.z))].sort((a, b) => a - b), at = new Map(zs.map((z, k) => [z, k]));
  const y = rows.map(r => r.mu), w = rows.map(r => r.w), zi = rows.map(r => at.get(r.z));
  const cells = [];
  let best = Infinity;
  for (let q0 = -2.375; q0 < 1.6; q0 += 0.05) for (let q1 = -3.95; q1 < 6; q1 += 0.1) {
    const f = z => Math.pow(1 + z, -(1 + q0 - q1)) * Math.exp(-q1 * z);
    const mu = new Float64Array(zs.length);
    let I = 0, zc = 0;
    zs.forEach((z, k) => {
      const n = 2 * Math.max(1, Math.ceil((z - zc) / 0.008)), h = (z - zc) / n;
      let s = f(zc) + f(z);
      for (let i = 1; i < n; i++) s += (i % 2 ? 4 : 2) * f(zc + i * h);
      I += s * h / 3; zc = z;
      mu[k] = 5 * Math.log10((1 + z) * I);
    });
    const c = indepOffsetChi2(y, w, zi.map(k => mu[k])).chi2;
    cells.push([q0, q1, c]); if (c < best) best = c;
  }
  let Z = 0, Zq = 0;
  for (const [q0, q1, c] of cells) { const d = Math.exp(-(c - best) / 2); Z += d; if (q0 < 0 && q1 > 0) Zq += d; }
  return Zq / Z;
}
// An independent best flat LambdaCDM chi2 (own distances, own offset fit, a fine scan in OmegaM).
function indepFlatChi2(rows) {
  let best = Infinity;
  for (let Om = 0.2; Om <= 0.42; Om += 0.0005) best = Math.min(best, indepOffsetChi2(rows.map(r => r.mu), rows.map(r => r.w), rows.map(r => indepMu(r.z, Om, 1 - Om, 400))).chi2);
  return best;
}
// The page's own pin check, data.js load(), run on the frozen bytes and on a copy with one byte changed,
// through a stubbed fetch that serves the files from disk.
async function pinCheck(mutate) {
  const saved = globalThis.fetch;
  globalThis.fetch = async u => {
    const name = path.basename(new URL(u).pathname);
    let buf = Buffer.from(fs.readFileSync(path.join(dir, name)));
    if (mutate && name === FILES.d04) buf = mutate(buf);
    return new Response(buf);
  };
  try { return await loadPinned(pathToFileURL(dir + '/')); } finally { globalThis.fetch = saved; }
}
const pinClean = await pinCheck(null);
const pinTampered = await pinCheck(buf => { const i = buf.indexOf(Buffer.from('45.53')); buf[i + 4] = '4'.charCodeAt(0); return buf; });

// ================================================================== anchor: the claim at full strength
test('anchor', 'the frozen 1998 file holds the tables and the printed numbers the page compares against', () => {
  const T = D98.tables;
  assert.deepEqual([T.t1.rows.length, T.t5.rows.length, T.t6.rows.length, T.t7.rows.length, T.t9.rows.length, T.t10.rows.length], [14, 10, 10, 6, 7, 27]);
  assert.equal(D98.kind, 'transcribed'); assert.equal(D98.source.pdf_sha256, '5edf2da6f5ff6438649e818e82ea86c7a168fbe1294fa165a252f9640b24e039');
  const r5 = Object.fromEntries(T.t5.rows.map(r => [r.sn, r]));
  assert.deepEqual([r5['1996E'].mu0, r5['1996E'].sig, r5['1997ck'].z, r5['1997ck'].mu0, r5['1995K'].mu0], [41.74, 0.28, 0.97, 44.39, 42.45]);
  assert.deepEqual(T.t10.rows.find(r => r.sn === '1992bo').mlcs, [34.72, 0.16]);
  assert.deepEqual(T.t7.rows.map(r => r.z), [0.3, 0.23, 0.16, 0.24, 0.17, 0.83], 'Table 7 redshifts as printed');
  assert.equal(D98.printed.meanExcess.mlcs, 0.25); assert.equal(D98.printed.meanExcess.template, 0.28);
  assert.equal(D98.printed.quotes.fig4_caption.page, 35); assert.equal(D98.printed.quotes.discussion_mag.page, 18);
  assert.equal(D98.printed.table8.rows[0].pq[1], 99.5); assert.equal(D98.printed.table8.rows[4].H0[0], 65.2);
});
test('anchor', 'the page engine reproduces the printed 0.25 mag within 0.01, and the template 0.28 within 0.02 (stronger)', () => {
  const c = res.c98;
  near(c.excess.mean, D98.printed.meanExcess.mlcs, 0.01, 'MLCS mean excess');
  assert.equal(c.excess.n, 10, 'the ten high-z supernovae of Figure 4, SN 1997ck included');
  near(c.fit.H0, D98.printed.H0.mlcs[0], 0.1, 'H0 at the best fit');
  near(c.fit.chi2, 40.29, 0.02, 'chi2 of the MLCS(9) best fit');
  near(res.c98tpl.excess.mean, D98.printed.meanExcess.template, 0.025, 'template mean excess');
  assert.ok(res.c98tpl.excess.mean > D98.printed.meanExcess.template, 'the template reproduction is stronger than printed, as the page says');
  near(res.c98nock.excess.mean, 0.226, 0.001);
  assert.equal(F['a98.excess'], c.excess.mean.toFixed(3)); assert.equal(F['a98.pct'], c.excess.pctFarther.toFixed(1));
});
test('anchor', 'an independent implementation recomputes the mean excess and H0 from the frozen tables', () => {
  const { lc } = indepRows98('mlcs', false);
  // best fit located on a fine grid around the engine's, by independent code
  let best = null;
  for (let Om = 0; Om <= 0.4; Om += 0.005) for (let OL = 0.3; OL <= 0.8; OL += 0.005) {
    const r = indepOffsetChi2(lc.map(x => x.mu), lc.map(x => x.w), lc.map(x => indepMu(x.z, Om, OL, 200)));
    if (!best || r.chi2 < best.chi2) best = { ...r, Om, OL };
  }
  const H0 = C / 10 ** ((best.off - 25) / 5);
  near(H0, res.c98.fit.H0, 0.1, 'independent H0');
  const hz = D98.tables.t5.rows;
  const mean = hz.reduce((s, r) => s + (r.mu0 - indepMu(r.z, 0.2, 0) - best.off), 0) / hz.length;
  near(mean, res.c98.excess.mean, 0.003, 'independent mean excess');
  near(mean, 0.25, 0.01, 'independent mean excess against the printed 0.25');
});
test('anchor', 'a corrupted claimant record fails the same anchor', () => {
  near(res.anchorFault, 0, 0.05, 'Table 5 reduced by 0.25 mag');
  assert.ok(Math.abs(res.anchorFault - 0.25) > 0.01);
  const bad = clone(D98); bad.tables.t5.rows[1].mu0 += 1.0;
  const r = E.claim1998(bad, ctx.P, {});
  const dm = r.excess.mean - res.c98.excess.mean;
  assert.ok(dm > 0.08 && dm < 0.16, 'one supernova moved by 1 mag moves the mean by about a tenth (the refit zero point moves too): ' + dm);
  const bad2 = clone(D98); bad2.tables.t10.rows.forEach(x => { x.mlcs[0] += 0.3; });
  assert.ok(Math.abs(E.claim1998(bad2, ctx.P, {}).excess.mean - res.c98.excess.mean) > 0.2, 'a shifted nearby zero point moves the anchor');
});
test('anchor', 'the significance is reproduced weaker than printed, both are printed, and rounding does not explain the gap', () => {
  const p = D98.printed.table8.rows[0];
  assert.ok(res.c98.L.pq < p.pq[1] / 100 && res.c98.L.pL < p.pL[1] / 100, 'weaker than printed');
  assert.ok(p.pq[1] - 100 * res.c98.L.pq < 0.5, 'within half a percentage point');
  near(E.sigmaTwoSided(0.995), 2.807, 0.002, 'the paper\'s sigma convention');
  assert.ok(100 * res.round.sdPq < (p.pq[1] - 100 * res.c98.L.pq) / 2, 'table rounding moves p(q0<=0) by less than half the gap');
  assert.ok(res.round.maxPq < p.pq[1] / 100, 'no rounding draw reaches the printed value');
  assert.ok(has('≤ 0) = ' + F['a98.pq']), 'the page prints p(q0 ≤ 0) = ' + F['a98.pq']);
  assert.ok(html.includes('data-fig="a98.pqPrinted"') && html.includes('data-fig="a98.pq"'), 'both numbers are printed');
  const ind = indepP98();
  near(ind.pq, res.c98.L.pq, 0.003, 'independent grid p(q0<=0)');
  near(ind.pL, res.c98.L.pL, 0.003, 'independent grid p(OmegaL>=0)');
});
test('anchor', 'every row of Table 8 is recomputed within a point of print, and 17 of its 18 probabilities come out weaker, as the page says', () => {
  assert.equal(res.t8.length, 9);
  for (const t of res.t8) {
    for (const [k, pr] of [['pL', t.row.pL], ['pq', t.row.pq]]) {
      if (pr[0] === '>') assert.ok(t[k] > 0.999, t.row.row + ' ' + k + ' should exceed 99.9%');
      else near(100 * t[k], pr[1], 1.0, t.row.row + ' ' + k);
    }
    if (t.row.H0) near(t.H0, t.row.H0[0], 0.6, t.row.row + ' H0');
  }
  const cmp = FG.table8Compare(res.t8);
  assert.equal(cmp.length, 18);
  const stronger = cmp.filter(c => !c.weaker);
  assert.deepEqual(stronger.map(c => c.row + ' ' + c.k), ['MLCS+Snap.+97ck(16) pL'], 'the one probability that comes out stronger, named on the page');
  assert.ok(has('and one, p(ΩΛ ≥ 0) for MLCS+Snap.+97ck(16), comes out'));
  assert.ok(cmp.filter(c => c.bound).every(c => c.agrees && c.weaker), 'the >99.9% entries agree with the bound and fall short of their printed sigma');
  assert.ok(cmp.filter(c => c.weaker).every(c => c.gap > 0 && c.gap < 0.25), 'every weaker entry is within a quarter of a sigma');
  assert.ok(!has('weaker by roughly a tenth of a sigma') && !has('in every row of Table 8'), 'the page no longer says every row is weaker');
});

// ================================================================== control: the deciding control, recomputed
test('control', 'the frozen 2004 table: 186 rows, 157 gold, the TeX values, the printed Table 4', () => {
  assert.equal(D04.rows.length, 186); assert.equal(D04.rows.filter(r => r.sample === 'gold').length, 157);
  assert.equal(new Set(D04.rows.map(r => r.sn)).size, 186);
  const r = Object.fromEntries(D04.rows.map(x => [x.sn, x]));
  assert.deepEqual([r['1997ff'].z, r['1997ff'].mu0, r['1997ff'].sig, r['1990T'].mu0, r['1991ag'].sample, r['2003lv'].z], [1.755, 45.53, 0.35, 36.38, 'gold', 0.94]);
  assert.deepEqual(D04.printed.table4.rows.map(x => x.chi2), [178, 325, 192, 307, 175, 253]);
  assert.equal(D04.printed.hstDiscovered.names.length, 16);
  assert.equal(D04.source.tex_sha256, '8de8c0911abb01ca5b55af54f2e84b4b62289d9bb886f525e27ed755bc4c6dbf');
});
test('control', 'Table 4 reproduces: cosmologies within 0.5 of print, tuned astrophysical models within 8', () => {
  const g = res.gold.t4, T4 = Object.fromEntries(D04.printed.table4.rows.map(x => [x.id, x.chi2]));
  for (const id of ['lcdm', 'eds', 'empty']) near(g[id], T4[id], 0.5, id);
  for (const id of ['highzdust', 'replenishing', 'propz']) near(g[id], T4[id], 8, id);
  near(g.A05, 0.479, 0.001, 'the tuned dimming at z = 0.5'); assert.equal(g.nBin, 38);
  near(res.replEq.replenishing, 175.4, 0.05, 'the equation read literally');
  near(res.replEqC.replenishing, 212.75, 0.05, 'the equation with continuous density');
});
test('control', 'an independent implementation recomputes the three cosmologies of Table 4', () => {
  const gold = D04.rows.filter(r => r.sample === 'gold');
  for (const [Om, OL, id] of [[0.27, 0.73, 'lcdm'], [1, 0, 'eds'], [0, 0, 'empty']]) {
    const r = indepOffsetChi2(gold.map(x => x.mu0), gold.map(x => 1 / x.sig ** 2), gold.map(x => indepMu(x.z, Om, OL, 600)));
    near(r.chi2, res.gold.t4[id], 0.01, 'independent ' + id);
  }
});
test('control', 'the kinematic distance agrees with its closed form, and the quadrant, transition and flat fit reproduce', () => {
  for (const q0 of [-0.8, -0.3, 0.4]) {
    const zs = [0.1, 0.5, 1.0, 1.755];
    const mu = E.muKin(zs, q0, 0);
    zs.forEach((z, i) => near(mu[i], 5 * Math.log10((1 + z) * ((1 + z) ** (-q0) - 1) / (-q0)), 1e-8, 'closed form, q0 ' + q0));
  }
  const k = res.gold.kin;
  assert.ok(k.quadrant >= 0.992, 'quadrant at least the printed 99.2%');
  near(k.zt.best, 0.46, 0.13, 'transition within the printed interval');
  near(k.best.q0, -0.75, 0.05); near(k.best.q1, 1.65, 0.1);
  assert.ok(res.gold.flat.Om >= 0.26 && res.gold.flat.Om <= 0.34, 'flat OmegaM inside the printed 0.29 (+0.05, -0.03)');
  near(res.gold.t4.lcdm / 157, 1.13, 0.006, 'chi2/dof reproduces section 4.2');
  assert.ok(res.gs.kin.quadrant >= 0.998);
  assert.ok(k.edgeMass < 1e-6, 'the prior box holds the posterior');
});
test('control', 'the abstract\'s chi2dof = 1.06 is not reproduced at the model it names, by the engine or by independent code', () => {
  const gold = D04.rows.filter(r => r.sample === 'gold');
  const r = indepOffsetChi2(gold.map(x => x.mu0), gold.map(x => 1 / x.sig ** 2), gold.map(x => indepMu(x.z, 0.3, 0.7, 600)));
  near(r.chi2, res.concord, 0.01, 'independent chi2 at (0.3, 0.7)');
  assert.ok(res.concord / 157 > 1.1, 'far from 1.06');
  assert.equal(F['c.chi2Concord'], res.concord.toFixed(2));
});
test('control', 'an independent kinematic posterior reproduces the quadrant probability of the real rows and of three planted copies', () => {
  const pairs = [['real', ctx.gold], ...['lookback', 'highzdust', 'claim'].map(m => [m, E.plant(ctx.gold, { model: m, sizeMag: 0.25 }).rows])];
  for (const [name, rows] of pairs) {
    const eng = E.kinematic(ctx.K, rows, { h0prior: 'flat-offset' }).quadrant;
    near(indepKinQuadrant(rows), eng, 0.001, 'independent quadrant, ' + name);
  }
  near(E.kinematic(ctx.K, ctx.gold, { h0prior: 'flat-offset' }).quadrant, res.kinOff.quadrant, 1e-12);
});
test('control', 'the quadrant probability does not depend on the prior box or the grid', () => {
  const K2 = E.prepareKin(D04.rows.map(r => r.z), { q0: { lo: -3.2, hi: 2.4, step: 0.08 }, q1: { lo: -6, hi: 9, step: 0.12 } });
  const k2 = E.kinematic(K2, ctx.gold);
  near(k2.quadrant, res.gold.kin.quadrant, 0.001, 'wider box, coarser grid');
});
test('control', 'the leave-outs: the z > 1 supernovae multiply the case against the objections; the 1998 supernovae are not needed', () => {
  const L = res.leave;
  assert.equal(L.hst.removed, 14); assert.equal(L.beyond1.removed, 9); assert.equal(L.claimants1998.removed, 11); assert.equal(L.all1998.removed, 36);
  assert.equal(ctx.names1998.length, 16); assert.equal(ctx.names1998near.length, 34); assert.equal(ctx.names1998all.length, 50);
  const g157 = new Set(ctx.gold.map(r => r.sn));
  assert.equal(ctx.names1998.filter(n => g157.has(n)).length, 11, 'high-redshift 1998 supernovae in the gold set');
  assert.equal(ctx.names1998near.filter(n => g157.has(n)).length, 25, 'nearby 1998 supernovae in the gold set');
  assert.ok(L.all1998.r.dchi2.highzdust > 100 && L.all1998.r.dchi2.propz > 60, 'without every 1998 supernova the objections are still refused');
  assert.ok(L.all1998.r.kin.quadrant < FG.PRINTED_QUADRANT && L.all1998.r.kin.quadrant > 0.98, 'and the quadrant falls just under the printed 0.992, as the page says');
  assert.ok(has('just under the printed 0.992') && !has('the 1998 claimants’ 11'));
  assert.ok(L.beyond1.r.dchi2.highzdust < res.gold.dchi2.highzdust / 2.5, 'grey dust Δχ² more than 2.5 times larger with them');
  assert.ok(L.beyond1.r.kin.quadrant > 0.99, 'the quadrant does not need them');
  near(L.claimants1998.r.dchi2.highzdust, res.gold.dchi2.highzdust, 2, 'without the 1998 supernovae');
});

// ================================================================== power: the control on the control
const plantOf = (m, size = 0.25) => E.plant(ctx.gold, { model: m, sizeMag: size });
test('power', 'the plant is a deep copy of the control\'s own rows, with the real residuals transplanted exactly', () => {
  const before = JSON.stringify(ctx.gold);
  for (const m of FG.PLANT_ORDER) {
    const p = plantOf(m);
    assert.equal(p.rows.length, 157);
    assert.notEqual(p.rows, ctx.gold); assert.notEqual(p.rows[0], ctx.gold[0]);
    const zs = E.uniqueSorted(ctx.gold.map(r => r.z)), idx = new Map(zs.map((z, k) => [z, k]));
    const fit = E.muFRW(zs, p.meta.refFit.Om, 1 - p.meta.refFit.Om), model = E.plantedMu(m, zs, { sizeMag: 0.25 });
    let worst = 0;
    p.rows.forEach((r, i) => {
      assert.equal(r.z, ctx.gold[i].z); assert.equal(r.w, ctx.gold[i].w); assert.equal(r.sn, ctx.gold[i].sn);
      worst = Math.max(worst, Math.abs((r.mu - model[idx.get(r.z)]) - (ctx.gold[i].mu - fit[idx.get(r.z)])));
    });
    assert.ok(worst < 1e-9, m + ': doctored residuals about the planted model equal the real residuals about the fit (' + worst + ')');
  }
  assert.equal(JSON.stringify(ctx.gold), before, 'the frozen rows are untouched');
  near(ctx.res.plants.claim.meta.refFit.Om, res.gold.flat.Om, 1e-9, 'the reference fit is the engine\'s own best flat fit');
});
test('power', 'the injection used the claimed size, 0.25 mag at z = 0.5, never weaker', () => {
  for (const m of ['claim', 'highzdust', 'propz', 'lookback']) {
    const p = plantOf(m);
    assert.equal(p.meta.injectedSizeMag, 0.25);
    near(p.meta.excessAt05, 0.25, 1e-9, m + ': excess over (0.2, 0) at z = 0.5');
  }
  near(res.plants.claim.meta.claimOm, 0.2185, 0.001);
  near(res.plants.lookback.meta.dimAt05, 0.463, 0.001);
  assert.equal(D98.printed.meanExcess.mlcs, 0.25, 'the size is the printed MLCS average');
  assert.ok(E.refusePlant({ model: 'claim', sizeMag: 0.2 }).refused, 'a size weaker than 10% farther is refused');
});
test('power', 'the plants go through the same runControl the page calls, and nothing is appended to a result', () => {
  for (const m of FG.PLANT_ORDER) {
    const direct = E.runControl(ctx.K, plantOf(m).rows, { skipFlat: true });
    assert.deepEqual({ q: direct.kin.quadrant, b: direct.kin.best, t: direct.t4.lcdm, d: direct.dchi2 }, { q: res.plants[m].r.kin.quadrant, b: res.plants[m].r.kin.best, t: res.plants[m].r.t4.lcdm, d: res.plants[m].r.dchi2 }, m);
  }
  const fsrc = read('figures.js'), psrc = read('page.js');
  assert.match(fsrc, /E\.plant\(gold, \{ model: m, sizeMag: 0\.25 \}\)[\s\S]{0,200}E\.runControl\(K, p\.rows/);
  assert.match(psrc, /E\.plant\(gold, \{ model: state\.plant, sizeMag: size\(\) \}\)[\s\S]{0,200}E\.runControl\(ctx\.K, p\.rows/);
  assert.ok(!/\.push\(\{[^}]*quadrant/.test(fsrc + psrc), 'no result is appended by hand');
});
test('power', 'grade A: the claim is recovered, both objections refused, dimming with lookback time indistinguishable', () => {
  const P = res.plants, line = FG.PRINTED_QUADRANT;
  assert.ok(P.claim.r.kin.quadrant >= line && P.claim.r.dchi2.highzdust >= 9 && P.claim.r.dchi2.propz >= 9, 'the claim recovered');
  near(P.claim.r.kin.zt.best, 0.56, 0.05);
  for (const m of ['highzdust', 'propz']) { assert.ok(P[m].r.kin.quadrant < line, m + ' quadrant'); assert.ok(-P[m].r.dchi2[m] >= 9, m + ': Λ worse than the planted rival'); }
  assert.ok(P.lookback.r.kin.quadrant >= 0.999, 'lookback reports acceleration after deceleration');
  near(P.lookback.r.kin.zt.best, 0.46, 0.03);
  assert.ok(Math.abs(P.lookback.r.dchi2.replenishing) < 4);
  assert.ok(P.eds.r.kin.quadrant < 0.5 && P.eds.r.kin.best.q0 > 0, 'nothing planted, matter only: no acceleration');
  const PR = FG.powerReading(res);
  assert.equal(PR.text, 'the control COULD have confirmed the claim, and could have refused it, against the two objections it was built for (gray dust at high redshift, dimming proportional to redshift); it could NOT distinguish the claim from dimming proportional to lookback time, and the page reports that comparison as inconclusive.');
  assert.ok(has(PR.text), 'the page prints the power verdict');
  assert.ok(has('Grade A · injection'), 'the page prints the grade');
});
test('power', 'at every printed size the kinematic half stays blind to lookback dimming, and the Table 4 half moves past the line at 0.28 and 0.303 mag', () => {
  const L = res.lookbackBySize;
  assert.equal(L.length, 4);
  assert.deepEqual({ q: L[1].kin.quadrant, d: L[1].dchi2 }, { q: res.plants.lookback.r.kin.quadrant, d: res.plants.lookback.r.dchi2 }, 'the 0.25 entry is the grade A plant');
  for (const r of L) assert.ok(r.kin.quadrant >= FG.PRINTED_QUADRANT, 'lookback reads as acceleration after deceleration at every size');
  assert.ok(Math.abs(L[0].dchi2.replenishing) < 4 && Math.abs(L[1].dchi2.replenishing) < 4, 'indistinguishable at 0.207 and 0.25');
  assert.ok(L[2].dchi2.replenishing < -4 && L[3].dchi2.replenishing < -4, 'replenishing dust preferred past the line at 0.28 and 0.303');
  // the reading at 0.303 mag, by the same rule, through the same functions the page's size control calls
  const plants = Object.fromEntries(FG.PLANT_ORDER.map(m => [m, { r: E.runControl(ctx.K, plantOf(m, E.SIZES[3]).rows, { skipFlat: true }) }]));
  assert.match(FG.powerReading({ plants }).text, /lookback time distinguished/);
  assert.ok(has('The control on the control, at the printed 0.25 mag') && has('with the real residuals transplanted (over fresh noise, see the next panel)'));
  assert.ok(has('dimming with lookback time is indistinguishable when the test reports acceleration after deceleration and replenishing dust'), 'the thresholds are stated');
  assert.match(read('page.js'), /FG\.powerReading\(\{ plants: Object\.fromEntries\(runs\) \}\)/, 'the size control recomputes the reading');
});
test('power', 'the power verdict can come out otherwise: a test blind to the claim is called inconclusive', () => {
  const fake = clone({ plants: Object.fromEntries(Object.entries(res.plants).map(([k, v]) => [k, { r: { kin: { quadrant: v.r.kin.quadrant }, dchi2: { ...v.r.dchi2 } } }])) });
  fake.plants.claim.r.kin.quadrant = 0.5;
  assert.match(FG.powerReading(fake).text, /could NOT have confirmed the claim/);
  const fake2 = clone(fake); fake2.plants.claim.r.kin.quadrant = 0.999; fake2.plants.lookback.r.dchi2.replenishing = 30;
  assert.match(FG.powerReading(fake2).text, /lookback time distinguished/);
});
test('power', 'the same plant over fresh noise: the objections are robustly refused, the printed quadrant level is fragile', () => {
  const N = res.noise, n = FG.N_NOISE;
  assert.ok(E.countAtLeast(N.claim.dDust, 9) >= 0.9 * n && E.countAtLeast(N.claim.dPropz, 9) >= 0.7 * n, 'the claim beats both objections in most draws');
  for (const m of ['highzdust', 'propz']) {
    assert.equal(E.countAtLeast(N[m].dDust, 9) + E.countAtLeast(N[m].dPropz, 9) + E.countAtLeast(N[m].quadrant, FG.PRINTED_QUADRANT), 0, m + ': the claim preferred in none of the draws');
    assert.ok(E.countAtLeast(Float64Array.from(N[m].dPropz, v => -v), 9) >= 0.95 * n, m + ': Λ worse than the rival');
  }
  assert.ok(E.countAtLeast(N.claim.quadrant, FG.PRINTED_QUADRANT) < 0.5 * n, 'the printed quadrant level is reached by the claim in a minority of draws');
  assert.ok(E.countAtLeast(N.lookback.quadrant, FG.PRINTED_QUADRANT) > E.countAtLeast(N.claim.quadrant, FG.PRINTED_QUADRANT), 'lookback reaches it more often than the claim');
  assert.ok(E.countAtLeast(N.bestflat.dDust, res.gold.dchi2.highzdust) <= 0.1 * n, 'the real data sit in the favourable tail');
  const one = E.noisePower(ctx.K, ctx.gold, { model: 'claim', sizeMag: 0.25, n, seed: FG.SEEDNOISE, from: 3, to: 4 });
  assert.equal(one.quadrant[3], N.claim.quadrant[3], 'a single draw reproduces from its own seed');
  assert.match(read('engine.js'), /export function noisePower[\s\S]{0,1500}kinematic\(K, fake, \{ lite: true \}\)[\s\S]{0,200}table4\(fake/, 'fresh noise goes through the control\'s own kinematic and table4');
  assert.ok(E.noisePower(ctx.K, ctx.gold, { model: 'claim', sizeMag: 0.5 }).refused, 'refused at another size');
});
test('power', 'dimming with lookback time and dust of constant density are the same function, computed two ways', () => {
  assert.ok(res.lookbackDiff < 1e-9, 'optical depth over z against time over the scale factor: ' + res.lookbackDiff);
  assert.ok(res.lookbackClosed < 1e-9, 'against (2/3)(1 - (1+z)^-1.5) in OmegaM = 1: ' + res.lookbackClosed);
  const zs = E.uniqueSorted(ctx.gold.map(r => r.z));
  const a = E.dimShape('lookback', zs, E.HOSTS.open03), b = E.dimShape('replenishing', zs, E.HOSTS.open03);
  assert.ok(Math.max(...zs.map((z, i) => Math.abs(a[i] - b[i]))) < 1e-9, 'also in an open host');
});
test('power', 'the second layer: the blind zone on the slider\'s own stops, both edges, the claim-sized band, and the table rows', () => {
  assert.deepEqual(res.blind.eds.map(b => b.zsat), E.BLIND_STEPS, 'the map is computed on every stop the reader can choose');
  assert.deepEqual(FG.blindTable(res.blind.eds).map(b => b.zsat), E.BLIND_ZS, 'the printed table is those stops at BLIND_ZS');
  const B = FG.blindSummary(res.blind.eds), Bo = FG.blindSummary(res.blind.open03);
  assert.ok(B.contiguous && Bo.contiguous, 'each band is one run of stops');
  assert.deepEqual([B.zsMin, B.zsMax, B.claimMin, B.claimMax], [0.1, 0.9, 0.15, 0.6]);
  assert.deepEqual([Bo.zsMin, Bo.zsMax, Bo.claimMax], [0.05, 0.5, 0.3]);
  assert.ok(!B.inZone(B.low) && B.low.realFree > 4 && B.low.zsat === 0.075, 'below the band the dimming is over too early to fit');
  assert.ok(B.first.zsat === 1 && B.first.realFree < 4 && B.first.planted.quadrant < FG.PRINTED_QUADRANT, 'above it the fit holds but the quadrant falls under the line');
  assert.ok(B.minQuad >= 0.992 && B.maxFree < 4);
  assert.ok(B.growTunedMin > 25 && B.growQuadMax < 0.9, 'dimming still growing beyond z = 1 is excluded when tuned, and not read as a transition');
  for (const b of res.blind.eds) near(b.meta.dimAt05, res.plants.lookback.meta.dimAt05, 1e-9, 'every planted history carries the claimed size');
  const inf = res.blind.eds[res.blind.eds.length - 1];
  near(inf.realTuned, res.gold.dchi2.propz, 1e-6, 'the zs = infinity end is dimming proportional to z');
  near(inf.planted.quadrant, res.plants.propz.r.kin.quadrant, 1e-9, 'and planted, it is the propz plant');
  assert.ok(E.blindZone(ctx.K, ctx.gold, { zsat: 0 }).refused);
  // the three real-data fits, recomputed at two stops by independent code
  const gold = D04.rows.filter(r => r.sample === 'gold').map(r => ({ z: r.z, mu: r.mu0, w: 1 / r.sig ** 2 }));
  const flat = indepFlatChi2(gold);
  let lo = 0, hi = 1; const ref = indepMu(0.5, 0.2, 0);
  for (let i = 0; i < 50; i++) { const m = (lo + hi) / 2; if (indepMu(0.5, m, 1 - m) - ref > 0.25) lo = m; else hi = m; }
  const A = indepMu(0.5, lo, 1 - lo) - indepMu(0.5, 1, 0);
  near(A, res.blind.eds[0].meta.dimAt05, 1e-4, 'the claimed dimming at z = 0.5');
  for (const zsat of [0.3, 0.75]) {
    const b = res.blind.eds.find(x => x.zsat === zsat);
    const shape = gold.map(r => -Math.expm1(-r.z / zsat) / -Math.expm1(-0.5 / zsat)), base = gold.map(r => indepMu(r.z, 1, 0, 600));
    let W = 0, Sx = 0, Sy = 0, Sxx = 0, Sxy = 0;
    gold.forEach((r, i) => { const d = r.mu - base[i]; W += r.w; Sx += r.w * shape[i]; Sy += r.w * d; Sxx += r.w * shape[i] ** 2; Sxy += r.w * shape[i] * d; });
    const K = (Sxy - Sx * Sy / W) / (Sxx - Sx * Sx / W), off = (Sy - K * Sx) / W;
    const free = gold.reduce((c, r, i) => c + r.w * (r.mu - base[i] - K * shape[i] - off) ** 2, 0) - flat;
    const claim = indepOffsetChi2(gold.map(r => r.mu), gold.map(r => r.w), gold.map((r, i) => base[i] + A * shape[i])).chi2 - flat;
    near(free, b.realFree, 0.02, 'independent fitted-amplitude fit at zs ' + zsat);
    near(claim, b.realClaim, 0.02, 'independent claim-sized fit at zs ' + zsat);
  }
  assert.ok(has('Held at the claimed size instead of fitted') && !has('sized to the 1998 claim that saturates by'), 'the page states the claim-sized band and no longer calls the fitted leg claim-sized');
});

// ================================================================== null: the claimants' methods on nothing
test('null', 'the 1998 procedure on universes with no cosmological constant: rare false alarms, a high median', () => {
  const n = res.n98;
  assert.equal(n.n, FG.N_NULL98);
  const hits = E.countAtLeast(n.pq, 0.995);
  assert.equal(String(hits), F['n98.hitPrinted']);
  assert.ok(hits > 0 && hits / n.n < 0.02, 'false alarms at the printed level: ' + hits);
  const m = E.median(n.pq);
  assert.ok(m > 0.6 && m < 0.85, 'median p(q0<=0) in a universe with no Λ: ' + m);
  // the null has the claimants' structure: the anchor's own rows, and any index range reproduces
  const one = E.null1998(D98, ctx.P, { n: FG.N_NULL98, seed: FG.SEED98, from: 7, to: 8 });
  assert.equal(one.pq[7], n.pq[7], 'a single null universe reproduces from its own seed');
});
test('null', 'the same procedure finds acceleration where there is some, so its quiet on nothing means something', () => {
  const lam = E.null1998(D98, ctx.P, { n: 30, seed: 4242, model: { Om: 0.3, OL: 0.7 } });
  assert.ok(E.median(lam.pq) > 0.95, 'median p(q0<=0) when the truth is flat Λ: ' + E.median(lam.pq));
});
test('null', 'the 2004 kinematic test on noise alone manufactures no deceleration epoch', () => {
  assert.equal(E.countAtLeast(res.nk02.quadrant, 0.992), 0); assert.equal(E.countAtLeast(res.nk1.quadrant, 0.992), 0);
  assert.ok(E.median(res.nk02.quadrant) < 0.5 && E.median(res.nk1.quadrant) < 0.05);
  const lam = E.nullKin(ctx.K, ctx.gold, { n: 20, seed: 99, model: { Om: 0.27, OL: 0.73 } });
  assert.ok(E.median(lam.quadrant) > 0.8, 'and leans to one when the truth has it: median ' + E.median(lam.quadrant));
});

// ================================================================== surface: what the reader sees
test('surface', 'every figure printed in the page equals the recomputation', () => {
  const figs = S.dataFigs(html);
  assert.ok(figs.length >= 300, 'figure spans: ' + figs.length);
  assert.deepEqual(surfaceDisagreements(html, F), []);
  const used = new Set(figs.map(f => f.key));
  for (const k of ['a98.excess', 'a98.pct', 'a98.printed', 'a98.pq', 'a98.pqPrinted', 'a98.tpl', 't4.lcdm', 't4.highzdust', 'c.dDust', 'c.dPropz', 'c.quad', 'c.zt', 'pw.lookback.quad', 'pw.lookback.zt', 'pw.claim.quad', 'pw.verdict', 'n98.hitPrinted', 'bz.zsMin', 'bz.zsMax', 'bz.minQuad', 'bz.claimMin', 'bz.claimMax', 'bz.4.claim', 'lo.beyond1.dDust', 'lo.all1998.dDust', 'lo.all1998.quad', 'lo.near1998gold', 't8.nWeaker', 't8.strongerGap', 'pw.lbSize.3.dRepl', 'pw.lbSize.minQuad', 'c.chi2Concord'])
    assert.ok(used.has(k), 'the page prints ' + k);
});
test('surface', 'dek, headline, title, meta description, OG, Twitter and JSON-LD match the recomputed text', () => {
  assert.equal(S.decodeEntities((html.match(/<p class="dek" data-dek>([\s\S]*?)<\/p>/) || [])[1] || ''), X.DEK);
  assert.equal(S.decodeEntities((html.match(/<p class="lede" id="headline" data-headline>([\s\S]*?)<\/p>/) || [])[1] || ''), X.HEADLINE);
  assert.equal((html.match(/<title>([\s\S]*?)<\/title>/) || [])[1], S.escText(X.SEO));
  assert.equal(meta('name', 'description'), S.escAttr(X.DEK));
  assert.equal(meta('property', 'og:description'), S.escAttr(X.OG));
  assert.equal(meta('name', 'twitter:description'), S.escAttr(X.TW));
  assert.equal(meta('property', 'og:image:alt'), S.escAttr(X.OG_ALT));
  assert.equal(meta('property', 'og:image'), S.OG_IMAGE); assert.equal(meta('name', 'twitter:image'), S.OG_IMAGE);
  assert.equal(meta('property', 'og:url'), S.URL);
  assert.equal(meta('property', 'og:title'), 'The Dimming That Turned Around &middot; Artificial Wasteland');
  assert.match(html, /<link rel="canonical" href="https:\/\/artwaste\.land\/strata\/the-dimming-that-turned-around\/" \/>/);
  const scripts = [...html.matchAll(/<script type="application\/ld\+json">([\s\S]*?)<\/script>/g)];
  assert.equal(scripts.length, 1);
  const ld = JSON.parse(scripts[0][1]);
  assert.equal(ld['@type'], 'Article'); assert.equal(ld.name, X.SEO); assert.equal(ld.headline, S.TITLE); assert.equal(ld.description, X.DEK);
  assert.equal(ld.url, S.URL); assert.equal(ld.image, S.OG_IMAGE); assert.match(ld.datePublished, /^\d{4}-\d{2}-\d{2}$/);
});
test('surface', 'frontmatter: dek, plain, seoTitle and body match the recomputed text; placard rules hold', () => {
  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'), S.SEAM); assert.equal(fmField('href'), '/strata/' + S.SLUG + '/');
  assert.equal(mdBody, X.BODY.join('\n\n'));
  const plain = fmField('plain');
  assert.ok(plain.length >= 90 && plain.length <= 420, 'plain length ' + plain.length);
  assert.ok(!plain.includes('"')); assert.ok((plain.match(/[.!?](\s|$)/g) || []).length <= 3);
  const aw = html.match(/<meta name="aw-plain" content="([^"]*)"/);
  if (aw) assert.equal(S.decodeEntities(aw[1]), X.PLAIN, 'an injected placard must match the frontmatter');
  const rel = [...fm.matchAll(/^\s+- to: (\S+)$/gm)].map(m => m[1]);
  assert.deepEqual(rel, S.RELATES.map(r => r[0]));
  for (const r of rel) assert.ok(fs.existsSync(path.join(root, 'src/content/strata', r + '.md')), 'relates target exists: ' + r);
  assert.equal(H.markdown(X, (md.match(/^date:\s*(\S+)/m) || [])[1]), md, 'the markdown file is exactly what the fill script writes');
});
test('surface', 'the verdict box, sources, exchange and notes are exactly what readings.js says', () => {
  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);
  H.SOURCE_IDS.forEach((id, i) => assert.equal(S.decodeEntities((html.match(new RegExp('<li id="' + id + '">([\\s\\S]*?)<\\/li>')) || [])[1] || ''), VERDICT.sources[i]));
  for (const e of EXCHANGE) assert.equal((html.match(new RegExp('<li id="ex-' + e.id + '">([\\s\\S]*?)<\\/li>')) || [])[1], H.exchangeHtml(e));
  assert.equal(S.decodeEntities((html.match(/<span id="desiText">([\s\S]*?)<\/span>/) || [])[1] || ''), DESI);
  assert.equal(S.decodeEntities((html.match(/<p class="small" id="preprintNote">([\s\S]*?)<\/p>/) || [])[1] || ''), PREPRINT_NOTE);
  assert.equal(S.decodeEntities((html.match(/<span id="novelty">([\s\S]*?)<\/span>/) || [])[1] || ''), NOVELTY);
});
test('surface', 'the shareable surfaces say only what the page establishes, and the wording and wiring fixed on 2026-09-23 hold', () => {
  // the claim's comparison universe on every shareable surface, and the lookback plant described as what the test reports
  for (const [k, t] of [['DEK', X.DEK], ['OG', X.OG], ['TW', X.TW], ['HEADLINE', X.HEADLINE], ['BODY', X.BODY[0]]]) {
    assert.ok(/low-density/.test(t) && !/cosmological constant allow/.test(t), k + ': the ΩM = 0.2 comparison, not every universe without Λ');
  }
  for (const t of [X.DEK, X.OG, X.HEADLINE, ...X.BODY, NOVELTY]) assert.ok(!/deceleration epoch/.test(t), 'a planted lookback universe is reported as acceleration after deceleration, not as a deceleration epoch');
  assert.ok(/ruled out the two rivals it was built against/.test(X.PLAIN) && !/rival explanations of the time/.test(X.PLAIN), 'the placard is scoped to the two objections');
  assert.ok(/between z of about/.test(X.BODY[2]), 'the placard body gives the blind zone as a band');
  // the body
  assert.ok(has('too faint, at 2.8σ to 3.9σ depending on the fitting method, for a universe whose expansion was slowing down') && !has('too faint for any universe'));
  assert.ok(has('The searches did not find the planted map in print') && !has('What is new here is only the planted map') && has('arXiv 2604.24761'));
  assert.ok(has('(> 9σ) tension with the ΛCDM model'), 'the challengers\' own headline is given');
  assert.ok(EXCHANGE.some(e => e.id === 'park' && e.side === 'challenge') && has('Murakami') && has('v1 21 July 2026, v2 3 August 2026'), 'both sides of 2026, published and preprint');
  assert.ok(!/printed size/.test(FG.PLANT_LABEL.claim), 'the plant label follows the size control');
  assert.ok(!read('NOTICE.txt').includes('published beside the page'), 'the verifier is not served beside the page');
  // the wiring: controls wait for their stage, the hero's printed figure follows the method, the zs label never flashes Infinity
  const ps = read('page.js');
  assert.match(ps, /if \(ready\.has\('control'\)\) drawCtl\(\)/); assert.match(ps, /if \(ready\.has\('plants'\)\) \{ drawPower\(\); drawPowerTable\(\); \}/);
  assert.match(ps, /if \(name === 'plants'\) \{ drawPower\(\); if \(state\.sizeIdx !== 1\) drawPowerTable\(\); \}/, 'a size chosen before the plants stage is drawn when it runs');
  assert.match(ps, /\$\('heroPrinted'\)\.textContent = /); assert.ok(html.includes('<span id="heroPrinted">'));
  assert.match(ps, /zsWord\(E\.BLIND_STEPS\[state\.zsIdx\]\)/); assert.ok(!/String\(E\.BLIND_STEPS/.test(ps));
  assert.match(ps, /yLabelNarrow: 'Δμ vs coasting, mag', yFmt: v => FG\.fx\(v, 1\)/); assert.match(read('render.js'), /if \(narrow && yLabelNarrow\) yLabel = yLabelNarrow;/);
});
test('surface', 'every other number a reader can see matches the inventory, in order', () => {
  const inv = path.join(here, 'surface-literals.json');
  const now = S.literalNumbers(html);
  if (REGEN && results.every(r => r.pass)) fs.writeFileSync(inv, JSON.stringify(now) + '\n');
  assert.ok(fs.existsSync(inv), 'surface-literals.json missing: run with --regen once every other assertion passes');
  assert.deepEqual(now, JSON.parse(fs.readFileSync(inv, 'utf8')));
});
test('surface', 'every quotation on the page is in the frozen transcriptions, which pin its PDF page', () => {
  const q98 = D98.printed.quotes, q04 = D04.printed.quotes;
  for (const k of ['headline', 'discussion_mag', 'discussion_sig', 'fig4_caption', 'evolution', 'unphysical'])
    assert.ok(has(q98[k].text.replace(/^We do not consider /, '').replace(/\.$/, '')), '1998 quotation ' + k);
  assert.ok(has(q98.abstract_sig_a.text + ' ' + q98.abstract_sig_b.text), 'the abstract significance, across its page break');
  assert.ok(has('which do not monotonically expand from a ‘big bang’ and for which equation (2) is not solvable'), 'the bounce reason (quoted inside a quotation)');
  assert.ok(q98.bounce.text.includes('which do not monotonically expand from a “big bang” and for which equation (2) is not solvable'));
  assert.ok(has('full strength of the high-redshift sample') && q98.full_strength.text.includes('full strength of the high-redshift sample'));
  // a quotation nested inside the page's own quotation marks is printed with single quotes, and a quotation
  // that ends a sentence of the page may leave its full stop outside
  const hasQ = t => [t, t.replace(/\.$/, '')].some(v => has(v) || has(v.replace(/“/g, '‘').replace(/”/g, '’')));
  for (const k of ['abstract_first', 'abstract_concordance', 'indistinguishable', 'lookback', 'proof', 'complex'])
    assert.ok(hasQ(q04[k].text), '2004 quotation ' + k);
  assert.ok(hasQ(q04.tuning.text.replace(/^A single free \(opacity\) parameter is /, '')), '2004 quotation tuning');
  assert.ok(has('the transition between the two epochs is constrained to be at z = 0.46 ± 0.13.'));
  assert.ok(has('the precise value depends on the kinematic model employed') && q04.precise.text.includes('the precise value depends on the kinematic model employed'));
  assert.ok(has('continually replenished at precisely the same rate in which it is diluted') && q04.replenishing_prose.text.includes('continually replenished at precisely the same rate in which it is diluted'));
  assert.ok(has('∆χ² = 122') && q04.dchi2.text.includes('∆χ² = 122') && has('∆χ² = 70') && q04.dchi2.text.includes('∆χ² = 70'));
  assert.deepEqual([q98.fig4_caption.page, q98.discussion_mag.page, q98.evolution.page, q98.unphysical.page, q04.tuning.page, q04.indistinguishable.page, q04.lookback.page, q04.complex.page, q04.precise.page],
    [35, 18, 20, 12, 26, 27, 32, 40, 40], 'the pages the page cites');
  for (const e of EXCHANGE) assert.ok(e.evidence.length > 40 && /“/.test(e.evidence));
});
test('surface', 'house rules: no em dash, no forbidden words, no third-party requests, no shell at the reader', () => {
  const files = fs.readdirSync(dir).filter(f => fs.statSync(path.join(dir, f)).isFile());
  for (const f of files) assert.ok(!read(f).includes(EM_DASH), 'em dash in ' + f);
  for (const f of fs.readdirSync(here).filter(f => fs.statSync(path.join(here, f)).isFile())) assert.ok(!fs.readFileSync(path.join(here, f), 'utf8').includes(EM_DASH), 'em dash in research/' + f);
  assert.ok(!md.includes(EM_DASH));
  const text = fullVisible.toLowerCase() + ' ' + md.toLowerCase();
  for (const w of [...FORBIDDEN, 'illusion', 'proved']) assert.ok(!text.includes(w), 'forbidden word: ' + w);
  assert.ok(!/github\.com\/[^"]*Artificial-Wasteland/i.test(html));
  assert.ok(!/\b(node|npm|npx|python3?) [\w./-]+/.test(fullVisible), 'no shell command at the reader');
  for (const m of html.matchAll(/<(?:script|img|iframe|audio|video|source)\b[^>]*\ssrc="([^"]+)"/g)) assert.ok(!/^(https?:)?\/\//.test(m[1]), 'external resource ' + m[1]);
  for (const m of html.matchAll(/<link\b([^>]*)>/g)) {
    const relv = (m[1].match(/\srel="([^"]+)"/) || [])[1] || '', href = (m[1].match(/\shref="([^"]+)"/) || [])[1] || '';
    if (/stylesheet|preload|modulepreload|icon|manifest|prefetch/.test(relv)) assert.ok(!/^(https?:)?\/\//.test(href), 'external resource ' + href);
  }
  assert.ok(!/url\(\s*['"]?https?:/.test(html.slice(html.indexOf('<style'), html.indexOf('</style>'))), 'no external CSS resources');
  for (const f of files.filter(f => f.endsWith('.js'))) {
    const src = read(f);
    assert.ok(!/(fetch|import)\s*\(\s*['"`]https?:/.test(src) && !/from\s+['"]https?:/.test(src) && !/XMLHttpRequest|WebSocket|sendBeacon|EventSource/.test(src), 'third-party request in ' + f);
    for (const u of src.match(/(?:https?:)?\/\/[a-z0-9.-]+\.[a-z]{2,}[^\s'"`)]*/gi) || []) assert.equal(u, 'http://www.w3.org/2000/svg', 'absolute URL in ' + f + ': ' + u);
  }
});
test('surface', 'structure: closing tags, one inline script (the JSON-LD), modules parse, accessibility basics', () => {
  assert.match(html.trimEnd(), /<script type="module" src="page\.js"><\/script>\s*<\/body>\s*<\/html>$/);
  const inline = [...html.matchAll(/<script(?![^>]*\ssrc=)([^>]*)>([\s\S]*?)<\/script>/g)];
  assert.equal(inline.length, 1); assert.match(inline[0][1], /application\/ld\+json/);
  for (const f of fs.readdirSync(dir).filter(f => f.endsWith('.js'))) {
    const r = spawnSync(process.execPath, ['--check', path.join(dir, f)], { encoding: 'utf8' });
    assert.equal(r.status, 0, f + ': ' + r.stderr);
  }
  assert.match(html, /prefers-reduced-motion/); assert.match(html, /:focus-visible/);
  assert.ok((html.match(/role="status"/g) || []).length >= 12, 'live readouts');
  assert.ok(!/<span[^>]*(onclick|role="button"|tabindex)/.test(html), 'no clickable span');
  for (const m of html.matchAll(/<button\b([^>]*)>/g)) assert.match(m[1], /type="button"/);
  for (const m of html.matchAll(/<(input|select)\b([^>]*)>/g)) {
    const attrs = m[2]; const id = (attrs.match(/\sid="([^"]+)"/) || [])[1];
    assert.ok(/type="radio"/.test(attrs) || (id && html.includes('for="' + id + '"')) || /aria-label=/.test(attrs), 'unlabelled control ' + attrs);
  }
  for (const m of html.matchAll(/<table\b/g)) assert.match(html.slice(Math.max(0, m.index - 80), m.index), /<div class="scroll">\s*$/, 'every table sits in a horizontal scroller');
  for (const m of html.matchAll(/<canvas\b([^>]*)>/g)) { assert.match(m[1], /\srole="img"/, 'a canvas is exposed as an image'); assert.match(m[1], /aria-label="/); }
  assert.ok(!/aria-pressed/.test(html), 'the beyond-z = 1 button changes its label, so it carries no pressed state as well');
  assert.match(html, /<span role="status" aria-live="polite" id="progress">[^<]*<\/span> <span id="progressDetail" aria-hidden="true"><\/span>/, 'the running count is kept out of the live region');
  for (const m of html.matchAll(/<svg\b([^>]*)>/g)) assert.match(m[1], /role="img" aria-labelledby="/);
  assert.match(html, /\.grid2 > \*\{min-width:0\}/); assert.match(html, /\.scroll\{overflow-x:auto/);
  // the page's own data rows are the ones the verifier used
  assert.ok(read('render.js').includes('It computes nothing that this page reports as a result'));
  assert.ok(!/from '\.\/engine\.js'/.test(read('render.js')), 'render.js does not import the engine');
});

// ================================================================== choices: each changes an output
const CHOICES = [
  { id: 'method', label: '1998 light-curve method', options: ['mlcs', 'template'], default: 'mlcs', affects: ['mean excess', 'H0', 'p(OmegaL >= 0)', 'p(q0 <= 0)'], inert: false },
  { id: 'ck', label: 'SN 1997ck (no spectrum, no colour)', options: ['printed', 'everywhere', 'nowhere'], default: 'printed', affects: ['mean excess', 'p(OmegaL >= 0)', 'p(q0 <= 0)'], inert: false },
  { id: 'sample', label: '1998 supernovae in the likelihood', options: ['lc+snap', 'lc', 'snap'], default: 'lc+snap', affects: ['p(OmegaL >= 0)', 'p(q0 <= 0)'], inert: false },
  { id: 'zeroPoint', label: 'Zero point of the mean excess', options: ['fit', 'nearby'], default: 'fit', affects: ['mean excess'], inert: false },
  { id: 'snapZ', label: 'Redshifts of SN 1995ao and SN 1995ap', options: ['table7', 'table1'], default: 'table7', affects: ['p(q0 <= 0)', 'p(OmegaL >= 0)'], inert: false },
  { id: 'h0prior', label: 'Prior on the Hubble constant', options: ['flat-H0', 'flat-offset'], default: 'flat-H0', affects: ['p(q0 <= 0)', 'quadrant probability'], inert: false },
  { id: 'sample04', label: '2004 sample', options: ['gold', 'gold+silver'], default: 'gold', affects: ['quadrant probability', 'transition redshift', 'Δχ² grey dust', 'Δχ² dimming ∝ z'], inert: false },
  { id: 'leave', label: 'Leave out of the gold set', options: ['none', 'hst', 'beyond1', 'claimants1998', 'all1998', 'nearby'], default: 'none', affects: ['quadrant probability', 'transition redshift', 'Δχ² grey dust', 'Δχ² dimming ∝ z'], inert: false, note: 'nearby is refused: no supernova below z = 0.1' },
  { id: 'ampRule', label: 'Dimming amplitude', options: ['tuned', 'free'], default: 'tuned', affects: ['Δχ² grey dust', 'Δχ² dimming ∝ z'], inert: false },
  { id: 'host', label: 'Host universe of the dimming', options: ['eds', 'open03'], default: 'eds', affects: ['Table 4 astrophysical rows', 'blind-zone edge'], inert: false },
  { id: 'replenishing', label: 'Replenishing dust, read as', options: ['prose', 'equation', 'equation-continuous'], default: 'prose', affects: ['Table 4 replenishing row'], inert: false },
  { id: 'plant', label: 'Plant into a copy of the gold set', options: ['none', ...FG.PLANT_ORDER], default: 'none', affects: ['every planted readout'], inert: false },
  { id: 'size', label: 'Claimed size at z = 0.5 (mag)', options: E.SIZES.map(v => Number(v.toFixed(3))), default: 0.25, affects: ['planted readouts', 'blind zone'], inert: false },
  { id: 'zs', label: 'Saturation redshift of the second layer', options: E.BLIND_STEPS.map(v => (Number.isFinite(v) ? v : 'infinity')), default: 0.75, affects: ['blind-zone readouts'], inert: false },
];
test('choices', 'the 1998 choices each move their named outputs', () => {
  const base = res.c98;
  assert.ok(Math.abs(res.c98tpl.excess.mean - base.excess.mean) > 0.03 && Math.abs(res.c98tpl.L.pq - base.L.pq) > 0.0005 && Math.abs(res.c98tpl.fit.H0 - base.fit.H0) > 0.5, 'method');
  const ev = E.claim1998(D98, ctx.P, { ck: 'everywhere' });
  assert.ok(Math.abs(res.c98nock.excess.mean - base.excess.mean) > 0.01 && Math.abs(ev.L.pq - base.L.pq) > 0.0005, 'ck');
  assert.ok(Math.abs(res.t8[4].pq - base.L.pq) > 0.001 && Math.abs(res.t8[8].pq - base.L.pq) > 0.1, 'sample');
  assert.ok(Math.abs(res.c98near.excess.mean - base.excess.mean) > 0.01, 'zeroPoint');
  assert.ok(Math.abs(res.c98off.L.pq - base.L.pq) > 0.0002 && Math.abs(res.kinOff.quadrant - res.gold.kin.quadrant) > 1e-5, 'h0prior');
  assert.ok(base.L.pq - res.c98t1z.L.pq > 0.001, 'snapZ: Table 1 redshifts move p(q0<=0) away from print');
  assert.deepEqual(E.rows1998(D98, { snapZ: 'table1' }).snap.filter(r => ['1995ao', '1995ap'].includes(r.sn)).map(r => r.z), [0.24, 0.3]);
});
test('choices', 'the 2004 choices each move their named outputs', () => {
  const g = res.gold;
  assert.ok(Math.abs(res.gs.kin.quadrant - g.kin.quadrant) > 1e-4 && Math.abs(res.gs.dchi2.highzdust - g.dchi2.highzdust) > 5, 'sample04');
  for (const w of ['hst', 'beyond1', 'claimants1998', 'all1998']) assert.ok(Math.abs(res.leave[w].r.kin.quadrant - g.kin.quadrant) > 1e-4 && Math.abs(res.leave[w].r.dchi2.propz - g.dchi2.propz) > 0.01, 'leave ' + w);
  assert.ok(E.leaveOut(ctx.gold, 'nearby', {}).refused, 'leave nearby is refused');
  assert.ok(Math.abs(res.free.dchi2.highzdust - g.dchi2.highzdust) > 50, 'ampRule');
  assert.ok(Math.abs(res.open03.t4.highzdust - g.t4.highzdust) > 5 && FG.blindSummary(res.blind.open03).zsMax !== FG.blindSummary(res.blind.eds).zsMax, 'host');
  assert.ok(Math.abs(res.replEq.replenishing - g.t4.replenishing) > 1 && Math.abs(res.replEqC.replenishing - g.t4.replenishing) > 1, 'replenishing');
});
test('choices', 'the plant, the claimed size and the saturation redshift each move the planted readouts', () => {
  const qs = FG.PLANT_ORDER.map(m => res.plants[m].r.kin.quadrant);
  assert.equal(new Set(qs.map(q => q.toFixed(4))).size, qs.length, 'every plant reads differently');
  const small = E.runControl(ctx.K, plantOf('claim', E.SIZES[0]).rows, { skipFlat: true }), large = E.runControl(ctx.K, plantOf('claim', E.SIZES[3]).rows, { skipFlat: true });
  assert.ok(Math.abs(small.kin.best.q0 - large.kin.best.q0) > 0.05, 'size moves the planted claim');
  const at = z => res.blind.eds.find(b => b.zsat === z);
  const b1 = E.blindZone(ctx.K, ctx.gold, { zsat: 0.3, sizeMag: E.SIZES[3] });
  assert.ok(Math.abs(b1.planted.q1 - at(0.3).planted.q1) > 0.05 && Math.abs(b1.realClaim - at(0.3).realClaim) > 0.5, 'size moves the blind zone');
  assert.ok(Math.abs(at(0.1).planted.q1 - at(5).planted.q1) > 1, 'zs moves the planted readout');
  for (const k of CHOICES) {
    assert.ok(k.id && Array.isArray(k.options) && k.options.length >= 2 && Array.isArray(k.affects) && typeof k.inert === 'boolean');
    assert.ok(k.options.some(o => String(o) === String(k.default)), k.id + ': default among its options');
  }
});
test('choices', 'every choice is declared on the page and in record.json', () => {
  for (const [id, ctl] of [['method', 'data-state="method"'], ['ck', 'data-state="ck"'], ['sample', 'data-state="sample"'], ['sample04', 'data-state="sample04"'], ['leave', 'data-state="leave"'], ['ampRule', 'data-state="ampRule"'], ['host', 'data-state="host"'], ['replenishing', 'data-state="repl"'], ['plant', 'data-state="plant"'], ['size', 'id="sizeSel"'], ['zs', 'id="zsSlider"']])
    assert.ok(html.includes(ctl), id + ' has a control');
  assert.ok(has('Zero point of the mean excess') && has('Prior on the Hubble constant') && has('Redshifts of SN 1995ao and SN 1995ap'), 'the fixed free choices are named in the check');
});

// ================================================================== fault: planted faults are caught
test('fault', 'a fault planted in a copy of the gold set moves what the unmodified control reports', () => {
  const before = JSON.stringify(ctx.gold);
  const bad = E.faultBeyond1(ctx.gold);
  assert.equal(JSON.stringify(ctx.gold), before, 'the frozen rows are untouched');
  assert.equal(bad.filter((r, i) => r.mu !== ctx.gold[i].mu).length, 9);
  const r = E.runControl(ctx.K, bad, { skipFlat: true });
  assert.ok(r.kin.quadrant < 0.2 && r.kin.best.q1 < 0 && r.dchi2.propz < 5, 'quadrant ' + r.kin.quadrant);
  near(r.kin.quadrant, res.fault.kin.quadrant, 1e-12);
});
test('fault', 'the surface check goes red on a corrupted displayed figure, dek and headline', () => {
  const mut = html.replace(/(data-fig="c\.dDust">)([^<]*)/, (m, a, b) => a + b.replace(/\d$/, d => String((Number(d) + 1) % 10)));
  assert.ok(surfaceDisagreements(mut, F).includes('c.dDust'));
  const mut2 = html.replace(/(data-fig="t4\.lcdm"[^>]*>)([^<]*)/, (m, a) => a + '178.18');
  assert.ok(surfaceDisagreements(mut2, F).includes('t4.lcdm'));
  const X2 = S.texts({ ...F, 'a98.excess': '0.246' });
  assert.notEqual(X2.DEK, X.DEK);
  const litMut = html.replace('27 nearby and 10 high-redshift', '28 nearby and 10 high-redshift');
  assert.notDeepEqual(S.literalNumbers(litMut), S.literalNumbers(html), 'a literal number change is seen by the inventory');
});
test('fault', 'a changed byte in a frozen file is caught by the page\'s own pin check (data.js load, run on the altered bytes)', () => {
  assert.equal(pinClean.hashOk[FILES.d98], true); assert.equal(pinClean.hashOk[FILES.d04], true);
  assert.equal(pinTampered.hashOk[FILES.d98], true, 'the untouched file still passes');
  assert.equal(pinTampered.hashOk[FILES.d04], false, 'the altered file fails its pin');
  const changed = pinTampered.d04.rows.filter((r, i) => r.mu0 !== D04.rows[i].mu0);
  assert.equal(changed.length, 1); near(changed[0].mu0 - D04.rows[D04.rows.indexOf(D04.rows.find(r => r.sn === changed[0].sn))].mu0, 0.01, 1e-9);
  assert.match(read('page.js'), /li\(data\.hashOk\[name\],/, 'the check panel marks a file by the result of that pin check');
});

// ================================================================== refusal
test('refusal', 'the instrument refuses what the record does not support, and says why on the page', () => {
  const r1 = E.refuse1998(-0.1, 0.5);
  assert.ok(r1.refused && /unphysical region of parameter space where ΩM < 0/.test(r1.reason));
  const r2 = E.refuse1998(0.3, 2.5);
  assert.ok(r2.refused && /big bang/.test(r2.reason) && /not solvable/.test(r2.reason));
  assert.ok(!E.refuse1998(0.3, 0.7).refused);
  assert.ok(has('A universe with ΩM below zero or with no big bang is refused, with the paper’s own reason'));
  const z1 = E.refuseZ(1.9, 2004), z2 = E.refuseZ(1.0, 1998);
  assert.ok(z1.refused && /1\.755/.test(z1.reason) && z2.refused && /0\.97/.test(z2.reason));
  assert.equal(FG.ztText(3.43), 'beyond the data'); assert.ok(has('beyond the data'));
  assert.ok(has('A transition redshift beyond z = 1.755, the most distant gold supernova, is refused as beyond the data.'));
  const s = E.refusePlant({ model: 'claim', sizeMag: 0.4 });
  assert.ok(s.refused && /another size is another claim/.test(s.reason) && has('Any other size is refused: another size is another claim.'));
  const L = E.leaveOut(ctx.gold, 'nearby', {});
  assert.ok(L.refused && /below z = 0\.1/.test(L.reason) && has('every supernova below z = 0.1'));
  const p = E.plant(ctx.gold, { model: 'claim', sizeMag: 0.1 });
  assert.ok(p.refused && !p.rows, 'a refused plant returns no rows');
});

// ================================================================== provenance
const hashes = Object.fromEntries(Object.values(FILES).map(f => [f, sha(fs.readFileSync(path.join(dir, f)))]));
test('provenance', 'every frozen file is pinned in data.js, the research README and record.json, and copied byte for byte', () => {
  for (const f of Object.values(FILES)) {
    assert.equal(hashes[f], SHA256[f], f + ' pin in data.js');
    assert.ok(readme.includes(hashes[f]), f + ' hash in the README');
    const copy = path.join(here, 'data', f);
    assert.ok(fs.existsSync(copy), 'research copy of ' + f);
    assert.equal(sha(fs.readFileSync(copy)), hashes[f], 'research copy identical: ' + f);
  }
  for (const h of [D98.source.pdf_sha256, D04.source.tex_sha256, D04.source.pdf_sha256]) assert.ok(readme.includes(h), 'source hash in the README: ' + h);
  assert.ok(fs.existsSync(path.join(here, 'extract', 'extract_1998.py')) && fs.existsSync(path.join(here, 'extract', 'extract_2004.py')));
  assert.ok(read('NOTICE.txt').includes('American Astronomical Society'));
  // with --regen the file is about to be rewritten from this run; the manifest test then checks it whole
  if (fs.existsSync(recordPath) && !REGEN) {
    const rec = JSON.parse(fs.readFileSync(recordPath, 'utf8'));
    for (const r of rec.records) assert.equal(r.sha256, hashes[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.ok(VERDICT.sources.length >= 2);
  assert.ok(has('six years after the claim (September 1998 to June 2004)') && VERDICT.years_to_decision === 6 && VERDICT.decided_by === 'more-data');
  assert.ok(has(NOVELTY) && /^We searched arXiv, the web/.test(NOVELTY) && NOVELTY.includes('on 2026-09-23'));
  assert.ok(has(X.HEADLINE));
  assert.ok(has('The verdict covers the first') && /constant/.test(VERDICT.scope), 'the second half of the title is not in the verdict');
  const dates = EXCHANGE.map(e => e.date);
  assert.deepEqual(dates, [...dates].sort(), 'the exchange in date order');
  assert.ok(EXCHANGE.some(e => e.side === 'reply') && EXCHANGE.some(e => e.side === 'rejoinder'), 'both the reply and the rejoinder are given');
  assert.ok(has('Its authors include three of the 1998 claimants (Riess, Jha and Schmidt)') && has('Three of its authors (Riess, Jha and Schmidt) were claimants in 1998'));
  assert.ok(!has('Two of its authors') && !has('two of the 1998 claimants'), 'the old author count is gone');
  assert.ok(has('Decided by more data: the 2004 gold set, and above all its supernovae beyond z = 1'));
  for (const w of ['debunked', 'refuted', 'disproved']) assert.ok(!new RegExp('\\b' + w + '\\b', 'i').test(fullVisible), w);
  if (fs.existsSync(recordPath) && !REGEN) {
    const rec = JSON.parse(fs.readFileSync(recordPath, 'utf8'));
    assert.deepEqual(rec.verdict, { category: VERDICT.category, as_of: VERDICT.as_of, sources: [...VERDICT.sources], would_change: VERDICT.would_change });
  }
});

// ================================================================== record.json
function makeRecord(ledger) {
  const c = res.c98, g = res.gold, P = res.plants, t8 = D98.printed.table8.rows[0];
  return {
    slug: S.SLUG, title: S.TITLE, href: '/strata/' + S.SLUG + '/', field: 'astronomy',
    claim: {
      statement: D98.printed.quotes.headline.text,
      claimants: 'The High-Z Supernova Search Team: Adam G. Riess, Alexei V. Filippenko, Peter Challis, Alejandro Clocchiatti, Alan Diercks, Peter M. Garnavich, Ron L. Gilliland, Craig J. Hogan, Saurabh Jha, Robert P. Kirshner, B. Leibundgut, M. M. Phillips, David Reiss, Brian P. Schmidt, Robert A. Schommer, R. Chris Smith, J. Spyromilio, Christopher Stubbs, Nicholas B. Suntzeff, John Tonry',
      citation: D98.source.citation,
      year: 1998,
      headline_as_printed: '10% to 15% farther than expected in a low mass density (ΩM = 0.2) Universe without a cosmological constant (abstract); "The average difference between the data and the ΩM = 0.20, ΩΛ = 0 prediction is 0.25 mag." (Figure 4 caption, MLCS); p(q0 ≤ 0) = 99.5% (2.8σ), p(ΩΛ ≥ 0) = 99.7% (3.0σ), MLCS+Snap.(15), Table 8',
    },
    records: [
      { file: FILES.d98, role: 'claimant-data', name: 'Riess et al. 1998: measured distances of Tables 5, 6, 7, 9 and 10 and the redshift sources of Table 1, transcribed from the PDF text layer and checked against the page images, with the printed results of Table 8 and the quoted sentences with their pages', url: 'https://arxiv.org/pdf/astro-ph/9805201v1', licence: 'Transcribed measured values and short quotations from an AAS-copyright article (The Astronomical Journal); the typeset tables are not reproduced', licence_url: 'https://journals.aas.org/article-charges-and-copyright/', retrieved: '2026-09-23', sha256: hashes[FILES.d98], units: Object.values(D98.tables).reduce((s, t) => s + t.rows.length, 0) },
      { file: FILES.d04, role: 'control-data', name: 'Riess et al. 2004: the 186 rows of Table 5 (MLCS2k2 Full Sample: SN, z, mu0, sigma*, host A_V, gold or silver) from the arXiv v2 TeX, with the printed Table 4, the HST discovery list of Table 1, and the quoted sentences with their pages', url: 'https://arxiv.org/e-print/astro-ph/0402512v2', licence: 'Transcribed measured values and short quotations from an AAS-copyright article (The Astrophysical Journal); the VizieR copy (J/ApJ/607/665) is labelled CC BY-NC and is not shipped', licence_url: 'https://journals.aas.org/article-charges-and-copyright/', retrieved: '2026-09-23', sha256: hashes[FILES.d04], units: D04.rows.length },
    ],
    anchor: {
      what: 'The mean difference between the ten high-redshift MLCS distances plotted in Figure 4 (SN 1997ck included, as plotted) and the ΩM = 0.2, ΩΛ = 0 prediction, through the page engine (rows1998, like1998, bestFit1998, meanExcess) from the frozen tables; and the Table 8 probabilities through the same likelihood',
      expected: 'as printed: 0.25 mag (Figure 4 caption, p. 35; "0.25 and 0.28 mag farther on average", section 5, p. 18); p(q0 ≤ 0) 99.5% (2.8σ) and p(ΩΛ ≥ 0) 99.7% (3.0σ) for MLCS+Snap.(15); H0 = 65.2 for MLCS(9)',
      computed: c.excess.mean.toFixed(3) + ' mag (' + c.excess.pctFarther.toFixed(1) + '% farther) with the zero point of the engine\'s own best fit, H0 = ' + c.fit.H0.toFixed(2) + '; template ' + res.c98tpl.excess.mean.toFixed(3) + ' mag against the printed 0.28; p(q0 ≤ 0) = ' + FG.pct(c.L.pq) + ' (' + FG.sig(c.L.pq) + ') and p(ΩΛ ≥ 0) = ' + FG.pct(c.L.pL) + ', weaker than printed by about ' + (E.sigmaTwoSided(t8.pq[1] / 100) - E.sigmaTwoSided(c.L.pq)).toFixed(2) + 'σ; table rounding moves p(q0 ≤ 0) by a standard deviation of ' + (100 * res.round.sdPq).toFixed(2) + ' points over ' + res.round.draws + ' jittered draws',
      agrees: Math.abs(c.excess.mean - D98.printed.meanExcess.mlcs) <= 0.01,
      tolerance: '0.01 mag on the mean excess: the table entries are rounded to 0.01 mag, the printed average to 0.01 and the printed H0 to 0.1. The probabilities are not part of the anchor: ' + F['t8.nWeaker'] + ' of the ' + F['t8.n'] + ' probabilities Table 8 prints reproduce weaker than printed, by up to ' + F['t8.gapHi'] + 'σ, and one (p(ΩΛ ≥ 0), MLCS+Snap.+97ck(16)) ' + F['t8.strongerGap'] + 'σ stronger, for a reason the page could not identify; the page prints both.',
    },
    control: {
      name: 'The 2004 test with 16 HST-discovered supernovae: the kinematic q(z) = q0 + z dq/dz fit and its quadrant probability, and the Table 4 comparison of a cosmological constant with grey dust and evolution, on the 157 gold supernovae',
      citation: D04.source.citation,
      computed: 'Table 4: ' + ['lcdm', 'eds', 'empty', 'highzdust', 'replenishing', 'propz'].map(id => id + ' ' + g.t4[id].toFixed(2)).join(', ') + '; grey dust worse than ΩM = 0.27, ΩΛ = 0.73 by Δχ² = ' + g.dchi2.highzdust.toFixed(1) + ', dimming ∝ z by ' + g.dchi2.propz.toFixed(1) + '; quadrant probability ' + g.kin.quadrant.toFixed(4) + ' (gold), ' + res.gs.kin.quadrant.toFixed(4) + ' (gold and silver); transition z = ' + g.kin.zt.best.toFixed(3) + ' (median ' + g.kin.zt.median.toFixed(2) + ', 68% ' + g.kin.zt.lo.toFixed(2) + ' to ' + g.kin.zt.hi.toFixed(2) + '); flat ΩM = ' + g.flat.Om.toFixed(3),
      as_printed: 'Table 4 (157 gold): 178, 325, 192, 307 (high-z grey dust), 175 (replenishing dust), 253 (dimming ∝ z); text: Δχ² = 122 (grey dust) and 70 (∝ z); quadrant 99.2% (gold) and 99.8% (gold and silver); zt = 0.46 ± 0.13; flat ΩM = 0.29 (+0.05, -0.03); χ²dof 1.13 (section 4.2) and 1.06 (abstract)',
    },
    power: {
      grade: 'A-injection',
      planted: 'In deep copies of the 157 gold rows, each distance modulus had the engine\'s own best flat ΛCDM fit (ΩM = ' + P.claim.meta.refFit.Om.toFixed(3) + ') subtracted and a planted universe added, keeping every real residual, redshift and error: the claim at its printed size (0.25 mag farther than ΩM = 0.2, ΩΛ = 0 at z = 0.5, a flat universe with ΩM = ' + P.claim.meta.claimOm.toFixed(3) + '), and as rivals an ΩM = 1 universe plus high-redshift grey dust, dimming ∝ z, or dimming ∝ lookback time, each sized to the same distance at z = 0.5 (' + P.lookback.meta.dimAt05.toFixed(3) + ' mag of dimming); each copy run through the unmodified runControl',
      recovered: 'with the real residuals transplanted: ' + FG.PLANT_ORDER.map(m => m + ': quadrant ' + P[m].r.kin.quadrant.toFixed(4) + ', q0 ' + P[m].r.kin.best.q0.toFixed(2) + ', dq/dz ' + P[m].r.kin.best.q1.toFixed(2) + ', zt ' + FG.ztText(P[m].r.kin.zt.best) + ', Δχ²(grey dust - Λ) ' + P[m].r.dchi2.highzdust.toFixed(1) + ', Δχ²(∝ z - Λ) ' + P[m].r.dchi2.propz.toFixed(1)).join('; ') + '. Over fresh Gaussian noise of the printed errors (' + FG.N_NOISE + ' universes each): the claim beats grey dust by Δχ² >= 9 in ' + E.countAtLeast(res.noise.claim.dDust, 9) + ', dimming ∝ z in ' + E.countAtLeast(res.noise.claim.dPropz, 9) + ', and reaches quadrant >= 0.992 in ' + E.countAtLeast(res.noise.claim.quadrant, 0.992) + '; grey dust and ∝ z universes are never read as the claim; dimming ∝ lookback time reaches quadrant >= 0.992 in ' + E.countAtLeast(res.noise.lookback.quadrant, 0.992) + '; about the best flat fit, noise matches the real quadrant in ' + E.countAtLeast(res.noise.bestflat.quadrant, res.gold.kin.quadrant) + ' and the real Δχ² against grey dust in ' + E.countAtLeast(res.noise.bestflat.dDust, res.gold.dchi2.highzdust) + '. Dimming ∝ lookback time at the other printed sizes: ' + res.lookbackBySize.map((r, i) => E.SIZES[i].toFixed(3) + ' mag: quadrant ' + r.kin.quadrant.toFixed(4) + ', Δχ²(replenishing dust - Λ(0.27, 0.73)) ' + r.dchi2.replenishing.toFixed(1)).join('; ') + ' (the verdict below is at the printed 0.25 mag; at 0.28 and 0.303 mag the Table 4 comparison prefers replenishing dust by more than 4, while the kinematic test still reports acceleration after deceleration)',
      verdict: FG.powerReading(res).text,
    },
    null_through_claimant_method: {
      applicable: true,
      what: 'Two nulls. The 1998 likelihood (the anchor\'s own like1998, on the anchor\'s own 36 light-curve and 13 snapshot rows, their redshifts and total errors) on ' + FG.N_NULL98 + ' universes with ΩM = 0.2 and ΩΛ = 0, each distance drawn with Gaussian noise of its row\'s own error (seed ' + FG.SEED98 + '); and the 2004 kinematic test on ' + FG.N_NULLKIN + ' universes each with ΩM = 0.2, ΩΛ = 0 and with ΩM = 1, using the gold set\'s redshifts and errors',
      result: 'the 1998 procedure gives p(q0 ≤ 0) at least the printed 99.5% in ' + E.countAtLeast(res.n98.pq, 0.995) + ' of ' + FG.N_NULL98 + ' null universes, at least the page\'s ' + FG.pct(c.L.pq) + ' in ' + E.countAtLeast(res.n98.pq, c.L.pq) + ', with median ' + FG.pct(E.median(res.n98.pq), 1) + '; the 2004 kinematic test gives quadrant probability at least 0.992 in ' + E.countAtLeast(res.nk02.quadrant, 0.992) + ' and ' + E.countAtLeast(res.nk1.quadrant, 0.992) + ' of ' + FG.N_NULLKIN + ' (medians ' + E.median(res.nk02.quadrant).toFixed(3) + ' and ' + E.median(res.nk1.quadrant).toFixed(3) + '): it does not manufacture a switch from deceleration to acceleration from noise, only from saturating dimming',
    },
    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.years_to_decision,
    choices: CHOICES,
    headline: X.HEADLINE,
    novelty: NOVELTY,
    ledger,
  };
}
const ASSERTIONS = {
  claim_reproduced: 'anchor:mean-excess-0.25-through-like1998-and-independent',
  control_computed: 'control:riess2004-table4-kinematic-quadrant-through-runControl',
  control_can_confirm: 'power:claim-and-rivals-planted-into-157-gold-rows-at-0.25-mag',
  rendered_figures_asserted: 'surface:data-fig-spans-head-frontmatter-verdict-and-literal-inventory',
  choices_are_live: 'choices:fourteen-each-changes-an-output',
  planted_fault_caught: 'fault:plus-0.5-mag-beyond-z1-and-corrupted-figures-and-bytes',
  refusal_asserted: 'refuse:omegam-negative-no-big-bang-beyond-data-size-and-leave-out',
  provenance_pinned: 'provenance:sha256-in-data-readme-record-and-research-copy',
  verdict_dated: 'verdict:category-date-scope-sources-exchange-printed',
};
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') && group('null'),
  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'),
};
const expected = makeRecord(Object.fromEntries(Object.entries(ledger).map(([k, v]) => [k, { value: v, assertion: ASSERTIONS[k] }])));
if (REGEN) {
  if (results.some(t => !t.pass)) { for (const f of results.filter(t => !t.pass)) 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');
}
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;
