#!/usr/bin/env node
// verify-boolean-pythagorean.mjs
//
// Offline mirror of every number the stratum page displays.
//
// The rule this file exists to satisfy: it must read
// public/strata/boolean-pythagorean/index.html and assert that the numbers
// SHIPPED IN THAT FILE agree with numbers recomputed here from the
// definitions and from the digest-pinned published artifacts in ./vendor/.
// A verifier that only re-derives mathematics without comparing against what
// the page shows is checking nothing we ship.
//
// Dependency free. Node 18+.
//
// It does NOT reprove that the 7825 formula is unsatisfiable. That claim is
// cited, not reproduced, and the final report says so explicitly.

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

const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, '..', '..');
const PAGE = path.join(ROOT, 'public', 'strata', 'boolean-pythagorean', 'index.html');
const VENDOR = path.join(HERE, 'vendor');

let pass = 0, fail = 0;
const failures = [];
function ok(name, cond, detail) {
  if (cond) { pass++; console.log(`  ok   ${name}${detail ? '   ' + detail : ''}`); }
  else { fail++; failures.push(name); console.log(`  FAIL ${name}${detail ? '   ' + detail : ''}`); }
}
function eq(name, got, want) {
  ok(name, got === want, `got ${JSON.stringify(got)} want ${JSON.stringify(want)}`);
}
function section(t) { console.log(`\n== ${t}`); }

// ---------------------------------------------------------------------------
// 0. The vendored published artifacts, pinned by SHA-256.
// ---------------------------------------------------------------------------
const PINNED = {
  'plain7824.cnf':    'c3e372c1329f1251f9e9b71171039aee33bd95fd496fe41b10ba3f5a58aa0359',
  'plain7825.cnf':    '49735fb2d9dcce1ea5a610297d0128a60876ec82b29f6824f20e01e89e7223a7',
  'bce7825.cnf':      'c1b3fe88c8df6a89affbaae30c48d184101a965d5c307a1829f2005dff7da2c3',
  'backbone7824.cnf': '9226d9d30c34fbc1338b5c3d2d36acb3781759a2204d85b089579fdc3f5f5955',
  'ptn-encode.c':     '7a7056f55fa9e58417eb65bddd5797ea413118f377f95ecd97f5cca8cf2cbff7'
};
// SHA-256 of the shipped 7,824-character witness bitstring ('1' = red).
const WITNESS_SHA256 = '81f579f137c9b0a0a7c7799feb52e1d9e9b5e7c363fb3ad6e884eb64bd3d14ec';

section('vendored published artifacts, digest pinned');
for (const [f, want] of Object.entries(PINNED)) {
  const p = path.join(VENDOR, f);
  const got = fs.existsSync(p)
    ? crypto.createHash('sha256').update(fs.readFileSync(p)).digest('hex')
    : '(missing)';
  eq(`sha256 ${f}`, got, want);
}

function readCNF(file) {
  const txt = fs.readFileSync(path.join(VENDOR, file), 'utf8');
  const lines = txt.split('\n');
  let header = null;
  const clauses = [];
  for (const raw of lines) {
    const s = raw.trim();
    if (!s) continue;
    if (s[0] === 'c') continue;
    if (s[0] === 'p') { const p = s.split(/\s+/); header = { vars: +p[2], clauses: +p[3] }; continue; }
    const lits = s.split(/\s+/).map(Number);
    if (lits[lits.length - 1] !== 0) throw new Error(`clause not 0-terminated in ${file}: ${s}`);
    clauses.push(lits.slice(0, -1));
  }
  return { header, clauses };
}

// ---------------------------------------------------------------------------
// 1. Pythagorean triples, two independent generators.
// ---------------------------------------------------------------------------
function triplesDirect(N) {
  const out = [];
  for (let a = 1; a <= N; a++) {
    const lim = Math.floor(Math.sqrt(N * N - a * a));
    for (let b = a; b <= lim; b++) {
      const s = a * a + b * b;
      const c = Math.round(Math.sqrt(s));
      if (c <= N && c * c === s) out.push([a, b, c]);
    }
  }
  out.sort((p, q) => p[2] - q[2] || p[1] - q[1] || p[0] - q[0]);
  return out;
}
function triplesEuclid(N) {
  const gcd = (x, y) => { while (y) { const t = x % y; x = y; y = t; } return x; };
  const seen = new Set(), out = [];
  for (let m = 2; m * m <= N; m++) {
    for (let n = 1; n < m; n++) {
      if (((m - n) & 1) === 0) continue;
      if (gcd(m, n) !== 1) continue;
      let a = m * m - n * n, b = 2 * m * n;
      const c = m * m + n * n;
      if (c > N) continue;
      if (a > b) { const t = a; a = b; b = t; }
      for (let k = 1; k * c <= N; k++) {
        const key = `${k * a},${k * b},${k * c}`;
        if (!seen.has(key)) { seen.add(key); out.push([k * a, k * b, k * c]); }
      }
    }
  }
  out.sort((p, q) => p[2] - q[2] || p[1] - q[1] || p[0] - q[0]);
  return out;
}
const key3 = t => t.slice().sort((x, y) => x - y).join(',');
const setOf = T => new Set(T.map(key3));
function sameSet(A, B) {
  if (A.size !== B.size) return false;
  for (const k of A) if (!B.has(k)) return false;
  return true;
}

section('the triple census, generated two ways');
const T7825 = triplesDirect(7825);
const T7825e = triplesEuclid(7825);
const T7824 = triplesDirect(7824);
eq('direct generator, c at most 7825', T7825.length, 9472);
eq('Euclid parameters plus multiples, c at most 7825', T7825e.length, 9472);
ok('the two generated SETS are identical', sameSet(setOf(T7825), setOf(T7825e)));
eq('direct generator, c at most 7824', T7824.length, 9465);
eq('triples whose largest member is exactly 7825', T7825.length - T7824.length, 7);
{
  let maxv = 0;
  for (const t of T7824) if (t[2] > maxv) maxv = t[2];
  eq('highest number occurring in a triple with c at most 7824', maxv, 7820);
  let bad = 0;
  for (const [a, b, c] of T7825) if (a * a + b * b !== c * c || !(a <= b && b <= c)) bad++;
  eq('triples failing a squared plus b squared equals c squared', bad, 0);
}

section('the generated clause set against the authors published CNFs');
for (const [file, N, wantVars, wantClauses] of [
  ['plain7824.cnf', 7824, 7820, 18930],
  ['plain7825.cnf', 7825, 7825, 18944]
]) {
  const { header, clauses } = readCNF(file);
  eq(`${file} header vars`, header.vars, wantVars);
  eq(`${file} header clauses`, header.clauses, wantClauses);
  eq(`${file} clause lines`, clauses.length, wantClauses);
  const T = triplesDirect(N);
  eq(`${file} clauses equals two per generated triple`, clauses.length, 2 * T.length);
  // rebuild both polarities from our triples and compare as sets
  const mine = new Set();
  for (const t of T) { mine.add(key3(t)); mine.add(key3(t.map(x => -x))); }
  const theirs = new Set();
  for (const cl of clauses) theirs.add(cl.slice().sort((x, y) => x - y).join(','));
  const mineSorted = new Set([...mine].map(s => s.split(',').map(Number).sort((x, y) => x - y).join(',')));
  ok(`${file} clause set identical to the one generated here`, sameSet(mineSorted, theirs));
}

// ---------------------------------------------------------------------------
// 2. Blocked clause elimination, the authors' first proof step, as a fixpoint.
// ---------------------------------------------------------------------------
function bce(T) {
  let L = T.slice(), rounds = 0;
  for (;;) {
    const cnt = new Map();
    for (const t of L) for (const x of t) cnt.set(x, (cnt.get(x) || 0) + 1);
    const keep = L.filter(t => t.every(x => cnt.get(x) > 1));
    if (keep.length === L.length) break;
    L = keep; rounds++;
  }
  const vars = new Set();
  for (const t of L) for (const x of t) vars.add(x);
  return { L, rounds, vars };
}

section('blocked clause elimination reproduced');
const B = bce(T7825);
eq('surviving triples', B.L.length, 7336);
eq('triples eliminated', T7825.length - B.L.length, 2136);
eq('numbers still used', B.vars.size, 3745);
eq('rounds to a fixpoint', B.rounds, 6);
{
  const { header, clauses } = readCNF('bce7825.cnf');
  eq('bce7825.cnf header clauses', header.clauses, 14672);
  eq('bce7825.cnf clause lines', clauses.length, 14672);
  const pubTriples = new Set();
  for (const cl of clauses) if (cl[0] > 0) pubTriples.add(key3(cl));
  ok('our surviving triple SET equals the published bce7825.cnf', sameSet(setOf(B.L), pubTriples));
  const pubVars = new Set();
  for (const cl of clauses) for (const l of cl) pubVars.add(Math.abs(l));
  eq('distinct variables in bce7825.cnf', pubVars.size, 3745);
}
// negative control: a broken elimination must not reach the published set
{
  const L1 = T7825.filter(t => {
    const cnt = new Map();
    for (const u of T7825) for (const x of u) cnt.set(x, (cnt.get(x) || 0) + 1);
    return t.every(x => cnt.get(x) > 1);
  });
  ok('one round alone does NOT reach the fixpoint (the loop is load bearing)', L1.length !== B.L.length,
     `one round leaves ${L1.length}, fixpoint is ${B.L.length}`);
}

// ---------------------------------------------------------------------------
// 3. The page's shipped data: witness bits and backbone literals.
// ---------------------------------------------------------------------------
section('reading what the page actually ships');
const html = fs.readFileSync(PAGE, 'utf8');

function grabB64(name) {
  const m = html.match(new RegExp(`var\\s+${name}\\s*=\\s*'([A-Za-z0-9+/=]+)'`));
  if (!m) throw new Error(`could not find ${name} in the page`);
  return m[1];
}
function b64bits(b64, len) {
  const buf = Buffer.from(b64, 'base64');
  const out = new Uint8Array(len);
  for (let i = 0; i < len; i++) out[i] = (buf[i >> 3] >> (7 - (i & 7))) & 1;
  return out;
}
const witBits = b64bits(grabB64('WITNESS_B64'), 7824);
const bbMask = b64bits(grabB64('BB_MASK_B64'), 7824);
const bbPol = b64bits(grabB64('BB_POL_B64'), 7824);
eq('witness bit length', witBits.length, 7824);

const witStr = Array.from(witBits).join('');
eq('sha256 of the shipped witness bitstring',
   crypto.createHash('sha256').update(witStr).digest('hex'), WITNESS_SHA256);

let R_free = 0, R_occurring = 0, R_critical = 0, R_slack = 0;
let R_bbunits = 0, R_bbdisagree = 0, R_dratrup = 0, R_dratrat = 0;
let R_negsym = 0, R_hingeopp = 0;
let R_cubecover = 0, R_cubedup = -1, R_cubemodels = 0, R_cubedeep = -1;
let R_pow2digits = 0, R_pow2lead3 = 0;

section('the shipped witness against triples generated here');
{
  const col = i => witBits[i - 1] === 1;
  let mono = 0, first = null;
  for (const [a, b, c] of T7824) {
    if (col(a) === col(b) && col(b) === col(c)) { mono++; if (!first) first = [a, b, c]; }
  }
  eq('monochromatic triples in the witness (c at most 7824)', mono, 0);
  ok('a good colouring of 1 to 7824 therefore EXISTS', mono === 0,
     first ? `first failure ${first}` : 'checked all 9,465');
  // free numbers: those appearing in no triple with c at most 7824
  const occurring = new Set();
  for (const t of T7824) for (const x of t) occurring.add(x);
  eq('numbers in 1..7824 occurring in some triple', occurring.size, 6492);
  eq('numbers in 1..7824 occurring in NO triple (unconstrained)', 7824 - occurring.size, 1332);
  R_occurring = occurring.size;
  R_free = 7824 - occurring.size;
  // The page's caption is careful that "free" means "in no triple with all three
  // members at most 7824", not "in no triple". 7313 is the counter-example it
  // names: it is unconstrained on the tape, yet 2784^2 + 7313^2 = 7825^2.
  ok('7313 is one of the free numbers on the tape', !occurring.has(7313));
  eq('2784^2 + 7313^2', 2784 * 2784 + 7313 * 7313, 7825 * 7825);
  ok('so 7313 does occur in a Pythagorean triple, just not one with c at most 7824',
     setOf(T7825).has(key3([2784, 7313, 7825])));

  // how tight is it? count the numbers whose single flip creates a
  // monochromatic triple. This is the negative control for the witness:
  // a colouring that survived by accident would have few such numbers.
  const inc = new Array(7825);
  for (let i = 0; i < T7824.length; i++) for (const x of T7824[i]) (inc[x] = inc[x] || []).push(i);
  const bits = Uint8Array.from(witBits);
  let critical = 0, freeFlipBreaks = 0;
  const namedBreak = [];
  for (let v = 1; v <= 7824; v++) {
    const deg = inc[v] ? inc[v].length : 0;
    bits[v - 1] ^= 1;
    let bad = false;
    for (const i of (inc[v] || [])) {
      const [a, b, c] = T7824[i];
      if (bits[a - 1] === bits[b - 1] && bits[b - 1] === bits[c - 1]) { bad = true; break; }
    }
    bits[v - 1] ^= 1;
    if (bad) critical++;
    if (deg === 0 && bad) freeFlipBreaks++;
    if ([5180, 625, 2520, 7800].includes(v) && bad) namedBreak.push(v);
  }
  eq('numbers whose single flip destroys the witness', critical, 4260);
  R_critical = critical;
  R_slack = R_occurring - critical;
  eq('numbers in a triple that can still be flipped', R_slack, 2232);
  eq('unconstrained numbers whose flip destroys it (must be zero)', freeFlipBreaks, 0);
  eq('the four hinge/symmetry numbers all break it when flipped', namedBreak.length, 4);
  // neither colour extends to 7825 (for THIS witness; not the theorem)
  const at7825 = triplesDirect(7825).filter(t => t[2] === 7825);
  eq('triples whose largest member is 7825', at7825.length, 7);
  let extends_ = 0;
  for (const v of [0, 1]) {
    const c3 = i => (i === 7825 ? v === 1 : witBits[i - 1] === 1);
    let bad = 0;
    for (const [a, b, c] of at7825) if (c3(a) === c3(b) && c3(b) === c3(c)) bad++;
    if (bad === 0) extends_++;
  }
  eq('colours for 7825 that keep THIS witness proper', extends_, 0);
}

section('the shipped backbone blob against backbone7824.cnf');
{
  const { header, clauses } = readCNF('backbone7824.cnf');
  const units = clauses.filter(c => c.length === 1).map(c => c[0]);
  eq('backbone7824.cnf header clauses', header.clauses, 21234);
  eq('unit clauses in backbone7824.cnf', units.length, 2304);
  eq('backbone7824.cnf equals plain7824.cnf plus the units', header.clauses - units.length, 18930);
  const fromPage = [];
  for (let i = 1; i <= 7824; i++) if (bbMask[i - 1]) fromPage.push(bbPol[i - 1] ? i : -i);
  eq('backbone literals decoded from the page', fromPage.length, 2304);
  const a = new Set(units), b = new Set(fromPage);
  ok('the page\'s backbone blob is literal-for-literal the published file',
     a.size === b.size && [...a].every(x => b.has(x)));
  // the witness must agree with every backbone literal
  let dis = 0;
  for (const u of units) if ((witBits[Math.abs(u) - 1] === 1) !== (u > 0)) dis++;
  eq('witness values disagreeing with the backbone', dis, 0);
  eq('symmetry-breaking unit 2520 is positive in the backbone', units.includes(2520), true);
  R_bbunits = units.length;
  R_bbdisagree = dis;
  // The witness was PRODUCED from backbone7824.cnf, so the agreement above is
  // guaranteed by construction and is a decoding check, not evidence. The page
  // has to say so at the bench, not only in a footnote ninety lines away.
  ok('the bench itself discloses that the witness was seeded with these units',
     /produced by giving CaDiCaL the published backbone7824\.cnf/.test(html));
}

section('the hinge at 7825, and the orientation the two sources disagree about');
{
  const polOf = v => (bbMask[v - 1] ? (bbPol[v - 1] ? 'red' : 'blue') : null);
  // What the PUBLISHED FILE says (this is what the page prints).
  eq('backbone7824.cnf, x_5180', polOf(5180), 'blue');
  eq('backbone7824.cnf, x_5865', polOf(5865), 'blue');
  eq('backbone7824.cnf, x_625', polOf(625), 'red');
  eq('backbone7824.cnf, x_7800', polOf(7800), 'red');
  eq('backbone7824.cnf, x_2520 (the symmetry break)', polOf(2520), 'red');
  {
    // read the same five polarities straight out of the vendored file, so this
    // is not just the page's blob agreeing with itself
    const { clauses } = readCNF('backbone7824.cnf');
    const units = new Set(clauses.filter(c => c.length === 1).map(c => c[0]));
    for (const [v, lit] of [[5180, -5180], [5865, -5865], [625, 625], [7800, 7800], [2520, 2520]]) {
      ok(`vendored backbone7824.cnf contains the unit ${lit}`, units.has(lit), `variable ${v}`);
    }
  }
  eq('5180^2 + 5865^2', 5180 * 5180 + 5865 * 5865, 7825 * 7825);
  eq('625^2 + 7800^2', 625 * 625 + 7800 * 7800, 7825 * 7825);
  ok('both hinge triples are in the generated triple list',
     setOf(T7825).has(key3([5180, 5865, 7825])) && setOf(T7825).has(key3([625, 7800, 7825])));

  // The orientation-free content: the two pairs take different colours.
  ok('5180 and 5865 share a colour', polOf(5180) === polOf(5865));
  ok('625 and 7800 share a colour', polOf(625) === polOf(7800));
  ok('and the two colours are different', polOf(5180) !== polOf(625));

  // run the argument itself: no value of x_7825 survives both clauses
  let survivors = 0;
  for (const v of [true, false]) {
    const c = { 5180: polOf(5180) === 'red', 5865: polOf(5865) === 'red',
                625: polOf(625) === 'red', 7800: polOf(7800) === 'red', 7825: v };
    const bad1 = c[5180] === c[5865] && c[5865] === c[7825];
    const bad2 = c[625] === c[7800] && c[7800] === c[7825];
    if (!bad1 && !bad2) survivors++;
  }
  eq('colours for 7825 consistent with the four backbone values', survivors, 0);
  // and the mirror-image orientation kills 7825 just as dead
  let mirrorSurvivors = 0;
  for (const v of [true, false]) {
    const c = { 5180: polOf(5180) !== 'red', 5865: polOf(5865) !== 'red',
                625: polOf(625) !== 'red', 7800: polOf(7800) !== 'red', 7825: v };
    const bad1 = c[5180] === c[5865] && c[5865] === c[7825];
    const bad2 = c[625] === c[7800] && c[7800] === c[7825];
    if (!bad1 && !bad2) mirrorSurvivors++;
  }
  eq('colours for 7825 consistent with the MIRRORED four values', mirrorSurvivors, 0);
}

// ---------------------------------------------------------------------------
// 3b. THE SOURCE CONFLICT. Section 6.3 of Heule, Kullmann & Marek 2016 states
// the four hinge polarities the other way round from the published file. This
// is checked here rather than glossed: the page must carry the paper's sentence
// verbatim, must carry the paper's polarities as data, and must not present its
// own orientation as what the paper says.
// ---------------------------------------------------------------------------
section('the file against the paper: the disputed orientation');
{
  // arXiv:1605.00723v1, Sect. 6.3 "Extreme Solutions", read 31 July 2026.
  const HKM_SECT63 = { 5180: 1, 5865: 1, 625: 0, 7800: 0 };   // 1 = positive = true = red
  // the page must ship exactly these, as the paper's claim, not as its own
  const m = html.match(/var\s+HKM_63\s*=\s*\{([^}]*)\}/);
  ok('the page ships the paper\'s stated polarities as data', !!m);
  const pagePaper = {};
  if (m) for (const mm of m[1].matchAll(/(\d+)\s*:\s*(\d)/g)) pagePaper[mm[1]] = Number(mm[2]);
  for (const v of Object.keys(HKM_SECT63)) {
    eq(`page's record of HKM Sect. 6.3 for x_${v}`, pagePaper[v], HKM_SECT63[v]);
  }
  // and the disagreement itself, counted
  let opp = 0;
  for (const v of Object.keys(HKM_SECT63)) {
    const filePos = bbPol[Number(v) - 1] ? 1 : 0;
    if (filePos !== HKM_SECT63[v]) opp++;
  }
  eq('hinge polarities where backbone7824.cnf and HKM Sect. 6.3 disagree', opp, 4);
  R_hingeopp = opp;
  ok('all four disagree, i.e. the paper states the exact global mirror image', opp === 4);
  // the paper agrees with the file on 2520, which is why a global flip cannot
  // reconcile the two: one of the paper's two statements has to be a slip.
  // The paper and the file AGREE that 2520 is positive, which is exactly why a
  // global flip cannot reconcile the two: one of the paper's own statements has
  // to be a slip, and the page has to say that rather than pick a winner.
  const flat = html.replace(/\s+/g, ' ');
  ok('page carries the LPAR-21 sentence fixing the symmetry break to true',
     flat.includes('"2520 was assigned to true"'));
  ok('page states that the file and Sect. 6.3 cannot both be right under that convention',
     flat.includes("What we cannot reconcile is the paper with itself"));
  ok('page does not claim to have resolved which statement is the slip',
     flat.includes('We have not resolved which is the slip, and we do not know.'));
  // the page must quote the paper, verbatim, where it contradicts the page
  for (const q of [
    'variables x5180 and x5865 are both positive in the backbone',
    'variables x625\n    and x7800 are both negative in the backbone'
  ]) {
    ok(`page quotes the paper verbatim: "${q.replace(/\s+/g, ' ')}"`, html.replace(/\s+/g, ' ').includes(q.replace(/\s+/g, ' ')));
  }
  ok('page does not attribute the four printed polarities to the paper',
     /<strong>Not<\/strong> the\s*source of the four hinge polarities/.test(html));
  ok('page names the orientation as unresolved in the check list',
     /Unresolved: which orientation of the backbone is the published one/.test(html));
}

// ---------------------------------------------------------------------------
// 3c. Why the two orientations are the same fact: the clause set is closed
// under negating every literal. Counted over the whole 7825 formula.
// ---------------------------------------------------------------------------
section('the colour swap is a symmetry of the formula');
{
  const F = [];
  for (const [a, b, c] of T7825) { F.push([a, b, c]); F.push([-a, -b, -c]); }
  const have = new Set(F.map(cl => cl.slice().sort((x, y) => x - y).join(',')));
  let mirrored = 0;
  for (const cl of F) {
    const neg = cl.map(x => -x).sort((x, y) => x - y).join(',');
    if (have.has(neg)) mirrored++;
  }
  eq('clauses whose literal-for-literal negation is also a clause', mirrored, F.length);
  eq('and that is all 18,944 of them', mirrored, 18944);
  R_negsym = mirrored;
  // the consequence, made concrete: mirroring the witness gives another witness
  let monoMirror = 0;
  for (const [a, b, c] of T7824) {
    const A = witBits[a - 1] ^ 1, B = witBits[b - 1] ^ 1, C = witBits[c - 1] ^ 1;
    if (A === B && B === C) monoMirror++;
  }
  eq('monochromatic triples in the MIRRORED witness', monoMirror, 0);
}

// ---------------------------------------------------------------------------
// 4. The nine-variable a+b=c example and its four-line DRAT refutation.
// ---------------------------------------------------------------------------
function sumTriples9() {
  const T = [];
  for (let a = 1; a <= 9; a++) for (let b = a + 1; b <= 9; b++) { const c = a + b; if (c <= 9 && b < c) T.push([a, b, c]); }
  return T;
}
function sumFormula9() {
  const F = [];
  for (const [a, b, c] of sumTriples9()) { F.push([a, b, c]); F.push([-a, -b, -c]); }
  return F;
}
function propagate(clauses, assign) {
  let changed = true;
  while (changed) {
    changed = false;
    for (const cl of clauses) {
      let un = 0, lit = 0, satisfied = false;
      for (const l of cl) {
        const v = Math.abs(l), val = assign.get(v);
        if (val === undefined) { un++; lit = l; }
        else if ((val && l > 0) || (!val && l < 0)) { satisfied = true; break; }
      }
      if (satisfied) continue;
      if (un === 0) return true;
      if (un === 1) { assign.set(Math.abs(lit), lit > 0); changed = true; }
    }
  }
  return false;
}
function isRUP(clauses, cl) {
  const a = new Map();
  for (const l of cl) {
    const v = Math.abs(l), want = l < 0;
    if (a.has(v) && a.get(v) !== want) return true;
    a.set(v, want);
  }
  return propagate(clauses, a);
}
function isRAT(clauses, cl) {
  if (cl.length === 0) return false;
  const l = cl[0];
  for (const C of clauses) {
    if (!C.includes(-l)) continue;
    const res = cl.slice();
    for (const x of C) { if (x === -l) continue; if (!res.includes(x)) res.push(x); }
    if (res.some(x => res.includes(-x))) continue;
    if (!isRUP(clauses, res)) return false;
  }
  return true;
}
// A proof line is either a clause to add, or {del: [...]}: a deletion, which a
// DRAT checker performs without checking anything. Deletion is sound because
// removing clauses can only make the empty clause harder to derive; it is not
// harmless, because a later line may have needed the clause.
const same = (a, b) => a.length === b.length &&
  a.slice().sort((x, y) => x - y).join(',') === b.slice().sort((x, y) => x - y).join(',');
function checkDRAT(proof) {
  let F = sumFormula9().map(c => c.slice());
  const status = [];
  for (const raw of proof) {
    if (raw && raw.del) {
      const i = F.findIndex(c => same(c, raw.del));
      if (i >= 0) F = F.slice(0, i).concat(F.slice(i + 1));
      status.push('delete');
      continue;
    }
    const line = raw;
    const rup = isRUP(F, line);
    const rat = line.length ? isRAT(F, line) : false;
    if (!rup && !rat) { status.push('reject'); return { status, refuted: false }; }
    status.push(rup ? 'RUP' : 'RAT');
    F = F.concat([line.slice()]);
    if (line.length === 0) return { status, refuted: true };
  }
  return { status, refuted: false };
}

section('the nine-variable analogue');
{
  const T = sumTriples9(), F = sumFormula9();
  eq('solutions of a+b=c with a<b<c in 1..9', T.length, 16);
  eq('clauses', F.length, 32);
  let proper = 0, sat = 0;
  for (let m = 0; m < 512; m++) {
    let good = true;
    for (const [a, b, c] of T) {
      const x = (m >> (a - 1)) & 1, y = (m >> (b - 1)) & 1, z = (m >> (c - 1)) & 1;
      if (x === y && y === z) { good = false; break; }
    }
    if (good) proper++;
    let s = true;
    for (const cl of F) {
      let hit = false;
      for (const l of cl) { const v = (m >> (Math.abs(l) - 1)) & 1; if ((l > 0 && v) || (l < 0 && !v)) { hit = true; break; } }
      if (!hit) { s = false; break; }
    }
    if (s) sat++;
  }
  eq('colourings of 1..9 with no monochromatic solution', proper, 0);
  eq('assignments satisfying the CNF', sat, 0);
  ok('the direct rule and the clause set agree on all 512', proper === sat);
}

section('the four published DRAT lines');
{
  // Pinned from the artifact page's "Proof Example": "1 4 0", "1 0", "4 0", "0".
  const PUBLISHED_PROOF = [[1, 4], [1], [4], []];
  // the page's own PROOF_DEFAULT must be these same four lines
  const m = html.match(/var\s+PROOF_DEFAULT\s*=\s*\[([^\]]*)\]/);
  ok('the page ships a PROOF_DEFAULT', !!m);
  const pageProof = m[1].split(',').map(s => s.trim().replace(/^'|'$/g, ''))
    .map(s => s.length ? s.split(/\s+/).map(Number) : []);
  ok('the page\'s four lines are the published ones',
     JSON.stringify(pageProof) === JSON.stringify(PUBLISHED_PROOF),
     JSON.stringify(pageProof));

  const r = checkDRAT(PUBLISHED_PROOF);
  ok('the published proof is accepted and derives the empty clause', r.refuted);
  eq('line verdicts', r.status.join(','), 'RUP,RAT,RAT,RUP');
  eq('lines accepted by plain RUP', r.status.filter(s => s === 'RUP').length, 2);
  eq('lines that need the RAT rule', r.status.filter(s => s === 'RAT').length, 2);
  R_dratrup = r.status.filter(s => s === 'RUP').length;
  R_dratrat = r.status.filter(s => s === 'RAT').length;

  // The page offers two deletion buttons and its foot says one is harmless and
  // one is fatal. That is a claim about behaviour, so it is checked here.
  const withDel = d => [[1, 4], [1], [4], { del: d }, []];
  const harmless = checkDRAT(withDel([1, 4]));
  const fatal = checkDRAT(withDel([1]));
  ok('deleting (1 or 4) before the last line leaves the proof accepted', harmless.refuted);
  ok('deleting the unit (1) before the last line breaks the proof', !fatal.refuted);
  eq('the broken run ends in a rejection', fatal.status[fatal.status.length - 1], 'reject');
  ok('the page ships both deletion buttons', /d 1 4<\/span><\/button>/.test(html) && /d 1<\/span><\/button>/.test(html));
  ok('the page says one deletion is harmless and one is fatal',
     html.replace(/\s+/g, ' ').includes('One of them is harmless and one of them is fatal.'));
  ok('the page states that deletion lines are not checked',
     html.replace(/\s+/g, ' ').includes('Deletion lines are not checked at all, by design'));

  // mutation sweep: the checker must actually reject damage
  const mutations = [
    { name: 'first line literal changed (1 4 -> 1 5)', p: [[1, 5], [1], [4], []] },
    { name: 'unit line negated (1 -> -1)', p: [[1, 4], [-1], [4], []] },
    { name: 'second unit negated (4 -> -4)', p: [[1, 4], [1], [-4], []] },
    { name: 'a line deleted', p: [[1, 4], [1], []] },
    { name: 'lines reordered', p: [[1], [1, 4], [4], []] },
    { name: 'empty clause moved first', p: [[], [1, 4], [1], [4]] },
    { name: 'a literal appended to a unit (1 -> 1 2)', p: [[1, 4], [1, 2], [4], []] }
  ];
  let rejected = 0;
  for (const mu of mutations) {
    const res = checkDRAT(mu.p);
    if (!res.refuted) { rejected++; }
    else { console.log(`       (mutation still accepted: ${mu.name})`); }
  }
  eq('mutations the checker refuses', rejected, mutations.length);
}

// ---------------------------------------------------------------------------
// 4b. Cube and conquer on the nine-variable analogue, written independently of
// the page: split on the k most frequently occurring variables, refute each
// cube, and check that the cubes cover every one of the 512 colourings.
// ---------------------------------------------------------------------------
section('cube and conquer, reproduced');
function splitOrder9() {
  const cnt = new Map();
  for (const cl of sumFormula9()) for (const l of cl) {
    const v = Math.abs(l); cnt.set(v, (cnt.get(v) || 0) + 1);
  }
  const vs = [1, 2, 3, 4, 5, 6, 7, 8, 9];
  vs.sort((a, b) => (cnt.get(b) - cnt.get(a)) || (a - b));
  return vs;
}
function cubeAndConquer9(k) {
  const F = sumFormula9(), ord = splitOrder9().slice(0, k);
  let cubes = 1 << k, byProp = 0, searched = 0, examined = 0, models = 0, covered = 0, dup = 0;
  const seen = new Set();                       // every colouring, exactly once
  for (let m = 0; m < cubes; m++) {
    const fixed = new Map();
    for (let j = 0; j < k; j++) fixed.set(ord[j], ((m >> j) & 1) === 1);
    covered += 1 << (9 - k);
    if (propagate(F, new Map(fixed))) { byProp++; }
    else {
      searched++;
      const free = [];
      for (let v = 1; v <= 9; v++) if (!fixed.has(v)) free.push(v);
      examined += 1 << free.length;
      for (let mm = 0; mm < (1 << free.length); mm++) {
        const asg = new Array(10);
        for (const [v, b] of fixed) asg[v] = b ? 1 : 0;
        for (let j = 0; j < free.length; j++) asg[free[j]] = (mm >> j) & 1;
        let sat = true;
        for (const cl of F) {
          let hit = false;
          for (const l of cl) if ((l > 0 && asg[Math.abs(l)] === 1) || (l < 0 && asg[Math.abs(l)] === 0)) { hit = true; break; }
          if (!hit) { sat = false; break; }
        }
        if (sat) models++;
      }
    }
    // coverage, checked rather than asserted: enumerate the colourings this cube owns
    const free = [];
    for (let v = 1; v <= 9; v++) if (!fixed.has(v)) free.push(v);
    for (let mm = 0; mm < (1 << free.length); mm++) {
      let code = 0;
      for (const [v, b] of fixed) if (b) code |= 1 << (v - 1);
      for (let j = 0; j < free.length; j++) if ((mm >> j) & 1) code |= 1 << (free[j] - 1);
      if (seen.has(code)) dup++;
      seen.add(code);
    }
  }
  return { cubes, byProp, searched, examined, models, covered, dup,
           distinct: seen.size, missed: 512 - seen.size, vars: ord };
}
{
  eq('most-occurring-first split order on the nine-variable formula',
     splitOrder9().join(','), '1,2,3,5,4,6,7,8,9');
  const r3 = cubeAndConquer9(3);
  eq('k = 3: cubes', r3.cubes, 8);
  eq('k = 3: cubes refuted by unit propagation alone', r3.byProp, 6);
  eq('k = 3: cubes handed to the conquer phase', r3.searched, 2);
  eq('k = 3: colourings the conquer phase examined', r3.examined, 128);
  eq('k = 3: colourings covered', r3.covered, 512);
  eq('k = 3: distinct colourings covered', r3.distinct, 512);
  eq('k = 3: colourings covered by two cubes (the cubes must partition)', r3.dup, 0);
  eq('k = 3: colourings missed by every cube', r3.missed, 0);
  eq('k = 3: models found in any cube', r3.models, 0);
  const r4 = cubeAndConquer9(4);
  eq('k = 4: cubes', r4.cubes, 16);
  eq('k = 4: every cube dies to unit propagation', r4.byProp, 16);
  eq('k = 4: nothing left to search', r4.searched, 0);
  let deep = -1;
  for (let k = 0; k <= 9; k++) if (cubeAndConquer9(k).searched === 0) { deep = k; break; }
  eq('shallowest split depth at which the conquer phase is empty', deep, 4);
  R_cubecover = r3.distinct;
  R_cubedup = r3.dup;
  R_cubemodels = r3.models;
  R_cubedeep = deep;
  ok('the page names the two ways its miniature split differs from the published one',
     html.replace(/\s+/g, ' ').includes('its million cubes are not a uniform tree over one fixed variable list'));
}

// ---------------------------------------------------------------------------
// 5. The encoding is faithful: two routes over every colouring, small n.
// ---------------------------------------------------------------------------
section('encoding faithfulness by exhaustion, n = 1..20');
{
  let agree = 0, nonvacuous = 0;
  for (let n = 1; n <= 20; n++) {
    const T = triplesDirect(n);
    const F = [];
    for (const [a, b, c] of T) { F.push([a, b, c]); F.push([-a, -b, -c]); }
    let proper = 0, sat = 0;
    for (let m = 0; m < (1 << n); m++) {
      let good = true;
      for (const [a, b, c] of T) {
        const x = (m >> (a - 1)) & 1, y = (m >> (b - 1)) & 1, z = (m >> (c - 1)) & 1;
        if (x === y && y === z) { good = false; break; }
      }
      if (good) proper++;
      let s = true;
      for (const cl of F) {
        let hit = false;
        for (const l of cl) { const v = (m >> (Math.abs(l) - 1)) & 1; if ((l > 0 && v) || (l < 0 && !v)) { hit = true; break; } }
        if (!hit) { s = false; break; }
      }
      if (s) sat++;
    }
    if (proper === sat) agree++;
    if (T.length > 0) nonvacuous++;
  }
  eq('values of n where the two routes agree', agree, 20);
  eq('values of n in 1..20 that are NOT vacuous (a triple exists)', nonvacuous, 16);
  // Negative control. A single flipped clause sign must change WHICH
  // assignments are accepted. (Counts alone are not enough: flipping one
  // literal of one clause can leave the totals equal by coincidence, which is
  // exactly what happens at n = 12. Comparing the accepted sets is the real test.)
  const T = triplesDirect(12);
  const Fgood = [], Fbad = [];
  for (const [a, b, c] of T) {
    Fgood.push([a, b, c]); Fgood.push([-a, -b, -c]);
    Fbad.push([a, b, c]); Fbad.push([-a, -b, c]);
  }
  const acc = F => {
    const s = new Set();
    for (let m = 0; m < (1 << 12); m++) {
      let good = true;
      for (const cl of F) {
        let hit = false;
        for (const l of cl) { const v = (m >> (Math.abs(l) - 1)) & 1; if ((l > 0 && v) || (l < 0 && !v)) { hit = true; break; } }
        if (!hit) { good = false; break; }
      }
      if (good) s.add(m);
    }
    return s;
  };
  const A = acc(Fgood), Bb = acc(Fbad);
  const symDiff = [...A].filter(x => !Bb.has(x)).length + [...Bb].filter(x => !A.has(x)).length;
  ok('a single flipped clause sign DOES change the accepted set (the test has teeth)',
     symDiff > 0, `${symDiff} assignments differ (sizes ${A.size} and ${Bb.size})`);
  ok('the correct clause set accepts exactly the proper colourings', (() => {
    for (const m of A) {
      for (const [a, b, c] of T) {
        const x = (m >> (a - 1)) & 1, y = (m >> (b - 1)) & 1, z = (m >> (c - 1)) & 1;
        if (x === y && y === z) return false;
      }
    }
    return true;
  })());
}

// ---------------------------------------------------------------------------
// 6. 2^7825, the size of the space the proof had to exclude.
// ---------------------------------------------------------------------------
section('the size of the search space');
{
  const str = (2n ** 7825n).toString();
  eq('decimal digits in 2^7825', str.length, 2356);
  R_pow2digits = str.length;
  // Correctly rounded first three significant digits, as an integer: 362|84...
  // rounds UP to 363. Truncation gives 362 and would render as "3.62", which
  // is what the page used to do and what its own cited source contradicts.
  let head = parseInt(str.slice(0, 3), 10);
  if (str.charCodeAt(3) >= 53) head += 1;
  eq('first three digits of 2^7825, correctly rounded', head, 363);
  R_pow2lead3 = head;
  ok('truncating instead of rounding would have given 362 (this is the bug that shipped)',
     parseInt(str.slice(0, 3), 10) === 362, `starts ${str.slice(0, 8)}`);
  // The artifact page (cs.utexas.edu/~marijn/ptn/, retrieved 31 July 2026) says
  // "approximately 3.63 * 10^2355, that is, a number with 2356 decimal places".
  const n362 = (html.match(/3\.62/g) || []).length;
  ok('the only 3.62 left in the page is the comment recording the bug',
     n362 === 1 && html.replace(/\s+/g, ' ').includes('truncates to 3.62 and rounds to 3.63'),
     `${n362} occurrence(s)`);
  ok('the page derives the mantissa by rounding, not by slicing three digits',
     /function round3\(str\)/.test(html) && /charCodeAt\(3\) >= 53/.test(html));
}

// ---------------------------------------------------------------------------
// 7. THE COUPLING: every number above, against the page's own shipped values.
// ---------------------------------------------------------------------------
section('the page\'s shipped numbers, compared against everything recomputed above');
// Every entry below is a variable computed earlier in this file. Nothing here is
// a literal: a literal would make this table agree with the page by assertion
// rather than by computation, which is the failure mode this file exists to
// prevent.
const RATIOS = {
  dec: Math.round(200 * 1e12 / (68 * 1e9)),
  bin: Math.round(200 * 2 ** 40 / (68 * 2 ** 30)),
  mixlo: Math.round(200 * 1e12 / (68 * 2 ** 30)),
  mixhi: Math.round(200 * 2 ** 40 / (68 * 1e9))
};
const RECOMPUTED = {
  triples7824: T7824.length,
  triples7825: T7825.length,
  clauses7824: T7824.length * 2,
  clauses7825: T7825.length * 2,
  euclid7825: T7825e.length,
  negsym: R_negsym,
  bcetriples: B.L.length,
  bceremoved: T7825.length - B.L.length,
  bcevars: B.vars.size,
  bcerounds: B.rounds,
  sumtriples: sumTriples9().length,
  sumclauses: sumFormula9().length,
  sumproper: 0,
  dratrup: R_dratrup,
  dratrat: R_dratrat,
  cubecover: R_cubecover,
  cubedup: R_cubedup,
  cubemodels: R_cubemodels,
  cubedeep: R_cubedeep,
  bbunits: R_bbunits,
  bbdisagree: R_bbdisagree,
  hingeopp: R_hingeopp,
  freenums: R_free,
  critical: R_critical,
  slack: R_slack,
  pow2digits: R_pow2digits,
  pow2lead3: R_pow2lead3,
  ratiodec: RATIOS.dec,
  ratiobin: RATIOS.bin,
  ratiomixlo: RATIOS.mixlo,
  ratiomixhi: RATIOS.mixhi
};
// sumproper is the only entry above that is not carried in a variable, so it is
// recomputed right here rather than trusted.
{
  let proper = 0;
  for (let m = 0; m < 512; m++) {
    let good = true;
    for (const [a, b, c] of sumTriples9()) {
      const x = (m >> (a - 1)) & 1, y = (m >> (b - 1)) & 1, z = (m >> (c - 1)) & 1;
      if (x === y && y === z) { good = false; break; }
    }
    if (good) proper++;
  }
  RECOMPUTED.sumproper = proper;
  eq('proper colourings of 1..9 (recomputed for the ledger)', proper, 0);
}
for (const [k, v] of Object.entries(RECOMPUTED)) {
  ok(`ledger value ${k} came from a computation, not a literal`, Number.isInteger(v), `= ${v}`);
}
{
  const m = html.match(/var\s+EXPECTED\s*=\s*\{([\s\S]*?)\};/);
  ok('the page ships an EXPECTED ledger', !!m);
  const shipped = {};
  for (const mm of m[1].matchAll(/([A-Za-z0-9_]+)\s*:\s*(-?\d+)/g)) shipped[mm[1]] = Number(mm[2]);
  eq('ledger entries in the page', Object.keys(shipped).length, Object.keys(RECOMPUTED).length);
  for (const k of Object.keys(RECOMPUTED)) {
    ok(`page EXPECTED.${k}`, shipped[k] === RECOMPUTED[k],
       `page says ${shipped[k]}, recomputed ${RECOMPUTED[k]}`);
  }
  // every ledger key must also have a row, or it is a value nothing displays
  const rows = [...html.matchAll(/\['([A-Za-z0-9_]+)',\s*'[^']*'\],?\s*(?=\n)/g)].map(x => x[1]);
  for (const k of Object.keys(shipped)) {
    ok(`EXPECTED.${k} has a visible row in CHECK_ROWS`, rows.includes(k));
  }
  // and every recorded() call must name a key the ledger knows about: a write to
  // an unknown key is a dead write that silently repaints the check panel.
  // recorded() is called with a literal key everywhere except the size table,
  // where the key is built as 'triples' + n for n in {7824, 7825}. Expand those.
  const written = new Set([...html.matchAll(/recorded\('([A-Za-z0-9_]+)'/g)].map(x => x[1]));
  for (const mm of html.matchAll(/recorded\('([A-Za-z0-9_]+)'\s*\+\s*n\b/g)) {
    written.delete(mm[1]);
    written.add(mm[1] + '7824');
    written.add(mm[1] + '7825');
  }
  for (const k of written) ok(`recorded('${k}') is a key the ledger declares`, shipped[k] !== undefined);
  for (const k of Object.keys(shipped)) ok(`ledger key ${k} is actually written by a bench`, written.has(k));
}
{
  // the PUBLISHED header table the page draws must match the vendored files
  const rows = [...html.matchAll(/\{\s*file:'([^']+)',\s*n:(\d+),\s*vars:(\d+),\s*clauses:(\d+)\s*\}/g)];
  eq('published-header rows shipped in the page', rows.length, 3);
  for (const r of rows) {
    const { header } = readCNF(r[1]);
    eq(`page header row ${r[1]} vars`, Number(r[3]), header.vars);
    eq(`page header row ${r[1]} clauses`, Number(r[4]), header.clauses);
  }
  // and the page must not claim the browser compares more than a header
  ok('the page does not claim the browser compares the bce triple SET',
     !/Not just the count: the set\./.test(html));
  ok('the page says the set comparison is offline',
     html.replace(/\s+/g, ' ').includes('it is not running in this tab'));
  ok('the page says the header table is a hand transcription',
     html.replace(/\s+/g, ' ').includes('transcribed by hand into this page\'s source'));
}
{
  // EVERY number written into the page's prose with data-key must be a ledger
  // key, and must equal the recomputed value. The previous version of this file
  // checked three of six by hand, and a key that no bench ever recomputed
  // (formulas: 1,000,001) slipped through wearing the same styling.
  const found = {};
  for (const mm of html.matchAll(/data-key="([A-Za-z0-9_]+)"[^>]*>([^<]*)</g)) {
    found[mm[1]] = mm[2].trim();
  }
  const keys = Object.keys(found);
  ok('the page carries at least six prose numbers', keys.length >= 6, `found ${keys.length}: ${keys.join(', ')}`);
  for (const k of keys) {
    ok(`prose data-key ${k} is a key some bench recomputes`, RECOMPUTED[k] !== undefined,
       `value in prose: ${found[k]}`);
    if (RECOMPUTED[k] !== undefined) {
      eq(`prose ${k} equals the recomputed value`,
         Number(found[k].replace(/,/g, '')), RECOMPUTED[k]);
    }
  }
  // the cited-but-not-recomputed figure must NOT wear the ledger's data-key
  ok('the cited 1,000,001 is present', html.includes('1,000,001'));
  ok('and it is not dressed as a recomputed number', !/data-key="formulas"/.test(html));
  ok('and the page says so in the sentence that introduces it',
     html.replace(/\s+/g, ' ').includes('not recomputed anywhere on this page, which is why it does not appear in the ledger below'));
  ok('the summary sentence counts prose keys instead of asserting they are all fine',
     /proseKeys\.length/.test(html) && !/all replaced by the recomputed value, none contradicted/.test(html));
}
{
  // the quoted, rounded figures must be present verbatim and unaltered
  const quotes = [
    'almost 200 terabytes',
    'a compressed certificate of 68 gigabytes',
    '1,000,000 top-level cubes',
    '800 cores, about 2 days',
    '2136 of the original 9472',
    '3745 propositional variables actually used',
    'the largest math proof ever',
    'was asked by Ronald Graham in the 1980s',
    'the $100 we got',
    'A prize for the\n    solution was offered by Ronald Graham over two decades ago'
  ];
  const flat = html.replace(/\s+/g, ' ');
  for (const q of quotes) ok(`page carries the sourced phrase: "${q.replace(/\s+/g, ' ')}"`, flat.includes(q.replace(/\s+/g, ' ')));
  // The artifact page dates the QUESTION to the 1980s; the abstract dates the
  // PRIZE only as "over two decades ago"; neither dates the money to the 1980s.
  // The page must keep those three facts apart.
  ok('page no longer merges the two source statements',
     !/In the 1980s Ronald Graham offered/.test(flat) &&
     !/offered one hundred dollars/.test(flat));
  ok('page says outright that the two sources date the two acts differently',
     flat.includes('The two sources date those two acts differently and neither dates the money'));
  ok('page does NOT quote a compression ratio as a fact',
     !/\b\d+(\.\d+)?\s*(x|times)\s*(smaller|compression)/i.test(html));
  ok('page no longer states the unreachable 2,900 to 3,200 interval',
     !/2,900/.test(html) && !/3,200/.test(html));
  ok('page states it does not replay the certificate',
     /does <em>not<\/em> replay the\s*68-gigabyte certificate/.test(html.replace(/\s+/g, ' ')));
  ok('page scopes its speed claim to a measurement rather than a boast',
     flat.includes('a phone is several times slower than a desktop') &&
     !flat.includes('runs in a browser tab in well under a second'));
  ok('page tells the reader the tape is clickable',
     flat.includes('Click any cell to flip that number'));
  ok('page legend no longer says simply "in no triple"',
     !flat.includes('>in no triple (free)<'));
}

// ---------------------------------------------------------------------------
// 8. Report.
// ---------------------------------------------------------------------------
console.log('\n== scope');
console.log('  This verifier does NOT independently reprove that the 7825 formula is');
console.log('  unsatisfiable. No full-certificate mode has been run. That claim is cited');
console.log('  (Heule, Kullmann & Marek 2016; Cruz-Filipe, Marques-Silva & Schneider-Kamp 2019),');
console.log('  not reproduced here. What is reproduced: the triple census by two methods, the');
console.log('  clause encoding against the authors\' own CNF files, the blocked-clause-elimination');
console.log('  fixpoint against bce7825.cnf, the witness for 1..7824, the backbone blob against');
console.log('  backbone7824.cnf, the hinge arithmetic, and the four-line DRAT refutation with a');
console.log('  seven-way mutation sweep.');

const total = pass + fail;
console.log(`\n${fail === 0 ? 'PASS' : 'FAIL'}  ${pass}/${total} checks`);
if (fail) { console.log('failed: ' + failures.join('; ')); process.exit(1); }
process.exit(0);
