#!/usr/bin/env node
// verify-the-sum-nobody-knew.mjs: recomputes every number the page shows from the two frozen files,
// checks the shipped page, frontmatter, head tags, JSON-LD and record.json against the recomputation,
// and exits non-zero on any disagreement.
//
//   node research/the-sum-nobody-knew/verify-the-sum-nobody-knew.mjs            # run every assertion
//   node research/the-sum-nobody-knew/verify-the-sum-nobody-knew.mjs --ledger   # print the nine ledger cells
//   node research/the-sum-nobody-knew/verify-the-sum-nobody-knew.mjs --regen    # rewrite record.json and the
//        literal inventory, only if every other assertion passes. It never rewrites a data file.
//
// Two kinds of check are kept apart. The page's own functions are run on the frozen data and on
// doctored copies of it. And the key statistics are recomputed a second time here, by an
// independent exact implementation in BigInt rationals that shares no code with engine.js, so an
// error in the engine cannot be confirmed by the engine.

import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import assert from 'node:assert/strict';
import { spawnSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import * as E from '../../public/strata/the-sum-nobody-knew/engine.js';
import { figures, cellWord, survivorSentence, powerSentence } from '../../public/strata/the-sum-nobody-knew/figures.js';
import { PREDICTIONS, VERDICT, NOVELTY, EXPLANATIONS } from '../../public/strata/the-sum-nobody-knew/readings.js';
import { FILES, SHA256 } from '../../public/strata/the-sum-nobody-knew/data.js';
import * as S from './surface.mjs';

// The site's chrome writers (nearby-layers, way-out, check-placard, site-bar) inject furniture into every shipped
// page after the build. It is gated by the writers' own --check modes; this verifier checks the page's OWN content,
// so it reads the page with exactly those marked blocks and the shared banner script removed (2026-09-23, landing).
const stripChrome = (s) => s.replace(/\s*<!--aw-(nearby|wayout|checkkind):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 html = stripChrome(read('index.html'));
const md = fs.readFileSync(mdPath, 'utf8');
const L = JSON.parse(read(FILES.ledger));
const C = JSON.parse(read(FILES.claimant));
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 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 rel = (a, b, tol, msg) => assert.ok(Number.isFinite(a) && Math.abs(a - b) <= tol * Math.abs(b), (msg || '') + ` ${a} differs from ${b} by more than ${tol} relative`);
const clone = structuredClone;
const EM_DASH = String.fromCharCode(0x2014);
const qnorm = t => t.replace(/[\u2018\u2019]/g, "'").replace(/[\u201c\u201d]/g, '"');

// ------------------------------------------------------------------ independent exact arithmetic
const chooseMemo = new Map();
function choose(n, k) {
  if (k < 0 || k > n) return 0n;
  const key = n + ',' + k;
  if (chooseMemo.has(key)) return chooseMemo.get(key);
  let r = 1n;
  for (let i = 1; i <= k; i++) r = (r * BigInt(n - k + i)) / BigInt(i);
  chooseMemo.set(key, r);
  return r;
}
function ratToFloat(num, den) {
  if (num === 0n) return 0;
  const shift = den.toString(2).length - num.toString(2).length + 64;
  const q = shift >= 0 ? (num << BigInt(shift)) / den : num / (den << BigInt(-shift));
  return Number(q) * Math.pow(2, -shift);
}
// P(X >= k), X ~ Bin(n, a/b): returns [num, den]
function tailGE(k, n, a, b) {
  let num = 0n;
  const A = BigInt(a), B = BigInt(b);
  for (let i = Math.max(k, 0); i <= n; i++) num += choose(n, i) * A ** BigInt(i) * (B - A) ** BigInt(n - i);
  return [num, B ** BigInt(n)];
}
function tailLE(k, n, a, b) {
  let num = 0n;
  const A = BigInt(a), B = BigInt(b);
  for (let i = 0; i <= Math.min(k, n); i++) num += choose(n, i) * A ** BigInt(i) * (B - A) ** BigInt(n - i);
  return [num, B ** BigInt(n)];
}
function kStarX(n, a, b) { // smallest k with P(X >= k) <= 1/20
  for (let k = 0; k <= n + 1; k++) { const [num, den] = tailGE(k, n, a, b); if (20n * num <= den) return k; }
  return n + 1;
}
function mcnemarX(b, c) {
  const m = b + c;
  if (m === 0) return [1n, 1n];
  const [num, den] = tailLE(Math.min(b, c), m, 1, 2);
  const two = 2n * num;
  return two >= den ? [1n, 1n] : [two, den];
}
function fisherLowerX(k1, n1, k2, n2) {
  const K = k1 + k2; let num = 0n;
  for (let x = Math.max(0, K - n2); x <= k1; x++) num += choose(n1, x) * choose(n2, K - x);
  return [num, choose(n1 + n2, K)];
}
function fisherUpperX(k1, n1, k2, n2) {
  const K = k1 + k2; let num = 0n;
  for (let x = k1; x <= Math.min(n1, K); x++) num += choose(n1, x) * choose(n2, K - x);
  return [num, choose(n1 + n2, K)];
}
function lessThanAlpha([num, den]) { return 20n * num < den; }
// The knowledge control, reimplemented: verdict code for kw of n without, kk of n with, chance a/b.
function verdictX(kw, kk, n, a, b) {
  if (kw < kStarX(n, a, b)) return 'none';
  let allSig = true;
  for (let n11 = Math.max(0, kw + kk - n); n11 <= Math.min(kw, kk); n11++) {
    if (!lessThanAlpha(mcnemarX(kk - n11, kw - n11))) allSig = false;
  }
  return allSig ? 'helps' : 'irrelevant';
}
// Exact verdict distribution when each of m recorded failures becomes a success with probability p/q.
function verdictDistX(k0, n, kk, p, q, a, b) {
  const m = n - k0; const P = BigInt(p), Q = BigInt(q);
  const acc = { none: 0n, helps: 0n, irrelevant: 0n };
  for (let j = 0; j <= m; j++) acc[verdictX(k0 + j, kk, n, a, b)] += choose(m, j) * P ** BigInt(j) * (Q - P) ** BigInt(m - j);
  const den = Q ** BigInt(m);
  return Object.fromEntries(Object.entries(acc).map(([k, v]) => [k, ratToFloat(v, den)]));
}

// ------------------------------------------------------------------ fixtures
const F = figures(L, C, PREDICTIONS);
const X = S.texts(F);
const arms = E.arithmeticArms(L);
const P0S = [[0.05, 1, 20], [0.10, 1, 10], [0.20, 1, 5]];
const aClaim = E.aClaim(L);
const fm = (md.match(/^---\n([\s\S]*?)\n---/) || [])[1] || '';
const fmField = k => { const m = fm.match(new RegExp('^' + k + ':\\s*"(.*)"\\s*$', 'm')); return m ? m[1] : null; };
const mdBody = md.slice(md.indexOf('\n---', 4) + 4).trim();
const meta = (attr, name) => { const m = html.match(new RegExp('<meta ' + attr + '="' + name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '" content="([^"]*)"')); return m ? m[1] : null; };
const visible = S.visibleOutsideFigs(html);
const fullVisible = S.decodeEntities(html.slice(html.indexOf('<body')).replace(/<script[\s\S]*?<\/script>/g, ' ').replace(/<style[\s\S]*?<\/style>/g, ' ').replace(/<!--[\s\S]*?-->/g, ' ').replace(/<[^>]+>/g, ' ')).replace(/\s+/g, ' ');
const has = s => qnorm(fullVisible).includes(qnorm(s.replace(/\s+/g, ' ')));

// Compare every data-fig span with a figure map; returns the list of disagreements.
function surfaceDisagreements(h, figs) {
  const out = [];
  for (const d of S.dataFigs(h)) if (!(d.key in figs) || d.inner.trim() !== figs[d.key]) out.push(d.key);
  return out;
}

// ================================================================== anchor: the claim at full strength
test('anchor', 'the claimant transcription holds the printed numbers, and each printed fragment carries them', () => {
  const m = C.records.find(r => r.id === 'minutes-1905');
  const k = C.records.find(r => r.id === 'krall-1912');
  assert.equal(m.page, 470); assert.equal(k.page, 163);
  const t = Object.fromEntries([...m.trials, ...k.trials].map(x => [x.id, x]));
  // The minutes print the first card's numbers only as the horse's taps; the card is given as an example
  // ('z. B.') and is not reported as turned over, so the file must not present taps as the card.
  assert.deepEqual([t['card-1'].operands, t['card-1'].operands_from_taps, t['card-1'].op, t['card-1'].tapped, t['card-1'].tapped_operands], [null, true, '+', 11, [4, 7]]);
  assert.match(t['card-1'].operands_source, /do not say this card was turned over/);
  assert.match(m.example_cards_de, /^z\. B\. 4 und 7; 12 weniger 6$/);
  assert.deepEqual([t.tablets.operands, t.tablets.op, t.tablets.tapped], [[5, 4], '+', 9]);
  assert.deepEqual([t['krall-card-a'].operands, t['krall-card-a'].tapped, t['krall-card-a'].tapped_operands], [[2, 3], 5, [2, 3]]);
  assert.deepEqual([t['krall-card-b'].operands, t['krall-card-b'].op, t['krall-card-b'].tapped, t['krall-card-b'].tapped_operands], [[12, 5], '-', 7, [12, 5]]);
  for (const x of Object.values(t)) {
    for (const v of [x.tapped, ...(x.operands || []), ...(x.tapped_operands || [])]) assert.ok(new RegExp('\\b' + v + '\\b').test(x.printed), x.id + ': ' + v + ' not in its printed words');
  }
  assert.equal(m.described_without_operands.count, 3); assert.match(m.described_without_operands.printed, /drei anderen Zetteln/);
  assert.equal(m.printed_failures, 0); assert.equal(m.repetitions.experiments, 2); assert.equal(m.repetitions.count_printed, null);
  assert.match(m.repetitions.printed, /^Beide Versuche wurden wiederholt und gelangen\.$/);
  assert.equal(m.claim_de, 'dass Hans wirklich lesen, das Gelesene verstehen und richtig rechnen könne');
  assert.match(m.reply_de, /kontroliert werden könne/);
});
test('anchor', 'the page engine reproduces the claimants’ record: every described trial right', () => {
  const a = E.claimantAnchor(C);
  assert.equal(a.agrees, true);
  assert.deepEqual([a.minutes.checkable, a.minutes.correct, a.minutes.independent, a.minutes.operandsChecked, a.minutes.operandsCorrect], [2, 2, 1, 0, 0]);
  assert.deepEqual([a.krall.checkable, a.krall.correct, a.krall.independent, a.krall.operandsChecked, a.krall.operandsCorrect], [2, 2, 2, 2, 2]);
  // no row whose numbers are the horse's own taps is counted as a check of those taps against a card
  for (const row of [...a.minutes.rows, ...a.krall.rows].filter(x => x.checkable)) if (row.fromTaps) assert.equal(row.operandsCorrect, null, row.id);
  assert.equal(a.minutes.rows.find(x => x.id === 'card-1').fromTaps, true);
  assert.deepEqual([a.k, a.n], [5, 5]);
  near(a.lowerBound, Math.pow(0.05, 1 / 5), 1e-9, 'face-value lower bound against the closed form 0.05^(1/5)');
  const r = E.claimantAnchor(C, { repetitions: 'one-each' });
  assert.deepEqual([r.k, r.n], [7, 7]);
  near(r.lowerBound, Math.pow(0.05, 1 / 7), 1e-9);
  for (const row of a.minutes.rows.filter(x => x.checkable)) assert.equal(row.expected, row.op === '+' ? row.operands[0] + row.operands[1] : row.operands[0] - row.operands[1]);
});
test('anchor', 'a corrupted claimant record fails the same anchor', () => {
  const bad = clone(C); bad.records[0].trials[0].tapped = 12;
  const a = E.claimantAnchor(bad);
  assert.equal(a.agrees, false); assert.deepEqual([a.minutes.correct, a.k, a.n], [1, 4, 5]);
  assert.notEqual(a.lowerBound.toFixed(3), F['claim.lb'], 'the corrupted record must move the printed bound');
  const bad2 = clone(C); bad2.records[0].trials[0].tapped_operands = [4, 8];
  assert.equal(E.claimantAnchor(bad2).agrees, false, 'taps that do not add up (4 and 8 against 11) must fail the anchor');
  const bad5 = clone(C); bad5.records[1].trials[0].operands_from_taps = true;
  const a5 = E.claimantAnchor(bad5);
  assert.deepEqual([a5.krall.operandsChecked, a5.krall.independent], [1, 1], 'the from-taps flag is read: a flagged row is no longer counted as checked against its card');
  const bad6 = clone(C); bad6.records[0].trials[0].operands = [5, 5];
  assert.equal(E.claimantAnchor(bad6).agrees, true, 'for a from-taps row the engine uses the taps, never an operand typed beside them');
  const bad3 = clone(C); bad3.records[1].trials[1].tapped = 8;
  assert.equal(E.claimantAnchor(bad3).agrees, false, 'a wrong Krall tap must fail the anchor');
  const bad4 = clone(C); bad4.records[0].printed_failures = 1;
  assert.equal(E.claimantAnchor(bad4).agrees, false, 'a printed failure must fail the anchor');
});
test('anchor', 'the page quotes the claim in the claimants’ words, with the page’s translation labelled', () => {
  const m = C.records[0];
  assert.ok(has(m.claim_de), 'German claim sentence on the page');
  assert.ok(has(m.claim_en_page), 'page translation on the page');
  assert.ok(has('The page’s translation'), 'translation labelled as the page’s');
  assert.ok(has('as recorded in') || has('The society’s minutes record') || has('minutes record the result in reported speech'), 'reported speech named');
  assert.ok(has(m.reply_de.replace('kontroliert', 'kontroliert [sic]')), 'reply quoted with [sic]');
  assert.ok(has(m.reply_context_en_page.replace(/^for, first, /, '')), 'reply context rendered');
});

// ================================================================== control: the deciding control
test('control', 'the ledger holds Pfungst’s printed arithmetic counts, in both editions’ words', () => {
  const s = E.series(L, 'arithmetic');
  assert.deepEqual([s.without.n, s.without.k_printed, s.with.n, s.with.k_printed, s.p1911, s.p1907], [31, 3, 31, 29, 37, '32']);
  assert.match(s.without.printed, /In 31 tests .* 3 of the horse's answers were correct/);
  assert.match(s.with.printed, /31 tests .* 29 of his responses were correct/);
  assert.match(s.without.printed_de, /Von 62 Versuchen fielen auf die 31 unwissentlichen 3 richtige Antworten/);
  assert.match(s.with.printed_de, /31 wissentlichen dagegen 29/);
  assert.ok(has(s.design), 'the p. 37 design quoted verbatim');
  assert.ok(has(s.without.printed + ', ' + s.with.printed), 'the p. 37 result quoted verbatim');
  const seq = L.numeral_sequence.rows;
  const pairs = []; for (let i = 0; i < seq.length; i += 2) pairs.push([seq[i], seq[i + 1]]);
  const prose = 'exposed ' + seq[0][1] + ', tapped ' + seq[0][2] + '; then ' + seq.slice(1).map(r => r[1] + ' and ' + r[2]).join('; ');
  assert.ok(has(prose), 'the p. 35 rows printed as transcribed');
  const lb = L.blinders.large;
  assert.ok(has('printed ' + lb.not_seen.pct_printed + '%, which Pfungst says was only two, ' + lb.seen.pct_printed + '% and ' + lb.undecided.pct_printed + '%'), 'blinder percentages as transcribed');
  assert.ok(has('With blinders 15 by 15 cm') && /15 x 15|15 by 15/.test(lb.label), 'blinder size as transcribed');
});
test('control', 'k* and the verdict at every chance rate, against an independent exact implementation', () => {
  const want = { 0.05: 5, 0.1: 7, 0.2: 11 };
  for (const [p0, a, b] of P0S) {
    const r = E.knowledgeControl(arms.without, arms.with, { p0 });
    assert.equal(r.kStar, kStarX(31, a, b), 'kStar at ' + p0);
    assert.equal(r.kStar, want[p0]);
    assert.equal(r.verdictCode, 'none');
    assert.equal(r.verdictCode, verdictX(3, 29, 31, a, b));
  }
});
test('control', 'the pairing bound: three consistent pairings, exact McNemar p recomputed independently', () => {
  const r = E.knowledgeControl(arms.without, arms.with);
  assert.deepEqual(r.pairings.map(p => [p.n11, p.n10, p.n01, p.n00]), [[1, 28, 2, 0], [2, 27, 1, 1], [3, 26, 0, 2]]);
  for (const p of r.pairings) rel(p.p, ratToFloat(...mcnemarX(p.n10, p.n01)), 1e-9, 'McNemar n11=' + p.n11);
  rel(r.pLo, 2.9802322387695312e-8, 1e-9); rel(r.pHi, 8.67992639541626e-7, 1e-9);
  assert.equal(r.knowledgeMatters, true);
});
test('control', 'guessing threshold: 3 of 31 is consistent with guessing only above 0.0269', () => {
  near(E.guessThreshold(3, 31), 0.0269001196911, 1e-9);
  assert.ok(!lessThanAlpha(tailGE(3, 31, 2691, 100000)) && lessThanAlpha(tailGE(3, 31, 2689, 100000)), 'the threshold brackets independently');
});
test('control', 'every printed percentage recovers a unique count, and the laboratory 73% does not', () => {
  const cases = [[49, 8, [4]], [42, 98, [41]], [14, 100, [14]], [56, 89, [50]], [11, 18, [2]], [35, 6, [2]], [25, 24, [6]], [44, 82, [36]], [39, 72, [28]], [20, 95, [19]]];
  for (const [n, pct, want] of cases) assert.deepEqual(E.recoverCount(n, pct), want, pct + '% of ' + n);
  assert.deepEqual(E.recoverCount(350, 73), [254, 255, 256, 257]);
  const lb = L.blinders.large.not_seen;
  assert.equal(E.arm(lb).consistent, true, 'the printed 6% and the printed two agree');
});
test('control', 'Pfungst’s p. 40 summary recomputed: 90 to 100% with knowledge, at most 10% for paired series', () => {
  const s = E.summaryCheck(L);
  assert.deepEqual(s.withRates.map(r => [r.id, r.k, r.n]), [['numerals', 41, 42], ['words', 14, 14], ['arithmetic', 29, 31], ['abacus', 8, 8]]);
  assert.equal(s.withHolds, true); assert.equal(s.pairedHolds, true);
  assert.deepEqual(s.exceed, ['memory', 'calendar']);
  near(s.withMin, 100 * 29 / 31, 1e-12); near(s.pairedWithoutMax, 100 * 3 / 31, 1e-12);
  const seq = E.numeralSequence(L);
  assert.deepEqual([seq.without.k, seq.without.n, seq.with.k, seq.with.n], [0, 5, 5, 5]);
});
test('control', 'the sight control: Fisher p for every blinder counting, recomputed independently', () => {
  const combos = [['large', 'excluded', 2, 35, 50, 56], ['large', 'as-not-seen', 4, 46, 50, 56], ['small', 'excluded', 6, 25, 36, 44], ['small', 'as-not-seen', 34, 64, 36, 44]];
  for (const [bl, und, k1, n1, k2, n2] of combos) {
    const s = E.sightArms(L, { blinders: bl, undecided: und });
    assert.deepEqual([s.notSeen.k, s.notSeen.n, s.seen.k, s.seen.n], [k1, n1, k2, n2]);
    rel(E.sightControl(s.notSeen, s.seen).p, ratToFloat(...fisherLowerX(k1, n1, k2, n2)), 1e-9, bl + ' ' + und);
  }
});
test('control', 'the decision took 88 days, counted independently', () => {
  assert.equal(E.decisionDays(L), 88);
  // an independent count from the two dates' own fields and a month-length table, no Date arithmetic
  const ymd = id => L.timeline.find(t => t.id === id).date.split('-').map(Number);
  const [y1, m1, d1] = ymd('commission'), [y2, m2, d2] = ymd('stumpf-report');
  const leap = y => (y % 4 === 0 && y % 100 !== 0) || y % 400 === 0;
  const len = (y, m) => [31, leap(y) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][m - 1];
  assert.equal(y1, y2);
  let days = len(y1, m1) - d1;
  for (let m = m1 + 1; m < m2; m++) days += len(y1, m);
  days += d2;
  assert.equal(E.decisionDays(L), days);
});

// ================================================================== power: the control on the control
test('power', 'the claimed size is read from the frozen arms, and moves when they move', () => {
  near(aClaim, 26 / 28, 1e-15);
  const moved = clone(L); E.series(moved, 'arithmetic').with.k_printed = 30;
  near(E.aClaim(moved), 27 / 28, 1e-15, 'a_claim must follow the ledger');
});
test('power', 'planted at the claimed size into copies of the 31 rows, the unmodified control sees the ability', () => {
  const r = E.powerByInjection(L, { a: aClaim });
  assert.equal(r.usedControl, 'knowledgeControl');
  assert.equal(r.a, aClaim);
  assert.equal(r.counts.none + r.counts.helps + r.counts.irrelevant, r.copies);
  assert.ok(r.fracSeen >= E.POWER_LINE, 'power ' + r.fracSeen);
  near(r.meanK, 3 + 28 * aClaim, 0.1, 'the plant happened at the claimed size');
  assert.deepEqual(r.example.rows.slice(0, 3), [1, 1, 1], 'the recorded successes stay');
  assert.equal(r.example.planted.a, aClaim);
  for (const [p0] of P0S) assert.ok(E.powerByInjection(L, { a: aClaim, p0, copies: 2000 }).fracSeen >= E.POWER_LINE, 'at p0 ' + p0);
});
test('power', 'the plant runs through the page’s own control function and nothing is appended to its result', () => {
  const calls = [];
  const spy = (w, k, o) => { calls.push([w, k]); return E.knowledgeControl(w, k, o); };
  const viaSpy = E.powerByInjection(L, { a: aClaim, copies: 3000, control: spy });
  const direct = E.powerByInjection(L, { a: aClaim, copies: 3000 });
  assert.equal(calls.length, 3000, 'one control call per doctored copy');
  assert.deepEqual(viaSpy.counts, direct.counts, 'the spy and the page path agree exactly');
  for (const [w, k] of calls) { assert.deepEqual(k, arms.with, 'the known-sum arm is passed unmodified'); assert.equal(w.n, 31); assert.ok(w.k >= 3); }
  const sentinel = E.powerByInjection(L, { a: aClaim, copies: 500, control: () => ({ verdictCode: 'none' }) });
  assert.equal(sentinel.counts.none, 500, 'the tally comes only from the control’s own verdicts');
  assert.ok(Object.isFrozen(E.knowledgeControl(arms.without, arms.with)), 'a verdict cannot be appended to');
  const rows = E.rowsFromArm(arms.without);
  E.plantAbility(rows, 1, E.mulberry32(1));
  assert.equal(rows.rows.filter(v => v === 1).length, 3, 'the plant never touches the original rows');
});
test('power', 'the plant at zero returns the real verdict, so the control is not a constant', () => {
  const r = E.powerByInjection(L, { a: 0, copies: 2000 });
  assert.equal(r.counts.none, 2000);
  assert.equal(E.exactVerdictDist(L, { a: 0 }).none, 1);
});
test('power', 'exact verdict probabilities agree with an independent exact calculation', () => {
  for (const [p0, a, b] of P0S) {
    const e = E.exactVerdictDist(L, { a: aClaim, p0 });
    const x = verdictDistX(3, 31, 29, 13, 14, a, b);
    near(e.none, x.none, 1e-12); near(e.helps, x.helps, 1e-12); near(e.irrelevant, x.irrelevant, 1e-9);
    assert.ok(e.seen >= E.POWER_LINE);
  }
  near(E.exactVerdictDist(L, { a: aClaim }).irrelevant, 0.9999863629735987, 1e-9);
  const mid = E.exactVerdictDist(L, { a: 0.188, p0: 0.1 });
  const mc = E.powerByInjection(L, { a: 0.188, p0: 0.1 });
  near(mc.fracSeen, mid.seen, 4 * Math.sqrt(mid.seen * (1 - mid.seen) / mc.copies), 'Monte Carlo against exact at a mid-power point');
  const want80 = { 0.05: 0.1031977636389691, 0.1: 0.1882035247679214, 0.2: 0.3440173927953050 };
  for (const [p0] of P0S) near(E.abilityForPower(L, p0), want80[p0], 1e-6, 'a for 80% power at ' + p0);
});
test('power', 'the supporters’ weakest face-value rate would also have been seen', () => {
  const lb = E.claimantAnchor(C).lowerBound;
  const a = E.abilityForRate(3, 31, lb);
  near((3 + 28 * a) / 31, lb, 1e-12);
  assert.ok(E.exactVerdictDist(L, { a }).seen > 0.9999);
});
test('power', 'the sight control, planted at the seen rate into the unseen rows, reads no difference', () => {
  const sp = E.sightPower(L, {});
  near(sp.a, 39 / 44, 1e-15);
  assert.equal(sp.usedControl, 'sightControl');
  let exact = 0n; const m = 33;
  for (let j = 0; j <= m; j++) {
    if (!lessThanAlpha(fisherLowerX(2 + j, 35, 50, 56))) exact += choose(m, j) * 39n ** BigInt(j) * 5n ** BigInt(m - j);
  }
  near(sp.exact, ratToFloat(exact, 44n ** 33n), 1e-9, 'sight power, independently');
  assert.ok(sp.exact > 0.99 && sp.sameFrac > 0.99);
});
test('power', 'the power verdict is computed, can come out INCONCLUSIVE, and the page prints it and its line', () => {
  const v = E.powerVerdict(L);
  assert.equal(v.a, aClaim, 'the verdict plants at the claimed size read from the ledger');
  assert.equal(v.line, E.POWER_LINE); assert.equal(E.POWER_LINE, 0.95);
  for (const [p0, a, b] of P0S) near(v.seenBy[p0], 1 - verdictDistX(3, 31, 29, 13, 14, a, b).none, 1e-12, 'seen at ' + p0 + ', independently');
  assert.equal(v.code, 'could');
  assert.equal(F['pow.verdictSentence'], powerSentence(v));
  assert.equal(F['pow.line'], '0.95');
  // a doctored ledger whose known-sum arm is barely above the unknown one: the claimed size is small,
  // the control cannot see it, and the same function says so
  const weak = clone(L); E.series(weak, 'arithmetic').with.k_printed = 5;
  const wv = E.powerVerdict(weak);
  assert.equal(wv.code, 'inconclusive'); assert.ok(wv.minSeen < E.POWER_LINE);
  assert.notEqual(figures(weak, C, PREDICTIONS)['pow.verdictSentence'], F['pow.verdictSentence'], 'the printed sentence follows the verdict');
  assert.ok(has('Grade A, with a stated limit'));
  assert.ok(has('It cannot plant into the addends'));
  assert.ok(has('below that line the sentence would read that the control could not have confirmed the claim'));
});

// ================================================================== the second layer
test('matrix', 'which control contradicts which reply, recomputed', () => {
  const m = E.matrix(L, PREDICTIONS);
  assert.deepEqual(m.contradictedBy, { H: ['K', 'S', 'P'], W1: ['S', 'P'], W2: ['P'], C: [] });
  assert.deepEqual(m.survivors, ['C']);
  assert.deepEqual(E.matrix(L, PREDICTIONS, { edition: '1911' }).survivors, ['W2', 'C'], 'without the German count the posture column cannot decide');
  assert.deepEqual(E.matrix(L, PREDICTIONS, { blinders: 'small', undecided: 'as-not-seen' }).survivors, [], 'von Osten’s counting turns the sight column');
  assert.deepEqual(E.matrix(L, PREDICTIONS, { controls: ['K'] }).survivors, ['W1', 'W2', 'C']);
  assert.deepEqual(E.matrix(L, PREDICTIONS, { controls: ['K', 'S'] }).survivors, ['W2', 'C']);
  const ci26 = E.exactInterval(26, 26);
  near(ci26.lo, Math.pow(0.025, 1 / 26), 1e-9, 'the 26 of 26 interval against its closed form');
  const ci3 = E.exactInterval(3, 31);
  assert.ok(ratToFloat(...tailLE(3, 31, 2576, 10000)) < 0.025 && ratToFloat(...tailLE(3, 31, 2574, 10000)) > 0.025, 'upper end of 3 of 31 independently');
  assert.ok(ci3.hi > 0.25 && ci3.hi < 0.5, 'the knowledge column contradicts H through the whole interval');
});
test('matrix', 'the stated interval rule, not a point-rate rule, decides a cell', () => {
  // 10 of 31 is 32%, below the 50% line, but its exact interval reaches above 50%: not a contradiction
  const o10 = E.classify(10, 31);
  assert.ok(o10.rate < E.CORRECT_LINE && o10.ci.hi > E.CORRECT_LINE);
  assert.equal(E.contradicts('correct', o10), false);
  // 12 of 31 is 38.7%, above the 25% line, but its interval reaches below 25%: not a contradiction of 'fails'
  const o12 = E.classify(12, 31);
  assert.ok(o12.rate > E.FAIL_LINE && o12.ci.lo < E.FAIL_LINE);
  assert.equal(E.contradicts('fails', o12), false);
  // and cases where the whole interval is on the wrong side are contradictions
  assert.equal(E.contradicts('correct', E.classify(3, 31)), true);
  assert.equal(E.contradicts('fails', E.classify(26, 26)), true);
  assert.equal(E.contradicts('either', E.classify(0, 31)), false);
});
test('matrix', 'no control included tests nothing; the one setting that leaves both replies standing is named', () => {
  const none = E.matrix(L, PREDICTIONS, { controls: [] });
  assert.equal(none.tested, false);
  assert.equal(survivorSentence(none, EXPLANATIONS), 'No control is included, so nothing is tested.');
  assert.equal(E.matrix(L, PREDICTIONS).tested, true);
  const vo11 = E.matrix(L, PREDICTIONS, { blinders: 'small', undecided: 'as-not-seen', edition: '1911' });
  assert.deepEqual(vo11.survivors, ['W1', 'W2']);
  assert.deepEqual(vo11.undecidedAsUnseen, { n: 39, p1911: '44 to 45' });
  assert.match(survivorSentence(vo11, EXPLANATIONS), /This counting scores 39 tests in which the horse may have seen the questioner as unseen \(Pfungst, 1911, pp\. 44 to 45\)\.$/);
  assert.equal(F['mx.vo1911Survivors'], 'W1 and W2');
  assert.ok(has('the supporters’ two replies'), 'the page names that setting in prose');
  assert.equal(F['mx.status'], survivorSentence(E.matrix(L, PREDICTIONS), EXPLANATIONS));
  assert.ok(!/hans calculates/.test(survivorSentence(E.matrix(L, PREDICTIONS, { controls: ['S'] }), EXPLANATIONS)), 'the proper name keeps its capital');
});
test('matrix', 'the held bend is counted only in the 1907 German, as printed', () => {
  const h = L.posture.held_bend;
  assert.equal(h.n, 26); assert.equal(h.k_1907, 26); assert.equal(h.k_1911, null); assert.equal(h.k_1907_word, 'alle');
  assert.match(h.printed_de, /26 derartige Versuche hatten alle den nämlichen Erfolg\./);
  assert.match(h.printed, /Twenty-six such tests gave similar results\./);
  assert.ok(has('26 derartige Versuche hatten alle den nämlichen Erfolg'));
  assert.ok(has(h.printed.split(' Twenty-six')[0]), 'the p. 57 examples quoted verbatim');
  assert.deepEqual(h.examples.map(e => [e.answer, e.bow_ends, e.tapped]), [[13, 20, 20], [7, 14, 14]]);
});

// ================================================================== the claimants' method on nothing
test('null', 'a responder who could not know, and a factor that did nothing, through the page’s functions', () => {
  const lab = E.labNull(L, 1 / 4);
  assert.deepEqual(lab.kRange, [254, 257]);
  rel(lab.tailAtMin, ratToFloat(...tailGE(254, 350, 1, 4)), 1e-9);
  rel(E.labNull(L, 1 / 6).tailAtMin, ratToFloat(...tailGE(254, 350, 1, 6)), 1e-9);
  const au = E.auditoryDemo(L);
  assert.deepEqual([au.blocked.k, au.blocked.n, au.unblocked.k, au.unblocked.n], [1, 20, 28, 28]);
  rel(au.p, ratToFloat(...fisherUpperX(28, 28, 1, 20)), 1e-9);
  near(au.diff, 0.95, 1e-12);
  assert.ok(au.diff > au.knowledgeDiff, 'the claimant’s own contrast exceeds the knowledge effect');
  // counted the supporters' way: the same face-value bound the anchor gives 5 of 5, recomputed independently
  const [lb0, lb1] = lab.lbRange;
  near(lb0, E.exactLowerBound(254, 350), 0); near(lb1, E.exactLowerBound(257, 350), 0);
  for (const [k, lb] of [[254, lb0], [257, lb1]]) {
    const lo = Math.floor(lb * 10000), hi = lo + 1;
    assert.ok(lessThanAlpha(tailGE(k, 350, lo - 1, 10000)) && !lessThanAlpha(tailGE(k, 350, hi, 10000)), 'face-value bound for ' + k + ' of 350, independently');
  }
  assert.ok(lb0 > E.claimantAnchor(C).lowerBound, 'the mind-reading null earns a higher face-value bound than the supporters’ record');
  assert.equal(F['lab.lb'], lb0.toFixed(3) + ' to ' + lb1.toFixed(3));
  const two = E.twoRecords(E.claimantAnchor(C), L);
  rel(two.p, ratToFloat(...fisherUpperX(5, 5, 3, 31)), 1e-9);
  rel(E.twoRecords(E.claimantAnchor(C, { repetitions: 'one-each' }), L).p, ratToFloat(...fisherUpperX(7, 7, 3, 31)), 1e-9);
});

// ================================================================== surface: what the reader sees
test('surface', 'every figure printed in the page equals the recomputation', () => {
  const figs = S.dataFigs(html);
  assert.ok(figs.length >= 120, 'figure spans: ' + figs.length);
  const bad = surfaceDisagreements(html, F);
  assert.deepEqual(bad, []);
  const used = new Set(figs.map(f => f.key));
  for (const k of ['claim.kn', 'claim.lb', 'claim.lbRep', 'k.without', 'k.with', 'k.pLo', 'k.pHi', 'k.guess', 'pow.aClaim', 'pow.mcSeen', 'pow.seenExact', 'pow.a80', 'sight.p', 'sight.exact', 'post.held', 'two.p', 'lab.range', 'lab.tail', 'aud.p', 'days', 'mx.survivors', 'mx.W2by', 'mx.survivors1911', 'mx.status', 'mx.vo1911Survivors', 'pow.verdictSentence', 'pow.line', 'lab.lb', 'sight.seenPct', 'claim.independent'])
    assert.ok(used.has(k), 'the page prints ' + k);
});
test('surface', 'dek, headline, title, meta description, OG, Twitter and JSON-LD match the recomputed text', () => {
  const dek = (html.match(/<p class="dek" data-dek>([\s\S]*?)<\/p>/) || [])[1];
  assert.equal(dek, S.escText(X.DEK));
  assert.equal((html.match(/<p class="lede" id="headline" data-headline>([\s\S]*?)<\/p>/) || [])[1], S.escText(X.HEADLINE));
  assert.equal((html.match(/<title>([\s\S]*?)<\/title>/) || [])[1], S.escText(X.SEO));
  assert.equal(meta('name', 'description'), S.escAttr(X.DEK));
  assert.equal(meta('property', 'og:description'), S.escAttr(X.OG));
  assert.equal(meta('name', 'twitter:description'), S.escAttr(X.TW));
  assert.equal(meta('property', 'og:image'), S.OG_IMAGE); assert.equal(meta('name', 'twitter:image'), S.OG_IMAGE);
  assert.equal(meta('property', 'og:url'), S.URL);
  assert.equal(meta('property', 'og:image:alt'), S.escAttr(X.OG_ALT));
  assert.equal(meta('property', 'og:title'), 'The Sum Nobody Knew &middot; Artificial Wasteland');
  assert.equal(meta('name', 'twitter:title'), 'The Sum Nobody Knew &middot; Artificial Wasteland');
  assert.equal((html.match(/id="aSlider"[^>]*value="([^"]+)"/) || [])[1], F['pow.aClaim'], 'slider starts at the claimed size');
  assert.equal((html.match(/id="aNumber"[^>]*value="([^"]+)"/) || [])[1], F['pow.aClaim']);
  assert.equal((html.match(/id="pwSeed" value="([^"]+)"/) || [])[1], F['pow.seed']);
  assert.match(html, /<link rel="canonical" href="https:\/\/artwaste\.land\/strata\/the-sum-nobody-knew\/" \/>/);
  const scripts = [...html.matchAll(/<script type="application\/ld\+json">([\s\S]*?)<\/script>/g)];
  assert.equal(scripts.length, 1);
  const ld = JSON.parse(scripts[0][1]);
  assert.equal(ld['@type'], 'Article'); assert.equal(ld.name, X.SEO); assert.equal(ld.headline, S.TITLE); assert.equal(ld.description, X.DEK);
  assert.equal(ld.url, S.URL); assert.equal(ld.image, S.OG_IMAGE); assert.match(ld.datePublished, /^\d{4}-\d{2}-\d{2}$/);
});
test('surface', 'frontmatter: dek, plain, seoTitle and body match the recomputed text; placard rules hold', () => {
  assert.equal(fmField('title'), S.TITLE);
  assert.equal(fmField('dek'), X.DEK); assert.equal(fmField('seoTitle'), X.SEO); assert.equal(fmField('plain'), X.PLAIN);
  assert.equal(fmField('seam'), 'mind'); assert.equal(fmField('href'), '/strata/' + S.SLUG + '/');
  assert.equal(mdBody, X.BODY.join('\n\n'));
  const plain = fmField('plain');
  assert.ok(plain.length >= 90 && plain.length <= 420, 'plain length ' + plain.length);
  assert.ok(!plain.includes('"'));
  assert.ok((plain.match(/[.!?](\s|$)/g) || []).length <= 3, 'at most three sentences');
  const aw = html.match(/<meta name="aw-plain" content="([^"]*)"/);
  if (aw) assert.equal(S.decodeEntities(aw[1]), X.PLAIN, 'an injected placard must match the frontmatter');
  const relBlock = (fm.match(/^relates:\n([\s\S]*?)\ndraft:/m) || [])[1];
  assert.equal(relBlock, S.RELATES.map(([to, note]) => '  - to: ' + to + '\n    note: "' + note + '"').join('\n'), 'relates notes exactly as written in surface.mjs');
  const rel = [...fm.matchAll(/^\s+- to: (\S+)$/gm)].map(m => m[1]);
  assert.ok(rel.length >= 3 && rel.length <= 5);
  for (const r of rel) assert.ok(fs.existsSync(path.join(root, 'src/content/strata', r + '.md')), 'relates target exists: ' + r);
});
test('surface', 'every other number a reader can see matches the inventory, in order', () => {
  const inv = path.join(here, 'surface-literals.json');
  const now = S.literalNumbers(html);
  if (REGEN && results.every(r => r.pass)) fs.writeFileSync(inv, JSON.stringify(now, null, 0) + '\n');
  assert.ok(fs.existsSync(inv), 'surface-literals.json missing: run with --regen once every other assertion passes');
  assert.deepEqual(now, JSON.parse(fs.readFileSync(inv, 'utf8')));
});
test('surface', 'every quotation of the frozen record appears as transcribed', () => {
  const s = E.series(L, 'arithmetic');
  assert.ok(has(s.without.printed_de + ', ' + s.with.printed_de), 'the German result sentence');
  assert.ok(has(s.judgement.replace(/^Since /, '').replace(/, the results.*$/, '')), 'Pfungst’s judgement');
  assert.ok(has(L.blinders.small.note.match(/'([^']+)'/)[1]), 'the p. 45 conclusion');
  assert.ok(has(L.posture.two_thinkers.printed.split('. ').pop().replace(/\.$/, '')));
  assert.ok(has(L.auditory_demo.pfungst_repeat.match(/always found some correct responses/)[0]));
  assert.ok(has(L.lab_null.printed));
  assert.ok(has(L.others_knowing.printed.match(/twenty-one problems/)[0]) || has('2 of 21'));
  const k = C.records[1];
  assert.ok(has(k.described_without_operands.printed.match(/die mit wenigen Ausnahmen gelangen/)[0]));
  assert.ok(has(EXPLANATIONS.find(e => e.id === 'W1').quote), 'von Osten’s reply, p. 258');
  assert.ok(has(EXPLANATIONS.find(e => e.id === 'W2').quote), 'Krall’s reply, p. 162');
  // quotations added after the fact audit, each read in the Gutenberg text of the 1911 edition
  for (const q of ['one step beyond that which it had proposed to itself', 'that unintentional signs of the kind which are at present familiar, are likewise excluded',
    'to replace his hypothesis of independent conceptual thinking by one of some kind of suggestion', 'embraced it without wavering',
    'an example of the course which the series tended to take', 'a large number of successful tests', 'seemed also to be efficacious', 'the notice even of practised observers',
    'can now call forth at will all the various reactions of the horse by making the proper kind of voluntary movements, without asking the relevant question'])
    assert.ok(has(q), 'quoted: ' + q);
  assert.ok(has('4 und 7&ldquo; is among the example cards'.replace('&ldquo;', '“')) && has('without saying that this card was turned over'), 'the first card is not presented as read from the card');
  assert.ok(has('the lower end of its exact two-sided 95% interval being'), 'the 26 of 26 bound is named for the convention it uses');
  assert.ok(has('Three further printed series point the same way') && !has('Two further printed series'));
  assert.ok(has('Frontiers in Artificial Intelligence 8: 1692454, 2026') && read('NOTICE.txt').includes('published 9 January 2026'), 'the citation year as the publisher prints it');
  assert.ok(!has('Every counted series in chapter II') && !has('the first ten of one numeral series'), 'no over-broad scope sentence');
  assert.ok(has('Empty: the failures the record kept.'), 'the tally legend matches the drawing');
  assert.ok(!/only one control, a questioner bowing past the answer, separates/.test(X.DEK) && /Of the three controls the page sets against/.test(X.DEK), 'the dek scopes the separation to the page’s three controls');
});
test('surface', 'house rules: no em dash anywhere, no forbidden words, no third-party requests, no shell at the reader', () => {
  const files = fs.readdirSync(dir).filter(f => fs.statSync(path.join(dir, f)).isFile());
  for (const f of files) assert.ok(!read(f).includes(EM_DASH), 'em dash in ' + f);
  for (const f of fs.readdirSync(here).filter(f => fs.statSync(path.join(here, f)).isFile())) assert.ok(!fs.readFileSync(path.join(here, f), 'utf8').includes(EM_DASH), 'em dash in research/' + f);
  assert.ok(!md.includes(EM_DASH), 'em dash in the frontmatter');
  const text = fullVisible.toLowerCase() + ' ' + md.toLowerCase();
  for (const w of ['fraud', 'hoax', 'fabricat', 'misconduct', 'debunk', 'stupid', 'dumb', 'unintelligent', 'gullib', 'credulity', 'charlatan', 'scam', 'trick', 'facial', 'owner’s face', 'his owner'])
    assert.ok(!text.includes(w), 'forbidden word: ' + w);
  assert.ok(!/github\.com\/[^"]*Artificial-Wasteland/i.test(html), 'no private repository link');
  assert.ok(!/\b(node|npm|npx|python3?) [\w./-]+/.test(fullVisible), 'no shell command at the reader');
  for (const m of html.matchAll(/<(?:script|img|iframe|audio|video|source)\b[^>]*\ssrc="([^"]+)"/g)) assert.ok(!/^(https?:)?\/\//.test(m[1]), 'external resource ' + m[1]);
  for (const m of html.matchAll(/<link\b([^>]*)>/g)) {
    const relv = (m[1].match(/\srel="([^"]+)"/) || [])[1] || '';
    const href = (m[1].match(/\shref="([^"]+)"/) || [])[1] || '';
    if (/stylesheet|preload|modulepreload|icon|manifest|prefetch/.test(relv)) assert.ok(!/^(https?:)?\/\//.test(href), 'external resource ' + href);
  }
  assert.ok(!/@import\s+url\(\s*['"]?https?:/.test(html) && !/url\(\s*['"]?https?:/.test(html.slice(html.indexOf('<style'), html.indexOf('</style>'))), 'no external CSS resources');
  for (const f of files.filter(f => f.endsWith('.js'))) {
    const src = read(f);
    assert.ok(!/(fetch|import)\s*\(\s*['"`]https?:/.test(src) && !/from\s+['"]https?:/.test(src) && !/XMLHttpRequest|WebSocket|sendBeacon|EventSource/.test(src), 'third-party request in ' + f);
    // any absolute URL at all in a script must be the SVG namespace, which is a name, not a request
    for (const u of src.match(/(?:https?:)?\/\/[a-z0-9.-]+\.[a-z]{2,}[^\s'"`)]*/gi) || []) assert.equal(u, 'http://www.w3.org/2000/svg', 'absolute URL in ' + f + ': ' + u);
  }
});
test('surface', 'structure: closing tags, one inline script (the JSON-LD), modules parse, accessibility basics', () => {
  assert.match(html.trimEnd(), /<script type="module" src="page\.js"><\/script>\s*<\/body>\s*<\/html>$/);
  const inline = [...html.matchAll(/<script(?![^>]*\ssrc=)([^>]*)>([\s\S]*?)<\/script>/g)];
  assert.equal(inline.length, 1); assert.match(inline[0][1], /application\/ld\+json/);
  for (const f of fs.readdirSync(dir).filter(f => f.endsWith('.js'))) {
    const r = spawnSync(process.execPath, ['--check', path.join(dir, f)], { encoding: 'utf8' });
    assert.equal(r.status, 0, f + ': ' + r.stderr);
  }
  assert.match(html, /prefers-reduced-motion/); assert.match(html, /:focus-visible/);
  assert.ok((html.match(/role="status"/g) || []).length >= 10, 'live readouts');
  assert.ok(!/<span[^>]*(onclick|role="button"|tabindex)/.test(html), 'no clickable span');
  for (const m of html.matchAll(/<button\b([^>]*)>/g)) assert.match(m[1], /type="button"/);
  for (const m of html.matchAll(/<input\b([^>]*)>/g)) {
    const attrs = m[1]; const id = (attrs.match(/\sid="([^"]+)"/) || [])[1];
    const wrapped = /type="radio"/.test(attrs);
    assert.ok(wrapped || (id && html.includes('for="' + id + '"')) || /aria-label=/.test(attrs), 'unlabelled input ' + attrs);
  }
  for (const m of html.matchAll(/<table\b/g)) {
    const before = html.slice(Math.max(0, m.index - 120), m.index);
    assert.match(before, /<div class="scroll">\s*$/, 'every table sits in a horizontal scroller');
  }
  assert.match(html, /\.grid2 > \*\{min-width:0\}/);
  assert.match(html, /\.scroll\{overflow-x:auto/);
});

// ================================================================== choices: each changes an output, or is inert
const CHOICES = [
  { id: 'p0', label: 'Chance model: how often a horse that cannot add hits the sum by luck', options: [0.05, 0.1, 0.2], default: 0.1, affects: ['k* (the count that shows ability)', 'ability seen with 80% power'], inert: false },
  { id: 'repetitions', label: 'Count the minuted repetitions', options: ['described', 'one-each'], default: 'described', affects: ['claimants’ face-value lower bound', 'two-records Fisher p'], inert: false },
  { id: 'undecided', label: 'Undecided blinder tests', options: ['excluded', 'as-not-seen'], default: 'excluded', affects: ['unseen arm', 'sight-test p', 'second-layer matrix'], inert: false },
  { id: 'blinders', label: 'Blinder set', options: ['large', 'small'], default: 'large', affects: ['unseen and seen arms', 'sight-test p'], inert: false },
  { id: 'a', label: 'Planted ability', options: [0, Number(E.abilityForRate(3, 31, E.claimantAnchor(C).lowerBound).toFixed(3)), Number(aClaim.toFixed(3))], default: Number(aClaim.toFixed(3)), affects: ['doctored verdict counts', 'exact power'], inert: false, note: 'a slider from 0 to 1; the options are the three marked values the page offers as buttons: no ability, the supporters’ weakest face-value rate, and the claimed size' },
  { id: 'edition', label: 'Whose words for the 26 held-bend tests', options: ['1907', '1911'], default: '1907', affects: ['posture column of the matrix', 'explanations left standing'], inert: false },
  { id: 'order', label: 'Row display order', options: ['recorded', 'shuffled'], default: 'recorded', affects: [], inert: true, reason: 'the record gives no order and every control uses counts only' },
];
test('choices', 'the chance model moves k* and the 80% ability, and leaves the verdict', () => {
  const ks = [0.05, 0.1, 0.2].map(p0 => E.knowledgeControl(arms.without, arms.with, { p0 }).kStar);
  assert.deepEqual(ks, [5, 7, 11]);
  const a80 = [0.05, 0.1, 0.2].map(p0 => E.abilityForPower(L, p0));
  assert.ok(a80[0] < a80[1] && a80[1] < a80[2]);
});
test('choices', 'counting the repetitions moves the lower bound and the two-records p', () => {
  const d = E.claimantAnchor(C), r = E.claimantAnchor(C, { repetitions: 'one-each' });
  assert.notEqual(d.lowerBound.toFixed(3), r.lowerBound.toFixed(3));
  assert.ok(E.twoRecords(r, L).p < E.twoRecords(d, L).p / 10);
});
test('choices', 'the undecided counting and the blinder set move the unseen arm, the p and the matrix', () => {
  const base = E.sightArms(L, {});
  const und = E.sightArms(L, { undecided: 'as-not-seen' });
  const small = E.sightArms(L, { blinders: 'small' });
  assert.notDeepEqual([base.notSeen.k, base.notSeen.n], [und.notSeen.k, und.notSeen.n]);
  assert.notDeepEqual([base.notSeen.k, base.notSeen.n], [small.notSeen.k, small.notSeen.n]);
  assert.notEqual(E.sightControl(base.notSeen, base.seen).p, E.sightControl(small.notSeen, small.seen).p);
  assert.notDeepEqual(E.matrix(L, PREDICTIONS).survivors, E.matrix(L, PREDICTIONS, { blinders: 'small', undecided: 'as-not-seen' }).survivors);
});
test('choices', 'every choice is well formed for the wave’s gate, 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 && c.default !== undefined && Array.isArray(c.affects) && typeof c.inert === 'boolean', 'choice ' + c.id + ' shape');
    assert.ok(c.options.includes(c.default), 'default of ' + c.id + ' among its options');
    assert.equal(new Set(c.options.map(String)).size, c.options.length, 'options of ' + c.id + ' distinct');
    if (c.inert) assert.ok(c.reason, 'an inert choice says why');
  }
});
test('choices', 'the planted ability moves the doctored verdicts, at each of its marked values', () => {
  const a = CHOICES.find(c => c.id === 'a');
  assert.deepEqual(a.options, [0, Number(F['pow.aLB']), Number(F['pow.aClaim'])], 'the marked values are the ones the page prints');
  const seen = a.options.map(v => E.exactVerdictDist(L, { a: v }).seen);
  const irr = a.options.map(v => E.exactVerdictDist(L, { a: v }).irrelevant);
  assert.equal(new Set(seen.map(v => v.toFixed(9))).size + new Set(irr.map(v => v.toFixed(9))).size >= 5, true, 'each marked value moves an output: ' + seen + ' / ' + irr);
  assert.equal(E.exactVerdictDist(L, { a: 0 }).seen, 0);
  assert.ok(E.exactVerdictDist(L, { a: 0.3 }).seen > 0.9 && E.exactVerdictDist(L, { a: 0.3 }).irrelevant < 0.01);
  assert.ok(E.exactVerdictDist(L, { a: aClaim }).irrelevant > 0.99);
});
test('choices', 'the edition moves the posture column', () => {
  assert.equal(E.matrix(L, PREDICTIONS).cells.W2.P.contradicted, true);
  assert.equal(E.matrix(L, PREDICTIONS, { edition: '1911' }).cells.W2.P.contradicted, false);
  assert.equal(cellWord(E.matrix(L, PREDICTIONS, { edition: '1911' }).cells.W2.P), 'not counted');
});
test('choices', 'the row order is inert: fifty shuffles leave every control output and every plant unchanged', () => {
  assert.notDeepEqual(E.powerByInjection(L, { a: 0.2, copies: 3, seed: 5, order: 'shuffled', orderSeed: 2 }).example.rows,
    E.powerByInjection(L, { a: 0.2, copies: 3, seed: 5, order: 'shuffled', orderSeed: 3 }).example.rows, 'the plant sees differently shuffled rows');
  const real = E.knowledgeControl(arms.without, arms.with);
  const plantRef = E.powerByInjection(L, { a: 0.2, copies: 400, seed: 5 });
  for (let s = 1; s <= 50; s++) {
    const rows = E.rowsFromArm(arms.without, { order: 'shuffled', seed: s });
    assert.equal(rows.rows.length, 31);
    const r = E.knowledgeControl(E.countRows(rows), arms.with);
    assert.deepEqual([r.verdictCode, r.kStar, r.pLo, r.pHi], [real.verdictCode, real.kStar, real.pLo, real.pHi]);
    const p = E.powerByInjection(L, { a: 0.2, copies: 400, seed: 5, order: 'shuffled', orderSeed: s });
    assert.deepEqual(p.example.rows.length, 31);
    assert.deepEqual(p.counts, plantRef.counts);
  }
  assert.notDeepEqual(E.rowsFromArm(arms.without, { order: 'shuffled', seed: 2 }).rows, E.rowsFromArm(arms.without).rows, 'the shuffle does reorder');
});
test('choices', 'every choice is declared on the page and in record.json', () => {
  for (const c of CHOICES) assert.ok(html.includes('data-state="' + c.id + '"') || (c.id === 'a' && html.includes('id="aSlider"')), 'control for ' + c.id);
  if (record) assert.deepEqual(record.choices, CHOICES);
});

// ================================================================== fault: planted into copies of the data
test('fault', 'faults planted in copies of the frozen files move the results the page prints', () => {
  const l1 = clone(L); E.series(l1, 'arithmetic').without.k_printed = 12;
  const r1 = E.knowledgeControl(E.arithmeticArms(l1).without, E.arithmeticArms(l1).with);
  assert.equal(r1.verdictCode, 'helps', 'twelve right without knowledge would show ability');
  assert.notEqual(figures(l1, C, PREDICTIONS)['k.verdict'], F['k.verdict']);
  const l2 = clone(L); l2.blinders.large.not_seen.pct_printed = 16;
  assert.equal(E.arm(l2.blinders.large.not_seen).consistent, false, 'a corrupted percentage no longer matches the printed two');
  const l3 = clone(L); l3.posture.held_bend.k_1907 = 5;
  assert.ok(E.matrix(l3, PREDICTIONS).survivors.includes('W2'), 'a held bend that rarely worked would leave W2 standing');
  const l4 = clone(L); l4.timeline.find(t => t.id === 'stumpf-report').date = '1905-12-09';
  assert.notEqual(E.decisionDays(l4), 88);
});
test('fault', 'the surface check goes red on a corrupted displayed figure and a corrupted dek', () => {
  const first = S.dataFigs(html).find(d => d.key === 'k.without');
  const corrupted = html.slice(0, first.index) + first.full.replace('3 of 31', '4 of 31') + html.slice(first.index + first.full.length);
  assert.deepEqual(surfaceDisagreements(corrupted, F), ['k.without']);
  const badDek = X.DEK.replace('10,000 of 10,000', '9,000 of 10,000');
  assert.notEqual(badDek, X.DEK);
  assert.notEqual(S.escText(badDek), (html.match(/<p class="dek" data-dek>([\s\S]*?)<\/p>/) || [])[1]);
  const lits = S.literalNumbers(html);
  const bumped = html.replace('11 by 4&frac12; cm', '12 by 4&frac12; cm');
  assert.notDeepEqual(S.literalNumbers(bumped), lits, 'a changed literal is visible to the inventory');
});
// The pin check the provenance group relies on, as one function run on real and on doctored bytes.
function pinMismatches(bufs) {
  return Object.entries(bufs).filter(([f, b]) => crypto.createHash('sha256').update(b).digest('hex') !== SHA256[f]).map(([f]) => f).sort();
}
test('fault', 'a changed byte in a frozen file is caught by the same pin check the provenance group runs', () => {
  const real = Object.fromEntries(Object.values(FILES).map(f => [f, fs.readFileSync(path.join(dir, f))]));
  assert.deepEqual(pinMismatches(real), []);
  const bad = { ...real, [FILES.claimant]: Buffer.from(real[FILES.claimant]) };
  bad[FILES.claimant][bad[FILES.claimant].indexOf('"tapped": 11')] = 0x20;
  assert.deepEqual(pinMismatches(bad), [FILES.claimant]);
});

// ================================================================== refusal
test('refusal', 'the instrument refuses what the record does not hold, and says why on the page', () => {
  assert.equal(E.trialDetail().refused, true); assert.equal(E.trialDetail().reason, E.REASONS.perTrial);
  assert.equal(E.singlePairedP().refused, true);
  assert.equal(E.cell('unknown', 'unseen').refused, true);
  for (const [k, s] of [['known', 'seen'], ['known', 'unseen'], ['unknown', 'seen']]) assert.equal(E.cell(k, s).refused, false);
  const rows = E.rowsFromArm(arms.without);
  for (const a of [1.5, -0.1, NaN, '0.5']) assert.equal(E.plantAbility(rows, a, E.mulberry32(1)).refused, true, 'a = ' + a);
  // the known-sum arm is refused by what it is, not by a label the caller supplies
  assert.equal(E.plantAbility(E.rowsFromArm(arms.with), 0.5, E.mulberry32(1)).code, 'plant-arm');
  assert.equal(E.plantAbility(E.rowsFromArm(arms.with, { role: 'removed' }), 0.5, E.mulberry32(1)).code, 'plant-arm', 'a caller cannot relabel the kept arm');
  assert.equal(E.plantAbility(E.rowsFromArm(E.sightArms(L, {}).seen), 0.5, E.mulberry32(1)).code, 'plant-arm', 'the seen arm of the sight control');
  assert.equal(E.plantAbility(E.rowsFromArm({ k: 3, n: 31 }), 0.5, E.mulberry32(1)).code, 'plant-arm', 'an arm that does not say which it is');
  assert.equal(E.plantAbility(E.rowsFromArm(E.sightArms(L, { undecided: 'as-not-seen' }).notSeen), 0.5, E.mulberry32(1)).refused, undefined, 'the combined unseen arm may be doctored');
  assert.equal(E.powerByInjection(L, { a: 2 }).refused, true);
  assert.equal(E.exactVerdictDist(L, { a: 2 }).refused, true);
  assert.equal(E.heldBend(L, '1911').refused, true);
  assert.equal(E.rateFor(L, 'tones', 'with').refused, true);
  assert.equal(E.rateFor(L, 'clangs', 'with').refused, true);
  assert.equal(E.arm(L.blinders.schillings_small).refused, true);
  const lab = E.arm({ n: 350, pct_printed: 73 });
  assert.equal(lab.refused, true); assert.deepEqual(lab.kRange, [254, 257]); assert.equal(lab.k, undefined);
  assert.equal(E.claimantAnchor(C).reps, 0, 'no repetition counted unless asked');
  const pageJs = read('page.js');
  for (const id of ['heroWhich', 'askPair', 'noCell', 'plantWith']) { assert.ok(html.includes('id="' + id + '"')); assert.ok(pageJs.includes("$('" + id + "')")); }
  for (const phrase of ['Which sums were these?', 'Give me the one paired p-value', 'nobody knows, and nobody is seen', 'Plant into the known-sum arm instead', 'What it refuses.'])
    assert.ok(has(phrase), 'the page offers: ' + phrase);
  assert.ok(!/role:\s*'kept'/.test(pageJs), 'the page never labels the kept arm itself');
  assert.match(pageJs, /value\.trim\(\) === '' \? NaN/, 'an empty ability box is refused, not read as zero');
  assert.equal(E.powerByInjection(L, { a: NaN }).refused, true);
});

// ================================================================== provenance
const hashes = Object.fromEntries(Object.values(FILES).map(f => [f, crypto.createHash('sha256').update(fs.readFileSync(path.join(dir, f))).digest('hex')]));
test('provenance', 'every frozen file is pinned in data.js, the research README and record.json, and copied byte for byte', () => {
  for (const [f, h] of Object.entries(hashes)) {
    assert.equal(SHA256[f], h, 'data.js pin for ' + f);
    assert.ok(readme.includes(h), 'README hash for ' + f);
    assert.deepEqual(fs.readFileSync(path.join(dir, f)), fs.readFileSync(path.join(here, 'data', f)), 'research copy of ' + f);
    assert.ok(fs.statSync(path.join(dir, f)).size < 2_000_000);
  }
  const shipped = fs.readdirSync(dir).filter(f => f.endsWith('.json') && f !== 'record.json').sort();
  assert.deepEqual(shipped, Object.values(FILES).sort());
  for (const u of ['https://archive.org/details/bub_gb_fS4XAAAAYAAJ', 'https://archive.org/details/denkendetierebei00kral', 'https://archive.org/details/daspferddesherr00stumgoog', 'https://archive.org/details/cu31924024783973', 'https://www.gutenberg.org/ebooks/33936']) {
    assert.ok(readme.includes(u), 'README names ' + u);
    assert.ok(read('NOTICE.txt').includes(u), 'NOTICE names ' + u);
  }
  if (record) for (const r of record.records) assert.equal(r.sha256, hashes[r.file], 'record.json pin for ' + r.file);
});

// ================================================================== verdict
test('verdict', 'category, date, scope, sources and what would change it are printed and match record.json', () => {
  assert.match(html, /<p class="cat" id="verdictCat">ARTEFACT<\/p>/);
  assert.equal(VERDICT.category, 'ARTEFACT'); assert.equal(VERDICT.as_of, '2026-09-22');
  assert.match(html, /<time datetime="2026-09-22" id="verdictDate">22 September 2026<\/time>/);
  assert.equal(S.decodeEntities((html.match(/<span id="verdictScope">([\s\S]*?)<\/span>/) || [])[1]), VERDICT.scope);
  assert.equal(S.decodeEntities((html.match(/<span id="verdictChange">([\s\S]*?)<\/span>/) || [])[1]), VERDICT.would_change);
  const lis = [...html.matchAll(/<li id="src-[a-z]+">([\s\S]*?)<\/li>/g)];
  assert.ok(lis.length >= 2);
  assert.equal(lis.length, VERDICT.sources.length);
  for (let i = 0; i < lis.length; i++) {
    const shown = S.decodeEntities(lis[i][1].replace(/<[^>]+>/g, '')).replace(/\s+/g, ' ');
    assert.ok(shown.startsWith(VERDICT.sources[i].replace(/\.$/, '').slice(0, 60)), 'source ' + i + ' printed as recorded');
  }
  assert.ok(has('10.4161/cib.27122'));
  assert.ok(has('Although it turned out that these horses and dogs had no such mathematical powers'));
  assert.ok(has(NOVELTY), 'the novelty sentence, verbatim');
  assert.ok(has(X.HEADLINE), 'the headline, verbatim');
  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, VERDICT.decided_by); assert.equal(record.years_to_decision, 0);
    // the anchored claim wording postdates the deciding report, and the record says so (note 44e0b0)
    assert.ok(E.daysBetween(E.timelineDate(L, 'stumpf-report'), E.timelineDate(L, 'grabow')) > 0, 'Grabow speaks after Stumpf reports');
    assert.equal(E.daysBetween('1904-12-09', '1905-01-05'), 27);
    assert.match(record.years_to_decision_definition || '', /which came 27 days after the deciding report/);
  }
});

// ================================================================== record.json
// The claim year is the anchored wording's (Grabow, 5 January 1905), and that wording came after the
// deciding report, so the zero years would read as "decided in 1905" on the portal's timeline. Say so
// in the record's own words, built from the frozen timeline rather than typed. (Added 2026-09-26, note 44e0b0.)
function ytdDefinition() {
  const long = d => { const [y, m, dd] = d.split('-').map(Number); return dd + ' ' + ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'][m - 1] + ' ' + y; };
  const c = E.timelineDate(L, 'commission'), s = E.timelineDate(L, 'stumpf-report'), g = E.timelineDate(L, 'grabow');
  return 'Whole years in the ' + E.decisionDays(L) + ' days from the commission report of ' + long(c) + ' to Stumpf\u2019s report of ' + long(s) +
    '. The claim year is that of the anchored wording, Grabow\u2019s remarks of ' + long(g) + ', which came ' + E.daysBetween(s, g) +
    ' days after the deciding report: the claim was already under test in 1904, and its supporters restated it after the decision. So zero here means decided within the same year as the tests, in 1904, not in ' + g.slice(0, 4) + '.';
}
function makeRecord(ledger) {
  const m = C.records[0];
  const an = E.claimantAnchor(C);
  const ctl = E.knowledgeControl(arms.without, arms.with);
  const pw = E.powerByInjection(L, { a: aClaim });
  const ex = E.exactVerdictDist(L, { a: aClaim });
  return {
    slug: S.SLUG, title: S.TITLE, href: '/strata/' + S.SLUG + '/', field: 'psychology',
    claim: {
      statement: m.claim_de,
      claimants: 'Schulrat Dr. A. Grabow, as recorded in the minutes of the Psychologische Gesellschaft zu Berlin, speaking for the claim made for Mr. von Osten’s horse Hans',
      citation: m.citation,
      year: 1905,
      headline_as_printed: 'cards nobody present could see: ' + m.trials[0].printed + '; ' + m.described_without_operands.printed + ' Tablets: ' + m.trials[1].printed + '. ' + m.repetitions.printed,
    },
    records: [
      { file: FILES.claimant, role: 'claimant-data', name: 'The supporters’ without-knowledge record: the 1905 minutes (p. 470) and Grabow’s report as excerpted by Krall (1912, p. 163), transcribed from the page images', url: 'https://archive.org/details/bub_gb_fS4XAAAAYAAJ (leaf 479); https://archive.org/details/denkendetierebei00kral (leaf 186)', licence: 'Transcribed facts and short quotations; the 1904 volume carries the Public Domain Mark 1.0 at the Internet Archive; Krall 1912 carries no licence field there', licence_url: 'http://creativecommons.org/publicdomain/mark/1.0/', retrieved: '2026-09-22', sha256: hashes[FILES.claimant], units: C.records.reduce((s, r) => s + r.trials.length, 0) },
      { file: FILES.ledger, role: 'control-data', name: 'Every counted series Pfungst printed (knowledge, blinders, posture, laboratory, von Osten’s hearing demonstration), with the printed words and page for each count', url: 'https://www.gutenberg.org/ebooks/33936; https://archive.org/details/cu31924024783973; https://archive.org/details/daspferddesherr00stumgoog', licence: 'Transcribed counts and short quotations; Project Gutenberg licence (use for nearly any purpose, local law outside the United States); the 1907 scan marked not in copyright at the Internet Archive', licence_url: 'https://www.gutenberg.org/policy/license.html', retrieved: '2026-09-22', sha256: hashes[FILES.ledger], units: L.series.length + 2 + Object.keys(L.posture).length },
    ],
    anchor: {
      what: 'The supporters’ without-knowledge trials, scored by the page’s scoreRecord from the frozen transcription: the arithmetic of every trial with printed numbers, and the tally of every described trial',
      expected: 'as printed: first card tapped 11, then 4 for the first number and 7 for the second (the card itself is not reported as read; 4 und 7 is among the example cards); three more cards likewise; tablets, turned round, 5 and 4, tapped 9; both repeated and succeeded; Krall 1912: 2 und 3 tapped 5, 12 weniger 5 tapped 7; no failure printed in the minutes',
      computed: an.minutes.correct + ' of ' + an.minutes.checkable + ' trials with printed numbers in the minutes add up (' + an.minutes.independent + ' checked against the tablets as turned round; the first card only as agreement among the horse’s own taps), ' + an.krall.correct + ' of ' + an.krall.checkable + ' in the 1912 excerpt (' + an.krall.operandsCorrect + ' of ' + an.krall.operandsChecked + ' tapped operand pairs as printed); ' + an.k + ' of ' + an.n + ' described trials correct; face-value one-sided 95% lower bound ' + an.lowerBound.toFixed(3),
      agrees: an.agrees,
      tolerance: 'exact: the record is integers and arithmetic',
    },
    control: {
      name: 'The two-whisperer addition test: von Osten and Pfungst each whispered one number, so that nobody present knew the sum; each test repeated at once with the sum known',
      citation: 'Oskar Pfungst, Clever Hans (The Horse of Mr. von Osten), tr. C. L. Rahn, New York: Holt, 1911, p. 37; Das Pferd des Herrn von Osten, Leipzig: Barth, 1907, p. 32. Investigation by C. Stumpf, E. von Hornbostel and O. Pfungst, 13 October to 29 November 1904.',
      computed: arms.without.k + ' of ' + arms.without.n + ' without knowledge against ' + arms.with.k + ' of ' + arms.with.n + ' with; the page’s control at chance 1 in 10 needs ' + ctl.kStar + ' (5, 7 or 11 at 1 in 20, 10 or 5): ' + ctl.verdict + '; exact McNemar over the ' + ctl.pairings.length + ' consistent pairings, p from ' + ctl.pLo.toExponential(2) + ' to ' + ctl.pHi.toExponential(2),
      as_printed: 'In 31 tests in which the method was procedure without knowledge, 3 of the horse’s answers were correct, whereas in the 31 tests in which the method was procedure with knowledge, 29 of his responses were correct.',
    },
    power: {
      grade: 'A-injection',
      planted: 'In copies of the 31 without-knowledge rows, each recorded failure became a success with probability a = (29 - 3)/(31 - 3) = ' + aClaim.toFixed(4) + ', read from the frozen counts (the ability at which the doctored arm is expected to equal the known-sum arm); ' + pw.copies + ' copies, seed ' + pw.seed + ', each run through the unmodified knowledgeControl against the real known-sum arm',
      recovered: (pw.counts.helps + pw.counts.irrelevant) + ' of ' + pw.copies + ' copies read ability seen, ' + pw.counts.irrelevant + ' no knowledge effect detected; exact probabilities ' + ex.seen.toFixed(6) + ' and ' + ex.irrelevant.toFixed(6) + ' (ability seen with probability at least ' + E.powerVerdict(L).minSeen.toFixed(6) + ' at every offered chance rate, against the page’s line of ' + E.POWER_LINE.toFixed(2) + '). Sight control planted at the seen rate: no sight effect detected with exact probability ' + E.sightPower(L, {}).exact.toFixed(3),
      verdict: E.powerVerdict(L).text,
    },
    null_through_claimant_method: {
      applicable: true,
      what: 'The supporters’ procedure (a knower asks, correct answers are counted as the responder’s knowledge) in two historical runs whose counted effect cannot have been knowledge: Pfungst standing in for the horse in the laboratory, and von Osten’s own two-condition hearing demonstration, both through the page’s arm, labNull and compareArms functions, with the laboratory run also given the face-value bound (exactLowerBound) that the anchor gives the supporters’ record. These are historical runs, not synthetic nulls with the supporters’ structure: their record prints no denominator or cadence to imitate',
      result: (() => {
        const lab = E.labNull(L, 1 / 4), au = E.auditoryDemo(L);
        return 'a responder who could not know the answer scored ' + L.lab_null.pct_printed + '% in ' + lab.n + ' tests (' + lab.kRange[0] + ' to ' + lab.kRange[1] + ' correct if the average is pooled, a face-value lower bound of ' + lab.lbRange[0].toFixed(3) + ' to ' + lab.lbRange[1].toFixed(3) + ', above the supporters’ ' + E.claimantAnchor(C).lowerBound.toFixed(3) + ') where guessing one of four gives ' + lab.expected.toFixed(1) +
          '; the claimant’s own demonstration produced ' + au.blocked.k + ' of ' + au.blocked.n + ' against ' + au.unblocked.k + ' of ' + au.unblocked.n + ' (a ' + (100 * au.diff).toFixed(1) + '-point contrast, larger than the ' + (100 * au.knowledgeDiff).toFixed(1) + '-point knowledge effect) for a factor Pfungst found irrelevant';
      })(),
    },
    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: Math.floor(E.decisionDays(L) / 365.25),
    years_to_decision_definition: ytdDefinition(),
    choices: CHOICES,
    headline: X.HEADLINE,
    novelty: NOVELTY,
    ledger,
  };
}
const ASSERTIONS = {
  claim_reproduced: 'anchor:grabow-1905-through-scoreRecord',
  control_computed: 'control:pfungst-two-whisperers-knowledgeControl',
  control_can_confirm: 'power:claimed-ability-planted-into-31-rows-verdict-computed',
  rendered_figures_asserted: 'surface:data-fig-spans-head-frontmatter-and-literal-inventory',
  choices_are_live: 'choices:six-live-one-inert-and-well-formed',
  planted_fault_caught: 'fault:corrupted-counts-figures-and-bytes',
  refusal_asserted: 'refuse:per-trial-pairing-unseen-cell-plant-range-and-uncounted-series',
  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') && group('matrix'),
  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;
