#!/usr/bin/env node
// verify-the-word-you-were-going-to-say.mjs
//
//   node research/the-word-you-were-going-to-say/verify-the-word-you-were-going-to-say.mjs
//
// Recomputes every number the page displays, from the shipped CC-BY CSVs, and asserts the
// rendered HTML says the same thing. Exits 0 only if all of it holds.
//
// It reads the shipped source under public/, never a build output directory. A verifier
// that reads a stale build can certify a page nobody shipped.
//
// The negative controls at the foot are the point. Every assertion above them could pass on
// a page whose mechanism was quietly broken, so each one is followed by a deliberate break
// and a demand that the check notices. In particular:
//   * shuffle the American frequencies and the out-of-sample rate must collapse;
//   * rank the WORST three instead of the best and the in-sample rate must collapse;
//   * remove the matching rule from a seal and the seal audit must refuse it;
//   * feed the predictor a CSPRNG and it must fall to arithmetic chance.

import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
import { createHash, webcrypto } from 'node:crypto';
import vm from 'node:vm';
import {
  buildNorms, readCSV, count, fold, match as matches, hit, topK, inSample, leaveOneOut,
  outOfSample, suite, ci, spearman, pairsComplete, MATCH_RULE, RANK_RULE, SCORE_RULE,
} from './norms-core.mjs';

const here = dirname(fileURLToPath(import.meta.url));
const ROOT = join(here, '..', '..');
const PAGE_DIR = join(ROOT, 'public', 'strata', 'the-word-you-were-going-to-say');
const DATA = join(PAGE_DIR, 'data');
const HTML = readFileSync(join(PAGE_DIR, 'index.html'), 'utf8');
const MD = readFileSync(join(ROOT, 'src', 'content', 'strata', 'the-word-you-were-going-to-say.md'), 'utf8');

let pass = 0, fail = 0;
const ok = (name, cond, detail) => {
  if (cond) { pass++; console.log('  ok   ' + name); }
  else { fail++; console.error('  FAIL ' + name + (detail !== undefined ? '  [' + detail + ']' : '')); }
};
const head = (s) => console.log('\n' + s);
const sha = (b) => createHash('sha256').update(b).digest('hex');
const pct1 = (x) => (100 * x).toFixed(1) + '%';

// ---------------------------------------------------------------- 1. provenance
head('1. provenance of the shipped data');

// Pinned on 2026-08-13 by downloading each file twice from osf.io/jgcu6 (a public node whose
// OSF licence field reads "CC-By Attribution 4.0 International") and comparing digests.
const PINNED = {
  'bc_item_ref.csv': '9c22790b601a9531a331a550a71be4e5fe584946c4a5722fd49db42bd51a2ada',
  'bc_item_full.csv': 'e87316f4b83ef1da1c55131312bf9105a942f7983fbf4804894471728c699c1b',
  'bc_trial.csv': '65c493b81db209426b3bd0df2a1968c83e0bddc48f4a172925530ddf1921830e',
  'cmp_vo.csv': 'a56e5488d3a7f67dbd78340034a8f90bbe3a997fcc0d711235aa877e6062a43d',
  'cmp_hg.csv': 'f3ba9be33fbf303a2035424574a1f30cc33a53161530caa1c42f9f84cee58d81',
};
for (const [f, want] of Object.entries(PINNED)) {
  const got = sha(readFileSync(join(DATA, f)));
  ok('shipped ' + f + ' is the OSF file, unmodified', got === want, got);
}

// The attribution notice shipped beside the CC-BY files is itself a claim: it states a row
// count for each one, and a licence. Check the counts.
const ATTR = readFileSync(join(DATA, 'ATTRIBUTION.md'), 'utf8');
ok('the data directory carries an attribution notice naming CC BY 4.0 and the OSF node',
  /CC BY 4\.0/.test(ATTR) && /osf\.io\/jgcu6/.test(ATTR));
for (const [f, rows] of [['bc_item_ref.csv', 5475], ['bc_item_full.csv', 6448], ['bc_trial.csv', 17707],
  ['cmp_vo.csv', 1376], ['cmp_hg.csv', 584]]) {
  const got = readCSV(join(DATA, f)).length;
  const printed = new RegExp(rows.toLocaleString('en-US') + ' rows').test(ATTR);
  ok(`attribution row count for ${f} is ${rows} and matches the file`, got === rows && printed, got);
}
ok('every pinned digest is also printed in the attribution notice',
  Object.values(PINNED).every((d) => ATTR.includes(d)));

// ---------------------------------------------------------------- 2. the denominator
head('2. the denominator, from two independent files');

const cats = buildNorms(DATA);
const catsFull = buildNorms(DATA, 'full');
const itemsAll = readCSV(join(DATA, 'bc_item_ref.csv'));
const trials = readCSV(join(DATA, 'bc_trial.csv'));

const N44 = cats.reduce((s, c) => s + c.n, 0);
const rank1 = trials.filter((t) => Number(t.rank) === 1);
const voCatSet = new Set(cats.map((c) => c.c));
const trial44 = rank1.filter((t) => voCatSet.has(t.category)).length;
const item117 = itemsAll.reduce((s, r) => s + count(r['first.rank.freq']), 0);

ok('44 comparison categories', cats.length === 44, cats.length);
ok('861 first responses in them (item table)', N44 === 861, N44);
ok('861 first responses in them (trial table, a different file)', trial44 === 861, trial44);
ok('2277 first responses across all 117 (item table)', item117 === 2277, item117);
ok('2277 rank-1 rows across all 117 (trial table)', rank1.length === 2277, rank1.length);
ok('the flat-20 denominator the spec assumed would have been wrong', 44 * 20 !== N44 && 117 * 20 !== item117);
// 19 categories fall short of twenty, so a flat denominator invents misses.
const short = cats.filter((c) => c.n < 20).length;
ok('10 of the 44 categories have fewer than twenty scoreable first responses', short === 10, short);
ok('a flat denominator of 880 would have invented 19 misses', 44 * 20 - N44 === 19, 44 * 20 - N44);

// ---------------------------------------------------------------- 3. eight named rows
head('3. the eight first-rank counts named in the build specification');

const NAMED = [
  ['colour', 'red', 12], ['colour', 'blue', 5], ['fruit', 'apple', 15], ['vegetable', 'carrot', 8],
  ['four-legged animal', 'dog', 11], ['tool', 'hammer', 15], ['day of the week', 'monday', 17],
  ['unit of time', 'seconds', 10],
];
for (const [cat, member, want] of NAMED) {
  const row = itemsAll.find((r) => r.category === cat && r['category.member'] === member);
  const got = row ? count(row['first.rank.freq']) : null;
  ok(`${cat} / ${member} = ${want} of 20`, got === want, got);
}

// ---------------------------------------------------------------- 4. the published anchor
head('4. the published anchor: Banks & Connell\'s own six correlations');

const vo = readCSV(join(DATA, 'cmp_vo.csv'));
const hg = readCSV(join(DATA, 'cmp_hg.csv'));
const nz = (v) => Number(v) !== 0;
const ANCHOR = [
  ['Van Overschelde, production frequency, all items', vo, 'prod.freq.percent', 'VanOver_prod.freq', null, 0.35, 1376],
  ['Van Overschelde, production frequency, matching only', vo.filter((r) => nz(r['prod.freq']) && nz(r['VanOver_prod.freq'])), 'prod.freq.percent', 'VanOver_prod.freq', null, 0.72, 595],
  ['Van Overschelde, mean rank', vo, 'mean.rank', 'VanOver_mean.rank', null, 0.75, 595],
  ['Van Overschelde, first-rank frequency', vo, 'first.rank.freq.percent', 'VanOver_first.rank.freq', null, 0.63, 201],
  ['Hampton & Gardiner, production frequency, all items', hg, 'prod.freq.percent', 'HG_prod.freq.percent', null, 0.45, 584],
  ['Hampton & Gardiner, production frequency, matching only', hg.filter((r) => nz(r['prod.freq']) && nz(r['HG_prod.freq'])), 'prod.freq.percent', 'HG_prod.freq.percent', null, 0.64, 267],
  ['Hampton & Gardiner, first-rank frequency', hg, 'first.rank.freq.percent', 'HG_first.rank.freq.percent', null, 0.43, 54],
];
for (const [label, rows, ka, kb, , printed, printedN] of ANCHOR) {
  const p = pairsComplete(rows, ka, kb);
  const rho = spearman(p.xs, p.ys);
  ok(`${label}: rho ${rho.toFixed(4)} rounds to the printed ${printed.toFixed(2)}, N ${p.n} = ${printedN}`,
    Number(rho.toFixed(2)) === printed && p.n === printedN, `${rho.toFixed(4)} / ${p.n}`);
}

// ---------------------------------------------------------------- 5. the three scorings
head('5. the three hit rates, on one footing');

const S3 = suite(cats, 3);
const S1 = suite(cats, 1);
const RATE = { in: S3.inSample / S3.n, loo: S3.loo / S3.n, out: S3.out / S3.n };

ok('in-sample top three = 643 of 861 = 74.7%', S3.inSample === 643 && S3.n === 861, `${S3.inSample}/${S3.n}`);
ok('leave-one-out top three = 550 of 861 = 63.9%', S3.loo === 550, S3.loo);
ok('fully out-of-sample top three = 475 of 861 = 55.2%', S3.out === 475, S3.out);
ok('top word alone: 377 / 349 / 280 of 861',
  S1.inSample === 377 && S1.loo === 349 && S1.out === 280, `${S1.inSample}/${S1.loo}/${S1.out}`);
ok('the cascade is strictly decreasing', S3.inSample > S3.loo && S3.loo > S3.out);

for (const [k, v] of Object.entries(RATE)) {
  const c = ci(Math.round(v * S3.n), S3.n);
  console.log(`       ${k.padEnd(4)} ${pct1(v)}  95% CI ${pct1(c.lo)} to ${pct1(c.hi)}`);
}

// The three big cards are filled in live and ship with a "--" placeholder. The dek carries
// the literals so the sentence still reads with JavaScript off, which means those literals
// are a CLAIM: assert each one equals what the data actually says, so the page cannot go
// stale under its own hero paragraph.
for (const id of ['numIn', 'numLoo', 'numOut']) {
  ok(`#${id} ships as an unfilled placeholder, not a literal`,
    new RegExp('id="' + id + '"[^>]*>--<').test(HTML));
}
for (const [id, v] of [['dekIn', RATE.in], ['dekLoo', RATE.loo], ['dekOut', RATE.out]]) {
  const m = new RegExp('id="' + id + '"[^>]*>([0-9.]+%)<').exec(HTML);
  ok(`the dek literal in #${id} equals the recomputed ${pct1(v)}`, m && m[1] === pct1(v), m ? m[1] : 'absent');
}
// ...but it does state them in prose, where they are claims the verifier must stand behind.
ok('the page states 74.7 somewhere (the dishonest number, named)', /74\.7/.test(HTML));
ok('the page states 63\\.9 somewhere', /63\.9/.test(HTML));
ok('the page states 55\\.2 somewhere', /55\.2/.test(HTML));
ok('the honest number is what the head tags advertise, not 74.7',
  /<meta name="description" content="[^"]*55\.2%/.test(HTML) && /og:title" content="[^"]*74\.7% or 55\.2%/.test(HTML));
ok('the dek does not present 74.7% as the page\'s own result',
  /74\.7% when it is allowed to/.test(HTML) || /grades its own homework/.test(HTML));

// ---------------------------------------------------------------- 6. the free-choice grid
head('6. the free choices, and what each is worth');

const verb = suite(catsFull, 3);
ok('verbatim word merging costs the out-of-sample rate 3.7 points',
  Math.abs(100 * (S3.out - verb.out) / S3.n - 3.7) < 0.05, (100 * (S3.out - verb.out) / S3.n).toFixed(2));
const flip = suite(cats, 3, false);
// suite() has no flip parameter; recompute the reversed tie-break directly.
function outFlip() {
  let h = 0;
  for (const c of cats) {
    const ranked = c.us.slice().sort((a, b) => (b.frf - a.frf) || (a.matched < b.matched ? 1 : a.matched > b.matched ? -1 : 0)).slice(0, 3);
    const asUK = ranked.map((r) => r.uk);
    for (const [m, f] of c.first) if (asUK.indexOf(m) >= 0) h += f;
  }
  return h;
}
ok('the tie-break is worth 5 hits out of 861 (475 alphabetical, 480 reversed)',
  S3.out === 475 && outFlip() === 480, `${S3.out} / ${outFlip()}`);
const tied = cats.filter((c) => {
  const v = c.us.map((u) => u.frf).sort((a, b) => b - a);
  return v.length > 3 && v[2] === v[3];
}).length;
ok('7 of the 44 categories have a tie straddling third place', tied === 7, tied);

// The three numbers the build specification handed down, reproduced on their own footings,
// which is how we know they were three different instruments rather than one.
function allCatsFrom(file) {
  const m = new Map();
  for (const r of readCSV(join(DATA, file))) {
    const f = count(r['first.rank.freq']);
    if (f <= 0) continue;
    if (!m.has(r.category)) m.set(r.category, { c: r.category, n: 0, first: [], us: [] });
    const c = m.get(r.category); c.first.push([r['category.member'], f]); c.n += f;
  }
  return [...m.values()];
}
const a117 = allCatsFrom('bc_item_ref.csv');
const a117f = allCatsFrom('bc_item_full.csv');
const s117 = { in: a117.reduce((s, c) => s + inSample(c).hits, 0), loo: a117.reduce((s, c) => s + leaveOneOut(c).hits, 0), n: a117.reduce((s, c) => s + c.n, 0) };
const s117f = { in: a117f.reduce((s, c) => s + inSample(c).hits, 0), loo: a117f.reduce((s, c) => s + leaveOneOut(c).hits, 0), n: a117f.reduce((s, c) => s + c.n, 0) };
ok("the spec's 74.7% is the referential 117-category count over a flat denominator of 2340",
  Math.abs(100 * s117.in / 2340 - 74.7) < 0.05, (100 * s117.in / 2340).toFixed(2));
ok("the spec's 60.9% is the VERBATIM 117-category leave-one-out, 1387 of 2277",
  s117f.loo === 1387 && s117f.n === 2277, `${s117f.loo}/${s117f.n}`);
ok("the spec's 54.1% is the 44-category out-of-sample over a flat denominator of 880",
  Math.abs(100 * 476 / 880 - 54.1) < 0.05 && Math.abs(100 * S3.out / 880 - 54.0) < 0.06,
  (100 * S3.out / 880).toFixed(2));
ok('so the specified cascade mixed word merging and category set; the matched cascade does not',
  s117.in / s117.n > s117.loo / s117.n && s117f.in / s117f.n > s117f.loo / s117f.n);

// ---------------------------------------------------------------- 7. the matching rule
head('7. the matching rule, folded identically on both sides');

ok('apples folds onto apple', matches('apples', 'apple'));
ok('Carrot, with a capital and a space, folds onto carrot', matches('  Carrot ', 'carrot'));
ok('"a carrot" folds onto carrot', matches('a carrot', 'carrot'));
ok('glass does NOT lose its s', fold('glass') === 'glass');
ok('bus does NOT lose its s', fold('bus') === 'bus');
ok('mum does NOT match mother, and the page says so', !matches('mum', 'mother'));
ok('sailboat does NOT match sailing boat', !matches('sailboat', 'sailing boat'));
ok('an empty word matches nothing', !matches('', 'red') && !matches('!!!', 'red'));

let collisions = [];
for (const c of cats) {
  const seen = new Map();
  for (const w of c.vocab) {
    const f = fold(w);
    if (seen.has(f)) collisions.push([c.c, seen.get(f), w]); else seen.set(f, w);
  }
}
ok('the fold merges exactly 6 pairs of distinct listed members across the 44 categories',
  collisions.length === 6, collisions.length);
ok('and every one of the 6 is a word and its own plural',
  collisions.every(([, a, b]) => b === a + 's' || a === b + 's'), JSON.stringify(collisions));

// ---------------------------------------------------------------- 8. the seal
head('8. the seal, and what it must contain');

const kitSrc = readFileSync(join(ROOT, 'public', '_kit', 'precommit.js'), 'utf8');
const sandbox = { crypto: webcrypto, TextEncoder, console };
vm.createContext(sandbox);
vm.runInContext(kitSrc, sandbox);
const K = sandbox.AW.precommit;

// The audit the page's honesty rests on: a commitment to three words, without a commitment
// to how those words will be marked, is not a commitment at all.
function auditSeal(sealed) {
  const t = K.revealText(sealed);
  const problems = [];
  if (!/"matchingRule"/.test(t)) problems.push('no matching rule');
  if (!/"scoringRule"/.test(t)) problems.push('no scoring rule');
  if (!/"rankingRule"/.test(t)) problems.push('no ranking rule');
  if (!/"predictsBritishTopThree"/.test(t) && !/"predictsAmerican2004TopThree"/.test(t)) problems.push('no prediction');
  if (!/"dataset"/.test(t)) problems.push('no dataset identity');
  return problems;
}
const goodSeal = await K.seal({
  round: 1, category: 'colour', dataset: 'norms.json sha256 deadbeef',
  predictsBritishTopThree: topK(cats.find((c) => c.c === 'colour').first),
  predictsAmerican2004TopThree: ['red', 'blue', 'green'],
  rankingRule: RANK_RULE, matchingRule: MATCH_RULE, scoringRule: SCORE_RULE,
});
ok('a complete seal passes the audit', auditSeal(goodSeal).length === 0, auditSeal(goodSeal).join('; '));
ok('the digest verifies against its own preimage', await K.verify(goodSeal.hash, K.revealText(goodSeal)));
ok('and does not verify against a tampered preimage',
  !(await K.verify(goodSeal.hash, K.revealText(goodSeal).replace('colour', 'colours'))));
ok('the shell command reproduces the digest',
  K.shellCommand(K.revealText(goodSeal)).startsWith('printf %s ') &&
  sha(K.revealText(goodSeal)) === goodSeal.hash);

// NEGATIVE CONTROL: a seal that names three words but not how they will be marked.
const naked = await K.seal({ round: 1, category: 'colour', dataset: 'x', predictsBritishTopThree: ['red', 'blue', 'orange'] });
const nakedProblems = auditSeal(naked);
ok('NEGATIVE: a seal with no matching rule is caught',
  nakedProblems.includes('no matching rule') && nakedProblems.includes('no scoring rule'), nakedProblems.join('; '));

ok('the page seals the matching rule, the ranking rule and the scoring rule',
  /matchingRule: MATCH_RULE/.test(HTML) && /scoringRule: SCORE_RULE/.test(HTML) && /rankingRule: RANK_RULE/.test(HTML));
ok('the page ships the same three rule texts the verifier uses',
  HTML.includes(MATCH_RULE.replace(/'/g, "\\'")) || HTML.includes(MATCH_RULE),
  'match rule drift between page and verifier');
ok('the page holds its input disabled until the digest exists',
  /id="answer"[^>]*disabled/.test(HTML) && /input\.disabled = false;/.test(HTML));

// ---------------------------------------------------------------- 9. the chance control
head('9. the chance control, run with enough rounds to have power');

// The SAME judging path the live round uses. If the control needed its own copy of the
// scorer it would be testing a function no reader ever plays against.
const machine = {
  guessesFor(cat, mode) {
    if (mode === 'out') return outOfSample(cat).asUK.filter(Boolean);
    return topK(cat.first);
  },
  judge(cat, mode, word) { return hit(this.guessesFor(cat, mode), word); },
};
const ROUNDS = 400;
let ch3 = 0, chN = 0, exp3 = 0, atChance = 0, ch1 = 0, exp1 = 0;
for (const c of cats) {
  const folded = [...new Set(c.vocab.map(fold).filter(Boolean))];
  const guesses = [...new Set(machine.guessesFor(c, 'out').map(fold).filter(Boolean))];
  const res = K.chanceControl({ predict: () => guesses[0] || '' }, ROUNDS, folded);
  ch1 += res.hits; exp1 += guesses.length ? ROUNDS / folded.length : 0;
  if (res.atChance) atChance++;
  const draw = K.randomOpponent(c.vocab);
  for (let i = 0; i < ROUNDS; i++) { if (machine.judge(c, 'out', draw())) ch3++; chN++; }
  // The draw is over the UNFOLDED vocabulary, so the exact hit probability is the share of
  // vocabulary entries that fold onto a guess, not the share of distinct folded words. Six
  // singular/plural pairs in these 44 categories collapse under the fold, and using the
  // folded count would put the baseline slightly in the predictor's favour.
  const gset = new Set(guesses);
  exp3 += ROUNDS * c.vocab.filter((w) => gset.has(fold(w))).length / c.vocab.length;
}
const c3 = ci(ch3, chN), c1 = ci(ch1, chN);
const b3 = exp3 / chN, b1 = exp1 / chN;
console.log(`       top three vs CSPRNG: ${ch3}/${chN} = ${pct1(ch3 / chN)}, 95% CI ${pct1(c3.lo)} to ${pct1(c3.hi)}, exact baseline ${pct1(b3)}`);
console.log(`       top word  vs CSPRNG: ${ch1}/${chN} = ${pct1(ch1 / chN)}, 95% CI ${pct1(c1.lo)} to ${pct1(c1.hi)}, exact baseline ${pct1(b1)}`);
// The assertion uses a 99.9% interval, not the 95% printed above. At n = 17600 the true rate
// IS the baseline, so a 95% containment test would fail one run in twenty by construction:
// a check that cries wolf 5% of the time teaches everyone to ignore it.
const w3 = ci(ch3, chN, 0.999), w1 = ci(ch1, chN, 0.999);
ok('the top-three predictor is at chance against a CSPRNG', w3.lo <= b3 && b3 <= w3.hi, `${pct1(ch3 / chN)} vs ${pct1(b3)}`);
ok('the top-word predictor is at chance against a CSPRNG', w1.lo <= b1 && b1 <= w1.hi, `${pct1(ch1 / chN)} vs ${pct1(b1)}`);
ok('n = 17600 draws, not 20: the control has power', chN === 44 * ROUNDS, chN);
ok('the same predictor against real people is far above that baseline', RATE.out > b3 * 5, `${pct1(RATE.out)} vs ${pct1(b3)}`);
// The per-category verdicts are 44 independent 95% interval tests, so about 2.2 of them are
// expected to exclude the truth even when everything is correct. A hard threshold here would
// be a flaky assertion pretending to be a check, so the bound is derived: the smallest number
// of exclusions whose upper tail under Binomial(44, 0.05) is below one in a thousand.
let maxExcl = 1;
while (1 - K.cdf(maxExcl - 1, cats.length, 0.05) >= 0.001) maxExcl++;
const excl = cats.length - atChance;
ok(`per-category kit verdicts at chance: ${atChance} of 44, ${excl} exclusions, bound ${maxExcl}`,
  excl < maxExcl, `${excl} >= ${maxExcl}`);

// NEGATIVE CONTROL: hand chanceControl a predictor that can see the answer, and demand it
// says so. A control that certifies everything certifies nothing.
let peeked = null;
const cheat = {
  predict: () => peeked,
  observe: () => {},
};
const alphabet = ['a', 'b', 'c', 'd'];
// Rebuild the draw so the cheat sees the value before predicting: emulate by predicting the
// symbol that the next draw will be, using a fixed opponent.
const fixedDraw = K.randomOpponent(alphabet);
let cheatHits = 0;
for (let i = 0; i < 600; i++) { const a = fixedDraw(); peeked = a; if (cheat.predict() === a) cheatHits++; }
const cc = ci(cheatHits, 600);
ok('NEGATIVE: a predictor that sees the answer is NOT reported at chance',
  !(cc.lo <= 0.25 && 0.25 <= cc.hi), `${cheatHits}/600`);

// ---------------------------------------------------------------- 10. break the mechanism
head('10. negative controls: break it and demand the check notices');

// (a) shuffle the American first-rank column inside each category.
function shuffledOut(seed) {
  let s = seed >>> 0;
  const rnd = () => { s ^= s << 13; s >>>= 0; s ^= s >> 17; s ^= s << 5; s >>>= 0; return s / 4294967296; };
  let h = 0;
  for (const c of cats) {
    const vals = c.us.map((u) => u.frf);
    for (let i = vals.length - 1; i > 0; i--) { const j = Math.floor(rnd() * (i + 1)); const t = vals[i]; vals[i] = vals[j]; vals[j] = t; }
    const shuffled = c.us.map((u, i) => ({ matched: u.matched, uk: u.uk, frf: vals[i] }));
    h += outOfSample({ c: c.c, n: c.n, first: c.first, us: shuffled }).hits;
  }
  return h;
}
const shuf = [];
for (let s = 1; s <= 200; s++) shuf.push(shuffledOut(s * 7919));
const shufMean = shuf.reduce((a, b) => a + b, 0) / shuf.length;
const shufMax = Math.max(...shuf);
console.log(`       shuffled: mean ${shufMean.toFixed(1)}/861 = ${pct1(shufMean / 861)}, best of 200 = ${shufMax}`);
ok('NEGATIVE: shuffling the American frequencies collapses the out-of-sample rate to near chance',
  shufMean / 861 < 0.16, pct1(shufMean / 861));
ok('NEGATIVE: not one of 200 shuffles reached the real 475 hits', shufMax < S3.out, shufMax);

// (b) rank the WORST three instead of the best. If this does not collapse, the ranking
// rule is not doing the work the page says it is.
function worstThree(cat) {
  const asc = cat.first.slice().sort((a, b) => (a[1] - b[1]) || (a[0] < b[0] ? -1 : 1)).slice(0, 3).map((p) => p[0]);
  let h = 0; for (const [m, f] of cat.first) if (asc.indexOf(m) >= 0) h += f;
  return h;
}
const worst = cats.reduce((s, c) => s + worstThree(c), 0);
// 194, not 0: in a category where only three or four words were ever said first, the worst
// three and the best three overlap. That is itself the empty-tail problem the page is about.
ok('NEGATIVE: taking the three LEAST-said words drops in-sample from 643 to 194',
  worst === 194 && worst < S3.inSample / 3, worst);

// (c) break the fold and demand a known match stops working.
const brokenFold = (s) => String(s).toUpperCase();
ok('NEGATIVE: a fold that does not lowercase stops apples matching apple',
  brokenFold('Apples') !== brokenFold('apple'));

// (d) leave-one-out must be strictly harder than in-sample, category by category, never easier.
const looEasier = cats.filter((c) => leaveOneOut(c).hits > inSample(c).hits).length;
ok('NEGATIVE: leave-one-out never beats in-sample in any category', looEasier === 0, looEasier);

// ---------------------------------------------------------------- 11. Yoon's whitelist
head("11. Yoon et al. (2004)'s thirteen-category whitelist, tested out of sample");

const YOON = ['unit of time', 'colour', 'metal', 'fruit', 'chemical element', 'part of the body'];
const per = {};
for (const c of cats) per[c.c] = { h: outOfSample(c).hits, n: c.n };
const pooled = (names) => { let h = 0, n = 0; for (const k of names) { h += per[k].h; n += per[k].n; } return { h, n, r: h / n }; };
const A = pooled(YOON);
const B = pooled(cats.map((c) => c.c).filter((n) => !YOON.includes(n)));
ok('all six whitelisted names exist in the 44', YOON.every((y) => per[y] !== undefined));
ok('whitelisted categories: 85 of 119 = 71.4%', A.h === 85 && A.n === 119, `${A.h}/${A.n}`);
ok('the other 38: 390 of 742 = 52.6%', B.h === 390 && B.n === 742, `${B.h}/${B.n}`);
// Category-level permutation, deterministic seed, because the responses inside a category
// are not independent draws and a per-response interval would overstate the precision.
let s2 = 123456789 >>> 0;
const rnd2 = () => { s2 ^= s2 << 13; s2 >>>= 0; s2 ^= s2 >> 17; s2 ^= s2 << 5; s2 >>>= 0; return s2 / 4294967296; };
const names = cats.map((c) => c.c);
const obs = A.r - B.r;
let ge = 0; const R = 50000;
for (let t = 0; t < R; t++) {
  const pool = names.slice(); const pick = [];
  for (let i = 0; i < 6; i++) pick.push(pool.splice(Math.floor(rnd2() * pool.length), 1)[0]);
  if (pooled(pick).r - pooled(pool).r >= obs - 1e-12) ge++;
}
const pPerm = ge / R;
console.log(`       difference ${(100 * obs).toFixed(1)} points, permutation p = ${pPerm.toFixed(4)}`);
ok('the whitelist advantage is real but marginal at the category level (0.02 < p < 0.10)',
  pPerm > 0.02 && pPerm < 0.10, pPerm.toFixed(4));
ok('the page prints the permutation p rather than a verdict', /permutation p/.test(HTML) && /suggestive, not settled/.test(HTML));

// ---------------------------------------------------------------- 12. per-category extremes
head('12. the per-category spread the page prints in prose');

const rateOf = (name) => per[name].h / per[name].n;
ok('weapon 0.95', Math.abs(rateOf('weapon') - 0.95) < 1e-9, rateOf('weapon'));
ok('family relationship 0.00', rateOf('family relationship') === 0);
ok('weather 0.00', rateOf('weather') === 0);
ok('drug 0.05', Math.abs(rateOf('drug') - 0.05) < 1e-9, rateOf('drug'));
ok('the American top three for family relationship is aunt, mom, cousin',
  topK(cats.find((c) => c.c === 'family relationship').us.map((u) => [u.matched, u.frf])).join(',') === 'aunt,mom,cousin');
ok('the British top three for family relationship is mother, brother, father',
  topK(cats.find((c) => c.c === 'family relationship').first).join(',') === 'mother,brother,father');
ok('the American top three for weather is tornado, hurricane, rain',
  topK(cats.find((c) => c.c === 'weather').us.map((u) => [u.matched, u.frf])).join(',') === 'tornado,hurricane,rain');
ok('the British top three for weather is rainy, sunny, cold',
  topK(cats.find((c) => c.c === 'weather').first).join(',') === 'rainy,sunny,cold');
// four-wheeled vehicle: the emptiest tail in the whole dataset.
const fw = a117.find((c) => c.c === 'four-wheeled vehicle');
ok('four-wheeled vehicle in-sample top three is car, benz, van', topK(fw.first).join(',') === 'car,benz,van');
ok('and benz and van were each said first by exactly one person',
  fw.first.find((p) => p[0] === 'benz')[1] === 1 && fw.first.find((p) => p[0] === 'van')[1] === 1);
ok('2 of the 44, and 16 of the 117, reach a perfect in-sample score',
  cats.filter((c) => inSample(c).hits === c.n).length === 2 && a117.filter((c) => inSample(c).hits === c.n).length === 16,
  `${cats.filter((c) => inSample(c).hits === c.n).length} / ${a117.filter((c) => inSample(c).hits === c.n).length}`);

// ---------------------------------------------------------------- 13. the page itself
head('13. the rendered page');

const inlined = /<script type="application\/json" id="norms">([\s\S]*?)<\/script>/.exec(HTML);
ok('the page carries an inlined norms block', !!inlined);
const built = readFileSync(join(here, 'norms.json'), 'utf8');
ok('and it is byte-identical to what build-norms.mjs emits from the CSVs',
  inlined && inlined[1] === built, inlined ? `${inlined[1].length} vs ${built.length}` : 'n/a');
const inlineDigest = sha(inlined ? inlined[1] : '');
console.log('       inlined norms sha256 ' + inlineDigest);
ok('the norms JSON parses', (() => { try { JSON.parse(inlined[1]); return true; } catch { return false; } })());

const scripts = [...HTML.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)];
const own = scripts.filter((m) => !/\bsrc=/.test(m[1]) && !/json/i.test(m[1]));
ok('the page has exactly one script of its own', own.length === 1, own.length);
ok('it loads the shared precommit kit', /_kit\/precommit\.js/.test(HTML));
ok('closing tags present', /<\/body>/i.test(HTML) && /<\/html>/i.test(HTML));
ok('script tags balanced', (HTML.match(/<script\b/gi) || []).length === (HTML.match(/<\/script>/gi) || []).length);

let offenders = [];
for (const m of scripts) {
  for (const u of m[2].matchAll(/https?:\/\/[^\s"'`)]+/g)) {
    if (!/^https?:\/\/(schema\.org|artwaste\.land)/.test(u[0])) offenders.push(u[0]);
  }
}
ok('no third-party URL in any script body, in any syntactic form', offenders.length === 0, offenders.slice(0, 3).join(' '));
ok('no fetch, XHR or WebSocket anywhere in the page',
  !/\bfetch\s*\(|XMLHttpRequest|WebSocket|EventSource|navigator\.sendBeacon/.test(HTML));
ok('no em dash in the page', !HTML.includes('\u2014'));
ok('accessibility: aria-live readouts present', (HTML.match(/aria-live="polite"/g) || []).length >= 6);
ok('accessibility: prefers-reduced-motion guard', /prefers-reduced-motion/.test(HTML));
ok('accessibility: focus-visible outline', /:focus-visible/.test(HTML));
ok('self-hosted fonts only', /href="\/fonts\/fonts\.css"/.test(HTML) && !/fonts\.googleapis|fonts\.gstatic/.test(HTML));
ok('head tags: title, description, canonical, og, twitter, JSON-LD',
  /<title>/.test(HTML) && /<meta name="description"/.test(HTML) && /rel="canonical"/.test(HTML) &&
  /property="og:title"/.test(HTML) && /name="twitter:card"/.test(HTML) && /application\/ld\+json/.test(HTML));
const ld = JSON.parse(/<script type="application\/ld\+json">([\s\S]*?)<\/script>/.exec(HTML)[1]);
ok('JSON-LD is a well-formed Article with the right url and date',
  ld['@type'] === 'Article' && ld.url === 'https://artwaste.land/strata/the-word-you-were-going-to-say/' && ld.datePublished === '2026-08-13');
ok('the page tells the reader nothing leaves the browser, and it is true',
  /Nothing you type leaves your browser/.test(HTML));
ok('the way out has its own section', /id="the-way-out"/.test(HTML));
ok('the chance control is on the page as a button', /chanceControl\s*\(/.test(HTML) && /id="runChance"/.test(HTML));
ok('the ledger and the exact interval are used', /ledger\s*\(/.test(HTML) && /K\.ci\s*\(/.test(HTML));
ok('the shell escape hatch is printed', /shellCommand\s*\(/.test(HTML));
ok('revealText is the only reveal path', /revealText\s*\(/.test(HTML) && !/reveal.*textContent\s*=\s*JSON\.stringify/.test(HTML));

// ---------------------------------------------------------------- 14. the frontmatter
head('14. the frontmatter, which is a set of claims');

const fm = /^---\n([\s\S]*?)\n---/.exec(MD);
ok('frontmatter parses', !!fm);
const fmText = fm ? fm[1] : '';
for (const key of ['title:', 'date:', 'dek:', 'plain:', 'seoTitle:', 'seam:', 'tags:', 'href:', 'relates:', 'draft: false']) {
  ok('frontmatter has ' + key, fmText.includes(key));
}
ok('seam is language', /seam:\s*"language"/.test(fmText));
ok('href points at the page', /href:\s*"\/strata\/the-word-you-were-going-to-say\/"/.test(fmText));
ok('tags include immersive and interactive', /"immersive"/.test(fmText) && /"interactive"/.test(fmText));
ok('the dek quotes the honest number, 55.2', /55\.2/.test(fmText));
ok('the dek names all three rates', /74\.7/.test(fmText) && /63\.9/.test(fmText) && /55\.2/.test(fmText));
ok('the dek does not claim the page reads minds', !/mind.read|reads your mind/i.test(fmText));
ok('the plain paragraph exists and avoids jargon',
  /plain:\s*"/.test(fmText) && !/leave-one-out|Clopper|lemmati/i.test(/plain:\s*"([^"]*)"/.exec(fmText)?.[1] || ''));
const relatesSlugs = [...fmText.matchAll(/- to:\s*([a-z0-9-]+)/g)].map((m) => m[1]);
ok('2 to 4 relates edges', relatesSlugs.length >= 2 && relatesSlugs.length <= 4, relatesSlugs.length);
for (const slug of relatesSlugs) {
  let exists = true;
  try { readFileSync(join(ROOT, 'src', 'content', 'strata', slug + '.md')); } catch { exists = false; }
  ok('relates target exists: ' + slug, exists);
}
ok('no em dash in the content file', !MD.includes('\u2014'));

// ---------------------------------------------------------------- 15. kit agreement
head('15. the verifier and the kit agree on the arithmetic');

for (const [k, n] of [[643, 861], [550, 861], [475, 861], [7, 10], [0, 20], [20, 20]]) {
  const mine = ci(k, n), theirs = K.ci(k, n);
  ok(`Clopper-Pearson agrees with the kit at ${k}/${n}`,
    Math.abs(mine.lo - theirs.lo) < 1e-9 && Math.abs(mine.hi - theirs.hi) < 1e-9,
    `${mine.lo} vs ${theirs.lo}`);
}
const c710 = K.ci(7, 10);
ok('7 of 10 really does have a 95% interval of 34.8% to 93.3%, as the page says',
  Math.abs(100 * c710.lo - 34.8) < 0.05 && Math.abs(100 * c710.hi - 93.3) < 0.05,
  `${pct1(c710.lo)} to ${pct1(c710.hi)}`);
ok('the page prints that interval', /34\.8% to 93\.3%/.test(HTML));

// ---------------------------------------------------------------- done
console.log(`\n${pass} passed, ${fail} failed`);
process.exit(fail === 0 ? 0 : 1);
