#!/usr/bin/env node
/**
 * verify-everything-arrives-at-once.mjs
 *
 * Checks /strata/everything-arrives-at-once/ against the data it claims to rest on.
 *
 * WHAT IS RE-RUN HERE. Everything. The two source files are committed and small enough to
 * ship (ASL-LEX 2.0's signdata.csv, 2.0 MB, and cmudict.dict, 3.6 MB), so this program does
 * not read a summary and compare it to a page: it rebuilds both lexicons from those bytes,
 * recomputes every quantity the page prints, and only then asks whether the page agrees.
 *
 * FOUR THINGS HAVE TO AGREE, and the point of the design is that they are not the same thing:
 *   1. the recomputation done here, from the two source files;
 *   2. research/sign-lexicon-channels/out/results.json, written by analyse.mjs;
 *   3. the compact payload the page ships to your browser, lexicon.json;
 *   4. the numbers written into the built HTML as prose.
 * (2) and (4) are the ones that rot. (3) is a re-encoding and could silently lose a cell,
 * which is why it is expanded and diffed against (1) rather than trusted.
 *
 * The measure itself lives in the page's own engine, channels-core.mjs, which this program
 * imports over a relative path. That is deliberate: the arithmetic your browser ran is the
 * arithmetic under test, not a second copy of it.
 *
 *   node verify-everything-arrives-at-once.mjs             the checks
 *   node verify-everything-arrives-at-once.mjs --verbose   name every passing check too
 *   node verify-everything-arrives-at-once.mjs --selftest  plant defects, require each to go red
 */

import { readFileSync, existsSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

import { build, ASL_CHANNELS, ASL_CODING_A } from './research/sign-lexicon-channels/build-lexicons.mjs';
import { VOWELS, CONSONANTS, ENGLISH_CHANNELS, phoneFeatures }
  from './research/sign-lexicon-channels/lib/english-features.mjs';
import {
  partition, entropy, collapsedFraction, mergedGroups, expand,
  readAsl, readEng, readEngTruncated, ASL_SLOTS,
} from './public/strata/everything-arrives-at-once/channels-core.mjs';

const ROOT = path.dirname(fileURLToPath(import.meta.url));
const RES = path.join(ROOT, 'research', 'sign-lexicon-channels');
const PUB = path.join(ROOT, 'public', 'strata', 'everything-arrives-at-once');

let pass = 0, fail = 0, quiet = false;
const notRun = [];
const verbose = process.argv.includes('--verbose');
function check(name, ok, detail) {
  if (ok) { pass++; if (verbose && !quiet) console.log(`  ok   ${name}${detail ? '   ' + detail : ''}`); }
  else { fail++; if (!quiet || verbose) console.log(`  ${quiet ? '     ' : 'FAIL '}${name}${detail ? '   ' + detail : ''}`); }
  return ok;
}
const pct = (x) => (100 * x).toFixed(2);
const d4 = (x) => x.toFixed(4);

// ---------------------------------------------------------------------------------------
// the recomputation, exported so the selftest can drive it over mutated inputs

export function recompute(lex) {
  const items = lex.items;
  const aslKeys = ASL_CHANNELS.map((c) => c.key);
  const engKeys = ENGLISH_CHANNELS.map((c) => c.key);
  const uniform = () => 1;

  function side(keys, read, pad) {
    const base = partition(items, keys, new Set(), read, pad);
    const baseH = entropy(base, uniform);
    const rows = keys.map((k) => {
      const g = partition(items, keys, new Set([k]), read, pad);
      const solo = partition(items, keys, new Set(keys.filter((o) => o !== k)), read, pad);
      return {
        key: k,
        fl: baseH > 0 ? (baseH - entropy(g, uniform)) / baseH : 0,
        soloRetained: solo.size / base.size,
        soloOfN: solo.size / items.length,
        free: g.size === base.size,
      };
    }).sort((a, b) => b.fl - a.fl);

    // greedy worst-first to half-collapse
    const erased = new Set();
    let half = null;
    while (erased.size < keys.length && half === null) {
      let bestK = null, bestN = null;
      for (const k of keys) {
        if (erased.has(k)) continue;
        const n = partition(items, keys, new Set([...erased, k]), read, pad).size;
        if (bestN === null || n < bestN || (n === bestN && k < bestK)) { bestN = n; bestK = k; }
      }
      erased.add(bestK);
      if (bestN / base.size < 0.5) half = erased.size;
    }

    return {
      baseDistinct: base.size,
      baseRetained: base.size / items.length,
      collapsed: collapsedFraction(base, items.length),
      groups: mergedGroups(base).length,
      groupItems: mergedGroups(base).reduce((a, g) => a + g.length, 0),
      rows, half, n: items.length,
    };
  }

  const asl = side(aslKeys, readAsl, ASL_SLOTS);
  const eng = side(engKeys, readEng, 0);

  const truncation = [];
  const maxLen = Math.max(...items.map((it) => it.phones.length));
  for (let K = 1; K <= Math.min(8, maxLen); K++) {
    const base = partition(items, engKeys, new Set(), readEngTruncated(K), 0);
    const baseH = entropy(base, uniform);
    let maxFl = 0, maxKey = null;
    for (const k of engKeys) {
      const g = partition(items, engKeys, new Set([k]), readEngTruncated(K), 0);
      const fl = baseH > 0 ? (baseH - entropy(g, uniform)) / baseH : 0;
      if (fl > maxFl) { maxFl = fl; maxKey = k; }
    }
    truncation.push({ K, retained: base.size / items.length, maxFl, maxKey });
  }

  const oneH = items.filter((it) => it.signType === 'OneHanded');
  const twoH = items.filter((it) => it.signType && it.signType !== 'OneHanded' && it.signType !== 'NA');
  const handSide = (sub) => {
    const base = partition(sub, aslKeys, new Set(), readAsl, ASL_SLOTS);
    const baseH = entropy(base, uniform);
    let maxFl = 0;
    for (const k of aslKeys) {
      const g = partition(sub, aslKeys, new Set([k]), readAsl, ASL_SLOTS);
      const fl = baseH > 0 ? (baseH - entropy(g, uniform)) / baseH : 0;
      if (fl > maxFl) maxFl = fl;
    }
    return { n: sub.length, retained: base.size / sub.length, maxFl };
  };

  // the skeleton floor
  const skeletonEng = eng.rows.find((r) => r.key === 'syllabic').soloOfN;
  const lengthOnly = new Set(items.map((it) => it.phones.length)).size / items.length;

  return { asl, eng, truncation, oneH: handSide(oneH), twoH: handSide(twoH), skeletonEng, lengthOnly, items };
}

/** Is `to` a function of `from` across these items? */
export function functionTest(items, from, to) {
  const seen = new Map();
  let violations = 0;
  for (const it of items) {
    const f = from(it), t = to(it);
    if (!seen.has(f)) { seen.set(f, t); continue; }
    if (seen.get(f) !== t) violations++;
  }
  return violations;
}

// ---------------------------------------------------------------------------------------

function main() {
  console.log('verify-everything-arrives-at-once');

  // The two datasets are not shipped with this program. They are CC BY-NC 4.0 and BSD, so
  // shipping them would be allowed, but a check that runs against OUR copy of a dataset can
  // only show that we agree with ourselves. fetch-data.mjs pulls them from the publishers and
  // refuses any file whose sha256 is not the one recorded on 2026-09-13.
  const need = ['signdata.csv', 'cmudict.dict', 'cmudict.phones']
    .filter((f) => !existsSync(path.join(RES, 'data', f)));
  if (need.length) {
    console.log(`\n  The data is not here yet (missing: ${need.join(', ')}).`);
    console.log('  One command, about six megabytes, digests pinned:\n');
    console.log('      node research/sign-lexicon-channels/fetch-data.mjs\n');
    return false;
  }

  console.log('  rebuilding both lexicons from ASL-LEX 2.0 and CMUdict...');

  // ---- A. the feature table
  const phones = Object.keys(VOWELS).concat(Object.keys(CONSONANTS));
  check('A1 feature table covers 39 ARPAbet phones', phones.length === 39, `${phones.length}`);
  const bundles = new Set(phones.map((p) => JSON.stringify(phoneFeatures(p))));
  check('A2 feature table is lossless (no two phones share a bundle)',
    bundles.size === 39, `${bundles.size} distinct bundles`);
  const phonesFile = path.join(RES, 'data', 'cmudict.phones');
  if (existsSync(phonesFile)) {
    const listed = readFileSync(phonesFile, 'latin1').split('\n')
      .map((l) => l.split('\t')[0].trim()).filter(Boolean);
    const missing = listed.filter((p) => !VOWELS[p] && !CONSONANTS[p]);
    check('A3 every phone CMUdict declares is in the table', missing.length === 0, missing.join(','));
  }

  const lex = build();
  const R = recompute(lex);
  lexChecks(lex, R);
  pageChecks(lex, R);

  console.log(`\n  ${pass} passed, ${fail} failed`);
  if (notRun.length) {
    // Not passed. NOT RUN, which is a different thing, and saying so is the whole point:
    // a check suite that quietly shrinks when a file is absent is how a green tick starts
    // meaning nothing. These need one command each.
    console.log(`\n  ${notRun.length} group${notRun.length === 1 ? '' : 's'} need something this `
      + 'bundle does not carry. They were NOT run, and they are');
    console.log('  not counted above. One command each:');
    for (const [what, cmd] of notRun) console.log(`\n    ${what}\n      ${cmd}`);
    console.log('');
  }
  return fail === 0;
}

/**
 * Every assertion that depends only on the rebuilt lexicon. Split out from main() so the
 * selftest can run THIS, the real battery, over a mutated lexicon: "plant a defect and
 * require it to go red" means red on the checks a reader actually runs, not red on a
 * separate criterion written to be easy to trip.
 */
function lexChecks(lex, R) {
  // ---- B. the build
  check('B1 ASL-LEX rows read', lex.aslEntries === 2723, `${lex.aslEntries}`);
  check('B2 paired concepts', lex.items.length === 1977, `${lex.items.length}`);
  check('B3 dropped, gloss not one word', lex.dropped.multiWord === 291, `${lex.dropped.multiWord}`);
  check('B4 dropped, gloss not in CMUdict', lex.dropped.notInCmudict === 52, `${lex.dropped.notInCmudict}`);
  check('B5 dropped, extra sign variant of a kept gloss', lex.dropped.variantOfKept === 403, `${lex.dropped.variantOfKept}`);
  check('B6 one entry per English word', new Set(lex.items.map((i) => i.word)).size === lex.items.length);

  const meanAsl = lex.items.reduce((a, x) => a + x.nSlotsAsl, 0) / lex.items.length;
  const meanEng = lex.items.reduce((a, x) => a + x.nSlotsEng, 0) / lex.items.length;
  check('B7 mean ASL morpheme slots is 1.10', meanAsl.toFixed(2) === '1.10', meanAsl.toFixed(4));
  check('B8 mean English phonemes is 4.89', meanEng.toFixed(2) === '4.89', meanEng.toFixed(4));

  let beyond = 0;
  for (const it of lex.items) {
    for (const ch of ASL_CHANNELS) {
      for (let k = it.nSlotsAsl; k < ASL_SLOTS; k++) if (it.asl[ch.key][k] !== 'NA') beyond++;
    }
  }
  check('B9 no ASL cell carries data past the counted slot, which the payload relies on',
    beyond === 0, `${beyond} stragglers`);

  // ---- C. the recomputation
  // R is passed in, recomputed by the caller from this lexicon.

  check('C1 ASL baseline distinct classes', R.asl.baseDistinct === 1720, `${R.asl.baseDistinct}`);
  check('C2 ASL baseline distinctness 87.00%', pct(R.asl.baseRetained) === '87.00', pct(R.asl.baseRetained));
  check('C3 English baseline distinct classes', R.eng.baseDistinct === 1954, `${R.eng.baseDistinct}`);
  check('C4 English baseline distinctness 98.84%', pct(R.eng.baseRetained) === '98.84', pct(R.eng.baseRetained));
  check('C5 ASL baseline collapsed 22.76%', pct(R.asl.collapsed) === '22.76', pct(R.asl.collapsed));
  check('C6 English baseline collapsed 2.33%', pct(R.eng.collapsed) === '2.33', pct(R.eng.collapsed));
  check('C7 ASL baseline groups 193 over 450 signs',
    R.asl.groups === 193 && R.asl.groupItems === 450, `${R.asl.groups}/${R.asl.groupItems}`);
  check('C8 English baseline groups 23 over 46 words',
    R.eng.groups === 23 && R.eng.groupItems === 46, `${R.eng.groups}/${R.eng.groupItems}`);

  // ---- D. functional load
  const aslTop = R.asl.rows[0], engTop = R.eng.rows[0];
  check('D1 ASL heaviest channel is path movement', aslTop.key === 'Movement', aslTop.key);
  check('D2 ASL heaviest functional load 0.0206', d4(aslTop.fl) === '0.0206', d4(aslTop.fl));
  check('D3 English heaviest channel is consonant place', engTop.key === 'cplace', engTop.key);
  check('D4 English heaviest functional load 0.0156', d4(engTop.fl) === '0.0156', d4(engTop.fl));
  check('D5 the ratio is 1.32, not the registered 3',
    (aslTop.fl / engTop.fl).toFixed(2) === '1.32', (aslTop.fl / engTop.fl).toFixed(2));

  // What deleting path movement does to the classes, in the page's own words. Until
  // 2026-09-22 the page read the class count after the deletion (1,573) as the number of
  // classes left intact, and the merged-group count after it (240) as the number of new
  // groups. Both are recomputed here as what the sentence now says they are.
  {
    const aslKeys = ASL_CHANNELS.map((c) => c.key);
    const base = partition(lex.items, aslKeys, new Set(), readAsl, ASL_SLOTS);
    const cut = partition(lex.items, aslKeys, new Set(['Movement']), readAsl, ASL_SLOTS);
    const classOf = new Map();
    for (const [code, g] of base) for (const it of g) classOf.set(it, code);
    let intact = 0, joining = 0;
    for (const g of cut.values()) {
      const from = new Set(g.map((it) => classOf.get(it)));
      if (from.size === 1 && base.get([...from][0]).length === g.length) intact++;
      if (from.size > 1) joining++;
    }
    check('D6 deleting path movement leaves 1,573 classes, 1,451 of the 1,720 intact',
      cut.size === 1573 && intact === 1451 && base.size === 1720, `${cut.size} ${intact}`);
    check('D7 deleting path movement makes 122 groups of formerly distinct signs',
      joining === 122 && intact + joining === cut.size, `${joining}`);
  }

  // ---- E. solo power
  // Every percentage here is a share of the 1,977 items, which is the denominator the page's
  // own instrument shows. An earlier draft reported solo power against the baseline class
  // count instead, and the page then disagreed with its own readout by six tenths of a point.
  const solo = (side, key) => side.rows.find((r) => r.key === key).soloOfN;
  check('E1 English consonant place alone separates 52.91%', pct(solo(R.eng, 'cplace')) === '52.91', pct(solo(R.eng, 'cplace')));
  check('E2 English consonant manner alone separates 52.76%', pct(solo(R.eng, 'cmanner')) === '52.76', pct(solo(R.eng, 'cmanner')));
  check('E3 English vowel height alone separates 31.56%', pct(solo(R.eng, 'vheight')) === '31.56', pct(solo(R.eng, 'vheight')));
  const aslBestSolo = [...R.asl.rows].sort((a, b) => b.soloOfN - a.soloOfN)[0];
  check('E4 ASL best solo channel is nondominant handshape at 5.77%',
    aslBestSolo.key === 'NonDominantHandshape' && pct(aslBestSolo.soloOfN) === '5.77',
    `${aslBestSolo.key} ${pct(aslBestSolo.soloOfN)}`);
  check('E5 ASL minor location alone separates 5.46%', pct(solo(R.asl, 'MinorLocation')) === '5.46', pct(solo(R.asl, 'MinorLocation')));
  check('E6 the solo gap is about nine to one',
    (solo(R.eng, 'cplace') / aslBestSolo.soloOfN) > 8.5 && (solo(R.eng, 'cplace') / aslBestSolo.soloOfN) < 9.5,
    (solo(R.eng, 'cplace') / aslBestSolo.soloOfN).toFixed(2));
  check('E7 the English skeleton floor is 9.41%', pct(R.skeletonEng) === '9.41', pct(R.skeletonEng));
  check('E8 English word length alone is 0.66%', pct(R.lengthOnly) === '0.66', pct(R.lengthOnly));
  check('E9 every solo figure shares the page instrument\'s denominator',
    R.eng.rows.every((r) => Math.abs(r.soloOfN * R.eng.n - r.soloRetained * R.eng.baseDistinct) < 1e-9));

  // ---- F. free channels
  const aslFree = R.asl.rows.filter((r) => r.free).map((r) => r.key).sort();
  const engFree = R.eng.rows.filter((r) => r.free).map((r) => r.key).sort();
  check('F1 exactly one ASL channel is free, and it is major location',
    aslFree.length === 1 && aslFree[0] === 'MajorLocation', aslFree.join(','));
  check('F2 exactly three English channels are free',
    engFree.length === 3 && engFree.join(',') === 'stress,syllabic,vround', engFree.join(','));
  const roundViolations = functionTest(lex.items,
    (it) => it.eng.vheight.map((v, i) => `${v}/${it.eng.vback[i]}`).join('|'),
    (it) => it.eng.vround.join('|'));
  check('F3 lip rounding is exactly determined by height and backness', roundViolations === 0, `${roundViolations}`);
  const locViolations = functionTest(lex.items,
    (it) => it.asl.MinorLocation.join('|'), (it) => it.asl.MajorLocation.join('|'));
  check('F4 minor location does NOT determine major location: 36 pairs disagree',
    locViolations === 36, `${locViolations}`);
  const majorByRest = functionTest(lex.items,
    (it) => ASL_CHANNELS.filter((c) => c.key !== 'MajorLocation').map((c) => it.asl[c.key].join('~')).join('|'),
    (it) => it.asl.MajorLocation.join('|'));
  check('F5 major location IS determined by the other fifteen jointly', majorByRest === 0, `${majorByRest}`);

  // ---- G. truncation and the exchange rate
  const t = (K) => R.truncation.find((x) => x.K === K);
  check('G1 English at 1 phoneme retains 2.58%', pct(t(1).retained) === '2.58', pct(t(1).retained));
  check('G2 English at 2 phonemes retains 23.93%', pct(t(2).retained) === '23.93', pct(t(2).retained));
  check('G3 English at 3 phonemes retains 69.20%', pct(t(3).retained) === '69.20', pct(t(3).retained));
  check('G4 English at 4 phonemes retains 91.96%', pct(t(4).retained) === '91.96', pct(t(4).retained));
  check('G5 the whole ASL sign falls between the third phoneme and the fourth',
    t(3).retained < R.asl.baseRetained && R.asl.baseRetained < t(4).retained,
    `${pct(t(3).retained)} < ${pct(R.asl.baseRetained)} < ${pct(t(4).retained)}`);
  check('G6 English cut to 2 phonemes carries 0.1221', d4(t(2).maxFl) === '0.1221', d4(t(2).maxFl));
  check('G7 English cut to 1 phoneme carries 0.2453', d4(t(1).maxFl) === '0.2453', d4(t(1).maxFl));
  check('G8 the registered control holds: 2-phoneme English outweighs whole ASL',
    t(2).maxFl > aslTop.fl, `${d4(t(2).maxFl)} > ${d4(aslTop.fl)}`);

  // ---- H. half-collapse
  check('H1 ASL needs 5 of 16 channels erased to fall below half', R.asl.half === 5, `${R.asl.half}`);
  check('H2 English needs 3 of 10', R.eng.half === 3, `${R.eng.half}`);
  check('H3 as fractions the two are within two points',
    Math.abs(R.asl.half / 16 - R.eng.half / 10) < 0.02,
    `${(100 * R.asl.half / 16).toFixed(1)}% vs ${(100 * R.eng.half / 10).toFixed(1)}%`);

  // ---- I. the hand split, where a prediction broke
  check('I1 one-handed signs: 748 of them, 91.71% distinct',
    R.oneH.n === 748 && pct(R.oneH.retained) === '91.71', `${R.oneH.n} ${pct(R.oneH.retained)}`);
  check('I2 two-handed signs: 1229 of them, 84.13% distinct',
    R.twoH.n === 1229 && pct(R.twoH.retained) === '84.13', `${R.twoH.n} ${pct(R.twoH.retained)}`);
  check('I3 two-handed carries MORE per channel, against the registered direction',
    d4(R.oneH.maxFl) === '0.0151' && d4(R.twoH.maxFl) === '0.0270',
    `${d4(R.oneH.maxFl)} vs ${d4(R.twoH.maxFl)}`);

}

function pageChecks(lex, R) {
  const aslTop = R.asl.rows[0], engTop = R.eng.rows[0];
  // ---- J. what the page ships to a browser
  const payloadPath = path.join(PUB, 'lexicon.json');
  if (!existsSync(payloadPath)) {
    notRun.push(['J, the agreement with the payload your browser receives (7 checks)',
      'curl -sL https://artwaste.land/strata/everything-arrives-at-once/lexicon.json '
      + '-o public/strata/everything-arrives-at-once/lexicon.json']);
  } else {
    const data = JSON.parse(readFileSync(payloadPath, 'utf8'));
    const ex = expand(data);
    check('J2 payload carries the same 1,977 items', ex.items.length === lex.items.length,
      `${ex.items.length}`);
    check('J3 payload glosses match the repository build in order',
      ex.items.every((it, i) => it.gloss === lex.items[i].gloss));
    // the re-encoding must reproduce every partition, not merely the baseline
    const aslKeys = ASL_CHANNELS.map((c) => c.key);
    const engKeys = ENGLISH_CHANNELS.map((c) => c.key);
    const sig = (its, keys, erased, read, pad) =>
      [...partition(its, keys, erased, read, pad).values()]
        .map((g) => g.map((x) => x.gloss).sort().join(',')).sort().join(';');
    let agree = 0, disagree = 0;
    for (const k of [null, ...aslKeys]) {
      const e = new Set(k ? [k] : []);
      if (sig(ex.items, aslKeys, e, readAsl, ASL_SLOTS) === sig(lex.items, aslKeys, e, readAsl, ASL_SLOTS)) agree++;
      else disagree++;
    }
    for (const k of [null, ...engKeys]) {
      const e = new Set(k ? [k] : []);
      if (sig(ex.items, engKeys, e, readEng, 0) === sig(lex.items, engKeys, e, readEng, 0)) agree++;
      else disagree++;
    }
    check('J4 the browser payload reproduces all 28 partitions exactly',
      disagree === 0 && agree === 28, `${agree} agree, ${disagree} disagree`);
    for (const K of [1, 2, 3, 4]) {
      const same = sig(ex.items, engKeys, new Set(), readEngTruncated(K), 0)
                === sig(lex.items, engKeys, new Set(), readEngTruncated(K), 0);
      check(`J5.${K} payload reproduces the ${K}-phoneme truncation`, same);
    }
  }

  // ---- K. results.json, written by analyse.mjs
  const resPath = path.join(RES, 'out', 'results.json');
  if (!existsSync(resPath)) {
    notRun.push(['K, the agreement with analyse.mjs (8 checks)',
      'node research/sign-lexicon-channels/analyse.mjs']);
  } else {
    const res = JSON.parse(readFileSync(resPath, 'utf8'));
    check('K2 results.json agrees on the ASL baseline', res.asl.baseDistinct === R.asl.baseDistinct);
    check('K3 results.json agrees on the English baseline', res.eng.baseDistinct === R.eng.baseDistinct);
    check('K4 results.json agrees on the ASL heaviest channel',
      res.asl.single[0].key === aslTop.key && d4(res.asl.single[0].fl.type) === d4(aslTop.fl));
    check('K5 results.json agrees on the English heaviest channel',
      res.eng.single[0].key === engTop.key && d4(res.eng.single[0].fl.type) === d4(engTop.fl));
    const held = res.predictions.filter((p) => p.held).length;
    check('K6 three of eight registered predictions held',
      res.predictions.length === 8 && held === 3, `${held}/8`);
    check('K7 the predictions that held are 4, 6 and 7',
      res.predictions.filter((p) => p.held).map((p) => p.n).join(',') === '4,6,7',
      res.predictions.filter((p) => p.held).map((p) => p.n).join(','));
    check('K8 coding A, the classical parameters, keeps movement on top and 86.80%',
      res.codingA.single[0].key === 'A_Movement' && pct(res.codingA.baseRetained) === '86.80',
      `${res.codingA.single[0].key} ${pct(res.codingA.baseRetained)}`);
    check('K9 keeping all 2,380 entries moves the ASL baseline to 86.09%',
      res.allVariants.asl.n === 2380 && pct(res.allVariants.asl.baseRetained) === '86.09',
      `${res.allVariants.asl.n} ${pct(res.allVariants.asl.baseRetained)}`);
  }

  // ---- L. the page's own prose
  const pagePath = path.join(PUB, 'index.html');
  if (!existsSync(pagePath)) {
    notRun.push(['L, the agreement with the page itself (8 checks)',
      'curl -sL https://artwaste.land/strata/everything-arrives-at-once/ '
      + '-o public/strata/everything-arrives-at-once/index.html']);
  } else {
    const html = readFileSync(pagePath, 'utf8');
    const strip = html.replace(/&nbsp;/g, ' ');
    const mustSay = [
      '1,977', '2,723'.replace('2,723', '2,723'),
      '1,720', '87.00%', '1,954', '98.84%', '22.76%', '2.33%',
      '193 groups', '450 signs', 'Twenty-three groups, forty-six words',
      '0.0206', '0.0156', '1.32', '52.91%', '52.76%', '31.56%', '5.77%', '5.46%',
      '9.41%', '0.66%', '4.89', '1.10',
      '2.58%', '23.93%', '69.20%', '91.96%', '0.1221', '0.2453',
      '5 of its 16', '3 of its 10', '31.3%', '30.0%',
      '1,229', '84.13%', '748', '91.71%', '0.0151', '0.0270',
      '86.80%', '86.09%', '2,380',
      '36 pairs', 'fall to 1,573', '122 groups', '1,451 of', '9-to-1',
    ];
    const absent = mustSay.filter((s) => !strip.includes(s));
    check('L2 every number the checks just proved is on the page', absent.length === 0,
      absent.length ? 'missing: ' + absent.join(' | ') : `${mustSay.length} figures`);
    check('L3 the page ships the engine this program imported',
      html.includes("from './channels-core.mjs'"));
    // The dek is the meta description and the front-page summary, so it is the sentence a
    // stranger reads first. On 2026-09-16 it still quoted an earlier draft's denominator.
    const mdPath = path.join(ROOT, 'src', 'content', 'strata', 'everything-arrives-at-once.md');
    if (existsSync(mdPath)) {
      const dek = (/^dek:\s*"(.*)"\s*$/m.exec(readFileSync(mdPath, 'utf8')) || [])[1] || '';
      const want = [`${pct(R.eng.rows.find((r) => r.key === 'cplace').soloOfN)}%`,
        `${pct([...R.asl.rows].sort((a, b) => b.soloOfN - a.soloOfN)[0].soloOfN)}%`, '1.32', '1,977'];
      const said = dek.match(/\d+(?:\.\d+)?%/g) || [];
      const stray = said.filter((x) => !want.includes(x));
      check('L8 the dek quotes the recomputed solo figures and no other percentage',
        want.every((w) => dek.includes(w)) && stray.length === 0,
        stray.length ? 'stray: ' + stray.join(' ') : want.filter((w) => !dek.includes(w)).join(' ') || said.join(' '));
      check('L9 the page states every figure the dek states', want.every((w) => strip.includes(w)));
    }
    check('L4 the page names its own limits section', strip.includes('What this is a measurement of'));
    check('L5 the page says the same-row signs are different signs',
      strip.includes('Those are six different'));
    check('L6 canonical URL is set', html.includes('rel="canonical" href="https://artwaste.land/strata/everything-arrives-at-once/"'));
    check('L7 the closing tags are present, which decide whether any script runs at all',
      /<\/script>\s*<\/body>\s*<\/html>\s*$/.test(html.trimEnd() + '\n') || html.trimEnd().endsWith('</html>'));
  }
}

// ---------------------------------------------------------------------------------------
// the selftest: plant a defect, require the checks to notice

function selftest() {
  console.log('selftest: planting defects, each must turn the REAL battery red\n');
  const baseline = build();

  // Defects that must be caught. Each changes something the page states.
  const defects = [
    ['one concept is dropped from the set',
      (lex) => { lex.items.splice(5, 1); }],
    ['two signs are given the same code, so a class disappears',
      (lex) => { lex.items[1].asl = JSON.parse(JSON.stringify(lex.items[0].asl)); }],
    ['two concepts are given the same pronunciation',
      (lex) => { lex.items[1].eng = JSON.parse(JSON.stringify(lex.items[0].eng));
                 lex.items[1].phones = lex.items[0].phones.slice(); }],
    ['every sign is given the same nondominant handshape',
      (lex) => { for (const it of lex.items) it.asl.NonDominantHandshape = new Array(6).fill('NA'); }],
    ['path movement is flattened, so its functional load should vanish',
      (lex) => { for (const it of lex.items) it.asl.Movement = new Array(6).fill('None'); }],
    ['the sign-type labels are shuffled onto the wrong signs',
      (lex) => { const t = lex.items.map((i) => i.signType);
                 lex.items.forEach((it, i) => { it.signType = t[(i + 7) % t.length]; }); }],
    ['one vowel is rounded against its own backness, breaking the rounding implication',
      (lex) => { const it = lex.items.find((x) => x.eng.vround.includes('0'));
                 it.eng.vround[it.eng.vround.indexOf('0')] = '1'; }],
    ['major location is made to disagree with the other fifteen channels',
      (lex) => { for (const it of lex.items) it.asl.MajorLocation[0] = it.gloss.length % 2 ? 'Head' : 'Body'; }],
    ['a slot count is understated, which would silently truncate the payload',
      (lex) => { for (const it of lex.items) it.nSlotsAsl = 1; }],
    ['every word loses its last phoneme',
      (lex) => { for (const it of lex.items) { if (it.phones.length > 1) { it.phones.pop();
                 for (const k of Object.keys(it.eng)) it.eng[k].pop(); } } }],
  ];

  let caught = 0;
  for (const [name, mutate] of defects) {
    const lex = clone(baseline);
    mutate(lex);
    const before = fail;
    let threw = null;
    quiet = true;
    try { lexChecks(lex, recompute(lex)); } catch (e) { threw = e.message; }
    quiet = false;
    const went = threw !== null || fail > before;
    if (went) { console.log(`  ok   ${name}${threw ? '  (threw: ' + threw + ')' : '  (' + (fail - before) + ' checks red)'}`); caught++; }
    else console.log(`  FAIL ${name}  (the battery stayed green; it would not have noticed)`);
  }

  // The control, and it is the point: an unmutated rebuild must be entirely green.
  const beforeCtl = fail;
  quiet = true;
  lexChecks(clone(baseline), recompute(clone(baseline)));
  quiet = false;
  const stable = fail === beforeCtl;
  console.log(`  ${stable ? 'ok  ' : 'FAIL'} control: an unmutated rebuild passes every check`);

  // The negative control, which is here to bound the claim rather than to pass. A partition
  // measure sees only which items share a code. Alter a sign that is already alone, to a value
  // nothing else carries, and it is still alone: no class changes, so no check can move. That
  // class of defect is invisible to this program BY CONSTRUCTION, and the honest thing is to
  // demonstrate it rather than to plant only defects that happen to be catchable.
  const lex = clone(baseline);
  const counts = new Map();
  for (const it of lex.items) {
    const code = ASL_CHANNELS.map((c) => it.asl[c.key].join('~')).join('|');
    counts.set(code, (counts.get(code) || 0) + 1);
  }
  const lone = lex.items.find((it) =>
    counts.get(ASL_CHANNELS.map((c) => it.asl[c.key].join('~')).join('|')) === 1);
  lone.asl.ThumbPosition[0] = 'NoSuchThumbPositionExistsAnywhere';
  const beforeNeg = fail;
  quiet = true;
  lexChecks(lex, recompute(lex));
  quiet = false;
  const invisible = fail === beforeNeg;
  console.log(`  ${invisible ? 'ok  ' : 'FAIL'} negative control: a lone sign (${lone.gloss}) given a thumb position `
    + `nothing else has stays lone, so the battery ${invisible ? 'correctly cannot see it' : 'moved, which should be impossible'}`);

  console.log(`\n  ${caught}/${defects.length} defects caught, control ${stable ? 'green' : 'RED'}, `
    + `negative control ${invisible ? 'invisible as designed' : 'MISBEHAVED'}`);
  return caught === defects.length && stable && invisible;
}

function clone(lex) {
  return { ...lex, items: lex.items.map((it) => JSON.parse(JSON.stringify(it))) };
}

const ok = process.argv.includes('--selftest') ? selftest() : main();
process.exit(ok ? 0 : 1);
