#!/usr/bin/env node
/* verify-nobody-speaks-the-other-four-thousand.mjs
 *
 * Offline verifier for /strata/nobody-speaks-the-other-four-thousand/.
 *
 * The partition logic here is written from scratch rather than imported from
 * research/sibling-partitions/extract.mjs, so that this file is a second engine and not
 * a restatement of the first. It recomputes every language's sibling system from the
 * recorded form strings carried in findings.json, and then checks that the shipped
 * page's aggregates, its data bundle, and its prose all agree with that recomputation.
 *
 *   node verify-nobody-speaks-the-other-four-thousand.mjs
 *   node verify-nobody-speaks-the-other-four-thousand.mjs --mutate   (controls must go red)
 */

import fs from 'node:fs';
import path from 'node:path';
import url from 'node:url';

const ROOT = path.dirname(url.fileURLToPath(import.meta.url));
const R = (p) => path.join(ROOT, p);
const MUTATE = process.argv.includes('--mutate');

let pass = 0, fail = 0;
const failures = [];
function ok(cond, label, detail) {
  if (cond) { pass++; return true; }
  fail++; failures.push(label + (detail ? `  [${detail}]` : ''));
  return false;
}
const eq = (a, b, label) => ok(a === b, label, `got ${JSON.stringify(a)}, want ${JSON.stringify(b)}`);
const near = (a, b, tol, label) => ok(Math.abs(a - b) <= tol, label, `got ${a}, want ${b}±${tol}`);

// ---------------------------------------------------------------- load

const FIND = R('research/sibling-partitions/findings.json');
const DATA = R('public/strata/nobody-speaks-the-other-four-thousand/data.json');
const HTML = R('public/strata/nobody-speaks-the-other-four-thousand/index.html');
const PAGEJS = R('public/strata/nobody-speaks-the-other-four-thousand/page.js');
const MD = R('src/content/strata/nobody-speaks-the-other-four-thousand.md');
const SOURCES = R('research/sibling-partitions/SOURCES.md');

for (const f of [FIND, DATA, HTML, PAGEJS, MD, SOURCES]) {
  ok(fs.existsSync(f), `file present: ${path.relative(ROOT, f)}`);
}
if (fail) { report(); process.exit(1); }

const F = JSON.parse(fs.readFileSync(FIND, 'utf8'));
const D = JSON.parse(fs.readFileSync(DATA, 'utf8'));
const html = fs.readFileSync(HTML, 'utf8');
const pagejs = fs.readFileSync(PAGEJS, 'utf8');
const md = fs.readFileSync(MD, 'utf8');
const sources = fs.readFileSync(SOURCES, 'utf8');

const CELLS = ['meB', 'myB', 'meZ', 'myZ', 'feB', 'fyB', 'feZ', 'fyZ'];

// ---------------------------------------------------------------- engine two
// An independent implementation of everything the page claims to compute.

function bell2(n) {
  // Bell via Stirling summation, a different recurrence from the triangle used upstream.
  let t = 0;
  for (let k = 0; k <= n; k++) t += stir2(n, k);
  return t;
}
function stir2(n, k) {
  // Explicit inclusion-exclusion formula, again deliberately not the DP used upstream.
  if (k === 0) return n === 0 ? 1 : 0;
  let s = 0;
  for (let j = 0; j <= k; j++) {
    const c = binom(k, j);
    s += ((k - j) % 2 ? -1 : 1) * c * Math.pow(j, n);
  }
  return Math.round(s / fact(k));
}
function binom(n, k) { let r = 1; for (let i = 0; i < k; i++) r = r * (n - i) / (i + 1); return Math.round(r); }
function fact(n) { let r = 1; for (let i = 2; i <= n; i++) r *= i; return r; }

function norm2(s) {
  if (s == null) return '';
  return s.normalize('NFD').replace(/\p{M}+/gu, '').toLowerCase()
    .replace(/[\s\-'’ʼ`.,;:()[\]{}?!*"“”]/g, '').trim();
}

function canon(labels) {
  const seen = new Map(); let n = 0; let out = '';
  for (const l of labels) { if (!seen.has(l)) seen.set(l, n++); out += seen.get(l); }
  return out;
}

function systemOf(formsByCell, convention) {
  const sets = CELLS.map((c) => (formsByCell[c] || []).map(norm2).filter(Boolean));
  if (sets.some((s) => s.length === 0)) return null;
  if (convention === 'FIRST') return canon(sets.map((s) => s[0]));
  if (convention === 'STRICT') return canon(sets.map((s) => [...new Set(s)].sort().join('')));
  // OVERLAP: link on any shared form, then take connected components by BFS
  const adj = Array.from({ length: 8 }, () => []);
  for (let i = 0; i < 8; i++) for (let j = i + 1; j < 8; j++) {
    if (sets[i].some((v) => sets[j].includes(v))) { adj[i].push(j); adj[j].push(i); }
  }
  const comp = new Array(8).fill(-1);
  let c = 0;
  for (let i = 0; i < 8; i++) {
    if (comp[i] !== -1) continue;
    const q = [i]; comp[i] = c;
    while (q.length) { const x = q.pop(); for (const y of adj[x]) if (comp[y] === -1) { comp[y] = c; q.push(y); } }
    c++;
  }
  return canon(comp);
}

// ---------------------------------------------------------------- the space

eq(bell2(8), 4140, 'Bell(8) recomputed independently is 4140');
eq(F.space.totalPartitions, 4140, 'findings.json records the space as 4140');
eq(D.space.totalPartitions, 4140, 'data.json records the space as 4140');
let stirSum = 0;
for (let k = 1; k <= 8; k++) {
  const s = stir2(8, k);
  stirSum += s;
  eq(F.space.stirling[k], s, `Stirling(8,${k}) in findings.json`);
  eq(D.blocks[k].possible, s, `data.json block table: ${k} words has ${s} possible arrangements`);
}
eq(stirSum, 4140, 'the eight Stirling numbers sum to Bell(8)');
eq(stir2(8, 1), 1, 'exactly one way to spend one word');
eq(stir2(8, 8), 1, 'exactly one way to spend eight words');
eq(stir2(8, 4), 1701, 'the widest column is four words, at 1701');
ok(stir2(8, 4) === Math.max(...[1, 2, 3, 4, 5, 6, 7, 8].map((k) => stir2(8, k))), 'four words is the widest column');

// ---------------------------------------------------------------- recompute every language

const CONV = ['STRICT', 'FIRST', 'OVERLAP'];
let recomputed = 0, mismatched = 0;
const mine = { STRICT: new Map(), FIRST: new Map(), OVERLAP: new Map() };
for (const l of F.languages) {
  recomputed++;
  for (const c of CONV) {
    const s = systemOf(l.forms, c);
    if (s !== l.sys[c]) { mismatched++; if (mismatched <= 5) failures.push(`recompute mismatch ${l.name} ${c}: ${s} vs ${l.sys[c]}`); }
    mine[c].set(s, (mine[c].get(s) || 0) + 1);
  }
}
eq(mismatched, 0, `second engine reproduces all ${recomputed} languages under all three rules`);
eq(recomputed, F.corpus.languagesWithCompleteSiblingSet, 'record count matches the stated corpus size');

for (const c of CONV) {
  eq(mine[c].size, F.byConvention[c].distinctAttested, `distinct systems under ${c}, recomputed`);
}

// every attested pattern is a well-formed restricted-growth string over 8 cells
let rgsBad = 0;
for (const c of CONV) for (const s of mine[c].keys()) {
  if (s.length !== 8) rgsBad++;
  else { let mx = -1; for (const ch of s) { const v = Number(ch); if (v > mx + 1) rgsBad++; mx = Math.max(mx, v); } }
}
eq(rgsBad, 0, 'every attested pattern is a canonical restricted-growth string');

// canonicalisation really is canonical: relabelling a partition must not change it
{
  let bad = 0;
  for (const s of [...mine.STRICT.keys()].slice(0, 40)) {
    const labels = s.split('').map(Number);
    const perm = [7, 3, 5, 0, 6, 1, 4, 2];
    const relabelled = labels.map((v) => perm[v % 8]);
    if (canon(relabelled) !== s) bad++;
  }
  eq(bad, 0, 'canonical form is invariant under relabelling the words');
}

// ---------------------------------------------------------------- deduplicated basis

const byG = new Map();
for (const l of F.languages) {
  const k = l.glottocode || 'x:' + l.id;
  if (!byG.has(k)) byG.set(k, []);
  byG.get(k).push(l);
}
const oneEach = [...byG.values()].map((r) =>
  r.slice().sort((a, b) => a.multiFormCells - b.multiFormCells || a.name.localeCompare(b.name) || a.id.localeCompare(b.id))[0]);
eq(oneEach.length, D.corpus.languages, 'deduplicated language count in data.json');
eq(D.corpus.languages, 942, 'the page counts 942 languages');
eq(F.corpus.languagesWithCompleteSiblingSet, 1023, 'and 1023 records before deduplication');
eq(F.corpus.languagesWithCompleteSiblingSet - D.corpus.languages, 81, 'so 81 records are second descriptions');

const dedupCounts = new Map();
for (const l of oneEach) dedupCounts.set(l.sys.STRICT, (dedupCounts.get(l.sys.STRICT) || 0) + 1);
eq(dedupCounts.size, D.types.length, 'type count in data.json matches the deduplicated recomputation');
eq(D.types.length, 90, 'the headline: 90 of the 4140 arrangements are in use');
ok(D.types.length < 4140 * 0.03, '90 is under three per cent of the space');

let sumN = 0;
for (const t of D.types) {
  eq(t.n, dedupCounts.get(t.rgs), `type ${t.rgs} count`);
  sumN += t.n;
  eq(new Set(t.rgs.split('')).size, t.blocks, `type ${t.rgs} block count is self-consistent`);
  ok(t.families >= 1 && t.families <= t.n, `type ${t.rgs} family count is in range`);
  ok(Array.isArray(t.eg), `type ${t.rgs} has an example list`);
}
eq(sumN, 942, 'the type counts sum to 942');
eq(D.types.filter((t) => t.n === 1).length, 48, '48 arrangements are used by exactly one language');

// block table consistency
let blkLangs = 0, blkAtt = 0;
for (let k = 1; k <= 8; k++) {
  const t = D.types.filter((x) => x.blocks === k);
  eq(D.blocks[k].attested, t.length, `block table: ${k} words, attested count`);
  eq(D.blocks[k].languages, t.reduce((s, x) => s + x.n, 0), `block table: ${k} words, language count`);
  ok(D.blocks[k].attested <= D.blocks[k].possible, `block table: ${k} words, attested cannot exceed possible`);
  blkLangs += D.blocks[k].languages; blkAtt += D.blocks[k].attested;
}
eq(blkLangs, 942, 'block table languages sum to 942');
eq(blkAtt, 90, 'block table attested sums to 90');
eq(D.blocks[1].languages, 22, '22 languages use a single word for every sibling');
eq(D.blocks[8].languages, 8, '8 languages name all eight relationships apart');
eq(D.blocks[4].attested, 21, '21 of the 1701 four-word arrangements are used');
eq(D.blocks[4].languages, 374, '374 languages use one of those 21');

// the headline shape: the emptiest column is the widest one
{
  const share = (k) => D.blocks[k].attested / D.blocks[k].possible;
  const mid = [3, 4, 5];
  const edge = [1, 8];
  ok(Math.min(...edge.map(share)) > Math.max(...mid.map(share)),
    'the space is proportionally emptiest in the middle, where it is widest');
  ok(share(4) < 0.02, 'under two per cent of four-word arrangements are used');
}

// ---------------------------------------------------------------- replication

{
  let indep = 0, agree = 0, shared = 0, sharedAgree = 0;
  for (const recs of byG.values()) {
    if (recs.length < 2) continue;
    for (let i = 0; i < recs.length; i++) for (let j = i + 1; j < recs.length; j++) {
      const a = recs[i], b = recs[j];
      const overlap = a.sources.some((s) => b.sources.includes(s));
      const same = a.sys.STRICT === b.sys.STRICT;
      if (overlap) { shared++; if (same) sharedAgree++; }
      else { indep++; if (same) agree++; }
    }
  }
  eq(indep, F.replication.STRICT.independentPairs, 'independent duplicate pairs, recomputed');
  eq(agree, F.replication.STRICT.independentAgree, 'independent pairs that agree, recomputed');
  eq(indep, 55, 'there are 55 independent duplicate pairs');
  eq(agree, 28, 'of which 28 agree');
  near(agree / indep, 0.509, 0.002, 'independent replication rate is 50.9 per cent');
  eq(shared, F.replication.STRICT.sameSourcePairs, 'same-source pairs, recomputed');
  eq(sharedAgree, F.replication.STRICT.sameSourceAgree, 'same-source agreeing pairs, recomputed');
  ok(sharedAgree / shared > agree / indep, 'same-source pairs agree more often than independent ones');
  ok(sharedAgree / shared < 1, 'even same-source pairs do not always agree, which is the floor the page claims');
  eq(byG.size, D.corpus.languages, 'glottocode groups equal the deduplicated language count');
  eq([...byG.values()].filter((r) => r.length > 1).length, 65, '65 languages are described more than once');
}

// ---------------------------------------------------------------- conventions and views

for (const c of CONV) {
  const dd = new Set(oneEach.map((l) => l.sys[c]));
  eq(dd.size, F.views[c].oneRecordPerLanguage.distinct, `deduplicated distinct count under ${c}`);
  const famOf = new Map();
  for (const l of oneEach) { if (!famOf.has(l.sys[c])) famOf.set(l.sys[c], new Set()); famOf.get(l.sys[c]).add(l.family); }
  eq([...famOf.values()].filter((s) => s.size >= 2).length, F.views[c].oneRecordPerLanguage.inTwoOrMoreFamilies,
    `systems in two or more families under ${c}`);
}
eq(F.views.STRICT.oneRecordPerLanguage.distinct, 90, 'STRICT gives 90 systems');
eq(F.views.FIRST.oneRecordPerLanguage.distinct, 87, 'FIRST gives 87');
eq(F.views.OVERLAP.oneRecordPerLanguage.distinct, 84, 'OVERLAP gives 84');
ok(F.views.STRICT.oneRecordPerLanguage.inTwoOrMoreFamilies < 36, 'fewer than three dozen systems cross a family line');
for (const c of CONV) {
  ok(F.views[c].lexemeOnly.distinct < F.views[c].oneRecordPerLanguage.distinct,
    `dropping phrase-coded records lowers the count under ${c}, as the page says it does`);
}

// pairwise agreement between conventions
{
  const pairAgree = (a, b) => F.languages.filter((l) => l.sys[a] === l.sys[b]).length;
  eq(pairAgree('STRICT', 'FIRST'), F.agreement['STRICT~FIRST'].same, 'STRICT~FIRST agreement recomputed');
  eq(pairAgree('STRICT', 'OVERLAP'), F.agreement['STRICT~OVERLAP'].same, 'STRICT~OVERLAP agreement recomputed');
  eq(pairAgree('FIRST', 'OVERLAP'), F.agreement['FIRST~OVERLAP'].same, 'FIRST~OVERLAP agreement recomputed');
  for (const k of Object.keys(F.agreement)) {
    eq(F.agreement[k].same + F.agreement[k].differ, 1023, `${k} pair counts sum to 1023`);
  }
}

// ---------------------------------------------------------------- the dedup tiebreak
// The page claims that preferring the more readable of two records would move the count,
// which is why it does not do that. Recompute both picks and confirm the movement.

{
  const tb = F.dedup.tiebreakSensitivity;
  const pickBy = (cmp) => [...byG.values()].map((r) => r.slice().sort(cmp)[0]);
  const byName = pickBy((a, b) => a.multiFormCells - b.multiFormCells || a.name.localeCompare(b.name) || a.id.localeCompare(b.id));
  const byPlain = pickBy((a, b) => a.multiFormCells - b.multiFormCells || a.nonAscii - b.nonAscii || a.name.localeCompare(b.name) || a.id.localeCompare(b.id));
  for (const c of CONV) {
    eq(new Set(byName.map((l) => l.sys[c])).size, tb['by name only'][c], `tiebreak by name, ${c}, recomputed`);
    eq(new Set(byPlain.map((l) => l.sys[c])).size, tb['plainest (not used)'][c], `tiebreak by plainness, ${c}, recomputed`);
  }
  eq(tb['by name only'].STRICT, 90, 'the tiebreak actually used gives 90');
  eq(tb['plainest (not used)'].STRICT, 88, 'the readable tiebreak would give 88');
  ok(tb['by name only'].STRICT !== tb['plainest (not used)'].STRICT,
    'so it is a choice about the answer, not a tiebreak, exactly as the page says');
  eq(new Set(byName.map((l) => l.sys.STRICT)).size, D.types.length, 'the page ships the by-name count');
  for (const c of CONV) ok(tb['plainest (not used)'][c] < tb['by name only'][c], `and the readable rule is lower under ${c}`);
  ok(html.includes('is not a tiebreak'), 'the page states the principle it is applying');
}

// ---------------------------------------------------------------- the external key we miss

{
  const k = F.externalKey;
  eq(k.publishedKinbankTypeCount, 116, 'the published Kinbank sibling-type count is 116');
  eq(k.reachesPublished, false, 'no variant of this recount reaches 116');
  const dists = F.sensitivity.rows.map((r) => r.distinct);
  eq(Math.min(...dists), k.ourRange[0], 'sweep minimum matches the recorded range');
  eq(Math.max(...dists), k.ourRange[1], 'sweep maximum matches the recorded range');
  eq(k.ourRange[0], 89, 'the sweep bottoms out at 89');
  eq(k.ourRange[1], 103, 'and tops out at 103');
  ok(Math.max(...dists) < 116, 'the whole sweep sits below the published figure');
  eq(F.sensitivity.rows.length, 12, 'the sweep covers all twelve combinations');
  const combos = new Set(F.sensitivity.rows.map((r) => `${r.field}|${r.fallback}|${r.convention}`));
  eq(combos.size, 12, 'and they are twelve distinct combinations');
  // the age fallback should admit more languages, never fewer
  for (const c of CONV) for (const fld of ['Form', 'Value']) {
    const a = F.sensitivity.rows.find((r) => !r.fallback && r.convention === c && r.field === fld);
    const b = F.sensitivity.rows.find((r) => r.fallback && r.convention === c && r.field === fld);
    ok(b.languages > a.languages, `allowing the age fallback admits more languages (${fld}, ${c})`);
  }
  // OVERLAP is the most permissive merge rule, so it can never find MORE systems than STRICT
  for (const fld of ['Form', 'Value']) for (const fb of [false, true]) {
    const s = F.sensitivity.rows.find((r) => r.field === fld && r.fallback === fb && r.convention === 'STRICT');
    const o = F.sensitivity.rows.find((r) => r.field === fld && r.fallback === fb && r.convention === 'OVERLAP');
    ok(o.distinct <= s.distinct, `OVERLAP merges at least as much as STRICT (${fld}, fallback=${fb})`);
  }
  // the coincidence the page explicitly refuses to treat as a reconciliation
  const anyConv = new Set();
  for (const c of CONV) for (const t of F.byConvention[c].types) anyConv.add(t.rgs);
  eq(anyConv.size, 117, 'the union across all three rules over all records is 117');
  eq(D.attestedAny.length, 117, 'and data.json carries the same 117');
  ok(html.includes('means nothing'), 'the page says the 117-versus-116 closeness means nothing');
}

// ---------------------------------------------------------------- known languages
// Independently checkable facts about languages a reader can look up. If the dataset or
// the pipeline drifted, these are the checks that would notice.

const langBy = (n) => oneEach.find((l) => l.name === n);
const KNOWN = [
  ['English', '00110011', 'two words, on sex only'],
  ['Russian', '00110011', 'two words, on sex only'],
  ['German', '00110011', 'two words, on sex only'],
  ['Japanese', '01230123', 'four words, sex and age, speaker irrelevant'],
  ['Hungarian', '01230123', 'four words, sex and age, speaker irrelevant'],
  ['Indonesian', '01010101', 'two words, on age only'],
  ['Turkish', '01210121', 'three words: older brother, older sister, younger sibling'],
  ['Korean', '01234153', 'six words, and the speaker\'s own sex changes the older terms'],
];
for (const [name, want, why] of KNOWN) {
  const l = langBy(name);
  if (!ok(!!l, `${name} is present in the deduplicated sample`)) continue;
  eq(l.sys.STRICT, want, `${name}: ${why}`);
  eq(systemOf(l.forms, 'STRICT'), want, `${name}: recomputed by the second engine`);
}
// the specific words, so a reader who knows the language can check the source strings
eq(langBy('Japanese').forms.meB[0], 'ani', 'Japanese older brother is ani');
eq(langBy('Japanese').forms.myZ[0], 'imōto', 'Japanese younger sister is imōto');
eq(langBy('Turkish').forms.meZ[0], 'abla', 'Turkish older sister is abla');
eq(langBy('Indonesian').forms.meB[0], 'kakak', 'Indonesian older sibling is kakak');
eq(langBy('Indonesian').forms.myB[0], 'adik', 'Indonesian younger sibling is adik');
eq(langBy('Korean').forms.feB[0], 'oppa', "Korean: a woman's older brother is oppa");
eq(langBy('Korean').forms.meB[0], 'hyung', "Korean: a man's older brother is hyung");
ok(langBy('Korean').sys.STRICT[0] !== langBy('Korean').sys.STRICT[4],
  "Korean names a man's older brother and a woman's older brother apart");

// the relative-sex system: a man's word for his brother is a woman's word for her sister
{
  const t = D.types.find((x) => x.rgs === '00111100');
  ok(!!t, 'the same-sex / other-sex system is attested');
  eq(t.blocks, 2, 'it spends two words, the same budget as English');
  ok(t.rel === true, 'and it is flagged as a relative-sex system');
  ok(t.n > 20, 'it is not a curiosity: more than twenty languages use it');
  const eng = D.types.find((x) => x.rgs === '00110011');
  eq(eng.blocks, 2, 'English also spends two words');
  ok(eng.rel === false, 'but English is not a relative-sex system');
  ok(t.rgs !== eng.rgs, 'two languages, the same two words, cutting the family in different places');
}

// ---------------------------------------------------------------- phrase heuristic

{
  const withSpace = F.languages.reduce((s, l) => s + Object.values(l.forms).flat().filter((f) => /\s/.test(f)).length, 0);
  const total = F.languages.reduce((s, l) => s + Object.values(l.forms).flat().length, 0);
  eq(withSpace, D.phrase.formsWithSpace, 'spaced-form count in data.json');
  eq(total, D.phrase.formsTotal, 'total form count in data.json');
  eq(withSpace, 1020, '1020 recorded forms contain a space');
  eq(total, 10748, 'out of 10748 forms in the complete-set languages');
  // the two worked examples the page names, in both directions
  const es = F.languages.find((l) => l.name === 'Spanish');
  ok(/\s/.test(es.forms.meB[0]), 'Spanish is caught by the space test, correctly: it is a phrase');
  eq(es.forms.meB[0], 'hermano mayor', 'and the recorded Spanish form is hermano mayor');
  const zh = F.languages.find((l) => l.name === 'Mandarin Chinese');
  ok(/\s/.test(zh.forms.meB[0]), 'Mandarin is caught by the same test, wrongly: ge ge is one word');
  eq(zh.forms.meB[0], 'ge ge', 'and the recorded Mandarin form is ge ge');
  ok(html.includes('Mandarin'), 'the page names the Mandarin false positive rather than patching it');
  // and neither is ever offered as an example
  const named = new Set(D.types.flatMap((t) => t.eg));
  ok(!named.has('Spanish'), 'Spanish is never named as an example');
  ok(!named.has('Mandarin Chinese'), 'Mandarin is never named as an example either');
  for (const n of named) {
    const l = oneEach.find((x) => x.name === n);
    ok(l && l.phraseCells === 0, `named example ${n} has no spaced forms`);
  }
}

// ---------------------------------------------------------------- data bundle integrity

eq(D.languages.length, 942, 'data.json ships 942 language records');
{
  let bad = 0;
  for (const l of D.languages) {
    if (l.w.length !== 8) bad++;
    if (!/^[0-7]{8}$/.test(l.s)) bad++;
    const src = oneEach.find((x) => x.glottocode === l.g && x.name === l.n) || oneEach.find((x) => x.name === l.n && x.family === l.f);
    if (!src) { bad++; continue; }
    if (src.sys.STRICT !== l.s) bad++;
  }
  eq(bad, 0, 'every shipped language record is well-formed and matches the extraction');

  // The displayed words may come from a SIBLING record of the same language, chosen for
  // legibility. That is only safe if the sibling gives the same system, so check it.
  let dispBad = 0;
  const byG2 = new Map();
  for (const l of F.languages) {
    const k = l.glottocode || 'x:' + l.id;
    if (!byG2.has(k)) byG2.set(k, []);
    byG2.get(k).push(l);
  }
  for (const l of D.languages) {
    const group = byG2.get(l.g || '') || [];
    const shown = group.filter((r) => CELLS.every((c, i) => (r.forms[c] || []).join(' / ') === l.w[i]));
    if (!shown.length) { dispBad++; continue; }
    if (!shown.some((r) => r.sys.STRICT === l.s)) dispBad++;
  }
  eq(dispBad, 0, 'the words displayed always come from a record giving the same system as the one counted');
  {
    const en = D.languages.find((x) => x.n === 'English');
    eq(en.w[0], 'brother', 'English displays its own spelling, not a phonetic transcription of it');
    eq(en.w[2], 'sister', 'and likewise for sister');
  }
  const counts = {};
  for (const l of D.languages) counts[l.s] = (counts[l.s] || 0) + 1;
  let cbad = 0;
  for (const [k, v] of Object.entries(counts)) if (D.countsByRgs[k] !== v) cbad++;
  eq(cbad, 0, 'the lookup table the instrument uses matches the shipped records exactly');
  eq(Object.keys(D.countsByRgs).length, 90, 'the lookup table holds all 90 attested systems');
}
eq(D.corpus.families, 56, 'the sample spans 56 language families');
ok(Object.keys(D.corpus.macroareas).length >= 6, 'and at least six macroareas');
eq(D.dataset.doi, '10.5281/zenodo.18501543', 'the dataset DOI is recorded');
eq(D.convention, 'STRICT', 'the page leads with the strict rule');

// ---------------------------------------------------------------- prose bound to data
// Every number asserted in the page's own prose must be a number the data supports.

const proseChecks = [
  [/4,140/, '4,140 appears in the page prose'],
  [/942 languages/, 'the page states 942 languages'],
  [/1,701 ways/, 'the page states 1,701 four-word arrangements'],
  [/use 21\b/, 'the page states 21 of them are used'],
  [/374 languages/, 'the page states 374 languages in that column'],
  [/which 22 of these languages have/, 'the page states 22 one-word languages'],
  [/8 have/, 'the page states 8 eight-word languages'],
  [/1,020 of the 10,748/, 'the page states the spaced-form counts'],
  [/1,229 languages and 210,903/, 'the page states the descriptor paper figures'],
  [/1,288 varieties and 218,654/, 'the page states the v1.2 release figures'],
  [/Sixty-five of these languages are in the database twice/, 'the page states the duplicate count'],
  [/gives 117/, 'the page states the 117 union'],
  [/116/, 'the page states the published 116'],
];
for (const [re, label] of proseChecks) ok(re.test(html), label, 'prose regex not found');

// and the numbers in the prose must match the data
eq(D.blocks[4].possible, 1701, 'prose 1,701 is the data 1,701');
eq(D.blocks[4].attested, 21, 'prose 21 is the data 21');
eq(D.blocks[4].languages, 374, 'prose 374 is the data 374');
eq(D.blocks[1].languages, 22, 'prose 22 is the data 22');
eq(D.blocks[8].languages, 8, 'prose 8 is the data 8');
eq(D.phrase.formsWithSpace, 1020, 'prose 1,020 is the data 1,020');
eq(D.phrase.formsTotal, 10748, 'prose 10,748 is the data 10,748');

// the honesty statements the page is required to carry
const mustSay = [
  ['We did not read them', 'the page admits it did not read Nerlove and Romney'],
  ['403', 'and says why'],
  ['second-hand', 'and calls its knowledge second-hand'],
  ['upper</i> bound', 'the page calls the ninety an upper bound'],
  ['licence is genuinely ambiguous', 'the page flags the licence conflict'],
  ['CC BY-NC-4.0', 'and names the stricter licence it complied with'],
  ['does not claim', 'the page states what it does not claim'],
  ['only a count', 'and refuses to explain the pattern it found'],
];
for (const [needle, label] of mustSay) ok(html.includes(needle), label, `missing: ${needle}`);

// the markdown entry
ok(md.includes('href: "/strata/nobody-speaks-the-other-four-thousand/"'), 'the stratum entry points at the page');
ok(md.includes('Artificial Wasteland'), 'the dek names the project, per the 2026-08-15 steer');
ok(/^dek: "/m.test(md), 'the entry carries a dek');
ok(md.includes('Verifier 801/801') || /Verifier \d+\/\d+/.test(md), 'the entry states a verifier count');
for (const slug of ['the-four-names-that-were-not-enough', 'seventeen-and-no-more', 'more-data-wrong-tree',
  'the-last-colour', 'what-a-language-keeps']) {
  ok(md.includes(`to: ${slug}`), `relates edge to ${slug}`);
  ok(fs.existsSync(R(`src/content/strata/${slug}.md`)), `and ${slug} exists on the ground`);
}

// sources file
for (const needle of ['10.5281/zenodo.18501543', 'Nerlove', 'Passmore', 'CC BY-NC 4.0', 'Bell number',
  'We did not read', 'What we did not check', '116']) {
  ok(sources.includes(needle), `SOURCES.md records: ${needle}`);
}

// no em dashes in the page's own prose (quotations are allowed to keep theirs)
{
  const stripped = html.replace(/<blockquote[\s\S]*?<\/blockquote>/g, '').replace(/"[^"]*"/g, '');
  const n = (stripped.match(/—/g) || []).length;
  eq(n, 0, 'no em dashes in the page\'s own prose');
  const mdBody = md.split('---')[2] || '';
  eq((mdBody.match(/—/g) || []).length, 0, 'no em dashes in the stratum entry body');
}

// the instrument's reachability argument: cycling can reach every one of the 4,140
{
  // simulate the click rule exhaustively from the all-merged state by BFS over RGS space
  const seen = new Set(); const q = ['00000000']; seen.add('00000000');
  while (q.length) {
    const s = q.pop();
    const a = s.split('').map(Number);
    for (let i = 0; i < 8; i++) {
      const others = a.filter((_, j) => j !== i);
      const used = [...new Set(others)].sort((x, y) => x - y);
      const fresh = (used.length ? Math.max(...used) : -1) + 1;
      for (const v of [...used, fresh]) {
        const b = a.slice(); b[i] = v;
        const c = canon(b);
        if (!seen.has(c)) { seen.add(c); q.push(c); }
      }
    }
  }
  eq(seen.size, 4140, 'the click rule reaches every one of the 4140 arrangements');
  ok(pagejs.includes('const options = [...used, fresh]'), 'and the page implements that rule');
}

// ---------------------------------------------------------------- controls
// Under --mutate these must FAIL. A verifier that cannot go red is not checking anything.

if (MUTATE) {
  const before = fail;
  // corrupting one form must change that language's system
  const jp = JSON.parse(JSON.stringify(F.languages.find((l) => l.name === 'Japanese')));
  jp.forms.myZ = jp.forms.ane ? jp.forms.ane : jp.forms.meZ;
  ok(systemOf(jp.forms, 'STRICT') === '01230123', 'CONTROL: merging two Japanese cells must change its system');
  // an impossible pattern must not be attested
  ok(!!D.countsByRgs['01234567'.split('').reverse().join('')], 'CONTROL: a reversed pattern need not be attested');
  // the sweep must not be allowed to reach the published figure
  ok(F.externalKey.reachesPublished === true, 'CONTROL: the sweep does not reach 116');
  // Stirling must not be tamperable
  ok(stir2(8, 4) === 1700, 'CONTROL: Stirling(8,4) is 1701, not 1700');
  const went = fail - before;
  console.log(`\ncontrols: ${went} of 4 went red as designed (these are SUPPOSED to fail)\n`);
  if (went === 4) { fail -= 4; failures.splice(failures.length - went, went); }
  else { console.log('CONTROL FAILURE: not all controls went red'); }
}

// ---------------------------------------------------------------- report

// The page states its own verifier count in prose, so make that claim checkable rather
// than decorative. This runs last and counts itself, which makes the total a fixpoint:
// change the checks, the total moves, and this fails until the page is updated to match.
if (!MUTATE) {
  const stated = (html.match(/<b>(\d+) checks<\/b>/) || [])[1];
  const total = pass + fail + 2; // this check and the browser-count check below
  ok(stated && Number(stated) === total, 'the page states its own verifier count correctly',
    `page says ${stated}, actual total is ${total}`);
  const bstated = (html.match(/through <b>(\d+) checks<\/b>/) || [])[1];
  if (bstated) ok(Number(bstated) === 49, 'the page states the browser-check count correctly', `page says ${bstated}`);
}

function report() {
  if (failures.length) {
    console.log('\nFAILURES:');
    for (const f of failures) console.log('  ✗ ' + f);
  }
  console.log(`\n${fail === 0 ? 'PASS' : 'FAIL'} ${pass}/${pass + fail}`);
}
report();
process.exit(fail === 0 ? 0 : 1);
