#!/usr/bin/env node
// verify-tang-poetry-tone-rules.mjs: checks /strata/tang-poetry-tone-rules/ ("The Tone That Went Missing").
//
//   node verify-tang-poetry-tone-rules.mjs            # engine, rules, data, and every figure the page states
//   node verify-tang-poetry-tone-rules.mjs --mutate   # also break the engine on purpose; checks must go red
//
// Needs only Node 18+. Inside the repository it tests the local files; from an empty directory it
// downloads the page's engine.mjs, readers.mjs, readings.json, more-readers.json and index.html from
// https://artwaste.land into ./tang-poetry-tone-rules-files/ (the bytes your browser runs).
// Exit 0 = every check passed.
//
// What it checks:
//  A. the three tone classifiers against readings worked by hand;
//  B. the rule tests on hand-made poems: how many tests a quatrain and an octave get, that the
//     textbook pattern passes all of them, and that one flipped syllable fails exactly the tests
//     it should;
//  C. the data: poem and group counts, the five errata against the text they correct;
//  D. every figure the prose quotes, recomputed here from the engine and found in the page's text,
//     and the verdicts it states (which predictions held, what Mandarin does to line 7);
//  E. the six readers added on 7 November 2026 (readers.mjs, more-readers.json): their tone
//     classes against readings worked by hand, the repair rule, and every figure and verdict the
//     section "Six more readers" states.
// What it does NOT check: that each reader's reading of a character is right (they are software:
// qieyun 0.13.5, to-jyutping 3.1.1, pinyin-pro 3.29.4, run once by
// research/tang-poetry-tone-rules/extract/extract.mjs; and the November readers are dictionaries,
// read once by research/tang-poetry-tone-rules/more-readers/extract-readers.mjs), nor what the
// sources say (the words relied on are in assay/sources/tang-poetry-tone-rules.json).

import { existsSync, mkdirSync, writeFileSync, readFileSync, mkdtempSync } from 'node:fs';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { dirname, join, resolve } from 'node:path';
import { tmpdir } from 'node:os';

const here = dirname(fileURLToPath(import.meta.url));
const slug = 'tang-poetry-tone-rules';
const MUTATE = process.argv.includes('--mutate');
const FILES = ['engine.mjs', 'readers.mjs', 'readings.json', 'more-readers.json', 'index.html'];
let dir = process.env.AW_DIR || join(here, 'public/strata', slug);
const inRepo = !process.env.AW_DIR && existsSync(join(dir, 'engine.mjs'));
if (!process.env.AW_DIR && !inRepo) {
  dir = resolve(`${slug}-files`); mkdirSync(dir, { recursive: true });
  for (const f of FILES) {
    const r = await fetch(`https://artwaste.land/strata/${slug}/${f}`);
    if (!r.ok) throw new Error(`could not download ${f}: ${r.status}`);
    writeFileSync(join(dir, f), Buffer.from(await r.arrayBuffer()));
  }
}
const data = JSON.parse(readFileSync(join(dir, 'readings.json'), 'utf8'));
const more = JSON.parse(readFileSync(join(dir, 'more-readers.json'), 'utf8'));
const html = readFileSync(join(dir, 'index.html'), 'utf8');
const text = html.replace(/<[^>]+>/g, ' ').replace(/&nbsp;/g, ' ').replace(/\s+/g, ' ');

async function run(engineSrc, quiet, readersSrc = readersSrc0) {
  const tmp = mkdtempSync(join(tmpdir(), 'tang-'));
  writeFileSync(join(tmp, 'engine.mjs'), engineSrc);
  writeFileSync(join(tmp, 'readers.mjs'), readersSrc);
  const E = await import(pathToFileURL(join(tmp, 'engine.mjs')).href);
  const RD = await import(pathToFileURL(join(tmp, 'readers.mjs')).href);
  let pass = 0, fail = 0;
  const ok = (cond, what) => { if (cond) pass++; else { fail++; if (!quiet) console.log('  FAIL ' + what); } };
  const has = (s, what) => ok(text.includes(s), `${what}: page says "${s}"`);
  const f1 = x => x.toFixed(1);
  const pct = t => 100 * t.pass / t.n;

  // A. classifiers, by hand
  ok(E.classG(['平']) === 'P' && E.classG(['上']) === 'Z' && E.classG(['去']) === 'Z' && E.classG(['入']) === 'Z', 'A1 level is level; rising, departing, entering are oblique');
  ok(E.classG(['平', '去']) === 'A' && E.classG(['上', '去']) === 'Z' && E.classG(undefined) === null, 'A2 a character in both classes is ambiguous; two oblique tones are oblique; none is null');
  ok(E.classC('saan1') === 'P' && E.classC('wong4') === 'P' && E.classC('hoi2') === 'Z' && E.classC('zeon6') === 'Z', 'A3 Cantonese tones 1 and 4 level, others oblique');
  ok(E.classC('baak6') === 'Z' && E.classC('jat1') === 'Z' && E.classC('sik1') === 'Z' && E.classC('jap6') === 'Z', 'A4 a Cantonese syllable in -p -t -k is oblique whatever its tone number');
  ok(E.classM('shan1') === 'P' && E.classM('bai2') === 'P' && E.classM('hai3') === 'Z' && E.classM('ri4') === 'Z' && E.classM('shang0') === null, 'A5 Mandarin 1 and 2 level, 3 and 4 oblique, neutral unscored');

  // B. rules on hand-made poems. The textbook quatrain 仄仄平平仄 / 平平仄仄平 / 平平平仄仄 / 仄仄仄平平
  const grid = rows => rows.map(r => [...r].map(c => (c === '平' ? 'P' : c === '仄' ? 'Z' : c === '?' ? 'A' : null)));
  const q = { len: 5, lines: ['一二三四五', '一二三四五', '一二三四五', '一二三四五'] };
  const tq = E.testsFor(q);
  const count = (T, r) => T.filter(t => t.rule === r).length;
  ok(count(tq, 'R1') === 4 && count(tq, 'R2') === 2 && count(tq, 'R3') === 1 && count(tq, 'R4') === 2 && count(tq, 'R5') === 1, 'B1 a five-syllable quatrain gets 4 + 2 + 1 + 2 + 1 tests');
  const o = { len: 7, lines: Array(8).fill('一二三四五六七') };
  const to = E.testsFor(o);
  ok(count(to, 'R1') === 16 && count(to, 'R2') === 4 && count(to, 'R3') === 3 && count(to, 'R4') === 4 && count(to, 'R5') === 3, 'B2 a seven-syllable octave gets 16 + 4 + 3 + 4 + 3 tests');
  const good = grid(['仄仄平平仄', '平平仄仄平', '平平平仄仄', '仄仄仄平平']);
  ok(tq.every(t => E.judge(t, good) === true), 'B3 the textbook quatrain passes every test');
  const bad = grid(['仄仄平平仄', '平平仄仄平', '仄仄平仄仄', '仄仄仄平平']); // line 3 second syllable flipped
  const failed = tq.filter(t => E.judge(t, bad) === false).map(t => t.rule).sort().join(',');
  ok(failed === 'R1,R2,R3', 'B4 flipping line 3\'s second syllable fails R1 (its own line), R2 (its couplet) and R3 (adhesion), nothing else: ' + failed);
  const amb = grid(['仄?平平仄', '平平仄仄平', '平平平仄仄', '仄仄仄平平']);
  ok(tq.filter(t => E.judge(t, amb) === null).length === 2, 'B5 an ambiguous key syllable makes its two tests unscorable');
  const sk = E.skeleton('Z', false).map(l => l.map(k => k ?? '.').join('')).join(' ');
  ok(sk === '.Z.PZ .P.ZP .P.ZZ .Z.PP', 'B6 the two-choice skeleton reproduces the textbook quatrain: ' + sk);
  const sk2 = E.skeleton('P', true).map(l => l.map(k => k ?? '.').join('')).join(' ');
  ok(sk2 === '.P.ZP .Z.PP .Z.PZ .P.ZP', 'B7 level start, first line rhyming: ' + sk2);
  ok(E.skeleton('Z', false).flat().filter(Boolean).length === 12, 'B8 the rules fix 12 of 20 syllables');

  // C. the data
  const scored = g => data.poemsData.filter(p => p.scored && E.group(p.type) === g).length;
  ok(data.poemsData.length === 320, 'C1 320 poems');
  ok(scored('regulated') === 213 && data.poemsData.filter(p => E.group(p.type) === 'regulated').length === 213, 'C2 213 regulated poems, none dropped');
  ok(scored('control') === 51 && scored('yuefu') === 34 && data.dropped.length === 22, 'C3 51 old-style and 34 yuefu scored, 22 dropped');
  ok(data.errata.length === 5 && data.errata.every(e => [...data.poemsData.find(p => p.id === e.id).lines[e.line]][e.pos] === '幹'), 'C4 every erratum replaces a 幹 that is in the text');
  ok(data.guangyunMissing.length === 13, 'C5 thirteen characters unresolved in the rhyme-book data');
  has('Thirteen characters could not be found', 'C5');
  has('213 poems, scored here as regulated verse, and every one of them fits the scoring', 'C2');

  // D. every figure on the page
  const byId0 = new Map(data.poemsData.map(p => [p.id, p]));
  for (const v of ['P1 · PARTLY FAILED', 'P2 · PARTLY FAILED', 'P3 · HELD', 'P4 · HELD', 'P5 · HELD']) has(v, 'D0 the verdict labels');
  const S = E.score(data);
  const R = S.same.regulated, C = S.same.control;
  const u = S.unscored.regulated;
  ok(u.tests === 4354 && u.tests - u.notAllThree === 3396, 'D1 3,396 of 4,354 regulated tests scorable by all three');
  has('That leaves 3,396 of the 4,354 regulated tests', 'D1');
  const T = E.totals(R);
  ok(Math.round(pct(T.G)) === 97 && Math.round(pct(T.C)) === 96 && 100 - pct(T.M) > 10 && 100 - pct(T.M) < 100 / 9, 'D2 overall: 97%, 96%, and Mandarin fails more than one in ten (and fewer than one in nine)');
  has('the rules hold on 97% of tests; read them in Cantonese and they hold on 96%; read them in Mandarin and more than one test in ten fails', 'D2');
  // the prediction scorecard
  const g = r => pct(R[r].G);
  ok(f1(g('R1')) === '95.5' && f1(g('R2')) === '98.7' && f1(g('R3')) === '96.7' && f1(g('R4')) === '96.2', 'D3 P1 figures');
  has('(held: 95.5, 98.7, 96.7), and R4 at least 98% (failed: 96.2', 'D3');
  ok(f1(pct(C.R3.G)) === '54.9' && f1(pct(C.R2.G)) === '79.0', 'D4 P2 figures');
  has('adhesion at most 70% (held: 54.9) and opposition at most 75% (failed: 79.0)', 'D4');
  has('the adhesion rule holds 54.9% of the time', 'D4');
  has('79.0% of the time', 'D4');
  const dM = ['R1', 'R2', 'R3'].map(r => pct(R[r].G) - pct(R[r].M));
  ok(dM.map(f1).join(',') === '8.4,9.2,8.5' && dM.every(x => x >= 5 && x <= 20), 'D5 P3 held: ' + dM.map(f1));
  has('8.4, 9.2 and 8.5 points', 'D5');
  const dC = ['R1', 'R2', 'R3'].map(r => Math.abs(pct(R[r].G) - pct(R[r].C)));
  ok(dC.map(f1).join(',') === '0.6,0.6,1.1' && dC.every(x => x <= 3), 'D6 P4 held: ' + dC.map(f1));
  has('0.6, 0.6 and 1.1', 'D6');
  const flips = S.flips.filter(f => f.group === 'regulated');
  const ent = flips.filter(f => f.entering).length;
  ok(flips.length === 253 && ent === 246 && f1(100 * ent / flips.length) === '97.2', 'D7 P5 held: 246 of 253');
  has('246 of 253, 97.2%', 'D7');
  has('246 of 253 involve a syllable whose tone in 1008 was entering', 'D7');
  const changed = flips.filter(f => f.enteringChanged);
  ok(changed.length === 245, 'D7b in 245 the entering syllable itself changed class: ' + changed.length);
  has('and in 245 of them that syllable is the one Mandarin moved into the level class', 'D7b');
  const odd = flips.filter(f => f.entering && !f.enteringChanged).map(f => f.cells.map(([i, j]) => [...byId0.get(f.id).lines[i]][j]).join(''));
  ok(odd.length === 1 && odd[0].includes('莫') && odd[0].includes('場'), 'D7c the one other: 莫 and 場 ' + odd);
  // the seven others, by character
  const byId = new Map(data.poemsData.map(p => [p.id, p]));
  const other = {};
  for (const f of flips.filter(f => !f.entering)) {
    const p = byId.get(f.id);
    const chs = f.cells.map(([i, j]) => [...p.lines[i]][j]);
    const k = chs.includes('場') ? '場' : chs.includes('值') ? '值' : chs.includes('俱') ? '俱' : '?';
    other[k] = (other[k] || 0) + 1;
  }
  ok(other['場'] === 4 && other['值'] === 2 && other['俱'] === 1 && !other['?'], 'D8 the seven: 場 x4, 值 x2, 俱 x1 ' + JSON.stringify(other));
  has('場 read chǎng (four tests)', 'D8'); has('(two)', 'D8'); has('(one)', 'D8');
  // what the rules do between readers, rule by rule
  const maxGC = Math.max(...E.RULES.map(r => Math.abs(pct(R[r].G) - pct(R[r].C))));
  ok(maxGC < 2, 'D9 rhyme book and Cantonese within two points on every rule: max ' + f1(maxGC));
  has('agree to within two points on every rule', 'D9');
  const drops = ['R1', 'R2', 'R3', 'R5'].map(r => pct(R[r].G) - pct(R[r].M));
  ok(drops.every(x => x >= 8 && x <= 10) && Math.abs(pct(R.R4.G) - pct(R.R4.M)) < 1e-9, 'D10 Mandarin loses 8 to 10 points on every rule but rhyme, where it loses nothing: ' + drops.map(f1));
  has('Mandarin loses between eight and ten points on every rule except the rhyme, where it loses nothing', 'D10');
  // the entering tone
  const es = E.enteringStats(data);
  ok(es.entering === 984 && es.mLevel === 368 && es.mOblique === 615 && es.mNone === 1 && es.cOblique === 984, 'D11 984 entering syllables: Mandarin 368 level, 615 oblique, 1 toneless; Cantonese all oblique');
  has('In the regulated poems 984 syllables have only an entering reading. The Mandarin reader gives 368 of them a level tone and 615 an oblique one (and leaves one toneless). The Cantonese reader gives all 984 an oblique reading', 'D11');
  // the rhyme exceptions
  let r4fails = 0; const r4poems = new Map();
  for (const p of data.poemsData) {
    if (!p.scored || E.group(p.type) !== 'regulated') continue;
    const rd = E.readPoem(p, data.g);
    for (const t of E.testsFor(p)) if (t.rule === 'R4' && E.judge(t, rd.G) === false) { r4fails++; r4poems.set(p.id, (r4poems.get(p.id) || 0) + 1); }
  }
  const twice = [...r4poems].filter(([, n]) => n === 2).map(([id]) => byId.get(id));
  ok(r4fails === 22 && twice.length === 9 && twice.every(p => p.type === '五言絕句'), 'D12 22 rhyme failures; nine five-syllable quatrains fail both rhymes (18)');
  has('Nine poems in the anthology\'s five-syllable quatrain section rhyme on oblique tones throughout, which makes 18 of the 22 rhyme failures', 'D12');
  ok(['鹿柴', '竹裏館', '春曉', '江雪'].every(t => twice.some(p => p.title === t)), 'D13 the named four are among the nine');
  const once = [...r4poems].filter(([, n]) => n === 1).map(([id]) => byId.get(id).title).sort().join(',');
  ok(once === ['早寒有懷', '月夜', '無題·相見時難別亦難', '逢入京使'].sort().join(','), 'D14 the four single failures are the three 幹 poems and 早寒有懷: ' + once);
  const fixed = E.score(E.applyErrata(data)).same.regulated.R4.G;
  ok(R.R4.G.pass === 561 && fixed.pass === 564 && fixed.n === 583, 'D15 errata: rhyme 561 -> 564 of 583');
  has('the rhyme rule goes from 561 to 564 of 583', 'D15');
  const r1 = E.r1FailuresG(data);
  ok(r1.total === 67 && r1.special === 26 && r1.maybe === 9, 'D16 R1 failures 67; special form 26; maybe 9');
  has('Of the 67 within-line failures, 26 end in one shape', 'D16'); has('Nine more would end in the shape', 'D16');
  const headOblique = r1.specialLines.filter(s => s.head === 'Z');
  const jiangxue = r1.specialLines.filter(s => byId.get(s.id).title === '江雪' && s.line === 0);
  ok(headOblique.length === 4 && jiangxue.length === 1 && jiangxue[0].head !== 'Z' && r1.special - headOblique.length - jiangxue.length === 21, 'D16b 21 fit strictly: 4 with an oblique head syllable, and 江雪 line 1, a rhyme line');
  has('Only 21 of the 26 fit that form as the source describes it', 'D16b');
  ok(r1.other.some(o => byId.get(o.id).lines[o.line] === '黃鶴一去不復返') && r1.other.some(o => byId.get(o.id).title === '靜夜思'), 'D17 黃鶴一去不復返 and 靜夜思 are among the rest');
  const clean = E.cleanPoems(data);
  ok(clean.G === 151 && clean.C === 136 && clean.M === 65 && clean.poems === 213, 'D18 clean poems 151, 136, 65 of 213');
  has('151 of 213 in the rhyme book, 136 in Cantonese, 65 in Mandarin', 'D18');
  // the opening poem
  const du = data.poemsData.find(p => p.id === 189);
  const rd = E.readPoem(du, data.g);
  ok(du.title === '聞官軍收河南河北' && du.lines[6] === '即從巴峽穿巫峽', 'D19 the opening poem and its seventh line');
  ok(rd.M[6].every(k => k === 'P'), 'D20 in Mandarin line 7 is seven level tones');
  ok(['即', '峽'].every(ch => data.g[ch].length === 1 && data.g[ch][0] === '入') && [...du.lines[6]].filter(ch => data.g[ch]?.[0] === '入' && data.g[ch].length === 1).length === 3, 'D21 three of its syllables (即 峽 峽) are entering only');
  ok(du.m[6][0] === 'ji2' && du.m[6][3] === 'xia2' && du.m[6][6] === 'xia2', 'D22 and Mandarin says them with tone 2');
  const l7 = E.testsFor(du).filter(t => t.cells.some(([i]) => i === 6));
  ok(l7.every(t => E.judge(t, rd.G) !== false), 'D23 in the rhyme book line 7 fails no scorable test');
  const kan = E.testsFor(du).filter(t => E.judge(t, rd.M) === false && t.cells.some(([i, j]) => [...du.lines[i]][j] === '看'));
  ok(kan.length === 3 && E.classG(data.g['看']) === 'A' && du.c[2][1] === 'hon3' && du.m[2][1] === 'kan4', 'D24 看 in line 3: ambiguous in 1008, oblique in both modern readers, three Mandarin failures');
  has('The Mandarin reading breaks three more rules on 看', 'D24');
  has('即從巴峽穿巫峽, comes out as seven level tones. Three of its syllables (即, 峽, 峽)', 'D20');
  // the control poems keep none clean (so "no tone rule" is visible) and the regulated sections
  ok(E.cleanPoems(data, 'control').G === 0, 'D25 no old-style poem keeps every rule in the rhyme book');

  // E. the readers added on 7 November 2026: tone classes by hand
  ok(RD.classV('thập') === 'Z' && RD.classV('quốc') === 'Z' && RD.classV('bạch') === 'Z' && RD.classV('trung') === 'P' && RD.classV('hà') === 'P' && RD.classV('tà') === 'P', 'E1 Hán-Việt: -p -c -ch oblique; ngang and huyền level');
  ok(RD.classV('mã') === 'Z' && RD.classV('khán') === 'Z' && RD.classV('thượng') === 'Z' && RD.classV('hải') === 'Z', 'E2 Hán-Việt: ngã, sắc, nặng and hỏi oblique');
  ok(RD.classH('mâ') === 'P' && RD.classH('ngìn') === 'P' && RD.classH('hó') === 'Z' && RD.classH('fa') === 'Z' && RD.classH('koet') === 'Z' && RD.classH('pha̍k') === 'Z', 'E3 Sixian: circumflex and grave level; acute, an unmarked open syllable, and -p -t -k oblique');
  ok(RD.classT('sam') === 'P' && RD.classT('sâm') === 'P' && RD.classT('má') === 'Z' && RD.classT('sè') === 'Z' && RD.classT('tiōng') === 'Z' && RD.classT('chhit') === 'Z' && RD.classT('si̍p') === 'Z' && RD.classT('pe̍h') === 'Z' && RD.classT('saⁿ') === 'P', 'E4 Hokkien: tones 1 and 5 level; 2, 3, 7 and the checked tones oblique');
  ok(RD.enteringK('십') === true && RD.enteringK('국') === true && RD.enteringK('불') === true && RD.enteringK('마') === false && RD.enteringK('상') === false, 'E5 Korean: a syllable ending in ㅂ, ㄱ or ㄹ is entering, others are not');
  ok(RD.enteringJ('じふ') === true && RD.enteringJ('じゅう') === false && RD.enteringJ('こく') === true && RD.enteringJ('いち') === true && RD.enteringJ('く') === false && RD.enteringJ('せう') === false, 'E6 Japanese: two morae ending in く き つ ち ふ; 十 is じふ in the old spelling and じゅう in the new');
  ok(RD.hybrid('P', true) === 'Z' && RD.hybrid('P', false) === 'P' && RD.hybrid('P', 'mixed') === 'A' && RD.hybrid('P', null) === null && RD.hybrid('Z', false) === 'Z' && RD.hybrid(null, true) === null, 'E7 the repair: only a level Mandarin syllable moves, and only when every reading shows a stop');
  ok(RD.combine(['P', 'P']) === 'P' && RD.combine(['P', 'Z']) === 'A' && RD.combine([]) === null && RD.combineEntering([true, false]) === 'mixed', 'E8 readings in both classes are ambiguous, as in the rhyme book');
  ok(RD.classS('*mǎ') === 'Z' && RD.classS('kɑ̀n') === 'Z' && RD.classS('*kɑn') === 'P' && RD.classS('*zhip') === 'Z', 'E9 kTang: caron rising, grave departing, -p -t -k entering, unmarked level');
  const allChars = new Set(data.poemsData.flatMap(p => p.lines.flatMap(l => [...l])));
  ok([...allChars].every(ch => more.chars[ch]), 'E10 more-readers.json has a record for every corpus character');
  // E, continued: every figure the section "Six more readers" states, recomputed and found on the page
  const sg = x => (x < 0 ? '−' : '') + Math.abs(x).toFixed(1);
  const shortOf = (S, x) => ['R1', 'R2', 'R3'].map(r => pct(S.rules[r].G) - pct(S.rules[r][x]));
  const SV = RD.scoreSet(data, more, RD.sameSet('V')), ST = RD.scoreSet(data, more, RD.sameSet('T')), SH = RD.scoreSet(data, more, RD.sameSet('H'));
  const SK = RD.scoreSet(data, more, RD.sameSet('MK')), SJh = RD.scoreSet(data, more, RD.sameSet('MJh')), SHgd = RD.scoreSet(data, more, RD.sameSet('Hgd'));
  const v3 = shortOf(SV, 'V'), t3 = shortOf(ST, 'T'), k3 = shortOf(SK, 'MK'), j3 = shortOf(SJh, 'MJh'), h3 = shortOf(SH, 'H'), hm3 = shortOf(SH, 'M'), hc3 = shortOf(SH, 'C'), g3 = shortOf(SHgd, 'Hgd');
  ok(v3.map(sg).join(',') === '0.0,−0.4,0.0' && SV.rules.R2.V.pass - SV.rules.R2.G.pass === 2 && v3.every(x => Math.abs(x) <= 2), 'E12 P6: Hán-Việt 0.0, −0.4, 0.0, two opposition tests more than the rhyme book: ' + v3.map(sg));
  has('Hán-Việt within 2 points of the rhyme book on R1, R2 and R3: 0.0, −0.4 and 0.0', 'E12');
  has('Hán-Việt falls short of the rhyme book by 0.0 points on R1 and R3 and passes two opposition tests more than the rhyme book on R2', 'E12');
  ok(t3.map(sg).join(',') === '0.0,0.0,0.0' && ST.scored === 3121 && ST.flips.T.length === 0, 'E13 P7: Hokkien 0.0, 0.0, 0.0 on 3,121 tests, none failing that the rhyme book passes: ' + t3.map(sg) + ' ' + ST.scored);
  has('Hokkien falls short by 0.0, 0.0 and 0.0: of its 3,121 tests, not one that passes in the rhyme book fails in Hokkien', 'E13');
  has('Hokkien within 2 points of the rhyme book on the same three: 0.0, 0.0 and 0.0', 'E13');
  ok(k3.map(sg).join(',') === '0.1,0.2,0.6' && j3.map(sg).join(',') === '0.1,−0.2,0.3' && [...k3, ...j3].every(x => Math.abs(x) <= 2), 'E14 P10, P11: Mandarin mended with Korean 0.1, 0.2, 0.6; with the old spelling 0.1, −0.2, 0.3');
  has('Mandarin mended with Korean falls short by 0.1, 0.2 and 0.6 points on R1, R2 and R3, and mended with Japanese in the old spelling by 0.1, −0.2 and 0.3', 'E14');
  has('Mandarin mended with Korean within 2 points on R1, R2 and R3: 0.1, 0.2 and 0.6', 'E14');
  has('Mandarin mended with Japanese in the old spelling within 2 points: 0.1, −0.2 and 0.3', 'E14');
  const byIdE = new Map(data.poemsData.map(p => [p.id, p]));
  const breakers = (S, x) => { const set = new Set(); for (const f of S.flips[x]) { const p = byIdE.get(f.id), rd = RD.readPoemMore(p, data, more); for (const [i, j] of f.cells) if (rd[x][i][j] !== rd.G[i][j]) set.add([...p.lines[i]][j]); } return [...set].sort().join(''); };
  ok(breakers(SK, 'MK') === ['場', '值', '俱'].sort().join(''), 'E15 what the Korean mending leaves: 場, 值, 俱 (' + breakers(SK, 'MK') + ')');
  ok(data.g['值'].join() === '去' && more.chars['值'].K.join() === '치' && RD.enteringK('치') === false && data.g['場'].join() === '平' && data.g['俱'].join() === '平', 'E15b 值 is only departing in the rhyme book and its Korean reading 치 has no stop; 場 and 俱 are level in the rhyme book');
  has('What the mending leaves are a few Mandarin readings it cannot reach: 場 read chǎng and 俱 read jù, which have nothing to do with the entering tone, and 值 read zhí, which reflects an entering reading the rhyme book of 1008 does not list (a later rhyme book, the Jiyun, does) and whose Korean reading, 치, keeps no ending', 'E15');
  ok(h3.map(sg).join(',') === '7.5,10.2,9.8' && hm3.map(sg).join(',') === '8.4,10.7,8.2' && h3[2] > hm3[2], 'E16 Hakka 7.5, 10.2, 9.8 against Mandarin 8.4, 10.7, 8.2 on its tests: ' + h3.map(sg) + ' / ' + hm3.map(sg));
  has('On its tests it falls 7.5 points short on R1, 10.2 on R2 and 9.8 on R3, against Mandarin\'s 8.4, 10.7 and 8.2 on the same tests: about as far, and on adhesion further', 'E16');
  const p8a = h3[0] >= hc3[0] + 1, p8b = h3[0] < hm3[0] / 2;
  ok(p8a && !p8b && sg(hc3[0]) === '0.6', 'E17 P8 failed: at least a point beyond Cantonese (held), less than half of Mandarin (failed)');
  has('Hakka on R1 at least 1 point further short than Cantonese (held: 7.5 against 0.6) and less than half as far short as Mandarin (failed: 7.5 against 8.4)', 'E17');
  const hb = RD.hakkaBreaks(data, more);
  ok(hb.flips === 193 && hb.voiced === 173 && hb.voiced * 2 >= hb.flips, 'E18 P9: 173 of 193 Hakka failures involve a voiced rising syllable read level: ' + hb.voiced + '/' + hb.flips);
  has('Of the 193 tests that pass in the rhyme book and fail in Hakka, 173 involve a syllable that had a rising tone and a voiced initial and that Hakka reads in a level tone', 'E18');
  has('173 of 193', 'E18');
  const em = RD.enteringMemory(data, more);
  ok(em.H.P === 0 && em.H.Z > 900, 'E19 Hakka reads none of the old entering syllables as level');
  has('Hakka reads none of the old entering syllables only as level', 'E19');
  const hChars = Object.values(more.chars).filter(r => r.H && r.H.all.length);
  ok(hChars.length === 1987 && hChars.filter(r => r.H.by === 'literary').length === 59 && allChars.size === 2519, 'E20 Sixian readings for 1,987 of the 2,519 characters, a literary one named for 59');
  has('English Wiktionary names a literary reading for only 59 of the 1,987 corpus characters it gives Sixian readings for', 'E20');
  ok(g3.map(sg).join(',') === '6.0,8.6,7.4', 'E21 Meixian slips the same way: ' + g3.map(sg));
  has('The Meixian readings, a second Hakka variety, slip the same way: 6.0, 8.6 and 7.4 points', 'E21');
  ok(em.Jh.byEnding.p.join('/') === '115/117' && em.Jm.byEnding.p.join('/') === '0/117' && em.Jh.byEnding.t.join() === em.Jm.byEnding.t.join() && em.Jh.byEnding.k.join() === em.Jm.byEnding.k.join(), 'E22 the old spelling marks 115 of 117 -p syllables entering, the new none; -t and -k agree');
  has('the old spelling marks 115 of the 117 it reads one way as entering and the new spelling none of them; on -t and -k the two agree', 'E22');
  ok(em.byEnding.p === 118 && em.Jh.byEnding.p[1] === 117, 'E22b 118 old -p syllables, 117 of them read one way in each spelling');
  const SJ = RD.scoreSet(data, more, ['G', 'C', 'M', 'MJh', 'MJm']);
  const r1j = x => pct(SJ.rules.R1.G) - pct(SJ.rules.R1[x]);
  ok(sg(r1j('MJm')) === '1.1' && sg(r1j('MJh')) === '0.1' && (r1j('MJm') - r1j('MJh')).toFixed(2) === '1.04' && r1j('MJm') >= r1j('MJh') + 1, 'E23 P12: R1 1.1 against 0.1, a difference of 1.04: ' + (r1j('MJm') - r1j('MJh')).toFixed(3));
  has('falls 1.1 points short on R1, against 0.1 with the old, a difference of 1.04 points against the 1 predicted', 'E23');
  has('1.1 against 0.1, a difference of 1.04', 'E23');
  const sMJm = RD.scoreSet(data, more, RD.sameSet('MJm'));
  let xia2 = 0; for (const f of sMJm.flips.MJm) { const p = byIdE.get(f.id), rd = RD.readPoemMore(p, data, more); if (f.cells.some(([i, j]) => [...p.lines[i]][j] === '峽' && rd.MJm[i][j] !== rd.G[i][j])) xia2++; }
  ok(xia2 === 10, 'E24 峽 is in 10 of the new spelling\'s failures: ' + xia2);
  has('the gorge in Du Fu\'s seventh line (10 tests)', 'E24');
  { const SJ2 = RD.scoreSet(data, more, ['G', 'C', 'M', 'MJh', 'MJm']); let extra = 0, onP = 0;
    for (const poem of data.poemsData) { if (!poem.scored || E.group(poem.type) !== 'regulated') continue; const rd = RD.readPoemMore(poem, data, more);
      for (const t of E.testsFor(poem)) { const a = E.judge(t, rd.MJh), b = E.judge(t, rd.MJm); if ([a, b, E.judge(t, rd.G), E.judge(t, rd.C), E.judge(t, rd.M)].includes(null)) continue;
        if (a && !b) { extra++; if (t.cells.some(([i, j]) => RD.enteringEnding(more.chars[[...poem.lines[i]][j]]) === 'p' && rd.MJm[i][j] !== rd.MJh[i][j])) onP++; } } }
    ok(extra === 32 && onP === extra && SJ2.scored === 3350, 'E39 every test the new spelling fails and the old passes turns on an old -p syllable: ' + onP + ' of ' + extra); }
  has('Japanese in the new spelling slips where it was predicted to, and only there', 'E39');
  { const counts = new Map(); for (const f of sMJm.flips.MJm) { const p = byIdE.get(f.id), rd = RD.readPoemMore(p, data, more); for (const ch of new Set(f.cells.filter(([i, j]) => rd.MJm[i][j] !== rd.G[i][j]).map(([i, j]) => [...p.lines[i]][j]))) counts.set(ch, (counts.get(ch) || 0) + 1); }
    const top = [...counts].sort((a, b) => b[1] - a[1]); ok(top[0][0] === '峽' && top[0][1] === 10 && top[1][1] < 10, 'E24b 峽 does more of the new spelling\'s breaking than any other syllable: ' + top.slice(0, 3).map(x => x.join(' ')).join(', ')); }
  has('The syllable that does more of the breaking than any other is 峽', 'E24b');
  const xj = (more.chars['峽'].J || []).map(r => r.join('<')).sort().join(' ');
  ok(xj === ['ぎょう<げふ', 'こう<かふ'].sort().join(' '), 'E25 峽 was かふ and げふ, now こう and ぎょう: ' + xj);
  has('its go-on and kan-on readings were written げふ and かふ before 1946 and are now ぎょう and こう', 'E25');
  const duE = data.poemsData.find(p => p.id === 189), rdE = RD.readPoemMore(duE, data, more);
  const onLine7 = t => t.cells.some(([i]) => i === 6);
  const failSet = x => E.testsFor(duE).filter(t => onLine7(t) && E.judge(t, rdE[x]) === false).map(t => t.rule + t.cells.join()).join('|');
  ok(rdE.MJh[6][3] === 'Z' && rdE.MJh[6][6] === 'Z' && rdE.MJm[6][3] === 'P' && rdE.MJm[6][6] === 'P' && failSet('MJh') === '' && failSet('MJm') === failSet('M') && failSet('M') !== '', 'E26 Du Fu line 7: the old spelling mends both 峽, the new leaves the tests Mandarin breaks');
  has('Mandarin mended with the old spelling turns both 峽 back to oblique; with the new spelling they stay level, and the line breaks the same tests it breaks in Mandarin', 'E26');
  const keepT = x => 100 * em[x].Z / (em[x].Z + em[x].P), keepF = x => 100 * em[x].yes / (em[x].yes + em[x].no + em[x].mixed);
  const p13 = [keepT('V'), keepT('T'), keepT('H'), keepF('K'), keepF('Jh')];
  ok(p13.map(x => (x === 100 ? '100' : x.toFixed(1))).join(',') === '99.9,100,100,95.7,97.4' && keepF('Jm').toFixed(1) === '85.7' && p13.every(x => x >= 95) && keepF('Jh') - keepF('Jm') >= 5, 'E27 P13: 99.9, 100, 100, 95.7, 97.4; new spelling 85.7');
  has('(99.9, 100, 100, 95.7 and 97.4%), and the new spelling at least 5 points fewer (85.7%)', 'E27');
  ok(['K', 'Jh', 'Jm'].every(x => em[x].falseYes === 0 && em[x].falseOf > 6800 && em[x].falseOf < 7000), 'E28 P14: no false alarms in about 6,900 syllables each');
  has('none of about 6,900, in either spelling', 'E28');
  ok(breakers(SV, 'V') === ['幡', '婢', '榴'].sort().join('') && more.chars['幡'].V.join() === 'phướn' && more.chars['婢'].V.join() === 'tỳ' && more.chars['榴'].V.join() === 'lựu', 'E29 Hán-Việt\'s breaks are three readings: 幡 phướn, 婢 tỳ, 榴 lựu');
  has('Of its three readings that break a rule here, 婢 tỳ is the standard Hán-Việt reading; for 幡 the list gives only phướn', 'E29');
  has('and for 榴 it keeps only lựu', 'E29');
  ok((more.chars['一'].K || []).includes('일') && (more.chars['十'].J || []).some(([m, h]) => m === 'じゅう' && h === 'じふ'), 'E30 the examples: 一 is 일; 十 is じゅう, once じふ');
  for (const v of ['P6 · HELD', 'P7 · HELD', 'P8 · FAILED', 'P9 · HELD', 'P10 · HELD', 'P11 · HELD', 'P12 · HELD', 'P13 · HELD', 'P14 · HELD']) has(v, 'E31 the verdict labels');
  // each scorecard line whole, threshold included, and each verdict as the line's threshold makes it
  const card = [
    ['P6 · HELD. Hán-Việt within 2 points of the rhyme book on R1, R2 and R3: 0.0, −0.4 and 0.0.', v3.every(x => Math.abs(x) <= 2)],
    ['P7 · HELD. Hokkien within 2 points of the rhyme book on the same three: 0.0, 0.0 and 0.0.', t3.every(x => Math.abs(x) <= 2)],
    ['P8 · FAILED. Hakka on R1 at least 1 point further short than Cantonese (held: 7.5 against 0.6) and less than half as far short as Mandarin (failed: 7.5 against 8.4).', !(h3[0] >= hc3[0] + 1 && h3[0] < hm3[0] / 2)],
    ['P9 · HELD. At least half of the tests Hakka fails and the rhyme book passes involve an old rising syllable with a voiced initial that Hakka reads level: 173 of 193.', hb.voiced >= hb.flips / 2],
    ['P10 · HELD. Mandarin mended with Korean within 2 points on R1, R2 and R3: 0.1, 0.2 and 0.6.', k3.every(x => Math.abs(x) <= 2)],
    ['P11 · HELD. Mandarin mended with Japanese in the old spelling within 2 points: 0.1, −0.2 and 0.3.', j3.every(x => Math.abs(x) <= 2)],
    ['P12 · HELD. With the new spelling, at least 1 point further short on R1 than with the old: 1.1 against 0.1, a difference of 1.04.', r1j('MJm') >= r1j('MJh') + 1],
    ['P13 · HELD. Hán-Việt, Hokkien, Hakka, Korean and Japanese in the old spelling each keep at least 95% of the old entering syllables they read (99.9, 100, 100, 95.7 and 97.4%), and the new spelling at least 5 points fewer (85.7%).', p13.every(x => x >= 95) && keepF('Jh') - keepF('Jm') >= 5],
    ['P14 · HELD. Korean and Japanese mark fewer than 1% of the syllables with no entering reading in the rhyme book as entering: none of about 6,900, in either spelling.', ['K', 'Jh', 'Jm'].every(x => em[x].falseYes < em[x].falseOf / 100)],
  ];
  for (const [line, verdict] of card) { has(line, 'E33 the scorecard line, threshold and all'); ok(verdict, 'E33 the verdict the line prints is what its threshold gives: ' + line.slice(0, 12)); }
  ok(card.length === 9, 'E34 nine predictions'); has('nine predictions about them were committed before any of them was scored', 'E34');
  has('Hakka was predicted to slip, by at least a point more than Cantonese and by less than half as much as Mandarin. It slipped much further.', 'E35 P8\'s two thresholds as the prose states them');
  { const close = RD.NEW.filter(x => { const S0 = RD.scoreSet(data, more, RD.sameSet(x)); return S0.flips[x].length <= 8 && shortOf(S0, x).every(d => Math.abs(d) < 1); });
    ok(close.join() === 'V,T,MK,MJh', 'E36 four of the six fail at most eight tests the rhyme book passes and stay within a point: ' + close); }
  has('Four of the six hear the rules as the rhyme book does, or within a few tests of it', 'E36');
  ok((html.match(/data-reader="/g) || []).length === 9 && (html.match(/scored on 213 poems under nine readers: the rhyme book of 1008, Cantonese, Mandarin, Hán-Việt, Hokkien, Hakka, and Mandarin mended with Korean or Japanese readings\. Mandarin and Hakka break the most rules, for different reasons\./g) || []).length === 3, 'E37 nine reader buttons, and the three short descriptions say nine readers');
  { const S9 = RD.scoreSet(data, more, ['G', 'C', 'M', ...RD.NEW]); const all = x => { let pass = 0, n = 0; for (const r of E.RULES) { pass += S9.rules[r][x].pass; n += S9.rules[r][x].n; } return pass / n; };
    const worst = ['G', 'C', 'M', ...RD.NEW].sort((a, b) => all(a) - all(b)).slice(0, 2).sort().join();
    ok(worst === 'H,M', 'E38 on the tests every reader can score, Mandarin and Hakka break the most rules: ' + worst); }
  // the two Hakka romanizations against each other: where each gives one reading, the classes agree
  let both = 0, agree = 0;
  for (const r of Object.values(more.chars)) { if (!r.H || !r.Hgd || r.H.all.length !== 1 || r.Hgd.all.length !== 1) continue; const a = RD.classH(r.H.all[0]), b = RD.classHgd(r.Hgd.all[0]); if (!a || !b) continue; both++; if (a === b) agree++; }
  ok(both > 1000 && agree / both >= 0.95, 'E11 Sixian marks and Meixian tone numbers agree on the class of ' + agree + ' of ' + both + ' single-reading characters');
  // the dek: what it says of the new readers
  const SM = RD.scoreSet(data, more, RD.sameSet('MJm'));
  ok([...v3, ...t3].every(x => Math.abs(x) < 0.5) && [...k3, ...j3].every(x => Math.abs(x) < 1) && shortOf(SM, 'MJm').every(x => x < 2) && h3[0] > 0.8 * hm3[0], 'E32 the dek: Hán-Việt and Hokkien keep the rules, the mended readers nearly do, Hakka almost as often as Mandarin');
  has('Hán-Việt and Hokkien keep the rules as the rhyme book does, Korean or Japanese readings mend Mandarin, and Hakka, read from its dictionary, breaks them almost as often as Mandarin, for a different reason', 'E32');

  return { pass, fail };
}

const src = readFileSync(join(dir, 'engine.mjs'), 'utf8');
const readersSrc0 = readFileSync(join(dir, 'readers.mjs'), 'utf8');
const base = await run(src, false);
console.log(`${base.pass}/${base.pass + base.fail} checks passed`);
let exit = base.fail ? 1 : 0;
if (MUTATE) {
  const mutants = [
    ['Cantonese ignores the -p -t -k ending', src.replace("if (/[ptk]$/.test(m[1])) return OBLIQUE;", '')],
    ['Mandarin tone 3 counted as level', src.replace("t === '1' || t === '2' ? LEVEL", "t === '1' || t === '2' || t === '3' ? LEVEL")],
    ['adhesion tested as opposition', src.replace("T.push({ rule: 'R3', kind: 'same'", "T.push({ rule: 'R3', kind: 'diff'")],
    ['an ambiguous character scored as level', src.replace('return lv && ob ? AMBIG : lv ? LEVEL : OBLIQUE;', 'return lv ? LEVEL : OBLIQUE;')],
    ['R1 skips the fourth-sixth pair', src.replace('const key = L === 5 ? [1, 3] : [1, 3, 5];', 'const key = [1, 3];')],
    ['a flip credited to the entering tone whether or not it changed', src.replace('rd.E[i][j] && rd.G[i][j] !== rd.M[i][j]', 'rd.E[i][j]')],
    ['errata not applied', src.replace('chs[e.pos] = e.to; q.lines[e.line] = chs.join(\'\');', '')],
  ];
  // mutants of readers.mjs, the readers added on 7 November 2026
  const rs = readersSrc0;
  const readerMutants = [
    ['Hán-Việt huyền counted oblique', rs.replace('if (has(syl, ACUTE) || has(syl, HOOK) || has(syl, TILDE) || has(syl, DOT)) return OBLIQUE;', 'if (has(syl, ACUTE) || has(syl, HOOK) || has(syl, TILDE) || has(syl, DOT) || has(syl, GRAVE)) return OBLIQUE;')],
    ['Sixian grave (陽平) counted oblique', rs.replace('return has(syl, CIRC) || has(syl, GRAVE) ? LEVEL : OBLIQUE;', 'return has(syl, CIRC) ? LEVEL : OBLIQUE;')],
    ['Korean ㄹ not counted as an old -t', rs.replace('return jong === 1 || jong === 8 || jong === 17;', 'return jong === 1 || jong === 17;')],
    ['Japanese ふ not counted as an old -p', rs.replace("/[くきつちふ]$/.test(s)", "/[くきつち]$/.test(s)")],
    ['the repair moves a syllable on mixed readings', rs.replace('return entering === true ? OBLIQUE : entering === false ? LEVEL : AMBIG;', 'return entering === false ? LEVEL : OBLIQUE;')],
    ['Hakka reads every reading, not the literary one', rs.replace('H: rec.H ? combine(rec.H.use.map(classH)) : null,', 'H: rec.H ? combine(rec.H.all.map(classH)) : null,')],
    ['a new reader scored on its tests with the rhyme book alone, not the shared ones', rs.replace("export const sameSet = x => ['G', 'C', 'M', x];", "export const sameSet = x => ['G', x];")],
  ];
  let red = 0;
  for (const [name, m] of mutants) {
    if (m === src) { console.log(`  mutant "${name}" did not apply`); exit = 1; continue; }
    let r; try { r = await run(m, true); } catch { r = { fail: 1 }; } // a mutant that crashes the run is caught too
    if (r.fail) red++; else { console.log(`  mutant "${name}" survived`); exit = 1; }
  }
  for (const [name, m] of readerMutants) {
    if (m === rs) { console.log(`  mutant "${name}" did not apply`); exit = 1; continue; }
    let r; try { r = await run(src, true, m); } catch { r = { fail: 1 }; }
    if (r.fail) red++; else { console.log(`  mutant "${name}" survived`); exit = 1; }
  }
  console.log(`${red}/${mutants.length + readerMutants.length} mutants caught`);
}
process.exit(exit);
