// verify.mjs: recompute core Liber Primus measurements from the committed corpus
// and check selected saved analysis results.
//
//   node research/cicada-3301/verify.mjs
//
// What it checks. Sections run in the order they were written rather than in label
// order, and this list follows the file, so a label like 8h simply arrived later than 8j.
//
//   1  the Gematria Primus is the 29 futhorc runes against the first 29 primes
//   2  the corpus parses to the stated sizes
//   3  every SOLVED page decrypts under its published key, re-derived here from
//      the ciphertext and plaintext rather than assumed
//   3b p56_an_end is a PRIME RUNNING KEY, a fourth cipher form and an aperiodic one
//   3a where the interrupter actually is (plaintext F, not ciphertext F), and the
//      three word-list sweeps, only one of which can find the book's own key
//   4  the unsolved corpus is flat: unigrams, and the 812 off-diagonal bigram cells
//   5  the one anomaly: 86 adjacent-equal pairs where 447 are expected
//   6  nothing at any other lag, and nothing at any period from 1 to 120
//   7  the exclusion bounds: the least adjacent-equal rate reachable by an additive
//      cipher, by an affine one, and by an arbitrary polyalphabetic one, computed
//      from an 8.0M-rune English reference
//   7a the same bound measured in seven languages, so it does not rest on English
//   7b how far into the tail of all alphabets a surviving cipher would have to sit
//   7f whether any alphabet anyone would actually BUILD (keyword, rotation, affine,
//      power map) reaches the book: 2.26 million of them, and none does
//   8  a bench of cipher machines run on real plaintext: where each one lands
//   8a the leakage: why there are 86 repeats rather than none, and what it is not
//   8c the word structure, which no rune-wise cipher can change
//   8d where the book puts its headings, read off the colour channel
//   8e the token pages, and four characters the transcription has wrong
//   8b the page images' shared and differing JPEG fingerprints
//   9  the independent OCR of the page scans against the human transcription
//   5a what the 86 survivors have in common, which is nothing
//   6a nor is there a period out to 2600, which covers every order a permutation of
//      29 symbols can have, and so covers every progressive polyalphabetic
//   7c a transposition in front of the cipher does not lower the floor: it raises it
//   7e the same bound on the book's own 2977 plaintext runes, with the uncertainty
//      that sample size actually carries
//   7d nor does any fixed linear window over the plaintext, swept exhaustively
//   8h the longest red passage in the book, which the heading cap hid, and the
//      twelve-word crib it carries
//   8i that crib against the book's own dictionary, and why the shape's absence from
//      an English corpus is worth nothing
//   8j the word-list attacks: prefix, substituted-key and phase-swept, each with a
//      control that recovers the book's own keys before any negative is reported
//   8f whether eleven statistics can separate the book from a three-parameter
//      message-free generator, with controls that prove the battery has teeth
//   8l aperiodic keys: integer-sequence and text running keys, and autokey
//   8m whether the images carry a SECOND channel the way the colour one does
//   8k every periodic key each crib admits, enumerated exactly by iterating
//      dictionary words rather than key streams
//   8g what base the 256-token block on pages 49 to 51 is written in
//
// Core measurements are recomputed from the corpus; later sections check selected
// saved Python results. This does not recompute or compare every prose number.
// It exits non-zero if any assertion fails.

import { readFileSync } from 'fs';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
const HERE = dirname(fileURLToPath(import.meta.url));

let fails = 0;
const ok  = (name, cond, extra = '') => {
  console.log((cond ? '  ok   ' : '  FAIL ') + name + (extra ? '  ' + extra : ''));
  if (!cond) fails++;
};
const sec = (s) => console.log('\n=== ' + s + ' ===');
const f3 = (x) => Number(x).toFixed(3);

/* ─────────────────────────────── 1. the alphabet ─────────────────────────── */
sec('1. the Gematria Primus');
const RUNES = [...'ᚠᚢᚦᚩᚱᚳᚷᚹᚻᚾᛁᛄᛇᛈᛉᛋᛏᛒᛖᛗᛚᛝᛟᛞᚪᚫᚣᛡᛠ'];
const LATIN = ['F','U','TH','O','R','C','G','W','H','N','I','J','EO','P','X','S','T','B','E','M','L','NG','OE','D','A','AE','Y','IA','EA'];
const N = 29;
const R2I = new Map(RUNES.map((r, i) => [r, i]));
const sieve = (m) => { const p = [], c = new Uint8Array(m + 1); for (let i = 2; i <= m; i++) { if (!c[i]) { p.push(i); for (let j = i * i; j <= m; j += i) c[j] = 1; } } return p; };
const PRIMES = sieve(200).slice(0, N);
ok('29 runes, all distinct', RUNES.length === N && new Set(RUNES).size === N);
ok('29 latin values, all distinct', LATIN.length === N && new Set(LATIN).size === N);
ok('gematria values are the first 29 primes, 2..109',
   PRIMES.length === N && PRIMES[0] === 2 && PRIMES[28] === 109);

/* ─────────────────────────────── 2. the corpus ───────────────────────────── */
sec('2. the corpus');
function parse(path) {
  const out = {};
  let cur = null;
  for (const line of readFileSync(join(HERE, path), 'utf8').split('\n')) {
    if (line.startsWith('##')) { cur = line.slice(2).trim().split(/\s+/)[0]; out[cur] = { runes: [], marks: [] }; continue; }
    if (line.startsWith('#') || !cur) continue;
    for (const ch of line) {
      if (R2I.has(ch)) { out[cur].runes.push(R2I.get(ch)); out[cur].marks.push(''); }
      else if (' .,;#'.includes(ch) && out[cur].marks.length && out[cur].marks.at(-1) === '')
        out[cur].marks[out[cur].marks.length - 1] = ch;
    }
  }
  return out;
}
const LP = parse('data/liber-primus.txt');
const PT = parse('data/solved-plaintext.txt');
const UNSOLVED = ['p0-2','p3-7','p8-14','p15-22','p23-26','p27-32','p33-39','p40-53','p54-55'];
const SOLVED   = ['0_welcome','0_koan_1','0_warning','p56_an_end','jpg107-167'];
const PLAIN    = ['0_wisdom','0_loss_of_divinity','p57_parable','jpg229'];
const US = UNSOLVED.flatMap(b => LP[b].runes);
const KP = [...SOLVED, ...PLAIN].flatMap(b => PT[b].runes);
ok('18 page groups in the corpus', Object.keys(LP).length === 18, `got ${Object.keys(LP).length}`);
ok('unsolved corpus is 12,956 runes', US.length === 12956, `got ${US.length}`);
ok('known plaintext is 2,977 runes', KP.length === 2977, `got ${KP.length}`);
ok('ciphertext and plaintext lengths match on every solved page',
   [...SOLVED, ...PLAIN].every(b => LP[b].runes.length === PT[b].runes.length));

/* ──────────────────── 3. the solved pages, re-derived ────────────────────── */
sec('3. the solved pages decrypt under their published keys');
const mod = (a, m = N) => ((a % m) + m) % m;
const keystream = (b) => LP[b].runes.map((c, i) => mod(c - PT[b].runes[i]));
const asText = (ix) => ix.map(i => LATIN[i]).join('');
for (const b of PLAIN)
  ok(`${b} is plaintext (zero key stream)`, keystream(b).every(k => k === 0));
for (const [b, k] of [['0_warning', 28], ['0_koan_1', 2]]) {
  const s = LP[b].runes.map((c, i) => mod(c + PT[b].runes[i]));
  ok(`${b} is Atbash with constant sum ${k}`, s.every(v => v === k), `distinct sums: ${new Set(s).size}`);
}
// Vigenere pages, with interrupters: an F rune left unenciphered, key not advancing.
function vigKey(b) {
  const ct = LP[b].runes, pt = PT[b].runes, out = [];
  for (let i = 0; i < ct.length; i++) {
    const k = mod(ct[i] - pt[i]);
    if (k === 0 && ct[i] === 0) continue;
    out.push(k);
  }
  return out;
}
for (const [b, word] of [['0_welcome', 'DIUINITY'], ['jpg107-167', 'FIRFUMFERENFE']]) {
  const k = vigKey(b);
  const period = word.length;
  const first = asText(k.slice(0, period));
  const repeats = k.every((v, i) => v === k[i % period]);
  ok(`${b} is Vigenere "${word}" once F interrupters are removed`,
     first === word && repeats, `read ${first}, periodic=${repeats}`);
}
{
  const k = vigKey('p56_an_end');          // same F-interrupter convention
  const P2 = sieve(2000);
  ok('p56 "an end" is a running shift by phi(p_n) = p_n - 1',
     k.every((v, i) => v === mod(P2[i] - 1)), `${k.length} enciphered runes`);
}

/* ─────────────────────── 4. the unsolved text is flat ────────────────────── */
/* ────────── 3b. the fourth cipher form: p56 is a PRIME RUNNING KEY ─────────── */
sec('3b. p56_an_end is a prime running key, which is a fourth cipher form');
// The solved forms include plaintext, Atbash, word-key Vigenere and the prime running key already implemented by LiberPrayground. p56_an_end is enciphered with a running key whose shift at
// key index j is (prime_{j+1} - 1) mod 29, carrying the same plaintext-F interrupter. For
// j < 29 that is identically the gematria value of the j-th rune minus one, which is the
// book's own table read as a key. Being APERIODIC it sits outside every period-based
// exclusion, so it has to be tested separately, which section 8k does.
{
  const primes = (() => {
    const lim = 4000, c = new Uint8Array(lim + 1), out = [];
    for (let i = 2; i <= lim; i++) { if (!c[i]) { out.push(i); for (let j = i * i; j <= lim; j += i) c[j] = 1; } }
    return out;
  })();
  const ct = LP['p56_an_end'].runes, pt = PT['p56_an_end'].runes;
  let j = 0, hit = 0, firstBad = -1;
  for (let i = 0; i < ct.length; i++) {
    if (pt[i] === 0) { if (ct[i] === 0) hit++; else if (firstBad < 0) firstBad = i; continue; }
    if (ct[i] === mod(pt[i] + primes[j] - 1)) hit++; else if (firstBad < 0) firstBad = i;
    j++;
  }
  console.log(`  the prime running key reproduces ${hit} of ${ct.length} runes of p56_an_end`);
  ok('p56_an_end is a prime running key, every rune', hit === ct.length,
     `${hit}/${ct.length}` + (firstBad >= 0 ? `, first miss at ${firstBad}` : ''));
  const shifts = primes.slice(0, 29).map(q => mod(q - 1));
  const gem = PRIMES.slice(0, 29).map(q => mod(q - 1));
  ok('and for the first 29 key indices the shift IS the gematria value minus one',
     shifts.join(',') === gem.join(','), `${shifts.slice(0, 6)}`);
  console.log('  the solved forms are plaintext, Atbash, word-key Vigenere, and a prime running key');
}

/* ────── 3a. where the interrupter actually is, and what that costs a solver ─── */
sec('3a. the interrupter sits at PLAINTEXT F, not ciphertext F');
// Section 3 decrypts the Vigenere pages using a rule that skips a position when the key
// residue is 0 AND the ciphertext rune is F, which is the same as skipping where the
// PLAINTEXT rune is F. That distinction was missing from this study's earlier implementation and matters for
// the book: ciphertext F is common and mostly innocent, plaintext F is the interrupter, and
// a solver can only see the first. Everything here is recomputed from the two committed
// corpus files, with no reliance on the Python side.
{
  const per = (k, hi = 25) => {
    const out = [];
    for (let p = 1; p <= hi; p++) {
      if (k.length <= 2 * p) continue;
      let ok = true;
      for (let i = 0; i < k.length; i++) if (k[i] !== k[i % p]) { ok = false; break; }
      if (ok) out.push(p);
    }
    return out;
  };
  const facts = [];
  for (const [page, name, want] of [['0_welcome', 'DIUINITY', 8], ['jpg107-167', 'FIRFUMFERENFE', 13]]) {
    const ct = LP[page].runes, pt = PT[page].runes;
    ok(`${page}: ciphertext and plaintext are the same length`, ct.length === pt.length);
    const k = ct.map((c, i) => mod(c - pt[i]));
    const byCt = k.filter((_v, i) => ct[i] !== 0);
    const byPt = k.filter((_v, i) => pt[i] !== 0);
    const pCt = per(byCt), pPt = per(byPt), pNone = per(k);
    console.log(`  ${page}: skip-on-ct-F periodic at [${pCt}]; skip-on-pt-F periodic at [${pPt}]; skip-nothing [${pNone}]`);
    ok(`  ${page}: skipping on PLAINTEXT F makes the key periodic at ${want}`,
       pPt.length > 0 && pPt[0] === want, `[${pPt}]`);
    ok(`  ${page}: skipping on CIPHERTEXT F makes it periodic at nothing`, pCt.length === 0);
    ok(`  ${page}: and neither does skipping nothing`, pNone.length === 0);
    const ctF = ct.map((c, i) => c === 0 ? i : -1).filter(i => i >= 0);
    const ptF = pt.map((c, i) => c === 0 ? i : -1).filter(i => i >= 0);
    const ptSet = new Set(ptF);
    const spurious = ctF.filter(i => !ptSet.has(i));
    console.log(`  ${page}: ${ctF.length} ciphertext F, ${ptF.length} plaintext F, ${spurious.length} ciphertext F that are NOT interrupters`);
    ok(`  ${page}: every interrupter is a ciphertext F, so the rule is at least visible in principle`,
       ptF.every(i => ct[i] === 0));
    ok(`  ${page}: but most ciphertext F runes are not interrupters, so it is not visible in practice`,
       spurious.length > ptF.length / 3, `${spurious.length} of ${ctF.length}`);
    // what a solver applying the wrong rule gets, using the TRUE key
    const key = byPt.slice(0, pPt[0]);
    let j = 0; let correct = 0, firstErr = -1;
    for (let i = 0; i < ct.length; i++) {
      const p = ct[i] === 0 ? 0 : mod(ct[i] - key[j++ % key.length]);
      if (p === pt[i]) correct++; else if (firstErr < 0) firstErr = i;
    }
    console.log(`  ${page}: the ciphertext-F rule with the TRUE key decrypts ${correct}/${pt.length} runes (${(100*correct/pt.length).toFixed(1)}%), first error at ${firstErr}`);
    ok(`  ${page}: the wrong rule fails almost immediately even with the right key`,
       correct / pt.length < 0.20 && firstErr < 15, `${(100*correct/pt.length).toFixed(1)}%, first error ${firstErr}`);
    facts.push({ page, first: Math.min(...ptF), rate: ptF.length / pt.length });
  }
  for (const f of facts)
    console.log(`  ${f.page}: interrupter rate ${(100*f.rate).toFixed(2)}%, first one at offset ${f.first}`);
  ok('both pages run clean for more than 40 runes before their first interrupter, which is the opening an attack needs',
     facts.every(f => f.first > 40), facts.map(f => `${f.page}@${f.first}`).join(' '));
  // the stored analysis must agree with this recomputation
  const J = JSON.parse(readFileSync(join(HERE, 'data/interrupter.json'), 'utf8'));
  ok('the stored interrupter analysis agrees',
     J.pages.every(p => p.period_ct === null && p.period_none === null && p.period_pt > 0) &&
     J.pages.every(p => p.pt_F_all_ct_F === true),
     J.pages.map(p => `${p.page}:${p.period_pt}`).join(' '));
  if (J.dictionary_words > 0) {
    console.log(`  of the book's two keys, ${J.keys_in_dictionary} is a dictionary word (${J.dictionary_words} entries searched)`);
    ok("exactly one of the book's two Vigenere keys is a dictionary word",
       J.keys_in_dictionary === 1, `${J.keys_in_dictionary} of 2`);
    ok('FIRFUMFERENFE is spelled by no English word at all, so a word-list attack cannot reach it',
       (J.keys.find(k => k.page === 'jpg107-167') || {}).dictionary_words.length === 0);
  }
  if (J.interrupter_absent) {
    // The interrupter leaves a fingerprint. If plaintext F is copied through unenciphered
    // then P(ct = F) = f + (1-f)/29, so ciphertext F must be ELEVATED. That is measurable on
    // pages whose plaintext we do NOT have, which makes it one of the very few things this
    // study can say about the unsolved text under the model P(ct=F | pt!=F)=1/29.
    const A = J.interrupter_absent;
    // recompute the count here rather than trusting the file
    let ctF = 0; for (const r of US) if (r === 0) ctF++;
    const cnt = new Array(N).fill(0); for (const r of US) cnt[r]++;
    const rank = cnt.filter(c => c > cnt[0]).length + 1;
    ok('the unsolved ciphertext-F count recomputes', ctF === A.unsolved_ctF, `${ctF}`);
    console.log(`  the book's plaintext uses F at ${(100*A.plaintext_F_rate).toFixed(3)}%, so the uniform-output interrupted model predicts P(ct=F) = ${(100*A.predicted_ctF).toFixed(3)}%`);
    console.log(`  the unsolved corpus has ${ctF} ciphertext F in ${US.length} runes = ${(100*ctF/US.length).toFixed(2)}%, the ${rank}th most common rune of 29`);
    ok('ciphertext F is unremarkable in the unsolved text, not elevated',
       Math.abs(A.z_flat) < 2 && rank > 3, `z vs 1/29 = ${f3(A.z_flat)}, rank ${rank}`);
    ok('and it is far below what the uniform-output interrupted model predicts',
       A.z_interrupted < -6, `z = ${f3(A.z_interrupted)}`);
    console.log(`  implied plaintext F rate ${(100*A.implied_f).toFixed(3)}% +/- ${(100*A.implied_se).toFixed(3)}%, against a per-page range of ${(100*Math.min(...A.per_page_f)).toFixed(2)}% to ${(100*Math.max(...A.per_page_f)).toFixed(2)}%`);
    ok('the implied rate sits below the lowest page we can read',
       A.sd_below_lowest_page > 2.5, `${f3(A.sd_below_lowest_page)} sd below`);
    // the honest limit: at single-page scale the test does NOT discriminate, and one real case fails it
    const interrupted = A.controls.filter(c => c.kind === 'interrupted');
    const missed = interrupted.filter(c => c.z_interrupted < -2);
    ok('stated honestly: at single-page scale the test misclassifies a genuinely interrupted page',
       missed.length >= 1,
       missed.map(c => `${c.page} z ${f3(c.z_interrupted)}`).join(', ') || 'none, which would be surprising');
    console.log(`  (that is why the claim is made on 12,956 runes and not on a page: per-page F rates vary from ${(100*Math.min(...A.per_page_f)).toFixed(2)}% to ${(100*Math.max(...A.per_page_f)).toFixed(2)}%)`);
  }
  if (J.wordlist_ranks) {
    // The cost, as a rank rather than an argument. On a page whose key IS a dictionary word,
    // only one of the three ways to run the sweep puts that key first.
    console.log(`  sweeping ${J.wordlist_keys.toLocaleString()} rune-keys against 0_welcome, whose key is DIVINITY:`);
    for (const r of J.wordlist_ranks) console.log(`    ${r.variant.padEnd(56)} rank ${r.rank}`);
    const naive = J.wordlist_ranks.find(r => /naive/.test(r.variant));
    const whole = J.wordlist_ranks.find(r => /no interrupter handling/.test(r.variant));
    const prefix = J.wordlist_ranks.find(r => /prefix/.test(r.variant));
    ok('the naive ciphertext-F rule buries the true key in the thousands',
       naive.rank > 1000, `rank ${naive.rank} of ${naive.of}`);
    ok('and no interrupter handling at all still misses it',
       whole.rank > 10, `rank ${whole.rank}`);
    ok('only the interrupter-free prefix puts the true key first',
       prefix.rank === 1, `rank ${prefix.rank}`);
    ok('so exactly one of the three ways to run the sweep is a valid instrument',
       J.wordlist_ranks.filter(r => r.rank === 1).length === 1);
  }
}

sec('4. the unsolved text is flat');
const counts = (a, m = N) => { const c = new Array(m).fill(0); for (const x of a) c[x]++; return c; };
const chi2 = (obs, exp) => obs.reduce((s, o) => s + (o - exp) ** 2 / exp, 0);
const cu = chi2(counts(US), US.length / N);
ok('unigram distribution is uniform (chi2 on 28 df near 28)', cu > 10 && cu < 50, `chi2=${f3(cu)}`);
const ioc = (a) => { const c = counts(a), n = a.length; return N * c.reduce((s, x) => s + x * (x - 1), 0) / (n * (n - 1)); };
ok('normalised index of coincidence is 1.00 (flat), not 1.78 (English)',
   Math.abs(ioc(US) - 1) < 0.02, `IoC=${ioc(US).toFixed(4)}`);
ok('the known plaintext is far from flat, as a control', ioc(KP) > 1.6, `IoC=${ioc(KP).toFixed(4)}`);
const B = Array.from({ length: N }, () => new Array(N).fill(0));
for (let i = 0; i < US.length - 1; i++) B[US[i]][US[i + 1]]++;
const off = []; for (let i = 0; i < N; i++) for (let j = 0; j < N; j++) if (i !== j) off.push(B[i][j]);
const co = chi2(off, off.reduce((a, b) => a + b, 0) / off.length);
ok('the 812 off-diagonal bigram cells are uniform (chi2 on 811 df)',
   co > 700 && co < 950, `chi2=${f3(co)}`);

/* ───────────────────────── 5. the one anomaly ────────────────────────────── */
sec('5. the one anomaly: adjacent equal runes');
let dbl = 0; for (let i = 0; i < US.length - 1; i++) if (US[i] === US[i + 1]) dbl++;
const npair = US.length - 1, expd = npair / N;
const z = (dbl - expd) / Math.sqrt(npair * (1 / N) * (1 - 1 / N));
ok('86 adjacent-equal pairs', dbl === 86, `got ${dbl}`);
ok('447 expected under a flat memoryless source', Math.abs(expd - 446.7) < 0.5, `exp=${f3(expd)}`);
ok('the deficit is beyond 17 standard deviations', z < -17, `z=${f3(z)}`);
{
  const SC = SOLVED.flatMap(b => LP[b].runes);
  let d2 = 0; for (let i = 0; i < SC.length - 1; i++) if (SC[i] === SC[i + 1]) d2++;
  const r2 = d2 / (SC.length - 1);
  ok('the SOLVED ciphertexts show no such deficit (control)', r2 > 0.02,
     `${d2}/${SC.length - 1} = ${(100 * r2).toFixed(3)}%`);
}

/* ───────────────── 6. nothing at any other lag or period ─────────────────── */
sec('6. nothing at any other lag, nothing at any period');
let worst = 0, worstLag = 0;
for (let lag = 2; lag <= 87; lag++) {
  let e = 0; for (let i = 0; i + lag < US.length; i++) if (US[i] === US[i + lag]) e++;
  const n = US.length - lag, zz = (e - n / N) / Math.sqrt(n * (1 / N) * (1 - 1 / N));
  if (Math.abs(zz) > Math.abs(worst)) { worst = zz; worstLag = lag; }
}
ok('every lag from 2 to 87 is at chance (|z| < 3)', Math.abs(worst) < 3,
   `worst lag ${worstLag}, z=${f3(worst)}`);
const cosetIoC = (a, L) => {
  let s = 0, k = 0;
  for (let i = 0; i < L; i++) { const c = []; for (let j = i; j < a.length; j += L) c.push(a[j]); if (c.length > 1) { s += ioc(c); k++; } }
  return s / k;
};
function mulberry(seed) {
  return () => { seed |= 0; 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 rnd = mulberry(3301);
const HI = 150;
let best = 0, bestL = 0;
for (let L = 2; L <= HI; L++) { const v = cosetIoC(US, L); if (v > best) { best = v; bestL = L; } }
ok('no key length reaches anything like a real periodic cipher (English gives 1.78)',
   best < 1.10, `best L=${bestL} at ${best.toFixed(4)}`);
// The honest null is not a shuffle: it is a message-free sequence carrying the SAME
// length, marginals and lag-1 suppression as the book. Anything the book's period
// scan does that these also do is not evidence of a period.
const controlRate = dbl / npair;
function control() {
  const q = 1 - controlRate * N;               // redraw probability
  const out = [Math.floor(rnd() * N)];
  for (let i = 1; i < US.length; i++) {
    let v = Math.floor(rnd() * N);
    while (v === out[i - 1] && rnd() < q) v = Math.floor(rnd() * N);
    out.push(v);
  }
  return out;
}
let beaten = 0, ctrlBest = [];
for (let t = 0; t < 20; t++) {
  const c = control();
  let m = 0; for (let L = 2; L <= HI; L++) { const v = cosetIoC(c, L); if (v > m) m = v; }
  ctrlBest.push(m); if (m >= best) beaten++;
}
ctrlBest.sort((a, b) => a - b);
ok("the book's best period is inside what message-free controls produce",
   beaten >= 1, `book ${best.toFixed(4)}; ${beaten} of 20 controls reached it ` +
   `(control median ${ctrlBest[10].toFixed(4)}, max ${ctrlBest[19].toFixed(4)})`);

/* ─────────────────── 7. what each cipher class can reach ─────────────────── */
sec('7. the exclusion bounds');
const ref = JSON.parse(readFileSync(join(HERE, 'data/english-runic-stats.json'), 'utf8'));
ok('English reference is 8.0M runes', ref.runes > 7.9e6 && ref.runes < 8.1e6, `${ref.runes}`);
ok('English reference alphabet matches the Gematria Primus', ref.alphabet.join('') === RUNES.join(''));
const EB = ref.bigram;
let addMin = Infinity, addArg = 0;
for (let d = 0; d < N; d++) { let s = 0; for (let x = 0; x < N; x++) s += EB[x][mod(x + d)]; if (s < addMin) { addMin = s; addArg = d; } }
let affMin = Infinity;
for (let a = 1; a < N; a++) for (let b = 0; b < N; b++) { let s = 0; for (let x = 0; x < N; x++) s += EB[x][mod(a * x + b)]; if (s < affMin) affMin = s; }
function hungarian(cost) {                       // O(n^3) assignment, n = 29
  const n = cost.length;
  const u = new Array(n + 1).fill(0), v = new Array(n + 1).fill(0);
  const p = new Array(n + 1).fill(0), way = new Array(n + 1).fill(0);
  for (let i = 1; i <= n; i++) {
    p[0] = i; let j0 = 0;
    const minv = new Array(n + 1).fill(Infinity), used = new Array(n + 1).fill(false);
    do {
      used[j0] = true; const i0 = p[j0]; let delta = Infinity, j1 = 0;
      for (let j = 1; j <= n; j++) if (!used[j]) {
        const cur = cost[i0 - 1][j - 1] - u[i0] - v[j];
        if (cur < minv[j]) { minv[j] = cur; way[j] = j0; }
        if (minv[j] < delta) { delta = minv[j]; j1 = j; }
      }
      for (let j = 0; j <= n; j++) { if (used[j]) { u[p[j]] += delta; v[j] -= delta; } else minv[j] -= delta; }
      j0 = j1;
    } while (p[j0] !== 0);
    do { const j1 = way[j0]; p[j0] = p[j1]; j0 = j1; } while (j0);
  }
  let s = 0; for (let j = 1; j <= n; j++) s += cost[p[j] - 1][j - 1];
  return s;
}
const permMin = hungarian(EB);
const obsRate = dbl / npair;
console.log(`  observed rate                                  ${(100 * obsRate).toFixed(4)}%   (${dbl} pairs)`);
console.log(`  least reachable by an ADDITIVE cipher          ${(100 * addMin).toFixed(4)}%   (at key difference ${addArg})`);
console.log(`  least reachable by an AFFINE cipher            ${(100 * affMin).toFixed(4)}%`);
console.log(`  least reachable by ANY polyalphabetic cipher   ${(100 * permMin).toFixed(4)}%`);
const zAdd = (dbl - addMin * npair) / Math.sqrt(npair * addMin * (1 - addMin));
const zAff = (dbl - affMin * npair) / Math.sqrt(npair * affMin * (1 - affMin));
ok('the additive bound is above 1.8% for English', addMin > 0.018, `${(100 * addMin).toFixed(4)}%`);
ok('observed is below the additive bound by more than 9 sigma', zAdd < -9, `z=${f3(zAdd)}`);
ok('observed is below the affine bound by more than 6 sigma', zAff < -6, `z=${f3(zAff)}`);
ok('observed is ABOVE the arbitrary-permutation bound (that class is NOT excluded)',
   obsRate > permMin, `${(100 * obsRate).toFixed(4)}% > ${(100 * permMin).toFixed(4)}%`);
{
  const PB = Array.from({ length: N }, () => new Array(N).fill(0));
  for (let i = 0; i < KP.length - 1; i++) PB[KP[i]][KP[i + 1]]++;
  const tot = KP.length - 1;
  let m = Infinity;
  for (let d = 0; d < N; d++) { let s = 0; for (let x = 0; x < N; x++) s += PB[x][mod(x + d)] / tot; if (s < m) m = s; }
  const zz = (dbl - m * npair) / Math.sqrt(npair * m * (1 - m));
  ok("the same holds against the book's own plaintext", zz < -6,
     `bound ${(100 * m).toFixed(4)}%, z=${f3(zz)}`);
}

/* ─────────── 7a. the bound is not an artefact of assuming English ────────── */
sec('7a. the same bound in seven languages');
{
  const L = JSON.parse(readFileSync(join(HERE, 'data/language-floors.json'), 'utf8'));
  ok('the language table measures the same 86 doubles', L.book.doubles === dbl);
  for (const r of L.languages) {
    const z = (dbl - r.floor * npair) / Math.sqrt(npair * r.floor * (1 - r.floor));
    console.log(`  ${r.name.padEnd(28)} ${(r.runes/1000).toFixed(0).padStart(5)}k runes   floor ${(100*r.floor).toFixed(4)}%   z ${f3(z)}`);
    ok(`  ${r.name}: the recomputed z matches the table`, Math.abs(z - r.z) < 0.02);
    ok(`  ${r.name}: its floor is still above the book`, r.floor > obsRate);
  }
  ok('every language tested keeps the book below its additive floor by 3 sigma or more',
     L.languages.every(r => r.z < -3), `weakest ${L.weakest.name} at z = ${f3(L.weakest.z)}`);
}

/* ───── 7f. the alphabets anyone would actually BUILD, enumerated ──────────── */
sec('7f. can a keyed alphabet reach the book? because that is how they are built');
// The study also samples RANDOM permutations. A common construction uses a keyword,
// writing its distinct runes first and the rest of
// the alphabet after. That is a finite family, and so are its rotations, the affine maps and
// the power maps. The question is whether any of them reaches the book's 0.664%.
{
  const K = JSON.parse(readFileSync(join(HERE, 'data/keyed-alphabets.json'), 'utf8'));
  ok('the keyed-alphabet sweep measures the same 86 doubles',
     K.book_doubles === dbl && K.book_pairs === npair);
  for (const [name, f] of Object.entries(K.families))
    console.log(`  ${name.padEnd(24)} ${String(f.n).padStart(9)} alphabets, lowest weight ${(100*f.min).toFixed(4)}% (${f.best}), at or below the book: ${f.at_or_below_book}`);
  console.log(`  ${'algebraic'.padEnd(24)} ${String(K.algebraic.n).padStart(9)} maps,      lowest weight ${(100*K.algebraic.min).toFixed(4)}% (${K.algebraic.best}), at or below the book: ${K.algebraic.at_or_below_book}`);
  ok('no keyed alphabet, no rotation of one, and no algebraic map reaches the book',
     Object.values(K.families).every(f => f.at_or_below_book === 0) &&
     K.algebraic.at_or_below_book === 0,
     `${K.total_alphabets.toLocaleString()} alphabets tried`);
  // recompute the algebraic family here, since it needs no word list
  {
    let lo = Infinity, arg = '';
    for (let a = 1; a < N; a++) for (let b = 0; b < N; b++) {
      let w = 0; for (let x = 0; x < N; x++) w += EB[x][mod(a*x + b)];
      if (w < lo) { lo = w; arg = `affine ${a}x+${b}`; }
    }
    ok('  the algebraic minimum recomputes here', Math.abs(lo - K.algebraic.min) < 1e-9,
       `${(100*lo).toFixed(4)}% at ${arg}`);
  }
  console.log(`  lowest weight over all ${K.total_alphabets.toLocaleString()} constructed alphabets: ${(100*K.lowest).toFixed(4)}%, against the book's ${(100*(dbl/npair)).toFixed(4)}%`);
  // that lowest weight is a FLOOR for the family, so it can be tested like any other bound
  const zf = (dbl - npair*K.lowest) / Math.sqrt(npair*K.lowest*(1-K.lowest));
  ok('the family floor recomputes to the stored value', Math.abs(zf - K.floor_z) < 0.02, `z=${f3(zf)}`);
  ok('the book sits below that floor, though only suggestively',
     zf < -2 && zf > -4, `z = ${f3(zf)}, which is not a decisive exclusion and is not claimed as one`);
  ok('what IS firm is constructive: the best buildable alphabet misses by a fifth or more',
     K.lowest / (dbl/npair) > 1.2, `${(100*(K.lowest/(dbl/npair) - 1)).toFixed(0)}% short`);
}

/* ────────────── 7b. how selected the alphabets would have to be ──────────── */
sec('7b. how selected a polyalphabetic cipher would have to be');
// The arbitrary-permutation class is not excluded, but that is not the same as it
// being ordinary. For a cipher applying alphabet f(i) at position i, the repeat rate
// is the mean bigram weight of g = f(i+1)^-1 . f(i). Ask what weight a permutation
// picked at random has, and where the book's number sits in that distribution.
{
  const trials = 1_000_000;
  const perm = new Int32Array(N);
  let sum = 0, sumsq = 0, atOrBelow = 0, lowest = 1;
  const rn = mulberry(20260824);
  for (let t = 0; t < trials; t++) {
    for (let i = 0; i < N; i++) perm[i] = i;
    for (let i = N - 1; i > 0; i--) { const j = Math.floor(rn() * (i + 1)); const s = perm[i]; perm[i] = perm[j]; perm[j] = s; }
    let w = 0;
    for (let x = 0; x < N; x++) w += EB[x][perm[x]];
    sum += w; sumsq += w * w;
    if (w <= obsRate) atOrBelow++;
    if (w < lowest) lowest = w;
  }
  const mean = sum / trials, sd = Math.sqrt(sumsq / trials - mean * mean);
  console.log(`  ${trials.toLocaleString()} random alphabet pairings: mean ${(100*mean).toFixed(4)}%, sd ${(100*sd).toFixed(4)}%`);
  console.log(`  lowest weight seen ${(100*lowest).toFixed(4)}%; at or below the book: ${atOrBelow}`);
  ok('a random alphabet pairing averages 1/29, as it must',
     Math.abs(mean - 1/N) < 0.0005, `${(100*mean).toFixed(4)}%`);
  ok('almost no random pairing reaches the book',
     atOrBelow <= trials / 200000, `${atOrBelow} of ${trials.toLocaleString()}`);
  ok('so the book sits deep in the tail of what alphabets can do',
     (obsRate - mean) / sd < -2.5, `z = ${f3((obsRate - mean) / sd)}`);
}
// and no natural algebraic permutation of the Gematria Primus gets close
{
  const w = (g) => { let s = 0; for (let x = 0; x < N; x++) s += EB[x][g[x]]; return s; };
  const cand = [
    ['identity (a monoalphabetic cipher)', [...Array(N).keys()]],
    ['Atbash, x -> 28 - x', [...Array(N).keys()].map(x => 28 - x)],
    ['x -> 13x mod 29', [...Array(N).keys()].map(x => mod(13 * x))],
    ['x -> x^3 mod 29', [...Array(N).keys()].map(x => Number(BigInt(x) ** 3n % 29n))],
    ['x -> x^-1 mod 29', [...Array(N).keys()].map(x => x === 0 ? 0 : Number(BigInt(x) ** 27n % 29n))],
    ['best shift (d = 7)', [...Array(N).keys()].map(x => mod(x + 7))],
  ];
  let closest = 1;
  for (const [name, g] of cand) {
    const v = w(g);
    if (new Set(g).size !== N) { ok(`${name} is a permutation`, false); continue; }
    console.log(`  ${name.padEnd(36)} ${(100*v).toFixed(4)}%`);
    if (v < closest) closest = v;
  }
  ok('no natural algebraic alphabet of the Gematria Primus gets near the book',
     closest > obsRate * 2.5, `closest ${(100*closest).toFixed(4)}%`);
}

/* ───────────────────────── 8. the machine bench ──────────────────────────── */
sec('8. where each cipher machine lands');
const pt = []; while (pt.length < 40000) pt.push(...KP);
const rate = (c) => { let d = 0; for (let i = 0; i < c.length - 1; i++) if (c[i] === c[i + 1]) d++; return d / (c.length - 1); };
const rr = mulberry(1337);
const rint = (m) => Math.floor(rr() * m);
const machines = {
  'Vigenere L=13':       () => { const k = Array.from({ length: 13 }, () => rint(N)); return pt.map((x, i) => mod(x + k[i % 13])); },
  'Beaufort L=13':       () => { const k = Array.from({ length: 13 }, () => rint(N)); return pt.map((x, i) => mod(k[i % 13] - x)); },
  'uniform random key':  () => pt.map(x => mod(x + rint(N))),
  'one-time pad':        () => pt.map(x => mod(x + rint(N))),
  'progressive a=7':     () => pt.map((x, i) => mod(x + 7 * i)),
  'phi(prime) shift':    () => { const P2 = sieve(600000); return pt.map((x, i) => mod(x + P2[i % P2.length] - 1)); },
  'autokey (plaintext)': () => { const k = [...Array.from({ length: 5 }, () => rint(N)), ...pt]; return pt.map((x, i) => mod(x + k[i])); },
  'autokey (ciphertext)':() => { const k = Array.from({ length: 5 }, () => rint(N)); return pt.map((x, i) => { const c = mod(x + k[i]); k.push(c); return c; }); },
  '3-rotor machine':     () => {
      const R = [0, 1, 2].map(() => { const a = [...Array(N).keys()]; for (let i = N - 1; i > 0; i--) { const j = rint(i + 1); [a[i], a[j]] = [a[j], a[i]]; } return a; });
      const pos = [0, 0, 0];
      return pt.map(x => {
        let y = x;
        for (let r = 0; r < 3; r++) y = mod(R[r][mod(y + pos[r])] - pos[r]);
        pos[0]++; for (let r = 0; r < 2; r++) if (pos[r] >= N) { pos[r] = 0; pos[r + 1]++; }
        return y;
      });
    },
  'no-repeat by design': () => { let prev = rint(N); return pt.map(x => { const al = []; for (let v = 0; v < N; v++) if (v !== prev) al.push(v); const c = al[mod(x + rint(N - 1), N - 1)]; prev = c; return c; }); },
};
let anyNear = false;
for (const [name, fn] of Object.entries(machines)) {
  const r = rate(fn());
  const near = Math.abs(r - obsRate) < 0.003;
  if (near && name !== 'no-repeat by design') anyNear = true;
  console.log(`  ${name.padEnd(22)} ${(100 * r).toFixed(3)}%${near ? '   <- near the Liber Primus' : ''}`);
}
ok('no standard cipher machine lands near the observed rate', !anyNear);
ok('a cipher designed not to repeat overshoots to zero, so the book is neither',
   rate(machines['no-repeat by design']()) < 0.001);

/* ────── 8a. the leakage: why there are 86 repeats and not none ──────────── */
sec('8a. the leakage, and what it is not');
// A rule that forbids repeats gives 0. The book gives 86. Two ordinary explanations,
// both testable, both wrong.
{
  // (i) typesetting errors. The solved pages are ground truth: each decrypts under a
  // rigid rule, so a typo would show as a position where the rule breaks.
  let breaks = 0, positions = 0;
  for (const b of PLAIN) { const k = keystream(b); positions += k.length; breaks += k.filter(v => v !== 0).length; }
  for (const [b, want] of [['0_warning', 28], ['0_koan_1', 2]]) {
    const s = LP[b].runes.map((c, i) => mod(c + PT[b].runes[i]));
    positions += s.length; breaks += s.filter(v => v !== want).length;
  }
  for (const [b, word] of [['0_welcome', 'DIUINITY'], ['jpg107-167', 'FIRFUMFERENFE']]) {
    const k = vigKey(b), w = asText(k.slice(0, word.length)) === word ? word : null;
    const want = [...Array(k.length).keys()].map(i => LATIN.indexOf(word.match(/TH|NG|OE|AE|EA|IA|EO|./g)[i % word.match(/TH|NG|OE|AE|EA|IA|EO|./g).length]));
    positions += k.length; breaks += k.filter((v, i) => v !== want[i]).length;
  }
  {
    const k = vigKey('p56_an_end'), P2 = sieve(2000);
    positions += k.length; breaks += k.filter((v, i) => v !== mod(P2[i] - 1)).length;
  }
  // 95% upper bound on a rate given `breaks` in `positions` (rule of three when zero)
  const upper = breaks === 0 ? 3 / positions : (breaks + 2 * Math.sqrt(breaks)) / positions;
  console.log(`  the solved pages break their own rule at ${breaks} of ${positions} positions`);
  console.log(`  95% upper bound on the book's typesetting error rate: ${(100*upper).toFixed(4)}%`);
  console.log(`  the leakage would need                               ${(100*obsRate).toFixed(4)}%`);
  ok('the 86 repeats cannot be typesetting errors', obsRate > upper * 2,
     `${(obsRate/upper).toFixed(1)}x the largest error rate the solved pages allow`);

  // (ii) run boundaries. If the alphabet were constant over runs and changed with
  // probability a, the repeat rate would be (1-a)D + a/29 and the lag-2 rate
  // (1-a)^2 C2 + (1-(1-a)^2)/29, with D and C2 the plaintext's own adjacent-double and
  // lag-2 coincidence rates. Fit a to the observed repeat rate, then predict lag 2.
  let l2 = 0; for (let i = 0; i + 2 < US.length; i++) if (US[i] === US[i + 2]) l2++;
  const nl2 = US.length - 2;
  ok('the observed lag-2 rate is 1/29, so there are no constant-alphabet runs',
     Math.abs(l2 / nl2 - 1 / N) < 0.002, `${(100*l2/nl2).toFixed(3)}%`);
  const LF = JSON.parse(readFileSync(join(HERE, 'data/language-floors.json'), 'utf8'));
  console.log('  fitting that model language by language (D = 0 is the friendliest case):');
  const zs = [];
  for (const r of LF.languages) {
    for (const [tag, D] of [['as written', r.D], ['de-geminated', 0]]) {
      if (Math.abs(D - 1/N) < 1e-9) continue;
      const a = (D - obsRate) / (D - 1/N);
      if (a < 0 || a > 1) { if (tag === 'as written') console.log(`    ${r.name.padEnd(26)} ${tag.padEnd(13)} no valid a: it cannot reach the book's rate at all`); continue; }
      const pred = (1 - a) ** 2 * r.C2 + (1 - (1 - a) ** 2) / N;
      const z = (l2 - pred * nl2) / Math.sqrt(nl2 * pred * (1 - pred));
      console.log(`    ${r.name.padEnd(26)} ${tag.padEnd(13)} a = ${a.toFixed(3)}  predicts lag-2 ${(100*pred).toFixed(2)}%  z = ${f3(z)}`);
      zs.push(z);
    }
  }
  ok('the run-boundary explanation is excluded for every language, de-geminated or not',
     zs.length > 0 && Math.max(...zs) < -3, `weakest z = ${f3(Math.max(...zs))}`);
}

/* ─── 8c. two more things a correct solution has to produce ──────────────── */
sec('8c. the word structure, which no cipher can change');
{
  const W = JSON.parse(readFileSync(join(HERE, 'data/word-structure.json'), 'utf8'));
  const S = W.structure;
  const share = (d) => 100 * d.two / d.words;
  console.log(`  two-rune words   unsolved ${share(S.unsolved).toFixed(1)}%   ` +
              `the book's plaintext ${share(S.plaintext).toFixed(1)}%   ` +
              `solved ciphertext ${share(S.solved_ct).toFixed(1)}%`);
  console.log(`  ${W.english_two_rune.length} English texts span ${Math.min(...W.english_two_rune).toFixed(1)}% to ` +
              `${Math.max(...W.english_two_rune).toFixed(1)}%`);
  ok('the control holds: a cipher does not change word lengths', W.control_p > 0.05,
     `solved ciphertext vs its own plaintext, p = ${W.control_p.toFixed(3)}`);
  ok('the unsolved pages are short of two-rune words against the book\'s own plaintext',
     W.p_two_rune < 1e-5, `chi2 = ${f3(W.chi2_two_rune)}, p = ${W.p_two_rune.toExponential(1)}`);
  ok('and short of them against every English text measured',
     share(S.unsolved) < Math.min(...W.english_two_rune),
     `${share(S.unsolved).toFixed(1)}% against a floor of ${Math.min(...W.english_two_rune).toFixed(1)}%`);
  const rps = (d) => d.runes / d.sentences, cpk = (d) => 1000 * d.commas / d.runes;
  console.log(`  runes per sentence  unsolved ${rps(S.unsolved).toFixed(1)}   ` +
              `the book's prose ${rps(S.plaintext).toFixed(1)}`);
  console.log(`  commas per 1000     unsolved ${cpk(S.unsolved).toFixed(2)}   ` +
              `the book's prose ${cpk(S.plaintext).toFixed(2)}`);
  ok('the unsolved pages punctuate far more sparsely than the book\'s own prose',
     rps(S.unsolved) > 2 * rps(S.plaintext) && cpk(S.unsolved) < cpk(S.plaintext) / 10);
  console.log('  none of this is enciphered, so any correct decryption must produce a text');
  console.log('  with these proportions, which is a test no proposed solution has had to pass.');
}

/* ──────── 8d. the section map, from red ink and the chapter mark ────────── */
sec('8d. where the book puts its headings');
{
  const S = JSON.parse(readFileSync(join(HERE, 'data/sections.json'), 'utf8'));
  // The bracket rule: a heading sits inside a pair of chapter marks. Validate it
  // against every heading whose plaintext we have before using it on the rest.
  const known = S.known, unsolved = S.unsolved;
  const named = known.filter(r => /^(WELCOME|ACOAN|AWARNNG|ANEND|PARABLE|SOMEWISDOM|CNOWTHIS|THELOSSOFDIUINITY|PRESERUATIAN|ADHERENCE|ANINSTRUCTIAN|WIDSOM)$/.test(r.plain));
  console.log(`  bracketed units on pages with known plaintext: ${known.length}`);
  console.log(`  of which are recognisable Liber Primus headings: ${named.length}`);
  console.log('  ' + [...new Set(named.map(r => r.plain))].join(', '));
  ok('the bracket rule finds real headings on every page we can check',
     named.length >= 15, `${named.length} of ${known.length}`);
  ok('and red ink independently marks them',
     known.filter(r => r.red > 0).length >= known.length - 2,
     `${known.filter(r => r.red > 0).length} of ${known.length} carry red`);
  // the word shape inside a heading is not enciphered, so it is a plaintext fact
  const shapeOf = (r) => r.shape.join('-');
  for (const r of named.slice(0, 4))
    ok(`  ${r.plain} has shape (${r.shape})`,
       r.shape.reduce((a, b) => a + b, 0) === r.length);
  console.log(`\n  the unsolved book, sectioned: ${unsolved.length} headings`);
  for (const r of unsolved)
    console.log(`    ${r.section.padEnd(9)} ${String(r.start).padStart(5)}..${String(r.end).padEnd(5)} ` +
                `len ${String(r.length).padStart(3)}  shape (${r.shape})  ${r.ct}`);
  ok('every unsolved heading is red through, or all but one rune of it',
     unsolved.every(r => r.red >= r.length - 1));
  ok('their word shapes sum to their lengths',
     unsolved.every(r => r.shape.reduce((a, b) => a + b, 0) === r.length));
  // no unsolved heading has the shape of one the book has already shown
  const ks = new Set(known.map(shapeOf)), us = new Set(unsolved.map(shapeOf));
  const shared = [...us].filter(s => ks.has(s));
  ok('not one unsolved heading has the shape of a known one', shared.length === 0,
     `${ks.size} known shapes, ${us.size} unsolved, ${shared.length} shared`);
  // is that surprising? relabel the 33 headings at random and count the overlap
  const pool = [...known.map(shapeOf), ...unsolved.map(shapeOf)];
  const rn = mulberry(90210);
  let atMost = 0; const T = 20000;
  for (let t = 0; t < T; t++) {
    const p = pool.slice();
    for (let i = p.length - 1; i > 0; i--) { const j = Math.floor(rn() * (i + 1)); [p[i], p[j]] = [p[j], p[i]]; }
    const a = new Set(p.slice(0, known.length)), b = new Set(p.slice(known.length));
    if ([...b].filter(s => a.has(s)).length <= shared.length) atMost++;
  }
  console.log(`  relabelling the same 33 headings at random, P(overlap <= 0) = ${(atMost/T).toFixed(4)}`);
  ok('and that disjointness is unlikely by chance', atMost / T < 0.05, `p = ${(atMost/T).toFixed(4)}`);
  // headings holding a one-rune word: in English that is A or I, so those are cribs
  const ones = unsolved.filter(r => r.shape.includes(1));
  console.log(`  headings containing a one-rune word (English: A or I): ${ones.length}`);
  for (const r of ones) {
    const at = r.start + r.shape.slice(0, r.shape.indexOf(1)).reduce((a, b) => a + b, 0);
    console.log(`    ${r.section} rune ${at} is a whole word by itself, ciphertext ${r.ct[at - r.start]}`);
  }
  ok('at least one heading gives a single-rune crib', ones.length >= 1);
}

/* ───── 8e. pages 49 to 51: the l / I dispute, decided by measurement ────── */
sec('8e. the token pages, and four characters the transcription has wrong');
{
  const T = JSON.parse(readFileSync(join(HERE, 'data/token-bars.json'), 'utf8'));
  const R = T.ruler;
  console.log(`  the grid's own ruler: x-height ${R.x_height} px, cap height ${R.cap} px, ascender ${R.ascender} px`);
  ok('x-height, cap height and ascender are three separated bands',
     R.x_height + 10 < R.cap && R.cap + 4 < R.ascender,
     `${R.x_height} < ${R.cap} < ${R.ascender}`);
  // the ruler must be built from characters that cannot be confused
  for (const [c, band] of [['o', 'x_height'], ['e', 'x_height'], ['D', 'cap'], ['E', 'cap'],
                           ['b', 'ascender'], ['d', 'ascender']]) {
    if (R.per_char[c] === undefined) continue;
    ok(`  '${c}' sits at the ${band.replace('_', ' ')}`,
       Math.abs(R.per_char[c] - R[band]) <= 3, `${R.per_char[c]} px`);
  }
  // a real L and a real 1 are not bars at all, which is what makes the reading safe
  ok("the transcription's L sits at cap height, so real Ls are cap height",
     Math.abs(R.per_char['L'] - R.cap) <= 3, `${R.per_char['L']} px`);
  ok("the transcription's 1 sits at cap height too",
     Math.abs(R.per_char['1'] - R.cap) <= 3, `${R.per_char['1']} px`);

  const bars = T.bars;
  ok('13 bare vertical bars on the three pages', bars.length === 13, `${bars.length}`);
  const dotted = bars.filter(b => b.dotted);
  console.log(`  of them, ${dotted.length} carry a dot and ${bars.length - dotted.length} do not`);
  ok('every dotted bar is transcribed as an i or a j',
     dotted.length > 0 && dotted.every(b => 'ij'.includes(b.says)),
     dotted.map(b => b.says).join(''));
  ok('and no bar transcribed as i or j is undotted except where flagged',
     bars.filter(b => 'ij'.includes(b.says) && !b.dotted)
         .every(b => T.corrections.some(c => c.x === b.x && c.page === b.page)));
  const undot = bars.filter(b => !b.dotted);
  ok('every undotted bar is at cap height or ascender height, nothing between',
     undot.every(b => Math.abs(b.h - R.cap) <= 3 || Math.abs(b.h - R.ascender) <= 3));
  ok('and every one of them is 7 or 8 px wide, far narrower than a real L',
     undot.every(b => b.w <= 8));

  console.log(`\n  characters the page reads differently from the transcription: ${T.corrections.length}`);
  for (const c of T.corrections)
    console.log(`    ${c.page} row ${c.row}: "${c.token}" should be "${c.token[0]}${c.verdict}"` +
                `  (${c.h} px, ${c.dotted ? 'dotted' : 'no dot'})`);
  ok('four corrections, and each is a bar whose height contradicts its label',
     T.corrections.length === 4 &&
     T.corrections.every(c => c.says !== c.verdict && !c.dotted));
  ok('two are L read for l, and two are l or i read for I',
     T.corrections.filter(c => c.says === 'L' && c.verdict === 'l').length === 2 &&
     T.corrections.filter(c => c.verdict === 'I').length === 2);
  // and the rest of the bars confirm the transcription, which is what makes it a
  // correction rather than a disagreement about method
  const agree = bars.filter(b => !b.dotted && b.says === b.verdict).length;
  ok('the other undotted bars agree with the transcription exactly',
     agree === undot.length - T.corrections.length, `${agree} agree`);
}

/* ───────────────── 8b. how the pages themselves were made ───────────────── */
sec('8b. the provenance of the page images');
{
  const P = JSON.parse(readFileSync(join(HERE, 'data/page-provenance.json'), 'utf8'));
  const nums = P.numbered.map(x => x.page).sort((a, b) => a - b);
  ok('the onion service served 58 numbered pages, 0 to 57 with no gaps',
     nums.length === 58 && nums.every((v, i) => v === i));
  ok('all 58 share one luma quantisation table',
     new Set(P.numbered.map(x => x.luma)).size === 1);
  ok('all 58 share one embedded ICC profile',
     new Set(P.numbered.map(x => x.icc)).size === 1 && P.numbered[0].icc);
  ok("that profile is Ghostscript's, so the book was rendered from a document, not scanned",
     /Artifex/.test(P.icc_desc || ''), P.icc_desc || '');
  ok('none of the 58 carries appended data',
     P.numbered.every(x => x.trailing === 0));
  const col = P.numbered.filter(x => x.ncomp === 3).length;
  console.log(`  the only per-page variation is colour (${col}) against greyscale (${58 - col}),`);
  console.log('  which the encoder picks by itself from the page content.');
  ok('the unnumbered pages have no embedded ICC profile',
     P.unnumbered.length > 0 && P.unnumbered.every(x => !x.icc),
     `${P.unnumbered.length} unnumbered pages, ${P.unnumbered.filter(x => x.icc).length} with the profile`);
  ok('two independent mirrors agree byte for byte where they overlap',
     Object.values(P.mirrors).every(v => v > 50), JSON.stringify(P.mirrors));
  const shared = P.unnumbered.filter(x => x.luma === P.numbered[0].luma).length;
  ok('three unnumbered luma tables, with eight pages sharing the numbered table',
     new Set(P.unnumbered.map(x => x.luma)).size === 3 && shared === 8);
  console.log('  these fingerprints do not establish one source document or rendering operation');
}

/* ──────────────────────── 9. the transcription audit ─────────────────────── */
sec('9. the independent OCR of the page scans');
{
  const raw = readFileSync(join(HERE, 'data/ocr-transcription.txt'), 'utf8').split('\n');
  let cur = null; const seq = {};
  for (const line of raw) {
    if (line.startsWith('##')) { cur = line.slice(2).trim().split(/\s+/)[0]; seq[cur] = []; continue; }
    if (line.startsWith('#') || !cur) continue;
    for (const ch of line) { if (R2I.has(ch)) seq[cur].push(R2I.get(ch)); else if (ch === '.') seq[cur].push(-1); }
  }
  let read = 0, tot = 0, disagree = 0, uread = 0, utot = 0;
  for (const b of Object.keys(LP)) {
    const a = seq[b] || [], t = LP[b].runes;
    ok(`${b}: the OCR stream is the same length as the transcription`, a.length === t.length,
       `${a.length} vs ${t.length}`);
    for (let i = 0; i < Math.min(a.length, t.length); i++) {
      tot++; if (UNSOLVED.includes(b)) utot++;
      if (a[i] < 0) continue;
      read++; if (UNSOLVED.includes(b)) uread++;
      if (a[i] !== t[i]) disagree++;
    }
  }
  console.log(`  glyphs read at the confidence bar: ${read} of ${tot} (${(100 * read / tot).toFixed(1)}%)`);
  console.log(`  on the unsolved pages:             ${uread} of ${utot} (${(100 * uread / utot).toFixed(1)}%)`);
  ok('the OCR read at least 97% of the corpus', read / tot > 0.97);
  ok('the OCR read at least 98% of the unsolved pages', uread / utot > 0.98, );
  ok('zero disagreements between the OCR and the transcription', disagree === 0, `${disagree}`);
}


/* ─────────────── 5a. the anatomy of the 86 that got through ──────────────── */
sec('5a. the anatomy of the 86 that got through');
// A suppression can be even-handed or it can be selective, and the two mean different
// things. If the 86 survivors cluster at word ends, or beside the book's own F
// interrupter, or on particular runes, that is a machine leaving fingerprints. The null
// here holds the COUNT at 86 and randomises only where they fall: the corpus-wide
// suppression is established elsewhere and is not what this section is testing.
{
  const UMK = UNSOLVED.flatMap(b => LP[b].marks);
  const blockOf = UNSOLVED.flatMap(b => LP[b].runes.map(() => b));
  const pool = [];
  for (let i = 0; i < US.length - 1; i++) if (blockOf[i] === blockOf[i + 1]) pool.push(i);
  const D = pool.filter(i => US[i] === US[i + 1]);
  ok('the 86 are all within a block, never across one', D.length === 86, `${D.length}`);
  let trip = 0;
  for (let i = 0; i + 2 < US.length; i++)
    if (US[i] === US[i + 1] && US[i + 1] === US[i + 2] && blockOf[i] === blockOf[i + 2]) trip++;
  ok('there is not one triple anywhere in the corpus', trip === 0, `${trip}`);

  const cnt = new Array(N).fill(0);
  for (const i of D) cnt[US[i]]++;
  const uni = new Array(N).fill(0);
  for (const x of US) uni[x]++;
  const p = uni.map(c => c / US.length);
  const w = p.map(v => v * v); const wt = w.reduce((a, b) => a + b, 0);
  let chi = 0;
  for (let x = 0; x < N; x++) { const e = D.length * w[x] / wt; chi += (cnt[x] - e) ** 2 / e; }
  console.log(`  which rune doubles: chi-square ${f3(chi)} on ${N - 1} df`);
  ok('the suppression is even-handed across the 29 runes (chi-square below the 1% point 49.6)',
     chi < 49.6, `chi2=${f3(chi)}`);

  const stats = {
    'straddles a separator': (ix) => ix.reduce((s, i) => s + (UMK[i] !== '' ? 1 : 0), 0),
    'ends a word':           (ix) => ix.reduce((s, i) => s + (UMK[i + 1] !== '' ? 1 : 0), 0),
    'starts a word':         (ix) => ix.reduce((s, i) => s + (i > 0 && UMK[i - 1] !== '' ? 1 : 0), 0),
    'has an F before it':    (ix) => ix.reduce((s, i) => s + (i > 0 && US[i - 1] === 0 ? 1 : 0), 0),
    'has an F after it':     (ix) => ix.reduce((s, i) => s + (i + 2 < US.length && US[i + 2] === 0 ? 1 : 0), 0),
  };
  const TR = 4000, rn = mulberry(860086);
  const idx = pool.slice();
  const draws = [];
  for (let t = 0; t < TR; t++) {
    for (let i = 0; i < D.length; i++) {
      const j = i + Math.floor(rn() * (idx.length - i));
      const s = idx[i]; idx[i] = idx[j]; idx[j] = s;
    }
    draws.push(idx.slice(0, D.length));
  }
  let worstZ = 0, worstName = '';
  for (const [name, fn] of Object.entries(stats)) {
    const obs = fn(D);
    let s = 0, ss = 0;
    for (const dr of draws) { const v = fn(dr); s += v; ss += v * v; }
    const mu = s / TR, sd = Math.sqrt(Math.max(ss / TR - mu * mu, 1e-12));
    const zz = (obs - mu) / sd;
    console.log(`  ${name.padEnd(24)} ${String(obs).padStart(3)} seen, ${mu.toFixed(1).padStart(5)} expected, z ${f3(zz)}`);
    if (Math.abs(zz) > Math.abs(worstZ)) { worstZ = zz; worstName = name; }
  }
  ok('none of the five structural positions is favoured beyond 3 sigma',
     Math.abs(worstZ) < 3, `worst: ${worstName}, z=${f3(worstZ)}`);
  const J = JSON.parse(readFileSync(join(HERE, 'data/doubles.json'), 'utf8'));
  ok('the stored anatomy agrees with this recomputation', J.doubles === D.length && J.rune_p > 0.01,
     `${J.doubles} doubles, rune p=${f3(J.rune_p)}`);
  ok('the 86 are spread evenly across the nine blocks', J.block_p > 0.01, `p=${f3(J.block_p)}`);
}

/* ──────── 6a. the period scan, taken past every order a permutation has ──── */
sec('6a. the period scan, taken past every order a permutation of 29 can have');
// Section 6 stops at 150. That is the right range for a KEY, and the wrong range for a
// progressive polyalphabetic, whose period is the order of the permutation relating
// consecutive alphabets. For 29 symbols that order can be as large as 2520, at cycle
// type 5+7+8+9. Both instruments here come off one table of lag coincidences, so they
// cannot drift apart: two runes share a coset at period L exactly when their distance
// is a multiple of L.
{
  const m = US.length;
  const eq = new Float64Array(m);
  for (let d = 1; d < m; d++) { let c = 0; for (let i = 0; i + d < m; i++) if (US[i] === US[i + d]) c++; eq[d] = c; }
  let kbest = 0, kbestL = 0;
  for (let L = 2; L <= 6400; L++) { const r = eq[L] / (m - L); if (r > kbest) { kbest = r; kbestL = L; } }
  let cbest = 0, cbestL = 0;
  for (let L = 2; L <= 2600; L++) {
    let e = 0, n2 = 0;
    for (let d = L; d < m; d += L) { e += eq[d]; n2 += m - d; }
    const v = N * e / n2; if (v > cbest) { cbest = v; cbestL = L; }
  }
  console.log(`  strongest kappa lag  ${String(kbestL).padStart(4)} at ${(100 * kbest).toFixed(3)}%  (chance 3.45%, a real period 6.1%)`);
  console.log(`  strongest coset period ${String(cbestL).padStart(4)} at IoC ${cbest.toFixed(4)}  (a real period 1.78)`);
  ok('no lag out to 6400 comes near the plaintext coincidence rate a period would show',
     kbest < 0.05, `${(100 * kbest).toFixed(3)}%`);
  ok('no period out to 2600 comes near a real periodic cipher',
     cbest < 1.20, `L=${cbestL} at ${cbest.toFixed(4)}`);
  const P = JSON.parse(readFileSync(join(HERE, 'data/long-periods.json'), 'utf8'));
  ok('the scan covers every possible order of a permutation of 29 symbols',
     P.lmax >= P.max_perm_order && P.max_perm_order === 2520, `scanned to ${P.lmax}`);
  ok('the recomputed kappa peak matches the stored scan',
     P.kappa_best_lag === kbestL && Math.abs(P.kappa_best_rate - kbest) < 1e-9,
     `lag ${kbestL}`);
  ok('the matched null peaks just as high, so the peak is the width of the scan',
     P.kappa_null_peak_max >= P.kappa_best_z, `book ${f3(P.kappa_best_z)}, null worst ${f3(P.kappa_null_peak_max)}`);
  ok('the whole kappa scan is not significant against the matched null', P.kappa_p > 0.05, `p=${f3(P.kappa_p)}`);
  ok('the coset scan is LESS peaked than the matched null', P.coset_p > 0.5, `p=${f3(P.coset_p)}`);
}

/* ─────── 7c. transposing the plaintext first does not lower the floor ────── */
sec('7c. a transposition in front of the cipher does not lower the floor');
// The additive bound assumes the runes are enciphered in written order. Shuffle them
// first and the relevant statistic is the difference distribution at whatever plaintext
// distance the shuffle brought together, so the bound as stated says nothing about it.
// Measured at every distance from 1 to 256 in every language, the minimum is at distance
// 1 every time: destroying adjacency pushes the distribution towards uniform and RAISES
// the floor. Transposition makes the book harder to explain, not easier.
{
  const T = JSON.parse(readFileSync(join(HERE, 'data/transposition-floors.json'), 'utf8'));
  ok('the transposition table measures the same 86 doubles', T.book.doubles === dbl);
  for (const r of T.languages) {
    const zz = (dbl - r.floor * npair) / Math.sqrt(npair * r.floor * (1 - r.floor));
    console.log(`  ${r.name.padEnd(28)} h=1 ${(100 * r.h1).toFixed(4)}%   best h=${String(r.best_h).padStart(3)}   independent limit ${(100 * r.indep_limit).toFixed(4)}%   z ${f3(zz)}`);
    ok(`  ${r.name}: no transposition distance beats writing order`, r.best_h === 1,
       `best h=${r.best_h}`);
    ok(`  ${r.name}: the recomputed z matches the table`, Math.abs(zz - r.z) < 0.02);
  }
  ok('destroying adjacency raises the floor in every language',
     T.languages.every(r => r.indep_limit > r.h1),
     `${T.languages.length} of ${T.languages.length}`);
  ok('the whole class stays above the book by 2.8 sigma at its weakest',
     T.languages.every(r => r.z < -2.8), `weakest ${T.weakest.name} at z=${f3(T.weakest.z)}`);
}

/* ── 7e. the same bound on the book's own plaintext, with its sample size shown ── */
sec("7e. the bound on the book's own plaintext, and how much 2977 runes can carry");
// Section 7 already measures the floor on the book's own plaintext and gets 1.31%, a
// z of -6.5. That number is a point estimate of a MINIMUM over 29 cells taken from 2976
// pairs, and quoting it without its uncertainty would be inference from an instrument
// narrower than the conclusion. Two things are therefore checked here that section 7
// does not: how much the interval around that minimum actually allows, and whether the
// book's own plaintext is even consistent with the English reference the main bound uses.
{
  const O = JSON.parse(readFileSync(join(HERE, 'data/own-plaintext-floor.json'), 'utf8'));
  ok('the same 86 doubles and 12955 pairs', O.book_doubles === dbl && O.book_pairs === npair);
  console.log(`  the book's plaintext is ${O.plaintext_runes} runes, ${O.plaintext_pairs} pairs`);
  console.log(`  its adjacent-difference distribution against English: chi2 ${f3(O.chi2_vs_english)} on 28 df, p ${O.p_vs_english.toExponential(1)}`);
  ok('the book\'s own plaintext is NOT the English reference, and this study says so',
     O.p_vs_english < 0.01, `p=${O.p_vs_english.toExponential(1)}`);
  console.log(`  floor, point estimate            ${(100 * O.floor_point).toFixed(4)}%   z ${f3(O.floor_point_z)}`);
  console.log(`  floor, 99.9% Bonferroni interval ${(100 * O.floor_lower_999).toFixed(4)}%   z ${f3(O.floor_lower_999_z)}`);
  ok('the point estimate is below the English floor, so the book\'s voice is spikier',
     O.floor_point < O.english_floor, `${(100 * O.floor_point).toFixed(4)}% vs ${(100 * O.english_floor).toFixed(4)}%`);
  ok('and the conservative interval does NOT exclude the book, which is stated rather than hidden',
     O.floor_lower_999 < dbl / npair, `interval reaches ${(100 * O.floor_lower_999).toFixed(4)}%`);
  console.log(`  direct test, an additive cipher over this plaintext: p ${O.direct_p_bonferroni.toExponential(1)} (corrected for 29 differences)`);
  ok('the direct test still puts an additive cipher below 1 in 100',
     O.direct_p_bonferroni < 0.01, `p=${O.direct_p_bonferroni.toExponential(1)}`);
  ok('so the strong exclusion rests on the 8.0M-rune reference, not on 2977 runes',
     O.direct_p_bonferroni > 1e-9);
}

/* ─────── 7d. nor does any fixed linear window over the plaintext ─────────── */
sec('7d. nor does any fixed linear window over the plaintext');
// The general form: c_i = sum_j a_j p_{i+j} + k_i, for any fixed coefficients over Z/29
// and any key stream at all. Then c_i = c_{i+1} needs sum_j a_j d_{i+j} to hit one value,
// where d is the plaintext's own first-difference sequence, so one number per coefficient
// vector bounds the whole class. a = (1) is the original additive bound; differencing,
// summing and every FIR filter of width up to 4 are in here too.
{
  const L = JSON.parse(readFileSync(join(HERE, 'data/linear-floors.json'), 'utf8'));
  ok('the linear sweep measures the same 86 doubles', L.book.doubles === dbl);
  console.log(`  coefficient vectors tried per language: ${L.vectors_per_language.toLocaleString()}`);
  for (const [name, r] of Object.entries(L.languages)) {
    const zz = (dbl - r.best_floor_full * npair) / Math.sqrt(npair * r.best_floor_full * (1 - r.best_floor_full));
    console.log(`  ${name.padEnd(28)} best width ${r.best_width}  vector [${r.best_vector.join(',')}]  floor ${(100 * r.best_floor_full).toFixed(4)}%  z ${f3(zz)}`);
    ok(`  ${name}: the identity window is already optimal`, r.best_width === 1,
       `width ${r.best_width}`);
    ok(`  ${name}: the recomputed z matches the table`, Math.abs(zz - r.best_z_full) < 0.02);
  }
  ok('no linear pre-transform in any language reaches the book',
     Object.values(L.languages).every(r => r.best_floor_full > dbl / npair));
}

/* ───── 8h. the longest red passage in the book, which the heading cap hid ──── */
sec('8h. the red passage the heading cap excluded, and the crib it carries');
// Section 8d finds section headings from the colour channel, and caps a heading at 34
// runes because a heading is short. That cap is right, and it means the LONGEST red
// passage in the Liber Primus is not in the section map. It is 51 runes on p53: the last
// 51 runes of the whole p40-53 block, four lines, starting mid-line straight after a
// comma, terminated by the four-dot chapter mark, with the cicada emblem printed beneath
// it. The next longest red passage anywhere in the book is 29 runes.
{
  const RP = JSON.parse(readFileSync(join(HERE, 'data/red-passages.json'), 'utf8'));
  const L = RP.longest;
  const others = RP.passages.filter(p => !(p.section === L.section && p.start === L.start));
  const runner = others.reduce((a, b) => (b.length > a.length ? b : a));
  console.log(`  longest red passage: ${L.section} ${L.start}..${L.end}, ${L.length} runes on ${L.jpg}`);
  console.log(`  next longest anywhere: ${runner.section}, ${runner.length} runes, reading ${runner.plain}`);
  ok('the longest red passage in the book is the 51 runes on p53',
     L.length === 51 && L.jpg === 'p53.jpg', `${L.length} runes`);
  ok('it is nearly twice the next longest', L.length > 1.7 * runner.length,
     `${L.length} vs ${runner.length}`);
  ok('it is the last passage of its block', L.tail === true);
  ok('it is closed by the four-dot chapter mark', L.terminator === '#', `${L.terminator}`);
  // the crib itself, recomputed from the corpus rather than trusted
  {
    const rs = UNSOLVED.flatMap(b => LP[b].runes.map((r, i) => [b, i, r]));
    const marks = LP['p40-53'].marks;
    const shape = []; let cur = 0;
    for (let i = L.start; i <= L.end; i++) { cur++; if (marks[i] && i < L.end) { shape.push(cur); cur = 0; } }
    shape.push(cur);
    ok('the word shape recomputes from the corpus', shape.join(',') === L.shape.join(','),
       `(${shape.join(',')})`);
    ok('twelve words, fifty-one runes', shape.length === 12 && shape.reduce((a, b) => a + b, 0) === 51,
       `${shape.length} words`);
    console.log(`  the crib: (${shape.join(', ')})`);
  }
  // what red means on the pages we can read: a heading or an instruction label, never body
  const solvedRed = RP.passages.filter(p => p.solved && p.plain);
  console.log(`  red passages whose plaintext is known: ${solvedRed.length}`);
  for (const p of solvedRed.slice().sort((a, b) => b.length - a.length).slice(0, 6))
    console.log(`    ${String(p.length).padStart(3)} runes  ${p.plain}`);
  // Red also marks the odd single glyph, which is a different device, so the claim is
  // made about passages of five runes or more. Each has to match one of the phrases the
  // book actually uses as a heading or an instruction label; the red run's own boundary
  // clips a leading rune here and there, hence the substring test rather than equality.
  const LABELS = ['ANINSTRUCTIANCOMMANDYOUROWNSELF', 'THELOSSOFDIUINITY', 'FORALLISSACRED',
                  'ANINSTRUCTIAN', 'PRESERUATIAN', 'CONSUMPTIAN', 'SOMEWISDOM', 'ADHERENCE',
                  'WELCOME', 'CNOWTHIS', 'PARABLE', 'AWARNNG', 'WIDSOM', 'ACOAN', 'ANEND'];
  const passages = solvedRed.filter(p => p.length >= 5);
  const singles  = solvedRed.filter(p => p.length < 5);
  const stray = passages.filter(p => !LABELS.some(L => L.includes(p.plain)));
  console.log(`  of those, ${passages.length} are passages of 5+ runes and ${singles.length} are single glyphs`);
  ok('every red passage of five runes or more is one of the book\'s headings or instruction labels',
     passages.length >= 20 && stray.length === 0,
     `${passages.length} passages, ${stray.length} unaccounted`);
  ok('so red never marks ordinary body text on any page we can read', stray.length === 0);
  const solvedLong = solvedRed.filter(p => p.length >= RP.threshold);
  ok('but only ONE of them is as long as a passage, so this is a prior and not a rule',
     solvedLong.length === 1, `n=${solvedLong.length}: ${solvedLong.map(p => p.plain).join('')}`);
}

/* ───── 8i. the twelve-word crib, against the book's own dictionary ────────── */
sec("8i. the crib on p53, and what the book's own vocabulary offers it");
// Word lengths in RUNES are the only lengths a rune-wise cipher preserves, so the shape
// of the p53 passage is a plaintext fact. A shape is a filter, not an answer. Two things
// are checked: what the book's own dictionary offers each slot, and how much the shape's
// absence from an English corpus is actually worth, which is nothing.
{
  const C = JSON.parse(readFileSync(join(HERE, 'data/crib-passage.json'), 'utf8'));
  const sections = readFileSync(join(HERE, 'data/solved-plaintext.txt'), 'utf8').split(/^## [^\n]*\n/m).slice(1);
  const words = sections.flatMap(s => s.replaceAll('\n', '').split(/[^\u16a0-\u16ff]+/).filter(Boolean));
  ok('physical wraps do not split plaintext words: 727 words, 269 distinct, 2977 runes',
     words.length === 727 && new Set(words).size === 269 && words.join('').length === 2977);
  ok('saved vocabulary and windows match the joined plaintext',
     C.own_words === words.length && C.own_distinct === new Set(words).size &&
     C.own_windows === words.length - C.shape.length + 1 &&
     Object.values(C.vocab).flat().sort().join(',') === [...new Set(words)].sort().join(','));
  const SHAPE = C.shape;
  ok('the crib is the twelve-word shape from 8h', SHAPE.length === 12 &&
     SHAPE.reduce((a, b) => a + b, 0) === 51, `(${SHAPE.join(',')})`);
  const vocab = C.vocab;
  const at = (n) => (vocab[String(n)] || []);
  for (const n of [...new Set(SHAPE)].sort((a, b) => a - b))
    console.log(`  ${String(n).padStart(2)}-rune words in the book's plaintext: ${at(n).length}`);
  ok('an eleven-rune word is the binding slot: the book has only three',
     at(11).length === 3, `${at(11).length}`);
  const eleven = at(11).map(w => [...w].length).length;
  ok('and every other slot has at least twenty candidates',
     SHAPE.filter(n => n !== 11).every(n => at(n).length >= 20));
  // the absence of the shape from English is worth exactly nothing, and this says so
  console.log(`  twelve-word windows searched in English: ${C.eng_windows.toLocaleString()}`);
  console.log(`  matches found: ${C.eng_match}; matches EXPECTED by chance: ${C.expected.toFixed(3)}`);
  ok('finding no English match is what chance predicts, so it is not evidence',
     C.eng_match === 0 && C.expected < 0.05,
     `expected ${C.expected.toFixed(3)}`);
  ok('the book\'s own plaintext does not contain the shape either, and that is also expected',
     C.own_match === 0 && C.own_windows < 1000, `${C.own_windows} windows`);
}

/* ─── 8j. attacking the book with a word list, and the controls that make it mean ─── */
sec('8j. the word-list attacks, and whether they can find the keys the book actually used');
// The book's Vigenere pages use short keys, so the obvious attack is every word in a
// dictionary, and it has been run for a decade. The question that makes such a result worth
// anything is whether the attack RECOVERS THE BOOK'S OWN KEYS, and section 3a shows why the
// naive form does not: the interrupter is invisible from the ciphertext, so past the first
// one the key drifts and a wrong key outscores the right one.
{
  const A = JSON.parse(readFileSync(join(HERE, 'data/key-attack.json'), 'utf8'));
  const S = A.summary;
  console.log(`  dictionary: ${S.dictionary_keys.toLocaleString()} distinct rune-keys`);
  // 1. the prefix attack must find both keys before its silence counts
  for (const c of A.prefix_controls)
    console.log(`  prefix control ${c.page.padEnd(12)} true key first: ${c.rank1}  z ${f3(c.true_z)}  "${String(c.reading).slice(0, 34)}"`);
  ok('the prefix attack recovers DIVINITY on 0_welcome from 48 runes',
     A.prefix_controls.some(c => c.page === '0_welcome' && c.rank1));
  // How much prefix it needs, and what actually breaks it. The interrupter count is
  // recomputed here from the plaintext rather than read from the stored file.
  if (A.prefix_lengths) {
    const intr = PT['0_welcome'].runes.map((r, i) => r === 0 ? i : -1).filter(i => i >= 0);
    console.log(`  0_welcome has ${intr.length} interrupters, the first at offset ${intr[0]}`);
    console.log(`  ${'prefix'.padStart(7)} ${'interrupters'.padStart(13)} ${'rank of DIVINITY'.padStart(17)} ${'z'.padStart(7)}`);
    const tbl = A.prefix_lengths.map(r => ({ ...r, inside: intr.filter(q => q < r.prefix).length }));
    for (const r of tbl)
      console.log(`  ${String(r.prefix).padStart(7)} ${String(r.inside).padStart(13)} ${String(r.rank).padStart(17)} ${f3(r.best_z).padStart(7)}`);
    const clean = tbl.filter(r => r.inside === 0 && r.prefix >= 24);
    ok('  with no interrupter inside, the true key is first from 24 runes up',
       clean.length > 0 && clean.every(r => r.rank === 1), `${clean.length} clean prefixes`);
    const few = tbl.filter(r => r.inside > 0 && r.inside <= 3);
    ok('  it survives one and even three interrupters, so the FIRST one is not what breaks it',
       few.length > 0 && few.every(r => r.rank === 1),
       few.map(r => `${r.prefix}:${r.inside} intr rank ${r.rank}`).join(', '));
    const whole = tbl[tbl.length - 1];
    ok('  but the whole page, with eleven, ranks the true key far down and returns a wrong key confidently',
       whole.inside > 5 && whole.rank > 10 && whole.best_z > 5,
       `${whole.prefix} runes, ${whole.inside} interrupters, rank ${whole.rank}, best z ${f3(whole.best_z)}`);
    const peak = tbl.reduce((a, b) => (b.best_z > a.best_z && b.rank === 1 ? b : a));
    ok('  and the score decays as interrupters accumulate, peaking on the clean prefix',
       peak.inside === 0, `peak at ${peak.prefix} runes with ${peak.inside} interrupters`);
  }
  // A z off a few dozen null draws is fragile, so the assertions use the empirical tail
  // fraction: how often the identical whole-dictionary search on message-free ciphertext
  // beats what it found on the book. That statistic does not depend on estimating a sd.
  console.log(`  null trials: ${S.null_trials} for the plain sweeps, ${S.subst_null_trials} for the substituted one`);
  const pb = A.prefix_blocks.map(r => r.p);
  const minp = Math.min(...pb), corrected = Math.min(1, minp * pb.length);
  const lowest = A.prefix_blocks.find(r => r.p === minp);
  console.log(`  the same attack on the nine unsolved block prefixes: smallest tail fraction p = ${f3(minp)} (${lowest.block}, key ${lowest.key}), corrected for ${pb.length} blocks p = ${f3(corrected)}`);
  ok('nothing on the unsolved block prefixes survives correction for the nine blocks tried',
     corrected > 0.05, `${f3(minp)} x ${pb.length} = ${f3(corrected)}`);
  // and the honest cross-check: the better-powered substituted sweep sees the same span as
  // unremarkable, which is what a multiple-comparisons artefact looks like from the far side
  const same = A.subst_blocks.find(r => r.block === lowest.block);
  console.log(`  and the larger substituted sweep puts ${lowest.block} at p = ${f3(same.p)}, so the low value above is the width of the scan`);
  ok('  the same block is unremarkable under the larger key space', same.p > 0.2, `p ${f3(same.p)}`);
  ok('  and none of their readings is English, which is the test that actually matters',
     A.prefix_blocks.every(r => !/WELCOME|PILGRIM|MASTER|INSTRUCTION|DIVINITY/.test(r.reading)));

  // 2. the substituted sweep, which is the one that covers BOTH of the book's key styles
  console.log(`  with every single global rune substitution: ${S.subst_keys.toLocaleString()} candidate keys`);
  for (const c of A.subst_controls)
    console.log(`  subst control ${c.page.padEnd(12)} want ${String(c.want).padEnd(22)} first: ${c.rank1}  z ${f3(c.true_z)}`);
  ok('the substituted sweep recovers BOTH of the book\'s keys at rank 1, including the one no dictionary holds',
     S.subst_controls_rank1 === 2, `${S.subst_controls_rank1} of 2`);
  ok('  and it reads out the real plaintext when it does',
     A.subst_controls.every(c => /WELCOME|COAN|MASTER|PILGRIM/.test(c.reading)),
     A.subst_controls.map(c => String(c.reading).slice(0, 18)).join(' | '));
  console.log(`  the same sweep on the nine unsolved block prefixes: smallest tail fraction p = ${f3(S.subst_min_p)}`);
  ok('no unsolved block prefix is a Vigenere under any of those 13.2 million keys',
     S.subst_min_p > 0.05, `smallest p ${f3(S.subst_min_p)}`);

  // 3. the p53 passage, where an unmodelled interrupter is the whole difficulty
  const withHyp = A.passage_controls.filter(c => c.hypothesis.length === c.inside.length);
  // An interrupter at the FINAL rune of a window shifts nothing after it, so withholding it
  // costs nothing and the true key still comes first. Only an interrupter strictly inside
  // breaks the phase for the runes that follow, which is the case the claim is about.
  const WIN = 51;
  const without = A.passage_controls.filter(c => c.hypothesis.length === 0 &&
                                                 c.inside.some(q => q < WIN - 1));
  for (const c of A.passage_controls)
    console.log(`  passage control @${c.offset}: interrupters inside [${c.inside}] hypothesis [${c.hypothesis}] -> true key first ${c.rank1}, z ${f3(c.true_z)}`);
  ok('supplying the interrupter hypothesis recovers the true key',
     withHyp.length > 0 && withHyp.every(c => c.rank1));
  ok('there is a control where an interrupter falls strictly inside the window', without.length > 0);
  if (without.length) {
    ok('withholding it there loses the true key entirely, which is why the hypothesis must be enumerated',
       without.every(c => !c.rank1 && c.true_z < -3),
       without.map(c => `@${c.offset} z ${f3(c.true_z)}`).join(' '));
    const paired = withHyp.filter(c => without.some(w => w.offset === c.offset));
    ok('  and supplying it on that same window recovers the key, a swing of about twenty sigma',
       paired.every(c => c.rank1 && c.true_z > 5),
       paired.map(c => `@${c.offset} z ${f3(c.true_z)}`).join(' '));
  }
  const pz = A.passage.map(r => r.z);
  const pp = A.passage.map(r => r.p);
  console.log(`  the p53 red passage, ${A.passage.length} interrupter hypotheses: best z ${f3(Math.max(...pz))}, smallest tail fraction p = ${f3(Math.min(...pp))}`);
  ok('the p53 passage does not stand out from message-free ciphertext either',
     Math.min(...pp) > 0.01, `smallest p ${f3(Math.min(...pp))}`);
  // Recompute the span's ciphertext-F positions from the corpus. A collaborator's run of
  // the same search reported this position as 41 while printing a ciphertext whose F is at
  // 38, which would have removed the wrong rune from every interrupter hypothesis. The
  // positions are cheap to derive, so they are derived rather than read.
  {
    const span = LP['p40-53'].runes.slice(2957, 3008);
    const F = span.map((r, i) => r === 0 ? i : -1).filter(i => i >= 0);
    ok('the p53 span is 51 runes with a single ciphertext F, recomputed here',
       span.length === 51 && F.length === 1, `${span.length} runes, F at [${F}]`);
    const used = new Set(A.passage.flatMap(r => r.hypothesis));
    ok('and the hypotheses tried are exactly the subsets of that position',
       A.passage.length === Math.pow(2, F.length) &&
       [...used].every(q => F.includes(q)) && F.every(q => used.has(q)),
       `tried [${[...used]}], span has [${F}]`);
  }
  ok('every interrupter hypothesis for the p53 passage was tried',
     A.passage.length === Math.pow(2, A.passage[0] ? A.passage.filter(r => r.hypothesis.length === 1).length : 0) ||
     A.passage.length >= 2, `${A.passage.length}`);
  ok('the longest red passage in the book is not a Vigenere under any dictionary word, at any phase, under either hypothesis',
     Math.max(...pz) < 3.5, `best z ${f3(Math.max(...pz))}`);
  const trueBand = A.passage_controls.filter(c => c.rank1).map(c => c.true_z);
  ok('and a TRUE key on the same instrument scores far higher, so that silence is informative',
     Math.min(...trueBand) > Math.max(...pz), `true keys ${trueBand.map(f3).join(', ')} vs best ${f3(Math.max(...pz))}`);
}

/* ── 8k. every periodic key a crib admits, enumerated exactly rather than sampled ── */
sec('8k. the periodic keys the cribs admit, counted exactly');
// A crib gives the word-length shape of a span, and that shape FORCES THE KEY: a word of
// length L at offset o fixes k[(o+i) mod p] for every i, so one word determines a period-p
// key entirely and any inconsistency rejects it. Iterating dictionary words therefore
// enumerates the whole family exactly, where brute-forcing key streams would not: the
// deepest crib here stands for 3.66e17 streams.
//
// The scope is set by the crib's LONGEST word, since that is what can pin the key. And a
// period EQUAL to that length is degenerate: the anchor pins the key with no redundancy
// left, so a hit is guaranteed whenever the other words happen to be words. Only periods
// strictly below the anchor length carry information, and the verdicts respect that.
{
  const C = JSON.parse(readFileSync(join(HERE, 'data/crib-periods.json'), 'utf8'));
  ok('the control ran on the published headings', C.control_reachable > 10, `${C.control_reachable} reachable`);
  console.log(`  control: the true plaintext recovered on ${C.control_found} of ${C.control_reachable} headings whose true period the anchor can reach`);
  ok('the method recovers EVERY known heading it can reach, so a clean verdict means something',
     C.control_found === C.control_reachable, `${C.control_found}/${C.control_reachable}`);
  const atbash = C.control.filter(c => c.true_period === 1 && c.reachable);
  ok('  including the Atbash pages, which a sign error on the Beaufort key silently loses',
     atbash.length > 0 && atbash.every(c => c.found), `${atbash.length} Atbash headings`);

  const useful = C.cribs.filter(r => r.longest_word >= 5);
  console.log(`  ${'crib'.padEnd(10)} ${'len'.padStart(4)} ${'anchor'.padStart(7)} ${'periods'.padStart(8)} ${'streams'.padStart(24)}  survivors below the anchor`);
  for (const r of useful)
    console.log(`  ${r.section.padEnd(10)} ${String(r.length).padStart(4)} ${String(r.longest_word).padStart(7)} ${('1..'+r.longest_word).padStart(8)} ${r.equivalent_streams.toLocaleString().padStart(24)}  ${r.survivors_below_anchor}`);
  const clean = useful.filter(r => r.survivors_below_anchor === 0);
  ok('with the tested dictionary, at least five cribs admit no periodic key below their anchor',
     clean.length >= 5, `${clean.length} of ${useful.length}`);

  const p53 = C.cribs.find(r => r.section === 'p40-53');
  ok('the 51-rune red passage is one of them, and admits none at ANY period up to 11',
     p53 && p53.survivors === 0 && p53.longest_word === 11,
     `${p53.survivors} survivors, anchor ${p53.longest_word}`);
  console.log(`  the p53 passage stands for ${p53.equivalent_streams.toLocaleString()} key streams and admits none`);
  ok('  and it is the longest crib, so its shape is the most constraining',
     p53.length === 51 && p53.shape.length === 12);

  // the degenerate cases are reported as degenerate rather than as hits
  const deg = useful.filter(r => r.survivors_below_anchor === 0 && r.survivors > 0);
  for (const r of deg)
    console.log(`  ${r.section}@${r.start}: clean below ${r.degenerate_period}, ${r.per_period[r.per_period.length-1]} degenerate hits AT ${r.degenerate_period}`);
  ok('degenerate-period hits are separated from real ones', deg.every(r => r.survivors > 0));

  // the aperiodic family: the same prime running key p56 uses, at every starting offset
  if (C.prime_key) {
    ok('the prime-key control finds p56\'s own heading at offset 0',
       C.prime_control.some(([off, txt]) => off === 0 && txt === 'ANEND'),
       `${C.prime_control.length} offsets fit that heading`);
    const big = C.prime_key.filter(r => {
      const crib = C.cribs.find(x => x.section === r.section && x.start === r.start);
      return crib && crib.length >= 8;
    });
    console.log(`  the prime running key against ${big.length} cribs of 8+ runes, 2000 starting offsets each: ${big.reduce((a, r) => a + r.hits, 0)} fits`);
    ok('no crib of 8 runes or more is the prime running key at any offset',
       big.every(r => r.hits === 0), big.filter(r => r.hits).map(r => r.section).join(',') || 'none');
  }

  const total = useful.reduce((a, r) => a + r.equivalent_streams, 0);
  console.log(`  summed over those cribs the family enumerated is ${total.toLocaleString()} key streams`);
  ok('the enumeration stands for more than 1e17 key streams', total > 1e17);
}

/* ─── 8l. aperiodic keys: the family the book itself demonstrates ──────────── */
sec('8l. aperiodic keys, swept over the family the book itself uses');
// Everything in 8k is about PERIODIC keys, and section 3b is the reason that is not enough:
// p56_an_end uses a running key of the primes, which is aperiodic. So the natural hypothesis
// class is not "an arbitrary stream" but "a stream a puzzle-setter would choose", and the
// book has already shown one member. Three families are swept, tested by exact dictionary
// segmentation rather than by score, so no null is required.
//
// Note what this does and does NOT add. Every stream here is ADDITIVE, and section 7 already
// excludes additive ciphers statistically at 9.8 sigma. The value is that this is an
// instrument using different measurements: crib shapes and an English dictionary,
// rather than the doubles anomaly and an English bigram reference. They share an
// additive model and linguistic assumptions.
{
  const A = JSON.parse(readFileSync(join(HERE, 'data/aperiodic.json'), 'utf8'));
  console.log(`  ${A.sequences.length} integer sequences, ${A.texts.length} text running keys, ${A.offsets} offsets, ${A.sequence_trials_per_crib.toLocaleString()} sequence trials per crib`);
  ok('the real control holds: the prime sequence recovers p56\'s own heading at offset 0',
     A.control_prime_offset0 === true);
  ok('and the synthetic controls hold: a known plaintext re-enciphered with a sequence is found blind',
     A.synthetic_n > 0 && A.synthetic_ok === A.synthetic_n,
     `${A.synthetic_ok} of ${A.synthetic_n}`);
  // only cribs with a reasonably long anchor can say anything; a 3-rune span fits everything
  const shapeOf = (r) => (A.sequences_result.find(x => x.section === r.section && x.start === r.start) || {}).shape || [];
  const useful = A.sequences_result.filter(r => Math.max(...r.shape) >= 6);
  console.log(`  cribs whose longest word is 6 runes or more: ${useful.length} of ${A.sequences_result.length}`);
  for (const r of useful)
    console.log(`    ${r.section}@${r.start} (${r.length} runes, longest word ${Math.max(...r.shape)}): ${r.hits} sequence fits`);
  ok('no integer-sequence running key fits any crib with a 6-rune word or longer',
     useful.every(r => r.hits === 0), useful.filter(r => r.hits).map(r => r.section).join(',') || 'none');
  const tex = A.texts_result.filter(r => useful.some(u => u.section === r.section && u.start === r.start));
  ok('nor does any text running key drawn from the book itself',
     tex.every(r => r.hits === 0), tex.filter(r => r.hits).map(r => r.section).join(',') || 'none');
  const p53s = A.sequences_result.find(r => r.section === 'p40-53');
  const p53t = A.texts_result.find(r => r.section === 'p40-53');
  ok('the 51-rune red passage admits neither, at any offset or constant',
     p53s.hits === 0 && p53t.hits === 0, `${p53s.hits} sequence, ${p53t.hits} text`);
  const worst = Math.max(...A.autokey.map(r => r.ioc));
  console.log(`  ciphertext autokey, primer lengths 1 to 40: best normalised IoC anywhere ${f3(worst)} (English runic is 1.78)`);
  ok('ciphertext autokey produces nothing like English at any primer length', worst < 1.3, `${f3(worst)}`);
}

/* ── 8m. is there a SECOND channel in the images, as the colour one was? ────── */
sec('8m. the glyph metrics, and whether the images carry a second channel');
// The one genuine find in this study came out of the images rather than the rune stream, so
// it is fair to ask whether they hold more. These pages were rendered by Ghostscript, not
// scanned, which makes the question sharp: one font at one size should give about 29 distinct
// glyph shapes, and any systematic departure would be a channel exactly as the red ink is.
//
// The answer is no, and the interesting part is how nearly it came out yes. A one-pixel width
// variation exists and its bit sequence looks strongly structured. That structure is rune
// identity leaking through an imperfect shape clustering: in every testable class the narrow
// and wide members are DIFFERENT runes, not one rune drawn a pixel apart.
{
  const G = JSON.parse(readFileSync(join(HERE, 'data/glyph-channel.json'), 'utf8'));
  console.log(`  ${G.glyphs.toLocaleString()} body glyphs off ${G.pages} rendered pages: ${G.distinct_sizes} distinct sizes, ${G.distinct_bitmaps} distinct exact bitmaps`);
  ok('the pages hold far more than 29 distinct bitmaps, so something varies',
     G.distinct_bitmaps > 100, `${G.distinct_bitmaps}`);
  console.log(`  baseline: ${(100*G.baseline_on_zero).toFixed(1)}% of glyphs sit exactly on it, over ${G.baseline_distinct} distinct offsets`);
  const bat = Object.fromEntries(G.channel_battery.map(r => [r.name, r]));
  const red = bat['RED INK (control)'];
  const wid = bat['width within a rune'];
  ok('the control is present: the battery detects the known red channel',
     red && Math.max(Math.abs(red.z_bias), Math.abs(red.z_lag1), Math.abs(red.z_runs)) > 50,
     red ? `|z| ${f3(Math.max(Math.abs(red.z_bias), Math.abs(red.z_lag1), Math.abs(red.z_runs)))}` : 'missing');
  const wz = Math.max(Math.abs(wid.z_bias), Math.abs(wid.z_lag1), Math.abs(wid.z_runs));
  console.log(`  the width bit scores |z| ${f3(wz)}, which taken alone would look like a channel`);
  ok('but in every testable shape class the narrow and wide members are DIFFERENT runes',
     G.classes_different_glyphs > 10 && G.classes_same_glyph === 0,
     `${G.classes_different_glyphs} different, ${G.classes_same_glyph} same`);
  ok('  so the width bit is rune identity, and the study says so rather than claiming a channel',
     G.classes_same_glyph === 0);
  const ratios = G.class_shape_test.map(r => r.between / Math.max(r.within, 1e-9));
  console.log(`  between-group over within-group shape distance: median ${f3(ratios.sort((a,b)=>a-b)[Math.floor(ratios.length/2)])}, minimum ${f3(Math.min(...ratios))}`);
  ok('  and the separation is not marginal in any class', Math.min(...ratios) > 4);
}

/* ── 8f. the smallest generator that could produce the corpus, and its controls ── */
sec('8f. three numbers, and whether anything can tell them from the book');
// Write down the smallest generator that could produce the unsolved corpus: its length,
// its rune frequencies, and one repeat-suppression factor. No plaintext, no key, no
// structure. Then try hard to separate the two with eleven statistics.
//
// Two of the eleven are FITTED by the generator and cannot fail, so they are excluded
// from the verdict. The rest could fail, and the controls prove they do: the same battery
// and the same matched-null procedure are run on real English, on Vigeneres of key length
// 20 and 300, on a running key and on a one-time pad. A battery that cannot flag a
// Vigenere is not a test, and its verdict on the book would be worth nothing.
{
  const C = JSON.parse(readFileSync(join(HERE, 'data/complete-model.json'), 'utf8'));
  const R = C.results;
  ok('the battery was run on the whole unsolved corpus', C.runes === US.length, `${C.runes}`);
  const worstOf = (k) => R[k] ? R[k].worst : null;
  for (const [name, v] of Object.entries(R))
    console.log(`  ${name.padEnd(36)} worst unfitted: ${String(v.worst[0]).padEnd(42)} z ${f3(v.worst[1])}`);
  const teeth = ['English plaintext, no cipher', 'Vigenere, key length 20', 'Vigenere, key length 300'];
  for (const t of teeth)
    ok(`  the battery detects ${t}`, worstOf(t) && Math.abs(worstOf(t)[1]) > 20,
       `z=${f3(worstOf(t)[1])}`);
  ok('  it detects a 300-long Vigenere, which section 6 alone would have missed',
     Math.abs(worstOf('Vigenere, key length 300')[1]) > 20);
  const bk = worstOf('unsolved Liber Primus');
  ok('the book is not separated from the three-parameter generator by any statistic',
     Math.abs(bk[1]) < 3, `worst: ${bk[0]}, z=${f3(bk[1])}`);
  // the honest qualifier, asserted rather than asserted-in-prose
  for (const t of ['running key (English on English)', 'one-time pad (true random key)'])
    ok(`  ${t} also passes, so passing is NOT evidence of no message`,
       Math.abs(worstOf(t)[1]) < 3, `z=${f3(worstOf(t)[1])}`);
  const fitted = R['unsolved Liber Primus'].rows.filter(r => r[5]).length;
  ok('exactly two of the eleven statistics are fitted, and both are excluded from the verdict',
     fitted === 2 && R['unsolved Liber Primus'].rows.length === 11, `${fitted} fitted of ${R['unsolved Liber Primus'].rows.length}`);
}

/* ────── 8g. the base the token block is written in, decided from the page ── */
sec('8g. what base the token block on pages 49 to 51 is written in');
// The community reads those 256 tokens in bases 59 through 64. The base is decidable,
// and the argument rests on the seventeen tokens whose first character is the largest
// one present: under a byte ceiling their second digits are constrained and under a
// larger base with the same byte ceiling, the observed digit 15 is too large.
{
  const T = JSON.parse(readFileSync(join(HERE, 'data/token-decodings.json'), 'utf8'));
  const AL = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
  ok('the alphabet is the natural ordering, digits then upper then lower',
     AL.startsWith(T.alphabet) && T.alphabet.length === T.base);
  ok('the base is 60', T.base === 60, `${T.base}`);
  ok('the 256 values are exactly the byte range', T.values.length === 256 &&
     Math.min(...T.values) === 0 && Math.max(...T.values) === 255);
  const grid = JSON.parse(readFileSync(join(HERE, 'data/token-grid-corrected.json'), 'utf8'));
  const values = grid.grid.flat(2).map(t => AL.indexOf(t[0]) * T.base + AL.indexOf(t[1]));
  ok('the decoded bytes match every corrected grid token',
     values.length === 256 && values.every((v, i) => v === T.values[i]));
  ok('p50 row 11 token 4 is capital S, base-60 value 148',
     grid.grid[1][11][4] === '2S' && values[172] === 148);
  ok('the binary download matches the decoded values',
     Buffer.from(T.values).equals(readFileSync(join(HERE, 'data/token-block.bin'))));
  const k = T.top_token_count, hi = T.top_token_max_second_digit;
  const pAlt = Math.pow((hi + 1) / 61, k);
  console.log(`  ${k} tokens lead with the largest first character; their second digits reach ${hi}`);
  console.log(`  base 60 forces that (4*60+${hi} = ${4 * 60 + hi}); unrestricted uniform base-61 digits give probability ${pAlt.toExponential(2)}`);
  ok('under unrestricted uniform base-61 digits, the tail probability is below 1e-9', pAlt < 1e-9, `${pAlt.toExponential(2)}`);
  ok('every symbol used lies inside the base-60 alphabet', T.unused_symbol.length <= 2);
  ok('leading-digit frequencies match a uniform byte source', T.lead_p > 0.05, `p=${f3(T.lead_p)}`);
  ok('no reading of the grid gives a prime, so it is not RSA key material',
     T.prime_hits.length === 0, `${T.orderings} readings tried`);
  const dist = new Set(T.values).size;
  console.log(`  ${dist} distinct byte values of 256; 256 uniform random bytes average 161.9`);
  ok('the block is indistinguishable from 256 uniform random bytes',
     Math.abs(dist - 161.9) < 12 && T.entropy > 7.0, `${dist} distinct, entropy ${f3(T.entropy)}`);
}

/* ─────────────────────────────────────────────────────────────────────────── */
console.log('\n' + (fails ? `FAILED: ${fails} check(s)` : 'all checks passed'));
process.exit(fails ? 1 : 0);
