#!/usr/bin/env node
// verify-the-test-for-intellectual-blooming.mjs: recomputes every number the page shows from the three
// frozen files, checks the shipped page, frontmatter, head tags, JSON-LD and record.json against the
// recomputation, and exits non-zero on any disagreement.
//
//   node research/the-test-for-intellectual-blooming/verify-the-test-for-intellectual-blooming.mjs            # every assertion
//   node research/the-test-for-intellectual-blooming/verify-the-test-for-intellectual-blooming.mjs --ledger   # the nine ledger cells
//   node research/the-test-for-intellectual-blooming/verify-the-test-for-intellectual-blooming.mjs --regen    # rewrite record.json and the
//        literal inventory, only if every other assertion passes. It never rewrites a data file.
//
// Two kinds of check are kept apart. The page's own functions are run on the frozen files and on
// doctored copies of them. And the central statistics are recomputed a second time here, by code that
// shares nothing with engine.js or stats.js (its own CSV reader, its own sums, a Student t tail by
// numerical integration, its own REML by grid search), so an error in the engine cannot be confirmed
// by the engine. The seeded simulations behind the dek (the planted-effect power for total and reasoning
// IQ, and the null rate of the claimants' test) are rerun by an independent sampler with its own random
// numbers and its own t test, and held to the engine's rates within four Monte Carlo standard errors.

import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import assert from 'node:assert/strict';
import { spawnSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import * as E from '../../public/strata/the-test-for-intellectual-blooming/engine.js';
import * as ST from '../../public/strata/the-test-for-intellectual-blooming/stats.js';
import { figures, blocks } from '../../public/strata/the-test-for-intellectual-blooming/figures.js';
import { CLAIM, QUOTES, VERDICT, NOVELTY, TRANSCRIPTION, CHOICES } from '../../public/strata/the-test-for-intellectual-blooming/readings.js';
import { FILES, SHA256 } from '../../public/strata/the-test-for-intellectual-blooming/data.js';
import * as S from './surface.mjs';

// The site's chrome writers insert marked blocks (aw-plain, aw-nearby, aw-wayout, aw-checkkind, a site
// bar) 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 every marked block and the banner script removed.
const stripChrome = s => s.replace(/\s*<!--aw-([a-z-]+):start-->[\s\S]*?<!--aw-\1:end-->/g, '')
  .replace(/\s*<script src="\/media\/home-banner\.js"[^>]*><\/script>/g, '');

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

const results = [];
function test(group, name, fn) {
  try { fn(); results.push({ group, name, pass: true }); }
  catch (error) { results.push({ group, name, pass: false, error: error.message }); }
}
const near = (a, b, tol, msg) => assert.ok(Number.isFinite(a) && Math.abs(a - b) <= tol, (msg || '') + ` ${a} differs from ${b} beyond ${tol}`);
const clone = x => structuredClone(x);
const EM_DASH = String.fromCharCode(0x2014);
const round = (x, d) => Math.round(x * 10 ** d + 1e-9 * Math.sign(x)) / 10 ** d;

// ------------------------------------------------------------------ fixtures from the page's engine
const records = E.parseListing(csv);
const rows = E.metaRows(metaJson);
const res = E.pageResults(records, metaJson, printed, { heavy: true });
const F = figures(res, printed);
const B = blocks(res, printed);
const X = S.texts(F);
const A = res.A;

// ------------------------------------------------------------------ an independent implementation
// Its own CSV reader: columns by name, blanks as null.
function indepRead(text) {
  const [head, ...lines] = text.trim().split('\n');
  const cols = head.split(',');
  return lines.map(l => { const v = l.split(','); const o = {}; cols.forEach((c, i) => { o[c] = v[i] === '' ? null : Number(v[i]); }); return o; });
}
const IR = indepRead(csv);
// Student t density and upper tail by Simpson's rule on [t, t + 60] (plenty for the df used here).
function lgam(x) { // Stirling series with shift, independent of stats.js
  let s = 0; while (x < 20) { s -= Math.log(x); x += 1; }
  return s + (x - 0.5) * Math.log(x) - x + 0.5 * Math.log(2 * Math.PI) + 1 / (12 * x) - 1 / (360 * x ** 3) + 1 / (1260 * x ** 5);
}
function tTail(t, df) {
  const c = Math.exp(lgam((df + 1) / 2) - lgam(df / 2)) / Math.sqrt(df * Math.PI);
  const f = x => c * Math.pow(1 + x * x / df, -(df + 1) / 2);
  const a = Math.abs(t), b = a + 60, n = 20000, h = (b - a) / n;
  let s = f(a) + f(b);
  for (let i = 1; i < n; i++) s += f(a + i * h) * (i % 2 ? 4 : 2);
  const up = s * h / 3;
  return t >= 0 ? up : 1 - up;
}
function indepClaim(measure, gradeList) {
  const key = { total: 'total', verbal: 'verbal', reasoning: 'reasoning' }[measure];
  const kids = IR.filter(r => gradeList.includes(r.grade) && r[key + '1'] !== null && r[key + '3'] !== null);
  const cells = new Map();
  let sE = 0, nE = 0, sC = 0, nC = 0;
  for (const k of kids) {
    const g = k[key + '3'] - k[key + '1'];
    const id = k.grade + ':' + k.track + ':' + k.group;
    if (!cells.has(id)) cells.set(id, []);
    cells.get(id).push(g);
    if (k.group === 1) { sE += g; nE++; } else { sC += g; nC++; }
  }
  let ssw = 0;
  for (const xs of cells.values()) { const m = xs.reduce((a, b) => a + b, 0) / xs.length; for (const x of xs) ssw += (x - m) ** 2; }
  const df = kids.length - gradeList.length * 3 * 2;
  const msw = ssw / df, adv = sE / nE - sC / nC, t = adv / Math.sqrt(msw * (1 / nE + 1 / nC));
  return { N: kids.length, nE, nC, adv, msw, df, t, p1: tTail(t, df) };
}
function indepTruncGain(measure, gradeList, lo, hi) {
  const key = measure;
  const e = [], c = [];
  for (const r of IR) {
    if (!gradeList.includes(r.grade)) continue;
    const x = r[key + '1'], y = r[key + '3'];
    if (x === null || y === null || x < lo || x > hi || y < lo || y > hi) continue;
    (r.group ? e : c).push(y - x);
  }
  const me = e.reduce((a, b) => a + b, 0) / e.length, mc = c.reduce((a, b) => a + b, 0) / c.length;
  const ss = e.reduce((a, b) => a + (b - me) ** 2, 0) + c.reduce((a, b) => a + (b - mc) ** 2, 0);
  const df = e.length + c.length - 2, t = (me - mc) / Math.sqrt(ss / df * (1 / e.length + 1 / c.length));
  return { adv: me - mc, t, p2: 2 * tTail(Math.abs(t), df), nE: e.length, nC: c.length };
}
// REML for a random-effects model by grid search then local refinement (no golden section, no shared code).
function indepREML(y, v) {
  const ll = t2 => { let sw = 0, swy = 0; for (let i = 0; i < y.length; i++) { const w = 1 / (v[i] + t2); sw += w; swy += w * y[i]; } const mu = swy / sw; let q = 0, ld = 0; for (let i = 0; i < y.length; i++) { q += (y[i] - mu) ** 2 / (v[i] + t2); ld += Math.log(v[i] + t2); } return { l: -0.5 * ld - 0.5 * Math.log(sw) - 0.5 * q, mu, sw }; };
  let best = 0, bl = ll(0).l;
  for (let t2 = 0; t2 <= 1; t2 += 0.0005) { const l = ll(t2).l; if (l > bl) { bl = l; best = t2; } }
  let step = 0.0005;
  for (let it = 0; it < 60; it++) { for (const c of [best - step, best + step]) { if (c < 0) continue; const l = ll(c).l; if (l > bl) { bl = l; best = c; } } step /= 2; }
  const f = ll(best);
  return { tau2: best, estimate: f.mu, se: Math.sqrt(1 / f.sw) };
}

// ================================================================== anchor
test('anchor', 'the transcription is the one the research record builds, and its counts are the page’s', () => {
  const tdir = path.join(here, 'transcription');
  const KEEP = ['id', 'G', 'A', 'T', 't1', 't2', 't3', 't4', 'v1', 'v2', 'v3', 'v4', 'r1', 'r2', 'r3', 'r4'];
  const passB = fs.readFileSync(path.join(tdir, 'passB.txt'), 'utf8').split('\n').filter(l => l.trim() && !l.startsWith('#')).map(l => { const t = l.replace(/\|/g, ' ').trim().split(/\s+/); return { key: t[0], v: Object.fromEntries(KEEP.map((k, i) => [k, t[i + 1]])) }; });
  const passA = JSON.parse(fs.readFileSync(path.join(tdir, 'passA.json'), 'utf8'));
  const resol = JSON.parse(fs.readFileSync(path.join(tdir, 'resolutions.json'), 'utf8'));
  assert.equal(passB.length, TRANSCRIPTION.rows, 'pass B rows');
  let disagree = 0, flagged = 0, cells = 0;
  for (const r of passB) for (const k of KEEP) {
    cells++;
    const b = r.v[k], a = passA[r.key][k];
    if (a !== b.replace(/\?$/, '')) disagree++;
    else if (b.endsWith('?')) flagged++;
  }
  assert.equal(cells, TRANSCRIPTION.cells, 'cells compared');
  assert.equal(disagree, TRANSCRIPTION.disagreements, 'disagreements');
  assert.equal(flagged, TRANSCRIPTION.flaggedOnly, 'flagged only');
  assert.equal(Object.keys(passA).filter(k => !passB.some(r => r.key === k)).length, TRANSCRIPTION.spuriousRows, 'spurious rows');
  // rebuild the CSV from pass B and the resolutions, independently of build-listing.py
  const byKey = Object.fromEntries(passB.map(r => [r.key, clone(r.v)]));
  let changed = 0;
  for (const x of resol) { if (!x.cell.includes(':')) continue; const [k, c] = x.cell.split(':'); if (byKey[k][c].replace(/\?$/, '') !== x.final) changed++; byKey[k][c] = x.final; }
  assert.equal(changed, TRANSCRIPTION.changedByGate, 'cells changed from pass B by a resolution');
  assert.equal(resol.filter(x => /residual uncertainty/.test(x.how)).length, TRANSCRIPTION.residual, 'residual uncertain cells logged');
  assert.equal(resol.filter(x => /Settled on 2026-09-23 by the book|re-read at 8x after gate V6 failed/i.test(x.how)).length, TRANSCRIPTION.changedByGate, 'cells settled by a printed table, logged');
  const perPage = {};
  const out = passB.map(r => { const pg = r.key.split('.')[0]; perPage[pg] = (perPage[pg] || 0) + 1; const v = byKey[r.key]; return [v.id, v.G, v.A, v.T, pg, perPage[pg], ...KEEP.slice(4).map(k => v[k].replace(/\?$/, '') === '-' ? '' : v[k].replace(/\?$/, ''))].join(','); });
  const lines = csv.trim().split('\n').slice(1);
  assert.deepEqual(lines, out, 'the shipped listing equals pass B with the logged resolutions');
  for (const c of csv.split('\n')[0].split(',')) assert.ok(!['M', 'S', 'age', 'minority', 'sex'].includes(c), 'no minority, sex or age column is shipped: ' + c);
});
test('anchor', 'transcription gates V1 and V2: 382 rows and every classroom count of Elashoff and Snow’s Table 2', () => {
  assert.equal(records.length, 382);
  const t2 = printed.es1970.table2;
  for (const g of ['1', '2', '3', '4', '5', '6']) for (const [grp, key] of [[0, 'C'], [1, 'E']]) {
    const got = [3, 2, 1].map(a => records.filter(r => r.grade === Number(g) && r.track === a && r.group === grp && r.total[0] !== null && r.total[2] !== null).length);
    assert.deepEqual(got, t2[key][g].map(x => x ?? 0), 'Table 2 grade ' + g + ' ' + key);
  }
  assert.deepEqual([102, 73, 80], [3, 2, 1].map(a => records.filter(r => r.track === a && r.group === 0 && r.total[0] !== null && r.total[2] !== null).length));
  assert.deepEqual(A.pretested, { '1-2': 126, '3-4': 131, '5-6': 125 }, 'Table 4 Ns');
});
test('anchor', 'gates V3 and V4: every row of Table 7-1 and the 1966 Table 1, means, Ns, sigmas and rounding marks', () => {
  const T = A.total, bk = printed.rj1968.table7_1, p1 = printed.rj1966.table1;
  T.byGrade.forEach((b, i) => {
    assert.equal(b.C.n, bk.rows[i].C.N); assert.equal(b.E.n, bk.rows[i].E.N);
    near(b.C.mean, bk.rows[i].C.gain, 0.05, 'C gain grade ' + b.grade); near(b.E.mean, bk.rows[i].E.gain, 0.05, 'E gain grade ' + b.grade);
    near(b.C.sd, p1.rows[i].C.sigma, 0.05, 'C sigma'); near(b.E.sd, p1.rows[i].E.sigma, 0.05, 'E sigma');
    near(b.adv, bk.rows[i].adv, 0.051, 'advantage grade ' + b.grade);
  });
  // grade 5: C printed 17.5 marked (-) (true value below), E 17.4 marked (+)
  assert.ok(T.byGrade[4].C.mean < 17.5 && T.byGrade[4].E.mean > 17.4, 'grade 5 rounding marks');
  assert.equal(T.C.n, 255); assert.equal(T.E.n, 65);
  near(T.C.mean, bk.total.C.gain, 0.005); near(T.E.mean, bk.total.E.gain, 0.005); near(T.adv, bk.total.adv, 0.005);
  near(T.C.sd, p1.weighted.C.sigma, 0.05); near(T.E.sd, p1.weighted.E.sigma, 0.05);
});
test('anchor', 'gate V5 and the anchor: the mean squares, t, p and F, through the page’s claimantTest and independently', () => {
  const T = A.total, bk = printed.rj1968.table7_1;
  near(T.msw, bk.msw, 0.01, 'total MSW'); near(A.verbal.msw, printed.rj1968.table7_3.msw, 0.01, 'verbal MSW'); near(A.reasoning.msw, printed.rj1968.table7_4.msw, 0.01, 'reasoning MSW');
  assert.equal(T.df, 284); assert.equal(T.designCells, 36); assert.equal(T.cellsPresent, 34);
  const gap = Math.abs(T.t - printed.rj1966.table1.weighted.t);
  assert.ok(gap <= 0.03, 'school-wide t gap ' + gap);
  assert.equal(round(T.p1, 2), printed.rj1966.table1.weighted.p, 'one-tailed p rounds to .02');
  near(T.byGrade[0].t, printed.rj1966.table1.rows[0].t, 0.02, 'grade 1 t'); near(T.byGrade[1].t, printed.rj1966.table1.rows[1].t, 0.02, 'grade 2 t');
  near(T.unweightedF, printed.rj1968.p74.F, 0.15, 'F');
  // the same numbers from the independent implementation
  const ind = indepClaim('total', [1, 2, 3, 4, 5, 6]);
  near(ind.adv, T.adv, 1e-9); near(ind.msw, T.msw, 1e-9); near(ind.t, T.t, 1e-9); near(ind.p1, T.p1, 1e-6, 'p by integration');
  near(indepClaim('verbal', [1, 2, 3, 4, 5, 6]).msw, printed.rj1968.table7_3.msw, 0.01);
  near(indepClaim('reasoning', [1, 2, 3, 4, 5, 6]).msw, printed.rj1968.table7_4.msw, 0.01);
});
test('anchor', 'gate V6: Tables 7-3 and 7-4, Ns, gains and rounding marks', () => {
  const v = printed.rj1968.table7_3, r = printed.rj1968.table7_4;
  const chk = (got, pr, d) => { assert.equal(got.C.n, pr.C.N); assert.equal(got.E.n, pr.E.N); near(got.C.mean, pr.C.gain, 0.5 * 10 ** -d + 1e-9); near(got.E.mean, pr.E.gain, 0.5 * 10 ** -d + 1e-9); near(got.adv, pr.adv, 10 ** -d); };
  chk(A.verbalGroups['1-2'], v.rows[0], 1); chk(A.verbalGroups['3-6'], v.rows[1], 1);
  chk({ C: A.verbal.C, E: A.verbal.E, adv: A.verbal.adv }, v.total, 2);
  chk(A.reasoningGroups['1-2'], r.rows[0], 1); chk(A.reasoningGroups['3-6'], r.rows[1], 1);
  chk({ C: A.reasoning.C, E: A.reasoning.E, adv: A.reasoning.adv }, r.total, 2);
  assert.ok(A.reasoningGroups['1-2'].C.mean < 27.0 && A.reasoningGroups['1-2'].E.mean > 39.6 && A.reasoningGroups['3-6'].C.mean < 9.1 && A.reasoningGroups['3-6'].E.mean > 15.9, 'Table 7-4 rounding marks');
});
test('anchor', 'gate V7: every N, mean, standard deviation, minimum and maximum of Elashoff and Snow’s Tables 4 and 5', () => {
  const key = { total: 'total', reasoning: 'reasoning', verbal: 'verbal' };
  const gs = { '1': [1], '2': [2], '1-2': [1, 2], '3-4': [3, 4], '5-6': [5, 6] };
  for (const [tab, occ] of [['table4', 1], ['table5', 3]]) for (const m of Object.keys(key)) for (const [g, pr] of Object.entries(printed.es1970[tab][m])) {
    const d = E.describe(records, { measure: m, grades: gs[g], occasion: occ });
    assert.equal(d.n, pr[0], `${tab} ${m} ${g} N`); near(d.mean, pr[1], 0.05 + 1e-9, `${tab} ${m} ${g} mean`);
    // single grades print the population SD, grade pairs the sample SD (the page's reading); one cell, the
    // reasoning pretest of grade 1 (36.851 against a printed 36.8), sits 0.001 past a rounding edge and is named on the page
    const sd = g.length === 1 ? d.popSd : d.sampleSd;
    const edge = tab === 'table4' && m === 'reasoning' && g === '1';
    near(sd, pr[2], edge ? 0.052 : 0.05 + 1e-9, `${tab} ${m} ${g} SD`);
    if (edge) assert.ok(Math.abs(sd - pr[2]) > 0.05, 'the named rounding-edge cell is the one that needs it');
    assert.equal(d.min, pr[3], `${tab} ${m} ${g} min`); assert.equal(d.max, pr[4], `${tab} ${m} ${g} max`);
  }
  near(res.pre382.popSd, printed.rr1971.sigmaPretest, 0.005, 'Rosenthal and Rubin’s sigma of all 382 pretests');
});
test('anchor', 'gates V8 and V9: the 1966 text and Table 2, with the two printed values that do not come back named', () => {
  const t = printed.rj1966.text;
  near(A.bestRoom1.excess, t.firstGradeExcess, 0.0501); near(A.bestRoom1.C.mean, t.firstGradeControlGain, 0.0501);
  near(A.bestRoom2.excess, t.secondGradeExcess, 0.05); near(A.bestRoom2.C.mean, t.secondGradeControlGain, 0.05);
  near(A.rhoRooms, t.rhoClassroomGains, 0.005); near(A.r86, printed.rj1968.p74.r, 0.005);
  // rho = -.94 comes back from the rounded table only; from the listing it is -0.83 (reported, not tuned)
  near(ST.spearman([1, 2, 3, 4, 5, 6], printed.rj1966.table1.rows.map(r => r.diff)), t.rhoGradeAdvantage, 0.005);
  near(A.rho, -0.8286, 0.001);
  // the same rank correlation and the 10-point count from the independent reader, with its own ranking
  const advOf = g => { const k = IR.filter(r => r.grade === g && r.total1 !== null && r.total3 !== null); const m = grp => { const x = k.filter(r => r.group === grp).map(r => r.total3 - r.total1); return x.reduce((a, b) => a + b, 0) / x.length; }; return m(1) - m(0); };
  const adv = [1, 2, 3, 4, 5, 6].map(advOf), rk = adv.map(a => 1 + adv.filter(b => b < a).length);
  const rs = 1 - 6 * rk.reduce((s, r, i) => s + (r - (i + 1)) ** 2, 0) / (6 * 35);
  near(rs, A.rho, 1e-9, 'rho from the independent reader');
  const g12 = IR.filter(r => r.grade <= 2 && r.group === 0 && r.total1 !== null && r.total3 !== null);
  assert.deepEqual([g12.filter(r => r.total3 - r.total1 >= 10).length, g12.length], [46, 95], 'the listing’s 46 of 95 unnamed first and second graders gaining 10 points');
  A.thresholds.forEach((th, i) => {
    const pr = printed.rj1966.table2.rows[i];
    assert.equal(Math.round(th.E.pct), pr.E, 'E share at ' + th.cut);
    if (th.cut === 10) assert.equal(Math.round(th.C.pct), 48, 'the listing’s 48%, printed 49%');
    else assert.equal(Math.round(th.C.pct), pr.C, 'C share at ' + th.cut);
    near(th.chi2, pr.chi2, 0.03, 'chi-square at ' + th.cut);
  });
});
test('anchor', 'gate V11: the book’s appendix classroom tables for January 1965 and May 1966 come back exactly, under the book’s rounding', () => {
  const ap = res.appendix;
  assert.equal(ap.tables, 6); assert.equal(ap.numbers, 594); assert.equal(ap.exact, ap.numbers, 'misses: ' + ap.misses.join('; '));
  assert.equal(E.bookRound(92.76470588235294), 92.77); assert.equal(E.bookRound(18.06469853978564), 18.07); assert.equal(E.bookRound(120.625), 120.63); assert.equal(E.bookRound(-1.357142857), -1.36);
  // the two cells the scan left open are the only values that reproduce the book
  const only = (id, measure, occ, table, cls, lo, hi) => {
    const fits = [];
    for (let v = lo; v <= hi; v++) {
      const bad = clone(records); bad.find(r => r.id === id)[measure][occ - 1] = v;
      const row = E.classroomTable(bad, { measure, occasion: occ })[cls].C, pr = printed.rj1968.appendix.tables[table].rows[cls].C;
      if (row.n === pr[0] && E.bookRound(row.mean) === pr[1] && E.bookRound(row.sd) === pr[2]) fits.push(v);
    }
    return fits;
  };
  assert.deepEqual(only(444, 'verbal', 2, 'A-17', '6C', 0, 200), [58], 'ID 444 verbal January 1965');
  assert.deepEqual(only(297, 'reasoning', 4, 'A-26', '4B', 0, 250), [118], 'ID 297 reasoning May 1966');
  // the six gain tables, against the shipped whitelist OCR of the page images: every predicted value's digits in order
  const adir = path.join(here, 'transcription', 'appendix');
  const GAIN = { 221: ['total', 2], 222: ['verbal', 2], 223: ['reasoning', 2], 229: ['total', 4], 230: ['verbal', 4], 231: ['reasoning', 4] };
  const dig = s => String(s).replace(/[^0-9]/g, '');
  const f2 = x => E.bookRound(Math.abs(x)).toFixed(2);
  let rowsSeen = 0;
  for (const [page, [m, occ]] of Object.entries(GAIN)) {
    const lines = fs.readFileSync(path.join(adir, 'ocr-' + page + '.txt'), 'utf8').split('\n').filter(l => /^\s*[1-8][ABC]\s/.test(l));
    lines.forEach((line, i) => {
      const g = Math.floor(i / 3) + 1, a = [3, 2, 1][i % 3];
      const cell = grp => { const x = records.filter(r => r.grade === g && r.track === a && r.group === grp && r[m][0] !== null && r[m][occ - 1] !== null).map(r => r[m][occ - 1] - r[m][0]); return { n: x.length, mean: ST.mean(x), sd: ST.popSd(x) }; };
      const C = cell(0), Ee = cell(1);
      const pred = [C.n, f2(C.mean), f2(C.sd), Ee.n, f2(Ee.mean), f2(Ee.sd), (Math.abs(E.bookRound(Ee.mean) - E.bookRound(C.mean))).toFixed(2)];
      const d = dig(line.trim().split(/\s+/).slice(1).join(' '));
      let pos = 0;
      for (const q of pred) { const j = d.indexOf(dig(q), pos); assert.ok(j >= 0, 'gain table page ' + page + ' row ' + (i + 1) + ': ' + q + ' not in ' + line.trim()); pos = j + dig(q).length; }
      rowsSeen++;
    });
  }
  assert.equal(rowsSeen, 99, 'gain-table rows compared');
});
test('anchor', 'gate V6b: the claimants’ t for grades 1 and 2 on the whole school’s mean square, as the book prints it', () => {
  const v = A.verbalGroups['1-2'], r = A.reasoningGroups['1-2'], r36 = A.reasoningGroups['3-6'];
  near(v.t, printed.rj1968.p77.tVerbal12, 0.005, 'verbal t, book p. 77'); assert.ok(v.p1 < printed.rj1968.p77.pVerbal12Below, 'verbal p < .02');
  assert.equal(round(r.p1, 2), printed.rj1968.table7_4.rows[0].p, 'reasoning grades 1 and 2, printed .03');
  assert.equal(round(r36.p1, 2), printed.rj1968.table7_4.rows[1].p, 'reasoning grades 3 to 6, printed .06');
  assert.ok(Math.abs(A.reasoning.p1 - printed.rj1968.table7_4.total.p) > 0.01, 'the school-wide reasoning p .005 does not come back from the t (named on the page)');
  // the same t from the independent implementation's mean square
  const ind = indepClaim('reasoning', [1, 2, 3, 4, 5, 6]);
  near(r.adv / Math.sqrt(ind.msw * (1 / r.E.n + 1 / r.C.n)), r.t, 1e-9);
});
test('anchor', 'Snow’s five children are in the listing with the scores he printed, and the claim is quoted as deposited', () => {
  const five = { 10: [17, 110], 1: [18, 122], 106: [133, 202], 139: [111, 208], 119: [113, 211] };
  for (const [id, [a, b]] of Object.entries(five)) { const r = records.find(x => x.id === Number(id)); assert.deepEqual([r.reasoning[0], r.reasoning[2], r.group], [a, b, 1], 'ID ' + id); }
  assert.ok(html.includes(S.escText(CLAIM.statement)), 'the claim appears verbatim');
  assert.ok(html.includes('doi:10.2466/pr0.1966.19.1.115'));
});
test('anchor', 'a corrupted listing fails the same anchor', () => {
  const bad = clone(records);
  for (const r of bad) if (r.grade === 1 && r.group === 1 && r.total[2] !== null) r.total[2] -= 10;
  const T = E.claimantTest(bad, { measure: 'total' });
  assert.ok(Math.abs(T.adv - printed.rj1968.table7_1.total.adv) > 0.005, 'a shifted record must miss 3.80');
  const drop = records.slice(1);
  assert.ok(E.claimantTest(drop, { measure: 'total' }).C.n !== 255, 'a dropped row must miss N');
});

// ================================================================== control
test('control', 'every cell of Tables 20 to 22 from the page’s esControl: 103 within 0.10 of print, the five others named and within 0.15, significance marks all equal', () => {
  let n = 0, marks = 0, worst = 0; const over = [];
  const crit = ['pretest', 'posttest', 'gain', 'adjusted'];
  for (const m of ['total', 'verbal', 'reasoning']) for (const g of ['1-2', '3-4', '5-6']) for (const s of ['all', 'renormed', 'truncated']) {
    const pr = printed.es1970.tables20to22[m][g][s];
    res.es[m + '|' + g + '|' + s].forEach((r, i) => { n++; const dv = Math.abs(r.advantage - pr[i][0]); worst = Math.max(worst, dv); if (dv > 0.1 + 1e-9) over.push([m, g, s, crit[i]].join(' ')); if (r.significant === pr[i][1]) marks++; });
  }
  assert.equal(n, 108); assert.equal(marks, 108, 'significance marks'); assert.ok(worst <= 0.15, 'worst ' + worst);
  assert.deepEqual(over.sort(), ['reasoning 1-2 all adjusted', 'total 3-4 all adjusted', 'total 5-6 renormed adjusted', 'verbal 1-2 renormed adjusted', 'verbal 1-2 renormed gain'], 'the cells beyond 0.10 are the five the page names');
  assert.deepEqual(res.esAgree.over.map(o => [o.measure, o.gradeGroup, o.scores, o.criterion].join(' ')).sort(), over.sort(), 'the engine names the same five');
  assert.equal(res.esAgree.within, 103); assert.equal(res.esAgree.maxAll, worst);
});
test('control', 'the printed pre, post and gain columns are mostly differences of rounded means (the page’s reading, measured)', () => {
  const r1 = x => Math.round(x * 10 + 1e-9) / 10;
  let exact = 0, n = 0;
  for (const m of ['total', 'verbal', 'reasoning']) for (const g of ['1-2', '3-4', '5-6']) for (const s of ['all', 'renormed', 'truncated']) {
    const { kept } = E.prepare(records, { measure: m, gradeGroup: g, scores: s });
    const pr = printed.es1970.tables20to22[m][g][s];
    [k => k.x, k => k.y, k => k.y - k.x].forEach((f, i) => {
      const e = kept.filter(k => k.group === 1).map(f), c = kept.filter(k => k.group === 0).map(f);
      n++; if (Math.abs(r1(ST.mean(e)) - r1(ST.mean(c)) - pr[i][0]) < 1e-9) exact++;
    });
  }
  assert.equal(n, 81); assert.ok(exact >= 70, 'exact under the rounded-means reading: ' + exact);
  assert.equal(res.esAgree.roundedExact, exact, 'the engine counts the same'); assert.equal(res.esAgree.roundedN, 81);
});
test('control', 'the truncated grades 1 and 2 gains, recomputed independently, equal the engine and Elashoff and Snow', () => {
  for (const m of ['total', 'reasoning']) {
    const ind = indepTruncGain(m, [1, 2], 60, 160);
    const r = res.es[m + '|1-2|truncated'][2];
    near(ind.adv, r.advantage, 1e-9); near(ind.t, r.t, 1e-9); near(ind.p2, r.p, 1e-6); assert.equal(ind.nE, r.nE); assert.equal(ind.nC, r.nC);
    near(ind.adv, printed.es1970.tables20to22[m]['1-2'].truncated[2][0], 0.15);
  }
  assert.ok(res.es['total|1-2|truncated'][2].significant && !res.es['reasoning|1-2|truncated'][2].significant);
});
test('control', 'Rosenthal and Rubin’s Table 31 comes back from the page’s own cells', () => {
  for (const g of ['1-2', '3-4', '5-6']) {
    const x = res.t31[g], pr = printed.rr1971.table31.rows[g];
    near(x.rj, pr.rj, 0.05, g + ' RJ'); near(x.ciLo, pr.ciLo, 0.05, g + ' interval low'); near(x.ciHi, pr.ciHi, 0.05, g + ' interval high');
    // their mean, median, lowest and highest were taken over Elashoff and Snow's printed (rounded) cells
    for (const k of ['mean', 'median', 'lowest', 'highest']) near(x[k], pr[k], 0.1, g + ' ' + k);
    assert.equal(x.nSig, pr.nSig, g + ' significant of nine');
  }
  near(printed.rr1971.table31.msw, A.total.msw, 0.01, 'their mean square is the anchor’s');
  // the interval uses t on the design's 284 degrees of freedom: with z the grades 5 and 6 upper end misses print
  const se56 = res.t31['5-6'].ciHi - res.t31['5-6'].rj;
  assert.ok(Math.abs(res.t31['5-6'].rj + se56 / ST.qt(0.025, A.total.df) * ST.qnorm(0.975) - printed.rr1971.table31.rows['5-6'].ciHi) > 0.05);
});
test('control', 'the other experiments: metadat’s printed fit reproduced, and independently by grid-search REML', () => {
  const m = printed.metadat.re, r = res.re19;
  near(r.estimate, m.estimate, 0.00005); near(r.se, m.se, 0.00005); near(r.z, m.z, 0.0001); near(r.p, m.p, 0.00005);
  near(r.ciLo, m.ciLo, 0.00005); near(r.ciHi, m.ciHi, 0.00005); near(r.tau2, m.tau2, 0.00005); near(r.I2, m.I2, 0.02); near(r.H2, m.H2, 0.005);
  near(r.Q, m.Q, 0.0001); near(r.Qp, m.Qp, 0.00005);
  const mm = printed.metadat.mod, mo = res.mod19;
  near(mo.intercept, mm.intercept, 0.0005); near(mo.slope, mm.slope, 0.0005); near(mo.interceptSe, mm.interceptSe, 0.0005); near(mo.slopeSe, mm.slopeSe, 0.0005);
  near(mo.QM, mm.QM, 0.001); near(mo.QE, mm.QE, 0.001); near(mo.tau2, mm.tau2, 0.0005);
  const ind = indepREML(rows.map(x => x.yi), rows.map(x => x.vi));
  near(ind.estimate, r.estimate, 1e-6); near(ind.tau2, r.tau2, 1e-6);
});
test('control', 'the other experiments split by contact: the values the spec verified, and Oak left out by default', () => {
  const c = res.c2;
  assert.equal(c.k, 18); assert.ok(!c.used.some(r => r.oak), 'Oak does not vote by default');
  near(c.all.estimate, 0.057, 0.0005); near(c.all.z, 1.22, 0.005);
  assert.equal(c.low.k, 10); near(c.low.estimate, 0.274, 0.0005); near(c.low.z, 2.81, 0.005);
  assert.equal(c.high.k, 8); near(c.high.estimate, -0.063, 0.0005); near(c.high.z, -1.26, 0.005);
  near(res.c2snow.low.estimate, 0.198, 0.0005); near(res.c2snow.low.z, 2.53, 0.005);
  near(res.c2cut1.low.estimate, 0.416, 0.0005); near(res.c2cut1.low.z, 3.10, 0.005);
  near(res.c2cut1snow.low.estimate, 0.332, 0.0005); near(res.c2cut1snow.low.z, 3.02, 0.005);
});
test('control', 'the distribution functions agree with independent values', () => {
  near(ST.tUpper(2.1316, 284), tTail(2.1316, 284), 1e-7); near(ST.tUpper(-1.2, 30), tTail(-1.2, 30), 1e-7);
  near(ST.normUpper(1.959963984540054), 0.025, 1e-12); near(ST.chi2Upper(3.841458820694124, 1), 0.05, 1e-12);
  near(ST.qnorm(0.975), 1.959963984540054, 1e-9);
});

// ================================================================== power (grade A: planted into the real children)
const pT = res.power.total, pR = res.power.reasoning;
test('power', 'the injection uses the claim’s printed sizes, read from the printed record, and moves when they move', () => {
  const bk = printed.rj1968.table7_1.rows;
  assert.deepEqual(pT.injected.sizeByGrade, { 1: bk[0].adv, 2: bk[1].adv }); assert.equal(pT.injected.sizeByGrade[1], 15.4); assert.equal(pT.injected.sizeByGrade[2], 9.5);
  assert.deepEqual(pR.injected.sizeByGrade, { 1: 12.7, 2: 12.7 }); assert.equal(pR.injected.sizeByGrade[1], printed.rj1968.table7_4.rows[0].adv);
  const moved = clone(printed); moved.rj1968.table7_1.rows[0].adv = 20;
  assert.equal(E.claimedSizes(moved, { measure: 'total' }).sizeByGrade[1], 20, 'the size follows the printed record');
  near(E.uniformClaim(printed), 10.989, 0.001);
});
test('power', 'the plant goes into copies of the real children’s scores, unrounded and unclipped, and the real records are untouched', () => {
  const before = JSON.stringify(records);
  const copy = E.plantAdvantage(E.drawBloomers(records, { seed: 7, measure: 'total', grades: [1, 2] }), { measure: 'total', sizeByGrade: { 1: 15.4, 2: 9.5 } });
  assert.equal(JSON.stringify(records), before, 'records unchanged');
  assert.equal(copy.meta.drawn, 19); assert.ok(copy.every(r => r.realGroup === 0), 'pseudo-bloomers drawn only from unnamed children');
  for (const r of copy.filter(x => x.pseudo)) {
    const orig = records.find(x => x.id === r.id);
    near(r.total[2] - orig.total[2], r.grade === 1 ? 15.4 : 9.5, 1e-12); assert.deepEqual(r.verbal, orig.verbal); assert.equal(r.total[0], orig.total[0]);
  }
  for (const [k, n] of Object.entries(copy.meta.counts)) {
    const [g, a] = k.split('-').map(Number);
    assert.equal(copy.filter(r => r.grade === g && r.track === a && r.pseudo).length, n);
    assert.equal(n, records.filter(r => r.grade === g && r.track === a && r.group === 1 && r.total[0] !== null && r.total[2] !== null).length);
  }
});
test('power', 'the power runs through the unmodified esControl: a recount of the first 300 draws agrees draw by draw', () => {
  const sub = E.powerControl(records, printed, { measure: 'total', draws: 300, keep: true });
  const mine = [];
  for (let s = 1; s <= 300; s++) {
    const copy = E.plantAdvantage(E.drawBloomers(records, { seed: s, measure: 'total', grades: [1, 2] }), { measure: 'total', sizeByGrade: { 1: 15.4, 2: 9.5 } });
    const r = E.esControl(copy, { measure: 'total', gradeGroup: '1-2', scores: 'truncated', criterion: 'gain', tails: 2 });
    mine.push(r.advantage > 0 && r.p < 0.05);
  }
  assert.deepEqual(sub.detections, mine, 'draw by draw');
  assert.equal(Math.round(sub.power * 300), mine.filter(Boolean).length);
});
// An independent simulation: its own random numbers (xorshift32), its own within-classroom draw, its own
// truncated t test and t tail. It cannot reproduce the page's draws, only their long-run rates, so it is
// held to four combined Monte Carlo standard errors.
function xorshift(seed) { let x = (seed * 2654435761) >>> 0 || 1; return () => { x ^= x << 13; x >>>= 0; x ^= x >>> 17; x ^= x << 5; x >>>= 0; return x / 4294967296; }; }
const critCache = new Map();
function tCrit2(df) { if (!critCache.has(df)) { let lo = 0, hi = 10; for (let i = 0; i < 50; i++) { const m = (lo + hi) / 2; if (2 * tTail(m, df) > 0.05) lo = m; else hi = m; } critCache.set(df, (lo + hi) / 2); } return critCache.get(df); }
function indepPower(key, sizes, draws, seed) {
  const rng = xorshift(seed);
  const kids = IR.filter(r => r.grade <= 2 && r[key + '1'] !== null && r[key + '3'] !== null);
  const rooms = {};
  for (const r of kids) { const c = r.grade + ':' + r.track; (rooms[c] = rooms[c] || { named: 0, pool: [] }); if (r.group === 1) rooms[c].named++; else rooms[c].pool.push(r); }
  let hit = 0;
  for (let d = 0; d < draws; d++) {
    const e = [], c = [];
    for (const room of Object.values(rooms)) {
      const idx = room.pool.map((_, i) => i);
      for (let i = idx.length - 1; i > 0; i--) { const j = Math.floor(rng() * (i + 1)); [idx[i], idx[j]] = [idx[j], idx[i]]; }
      const chosen = new Set(idx.slice(0, room.named));
      room.pool.forEach((r, i) => {
        const x = r[key + '1'], y = r[key + '3'] + (chosen.has(i) ? sizes[r.grade] : 0);
        if (x < 60 || x > 160 || y < 60 || y > 160) return;
        (chosen.has(i) ? e : c).push(y - x);
      });
    }
    const me = e.reduce((a, b) => a + b, 0) / e.length, mc = c.reduce((a, b) => a + b, 0) / c.length;
    const ss = e.reduce((a, b) => a + (b - me) ** 2, 0) + c.reduce((a, b) => a + (b - mc) ** 2, 0);
    const df = e.length + c.length - 2, tt = (me - mc) / Math.sqrt(ss / df * (1 / e.length + 1 / c.length));
    if (tt > tCrit2(df)) hit++;
  }
  return hit / draws;
}
test('power', 'an independent simulation, sharing no code with the engine, lands on the same power within Monte Carlo error', () => {
  const n = 1000;
  const within = (a, na, b, nb) => { const p = (a * na + b * nb) / (na + nb); return Math.abs(a - b) <= 4 * Math.sqrt(p * (1 - p) * (1 / na + 1 / nb)); };
  const it = indepPower('total', { 1: 15.4, 2: 9.5 }, n, 11);
  assert.ok(within(it, n, pT.power, pT.draws), 'total IQ: independent ' + it + ' against ' + pT.power);
  const ir = indepPower('reasoning', { 1: 12.7, 2: 12.7 }, n, 12);
  assert.ok(within(ir, n, pR.power, pR.draws), 'reasoning IQ: independent ' + ir + ' against ' + pR.power);
  assert.ok(it >= 0.8 && ir < 0.8, 'the independent simulation reaches the same two verdicts');
});
test('power', 'the control is not a constant: nothing planted gives the false-positive rate, the claimed size gives the power', () => {
  const zero = clone(printed); zero.rj1968.table7_1.rows[0].adv = 0; zero.rj1968.table7_1.rows[1].adv = 0;
  const z = E.powerControl(records, zero, { measure: 'total', draws: 400 });
  const withPlant = E.powerControl(records, printed, { measure: 'total', draws: 400 });
  near(z.power, z.falsePos, 1e-12, 'a zero plant reads as the unplanted baseline');
  assert.ok(withPlant.power > z.power + 0.5, 'the plant is what the control finds');
  assert.ok(pT.falsePos < 0.05 && pR.falsePos < 0.05);
});
test('power', 'grade A verdicts: total IQ could, reasoning IQ could NOT, and the real list agrees with the total verdict', () => {
  assert.ok(pT.power >= E.POWER_LINE && pT.could); assert.ok(pR.power < E.POWER_LINE && !pR.could);
  assert.ok(pT.deletedByPlantPerDraw < 0.05); assert.ok(pR.deletedPerDraw > 5);
  assert.ok(res.es['total|1-2|truncated'][2].significant, 'on the real list the control keeps the total-IQ advantage');
  assert.ok(html.includes('<b><span data-fig="pow.t.verdict">COULD</span></b>') && html.includes('<b><span data-fig="pow.r.verdict">could NOT</span></b>'), 'the page prints both verdicts');
  assert.equal(record ? record.power.grade : 'A-injection', 'A-injection');
});
test('power', 'the other experiments: Oak’s own d planted into every other row and into the high-contact rows', () => {
  near(res.oakD, 0.30, 1e-12); assert.equal(res.oakD, rows.find(r => r.oak).yi, 'the planted d is the Oak row’s yi');
  near(res.c2plantNon.all.estimate, 0.357, 0.0005); near(res.c2plantNon.all.z, 7.58, 0.005);
  near(res.c2plantHigh.high.estimate, 0.237, 0.0005); near(res.c2plantHigh.high.z, 4.74, 0.005);
  assert.ok(res.c2.high.z < 1.96, 'the real high-contact rows show nothing');
  const cp = E.plantD(rows, { d: 0.3, target: 'high' });
  assert.equal(cp.meta.injectedD, 0.3); assert.equal(cp.meta.rows, 8); assert.ok(cp.every(r => r.vi === rows.find(x => x.study === r.study).vi));
  // the continuous threshold: tau^2 is 0 in the high-contact rows, so z = (d + (-0.063)) / 0.050 crosses 1.96 near 0.161
  near(res.minD.d, 0.161, 0.0005); near(res.minD.z, 1.96, 0.001);
  const zAt = d => E.control2(E.plantD(rows, { d, target: 'high' }), {}).high.z;
  assert.ok(zAt(0.16) < 1.96 && zAt(0.17) >= 1.96, 'the slider’s 0.01 steps cross z = 1.96 between 0.16 and 0.17');
});

// ================================================================== null (the claimants' method on nothing)
test('null', 'the null runs go through the anchor’s own claimantTest on unnamed children: a recount of 200 draws', () => {
  const sub = E.nullClaimant(records, printed, { draws: 200 });
  let hit = 0;
  for (let s = 1; s <= 200; s++) {
    const copy = E.drawBloomers(records, { pool: 'undesignated', seed: s, measure: 'total', grades: [1, 2, 3, 4, 5, 6] });
    assert.ok(copy.every(r => r.realGroup === 0));
    if (E.claimantTest(copy, { measure: 'total' }).t >= 2.15) hit++;
  }
  assert.equal(sub.hitT, hit);
  const n = res.nul;
  assert.equal(n.draws, 10000); assert.equal(n.tPrinted, printed.rj1966.table1.weighted.t); assert.equal(n.df, 219);
  assert.ok(n.rateT > n.nominalT * 2, 'the school-wide test fires well above its table'); assert.ok(n.hit12 < 20, 'the grades 1 and 2 advantage is rare in the null');
  near(n.nominalT, tTail(2.15, 219), 1e-6);
});
test('null', 'an independent null run, sharing no code with the engine, lands on the same rate within Monte Carlo error', () => {
  const rng = xorshift(21), n = 2000;
  const kids = IR.filter(r => r.total1 !== null && r.total3 !== null);
  const rooms = {};
  for (const r of kids) { const c = r.grade + ':' + r.track; (rooms[c] = rooms[c] || { named: 0, pool: [] }); if (r.group === 1) rooms[c].named++; else rooms[c].pool.push(r); }
  let hit = 0, hitObs = 0;
  const tObs = indepClaim('total', [1, 2, 3, 4, 5, 6]).t;
  for (let d = 0; d < n; d++) {
    const cells = new Map(); let sE = 0, nE = 0, sC = 0, nC = 0, N = 0;
    for (const room of Object.values(rooms)) {
      const idx = room.pool.map((_, i) => i);
      for (let i = idx.length - 1; i > 0; i--) { const j = Math.floor(rng() * (i + 1)); [idx[i], idx[j]] = [idx[j], idx[i]]; }
      const chosen = new Set(idx.slice(0, room.named));
      room.pool.forEach((r, i) => {
        const g = r.total3 - r.total1, grp = chosen.has(i) ? 1 : 0, id = r.grade + ':' + r.track + ':' + grp;
        if (!cells.has(id)) cells.set(id, []); cells.get(id).push(g); N++;
        if (grp) { sE += g; nE++; } else { sC += g; nC++; }
      });
    }
    let ssw = 0; for (const xs of cells.values()) { const m = xs.reduce((a, b) => a + b, 0) / xs.length; for (const x of xs) ssw += (x - m) ** 2; }
    const msw = ssw / (N - 36), tt = (sE / nE - sC / nC) / Math.sqrt(msw * (1 / nE + 1 / nC));
    if (tt >= 2.15) hit++; if (tt >= tObs) hitObs++;
  }
  const within = (a, na, b, nb) => { const p = (a * na + b * nb) / (na + nb); return Math.abs(a - b) <= 4 * Math.sqrt(p * (1 - p) * (1 / na + 1 / nb)); };
  assert.ok(within(hit / n, n, res.nul.rateT, res.nul.draws), 'rate t >= 2.15: independent ' + hit / n + ' against ' + res.nul.rateT);
  assert.ok(within(hitObs / n, n, res.nul.rateObs, res.nul.draws), 'rate t >= the listing’s t: independent ' + hitObs / n + ' against ' + res.nul.rateObs);
  near(res.nul.tObs, tObs, 1e-9, 'the observed t');
  assert.ok(res.nul.rateObs > 0.03 && res.nul.rateObs < 0.05, 'the listing’s own t is passed in 3 to 5% of null lists, not in most of them');
  // the exact offsets against their simulated means
  assert.ok(Math.abs(res.nul.meanAdv - res.nul.offsetExact) < 4 * res.nul.sdAdv / Math.sqrt(res.nul.draws), 'null offset: simulated ' + res.nul.meanAdv + ', exact ' + res.nul.offsetExact);
  const rr = res.rr['total|all'];
  assert.ok(Math.abs(rr.meanAll - res.rrOffsetExact) < 4 * rr.sdAll / Math.sqrt(rr.draws), 're-drawn offset: simulated ' + rr.meanAll + ', exact ' + res.rrOffsetExact);
  const acc = E.nullStart(records, printed, {}); E.nullRun(acc, 1, 150); E.nullRun(acc, 151, 50);
  const whole = E.nullClaimant(records, printed, { draws: 200 }), split = E.nullSummary(acc);
  assert.equal(split.hitT, whole.hitT); assert.equal(split.meanT, whole.meanT); assert.equal(split.hitObs, whole.hitObs, 'the null run in blocks equals the run in one piece');
});
test('null', 'the re-randomisation places the real list among re-drawn ones, and the real statistic is the anchor’s', () => {
  const r = res.rr['total|all'];
  near(r.obsAll, A.total.adv, 1e-9); near(r.obs12, A.total.grades12.adv, 1e-9);
  near(res.rr['total|truncated'].obs12, res.es['total|1-2|truncated'][2].advantage, 1e-9);
  assert.ok(r.pAll > A.total.p1, 'the re-drawn p is larger than the t test’s'); assert.ok(r.p12 < 0.01);
  assert.equal(res.curve.length, 21); assert.ok(res.curve[20].claimants > 0.99 && res.curve[0].truncated < 0.05);
});

// ================================================================== surface
test('surface', 'every figure printed in the page equals the recomputation', () => {
  const figs = S.dataFigs(html);
  assert.ok(figs.length > 150, 'figures found: ' + figs.length);
  for (const f of figs) {
    assert.ok(f.key in F, 'unknown figure key ' + f.key);
    assert.equal(S.decodeEntities(f.inner), F[f.key], 'figure ' + f.key);
  }
});
test('surface', 'every generated table equals the recomputation', () => {
  const g = S.genBlocks(html);
  assert.deepEqual(Object.keys(g).sort(), Object.keys(B).sort());
  for (const k of Object.keys(B)) assert.equal(g[k], B[k], 'table ' + k);
});
test('surface', 'dek, headline, title, meta description, OG, Twitter and JSON-LD match the recomputed text', () => {
  const meta = (attr, name) => { const m = html.match(new RegExp('<meta ' + attr + '="' + name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '" content="([^"]*)"')); return m ? S.decodeEntities(m[1]) : null; };
  assert.equal(S.decodeEntities((html.match(/<p class="dek" data-dek>([\s\S]*?)<\/p>/) || [])[1] || ''), X.DEK);
  assert.equal(S.decodeEntities((html.match(/<p class="lede" id="headline" data-headline>([\s\S]*?)<\/p>/) || [])[1] || ''), X.HEADLINE);
  assert.equal(S.decodeEntities((html.match(/<title>([\s\S]*?)<\/title>/) || [])[1]), X.SEO);
  assert.equal(meta('name', 'description'), X.DEK); assert.equal(meta('property', 'og:description'), X.OG); assert.equal(meta('name', 'twitter:description'), X.TW);
  assert.equal(meta('property', 'og:image:alt'), X.OG_ALT);
  assert.equal(meta('property', 'og:image'), S.OG_IMAGE); assert.equal(meta('name', 'twitter:image'), S.OG_IMAGE);
  assert.ok(html.includes('<link rel="canonical" href="' + S.URL + '" />'));
  const ld = JSON.parse((html.match(/<script type="application\/ld\+json">([\s\S]*?)<\/script>/) || [])[1]);
  const date = (md.match(/^date:\s*(\S+)/m) || [])[1];
  assert.deepEqual(ld, JSON.parse(S.jsonLd(X, date)));
});
test('surface', 'frontmatter: dek, plain, seoTitle, relates and body match the recomputed text; placard rules hold', () => {
  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('seoTitle'), X.SEO); assert.equal(field('plain'), X.PLAIN);
  assert.equal(field('title'), S.TITLE); assert.equal(field('seam'), 'mind'); assert.equal(field('href'), '/strata/' + S.SLUG + '/');
  const plain = X.PLAIN;
  assert.ok(plain.length >= 90 && plain.length <= 420, 'placard length ' + plain.length);
  assert.ok(!plain.includes('"') && !plain.includes(EM_DASH));
  const notes = [...fm.matchAll(/- to: (\S+)\n\s+note: "(.*)"/g)].map(m => [m[1], m[2]]);
  assert.deepEqual(notes, S.RELATES.map(([to, note]) => [to, S.fill(note, F)]));
  for (const [to] of notes) assert.ok(fs.existsSync(path.join(root, 'src/content/strata', to + '.md')), 'relates target ' + to);
  const body = md.slice(md.indexOf('\n---', 4) + 4).trim();
  assert.equal(body, X.BODY.join('\n\n'));
  assert.ok(body.includes(VERDICT.as_of_words) && body.includes(VERDICT.category));
});
test('surface', 'every other number a reader can see matches the inventory, in order', () => {
  const lits = S.literalNumbers(html);
  if (REGEN && results.every(t => t.pass)) fs.writeFileSync(literalsPath, JSON.stringify(lits, null, 0) + '\n');
  assert.ok(fs.existsSync(literalsPath), 'surface-literals.json missing');
  assert.deepEqual(lits, JSON.parse(fs.readFileSync(literalsPath, 'utf8')));
});
test('surface', 'every quotation appears as sourced, and the novelty and verdict texts as written', () => {
  const vis = S.decodeEntities(html);
  for (const [k, q] of Object.entries(QUOTES)) { assert.ok(vis.includes(q.text), 'quotation ' + k); assert.ok(vis.includes(q.cite) || ['snowFive', 'snow35', 'snowAsterisks', 'rjAdministrator', 'rjAdministrator2', 'rrUndiminished', 'rrConsistent', 'rrBias', 'esRebuttal', 'rosenthal1995', 'jussimDisconfirmed', 'rdhFinding', 'rdhCatalyst', 'unwise'].includes(k), 'citation ' + k); }
  assert.ok(vis.includes(NOVELTY));
});
test('surface', 'house rules: no em dash, no forbidden words, no third-party requests, no shell at the reader', () => {
  for (const f of fs.readdirSync(dir)) { const t = fs.readFileSync(path.join(dir, f), 'utf8'); assert.ok(!t.includes(EM_DASH), 'em dash in ' + f); }
  for (const f of [mdPath, ...fs.readdirSync(here).filter(f => f.endsWith('.mjs') || f.endsWith('.md')).map(f => path.join(here, f))]) assert.ok(!fs.readFileSync(f, 'utf8').includes(EM_DASH), 'em dash in ' + f);
  const lower = html.toLowerCase();
  for (const w of ['debunk', 'refuted', 'disproved', 'fraud', 'fabricat', 'misconduct', 'hoax', 'myth', 'worthless', 'absurd']) assert.ok(!lower.includes(w), 'forbidden word ' + w);
  for (const m of html.matchAll(/<(script|link|img|iframe)\b[^>]*\b(src|href)="([^"]+)"/g)) {
    if (m[1] === 'link' && /rel="canonical"/.test(m[0])) continue;
    assert.ok(!/^(https?:)?\/\//.test(m[3]), 'third-party ' + m[1] + ': ' + m[3]);
  }
  for (const f of fs.readdirSync(dir).filter(f => f.endsWith('.js'))) {
    const t = fs.readFileSync(path.join(dir, f), 'utf8');
    assert.ok(!/fetch\(\s*['"`]https?:/.test(t) && !/import\s.*from\s+['"]https?:/.test(t) && !/new\s+(WebSocket|EventSource)/.test(t) && !/sendBeacon|XMLHttpRequest/.test(t), 'network call in ' + f);
    // no absolute URL of any kind in a module, however it is used, except the SVG namespace name
    const urls = (t.match(/(?:https?:)?\/\/[a-z0-9.-]+\.[a-z]{2,}[^\s'"`)]*/gi) || []).filter(u => u !== 'http://www.w3.org/2000/svg');
    assert.deepEqual(urls, [], 'absolute URL in ' + f);
  }
  assert.ok(!/github\.com\/[^"\s]*Artificial-Wasteland/i.test(html) && !/\bnode research\//.test(html) && !/\$ node|npm run/.test(html));
});
test('surface', 'structure: closing tags, one inline script (the JSON-LD), modules parse, accessibility basics', () => {
  assert.ok(/<\/script>\s*<\/body>\s*<\/html>\s*$/.test(html), 'closing tags');
  const inline = [...html.matchAll(/<script(?![^>]*\bsrc=)[^>]*>([\s\S]*?)<\/script>/g)];
  assert.equal(inline.length, 1); assert.ok(/application\/ld\+json/.test(inline[0][0])); JSON.parse(inline[0][1]);
  const last = html.slice(html.lastIndexOf('<script')); assert.ok(last.startsWith('<script type="module" src="./page.js">'));
  for (const f of fs.readdirSync(dir).filter(f => f.endsWith('.js'))) { const r = spawnSync(process.execPath, ['--check', path.join(dir, f)]); assert.equal(r.status, 0, 'node --check ' + f); }
  assert.ok((html.match(/role="status"/g) || []).length >= 10, 'status readouts');
  assert.ok(/prefers-reduced-motion/.test(html) && /:focus-visible/.test(html) && /\/fonts\/fonts\.css/.test(html));
  for (const m of html.matchAll(/<input\b[^>]*>/g)) {
    const tag = m[0];
    if (/type="radio"/.test(tag) || /type="checkbox"/.test(tag)) { const i = html.lastIndexOf('<label', m.index); assert.ok(i > html.lastIndexOf('</label>', m.index), 'input inside a label: ' + tag); }
    else { const id = (tag.match(/id="([^"]+)"/) || [])[1]; assert.ok(id && (new RegExp('<label[^>]*for="' + id + '"').test(html) || html.lastIndexOf('<label', m.index) > html.lastIndexOf('</label>', m.index)), 'labelled: ' + tag); }
  }
  assert.ok(!/<span[^>]*onclick/.test(html) && !/<div[^>]*onclick/.test(html));
});

// ================================================================== choices
test('choices', 'every live choice moves a named engine output', () => {
  const es = o => E.esControl(records, { measure: 'total', gradeGroup: '1-2', scores: 'all', criterion: 'gain', tails: 2, lo: 60, hi: 160, ...o });
  const base = es({});
  assert.notEqual(es({ scores: 'truncated' }).advantage, base.advantage); assert.notEqual(es({ scores: 'renormed' }).advantage, base.advantage);
  const tr = o => es({ scores: 'truncated', measure: 'reasoning', ...o }).advantage;
  for (const lo of [50, 70]) assert.notEqual(tr({ lo }), tr({}), 'lower bound ' + lo);
  const rn = o => es({ scores: 'renormed', ...o }).advantage;
  for (const hi of [150, 170]) assert.notEqual(rn({ hi }), rn({}), 'upper bound ' + hi);
  assert.notEqual(es({ measure: 'reasoning' }).advantage, base.advantage); assert.notEqual(es({ measure: 'verbal' }).advantage, base.advantage);
  for (const c of ['posttest', 'pretest', 'adjusted']) assert.notEqual(es({ criterion: c }).advantage, base.advantage);
  for (const g of ['3-4', '5-6', 'all']) assert.notEqual(es({ gradeGroup: g }).advantage, base.advantage);
  assert.notEqual(es({ tails: 1 }).p, base.p);
  const an = o => E.claimantTest(records, { measure: 'total', ...o });
  assert.notEqual(an({ occasion: 2 }).adv, an({}).adv); assert.notEqual(an({ occasion: 4, grades: [1, 2, 3, 4, 5] }).adv, an({ grades: [1, 2, 3, 4, 5] }).adv);
  assert.notEqual(an({ grades: [1] }).adv, an({}).adv);
  const c2 = o => E.control2(rows, o);
  for (const cut of [0, 1, 3]) assert.notEqual(c2({ contactCut: cut }).low.estimate, c2({}).low.estimate);
  assert.notEqual(c2({ includeOak: true }).low.estimate, c2({}).low.estimate);
  assert.notEqual(c2({ phCoding: 'blind' }).low.estimate, c2({}).low.estimate);
  assert.notDeepEqual(c2({ model: 'moderator' }).summary, c2({}).summary);
  const rr = o => E.rerandomise(records, { measure: 'total', scores: 'all', draws: 200, ...o });
  assert.notEqual(rr({ measure: 'reasoning' }).obs12, rr({}).obs12); assert.notEqual(rr({ scores: 'renormed' }).obs12, rr({}).obs12); assert.notEqual(rr({ scores: 'truncated' }).obs12, rr({}).obs12);
  const pd = o => E.control2(E.plantD(rows, { d: 0.3, target: 'high', ...o }), {});
  assert.notEqual(pd({ d: 0.5 }).high.estimate, pd({}).high.estimate); assert.notEqual(pd({ target: 'nonOak' }).all.estimate, pd({}).all.estimate);
  const pw = o => E.powerControl(records, printed, { measure: 'total', draws: 300, ...o }).power;
  assert.notEqual(pw({ shape: 'uniform' }), pw({})); assert.notEqual(pw({ pool: 'all' }), pw({}));
  assert.notEqual(pw({ measure: 'reasoning' }), pw({}));
});
test('choices', 'the row order is inert: shuffled listings leave the anchor, the control and the seeded draws unchanged', () => {
  const rng = ST.mulberry32(99);
  const baseA = E.claimantTest(records, {}), baseE = E.esControl(records, { scores: 'truncated' }), baseP = E.powerControl(records, printed, { draws: 100 });
  for (let k = 0; k < 20; k++) {
    const sh = records.slice().sort(() => rng() - 0.5);
    const a = E.claimantTest(sh, {}), e = E.esControl(sh, { scores: 'truncated' });
    near(a.adv, baseA.adv, 1e-9); near(a.msw, baseA.msw, 1e-9); near(e.advantage, baseE.advantage, 1e-9);
    if (k < 3) assert.equal(E.powerControl(sh, printed, { draws: 100 }).power, baseP.power);
  }
});
test('choices', 'every choice is well formed for the wave’s gate, declared on the page, and its default is one of its options', () => {
  for (const c of CHOICES) {
    assert.ok(c.id && Array.isArray(c.options) && c.options.length >= 2 && Array.isArray(c.affects) && typeof c.inert === 'boolean');
    assert.ok(c.options.some(o => String(o) === String(c.default)), 'default of ' + c.id);
  }
  assert.equal(CHOICES.filter(c => c.inert).length, 1);
  for (const n of ['esScores', 'esMeasure', 'esGroup', 'esCrit', 'esTails', 'esLo', 'esHi', 'aOccasion', 'aGrades', 'aMeasure', 'c2Cut', 'c2Oak', 'c2PH', 'c2Model', 'pwShape', 'pwPool', 'pwMeasure', 'heroMeasure', 'heroNorm', 'rrMeasure', 'rrScores', 'pdD', 'pdTarget']) assert.ok(html.includes('"' + n + '"'), 'control ' + n);
  for (const id of ['rerandMeasure', 'rerandScores', 'plantD', 'plantTarget']) assert.ok(CHOICES.some(c => c.id === id && !c.inert), 'declared choice ' + id);
  assert.equal(CHOICES.filter(c => !c.inert).length, 19);
});

// ================================================================== faults
test('fault', 'faults planted in copies of the frozen files move the results the page prints', () => {
  const bad = clone(records);
  bad.find(r => r.id === 106).total[2] = 102;             // one child’s posttest, as a misread 2 for 0
  const t = E.claimantTest(bad, {});
  assert.ok(Math.abs(t.adv - A.total.adv) > 0.5, 'the anchor moves');
  assert.ok(Math.abs(E.describe(bad, { measure: 'total', grades: [1, 2], occasion: 3 }).max - printed.es1970.table5.total['1-2'][4]) > 0, 'the Table 5 gate goes red');
  const badRows = clone(metaJson); badRows.rows[16][8] = 0.9;
  assert.ok(Math.abs(E.rmaREML(E.metaRows(badRows).map(r => r.yi), E.metaRows(badRows).map(r => r.vi)).estimate - printed.metadat.re.estimate) > 0.001, 'metadat reproduction goes red');
  const swapped = clone(records); for (const r of swapped) if (r.grade === 1) r.group = 1 - r.group;
  assert.notDeepEqual(E.claimantTest(swapped, {}).byGrade[0].E.n, 7, 'Table 7-1 N goes red');
});
test('fault', 'the surface check goes red on a corrupted displayed figure, a corrupted table and a corrupted dek', () => {
  const figs = S.dataFigs(html);
  const f = figs.find(x => x.key === 'a.msw');
  const bent = html.slice(0, f.index) + html.slice(f.index).replace('>' + F['a.msw'] + '<', '>164.25<');
  assert.ok(S.dataFigs(bent).some(x => S.decodeEntities(x.inner) !== F[x.key]), 'figure');
  const g = S.genBlocks(html.replace('+15.4', '+15.5'));
  assert.ok(Object.keys(B).some(k => g[k] !== B[k]), 'table');
  const dek = html.replace(/(<p class="dek" data-dek>)([\s\S]*?)(<\/p>)/, (m, a, b, c) => a + b.replace(/\d/, '8') + c);
  assert.notEqual(S.decodeEntities(dek.match(/<p class="dek" data-dek>([\s\S]*?)<\/p>/)[1]), X.DEK, 'dek');
  const lits = S.literalNumbers(html.replace('May 1964 every child', 'May 1965 every child'));
  assert.notDeepEqual(lits, S.literalNumbers(html), 'literal inventory');
});
test('fault', 'a changed byte in a frozen file is caught by the same pin check the provenance group runs', () => {
  const buf = Buffer.from(fs.readFileSync(path.join(dir, FILES.listing)));
  assert.deepEqual(pinProblems(FILES.listing, buf), [], 'the real bytes pass');
  buf[buf.length - 3] ^= 1;
  const probs = pinProblems(FILES.listing, buf);
  assert.ok(probs.length >= 3, 'the altered bytes fail the data.js pin, the README and the research copy: ' + probs.join('; '));
});

// ================================================================== refusals
test('refusal', 'the instrument refuses what the record does not hold, and says why on the page', () => {
  const a = E.esControl(records, { gradeGroup: 'all', criterion: 'adjusted' });
  assert.ok(a.refused && a.reason.includes(QUOTES.unwise.text));
  const b = E.esControl(records, { scores: 'truncated', lo: 150, hi: 160, measure: 'reasoning' });
  assert.ok(b.refused && /at least 2 in each group/.test(b.reason), 'bounds that empty a group');
  const c = E.control2(rows, { contactCut: 21 });
  assert.ok(c.refused && /at least 2 rows on each side/.test(c.reason));
  const d = E.claimantTest(records, { occasion: 4 });
  assert.ok(d.refused && /grade 6 has no/.test(d.reason), 'no sixth grader at May 1966');
  assert.ok(E.claimantTest(records, { occasion: 1 }).refused);
  assert.ok(E.esControl(records, { lo: 160, hi: 60 }).refused);
  // bounds that renorm every kept score to one value leave nothing to compare: refused, never "p = 2.000"
  for (const [lo, hi, c] of [[155, 160, 'pretest'], [155, 160, 'adjusted'], [0, 40, 'posttest'], [200, 320, 'pretest']]) {
    const r = E.esControl(records, { scores: 'renormed', lo, hi, criterion: c });
    assert.ok(r.refused && /no spread left/.test(r.reason), 'renormed ' + lo + ' to ' + hi + ' ' + c + ': ' + JSON.stringify(r).slice(0, 120));
  }
  assert.ok(Number.isNaN(ST.tP(NaN, 10, 2)) && Number.isNaN(ST.tP(NaN, 10, 1)), 'a t that is not a number has no p');
  assert.ok(html.includes('so that combination is refused rather than computed from nothing') && html.includes('id="esRefusal"') && html.includes('id="c2Refusal"'));
  assert.ok(/'Refused: ' \+ r\.reason/.test(fs.readFileSync(path.join(dir, 'page.js'), 'utf8')));
});

// ================================================================== provenance
// One pin check, used by the provenance group on the shipped bytes and by the fault group on altered ones.
function pinProblems(name, buf) {
  const probs = [];
  const h = crypto.createHash('sha256').update(buf).digest('hex');
  if (h !== SHA256[name]) probs.push('data.js pin ' + name);
  if (!readme.includes(h)) probs.push('README does not list ' + name + ' at ' + h.slice(0, 12));
  if (!fs.readFileSync(path.join(here, 'data', name)).equals(buf)) probs.push('research copy of ' + name + ' differs');
  // with --regen, record.json is about to be rewritten from these hashes, and the manifest assertion then holds it to them
  if (record && !REGEN && !record.records.some(r => r.sha256 === h && r.file === name)) probs.push('record.json does not pin ' + name);
  return probs;
}
test('provenance', 'every frozen file is pinned in data.js, the research README and record.json, and copied byte for byte', () => {
  for (const name of Object.values(FILES)) assert.deepEqual(pinProblems(name, fs.readFileSync(path.join(dir, name))), [], name);
  assert.ok(readme.includes('876f47161c423c73f03c982e6427f3969938404803e3fcc6dcfae2bab61af7fd'), 'README pins the ERIC PDF');
  assert.ok(readme.includes('f5f2bb245d2241ed876e17b038c856732684f1884993546721b097b554c6e305'), 'README pins the metadat tarball');
});

// ================================================================== verdict
test('verdict', 'category, date, scope, sources and what would change it are printed and match record.json', () => {
  const vis = S.decodeEntities(html);
  assert.ok(html.includes('<p class="cat" id="vCat"><span data-fig="v.cat">' + VERDICT.category + '</span></p>'));
  assert.ok(html.includes('<span id="vAsOf"><span data-fig="v.asof">' + VERDICT.as_of + '</span></span>'));
  assert.ok(vis.includes(VERDICT.scope)); assert.ok(vis.includes(VERDICT.would_change));
  const src = S.decodeEntities((html.match(/<ol class="refs" id="vSources">([\s\S]*?)<\/ol>/) || [])[1] || '');
  assert.ok(VERDICT.sources.length >= 2); for (const s of VERDICT.sources) assert.ok(src.includes(s));
  for (const w of ['debunked', 'refuted', 'disproved']) assert.ok(!html.toLowerCase().includes(w));
  assert.equal(VERDICT.category, 'OPEN'); assert.equal(VERDICT.decided_by, 'not-yet'); assert.equal(VERDICT.years_to_decision, null);
  if (record) {
    assert.deepEqual(record.verdict, { category: VERDICT.category, as_of: VERDICT.as_of, sources: [...VERDICT.sources], would_change: VERDICT.would_change });
    assert.equal(record.decided_by, 'not-yet'); assert.equal(record.years_to_decision, null);
  }
});

// ================================================================== record.json
// how many printed numbers the reference file carries (every numeric leaf)
function countNumbers(x) { return typeof x === 'number' ? 1 : Array.isArray(x) ? x.reduce((s, v) => s + countNumbers(v), 0) : x && typeof x === 'object' ? Object.values(x).reduce((s, v) => s + countNumbers(v), 0) : 0; }
function makeRecord(ledger) {
  const T = A.total, bk = printed.rj1968.table7_1, w = printed.rj1966.table1.weighted;
  const hashes = Object.fromEntries(Object.values(FILES).map(n => [n, crypto.createHash('sha256').update(fs.readFileSync(path.join(dir, n))).digest('hex')]));
  const tr = res.es['total|1-2|truncated'][2], rr = res.es['reasoning|1-2|truncated'][2];
  return {
    slug: S.SLUG, title: S.TITLE, href: '/strata/' + S.SLUG + '/', field: 'psychology',
    claim: {
      statement: CLAIM.statement,
      claimants: CLAIM.claimants,
      citation: CLAIM.citation,
      year: CLAIM.year,
      headline_as_printed: 'Table 1 (1966), weighted: controls M 8.4 (sigma 13.5), experimentals M 12.2 (sigma 15.0), Diff. 3.8, t 2.15, p .02 one-tailed; book Table 7-1: N 255 gain +8.42, N 65 gain +12.22, advantage +3.80, p .02, mean square within treatments within classrooms 164.24; grade 1 +15.4 (t 2.97, p .002), grade 2 +9.5 (t 2.28, p .02). Text: ' + CLAIM.headlineText,
    },
    records: [
      { file: FILES.listing, role: 'claimant-data', name: 'Every child in Elashoff and Snow’s Appendix B listing of the data supplied by Rosenthal and Jacobson: ID, grade, track, designation and total, verbal and reasoning IQ at four testings, transcribed twice from the scan and reconciled (minority status, sex and age not transcribed)', url: 'https://files.eric.ed.gov/fulltext/ED046892.pdf (PDF pages 163 to 174; record https://eric.ed.gov/?id=ED046892)', licence: 'Numeric transcription of facts from a 1970 technical report that carries no copyright notice; ERIC: the authors or publishers retain copyright, so no part of the report other than the numbers is shipped', licence_url: 'https://eric.ed.gov/?copyright', retrieved: '2026-09-23', sha256: hashes[FILES.listing], units: records.length },
      { file: FILES.meta, role: 'control-data', name: 'dat.raudenbush1985 from the R package metadat 1.6-0: nineteen rows (eighteen experiments) of teacher-expectancy effects on IQ, as coded by Raudenbush and Bryk (1985)', url: 'https://cran.r-project.org/src/contrib/metadat_1.6-0.tar.gz (data/dat.raudenbush1985.rda)', licence: 'GPL (>= 2)', licence_url: 'https://www.gnu.org/licenses/old-licenses/gpl-2.0.html', retrieved: '2026-09-23', sha256: hashes[FILES.meta], units: rows.length },
      { file: FILES.printed, role: 'reference', name: 'The printed tables this page is held to, retyped: 1966 Tables 1 and 2, book Tables 7-1, 7-3 and 7-4, Elashoff and Snow Tables 2, 4, 5 and 20 to 22, the metadat printed fit, and single printed values from Raudenbush 1984, Rosenthal and Rubin 1971, Snow 1995 and Rubie-Davies and Hattie 2024', url: 'https://files.eric.ed.gov/fulltext/ED046892.pdf; https://gwern.net/doc/statistics/bias/1968-rosenthal-pygmalionintheclassroom.pdf; https://gwern.net/doc/statistics/bias/1971-elashoff-pygmalionreconsidered.pdf; https://homepages.gac.edu/~jwotton2/PSY225/rosenthal.pdf; https://wviechtb.github.io/metadat/reference/dat.raudenbush1985.html', licence: 'Individual printed numbers (facts) retyped as comparison targets; no table layout or page reproduced', licence_url: 'https://eric.ed.gov/?copyright', retrieved: '2026-09-23', sha256: hashes[FILES.printed], units: countNumbers(printed) },
    ],
    anchor: {
      what: 'The claimants’ gain-score comparison (claimantTest) run on the frozen listing: per-grade and school-wide gains, standard deviations, the mean square within treatments within classrooms, and t',
      expected: 'as printed: school-wide gains +8.42 (N 255) and +12.22 (N 65), advantage +3.80, mean square 164.24, t 2.15, one-tailed p .02; grade 1 +15.4 (t 2.97), grade 2 +9.5 (t 2.28); every per-grade mean and sigma of the 1966 Table 1',
      computed: 'gains +' + T.C.mean.toFixed(4) + ' (N ' + T.C.n + ') and +' + T.E.mean.toFixed(4) + ' (N ' + T.E.n + '), advantage +' + T.adv.toFixed(4) + ', mean square ' + T.msw.toFixed(3) + ' on ' + T.df + ' df (N minus all 36 design cells), t ' + T.t.toFixed(3) + ', one-tailed p ' + T.p1.toFixed(4) + '; grade 1 +' + T.byGrade[0].adv.toFixed(2) + ' (t ' + T.byGrade[0].t.toFixed(3) + '), grade 2 +' + T.byGrade[1].adv.toFixed(2) + ' (t ' + T.byGrade[1].t.toFixed(3) + '); grades 1 and 2 together +' + T.grades12.adv.toFixed(2) + '; every per-grade mean and population SD within half a unit of the printed digit',
      agrees: results.filter(t => t.group === 'anchor').every(t => t.pass),
      tolerance: 'counts exact; means and SDs within half a unit of the last printed digit; mean squares within 0.01; school-wide t within 0.03 of 2.15 (the listing gives ' + T.t.toFixed(3) + '; the last ' + Math.abs(w.t - T.t).toFixed(3) + ' is not recoverable and is reported) with p rounding to .02; grade t within 0.02',
    },
    control: {
      name: 'Elashoff and Snow’s deletion of scores outside the TOGA norms (60 to 160): the grades 1 and 2 gain advantage with every child dropped whose pretest or posttest lies outside, their Table 20 (total IQ) and Table 22 (reasoning IQ)',
      citation: 'Janet Dixon Elashoff and Richard E. Snow (1970). A Case Study in Statistical Inference: Reconsideration of the Rosenthal-Jacobson Data on Teacher Expectancy. Technical Report No. 15, Stanford Center for Research and Development in Teaching, pp. 61 and 102 to 105; ERIC ED046892. Revised as Pygmalion Reconsidered (1971), Charles A. Jones Publishing Company, a division of Wadsworth. With the other experiments: Raudenbush (1984), Journal of Educational Psychology 76(1), 85-97, rows as coded by Raudenbush and Bryk (1985).',
      computed: 'total IQ, grades 1 and 2, truncated: advantage ' + tr.advantage.toFixed(2) + ' (' + tr.nE + ' named, ' + tr.nC + ' not), two-tailed p ' + tr.p.toFixed(4) + '; reasoning IQ, truncated: ' + rr.advantage.toFixed(2) + ' (' + rr.nE + ' and ' + rr.nC + '), p ' + rr.p.toFixed(3) + '; all 108 cells of Tables 20 to 22 within ' + F['es.maxDev'] + ' of print, significance marks 108 of 108. Other experiments without Oak: low contact (2 weeks or less) ' + res.c2.low.estimate.toFixed(3) + ' (z ' + res.c2.low.z.toFixed(2) + ', 10 rows), high contact ' + res.c2.high.estimate.toFixed(3) + ' (z ' + res.c2.high.z.toFixed(2) + ', 8 rows)',
      as_printed: 'Table 20, total IQ, grades 1 and 2, truncated: pretest 0.7, posttest 10.6*, gain 9.9*, adjusted 10.1*; Table 22, reasoning IQ, truncated: 0.3, 6.0, 5.7, 5.8 (* two-tailed p < .05). Conclusion (1971, p. 44): ' + QUOTES.esConclusion.text,
    },
    power: {
      grade: 'A-injection',
      planted: 'Pseudo-bloomers drawn within each first- and second-grade classroom from the children not named (as many as that classroom had named), seeds 1 to ' + pT.draws + '; the claimed advantage added to each one’s May 1965 score, unrounded and unclipped: total IQ +15.4 in grade 1 and +9.5 in grade 2 (Table 7-1), reasoning IQ +12.7 (Table 7-4); run through the unmodified esControl, truncated, gain, two-tailed p < .05 with a positive advantage. Other experiments: d = 0.30 (the dataset’s own Oak coding) added to every non-Oak row and to the 8 high-contact rows',
      recovered: 'total IQ: kept in ' + (100 * pT.power).toFixed(1) + '% of copies (all scores ' + (100 * pT.powerAll).toFixed(1) + '%; nothing planted ' + (100 * pT.falsePos).toFixed(1) + '%), ' + pT.deletedByPlantPerDraw.toFixed(2) + ' pseudo-bloomers per copy deleted because of the plant; reasoning IQ: kept in ' + (100 * pR.power).toFixed(1) + '% (all scores ' + (100 * pR.powerAll).toFixed(1) + '%), ' + pR.deletedPerDraw.toFixed(1) + ' of 19 deleted per copy. Other experiments: all non-Oak rows ' + res.c2plantNon.all.estimate.toFixed(3) + ' (z ' + res.c2plantNon.all.z.toFixed(2) + '), high-contact rows ' + res.c2plantHigh.high.estimate.toFixed(3) + ' (z ' + res.c2plantHigh.high.z.toFixed(2) + ')',
      verdict: 'For total IQ the control COULD have confirmed the claim (' + (100 * pT.power).toFixed(1) + '% at the claimed size) and on the real list it keeps a ' + tr.advantage.toFixed(1) + '-point advantage; for reasoning IQ the control could NOT have confirmed it (' + (100 * pR.power).toFixed(1) + '%), and the page calls that half of the critique inconclusive; the high-contact experiments could have seen an Oak-sized effect (z ' + res.c2plantHigh.high.z.toFixed(2) + ') and did not',
    },
    null_through_claimant_method: {
      applicable: true,
      what: 'The claimants’ own test (claimantTest, the anchor’s function) run on 10,000 lists of pseudo-bloomers drawn within each of the 17 classrooms, with the real counts, from the 255 children not named: the same children, scores and test, nothing planted',
      result: 'school-wide t >= 2.15 in ' + (100 * res.nul.rateT).toFixed(2) + '% of lists (' + res.nul.hitT + ' of 10,000) where the t table promises ' + (100 * res.nul.nominalT).toFixed(2) + '%, and t >= the listing’s own ' + res.nul.tObs.toFixed(3) + ' in ' + (100 * res.nul.rateObs).toFixed(2) + '% (the t table: ' + (100 * res.nul.nominalObs).toFixed(2) + '%); some grade at one-tailed p <= .002 in ' + (100 * res.nul.rateGrade).toFixed(2) + '% (1.19% for six independent calibrated tests); grades 1 and 2 advantage >= ' + res.nul.adv12.toFixed(2) + ' in ' + res.nul.hit12 + ' of 10,000. Null offset ' + res.nul.meanAdv.toFixed(2) + ' points across the lists, ' + res.nul.offsetExact.toFixed(3) + ' in exact expectation (mean t ' + res.nul.meanT.toFixed(2) + ')',
    },
    verdict: { category: VERDICT.category, as_of: VERDICT.as_of, sources: [...VERDICT.sources], would_change: VERDICT.would_change },
    decided_by: VERDICT.decided_by,
    years_to_decision: VERDICT.years_to_decision,
    choices: CHOICES.map(c => ({ ...c, options: [...c.options], affects: [...c.affects] })),
    headline: X.HEADLINE,
    novelty: NOVELTY,
    ledger,
  };
}
const ASSERTIONS = {
  claim_reproduced: 'anchor:claimantTest-on-listing-reproduces-table-7-1-and-transcription-gates',
  control_computed: 'control:esControl-reproduces-tables-20-to-22-and-metadat-fit',
  control_can_confirm: 'power:claimed-sizes-planted-into-redrawn-real-children-through-esControl',
  rendered_figures_asserted: 'surface:data-fig-spans-tables-head-frontmatter-and-literal-inventory',
  choices_are_live: 'choices:nineteen-live-one-inert-and-well-formed',
  planted_fault_caught: 'fault:corrupted-listing-rows-figures-and-bytes',
  refusal_asserted: 'refuse:covariance-across-forms-empty-groups-contact-cut-and-missing-testing',
  provenance_pinned: 'provenance:sha256-in-data-readme-record',
  verdict_dated: 'verdict:category-date-scope-sources-printed',
};
const group = name => results.some(t => t.group === name) && results.filter(t => t.group === name).every(t => t.pass);
const ledger = {
  claim_reproduced: group('anchor'),
  control_computed: group('control'),
  control_can_confirm: group('power'),
  rendered_figures_asserted: group('surface'),
  choices_are_live: group('choices'),
  planted_fault_caught: group('fault'),
  refusal_asserted: group('refusal'),
  provenance_pinned: group('provenance'),
  verdict_dated: group('verdict') && group('null'),
};
const expected = makeRecord(Object.fromEntries(Object.entries(ledger).map(([k, v]) => [k, { value: v, assertion: ASSERTIONS[k] }])));
if (REGEN) {
  if (results.some(t => !t.pass)) { for (const f of results.filter(t => !t.pass)) console.error('FAIL ' + f.group + ': ' + f.name + '\n  ' + f.error); throw new Error('Refusing to write record.json while assertions fail.'); }
  fs.writeFileSync(recordPath, JSON.stringify(expected, null, 2) + '\n');
}
test('manifest', 'record.json equals the manifest built from this run’s own results', () => {
  assert.ok(fs.existsSync(recordPath), 'record.json missing');
  assert.deepEqual(JSON.parse(fs.readFileSync(recordPath, 'utf8')), expected);
});

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