#!/usr/bin/env node
// verify-where-a-word-breaks.mjs
//
// Re-derives every figure the page prints, from the pattern files and word
// lists, and then reads the SHIPPED PAGE and requires the derived value to
// appear in it. A verifier that only recomputes its own numbers and never looks
// at the page cannot catch the failure that actually happens, which is prose
// drifting away from a rerun.
//
//   node verify-where-a-word-breaks.mjs
//   node verify-where-a-word-breaks.mjs --tex     (also re-run the TeX differential)
//
// Exits 0 only if every check passes.

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

import { parsePatternFile, hyphenate, spell, legalPositions, DEFAULT_LEFT_MIN, DEFAULT_RIGHT_MIN }
  from './public/strata/where-a-word-breaks/hyphenate.mjs';
import { initialSeam, finalSeam, medialClusters, INITIAL_FORMS, FINAL_FORMS }
  from './public/strata/where-a-word-breaks/forms.mjs';

const ROOT = path.dirname(fileURLToPath(import.meta.url));
const PAGE_DIR = path.join(ROOT, 'public', 'strata', 'where-a-word-breaks');
const LAB_DIR = path.join(ROOT, 'research', 'hyphenation');

let pass = 0, fail = 0;
const failures = [];
function ok(name, cond, detail) {
  if (cond) { pass++; console.log(`  ok   ${name}${detail ? '  · ' + detail : ''}`); }
  else { fail++; failures.push(name + (detail ? '  · ' + detail : '')); console.log(`  FAIL ${name}${detail ? '  · ' + detail : ''}`); }
}
const approx = (a, b, tol) => Math.abs(a - b) <= tol;

// ---------------------------------------------------------------------------
// Load everything, and prove the loader is pointed at real data before trusting
// any zero it produces.
// ---------------------------------------------------------------------------
const HTML = fs.readFileSync(path.join(PAGE_DIR, 'index.html'), 'utf8');
const PAGE_JS = fs.readFileSync(path.join(PAGE_DIR, 'page.js'), 'utf8');
const MD = fs.readFileSync(path.join(ROOT, 'src', 'content', 'strata', 'where-a-word-breaks.md'), 'utf8');

console.log('\n· the instrument can return a positive ·');
ok('the page HTML is non-trivial', HTML.length > 20000, `${HTML.length} bytes`);
ok('a control string known to be in the page is found', HTML.includes('Where a Word May Break'));
ok('a control string known NOT to be in the page is not found', !HTML.includes('zzzznotpresentzzzz'));

const dataJs = fs.readFileSync(path.join(PAGE_DIR, 'data.js'), 'utf8');
ok('data.js ships the pattern files', dataJs.includes('PATTERN_FILES') && dataJs.length > 400000, `${(dataJs.length / 1024).toFixed(0)} KB`);

// The page's data module, imported rather than regexed.
const DATA = await import('./public/strata/where-a-word-breaks/data.js');
const MODELS = {};
for (const [id, text] of Object.entries(DATA.PATTERN_FILES)) MODELS[id] = parsePatternFile(text);
const LEX = DATA.SHARED_LEXICON.split('\n');

// The shipped pattern text must be byte-identical to the lab's source files.
for (const [id, file] of [['liang-1983', 'liang-1983-hyphen.tex'], ['en-us', 'hyph-en-us.tex'], ['en-gb', 'hyph-en-gb.tex']]) {
  const onDisk = fs.readFileSync(path.join(LAB_DIR, 'data', file), 'utf8');
  ok(`${id}: the page ships the lab's file byte for byte`, DATA.PATTERN_FILES[id] === onDisk);
}

// ---------------------------------------------------------------------------
// The engine's canonical answers, and that the page prints them
// ---------------------------------------------------------------------------
console.log('\n· the engine ·');
const CANON = [
  ['hyphenation', 'en-us', 'hy-phen-ation'],
  ['concatenation', 'en-us', 'con-cate-na-tion'],
  ['democracy', 'en-us', 'democ-racy'],
  ['democracy', 'en-gb', 'demo-cracy'],
  ['typography', 'en-us', 'ty-pog-ra-phy'],
  ['typography', 'en-gb', 'ty-po-graphy'],
  ['information', 'en-us', 'in-for-ma-tion'],
  ['information', 'en-gb', 'in-form-a-tion'],
  ['technology', 'en-us', 'tech-nol-ogy'],
  ['technology', 'en-gb', 'tech-no-logy'],
  ['security', 'en-us', 'se-cu-rity'],
  ['security', 'en-gb', 'se-cur-ity'],
  ['atmosphere', 'en-us', 'at-mos-phere'],
  ['atmosphere', 'en-gb', 'at-mo-sphere'],
  ['academically', 'en-us', 'aca-d-e-m-i-cally'],
  ['academically', 'liang-1983', 'aca-dem-i-cally'],
  ['fisherman', 'en-us', 'fish-er-man'],
];
for (const [w, m, want] of CANON) {
  const got = spell(w, hyphenate(w, MODELS[m]));
  ok(`${m}: ${w} → ${want}`, got === want, got === want ? '' : `got ${got}`);
}
// every canonical spelling the PROSE quotes must be one the engine produces
for (const [, , want] of CANON) {
  if (!HTML.includes(want)) continue;
  ok(`the page quotes ${want} and the engine agrees`, true);
}
for (const quoted of ['hy-phen-ation', 'democ-racy', 'demo-cracy', 'in-for-ma-tion', 'in-form-a-tion',
  'tech-nol-ogy', 'tech-no-logy', 'se-cu-rity', 'se-cur-ity', 'at-mos-phere', 'at-mo-sphere',
  'aca-d-e-m-i-cally', 'aca-dem-i-cally', 'fisher-m-an', 'of-f-load', 'of-fload', 'pre-sent', 'pro-ject']) {
  ok(`the page still contains the string ${quoted}`, HTML.includes(quoted));
}

// ---------------------------------------------------------------------------
// Counts
// ---------------------------------------------------------------------------
console.log('\n· the files ·');
const us = MODELS['en-us'], gb = MODELS['en-gb'], liang = MODELS['liang-1983'];
ok('en-us has 4,938 patterns', us.patterns.size === 4938, String(us.patterns.size));
ok('en-gb has 8,527 patterns', gb.patterns.size === 8527, String(gb.patterns.size));
ok('Liang 1983 has 4,447 patterns', liang.patterns.size === 4447, String(liang.patterns.size));
ok('en-us has 14 exceptions', us.exceptions.size === 14);
ok('en-gb has 8 exceptions', gb.exceptions.size === 8);
ok('the page states 4,938', HTML.includes('4,938'));
ok('the page states 8,527', HTML.includes('8,527'));
ok('the page states 4,447', HTML.includes('4,447'));

let contained = 0;
for (const [k, v] of liang.patterns) if (us.patterns.get(k) === v) contained++;
ok('en-us contains every 1983 pattern byte for byte', contained === liang.patterns.size, `${contained}/${liang.patterns.size}`);
ok('en-us adds exactly 491', us.patterns.size - liang.patterns.size === 491);
ok('the page states 491', HTML.includes('491'));

// ---------------------------------------------------------------------------
// The lexicon, rebuilt from the word lists rather than trusted from data.js
// ---------------------------------------------------------------------------
console.log('\n· the lexicon ·');
function lexiconFrom(text) {
  const kept = [], seen = new Set();
  for (const raw of text.split(/\r?\n/)) {
    const w = raw.trim();
    if (!w) continue;
    if (/[A-Z]/.test(w) || w.includes("'") || w.includes('’') || w.includes('-') || /[0-9]/.test(w)) continue;
    if (!/^[a-z]+$/.test(w)) continue;
    if (w.length < 5) continue;
    if (seen.has(w)) continue;
    seen.add(w); kept.push(w);
  }
  return kept.sort();
}
const lexA = lexiconFrom(fs.readFileSync(path.join(LAB_DIR, 'data', 'wordlist-american.txt'), 'utf8'));
const lexB = lexiconFrom(fs.readFileSync(path.join(LAB_DIR, 'data', 'wordlist-british.txt'), 'utf8'));
const setB = new Set(lexB);
const shared = lexA.filter(w => setB.has(w));
ok('the American lexicon is 60,630 words', lexA.length === 60630, String(lexA.length));
ok('the British lexicon is 60,265 words', lexB.length === 60265, String(lexB.length));
ok('they share 58,739', shared.length === 58739, String(shared.length));
ok('the page ships exactly that shared lexicon', LEX.length === shared.length && LEX.every((w, i) => w === shared[i]));
ok('the page states 58,739', HTML.includes('58,739'));
const union = Array.from(new Set([...lexA, ...lexB]));
ok('the union is 62,156', union.length === 62156, String(union.length));
ok('the page states 62,156', HTML.includes('62,156'));

// ---------------------------------------------------------------------------
// The headline
// ---------------------------------------------------------------------------
console.log('\n· the headline ·');
let identical = 0, differ = 0, usBreaks = 0, gbBreaks = 0, legal = 0, unbUs = 0, unbGb = 0;
const seams = {
  initial: { words: 0, usSeam: 0, gbSeam: 0, gbOnly: 0, usOnly: 0 },
  final: { words: 0, usSeam: 0, gbSeam: 0, gbOnly: 0, usOnly: 0 },
  cluster: { usOnlySplits: 0, gbOnlySplits: 0 },
};
for (const w of shared) {
  const pu = hyphenate(w, us), pg = hyphenate(w, gb);
  usBreaks += pu.length; gbBreaks += pg.length; legal += legalPositions(w.length);
  if (!pu.length) unbUs++;
  if (!pg.length) unbGb++;
  const differs = pu.join(',') !== pg.join(',');
  if (differs) differ++; else identical++;
  const su = new Set(pu), sg = new Set(pg);
  for (const [key, seam] of [['initial', initialSeam(w)], ['final', finalSeam(w)]]) {
    if (seam < 0) continue;
    const o = seams[key];
    o.words++;
    const u = su.has(seam), g = sg.has(seam);
    if (u) o.usSeam++;
    if (g) o.gbSeam++;
    if (g && !u) o.gbOnly++;
    if (u && !g) o.usOnly++;
  }
  if (!differs) continue;
  for (const [a, b] of medialClusters(w)) {
    const iu = pu.some(p => p > a && p < b), ig = pg.some(p => p > a && p < b);
    if (iu && !ig) seams.cluster.usOnlySplits++;
    if (ig && !iu) seams.cluster.gbOnlySplits++;
  }
}
const differRate = differ / shared.length;
ok('the disagreement rate is 35.63%', approx(differRate, 0.3563, 0.00005), (100 * differRate).toFixed(2) + '%');
ok('the page states 35.63%', HTML.includes('35.63%'));
ok('the American set allows 1.257 breaks per word', approx(usBreaks / shared.length, 1.257, 0.0005), (usBreaks / shared.length).toFixed(3));
ok('the British set allows 1.229', approx(gbBreaks / shared.length, 1.229, 0.0005), (gbBreaks / shared.length).toFixed(3));
ok('the page states both', HTML.includes('1.257') && HTML.includes('1.229'));
ok('P1 died: the American set really is the more permissive', usBreaks > gbBreaks);
ok('the page says the prediction died', /\bwrong\b/i.test(HTML) && HTML.includes('P1 died'));
ok('13,720 words the American set will not break', unbUs === 13720, String(unbUs));
ok('14,532 words the British set will not break', unbGb === 14532, String(unbGb));
ok('the page states both', HTML.includes('13,720') && HTML.includes('14,532'));
ok('share of legal positions: US 28.06%', approx(usBreaks / legal, 0.2806, 0.00005), (100 * usBreaks / legal).toFixed(2) + '%');
ok('share of legal positions: GB 27.45%', approx(gbBreaks / legal, 0.2745, 0.00005), (100 * gbBreaks / legal).toFixed(2) + '%');

// ---------------------------------------------------------------------------
// The direction
// ---------------------------------------------------------------------------
console.log('\n· the direction ·');
ok('80 initial combining forms', INITIAL_FORMS.length === 80, String(INITIAL_FORMS.length));
ok('37 final combining forms', FINAL_FORMS.length === 37, String(FINAL_FORMS.length));
ok('1,193 words carry an initial seam', seams.initial.words === 1193, String(seams.initial.words));
ok('the page states 1,193', HTML.includes('1,193'));
ok('British takes the initial seam 80.4% of the time',
  approx(seams.initial.gbSeam / seams.initial.words, 0.804, 0.0005), (100 * seams.initial.gbSeam / seams.initial.words).toFixed(1) + '%');
ok('American takes it 60.9%',
  approx(seams.initial.usSeam / seams.initial.words, 0.609, 0.0005), (100 * seams.initial.usSeam / seams.initial.words).toFixed(1) + '%');
ok('the page states 80.4% and 60.9%', HTML.includes('80.4%') && HTML.includes('60.9%'));
ok('initial-seam discordance is 323 to 91', seams.initial.gbOnly === 323 && seams.initial.usOnly === 91,
  `${seams.initial.gbOnly}/${seams.initial.usOnly}`);
ok('the page states 414 and 323', HTML.includes('414') && HTML.includes('323'));
ok('415 words carry a final seam', seams.final.words === 415, String(seams.final.words));
ok('final-seam split is British 92.0% to American 42.4%',
  approx(seams.final.gbSeam / seams.final.words, 0.920, 0.0005) && approx(seams.final.usSeam / seams.final.words, 0.424, 0.0005),
  `${(100 * seams.final.gbSeam / seams.final.words).toFixed(1)}% / ${(100 * seams.final.usSeam / seams.final.words).toFixed(1)}%`);
ok('final-seam discordance is 215 to 9', seams.final.gbOnly === 215 && seams.final.usOnly === 9,
  `${seams.final.gbOnly}/${seams.final.usOnly}`);
ok('the page states 215 to 9', HTML.includes('215') && HTML.includes(' 9'));
ok('cluster pairing is 4,607 American to 2,702 British',
  seams.cluster.usOnlySplits === 4607 && seams.cluster.gbOnlySplits === 2702,
  `${seams.cluster.usOnlySplits}/${seams.cluster.gbOnlySplits}`);
ok('the page states 4,607 and 2,702', HTML.includes('4,607') && HTML.includes('2,702'));

// the exact binomial p values, recomputed
function logChoose(n, k) { let s = 0; for (let i = 1; i <= k; i++) s += Math.log(n - k + i) - Math.log(i); return s; }
function binomTwoSidedP(k, n) {
  if (n === 0) return 1;
  const target = logChoose(n, k) - n * Math.LN2;
  let p = 0;
  for (let i = 0; i <= n; i++) { const l = logChoose(n, i) - n * Math.LN2; if (l <= target + 1e-12) p += Math.exp(l); }
  return Math.min(1, p);
}
const pInit = binomTwoSidedP(Math.min(seams.initial.gbOnly, seams.initial.usOnly), seams.initial.gbOnly + seams.initial.usOnly);
ok('the initial-seam p value is about 1.5e-31', pInit < 2e-31 && pInit > 1e-31, pInit.toExponential(3));
ok('the page states 1.5 × 10^-31', HTML.includes('1.5 &times; 10<sup>-31</sup>') || HTML.includes('1.5 × 10'));

// ---------------------------------------------------------------------------
// The confessions and the class it cannot see
// ---------------------------------------------------------------------------
console.log('\n· the confessions ·');
function redundantExceptions(model) {
  const bare = { patterns: model.patterns, exceptions: new Map() };
  let n = 0;
  const which = [];
  for (const [w, pts] of model.exceptions) {
    const legalPts = pts.filter(p => p >= DEFAULT_LEFT_MIN && p <= w.length - DEFAULT_RIGHT_MIN);
    if (legalPts.join(',') === hyphenate(w, bare).join(',')) { n++; which.push(w); }
  }
  return { n, which };
}
const redUs = redundantExceptions(us), redLiang = redundantExceptions(liang), redGb = redundantExceptions(gb);
ok('4 of the 14 American exceptions are redundant', redUs.n === 4, redUs.which.join(' '));
ok('they are declination, obligatory, philanthropic, retribution',
  redUs.which.slice().sort().join(' ') === 'declination obligatory philanthropic retribution', redUs.which.join(' '));
ok('the page names all four', ['declination', 'obligatory', 'philanthropic', 'retribution'].every(w => HTML.includes(w)));
ok('none of Liang 1983’s exceptions was redundant', redLiang.n === 0, String(redLiang.n));
ok('none of en-gb’s exceptions is redundant', redGb.n === 0, String(redGb.n));

const bareUs = { patterns: us.patterns, exceptions: new Map() };
for (const w of ['present', 'presents', 'project', 'projects']) {
  ok(`${w} ships unbreakable`, us.exceptions.has(w) && hyphenate(w, us).length === 0);
  ok(`${w} would be broken by the patterns alone`, hyphenate(w, bareUs).length > 0, spell(w, hyphenate(w, bareUs)));
}

// The CMUdict claim behind section 4, re-derived from the dictionary itself.
console.log('\n· the class it cannot see ·');
const CMU = path.join(ROOT, 'research', 'prosody-workshop', 'cmudict.dict');
if (fs.existsSync(CMU)) {
  const stressOf = new Map();
  for (const line of fs.readFileSync(CMU, 'utf8').split('\n')) {
    const t = line.trim(); if (!t) continue;
    const sp = t.indexOf(' '); if (sp < 0) continue;
    const word = t.slice(0, sp).replace(/\(\d+\)$/, '');
    if (!/^[a-z]+$/.test(word)) continue;
    const phones = t.slice(sp + 1).split(/\s+/).filter(p => !p.startsWith('#'));
    let syl = -1, primary = -1;
    for (const p of phones) { const m = /([0-2])$/.exec(p); if (!m) continue; syl++; if (m[1] === '1') { primary = syl; break; } }
    if (primary < 0) continue;
    if (!stressOf.has(word)) stressOf.set(word, new Set());
    stressOf.get(word).add(primary);
  }
  ok('CMUdict gives present two stress positions', (stressOf.get('present') || new Set()).size === 2);
  ok('CMUdict gives project two stress positions', (stressOf.get('project') || new Set()).size === 2);
  const amb = shared.filter(w => stressOf.has(w) && stressOf.get(w).size > 1);
  ok('476 stress-ambiguous words in the shared lexicon', amb.length === 476, String(amb.length));
  ok('the page ships exactly that list',
    DATA.STRESS_AMBIGUOUS.length === amb.length && DATA.STRESS_AMBIGUOUS.every((w, i) => w === amb[i]));
  ok('the page states 476', HTML.includes('476'));
  const refuses = amb.filter(w => hyphenate(w, us).length === 0).length;
  ok('the American file refuses 14.7% of them', approx(refuses / amb.length, 0.147, 0.0005), (100 * refuses / amb.length).toFixed(1) + '%');
  const unguarded = amb.filter(w => !us.exceptions.has(w) && hyphenate(w, us).length > 0).length;
  ok('406 are broken without comment', unguarded === 406, String(unguarded));
  ok('the page states 406', HTML.includes('406'));
  // the length-matched control, rebuilt
  const need = new Map();
  for (const w of amb) need.set(w.length, (need.get(w.length) || 0) + 1);
  let matched = 0, refusedCtl = 0;
  for (const w of shared) {
    if (stressOf.has(w) && stressOf.get(w).size > 1) continue;
    const n = need.get(w.length) || 0;
    if (n <= 0) continue;
    need.set(w.length, n - 1);
    matched++;
    if (hyphenate(w, us).length === 0) refusedCtl++;
  }
  ok('the length-matched control refuse rate is 22.9%', approx(refusedCtl / matched, 0.229, 0.0005), (100 * refusedCtl / matched).toFixed(1) + '%');
  ok('the ambiguous words are broken MORE often than the control, not less',
    refuses / amb.length < refusedCtl / matched);
  ok('the page states 22.9% and 14.7%', HTML.includes('22.9%') && HTML.includes('14.7%'));
} else {
  ok('CMUdict is present so section 4 can be verified', false, 'missing ' + CMU);
}

// ---------------------------------------------------------------------------
// The 1990 revision
// ---------------------------------------------------------------------------
console.log('\n· the 1990 revision ·');
const bareLiang = { patterns: liang.patterns, exceptions: new Map() };
let changed = 0, gained = 0, lost = 0, moved = 0;
for (const w of union) {
  const a = hyphenate(w, bareLiang), b = hyphenate(w, bareUs);
  if (a.join(',') === b.join(',')) continue;
  changed++;
  const sa = new Set(a), sb = new Set(b);
  const g = b.filter(p => !sa.has(p)).length, l = a.filter(p => !sb.has(p)).length;
  if (g && !l) gained++; else if (l && !g) lost++; else moved++;
}
ok('the 491 patterns change 1,074 words', changed === 1074, String(changed));
ok('743 gained a break, 156 lost one, 175 moved', gained === 743 && lost === 156 && moved === 175, `${gained}/${lost}/${moved}`);
ok('the page states 1,074 and 1.73%', HTML.includes('1,074') && HTML.includes('1.73%'));
ok('the page states 743, 156, 175', HTML.includes('743') && HTML.includes('156') && HTML.includes('175'));

// ---------------------------------------------------------------------------
// Dead weight, over the union lexicon (the figures section 7 prints)
// ---------------------------------------------------------------------------
console.log('\n· the dead weight ·');
function neverMatches(model) {
  const alive = new Set();
  for (const w of union) {
    const dotted = '.' + w + '.';
    for (let i = 0; i < dotted.length; i++) {
      for (let j = i + 1; j <= dotted.length && j <= i + 12; j++) {
        const sub = dotted.slice(i, j);
        if (model.patterns.has(sub)) alive.add(sub);
      }
    }
  }
  return model.patterns.size - alive.size;
}
const deadUs = neverMatches(us);
ok('280 en-us patterns never occur in the union lexicon', deadUs === 280, String(deadUs));
const deadGb = neverMatches(gb);
ok('1,439 en-gb patterns never occur', deadGb === 1439, String(deadGb));
ok('the page states 280 and 1,439', HTML.includes('280') && HTML.includes('1,439'));

const deadArtifact = JSON.parse(fs.readFileSync(path.join(LAB_DIR, 'artifacts', 'exceptions-and-dead.json'), 'utf8'));
ok('the artifact agrees about en-us dead patterns', deadArtifact.files['en-us'].deadWeight.neverMatchesAnyWord === deadUs);
ok('602 en-us patterns never change the answer',
  deadArtifact.files['en-us'].deadWeight.neverChangesTheAnswer === 602,
  String(deadArtifact.files['en-us'].deadWeight.neverChangesTheAnswer));
ok('the page states 602 and 12.2% and 27.7%', HTML.includes('602') && HTML.includes('12.2%') && HTML.includes('27.7%'));

// ---------------------------------------------------------------------------
// The learner's shape
// ---------------------------------------------------------------------------
console.log('\n· the learner ·');
const learn = JSON.parse(fs.readFileSync(path.join(LAB_DIR, 'artifacts', 'learn.json'), 'utf8'));
ok('the lab curve has five levels', learn.curve.length === 5);
ok('level 2 raises precision above level 1', learn.curve[1].testPrecision > learn.curve[0].testPrecision,
  `${(100 * learn.curve[0].testPrecision).toFixed(1)}% → ${(100 * learn.curve[1].testPrecision).toFixed(1)}%`);
ok('level 2 costs recall', learn.curve[1].testRecall < learn.curve[0].testRecall);
ok('level 3 wins recall back', learn.curve[2].testRecall > learn.curve[1].testRecall);
ok('level 4 raises precision again', learn.curve[3].testPrecision > learn.curve[2].testPrecision);
ok('level 5 raises recall again', learn.curve[4].testRecall > learn.curve[3].testRecall);
const cur = learn.curve.map(c => [(100 * c.testPrecision).toFixed(1) + '%', (100 * c.testRecall).toFixed(1) + '%']);
ok('the page quotes level 1 as 86.7% and 85.3%', cur[0][0] === '86.7%' && cur[0][1] === '85.3%' && HTML.includes('86.7%') && HTML.includes('85.3%'), cur[0].join(' / '));
ok('the page quotes level 2 precision 92.8%', cur[1][0] === '92.8%' && HTML.includes('92.8%'));
ok('the page quotes level 4 precision 95.6%', cur[3][0] === '95.6%' && HTML.includes('95.6%'));
ok('the page quotes level 5 recall 94.7%', cur[4][1] === '94.7%' && HTML.includes('94.7%'));
ok('the fit needed 16,284 patterns', learn.final.patterns === 16284 && HTML.includes('16,284'), String(learn.final.patterns));
ok('88.6% of held-out words exactly right',
  approx(learn.final.exactWordRate, 0.886, 0.0005) && HTML.includes('88.6%'), (100 * learn.final.exactWordRate).toFixed(1) + '%');
const worst = learn.sweep[learn.sweep.length - 1];
ok('38,690 patterns reach 92.6%',
  worst.patterns === 38690 && approx(worst.exactWordRate, 0.926, 0.0005) && HTML.includes('38,690') && HTML.includes('92.6%'),
  `${worst.patterns} / ${(100 * worst.exactWordRate).toFixed(1)}%`);
ok('13.1% of learned sequences appear in the published file',
  approx(learn.rediscovery.shareOfLearnedFoundInPublished, 0.131, 0.0005) && HTML.includes('13.1%'),
  (100 * learn.rediscovery.shareOfLearnedFoundInPublished).toFixed(1) + '%');
ok('the Liang baseline is labelled as not a fair race', learn.baselines['liang-1983'].fairRace === false);

// ---------------------------------------------------------------------------
// The TeX differential, reported as offline unless --tex is passed
// ---------------------------------------------------------------------------
console.log('\n· the reference implementation ·');
const diff = JSON.parse(fs.readFileSync(path.join(LAB_DIR, 'artifacts', 'tex-differential.json'), 'utf8'));
ok('the differential covered all 62,156 words', diff.tested === 62156, String(diff.tested));
ok('three pattern files were tested', diff.arms.length === 3);
const ligFree = diff.arms.reduce((n, a) => n + a.ligatureFreeFont.tested, 0);
const comparisons = ligFree + diff.arms.reduce((n, a) => n + a.ligatureFont.tested, 0);
ok('186,468 ligature-free comparisons', ligFree === 186468, String(ligFree));
ok('372,936 comparisons in all', comparisons === 372936, String(comparisons));
ok('the page states both totals', HTML.includes('186,468') && HTML.includes('372,936'));
ok('zero disagreements in a ligature-free font', diff.engineMatchesTexWithoutLigatures);
const ligDisagreements = diff.arms.reduce((n, a) => n + a.ligatureFont.disagree, 0);
ok('exactly 5 ligature-font disagreements', ligDisagreements === 5, String(ligDisagreements));
ok('every one is a break inside a ligature', diff.allLigatureDisagreementsExplained);
ok('the page says five', /\bfive\b/i.test(HTML) && HTML.includes('ligature'));

if (process.argv.includes('--tex')) {
  console.log('  re-running the TeX differential (this needs a TeX installation)…');
  try {
    execFileSync('node', [path.join(LAB_DIR, 'lab', '01-tex-differential.mjs')], { stdio: 'inherit' });
    ok('the TeX differential re-ran clean', true);
  } catch {
    ok('the TeX differential re-ran clean', false, 'nonzero exit');
  }
} else {
  console.log('  (pass --tex to re-run the differential against a live TeX)');
}

// ---------------------------------------------------------------------------
// Housekeeping the page depends on
// ---------------------------------------------------------------------------
console.log('\n· the page itself ·');
ok('the page loads its module', HTML.includes('<script type="module" src="./page.js">'));
ok('the closing tags are present', /<\/body>\s*<\/html>\s*$/.test(HTML.trim() + '\n') || HTML.trim().endsWith('</html>'));
ok('page.js imports the shared engine, not a copy', PAGE_JS.includes("from './hyphenate.mjs'"));
ok('page.js imports the shared learner', PAGE_JS.includes("from './learn.mjs'"));
ok('page.js imports the shared forms list', PAGE_JS.includes("from './forms.mjs'"));
ok('there is no second copy of the algorithm in page.js', !/function competition\s*\(/.test(PAGE_JS));
ok('the frontmatter points at the page', MD.includes('href: "/strata/where-a-word-breaks/"'));
ok('the frontmatter carries an seoTitle', /seoTitle:/.test(MD));
ok('the predictions file is committed', fs.existsSync(path.join(LAB_DIR, 'PREDICTIONS.md')));
const preds = fs.readFileSync(path.join(LAB_DIR, 'PREDICTIONS.md'), 'utf8');
ok('the predictions were written before the numbers', preds.includes('P1') && preds.includes('P5') && !preds.includes('35.63'));
ok('the page reports the prediction that died', HTML.includes('P1 died'));
ok('the page reports the test it got wrong and corrected', HTML.includes('377') && HTML.includes('136'));

// ---------------------------------------------------------------------------
console.log('');
if (fail === 0) {
  console.log(`${pass}/${pass} checks pass.`);
  process.exit(0);
} else {
  console.log(`${pass}/${pass + fail} pass, ${fail} FAILED:`);
  for (const f of failures) console.log(`   ✗ ${f}`);
  process.exit(1);
}
