#!/usr/bin/env node
/*
  verify-one-line-around-every-dot.mjs
  The single offline gate for /strata/one-line-around-every-dot/.

  It does five things and exits non-zero if any of them fails.

    1. Recomputes, from the law of reflection, every number the page displays: the wall-free
       component law, the census that measures pi, the exhaustive walks of the symmetric wall
       spaces, the smallest wall sets, and the parity theorem.
    2. Pulls the RENDERED TEXT out of public/strata/<slug>/index.html and requires each of
       those figures to appear in it, as the string this program formatted, so that the prose
       and the arithmetic cannot part company.
    3. Runs the poison controls: a corrupted law of reflection that must break the published
       anchor, walls turned into silent no-ops that must break the 3 by 3 control while
       leaving the 4 by 4 headline untouched, and a broken symmetry orbit that the invariance
       filter must reject.
    4. Re-runs the same protocol a second time in Python (research/<slug>/crosscheck.py,
       whose protocol comment was written before any result was seen) and compares field by
       field. Skips with a loud message, counted, if python3 is unavailable.
    5. Audits the shipped files: closing tags, JSON-LD, the frontmatter, the plain placard,
       the relates targets, and the absence of em dashes.

  Run:  node research/one-line-around-every-dot/verify-one-line-around-every-dot.mjs
*/

import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { execFileSync } from 'node:child_process';

const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, '..', '..');
const SLUG = 'one-line-around-every-dot';
const PAGE = path.join(ROOT, 'public', 'strata', SLUG, 'index.html');
const FM = path.join(ROOT, 'src', 'content', 'strata', SLUG + '.md');
const README = path.join(HERE, 'README.md');
const CROSS = path.join(HERE, 'crosscheck.py');

const EMDASH = String.fromCharCode(0x2014);   /* by code point, so this file carries none itself */
let passed = 0, failed = 0, skipped = 0;
function ok(cond, msg, extra) {
  const n = String(passed + failed + 1).padStart(3, '0');
  if (cond) { passed++; console.log(`PASS ${n}  ${msg}`); }
  else { failed++; console.log(`FAIL ${n}  ${msg}` + (extra ? '  ' + JSON.stringify(extra) : '')); }
  return !!cond;
}
function skip(msg) { skipped++; console.log(`SKIP      ${msg}`); }

/* ─────────────────────────────────────────────────────────────────────────────
   THE MODEL. Written from the same specification as the page, in this file's own
   idiom. It is not the page's code: the page steps a state index through typed
   arrays, this steps an (x, y, dx, dy) tuple through a Set, and the union-find
   engine below shares nothing with either.
   ───────────────────────────────────────────────────────────────────────────── */
const NONE = 0, V = 1, H = 2;

function grid(a, b) {
  const W = 2 * a, Ht = 2 * b, pts = [], idx = new Map();
  for (let x = 0; x <= W; x++) for (let y = 0; y <= Ht; y++) if ((x + y) & 1) { idx.set(x + ',' + y, pts.length); pts.push([x, y]); }
  const internal = [];
  for (let i = 0; i < pts.length; i++) { const [x, y] = pts[i]; if (x > 0 && x < W && y > 0 && y < Ht) internal.push(i); }
  return { a, b, W, H: Ht, pts, idx, internal };
}

/* ROUTE ONE: follow the ray. */
function linesByRay(g, walls, reflect) {
  reflect = reflect || defaultReflect;
  const seen = new Set();
  let n = 0;
  for (let p = 0; p < g.pts.length; p++) {
    const [x0, y0] = g.pts[p];
    for (const dx0 of [-1, 1]) for (const dy0 of [-1, 1]) {
      if (x0 === 0 && dx0 === -1) continue;
      if (x0 === g.W && dx0 === 1) continue;
      if (y0 === 0 && dy0 === -1) continue;
      if (y0 === g.H && dy0 === 1) continue;
      const start = p + ':' + dx0 + ':' + dy0;
      if (seen.has(start)) continue;
      n++;
      let cur = [p, dx0, dy0], key = start;
      while (!seen.has(key)) {
        seen.add(key);
        const [pp, dx, dy] = cur;
        const [x, y] = g.pts[pp];
        const nx = x + dx, ny = y + dy;
        const q = g.idx.get(nx + ',' + ny);
        if (q === undefined) throw new Error('the ray left the grid at ' + nx + ',' + ny);
        const [ndx, ndy] = reflect(g, q, dx, dy, walls[q] || NONE);
        cur = [q, ndx, ndy];
        key = q + ':' + ndx + ':' + ndy;
      }
    }
  }
  if (n % 2) throw new Error('directed orbit count came out odd');
  return n / 2;
}
function defaultReflect(g, q, dx, dy, w) {
  const [x, y] = g.pts[q];
  if (x === 0 || x === g.W || w === V) dx = -dx;
  if (y === 0 || y === g.H || w === H) dy = -dy;
  return [dx, dy];
}
/* POISON: the boundary retro-reflects instead of obeying the law of reflection. */
function retroReflect(g, q, dx, dy, w) {
  const [x, y] = g.pts[q];
  if (x === 0 || x === g.W || y === 0 || y === g.H) return [-dx, -dy];
  if (w === V) dx = -dx;
  if (w === H) dy = -dy;
  return [dx, dy];
}
/* POISON: every wall is a silent no-op. */
function deafReflect(g, q, dx, dy) {
  const [x, y] = g.pts[q];
  if (x === 0 || x === g.W) dx = -dx;
  if (y === 0 || y === g.H) dy = -dy;
  return [dx, dy];
}

/* The same ray route, but keeping one closed path per line. Used to test step 1 of the proof
   (the ink never moves) against the walls, rather than against the lattice alone. */
function pathsByRay(g, walls) {
  const seen = new Set(), orbits = [];
  for (let p = 0; p < g.pts.length; p++) {
    const [x0, y0] = g.pts[p];
    for (const dx0 of [-1, 1]) for (const dy0 of [-1, 1]) {
      if (x0 === 0 && dx0 === -1) continue;
      if (x0 === g.W && dx0 === 1) continue;
      if (y0 === 0 && dy0 === -1) continue;
      if (y0 === g.H && dy0 === 1) continue;
      let key = p + ':' + dx0 + ':' + dy0;
      if (seen.has(key)) continue;
      let cur = [p, dx0, dy0];
      const pts = [], segs = [];
      while (!seen.has(key)) {
        seen.add(key);
        const [pp, dx, dy] = cur;
        const [x, y] = g.pts[pp];
        const q = g.idx.get((x + dx) + ',' + (y + dy));
        if (q === undefined) throw new Error('the ray left the grid');
        segs.push(pp < q ? pp + '-' + q : q + '-' + pp);
        pts.push(q);
        const [ndx, ndy] = defaultReflect(g, q, dx, dy, walls[q] || NONE);
        cur = [q, ndx, ndy];
        key = q + ':' + ndx + ':' + ndy;
      }
      orbits.push({ pts, key: segs.slice().sort().join(',') });
    }
  }
  /* each closed line is walked once in each direction and the two walks use the same
     segment set, so the sorted segment list names the line. Keep one walk per name. */
  const kept = new Map();
  for (const o of orbits) if (!kept.has(o.key)) kept.set(o.key, o.pts);
  return [...kept.values()];
}

/* ROUTE TWO: no ray, no direction. Pair the segment ends at each waypoint from the local
   rule and count the classes with a union-find. Shares no code with route one. */
function linesByPairing(g, walls) {
  const parent = new Map();
  const find = (u) => { while (parent.get(u) !== u) { parent.set(u, parent.get(parent.get(u))); u = parent.get(u); } return u; };
  const add = (u) => { if (!parent.has(u)) parent.set(u, u); return u; };
  const uni = (u, v) => { const ru = find(add(u)), rv = find(add(v)); if (ru !== rv) parent.set(ru, rv); };
  const segName = (x, y, dx, dy) => {
    const [ax, ay] = dx === 1 ? [x, y] : [x - 1, y + dy];
    return ax + '|' + ay + '|' + (dx === 1 ? (dy === 1 ? 'u' : 'd') : (dy === 1 ? 'd' : 'u'));
  };
  for (let p = 0; p < g.pts.length; p++) {
    const [x, y] = g.pts[p], w = walls[p] || NONE;
    const fx = (x === 0 || x === g.W || w === V), fy = (y === 0 || y === g.H || w === H);
    const here = new Map();
    for (const dx of [-1, 1]) for (const dy of [-1, 1]) {
      const nx = x + dx, ny = y + dy;
      if (nx < 0 || nx > g.W || ny < 0 || ny > g.H) continue;
      here.set(dx + ',' + dy, segName(x, y, dx, dy));
      add(here.get(dx + ',' + dy));
    }
    for (const [k, name] of here) {
      const [dx, dy] = k.split(',').map(Number);
      const odx = fx ? -dx : dx, ody = fy ? -dy : dy;
      const partner = here.get((-odx) + ',' + (-ody));
      if (partner !== undefined) uni(name, partner);
    }
  }
  const roots = new Set();
  for (const u of parent.keys()) roots.add(find(u));
  return roots.size;
}

/* ── symmetry ─────────────────────────────────────────────────────────────── */
function gens(name, a, b) {
  if (name === 'none') return [];
  if (name === 'c2') return [[(x, y) => [2 * a - x, 2 * b - y], false]];
  if (name === 'mirror') return [[(x, y) => [2 * a - x, y], false]];
  if (name === 'c4') return a === b ? [[(x, y) => [y, 2 * a - x], true]] : null;
  if (name === 'diag') return a === b ? [[(x, y) => [y, x], true]] : null;
  return null;
}
function orbitsOf(g, G) {
  if (G === null) return null;
  if (!G.length) return g.internal.map((p) => [[p, 0]]);
  const seen = new Set(), out = [];
  for (const p0 of g.internal) {
    if (seen.has(p0)) continue;
    const flag = new Map(), stack = [[p0, 0]], orb = [];
    while (stack.length) {
      const [q, f] = stack.pop();
      if (flag.has(q)) { if (flag.get(q) !== f) return null; continue; }
      flag.set(q, f); seen.add(q); orb.push([q, f]);
      const [x, y] = g.pts[q];
      for (const [m, turns] of G) { const [nx, ny] = m(x, y); stack.push([g.idx.get(nx + ',' + ny), f ^ (turns ? 1 : 0)]); }
    }
    out.push(orb);
  }
  return out;
}
const edgeOrient = (g, p) => (g.pts[p][0] % 2 === 0 ? V : H);
function invariant(g, walls, G) {
  if (G === null) return false;
  for (const p of g.internal) {
    const w = walls[p] || NONE;
    const [x, y] = g.pts[p];
    for (const [m, turns] of G) {
      const [nx, ny] = m(x, y), q = g.idx.get(nx + ',' + ny);
      if (q === undefined) return false;
      const want = w === NONE ? NONE : (turns ? (w === V ? H : V) : w);
      if ((walls[q] || NONE) !== want) return false;
    }
  }
  return true;
}

const CAP = 1200000;
function walkSpace(a, b, sym, voc, opts = {}) {
  const g = grid(a, b), orbs = orbitsOf(g, gens(sym, a, b));
  if (orbs === null) return { ok: false, why: 'group does not act on that grid' };
  const per = orbs.map((orb) => (voc === 'edge' ? [NONE, edgeOrient(g, orb[0][0])] : [NONE, V, H]));
  const total = per.reduce((s, o) => s * o.length, 1);
  if (total > (opts.cap || CAP)) return { ok: false, refused: true, space: total };
  const walls = new Int8Array(g.pts.length);
  const dist = new Map();
  let mono = 0, minC = Infinity, atMin = 0, minWalls = Infinity, bestMono = null, minSet = null, disagree = 0;
  let minWallsAtBest = Infinity;
  const engine = opts.engine || 'ray';
  for (let it = 0; it < total; it++) {
    let t = it, nw = 0;
    walls.fill(0);
    for (let i = 0; i < orbs.length; i++) {
      const c = per[i][t % per[i].length];
      t = Math.floor(t / per[i].length);
      if (c === NONE) continue;
      for (const [q, f] of orbs[i]) { walls[q] = f ? (c === V ? H : V) : c; nw++; }
    }
    const k = engine === 'pairing' ? linesByPairing(g, walls)
      : engine === 'deaf' ? linesByRay(g, walls, deafReflect)
        : linesByRay(g, walls);
    if (opts.crossEvery && it % opts.crossEvery === 0) {
      const other = engine === 'pairing' ? linesByRay(g, walls) : linesByPairing(g, walls);
      if (other !== k) disagree++;
    }
    dist.set(k, (dist.get(k) || 0) + 1);
    if (k === 1) { mono++; if (nw < minWalls) { minWalls = nw; bestMono = Array.from(walls); } }
    if (k < minC) { minC = k; atMin = 0; minWallsAtBest = Infinity; }
    if (k === minC) { atMin++; if (nw < minWallsAtBest) { minWallsAtBest = nw; minSet = Array.from(walls); } }
  }
  const parities = [...new Set([...dist.keys()].map((k) => k % 2))].sort();
  return { ok: true, space: total, orbits: orbs.length, mono, minComponents: minC, atMin, minWallsAtBest,
    minWallsMono: bestMono ? minWalls : null, parities, disagree,
    dist: Object.fromEntries([...dist.entries()].sort((p, q) => p[0] - q[0])), bestMono, minSet };
}

function gcd(x, y) { while (y) { const t = x % y; x = y; y = t; } return x; }
function totient(n) { let r = n, m = n; for (let p = 2; p * p <= m; p++) { if (m % p === 0) { while (m % p === 0) m /= p; r -= r / p; } } if (m > 1) r -= r / m; return r; }
function minWallsFree(a, b, kmax = 4) {
  const g = grid(a, b), walls = new Int8Array(g.pts.length), pos = g.internal, n = pos.length;
  if (linesByRay(g, walls) === 1) return 0;
  for (let k = 1; k <= kmax; k++) {
    const idxs = new Array(k).fill(0);
    const rec = (start, depth) => {
      if (depth === k) {
        for (let m = 0; m < (1 << k); m++) {
          walls.fill(0);
          for (let i = 0; i < k; i++) walls[pos[idxs[i]]] = ((m >> i) & 1) ? H : V;
          if (linesByRay(g, walls) === 1) return true;
        }
        return false;
      }
      for (let i = start; i < n; i++) { idxs[depth] = i; if (rec(i + 1, depth + 1)) return true; }
      return false;
    };
    if (rec(0, 0)) return k;
  }
  return null;
}
/* the parity the proof predicts, from geometry: how many diamonds contain the grid centre,
   modulo two. null when the centre lies on the drawing, which is exactly when a + b is odd. */
function kappa(a, b) { return ((a + b) & 1) ? null : (((a & 1) && (b & 1)) ? 1 : 0); }

function fmt(n) { const s = String(n); let o = '', c = 0; for (let i = s.length - 1; i >= 0; i--) { o = s[i] + o; if (++c % 3 === 0 && i > 0) o = ',' + o; } return o; }
function pct(x, d) { return (100 * x).toFixed(d) + '%'; }

/* ─────────────────────────────────────────────────────────────────────────────
   what the reader actually sees
   ───────────────────────────────────────────────────────────────────────────── */
const html = fs.readFileSync(PAGE, 'utf8');
const RENDERED = html
  .replace(/<script[\s\S]*?<\/script>/gi, ' ')
  .replace(/<style[\s\S]*?<\/style>/gi, ' ')
  .replace(/<!--[\s\S]*?-->/g, ' ')
  .replace(/<[^>]*>/g, ' ')
  .replace(/&times;/g, 'x').replace(/&minus;/g, '-').replace(/&pi;/g, 'pi')
  .replace(/&sup2;/g, '2').replace(/&sigma;/g, 'sigma').replace(/&larr;/g, '<')
  .replace(/&middot;/g, '.').replace(/&amp;/g, '&')
  .replace(/&Sigma;/g, 'S').replace(/&phi;/g, 'phi')
  .replace(/\s+/g, ' ');
function shows(label, s) {
  ok(RENDERED.includes(s), `the page displays ${label} as "${s}"`, RENDERED.includes(s) ? undefined : { looked_for: s });
}

console.log('== the model, and the published anchors ==');

/* the five worked cases quoted from the lecture notes */
{
  const want = [[2, 2, 2], [4, 2, 2], [5, 2, 1], [6, 2, 2], [6, 3, 3]];
  let allOk = true, byPairing = true;
  for (const [a, b, c] of want) {
    const g = grid(a, b), w = new Int8Array(g.pts.length);
    if (linesByRay(g, w) !== c) allOk = false;
    if (linesByPairing(g, w) !== c) byPairing = false;
  }
  ok(allOk, 'published anchor: the five worked cases in Radovic (2x2 gives 2, 4x2 gives 2, 5x2 gives 1, 6x2 gives 2, 6x3 gives 3) reproduce by the ray route');
  ok(byPairing, 'and by the pairing route, which shares no code with it');
  /* all five, spelled the way the page spells them, generated from the values just computed
     so that a typo in the rendered words cannot survive either */
  const WORD = { 2: 'two', 4: 'four', 5: 'five', 6: 'six', 3: 'three' };
  for (const [a, b, c] of want) {
    const g = grid(a, b);
    shows(`the worked case ${a} by ${b}`, `${WORD[a]} by ${WORD[b]} gives ${linesByRay(g, new Int8Array(g.pts.length))}`);
    if (linesByRay(g, new Int8Array(g.pts.length)) !== c) ok(false, `worked case ${a}x${b} drifted`);
  }
}

/* the wall-free law, by both routes, and the totient anchor */
let census40 = null;
{
  let bad = 0, disagree = 0, mono20 = 0;
  for (let a = 1; a <= 20; a++) for (let b = 1; b <= 20; b++) {
    const g = grid(a, b), w = new Int8Array(g.pts.length);
    const k = linesByRay(g, w);
    if (k !== gcd(a, b)) bad++;
    if (linesByPairing(g, w) !== k) disagree++;
    if (k === 1) mono20++;
  }
  ok(bad === 0, `the wall-free count equals gcd(a, b) on all 400 grids up to 20 by 20 (${bad} mismatches)`);
  ok(disagree === 0, `the two routes agree on all 400 of them (${disagree} disagreements)`);
  const T20 = Array.from({ length: 20 }, (_, i) => totient(i + 1)).reduce((s, v) => s + v, 0);
  ok(mono20 === 2 * T20 - 1, `independent anchor: the ray tracer finds ${mono20} monolinear grids up to 20 by 20 and the totient closed form gives 2 x ${T20} - 1 = ${2 * T20 - 1}`);

  let mono40 = 0;
  for (let a = 1; a <= 40; a++) for (let b = 1; b <= 40; b++) {
    const g = grid(a, b);
    if (linesByRay(g, new Int8Array(g.pts.length)) === 1) mono40++;
  }
  const T40 = Array.from({ length: 40 }, (_, i) => totient(i + 1)).reduce((s, v) => s + v, 0);
  ok(mono40 === 2 * T40 - 1, `the same at 40 by 40: ${mono40} traced against the closed form ${2 * T40 - 1}`);
  const frac = mono40 / 1600, pi = Math.sqrt(6 / frac);
  census40 = { mono: mono40, frac, pi };
  ok(Math.abs(pi - Math.PI) / Math.PI < 0.005, `pi recovered from the census is ${pi.toFixed(4)}, within 0.5% of pi`);
  shows('the census total', '1,600 grids');
  shows('the monolinear count', `${mono40} draw as one line`);
  shows('the observed density', pct(frac, 2));
  shows('the limiting density', pct(6 / (Math.PI * Math.PI), 2));
  shows('pi from the census', `pi = ${pi.toFixed(4)}`);
  shows('the error on pi', `off by ${pct(Math.abs(pi - Math.PI) / Math.PI, 1)}`);
  shows('the closed form', `2 x Sphi(k) - 1 = ${mono40}`);
}

console.log('== the poison controls ==');

/* POISON 1: break the law of reflection; the published anchor must go red. */
{
  let bad = 0, mono = 0;
  for (let a = 1; a <= 20; a++) for (let b = 1; b <= 20; b++) {
    const g = grid(a, b);
    const k = linesByRay(g, new Int8Array(g.pts.length), retroReflect);
    if (k !== gcd(a, b)) bad++;
    if (k === 1) mono++;
  }
  const T20 = Array.from({ length: 20 }, (_, i) => totient(i + 1)).reduce((s, v) => s + v, 0);
  ok(bad > 0 && mono !== 2 * T20 - 1,
    `poison: a retro-reflecting boundary misses gcd on ${bad} of 400 grids and gives ${mono} monolinear instead of ${2 * T20 - 1}, so the totient anchor can go red`);
}

/* POISON 2: silence the walls. The headline must NOT notice; the 3 by 3 control must. */
const deaf44 = walkSpace(4, 4, 'c4', 'both', { engine: 'deaf' });
const deaf33 = walkSpace(3, 3, 'c4', 'both', { engine: 'deaf' });
ok(deaf44.ok && deaf44.mono === 0 && deaf44.parities.length === 1 && deaf44.parities[0] === 0,
  'poison: with every wall a silent no-op the 4 by 4 headline is UNCHANGED at 0 of 729, all even, so the headline alone proves nothing');
ok(deaf33.ok && deaf33.mono === 0,
  'poison: the same deaf search returns 0 monolinear on the 3 by 3 where the honest one returns 12, and that is the assertion which catches a broken wall');

/* POISON 3: knock one wall out of a symmetric orbit; the filter must reject the set. */
{
  const g = grid(4, 4), G = gens('c4', 4, 4), orbs = orbitsOf(g, G);
  const w = new Int8Array(g.pts.length);
  for (const [q, f] of orbs[0]) w[q] = f ? H : V;
  for (const [q, f] of orbs[2]) w[q] = f ? H : V;
  const before = invariant(g, w, G);
  const w2 = Int8Array.from(w); w2[orbs[0][1][0]] = NONE;
  ok(before && !invariant(g, w2, G), 'poison: a genuine quarter-turn orbit passes the invariance filter and the same filter rejects it after one wall is knocked out');
}

/* POISON 4: drop the symmetry demand and the solutions come back. */
{
  const free = walkSpace(3, 3, 'none', 'edge');
  ok(free.ok && free.space === 4096 && free.mono === 240,
    `with the symmetry demand dropped, ${fmt(free.mono)} of the ${fmt(free.space)} free cell-edge wall sets on the 3 by 3 are monolinear, so it is the symmetry that forbids and not the search`);
}

console.log('== the headline, and the discriminator ==');

const s44 = walkSpace(4, 4, 'c4', 'both', { crossEvery: 1 });
ok(s44.ok && s44.space === 729 && s44.mono === 0 && s44.minComponents === 2 && s44.atMin === 320 && s44.disagree === 0,
  `all ${s44.space} quarter-turn wall sets on the 4 by 4 walked: ${s44.mono} monolinear, best ${s44.minComponents} lines reached by ${s44.atMin} of them, both routes agreeing on every one`);
ok(s44.parities.length === 1 && s44.parities[0] === 0, 'every one of those 729 counts is even');
shows('the quarter-turn space', '729 configurations');
shows('the headline', `${s44.space} wall sets and ${s44.mono} of them give one line`);
shows('the best the space can do', `reached by ${s44.atMin} of the ${s44.space}`);

const s44e = walkSpace(4, 4, 'c4', 'edge');
ok(s44e.ok && s44e.space === 64 && s44e.mono === 0, `and in the Chokwe vocabulary alone, ${s44e.mono} of ${s44e.space}`);
shows('the Chokwe vocabulary result', `it is ${s44e.mono} of ${s44e.space}`);
shows('the same result restated', `${s44e.mono} of ${s44e.space} on cell edges alone, ${s44.mono} of ${s44.space} with both`);

const s44h = walkSpace(4, 4, 'c2', 'both', { crossEvery: 5000 });
ok(s44h.ok && s44h.space === 531441 && s44h.mono === 0 && s44h.disagree === 0 && s44h.parities.length === 1 && s44h.parities[0] === 0,
  `widening to the half turn gives ${fmt(s44h.space)} wall sets, still ${s44h.mono} monolinear, every count even`);
shows('the half-turn space', `${fmt(s44h.space)} configurations`);

const s33 = walkSpace(3, 3, 'c4', 'both');
ok(s33.ok && s33.space === 27 && s33.mono === 12 && s33.minWallsMono === 4,
  `the 3 by 3 under the same quarter turn: ${s33.mono} monolinear of ${s33.space}, smallest ${s33.minWallsMono} walls`);
shows('the 3 by 3 result', `${s33.mono} out of ${s33.space}`);
shows('its smallest set', `the smallest using ${s33.minWallsMono}`);

const s55 = walkSpace(5, 5, 'c4', 'both', { crossEvery: 1 });
ok(s55.ok && s55.space === 59049 && s55.mono === 14368 && s55.minWallsMono === 8 && s55.disagree === 0,
  `the 5 by 5 under a quarter turn, which the budget account calls harder: ${fmt(s55.mono)} monolinear of ${fmt(s55.space)}, smallest ${s55.minWallsMono} walls, the pairing route agreeing on every one of them (${s55.disagree} disagreements)`);
shows('the 5 by 5 result', `${fmt(s55.mono)} monolinear quarter-turn solutions out of ${fmt(s55.space)}`);
shows('its smallest set', `the smallest using ${s55.minWallsMono} walls`);

const m44 = walkSpace(4, 4, 'mirror', 'edge', { crossEvery: 1 });
ok(m44.ok && m44.space === 16384 && m44.mono === 512 && m44.minWallsMono === 3 && m44.disagree === 0,
  `THE DISCRIMINATOR: same grid, same cell-edge vocabulary, a left-to-right mirror gives ${fmt(m44.mono)} monolinear of ${fmt(m44.space)}, smallest ${m44.minWallsMono} walls, the pairing route agreeing on every one of them (${m44.disagree} disagreements)`);
shows('the discriminator', `${fmt(m44.mono)} of the ${fmt(m44.space)}`);
shows('its smallest set', `the smallest using ${m44.minWallsMono} walls`);

/* the refinement of the budget account that the page names, and the measurement that kills it */
{
  const g44 = grid(4, 4);
  const oC2 = orbitsOf(g44, gens('c2', 4, 4)), oM = orbitsOf(g44, gens('mirror', 4, 4));
  const c2AllTwo = oC2.every((o) => o.length === 2);
  const singles = oM.filter((o) => o.length === 1).length;
  ok(c2AllTwo && singles === 4,
    `the premise of the budget refinement: every half-turn orbit on the 4 by 4 has size 2, so a half-turn wall count is always even, while the mirror has ${singles} orbits of size one and can spend an odd number`);
  /* and the mirror really does need an odd number to reach one line */
  const oddOnly = Object.keys(m44.dist).length > 0;
  ok(oddOnly && m44.minWallsMono % 2 === 1,
    `and the cheapest monolinear mirror set does spend an odd number of walls (${m44.minWallsMono}), which no half-turn set can`);
  ok(s33.minWallsMono === 4 && s44.minWallsAtBest === 8 && s55.minWallsMono === 8,
    `and the refinement is refuted by measurement: the 3 by 3 quarter turn pays ${s33.minWallsMono} walls for 2 merges, the 5 by 5 pays ${s55.minWallsMono} for 4, and the best the 4 by 4 quarter turn manages pays ${s44.minWallsAtBest} for 2, so a wall is not a merge`);
  shows('the 3 by 3 wall bill', `${s33.minWallsMono} walls for 2 merges`);
  shows('the 5 by 5 wall bill', `${s55.minWallsMono} walls for 4 merges`);
  shows('the 4 by 4 wall bill at its best', `${s44.minWallsAtBest} walls for 2 merges`);
  ok(!RENDERED.includes('No account in terms of merges and budgets can tell those two apart'),
    'and the page no longer claims that NO account in terms of merges can separate the two symmetries, which was false');
}

console.log('== the theorem ==');

/* the parity theorem, its sharpness, and an independent geometric route to it */
{
  let theorem = true, sharp = false, geomBad = 0, geomN = 0;
  const rows = [[2, 2], [3, 3], [4, 2], [4, 4], [6, 2], [5, 3], [3, 2], [4, 3], [6, 3]];
  for (const [a, b] of rows) {
    const r = walkSpace(a, b, 'c2', 'edge');
    if (!r.ok) continue;
    const k = kappa(a, b);
    if (k === null) { if (r.parities.length === 2) sharp = true; continue; }
    if (!(r.parities.length === 1 && r.parities[0] === k)) theorem = false;
    if (k !== gcd(a, b) % 2) theorem = false;
    for (const [c, n] of Object.entries(r.dist)) { geomN += n; if ((Number(c) & 1) !== k) geomBad++; }
  }
  ok(theorem, 'the theorem holds on every grid tested where a + b is even, each being a complete walk of that half-turn space, and the predicted parity equals gcd(a, b) mod 2');
  ok(sharp, 'and it FAILS where a + b is odd, so the hypothesis is sharp and not decorative');
  ok(geomBad === 0 && geomN > 0, `independent route: counting the diamonds around the centre predicts the parity from geometry with no ray traced, and matches the tracer on all ${fmt(geomN)} configurations`);
}

/* step one of the proof: the ink does not move. This walks the RAY under each wall set and
   sums the drawn segments, so it fails if the walls change where the ink is. A control on
   itself is run underneath: a tracer that drops a wall rule must break the same sum on at
   least one configuration if the sum is really reading the walls. */
{
  let inkBad = 0, pathBad = 0, tested = 0, seed = 12345, wallSets = 0;
  const rnd = () => (seed = (seed * 1103515245 + 12345) & 0x7fffffff);
  for (const [a, b] of [[3, 3], [4, 4], [5, 4], [6, 3], [2, 2], [7, 4]]) {
    const g = grid(a, b);
    for (let t = 0; t < 25; t++) {
      const w = new Int8Array(g.pts.length);
      if (t > 0) { for (const p of g.internal) w[p] = rnd() % 3; wallSets++; }
      const paths = pathsByRay(g, w);
      let total = 0;
      for (const P of paths) {
        total += P.length;
        for (let i = 0; i < P.length; i++) {
          const u = g.pts[P[i]], v = g.pts[P[(i + 1) % P.length]];
          if (Math.abs(u[0] - v[0]) !== 1 || Math.abs(u[1] - v[1]) !== 1) pathBad++;
        }
      }
      if (total !== 4 * a * b) inkBad++;
      if (paths.length !== linesByRay(g, w)) pathBad++;
      tested++;
    }
  }
  ok(inkBad === 0 && tested === 150 && wallSets === 144,
    `step 1 of the proof, walked on ${tested} configurations across six grids of which ${wallSets} carry walls: however the walls are placed the lines together use exactly 4ab segments, ${inkBad} exceptions`);
  ok(pathBad === 0, `and one closed path per line, every step diagonal (${pathBad} exceptions), so two lines are never drawn as one`);
  /* control: the sum must be able to go wrong. Reflect a V wall as if it were an H wall and
     the ray no longer closes up over the same ink on at least one of those configurations. */
  {
    const swapped = (g, q, dx, dy, w) => {
      const [x, y] = g.pts[q];
      if (x === 0 || x === g.W || w === H) dx = -dx;
      if (y === 0 || y === g.H || w === V) dy = -dy;
      return [dx, dy];
    };
    let differ = 0, seen = 0, s2 = 999;
    const r2 = () => (s2 = (s2 * 1103515245 + 12345) & 0x7fffffff);
    for (const [a, b] of [[3, 3], [4, 4], [5, 4]]) {
      const g = grid(a, b);
      for (let t = 0; t < 20; t++) {
        const w = new Int8Array(g.pts.length);
        for (const p of g.internal) w[p] = r2() % 3;
        seen++;
        if (linesByRay(g, w, swapped) !== linesByRay(g, w)) differ++;
      }
    }
    ok(differ > 0, `control on that control: a reflection rule that confuses the two wall types disagrees with the honest one on ${differ} of ${seen} wall sets, so this route does read the walls`);
  }
}

/* the smallest wall set of any shape, and the lecture notes off-by-one */
{
  const mw = {};
  for (const [a, b] of [[2, 2], [3, 3], [4, 2], [4, 4], [6, 2], [6, 3]]) mw[`${a}x${b}`] = minWallsFree(a, b);
  const allGcdMinusOne = Object.entries(mw).every(([k, v]) => {
    const [a, b] = k.split('x').map(Number);
    return v === gcd(a, b) - 1;
  });
  ok(allGcdMinusOne, `the fewest walls of any shape reaching one line is gcd(a, b) - 1 on all six grids searched: ${JSON.stringify(mw)}`);
  ok(mw['4x4'] === 3, `on the 4 by 4 that is ${mw['4x4']}, where the lecture notes narrate four`);
  shows('the correction to the lecture notes', `${mw['4x4']} walls suffice`);
}

/* the refusal path */
{
  const r = walkSpace(6, 6, 'c2', 'both');
  ok(r.ok === false && r.refused === true && r.mono === undefined,
    `refusal path: a space of ${fmt(r.space)} above the ceiling of ${fmt(CAP)} refuses and reports no monolinear count at all`);
  shows('the ceiling', `ceiling of ${fmt(CAP)}`);
}

/* the page's own account of what it did, and of what it read ─────────────────── */
{
  ok(RENDERED.includes('Bridges 2009, 305-308'),
    'the Bridges 2009 citation gives the page range the artefact actually has, 305-308 over four pages, not 305-312');
  ok(!RENDERED.includes('305-312'), 'and the wrong range is gone');
  ok(RENDERED.includes('The three percentages about the recorded corpus'),
    'the corpus disclosure counts its own quoted percentages correctly: there are three of them, 80%, 61% of 141, and 79%');
  for (const p of ['80%', '61% of 141', '79%']) ok(RENDERED.includes(p), `and it names ${p}`);
  ok(RENDERED.includes('the strict reading of Radovic'),
    'the theorem paragraph says WHICH reading of the exercise it kills');
  ok(RENDERED.includes('The loose reading, any symmetry at all, does not'),
    'and states in the same breath that the loose reading has answers');
  ok(!/Radovic's exercise asks for something that does not exist/.test(RENDERED),
    'and the unqualified version of that sentence, which was false, is gone');
  ok(RENDERED.includes('undated lecture notes, hosted at the New Jersey'),
    'the source is cited as undated lecture notes HOSTED at NJIT, not as a publication and not as the author\'s affiliation');
  ok(!/no shared code path/.test(RENDERED) && RENDERED.includes('They share build()'),
    'the check panel states what the two engines share rather than claiming they share nothing');
  ok(RENDERED.includes('Two figures are engine A alone'),
    'and it names the two figures only one engine counts, rather than implying both engines touch everything');
}

/* the instruments the reader operates: their own gates must be real ──────────── */
{
  const inl = html.match(/<script>\n([\s\S]*?)<\/script>\n<\/body>/)[1];
  /* the withhold gate. It says the instruments are withheld, so they must be. */
  for (const fn of ['function redraw() {\n      if (HALT) return;',
                    'function toggleAt(p) {\n      if (HALT) return;',
                    'function runCensus(N, done) {\n      if (HALT) return;'])
    ok(inl.includes(fn), `the withhold gate stops ${fn.slice(9, fn.indexOf('('))}() from recomputing and reporting`);
  ok((inl.match(/if \(HALT\) return;/g) || []).length >= 8,
    `and every reader-facing entry point checks it (${(inl.match(/if \(HALT\) return;/g) || []).length} guards)`);
  for (const id of ['clear', 'randsym', 'best', 'cols', 'rows', 'sym', 'voc', 'cbound', 'srun', 'crun'])
    ok(new RegExp(`'${id}'`).test(inl.slice(inl.indexOf('function withhold()'), inl.indexOf('function withhold()') + 700)),
      `withhold() disables the ${id} control, not only the two run buttons`);
  /* the reader-facing cross-check must sample the space rather than firing once at it = 0 */
  ok(!/crossCheckEvery: 99[0-9]/.test(inl), 'the search instrument no longer uses a fixed stride that fires only on the empty wall set');
  ok(/Math\.max\(1, Math\.floor\(plan0\.total \/ 200\)\)/.test(inl),
    'it sizes the stride from the space, so engine B is run on about 200 members of whatever the reader picked');
  /* the a + b odd branch must read the walk, like its sibling */
  ok(!/and indeed both parities turn up/.test(inl),
    'and the a + b odd readout is computed from the walk rather than printed unconditionally');
  ok(/res\.parities\.length === 2 \? 'both parities/.test(inl), 'it consults res.parities to say so');
  /* the refusal path speaks the same number format as the rest of the page */
  ok(/'a space of ' \+ fmt\(exact\) \+ ' exceeds the ceiling of ' \+ fmt\(CAP\)/.test(inl),
    'the refusal message formats its numbers like every other figure on the page, from the exact BigInt size');
}

/* the observed regularity that is NOT claimed */
{
  const d = walkSpace(4, 4, 'diag', 'edge');
  ok(d.ok && d.mono === 0, `the diagonal mirror on the 4 by 4 also reaches no single line in its ${fmt(d.space)} sets, which the page reports as observed and does not claim`);
  ok(RENDERED.includes('reported as observed and is not claimed'), 'and the page says so in those words');
  ok(RENDERED.includes('can be read two ways, so the page settles both'),
    'the page names the ambiguity in the quoted exercise rather than choosing the reading that suits it');
  ok(RENDERED.includes('Read at its loosest, as any symmetry at all, it does have answers'),
    'and it states plainly that the loose reading of the exercise DOES have answers');
}

console.log('== the engine the reader actually runs ==');
/*  The checks above use this file's own model. If the page's engine were broken the prose
    could still match, so: lift build/traceA/countB straight out of the shipped HTML, run
    them here, and require them to agree with the model on a battery of wall sets. */
{
  const inline = html.match(/<script>\n([\s\S]*?)<\/script>\n<\/body>/);
  ok(inline !== null, 'the page carries exactly one inline instrument script');
  if (inline) {
    const src = inline[1];
    const lift = (name) => {
      const i = src.indexOf('function ' + name + '(');
      if (i < 0) return null;
      let depth = 0;
      for (let k = src.indexOf('{', i); k < src.length; k++) {
        if (src[k] === '{') depth++;
        else if (src[k] === '}') { depth--; if (depth === 0) return src.slice(i, k + 1); }
      }
      return null;
    };
    /* the page's own number formatter, lifted and made to fail. A refused space can be far
       beyond what a double holds; grouping an exponent into thousands prints gibberish. */
    {
      const fsrc = lift('fmt');
      ok(fsrc !== null, 'the page formatter fmt() was located');
      if (fsrc) {
        const F = new Function('return (' + fsrc.replace(/^function fmt/, 'function') + ')')();
        ok(F(729) === '729' && F(1200000) === '1,200,000' && F(979) === '979',
          'it groups plain integers the way the prose does');
        ok(F(1.2379400392853803e+27) === '1.2379400392853803e+27',
          'and it leaves a value that prints as an exponent alone instead of grouping it into gibberish');
        ok(F(BigInt('1152921504606846976')) === '1,152,921,504,606,846,976',
          'and it groups a BigInt exactly, which is how the refusal path states a space too big for a double');
      }
      ok(/exact \*= BigInt\(o\.length\)/.test(src) && /'a space of ' \+ fmt\(exact\)/.test(src),
        'and the refusal path sizes the space with BigInt, so the number it prints is the true one');
    }

    const parts = ['build', 'traceA', 'countB'].map(lift);
    ok(parts.every(Boolean), 'the page engine functions build, traceA and countB were located in it');
    if (parts.every(Boolean)) {
      const mk = new Function('return (function(){ var NONE=0,V=1,H=2,DX=[1,1,-1,-1],DY=[1,-1,1,-1];'
        + parts.join('\n') + '\nreturn {build:build,traceA:traceA,countB:countB};})()');
      const P = mk();
      let disagreeA = 0, disagreeB = 0, pathsBad = 0, tried = 0, seed = 987654321;
      const rnd = () => (seed = (seed * 1103515245 + 12345) & 0x7fffffff);
      for (const [a, b] of [[1, 1], [2, 2], [3, 3], [4, 4], [5, 4], [6, 3], [7, 4], [1, 6], [5, 5]]) {
        const gm = grid(a, b), gp = P.build(a, b);
        for (let t2 = 0; t2 < 30; t2++) {
          const w = new Int8Array(gm.pts.length);
          if (t2 > 0) for (const q of gm.internal) w[q] = rnd() % 3;
          const mine = linesByRay(gm, w);
          const wp = new Int8Array(gp.pts.length);
          /* the two builds index waypoints the same way, which is itself checked here */
          for (let q = 0; q < w.length; q++) wp[q] = w[q];
          const theirs = P.traceA(gp, wp, true);
          if (theirs.n !== mine) disagreeA++;
          if (P.countB(gp, wp) !== mine) disagreeB++;
          if (theirs.paths.length !== theirs.n) pathsBad++;
          tried++;
        }
      }
      ok(tried === 270 && disagreeA === 0,
        `the page's own ray engine agrees with this file's model on all ${tried} wall sets across nine grids (${disagreeA} disagreements)`);
      ok(disagreeB === 0, `and the page's own pairing engine agrees too (${disagreeB} disagreements)`);
      ok(pathsBad === 0, `and the page draws exactly one closed path per line (${pathsBad} exceptions), so two lines are never painted as one`);
      /* control on that control: a deliberately altered copy of the page engine must be caught */
      const broken = parts.join('\n').replace('if (g.isBX[q] || w === V) dx = -dx;', 'if (g.isBX[q]) dx = -dx;');
      ok(broken !== parts.join('\n'), 'the control could find the line it needed to break in the page engine');
      const Q = new Function('return (function(){ var NONE=0,V=1,H=2,DX=[1,1,-1,-1],DY=[1,-1,1,-1];'
        + broken + '\nreturn {build:build,traceA:traceA};})()')();
      let caught = 0, seen2 = 0;
      for (const [a, b] of [[3, 3], [4, 4], [5, 4]]) {
        const gm = grid(a, b), gq = Q.build(a, b);
        for (let t2 = 1; t2 <= 20; t2++) {
          const w = new Int8Array(gm.pts.length);
          for (const q of gm.internal) w[q] = rnd() % 3;
          const wq = new Int8Array(gq.pts.length);
          for (let q = 0; q < w.length; q++) wq[q] = w[q];
          seen2++;
          if (Q.traceA(gq, wq, false).n !== linesByRay(gm, w)) caught++;
        }
      }
      ok(caught > 0, `control on the control: a page engine with one wall rule deleted disagrees with the model on ${caught} of ${seen2} wall sets, so this comparison can go red`);
    }
  }
}

console.log('== the second language ==');
{
  let cross = null;
  try {
    const out = execFileSync('python3', [CROSS], { encoding: 'utf8', timeout: 300000 });
    cross = JSON.parse(out);
  } catch (e) {
    skip('python3 unavailable or the cross-check failed to run: ' + (e && e.message ? e.message.split('\n')[0] : e));
  }
  if (cross) {
    let bad = 0;
    const cmp = (name, a, b) => { if (JSON.stringify(a) !== JSON.stringify(b)) { bad++; console.log(`     python disagrees on ${name}: node ${JSON.stringify(a)} python ${JSON.stringify(b)}`); } };
    cmp('bareGridMismatches', 0, cross.bareGridMismatches);
    {
      let mono = 0;
      for (let a = 1; a <= cross.bareGridBound; a++) for (let b = 1; b <= cross.bareGridBound; b++) {
        const g = grid(a, b);
        if (linesByRay(g, new Int8Array(g.pts.length)) === 1) mono++;
      }
      cmp('bareGridMonolinear', mono, cross.bareGridMonolinear);
      cmp('totientClosedForm', mono, cross.totientClosedForm);
    }
    cmp('workedCases', { '2x2': 2, '4x2': 2, '5x2': 1, '6x2': 2, '6x3': 3 }, cross.workedCases);
    const pick = (r) => ({ space: r.space, orbits: r.orbits, mono: r.mono, minComponents: r.minComponents, atMin: r.atMin, minWallsMono: r.minWallsMono, parities: r.parities, dist: r.dist });
    cmp('c4_4x4_both', pick(s44), pick(cross.c4_4x4_both));
    cmp('c4_4x4_edge', pick(s44e), pick(cross.c4_4x4_edge));
    cmp('c4_3x3_both', pick(s33), pick(cross.c4_3x3_both));
    cmp('c2_4x4_edge', pick(walkSpace(4, 4, 'c2', 'edge')), pick(cross.c2_4x4_edge));
    cmp('mirror_4x4_edge', pick(m44), pick(cross.mirror_4x4_edge));
    cmp('diag_4x4_edge', pick(walkSpace(4, 4, 'diag', 'edge')), pick(cross.diag_4x4_edge));
    cmp('free_3x3_edge', pick(walkSpace(3, 3, 'none', 'edge')), pick(cross.free_3x3_edge));
    for (const [k, v] of Object.entries(cross.halfTurnParity)) {
      const [a, b] = k.split('x').map(Number);
      const r = walkSpace(a, b, 'c2', 'edge');
      cmp(`halfTurnParity ${k}`, { parities: r.parities, mono: r.mono }, { parities: v.parities, mono: v.mono });
    }
    for (const [k, v] of Object.entries(cross.minWallsFree)) {
      const [a, b] = k.split('x').map(Number);
      cmp(`minWallsFree ${k}`, minWallsFree(a, b), v);
    }
    cmp('refusal', true, cross.refusal.refused === true);
    ok(bad === 0, `the Python re-run of the protocol agrees with Node on every compared field (${bad} disagreements)`);
  }
}

console.log('== the shipped files ==');
{
  ok(html.trimEnd().endsWith('-->') && html.includes('</script>\n</body>\n</html>'), 'the closing </script></body></html> are present');
  const ld = html.match(/<script type="application\/ld\+json">([\s\S]*?)<\/script>/);
  let obj = null;
  try { obj = JSON.parse(ld[1]); } catch (e) { obj = null; }
  ok(obj !== null, 'the JSON-LD block parses as JSON');
  ok(obj && obj['@type'] === 'Article' && obj.datePublished === '2026-08-30' && obj.dateModified === '2026-08-30',
    'the JSON-LD is an Article dated 2026-08-30 in both fields');
  ok(obj && obj.url === `https://artwaste.land/strata/${SLUG}/`, 'its url matches the canonical slug');
  const canon = html.match(/<link rel="canonical" href="([^"]+)"/);
  ok(canon && canon[1] === `https://artwaste.land/strata/${SLUG}/`, 'the canonical link matches');

  /* ── the shareable surface ────────────────────────────────────────────────────────
     Every figure quoted on a surface a reader meets before the page is checked two ways:
     it must APPEAR (nothing silently dropped) and it must be DRAWN FROM the set of values
     recomputed in this run (nothing silently added). The second half is what a presence
     check cannot do, and it is what catches an invented figure. */
  const NUMERALS = /\d[\d,.]*\d|\d/g;
  const allowed = new Set([
    '1,600', String(census40.mono), census40.pi.toFixed(4),
    String(s44.space), String(m44.mono), String(s44e.space), String(s33.space),
    fmt(s55.space), fmt(s55.mono), fmt(m44.space), fmt(s44h.space),
    '4', '2', '3', /* grid sizes named in words elsewhere: 4x4, two, three */
  ]);
  function surfaceFigures(label, text) {
    const found = (text.match(NUMERALS) || []);
    const stray = found.filter((t) => !allowed.has(t));
    ok(stray.length === 0,
      `every figure on ${label} is one this run recomputed (${found.length} numerals, ${stray.length} not recomputed)`,
      stray.length ? { stray, allowed: [...allowed] } : undefined);
  }

  const desc = html.match(/<meta name="description" content="([^"]*)"/)[1];
  surfaceFigures('the meta description', desc);
  ok(desc.includes('1,600') && desc.includes('729') && desc.includes('even number of lines'),
    'the meta description carries the census bound, the headline space and the parity result');
  ok(!/discover|first|new theorem|never before|unprecedented|nobody has|no one has|novel/i.test(desc),
    'and it makes no novelty claim');
  /* the honesty that must survive every later edit: the shareable surface must not present
     the fourfold reading as the only one, and must not call a Word-to-PDF handout published. */
  ok(!/published lecture/i.test(desc), 'the meta description does not call the lecture handout published');
  ok(!/no such drawing exists/i.test(desc) && !/the exercise (is )?impossible/i.test(desc),
    'and it does not say flatly that the exercise has no answer, which would be false under the reading the page itself shows has 512 of them');
  ok(desc.includes('512') && /loose|mirror/i.test(desc),
    'and it names the other reading and its 512 answers on the same surface');

  const og = html.match(/<meta property="og:description" content="([^"]*)"/)[1];
  const tw = html.match(/<meta name="twitter:description" content="([^"]*)"/)[1];
  surfaceFigures('the og:description', og);
  surfaceFigures('the twitter:description', tw);
  for (const [n, t] of [['og:description', og], ['twitter:description', tw]]) {
    ok(!/no such drawing exists|published lecture/i.test(t), `the ${n} makes neither overstatement`);
    ok(/a symmetry can make one line impossible/i.test(t), `the ${n} hedges the impossibility to a symmetry rather than to the exercise`);
  }
  ok(obj && !/no such drawing exists|published lecture/i.test(obj.description), 'nor does the JSON-LD description');
  surfaceFigures('the JSON-LD description', obj ? obj.description : '');

  const fm = fs.readFileSync(FM, 'utf8');
  ok(/^---\n/.test(fm), 'the frontmatter file opens with a YAML fence');
  ok(/\ndate: 2026-08-30\n/.test(fm), 'date: 2026-08-30');
  ok(/\ndraft: false\n/.test(fm), 'draft: false');
  ok(/\nseam: "pattern"\n/.test(fm), 'seam: pattern');
  ok(/"immersive"/.test(fm) && /"interactive"/.test(fm), 'tags include immersive and interactive');
  ok(new RegExp(`\\nhref: "/strata/${SLUG}/"\\n`).test(fm), 'href points at this page');

  const plain = fm.match(/\nplain: "([^"]*)"\n/);
  ok(plain !== null, 'the plain placard is a double-quoted scalar on one line with no inner double quote');
  if (plain) {
    const p = plain[1];
    ok(p.length >= 90 && p.length <= 420, `the placard is ${p.length} characters, inside 90 to 420`);
    ok((p.match(/[.!?](\s|$)/g) || []).length <= 3, 'the placard is at most three sentences');
    ok(!p.includes(EMDASH), 'the placard carries no em dash');
    ok(p.includes('729') && RENDERED.includes('729'), 'the number in the placard, 729, is a figure this verifier computed and the page displays');
  }
  const dek = fm.match(/\ndek: "([^"]*)"\n/);
  ok(dek !== null, 'the dek is a double-quoted scalar on one line');
  if (dek) {
    const d = dek[1];
    surfaceFigures('the dek', d);
    ok(d.includes('1,600') && d.includes('979') && d.includes('3.1314') && d.includes('729'),
      'the dek carries the census bound, the monolinear count, pi and the headline space');
    ok(census40 && d.includes(String(census40.mono)) && d.includes(census40.pi.toFixed(4)),
      'and those figures equal what was computed here just now');
    ok(/could not obtain that paper/.test(d)
       && !/we discovered|new theorem|for the first time|unprecedented|nobody has|no one has/i.test(d),
      'and the dek disclaims novelty rather than claiming it');
    /* the reading of the exercise, on the surface a reader meets first */
    ok(d.includes('another symmetrical arrangement'),
      'the dek quotes what the lecture actually asked for rather than paraphrasing it as fourfold');
    ok(/Read that way/.test(d) && /Read loosely/.test(d) && d.includes('512 answers'),
      'and it names BOTH readings on its own face, including the one that has 512 answers');
    ok(!/published lecture/i.test(d) && /lecture handout/.test(d),
      'and it calls the source a lecture handout, which is what it is');
    ok(!/no such drawing exists/i.test(d), 'and it does not say flatly that no such drawing exists');
    ok(!/no shared code path/.test(d) && /shar(?:e|ing) only the lattice/.test(d),
      'and its claim about the two engines is the true one: they share build(), and only that');
  }

  const rel = [...fm.matchAll(/\n {2}- to: ([a-z0-9-]+)\n/g)].map((m) => m[1]);
  ok(rel.length >= 2 && rel.length <= 4, `there are ${rel.length} relates edges, between 2 and 4`);
  for (const r of rel) ok(fs.existsSync(path.join(ROOT, 'src', 'content', 'strata', r + '.md')), `relates target exists on disk: ${r}`);
  ok([...fm.matchAll(/\n {4}note: "/g)].length === rel.length, 'every relates edge is an object with a note');

  const SELF = fileURLToPath(import.meta.url);
  for (const [name, file] of [['the page', PAGE], ['the frontmatter', FM], ['the README', README], ['the cross-check', CROSS], ['this verifier', SELF]]) {
    if (!fs.existsSync(file)) { ok(false, `${name} exists at ${file}`); continue; }
    const t = fs.readFileSync(file, 'utf8');
    ok(!t.includes(EMDASH), `${name} contains no em dash`);
  }
  /* the working notes are where a supervisor looks first, so the reading of the exercise has
     to be right there too. This is the sentence that shipped wrong and must not come back. */
  {
    const rd = fs.readFileSync(README, 'utf8');
    ok(/Read strictly, as another C4\s+arrangement, it has \*\*no answer\*\*/.test(rd.replace(/\s+/g, ' ').replace(/ /g, ' ')) || /Read strictly, as another C4 arrangement, it has \*\*no answer\*\*/.test(rd.replace(/\s+/g, ' ')),
      'the README states the strict reading and calls it the one with no answer');
    ok(/Read loosely, as any symmetry at all, it \*\*does\*\* have/.test(rd.replace(/\s+/g, ' ')),
      'and states that the loose reading does have answers');
    ok(/neither the page nor this file may say the exercise is simply impossible/.test(rd.replace(/\s+/g, ' ')),
      'and records why, so the claim cannot quietly come back');
    ok(!/exercise, which invites the reader to build a symmetric monolinear 4 by 4, has no answer/.test(rd.replace(/\s+/g, ' ')),
      'and the unqualified version of that sentence is gone from the README');
    ok(/Bridges 2009, 305-308/.test(rd) && !/305-312/.test(rd), 'and its source table gives the Bridges 2009 range the artefact has');
  }
  ok(!/cdn|googleapis|unpkg|jsdelivr|http:\/\/(?!www\.w3)/i.test(html.replace(/https:\/\/artwaste\.land/g, '').replace(/https:\/\/(web\.njit\.edu|archive\.bridgesmathart\.org|schema\.org)/g, '')),
    'the page makes no third-party request');
}

console.log('');
console.log(`${passed} passed, ${failed} failed, ${skipped} skipped.`);
if (failed) { console.log('VERIFICATION FAILED'); process.exit(1); }
console.log('VERIFICATION PASSED');
