#!/usr/bin/env node
// verify-its-own-description.mjs: checks /strata/its-own-description/ (the Kolakoski sequence).
//
//   node verify-its-own-description.mjs            # the sequence, the counts, Steinsky's window, the identity, the data, the prose
//   node verify-its-own-description.mjs --mutate   # also break the engine on purpose; checks must go red
//   node verify-its-own-description.mjs --quick    # skip the two long walks (10^9 and 3 x 10^8 terms)
//
// Needs only Node 18+. Inside the repository it tests the local files; from an empty directory it
// downloads the page's engine.mjs, data.json and index.html from https://artwaste.land into
// ./its-own-description-files/ (the bytes your browser runs). Exit 0 = every check passed.
// The full run takes about a minute, most of it walking 10^9 terms in O(log n) memory.
//
// What it checks:
//  A. the sequence two independent ways (two-headed tape; Nilsson's log-space recursion) agree term
//     by term for the first 10^7 terms, and the sequence is its own run-length sequence;
//  B. the count of 1s at every power of ten through 10^9 against Nilsson's published Table 1, and
//     Brent's published delta(n) and Delta(n)/sqrt(n) at 10^3, 10^6, 10^9, all recomputed from scratch;
//  C. Steinsky's window: runs begun by n, at every millionth n from 10^8 to 3 x 10^8, recomputed and
//     compared with every stored checkpoint, and all of them above 2/3;
//  D. the cancellation identity on every prefix of the first 10^5 terms, and that at run boundaries
//     only the terms standing alone contribute;
//  E. the random run sequences (variance 1/6 per term, by simulation) and the levels of reading
//     (repeated readings converge on the Kolakoski sequence from the front);
//  F. data.json: the published counts (A195206) and our decades agree; Rao's rows are reduced fractions
//     whose decimals are what they say; the bound's percentages;
//  G. every figure the prose states, recomputed here and found in its own sentence on the page;
//  H. the tower calculated: the stacked-readings machine writes exactly what reading coin flips j times
//     writes; every state has two ways in; the long-run spread in fractions (levels 0 to 7) and in
//     floating point (to level 12; above that read from data.json) equals data.json; at level 4 exactly the states where the second
//     reading is about to write a 2 give a coin no push, and no other level does; every measured level
//     lies within 3.5 standard errors of its calculated value; and every figure the section states,
//     each in its own sentence (whole tokens), against these or data.json (level23, wobble).
// What it does NOT check: the C runs (to 10^11 or beyond, 4,002 random sequences of 10^8 terms, 1,000
// coin starts per level), which take hours; their outputs are inputs here, and their programs are kept
// with fixed seeds in the repository. Nor that the sources say what the page says they say: the words
// relied on, with URLs and fetch dates, are in assay/sources/its-own-description.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 = 'its-own-description';
const MUTATE = process.argv.includes('--mutate');
const QUICK = process.argv.includes('--quick');
const FILES = ['engine.mjs', 'data.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()));
  }
}
console.error(`files: ${dir}`);

let pass = 0, fail = 0;
const ok = (cond, msg) => { if (cond) pass++; else { fail++; console.log(`FAIL ${msg}`); } return cond; };

// Nilsson 2012, Table 1: number of 1s in the first 10^k terms (k = 0..13)
const NILSSON = ['1', '5', '49', '502', '4996', '49972', '499986', '5000046', '50000675', '500001223', '4999997671', '50000001587', '500000050701', '5000000008159'];
// Brent 2016, table "Computation of delta(n)": n, delta(n), Delta(n)/n^(1/2)
const BRENT = [[1e3, -4, 0.1897], [1e6, 28, 0.0660], [1e9, -2446, 0.1560]];

async function run(E, D, html, quiet, long) {
  const before = fail;
  const say = (m) => { if (!quiet) console.log(m); };

  // A. two generators, and the self-description
  const N = quiet ? 200000 : 10000000;
  const P = E.prefix(N);
  const g = E.nilsson();
  let agree = P[0] === 1 && P[1] === 2;
  for (let i = 2; i < N && agree; i++) if (g.next() !== P[i]) agree = false;
  ok(agree, `A: the tape and Nilsson's recursion disagree within the first ${N} terms`);
  ok([1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 2, 1, 2, 1, 1, 2, 1, 2, 2, 1, 1].every((x, i) => P[i] === x), 'A: the first 29 terms are not those of OEIS A000002');
  let r = 0, i = 0, self = true;
  while (i < N - 2) { let j = i; while (j < N && P[j] === P[i]) j++; if (j >= N) break; if (j - i !== P[r] || j - i > 2) { self = false; break; } r++; i = j; }
  ok(self && r > N / 2, `A: the run lengths of the first ${N} terms are not the sequence itself (${r} runs checked)`);
  const ms = E.machineSteps(60);
  ok(ms.terms.slice(0, 60).every((x, k) => x === P[k]), 'A: the animated machine writes different terms');
  say(`  A. ${N.toLocaleString('en')} terms by two methods agree; ${r.toLocaleString('en')} runs read back as the sequence`);

  // B. counts through 10^9 (or 10^7 when quick), Brent's delta and Delta/sqrt(n)
  const top = long ? 1e9 : (quiet ? 1e5 : 1e7);
  const decades = []; for (let n = 10; n <= top; n *= 10) decades.push(n);
  const seen = new Map();
  const res = E.walk(top, decades, (m, delta, runs, ones) => seen.set(m, { delta, ones }));
  for (const n of decades) {
    const k = Math.round(Math.log10(n));
    ok(String(seen.get(n)?.ones) === NILSSON[k], `B: ones in first 10^${k}: ${seen.get(n)?.ones}, Nilsson ${NILSSON[k]}`);
  }
  for (const [n, dl, Dl] of BRENT) {
    if (n > top) continue;
    ok(seen.get(n).delta === dl, `B: delta(${n}) = ${seen.get(n).delta}, Brent ${dl}`);
    const w = E.walk(n);
    ok(Math.abs(w.maxAbs / Math.sqrt(n) - Dl) < 6e-5, `B: Delta(${n})/sqrt n = ${(w.maxAbs / Math.sqrt(n)).toFixed(4)}, Brent ${Dl}`);
  }
  if (long) ok(res.depth === 50, `B: Nilsson's recursion used ${res.depth} levels at 10^9; his Table 1 says 50`);
  say(`  B. counts at ${decades.length} powers of ten match Nilsson's Table 1; Brent's figures to ${top.toExponential(0)} match`);

  // C. Steinsky's window
  if (long) {
    const at = []; for (let n = 1e8; n <= 3e8; n += 1e6) at.push(n);
    const pts = [];
    E.walk(3e8, at, (m, delta, runs) => pts.push([m, runs]));
    ok(pts.length === D.steinsky.points.length, `C: ${pts.length} checkpoints, data has ${D.steinsky.points.length}`);
    ok(pts.every((p, k) => D.steinsky.points[k] && p[0] === D.steinsky.points[k][0] && p[1] === D.steinsky.points[k][1]), 'C: a stored Steinsky checkpoint differs from the recomputation');
    ok(pts.every(([n, runs]) => 3 * runs > 2 * n), 'C: some checkpoint is not above 2/3');
    say(`  C. Steinsky's window: ${pts.length} checkpoints recomputed, all equal to the stored ones, all above 2/3`);
  }

  // D. the cancellation identity
  {
    const M = quiet ? 5000 : 100000;
    let alt = 0, pos = 0, d = 0, okId = true, okSurv = true, surv = 0;
    for (let m = 1; m <= M; m++) {
      const Km = P[m - 1];
      alt += (m % 2 ? -1 : 1) * Km;
      for (let t = 0; t < Km; t++) { d += P[pos] === 2 ? 1 : -1; pos++; }
      if (d !== alt) { okId = false; break; }
      const alone = (m === 1 || P[m - 2] !== Km) && P[m] !== Km;
      if (alone) surv += (m % 2 ? -1 : 1) * Km;
      if (P[m] !== Km && surv !== alt) okSurv = false;   // at a run boundary, pairs have all cancelled
    }
    ok(okId, 'D: 2s - 1s written by the first m terms is not the alternating sum');
    ok(okSurv, 'D: at a run boundary the alternating sum is not the sum over lone terms');
    const a = E.alternating(P, 1000);
    ok(a.survivors.every((k) => (k === 0 || P[k - 1] !== P[k]) && P[k + 1] !== P[k]), 'D: engine.alternating marks a paired term as alone');
    say(`  D. cancellation identity on every prefix of ${M.toLocaleString('en')} terms`);
  }

  // E. random run sequences and the levels of reading
  {
    const seeds = quiet ? 40 : 300, n = quiet ? 20000 : 100000;
    let s2 = 0;
    for (let s = 1; s <= seeds; s++) { const st = E.stats(E.tower(1, n, s)); s2 += st.delta * st.delta / n; }
    const v = s2 / seeds;
    ok(Math.abs(v - 1 / 6) < (quiet ? 0.08 : 0.04), `E: random run sequences: mean (2s-1s)^2/n = ${v.toFixed(4)}, expected 1/6`);
    const coins = E.tower(0, 100000, 7); let twos = 0; for (const c of coins) if (c === 2) twos++;
    ok(Math.abs(twos / 1e5 - 0.5) < 0.01, `E: level 0 is not fair coin flips (${twos} twos in 100,000)`);
    ok(E.stats(P.subarray(0, 1000)).delta === -4 && E.stats(Uint8Array.from([2, 2, 1])).delta === 1, 'E: stats does not count 2s minus 1s (Brent: delta(1000) = -4)');
    const Kp = E.prefix(200000);
    const agreeAt = (j, seed) => { const t = E.tower(j, 200000, seed); let q = 0; while (q < t.length && t[q] === Kp[q]) q++; return q; };
    const a5 = Math.min(...[1, 2, 3].map((s) => agreeAt(5, s))), a15 = Math.min(...[1, 2, 3].map((s) => agreeAt(15, s)));
    ok(a15 > a5 && a15 > 500, `E: readings do not close in on Kolakoski (agree ${a5} terms at 5 readings, ${a15} at 15)`);
    ok(E.decode(Kp.subarray(0, 1000)).every((x, k) => x === Kp[k]), 'E: decode does not leave the Kolakoski sequence unchanged');
    say(`  E. random runs: mean (2s-1s)^2/n = ${v.toFixed(4)} (1/6 = 0.1667); readings agree with Kolakoski for ${a5} terms at 5, ${a15} at 15`);
  }

  // F. data.json
  {
    const pubOnes = D.long.map((p) => BigInt(p.ones));
    ok(pubOnes.slice(0, 14).every((x, k) => x.toString() === NILSSON[k]), 'F: data.json disagrees with Nilsson Table 1 through 10^13');
    ok(D.long.every((p) => BigInt(p.delta) === 10n ** BigInt(p.k) - 2n * BigInt(p.ones)), 'F: a stored delta is not n - 2 x ones');
    ok(D.long.filter((p) => p.reproduced).every((p) => p.matches === true), 'F: a reproduced decade does not match the published count');
    ok(D.ours.filter((o) => /^10*$/.test(o.n)).every((o) => { const k = o.n.length - 1; return BigInt(o.ones) === pubOnes[k]; }), 'F: our C counts disagree with A195206');
    const gcd = (a, b) => (b ? gcd(b, a % b) : a);
    ok(D.rao.length === 33 && D.rao.every((x, k) => x.d === k + 1 && gcd(x.num, x.den) === 1 && Math.abs(x.num / x.den - Number(x.decimal)) < 1e-12), 'F: a Rao row is not a reduced fraction equal to its decimal');
    const t33 = D.rao[32];
    ok(t33.num * 33 === 455920839 && t33.den * 33 === 911696379, 'F: T33 is not 455920839/911696379 reduced');
    ok(D.rao.every((x, k) => k === 0 || x.num / x.den <= D.rao[k - 1].num / D.rao[k - 1].den), 'F: the ladder of bounds is not monotone');
    ok(Math.abs(D.random.meanD2 - 1 / 6) < 0.01 && Math.abs(D.tower.find((x) => x.level === 1).d2 - 1 / 6) < 0.01, 'F: the C runs do not reproduce the 1/6');
    ok((D.random.closer === 0) === (D.random.smallest > D.random.kolMax), 'F: random.closer and random.smallest disagree');
    say(`  F. data.json: published and recomputed counts agree; Rao's ${D.rao.length} rows sound`);
  }

  // G. the prose
  {
    const text = html.replace(/<script[\s\S]*?<\/script>/g, ' ').replace(/<style[\s\S]*?<\/style>/g, ' ').replace(/<sup>/g, '^').replace(/<[^>]+>/g, ' ')
      .replace(/&nbsp;/g, ' ').replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/\s+/g, ' ');
    const sentences = text.split(/(?<=[.:;!?])\s+(?=[A-Z“(0-9])/);
    // a figure counts only as a whole token: not inside a longer number ("49" is not found in "499,986")
    const esc = (x) => x.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    const whole = (sen, fig) => new RegExp(`(^|[^0-9.,])${esc(fig)}(?![0-9]|[.,][0-9])`).test(sen);
    const said = (anchor, figure) => ok(sentences.some((s) => s.includes(anchor) && whole(s, figure)), `G: no sentence containing "${anchor}" states ${figure}`);
    const fmt = (x) => Number(x).toLocaleString('en-GB');
    const t33 = D.rao[32], share = t33.num / t33.den;
    said('In the first 100', fmt(NILSSON[2])); said('in the first thousand', NILSSON[3]); said('in the first million', fmt(NILSSON[6]));
    said('proof holds it between', `${(100 * (1 - share)).toFixed(3)}%`); said('proof holds it between', `${(100 * share).toFixed(3)}%`);
    said('held between about', `${(100 * (1 - share)).toFixed(3)}%`); said('within 0.000080', '455920839/911696379');
    ok(Math.abs(455920839 / 911696379 - 0.5 - 0.000080) < 5e-7, 'G: 455920839/911696379 is not within 0.000080 of a half');
    said('a band of', (2 * (share - 0.5)).toFixed(5).replace(/0+$/, ''));
    said('never strays further than', fmt(D.random.kolMax));
    said('the median strayed', fmt(D.random.median)); said('the closest of all of them', fmt(D.random.smallest));
    said('That is a variance of exactly', D.random.meanD2.toFixed(3)); said('That is a variance of exactly', fmt(D.random.seeds));
    said('about a third of', (Math.sqrt(2 / Math.PI) * Math.sqrt(1 / 6)).toFixed(2));
    said('about seventeen thousand squared', 'seventeen'); ok(Math.round(Math.sqrt(3e8) / 1000) === 17, 'G: 3e8 is not about seventeen thousand squared');
    const lev = (j) => D.tower.find((x) => x.level === j).d2.toFixed(3);
    said('Read twice', lev(2)); said('three times', lev(3)); said('four times', lev(4)); said('Read once', lev(1));
    const plat = D.tower.filter((x) => x.level >= 10).map((x) => x.d2);
    said('it hovers between', Math.min(...plat).toFixed(4)); said('it hovers between', Math.max(...plat).toFixed(4)); said('it hovers between', D.kolakoski.d2.toFixed(4));
    said('at all', `${D.steinsky.points.length} checkpoints`); said('at all', (D.steinsky.points.at(-1)[1] / 3e8).toFixed(9));
    const L20 = D.long[20]; said('At 10^20 terms', L20.ones.replace(/\B(?=(\d{3})+(?!\d))/g, ','));
    const share20 = Number(BigInt(L20.ones) * 10n ** 16n / 10n ** 20n) / 1e16;
    said('At 10^20 terms', share20.toFixed(16)); said('At 10^20 terms', (0.5 - share20).toExponential(2).split('e')[0]);
    ok(text.includes(`off a half by ${(0.5 - share20).toExponential(2).split('e')[0]} × 10^ −${-Math.floor(Math.log10(0.5 - share20))}`) || text.includes(`off a half by ${(0.5 - share20).toExponential(2).split('e')[0]} × 10^−${-Math.floor(Math.log10(0.5 - share20))}`), 'G: the exponent of the 10^20 deviation is not as computed');
    said('In the first 10 terms there are', NILSSON[1]);
    said('pushed the count to ten trillion', 'ten trillion'); said('took the count to', '10^13');
    said('coin flips, and in twenty draws', String(Math.round(1e6 / 1.5 ** 20 / 100) * 100));
    if (!quiet) {
      const K6 = E.prefix(1e6); let least = Infinity;
      for (let seed = 1; seed <= 20; seed++) { const t = E.tower(20, 1e6, seed); let q = 0; while (q < t.length && t[q] === K6[q]) q++; least = Math.min(least, q); }
      said('coin flips, and in twenty draws', fmt(least));
    }
    said('run to 10^8 terms each', fmt(D.random.seeds));
    // the table rows
    for (const o of D.ours.filter((o) => /^10+$/.test(o.n))) ok(text.includes(o.ones.replace(/\B(?=(\d{3})+(?!\d))/g, ',') + ' ' + o.ones.replace(/\B(?=(\d{3})+(?!\d))/g, ',') + ' ✓'), `G: the table does not show ${o.ones} beside its published match`);
    say(`  G. the prose: every stated figure found in its sentence`);
  }
  // H. the tower, calculated
  {
    const X = D.towerExact, top = quiet ? 6 : 12;
    // the machine against the readings themselves: same coins, same terms
    let same = true;
    for (let j = 1; j <= (quiet ? 5 : 8) && same; j++) {
      const m = E.readingMachine(j);
      for (let seed = 1; seed <= 3 && same; seed++) {
        const R = E.rng(9000 + 31 * j + seed), coins = Uint8Array.from({ length: 200 }, () => (R() < 0.5 ? 1 : 2));
        let st = 0, d = 0, len = 0;
        for (const c of coins) { const e = 2 * st + c - 1; d += m.R[e]; len += m.L[e]; st = m.next[e]; }
        let s2 = coins; for (let k = 0; k < j; k++) s2 = E.decode(s2);
        const ref = E.stats(s2);
        if (ref.n !== len || ref.delta !== d) same = false;
      }
    }
    ok(same, 'H: the stacked-readings machine does not write what reading the coins j times writes');
    let twoIn = true;
    for (let j = 1; j <= top; j++) { const m = E.readingMachine(j), ins = new Int32Array(m.n); for (const t of m.next) ins[t]++; if (!ins.every((k) => k === 2)) twoIn = false; }
    ok(twoIn, `H: some state of the machine does not have exactly two ways in (levels 1 to ${top})`);
    const F = (q) => `${q[0]}/${q[1]}`;
    let fracs = true, zeroOk = true;
    for (let j = 0; j <= (quiet ? 5 : 7); j++) {
      const x = E.towerExact(j);
      if (F(x.perTerm) !== X[j].frac || F(x.perCoin) !== X[j].fracCoin || x.block[0] !== 3n ** BigInt(j) || x.block[1] !== 2n ** BigInt(j)) fracs = false;
      const zeros = x.push.map((p, e) => (p[0] === 0n ? e >> 1 : -1)).filter((s) => s >= 0);
      if (j === 4) {
        const want = []; for (let s = 0; s < 16; s++) if ((s >> 1) & 1) want.push(s, s);
        if (zeros.join() !== want.join() || !x.push.every((p) => p[0] === 0n || (p[1] === 2n && (p[0] === 1n || p[0] === -1n)))) zeroOk = false;
      } else if (zeros.length) zeroOk = false;
    }
    ok(fracs, 'H: the exact spreads (fractions) are not the ones in data.json');
    ok(zeroOk, 'H: at level 4 the coins with no push are not exactly those arriving while reading 2 is about to write a 2 (others pushing by 1/2), or another level has one');
    let floats = true, noZero = true;
    for (let j = 0; j <= top; j++) {
      const x = E.towerSpread(j);
      if (Math.abs(x.perTerm - X[j].perTerm) > 1e-9 * Math.max(1, X[j].perTerm) || Math.abs(x.block - 1.5 ** j) > 1e-9 * 1.5 ** j) floats = false;
      if (j !== 4 && j > 0 && x.push.some((p) => Math.abs(p) < 1e-9)) noZero = false;
    }
    ok(floats, `H: the floating-point spreads to level ${top} are not the ones in data.json`);
    ok(noZero, `H: a level other than 4 (to ${top}) has a coin with no push`);
    ok(X.slice(1).filter((r) => r.zeroShare > 0).map((r) => r.level).join() === '4' && X[4].zeroShare === 0.5, 'H: data.json does not have level 4, and only level 4, with half its coins at no push');
    const zs = D.tower.map((r) => Math.abs(r.d2 - X[r.level].perTerm) / r.se);
    ok(D.tower.length === X.length && Math.max(...zs) < 3.5, `H: a measured level is ${Math.max(...zs).toFixed(1)} standard errors from its calculated value`);
    ok(Math.abs(D.towerV1.find((r) => r.level === 23).d2 - X[23].perTerm) / D.tower.find((r) => r.level === 23).se > 3, 'H: the corrected first-run value at level 23 is not more than three standard errors from the calculation');
    if (html) {
      const text = html.replace(/<script[\s\S]*?<\/script>/g, ' ').replace(/<style[\s\S]*?<\/style>/g, ' ').replace(/<sup>/g, '^').replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ');
      const sentences = text.split(/(?<=[.:;!?])\s+(?=[A-Z“(0-9])/);
      const esc = (x) => x.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
      const said = (anchor, figure) => ok(sentences.some((t) => t.includes(anchor) && new RegExp(`(^|[^0-9.,/])${esc(figure)}(?![0-9]|[.,/][0-9])`).test(t)), `H: no sentence containing "${anchor}" states ${figure}`);
      const fmt = (x) => Number(x).toLocaleString('en-GB');
      const L23 = D.level23, W = D.wobble;
      said('With the old seeding', fmt(L23.v1.seeds)); said('With the old seeding', `${L23.v1.d2.toFixed(5)} ± ${L23.v1.se.toFixed(5)}`); said('With the old seeding', `${L23.v2.d2.toFixed(5)} ± ${L23.v2.se.toFixed(5)}`);
      ok(L23.v1.seeds === L23.v2.seeds && Math.abs(L23.v2.d2 - X[23].perTerm) < 2 * L23.v2.se && Math.abs(L23.v1.d2 - X[23].perTerm) > 2 * L23.v1.se, 'H: the 16,000-start runs do not show the old seeding low and the new on the calculated value');
      const v1lo = Math.min(...D.towerV1.filter((r) => r.level >= 10).map((r) => r.d2)).toFixed(4);
      said('This page first gave the 23rd reading as', v1lo); said('The likeliest mechanism', String(Math.round(1e6 / 1.5 ** 23)));
      said('has a standard deviation of about', `${Math.round(100 * W.rule9)}%`); said('I checked the rule on', `${Math.round(100 * W.measured5)}%`); said('I checked the rule on', `${Math.round(100 * W.rule5)}%`);
      said('I checked the rule on', fmt(W.walks)); said('below the top of the tower', `${Math.round(100 * (1 - D.kolakoski.d2 / X.at(-1).perTerm))}%`);
      ok(Math.abs(W.rule9 - 2 / Math.sqrt(Math.log(1e9))) < 1e-3 && Math.abs(W.rule5 - 2 / Math.sqrt(Math.log(1e5))) < 1e-3, 'H: the 2/sqrt(S) figures are not 2/sqrt(ln 10^9) and 2/sqrt(ln 10^5)');
      said('sits below that band', D.kolakoski.d2.toFixed(4)); ok(D.kolakoski.d2 < Math.min(...X.filter((r) => r.level >= 15).map((r) => r.perTerm)), 'H: Kolakoski is not below the 15th-24th band');
      said('exactly half the coins have no push', 'half'); said('Every other coin pushes it by', '½');
      said('No other level from 1 to', String(X.at(-1).level)); said('it stays between', '15th'); said('it stays between', `${X.at(-1).level}th`);
      ok(text.includes('2^ j memory states') || text.includes('2^j memory states'), 'H: the machine is not said to have 2^j states');
      said('cancel at the fourth reading', 'fourth');
      const pc = X.map((r) => r.perCoin), growth = (a, b) => pc[b] / pc[a];
      ok([9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23].every((j) => growth(j, j + 1) > 1.3 && growth(j, j + 1) < 1.7) && X[9].perTerm < 0.6 * X[6].perTerm, 'H: "one more clear step from the sixth to the ninth, then the squared push grows about as fast as the blocks" does not hold');
      said('one more clear step down', 'sixth'); said('one more clear step down', 'ninth');
      said('settles at exactly', [1, 2, 3, 4, 5].map((j) => X[j].frac).join(', ') + ' and ' + X[6].frac);
      said('The seventh reading is already', X[7].frac);
      said('land within', Math.max(...zs).toFixed(1));
      said('At the fourth it falls to', X[4].fracCoin); said('Per term,', '2/81'); ok(X[4].frac === '2/81' && X[4].fracCoin === '1/8', 'H: level 4 is not 1/8 per coin and 2/81 per term');
      said('the spread per coin is 1/4, 1/4 and 5/16', '5/16'); ok([1, 2, 3].map((j) => X[j].fracCoin).join() === '1/4,1/4,5/16', 'H: the first three spreads per coin are not 1/4, 1/4, 5/16');
      const high = X.filter((r) => r.level >= 15).map((r) => r.perTerm);
      said('it stays between', Math.min(...high).toFixed(5)); said('it stays between', Math.max(...high).toFixed(5));
      said('This page first gave the 23rd reading as', D.towerV1.find((r) => r.level === 23).d2.toFixed(5));
      said('The calculated value is', X[23].perTerm.toFixed(5)); said('The calculated value is', 'more than three standard errors away');
      ok(Math.round(1e6 / 1.5 ** 23) === 89, 'H: a million terms at the 23rd reading do not come from about 89 coins');
    }
    say(`  H. the tower calculated: machine = readings; fractions to level ${quiet ? 5 : 7}, floats to ${top}; level 4 alone has no-push coins; measured within ${Math.max(...zs).toFixed(1)} s.e.`);
  }
  return fail - before;
}

const engineSrc = readFileSync(join(dir, 'engine.mjs'), 'utf8');
const E = await import(pathToFileURL(join(dir, 'engine.mjs')).href);
const D = JSON.parse(readFileSync(join(dir, 'data.json'), 'utf8'));
const html = readFileSync(join(dir, 'index.html'), 'utf8');
await run(E, D, html, false, !QUICK);

if (MUTATE) {
  const MUTANTS = [
    ['the tape stops alternating its digit', 'sym = 3 - sym;\n  }\n  return a.subarray', 'sym = sym;\n  }\n  return a.subarray'],
    ['Nilsson starts a new level at 1 instead of 2', 'if (k === top) { sym[k] = 2; rem[k] = 2; top++; }', 'if (k === top) { sym[k] = 1; rem[k] = 2; top++; }'],
    ['decode starts with 2s', 'let w = 0, sym = 1;', 'let w = 0, sym = 2;'],
    ['stats counts the walk backwards', "d += s[i] === 2 ? 1 : -1;\n    if (d === 0) zeros++;", "d += s[i] === 2 ? -1 : 1;\n    if (d === 0) zeros++;"],
    ['the coin is biased', 's[i] = R() < 0.5 ? 1 : 2;', 's[i] = R() < 0.6 ? 1 : 2;'],
    ['the stacked reading switches digit after every copy, not every run', 'nN[e] = (1 - d) + 2 * cur;', 'nN[e] = (x === 2 ? d : 1 - d) + 2 * cur;'],
    ['the calculated spread forgets to divide by the block length', 'return { j, perTerm: perCoin / block, perCoin, block, push, iterations: it };', 'return { j, perTerm: perCoin, perCoin, block, push, iterations: it };'],
  ];
  const tmp = mkdtempSync(join(tmpdir(), 'kola-mut-'));
  let caught = 0;
  for (const [name, from, to] of MUTANTS) {
    if (!engineSrc.includes(from)) { ok(false, `mutant "${name}": its target text is not in engine.mjs`); continue; }
    const f = join(tmp, `engine-${caught}-${Math.random().toString(36).slice(2)}.mjs`);
    writeFileSync(f, engineSrc.replace(from, to));
    const M = await import(pathToFileURL(f).href);
    const passBefore = pass, failBefore = fail;
    let n = 0;
    try { n = await run(M, D, html, true, false); } catch { n = 1; }
    pass = passBefore; fail = failBefore;
    if (ok(n > 0, `mutant "${name}" turned no check red`)) caught++;
    console.log(`  mutant: ${name}: ${n > 0 ? 'caught' : 'MISSED'}`);
  }
  console.log(`  ${caught} of ${MUTANTS.length} mutants caught`);
}

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