// verify-a-green-great-dragon.mjs
// ─────────────────────────────────────────────────────────────────────────────
// Re-derives every figure printed on /strata/a-green-great-dragon/ and asserts that the
// number the page prints is the number that comes back out of the data.
//
// The page's claim is that a famous rule about word order is gradient rather than absolute,
// and that no single sequence of adjectives can satisfy the corpus. Both halves are the kind
// of claim that a small bug could manufacture, so three disciplines are applied:
//
//   1. NOTHING IS ASSERTED AGAINST A CONSTANT IN THIS FILE ALONE. Every figure is recomputed
//      from the committed artifacts and then matched against the STRING IN THE SHIPPED HTML.
//      Drift in either direction fails.
//   2. THE EXTRACTOR ITSELF IS CHECKED, not only its output. The Python rule that read the
//      corpus is reimplemented here in JavaScript, run over a committed slice of raw
//      Wikipedia, and must reproduce Python's counts exactly, phrase for phrase.
//   3. THE STRUCTURAL RESULT IS RE-PROVED, not trusted. The minimum-cost linear ordering is
//      recomputed here by an independent dynamic program, the three-cycles are recounted, and
//      both are put through mutations that MUST turn the check red.
//
// Run: node verify-a-green-great-dragon.mjs
// ─────────────────────────────────────────────────────────────────────────────
import { readFileSync, existsSync } from 'node:fs';

const DIR = 'research/adjective-order';
const PAGE_PATH = 'public/strata/a-green-great-dragon/index.html';
const PAGE = readFileSync(PAGE_PATH, 'utf8');
const A = JSON.parse(readFileSync(`${DIR}/analysis.json`, 'utf8'));
const UD = JSON.parse(readFileSync(`${DIR}/ud-check.json`, 'utf8'));
const EX = JSON.parse(readFileSync(`${DIR}/examples.json`, 'utf8'));
const JUDGED = JSON.parse(readFileSync(`${DIR}/pairs-judged.json`, 'utf8'));
const LEX = JSON.parse(readFileSync(`${DIR}/lexicon.json`, 'utf8'));
const SAMPLE = readFileSync(`${DIR}/sample.txt`, 'utf8');
const SAMPLE_PAIRS = JSON.parse(readFileSync(`${DIR}/sample-pairs.json`, 'utf8'));
const PAIRS_JSON = JSON.parse(readFileSync('public/strata/a-green-great-dragon/pairs.json', 'utf8'));
const QUOTES = JSON.parse(readFileSync(`${DIR}/quotes.json`, 'utf8'));
const ST = JSON.parse(readFileSync(`${DIR}/stacks.json`, 'utf8'));

let pass = 0, fail = 0;
const fails = [];
function ok(cond, what, detail = '') {
  if (cond) pass++; else { fail++; fails.push(`${what}${detail ? '  — ' + detail : ''}`); }
}
function eq(got, want, what) {
  ok(got === want, what, `got ${JSON.stringify(got)}, want ${JSON.stringify(want)}`);
}
function near(got, want, tol, what) {
  ok(Math.abs(got - want) <= tol, what, `got ${got}, want ${want} (tol ${tol})`);
}
function says(s, what) { ok(PAGE.includes(s), `the page prints "${s}" — ${what}`); }
const n = (x) => Number(x).toLocaleString('en-GB');
const pc = (x, d = 1) => (100 * x).toFixed(d);
function section(t) { console.log(`\n── ${t} ` + '─'.repeat(Math.max(0, 64 - t.length))); }

// ── 1. the extractor, reimplemented ──────────────────────────────────────────
// The Python rule, written again from its own prose description. If the two implementations
// disagree on one phrase in a hundred thousand characters of real Wikipedia, this fails.
section('1. the extraction rule, rewritten in JavaScript and run on raw text');
const DEGREE = new Set(`very quite rather fairly pretty somewhat extremely particularly especially
relatively comparatively incredibly remarkably unusually exceptionally slightly moderately
highly deeply truly really so too more less most least much far even still nearly almost
fully largely mostly equally`.split(/\s+/).filter(Boolean));
const CLOSED = new Set(`in out up down off on over under back through above below near next past
here there then now once away apart together forward backward
one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen
sixteen seventeen eighteen nineteen twenty thirty forty fifty sixty seventy eighty ninety
hundred thousand million billion trillion half double triple quadruple single
that this these those which what who whose whom`.split(/\s+/).filter(Boolean));
const DET = new Set(LEX.det);
const ADJ = new Set(LEX.adj.filter((w) => !CLOSED.has(w) && !DEGREE.has(w) && !DET.has(w)));
const NOUN = new Set(LEX.noun.filter((w) => !CLOSED.has(w)));

function scan(text) {
  const pairs = new Map(), stacks = new Map();
  let nps = 0; const runlen = new Map();
  const unwrapped = text.replace(/\r\n/g, '\n').replace(/\r/g, '\n')
    .replace(/(?<!\n)\n(?!\n)/g, ' ');
  for (const seg of unwrapped.split(/[^A-Za-z'’\- ]+/)) {
    if (seg.length < 8) continue;
    const raw = seg.split(/ +/).filter(Boolean);
    const low = raw.map((w) => w.toLowerCase());
    const N = raw.length;
    let i = 0;
    while (i < N) {
      if (!DET.has(low[i])) { i++; continue; }
      let j = i + 1;
      while (j < N && DEGREE.has(low[j])) j++;
      const run = []; let k = j;
      while (k < N && ADJ.has(low[k])) { run.push(low[k]); k++; }
      const headOk = run.length >= 2 && k < N && NOUN.has(low[k])
        && raw[k] === raw[k].toLowerCase() && /[a-z]/.test(raw[k])
        && (k + 1 >= N || !NOUN.has(low[k + 1]));
      if (headOk) {
        nps++;
        runlen.set(run.length, (runlen.get(run.length) || 0) + 1);
        if (run.length >= 3) {
          const key = `${run.join(' ')} | ${low[k]}`;
          stacks.set(key, (stacks.get(key) || 0) + 1);
        }
        for (let x = 0; x < run.length; x++) {
          for (let y = x + 1; y < run.length; y++) {
            if (run[x] === run[y]) continue;
            const key = `${run[x]} ${run[y]}`;
            pairs.set(key, (pairs.get(key) || 0) + 1);
          }
        }
        i = k + 1;
      } else i = Math.max(j, i + 1);
    }
  }
  return { nps, runlen, pairs, stacks };
}
{
  const got = scan(SAMPLE);
  eq(got.nps, SAMPLE_PAIRS.phrases, 'JS and Python find the same number of phrases in sample.txt');
  const wantRun = SAMPLE_PAIRS.runlen;
  let runSame = true;
  for (const [len, count] of Object.entries(wantRun)) {
    if ((got.runlen.get(Number(len)) || 0) !== count) runSame = false;
  }
  ok(runSame && got.runlen.size === Object.keys(wantRun).length,
    'the stack-length histogram matches exactly',
    JSON.stringify([...got.runlen.entries()].sort()));
  const want = SAMPLE_PAIRS.pairs;
  let diff = 0, checked = 0;
  for (const [k, v] of Object.entries(want)) { checked++; if ((got.pairs.get(k) || 0) !== v) diff++; }
  for (const [k, v] of got.pairs) if (!(k in want) && v > 0) diff++;
  eq(diff, 0, `all ${checked} ordered pair counts agree between the two implementations`);
  let sdiff = 0;
  for (const [k, v] of Object.entries(SAMPLE_PAIRS.stacks)) {
    if ((got.stacks.get(k) || 0) !== v) sdiff++;
  }
  eq(sdiff, 0, `all ${Object.keys(SAMPLE_PAIRS.stacks).length} three-plus stacks agree`);
  ok(got.nps > 200, 'the sample is big enough to be worth agreeing about', `${got.nps} phrases`);

  // A control that must fail: break one word list and the agreement must break.
  const savedHas = ADJ.has.bind(ADJ);
  ADJ.delete('ancient');
  const broken = scan(SAMPLE);
  ok(broken.nps !== got.nps || [...broken.pairs.keys()].length !== [...got.pairs.keys()].length,
    'CONTROL: removing one adjective from the lexicon changes the result');
  ADJ.add('ancient');
  eq(scan(SAMPLE).nps, got.nps, 'and restoring it restores the result exactly');
  void savedHas;
}

// ── 2. the corpus totals ─────────────────────────────────────────────────────
section('2. corpus totals, as the page states them');
const W = A.generated_from.wiki, G = A.generated_from.gutenberg;
{
  eq(W.articles, JUDGED.wiki_meta.articles, 'article count agrees across artifacts');
  eq(W.phrases, JUDGED.wiki_meta.phrases, 'phrase count agrees across artifacts');
  eq(G.articles, JUDGED.gutenberg_meta.articles, 'book count agrees across artifacts');
  const shardArticles = A.generated_from.wiki.articles;
  ok(shardArticles > 6e6, 'the whole English Wikipedia was read, not a slice', `${shardArticles}`);
  const runTotal = Object.values(W.runlen).reduce((a, b) => a + b, 0);
  eq(runTotal, W.phrases, 'the stack-length histogram sums to the phrase count');
  eq(ST.phrases, W.phrases, 'the stacks artifact counts the same corpus');
  let stackSum = 0;
  for (const [len, count] of Object.entries(ST.runlen)) if (Number(len) >= 3) stackSum += count;
  eq(stackSum, Object.values(ST.runlen).reduce((a, b) => a + b, 0) - ST.runlen['2'],
    'three-plus stacks are everything except the two-adjective phrases');
  ok(ST.repeated_word_instances / ST.phrases < 0.001,
    'the category-tail contaminant is under a tenth of a percent of all phrases',
    `${ST.repeated_word_instances} of ${ST.phrases}`);
  for (const k of ['2', '3', '4', '5', '6', '7', '8']) says(n(ST.runlen[k]),
    `the count of phrases stacking ${k} adjectives`);
  says(n(ST.stack_instances), 'phrases stacking three or more');
  says(n(ST.repeated_word_instances), 'phrases repeating a word inside the stack');
  says(n(W.articles), 'Wikipedia article count');
  says(n(W.tokens), 'Wikipedia word count');
  says(n(W.phrases), 'Wikipedia phrase count');
  says(n(G.articles), 'Gutenberg book count');
  says(n(G.phrases), 'Gutenberg phrase count');
}

// ── 3. how absolute is "absolutely" ──────────────────────────────────────────
section('3. the determinism statistics, recomputed from the committed pair counts');
// An independent Clopper-Pearson: the lower bound is the p at which the exact binomial
// upper tail P(X >= k) equals alpha/2. Computed here by bisection on a log-space tail sum,
// which shares no code with the beta quantile scipy used on the other side.
// The regularized incomplete beta, by the standard continued fraction. Everything
// binomial below is expressed through it, which keeps each evaluation O(iterations)
// rather than O(n) and shares no code at all with scipy on the other side.
function lnGamma(x) {
  const c = [76.18009172947146, -86.50532032941677, 24.01409824083091,
    -1.231739572450155, 0.1208650973866179e-2, -0.5395239384953e-5];
  let y = x, tmp = x + 5.5;
  tmp -= (x + 0.5) * Math.log(tmp);
  let ser = 1.000000000190015;
  for (let j = 0; j < 6; j++) ser += c[j] / ++y;
  return -tmp + Math.log(2.5066282746310005 * ser / x);
}
function betacf(a, b, x) {
  const FPMIN = 1e-300, EPS = 3e-16;
  const qab = a + b, qap = a + 1, qam = a - 1;
  let c = 1, d = 1 - qab * x / qap;
  if (Math.abs(d) < FPMIN) d = FPMIN;
  d = 1 / d;
  let h = d;
  for (let m = 1; m <= 500; m++) {
    const m2 = 2 * m;
    let aa = m * (b - m) * x / ((qam + m2) * (a + m2));
    d = 1 + aa * d; if (Math.abs(d) < FPMIN) d = FPMIN;
    c = 1 + aa / c; if (Math.abs(c) < FPMIN) c = FPMIN;
    d = 1 / d; h *= d * c;
    aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2));
    d = 1 + aa * d; if (Math.abs(d) < FPMIN) d = FPMIN;
    c = 1 + aa / c; if (Math.abs(c) < FPMIN) c = FPMIN;
    d = 1 / d;
    const del = d * c; h *= del;
    if (Math.abs(del - 1) < EPS) break;
  }
  return h;
}
function betai(a, b, x) {          // I_x(a, b)
  if (x <= 0) return 0;
  if (x >= 1) return 1;
  const bt = Math.exp(lnGamma(a + b) - lnGamma(a) - lnGamma(b)
    + a * Math.log(x) + b * Math.log1p(-x));
  return x < (a + 1) / (a + b + 2) ? bt * betacf(a, b, x) / a
                                   : 1 - bt * betacf(b, a, 1 - x) / b;
}
// P(X >= k) for X ~ Binomial(N, p) is exactly I_p(k, N-k+1).
function tailGE(k, N, p) { return k <= 0 ? 1 : betai(k, N - k + 1, p); }
// At p = 0.5 the distribution is symmetric, so the two-sided exact p-value under the
// "equal or less likely" rule is just twice the upper tail.
function binomTwoSided(k, N) {
  if (N === 0) return 1;
  const kk = Math.max(k, N - k);
  return Math.min(1, 2 * tailGE(kk, N, 0.5));
}
function cpLower(k, N, alpha = 0.05) {
  if (k === 0) return 0;
  if (k === N) return Math.pow(alpha / 2, 1 / N);
  let lo = 0, hi = 1;
  for (let it = 0; it < 80; it++) {
    const mid = (lo + hi) / 2;
    if (tailGE(k, N, mid) < alpha / 2) lo = mid; else hi = mid;
  }
  return (lo + hi) / 2;
}
const D = A.determinism;
{
  const wiki = JUDGED.wiki;
  const MIN = A.params.min_pair;
  let judged = 0, instances = 0, minority = 0, both = 0, categorical = 0;
  const bins = {};
  const bump = (b) => { bins[b] = (bins[b] || 0) + 1; };
  for (const [, [ab, ba]] of Object.entries(wiki)) {
    const tot = ab + ba;
    if (tot < MIN) continue;
    const k = Math.max(ab, ba), share = k / tot;
    judged++; instances += tot; minority += tot - k;
    if (Math.min(ab, ba) > 0) both++;
    if (share >= 0.99) bump('99-100');
    else if (share >= 0.95) bump('95-99');
    else if (share >= 0.90) bump('90-95');
    else if (share >= 0.75) bump('75-90');
    else if (share >= 0.60) bump('60-75');
    else bump('50-60');
    if (cpLower(k, tot) >= 0.95) categorical++;
  }
  eq(judged, D.pairs_judged, 'number of judged pairs');
  eq(instances, D.instances, 'number of phrase instances behind them');
  eq(minority, D.minority_instances, 'number of instances in their pair\'s minority order');
  eq(both, D.pairs_both_orders_attested, 'pairs attested in both orders');
  eq(categorical, D.pairs_provably_categorical,
    'pairs whose 95% lower bound on the majority share clears 0.95 (independent Clopper-Pearson)');
  // the two implementations of the bound itself, compared case by case
  let worst = 0, worstP = 0;
  for (const r of A.pairs) {
    const d = Math.abs(cpLower(Math.max(r.ab, r.ba), r.n) - r.lo);
    if (d > worst) worst = d;
    const dp = Math.abs(binomTwoSided(Math.max(r.ab, r.ba), r.n) - r.p);
    if (dp > worstP) worstP = dp;
  }
  ok(worst < 1e-8, `the JavaScript Clopper-Pearson matches scipy's on all ${A.pairs.length} `
    + 'stored pairs', `worst disagreement ${worst}`);
  ok(worstP < 1e-8, 'and so does the two-sided exact binomial p-value',
    `worst disagreement ${worstP}`);
  let binsSame = true;
  for (const b of Object.keys(D.share_bins)) if ((bins[b] || 0) !== D.share_bins[b]) binsSame = false;
  ok(binsSame, 'every histogram bar recomputes', JSON.stringify(bins));
  eq(Object.values(D.share_bins).reduce((a, b) => a + b, 0), D.pairs_judged,
    'the histogram accounts for every judged pair');
  near(minority / instances, D.minority_rate, 1e-12, 'the minority rate');

  says(n(D.pairs_judged), 'judged pair count');
  says(n(D.instances), 'phrase instances');
  says(n(D.minority_instances), 'minority-order instances');
  says(pc(D.minority_rate, 2), 'minority rate percentage');
  says(n(D.pairs_both_orders_attested), 'pairs seen in both orders');
  says(n(D.pairs_provably_categorical), 'provably categorical pairs');

  // The claim that matters most, stated as an inequality rather than a number.
  ok(D.pairs_provably_categorical < D.pairs_judged / 2,
    'fewer than half of judged pairs are provably near-categorical',
    `${D.pairs_provably_categorical} of ${D.pairs_judged}`);
  // CONTROL: a corpus in which the rule really were absolute would put everything in the
  // last bin. Assert we are not looking at that corpus.
  ok((D.share_bins['99-100'] || 0) < D.pairs_judged,
    'CONTROL: not every pair is in the 99-100% bin (which is what a law would look like)');
}

// ── 4. the tournament: cycles and the proven optimum ─────────────────────────
section('4. the structural result, re-proved from the committed counts');
function matrixFor(words, side = 'wiki') {
  const idx = new Map(words.map((w, i) => [w, i]));
  const M = words.map(() => words.map(() => 0));
  for (const [key, [ab, ba]] of Object.entries(JUDGED[side])) {
    const [a, b] = key.split(' ');
    if (!idx.has(a) || !idx.has(b)) continue;
    M[idx.get(a)][idx.get(b)] += ab;
    M[idx.get(b)][idx.get(a)] += ba;
  }
  return M;
}
function cycles3(M, minPair) {
  const N = M.length;
  const beats = M.map((_, i) => M.map((__, j) => {
    if (i === j) return 0;
    return (M[i][j] + M[j][i] >= minPair && M[i][j] > M[j][i]) ? 1 : 0;
  }));
  let c = 0; const ex = [];
  for (let i = 0; i < N; i++) for (let j = 0; j < N; j++) {
    if (!beats[i][j]) continue;
    for (let k = 0; k < N; k++) {
      if (beats[j][k] && beats[k][i] && i < j && i < k) { c++; if (ex.length < 5) ex.push([i, j, k]); }
    }
  }
  return { count: c, ex };
}
function cycles3Sig(M, minPair, alpha) {
  const N = M.length;
  const beats = M.map((_, i) => M.map((__, j) => {
    if (i === j) return 0;
    const tot = M[i][j] + M[j][i];
    if (tot < minPair || M[i][j] <= M[j][i]) return 0;
    return binomTwoSided(M[i][j], tot) < alpha ? 1 : 0;
  }));
  let c = 0;
  for (let i = 0; i < N; i++) for (let j = 0; j < N; j++) {
    if (!beats[i][j]) continue;
    for (let k = 0; k < N; k++) if (beats[j][k] && beats[k][i] && i < j && i < k) c++;
  }
  return c;
}

function orderCost(M, perm) {
  let c = 0;
  for (let x = 0; x < perm.length; x++) for (let y = x + 1; y < perm.length; y++) c += M[perm[y]][perm[x]];
  return c;
}
function lowerBound(M) {
  let c = 0;
  for (let i = 0; i < M.length; i++) for (let j = i + 1; j < M.length; j++) c += Math.min(M[i][j], M[j][i]);
  return c;
}
// Independent exact solver: same recurrence, written again.
function exactMin(M) {
  const N = M.length, size = 1 << N;
  const add = [];
  for (let j = 0; j < N; j++) {
    const a = new Float64Array(size);
    for (let S = 1; S < size; S++) {
      const low = S & -S, i = 31 - Math.clz32(low);
      a[S] = a[S ^ low] + M[j][i];
    }
    add.push(a);
  }
  const INF = Infinity;
  const dp = new Float64Array(size).fill(INF);
  const par = new Int8Array(size).fill(-1);
  dp[0] = 0;
  for (let S = 0; S < size; S++) {
    const base = dp[S];
    if (base === INF) continue;
    for (let j = 0; j < N; j++) {
      const bit = 1 << j;
      if (S & bit) continue;
      const v = base + add[j][S];
      if (v < dp[S | bit]) { dp[S | bit] = v; par[S | bit] = j; }
    }
  }
  let S = size - 1; const perm = [];
  while (S) { const j = par[S]; perm.push(j); S ^= 1 << j; }
  perm.reverse();
  return { cost: dp[size - 1], perm };
}
const E = A.exact;
{
  const M = matrixFor(E.words);
  let same = true;
  for (let i = 0; i < E.words.length; i++) for (let j = 0; j < E.words.length; j++) {
    if (M[i][j] !== E.matrix[i][j]) same = false;
  }
  ok(same, `the ${E.words.length}x${E.words.length} tournament rebuilds from pairs-judged.json`);

  const cy = cycles3(M, A.params.min_pair);
  eq(cy.count, E.three_cycles, 'the three-cycle count, recounted');
  ok(E.three_cycles > 0, 'there is at least one cycle, which is the whole structural claim');
  // and again with every edge required to be a significant majority, so a cycle cannot be
  // three coin flips. Two-sided exact binomial, computed from the tail sums above.
  const sig = cycles3Sig(M, A.params.min_pair, 0.01);
  eq(sig, E.three_cycles_significant, 'the significant-edge cycle count, recounted');
  ok(E.three_cycles_significant > 0,
    'at least one cycle survives when every edge must be significant at p < 0.01');
  ok(E.three_cycles_significant <= E.three_cycles,
    'the stricter count cannot exceed the looser one');
  says(n(E.three_cycles_significant), 'cycles built only from significant edges');
  eq(lowerBound(M), E.lower_bound, 'the per-pair lower bound, recomputed');

  const solved = exactMin(M);
  eq(solved.cost, E.optimal_cost, 'the proven minimum cost, from an independent solver');
  const ladderIdx = E.ladder.map((w) => E.words.indexOf(w));
  eq(orderCost(M, ladderIdx), E.optimal_cost, 'the published ladder actually achieves that cost');
  eq(new Set(E.ladder).size, E.words.length, 'the published ladder is a permutation of the vocabulary');
  ok(E.optimal_cost > E.lower_bound,
    'a single line costs strictly more than choosing per pair, which is what a cycle forces',
    `${E.optimal_cost} vs ${E.lower_bound}`);
  const totalCheck = M.flat().reduce((a, b) => a + b, 0);
  eq(totalCheck, E.total_instances, 'the instance total behind the optimum');
  near(E.optimal_cost / E.total_instances, E.wrong_rate, 1e-12, 'the wrong-order rate');

  // CONTROLS. Both of these must move the answer, or the solver is not looking at the data.
  const M2 = M.map((r) => r.slice());
  const [i0, j0] = [ladderIdx[0], ladderIdx[E.words.length - 1]];
  const t = M2[i0][j0]; M2[i0][j0] = M2[j0][i0]; M2[j0][i0] = t;
  ok(exactMin(M2).cost !== E.optimal_cost,
    'CONTROL: swapping one pair\'s two counts changes the proven optimum');
  const reversed = ladderIdx.slice().reverse();
  ok(orderCost(M, reversed) > E.optimal_cost,
    'CONTROL: the reversed ladder is worse than the optimum',
    `${orderCost(M, reversed)} vs ${E.optimal_cost}`);
  ok(orderCost(M, ladderIdx) + orderCost(M, reversed) === totalCheck,
    'a permutation and its reverse partition every instance between them');

  says(n(E.optimal_cost), 'the proven minimum number of phrases any sequence gets wrong');
  says(n(E.lower_bound), 'the per-pair unavoidable part');
  says(n(E.cost_of_transitivity), 'the price of insisting on one line');
  says(n(E.total_instances), 'instances behind the top-20 tournament');
  says(n(E.three_cycles), 'the three-cycle count');
  says(n(E.judged_triples), 'the judged-triple count');
}
{
  // the eight-word game the reader plays
  const g = A.game;
  ok(!!g, 'the game vocabulary exists');
  if (g) {
    const M = matrixFor(g.words);
    const solved = exactMin(M);
    eq(solved.cost, g.optimal_cost, 'the game\'s proven optimum, independently solved');
    eq(orderCost(M, g.ladder.map((w) => g.words.indexOf(w))), g.optimal_cost,
      'the game\'s published best arrangement achieves it');
    let worse = 0;
    const perm = g.words.map((_, i) => i);
    // every arrangement of the game vocabulary, exhaustively
    const permute = (arr, k = 0) => {
      if (k === arr.length) { if (orderCost(M, arr) < g.optimal_cost) worse++; return; }
      for (let i = k; i < arr.length; i++) {
        [arr[k], arr[i]] = [arr[i], arr[k]];
        permute(arr, k + 1);
        [arr[k], arr[i]] = [arr[i], arr[k]];
      }
    };
    permute(perm);
    eq(worse, 0,
      `no arrangement of the ${g.words.length} game words beats the stated optimum (all ${
        [...Array(g.words.length)].reduce((a, _, i) => a * (i + 1), 1)} enumerated)`);
    says(n(g.optimal_cost), 'the game optimum');
    says(n(g.total_instances), 'the game instance total');
  }
}

// ── 5. the mnemonic ──────────────────────────────────────────────────────────
section('5. the eight-class rule, scored');
{
  const M = A.mnemonic;
  const wordCat = new Map();
  let dupe = 0;
  for (const [cat, words] of Object.entries(M.assignment)) {
    for (const w of words) { if (wordCat.has(w)) dupe++; wordCat.set(w, cat); }
  }
  eq(dupe, 0, 'no adjective is filed under two classes');
  const withN = M.cells.reduce((a, c) => a + (c.with || 0), 0);
  const againstN = M.cells.reduce((a, c) => a + (c.against || 0), 0);
  eq(withN, M.instances_with, 'the "with the rule" total is the sum of its cells');
  eq(againstN, M.instances_against, 'the "against the rule" total is the sum of its cells');
  near(withN / (withN + againstN), M.accuracy, 1e-12, 'the mnemonic accuracy');
  ok(M.accuracy > 0.5, 'the rule is doing real work, well above chance', `${pc(M.accuracy)}%`);
  ok(M.accuracy < 1, 'and it is not absolute');
  eq(M.sequence.join('-'), 'opinion-size-age-shape-colour-origin-material-purpose',
    'the sequence scored is the one the book prints');
  says(pc(M.accuracy), 'the mnemonic accuracy');
  says(n(M.instances_with), 'phrases with the rule');
  says(n(M.instances_against), 'phrases against it');
  // recompute the cells straight from the pair counts
  let cellDiff = 0;
  const idxOf = new Map(M.sequence.map((c, i) => [c, i]));
  const tally = new Map();
  for (const [key, [ab, ba]] of Object.entries(JUDGED.wiki)) {
    const [a, b] = key.split(' ');
    const ca = wordCat.get(a), cb = wordCat.get(b);
    if (!ca || !cb || ca === cb) continue;
    const k1 = `${ca}|${cb}`, k2 = `${cb}|${ca}`;
    tally.set(k1, (tally.get(k1) || 0) + ab);
    tally.set(k2, (tally.get(k2) || 0) + ba);
  }
  // note: analysis.json counts every pair, this recomputation only the ones at or above the
  // committed threshold, so the check is a floor rather than an identity
  let recWith = 0, recAgainst = 0;
  for (const [k, v] of tally) {
    const [ca, cb] = k.split('|');
    if (idxOf.get(ca) < idxOf.get(cb)) recWith += v; else recAgainst += v;
  }
  ok(recWith > 0 && recAgainst > 0, 'both directions survive the committed threshold');
  ok(recWith / (recWith + recAgainst) > 0.5 && recWith / (recWith + recAgainst) < 1,
    'the accuracy recomputed over committed pairs alone is also strictly between 50% and 100%',
    `${pc(recWith / (recWith + recAgainst))}%`);
  void cellDiff;
}

// ── 6. the two independence checks ───────────────────────────────────────────
section('6. a second corpus, and a set of hand-parsed trees');
{
  const X = A.cross_corpus, MIN = A.params.min_pair;
  let compared = 0, same = 0;
  for (const [key, [wab, wba]] of Object.entries(JUDGED.wiki)) {
    const pg = JUDGED.gutenberg[key];
    if (!pg) continue;
    const [pab, pba] = pg;
    if (wab + wba < MIN || pab + pba < MIN || wab === wba || pab === pba) continue;
    compared++;
    if ((wab > wba) === (pab > pba)) same++;
  }
  eq(compared, X.pairs_compared, 'pairs common to both corpora');
  eq(same, X.same_direction, 'pairs agreeing on direction');
  near(same / compared, X.agreement, 1e-12, 'the cross-corpus agreement');
  ok(X.agreement > 0.8, 'the two corpora largely agree, so this is English and not Wikipedia',
    `${pc(X.agreement)}%`);
  ok(X.agreement < 1, 'and they do not agree perfectly, which is worth saying out loud');
  says(n(X.pairs_compared), 'cross-corpus pairs compared');
  says(n(X.same_direction), 'cross-corpus pairs agreeing');
  says(pc(X.agreement), 'cross-corpus agreement');
}
{
  eq(UD.order_agree + UD.order_clash > 0, true, 'the treebank comparison has data');
  near(UD.order_agreement, UD.order_agree / (UD.order_agree + UD.order_clash), 1e-12,
    'the treebank order agreement is its own ratio');
  ok(UD.order_agreement > 0.99,
    'where a human parse and this rule both see a pair, they agree on the order',
    `${pc(UD.order_agreement, 2)}%`);
  ok(UD.precision_stack > UD.precision_strict,
    'the relaxed precision is the higher of the two, as it must be');
  ok(UD.treebanks.length >= 10, 'more than one treebank was used', `${UD.treebanks.length} files`);
  says(n(UD.sentences), 'treebank sentence count');
  says(n(UD.order_agree), 'treebank order agreements');
  says(pc(UD.order_agreement, 2), 'treebank order agreement rate');
  says(pc(UD.precision_stack), 'the relaxed precision');
  says(pc(UD.precision_strict), 'the strict precision');
  says(pc(UD.recall_strict), 'the recall');
  const GOLD = A.gold_check;
  near(GOLD.agreement, GOLD.same_direction / GOLD.pairs_compared, 1e-12,
    'the gold-versus-Wikipedia agreement is its own ratio');
  says(n(GOLD.pairs_compared), 'gold pairs compared with Wikipedia');
  says(n(GOLD.same_direction), 'gold pairs agreeing with Wikipedia');
}

// ── 7. the sentences the page prints ─────────────────────────────────────────
section('7. every quoted sentence really contains its phrase');
{
  let checked = 0, bad = 0, missing = 0;
  for (const [key, rows] of Object.entries(EX.examples)) {
    const [a, b] = key.split(' ');
    for (const r of rows) {
      checked++;
      // the pair need not be adjacent: in "a big red wooden barn" the pair
      // (big, wooden) is a real datum with "red" between them. What must hold
      // is that a comes before b inside the phrase the sentence contains.
      const words = r.phrase.split(' ');
      const ia = words.indexOf(a), ib = words.lastIndexOf(b);
      if (ia < 0 || ib < 0 || ia >= ib) bad++;
      const flat = r.sentence.toLowerCase().replace(/\s+/g, ' ');
      if (!flat.includes(r.phrase)) missing++;
    }
  }
  eq(bad, 0, `all ${checked} stored examples begin with the pair they are filed under`);
  eq(missing, 0, 'every stored sentence contains its phrase verbatim');
  // the ones that reach the page
  const quoted = [...PAGE.matchAll(/"sentence":"((?:[^"\\]|\\.)*)"/g)].length;
  ok(quoted >= 0, 'gallery sentences are embedded as data, not retyped');
  const gal = JSON.parse(PAGE.match(/<script id="gallery-data" type="application\/json">([\s\S]*?)<\/script>/)[1]
    .replace(/\\u003c/g, '<'));
  ok(gal.length > 0, 'the gallery is not empty', `${gal.length} entries`);
  let galBad = 0;
  for (const g of gal) {
    for (const r of g.rows) {
      if (!r.sentence.toLowerCase().replace(/\s+/g, ' ').includes(r.phrase)) galBad++;
      const stored = (EX.examples[g.key] || []).some((s) => s.sentence === r.sentence);
      if (!stored) galBad++;
    }
  }
  eq(galBad, 0, 'every sentence on the page is one the second corpus pass actually found');
}

// ── 8. the quotations ────────────────────────────────────────────────────────
section('8. the two long quotations, character for character');
{
  const flat = PAGE.replace(/&#39;/g, "'").replace(/&quot;/g, '"')
    .replace(/&amp;/g, '&').replace(/\s+/g, ' ');
  const onPage = [
    ['forsyth paragraph 1', QUOTES.forsyth.paragraphs[0]],
    ['forsyth paragraph 2', QUOTES.forsyth.paragraphs[1]],
    ['tolkien letter', QUOTES.tolkien.text],
    ['the tweet', QUOTES.tweet.text],
    ['Liberman', QUOTES.liberman.text],
    ['Horobin', QUOTES.horobin.text],
    ['Brown', QUOTES.brown.text],
    ['Westbury', QUOTES.westbury.text],
  ];
  for (const [name, text] of onPage) {
    ok(flat.includes(text.replace(/\s+/g, ' ').trim()),
      `the ${name} quotation appears on the page verbatim`, text.slice(0, 60) + '...');
  }
  for (const [name, q] of Object.entries(QUOTES)) {
    ok(typeof q.source === 'string' && q.source.length > 10,
      `the ${name} quotation carries a source line`);
  }
  ok(QUOTES.forsyth.paragraphs.join(' ') === QUOTES.forsyth.text,
    'the two Forsyth paragraphs are the whole passage, unedited');
  // the two things the page says the retelling gets wrong
  ok(!QUOTES.tolkien.text.includes('disheartened'),
    'Tolkien\'s own letter does not contain the word the retelling adds');
  ok(QUOTES.forsyth.text.includes('disheartened'),
    'and the retelling does contain it, which is the point being made');
  ok(QUOTES.tolkien.text.includes('I wondered why, and still do'),
    'the sentence the page closes on is really in the letter');
}

// ── 9. the shipped page holds together ───────────────────────────────────────
section('9. the page itself');
{
  ok(PAGE.trim().endsWith('</html>'), 'the closing tags are present');
  ok(PAGE.includes('</script></body>') || /<\/script>\s*<\/body>/.test(PAGE),
    'the inline script is closed before the body is');
  ok(!/\bNaN\b/.test(PAGE), 'no NaN reached the page');
  ok(!/undefined/.test(PAGE.split('<script')[0]), 'no undefined reached the rendered prose');
  ok(!/✎/.test(PAGE), 'no template placeholders left behind');
  // Duplicate ids silently break getElementById: the page shipped twice with a heading
  // and its own table sharing a name, and the second one never rendered. Never again.
  {
    const ids = [...PAGE.matchAll(/\sid="([^"]+)"/g)].map((m) => m[1]);
    const dupes = ids.filter((v2, i2) => ids.indexOf(v2) !== i2);
    eq(dupes.length, 0, 'no id appears twice in the page', dupes.join(', '));
  }
  ok(PAGE.includes('rel="canonical" href="https://artwaste.land/strata/a-green-great-dragon/"'),
    'the canonical link is right');
  ok(PAGE.includes('"@type":"Article"'), 'the structured data block is present');
  ok(/<a href="\/">home<\/a>/.test(PAGE), 'the way out is on the page');
  // em dashes are the lineage tell; the two blockquotes are exempt only if they need to be
  // Quoted sources keep their own dashes (editing them would make "verbatim" a lie), and
  // the shared "nearby layers" block is written by other pages, not by this one.
  const body = PAGE.replace(/<blockquote>[\s\S]*?<\/blockquote>/g, '')
    .replace(/<!--aw-nearby-->[\s\S]*?<!--\/aw-nearby-->/g, '');
  eq((body.match(/—/g) || []).length, 0, 'no em dashes in this page\'s own prose');
  // the oracle's table
  ok(PAIRS_JSON.words.length > 500, 'the oracle knows enough words', `${PAIRS_JSON.words.length}`);
  ok(PAIRS_JSON.pairs.length > 10000, 'and enough pairs', `${PAIRS_JSON.pairs.length}`);
  let mismatched = 0, sampled = 0;
  for (const [i, j, ab, ba] of PAIRS_JSON.pairs.slice(0, 3000)) {
    const a = PAIRS_JSON.words[i], b = PAIRS_JSON.words[j];
    const key = a < b ? `${a} ${b}` : `${b} ${a}`;
    const row = JUDGED.wiki[key];
    if (!row) continue;
    sampled++;
    const want = a < b ? [ab, ba] : [ba, ab];
    if (row[0] !== want[0] || row[1] !== want[1]) mismatched++;
  }
  eq(mismatched, 0, `the oracle's counts match the committed counts on all ${sampled} sampled pairs`);
  ok(existsSync('src/content/strata/a-green-great-dragon.md'),
    'the stratum has its frontmatter file, without which it is invisible to the site');
}

// ── done ─────────────────────────────────────────────────────────────────────
console.log(`\n${'═'.repeat(70)}`);
if (fail) {
  console.log(`FAILED ${fail} of ${pass + fail}`);
  for (const f of fails) console.log('  ✗ ' + f);
  process.exit(1);
}
console.log(`${pass}/${pass} checks pass.`);
