#!/usr/bin/env node
// Everything /strata/tyndale-exactly/ says, checked.
//
//   node verify-tyndale-exactly.mjs
//
// Three kinds of assertion, and the third is the one that matters most here.
//
//  1. The census is reproducible: re-derive the headline from the committed
//     texts, in this file, without calling census.mjs, and demand the same
//     number.
//  2. The page is coupled to the data: every figure it prints is written in
//     from census.json at run time, so this checks that every path it asks for
//     exists, and that every quotation on it is verbatim from claims.json.
//  3. The code the READER runs is the code we ran. The page ships engine.js and
//     recomputes the alignment in the browser. If that port ever drifts from
//     research/tyndale-census/, the page would show a stranger a different
//     number from the one this repository stands behind. So the whole New
//     Testament is aligned twice, once through each implementation, and the two
//     must agree token for token.
//
// Negative controls are included, and they are the reason a green here means
// anything: each is a planted defect that the corresponding check must catch.

import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import vm from 'node:vm';

import { NT_BOOKS } from './research/tyndale-census/usfm.mjs';
import * as node from './research/tyndale-census/normalize.mjs';
import { lcs as nodeLcs } from './research/tyndale-census/lcs.mjs';
import { harvestGaps, learnVariants, keyer, CRITERIA } from './research/tyndale-census/learn.mjs';
import * as browser from './public/strata/tyndale-exactly/engine.js';

const ROOT = path.dirname(fileURLToPath(import.meta.url));
const R = (...p) => path.join(ROOT, ...p);
const CENSUS_DIR = R('research', 'tyndale-census');
const PAGE = R('public', 'strata', 'tyndale-exactly', 'index.html');

const checks = [];
let failed = 0;
function check(name, fn) {
  let ok = false, detail = '';
  try {
    const r = fn();
    if (r && typeof r === 'object' && 'ok' in r) { ok = r.ok; detail = r.detail || ''; }
    else { ok = !!r; }
  } catch (e) {
    ok = false; detail = String(e && e.message ? e.message : e);
  }
  if (!ok) failed += 1;
  checks.push([ok, name, detail]);
}

const read = (p) => fs.readFileSync(p, 'utf8');
const json = (p) => JSON.parse(read(p));
const near = (a, b, tol) => Math.abs(a - b) <= tol;

// ---------------------------------------------------------------------------
// Load
// ---------------------------------------------------------------------------

const census = json(path.join(CENSUS_DIR, 'data', 'census.json'));
const provenance = json(path.join(CENSUS_DIR, 'data', 'provenance.json'));
const mansbridge = json(path.join(CENSUS_DIR, 'data', 'mansbridge.json'));
const claims = json(path.join(CENSUS_DIR, 'claims.json'));
const sources = json(path.join(CENSUS_DIR, 'sources.json'));
const page = read(PAGE);
const emitted = json(R('public', 'strata', 'tyndale-exactly', 'data', 'census.json'));
const emittedMap = json(R('public', 'strata', 'tyndale-exactly', 'data', 'map.json'));

function loadWitness(id) {
  const rows = new Map();
  for (const line of read(path.join(CENSUS_DIR, 'data', 'text', `${id}.tsv`)).split('\n')) {
    if (!line || line.startsWith('#')) continue;
    const [ref, , text] = line.split('\t');
    if (ref && text) rows.set(ref, text);
  }
  return rows;
}
const tyn = loadWitness('engtnt');
const kjv = loadWitness('eng-kjv');

// The pairing the census uses: every verse the King James carries.
const pairs = [];
for (const [ref, k] of kjv) {
  pairs.push({ ref, book: ref.split(' ')[0], a: tyn.has(ref) ? node.tokenize(tyn.get(ref)) : [], b: node.tokenize(k) });
}

// ---------------------------------------------------------------------------
// 1 · The census reproduces, computed here rather than read
// ---------------------------------------------------------------------------

function retentionWith(keyFn, ps = pairs) {
  let matched = 0, total = 0;
  for (const p of ps) {
    total += p.b.length;
    if (!p.a.length || !p.b.length) continue;
    matched += nodeLcs(p.a.map(keyFn), p.b.map(keyFn)).length;
  }
  return { matched, total, retention: matched / total };
}

const fit = learnVariants(harvestGaps(pairs.filter((p) => p.a.length && p.b.length)));
const learnedKey = keyer(fit.map);

check('the King James New Testament has the number of words the page prints', () => {
  const total = pairs.reduce((s, p) => s + p.b.length, 0);
  return { ok: total === census.corpus.target.tokens, detail: `${total} vs ${census.corpus.target.tokens}` };
});

check('Tyndale\'s New Testament has the number of words the census records', () => {
  const total = [...tyn.values()].reduce((s, t) => s + node.tokenize(t).length, 0);
  return { ok: total === census.corpus.source.tokens, detail: `${total} vs ${census.corpus.source.tokens}` };
});

for (const [id, fn] of [['L0', node.L0], ['L1', node.L1], ['L2', (w) => node.L2(w)]]) {
  check(`retention at ${id} recomputes to what census.json records`, () => {
    const got = retentionWith(fn).retention;
    return { ok: near(got, census.ladder[id].retention, 1e-9), detail: `${got} vs ${census.ladder[id].retention}` };
  });
}

check('the learned map recomputes to the same size and the same retention', () => {
  const got = retentionWith(learnedKey).retention;
  return {
    ok: fit.map.size === census.ladder.learned.mapSize && near(got, census.ladder.learned.retention, 1e-9),
    detail: `${fit.map.size} pairs, ${got} vs ${census.ladder.learned.mapSize} pairs, ${census.ladder.learned.retention}`,
  };
});

check('the learner\'s acceptance criteria are the ones the pre-registration fixes', () => {
  const pre = read(path.join(CENSUS_DIR, 'PREREGISTRATION.md'));
  return pre.includes('MIN_COUNT = 3')
    && pre.includes('MAX_REL_DIST = 0.34')
    && CRITERIA.MIN_COUNT === 3 && CRITERIA.MAX_REL_DIST === 0.34
    && CRITERIA.MUTUAL_BEST === true && CRITERIA.REJECT_IF_NATIVE_TO_BOTH === true;
});

check('the cross-fitted figure is below the in-sample one, so fitting is costed and not hidden', () => {
  const cf = census.crossFit;
  return { ok: cf.combined.retention < cf.inSample && cf.inflation > 0, detail: `${cf.combined.retention} < ${cf.inSample}` };
});

check('the ordering of the ladder is what a ladder means: L0 < L1 < L2 and both bounds above', () => {
  const l = census.ladder;
  return l.L0.retention < l.L1.retention
    && l.L1.retention < l.L2.retention
    && l.bagOfWords.retention >= l.learned.retention
    && l.fuzzy.retention > l.bagOfWords.retention;
});

// ---------------------------------------------------------------------------
// 2 · The controls, which are what make the number mean anything
// ---------------------------------------------------------------------------

check('the ceiling is near one: two editions of the King James against each other', () => {
  const c = census.controls;
  return { ok: c.ceilingKjv2006 >= 0.999 && c.ceilingCambridgeParagraph >= 0.99,
    detail: `${c.ceilingKjv2006} and ${c.ceilingCambridgeParagraph}` };
});

check('the chance floor is low: each verse against a different verse of the same book', () => {
  const f = census.controls.chanceFloor;
  return { ok: f.learned < 0.15 && f.L1 < 0.15 && f.L2 < 0.15, detail: JSON.stringify(f) };
});

check('the floor really is a floor: it sits far below every real pairing in the corpus', () => {
  const f = census.controls.chanceFloor.learned;
  return census.survival.every((s) => s.retention > f * 2);
});

check('the shuffle control is genuinely shuffled, so its low score is not an empty comparison', () => {
  // Recompute it here, independently of census.mjs, and demand the same shape.
  let seed = 20260907 >>> 0;
  const rnd = () => {
    seed = (seed + 0x6D2B79F5) >>> 0;
    let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
  const byBook = new Map();
  for (const p of pairs) {
    if (!byBook.has(p.book)) byBook.set(p.book, []);
    byBook.get(p.book).push(p);
  }
  let same = 0, total = 0;
  for (const list of byBook.values()) {
    const src = list.map((p) => p.a);
    for (let i = src.length - 1; i > 0; i--) {
      const j = Math.floor(rnd() * (i + 1));
      const t = src[i]; src[i] = src[j]; src[j] = t;
    }
    for (let i = 0; i < list.length; i++) { if (src[i] === list[i].a) same += 1; total += 1; }
  }
  return { ok: same / total < 0.05, detail: `${same} of ${total} verses kept their own partner` };
});

check('holding out the King James\'s italicised supplied words barely moves the answer', () => {
  const d = Math.abs(census.controls.withoutSuppliedWords - census.ladder.learned.retention);
  return { ok: d < 0.01, detail: `${d}` };
});

check('removing the verse boundaries barely moves the answer, so the retrofitted numbering is not driving it', () => {
  const d = Math.abs(census.controls.chapterLevel.retention - census.ladder.learned.retention);
  return { ok: d < 0.02, detail: `${d}` };
});

check('the collision census finds nothing to fuse at L0 and L1, and something at L2', () => {
  const c = census.collisions;
  return c.L0.fusedTypes === 0 && c.L1.fusedTypes === 0 && c.L2.fusedTypes > 0;
});

check('the learned map fuses far less of the King James than the hand rules do', () => {
  const c = census.collisions;
  return { ok: c.learned.fusedTokenShare < c.L2.fusedTokenShare / 5,
    detail: `${c.learned.fusedTokenShare} vs ${c.L2.fusedTokenShare}` };
});

check('a target-only collision census does not bound false matches across texts', () => {
  const targetOnly = node.collisionCensus(new Map([['good', 1]]), node.L2);
  const both = node.collisionCensus(new Map([['good', 1], ['god', 1]]), node.L2);
  const matched = nodeLcs(['god'].map(node.L2), ['good'].map(node.L2)).length;
  return { ok: targetOnly.fusedTokenShare === 0 && both.fusedTypes === 2 && matched === 1,
    detail: 'good/god: zero target-only collisions, one false match; both spellings give two fused types' };
});

// ---------------------------------------------------------------------------
// 3 · The reader's code is our code
// ---------------------------------------------------------------------------

check('the browser tokeniser agrees with the repository\'s over every verse of both texts', () => {
  let n = 0;
  for (const [, text] of kjv) {
    const a = node.tokenize(text).join(' ');
    const b = browser.tokenize(text).join(' ');
    if (a !== b) return { ok: false, detail: `first disagreement after ${n} verses` };
    n += 1;
  }
  for (const [, text] of tyn) {
    if (node.tokenize(text).join(' ') !== browser.tokenize(text).join(' ')) {
      return { ok: false, detail: `Tyndale verse ${n}` };
    }
    n += 1;
  }
  return { ok: true, detail: `${n} verses` };
});

check('the browser spelling ladder agrees with the repository\'s on every word type in the corpus', () => {
  const types = new Set();
  for (const [, t] of kjv) for (const w of node.tokenize(t)) types.add(w);
  for (const [, t] of tyn) for (const w of node.tokenize(t)) types.add(w);
  for (const w of types) {
    if (node.L1(w) !== browser.L1(w)) return { ok: false, detail: `L1 differs on "${w}"` };
    if (node.L2(w) !== browser.L2(w)) return { ok: false, detail: `L2 differs on "${w}": ${node.L2(w)} vs ${browser.L2(w)}` };
  }
  return { ok: true, detail: `${types.size} word types` };
});

check('the browser measure returns the repository\'s number over all of the New Testament', () => {
  const rows = [];
  for (const [ref, k] of kjv) rows.push([ref, tyn.get(ref) || null, k]);
  const map = new Map(emittedMap.pairs.map((p) => [p[0], p[1]]));
  const got = browser.retention(rows, browser.keyer(map));
  const want = census.ladder.learned.retention;
  return { ok: near(got.retention, want, 5e-5) && got.total === census.corpus.target.tokens,
    detail: `${got.retention} vs ${want}, ${got.total} words` };
});

check('the map the page ships is the map the census learned', () => {
  if (emittedMap.pairs.length !== fit.accepted.length) {
    return { ok: false, detail: `${emittedMap.pairs.length} vs ${fit.accepted.length}` };
  }
  for (const [from, to] of emittedMap.pairs) {
    if (fit.map.get(from) !== to) return { ok: false, detail: `${from} -> ${to}` };
  }
  return { ok: true, detail: `${emittedMap.pairs.length} pairs` };
});

check('the browser LCS finds the same length as the repository\'s on ten thousand random word pairs', () => {
  let seed = 4271993;
  const rnd = () => (seed = (seed * 1103515245 + 12345) & 0x7fffffff) / 0x7fffffff;
  for (let t = 0; t < 10000; t++) {
    const mk = (n) => Array.from({ length: n }, () => 'abcdefg'[Math.floor(rnd() * 7)]);
    const a = mk(1 + Math.floor(rnd() * 12)), b = mk(1 + Math.floor(rnd() * 12));
    if (nodeLcs(a, b).length !== browser.lcs(a, b).length) return { ok: false, detail: `${a.join('')} / ${b.join('')}` };
  }
  return true;
});

// NEGATIVE CONTROLS. Each plants a defect and demands that the corresponding
// check above would have caught it. Without these, a green means only that
// nothing was tested.
check('NEGATIVE CONTROL: a one-word change to a verse changes the measured retention', () => {
  const p = pairs.find((x) => x.ref === 'JHN 1:1');
  const before = nodeLcs(p.a.map(learnedKey), p.b.map(learnedKey)).length;
  const broken = p.b.slice();
  broken[0] = 'zzzzz';
  const after = nodeLcs(p.a.map(learnedKey), broken.map(learnedKey)).length;
  return { ok: after < before, detail: `${before} -> ${after}` };
});

check('NEGATIVE CONTROL: a browser engine that folded one letter differently would be caught', () => {
  const rigged = (w) => browser.L1(w).replace(/z/g, 's');
  let differs = false;
  for (const [, t] of kjv) {
    for (const w of node.tokenize(t)) if (node.L1(w) !== rigged(w)) { differs = true; break; }
    if (differs) break;
  }
  return differs;
});

check('NEGATIVE CONTROL: the ceiling check would fail on two texts that are not the same translation', () => {
  const a = [];
  for (const [ref, k] of kjv) a.push({ ref, book: ref.split(' ')[0], a: node.tokenize(k), b: node.tokenize(k) });
  const identical = retentionWith(node.L1, a).retention;
  const kjvVsTyndale = census.ladder.L1.retention;
  return { ok: identical > 0.999 && kjvVsTyndale < 0.99, detail: `${identical} vs ${kjvVsTyndale}` };
});

// ---------------------------------------------------------------------------
// 4 · The page says only what the data says
// ---------------------------------------------------------------------------

check('every figure the page asks for exists in the data it is handed', () => {
  const wanted = [...page.matchAll(/data-n="([^"]+)"/g)].map((m) => m[1]);
  if (!wanted.length) return { ok: false, detail: 'the page binds no figures at all, which cannot be right' };
  for (const p of wanted) {
    let v = emitted;
    for (const k of p.split('.')) v = v == null ? undefined : v[k];
    if (v === undefined || v === null) return { ok: false, detail: `${p} is not in the emitted census` };
  }
  return { ok: true, detail: `${wanted.length} bindings` };
});

check('every quotation on the page is verbatim from claims.json', () => {
  for (const c of claims.claims) {
    const inData = emitted.claims.claims.find((x) => x.id === c.id);
    if (!inData || inData.quote !== c.quote) return { ok: false, detail: `${c.id} is not carried to the page` };
  }
  // The Library of Congress sentence is quoted in the page's own body, so check
  // it there character for character.
  const loc = claims.claims.find((c) => c.id === 'daniell-loc-1997');
  const inPage = page.includes('83 percent of the King James New Testament')
    && page.includes('an exact percentage had not been determined');
  return { ok: inPage && loc.quote.includes('83 percent of the King James New Testament is Tyndale exactly.'),
    detail: 'Library of Congress quotation' };
});

check('the page links every source it quotes', () => {
  for (const c of claims.claims) {
    if (!/^https:\/\//.test(c.url)) return { ok: false, detail: `${c.id} has no URL` };
  }
  return page.includes('https://www.loc.gov/loc/lcib/9707/daniell.html')
    && page.includes('https://studybible.info/Tyndale/')
    && page.includes('https://archive.org/details/1534-tyndale-nt')
    && page.includes('https://ebible.org/find/details.php?id=engtnt');
});

check('the page prints no command a reader cannot obtain', () => {
  const cmds = [...page.matchAll(/node ((?:research|scripts|lib|oversight)\/[^\s<`"]+\.mjs|verify-[a-z0-9-]+\.mjs)/g)]
    .map((m) => m[1]);
  const missing = cmds.filter((c) => !fs.existsSync(R(c)));
  return { ok: missing.length === 0, detail: missing.join(', ') || `${cmds.length} commands, all present` };
});

check('the page carries the shared site bar and does not link into a private repository', () => {
  return page.includes('/media/home-banner.js')
    && !/github\.com\/[^"'\s]*artificial-wasteland/i.test(page);
});

check('the page ships the engine it claims to run in the reader\'s browser', () => {
  return page.includes('/strata/tyndale-exactly/engine.js')
    && fs.existsSync(R('public', 'strata', 'tyndale-exactly', 'engine.js'));
});

check('every book of the New Testament is served to the page as its own file', () => {
  const missing = NT_BOOKS.filter((b) => !fs.existsSync(R('public', 'strata', 'tyndale-exactly', 'data', `${b}.json`)));
  return { ok: missing.length === 0 && NT_BOOKS.length === 27, detail: missing.join(', ') };
});

check('the per-book files carry the same text the census counted', () => {
  let n = 0;
  for (const book of NT_BOOKS) {
    const d = json(R('public', 'strata', 'tyndale-exactly', 'data', `${book}.json`));
    for (const [suffix, t, k] of d.verses) {
      const ref = `${book} ${suffix}`;
      if (kjv.get(ref) !== k) return { ok: false, detail: `King James text differs at ${ref}` };
      const want = tyn.get(ref) || null;
      if ((t || null) !== want) return { ok: false, detail: `Tyndale text differs at ${ref}` };
      n += 1;
    }
  }
  return { ok: n === kjv.size, detail: `${n} verses` };
});

// ---------------------------------------------------------------------------
// 5 · Provenance
// ---------------------------------------------------------------------------

check('every witness has a recorded digest, and every committed text has a witness', () => {
  const ids = sources.witnesses.map((w) => w.id);
  for (const w of sources.witnesses) if (!/^[0-9a-f]{64}$/.test(w.sha256 || '')) return { ok: false, detail: w.id };
  const files = fs.readdirSync(path.join(CENSUS_DIR, 'data', 'text')).filter((f) => f.endsWith('.tsv'));
  const orphans = files.filter((f) => !ids.includes(f.replace('.tsv', '')));
  return { ok: orphans.length === 0, detail: orphans.join(', ') || `${ids.length} witnesses` };
});

check('the two digitisations of Tyndale agree on more than 95 per cent of words', () => {
  const d = provenance.independentDigitisation;
  return { ok: d.chapterRate > 0.95 && d.versesCompared > 500,
    detail: `${d.chapterRate} over ${d.versesCompared} verses` };
});

check('the disagreements between them are dominated by the expansion of Tudor abbreviations', () => {
  const b = provenance.independentDigitisation.buckets.filter((x) => x.name !== 'not one word against one');
  const named = b.filter((x) => x.name !== 'something else').reduce((s, x) => s + x.n, 0);
  const all = b.reduce((s, x) => s + x.n, 0);
  return { ok: all > 0 && named / all > 0.9, detail: `${named} of ${all}` };
});

check('the distinctive Tudor spellings of our text are on the photographed 1534 leaves', () => {
  const f = provenance.facsimile;
  return { ok: f.rate > 0.7 && f.distinctive > 500, detail: `${f.found} of ${f.distinctive}` };
});

check('and the decoy control says that is evidence: shuffled words of the same shape are not', () => {
  const f = provenance.facsimile;
  return { ok: f.decoyRate < 0.02 && f.rate > f.decoyRate * 20, detail: `${f.rate} against ${f.decoyRate}` };
});

// ---------------------------------------------------------------------------
// 6 · The comparison with what is published
// ---------------------------------------------------------------------------

check('the replication uses the passages the published study actually names', () => {
  const refs = mansbridge.passages.map((p) => p.ref);
  return { ok: refs.length === 6 && refs.includes('ACT 25:1-15') && refs.includes('REV 20'),
    detail: refs.join(', ') };
});

check('his word counts and ours agree, so the two are counting the same objects', () => {
  const t = mansbridge.totals;
  return { ok: t.wordCountGap < 0.05, detail: `${t.hisWords} vs ${t.ourWords}` };
});

check('his passages are not unrepresentative: our figure on them matches our figure on the whole', () => {
  const t = mansbridge.totals;
  return { ok: Math.abs(t.learned - t.wholeNewTestament) < 0.03,
    detail: `${t.learned} on his six, ${t.wholeNewTestament} on all 27 books` };
});

check('so the gap is the counting rule, and the permissive rung is where it closes', () => {
  const t = mansbridge.totals;
  const strictGap = Math.abs(t.hisRetention - t.learned);
  const looseGap = Math.abs(t.hisRetention - t.fuzzy);
  return { ok: looseGap < strictGap / 3,
    detail: `strict is ${(strictGap * 100).toFixed(1)} points away, permissive ${(looseGap * 100).toFixed(1)}` };
});

check('neither recorded set of twenty thousand eighteen-passage draws reached 83 percent', () => {
  const a = census.sampling.chapters, b = census.sampling.blocksOf20Verses;
  return { ok: a.max < 0.83 && b.max < 0.83 && a.draws === 20000 && b.draws === 20000,
    detail: `highest draw ${Math.max(a.max, b.max)}` };
});

// Rebuild the exact partition from the texts, including its final short block.
// A list of chapter totals cannot stand in for consecutive twenty-verse blocks.
const assayBlocks = [];
for (let i = 0; i < pairs.length; i += 20) {
  const slice = pairs.slice(i, i + 20);
  const measured = retentionWith(learnedKey, slice);
  assayBlocks.push({ key: `${slice[0].ref}-${slice.at(-1).ref}`,
    matched: measured.matched, total: measured.total });
}

check('the histogram receives the exact consecutive verse blocks the census sampled', () => {
  return { ok: JSON.stringify(census.blockUnits) === JSON.stringify(assayBlocks)
      && JSON.stringify(emitted.blockUnits) === JSON.stringify(assayBlocks),
    detail: `${assayBlocks.length} blocks, ${assayBlocks.reduce((s, b) => s + b.total, 0)} words` };
});

check('a permitted selection of eighteen blocks can exceed 83 percent', () => {
  const indices = [176, 168, 157, 145, 373, 181, 151, 170, 160, 146, 173, 155, 158, 179, 154, 161, 374, 200];
  const selected = indices.map((i) => assayBlocks[i]);
  const matched = selected.reduce((s, b) => s + b.matched, 0);
  const total = selected.reduce((s, b) => s + b.total, 0);
  return { ok: new Set(indices).size === 18 && matched === 6400 && total === 7705 && matched / total > 0.83,
    detail: `${matched}/${total}; deliberately selected, not a random draw or a probability estimate` };
});

check('both histogram options render real draws, and block draws reproduce the recorded summary', () => {
  const nodes = new Map();
  const el = (id) => {
    if (!nodes.has(id)) nodes.set(id, { children: [], style: {},
      appendChild(child) { this.children.push(child); },
      set innerHTML(value) { this.children = []; } });
    return nodes.get(id);
  };
  const context = vm.createContext({ census: emitted, el,
    document: { createElement: () => ({ style: {} }) },
    pct: (x, n) => (x * 100).toFixed(n), int: (x) => x.toLocaleString('en-US') });
  const start = page.indexOf('function mulberry32(seed)');
  const end = page.indexOf('function renderSampNote()');
  if (start < 0 || end <= start) return false;
  vm.runInContext(page.slice(start, end), context);
  for (const kind of ['chapters', 'blocksOf20Verses']) {
    vm.runInContext(`renderHist('${kind}')`, context);
    const bars = el('hist').children;
    const status = el('sampstat').textContent;
    const label = kind === 'chapters' ? 'eighteen chapters' : 'eighteen blocks of up to twenty verses';
    if (bars.length !== 70 || !bars.some((b) => b.style.height === '100.00%')
        || !status.includes(label) || !status.includes('20,000')) return { ok: false, detail: `${kind}: ${status}` };
  }
  const draws = vm.runInContext("drawSamples(unitsFor('blocksOf20Verses'), 18, 20000, 4271993)", context);
  const mean = draws.reduce((s, x) => s + x, 0) / draws.length;
  const stat = census.sampling.blocksOf20Verses;
  return { ok: near(mean, stat.mean, 1e-12) && near(Math.max(...draws), stat.max, 1e-12),
    detail: `both charts populated; block mean ${mean}, maximum ${Math.max(...draws)}` };
});

check('the resampling is centred on the census, which is what says it is a sample of it', () => {
  const a = census.sampling.chapters;
  return { ok: Math.abs(a.mean - census.ladder.learned.retention) < 0.01, detail: `${a.mean}` };
});

// ---------------------------------------------------------------------------
// 7 · The independence arm
// ---------------------------------------------------------------------------

check('the 1582 Rheims covers all 27 books and about as many verses as the King James', () => {
  const rh = loadWitness('rheims1582');
  const books = new Set([...rh.keys()].map((r) => r.split(' ')[0]));
  return { ok: books.size === 27 && rh.size > 7500, detail: `${books.size} books, ${rh.size} verses` };
});

check('an English New Testament not descended from Tyndale still shares more than half his words', () => {
  const rh = census.survival.find((s) => s.id === 'rheims1582');
  return { ok: rh && rh.retention > 0.4 && rh.retention < census.ladder.learned.retention,
    detail: `${rh && rh.retention}` };
});

check('so the margin that descent buys is far smaller than the headline figure', () => {
  // Like against like (corrected 2026-09-25): the Rheims row is cross-fitted, so it is
  // set against the King James cross-fitted, never against the in-sample 72.3.
  const rh = census.survival.find((s) => s.id === 'rheims1582');
  const margin = census.crossFit.combined.retention - rh.retention;
  const inSample = census.ladder.learned.retention - (rh.retention + rh.inflation);
  const pageLikeForLike = /census\.crossFit\.combined\.retention - dra\.retention/.test(page);
  return { ok: margin > 0 && margin < 0.3 && inSample > 0 && inSample < 0.3 && pageLikeForLike,
    detail: `${(margin * 100).toFixed(1)} points cross-fitted, ${(inSample * 100).toFixed(1)} in-sample` };
});

check('the page reports its own pre-registered falsifier, and what it returned', () => {
  // PREREGISTRATION.md: if the cross-fitted learned figure and L2 disagree by more than
  // about two points, no single number should be quoted. They do (3.2), and the page
  // must say so rather than print one number as if the rule had passed.
  const pre = read(R('research', 'tyndale-census', 'PREREGISTRATION.md')).replace(/\s+/g, ' ');
  const rule = 'If the cross-fitted learned figure and the L2 figure disagree by more than about two percentage points, the two methods do not agree and no single number should be quoted.';
  const gap = census.ladder.L2.retention - census.crossFit.combined.retention;
  const said = page.replace(/\s+/g, ' ').replace(/&ldquo;|&rdquo;/g, '"').includes(rule) && page.includes('id="prereg-correction"');
  return { ok: pre.includes(rule) && (gap <= 0.02 || said), detail: `L2 minus cross-fitted = ${(gap * 100).toFixed(2)} points; reported ${said}` };
});

check('Challoner\'s revision scores higher than the 1582 text it revises, as the page says it does', () => {
  const rh = census.survival.find((s) => s.id === 'rheims1582');
  const ch = census.survival.find((s) => s.id === 'engDRA');
  return { ok: ch.retention > rh.retention, detail: `${ch.retention} vs ${rh.retention}` };
});

check('taking out the hundred commonest words lowers every arm, and lowers the independent one further', () => {
  const kj = census.survival.find((s) => s.id === 'eng-kjv');
  const rh = census.survival.find((s) => s.id === 'rheims1582');
  return { ok: kj.contentWords < kj.retention && rh.contentWords < rh.retention
      && (kj.retention - rh.retention) < (kj.contentWords - rh.contentWords),
    detail: `${kj.contentWords} vs ${rh.contentWords}` };
});

check('the versification drift the census reports is real: the worst chapter recovers when the numbers are ignored', () => {
  const worst = census.drift.worst[0];
  return { ok: worst.chapterLevel - worst.verse > 0.2, detail: `${worst.chapter}: ${worst.verse} -> ${worst.chapterLevel}` };
});

check('every attributed share adds to the whole, with nothing lost between the buckets', () => {
  const a = census.attribution;
  return { ok: a.tyndale + a.genevaNotTyndale + a.neither === a.total && a.total === census.corpus.target.tokens,
    detail: `${a.total}` };
});

// ---------------------------------------------------------------------------

const passed = checks.filter(([ok]) => ok).length;
for (const [ok, name, detail] of checks) {
  console.log(`  ${ok ? 'ok  ' : 'FAIL'}  ${name}${detail ? `  [${detail}]` : ''}`);
}
console.log(`\n${passed} passed, ${failed} failed`);
process.exit(failed ? 1 : 0);
