#!/usr/bin/env node
/*
  verify-kempe-and-the-eleven-years.mjs
  The offline gate for /strata/kempe-and-the-eleven-years/.

  HOW IT IS WIRED, AND WHAT THAT BUYS.

  The page's computation lives in one region of index.html marked ENGINE-BEGIN /
  ENGINE-END. This file slices that region out and runs it, so a figure printed on the
  page and a figure asserted here cannot come from two different pieces of code. That
  removes drift. It does NOT buy independence, and pretending otherwise is the standard
  way a green check panel ends up under a wrong page. So independence is bought
  separately, four ways, and every one of them is written here rather than in the engine:

    1. CLOSED FORMS. Ring colouring counts against the chromatic polynomial of a cycle,
       and orbit counts against Burnside's lemma summed over the cycle types of S4. Two
       formulas, no enumeration, nothing shared with the page.
    2. A CONCRETE ROUTE. D-reducibility of the four-neighbour configuration is an abstract
       claim about non-crossing partitions of a ring. This file also tests its CONSEQUENCE
       on real graphs: every proper four-colouring of every triangulation up to nine
       vertices, minus a degree-four vertex, searched over real Kempe interchanges in the
       real graph until a colour comes free. Different data structure, different algorithm,
       same claim.
    3. PUBLISHED ANCHORS nobody could have picked after seeing an answer: OEIS A000109 for
       the triangulation census, and the historical verdicts on which configurations are
       reducible (Kempe 1879, Heawood 1890, Birkhoff 1913).
    4. POISON CONTROLS. Data is doctored and the UNMODIFIED engine is re-run, and the
       engine is required to go red. Including a control on this file's own string
       matcher, because a matcher that cannot fail proves nothing about the prose.

  Run:  node research/kempe-and-the-eleven-years/verify-kempe-and-the-eleven-years.mjs
  Exit: 0 if every assertion holds, 1 otherwise. Zero dependencies.
*/
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, '..', '..');
const SLUG = 'kempe-and-the-eleven-years';
const PAGE = path.join(ROOT, 'public', 'strata', SLUG, 'index.html');
const MD   = path.join(ROOT, 'src', 'content', 'strata', `${SLUG}.md`);

let pass = 0, fail = 0, refusals = 0, refusalTotal = 0;
const failures = [];
function ok(cond, msg, detail) {
  if (cond) { pass++; console.log(`PASS ${String(pass + fail).padStart(3, '0')}  ${msg}${detail ? '  [' + detail + ']' : ''}`); }
  else { fail++; failures.push(msg); console.log(`FAIL ${String(pass + fail).padStart(3, '0')}  ${msg}${detail ? '  [' + detail + ']' : ''}`); }
  return cond;
}
function eq(a, b, msg) { return ok(a === b, msg, `got ${JSON.stringify(a)}, want ${JSON.stringify(b)}`); }
function section(t) { console.log(`\n=== ${t} ===`); }

/* ------------------------------------------------------------------ the engine */
const html = fs.readFileSync(PAGE, 'utf8');
const B = html.indexOf('/* ENGINE-BEGIN');
const E = html.indexOf('/* ENGINE-END */');
if (B < 0 || E < 0 || E < B) { console.error('FATAL: could not find the ENGINE markers in ' + PAGE); process.exit(1); }
const engineSrc = html.slice(B, E);
const K = new Function(engineSrc + '; return KEMPE;')();

section('the engine, sliced out of the page itself');
ok(engineSrc.length > 8000, 'the ENGINE region was found and is the real thing', engineSrc.length + ' bytes');
ok(typeof K.dReducible === 'function' && typeof K.kempeStep === 'function',
   'it exposes the functions the page calls');

/* ------------------------------------------------------ what the reader can see */
const visible = html
  .replace(/<script[\s\S]*?<\/script>/gi, ' ')
  .replace(/<style[\s\S]*?<\/style>/gi, ' ')
  .replace(/<!--[\s\S]*?-->/g, ' ')
  .replace(/<[^>]*>/g, ' ')
  .replace(/&middot;/g, '·').replace(/&ndash;/g, '-').replace(/&larr;/g, '<-').replace(/&nbsp;/g, ' ')
  .replace(/\s+/g, ' ');
// the head is not visible text but it IS the shareable surface, so it is matched too
const shareable = [
  /<meta name="description" content="([^"]*)"/, /<meta property="og:description" content="([^"]*)"/,
  /<meta name="twitter:description" content="([^"]*)"/, /<title>([^<]*)<\/title>/
].map(re => (re.exec(html) || [, ''])[1]).join(' ') + ' ' + (/"description":"((?:[^"\\]|\\.)*)"/.exec(html) || [, ''])[1];

function shows(re, msg, hay) {
  return ok(re.test(hay === undefined ? visible : hay), msg, String(re));
}

/* =========================================================== 1. the exhibit map */
section('the nine country map, and the 1879 step');
const MAP = K.MAP, EDGES = K.edgesOf(MAP.nb), S = K.kempeStep(MAP);

// an independent adjacency check: rebuild the neighbour lists from the edge list
{
  const back = Array.from({ length: MAP.n }, () => []);
  for (const [a, b] of EDGES) { back[a].push(b); back[b].push(a); }
  const same = back.every((l, i) => l.slice().sort((x, y) => x - y).join(',') === MAP.nb[i].slice().sort((x, y) => x - y).join(','));
  ok(same, 'the shipped neighbour lists and the edge list describe the same graph');
}
eq(MAP.n, 9, 'the map has 9 countries');
eq(EDGES.length, 21, 'and 21 borders');
eq(EDGES.length, 3 * MAP.n - 6, 'which is 3n-6, so it is a triangulation of the sphere');
{
  const deg = MAP.nb.map(l => l.length);
  eq(deg.reduce((a, b) => a + b, 0), 2 * EDGES.length, 'the degree sum is twice the border count');
  eq(deg[MAP.v], 5, 'country 0 has five neighbours, which is the case Kempe could not finish');
  ok(deg.every(d => d >= 3), 'no country has fewer than three neighbours', 'degrees ' + deg.join(','));
}
// planarity, certified rather than asserted
{
  const r = K.crossingReport(MAP.xy, EDGES);
  eq(r.tested, 132, 'the planarity certificate tests every disjoint border pair');
  eq(r.crossings.length, 0, 'and no two borders cross, so the map really is flat');
  // POISON: move one country across the map and the same unmodified checker must find crossings
  const doctored = MAP.xy.map((p, i) => (i === 7 ? [1.9, 1.4] : p));
  const r2 = K.crossingReport(doctored, EDGES);
  ok(r2.crossings.length > 0, 'POISON: drag country 7 across the drawing and the crossing check fires',
     r2.crossings.length + ' crossings found');
  ok(K.crossingReport(MAP.xy, EDGES).crossings.length === 0, 'and the undoctored drawing is unchanged afterwards');
}
// an independent properness scan, written here, not in the engine
function properHere(nb, col, skip) {
  const bad = [];
  for (let a = 0; a < nb.length; a++) for (const b of nb[a])
    if (a < b && a !== skip && b !== skip && col[a] === col[b]) bad.push([a, b]);
  return bad;
}
eq(properHere(MAP.nb, MAP.col, MAP.v).length, 0, 'the shipped colouring is proper (independent scan written in this file)');
{
  // POISON: recolour one country and the independent scan must go red
  const bent = MAP.col.slice(); bent[7] = MAP.col[1];
  ok(properHere(MAP.nb, bent, MAP.v).length > 0, 'POISON: give country 7 country 1\'s colour and the scan finds the clash',
     JSON.stringify(properHere(MAP.nb, bent, MAP.v)));
  eq(properHere(MAP.nb, MAP.col, MAP.v).length, 0, 'and the real colouring is still clean');
}

section("the step itself, recomputed here from the definitions");
// chains recomputed with code written in this file
function chainHere(nb, col, start, x, y, skip) {
  const seen = new Set([start]), st = [start];
  while (st.length) { const v = st.pop();
    for (const u of nb[v]) { if (u === skip) continue;
      if ((col[u] === x || col[u] === y) && !seen.has(u)) { seen.add(u); st.push(u); } } }
  return [...seen].sort((a, b) => a - b);
}
const [c1, c2, c3, c4] = S.cols;
ok(S.refused === null, "the fifth case is reached, not refused", 'ring ' + S.V.map(u => K.LETTER[MAP.col[u]]).join(''));
eq(S.V.length, 5, 'the ring is read as v1..v5');
eq(MAP.col[S.V[1]], c2, 'the doubled colour sits on v2');
eq(MAP.col[S.V[4]], c2, 'and on v5, which is what makes v1 the one in between');
{
  const h13 = chainHere(MAP.nb, MAP.col, S.V[0], c1, c3, MAP.v);
  const h14 = chainHere(MAP.nb, MAP.col, S.V[0], c1, c4, MAP.v);
  eq(h13.join(','), S.chain13.join(','), 'the first escape chain recomputed here matches the engine');
  eq(h14.join(','), S.chain14.join(','), 'and so does the second');
  ok(h13.includes(S.V[2]) && h14.includes(S.V[3]),
     'both single-chain escapes are blocked, which is what forces Kempe onto the double move',
     `A/D {${h13}} reaches v3, A/B {${h14}} reaches v4`);
}
{
  const hA = chainHere(MAP.nb, MAP.col, S.V[1], c2, c4, MAP.v);
  const hB = chainHere(MAP.nb, MAP.col, S.V[4], c2, c3, MAP.v);
  eq(hA.join(','), S.chainA.join(','), 'the C/B island at v2 matches');
  eq(hB.join(','), S.chainB.join(','), 'the C/D island at v5 matches');
  ok(!hA.includes(S.V[3]), 'the C/B island really cannot reach v4, exactly as Kempe proves');
  ok(!hB.includes(S.V[2]), 'the C/D island really cannot reach v3, exactly as Kempe proves');
  eq(hA.filter(x => hB.includes(x)).length, 0, 'and the two islands share no country, so this is not the naive story');
  // read as written, recomputed here
  const sim = MAP.col.slice();
  for (const u of hA) sim[u] = MAP.col[u] === c2 ? c4 : c2;
  for (const u of hB) sim[u] = MAP.col[u] === c2 ? c3 : c2;
  const broke = properHere(MAP.nb, sim, MAP.v);
  eq(broke.length, 1, 'READ AS WRITTEN: exactly one border ends up broken');
  eq(broke[0].join('-'), '4-7', 'and it is the border between countries 4 and 7');
  eq(broke.map(e => e.join('-')).join(','), S.simultaneous.broken.map(e => e.join('-')).join(','),
     'which is what the engine reports too');
  // one after the other, recomputed here
  const seq = MAP.col.slice();
  for (const u of hA) seq[u] = seq[u] === c2 ? c4 : c2;
  const hB2 = chainHere(MAP.nb, seq, S.V[4], c2, c3, MAP.v);
  eq(hB2.length, 4, 'ONE AFTER THE OTHER: the second island has grown from 2 countries to 4');
  ok(hB2.includes(S.V[2]), 'and it now reaches v3, which is exactly the safety Kempe had proved away');
  for (const u of hB2) seq[u] = seq[u] === c2 ? c3 : c2;
  eq(properHere(MAP.nb, seq, MAP.v).length, 0, 'this reading keeps the map proper');
  const ringNow = new Set(S.V.map(u => seq[u]));
  eq(ringNow.size, 4, 'and leaves all four colours on the ring, so nothing is freed');
  eq(S.V.map(u => K.LETTER[seq[u]]).join(''), S.V.map(u => K.LETTER[S.sequential.col[u]]).join(''),
     'the engine agrees on the resulting ring');
}

section('the refusal path, which is where a measuring page most often lies');
{
  const cases = [
    [{ n: 5, nb: [[1,2,3,4],[0,2,4],[0,1,3],[0,2,4],[0,1,3]], v: 0, ring: [1,2,3,4], col: [-1,0,1,2,3] },
     'a four-country ring'],
    [{ n: MAP.n, nb: MAP.nb, v: MAP.v, ring: MAP.ring, col: [-1,0,1,0,1,0,1,0,1] },
     'a ring wearing only two colours'],
    [{ n: MAP.n, nb: MAP.nb, v: MAP.v, ring: MAP.ring, col: [-1,0,1,2,0,1,2,0,1] },
     'a ring wearing three colours']
  ];
  for (const [m, what] of cases) {
    refusalTotal++;
    const r = K.kempeStep(m);
    if (r.refused !== null) refusals++;
    ok(r.refused !== null, `the step refuses ${what} instead of guessing`, r.refused || 'NO REFUSAL');
  }
  ok(K.kempeStep(MAP).refused === null, 'and it does not refuse the real case', 'refusals ' + refusals + '/' + refusalTotal);
}

section('more swapping: what it buys and what it does not');
const CL = K.interchangeClosure(MAP), REST = K.colouringsOfRest(MAP), WHOLE = K.colouringsOfWhole(MAP);
eq(CL.byDepth[1].freeing, 0, 'no single chain swap of any kind frees a colour on this map');
eq(CL.byDepth[1].states, 9, 'there are 9 distinct results at depth one');
eq(CL.firstEscape, 2, 'the first escape needs two swaps');
eq(CL.byDepth[2].freeing, 8, 'and there are 8 of them');
eq(CL.states, 192, 'the reachable set has 192 colourings');
eq(CL.freeing, 48, 'of which 48 free a colour');
eq(REST.total, 192, 'and the map minus country 0 has exactly 192 proper four-colourings, counted from scratch');
eq(CL.improper, 0, `every one of the ${CL.states * 24} swaps in that search left a proper colouring`);
eq(WHOLE.total, 48, 'the whole map is four colourable, in 48 ways: what broke is the argument, not the theorem');
{
  // independent route: count the colourings of the whole map by a different traversal order
  const order = [8,7,6,5,4,3,2,1,0], col = new Array(9).fill(-1);
  let n = 0;
  (function rec(i) {
    if (i === 9) { n++; return; }
    const u = order[i];
    for (let x = 0; x < 4; x++) {
      if (MAP.nb[u].some(w => col[w] === x)) continue;
      col[u] = x; rec(i + 1); col[u] = -1;
    }
  })(0);
  eq(n, WHOLE.total, 'recounted in the reverse vertex order, which shares no code with the engine');
}

/* ===================================================== 2. the exhaustive census */
section('every triangulated map up to 12 countries, against OEIS A000109');
const A000109 = { 4: 1, 5: 1, 6: 2, 7: 5, 8: 14, 9: 50, 10: 233, 11: 1249, 12: 7595 };
// The page carries its OWN copy of this sequence and prints it to the reader, so the two copies
// have to be compared or a bent digit in the engine ships green. Same for the historical verdicts.
{
  const mine = Object.keys(A000109).map(k => `${k}:${A000109[k]}`).join(' ');
  const theirs = Object.keys(A000109).map(k => `${k}:${K.A000109[k]}`).join(' ');
  eq(theirs, mine, "the engine's copy of A000109 is the sequence this file checks against");
  const RECORD = { ring3: true, ring4: true, ring5: false, diamond: true };
  for (const id of Object.keys(RECORD)) {
    eq(K.VERDICTS[id].reducible, RECORD[id],
       `the engine's stored verdict for ${id} is the one the record fixed`);
  }
  eq(K.CONFIGS.ring6.anchor, null, 'and the ring of six claims no published verdict, which is what the panel tells the reader');
}
const NMAX = Number(process.env.KEMPE_NMAX || 12);
const censusRows = [];
for (let n = 4; n <= NMAX; n++) {
  const w = K.triWalker(n);
  while (!w.done()) w.step(400);
  const agg = { n, tri: w.keep.length, reached: 0, brkSim: 0, brkSeq: 0, brkAny: 0, holds: 0, shared: 0, refusedTie: 0, withBreak: 0 };
  for (const t of w.keep) {
    const c = K.censusOne(t, n);
    for (const k of ['reached','brkSim','brkSeq','brkAny','holds','shared','refusedTie']) agg[k] += c[k];
    if (c.brkAny > 0) agg.withBreak++;
  }
  censusRows.push(agg);
  eq(agg.tri, A000109[n], `ANCHOR: the generator finds all ${A000109[n]} triangulations on ${n} nodes (A000109)`);
  agg.list = w.keep;
}
const cum = censusRows.reduce((a, r) => ({
  tri: a.tri + r.tri, wb: a.wb + r.withBreak, reached: a.reached + r.reached,
  brkSim: a.brkSim + r.brkSim, brkSeq: a.brkSeq + r.brkSeq, shared: a.shared + r.shared,
  refusedTie: a.refusedTie + r.refusedTie
}), { tri: 0, wb: 0, reached: 0, brkSim: 0, brkSeq: 0, shared: 0, refusedTie: 0 });
const row = n => censusRows.find(r => r.n === n);
ok(censusRows.filter(r => r.n < 9).every(r => r.withBreak === 0),
   'below 9 countries the step never breaks, on any map, under any colouring');
eq(row(9).withBreak, 2, 'at 9 countries it breaks, on 2 maps');
eq(row(9).tri, 50, 'out of the 50 that exist');
if (NMAX >= 12) {
  eq(cum.tri, 9150, 'the census covers 9150 maps in all');
  eq(cum.wb, 533, 'and 533 of them contain a colouring the step gets wrong');
  eq(cum.reached, 31910, '31910 colourings reach the double move');
  eq(cum.brkSim, 2131, 'read as written it breaks on 2131 of them');
  eq(cum.brkSeq, 1012, 'read one after the other it fails on 1012');
  eq(cum.shared, 866, 'and the two islands actually overlap in only 866');
  ok(censusRows.every(r => r.brkAny === r.brkSim),
     'measured, not proved: every sequential failure is also a written-as failure, at every size');
}
eq(cum.refusedTie, 0, `the census refusal path never fired: ${cum.refusedTie}/${cum.reached} malformed`);
// POISON on the canonical form the whole census depends on
{
  const nine = row(9).list[0], n = 9;
  const perm = [3,7,0,5,8,1,4,2,6];
  const relabel = nine.map(t => t.map(v => perm[v]));
  eq(K.canon(relabel, n), K.canon(nine, n), 'the canonical form is blind to relabelling, so the census cannot double count');
  const other = row(9).list[1];
  ok(K.canon(other, n) !== K.canon(nine, n), 'and it does tell two different triangulations apart');
  // POISON: plant a relabelled duplicate into a list and require the count check to go red
  const planted = row(9).list.concat([relabel]);
  const uniq = new Set(planted.map(t => K.canon(t, n)));
  ok(planted.length !== A000109[9] && uniq.size === A000109[9],
     'POISON: plant a relabelled duplicate and the raw list is wrong while the canonical count is not',
     `planted ${planted.length}, canonical ${uniq.size}`);
}

/* =============================================== 3. ring colourings, closed form */
section('ring colourings, against two formulas written in this file');
const Pcycle = (k, x) => Math.pow(x - 1, k) + Math.pow(-1, k) * (x - 1);   // chromatic polynomial of C_k
for (const k of [3, 4, 5, 6]) {
  eq(K.ringColourings(k).length, Pcycle(k, 4), `ring of ${k}: enumeration equals P(C_${k}, 4)`);
  eq(Pcycle(k, 4), Math.pow(3, k) + 3 * Math.pow(-1, k), `and P(C_${k}, 4) equals 3^k + 3(-1)^k`);
}
// Burnside over the cycle types of S4: 1 identity (4 fixed colours), 6 transpositions (2),
// 3 double transpositions (0), 8 three-cycles (1), 6 four-cycles (0).
const burnside = k => (Pcycle(k, 4) + 6 * Pcycle(k, 2) + 3 * Pcycle(k, 0) + 8 * Pcycle(k, 1) + 6 * Pcycle(k, 0)) / 24;
for (const k of [3, 4, 5, 6]) {
  eq(K.orbitCount(k), burnside(k), `ring of ${k}: enumerated orbits equal Burnside's count`);
}
eq([3,4,5,6].map(burnside).join(','), '1,4,10,31', 'and the orbit counts are the 1, 4, 10, 31 the literature quotes');

/* ===================================================== 4. the D-reducibility half */
section('D-reducibility, run to the end on five configurations');
const R = {};
for (const id of ['ring3', 'ring4', 'ring5', 'ring6', 'diamond']) R[id] = K.dReducible(K.CONFIGS[id].cfg);
eq(R.ring3.total, 24, 'ring of 3: 24 ring colourings');
eq(R.ring3.bad, 0, 'and none of them is hard, because a spare colour always exists');
eq(R.ring4.total, 84, 'ring of 4: 84 ring colourings');
eq(R.ring4.good, 60, 'the single country inside absorbs 60');
eq(R.ring4.stuck, 0, 'ANCHOR: and the sweep clears all 24 hard ones (Kempe 1879, undisputed since)');
eq(R.ring5.total, 240, 'ring of 5: 240 ring colourings');
eq(R.ring5.good, 120, 'the country inside absorbs 120');
eq(R.ring5.stuck, 120, 'ANCHOR: and the sweep clears NONE of the other 120 (the gap Heawood found in 1890)');
eq(R.ring5.sweeps, 1, 'the fixed point is reached on the first pass, so this is an answer and not a timeout');
eq(R.ring6.total, 732, 'ring of 6, one country inside: 732 ring colourings');
eq(R.ring6.stuck, 480, 'and 480 survive to the end');
eq(R.diamond.total, 732, "Birkhoff's diamond: the same 732 ring colourings as the ring of 6");
eq(R.diamond.good, 384, 'the four countries inside absorb 384 of them');
eq(R.diamond.bad, 348, 'leaving 348 hard');
eq(R.diamond.stuck, 0, 'ANCHOR: and the sweep clears every one (Birkhoff 1913, the first reducible configuration of ring size six)');
eq(R.diamond.hist.join(','), '348,252,192,96,24,0,0', 'by the staircase 348, 252, 192, 96, 24, 0');
ok(R.diamond.reducible !== R.ring6.reducible && R.diamond.total === R.ring6.total,
   'THE DISCRIMINATING PAIR: same ring size, same ring colourings, same code, opposite verdict');
{
  // ANCHOR, from primary data neither this page nor this file chose after the fact.
  // Robertson, Sanders, Seymour and Thomas publish the 633 configurations of their 1997 proof
  // as unavoidable.conf. Its FIRST entry is the Birkhoff diamond, filed as 0.7322, and its
  // header line reads "10   6      16       0": n = 10 vertices of the free completion,
  // r = 6 ring size, a = |C| = 16, b = |C'| = 0, where C is the set of ring colouring CLASSES
  // the configuration absorbs. So the page's 384 absorbed colourings must be 16 classes.
  // Counted here with an orbit counter written in this file, not the engine's.
  const perms = [];
  (function pr(a, rest) { if (!rest.length) { perms.push(a); return; }
    rest.forEach((x, i) => pr(a.concat(x), rest.filter((_, j) => j !== i))); })([], [0, 1, 2, 3]);
  const good = K.ringColourings(6).filter(c => K.extendsTo(K.CONFIGS.diamond.cfg, c));
  const seen = new Set(); let classes = 0;
  for (const c of good) {
    if (seen.has(c.join(''))) continue;
    classes++;
    for (const q of perms) seen.add(c.map(x => q[x]).join(''));
  }
  eq(good.length, 384, 'the diamond absorbs 384 ring colourings');
  eq(classes, 16, "ANCHOR: which is 16 classes under the 24 renamings, the a = 16 filed against configuration 0.7322 in RSST's unavoidable.conf");
  eq(K.absorbedClasses(K.CONFIGS.diamond.cfg), classes, "and the engine's own class count agrees with the one written here");
  // the same counter on a configuration whose published a is NOT 16, so the count is not a constant
  ok(K.absorbedClasses(K.CONFIGS.ring6.cfg) !== 16,
     'and the counter is not simply returning 16: the bare ring of six gives a different class count',
     `ring6 absorbs ${R.ring6.good} colourings in ${K.absorbedClasses(K.CONFIGS.ring6.cfg)} classes`);
}
for (const id of ['ring4', 'ring5', 'ring6', 'diamond']) {
  eq(R[id].improperFlips, 0, `${id}: every colour swap the sweep tried landed on a proper ring colouring`);
}
// the good set, by a route with no recursion and no pruning
for (const id of ['ring4', 'ring5', 'ring6', 'diamond']) {
  const bf = Object.keys(K.goodSetByBruteForce(K.CONFIGS[id].cfg)).length;
  eq(bf, R[id].good, `${id}: the absorbed set matches a brute force over all 4^(k+m) assignments`);
}
// the wheels' good sets also have a closed form: ring colourings using at most 3 of the 4 colours
for (const k of [3, 4, 5, 6]) {
  const exactly4 = Pcycle(k, 4) - 4 * Pcycle(k, 3) + 6 * Pcycle(k, 2) - 4 * Pcycle(k, 1);
  eq(R['ring' + k].good, Pcycle(k, 4) - exactly4,
     `ring of ${k}: the absorbed count equals the closed form for colourings using at most three colours`);
}
// the configuration schematics are drawn flat too
{
  let pairs = 0, bad = 0;
  for (const id of ['ring3', 'ring4', 'ring5', 'ring6', 'diamond']) {
    const rep = K.crossingReport(K.CONFIGS[id].xy, K.configEdges(K.CONFIGS[id].cfg));
    pairs += rep.tested; bad += rep.crossings.length;
  }
  eq(pairs, 206, 'the five configuration schematics test 206 disjoint edge pairs between them');
  eq(bad, 0, 'and none of them is drawn with a crossing');
}

section('POISON CONTROLS: doctor the data, re-run the unmodified checker, require red');
{
  // 1. take the chord out of the diamond and it stops being the diamond
  const flat = { k: 6, m: 4, edges: K.CONFIGS.diamond.cfg.edges.filter(e => !(e[0] === 7 && e[1] === 9)) };
  const rf = K.dReducible(flat);
  ok(rf.good !== R.diamond.good,
     'POISON: remove the chord across the middle and the absorbed set changes, so the interior is doing the work',
     `${rf.good} absorbed without the chord vs ${R.diamond.good} with it`);
  eq(K.dReducible(K.CONFIGS.diamond.cfg).good, 384, 'and the real diamond is unchanged afterwards');
}
{
  // 2. give the diamond's ring one country too few inside
  const thin = { k: 6, m: 1, edges: [[0, 6], [1, 6], [2, 6], [3, 6], [4, 6], [5, 6]] };
  const rt = K.dReducible(thin);
  ok(!rt.reducible, 'POISON: the same ring with a single country inside is NOT reducible, so the verdict tracks the patch',
     `${rt.stuck} stuck`);
}
{
  // 3. the two deliberate relaxations, each refuted by a different piece of the record
  const relA = K.dReducible(K.CONFIGS.ring4.cfg, 'independent-pairs');
  ok(relA.reducible === false,
     'CONTROL: drop the non-crossing rule between disjoint colour pairs and the four-neighbour case is wrongly rejected',
     `relaxed: ${relA.stuck} stuck, contradicting Kempe 1879`);
  const relB = K.dReducible(K.CONFIGS.ring5.cfg, 'singletons');
  ok(relB.reducible === true,
     'CONTROL: force every chain to be its own island and the five-neighbour case is wrongly accepted',
     'relaxed: reducible, which would make the four colour theorem a paragraph');
  ok(K.dReducible(K.CONFIGS.ring4.cfg).reducible === true && K.dReducible(K.CONFIGS.ring5.cfg).reducible === false,
     'and with the rules restored both verdicts come back correct');
}

/* ========== 5. AN INDEPENDENT ROUTE: the same claim, on real graphs ========== */
/*
  D-reducibility of the four-neighbour configuration is an abstract statement about
  non-crossing partitions of a six element circle. Its CONSEQUENCE is concrete: in any
  real map, delete a country with four neighbours, four-colour the rest however you like,
  and some sequence of real Kempe interchanges in that real graph must free a colour.
  This block tests the consequence, with its own graph code, on every triangulation up to
  nine countries. It shares nothing with the sweep above except the answer.
*/
section('an independent route: the abstract verdict tested on real graphs');
{
  function neighbours(tris, n) {
    const adj = Array.from({ length: n }, () => new Set());
    for (const t of tris) for (let j = 0; j < 3; j++) { adj[t[j]].add(t[(j + 1) % 3]); adj[t[(j + 1) % 3]].add(t[j]); }
    return adj.map(s => [...s]);
  }
  function freesAColour(nb, col, v) {
    return new Set(nb[v].map(u => col[u])).size < 4;
  }
  function escapes(nb, col0, v, cap) {
    // breadth-first over every real Kempe interchange in the real graph
    const seen = new Set([col0.join('')]); let fr = [col0], depth = 0;
    while (fr.length && seen.size < cap) {
      for (const c of fr) if (freesAColour(nb, c, v)) return { ok: true, depth };
      const next = [];
      for (const c of fr) for (let a = 0; a < nb.length; a++) {
        if (a === v) continue;
        for (let x = 0; x < 4; x++) {
          if (x === c[a]) continue;
          const seenC = new Set([a]), st = [a];
          while (st.length) { const w = st.pop();
            for (const u of nb[w]) { if (u === v) continue;
              if ((c[u] === c[a] || c[u] === x) && !seenC.has(u)) { seenC.add(u); st.push(u); } } }
          const t = c.slice(); for (const u of seenC) t[u] = t[u] === c[a] ? x : c[a];
          const key = t.join('');
          if (!seen.has(key)) { seen.add(key); next.push(t); }
        }
      }
      fr = next; depth++;
    }
    return { ok: false, depth };
  }
  const tally = { deg4: 0, deg4hard: 0, deg4fail: 0, deg5: 0, deg5hard: 0, deg5fail: 0, maxDepth: 0 };
  const upto = Math.min(NMAX, 9);
  for (const rr of censusRows) {
    if (rr.n > upto) continue;
    for (const tris of rr.list) {
      const nb = neighbours(tris, rr.n);
      for (let v = 0; v < rr.n; v++) {
        const d = nb[v].length;
        if (d !== 4 && d !== 5) continue;
        const others = []; for (let i = 0; i < rr.n; i++) if (i !== v) others.push(i);
        const col = new Array(rr.n).fill(-1);
        (function rec(i, mx) {
          if (i === others.length) {
            const key = d === 4 ? 'deg4' : 'deg5';
            tally[key]++;
            if (new Set(nb[v].map(u => col[u])).size < 4) return;      // a colour is already free
            tally[key + 'hard']++;
            const r = escapes(nb, col.slice(), v, 20000);
            if (!r.ok) tally[key + 'fail']++;
            if (r.ok && r.depth > tally.maxDepth) tally.maxDepth = r.depth;
            return;
          }
          const u = others[i], lim = Math.min(3, mx + 1);
          for (let x = 0; x <= lim; x++) {
            if (nb[u].some(w => w !== v && col[w] === x)) continue;
            col[u] = x; rec(i + 1, Math.max(mx, x)); col[u] = -1;
          }
        })(0, -1);
      }
    }
  }
  ok(tally.deg4hard > 0, 'the concrete route actually met hard four-neighbour cases',
     `${tally.deg4hard} of ${tally.deg4} colourings needed interchanges`);
  eq(tally.deg4fail, 0,
     'INDEPENDENT ROUTE: every hard four-neighbour case on every map up to 9 countries escapes, as D-reducibility predicts');
  eq(tally.deg5fail, 0,
     'and so does every hard five-neighbour case on those maps, which is the point worth being careful about: a particular outside can be lucky where no argument covering all outsides can be');
  ok(tally.maxDepth >= 2, 'and some of them needed more than one interchange to get out',
     `deepest escape found: ${tally.maxDepth} interchanges; hard five-neighbour cases: ${tally.deg5hard}`);
}

/* ============ 6. THE SHAREABLE SURFACE: what the reader actually sees =========== */
/*
  Verifiers assert about values; nothing asserts about the prose. So every figure a
  reader can see in static text below is required to equal the value computed above.
  The final block in this section is the control on this matcher: it corrupts the page
  text and requires the matcher to go red, because a matcher that cannot fail is
  decoration.
*/
section('the rendered page: every static figure matched against what was computed');
const FIGS = [];
function fig(re, msg, hay) { FIGS.push([re, msg]); return shows(re, msg, hay); }

fig(new RegExp(`This one has\\s+${MAP.n} countries\\s+and\\s+${EDGES.length} borders`),
    'the map size in the prose matches the graph');
fig(new RegExp(`testing all\\s+${K.crossingReport(MAP.xy, EDGES).tested}\\s+pairs of\\s+borders`),
    'the number of border pairs tested for crossings matches');
fig(new RegExp(`${S.simultaneous.broken.length} broken border\\s*</?strong>?\\s*out of ${EDGES.length}|${S.simultaneous.broken.length} broken border\\s+out of ${EDGES.length}`),
    'the broken border count in the prose matches the computed one');
fig(new RegExp(`grown to\\s+${S.sequential.chainB2.length} countries`),
    'the grown island size matches');
fig(new RegExp(`Countries\\s+${S.simultaneous.broken[0][0]} and ${S.simultaneous.broken[0][1]} then both end up`),
    'the pair of countries named in the prose is the pair the step actually breaks');
{
  const coloured = MAP.col.filter(x => x >= 0).length;      // 8 countries carry a colour
  const singleSwaps = coloured * 3;                          // 3 other colours each
  eq(singleSwaps, 24, 'there are 8 coloured countries and 3 other colours each, so 24 single swaps');
  fig(new RegExp(`there are\\s+${singleSwaps}\\s+single chain swaps available \\(${coloured} coloured countries,\\s+3 other colours each\\)`),
      'the count of single swaps in the prose is 8 countries times 3 colours, both computed');
}
fig(new RegExp(`collapsing to\\s+${CL.byDepth[1].states}\\s+distinct results`), 'the distinct depth-one results match');
fig(new RegExp(`free a colour for country 0 is\\s+${CL.byDepth[1].freeing}\\b`), 'and none of them frees a colour');
fig(new RegExp(`finds\\s+${CL.byDepth[2].freeing}\\s+colourings at depth two`), 'the depth-two escape count matches');
fig(new RegExp(`${CL.states}\\s+colourings are reachable`), 'the size of the reachable set matches');
fig(new RegExp(`of which\\s+${CL.freeing}\\s+free a colour`), 'and the number that free a colour matches');
fig(new RegExp(`map minus country 0 has exactly\\s+${REST.total}\\s+proper four-colourings`), 'the count of colourings of the rest matches');
fig(new RegExp(`it has\\s+${WHOLE.total}\\s+proper\\s+four-colourings`), 'the count of colourings of the whole map matches');
{
  // the page now PRINTS a four-colouring of all nine countries, so the witness has to be one
  const w = WHOLE.witness;
  ok(Array.isArray(w) && w.length === MAP.n && w.every(x => x >= 0 && x < 4),
     'the enumeration hands back a witness colouring with every country coloured', JSON.stringify(w));
  eq(properHere(MAP.nb, w, -1).length, 0,
     'and the witness is proper across all 21 borders, by the independent scan written in this file');
  ok(new Set(MAP.ring.map(u => MAP.col[u])).size === 4,
     'while the colouring the instrument displays is NOT one of the 48: its ring wears all four colours',
     'ring wears ' + new Set(MAP.ring.map(u => MAP.col[u])).size + ' colours');
  fig(/the first one the enumeration finds is printed under the table above/,
      'and the prose points at the witness rather than claiming a display that was never made');
  fig(/is\s+<em>not<\/em>\s+one of those 48|is not one of those 48/,
      'and the prose says outright that the displayed colouring is not one of the 48', html);
}
fig(new RegExp(`they fall\\s+into\\s+${K.absorbedClasses(K.CONFIGS.diamond.cfg)}\\s+classes under the 24 renamings`),
    "the diamond's class count in the prose matches the computed one");
fig(/in its published set of 633 configurations,\s+<strong>249<\/strong> are settled by D-reducibility alone and the other <strong>384<\/strong>\s+need a contraction too/,
    'the page says how much of the 1997 proof D-reducibility actually does, and it is 249 of 633 (counted from the b field of RSST unavoidable.conf: 249 entries carry b = 0, 384 carry b > 0)', html);
fig(/with the header <span class="mono">10 6 16 0<\/span>/,
    "and the RSST header line the anchor is read from is quoted verbatim", html);
fig(/the simultaneous execution of two colour interchanges, each of\s+which is admissible on its own, need not always be possible/,
    'the 1890 notice of the flaw is quoted in the form this page argues for');
fig(/it clears a ring colouring only if an escape exists\s+under <em>every<\/em> arrangement/,
    'the sweep rule is stated in the direction the code implements', html);
fig(new RegExp(`1, 1, 2, 5, 14, 50, 233, 1249, 7595`), 'the A000109 values are printed in full');
fig(new RegExp(`Below 9 countries the step never breaks\\. At\\s+9\\s+it does, on\\s+${row(9).withBreak}\\s+of the\\s+${row(9).tri}\\s+maps`),
    'the first-break claim matches the census');
if (NMAX >= 12) {
  fig(new RegExp(`Across all\\s+${cum.tri}\\s+maps up to 12 countries,\\s+${cum.wb}\\s+contain a colouring`),
      'the total map count and break count match');
  fig(new RegExp(`breaks on\\s+${cum.brkSim}\\s+of the\\s+${cum.reached}\\s+colourings that reach it`),
      'the written-as break count matches');
  fig(new RegExp(`it fails on\\s+${cum.brkSeq}\\b`), 'the sequential failure count matches');
  fig(new RegExp(`overlap in only\\s+${cum.shared}\\s+cases`), 'the overlap count matches');
}
fig(new RegExp(`ring can wear\\s+${R.ring5.total}\\s+colourings, of which\\s+${R.ring5.good}`), 'the ring-of-5 counts match');
fig(new RegExp(`The other\\s+${R.ring5.bad}\\s+are the hard ones`), 'and its hard count matches');
fig(new RegExp(`Its ring wears\\s+${R.diamond.total}\\s+colourings, the patch absorbs\\s+${R.diamond.good}\\s+of them, and\\s+${R.diamond.bad}\\s+are hard`),
    'the diamond counts match');
fig(new RegExp(`${R.diamond.hist.slice(0, -1).join(', ')}`), 'the diamond staircase in the prose matches the computed one');
fig(new RegExp(`same\\s+${R.ring6.total}\\s+colourings`), 'the discriminating pair shares its ring colouring count');
fig(new RegExp(`${R.ring6.bad}\\s+hard colourings,\\s+${R.ring6.stuck}\\s+still standing at the end`), 'the ring-of-6 verdict counts match');
fig(new RegExp(`in ${WHOLE.total} ways`, ''), 'the meta description repeats the four-colouring count', shareable);

/* ---------------------------------------------------------------------------------
   6b. THE FIGURES NOTHING ABOVE WAS LOOKING AT.

   A mutation test corrupted three figures in the rendered HTML (22.0562, 0.7322 and
   000109) and this gate stayed green, because every one of them is a STATIC DISPLAYED
   CLAIM: no script on the page rewrites that text, so a reader really would have read
   the wrong number under a passing check panel. All three are IDENTIFIERS rather than
   measurements, which does not make them safe: an identifier that drifts is a broken
   citation, and one of them (0.7322) is the label on the primary-source anchor this
   whole page leans on. They are asserted below as identifiers, held in one named
   constant each so the prose and this gate cannot disagree, and wherever the identifier
   travels with a quantity that quantity is tied to what the engine computed.

   The rest of this block sweeps the page for every other figure a reader can see that
   no assertion above touched, and closes with a coverage net: every number of three or
   more digits anywhere in the rendered text has to be accounted for, so the next figure
   added to the prose cannot slip in unasserted.
   -------------------------------------------------------------------------------- */
section('the figures a mutation test walked through: identifiers, and everything else static');

const WORDNUM = ['zero','one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve'];

/* ---- IDENTIFIER 1: the OEIS A-number the whole census is anchored to ---- */
// Not a measurement. It is the accession number of a published sequence, and the page
// prints it four times and links it once. If a digit bends, every count on the page is
// still right and the citation is silently pointing at a different sequence.
const OEIS_CENSUS = 'A000109';    // simplicial polyhedra (planar triangulations) on n nodes
fig(new RegExp(`\\(OEIS ${OEIS_CENSUS}\\)`),
    `IDENTIFIER: the census names ${OEIS_CENSUS} where it states the published enumeration`);
fig(new RegExp(`its own count against\\s+${OEIS_CENSUS}\\s+at every size`),
    `IDENTIFIER: and again where it says the panel checks itself against ${OEIS_CENSUS}`);
fig(new RegExp(`countries maps ${OEIS_CENSUS} reach the step`),
    `IDENTIFIER: and the census table's third column is headed ${OEIS_CENSUS}`);
fig(new RegExp(`OEIS ${OEIS_CENSUS}\\s*, simplicial polyhedra with n nodes`),
    `IDENTIFIER: and the footer cites ${OEIS_CENSUS} with the sequence's own description`);
{
  const anums = [...visible.matchAll(/A\d{6}/g)].map(m => m[0]);
  ok(anums.length === 4 && anums.every(a => a === OEIS_CENSUS),
     `IDENTIFIER: every A-number the reader can see is ${OEIS_CENSUS}, with no odd one out`,
     anums.join(' '));
  ok(html.includes(`https://oeis.org/${OEIS_CENSUS}`),
     'IDENTIFIER: and the link the reader would follow resolves to that same A-number');
  ok(new RegExp(`var\\s+${OEIS_CENSUS}\\s*=`).test(engineSrc),
     'IDENTIFIER: and the engine names its own copy of the table after the same A-number, so prose and code cannot drift apart');
}
// the sequence PRINTED next to that A-number, tied to the counts this run generated
if (NMAX >= 12) {
  const printed = censusRows.map(r => r.tri).join(', ');
  const lo = censusRows[0].n, hi = censusRows[censusRows.length - 1].n;
  fig(new RegExp(`polyhedra,\\s+${printed}\\s+for ${lo} to ${hi} nodes\\s+\\(OEIS ${OEIS_CENSUS}\\)`),
      'the sequence printed beside the A-number is the one the generator produced this run, over the range it covered');
}

/* ---- IDENTIFIER 2: the Jahrbuch record for Heawood 1890 ---- */
// 22.0562.02 is a JFM accession number, not a quantity. The sentence the page quotes as
// its statement of the flaw comes from that record, so a bent digit here is a quotation
// with no traceable source.
const JFM_HEAWOOD = '22.0562.02';   // JFM volume 22 (the volume for 1890), review 0562.02
const HEAWOOD_YEAR = 1890, KEMPE_YEAR = 1879;
fig(new RegExp(`the contemporaneous notice is JFM ${JFM_HEAWOOD.replace(/\./g, '\\.')}\\s*,`),
    `IDENTIFIER: the footer cites the Jahrbuch record as JFM ${JFM_HEAWOOD}`);
{
  const jfms = [...visible.matchAll(/JFM \d+\.\d+\.\d+/g)].map(m => m[0]);
  ok(jfms.length === 1 && jfms[0] === `JFM ${JFM_HEAWOOD}`,
     'IDENTIFIER: and it is the only JFM number on the page, so there is nothing to confuse it with', jfms.join(' '));
  const vol = Number(JFM_HEAWOOD.split('.')[0]);
  ok(new RegExp(`Jahrbuch über die Fortschritte der Mathematik</em> for ${HEAWOOD_YEAR}`).test(html),
     `and the body dates that Jahrbuch volume to ${HEAWOOD_YEAR}, which is the year JFM volume ${vol} covers`);
  ok(new RegExp(`Quarterly Journal of Pure and Applied Mathematics 24 \\(${HEAWOOD_YEAR}\\)`).test(visible),
     'and the footer gives the reviewed paper the same year, so the record and the paper agree');
}
// the eleven years of the title are the gap between the two dated events, not a decoration
eq(HEAWOOD_YEAR - KEMPE_YEAR, 11, 'the two dated events are eleven years apart');
fig(new RegExp(`Held for ${WORDNUM[HEAWOOD_YEAR - KEMPE_YEAR].replace(/^./, c => c.toUpperCase())} Years`),
    'and the headline names that gap');
fig(new RegExp(`lose ${WORDNUM[HEAWOOD_YEAR - KEMPE_YEAR]} years to a single step`), 'and so does the dek on the page');
fig(new RegExp(`In ${KEMPE_YEAR} Alfred\\s+Kempe published`), 'the dek dates the proof to the year the footer cites');
fig(new RegExp(`until ${HEAWOOD_YEAR}, when Percy Heawood`), 'and the break to the year the footer cites for Heawood');

/* ---- IDENTIFIER 3: the RSST configuration number, with a header that IS computed ---- */
// 0.7322 is the diamond's entry name in Robertson, Sanders, Seymour and Thomas's
// unavoidable.conf. It is the label on the one primary-source anchor this page has for
// its class count, so it is asserted as an identifier. The header line quoted beside it
// is a different matter: all four of its fields are recomputed here and matched as
// numbers, not typed.
const RSST_CONF_DIAMOND = '0.7322';
{
  const D = K.CONFIGS.diamond.cfg;
  const a = K.absorbedClasses(D);
  // n = vertices of the free completion = ring + interior; r = ring size; a = |C|, the
  // absorbed ring colouring classes; b = |C'|, the contraction set, which is empty exactly
  // when the configuration is D-reducible, and the sweep is what decides that here.
  const header = [D.k + D.m, D.k, a, R.diamond.reducible ? 0 : 1].join(' ');
  eq(header, '10 6 16 0', 'the RSST header line, rebuilt field by field from the engine');
  fig(new RegExp(`filed as\\s+${RSST_CONF_DIAMOND.replace('.', '\\.')}\\s+with the header ${header}\\s*:`),
      `IDENTIFIER: the page files the diamond as ${RSST_CONF_DIAMOND}, beside a header rebuilt from the computed ring size, interior size, class count and verdict`);
  fig(new RegExp(`${header}\\s*:\\s*${WORDNUM[D.k + D.m]} countries, ring size ${WORDNUM[D.k]}, and a , the number of ring colouring\\s+classes the patch absorbs, equal to ${a}\\b`),
      'and the sentence that spells the header out in words spells out the same four computed numbers');
  fig(new RegExp(`unavoidable.conf supplies the a = ${a} checked against the diamond above`),
      'and the footer repeats the same computed class count');
  fig(new RegExp(`Those ${R.diamond.good} absorbed colourings are the same colouring\\s+${a} times over`),
      'and the absorbed count and the class count in that paragraph are both computed');
  {
    const renamings = [1, 2, 3, 4].reduce((x, y) => x * y, 1);   // |S4|
    eq(renamings, 24, 'there are 4! = 24 renamings of the four colours');
    fig(new RegExp(`classes under the ${renamings} renamings`), 'and the page says 24 renamings, which is 4 factorial');
  }
  fig(new RegExp(`Now run Birkhoff's diamond, ${WORDNUM[D.m]} countries inside a ring of ${WORDNUM[D.k]},`),
      "the diamond's size spelled out in the prose is the configuration that shipped");
  const confs = [...visible.matchAll(/\b\d\.\d{4}\b/g)].map(m => m[0]);
  ok(confs.length === 1 && confs[0] === RSST_CONF_DIAMOND,
     'IDENTIFIER: and it is the only RSST configuration number on the page', confs.join(' '));
}

/* ---- the citation figures: not computed here, so held in one table with provenance ---- */
const RSST_TOTAL = 633;   // RSST unavoidable.conf: 633 entries
const RSST_DRED  = 249;   // of which 249 carry b = 0, so D-reducibility alone settles them
const AH_YEAR = 1976, RSST_YEAR = 1997;
eq(RSST_TOTAL - RSST_DRED, 384, 'and the rest of the RSST set, the ones that need a contraction, is 633 - 249');
fig(new RegExp(`the diamond is the first of their ${RSST_TOTAL} configurations`),
    'the diamond is filed as the first of the RSST set, and the set size matches the one used above');
fig(new RegExp(`rebuilt the whole thing in ${RSST_YEAR} with ${RSST_TOTAL} configurations`),
    'the history paragraph gives the same set size');
fig(new RegExp(`the ${RSST_TOTAL} of the ${RSST_YEAR} proof, the ${RSST_DRED} of them that are D-reducible`),
    'and so does the paragraph that names these as citations rather than measurements');
{
  // word boundaries, or the 1249 in the A000109 sequence counts as an occurrence of 249
  const sixes = (visible.match(new RegExp(`\\b${RSST_TOTAL}\\b`, 'g')) || []).length;
  const dreds = (visible.match(new RegExp(`\\b${RSST_DRED}\\b`, 'g')) || []).length;
  ok(sixes === 4 && dreds === 2,
     'every occurrence of the RSST set size and its D-reducible count is one of the ones matched above',
     `${sixes} occurrences of ${RSST_TOTAL}, ${dreds} of ${RSST_DRED}`);
}
fig(new RegExp(`settled it in\\s+${AH_YEAR} by running Kempe's argument`), 'the dismissal dates Appel and Haken to 1976');
fig(new RegExp(`the same volume of the Illinois Journal of Mathematics in 1977`),
    'while the papers are dated 1977, which is the year the footer cites, and the page keeps the two apart');
ok(RSST_YEAR - AH_YEAR === 21 && /It was independently reproved twenty years later/.test(visible),
   'and "twenty years later" is the round form of the 21 years between 1976 and 1997, which is a rounding and not a miscount');

/* ---- the step instrument: the letters and the chains the prose names ---- */
{
  const ring = S.V.map(u => K.LETTER[MAP.col[u]]).join(' ');
  fig(new RegExp(`On this map that is colours\\s+${ring}\\b`),
      'the ring colours the prose reads off are the colours the shipped map actually wears, in the v1 order the engine chose');
  const AD = `${K.LETTER[c1]}/${K.LETTER[c3]}`, AB = `${K.LETTER[c1]}/${K.LETTER[c4]}`;
  const CB = `${K.LETTER[c2]}/${K.LETTER[c4]}`, CD = `${K.LETTER[c2]}/${K.LETTER[c3]}`;
  fig(new RegExp(`the ${AD} chain from v1\\s+reaches v3\\s+-&gt;\\s+${S.reaches3 ? 'blocked' : 'free'}`),
      'the first line of the keyline names the computed colour pair and the computed verdict');
  fig(new RegExp(`the ${AB} chain from v1\\s+reaches v4\\s+-&gt;\\s+${S.reaches4 ? 'blocked' : 'free'}`),
      'and so does the second');
  fig(new RegExp(`The ${CB} chain at v2`), 'the first of the two simultaneous chains is named by its computed colour pair');
  fig(new RegExp(`the ${CD} chain at v5`), 'and so is the second');
  const brk = S.simultaneous.broken[0];
  fig(new RegExp(`then both end up ${K.LETTER[S.simultaneous.col[brk[0]]]}, and they share a`),
      'and the colour the two countries collide on is the colour the simultaneous swap actually leaves them wearing');
  ok(S.simultaneous.col[brk[0]] === S.simultaneous.col[brk[1]],
     'which is a collision because the swap really does leave both of them the same colour');
}

/* ---- the census panel: the depths the prose promises are the depths the code runs ---- */
{
  const autoTo = Number((/censusTo\((\d+)\);\s*\},\s*60\)/.exec(html) || [, ''])[1]);
  eq(autoTo, 10, 'the page starts its own census at 10 countries, read out of the page\'s own code');
  fig(new RegExp(`The table runs itself out to ${autoTo} countries`),
      'and the prose promises the reader exactly that depth');
  fig(new RegExp(`The census to ${autoTo}\\s+countries runs on its own`),
      'and so does the status line under the table');
  const b11 = Number((/id="btn-c11"[^>]*>Extend to (\d+) countries</.exec(html) || [, ''])[1]);
  const b12 = Number((/id="btn-c12"[^>]*>Extend to (\d+) countries/.exec(html) || [, ''])[1]);
  eq(b11, 11, 'the first extend button is labelled with the size it asks for');
  eq(b12, 12, 'and so is the second');
  ok(new RegExp(`btn-c11'\\)\\.addEventListener\\('click', function \\(\\) \\{ censusTo\\(${b11}\\); \\}\\)`).test(html)
     && new RegExp(`btn-c12'\\)\\.addEventListener\\('click', function \\(\\) \\{ censusTo\\(${b12}\\); \\}\\)`).test(html),
     'and each button is wired to the census depth its own label names');
  if (NMAX >= 12) {
    fig(new RegExp(`Extend to ${b12} countries \\(${row(b12).tri} more maps\\)`),
        'the count of extra maps on the second button is the number of triangulations at that size, computed');
    fig(new RegExp(`measured over all ${cum.tri} maps every one of\\s+those ${cum.brkSeq} is also in the ${cum.brkSim}`),
        'the second statement of the map, sequential and simultaneous totals matches the census too');
  }
}

/* ---- the reducibility panel: the figures beside it, and the ones it overwrites ---- */
{
  const stair = R.diamond.hist.slice(0, R.diamond.hist.indexOf(0) + 1).join(', ');
  fig(new RegExp(`this is the staircase:\\s+${stair}\\b`),
      'the staircase in the prose is the full computed one, including the zero it lands on');
  fig(new RegExp(`The sweep clears them in ${WORDNUM[R.diamond.sweeps - 1]} passes`),
      'and the number of passes, spelled out, is the number of eliminating passes the sweep took');
  ok(R.ring5.stuck === R.ring5.bad && /the sweep removes\s+none\s+of them/.test(visible),
     'the ring of five removes none of its hard colourings, and the prose says none because none is what it removed');
  ok(R.ring5.sweeps === 1 && /Zero, on the first pass, and the fixed point is reached immediately/.test(visible),
     'and the fixed point really is reached on the first pass, which is what the paragraph claims');
  for (const id of ['ring3', 'ring4', 'ring5', 'ring6']) {
    fig(new RegExp(`data-cfg="${id}"[^>]*>${K.CONFIGS[id].cfg.k} neighbours<`),
        `the ${id} button is labelled with the ring size of the configuration it selects`, html);
  }
  // RULE: the three readouts in this panel and the panel subtitle are placeholders the
  // page rewrites on load, so their static text is not asserted. What is asserted is the
  // value the script writes into them.
  ok(/\$\('dr-total'\)\.textContent = done \? done\.total : 'not run'/.test(html)
     && /\$\('cfg-sub'\)\.textContent = 'ring ' \+ C\.cfg\.k \+ ' · ' \+ C\.cfg\.m \+ ' inside'/.test(html),
     'the panel readouts and subtitle are written from the run, so their static text is a placeholder and not a claim');
  eq(`ring ${K.CONFIGS.diamond.cfg.k} · ${K.CONFIGS.diamond.cfg.m} inside`, 'ring 6 · 4 inside',
     'and the subtitle the reader ends up seeing is the shipped configuration');
}
// the same rule for the step instrument's readouts
ok(/\$\('ro-ring'\)\.textContent = letters\(st\.col, STEP\.V\)/.test(html)
   && /\$\('ro-broken'\)\.textContent = broken\.length/.test(html)
   && /\$\('step-status'\)\.innerHTML = '<b>Step '/.test(html),
   'the step readouts and status line are rewritten on load too, so their static text is not asserted either');

/* ---- the shareable surface ---- */
{
  const seo = (/^seoTitle: "([^"]*)"\s*$/m.exec(fs.readFileSync(MD, 'utf8')) || [, ''])[1];
  const title = (/<title>([^<]*)<\/title>/.exec(html) || [, ''])[1];
  ok(seo.length > 0 && seo === title,
     'the page title and the frontmatter seoTitle are the same string, so the card and the tab cannot disagree', title);
}
{
  // The head is the other place a static figure hides. A mutation of the meta description
  // or of og:title never touches the body, so the body matchers above cannot see it, and
  // the wrong number goes out on every card and every share.
  const h1 = (/<h1>([^<]*)<\/h1>/.exec(html) || [, ''])[1];
  fig(new RegExp(`Held for ${WORDNUM[HEAWOOD_YEAR - KEMPE_YEAR].replace(/^./, c => c.toUpperCase())} Years`),
      'the headline in the h1 names the computed gap', h1);
  const heads = [
    ['og:title', (/<meta property="og:title" content="([^"]*)"/.exec(html) || [, ''])[1]],
    ['twitter:title', (/<meta name="twitter:title" content="([^"]*)"/.exec(html) || [, ''])[1]],
    ['og:image:alt', (/<meta property="og:image:alt" content="([^"]*)"/.exec(html) || [, ''])[1]],
    ['JSON-LD headline', (/"headline":"((?:[^"\\]|\\.)*)"/.exec(html) || [, ''])[1]]
  ];
  for (const [where, value] of heads) {
    ok(value.startsWith(h1), `the ${where} in the head carries the same headline as the h1, gap and all`, value);
  }
  fig(new RegExp(`In ${KEMPE_YEAR} Alfred Kempe published`),
      'the meta description dates the proof to the same year the body and the footer do', shareable);
  fig(new RegExp(`in ${WHOLE.total} ways`), 'and repeats the computed four-colouring count', shareable);
  {
    // The three descriptions are deliberately three different lengths of the same claim, so
    // they are not required to be one string. Each is required to carry only figures that
    // are accounted for: a year the footer dates, or a value this run computed.
    const descs = [
      ['description', (/<meta name="description" content="([^"]*)"/.exec(html) || [, ''])[1]],
      ['og:description', (/<meta property="og:description" content="([^"]*)"/.exec(html) || [, ''])[1]],
      ['twitter:description', (/<meta name="twitter:description" content="([^"]*)"/.exec(html) || [, ''])[1]]
    ];
    const dated = [KEMPE_YEAR, HEAWOOD_YEAR, 1913, 1936, AH_YEAR, 1977, RSST_YEAR, 2005, 2008].map(String);
    const measured = [WHOLE.total, R.diamond.bad, R.ring5.stuck, R.diamond.total, R.diamond.good,
                      MAP.n, EDGES.length, CL.states, cum.tri, RSST_TOTAL, RSST_DRED].map(String);
    const allowed = new Set(dated.concat(measured));
    for (const [where, text] of descs) {
      ok(text.length > 0, `the head carries a ${where}`, text.length + ' chars');
      const nums = [...text.matchAll(/\b\d{2,}\b/g)].map(m => m[0]);
      const stray = nums.filter(t => !allowed.has(t));
      ok(stray.length === 0,
         `and every figure in the ${where} is either a year the footer dates or a value this run computed`,
         stray.length ? 'unaccounted: ' + stray.join(', ') : (nums.join(' ') || 'no figures'));
    }
  }
}

/* ---- the figures that are spelled out in words, which no digit net can see ---- */
{
  const CAP = w => w.replace(/^./, c => c.toUpperCase());
  const coloured = MAP.col.filter(x => x >= 0).length;
  fig(new RegExp(`${CAP(WORDNUM[coloured])} countries are coloured`),
      'the count of coloured countries, spelled out, is the number the shipped colouring carries');
  fig(new RegExp(`The step, on ${WORDNUM[MAP.n]} countries`), 'and the section heading names the size of the map that shipped');
  fig(new RegExp(`Below is a map of ${WORDNUM[MAP.n]} countries`), 'and so does the lede');
  {
    const deg = MAP.nb[MAP.v].length, wear = new Set(MAP.ring.map(u => MAP.col[u])).size;
    eq(deg, 5, 'country 0 has five neighbours');
    eq(wear, 4, 'and they wear four colours between them');
    fig(new RegExp(`its ${WORDNUM[deg]} neighbours are wearing all ${WORDNUM[wear]} colours`),
        'and the prose spells out both, from the graph and the colouring that shipped');
    fig(new RegExp(`The hard case is ${WORDNUM[deg]} neighbours wearing ${WORDNUM[wear]} colours between them`),
        'and the lede states the case with the same two numbers');
  }
  // A CITATION, not a measurement, and the page says so itself two paragraphs later. It is
  // held here because a spelled figure drifts as easily as a digit and no net above sees it.
  // Appel and Haken reported over 1200 hours of machine time for the reducibility half.
  const AH_HOURS = 'a thousand';
  fig(new RegExp(`took more than ${AH_HOURS} hours of machine time`),
      `CITATION: the machine time is given as more than ${AH_HOURS} hours`);
  fig(new RegExp(`the thousand hours,`), 'and the caveat paragraph names that same figure among the citations');
  fig(new RegExp(`The list ran to well over ${AH_HOURS} configurations`),
      'CITATION: and the size of the 1976 unavoidable set is given the same way, as an order of magnitude');
  ok(/are citations, not measurements: this page did not compute them/.test(visible),
     'and the page says outright that those three are citations rather than things it computed');
}

/* ---- THE COVERAGE NET, and its control ---- */
/*
  Everything above asserts figures one at a time, which is exactly how three of them went
  unasserted for as long as nobody looked. So: every number of three or more digits in the
  rendered text has to be in the accounted set below, which is built from the values this
  run computed plus one table of citation figures with their provenance. Add a figure to
  the prose and forget to assert it and this line goes red.
*/
{
  const computed = [
    MAP.n, EDGES.length, K.crossingReport(MAP.xy, EDGES).tested,
    CL.states, CL.freeing, CL.byDepth[1].states, CL.byDepth[2].freeing, REST.total, WHOLE.total,
    R.ring5.total, R.ring5.good, R.ring5.bad, R.ring6.total, R.ring6.bad, R.ring6.stuck,
    R.diamond.total, R.diamond.good, R.diamond.bad,
    ...R.diamond.hist, ...censusRows.map(r => r.tri), ...censusRows.map(r => r.withBreak),
    cum.tri, cum.wb, cum.reached, cum.brkSim, cum.brkSeq, cum.shared,
    K.absorbedClasses(K.CONFIGS.diamond.cfg), 24
  ];
  // Citation figures. Not computed by anything here; each is matched as a string against
  // the publisher record in the citation block above, and listed here so the net knows them.
  const cited = [
    193, 200,      // Kempe 1879, Amer. J. Math. 2
    332, 338,      // Heawood 1890, Quart. J. 24
    115, 128,      // Birkhoff 1913, Amer. J. Math. 35
    429, 490, 491, 567,   // Appel and Haken, and Appel, Haken and Koch, Illinois J. Math. 21
    1382, 1393,    // Gonthier, Notices of the AMS 55
    RSST_TOTAL, RSST_DRED,
    KEMPE_YEAR, HEAWOOD_YEAR, 1913, 1936, AH_YEAR, 1977, RSST_YEAR, 2005, 2008
  ];
  // Identifier digit groups: these are accession numbers, and each is asserted as one above.
  const identifiers = [...`${JFM_HEAWOOD} ${RSST_CONF_DIAMOND}`.matchAll(/\d{3,}/g)].map(m => m[0]);
  // Names, not measurements. SHA-256 is the digest the companion film's caption names when it
  // says how the film pins this page's engine; the 256 is the width of the digest, not a figure
  // anything here computed, so it is declared here the way a citation figure is.
  const named = ['256'];
  const accounted = new Set([...computed, ...cited].map(String).concat(identifiers, named));
  // The net scans this page's own text, not the site chrome landing writes around it (the
  // check placard, its "Last verified" date, the Nearby box, the way out): those blocks are
  // generated from other files and rebuilt on every landing (assay line, 2026-10-18).
  const article = html
    .replace(/<!--aw-(checkkind|nearby|wayout):start-->[\s\S]*?<!--aw-\1:end-->/g, ' ')
    .replace(/<script[\s\S]*?<\/script>/gi, ' ')
    .replace(/<style[\s\S]*?<\/style>/gi, ' ')
    .replace(/<!--[\s\S]*?-->/g, ' ')
    .replace(/<[^>]*>/g, ' ')
    .replace(/&middot;/g, '·').replace(/&ndash;/g, '-').replace(/&larr;/g, '<-').replace(/&nbsp;/g, ' ')
    .replace(/\s+/g, ' ');
  ok(article.length > 0.8 * visible.length && /JFM 22\.0562\.02/.test(article),
     'the article text the net scans is most of the page and still carries the citations',
     `${article.length} of ${visible.length} characters`);
  const seen = [...new Set([...article.matchAll(/\b\d{3,}\b/g)].map(m => m[0]))];
  const orphans = seen.filter(t => !accounted.has(t));
  ok(orphans.length === 0,
     'COVERAGE: every figure of three or more digits in the rendered text is either a value this run computed or a citation figure named above',
     orphans.length ? 'unaccounted: ' + orphans.join(', ') : `${seen.length} distinct figures, all accounted for`);
  // CONTROL on the net: bend one digit of an identifier and the net must find it
  const bent = article.replace(`JFM ${JFM_HEAWOOD}`, 'JFM 22.0563.02');
  const bentOrphans = [...new Set([...bent.matchAll(/\b\d{3,}\b/g)].map(m => m[0]))].filter(t => !accounted.has(t));
  ok(bentOrphans.length === 1 && bentOrphans[0] === '0563',
     'CONTROL: bend one digit of the JFM number in the rendered text and the coverage net names it',
     bentOrphans.join(', '));
}

ok(/2026-08-30/.test((/"datePublished":"([^"]*)"/.exec(html) || [, ''])[1]), 'the JSON-LD datePublished is 2026-08-30');
ok(/2026-08-30/.test((/"dateModified":"([^"]*)"/.exec(html) || [, ''])[1]), 'the JSON-LD dateModified is 2026-08-30');
ok(!/[\u2014]/.test(html), 'no em dash anywhere in the page');
// The chrome backfill inserts the aw-nearby and aw-wayout blocks after the last inline script,
// so this no longer demands a </script> immediately before the home-banner tag: it asserts what
// it was always protecting, which is that the deferred script is present and that the document
// closes in the right order after it. (Rewritten 2026-08-31; the stricter form had been red on
// this page and on 62 others since the backfill. See coordination/tending.tsv.)
ok(html.trimEnd().endsWith('-->')
   && /<script src="\/media\/home-banner\.js" defer><\/script>[\s\S]*<\/body>\s*<\/html>/.test(html),
   'the load-bearing closing tags are present and in order');
{
  const jsonld = /<script type="application\/ld\+json">([\s\S]*?)<\/script>/.exec(html);
  let parsed = null; try { parsed = JSON.parse(jsonld[1]); } catch (e) { /* reported below */ }
  ok(parsed && parsed['@type'] === 'Article' && parsed.headline && parsed.url.endsWith(`/strata/${SLUG}/`),
     'the JSON-LD parses and carries the Article fields');
}
/* ---- the citations, as strings, so a record corrected once cannot quietly regress ---- */
section('the citations, string-matched against the publisher records they were checked against');
{
  const cites = [
    [/A\. B\. Kempe, "On the Geographical Problem of the Four Colours," American Journal of Mathematics 2 \(1879\), 193-200/,
     'Kempe 1879, Amer. J. Math. 2, 193-200 (Crossref: this paper opens at 193 and the next paper in the issue opens at 201)'],
    [/P\. J\. Heawood, "Map-Colour Theorem," Quarterly Journal of Pure and Applied Mathematics 24 \(1890\), 332-338/,
     'Heawood 1890, title in the SINGULAR (JFM 22.0562.02: "Map-colour theorem.", Quart. J. XXIV, 332-338)'],
    [/G\. D\. Birkhoff, "The Reducibility of Maps," American Journal of Mathematics 35 \(1913\), 115-128/,
     'Birkhoff 1913, 115-128 (Crossref and JFM both say 115; that issue opens with this paper and the next opens at 129)'],
    [/K\. Appel and W\. Haken, "Every Planar Map is Four Colorable\. I\. Discharging,"/,
     'Appel and Haken, Part I, DISCHARGING, two authors (doi 10.1215/ijm/1256049011)'],
    [/K\. Appel, W\. Haken and J\. Koch, "II\. Reducibility,"/,
     'Appel, Haken and Koch, Part II, REDUCIBILITY, three authors (doi 10.1215/ijm/1256049012), which is the half this page is about'],
    [/published the\s+discharging half, and with John Koch the reducibility half/,
     'and the body says it the same way round as the footer'],
    [/N\. Robertson, D\. Sanders, P\. Seymour and R\. Thomas, "\s*The Four-Colour Theorem\s*," Journal of Combinatorial Theory Series B 70 \(1997\), 2-44/,
     'RSST 1997, JCTB 70, 2-44 (doi 10.1006/jctb.1997.1750)'],
    [/G\. Gonthier, "\s*Formal Proof: The Four-Color Theorem\s*," Notices of the AMS 55 \(2008\), 1382-1393/,
     'Gonthier, Notices 55 (2008), 1382-1393, cited as the write-up while the body dates the formalisation to 2005'],
    [/in 2005 Georges Gonthier and\s+Benjamin Werner formalised it inside Coq/,
     'and the body dates the Coq formalisation to 2005, not to the year of the article'],
    [/K\. Wagner, "Bemerkungen zum Vierfarbenproblem," Jahresbericht der DMV 46 \(1936\)/,
     'Wagner 1936, the flip-connectivity the generator relies on']
  ];
  for (const [re, msg] of cites) shows(re, 'CITATION: ' + msg);
  // CONTROL on the citation matcher: the inverted authorship this page shipped in its first
  // draft must be absent, and the matcher must be able to see it if it came back.
  const inverted = /K\. Appel, W\. Haken and J\. Koch, "Every Planar Map is Four Colorable\. I\. Discharging/;
  const relapsed = visible.replace('K. Appel and W. Haken, "Every Planar Map is Four Colorable. I. Discharging',
                                   'K. Appel, W. Haken and J. Koch, "Every Planar Map is Four Colorable. I. Discharging');
  ok(!inverted.test(visible) && inverted.test(relapsed),
     'CONTROL: put Koch back on the discharging paper and this check goes red');
}

/* ---- the refusal wiring, asserted about the page source rather than described ---- */
section('the on-page instrument gate, read out of the page source');
ok(/CONTROLS = \{ ok: relA\.reducible === false && relB\.reducible === true && anchorsOK/.test(html),
   'the configuration panel is gated by the ANCHORS as well as by the two controls');
ok(/var anchorsOK = \['ring3', 'ring4', 'ring5', 'diamond'\]\.every/.test(html),
   "and the anchor list is the four verdicts the record fixes, compared against the engine's stored verdicts");
ok(!/First break at <b>9<\/b>/.test(html),
   'the census status line no longer prints its verdict as a literal');
ok(/censusRows\.every\(function \(r\) \{ return r\.tri === K\.A000109\[r\.n\]; \}\)/.test(html)
   && /if \(firstBreak === null && r\.withBreak > 0\) firstBreak = r\.n;/.test(html),
   'and both of its clauses are read off the rows that actually finished');
ok(/Read as written the step broke on <b>' \+ sum\('brkSim'\)/.test(html)
   && /it failed on <b>' \+ sum\('brkSeq'\)/.test(html)
   && /overlapped in <b>' \+ sum\('shared'\)/.test(html),
   'and the three census figures the prose states are shown to the reader from the run, not only asserted offline');

{
  // THE CONTROL ON THIS MATCHER. Corrupt one rendered figure and require a red line.
  const corrupted = visible.replace('348, 252, 192, 96, 24, 0', '348, 252, 192, 96, 25, 0');
  const staircase = new RegExp(R.diamond.hist.slice(0, -1).join(', '));
  ok(staircase.test(visible) && !staircase.test(corrupted),
     'CONTROL: bend one digit of the staircase in the rendered text and the matcher goes red');
  const corrupted2 = visible.replace(`it has ${WHOLE.total} proper`, `it has ${WHOLE.total + 1} proper`);
  const re2 = new RegExp(`it has\\s+${WHOLE.total}\\s+proper\\s+four-colourings`);
  ok(re2.test(visible) && !re2.test(corrupted2),
     'CONTROL: bend the four-colouring count in the rendered text and the matcher goes red');
}

/* ================================ 7. the frontmatter ========================== */
section('the frontmatter entry, without which the page is invisible to the site');
{
  const md = fs.readFileSync(MD, 'utf8');
  const fm = /^---\n([\s\S]*?)\n---/.exec(md);
  ok(!!fm, 'the stratum markdown has frontmatter');
  const body = fm ? fm[1] : '';
  ok(/^date: 2026-08-30\s*$/m.test(body), 'date is 2026-08-30');
  ok(/^draft: false\s*$/m.test(body), 'draft is false');
  ok(/^seam: "pattern"\s*$/m.test(body), 'seam is the one the spec assigned');
  ok(/^href: "\/strata\/kempe-and-the-eleven-years\/"\s*$/m.test(body), 'href points at the page');
  ok(/"immersive"/.test(body) && /"interactive"/.test(body), 'tags include immersive and interactive');
  // THE DEK. It is the homepage card, the meta description and the first thing anyone reads,
  // and until now nothing in this file looked at it. Every figure in it is matched against a
  // value computed above, and the one sentence it used to get wrong is asserted absent.
  const dekM = /^dek: "([^"]*)"\s*$/m.exec(body);
  ok(!!dekM, 'there is a one-line double-quoted dek');
  if (dekM) {
    const dek = dekM[1];
    const dfig = (re, msg) => ok(re.test(dek), 'DEK: ' + msg, String(re));
    ok(!/Kempe proved that four colours/.test(dek) && /Kempe published a proof that four colours/.test(dek),
       'DEK: it says Kempe PUBLISHED a proof, not that he proved it, which is the thing this page spends its length refuting');
    dfig(new RegExp(`in ${WHOLE.total} ways`), `the map is four colourable in ${WHOLE.total} ways`);
    dfig(new RegExp(`enumerates all ${WHOLE.total} and prints one of them`),
         'and the page does enumerate them all and print one, which it now does');
    dfig(new RegExp(`${R.diamond.bad} hard ring colourings down to none`),
         `the diamond starts from ${R.diamond.bad} hard ring colourings`);
    eq(R.diamond.sweeps - 1, 5, 'the diamond takes five eliminating passes');
    dfig(/diamond in five passes/, 'and the dek says five passes');
    dfig(new RegExp(`where all ${R.ring5.stuck} survive for ever`),
         `and all ${R.ring5.stuck} hard colourings of the five-neighbour case survive`);
    if (NMAX >= 12) dfig(/up to twelve countries/, 'and the census in the dek is the one that runs, to twelve countries');
    dfig(/nine country map/, 'and the exhibit is a nine country map');
    eq(MAP.n, 9, 'which the graph agrees with');
    ok(!/[\u2014]/.test(dek), 'and the dek carries no em dash');
  }
  const plain = /^plain: "([^"]*)"\s*$/m.exec(body);
  ok(!!plain, 'there is a one-line double-quoted plain placard');
  if (plain) {
    const v = plain[1];
    ok(v.length >= 90 && v.length <= 420, 'the placard is between 90 and 420 characters', v.length + ' chars');
    ok((v.match(/[.!?](\s|$)/g) || []).length <= 3, 'and is at most three sentences');
    ok(!/[\u2014"]/.test(v), 'and carries no em dash and no raw double quote');
    ok(/nine country map/.test(v) && MAP.n === 9, 'and the placard\'s map size is the map that shipped');
    ok(/published a proof/.test(v), 'and it too says published a proof rather than proved');
  }
  const edges = [...body.matchAll(/-\s+to:\s*([^\s"]+)\s*\n\s+note:/g)].map(m => m[1]);
  ok(edges.length >= 2 && edges.length <= 4, 'there are 2 to 4 relates edges', edges.join(', '));
  for (const e of edges) {
    ok(fs.existsSync(path.join(ROOT, 'src', 'content', 'strata', `${e}.md`)), `relates target exists on disk: ${e}`);
  }
  ok(!/[\u2014]/.test(md), 'no em dash in the frontmatter file');
  const readme = fs.readFileSync(path.join(HERE, 'README.md'), 'utf8');
  ok(!/[\u2014]/.test(readme), 'no em dash in this directory\'s README');
  ok(readme.includes('verify-kempe-and-the-eleven-years.mjs'), 'and the README names the command that runs this gate');
  const self = fs.readFileSync(fileURLToPath(import.meta.url), 'utf8');
  ok(!/[\u2014]/.test(self), 'and no em dash in this gate either');
}

/* ==================================== the tally =============================== */
console.log(`\n${'-'.repeat(72)}`);
console.log(`${pass} passed, ${fail} failed.  refusal assertions: ${refusals}/${refusalTotal}.  ` +
            `figures string-matched out of the rendered page: ${FIGS.length}.  ` +
            `census depth: n <= ${NMAX}${NMAX < 12 ? '  (SET KEMPE_NMAX=12 FOR THE FULL RUN; totals were skipped)' : ''}.`);
if (fail) { console.log('\nfailures:'); failures.forEach(f => console.log('  ' + f)); }
process.exit(fail ? 1 : 0);
