#!/usr/bin/env node
// verify-the-sound-you-are-allowed-to-keep.mjs
// ─────────────────────────────────────────────────────────────────────────────
// The check behind /strata/the-sound-you-are-allowed-to-keep/.
//
// Three independent jobs, in this order:
//
//   1. RE-DERIVE. The headline counts are recomputed here from the committed
//      Wiktionary snapshot and the hand-audited pair table, with this file's own
//      arithmetic rather than by importing the analysis, so agreeing with
//      results.json is a real comparison and not a tautology. The statistics
//      (McNemar's exact test, the Poisson-binomial tail, Fisher's exact test) are
//      re-implemented here too, and cross-checked against closed forms.
//   2. AUDIT THE AUDIT. Every pair's source word must actually appear in the
//      Wiktionary entry it cites, at the revision snapshotted, and every excluded
//      entry must really be in the category. The hand audit is the one place a
//      human judgement enters this page, so it is the place that gets checked
//      hardest.
//   3. READ THE SHIPPED BYTES. Every figure the page prints is asserted against
//      the artifacts. A page can be wrong in a way its data file is not.
//
//   node verify-the-sound-you-are-allowed-to-keep.mjs
//
// Offline, about two seconds, from a clean checkout — but espeak-ng must be
// installed (sudo apt-get install -y espeak-ng). It is not an optional extra for
// the espeak section at the end: 22 of the words in the pair set have no CMUdict
// and no Wiktionary pronunciation at all, and the same-system rule means 25 of the
// 76 pairs can only be resolved inside espeak-ng. Without it the re-derivation
// below would quietly analyse 51 pairs and compare them against a 76-pair result,
// so this file refuses to run at all rather than report a number it cannot stand
// behind. (An earlier version of this note claimed espeak was needed for "six
// words" and that its checks would skip cleanly. Both were wrong: it crashed.)
// ─────────────────────────────────────────────────────────────────────────────

import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import { fileURLToPath } from 'node:url';
import { rimeParts, maximalOnset, isVowelPhone, bareVowel } from './research/prosody-workshop/rhyme.mjs';
import { cmudict, resolve, fromSystem, espeakAvailable, ipaToArpabet } from './research/minced-oaths/phones.mjs';
import { evidenceFor, machinePair } from './research/minced-oaths/extract.mjs';

const ROOT = path.dirname(fileURLToPath(import.meta.url));
const R = (p) => path.join(ROOT, p);
const SLUG = 'the-sound-you-are-allowed-to-keep';

let pass = 0, fail = 0, skip = 0;
const ok = (cond, label, detail) => {
  if (cond) { pass++; console.log(`  ✓ ${label}`); }
  else { fail++; console.log(`  ✗ ${label}${detail ? '  — ' + detail : ''}`); }
};
const eq = (got, want, label) => ok(got === want, label, `got ${JSON.stringify(got)}, want ${JSON.stringify(want)}`);
const near = (got, want, tol, label) => ok(Math.abs(got - want) <= tol, label, `got ${got}, want ${want} ± ${tol}`);
const section = (s) => console.log(`\n── ${s} ` + '─'.repeat(Math.max(0, 62 - s.length)));

const M = (f) => JSON.parse(fs.readFileSync(R(`research/minced-oaths/data/${f}`), 'utf8'));
const RES = M('results.json');
const CTL = M('control.json');
const PAIRS = M('pairs.json');
const SNAP = M('wiktionary.json');
const PARSED = M('parsed.json');
const PAGE = R(`public/strata/${SLUG}/index.html`);
const html = fs.existsSync(PAGE) ? fs.readFileSync(PAGE, 'utf8') : null;

console.log('THE SOUND YOU ARE ALLOWED TO KEEP — verification\n');

// ═════════════════════════════════════════════════════════════════════════════
// The one hard dependency, checked before anything is claimed.
//
// espeak-ng is the third transcription system, and the study's same-system rule
// means a pair is only usable if ONE system has both of its words. 25 of the 76
// pairs clear that bar only inside espeak-ng. With espeak-ng missing those pairs
// vanish from the re-derivation, `resolve()` starts returning null, and the swap
// null in section 4 dereferences it. A null guard there would not be a fix: it
// would let the file re-derive 51 pairs, silently drop a third of the corpus, and
// then disagree with the published counts for a reason that has nothing to do
// with whether those counts are right. So: refuse, loudly, and say why.
if (!espeakAvailable()) {
  const need = RES.systemUse?.espeak ?? '25';
  console.log('  ✗ espeak-ng is not installed, and it is load-bearing for this page.');
  console.log(`    The analysis resolves ${need} of the ${RES.pairs.length} pairs inside espeak-ng, because`);
  console.log('    neither CMUdict nor Wiktionary pronounces both of their words. Without it this');
  console.log('    verifier can only see part of the corpus, so it will not report a pass count.');
  console.log('\n    Install it and run again:  sudo apt-get install -y espeak-ng');
  console.log(`\n${'═'.repeat(64)}`);
  console.log('NOT RUN — the page is neither verified nor refuted.');
  process.exit(1);
}

// ═════════════════════════════════════════════════════════════════════════════
section('1. the sources are the ones the page names');

const cmuSha = crypto.createHash('sha256').update(fs.readFileSync(R('research/prosody-workshop/cmudict.dict'))).digest('hex');
ok(/^[0-9a-f]{64}$/.test(cmuSha), 'cmudict is present and hashable');
const dict = cmudict();
ok(dict.size > 100000, `cmudict has ${dict.size} headwords`);
eq(SNAP.categories['Category:English minced oaths'].length, 214, 'the snapshot holds all 214 members of Category:English minced oaths');
eq(Object.keys(SNAP.pages).length, 214, 'every category member has its wikitext snapshotted');
ok(Object.values(SNAP.pages).every((p) => Number.isInteger(p.revid) && p.revid > 0),
   'every snapshotted page carries the revision id its quotes come from');
eq(SNAP.licence, 'CC BY-SA 4.0', 'the Wiktionary licence is recorded with the snapshot');
ok(fs.existsSync(R('research/minced-oaths/PREREGISTRATION.md')), 'the pre-registration ships with the analysis');
const prereg = fs.readFileSync(R('research/minced-oaths/PREREGISTRATION.md'), 'utf8');
for (const phrase of ['H1', 'H2', 'H3', 'McNemar', 'phoneme class in the inventory', 'not answerable']) {
  ok(prereg.includes(phrase), `the pre-registration fixes "${phrase}" in advance`);
}

// ═════════════════════════════════════════════════════════════════════════════
section('2. the hand audit is faithful to the entries it cites');

const norm = (s) => s.toLowerCase().replace(/[’']/g, "'");
let evidenceInEntry = 0, sourceInEntry = 0;
const auditProblems = [];
for (const row of [...PAIRS.set, ...PAIRS.phrasePairs]) {
  const page = SNAP.pages[row.entry];
  if (!page) { auditProblems.push(`${row.entry}: not in the category snapshot`); continue; }
  const wt = norm(page.wikitext);
  // the source word must actually occur in the entry that is quoted for it
  if (wt.includes(norm(row.s))) sourceInEntry++;
  else auditProblems.push(`${row.entry}: does not contain "${row.s}"`);
  // and the entry must itself carry a cue naming a substitution, in the same evidence
  // item that names the source word. This is the substantive claim the audit makes; the
  // `evidence` field is a markup-stripped rendering of that line, not a byte quotation.
  const items = PARSED.parsed[row.entry]?.evidence || [];
  const supports = items.some((e) => e.cue && (
    norm(e.text).includes(norm(row.s)) || (e.links || []).some((l) => norm(l) === norm(row.s))));
  if (supports) evidenceInEntry++;
  else auditProblems.push(`${row.entry}: no cue-carrying line names "${row.s}"`);
}
const nPairs = PAIRS.set.length + PAIRS.phrasePairs.length;
eq(sourceInEntry, nPairs, 'every pair\'s source word occurs in the entry the pair cites');
eq(evidenceInEntry, nPairs, 'every pair is supported by a line in its entry that both names a substitution and names the source word');
ok(auditProblems.length === 0, 'no audit row cites an entry it cannot support', auditProblems.slice(0, 4).join('; '));

// every excluded entry names a real reason, and the hedge words it claims are really there
const hedges = ['probably', 'perhaps', 'possibly', 'likely', 'uncertain', 'either', 'apparently'];
let hedgeChecked = 0;
for (const x of PAIRS.excluded) {
  if (!/hedged|uncertain|forked/.test(x.why)) continue;
  const page = SNAP.pages[x.entry];
  if (!page) continue;
  hedgeChecked++;
  ok(hedges.some((h) => norm(page.wikitext).includes(h)),
     `the entry "${x.entry}" really does hedge, as the exclusion claims`);
}
ok(hedgeChecked >= 8, `${hedgeChecked} hedged exclusions were checked against their entries`);

// the pair set must not double-count one deformation: no euphemism appears twice, and no
// folded form is also a pair in its own right
const seenE = new Set(), dupes = [];
for (const row of [...PAIRS.set, ...PAIRS.phrasePairs]) {
  if (seenE.has(row.e)) dupes.push(row.e);
  seenE.add(row.e);
}
eq(dupes.length, 0, 'no euphemism is counted twice');
const folded = new Set([...PAIRS.set, ...PAIRS.phrasePairs].flatMap((r) => r.folded || []));
eq([...folded].filter((f) => seenE.has(f)).length, 0, 'no form folded into a base pair is also counted as its own pair');

// ═════════════════════════════════════════════════════════════════════════════
section('3. the headline counts, re-derived here');

// this file's own split, written independently of measure.mjs
function ownSplit(phones) {
  const i = phones.findIndex(isVowelPhone);
  return {
    onset: maximalOnset(i === -1 ? phones.slice() : phones.slice(0, i)),
    remainder: (i === -1 ? [] : phones.slice(i)).map(bareVowel),
  };
}
const same = (a, b) => a.join(' ') === b.join(' ');

const wiktPron = {};
for (const [t, p] of Object.entries(PARSED.parsed)) wiktPron[t] = p.pron;
for (const [t, p] of Object.entries(PARSED.cited)) if (!wiktPron[t]) wiktPron[t] = p.pron;

// The same-system policy, re-implemented here: both words of a pair must come from one
// transcription system, the best that has both. Stated in the method, so the verifier
// applies it too; the arithmetic on top of it is this file's own.
function ownPair(a, b) {
  for (const sys of ['cmudict', 'wiktionary', 'espeak']) {
    const pa = fromSystem(sys, a, wiktPron[a]), pb = fromSystem(sys, b, wiktPron[b]);
    if (pa && pb) return { a: pa, b: pb, sys };
  }
  return null;
}

const derived = [];
let unresolvable = 0, mixedOnset = 0;
for (const row of [...PAIRS.set, ...PAIRS.phrasePairs]) {
  const rp = ownPair(row.e, row.s);
  if (!rp) { unresolvable++; continue; }
  const pe = { phones: rp.a }, ps = { phones: rp.b };
  // what the mixed-source resolver would have said, for the check below
  const mE = resolve(row.e, wiktPron[row.e]), mS = resolve(row.s, wiktPron[row.s]);
  if (mE && mS && ownSplit(mE.phones).onset.join(' ') === ownSplit(mS.phones).onset.join(' ')) mixedOnset++;
  const E = ownSplit(pe.phones), S = ownSplit(ps.phones);
  derived.push({
    e: row.e, s: row.s, m: row.m,
    onsetKept: same(E.onset, S.onset),
    rimeKept: same(E.remainder, S.remainder),
    firstKept: pe.phones[0] === ps.phones[0],
    simple: ps.phones.filter(isVowelPhone).length === 1,
  });
}
eq(unresolvable, 0, 'every pair has both words available inside at least one transcription system');
eq(derived.length, RES.pairs.length, 'the re-derivation analyses the same number of pairs as the analysis did');

const dOnset = derived.filter((r) => r.onsetKept).length;
const dRime = derived.filter((r) => r.rimeKept).length;
const dFirst = derived.filter((r) => r.firstKept).length;
eq(dOnset, RES.h1.all.onset, 'onset-kept count re-derives');
eq(dRime, RES.h1.all.rime, 'remainder-kept count re-derives');
eq(dFirst, RES.h1.all.firstPhone, 'first-phoneme-kept count re-derives');
eq(derived.filter((r) => r.simple).length, RES.h1.simple.n, 'the one-syllable subset re-derives');
eq(derived.filter((r) => r.simple && r.onsetKept).length, RES.h1.simple.onset, 'onset-kept within the one-syllable subset re-derives');
ok(mixedOnset !== dOnset,
   `mixing transcription sources really does change the answer (${mixedOnset} against ${dOnset}), which is why the page does not`);

// no pair keeps its rime, and the nearest miss must be the one the page names
const rimeKeepers = derived.filter((r) => r.rimeKept).map((r) => r.e);
eq(rimeKeepers.length, 0, 'no pair in the set keeps its remainder intact');
eq(RES.overlap.nearestRime[0].e, 'cornography', 'the pair that comes closest to keeping its rime is cornography, as the page says');
ok(RES.overlap.nearestRime[0].sharedSuffix === 8 && !RES.pairs.find((p) => p.e === 'cornography').initialOnsetKept,
   'cornography shares 8 phones at the end and does not keep its onset, which is what the page claims about it');
ok(RES.overlap.meanPrefix > RES.overlap.meanSuffix,
   `pairs share more phones at the start than at the end (${RES.overlap.meanPrefix.toFixed(2)} vs ${RES.overlap.meanSuffix.toFixed(2)})`);

// the three-system robustness table must actually agree
for (const r of RES.systemRobustness) {
  ok(r.rime === 0, `computed entirely inside ${r.system}, the remainder is kept 0 times in ${r.n} pairs`);
  ok(r.onset / r.n > 0.45 && r.onset / r.n < 0.85, `${r.system} gives an onset rate of ${(100 * r.onset / r.n).toFixed(1)}%`);
}
ok(Object.values(RES.systemUse).reduce((a, b) => a + b, 0) === RES.pairs.length,
   'every pair is resolved inside exactly one system, so no pair mixes two transcription traditions');

// the mechanism split
for (const [m, n] of Object.entries(RES.mechanismCounts)) {
  eq(derived.filter((r) => r.m === m).length, n, `${n} pairs are classified "${m}"`);
}

// ═════════════════════════════════════════════════════════════════════════════
section('4. the statistics, re-implemented and cross-checked');

function mcnemar(b, c) {                       // exact two-sided binomial against 1/2
  const n = b + c;
  if (n === 0) return 1;
  const lc = (n, k) => { let s = 0; for (let i = 1; i <= k; i++) s += Math.log(n - k + i) - Math.log(i); return s; };
  const pmf = (i) => Math.exp(lc(n, i) - n * Math.LN2);
  const obs = pmf(Math.min(b, c));
  let p = 0;
  for (let i = 0; i <= n; i++) if (pmf(i) <= obs * (1 + 1e-9)) p += pmf(i);
  return Math.min(1, p);
}
// closed form sanity: with c = 0 the two-sided exact p is 2^(1-b)
const b = derived.filter((r) => r.onsetKept && !r.rimeKept).length;
const c = derived.filter((r) => !r.onsetKept && r.rimeKept).length;
eq(c, 0, 'no pair keeps the rime while losing the onset');
near(mcnemar(b, c), Math.pow(2, 1 - b), 1e-12, `McNemar with c = 0 agrees with the closed form 2^(1-${b})`);
near(RES.h1.all.mcnemarP, mcnemar(b, c), 1e-12, 'the analysis reports the same McNemar p as this file computes');
near(mcnemar(10, 10), 1, 1e-12, 'McNemar sanity: a perfectly balanced table gives p = 1');
near(mcnemar(5, 0), 0.0625, 1e-12, 'McNemar sanity: 5 versus 0 gives 2^-4');

function poissonBinomTail(ps, k) {
  let d = [1];
  for (const p of ps) {
    const n = new Array(d.length + 1).fill(0);
    for (let i = 0; i < d.length; i++) { n[i] += d[i] * (1 - p); n[i + 1] += d[i] * p; }
    d = n;
  }
  return d.slice(k).reduce((a, x) => a + x, 0);
}
// sanity: all p equal gives the ordinary binomial tail
const bin = (n, k, p) => { let s = 0; for (let i = k; i <= n; i++) { let lc = 0; for (let j = 1; j <= i; j++) lc += Math.log(n - i + j) - Math.log(j); s += Math.exp(lc + i * Math.log(p) + (n - i) * Math.log(1 - p)); } return s; };
near(poissonBinomTail(new Array(10).fill(0.3), 4), bin(10, 4, 0.3), 1e-12,
     'the Poisson-binomial tail reduces to the binomial when every probability is equal');
near(poissonBinomTail([0.5], 1), 0.5, 1e-12, 'Poisson-binomial sanity: one fair coin');

// re-derive the swap null from the lexicon, independently
const lexOnset = new Map();
let lexN = 0;
for (const [w, prons] of dict) {
  if (!/^[a-z'-]+$/.test(w)) continue;
  const s = ownSplit(prons[0]);
  if (!s.remainder.length) continue;
  lexN++;
  const k = s.onset.join(' ');
  lexOnset.set(k, (lexOnset.get(k) || 0) + 1);
}
eq(lexN, RES.lexicon.n, 'the null-model lexicon is the same size the analysis used');
const swaps = [...PAIRS.set, ...PAIRS.phrasePairs].filter((r) => r.m === 'swap');
const swapPs = swaps.map((r) => {
  const ps = resolve(r.s, wiktPron[r.s]);
  return (lexOnset.get(ownSplit(ps.phones).onset.join(' ')) || 0) / lexN;
});
const swapObs = derived.filter((r) => r.m === 'swap' && r.onsetKept).length;
eq(swapObs, RES.swapNull.onset.observed, 'the observed swap onset matches re-derive');
near(swapPs.reduce((a, x) => a + x, 0), RES.swapNull.onset.expected, 1e-9, 'the expected number of chance onset matches re-derives');
near(poissonBinomTail(swapPs, swapObs), RES.swapNull.onset.p, 1e-12, 'the swap null p-value re-derives');
ok(RES.swapNull.onset.p < 1e-15, `the swap result survives its null by a wide margin (p = ${RES.swapNull.onset.p.toExponential(2)})`);

// ═════════════════════════════════════════════════════════════════════════════
section('5. the control: same instrument, both categories, no audit');

const CSNAP = fs.existsSync(R('research/minced-oaths/data/control-wiktionary.json'))
  ? M('control-wiktionary.json') : null;
if (!CSNAP) { skip++; console.log('  ~ control snapshot absent, control checks skipped'); }
else {
  const mincedTitles = new Set(SNAP.categories['Category:English minced oaths']);
  eq(Object.keys(CSNAP.pages).filter((t) => mincedTitles.has(t)).length, 0,
     'the control category shares no page with the minced oaths, so the arms cannot overlap');
  // re-run the mechanical pairing over both, here, and count
  let tN = 0, tFirst = 0, cN = 0, cFirst = 0;
  for (const [pages, isT] of [[SNAP.pages, true], [CSNAP.pages, false]]) {
    for (const [title, page] of Object.entries(pages)) {
      const { evidence, pron } = evidenceFor(page.wikitext);
      const mp = machinePair(title, evidence);
      if (!mp) continue;
      const pe = resolve(mp.e, pron), ps = resolve(mp.s, null);
      if (!pe || !ps) continue;
      if (isT) { tN++; if (pe.phones[0] === ps.phones[0]) tFirst++; }
      else { cN++; if (pe.phones[0] === ps.phones[0]) cFirst++; }
    }
  }
  eq(tN, CTL.treatment.n, 'the machine pass over the minced oaths re-derives its pair count');
  eq(cN, CTL.control.n, 'the machine pass over the other euphemisms re-derives its pair count');
  eq(tFirst, CTL.treatment.first, 'the machine pass over the minced oaths re-derives its first-phoneme count');
  eq(cFirst, CTL.control.first, 'the machine pass over the other euphemisms re-derives its first-phoneme count');
  eq(CTL.pooledByTaboo.taboo.n + CTL.pooledByTaboo.plain.n, tN + cN,
     'the taboo split partitions exactly the pooled pairs, losing none');
  ok(CTL.pooledByTaboo.taboo.first / CTL.pooledByTaboo.taboo.n
     > CTL.pooledByTaboo.plain.first / CTL.pooledByTaboo.plain.n,
     'the taboo arm keeps the first phoneme more often than the non-taboo arm');
  ok(CTL.pooledByTaboo.fisherFirstP < 1e-10,
     `Fisher's exact test separates the two arms (p = ${CTL.pooledByTaboo.fisherFirstP.toExponential(2)})`);
  // both arms are far above the chance collision rate, which is itself re-derived
  let sq = 0;
  for (const v of lexOnset.values()) sq += (v / lexN) ** 2;
  near(sq, CTL.chance.onset, 1e-9, 'the chance onset-collision rate of the lexicon re-derives');
  ok(CTL.pooledByTaboo.plain.first / CTL.pooledByTaboo.plain.n > CTL.chance.firstPhone,
     'the non-taboo arm is still above pure chance, as the page says it is');
}

// ═════════════════════════════════════════════════════════════════════════════
section('6. the approximant replication ships with its whole inventory');

const CLASSES = ['stop', 'affricate', 'fricative', 'nasal', 'approximant', 'vowel'];
for (const cls of CLASSES) ok(RES.h2.all[cls], `class "${cls}" is reported`);
ok(RES.h2.all.approximant.up > RES.h2.all.approximant.down, 'approximants rise, replicating Lev-Ari and McKay');
ok(RES.h2.all.stop.down > RES.h2.all.stop.up && RES.h2.all.fricative.down > RES.h2.all.fricative.up,
   'stops and fricatives fall, so the rise is a trade and not a length artifact');
ok(RES.h2.lengths.meanEuphemismPhones > RES.h2.lengths.meanSourcePhones,
   'euphemisms really are longer than their sources, which is why the whole inventory is reported');

// ═════════════════════════════════════════════════════════════════════════════
section('7. the negatives are still negative');

ok(RES.generator.hit / RES.generator.n < 0.1,
   `the "keep the onset, reuse an attested rime" rule reproduces only ${RES.generator.hit}/${RES.generator.n}`);
const dated = RES.chronology.dated.filter((d) => d.riseYear1800);
const era = {};
for (const d of [...RES.chronology.dated, ...RES.chronology.univerbationDated]) {
  if (!d.riseYear1800 || !d.domain) continue;
  const k = d.riseYear1800 < 1900 ? 'pre1900' : d.riseYear1800 < 1970 ? 'mid' : 'late';
  era[k] = era[k] || {};
  era[k][d.domain] = (era[k][d.domain] || 0) + 1;
}
ok(era.pre1900 && era.pre1900.body > 0 && era.pre1900.deity > 0,
   'the pre-1900 group already mixes body and deity, so the migration story is not supported here');
ok(Object.keys(RES.chronology.citedDates).length < RES.chronology.dated.length / 2,
   `Wiktionary states a date for only ${Object.keys(RES.chronology.citedDates).length} entries, too few to date the set`);
ok(dated.length > 0 && dated.length <= RES.chronology.dated.length, 'the post hoc dating rule is reported with its coverage');

// ═════════════════════════════════════════════════════════════════════════════
section('8. the shipped page says what the analysis found');

if (!html) { fail++; console.log(`  ✗ the page is missing at public/strata/${SLUG}/index.html`); }
else {
  const has = (s, label) => ok(html.includes(s), label || `the page prints "${s}"`);
  has(`${RES.h1.all.onset} / ${RES.h1.all.n}`, 'the headline onset score is on the page');
  has(`${RES.h1.all.rime} / ${RES.h1.all.n}`, 'the headline rime score is on the page');
  has(String(RES.pairs.length), 'the pair count is on the page');
  has(`${RES.swapNull.onset.observed} times out of ${RES.swapNull.n}`, 'the swap result is stated with its denominator');
  has(RES.swapNull.onset.expected.toFixed(2), 'the swap null expectation is printed');
  has(`${RES.h1.simple.onset} of ${RES.h1.simple.n}`, 'the one-syllable cut is printed');
  has((100 * CTL.pooledByTaboo.taboo.first / CTL.pooledByTaboo.taboo.n).toFixed(1), 'the taboo arm percentage is printed');
  has((100 * CTL.pooledByTaboo.plain.first / CTL.pooledByTaboo.plain.n).toFixed(1), 'the non-taboo arm percentage is printed');
  has((100 * CTL.chance.firstPhone).toFixed(1), 'the chance collision rate is printed');
  has(`${RES.generator.hit} times in ${RES.generator.n}`, 'the failed generator is stated with its denominator');
  has('cornography', 'the single counterexample is named');
  has('PREREGISTRATION.md', 'the page points at what was fixed in advance');
  has('Lev-Ari', 'the replicated paper is credited');
  has('CC BY-SA', 'the Wiktionary licence is on the page');
  has('Three things that did not work', 'the negatives have their own section rather than a footnote');
  ok(html.includes('after seeing the first result') || html.includes('decided afterwards'),
     'the page flags its post hoc choices as post hoc');
  // every pair in the table
  let missing = [];
  for (const p of RES.pairs) if (!html.includes(`>${p.e}<`) && !html.includes(`>${p.e} `)) missing.push(p.e);
  ok(missing.length === 0, `all ${RES.pairs.length} euphemisms appear in the shipped table`, missing.slice(0, 6).join(', '));
  // structure and chrome
  ok(html.trimEnd().endsWith('</html>'), 'the page closes its tags (the silent-no-JS trap)');
  ok(html.includes('/media/home-banner.js'), 'the shared top bar is mounted');
  ok(html.includes('aw-wayout'), 'the canonical way-out footer is present');
  ok(html.includes(`rel="canonical"`) && html.includes(`/strata/${SLUG}/`), 'the canonical link is set to this slug');
  ok(!/__[A-Z0-9_]{3,}__/.test(html), 'no unfilled placeholder survived into the page');
  ok(!/[—]/.test(html.replace(/&mdash;/g, '')), 'no em dashes in the page prose');
  // the page must print the taboo words it is about, having said that it will
  ok(html.includes('so it prints them'), 'the page states plainly that it prints the words');
  for (const w of ['fuck', 'shit', 'damn', 'hell']) has(w, `the page does print "${w}", as it says it does`);
  // the verifier command the page prints must be a file that exists
  for (const cmd of ['research/minced-oaths/analyse.mjs', 'research/minced-oaths/control.mjs', 'research/minced-oaths/build-page.mjs', 'verify-the-sound-you-are-allowed-to-keep.mjs']) {
    if (!html.includes(cmd)) continue;
    ok(fs.existsSync(R(cmd)), `the command the page prints exists: ${cmd}`);
  }
}

// ═════════════════════════════════════════════════════════════════════════════
section('9. espeak, only where it is actually load-bearing');

// Reaching here at all means espeak-ng is present: the gate at the top of this file
// has already refused to continue without it. So these run unconditionally.
{
  eq(ipaToArpabet('ɡɒʃ').join(' '), 'G AA1 SH', 'the IPA converter renders gosh as CMUdict does');
  eq(ipaToArpabet('hɛk').join(' '), 'HH EH1 K', 'the IPA converter renders heck as CMUdict does');
  eq(ipaToArpabet('ˈdʒiːpɚz').join(' '), 'JH IY1 P ER0 Z', 'the IPA converter handles an affricate, a long vowel and an r-coloured schwa');
  ok(RES.calibration.espeak.firstPhone === RES.calibration.espeak.n,
     `espeak agrees with CMUdict on the first phoneme in all ${RES.calibration.espeak.n} words where both have an opinion`);
  ok(RES.calibration.espeak.exact / RES.calibration.espeak.n > 0.7,
     `espeak agrees exactly ${RES.calibration.espeak.exact}/${RES.calibration.espeak.n} of the time, which the page prints rather than assumes`);
}

// ═════════════════════════════════════════════════════════════════════════════
console.log(`\n${'═'.repeat(64)}`);
console.log(`${pass}/${pass + fail} checks passed` + (skip ? `, ${skip} skipped` : '') + (fail ? `, ${fail} FAILED` : ''));
process.exit(fail ? 1 : 0);
