#!/usr/bin/env node
// verify.mjs: the check behind /strata/every-edge-but-one/, runnable by a stranger with nothing but Node (18 or later).
//
//   node verify.mjs              reads the data from this repository if it is here, else downloads it from artwaste.land
//   node verify.mjs --remote     always downloads it from https://artwaste.land/strata/every-edge-but-one/
//   node verify.mjs --full       also runs the 32,653-graph control and the checks that go with it (a few minutes)
//   node verify.mjs --plant X    plants fault X first; every plant must turn this red (mutate.mjs runs them all)
//
// What each part would catch if the page were wrong:
//   A. The list. 398 graph6 strings decode to 74 on four to nine vertices and 324 on ten, with the per-order counts of
//      OEIS A308349 (0, 0, 0, 1, 1, 1, 3, 13, 55, then 324); every one has no cut vertex; and no member is contained in
//      another (a list of minimal graphs must be an antichain, so this also catches a duplicate under relabelling).
//      The statistics the page prints (edges, degrees, certificate types of the 324) are recounted.
//   B. The drawings. Every one of the 6,398 one-edge drawings, and every default drawing, has each remaining edge at
//      length 1 to 1e-9 and no two points closer than 1e-3. A drawing that cheats on one edge goes red.
//   C. The proofs. A proof checker written here, sharing no code with the page's engine.mjs, reads each of the 182
//      proofs and checks every relation against the graph and every weighted sum exactly, in (p + q w) with p, q
//      rational. Each proof must also FAIL against every one-edge deletion of its graph (2,840 cases), because those
//      deletions can be drawn: a checker that passed one of them would be unsound.
//   D. The engine. The page's own engine.mjs, downloaded, must refute exactly the 182 graphs that carry proofs, and
//      none of the 14,008 drawable graphs on at most nine vertices (all graphs avoiding the 74, counted against OEIS
//      A350507, and checked here to avoid them); with --full, none of the 32,653 ten-vertex graphs the search drew.
//   E. The Petersen drawing is exact to 1e-11 and is the Petersen graph (3-regular, girth 5, ten vertices).
//   F. The bounds. Exact coordinate counts anchor u(23) = 64 and u(24) = 68. Schade's lemma gives the new bounds
//      from 24, the dated September chain from 22, and AMP's unchanged printed bounds.
//   G. The page says what this found: the figures in its prose equal the ones recomputed here.
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import vm from 'node:vm';

const args = process.argv.slice(2);
const FULL = args.includes('--full');
const REMOTE = args.includes('--remote');
const PLANT = args.includes('--plant') ? args[args.indexOf('--plant') + 1] : null;
const BASE = args.includes('--base') ? args[args.indexOf('--base') + 1] : 'https://artwaste.land/strata/every-edge-but-one/';
const HERE = path.dirname(fileURLToPath(import.meta.url));
const LOCAL = path.resolve(HERE, '..', '..', 'public', 'strata', 'every-edge-but-one');
const useLocal = !REMOTE && fs.existsSync(path.join(LOCAL, 'data', 'the-398.json'));
const option = (name) => args.includes(name) ? args[args.indexOf(name) + 1] : null;
const copiedFile = (name) => {
  const value = option(name); if (!value) return null;
  const root = path.resolve(LOCAL, '../../..'), file = path.resolve(value);
  if (!useLocal || !file.startsWith(root + path.sep)) throw new Error(`${name} must name a copy inside this repository`);
  return fs.readFileSync(file, 'utf8');
};

let pass = 0, fail = 0;
const ok = (c, m) => { if (c) { pass++; console.log('  ok   ' + m); } else { fail++; console.log('  FAIL ' + m); } };
async function get(rel) {
  if (useLocal) return fs.readFileSync(path.join(LOCAL, rel), 'utf8');
  const r = await fetch(new URL(rel, BASE)); if (!r.ok) throw new Error(`${rel}: HTTP ${r.status}`); return r.text();
}
async function sibling(slug, rel) {
  if (useLocal) return fs.readFileSync(path.join(LOCAL, '..', slug, rel), 'utf8');
  const r = await fetch(new URL(`../${slug}/${rel}`, BASE));
  if (!r.ok) throw new Error(`${slug}/${rel}: HTTP ${r.status}`); return r.text();
}
// Direct radical multiplication, independent of either new page's squared-distance formula.
function exactUnits(lattice) {
  const mul = (x, y) => {
    const out = Array(4).fill(0n);
    for (let i = 0; i < 4; i++) for (let j = 0; j < 4; j++) out[i ^ j] += x[i] * y[j] * ((i & j & 1) ? 3n : 1n) * ((i & j & 2) ? 11n : 1n);
    return out;
  };
  let units = 0;
  for (let i = 0; i < lattice.length; i++) for (let j = i + 1; j < lattice.length; j++) {
    const [a, b, c, d] = lattice[i].map((x, k) => BigInt(x) - BigInt(lattice[j][k]));
    const x = [12n * a + 6n * b + 10n * c + 5n * d, 0n, 0n, -d], y = [0n, 6n * b + 5n * d, 2n * c + d, 0n];
    const xx = mul(x, x), yy = mul(y, y), q = xx.map((v, k) => v + yy[k]);
    if (q[0] === 144n && q.slice(1).every(v => v === 0n)) units++;
  }
  return units;
}
// where the data came from goes to stderr, so the output is identical whether it ran in the repository or from nothing
console.error(`every-edge-but-one verify: reading ${useLocal ? 'the repository copy' : BASE}${PLANT ? ` (planted fault: ${PLANT})` : ''}`);

// ---------- graphs ----------
function decode(s) {
  const n = s.charCodeAt(0) - 63; if (n < 1 || n > 62) throw new Error('bad graph6 ' + s);
  const adj = new Array(n).fill(0); const edges = []; let bit = 0;
  const bits = []; for (const ch of s.slice(1)) { const v = ch.charCodeAt(0) - 63; for (let k = 5; k >= 0; k--) bits.push((v >> k) & 1); }
  for (let j = 1; j < n; j++) for (let i = 0; i < j; i++) { if (bits[bit++]) { adj[i] |= 1 << j; adj[j] |= 1 << i; edges.push([i, j]); } }
  edges.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
  return { n, adj, edges, m: edges.length };
}
const popc = (x) => { let c = 0; while (x) { x &= x - 1; c++; } return c; };
function connectedWithout(G, drop) {
  const start = drop === 0 ? 1 : 0; let seen = 1 << start, stack = [start];
  while (stack.length) { const v = stack.pop(); let nb = G.adj[v] & ~seen & ~(drop >= 0 ? 1 << drop : 0); while (nb) { const w = 31 - Math.clz32(nb & -nb); nb &= nb - 1; seen |= 1 << w; stack.push(w); } }
  return popc(seen) === G.n - (drop >= 0 ? 1 : 0);
}
const biconnected = (G) => G.n >= 3 && connectedWithout(G, -1) && [...Array(G.n).keys()].every((v) => connectedWithout(G, v));
// is P a subgraph of H (injective, edges to edges)?
function contains(H, P) {
  if (P.n > H.n || P.m > H.m) return false;
  const order = [...Array(P.n).keys()].sort((a, b) => popc(P.adj[b]) - popc(P.adj[a]));
  const map = new Array(P.n).fill(-1); let used = 0;
  const degH = H.adj.map(popc);
  function go(k) {
    if (k === P.n) return true;
    const v = order[k], dv = popc(P.adj[v]);
    for (let w = 0; w < H.n; w++) {
      if (used & (1 << w) || degH[w] < dv) continue;
      let good = true;
      for (let j = 0; j < k; j++) { const u = order[j]; if (P.adj[v] & (1 << u) && !(H.adj[w] & (1 << map[u]))) { good = false; break; } }
      if (!good) continue;
      map[v] = w; used |= 1 << w;
      if (go(k + 1)) return true;
      map[v] = -1; used &= ~(1 << w);
    }
    return false;
  }
  return go(0);
}
function girth(G) {
  let best = Infinity;
  for (let s = 0; s < G.n; s++) {
    const dist = new Array(G.n).fill(-1), par = new Array(G.n).fill(-1); dist[s] = 0; const q = [s];
    while (q.length) { const v = q.shift(); for (let w = 0; w < G.n; w++) if (G.adj[v] & (1 << w)) { if (dist[w] < 0) { dist[w] = dist[v] + 1; par[w] = v; q.push(w); } else if (par[v] !== w) best = Math.min(best, dist[v] + dist[w] + 1); } }
  }
  return best;
}

// ---------- (p + q w) / 1 with p, q rational, w = e^(i pi/3), w^2 = w - 1: written independently of engine.mjs ----------
const gcd = (a, b) => { a = a < 0n ? -a : a; b = b < 0n ? -b : b; while (b) [a, b] = [b, a % b]; return a; };
const R = (n, d = 1n) => { if (d < 0n) { n = -n; d = -d; } const g = gcd(n, d) || 1n; return [n / g, d / g]; };
const radd = (x, y) => R(x[0] * y[1] + y[0] * x[1], x[1] * y[1]);
const rmul = (x, y) => R(x[0] * y[0], x[1] * y[1]);
const rneg = (x) => [-x[0], x[1]];
const Q = (p, q = R(0n)) => ({ p, q });                     // p + q w
const q0 = Q(R(0n)), q1 = Q(R(1n)), qw = Q(R(0n), R(1n)), qwb = Q(R(1n), R(-1n));
const qadd = (a, b) => Q(radd(a.p, b.p), radd(a.q, b.q));
const qneg = (a) => Q(rneg(a.p), rneg(a.q));
const qmul = (a, b) => { const pq = rmul(a.q, b.q); return Q(radd(rmul(a.p, b.p), rneg(pq)), radd(radd(rmul(a.p, b.q), rmul(a.q, b.p)), pq)); };
const qzero = (a) => a.p[0] === 0n && a.q[0] === 0n;
const qeq = (a, b) => qzero(qadd(a, qneg(b)));
const qparse = (s) => { const [A, B, D] = s.split(',').map((t) => BigInt(t)); return Q(R(A, D), R(B, D)); };
const normIsOne = (a) => { const [pn, pd] = a.p, [qn, qd] = a.q; // p^2 + pq + q^2 = 1
  const t = radd(radd(rmul(a.p, a.p), rmul(a.p, a.q)), rmul(a.q, a.q)); void pn; void pd; void qn; void qd; return t[0] === t[1]; };

function checkProof(G, proof) {
  const n = G.n; const key = (a, b) => (a < b ? `${a}-${b}` : `${b}-${a}`);
  const vec = () => new Array(n).fill(q0);
  function relation(g, E, orient) {
    const v = vec();
    if (g[0] === 'R') {
      const [, a, b, c, d] = g;
      if (new Set([a, b, c, d]).size !== 4 || [a, b, c, d].some((x) => !(x >= 0 && x < n))) throw new Error('rhombus: bad vertices');
      for (const [x, y] of [[a, b], [b, c], [c, d], [d, a]]) if (!E.has(key(x, y))) throw new Error(`rhombus ${a}-${b}-${c}-${d}: ${x}-${y} is not an edge`);
      v[a] = qadd(v[a], q1); v[c] = qadd(v[c], q1); v[b] = qadd(v[b], qneg(q1)); v[d] = qadd(v[d], qneg(q1)); // z_a + z_c - z_b - z_d
      return v;
    }
    if (g[0] === 'T') {
      const [, a, b, c, s] = g;
      if (!(a < b && b < c && a >= 0 && c < n)) throw new Error('triangle: bad vertices');
      for (const [x, y] of [[a, b], [b, c], [a, c]]) if (!E.has(key(x, y))) throw new Error(`triangle ${a},${b},${c}: ${x}-${y} is not an edge`);
      if (orient.get(`${a},${b},${c}`) !== s) throw new Error(`triangle ${a},${b},${c}: orientation ${s} not fixed on this path`);
      const t = s === 1 ? qw : s === -1 ? qwb : null; if (!t) throw new Error('triangle: s must be +1 or -1');
      v[c] = qadd(v[c], q1); v[b] = qadd(v[b], qneg(t)); v[a] = qadd(v[a], qadd(t, qneg(q1))); // z_c - z_a - t (z_b - z_a)
      return v;
    }
    throw new Error('unknown relation ' + g[0]);
  }
  function total(comb, E, orient) {
    const v = vec();
    for (const [g, c] of comb) { const r = relation(g, E, orient), k = qparse(c); for (let i = 0; i < n; i++) v[i] = qadd(v[i], qmul(k, r[i])); }
    return v;
  }
  function target(a, b, u, v, zeta) {
    const t = vec(); t[a] = qadd(t[a], q1); t[b] = qadd(t[b], qneg(q1));
    if (u !== undefined) { t[u] = qadd(t[u], qneg(zeta)); t[v] = qadd(t[v], zeta); }
    return t;
  }
  const same = (x, y) => x.every((e, i) => qeq(e, y[i]));
  function walk(nd, E, orient, first) {
    E = new Set(E);
    for (const l of nd.lemmas || []) {
      const [a, b] = l.edge, [u, v] = l.via, z = qparse(l.zeta);
      if (a === b || E.has(key(a, b))) throw new Error(`lemma ${a}-${b}: already an edge`);
      if (!E.has(key(u, v))) throw new Error(`lemma ${a}-${b}: ${u}-${v} is not an edge`);
      if (!normIsOne(z)) throw new Error(`lemma ${a}-${b}: |zeta| != 1`);
      if (!same(total(l.comb, E, orient), target(a, b, u, v, z))) throw new Error(`lemma ${a}-${b}: sum is wrong`);
      E.add(key(a, b));
    }
    if (nd.end) {
      const e = nd.end;
      if (e.type === 'collision') { const [a, b] = e.pair; if (a === b) throw new Error('self collision'); if (!same(total(e.comb, E, orient), target(a, b))) throw new Error('collision: sum is wrong'); return 1; }
      if (e.type === 'length') {
        const [a, b] = e.edge, [u, v] = e.via, z = qparse(e.zeta);
        if (!E.has(key(a, b)) || !E.has(key(u, v))) throw new Error('length: not edges');
        if (normIsOne(z)) throw new Error('length: |zeta| = 1');
        if (!same(total(e.comb, E, orient), target(a, b, u, v, z))) throw new Error('length: sum is wrong');
        return 1;
      }
      throw new Error('unknown ending');
    }
    if (!nd.split) throw new Error('node with no ending and no split');
    const [a, b, c] = nd.split.tri, k = `${a},${b},${c}`;
    if (!(a < b && b < c) || ![[a, b], [b, c], [a, c]].every(([x, y]) => E.has(key(x, y)))) throw new Error('split on a non-triangle');
    if (orient.has(k)) throw new Error('split on an oriented triangle');
    const needed = nd.split.mirror ? ['+1'] : ['+1', '-1'];
    if (nd.split.mirror && !first) throw new Error('reflection used below the root');
    const cs = nd.split.cases || {};
    if (Object.keys(cs).length !== needed.length || !needed.every((x) => cs[x])) throw new Error('cases missing');
    let leaves = 0;
    for (const x of needed) { const o = new Map(orient); o.set(k, x === '+1' ? 1 : -1); leaves += walk(cs[x], E, o, false); }
    return leaves;
  }
  try { walk(proof, new Set(G.edges.map(([a, b]) => key(a, b))), new Map(), true); return null; } catch (e) { return e.message; }
}

// ---------- read everything ----------
const D = JSON.parse(await get('data/the-398.json'));
let L = D.graphs;
const DEL = JSON.parse(await get('data/deletions.json')).graphs;
const PET = JSON.parse(await get('data/petersen.json'));
const LE9 = (await get('data/controls-le9.g6')).trim().split('\n');
const B10 = (await get('data/controls-b10.g6')).trim().split('\n');
let engineSrc = await get('engine.mjs');
let PAGE = copiedFile('--page') ?? await get('index.html');
let APP = copiedFile('--app') ?? await get('app.mjs');
if (PLANT === 'new-chain') APP = APP.replace('const up = { 24: 68 }', 'const up = { 24: 69 }');
// a figure changed in the sentence that states it, and left true in the printed transcript below it
if (PLANT === 'prose') PAGE = PAGE.replace('33,162 avoid all 74', '33,163 avoid all 74');

// plants: each must make this script fail
if (PLANT === 'drop') L = L.slice(1);
if (PLANT === 'dup') { const g = L[L.length - 1]; const G = decode(g.g6); const perm = [...Array(G.n).keys()].reverse(); const bits = []; for (let j = 1; j < G.n; j++) for (let i = 0; i < j; i++) bits.push(G.adj[perm[i]] & (1 << perm[j]) ? 1 : 0); while (bits.length % 6) bits.push(0); let s = String.fromCharCode(63 + G.n); for (let k = 0; k < bits.length; k += 6) s += String.fromCharCode(63 + parseInt(bits.slice(k, k + 6).join(''), 2)); L = [...L, { ...g, g6: s, i: L.length }]; }
if (PLANT === 'coord') DEL[200].drawings[3].xy[2][0] += 1e-6;
if (PLANT === 'coef') { const p = L.find((g) => g.proof && g.proof.end); p.proof.end.comb[0][1] = p.proof.end.comb[0][1].replace(/^(-?\d+)/, (m) => String(BigInt(m) + 1n)); }
if (PLANT === 'petersen') PET.xy[3][1] += 1e-7;
const ENGINE_PLANTS = {
  'engine-unit': ['const unit = isUnit(zeta), isEdge = adj[a][b];', 'const unit = true, isEdge = adj[a][b];'],
  'engine-nosplit': ['for (const s of mirror ? [1] : [1, -1]) {\n    const o2 = new Map(orient); o2.set(T[0], s);', 'for (const s of [1]) {\n    const o2 = new Map(orient); o2.set(T[0], s);'],
  'engine-rhombus': ['v[u] = add(v[u], ONE); v[p] = sub(v[p], ONE); v[w] = add(v[w], ONE); v[x] = sub(v[x], ONE);', 'v[u] = add(v[u], ONE); v[p] = add(v[p], ONE); v[w] = sub(v[w], ONE); v[x] = sub(v[x], ONE);'],
  'engine-length': ['if (isEdge && !unit) contra.push(', 'if (isEdge) contra.push('],
  'engine-norm': ['export const norm2 = (x) => [x[0] * x[0] + x[0] * x[1] + x[1] * x[1], x[2] * x[2]];', 'export const norm2 = (x) => [x[0] * x[0] + x[1] * x[1], x[2] * x[2]];'],
  'engine-angle': ['const wPow = (s) => (s > 0 ? W : WB);', 'const wPow = (s) => (s > 0 ? mul(W, W) : mul(WB, WB));'],
  'engine-parallel': ['for (let j = 0; j < n; j++) if (!eqq(dab[j], mul(zeta, duv[j]))) { par = false; break; }', ''],
};
if (PLANT && ENGINE_PLANTS[PLANT]) {
  const [from, to] = ENGINE_PLANTS[PLANT];
  if (!engineSrc.includes(from)) { console.log('  FAIL the plant does not match engine.mjs; it would test nothing'); process.exit(2); }
  engineSrc = engineSrc.split(from).join(to);
}
const E = await import('data:text/javascript;base64,' + Buffer.from(engineSrc).toString('base64'));

// ---------- A. the list ----------
console.log('A. the list');
const Gs = L.map((g) => ({ ...decode(g.g6), rec: g }));
const byN = {}; for (const G of Gs) byN[G.n] = (byN[G.n] || 0) + 1;
const A308349 = [0, 0, 0, 1, 1, 1, 3, 13, 55];
ok(Gs.length === 398, `398 graphs (${Gs.length})`);
ok(A308349.every((c, k) => (byN[k + 1] || 0) === c), `orders 1..9 match OEIS A308349: ${A308349.join(', ')} (${[...Array(9).keys()].map((k) => byN[k + 1] || 0).join(', ')})`);
ok(byN[10] === 324, `324 on ten vertices (${byN[10]})`);
ok(Gs.every((G, i) => G.m === L[i].m && G.n === L[i].n), 'every record\'s n and m agree with its graph6 string');
ok(Gs.every((G) => biconnected(G)), 'every graph has no cut vertex (a minimal forbidden graph cannot have one)');
let chains = 0, t0 = Date.now();
for (let i = 0; i < Gs.length; i++) for (let j = 0; j < Gs.length; j++) {
  if (i === j) continue; const P = Gs[i], H = Gs[j];
  if (P.n > H.n || P.m > H.m || (P.n === H.n && P.m === H.m && i > j)) continue;
  if (contains(H, P)) chains++;
}
ok(chains === 0, `no graph on the list contains another, so none is a relabelled copy of another (${chains} containments, ${((Date.now() - t0) / 1000).toFixed(1)} s)`);
const ten = Gs.filter((G) => G.n === 10);
const hist = (f) => { const h = {}; for (const G of ten) { const k = f(G); h[k] = (h[k] || 0) + 1; } return h; };
const same = (h, want) => Object.keys(want).length === Object.keys(h).length && Object.entries(want).every(([k, v]) => h[k] === v);
const byM = hist((G) => G.m), minD = hist((G) => Math.min(...G.adj.map(popc))), maxD = hist((G) => Math.max(...G.adj.map(popc))), cert = hist((G) => G.rec.cert);
ok(same(byM, { 15: 4, 16: 126, 17: 191, 18: 3 }), `the 324 by edges: 15: 4, 16: 126, 17: 191, 18: 3 (${JSON.stringify(byM)})`);
ok(same(minD, { 2: 124, 3: 200 }) && same(maxD, { 3: 1, 4: 145, 5: 145, 6: 30, 7: 3 }), `the 324 by degree: min 2: 124, 3: 200; max 3: 1, 4: 145, 5: 145, 6: 30, 7: 3`);
ok(same(cert, { tree: 103, 'real-dag': 97, 'null-dag': 65, real: 24, null: 22, tu: 13 }), `certificate types of the 324: tree 103, real-dag 97, null-dag 65, real 24, null 22, tu 13 (${JSON.stringify(cert)})`);
const M10 = Gs.find((G) => G.n === 10 && G.adj.every((a) => popc(a) === 3));
ok(!!M10 && ten.filter((G) => G.adj.every((a) => popc(a) === 3)).length === 1 && girth(M10) === 4, `exactly one of the 324 is 3-regular (${M10 && M10.rec.g6}), with 4-cycles, as the Möbius ladder has`);

// ---------- B. the drawings ----------
console.log('B. the drawings');
function measure(xy, edges, cut) {
  let worst = 0, gap = Infinity;
  for (const [a, b] of edges) { if (cut && ((a === cut[0] && b === cut[1]) || (a === cut[1] && b === cut[0]))) continue; worst = Math.max(worst, Math.abs(Math.hypot(xy[a][0] - xy[b][0], xy[a][1] - xy[b][1]) - 1)); }
  for (let i = 0; i < xy.length; i++) for (let j = i + 1; j < xy.length; j++) gap = Math.min(gap, Math.hypot(xy[i][0] - xy[j][0], xy[i][1] - xy[j][1]));
  return { worst, gap };
}
let dW = 0, dG = Infinity, nDraw = 0, badDraw = 0, missing = 0, defW = 0, defG = Infinity;
for (let i = 0; i < Gs.length; i++) {
  const G = Gs[i], rec = L[i];
  const m0 = measure(rec.xy, G.edges, rec.cut); defW = Math.max(defW, m0.worst); defG = Math.min(defG, m0.gap);
  const dels = (DEL.find((d) => d.g6 === rec.g6) || { drawings: [] }).drawings;
  if (dels.length !== G.m) { missing += G.m - dels.length; continue; }
  dels.forEach((d, k) => {
    if (!d) { missing++; return; }
    const e = G.edges[k];
    if (!(d.cut[0] === e[0] && d.cut[1] === e[1])) { badDraw++; return; }
    const r = measure(d.xy, G.edges, e); nDraw++; dW = Math.max(dW, r.worst); dG = Math.min(dG, r.gap);
    if (!(r.worst < 1e-9 && r.gap > 1e-3)) badDraw++;
  });
}
ok(defW < 1e-9 && defG > 1e-3, `398 default drawings: solid edges 1 to within ${defW.toExponential(1)}, points at least ${defG.toFixed(4)} apart`);
ok(missing === 0 && badDraw === 0 && nDraw === 6398, `every one-edge deletion drawn: ${nDraw} drawings, every remaining edge 1 to within ${dW.toExponential(1)}, points at least ${dG.toFixed(4)} apart (${missing} missing, ${badDraw} bad)`);
ok(Gs.reduce((s, G) => s + G.m, 0) === 6398, `the 398 have 6,398 edges between them, one drawing each`);

// ---------- C. the proofs ----------
console.log('C. the proofs, checked by code written here');
const proved = Gs.filter((G) => G.rec.proof);
let good = 0, whyBad = null;
for (const G of proved) { const why = checkProof(G, G.rec.proof); if (!why) good++; else whyBad ||= `${G.rec.g6}: ${why}`; }
ok(proved.length === 182 && good === 182, `182 proofs, every one checks exactly (${good} of ${proved.length})${whyBad ? ' first failure: ' + whyBad : ''}`);
let rej = 0, tried = 0;
for (const G of proved) for (let k = 0; k < G.m; k++) {
  const H = decode(G.rec.g6); const [a, b] = H.edges[k]; H.adj[a] &= ~(1 << b); H.adj[b] &= ~(1 << a); H.edges = H.edges.filter((_, j) => j !== k); H.m--;
  tried++; if (checkProof(H, G.rec.proof)) rej++;
}
ok(tried === 2840 && rej === tried, `against the wrong graph (the same graph minus one edge, which can be drawn) every proof fails: ${rej} of ${tried}`);
const byNp = {}; for (const G of proved) byNp[G.n] = (byNp[G.n] || 0) + 1;
ok([1, 1, 1, 2, 8, 27, 142].every((c, k) => byNp[k + 4] === c), `proved, by order 4..10: 1, 1, 1, 2, 8, 27, 142 (${[4, 5, 6, 7, 8, 9, 10].map((n) => byNp[n] || 0).join(', ')})`);
const agree = proved.every((G) => E.check(G.n, G.edges, G.rec.proof).ok);
ok(agree, 'the page\'s own checker (engine.mjs) agrees on all 182');

// ---------- D. the engine ----------
console.log('D. the engine the page runs');
t0 = Date.now();
const found = Gs.filter((G) => E.quickRefute(G.n, G.edges).refuted);
const sameSet = found.length === proved.length && found.every((G) => G.rec.proof);
ok(sameSet, `a fresh search refutes exactly the 182 that carry proofs (${found.length} refuted, ${((Date.now() - t0) / 1000).toFixed(1)} s)`);
const A350507 = [1, 2, 4, 10, 25, 85, 332, 1746, 11803];
const le9 = LE9.map(decode); const le9n = {}; for (const G of le9) le9n[G.n] = (le9n[G.n] || 0) + 1;
ok(le9.length === 14008 && A350507.every((c, k) => le9n[k + 1] === c), `14,008 control graphs on 1..9 vertices, as many per order as OEIS A350507 counts (${A350507.map((_, k) => le9n[k + 1] || 0).join(', ')})`);
const F74 = Gs.filter((G) => G.n <= 9);
let hits = 0; for (const H of le9) for (const P of F74) if (P.n <= H.n && contains(H, P)) { hits++; break; }
ok(hits === 0, `every control graph avoids all 74, so each can be drawn (Globus and Parshall's theorem): ${hits} contain one`);
t0 = Date.now(); let fp = 0; for (const G of le9) if (E.quickRefute(G.n, G.edges).refuted) fp++;
ok(fp === 0, `the engine refutes none of the 14,008 drawable graphs on at most nine vertices (${fp}, ${((Date.now() - t0) / 1000).toFixed(1)} s)`);
if (FULL) {
  const b10 = B10.map(decode);
  ok(b10.length === 32653 && b10.every((G) => G.n === 10 && biconnected(G)), `32,653 ten-vertex control graphs, each without a cut vertex`);
  let inside = 0; for (const H of b10) for (const P of Gs) if (contains(H, P)) { inside++; break; }
  ok(inside === 0, `none of them contains any of the 398 (${inside})`);
  const maxm = Math.max(...b10.map((G) => G.m)), atMax = b10.filter((G) => G.m === maxm).length;
  ok(maxm === 20 && atMax === 1, `the densest has 20 edges and is the only one with 20: u(10) = 20 with one densest graph, as in Alexeev, Mixon and Parshall's Table 1 (${maxm}, ${atMax})`);
  t0 = Date.now(); let fp10 = 0; for (const G of b10) if (E.quickRefute(G.n, G.edges).refuted) fp10++;
  ok(fp10 === 0, `the engine refutes none of the 32,653 (${fp10}, ${((Date.now() - t0) / 1000).toFixed(0)} s)`);
} else console.log('  (skipped: the 32,653-graph control; run with --full)');

// ---------- E. Petersen ----------
console.log('E. the Petersen drawing');
const P = decode(PET.g6);
const pm = measure(PET.xy, P.edges, null);
let nearOne = Infinity;
for (let i = 0; i < 10; i++) for (let j = i + 1; j < 10; j++) if (!(P.adj[i] & (1 << j))) nearOne = Math.min(nearOne, Math.abs(Math.hypot(PET.xy[i][0] - PET.xy[j][0], PET.xy[i][1] - PET.xy[j][1]) - 1));
ok(P.n === 10 && P.m === 15 && P.adj.every((a) => popc(a) === 3) && girth(P) === 5, 'it is the Petersen graph: ten vertices, 3-regular, girth 5 (the only such graph)');
ok(JSON.stringify(P.edges) === JSON.stringify(PET.edges.map(([a, b]) => (a < b ? [a, b] : [b, a])).sort((x, y) => x[0] - y[0] || x[1] - y[1])), 'its graph6 string and its edge list describe the same labelled graph, the one the coordinates are for');
ok(pm.worst < 1e-11 && pm.gap > 0.3 && nearOne > 1e-3, `all 15 edges are 1 to within ${pm.worst.toExponential(1)}, points at least ${pm.gap.toFixed(4)} apart, no other pair at distance 1`);
ok(Math.abs(1 / (4 * Math.sin(Math.PI / 5) ** 2) + 1 / (4 * Math.sin((2 * Math.PI) / 5) ** 2) - 1) < 1e-15, 'the circumradii of the unit pentagon and unit pentagram satisfy R1^2 + R2^2 = 1');

// ---------- F. the bounds ----------
console.log('F. the bounds, by Schade\'s lemma');
const resultPages = [
  { n: 23, slug: 'the-sixty-fifth-distance', title: 'The Sixty-Fifth Distance' },
  { n: 24, slug: 'the-sixty-ninth-distance', title: 'The Sixty-Ninth Distance' },
];
const run23 = JSON.parse(await sibling('the-sixty-fifth-distance', 'data/run.json'));
const dependencies23 = JSON.parse(await sibling('the-sixty-fifth-distance', 'data/dependencies.json'));
const sliceCount23 = new Set(run23.slices.map(slice => slice.id)).size;
const exact = { 22: 60 };
for (const result of resultPages) {
  const raw = JSON.parse(await sibling(result.slug, 'data/configuration.json')), cfg = raw.configuration ?? raw;
  const count = exactUnits(cfg.lattice), declared = cfg.claimedEdges ?? cfg.m;
  exact[result.n] = count;
  ok(cfg.n === result.n && cfg.lattice.length === result.n && count === declared, `${result.title}: ${result.n} points, ${count} unit pairs recomputed exactly, matching its frozen figure`);
  const moved = structuredClone(cfg.lattice); moved[0][0] += 7;
  ok(exactUnits(moved) < count, `${result.title}: moving a point breaks the exact pair count`);
  const target = await sibling(result.slug, 'index.html');
  ok(target.includes(result.title) || target.replace(/<[^>]*>/g, ' ').replace(/\s+/g, ' ').includes(result.title), `${result.title}: the link resolves to its repository page`);
}
const chain = (order, start) => { const u = {}; for (let n = order + 1; n <= 30; n++) { start = Math.floor(n * start / (n - 2)); u[n] = start; } return Object.values(u); };
const now = chain(24, exact[24]), old = chain(22, PLANT === 'schade' ? 61 : exact[22]), before = chain(22, 61);
ok(exact[23] === 64 && exact[24] === 68, `the two new exact values are u(23) = ${exact[23]} and u(24) = ${exact[24]}`);
ok(now.join() === '73,79,85,91,97,103', `from u(24) = ${exact[24]}, n = 25..30: ${now.join(', ')}`);
ok(old.join() === '65,70,76,82,88,94,100,107', `the 25 September 2026 chain from u(22) = 60: ${old.join(', ')}`);
ok(before.join() === '66,72,78,84,90,96,103,110', `from u(22) <= 61 it gives Alexeev, Mixon and Parshall's printed bounds: ${before.join(', ')}`);

// ---------- G. the page ----------
console.log('G. the page says what was found here');
// The page prints this verifier's own output in <pre class="out" id="verify-summary">, and that
// output contains every figure below, so matching against the whole page proved nothing (an outside
// claims pass on 2026-09-27 changed four prose numbers and this section still passed). The
// transcript is cut out first, and a figure must stand as a whole number, not inside another.
// The first version of that cut looked for <pre id="verify-summary">, which is not the tag the page
// has, so it cut nothing and twelve figures were still being found in the transcript (measured by
// research/self-reading-verifiers/scan.mjs --probe, 2026-09-27). So the cut is now checked: it must
// remove the transcript, and the 'prose' plant in mutate.mjs must turn this section red.
const CUT = /<pre\b[^>]*\bid="verify-summary"[^>]*>[\s\S]*?<\/pre>/;
const visible = (s) => s.replace(/<script\b[\s\S]*?<\/script>|<style\b[\s\S]*?<\/style>|<!--[\s\S]*?-->/gi, ' ').replace(/<[^>]+>/g, ' ').replace(/&nbsp;/g, ' ').replace(/\s+/g, ' ').trim();
const text = visible(PAGE.replace(CUT, ' ').replace(/<!--aw-assay:start-->[\s\S]*?<!--aw-assay:end-->/, ' '));
ok(CUT.test(PAGE) && !text.includes('-- from verify.mjs') && !text.includes('its figures add up'), 'the printed transcript is cut out before the prose is read');
// Citation identifiers are labels, not measurements; their displayed text must still agree with the actual links.
const anchors = [...PAGE.matchAll(/<a\b[^>]*href="([^"]+)"[^>]*>([\s\S]*?)<\/a>/g)].map(m => ({ href: m[1], label: visible(m[2]) }));
const labelledURLs = anchors.filter(a => /^(?:https?:\/\/|10\.\d{4,9}\/)/.test(a.label));
ok(labelledURLs.length > 0 && labelledURLs.every(a => a.label.startsWith('http') ? a.label === a.href : a.href === 'https://doi.org/' + a.label), 'every displayed URL or DOI identifier agrees with its clickable target');
const bibliography = [...PAGE.matchAll(/<li\b[^>]*>([\s\S]*?)<\/li>/g)].filter(m => /arXiv:/i.test(visible(m[1])));
ok(bibliography.length > 0 && bibliography.every(m => {
  const ids = [...m[1].matchAll(/href="https:\/\/arxiv\.org\/(?:abs|html)\/(\d{4}\.\d{4,5})/g)].map(a => a[1]);
  const labels = [...visible(m[1]).matchAll(/arXiv:(\d{4}\.\d{4,5})/gi)].map(a => a[1]);
  return labels.length > 0 && labels.every(label => ids.includes(label));
}) && anchors.filter(a => /^arXiv:/i.test(a.label)).every(a => a.href.match(/arxiv\.org\/(?:abs|html)\/(\d{4}\.\d{4,5})/)?.[1] === a.label.match(/arXiv:(\d{4}\.\d{4,5})/i)?.[1]), 'displayed arXiv identifiers agree with the linked bibliography and prose sources');
const says = (s) => new RegExp(`(?<![\\d,.])${s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?![\\d]|,\\d)`).test(text);
for (const s of ['398', '324', '74', '182', '216', '142', '6,398', '2,840', '14,008', '32,653', '33,162', '509', '185', '9,743,542', 'OEIS A308349', '65']) ok(says(s), `the page states ${s}`);
// Run the actual table renderer, then compare both it and the static fallback with independently derived rows.
const block = APP.match(/\/\/ U-BOUNDS-START([\s\S]*?)\/\/ U-BOUNDS-END/), nodes = {};
ok(!!block, 'the page exposes its table computation for this check');
if (block) vm.runInNewContext(block[1], { $: id => (nodes[id] ??= {}) }, { timeout: 1000 });
const rowsOf = (s) => [...(s.match(/<tbody>([\s\S]*?)<\/tbody>/)?.[1] ?? '').matchAll(/<tr>([\s\S]*?)<\/tr>/g)].map(m => [...m[1].matchAll(/<td\b[^>]*>([\s\S]*?)<\/td>/g)].map(c => visible(c[1])));
const actualRows = rowsOf(nodes['t-u']?.innerHTML ?? '');
const known = [41, 43, 46, 50, 54, 57], lower = [72, 76, 81, 85, 89, 93];
const expectedRows = Array.from({ length: 15 }, (_, i) => {
  const n = i + 16;
  if (n <= 21) return [String(n), String(known[i]), String(known[i]), 'exact (2024)', ''];
  if (n === 22) return ['22', String(exact[22]), String(exact[22]), 'was 60 or 61; exact (2026)', ''];
  if (n <= 24) return [String(n), String(exact[n]), String(exact[n]), `was at most ${before[n - 23]}`, `${resultPages[n - 23].title} : exact (2026)`];
  return [String(n), String(lower[n - 25]), String(now[n - 25]), `was at most ${before[n - 23]}`, ''];
});
ok(JSON.stringify(actualRows) === JSON.stringify(expectedRows), `the running table recomputes exact values and bounds from u(24) = ${exact[24]}: ${now.join(', ')}, with AMP's column unchanged`);
const staticTable = PAGE.match(/<table\b[^>]*\bid="t-u"[^>]*>([\s\S]*?)<\/table>/)?.[1] ?? '';
ok(JSON.stringify(rowsOf(staticTable)) === JSON.stringify(expectedRows), 'every static table cell matches the independently recomputed rows');
ok(staticTable === nodes['t-u']?.innerHTML, 'the static table is exactly the table the page computes');
const oldSentence = `When this page was written (25 September 2026), the chain started from u(22) = 60: ${old.join(', ')}.`;
ok(nodes['u-old-chain']?.textContent === oldSentence, 'the running page computes the dated old chain');
ok(PAGE.match(/<p\b[^>]*\bid="u-old-chain"[^>]*>([\s\S]*?)<\/p>/)?.[1] === oldSentence, 'the visible dated old chain matches its independent recomputation');
for (const result of resultPages) {
  const link = `<a href="/strata/${result.slug}/">${result.title}</a>: exact (2026)`;
  ok(staticTable.includes(link) && nodes['t-u']?.innerHTML.includes(link), `${result.title} is the exact-value table link`);
}
for (const id of ['since-then', 'u23-update', 'search-update']) {
  const note = PAGE.match(new RegExp(`<(?:aside|p)\\b[^>]*\\bid="${id}"[^>]*>([\\s\\S]*?)</(?:aside|p)>`))?.[1] ?? '';
  ok(note.includes('<time datetime="2026-10-08">8 October 2026</time>'), `${id}: the update has the correct machine and visible date`);
  if (id !== 'since-then') for (const result of resultPages) ok(note.includes(`<a href="/strata/${result.slug}/">${result.title}</a>`), `${id}: links to ${result.title}`);
  if (id === 'u23-update') {
    const t = visible(note);
    for (const result of resultPages) {
      const matches = [...t.matchAll(new RegExp(`u\\(${result.n}\\) = (\\d+)`, 'g'))];
      ok(matches.length === 1 && Number(matches[0][1]) === exact[result.n], `${id}: its u(${result.n}) figure equals the frozen-data count`);
      const recordedSearch = result.n !== 23 || (sliceCount23 === run23.slices.length && t.includes(`all ${sliceCount23.toLocaleString('en-US')} slices with the ${Gs.length}, ${['zero', 'one', 'two', 'three', 'four', 'five', 'six'][dependencies23.tu]} TU gadgets`));
      ok(t.includes(`lone ${exact[result.n] + 1}-edge survivor`) && recordedSearch, `${id}: the excluded edge target and search figures agree with the frozen inputs for u(${result.n})`);
    }
  }
  if (id === 'since-then') {
    const count11 = (await sibling('every-edge-but-one-at-eleven', 'data/L11.g6')).trim().split('\n').map(decode);
    const total = Gs.length + count11.length;
    ok(count11.length === 2833 && count11.every(g => g.n === 11), 'the eleven-vertex note is grounded in the frozen graph list');
    ok(note.includes(`<a href="/strata/every-edge-but-one-at-eleven/">Every Edge But One at Eleven</a>`) && (await sibling('every-edge-but-one-at-eleven', 'index.html')).includes('Every Edge But One at Eleven'), 'the eleven-vertex link resolves with its real title');
    const fmt = n => n.toLocaleString('en-US');
    ok(note.includes(`adds ${fmt(count11.length)} minimal forbidden graphs`) && note.includes(`${byN[9] + byN[8] + byN[7] + byN[6] + byN[5] + byN[4]} + ${byN[10]} + ${fmt(count11.length)} = ${fmt(total)}`) && note.includes(`terms of A308349 are ${byN[10]} and ${fmt(count11.length)}`), `the note's added and combined counts and A308349 terms are recomputed (${fmt(total)})`);
  }
}
const tableDate = PAGE.match(/<p\b[^>]*\bid="u-table-date"[^>]*>([\s\S]*?)<\/p>/)?.[1] ?? '';
ok(tableDate.includes('<time datetime="2026-10-08">8 October 2026</time>') && visible(tableDate).includes(`computed from u(24) = ${exact[24]} by Schade's lemma`), 'the table caption dates and identifies its exact starting value');
const pilot = JSON.parse(await get('data/pilot-costs.json'));
for (const p of pilot.measurements) {
  const ratio = (p.mode398Seconds / p.mode74Seconds).toFixed(2);
  ok(new RegExp(p.n === 23 ? `same slice ran ${ratio.replace('.', '\\.')} times slower` : `22-point search ${ratio.replace('.', '\\.')} times slower`).test(text), `the dated ${p.n}-point pilot ratio is recomputed (${ratio})`);
}
const drawable = [...text.matchAll(/on the ([\d,]+) ten-vertex graphs/g)];
ok(B10.length === 32653 && drawable.length > 0 && drawable.every(m => Number(m[1].replace(/,/g, '')) === B10.length), 'the prose control count matches the frozen ten-vertex control list');
ok(32653 + 509 === 33162 && 509 - 324 === 185 && 14008 + 32653 === 46661 && 398 - 182 === 216, 'its figures add up: 32,653 + 509 = 33,162; 509 - 324 = 185; 14,008 + 32,653 = 46,661; 398 - 182 = 216');

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