#!/usr/bin/env node
// verify-the-year-that-would-not-disappear.mjs: recomputes every number the page shows,
// from the frozen files, through the page's own engine, and fails on any disagreement.
//   (no flag)  run every assertion, print a report, exit 1 on any failure
//   --ledger   print the nine contract cells exactly as computed from the assertion outcomes
// It never writes a file.
import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import {execFileSync} from 'node:child_process';
import * as E from '../../public/strata/the-year-that-would-not-disappear/engine.js';
import * as M from '../../public/strata/the-year-that-would-not-disappear/model.js';
import {PAGE, PUBLISHED as P, SLUG, FILES} from '../../public/strata/the-year-that-would-not-disappear/data.js';
import * as S from './surface.mjs';

const LEDGER = process.argv.includes('--ledger');
const results = [];
function check(group, name, fn) {
  let ok = false, detail = '';
  try { const r = fn(); ok = r === true; if (!ok) detail = typeof r === 'string' ? r : `returned ${JSON.stringify(r)}`; }
  catch (error) { detail = error.message; }
  results.push({group, name, ok, detail});
}
const refused = (fn, pattern) => { try { fn(); return 'accepted, should have refused'; } catch (e) { return /^REFUSED/.test(e.message) && (!pattern || pattern.test(e.message)) ? true : e.message; } };
const near = (a, b, tol) => Number.isFinite(a) && Number.isFinite(b) && Math.abs(a - b) <= tol;
const rel = (a, b, tol = 1e-6) => Number.isFinite(a) && Number.isFinite(b) && Math.abs(a - b) <= tol * Math.max(Math.abs(a), Math.abs(b), 1e-12);
const clone = x => structuredClone(x);
const sha = file => crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex');
// Standard normal CDF (Abramowitz and Stegun 7.1.26), for the one power cross-check below.
const phi = x => { const t = 1 / (1 + 0.3275911 * Math.abs(x) / Math.SQRT2), y = 1 - (((((1.061405429 * t - 1.453152027) * t) + 1.421413741) * t - 0.284496736) * t + 0.254829592) * t * Math.exp(-x * x / 2); return x >= 0 ? (1 + y) / 2 : (1 - y) / 2; };

const records = S.loadFrozen();
const researchRecords = S.loadFrozen(path.join(S.RESEARCH, 'data'));
const X = JSON.parse(fs.readFileSync(path.join(S.RESEARCH, 'crosscheck.json'), 'utf8'));
const html = fs.readFileSync(path.join(S.PUBLIC, 'index.html'), 'utf8');
const md = fs.readFileSync(path.join(S.ROOT, 'src/content/strata', `${SLUG}.md`), 'utf8');
const record = JSON.parse(fs.readFileSync(path.join(S.PUBLIC, 'record.json'), 'utf8'));
const readme = fs.readFileSync(path.join(S.RESEARCH, 'README.md'), 'utf8');
const summary = S.makeSummary(records);
const D = E.DEFAULTS, PR = E.PRINTED;
const optsFor = state => M.controlOptions(records, state);

// ---------------------------------------------------------------- 1. the claim at full strength
const base = E.anchor(records.dama, {});
check('anchor', 'engine reproduces the printed free and fixed amplitudes, errors and ratios within the declared tolerances', () => base.agrees);
for (const [id, printed, tol] of [['floated-amplitude', 0.01014, E.TOLERANCE.amplitude], ['floated-error', 0.00074, E.TOLERANCE.error], ['floated-ratio', 13.7, E.TOLERANCE.ratio],
  ['fixed-amplitude', 0.00996, E.TOLERANCE.amplitude], ['fixed-error', 0.00074, E.TOLERANCE.error], ['fixed-ratio', 13.4, E.TOLERANCE.ratio]])
  check('anchor', `${id}: recomputed within ${tol} of the printed ${printed}`, () => near(base.rows.find(r => r.id === id).computed, printed, tol) && base.rows.find(r => r.id === id).printed === printed);
check('anchor', 'fixed-fit chi-square within 1 of the printed 130 for 155 degrees of freedom', () => near(base.fixed.chi2, 130, 1) && base.fixed.dof === 155);
check('anchor', 'all 156 points enter: 37 DAMA/NaI and 119 LIBRA', () => records.dama.rows.length === 156 && E.claimantRows(records.dama, 'nai').length === 37 && E.claimantRows(records.dama, 'libra').length === 119);
check('anchor', 'phase read at the central year lies within one printed sigma, and its error within 10% of the printed 4.2', () => near(base.floated.phase, 142.4, 4.2) && Math.abs(base.floated.phaseError / 4.2 - 1) < 0.1);
check('anchor', 'phase read at the 1995 origin does NOT reproduce the printed error (the page says so)', () => { const o = E.anchor(records.dama, {reading:'origin'}); return o.floated.phaseError > 3 * 4.2 && Math.abs(o.floated.phase - 142.4) > 4.2; });
check('anchor', 'period within one printed sigma, and the period error NOT reproduced under any convention (the page says so)', () => {
  if (!near(base.floated.periodYears, 0.99834, 0.00067)) return 'period';
  for (const sampling of ['average', 'centre']) for (const yearDays of [365, 365.25]) { const a = E.anchor(records.dama, {sampling, yearDays}); if (a.floated.periodErrorYears / 0.00067 < 2) return `${sampling} ${yearDays}`; }
  return true;
});
check('anchor', 'the tolerance discriminates: centre sampling fails the anchor', () => E.anchor(records.dama, {sampling:'centre'}).agrees === false);
check('anchor', 'the tolerance discriminates: a 365.25-day year fails the fixed fit and puts its chi-square above 135', () => { const q = E.anchor(records.dama, {yearDays:365.25}); return q.agrees === false && q.rows.find(r => r.id === 'fixed-amplitude').pass === false && q.fixed.chi2 > 135; });
check('anchor', 'a corrupted record fails: every residual rate scaled by 0.9', () => { const bad = clone(records.dama); bad.rows.forEach(r => { r.rate *= 0.9; }); return E.anchor(bad, {}).agrees === false; });
check('anchor', 'a corrupted record fails: every residual error scaled by 1.2', () => { const bad = clone(records.dama); bad.rows.forEach(r => { r.error *= 1.2; }); return E.anchor(bad, {}).agrees === false; });
check('anchor', 'a corrupted record fails: every day moved 30 days later', () => { const bad = clone(records.dama); bad.rows.forEach(r => { r.day += 30; if (r.bin_start !== null) { r.bin_start += 30; r.bin_end += 30; } }); return E.anchor(bad, {}).agrees === false; });
const audit = summary.audit.audit, budget = E.toleranceBudget(audit);
check('anchor', 'the declared tolerances cover the transcription budget from 256 seeded perturbations', () => audit.trials === 256 && budget.covered === true && E.TOLERANCE.amplitude >= budget.amplitude && E.TOLERANCE.error >= budget.error && E.TOLERANCE.ratio >= budget.ratio);
check('anchor', 'at least 95% of the 256 perturbed transcriptions reproduce the anchor, and the page prints the count, not "all"', () => audit.fraction >= 0.95 && summary.audit.text.includes(`${audit.agreeing} of 256 perturbed transcriptions`));
check('anchor', 'the "cover it" sentence is computed: an audit whose movements exceed the tolerance prints "do NOT cover it"', () => {
  const inflated = {...audit, fixedAmplitude:E.TOLERANCE.amplitude};
  return E.toleranceBudget(inflated).covered === false && M.auditView(inflated).text.includes('do NOT cover it') && summary.audit.text.includes(' cover it.') && !summary.audit.text.includes('NOT cover');
});
check('anchor', 'the browser button is not a replay: a different seed perturbs differently', () => {
  const a = E.transcriptionAudit(records.dama, records.calibration, 12, {}, E.AUDIT_SEED), b = E.transcriptionAudit(records.dama, records.calibration, 12, {}, 777);
  return a.seed === E.AUDIT_SEED && b.seed === 777 && a.floatedAmplitude !== b.floatedAmplitude && a.fixedAmplitude !== b.fixedAmplitude;
});
const periods = M.periodErrors(records);
check('anchor', 'period error two ways: the profile interval agrees with an independent NumPy profile, and neither method comes near the printed 0.00067', () =>
  rel(periods.profile.halfWidthYears * 365, X['average:365'].floated.profile_half, 1e-4) && periods.profile.halfWidthYears / 0.00067 > 2 && base.floated.periodErrorYears / 0.00067 > 2);
check('anchor', 'nested fits: this page\'s period errors grow as the record shrinks (24, 16, 8 years) and agree with NumPy; the printed ones barely change', () => {
  const [all, libra, phase2] = periods.nested, x = X['average:365'];
  const numpy = [x.floated.centre.period_error, x.subsets.libra.floated.centre.period_error, x.subsets.phase2.floated.centre.period_error].map(d => d / 365);
  return all.computed < libra.computed && libra.computed < phase2.computed && phase2.computed / all.computed > 2 && Math.max(all.printed, libra.printed, phase2.printed) / Math.min(all.printed, libra.printed, phase2.printed) < 1.2
    && [all, libra, phase2].every((n, i) => rel(n.computed, numpy[i], 2e-6)) && [24, 16, 8].every((y, i) => Math.round([all, libra, phase2][i].span) === y);
});
const subs = E.subsetTable(records.dama), sub = id => subs.find(r => r.id === id);
check('anchor', 'LIBRA-only and phase2-only printed amplitudes come back within the amplitude tolerance', () => ['libra-fixed', 'libra-floated', 'phase2-fixed', 'phase2-floated'].every(id => near(sub(id).computed, sub(id).printed, E.TOLERANCE.amplitude)));
check('anchor', 'DAMA/NaI printed amplitudes come back within tolerance plus printed rounding', () => near(sub('nai-fixed').computed, 0.019, 0.0005 + E.TOLERANCE.amplitude) && near(sub('nai-floated').computed, 0.0200, 0.00005 + E.TOLERANCE.amplitude));
check('anchor', 'no-modulation chi-squares: LIBRA within 1 of 240, DAMA/NaI within 1 of 71', () => near(sub('libra-null').computed, 240, 1) && near(sub('nai-null').computed, 71, 1));
check('anchor', 'subset phases within printed sigma (LIBRA 142.0 ± 4.5, phase2 141.1 ± 5.9, NaI at the origin 140 ± 22)', () => near(sub('libra-phase').computed, 142.0, 4.5) && near(sub('phase2-phase').computed, 141.1, 5.9) && near(sub('nai-phase').computed, 140, 22));
check('anchor', 'DAMA drew June 2 every 365 days: guide lines within the half-unit calibration cell at 365, more than 3 days off at 365.25', () => { const g = E.guideCheck(records.guides, records.calibration); return g[365].n === 56 && g[365].maxAbs <= g.halfCell && g[365.25].maxAbs > 3; });
check('anchor', 'the 1995 epoch and 365-day axis match DAMA Table 1: phase2 first bin starts within 1 day of 2 Nov 2011 and last ends within 1 day of 3 Oct 2019', () => {
  const p2 = E.claimantRows(records.dama, 'phase2');
  return near(p2[0].bin_start, E.dateAxis('2011-11-02', 365), 1) && near(p2.at(-1).bin_end, E.dateAxis('2019-10-03', 365), 1) && !near(p2[0].bin_start, E.dateAxis('2011-11-02', 365) - 365, 5);
});
for (const sampling of ['average', 'centre']) for (const yearDays of [365, 365.25]) {
  const x = X[`${sampling}:${yearDays}`];
  check('anchor', `independent NumPy/SciPy agrees (${sampling}, ${yearDays}): free amplitude, error, period, both phase readings; fixed amplitude, error, chi-square`, () => {
    const c = E.anchor(records.dama, {sampling, yearDays}), o = E.anchor(records.dama, {sampling, yearDays, reading:'origin'});
    const pairs = [[c.floated.amplitude, x.floated.amplitude], [c.floated.error, x.floated.centre.error], [c.floated.period, x.floated.period],
      [c.floated.phase, x.floated.centre_phase], [c.floated.phaseError, x.floated.centre.phase_error], [o.floated.phase, x.floated.origin_peak], [o.floated.phaseError, x.floated.origin.phase_error],
      [c.floated.periodError, x.floated.centre.period_error], [c.fixed.amplitude, x.fixed.amplitude], [c.fixed.error, x.fixed.error], [c.fixed.chi2, x.fixed.chi2]];
    const bad = pairs.findIndex(([a, b]) => !rel(a, b, 2e-6));
    return bad < 0 ? true : `pair ${bad}: ${pairs[bad]}`;
  });
}
check('anchor', 'independent NumPy/SciPy agrees on every subset fit (default conventions)', () => ['libra', 'phase2', 'nai'].every(s => {
  const f = E.fitFixed(records.dama, {subset:s}), g = E.fitFloated(records.dama, {subset:s}), x = X['average:365'].subsets[s];
  return rel(f.amplitude, x.fixed.amplitude, 2e-6) && rel(g.amplitude, x.floated.amplitude, 2e-6) && rel(g.period, x.floated.period, 2e-6);
}));
check('anchor', 'analytic Jacobian matches a numerical derivative of the model (phase error to 0.1%)', () => {
  const f = E.fitFloated(records.dama, {}), rows = records.dama.rows, h = 1e-4;
  const J = E.fitRates(rows, r => [0, 1, 2].map(k => {
    const p = [f.amplitude, f.period, f.peak]; const q = [...p]; p[k] += h; q[k] -= h;
    return (E.wave(r, p[0], p[1], p[2], 'average') - E.wave(r, q[0], q[1], q[2], 'average')) / (2 * h);
  }));
  return rel(Math.sqrt(J.covariance[2][2]), f.phaseError, 1e-3) && rel(Math.sqrt(J.covariance[0][0]), f.error, 1e-3);
});

// ---------------------------------------------------------------- 2. the deciding control
const anais = E.runControl(records.ANAIS, 'ANAIS'), cosine = E.runControl(records.COSINE, 'COSINE');
check('control', 'ANAIS reconstruction within 0.0002 of the printed 0.0011 and its error within 0.0001 of 0.0025', () => near(anais.amplitude, P.anais.amplitude, 0.0002) && near(anais.error, P.anais.error, 0.0001));
check('control', 'all 18 ANAIS nuisance parameters within their printed errors', () => E.anaisNuisance(records.ANAIS, anais).every((n, d) => near(n.index, P.anais.nuisance[d][0], P.anais.nuisance[d][1]) && near(n.fraction, P.anais.nuisance[d][2], P.anais.nuisance[d][3])));
check('control', 'ANAIS against the DAMA value it used (0.0102 ± 0.0008): within 0.05 of the printed 3.5 sigma', () => near(E.tension(anais, P.anais.dama2018), P.anais.tension26, 0.05));
check('control', 'COSINE fit within 0.0002 of the printed 0.0053 and its error within 0.0001 of 0.0031', () => near(cosine.amplitude, P.cosine.amplitude, 0.0002) && near(cosine.error, P.cosine.error, 0.0001));
check('control', 'row counts: ANAIS 9 detectors x 49 rows = 441 including every first row; COSINE 154 valid of 160 with 6 listed exclusions', () =>
  records.ANAIS.rows.length === 441 && [...Array(9).keys()].every(d => records.ANAIS.rows.filter(r => r.detector === d).length === 49 && records.ANAIS.rows.some(r => r.detector === d && r.day === 22.5))
  && records.COSINE.rows.length === 154 && records.COSINE.exclusions.length === 6);
check('control', 'independent NumPy agrees on both control fits', () => rel(anais.amplitude, X.controls.ANAIS.amplitude) && rel(anais.error, X.controls.ANAIS.error) && rel(cosine.amplitude, X.controls.COSINE.amplitude) && rel(cosine.error, X.controls.COSINE.error));
check('control', 'the background templates matter: dropping them moves the ANAIS amplitude by more than one error', () => {
  const noTemplate = E.fitRates(records.ANAIS.rows, r => { const v = Array(10).fill(0); v[r.detector] = 1; v[9] = E.controlCosine(r, records.ANAIS, 'ANAIS'); return v; });
  return Math.abs(noTemplate.coefficients[9] - anais.amplitude) > anais.error;
});
check('control', 'public research copy of every frozen file equals the served copy', () => FILES.every(n => sha(path.join(S.PUBLIC, 'data', n)) === sha(path.join(S.RESEARCH, 'data', n))) && JSON.stringify(researchRecords.dama) === JSON.stringify(records.dama));

// ---------------------------------------------------------------- 3. the control on the control
for (const name of ['ANAIS', 'COSINE']) {
  const rec = records[name], before = JSON.stringify(rec);
  const opts = optsFor(D), p = E.powerTest(rec, name, 'floated', 3, opts);
  check('power', `${name}: the plant goes into a COPY of the released rates; the original record is untouched`, () => JSON.stringify(rec) === before && p.doctored !== rec && p.doctored.rows.length === rec.rows.length);
  check('power', `${name}: the plant's metadata names the printed claim at its printed size (0.01014, period 0.99834 DAMA years); the doctored rates themselves are checked next`, () => p.planted.amplitude === 0.01014 && p.planted.amplitude === PR.floated.amplitude && rel(p.planted.periodDays, 0.99834 * 365, 1e-12));
  check('power', `${name}: every doctored rate equals the released rate plus the waveform, recomputed here with an independent calendar`, () => {
    const epoch = Date.parse(rec.epoch + 'T00:00:00Z'), peak = 365 * summary.centreYear + 142.4;
    return p.doctored.rows.every((r, i) => {
      const d = new Date(epoch + rec.rows[i].day * 86400000), y = d.getUTCFullYear();
      let doy = (d - Date.UTC(y, 0, 1)) / 86400000; if (y % 4 === 0 && doy >= 60) doy -= 1; else if (y % 4 === 0 && doy >= 59) doy = 59;
      const expected = 0.01014 * Math.cos(2 * Math.PI * (365 * (y - 1995) + doy - peak) / (0.99834 * 365));
      return Math.abs(r.rate - rec.rows[i].rate - expected) < 1e-15 && r.error === rec.rows[i].error && r.day === rec.rows[i].day;
    });
  });
  check('power', `${name}: the recovered fit is the page's own runControl on the doctored copy`, () => { const again = E.runControl(p.doctored, name); return again.amplitude === p.recovered.amplitude && again.error === p.recovered.error && M.controlView(records, {...D, control:name, template:'floated'}).power.recovered.amplitude === p.recovered.amplitude; });
  check('power', `${name}: the decision is the plant alone (paired change over the refitted error), never the doctored total`, () =>
    rel(p.plantAlone.ratio, p.paired / p.recovered.error, 1e-12) && p.detection.found === (p.plantAlone.ratio >= 3) && p.totalDetection.found === (p.recovered.ratio >= 3));
  check('power', `${name}: the plant-alone significance agrees with independent NumPy (paired change over error)`, () => rel(p.plantAlone.ratio, X.controls[name]['floated:centre:365'] / X.controls[name].error, 1e-6));
  check('power', `${name}: the untouched record does not show it at 3`, () => p.baseline.ratio < 3 && p.baselineDetection.found === false);
  check('power', `${name}: at 5 standard errors the plant alone is NOT detected, and the page says INCONCLUSIVE`, () => E.detection(p.plantAlone, 5).found === false && E.detection(p.plantAlone, 5).label === 'INCONCLUSIVE AT THIS THRESHOLD' && summary.control.grade.includes('this test is INCONCLUSIVE'));
  check('power', `${name}: linearity: runControl on a copy holding only the plant returns the change and the plant-alone ratio`, () => { const only = clone(rec); only.rows = rec.rows.map((r, i) => ({...r, rate:p.doctored.rows[i].rate - r.rate})); const f = E.runControl(only, name); return rel(f.amplitude, p.paired, 1e-9) && rel(f.ratio, p.plantAlone.ratio, 1e-9); });
  check('power', `${name}: the fixed plant adds exactly its printed amplitude (template identity)`, () => near(E.powerTest(rec, name, 'fixed', 3, opts).paired, PR.fixed.amplitude, 1e-12));
  check('power', `${name}: the fit is phase-sensitive: the same wave half a year late gives a negative change`, () => {
    const late = clone(rec); late.rows = rec.rows.map((r, i) => ({...r, rate:r.rate - (p.doctored.rows[i].rate - r.rate)}));
    return E.runControl(late, name).amplitude - p.baseline.amplitude < -0.008;
  });
  check('power', `${name}: independent NumPy agrees on every plant (both readings, both year lengths, fixed)`, () => ['centre', 'origin'].every(reading => [365, 365.25].every(yearDays =>
    rel(E.powerTest(rec, name, 'floated', 3, {yearDays, reading, centreYear:E.claimantCentreYear(records.dama, yearDays)}).paired, X.controls[name][`floated:${reading}:${yearDays}`], 1e-6)))
    && rel(E.powerTest(rec, name, 'fixed', 3, opts).paired, X.controls[name].fixed, 1e-6));
}
check('power', 'the page\'s error matches ANAIS\'s own simulated spread under DAMA (2.50 cpd/ton/keV) within 3%', () => Math.abs(1000 * anais.error / P.anais.mcSigma - 1) < 0.03);
check('power', 'ANAIS\'s own stated sensitivity, (4.1 ± 0.3) σ in 2-6 keV, comes back as the DAMA amplitude it used over this page\'s error', () => near(P.anais.dama2018.amplitude / anais.error, P.anais.sensitivity26, 0.05));
check('power', 'a total that includes the control\'s own excess cannot lend it power: COSINE with every error x1.5 still totals above 3 but its plant alone reads INCONCLUSIVE', () => {
  const wide = clone(records.COSINE); wide.rows.forEach(r => { r.error *= 1.5; });
  const p = E.powerTest(wide, 'COSINE', 'floated', 3, optsFor(D));
  return p.recovered.ratio >= 3 && p.plantAlone.ratio < 3 && p.detection.found === false && p.detection.label === 'INCONCLUSIVE AT THIS THRESHOLD';
});
check('power', 'two routes to COSINE\'s power at 3: its own pseudo-experiments and a normal curve on this page\'s plant alone agree within 0.1', () => {
  const pc = summary.powers.COSINE; return Math.abs(summary.pseudo.above[0] - phi(pc.plantAlone.ratio - 3)) < 0.1 && summary.pseudo.above[0] > 0.5 && summary.pseudo.above[0] < 0.65;
});
check('power', 'every "clears" column is the plant-alone decision, in the plants table and the calendar table', () => {
  const inj = summary.injections, cal = summary.calendars; let i = 0;
  for (const name of ['ANAIS', 'COSINE']) for (const template of ['floated', 'fixed']) {
    const p = E.powerTest(records[name], name, template, 3, optsFor(D)), row = inj[i++];
    if (row[4] !== M.fmt(p.plantAlone.ratio, 2) || row[6] !== (p.plantAlone.ratio >= 3 ? 'yes' : 'no') || row[7] !== (p.plantAlone.ratio >= 5 ? 'yes' : 'no')) return `plants row ${i}`;
  }
  i = 0;
  for (const reading of ['centre', 'origin']) for (const yearDays of [365, 365.25]) {
    const o = {yearDays, reading, centreYear:E.claimantCentreYear(records.dama, yearDays)}, row = cal[i++];
    const a = E.powerTest(records.ANAIS, 'ANAIS', 'floated', 3, o), c = E.powerTest(records.COSINE, 'COSINE', 'floated', 3, o);
    if (row[2] !== M.fmt(a.plantAlone.ratio, 2) || row[3] !== (a.plantAlone.ratio >= 3 ? 'yes' : 'no') || row[5] !== M.fmt(c.plantAlone.ratio, 2) || row[6] !== (c.plantAlone.ratio >= 3 ? 'yes' : 'no')) return `calendar row ${i}`;
  }
  return true;
});
check('power', 'COSINE\'s own 300,000 pseudo-experiments: mean within 0.0002 of DAMA\'s 0.00996, spread within 10% of this page\'s error', () => { const s = summary.pseudo; return s.n === 300000 && near(s.mean, 0.00996, 0.0002) && Math.abs(s.sd / cosine.error - 1) < 0.1; });
check('power', 'the page prints grade A and record.json declares A-injection', () => /Grade A: the claim, at its printed size, planted in the control's own released data/.test(html) && record.power.grade === 'A-injection');

// ---------------------------------------------------------------- 4. the operation on nothing
const unit = M.unitSweep(records, D), sweep = E.scaleSweep(unit, D.slope);
check('null', 'zero slope, computed directly at eight boundaries, induces nothing (a spec requirement; any mean-subtracting operator passes it, so the checks below carry the weight)', () => [0, 56, 100, 152, 200, 243, 300, 364].every(b => Math.abs(E.boundaryExperiment(records.dama, {slope:0, boundary:b}).induced.signed) < 1e-15));
check('null', 'a continuous straight-line fit induces zero for a nonzero slope', () => [0.05, -0.05, 0.031].every(slope => Math.abs(E.boundaryExperiment(records.dama, {slope, method:'continuous'}).induced.signed) < 1e-14));
check('null', 'linearity: the scaled sweep equals a direct computation at the default slope', () => [0, 56, 100, 152, 200, 243, 300, 364].every(b => rel(E.boundaryExperiment(records.dama, {boundary:b}).induced.signed, sweep[b].induced, 1e-9) && rel(E.boundaryExperiment(records.dama, {boundary:b}).retention, sweep[b].retention, 1e-9)));
check('null', 'independent NumPy agrees on the sweep and on DAMA\'s own cycles', () => Object.entries(X.sweep).every(([b, v]) => rel(sweep[Number(b)].induced, v.induced, 1e-6) && rel(sweep[Number(b)].retention, v.retained, 1e-6))
  && rel(summary.boundary.historical.induced.signed, X.historical.induced, 1e-6) && rel(summary.boundary.historical.retention, X.historical.retained, 1e-6));
check('null', 'ideal-sampling limit verified by independent numerical integration of a sawtooth: (b/pi) sin(2 pi (d - 152.5)/Y)', () => {
  const Y = 365, b = 0.031, n = 20000;
  return [0, 61, 152, 243, 300].every(d => {
    let sc = 0, cc = 0;
    for (let i = 0; i < n; i++) { const t = d + (i + 0.5) * Y / n, ramp = b * ((t - d) / Y - 0.5), c = Math.cos(2 * Math.PI * (t - 152.5) / Y); sc += ramp * c; cc += c * c; }
    return near(sc / cc, E.idealInduced(b, d, Y), 1e-6);
  });
});
check('null', 'a falling background flips the sign of what is induced (wiring: true of any linear pipeline)', () => rel(E.boundaryExperiment(records.dama, {slope:-0.031}).induced.signed, -E.boundaryExperiment(records.dama, {slope:0.031}).induced.signed, 1e-9));
check('null', 'DAMA/LIBRA cycles: 15 cycles and 119 points enter, starting between day 197 and day 315', () => { const h = summary.boundary.historical; return h.cycles === 15 && h.n === 119 && h.startMin === 197 && h.startMax === 315; });
check('null', 'a true annual signal keeps between 85% and 100% at every boundary', () => sweep.every(r => r.retention > 0.85 && r.retention <= 1.0000001));
check('null', 'the answer the sweep gives, run back through the unmodified historicalCycles: the stated slope induces DAMA/LIBRA\'s printed 0.00941, and Buttazzo\'s 0.0219 induces what the page says', () => {
  const b = summary.boundary, back = E.historicalCycles(records.dama, records.cycles, {slope:b.need}).induced.signed, butt = E.historicalCycles(records.dama, records.cycles, {slope:P.buttazzo.bestSlope}).induced.signed;
  return rel(back, PR.libraFixed.amplitude, 1e-9) && rel(butt, b.buttazzoInduced, 1e-9) && b.need > PR.libraFixed.amplitude && b.historicalText.includes(M.sgn(b.need, 4)) && b.historicalText.includes(M.sgn(butt, 4));
});
check('null', 'the sweep markers sit on the readout, in annual and in continuous mode', () => [['annual', 243], ['annual', 56], ['continuous', 243]].every(([method, boundary]) => {
  const v = M.boundaryView(records, {...D, method, boundary}, unit);
  const ok = v.inducedPlot.marker === v.experiment.induced.signed && v.retainedPlot.marker === v.experiment.retention && v.inducedPlot.method === method;
  return ok && (method === 'annual' ? rel(v.inducedPlot.marker, v.sweep[boundary].induced, 1e-9) : Math.abs(v.inducedPlot.marker) < 1e-14 && Math.abs(v.retainedPlot.marker - 1) < 1e-12);
}));

// ---------------------------------------------------------------- 5. every choice is live
const cv = (over) => M.controlView(records, {...D, ...over});
check('choices', 'control: ANAIS and COSINE give different amplitudes and errors', () => cv({control:'ANAIS'}).power.baseline.amplitude !== cv({control:'COSINE'}).power.baseline.amplitude);
check('choices', 'template: none, floated and fixed give three different recovered amplitudes', () => new Set(['none', 'floated', 'fixed'].map(t => cv({template:t}).power.recovered.amplitude)).size === 3);
check('choices', 'threshold: 3 and 5 change the margin and flip the detection of the floated ANAIS plant', () => { const a = cv({template:'floated', threshold:3}), b = cv({template:'floated', threshold:5}); return a.margin !== b.margin && a.power.detection.found && !b.power.detection.found; });
check('choices', 'sampling: bin average and bin centre give different anchors and gaps', () => { const a = E.anchor(records.dama, {sampling:'average'}), b = E.anchor(records.dama, {sampling:'centre'}); return a.floated.amplitude !== b.floated.amplitude && a.rows[0].gap !== b.rows[0].gap; });
check('choices', 'yearDays: 365 and 365.25 change the fixed fit, the phase day and the plant', () => { const a = E.anchor(records.dama, {yearDays:365}), b = E.anchor(records.dama, {yearDays:365.25}); return a.fixed.amplitude !== b.fixed.amplitude && a.floated.phase !== b.floated.phase && cv({template:'floated', yearDays:365}).power.paired !== cv({template:'floated', yearDays:365.25}).power.paired; });
check('choices', 'reading: centre and origin change the phase and the floated plant', () => E.anchor(records.dama, {reading:'centre'}).floated.phase !== E.anchor(records.dama, {reading:'origin'}).floated.phase && cv({template:'floated', reading:'centre'}).power.paired !== cv({template:'floated', reading:'origin'}).power.paired);
check('choices', 'slope: zero gives zero; two nonzero slopes give different induced amplitudes and total changes', () => { const e = s => E.boundaryExperiment(records.dama, {slope:s}); return e(0).induced.signed === 0 && e(0.02).induced.signed !== e(0.031).induced.signed && e(0.02).totalChange !== e(0.031).totalChange; });
check('choices', 'boundary: 1 September and 26 February induce opposite signs and different retentions', () => { const a = E.boundaryExperiment(records.dama, {boundary:243}), b = E.boundaryExperiment(records.dama, {boundary:56}); return a.induced.signed > 0 && b.induced.signed < 0 && a.retention !== b.retention; });
check('choices', 'method: annual subtraction and a continuous fit give different induced amplitudes', () => E.boundaryExperiment(records.dama, {method:'annual'}).induced.signed !== E.boundaryExperiment(records.dama, {method:'continuous'}).induced.signed);
// Every output each choice claims to move, at two of its settings, through the page's own functions.
const bx = o => E.boundaryExperiment(records.dama, {...o});
const EFFECTS = {
  control:{'control rate series':() => [cv({control:'ANAIS'}).plot.original.map(p => p.y), cv({control:'COSINE'}).plot.original.map(p => p.y)],
    'fitted amplitude':() => [cv({control:'ANAIS'}).power.baseline.amplitude, cv({control:'COSINE'}).power.baseline.amplitude],
    'fitted error':() => [cv({control:'ANAIS'}).power.baseline.error, cv({control:'COSINE'}).power.baseline.error],
    'injection result':() => [cv({control:'ANAIS', template:'floated'}).power.paired, cv({control:'COSINE', template:'floated'}).power.paired]},
  template:{'doctored rates':() => [cv({template:'floated'}).power.doctored.rows.map(r => r.rate), cv({template:'fixed'}).power.doctored.rows.map(r => r.rate)],
    'fitted amplitude':() => [cv({template:'none'}).power.recovered.amplitude, cv({template:'floated'}).power.recovered.amplitude],
    'plant-alone detection statistic':() => [cv({template:'floated'}).power.plantAlone.ratio, cv({template:'fixed'}).power.plantAlone.ratio]},
  threshold:{'threshold margin':() => [cv({template:'floated', threshold:3}).margin, cv({template:'floated', threshold:5}).margin],
    'detection state':() => [cv({template:'floated', threshold:3}).power.detection.found, cv({template:'floated', threshold:5}).power.detection.found]},
  sampling:{'reconstructed amplitude':() => [E.anchor(records.dama, {sampling:'average'}).floated.amplitude, E.anchor(records.dama, {sampling:'centre'}).floated.amplitude],
    'anchor gap':() => [E.anchor(records.dama, {sampling:'average'}).rows[0].gap, E.anchor(records.dama, {sampling:'centre'}).rows[0].gap],
    'boundary sweep':() => [bx({sampling:'average'}).induced.signed, bx({sampling:'centre'}).induced.signed]},
  yearDays:{'fixed-fit amplitude and chi-square':() => [[E.fitFixed(records.dama, {yearDays:365}).amplitude, E.fitFixed(records.dama, {yearDays:365}).chi2], [E.fitFixed(records.dama, {yearDays:365.25}).amplitude, E.fitFixed(records.dama, {yearDays:365.25}).chi2]],
    'period in years':() => [E.fitFloated(records.dama, {yearDays:365}).periodYears, E.fitFloated(records.dama, {yearDays:365.25}).periodYears],
    'phase day':() => [E.fitFloated(records.dama, {yearDays:365}).phase, E.fitFloated(records.dama, {yearDays:365.25}).phase],
    'planted waveform calendar':() => [cv({template:'floated', yearDays:365}).formula.formula, cv({template:'floated', yearDays:365.25}).formula.formula]},
  reading:{'recomputed phase and its error':() => [[E.fitFloated(records.dama, {reading:'centre'}).phase, E.fitFloated(records.dama, {reading:'centre'}).phaseError], [E.fitFloated(records.dama, {reading:'origin'}).phase, E.fitFloated(records.dama, {reading:'origin'}).phaseError]],
    'maximum of the floated plant':() => [M.plantedPeaks(records, {...D, reading:'centre'}), M.plantedPeaks(records, {...D, reading:'origin'})]},
  slope:{'induced amplitude':() => [bx({slope:0.02}).induced.signed, bx({slope:0.031}).induced.signed],
    'total rate change':() => [bx({slope:0.02}).totalChange, bx({slope:0.031}).totalChange]},
  boundary:{'induced amplitude':() => [bx({boundary:243}).induced.signed, bx({boundary:56}).induced.signed],
    'induced phase':() => [bx({boundary:243}).induced.phase, bx({boundary:100}).induced.phase],
    'retained true-signal amplitude':() => [bx({boundary:243}).retention, bx({boundary:56}).retention]},
  method:{'induced amplitude':() => [bx({method:'annual'}).induced.signed, bx({method:'continuous'}).induced.signed],
    'retained true-signal amplitude':() => [bx({method:'annual'}).retention, bx({method:'continuous'}).retention]},
};
for (const c of S.CHOICES) for (const a of c.affects) check('choices', `${c.id} moves "${a}"`, () => {
  if (!EFFECTS[c.id]?.[a]) return 'no effect test for this named output';
  const [x, y] = EFFECTS[c.id][a](); return JSON.stringify(x) !== JSON.stringify(y) && x !== undefined && y !== undefined;
});
check('choices', 'every declared choice is an engine default, has a labelled control on the page, and its inert flag equals what the effect tests computed', () => {
  const ids = {control:'experiment', template:'template', threshold:'threshold', sampling:'sampling', yearDays:'year', reading:'reading', slope:'slope', boundary:'boundary-day', method:'method'};
  const moves = c => c.affects.every(a => { const [x, y] = EFFECTS[c.id][a](); return JSON.stringify(x) !== JSON.stringify(y); });
  return S.CHOICES.every(c => c.id in D && D[c.id] === c.default && new RegExp(`<label for="${ids[c.id]}">`).test(html) && new RegExp(`id="${ids[c.id]}"`).test(html) && c.inert === !moves(c));
});

// ---------------------------------------------------------------- 6. faults planted in data
check('fault', 'removing the first row of each ANAIS detector in a copy makes the unmodified fit refuse', () => { const bad = clone(records.ANAIS); bad.rows = bad.rows.filter(r => r.day !== 22.5); return bad.rows.length === 432 && refused(() => E.runControl(bad, 'ANAIS'), /expected 441/) === true; });
check('fault', 'a wrong ANAIS epoch on a copy (1 January instead of 3 August 2017) changes the unmodified estimate by more than half an error', () => { const bad = clone(records.ANAIS); bad.epoch = '2017-01-01'; return Math.abs(E.runControl(bad, 'ANAIS').amplitude - anais.amplitude) > 0.5 * anais.error; });
check('fault', 'a wrong COSINE epoch on a copy (1 April 2016) changes the unmodified estimate by more than half an error', () => { const bad = clone(records.COSINE); bad.epoch = '2016-04-01'; return Math.abs(E.runControl(bad, 'COSINE').amplitude - cosine.amplitude) > 0.5 * cosine.error; });
check('fault', 'a claimant record with one point nudged 0.05 upward at the heaviest LIBRA bin moves the fixed amplitude', () => { const bad = clone(records.dama); const i = bad.rows.reduce((b, r, k) => r.error < bad.rows[b].error ? k : b, 0); bad.rows[i].rate += 0.05; return Math.abs(E.fitFixed(bad).amplitude - base.fixed.amplitude) > 1e-4; });
check('fault', 'a claimant record with its rates scaled by 0.9 fails the anchor (fault acts on data, not on results)', () => { const bad = clone(records.dama); bad.rows.forEach(r => { r.rate *= 0.9; }); const a = E.anchor(bad, {}); return !a.agrees && a.rows.find(r => r.id === 'floated-amplitude').pass === false; });

// ---------------------------------------------------------------- 7. refusals
check('refuse', 'a 1-6 keV record is refused', () => { const bad = clone(records.COSINE); bad.energy = [1, 6]; return refused(() => E.runControl(bad, 'COSINE'), /2-6 keV/); });
check('refuse', 'a 0.5-6 keV claimant record is refused', () => { const bad = clone(records.dama); bad.energy = [0.5, 6]; return refused(() => E.anchor(bad, {}), /2-6 keV/); });
check('refuse', 'an undefined epoch is refused', () => { const bad = clone(records.COSINE); bad.epoch = 'January 2016'; return refused(() => E.runControl(bad, 'COSINE'), /epoch/); });
check('refuse', 'duplicate point identities are refused', () => { const bad = clone(records.dama); bad.rows[1].id = bad.rows[0].id; return refused(() => E.anchor(bad, {}), /duplicate/); });
check('refuse', 'a nonpositive uncertainty is refused', () => { const bad = clone(records.dama); bad.rows[5].error = 0; return refused(() => E.anchor(bad, {}), /nonpositive/); });
check('refuse', 'too few independent time bins are refused', () => refused(() => E.fitRates(records.dama.rows.slice(0, 3), r => [1]), /insufficient/));
check('refuse', 'a singular design is refused', () => refused(() => E.fitRates(records.dama.rows, r => [1, 2]), /singular/));
check('refuse', 'an incomplete claimant record (155 points) is refused', () => { const bad = clone(records.dama); bad.rows.pop(); return refused(() => E.anchor(bad, {}), /156/); });
check('refuse', 'a slope outside plus or minus 0.05 and a boundary outside whole days 0 to 364 are refused', () => refused(() => E.boundaryExperiment(records.dama, {slope:0.06})) === true && refused(() => E.boundaryExperiment(records.dama, {boundary:365})) === true && refused(() => E.boundaryExperiment(records.dama, {boundary:2.5})) === true);
check('refuse', 'a threshold other than 3 or 5 is refused', () => refused(() => E.detection(anais, 4), /3 or 5/));
check('refuse', 'the hybrid waveform the spec warned against (floated amplitude, fixed phase) is refused as a template', () => refused(() => E.inject(records.ANAIS, 'ANAIS', 'hybrid'), /unsupported/));
check('refuse', 'a year that is neither 365 nor 365.25 days is refused, by the calendar and by the claimant fits', () => refused(() => E.damaAxis(Date.parse('2018-01-01'), 366), /365/) === true && refused(() => E.anchor(records.dama, {yearDays:366}), /365/) === true);
const GATES = {latest:/2-6 keV/, window:/2-6 keV/, hybrid:/unsupported/, year:/365/, incomplete:/156/, firstRows:/expected 441/, threshold:/3 or 5/};
for (const key of Object.keys(E.REQUESTS)) check('refuse', `request "${key}" goes through the real gate and is refused; its allowed twin is accepted; it is offered on the page`, () => {
  const no = E.ask(records, key), yes = E.ask(records, key, 'allowed');
  if (!GATES[key]) return 'no expected gate named for this request';
  return no.accepted === false && /^REFUSED/.test(no.message) && GATES[key].test(no.message) && yes.accepted === true && html.includes(`<option value="${key}">${S.escape(E.REQUESTS[key].label)}</option>`) ? true : `${no.message} | ${yes.message}`;
});
check('refuse', 'the stated limits are printed as limits, not dressed as computed refusals', () => E.LIMITS.every(l => html.includes(`<li>${S.escape(l)}</li>`)) && !/refuseInference|REFUSALS/.test(fs.readFileSync(path.join(S.PUBLIC, 'page.js'), 'utf8')));

// ---------------------------------------------------------------- 8. provenance
const hashes = Object.fromEntries(S.RECORD_FILES.map(r => [r.file, sha(path.join(S.PUBLIC, 'data', r.file))]));
check('provenance', 'every shipped data file is listed in record.json with its SHA-256, and the bytes match', () => S.RECORD_FILES.every(r => { const e = record.records.find(x => x.file === r.file); return e && e.sha256 === hashes[r.file] && e.retrieved === '2026-09-22'; }) && record.records.length === S.RECORD_FILES.length);
check('provenance', 'every shipped data file appears in the README with the same SHA-256', () => S.RECORD_FILES.every(r => readme.includes(r.file) && readme.includes(hashes[r.file])));
check('provenance', 'nothing else is shipped in data/', () => fs.readdirSync(path.join(S.PUBLIC, 'data')).sort().join() === S.RECORD_FILES.map(r => r.file).sort().join());
check('provenance', 'the retrieval logs record HTTP 200 for every source the extracts were made from', () => {
  const m = JSON.parse(fs.readFileSync(path.join(S.PUBLIC, 'data/source-manifest.json'), 'utf8')), s = JSON.parse(fs.readFileSync(path.join(S.PUBLIC, 'data/source-manifest-supplement.json'), 'utf8'));
  const need = ['dama2021.tar', 'dama2008.tar', 'cosine.csv', ...[...Array(9).keys()].flatMap(d => [`anais-event-D${d}.csv`, `anais-bkg-D${d}.csv`])];
  return need.every(f => m.find(e => e.file === f)?.status === 200) && ['cosine-pseudo-erc2-6.csv', 'dama2013.pdf'].every(f => s.find(e => e.file === f)?.status === 200);
});
check('provenance', 'the COSINE pseudo-experiment extract has the collaboration file\'s shape (100 bins, 300,000 experiments), and the source file\'s SHA-256 is logged', () => {
  const s = JSON.parse(fs.readFileSync(path.join(S.PUBLIC, 'data/source-manifest-supplement.json'), 'utf8')), e = s.find(x => x.file === 'cosine-pseudo-erc2-6.csv');
  return records.pseudo.rows.length === 100 && records.pseudo.rows.reduce((n, r) => n + r.pseudo_experiments, 0) === 300000 && /^[0-9a-f]{64}$/.test(e?.sha256 || '');
});

// ---------------------------------------------------------------- 9. verdict
const verdictSection = html.slice(html.indexOf('<section id="verdict"'), html.indexOf('</section>', html.indexOf('<section id="verdict"')));
check('verdict', 'the page prints OPEN with its as-of date, and record.json agrees', () => /<span class="verdict-word">OPEN<\/span> as of 22 September 2026/.test(verdictSection) && record.verdict.category === 'OPEN' && record.verdict.as_of === '2026-09-22');
check('verdict', 'at least two sources establishing the verdict are linked in the verdict section and listed in record.json', () => (verdictSection.match(/<a href="https?:/g) || []).length >= 4 && record.verdict.sources.length >= 2);
check('verdict', 'what would change the verdict is printed and equals record.json', () => PAGE.wouldChange.every(w => verdictSection.includes(S.escape(w))) && record.verdict.would_change === [...PAGE.wouldChange, PAGE.dismantled].join(' '));
check('verdict', 'decided by: not yet; no invented time to decision', () => record.decided_by === 'not-yet' && record.years_to_decision === null && verdictSection.includes('Decided by: not yet.'));
check('verdict', 'an OPEN claim is never called debunked, refuted or disproved, anywhere', () => ![html, md, JSON.stringify(record)].some(t => /debunk|refuted|refute\b|disprov/i.test(t)));
check('verdict', 'no fraud, fabrication or misconduct language anywhere', () => ![html, md, JSON.stringify(record)].some(t => /fraud|fabricat|misconduct/i.test(t)));
check('verdict', 'the claimants\' reply is given, with their words quoted at their printed scope ("some of their conclusions")', () => verdictSection.includes('<q>the observed DAMA annual modulation result cannot be mimicked by an artifact of the analysis method</q>') && verdictSection.includes('<q>some of their conclusions</q>') && verdictSection.includes('<q>the intrinsically uncertain joint combinations</q>'));
check('verdict', 'the June 2026 ANAIS full-exposure numbers are labelled preliminary and are not computed from', () => /preliminary results from its full 8\.4-year exposure/.test(verdictSection) && verdictSection.includes('marked preliminary') && verdictSection.includes('nothing on this page is computed from them'));
check('verdict', 'no out-of-date claim that DAMA never published a rate time series', () => !/never been published as a time series/.test(html));

// ---------------------------------------------------------------- 10. the rendered surface
const strip = s => s.replace(/<!--aw-[a-z-]+:start-->[\s\S]*?<!--aw-[a-z-]+:end-->/g, '');
const served = strip(html);
const mainServed = served.slice(served.indexOf('<main id="main">'), served.indexOf('</main>') + 7);
const mainExpected = S.makeMain(records, summary);
check('surface', 'every figure in the served <main> equals a fresh calculation, character for character', () => {
  if (mainServed === mainExpected) return true;
  let i = 0; while (i < mainServed.length && mainServed[i] === mainExpected[i]) i++;
  return `first difference at ${i}: served "${mainServed.slice(Math.max(0, i - 60), i + 60)}" expected "${mainExpected.slice(Math.max(0, i - 60), i + 60)}"`;
});
const meta = (attr, key) => { const m = served.match(new RegExp(`<meta ${attr}="${key.replace(/[:.]/g, '\\$&')}" content="([^"]*)"`)); return m ? m[1] : null; };
const canonical = `https://artwaste.land/strata/${SLUG}/`, og = `https://artwaste.land/og/${SLUG}.png`;
check('surface', 'head: title, description, canonical, OG and Twitter tags match the recomputed page', () => {
  const want = [['name', 'description', S.escape(PAGE.dek)], ['property', 'og:title', `${S.escape(PAGE.title)} &middot; Artificial Wasteland`], ['property', 'og:description', S.escape(PAGE.dek)], ['property', 'og:url', canonical],
    ['property', 'og:image', og], ['property', 'og:type', 'article'], ['name', 'twitter:card', 'summary_large_image'], ['name', 'twitter:title', `${S.escape(PAGE.title)} &middot; Artificial Wasteland`], ['name', 'twitter:description', S.escape(PAGE.dek)], ['name', 'twitter:image', og]];
  const bad = want.find(([a, k, v]) => meta(a, k) !== v);
  return bad ? `head ${bad[1]}` : served.includes(`<title>${S.escape(PAGE.seoTitle)}</title>`) && served.includes(`<link rel="canonical" href="${canonical}">`);
});
check('surface', 'the whole served <head> (injected aw- blocks aside) equals the recomputed head, JSON-LD included', () => {
  const h = served.slice(served.indexOf('<head>'), served.indexOf('</head>') + 7);
  return h === strip(S.makeHead(summary)) ? true : 'head differs';
});
check('surface', 'head: the JSON-LD parses and names the page, its dek and its image', () => {
  const m = html.match(/<script type="application\/ld\+json">([\s\S]*?)<\/script>/); const ld = JSON.parse(m[1]);
  return ld['@type'] === 'Article' && ld.name === PAGE.seoTitle && ld.headline === PAGE.title && ld.description === PAGE.dek && ld.url === canonical && ld.image === og;
});
check('surface', 'the plain placard is on the page, in the head and in the frontmatter, identically', () => html.includes(`<p id="plain-placard" class="plain">${S.escape(PAGE.plain)}</p>`) && md.includes(`plain: "${PAGE.plain}"`) && (!/aw-plain/.test(html) || html.includes(`<meta name="aw-plain" content="${S.escape(PAGE.plain)}"`)));
check('surface', 'the frontmatter and its body equal a fresh calculation (the landing date excepted)', () => md.replace(/^date: .*$/m, 'date: X') === S.makeFrontmatter(summary).replace(/^date: .*$/m, 'date: X'));
check('surface', 'record.json equals a fresh calculation in every field (its ledger is compared with the computed one at the end)', () => {
  const own = Object.fromEntries(S.LEDGER_KEYS.map(k => [k, record.ledger?.[k]?.value]));
  return JSON.stringify(record) === JSON.stringify(S.makeRecord(records, summary, hashes, own));
});
check('surface', 'spot check against the independent NumPy values, not the factory: the anchor readout carries them', () => {
  const x = X['average:365'].floated; return html.includes(`${M.fmt(x.amplitude)} ± ${M.fmt(x.centre.error)} cpd/kg/keV, ${M.fmt(x.amplitude / x.centre.error, 2)} standard errors`) && html.includes(`χ² ${M.fmt(X['average:365'].fixed.chi2, 1)} for 155 degrees of freedom`);
});
check('surface', 'spot check: the printed claim, the quotation and the 2026 update appear exactly', () => html.includes('(0.01014 ± 0.00074) cpd/kg/keV at 13.7 σ') && html.includes(`<q>${PAGE.quote}</q>`) && html.includes('(0.01028 ± 0.00067) cpd/kg/keV at 15.3 σ'));
check('surface', 'load-bearing closing tags, and the only inline script is the JSON-LD', () => /<\/script>\n<\/body>\n<\/html>\n$/.test(html) && (html.match(/<script(?![^>]*\bsrc=)[^>]*>/g) || []).length === 1 && /<script type="module" src="\.\/page\.js"><\/script>/.test(html));
check('surface', 'every module parses (node --check)', () => ['engine.js', 'data.js', 'model.js', 'render.js', 'page.js'].every(f => { execFileSync(process.execPath, ['--check', path.join(S.PUBLIC, f)]); return true; }));
check('surface', 'zero third-party requests: one fetch, of ./data/ beside data.js; no dynamic import, XHR, socket, beacon or worker; every script and stylesheet same-origin', () => {
  const code = Object.fromEntries(['engine.js', 'data.js', 'model.js', 'render.js', 'page.js'].map(f => [f, fs.readFileSync(path.join(S.PUBLIC, f), 'utf8')]));
  const all = Object.values(code).join('\n');
  if (/XMLHttpRequest|WebSocket|EventSource|sendBeacon|importScripts|new Worker|import\s*\(|new Image|\.src\s*=/.test(all)) return 'network primitive found';
  if ((all.match(/fetch\(/g) || []).length !== 1 || !/fetch\(new URL\('\.\/data\/' \+ name, import\.meta\.url\)\)/.test(code['data.js'])) return 'fetch';
  if (/https?:\/\//.test(code['engine.js'] + code['model.js'] + code['render.js'] + code['page.js'])) return 'absolute URL in code';
  const refs = [...html.matchAll(/<(?:script|link)[^>]+(?:src|href)="([^"]+)"/g)].map(m => m[1]).filter(u => !/^https:\/\/artwaste\.land\//.test(u));
  return refs.every(u => u.startsWith('/') || u.startsWith('./')) ? true : refs.join(' ');
});
check('surface', 'accessibility: every control is a native element with a label, readouts are live regions, canvases are labelled images, focus is visible, motion is guarded', () => {
  const css = fs.readFileSync(path.join(S.PUBLIC, 'style.css'), 'utf8');
  const ids = [...html.matchAll(/<(select|input)[^>]*id="([^"]+)"/g)].map(m => m[2]);
  return ids.length >= 10 && ids.every(id => html.includes(`<label for="${id}">`)) && !/onclick=|<span[^>]*tabindex/.test(html)
    && (html.match(/role="status" aria-live="polite"/g) || []).length >= 8 && [...html.matchAll(/<canvas[^>]*>/g)].every(m => /role="img"/.test(m[0]) && /aria-label="[^"]{20,}"/.test(m[0]))
    && /:focus-visible/.test(css) && /prefers-reduced-motion/.test(css) && html.includes('<link rel="stylesheet" href="/fonts/fonts.css">');
});
check('surface', 'mobile: every table sits inside a scrolling wrapper, and no fixed width above 390px outside one', () => {
  const css = fs.readFileSync(path.join(S.PUBLIC, 'style.css'), 'utf8');
  const tables = (html.match(/<table>/g) || []).length, wrapped = (html.match(/<div class="table-wrap"[^>]*>\s*<table>/g) || []).length;
  const widths = [...css.matchAll(/(?<!max-)(?<!min-)width:\s*(\d+(?:\.\d+)?)(px|rem)/g)].map(m => Number(m[1]) * (m[2] === 'rem' ? 16 : 1));
  return tables === wrapped && tables >= 6 && widths.every(w => w <= 390) && /\.table-wrap\{overflow-x:auto/.test(css);
});
check('surface', 'no em dash in anything written for this page (quotations included)', () => {
  const files = [...['index.html', 'engine.js', 'data.js', 'model.js', 'render.js', 'page.js', 'style.css', 'NOTICE.txt', 'record.json'].map(f => path.join(S.PUBLIC, f)),
    ...fs.readdirSync(S.RESEARCH).filter(f => /\.(mjs|py|md|json)$/.test(f)).map(f => path.join(S.RESEARCH, f)), path.join(S.ROOT, 'src/content/strata', `${SLUG}.md`)];
  const report = path.join(S.ROOT, 'oversight/waves/2026-09-22-at-full-strength/out', `build-${SLUG}.md`);
  if (fs.existsSync(report)) files.push(report);
  const bad = files.filter(f => fs.readFileSync(f, 'utf8').includes(String.fromCharCode(0x2014)));
  return bad.length ? bad.join(', ') : true;
});
check('surface', 'the headline and novelty sentence printed on the page are the ones in record.json', () => html.includes(`<p id="headline" class="lede">${S.escape(record.headline)}</p>`) && html.includes(S.escape(record.novelty)) && record.novelty.startsWith('we searched ') && record.headline === summary.headline);
check('surface', 'DAMA\'s record and both controls share one vertical range, and the caption states it', () => {
  const a = M.anchorView(records, D).plot.range, c = cv({}).plot.range, k = cv({control:'COSINE', template:'floated'}).plot;
  const inside = [...k.original, ...k.planted, ...cv({template:'floated'}).plot.original].every(p => p.y > c[0] && p.y < c[1]);
  return JSON.stringify(a) === JSON.stringify(c) && inside && html.includes(`The vertical range is the same as for DAMA's record above, ${M.sgn(c[0], 2)} to ${M.sgn(c[1], 2)} cpd/kg/keV.`);
});
check('surface', 'the sliders announce their values in words', () => html.includes(`aria-valuetext="${M.slopeValueText(D.slope)}"`) && html.includes(`aria-valuetext="${M.boundaryValueText(D.boundary)}"`) && /setAttribute\('aria-valuetext'/.test(fs.readFileSync(path.join(S.PUBLIC, 'page.js'), 'utf8')));
check('surface', 'no shell command is printed at the reader and nothing links to the private repository', () => !/github\.com\/[^"]*Artificial-Wasteland|\bnode research\/|\bpython3? research\//.test(html));

// ---------------------------------------------------------------- the ledger
function ledgerCells() {
  const all = g => { const r = results.filter(x => x.group === g); return r.length > 0 && r.every(x => x.ok); };
  return {claim_reproduced:all('anchor'), control_computed:all('control'), control_can_confirm:all('power'),
    rendered_figures_asserted:all('surface'),
    choices_are_live:all('choices'), planted_fault_caught:all('fault'), refusal_asserted:all('refuse'), provenance_pinned:all('provenance'), verdict_dated:all('verdict')};
}
const ledger = ledgerCells();
check('ledger', 'record.json ledger equals the ledger this run computed', () => S.LEDGER_KEYS.every(k => record.ledger?.[k]?.value === ledger[k]));
if (LEDGER) {
  for (const k of S.LEDGER_KEYS) console.log(`${k}=${ledger[k]}`);
} else {
  const groups = [...new Set(results.map(r => r.group))];
  for (const g of groups) {
    const r = results.filter(x => x.group === g);
    console.log(`\n[${g}] ${r.filter(x => x.ok).length}/${r.length}`);
    for (const x of r) console.log(`  ${x.ok ? 'ok  ' : 'FAIL'} ${x.name}${x.ok ? '' : '\n       ' + x.detail}`);
  }
  const failed = results.filter(x => !x.ok).length;
  console.log(`\n${results.length - failed} of ${results.length} assertions pass.`);
  console.log(S.LEDGER_KEYS.map(k => `${k}=${ledger[k]}`).join(' '));
}
process.exitCode = results.every(x => x.ok) ? 0 : 1;
