#!/usr/bin/env node
// verify-nine-points-for-ten-minutes.mjs: recomputes every number the page shows from the four 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/nine-points-for-ten-minutes/verify-nine-points-for-ten-minutes.mjs            # every assertion
//   node research/nine-points-for-ten-minutes/verify-nine-points-for-ten-minutes.mjs --ledger   # the nine ledger cells
//   node research/nine-points-for-ten-minutes/verify-nine-points-for-ten-minutes.mjs --regen    # rewrite record.json,
//        only when 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 key statistics are compared with data/crosscheck.json, written by
// crosscheck.py: Python and scipy, sharing no code with engine.js.

import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import assert from 'node:assert/strict';
import { execFileSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import * as E from '../../public/strata/nine-points-for-ten-minutes/engine.js';
import { figures, results, format, fx } from '../../public/strata/nine-points-for-ten-minutes/figures.js';
import { VERDICT, CHOICES, DEFAULT_STATE, NOVELTY, PRINTED_2010, DECIDED_BY, YEARS_TO_DECISION, TIMELINE, POWER_RULE } from '../../public/strata/nine-points-for-ten-minutes/readings.js';
import { FILES, SHA256, parseAll } from '../../public/strata/nine-points-for-ten-minutes/data.js';
import * as S from './surface.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" defer><\/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 sha = (buf) => crypto.createHash('sha256').update(buf).digest('hex');
const LEDGER = process.argv.includes('--ledger');
const REGEN = process.argv.includes('--regen');
const rawHtml = read('index.html');
const html = stripChrome(rawHtml);
const md = fs.readFileSync(mdPath, 'utf8');
const readme = fs.readFileSync(path.join(here, 'README.md'), 'utf8');
const XC = JSON.parse(fs.readFileSync(path.join(here, 'data/crosscheck.json'), 'utf8'));
const texts = Object.fromEntries(Object.entries(FILES).map(([k, f]) => [k, read(f)]));
const D = parseAll(texts);
const recordPath = path.join(dir, 'record.json');
const record = fs.existsSync(recordPath) ? JSON.parse(fs.readFileSync(recordPath, 'utf8')) : null;
const clone = structuredClone;
const EM = String.fromCharCode(0x2014);

const results_ = [];
const notes = [];   // what a conditional assertion could not check on this machine
function test(group, name, fn) {
  try { fn(); results_.push({ group, name, pass: true }); }
  catch (error) { results_.push({ group, name, pass: false, error: String(error && error.message || error).slice(0, 400) }); }
}
const near = (a, b, tol, msg = '') => assert.ok(Number.isFinite(a) && Math.abs(a - b) <= tol, `${msg} ${a} differs from ${b} beyond ${tol}`);
const refused = (fn, re) => { try { fn(); return false; } catch (e) { return e.name === 'Refusal' && (!re || re.test(e.message)); } };

const cache = {};
const R0 = results(D, DEFAULT_STATE, cache);
const F = format(R0, D);
const X = S.texts(F);
const claimGap = E.claimGap(D.claim, 'silence');

// ================================================================== provenance
test('provenance', 'each frozen file hashes to the SHA-256 pinned in data.js, in record.json and in the README', () => {
  for (const f of Object.values(FILES)) {
    const h = sha(fs.readFileSync(path.join(dir, f)));
    assert.equal(h, SHA256[f], f + ' against data.js');
    assert.ok(readme.includes(h), f + ' hash missing from README');
    if (record) assert.ok(record.records.some((r) => r.sha256 === h), f + ' hash missing from record.json');
  }
});
test('provenance', 'the research copy of the compilation is byte-identical to the shipped one, and the README pins the upstream bytes', () => {
  assert.equal(sha(fs.readFileSync(path.join(here, 'data/meta-mozart-38.csv'))), SHA256['meta-mozart-38.csv']);
  for (const h of ['dfafecf15d72577fce1cad38350e39f87b676e4608072fa4d2671bc373227b4b', '95e818f55b88b6ce8b7f5973df2ab7d3f3b6c510ea652cb3f0effb01ecbab8bd',
    '9641f9d1fb57c427b2bcfee6e42d35d1e48b4a3d39b87ce05e42cce0fcb44971', '79a9f1f779c7d1d4f1be05d95c736209da7a87ecc64416f5b518138bc280a73c']) assert.ok(readme.includes(h), 'README lacks ' + h);
  assert.equal(D.claim.mirror_sha256, '9641f9d1fb57c427b2bcfee6e42d35d1e48b4a3d39b87ce05e42cce0fcb44971');
  assert.equal(D.steele.source_pdf_sha256, D.chabris.source_pdf_sha256);
});
test('provenance', 'where this machine holds the fetched sources, their bytes match the pinned hashes', () => {
  const b = path.join(root, '.wave/build', S.SLUG);
  const pins = { 'rauscher1993.pdf': D.claim.mirror_sha256, 'chabris1999.pdf': D.chabris.source_pdf_sha256, 'metaviz_0.3.1.tar.gz': 'dfafecf15d72577fce1cad38350e39f87b676e4608072fa4d2671bc373227b4b' };
  let seen = 0;
  for (const [f, h] of Object.entries(pins)) if (fs.existsSync(path.join(b, f))) { assert.equal(sha(fs.readFileSync(path.join(b, f))), h, f); seen++; }
  if (seen < Object.keys(pins).length) notes.push(`provenance: only ${seen} of ${Object.keys(pins).length} fetched sources are on this machine, so the rest were not re-hashed`);
  // the GPL-2 text shipped beside the compilation is the CRAN text, byte for byte
  assert.equal(sha(fs.readFileSync(path.join(dir, 'GPL-2.txt'))), 'e6d6a009505e345fe949e1310334fcb0747f28dae2856759de102ab66b722cb4');
  assert.ok(readme.includes('e6d6a009505e345fe949e1310334fcb0747f28dae2856759de102ab66b722cb4') && read('LICENCE.txt').includes('GPL-2.txt'));
});
test('provenance', 'the compilation has 38 rows, 10 coded to the Rauscher or Rideout laboratories, and the six documented columns', () => {
  assert.equal(D.meta.length, 38); assert.equal(D.meta.filter((r) => r.lab).length, 10);
  assert.equal(texts.meta.split('\n')[0], 'study_name,n,d,se,unpublished,rr_lab');
  assert.equal(D.meta.reduce((s, r) => s + r.n, 0), 2339);
  assert.ok(D.meta.every((r) => Number.isFinite(r.d) && r.se > 0 && r.n > 0));
});

// ================================================================== anchor: the claim at full strength
test('anchor', 'the transcription carries the printed numbers as printed', () => {
  assert.deepEqual(D.claim.sas, { music: 57.56, relaxation: 54.61, silence: 54.00 });
  for (const k of Object.keys(D.claim.sas)) assert.equal(D.claim.sas[k].toFixed(2), D.claim.sas_printed[k]);
  assert.deepEqual(D.claim.iq_equivalent, { music: 119, relaxation: 111, silence: 110 });
  assert.deepEqual(D.claim.pairwise.map((p) => [p.t, p.p_printed]), [[3.41, '0.002'], [3.67, '0.0008'], [0.795, '0.432']]);
  for (const p of D.claim.pairwise) assert.equal(String(p.t), p.t_printed);
  assert.equal(D.claim.n, 36); assert.equal(D.claim.omnibus.F, 7.08); assert.equal(D.claim.omnibus.df_printed, '2,35');
  assert.equal(D.claim.headline_printed, '8–9 points');
});
test('anchor', 'the page engine reproduces every printed P from the printed t at 35 df, the axis equivalents and the 8 to 9', () => {
  const a = E.claimAnchor(D.claim);
  assert.equal(a.agrees, true); assert.equal(a.df, 35);
  for (const r of a.rows) { assert.ok(E.roundsTo(r.P, r.pPrinted), r.id); near(r.P, XC.claim_p[r.id], 1e-9, 'scipy ' + r.id); }
  near(a.iq.music, 118.9, 1e-9); near(a.iq.relaxation, 111.525, 1e-9); near(a.iq.silence, 110, 1e-9);
  assert.deepEqual([a.printedGaps.relaxation, a.printedGaps.silence], [8, 9]);
  near(a.axisGaps.relaxation, 7.375, 1e-9); near(a.axisGaps.silence, 8.9, 1e-9);
  near(E.axisLine(D.claim).slope, (125 - 100) / (60 - 50), 1e-12);
  const w = E.slopeWindow(D.claim);
  near(w.lo, 18.5 / 7.56, 1e-12); near(w.hi, 11.5 / 4.61, 1e-12);
  near(E.rForSlope(D.claim, 6 / Math.sqrt(3 + 6 * 0.3)), 0.3, 1e-12, 'r round trip');
});
test('anchor', 'the printed P values are the plain two-tailed ones; a Scheffe criterion gives larger P, still below 0.01 for both music contrasts, and matches scipy', () => {
  const a = E.claimAnchor(D.claim);
  for (const r of a.rows) {
    near(r.pScheffe, XC.claim_scheffe[r.id].df, 1e-9, 'scipy Scheffe ' + r.id); near(r.pScheffePooled, XC.claim_scheffe[r.id].pooled, 1e-9, 'scipy Scheffe pooled ' + r.id);
    assert.ok(r.pScheffe > r.P && r.pScheffePooled > r.P, 'a Scheffe P is larger than the plain one');
  }
  for (const id of ['music-relaxation', 'music-silence']) {
    const r = a.rows.find((x) => x.id === id);
    assert.ok(E.roundsTo(r.P, r.pPrinted) && !E.roundsTo(r.pScheffe, r.pPrinted) && !E.roundsTo(r.pScheffePooled, r.pPrinted), 'the printed P is the plain one, not a Scheffe P, for ' + id);
  }
  for (const id of ['music-relaxation', 'music-silence']) { const r = a.rows.find((x) => x.id === id); assert.ok(Math.max(r.pScheffe, r.pScheffePooled) < 0.01, id); }
});
test('anchor', 'the omnibus reconstructions match scipy by an independent route and are at least as strong as printed', () => {
  const o = E.claimOmnibus(D.claim);
  near(o.Frm, XC.omnibus.F_rm, 1e-9); near(o.Fh, XC.omnibus.F_h, 1e-9);
  assert.ok(o.atLeastAsStrong); assert.ok(o.rmRange[0] <= o.Frm && o.Frm <= o.rmRange[1]);
});
test('anchor', 'a corrupted claim record fails the same anchor', () => {
  const bad = clone(D.claim); bad.pairwise[1].t = 4.67;
  assert.equal(E.claimAnchor(bad).agrees, false, 't 3.67 read as 4.67 must fail');
  const swap = clone(D.claim); [swap.sas.music, swap.sas.silence] = [swap.sas.silence, swap.sas.music];
  assert.equal(E.claimAnchor(swap).agrees, false, 'swapped means must fail');
  const iq = clone(D.claim); iq.iq_equivalent.music = 121;
  assert.equal(E.claimAnchor(iq).agrees, false, 'a printed equivalent off the axis must fail');
  const df = clone(D.claim); df.n = 12;
  assert.equal(E.claimAnchor(df).agrees, false, 'the wrong df must fail');
});
test('anchor', 'the omnibus F is refused only because the record has no per-person scores: given scores, the same function computes it, and agrees with the reconstruction from paired t values', () => {
  assert.ok(refused(() => E.recomputeOmnibusF(D.claim), /never published/));
  // six synthetic students (not data: a doctored copy of the record), through the same function
  const toy = clone(D.claim);
  toy.scores = [[58, 55, 54], [61, 56, 57], [55, 54, 52], [60, 57, 55], [57, 53, 54], [59, 58, 56]].map(([music, relaxation, silence]) => ({ music, relaxation, silence }));
  const o = E.recomputeOmnibusF(toy);
  const n = toy.scores.length, mean = (k) => toy.scores.reduce((a, x) => a + x[k], 0) / n;
  const pt = (a, b) => { const d = toy.scores.map((x) => x[a] - x[b]), m = d.reduce((u, v) => u + v, 0) / n; const sd = Math.sqrt(d.reduce((u, v) => u + (v - m) ** 2, 0) / (n - 1)); return m / (sd / Math.sqrt(n)); };
  const rec = E.omnibusReconstruction({ music: mean('music'), relaxation: mean('relaxation'), silence: mean('silence') }, pt('music', 'relaxation'), pt('music', 'silence'), pt('relaxation', 'silence'), n);
  near(o.F, rec.Frm, 1e-9, 'repeated-measures F from scores against the reconstruction'); assert.deepEqual(o.df, [2, 2 * (n - 1)]);
});

// ================================================================== the deciding control
test('control', 'the table is transcribed as printed', () => {
  const t = Object.fromEntries(D.steele.arms.map((a) => [a.id, a.rows.map((r) => [r.condition, r.mean, r.se, r.n_printed])]));
  assert.deepEqual(t.UM, [['Mozart', 57.31, 1.26, 32], ['Silence', 59.06, 0.88, 32]]);
  assert.deepEqual(t.UWO, [['Mozart', 55.58, 0.64, 24], ['Silence', 54.27, 0.67, 21], ['Relaxation music', 54.14, 0.31, 22]]);
  assert.deepEqual(t.ASU, [['Mozart', 10.78, 0.74, 18], ['Silence', 11.42, 0.91, 17], ['Minimalist music', 10.83, 0.78, 18], ['10 min relaxation', 10.89, 0.86, 18], ['20 min relaxation', 11.07, 0.98, 15]]);
  assert.deepEqual(D.steele.arms.map((a) => a.printed.as_printed), ['UM, t(30) = 1.14, P = 0.263', 'UWO, F(2, 64) = 1.99, P = 0.145', 'ASU, F(4, 81) = 0.33, P = 0.86']);
  assert.deepEqual(E.arm(D.steele, 'UM').rows.map((r) => r.n), [16, 16], 'the 16-per-condition reading');
});
test('control', 'the recomputed Montreal t and Western Ontario F reproduce the printed values within their rounding, and match scipy', () => {
  const ca = E.controlAnchor(D.steele);
  assert.equal(ca.agrees, true);
  near(ca.control.um.t, XC.control.um.t, 1e-12); near(ca.control.um.p, XC.control.um.p, 1e-9);
  near(ca.control.uwoF.F, XC.control.uwoF.F, 1e-9); near(ca.control.uwoF.p, XC.control.uwoF.p, 1e-9);
  near(ca.control.uwo.t, XC.control.uwo.t, 1e-12); near(ca.control.asuPost.F, XC.control.asuPostF.F, 1e-9);
  assert.equal(fx(Math.abs(ca.control.um.t), 2), '1.14'); assert.equal(ca.control.um.df, 30);
  assert.ok(1.99 >= ca.uwoFRange[0] && 1.99 <= ca.uwoFRange[1]);
  near(ca.control.pooled.diff, XC.control.pooled.diff, 1e-12); near(ca.control.pooled.se, XC.control.pooled.se, 1e-12);
});
test('control', 'the printed mean d of 0.003 comes back only under the 16-per-condition reading', () => {
  const m = E.steeleMeanD(D.steele, D.chabris);
  assert.ok(E.roundsTo(m.mean, D.steele.mean_d_printed.printed), String(m.mean));
  const n32 = clone(D.steele); for (const r of E.arm(n32, 'UM').rows) r.n = r.n_printed;
  assert.ok(!E.roundsTo(E.steeleMeanD(n32, D.chabris).mean, '0.003')); assert.equal(E.runControl(n32).um.df, 62);
  assert.ok(!E.roundsTo(E.steeleMeanD(D.steele, D.chabris, { asuD: 'posttest' }).mean, '0.003'));
});
test('control', 'a transcription slip in the table (UWO Mozart s.e. 0.64 entered as 0.46) fails the control anchor', () => {
  const bad = clone(D.steele); E.arm(bad, 'UWO').rows[0].se = 0.46;
  assert.equal(E.controlAnchor(bad).agrees, false);
  const bad2 = clone(D.steele); E.arm(bad2, 'UM').rows[1].mean = 58.06;
  assert.equal(E.controlAnchor(bad2).agrees, false, 'a slipped Montreal mean must fail too');
});

// ================================================================== the control on the control
test('power', 'the plant goes into a copy of the frozen table, at the claim file’s own gap, through the same runControl', () => {
  const before = JSON.stringify(D.steele);
  const P = E.powerTest(D.steele, D.claim);
  assert.equal(JSON.stringify(D.steele), before, 'the frozen table must be untouched');
  assert.equal(P.doctored.meta.injectedSAS, E.claimGap(D.claim, 'silence'));
  assert.equal(P.doctored.meta.injectedSAS, Math.round((D.claim.sas.music - D.claim.sas.silence) * 100) / 100);
  assert.deepEqual(P.doctored.meta.plantedInto, ['UM', 'UWO']);
  near(E.arm(P.doctored, 'UWO').rows[0].mean - E.arm(D.steele, 'UWO').rows[0].mean, claimGap, 1e-9);
  near(E.arm(P.doctored, 'UWO').rows[0].se, E.arm(D.steele, 'UWO').rows[0].se, 0);
  assert.deepEqual(JSON.stringify(E.runControl(E.plant(D.steele, claimGap))), JSON.stringify(P.withSignal));
  // the injected size follows the claim file: a doctored claim moves it
  const c2 = clone(D.claim); c2.sas.music = 56.00;
  assert.equal(E.powerTest(D.steele, c2).doctored.meta.injectedSAS, 2.00);
});
test('power', 'planted at 3.56 the unmodified control finds it at Western Ontario and pooled, not at Montreal; the real data do not show it', () => {
  const P = E.powerTest(D.steele, D.claim);
  assert.deepEqual(P.recovered, { UM: false, UWO: true, pooled: true });
  assert.ok(P.withSignal.uwoF.p < 1e-8 && P.asMeasured.uwoF.p > 0.1);
  assert.ok(P.asMeasured.pooled.p > 0.5 && P.withSignal.pooled.z > 5);
  near(P.withSignal.uwoF.F, XC.planted.uwoF.F, 1e-9); near(P.withSignal.um.t, XC.planted.um.t, 1e-12); near(P.withSignal.pooled.z, XC.planted.pooled_z, 1e-9);
  assert.equal(P.could, true);
  assert.equal(E.powerTest(D.steele, D.claim, { arms: 'UM' }).could, false, 'Montreal alone could not');
  assert.equal(E.powerTest(D.steele, D.claim, { arms: 'UWO' }).could, true, 'Western Ontario alone could');
});
test('power', 'the recovery flags come from the planted data: planting nothing is recovered nowhere, planting a large gap is recovered everywhere, and a gap of the wrong sign is not the claim', () => {
  const c0 = clone(D.claim); c0.sas.music = c0.sas.silence;
  const P0 = E.powerTest(D.steele, c0);
  assert.equal(P0.gap, 0); assert.deepEqual(P0.recovered, { UM: false, UWO: false, pooled: false }); assert.equal(P0.could, false);
  const c8 = clone(D.claim); c8.sas.music = c8.sas.silence + 8;
  const P8 = E.powerTest(D.steele, c8);
  assert.deepEqual(P8.recovered, { UM: true, UWO: true, pooled: true }, 'eight SAS points are found even at Montreal');
  assert.equal(E.powerTest(D.steele, c8, { arms: 'UM' }).could, true, 'Montreal alone could confirm a gap of eight');
  const cn = clone(D.claim); cn.sas.music = cn.sas.silence - 8;
  assert.deepEqual(E.powerTest(D.steele, cn).recovered, { UM: false, UWO: false, pooled: false }, 'a planted deficit is not the claimed gain');
  // the rule's threshold is the engine's, and the page prints the engine's
  assert.ok(POWER_RULE.endsWith(`at least ${fx(E.POWER_LINE, 2)}`));
});
test('power', 'every power the page prints matches scipy’s noncentral t, noncentral F and normal', () => {
  for (const size of ['silence', 'relaxation']) for (const alpha of [0.05, 0.01]) {
    const P = E.powerTest(D.steele, D.claim, { size, alpha });
    const x = XC.power[`${size}|${alpha}`];
    near(P.power.UM, x.UM, 2e-6, `UM ${size} ${alpha}`); near(P.power.UWO, x.UWO, 2e-6, `UWO ${size} ${alpha}`);
    near(P.power.pooled, x.pooled, 2e-6, `pooled ${size} ${alpha}`); near(P.power.UWOomnibus, x.UWOomnibus, 2e-6, `omnibus ${size} ${alpha}`);
  }
});
test('power', 'planting zero reproduces the as-measured numbers, and the power curve starts at alpha', () => {
  const z = E.runControl(E.plant(D.steele, 0)), m = E.runControl(D.steele);
  assert.equal(z.um.t, m.um.t); assert.equal(z.uwoF.F, m.uwoF.F); assert.equal(z.pooled.diff, m.pooled.diff);
  const c = E.powerCurve(D.steele, 0.05, { step: 0.5 });
  near(c[0].UM, 0.05, 1e-6); near(c[0].pooled, 0.05, 1e-6);
  for (let i = 1; i < c.length; i++) assert.ok(c[i].UWO > c[i - 1].UWO, 'power rises with the gap');
});
test('power', 'the page prints the grade and its justification', () => {
  assert.match(html, /Grade A \(injection\), at the level of the printed summary table\./);
  assert.match(html, /an additive, constant effect with no ceiling/);
  assert.match(html, /Montreal&rsquo;s arm on its own could not have confirmed the claim/);
});

// ================================================================== Chabris and the compilation (further checks)
test('chabris', 'all 28 rows reproduce every summary Chabris printed, and match scipy', () => {
  assert.equal(D.chabris.rows.length, 28);
  assert.equal(D.chabris.rows.filter((r) => r.comparison === 'silence').length, 20);
  const P = D.chabris.printed_summary;
  const c = (o) => E.chabrisPool(D.chabris, D.steele, o);
  assert.ok(E.roundsTo(c({}).d, P.silence_all.d_printed)); assert.equal(c({}).N, P.silence_all.N);
  assert.ok(E.roundsTo(c({ cls: 'abstract' }).d, P.silence_abstract.d_printed));
  const st = c({ cls: 'spatial' });
  assert.ok(E.roundsTo(st.d, P.silence_spatial.d_printed)); assert.ok(E.roundsTo(st.P, P.silence_spatial.P_printed));
  const zi = E.roundingInterval(P.silence_spatial.Z_printed);
  assert.ok(st.Zrange[1] >= zi[0] && st.Zrange[0] < zi[1], 'printed Z inside the P-rounding interval');
  assert.ok(E.roundsTo(c({ comparison: 'relaxation' }).d, P.relaxation_all.d_printed)); assert.equal(c({ comparison: 'relaxation' }).N, P.relaxation_all.N);
  assert.ok(E.roundsTo(c({ comparison: 'relaxation', cls: 'spatial' }).d, P.relaxation_spatial.d_printed));
  assert.ok(E.roundsTo(E.chabrisIQ(c({}).d), P.silence_all.iq_printed)); assert.ok(E.roundsTo(E.chabrisIQ(st.d), P.silence_spatial.iq_printed));
  for (const cmp of ['silence', 'relaxation']) for (const cls of ['all', 'abstract', 'spatial']) {
    const e = c({ comparison: cmp, cls }), x = XC.chabris[`${cmp}|${cls}`];
    near(e.d, x.d, 1e-12); near(e.Z, x.Z, 1e-6); assert.equal(e.N, x.N);
  }
  near(c({ uwoRow: 'recomputed' }).d, XC.chabris['silence|all|uwo-recomputed'].d, 1e-12);
  near(c({ cls: 'spatial', uwoRow: 'recomputed' }).Z, XC.chabris['silence|spatial|uwo-recomputed'].Z, 1e-6);
});
test('meta', 'the compilation reproduces the printed 2010 estimate and interval, and matches scipy', () => {
  const dl = E.pool(D.meta, 'DL'), re = E.pool(D.meta, 'REML');
  assert.deepEqual([fx(dl.est, 2), fx(dl.ci[0], 2), fx(dl.ci[1], 2)], [PRINTED_2010.d, PRINTED_2010.lo, PRINTED_2010.hi]);
  near(dl.est, XC.meta.DL.est, 1e-12); near(dl.ci[0], XC.meta.DL.lo, 1e-9); near(re.est, XC.meta.REML.est, 1e-7); near(re.ci[1], XC.meta.REML.hi, 1e-7);
  const sp = E.labSplit(D.meta);
  near(sp.lab.est, XC.meta.lab.est, 1e-12); near(sp.other.est, XC.meta.other.est, 1e-12);
  const post = E.codeRows(D.meta, D.steele, { asuRow: 'posttest' }), drop = E.codeRows(D.meta, D.steele, { asuRow: 'dropped' });
  near(E.pool(post).est, XC.meta.asu.posttest_all, 1e-12); near(E.metaSubset(post, 'other').est, XC.meta.asu.posttest_other, 1e-12);
  near(E.pool(drop).est, XC.meta.asu.dropped_all, 1e-12); near(E.metaSubset(drop, 'other').est, XC.meta.asu.dropped_other, 1e-12);
  near(E.metaSubset(post, 'lab').est, sp.lab.est, 1e-12, 'the Rauscher and Rideout estimate must not move');
});
test('meta', 'the relabelling test is seeded and repeatable, and agrees in size with numpy’s own run', () => {
  const a = E.labPermutation(D.meta, { reps: 10000, seed: 448 }), b = E.labPermutation(D.meta, { reps: 10000, seed: 448 });
  assert.equal(a.hits, b.hits); assert.equal(a.hits, R0.permDefault.hits);
  assert.ok(a.hits <= 5 && XC.meta.perm_numpy.hits <= 5, `${a.hits} and ${XC.meta.perm_numpy.hits}`);
  near(a.real.gap, XC.meta.perm_numpy.gap, 1e-12);
  const shuffled = clone(D.meta); const labs = shuffled.map((r) => r.lab);
  // the test must be able to fail: with the labels given to the ten smallest effects, the gap is negative and common
  const order = shuffled.map((r, i) => [r.d, i]).sort((x, y) => x[0] - y[0]).slice(0, 10).map((x) => x[1]);
  shuffled.forEach((r, i) => { r.lab = order.includes(i); });
  assert.ok(E.labPermutation(shuffled, { reps: 500, seed: 1 }).hits > 400, 'a low-effect labelling is not unusual in the upper tail');
  assert.equal(labs.filter(Boolean).length, 10);
});
test('meta', 'leaving each study out in turn: the smallest and largest laboratory gaps match scipy, and even the smallest is rare under random labels', () => {
  const L = E.labLeaveOneOut(D.meta);
  near(L.min.gap, XC.meta.loo.min, 1e-12); near(L.max.gap, XC.meta.loo.max, 1e-12);
  assert.equal(L.min.study, XC.meta.loo.min_study); assert.equal(L.max.study, XC.meta.loo.max_study);
  assert.equal(L.rows.length, 38); assert.ok(L.min.gap < E.labSplit(D.meta).gap && L.max.gap > E.labSplit(D.meta).gap);
  const p = E.labPermutation(D.meta.filter((r) => r.study !== L.min.study), { reps: 10000, seed: 448 });
  assert.equal(p.hits, R0.looPerm.hits);
  assert.ok(p.hits >= 5 && p.hits <= 60 && XC.meta.loo.perm_numpy_hits >= 5 && XC.meta.loo.perm_numpy_hits <= 60, `${p.hits} and ${XC.meta.loo.perm_numpy_hits}`);
  // it can fail: if one study carried the whole gap, leaving it out would take the gap to about zero
  const one = clone(D.meta).map((r) => ({ ...r, d: r.lab ? 0.2 : r.d }));
  one[0].d = 9; one[0].se = 0.05;
  assert.ok(E.labLeaveOneOut(one).min.gap < 0.1 && E.labLeaveOneOut(one).min.study === one[0].study);
});

// ================================================================== planted faults
test('faults', 'the minus-sign trap: reading −0.989 as the text layer prints it moves Chabris’s d off the printed values', () => {
  const trap = clone(D.chabris); trap.rows.find((r) => r.id === 'pfc-14-um').d = 0.989;
  const P = D.chabris.printed_summary;
  assert.ok(!E.roundsTo(E.chabrisPool(trap, D.steele).d, P.silence_all.d_printed));
  assert.ok(!E.roundsTo(E.chabrisPool(trap, D.steele, { cls: 'spatial' }).d, P.silence_spatial.d_printed));
  const trap2 = clone(D.chabris); trap2.rows.find((r) => r.id === 'raven-11').d = 1.065;   // '10.065' misread as 1.065 rather than -0.065
  assert.ok(!E.roundsTo(E.chabrisPool(trap2, D.steele).d, P.silence_all.d_printed));
});
test('faults', 'a corrupted compilation row moves the 2010 reproduction off its printed rounding', () => {
  const bad = clone(D.meta); bad[13].d = 2.855;
  const p = E.pool(bad, 'DL');
  assert.notDeepEqual([fx(p.est, 2), fx(p.ci[0], 2), fx(p.ci[1], 2)], [PRINTED_2010.d, PRINTED_2010.lo, PRINTED_2010.hi]);
  const csv = texts.meta.replace('0.855,0.23', '0.855,0.32');
  assert.notEqual(sha(Buffer.from(csv)), SHA256['meta-mozart-38.csv'], 'a changed byte breaks the pinned hash');
});
test('faults', 'the page’s figure check notices a corrupted figure in a copy of the page', () => {
  const figs = S.dataFigs(html);
  const bad = html.replace('data-fig="pow.uwoF">26.2<', 'data-fig="pow.uwoF">26.3<');
  assert.notEqual(bad, html);
  const mism = S.dataFigs(bad).filter((d) => d.inner !== F[d.key]);
  assert.ok(mism.length >= 1 && figs.every((d) => d.inner === F[d.key]));
});

// ================================================================== refusals
test('refusal', 'the engine refuses what the record does not support, with its reason, through the same functions that do the supported work', () => {
  // the plant: SAS points into an arm scored in items is refused by the plant that fills the SAS arms
  assert.ok(refused(() => E.plant(D.steele, claimGap, { into: ['UM', 'UWO', 'ASU'] }), /Appalachian State University reported the number correct from 16 items/));
  assert.ok(!refused(() => E.plant(D.steele, claimGap, { into: ['UM', 'UWO'] })));
  const asSAS = clone(D.steele); E.arm(asSAS, 'ASU').unit = 'SAS';
  assert.ok(!refused(() => E.plant(asSAS, claimGap, { into: ['ASU'] })), 'the refusal reads the unit from the table');
  // the translation: an arm in items is refused by the function that puts the SAS arms on the 1993 axis
  assert.ok(refused(() => E.translateArm(D.claim, D.steele, 'ASU'), /number correct from 16 items/));
  near(E.translateArm(D.claim, D.steele, 'UM').iq.Mozart, E.axisLine(D.claim).at(57.31), 1e-12);
  assert.ok(!refused(() => E.translateArm(D.claim, asSAS, 'ASU')));
  assert.ok(refused(() => E.recomputeOmnibusF(D.claim), /never published/));
  // Chabris: one row is not a pool; two are
  assert.ok(refused(() => E.chabrisPool(D.chabris, D.steele, { comparison: 'relaxation', cls: 'neither' }), /one row is not a pool/));
  assert.equal(E.chabrisPool(D.chabris, D.steele, { comparison: 'relaxation', cls: 'abstract' }).k, 2);
  // the composite model: r is inert at one subtest and required above it
  assert.ok(!refused(() => E.translationSlope(D.claim, 'composite', { k: 1, r: NaN })));
  assert.ok(refused(() => E.translationSlope(D.claim, 'composite', { k: 2, r: NaN }), /between 0 and 1/));
  assert.ok(refused(() => E.translationSlope(D.claim, 'composite', { k: 4, r: 0.5 }), /1, 2 or 3/));
  assert.ok(refused(() => E.translationSlope(D.claim, 'composite', { k: 3, r: 1.2 }), /between 0 and 1/));
  assert.ok(refused(() => E.translationSlope(D.claim, 'composite', { k: 3, r: -0.1 }), /between 0 and 1/));
  assert.ok(refused(() => E.pool(D.meta.slice(0, 2)), /too few/));
  assert.ok(refused(() => E.claimGap(D.claim, 'minimalist'), /two contrasts/));
  assert.ok(!refused(() => E.translationSlope(D.claim, 'composite', { k: 3, r: 1 })), 'the edge of the model is allowed');
  assert.ok(!refused(() => E.pool(D.meta.slice(0, 3))), 'three studies are allowed');
});
test('refusal', 'the refusals are reachable on the page and said in words', () => {
  for (const id of ['asuBtn', 'asuTrBtn', 'omnibusBtn']) assert.match(html, new RegExp(`<button type="button" class="ghost" id="${id}">`));
  assert.match(html, /The model refuses a number of subtests other than 1, 2 or 3, and an r outside 0 to 1\./);
  assert.match(html, /Appalachian State stays out of the power statement\./);
});

// ================================================================== choices
const moved = (state, keys) => {
  const Fx = format(results(D, { ...DEFAULT_STATE, ...state }, cache), D);
  return keys.filter((k) => Fx[k] !== F[k]);
};
test('choices', 'every choice the page offers moves a named output, and record.json declares exactly these', () => {
  const probe = {
    size: [{ size: 'relaxation' }, ['live.umPl', 'live.uwoPl', 'live.poolPl', 'live.poolPow']],
    arms: [{ arms: 'UM' }, ['live.poolAs', 'live.poolPow', 'live.sentence']],
    alpha: [{ alpha: 0.01 }, ['live.umPow', 'live.uwoPow', 'live.poolPow']],
    translation: [{ translation: 'plain' }, ['tr.slope', 'tr.headline']],
    estimator: [{ estimator: 'REML' }, ['meta.live', 'meta.liveSplit']],
    subset: [{ subset: 'lab' }, ['meta.live']],
    asuRow: [{ asuRow: 'posttest' }, ['meta.liveSplit']],
    chabrisUWO: [{ chabrisUWO: 'recomputed' }, ['chab.live']],
    chabrisClass: [{ chabrisClass: 'spatial' }, ['chab.live']],
    chabrisComparison: [{ chabrisComparison: 'relaxation' }, ['chab.live']],
    asuD: [{ asuD: 'posttest' }, ['ctrl.meanDlive']],
  };
  assert.deepEqual(CHOICES.map((c) => c.id).sort(), Object.keys(probe).sort());
  for (const c of CHOICES) {
    const [st, keys] = probe[c.id];
    const m = moved(st, keys);
    assert.deepEqual(m, keys, `${c.id} must move ${keys.join(', ')}`);
    assert.equal(c.inert, false); assert.ok(c.options.length >= 2 && c.options.includes(c.default));
    assert.equal(DEFAULT_STATE[c.id], c.default);
  }
  // the composite's own two parameters are live
  assert.notEqual(format(results(D, { translation: 'composite', k: 2 }, cache), D)['tr.slope'], format(results(D, { translation: 'composite', k: 3 }, cache), D)['tr.slope']);
  assert.notEqual(format(results(D, { translation: 'composite', r: 0.2 }, cache), D)['tr.slope'], format(results(D, { translation: 'composite', r: 0.8 }, cache), D)['tr.slope']);
  if (record && !REGEN) assert.deepEqual(record.choices, CHOICES);   // --regen is what brings record.json up to date
});
test('choices', 'the power sentence turns on the page’s rule, not on a literal', () => {
  const s = format(results(D, { size: 'relaxation', alpha: 0.01, arms: 'UWO' }, cache), D)['live.sentence'];
  assert.match(s, /could not have confirmed/); assert.match(s, /recovered, but the power is only 0\.68/);
  assert.match(format(results(D, { arms: 'UM' }, cache), D)['live.sentence'], /not recovered/);
});
test('choices', 'every radio group on the page is a declared choice with the declared options', () => {
  const groups = {};
  for (const m of html.matchAll(/<input type="radio" name="(\w+)" data-state="(\w+)" value="([^"]+)"( checked)? \/>/g)) {
    assert.equal(m[1], m[2]); (groups[m[1]] ||= { values: [], checked: [] }).values.push(m[3]); if (m[4]) groups[m[1]].checked.push(m[3]);
  }
  for (const c of CHOICES) {
    assert.ok(groups[c.id], 'no radio group for ' + c.id);
    assert.deepEqual(groups[c.id].values, c.options.map(String), c.id);
    assert.deepEqual(groups[c.id].checked, [String(c.default)], c.id);
  }
  assert.deepEqual(Object.keys(groups).sort(), CHOICES.map((c) => c.id).sort());
});

// ================================================================== the rendered page
test('surface', 'every figure span the reader sees equals the recomputation', () => {
  const figs = S.dataFigs(html);
  assert.ok(figs.length > 250, 'expected the page’s figure spans, found ' + figs.length);
  const bad = figs.filter((d) => !(d.key in F) || d.inner !== F[d.key]).map((d) => `${d.key}: "${d.inner}" against "${F[d.key]}"`);
  assert.deepEqual(bad, []);
});
test('surface', 'the dek, headline, title, meta description, OG and Twitter cards and JSON-LD are the templates filled from the recomputation', () => {
  const regen = S.applyAll(html, F, '2026-09-23');
  assert.equal(regen, html, 'regenerating the page from the recomputation changes it');
  const meta = (attr, name) => { const m = html.match(new RegExp(`<meta ${attr}="${name}" content="([^"]*)"`)); return m ? S.decodeEntities(m[1]) : null; };
  assert.equal(meta('name', 'description'), X.DEK); assert.equal(meta('property', 'og:description'), X.OG);
  assert.equal(meta('name', 'twitter:description'), X.TW); assert.equal(meta('property', 'og:image:alt'), X.OG_ALT);
  assert.equal(S.decodeEntities(html.match(/<title data-surface="SEO">([^<]*)<\/title>/)[1]), X.SEO);
  const ld = JSON.parse(html.match(/<script type="application\/ld\+json" data-surface="JSONLD">([\s\S]*?)<\/script>/)[1]);
  assert.equal(ld.description, X.DEK); assert.equal(ld.name, X.SEO); assert.equal(ld.headline, S.TITLE);
  assert.equal(ld.image, 'https://artwaste.land/og/nine-points-for-ten-minutes.png');
  assert.ok(html.includes('<link rel="canonical" href="https://artwaste.land/strata/nine-points-for-ten-minutes/" />'));
  assert.equal(S.decodeEntities(html.match(/<p class="dek" data-surface="DEK">([^<]*)<\/p>/)[1]), X.DEK);
  assert.equal(S.decodeEntities(html.match(/<span data-surface="HEADLINE">([^<]*)<\/span>/)[1]), X.HEADLINE);
});
test('surface', 'no shareable surface says the 1999 control decided the question, and the page does not call the compilation\u2019s Rauscher-or-Rideout coding the originating laboratories', () => {
  const surfaces = [X.DEK, X.OG, X.OG_ALT, X.TW, X.HEADLINE, X.PLAIN, ...X.BODY, ...S.RELATES.map(([, n]) => S.fill(n, F))];
  for (const t of surfaces) assert.ok(!/decided it|that decided|deciding control/.test(t), 'a surface says decided: ' + t.slice(0, 80));
  const text = S.decodeEntities(html.replace(/<script[\s\S]*?<\/script>|<style[\s\S]*?<\/style>|<!--[\s\S]*?-->/g, ' ').replace(/<[^>]+>/g, ' '));
  assert.ok(!/control that decided|the deciding control/.test(text));
  assert.ok(!/originating laboratories|originating labs/.test(text), 'the compilation codes Rauscher or Rideout, not the originating laboratories');
  assert.ok(TIMELINE.filter((t) => t.decides).length === 1 && /2010/.test(TIMELINE.find((t) => t.decides).date) && YEARS_TO_DECISION === 2010 - 1993);
  assert.ok(!/ \u00b1 /.test(X.DEK + X.HEADLINE + X.TW + X.OG), 'the shareable surfaces spell out the standard error');
});
test('surface', 'the frontmatter carries the same dek, placard, title and relates notes, and the body is the template', () => {
  const fm = md.match(/^---\n([\s\S]*?)\n---/)[1];
  const field = (k) => { const m = fm.match(new RegExp('^' + k + ':\\s*"(.*)"\\s*$', 'm')); return m ? m[1] : null; };
  assert.equal(field('dek'), X.DEK); assert.equal(field('plain'), X.PLAIN); assert.equal(field('seoTitle'), X.SEO); assert.equal(field('title'), S.TITLE);
  assert.equal(field('seam'), 'mind'); assert.equal(field('href'), '/strata/nine-points-for-ten-minutes/');
  const notes = [...fm.matchAll(/- to: (\S+)\n\s+note: "(.*)"/g)].map((m) => [m[1], m[2]]);
  assert.deepEqual(notes, S.RELATES.map(([to, n]) => [to, S.fill(n, F)]));
  for (const [to] of notes) assert.ok(fs.existsSync(path.join(root, 'src/content/strata', to + '.md')), 'relates target missing: ' + to);
  const body = md.slice(md.indexOf('\n---', 4) + 4).trim();
  assert.equal(body, X.BODY.join('\n\n'));
  assert.ok(X.PLAIN.length >= 90 && X.PLAIN.length <= 420, 'placard length ' + X.PLAIN.length);
});
test('surface', 'every other number a reader can see is in the pinned inventory, and the labelled literals equal the recomputation', () => {
  const inv = JSON.parse(fs.readFileSync(path.join(here, 'data/surface-literals.json'), 'utf8'));
  assert.deepEqual(S.literalNumbers(html), inv);
  // literal numbers in control labels and captions that name a computed or printed value
  assert.ok(html.includes(`<span>music minus silence, ${F['claim.gapSilence']}</span>`));
  assert.ok(html.includes(`<span>music minus relaxation, ${F['claim.gapRelax']}</span>`));
  assert.ok(html.includes(`<span>as coded, d = ${F['meta.asuD']}</span>`));
  assert.ok(html.includes(`His row for Western Ontario (N = ${F['chab.uwoN']})`));
  const q = html.match(/We could show that the overall estimated effect is small in size \(d = ([\d.]+), 95% CI \[([\d.]+), ([\d.]+)\]\)[\s\S]*?yielded effects similar in strength \(d = ([\d.]+), 95% CI \[([\d.]+), ([\d.]+)\]\)[\s\S]*?\(d = ([\d.]+), 95% CI \[([\d.]+), ([\d.]+)\]\)/);
  assert.ok(q, 'the 2010 quotation');
  const P = PRINTED_2010;
  assert.deepEqual(q.slice(1), [P.d, P.lo, P.hi, P.otherMusic.d, P.otherMusic.lo, P.otherMusic.hi, P.between.d, P.between.lo, P.between.hi]);
  assert.ok(html.includes(`which rounds to the printed ${P.d} [${P.lo}, ${P.hi}]`));
  assert.ok(html.includes('(<em>F</em><sub>2,35</sub> = <span data-fig="claim.Fprinted">7.08</span>; <em>P</em> = 0.002)'));
  assert.equal(D.claim.omnibus.p_printed, '0.002');
  assert.ok(html.includes(`Steele, Bass and Crook (July 1999, 125 participants, raw item counts, treatment F(2, 122) = 0.11 as printed)`));
});
test('surface', 'where this machine holds the source texts, the quotations are found in them', () => {
  const b = path.join(root, '.wave/build', S.SLUG);
  const norm = (s) => S.decodeEntities(s.replace(/<[^>]+>/g, '')).replace(/[‘’]/g, "'").replace(/[“”]/g, '"').replace(/[–−]/g, '-').replace(/\s+/g, ' ').trim();
  const pairs = [
    ['eric-api.json', /We could show that the overall estimated effect[\s\S]*?Furthermore, formal tests yielded evidence for confounding publication bias, requiring downward correction of effects\./],
    ['oberleiter.xml', /This phenomenon was received with considerable skepticism[^<]*?measurement artifacts/],
    ['rh2006.txt', /Other studies also support the conclusion that the Mozart effect is largely due to arousal or mood rather than to Mozart or the specific composition/],
  ];
  for (const [f, re] of pairs) {
    if (!fs.existsSync(path.join(b, f))) { notes.push(`surface: ${f} is not on this machine, so its quotation was not checked against the source`); continue; }
    const src = norm(fs.readFileSync(path.join(b, f), 'utf8').replace(/\\"/g, '"').replace(/\\n/g, ' '));
    const m = html.match(re); assert.ok(m, 'quotation missing from the page: ' + f);
    assert.ok(src.includes(norm(m[0])), 'quotation not found in ' + f + ': ' + norm(m[0]).slice(0, 80));
  }
});
test('surface', 'the figure check can fail: a changed digit in a copy of the page is caught', () => {
  const bad = html.replace('data-fig="ctrl.pooledDiff">0.49<', 'data-fig="ctrl.pooledDiff">0.48<');
  assert.notEqual(bad, html);
  assert.ok(S.dataFigs(bad).some((d) => d.inner !== F[d.key]));
  const bad2 = html.replace(/(<p class="dek" data-surface="DEK">[^<]*?)0\.49 of those points/, '$10.59 of those points');
  assert.notEqual(bad2, html, 'the dek corruption must land');
  assert.notEqual(S.applyAll(bad2, F, '2026-09-23'), bad2);
});

// ================================================================== the verdict
test('verdict', 'the page prints the category, the date, two or more sources and what would change it, as in readings.js and record.json', () => {
  const slot = (id) => { const m = html.match(new RegExp(`<(\\w+)[^>]*\\sid="${id}"[^>]*>([\\s\\S]*?)<\\/\\1>`)); return m ? m[2] : null; };
  assert.equal(slot('verdictCategory'), VERDICT.category); assert.equal(VERDICT.category, 'DISSOLVED');
  assert.equal(slot('verdictAsOf'), VERDICT.as_of); assert.equal(VERDICT.as_of, '2026-09-23');
  assert.ok(html.includes(`<time id="verdictAsOf" datetime="${VERDICT.as_of}">`));
  const srcs = [...slot('verdictSources').matchAll(/<li>/g)].length; assert.ok(srcs >= 2 && srcs === VERDICT.sources.length);
  assert.equal(S.decodeEntities(slot('verdictWouldChange')), VERDICT.would_change);
  assert.equal(slot('yearsToDecision'), String(YEARS_TO_DECISION));
  assert.equal(TIMELINE.length, [...slot('timeline').matchAll(/<li/g)].length);
  if (record) {
    assert.equal(record.verdict.category, VERDICT.category); assert.equal(record.verdict.as_of, VERDICT.as_of);
    assert.equal(record.verdict.would_change, VERDICT.would_change); assert.deepEqual(record.verdict.sources, VERDICT.sources.map((s) => s.text));
    assert.equal(record.decided_by, DECIDED_BY); assert.equal(record.years_to_decision, YEARS_TO_DECISION);
  }
});
test('verdict', 'the page describes work, not people, and keeps the claim’s scope', () => {
  const text = S.decodeEntities(html.replace(/<script[\s\S]*?<\/script>|<style[\s\S]*?<\/style>|<!--[\s\S]*?-->/g, ' ').replace(/<[^>]+>/g, ' ')).toLowerCase();
  for (const w of ['fraud', 'fabricat', 'misconduct', 'p-hacking', 'hoax', 'pseudoscience', 'debunk', 'refuted', 'disproved']) assert.ok(!text.includes(w), 'the page uses ' + w);
  const myths = [...text.matchAll(/myth/g)].length, inTitle = [...text.matchAll(/perpetuate the mozart effect myth/g)].length;
  assert.equal(myths, inTitle, '"myth" appears outside the quoted 2023 title');
  assert.ok(text.includes('we made no such claim'));
  assert.ok(!/mozart makes you smarter/.test(text));
  assert.equal([...text.matchAll(/requiem/g)].length, [...text.matchAll(/prelude or requiem|a requiem may therefore be in order/g)].length, '"requiem" only inside quotation');
});

// ================================================================== hygiene
test('hygiene', 'no unmarked em dash in any file the page ships or in the frontmatter', () => {
  for (const f of fs.readdirSync(dir)) {
    const t = fs.readFileSync(path.join(dir, f), 'utf8');
    t.split('\n').forEach((l, i) => assert.ok(!l.includes(EM) || l.includes('em-dash-ok'), `${f}:${i + 1}`));
  }
  assert.ok(!md.includes(EM));
});
test('hygiene', 'the only inline script is the JSON-LD; the module scripts load from this directory; the page closes', () => {
  const inline = [...html.matchAll(/<script(?![^>]*\ssrc=)([^>]*)>([\s\S]*?)<\/script>/g)];
  assert.equal(inline.length, 1); assert.match(inline[0][1], /application\/ld\+json/); JSON.parse(inline[0][2]);
  assert.match(html, /<script type="module" src="page.js"><\/script>\s*<\/body>\s*<\/html>\s*$/);
  for (const f of fs.readdirSync(dir).filter((x) => x.endsWith('.js'))) {
    execFileSync(process.execPath, ['--check', path.join(dir, f)]);
    const t = fs.readFileSync(path.join(dir, f), 'utf8');
    // readings.js holds citation links the page prints as anchors; no other module may name a host
    if (f !== 'readings.js') assert.ok(!/https?:\/\/(?!www\.w3\.org\/2000\/svg)/.test(t.replace(/^\s*\/\/.*$/gm, '')), f + ' names an external URL in code');
    if (f !== 'data.js') assert.ok(!/\bfetch\s*\(/.test(t), f + ' fetches');
    assert.ok(!/\bimport\s*\(|importScripts|XMLHttpRequest|WebSocket|EventSource|sendBeacon/.test(t), f + ' has a network call other than fetch');
  }
  const dj = fs.readFileSync(path.join(dir, 'data.js'), 'utf8');
  assert.match(dj, /fetch\(new URL\(name, import\.meta\.url\)\)/);
  assert.ok(html.includes('<link rel="stylesheet" href="/fonts/fonts.css" />'));
  assert.ok(!/<link[^>]+href="https?:/.test(html.replace(/<link rel="canonical"[^>]*>/, '')));
  assert.match(html, /prefers-reduced-motion/); assert.match(html, /:focus-visible/);
  assert.ok((html.match(/role="status"/g) || []).length >= 8);
});
test('hygiene', 'no clickable span: every control is a button or a labelled input', () => {
  assert.ok(!/<span[^>]*\sonclick=/.test(html));
  for (const m of html.matchAll(/<input ([^>]*)\/>/g)) {
    const attrs = m[1];
    if (/type="radio"/.test(attrs)) continue;      // wrapped in a <label>
    const id = (attrs.match(/id="(\w+)"/) || [])[1];
    assert.ok(/aria-label=/.test(attrs) || (id && html.includes(`for="${id}"`)), 'unlabelled input ' + id);
  }
});

// ================================================================== record.json
function buildRecord(ledger) {
  const P = R0.powerDefault, c = R0.control.control, a = R0.anchor;
  return {
    slug: S.SLUG, title: S.TITLE, href: `/strata/${S.SLUG}/`,
    field: 'psychology (cognitive psychology, psychometrics, meta-analysis)',
    claim: {
      statement: 'The music condition yielded a mean SAS of 57.56; the mean SAS for the relaxation condition was 54.61 and the mean score for the silent condition was 54.00. To assess the impact of these scores, we ‘translated’ them to spatial IQ scores of 119, 111 and 110, respectively. Thus, the IQs of subjects participating in the music condition were 8–9 points above their IQ scores in the other two conditions.',
      claimants: 'Frances H. Rauscher, Gordon L. Shaw, Katherine N. Ky (byline as printed; Crossref gives Catherine N. Ky), Center for the Neurobiology of Learning and Memory, University of California, Irvine',
      citation: 'Rauscher, F. H., Shaw, G. L. & Ky, K. N. (1993). Music and spatial task performance. Nature 365 (6447), 611. Scientific Correspondence, 14 October 1993. DOI 10.1038/365611a0. PubMed 8413624.',
      year: 1993,
      headline_as_printed: 'mean SAS 57.56 (music), 54.61 (relaxation), 54.00 (silence); IQ equivalents 119, 111, 110; "8–9 points"; F2,35 = 7.08, P = 0.002; Scheffe’s t = 3.41, P = 0.002; t = 3.67, P = 0.0008; t = 0.795, P = 0.432',
    },
    records: [
      { role: 'claimant-data', name: 'Every number the 1993 letter prints about its experiment, transcribed from the page image', url: D.claim.mirror, licence: 'Transcribed facts and short quotations from a subscription Nature article; the PDF is linked, not shipped', licence_url: 'https://www.springernature.com/gp/open-science/policies/journal-policies/licensing-and-copyright', retrieved: '2026-09-23', sha256: SHA256[FILES.claim], units: 3, file: FILES.claim },
      { role: 'control-data', name: 'Steele et al. (1999) Table 1 (three laboratories, ten groups) and every statistic the letter prints, transcribed from the rendered page', url: D.steele.source_pdf, licence: 'Transcribed facts and short quotations from a subscription Nature article; the PDF is linked, not shipped', licence_url: 'https://www.springernature.com/gp/open-science/policies/journal-policies/licensing-and-copyright', retrieved: '2026-09-23', sha256: SHA256[FILES.steele], units: 10, file: FILES.steele },
      { role: 'control-data', name: 'Chabris (1999) Table 1: all 28 comparisons, read against the rendered page (the text layer drops minus signs)', url: D.chabris.source_pdf, licence: 'Transcribed facts and short quotations from a subscription Nature article; the PDF is linked, not shipped', licence_url: 'https://www.springernature.com/gp/open-science/policies/journal-policies/licensing-and-copyright', retrieved: '2026-09-23', sha256: SHA256[FILES.chabris], units: 28, file: FILES.chabris },
      { role: 'reference', name: 'The 38-study compilation behind Pietschnig, Voracek and Formann (2010), dataset mozart in the R package metaviz 0.3.1, decoded from the .rda', url: 'https://cran.r-project.org/src/contrib/metaviz_0.3.1.tar.gz', licence: 'GPL-2 (package DESCRIPTION)', licence_url: 'https://cran.r-project.org/web/licenses/GPL-2', retrieved: '2026-09-23', sha256: SHA256[FILES.meta], units: 38, file: FILES.meta },
    ],
    anchor: {
      what: 'The claimants’ own significance and translation, through the page’s claimAnchor on the frozen transcription: each printed paired t to a two-tailed P at 35 df, and each printed mean to an IQ equivalent on the figure’s own right axis',
      expected: 'as printed: P = 0.002, 0.0008 and 0.432 from t = 3.41, 3.67 and 0.795; IQ equivalents 119, 111 and 110; 8–9 points',
      computed: `P = ${fx(a.rows[0].P, 5)}, ${fx(a.rows[1].P, 6)} and ${fx(a.rows[2].P, 3)}, each rounding to the printed value; axis equivalents ${F['claim.iqAxisMusic']}, ${F['claim.iqAxisRelax']} and ${F['claim.iqAxisSilence']}; gaps ${F['claim.gapAxisRelax']} and ${F['claim.gapAxisSilence']} before rounding, ${F['claim.gapPrintedRelax']} and ${F['claim.gapPrintedSilence']} after, as printed. The printed omnibus F cannot be recomputed; the page’s two reconstructions, F(2, 70) = ${F['claim.Frm']} and F(2, 34) = ${F['claim.Fh']}, are both at least as strong as the printed ${F['claim.Fprinted']}`,
      agrees: a.agrees,
      tolerance: 'P values to the printed digits; IQ equivalents within 0.6, because the printed integers are lookups in a stepwise table that the figure’s axis draws as a line; the 8-point gap is 7.4 before rounding, a rounding gap the page prints beside the printed 8',
    },
    control: {
      name: 'The August 1999 Nature replication in three laboratories (Montreal and Western Ontario scored in Stanford-Binet SAS; Appalachian State in items out of 16), with Chabris’s meta-analysis in the same issue',
      citation: 'Steele, K. M., Dalla Bella, S., Peretz, I., Dunlop, T., Dawe, L. A., Humphrey, G. K., Shannon, R. A., Kirby, J. L. Jr & Olmstead, C. G. (1999). Prelude or requiem for the ‘Mozart effect’? Nature 400 (6747), 827. DOI 10.1038/23611. With Chabris, C. F. (1999), same title, Nature 400, 826-827, DOI 10.1038/23608',
      computed: `Montreal t(30) = ${F['ctrl.umT']}, P = ${F['ctrl.umP']}; Western Ontario F(2, 64) = ${F['ctrl.uwoF']}, P = ${F['ctrl.uwoP']} (printed 1.99 lies in the rounding interval ${F['ctrl.uwoFlo']} to ${F['ctrl.uwoFhi']}); mean d ${F['ctrl.meanD']}; the two SAS arms pooled: Mozart minus silence ${F['ctrl.pooledDiff']} SAS points, standard error ${F['ctrl.pooledSe']} (95% interval ${F['ctrl.pooledLo']} to ${F['ctrl.pooledHi']}); Chabris’s 28 rows give d = ${F['chab.silD']} (silence), ${F['chab.stD']} (spatial-temporal, Z = ${F['chab.stZ']})`,
      as_printed: 'UM, t(30) = 1.14, P = 0.263; UWO, F(2, 64) = 1.99, P = 0.145; ASU, F(4, 81) = 0.33, P = 0.86; mean d = 0.003. Chabris: d = 0.09 (20 comparisons, 714 subjects), spatial-temporal d = 0.14, Z = 1.14, P = 0.26',
    },
    power: {
      grade: 'A-injection',
      planted: `the claim’s own music-minus-silence gap, ${F['pow.gap']} SAS points (computed from the claim file), added to the Mozart row of each arm scored in SAS (Montreal and Western Ontario) in a copy of the printed table, rerun through the same runControl that reproduces the printed t and F; exact for an additive, constant effect because the recomputed tests depend on each group only through its mean, SD and N`,
      recovered: `Western Ontario F(2, 64) ${F['ctrl.uwoF2']} to ${F['pow.uwoF']} (P ${F['pow.uwoFP'].replace(/<\/?sup>/g, '').replace(' × 10', 'e')}), its Mozart-versus-silence t ${F['ctrl.uwoT']} to ${F['pow.uwoT']}: recovered, power ${F['pow.uwoPow']}; pooled ${F['pow.pooled']} SAS points, z = ${F['pow.pooledZ']}: recovered, power ${F['pow.pooledPow']}; Montreal t ${F['ctrl.umT']} to ${F['pow.umT']} (P ${F['pow.umP']}): not recovered, power ${F['pow.umPow']}`,
      verdict: 'the control COULD have confirmed the claim (Western Ontario alone, and the two SAS arms pooled); Montreal’s arm alone could NOT have, so its null is not evidence against the claim by itself',
    },
    null_through_claimant_method: {
      applicable: false,
      what: 'The history did not turn on the claimants’ analysis: their printed P values come back exactly from their printed t statistics, and the claim failed on replication. The page states the arithmetic instead of simulating it: on data with no effect the paired test gives t of 3.67 or more with probability ' + F['claim.nullRate'] + '. The method on nothing that the history does turn on is the critics’: the 2010 lab-affiliation split, rerun on random labels in the second layer',
      result: `not simulated; P(t >= 3.67 | df 35, no effect) = ${F['claim.nullRate']}; and the second layer’s lab-affiliation gap of ${F['meta.gap']} arises in ${F['meta.permHits']} of ${F['meta.permReps']} random relabellings (seed ${F['meta.seed']})`,
    },
    verdict: { category: VERDICT.category, as_of: VERDICT.as_of, sources: VERDICT.sources.map((s) => s.text), would_change: VERDICT.would_change },
    decided_by: DECIDED_BY,
    years_to_decision: YEARS_TO_DECISION,
    choices: CHOICES,
    headline: X.HEADLINE,
    novelty: NOVELTY,
    ledger: {
      claim_reproduced: { value: ledger.claim_reproduced, assertion: 'anchor:printed-t-to-printed-P-and-axis-equivalents-through-claimAnchor' },
      control_computed: { value: ledger.control_computed, assertion: 'control:UM-t-and-UWO-F-within-printed-rounding-through-runControl' },
      control_can_confirm: { value: ledger.control_can_confirm, assertion: 'power:3.56-SAS-planted-into-a-copy-of-the-printed-table-UWO-and-pooled-recovered-UM-not' },
      rendered_figures_asserted: { value: ledger.rendered_figures_asserted, assertion: 'surface:data-fig-spans-head-jsonld-frontmatter-and-literal-inventory' },
      choices_are_live: { value: ledger.choices_are_live, assertion: 'choices:eleven-live-each-moves-a-named-output' },
      planted_fault_caught: { value: ledger.planted_fault_caught, assertion: 'fault:minus-sign-trap-se-slip-corrupted-row-and-figure' },
      refusal_asserted: { value: ledger.refusal_asserted, assertion: 'refuse:ASU-plant-ASU-translation-omnibus-F-composite-range-and-small-pool' },
      provenance_pinned: { value: ledger.provenance_pinned, assertion: 'provenance:sha256-in-data-js-record-and-readme' },
      verdict_dated: { value: ledger.verdict_dated, assertion: 'verdict:category-date-sources-would-change-printed' },
    },
  };
}
const groupOk = (g) => results_.filter((r) => r.group === g).length > 0 && results_.filter((r) => r.group === g).every((r) => r.pass);
function ledgerNow() {
  return {
    claim_reproduced: groupOk('anchor'),
    control_computed: groupOk('control'),
    control_can_confirm: groupOk('power'),
    rendered_figures_asserted: groupOk('surface'),
    choices_are_live: groupOk('choices'),
    planted_fault_caught: groupOk('faults'),
    refusal_asserted: groupOk('refusal'),
    provenance_pinned: groupOk('provenance'),
    verdict_dated: groupOk('verdict'),
  };
}
test('record', 'record.json is exactly what this verifier builds from its own results', () => {
  assert.ok(record, 'record.json is missing');
  const expect = buildRecord(ledgerNow());
  assert.deepEqual(record, JSON.parse(JSON.stringify(expect)));
  assert.equal(record.headline, X.HEADLINE); assert.ok(html.includes(S.escText(X.HEADLINE)));
  assert.match(record.novelty, /^we searched /); assert.ok(S.decodeEntities(html).includes(NOVELTY));
});

// ================================================================== report
const failed = results_.filter((r) => !r.pass);
if (REGEN) {
  const others = failed.filter((r) => r.group !== 'record');
  if (others.length) { console.error('refusing to regenerate record.json while other assertions fail:'); for (const f of others) console.error(` - [${f.group}] ${f.name}: ${f.error}`); process.exit(1); }
  fs.writeFileSync(recordPath, JSON.stringify(buildRecord(ledgerNow()), null, 2) + '\n');
  console.log('wrote record.json');
  process.exit(0);
}
if (LEDGER) {
  const L = ledgerNow();
  for (const [k, v] of Object.entries(L)) console.log(`${k}=${v}`);
  process.exit(failed.length ? 1 : 0);
}
const groups = [...new Set(results_.map((r) => r.group))];
for (const g of groups) {
  const rs = results_.filter((r) => r.group === g);
  console.log(`${rs.every((r) => r.pass) ? 'ok ' : 'RED'} ${g.padEnd(11)} ${rs.filter((r) => r.pass).length}/${rs.length}`);
  for (const r of rs.filter((x) => !x.pass)) console.log(`      ✗ ${r.name}\n        ${r.error}`);
}
for (const n of notes) console.log(`note: ${n}`);
console.log(`\n${results_.length - failed.length} of ${results_.length} assertions pass.`);
process.exit(failed.length ? 1 : 0);
