#!/usr/bin/env node
/*
  verify-sudoku-16-clue.mjs

  Recomputes every number the stratum prints, and compares against what the
  shipped HTML actually contains.

  The page marks each printed number with data-claim="<id>". This script reads
  public/strata/sudoku-16-clue/index.html, pulls those attributes and the four
  puzzle strings out of the file itself, and recomputes each value with a solver
  written independently of the browser's (plain per-node candidate recomputation
  and an explicit MRV scan, no incremental trail, no shared code).

  What this script does NOT do: it does not rerun the 5,472,730,538-class
  exhaustive census of McGuire, Tugemann and Civario. That computation took about
  7.1 million core hours and is cited on the page as archival, never as a live
  check. The two numbers taken on citation here (6,670,903,752,021,072,936,960
  completed grids and 5,472,730,538 equivalence classes) are only cross-checked
  for arithmetic consistency against the order of the sudoku symmetry group.

  Exit code 0 = every check passed.
*/

import { readFileSync, existsSync, statSync } from 'node:fs';
import http from 'node:http';
import { fileURLToPath } from 'node:url';
import { dirname, resolve, join, extname, sep } from 'node:path';

const HERE = dirname(fileURLToPath(import.meta.url));
const PAGE = resolve(HERE, '../../public/strata/sudoku-16-clue/index.html');
const html = readFileSync(PAGE, 'utf8');

/* ------------------------------------------------------------------ */
/* an independent solver: recompute candidate masks at every node      */
/* ------------------------------------------------------------------ */
function makeSolver(N, BR, BC) {
  const NN = N * N, FULL = (1 << N) - 1, bpr = (N / BC) | 0;
  const boxOf = (r, c) => ((r / BR) | 0) * bpr + ((c / BC) | 0);
  const popcount = (m) => { let n = 0; while (m) { n += m & 1; m >>= 1; } return n; };

  /* returns { n, sols } with n capped at cap, keeping up to `keep` grids */
  return function solve(given, cap, keep = 2) {
    const rows = new Array(N).fill(0), cols = new Array(N).fill(0), boxes = new Array(N).fill(0);
    const g = Int8Array.from(given);
    for (let r = 0; r < N; r++) for (let c = 0; c < N; c++) {
      const v = g[r * N + c];
      if (!v) continue;
      const b = 1 << (v - 1), bx = boxOf(r, c);
      if ((rows[r] & b) || (cols[c] & b) || (boxes[bx] & b)) return { n: 0, sols: [] };
      rows[r] |= b; cols[c] |= b; boxes[bx] |= b;
    }
    let n = 0; const sols = [];
    function rec() {
      if (n >= cap) return;
      let best = -1, bestMask = 0, bestCnt = N + 1;
      scan: for (let r = 0; r < N; r++) for (let c = 0; c < N; c++) {
        const i = r * N + c;
        if (g[i]) continue;
        const m = FULL & ~(rows[r] | cols[c] | boxes[boxOf(r, c)]);
        const cnt = popcount(m);
        if (cnt === 0) return;
        if (cnt < bestCnt) { bestCnt = cnt; best = i; bestMask = m; if (cnt === 1) break scan; }
      }
      if (best < 0) { n++; if (sols.length < keep) sols.push(Int8Array.from(g)); return; }
      const r = (best / N) | 0, c = best % N, bx = boxOf(r, c);
      for (let v = 1; v <= N; v++) {
        const b = 1 << (v - 1);
        if (!(bestMask & b)) continue;
        g[best] = v; rows[r] |= b; cols[c] |= b; boxes[bx] |= b;
        rec();
        g[best] = 0; rows[r] &= ~b; cols[c] &= ~b; boxes[bx] &= ~b;
        if (n >= cap) return;
      }
    }
    rec();
    return { n, sols };
  };
}
const solve9 = makeSolver(9, 3, 3);
const solve4 = makeSolver(4, 2, 2);

const parse = (s) => Int8Array.from([...s].map(Number));
const commas = (s) => String(s).replace(/,/g, '');
const groupDigits = (v) => v.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');

/* ------------------------------------------------------------------ */
/* pull the page's own data out of the shipped file                    */
/* ------------------------------------------------------------------ */
function shippedString(name) {
  const m = html.match(new RegExp('var\\s+' + name + "\\s*=\\s*'([0-9]{81})'"));
  if (!m) throw new Error('could not find the shipped string ' + name + ' in the page');
  return m[1];
}
function printed(id) {
  const m = html.match(new RegExp('data-claim="' + id + '"[^>]*>([^<]*)<'));
  return m ? m[1].trim() : null;
}

const PUZ17 = shippedString('PUZ17');
const CANON = shippedString('CANON');
const GOOD18 = shippedString('GOOD18');
const NEAR18 = shippedString('NEAR18');

/* ------------------------------------------------------------------ */
/* the ledger                                                          */
/* ------------------------------------------------------------------ */
let pass = 0, fail = 0;
const failures = [];
/* every data-claim id this script actually recomputes, for the coverage test */
const VERIFIED = new Set();
function check(label, got, want) {
  const ok = String(got) === String(want);
  if (ok) pass++; else { fail++; failures.push(`${label}: recomputed ${got}, page says ${want}`); }
  console.log(`${ok ? 'ok  ' : 'FAIL'}  ${label.padEnd(58)} ${String(got)}`);
  return ok;
}
function claim(id, label, got) {
  VERIFIED.add(id);
  const want = printed(id);
  if (want === null) { fail++; failures.push(`${label}: no data-claim="${id}" found in the page`); console.log(`FAIL  ${label.padEnd(58)} (claim ${id} missing from page)`); return false; }
  return check(`${label} [${id}]`, commas(String(got)), commas(want));
}

console.log('recomputing everything the page prints\n');

/* ---- 1. the published 17-clue puzzle ------------------------------- */
const puz17 = parse(PUZ17);
const givens17 = [...puz17.keys()].filter((i) => puz17[i]);
claim('c17_clues', 'clues in the published puzzle', givens17.length);

const r17 = solve9(puz17, 3, 1);
claim('c17_sols', 'completions of the published puzzle', r17.n);

/* the completion is derived, never shipped: sanity-check it is a legal grid */
{
  const sol = r17.sols[0];
  let legal = true;
  for (let r = 0; r < 9; r++) {
    const rowSet = new Set(), colSet = new Set(), boxSet = new Set();
    for (let c = 0; c < 9; c++) {
      rowSet.add(sol[r * 9 + c]); colSet.add(sol[c * 9 + r]);
      boxSet.add(sol[(((r / 3) | 0) * 3 + ((c / 3) | 0)) * 9 + ((r % 3) * 3 + (c % 3))]);
    }
    if (rowSet.size !== 9 || colSet.size !== 9 || boxSet.size !== 9) legal = false;
  }
  for (const i of givens17) if (sol[i] !== puz17[i]) legal = false;
  check('the unique completion is a legal grid agreeing with all 17 clues', legal, true);
}

/* every single-clue deletion must leave at least two completions */
{
  let stillAmbiguous = 0;
  for (const i of givens17) {
    const p = Int8Array.from(puz17); p[i] = 0;
    if (solve9(p, 2, 0).n >= 2) stillAmbiguous++;
  }
  claim('c17_del', 'deletions leaving at least 2 completions', stillAmbiguous);
}

/* the page's claim that the deleted clue always sits inside the disagreement set:
   restoring the clue's own value to the 16-clue puzzle must bring uniqueness back,
   so every alternative completion has to differ from the original at that cell */
{
  let allInside = true;
  const sol = r17.sols[0];
  for (const i of givens17) {
    const p = Int8Array.from(puz17); p[i] = 0; p[i] = sol[i];
    if (solve9(p, 2, 0).n !== 1) allInside = false;
  }
  check('the deleted clue is inside every disagreement set', allInside, true);
}

/* the page shrinks the disagreement patch until no single cell can be dropped.
   Reimplemented here with a fixed order: the result must be a genuine unavoidable
   set containing the deleted clue, and single-cell removal must always break it. */
{
  const sol = r17.sols[0];
  const witnessOn = (set, x) => {
    const base = Int8Array.from(sol);
    for (const i of set) base[i] = 0;
    for (let d = 1; d <= 9; d++) {
      if (d === sol[x]) continue;
      const q = Int8Array.from(base); q[x] = d;
      if (solve9(q, 1, 0).n > 0) return true;
    }
    return false;
  };
  let ok = true, sizes = [];
  for (const x of givens17) {
    let U = [];
    for (let i = 0; i < 81; i++) if (!puz17[i] || i === x) U.push(i);
    if (!witnessOn(U, x)) { ok = false; continue; }
    let changed = true;
    while (changed) {
      changed = false;
      for (const c of U.slice()) {
        if (c === x) continue;
        const trial = U.filter((k) => k !== c);
        if (witnessOn(trial, x)) { U = trial; changed = true; }
      }
    }
    sizes.push(U.length);
    if (!U.includes(x)) ok = false;                       /* the clue is inside the patch */
    if (!witnessOn(U, x)) ok = false;                     /* the patch really is unavoidable */
    for (const c of U) {                                  /* and nothing can be dropped */
      if (c === x) continue;
      if (witnessOn(U.filter((k) => k !== c), x)) ok = false;
    }
    if (U.length < 4) ok = false;                         /* no unavoidable set is smaller than 4 */
  }
  check(`each deleted clue sits in a drop-nothing unavoidable patch (sizes ${Math.min(...sizes)} to ${Math.max(...sizes)})`, ok, true);
  check('the tightest patch is 4 cells, as the page says', Math.min(...sizes) === 4 && /come down to four cells/.test(html), true);
  /* the size-4 patches really are swappable rectangles: two digits, two rows, two columns */
  {
    let rectanglesOnly = true;
    for (const x of givens17) {
      let U = [];
      for (let i = 0; i < 81; i++) if (!puz17[i] || i === x) U.push(i);
      if (!witnessOn(U, x)) continue;
      let changed = true;
      while (changed) {
        changed = false;
        for (const c of U.slice()) {
          if (c === x) continue;
          const trial = U.filter((k) => k !== c);
          if (witnessOn(trial, x)) { U = trial; changed = true; }
        }
      }
      if (U.length !== 4) continue;
      const rows = new Set(U.map((i) => (i / 9) | 0));
      const cols = new Set(U.map((i) => i % 9));
      const vals = new Set(U.map((i) => sol[i]));
      if (rows.size !== 2 || cols.size !== 2 || vals.size !== 2) rectanglesOnly = false;
    }
    check('every 4-cell patch is a two-digit rectangle', rectanglesOnly, true);
  }
}

/* legal digits at each vacated clue cell: deterministic, order-independent */
{
  let mn = 99, mx = 0, sum = 0;
  for (const i of givens17) {
    const p = Int8Array.from(puz17); p[i] = 0;
    let k = 0;
    for (let d = 1; d <= 9; d++) {
      const q = Int8Array.from(p); q[i] = d;
      if (solve9(q, 1, 0).n > 0) k++;
    }
    mn = Math.min(mn, k); mx = Math.max(mx, k); sum += k;
  }
  claim('c17_digmin', 'fewest legal digits at a vacated clue cell', mn);
  claim('c17_digmax', 'most legal digits at a vacated clue cell', mx);
  claim('c17_digsum', 'legal digits summed over the 17 deletions', sum);
}

/* ---- 2. the size of the naive search ------------------------------- */
{
  let v = 1n;
  for (let i = 0n; i < 16n; i++) v = (v * (81n - i)) / (i + 1n);
  claim('c81_16', 'ways to choose 16 cells from 81', groupDigits(v));
}

/* ---- 3. group arithmetic on the two cited counts -------------------- */
{
  const rowMoves = 6n * 6n * 6n * 6n;            /* order the bands, order rows in each band */
  const positional = rowMoves * rowMoves * 2n;   /* rows, columns, transpose */
  let factorial9 = 1n;
  for (let i = 2n; i <= 9n; i++) factorial9 *= i;
  const full = positional * factorial9;
  claim('grp_rows', 'row moves', groupDigits(rowMoves));
  claim('grp_relabel', 'digit relabellings (9!)', groupDigits(factorial9));
  claim('grp_pos', 'positional symmetries', groupDigits(positional));
  claim('grp_full', 'full sudoku group order', groupDigits(full));

  const N0 = 6670903752021072936960n, classes = 5472730538n;
  const pct = (Number(N0) / Number(classes)) / Number(full) * 100;
  claim('grp_pct', 'published grids / classes as % of group order', pct.toFixed(4));
  /* the reconciliation the page prints beside the paper's 3.6 s per grid */
  claim('secpergrid', 'core-seconds per class from the two cited figures',
    (7.1e6 * 3600 / Number(classes)).toFixed(1));

  /* the cited numbers themselves must be present and flagged as citations */
  check('page carries the cited grid count 6,670,903,752,021,072,936,960',
    /data-cited="N0"[^>]*>6,670,903,752,021,072,936,960</.test(html), true);
  check('page carries the cited class count 5,472,730,538',
    /data-cited="classes"[^>]*>5,472,730,538</.test(html), true);
  check('page carries the cited compute figure 7.1 million core hours',
    /data-cited="corehours"[^>]*>7\.1 million core hours</.test(html), true);
  check('page states the census is not rerun here',
    /not rerun here/i.test(html), true);
}

/* ---- 4. the complete 4x4 census ------------------------------------ */
const all4 = solve4(new Int8Array(16), 1e6, 1e6);
claim('grid4', 'completed 4x4 grids', all4.n);

function combos(n, k) {
  const out = [], ix = [];
  (function rec(start) {
    if (ix.length === k) { out.push(ix.slice()); return; }
    for (let i = start; i < n; i++) { ix.push(i); rec(i + 1); ix.pop(); }
  })(0);
  return out;
}
{
  const tested = { 1: 0, 2: 0, 3: 0, 4: 0 }, proper = { 1: 0, 2: 0, 3: 0, 4: 0 };
  let firstFour = null;
  const subs = { 1: combos(16, 1), 2: combos(16, 2), 3: combos(16, 3), 4: combos(16, 4) };
  for (const G of all4.sols) {
    for (const k of [1, 2, 3, 4]) {
      for (const ix of subs[k]) {
        const p = new Int8Array(16);
        for (const i of ix) p[i] = G[i];
        tested[k]++;
        if (solve4(p, 2, 0).n === 1) {
          proper[k]++;
          if (k === 4 && !firstFour) firstFour = { G: Array.from(G), ix: ix.slice() };
        }
      }
    }
  }
  claim('sub4_le3', '4x4 subsets of 3 clues or fewer tested', groupDigits(tested[1] + tested[2] + tested[3]));
  claim('prop4_le3', 'of those, proper', proper[1] + proper[2] + proper[3]);
  claim('sub4_4', '4x4 four-clue subsets tested', groupDigits(tested[4]));
  claim('prop4_4', 'of those, proper', groupDigits(proper[4]));
  claim('sub4_pergrid', 'subsets of size 1 to 4 per grid',
    groupDigits(subs[1].length + subs[2].length + subs[3].length + subs[4].length));
  claim('sub4_total', 'uniqueness tests in the whole census',
    groupDigits(tested[1] + tested[2] + tested[3] + tested[4]));
  let scs4 = 0;
  for (const k of [1, 2, 3, 4]) if (!scs4 && proper[k] > 0) scs4 = k;
  claim('scs4', 'minimum clues for 4x4', scs4);

  /* not tautological: uniqueness must be invariant under the 4x4 sudoku group,
     so a wrong solver or a wrong box map shows up as a broken invariance */
  const perms3 = [];
  (function permute(arr, k) {
    if (k === arr.length) { perms3.push(arr.slice()); return; }
    for (let i = k; i < arr.length; i++) { [arr[k], arr[i]] = [arr[i], arr[k]]; permute(arr, k + 1); [arr[k], arr[i]] = [arr[i], arr[k]]; }
  })([0, 1, 2, 3], 0);
  const rowPerms = [];
  for (const bandOrder of [[0, 1], [1, 0]])
    for (const a of [[0, 1], [1, 0]])
      for (const b of [[0, 1], [1, 0]]) {
        const p = [];
        for (const band of bandOrder) {
          const inner = band === bandOrder[0] ? a : b;
          for (const r of inner) p.push(band * 2 + r);
        }
        rowPerms.push(p);
      }
  const base = firstFour;
  let invariance = true, transformsTried = 0;
  for (const rp of rowPerms) for (const cp of rowPerms) for (const relabel of perms3) for (const T of [false, true]) {
    const q = new Int8Array(16);
    for (let r = 0; r < 4; r++) for (let c = 0; c < 4; c++) {
      const src = base.ix.includes(rp[r] * 4 + cp[c]) ? base.G[rp[r] * 4 + cp[c]] : 0;
      const v = src ? relabel[src - 1] + 1 : 0;
      q[T ? c * 4 + r : r * 4 + c] = v;
    }
    transformsTried++;
    if (solve4(q, 2, 0).n !== 1) invariance = false;
  }
  check(`uniqueness invariant across ${transformsTried} 4x4 symmetry images`, invariance, true);

  /* the first proper 4-clue puzzle is minimal: pull any clue and it breaks */
  let minimal = true;
  for (const i of base.ix) {
    const p = new Int8Array(16);
    for (const j of base.ix) if (j !== i) p[j] = base.G[j];
    if (solve4(p, 2, 0).n === 1) minimal = false;
  }
  check('the exhibited 4-clue puzzle is minimal', minimal, true);
}

/* ---- 5. the structured grid and its nine degree-2 regions ---------- */
const canon = parse(CANON);
{
  /* rebuild Figure 10 from its structure rather than trusting the string:
     row R = 3*band + i, value at column C is ((C + 3i + band) mod 9) + 1 */
  let rebuilt = '';
  for (let R = 0; R < 9; R++) {
    const band = (R / 3) | 0, i = R % 3;
    for (let C = 0; C < 9; C++) rebuilt += String(((C + 3 * i + band) % 9) + 1);
  }
  check('the shipped Figure 10 string is the structured grid', rebuilt === CANON, true);
  check('Figure 10 is a legal completed grid with exactly one completion', solve9(canon, 2, 0).n, 1);
}

/* the page's region rule, read out of the page and rebuilt here */
{
  const m = html.match(/function regionOf\(i\)\s*\{\s*return ([^;]+);/);
  check('page defines regionOf as band-of-row times three plus column mod three',
    m && m[1].replace(/\s+/g, '') === '3*((((i/9)|0)/3)|0)+((i%9)%3)', true);
}
const regionOf = (i) => 3 * ((((i / 9) | 0) / 3) | 0) + ((i % 9) % 3);
const REGIONS = Array.from({ length: 9 }, () => []);
for (let i = 0; i < 81; i++) REGIONS[regionOf(i)].push(i);

claim('reg_n', 'regions in the structured grid', REGIONS.length);
claim('reg_size', 'cells per region', new Set(REGIONS.map((u) => u.length)).size === 1 ? REGIONS[0].length : 'ragged');
claim('reg_cover', 'distinct cells covered by the regions', new Set(REGIONS.flat()).size);

{
  /* withdrawing one region entirely */
  const p = Int8Array.from(canon);
  for (const i of REGIONS[0]) p[i] = 0;
  const blank = solve9(p, 1e6, 1).n;
  claim('reg_blank', 'completions when one region is withdrawn', blank);

  /* the same for all nine regions, to be sure the tinting is uniform */
  let sameEverywhere = true;
  for (const U of REGIONS) {
    const q = Int8Array.from(canon);
    for (const i of U) q[i] = 0;
    if (solve9(q, 1e6, 1).n !== blank) sameEverywhere = false;
  }
  check('all nine regions behave identically when withdrawn', sameEverywhere, true);
}
{
  /* degree 2: keep exactly one cell of a region and it is still ambiguous */
  let mn = Infinity, mx = 0;
  for (let i = 0; i < 81; i++) {
    const U = REGIONS[regionOf(i)];
    const p = Int8Array.from(canon);
    for (const j of U) if (j !== i) p[j] = 0;
    const n = solve9(p, 1e6, 1).n;
    mn = Math.min(mn, n); mx = Math.max(mx, n);
  }
  claim('reg_one', 'completions when a region keeps one clue', mn === mx ? mn : `${mn}-${mx}`);
  check('every one of the 81 cells leaves at least 2 completions', mn >= 2, true);
  claim('canon_lb', 'lower bound for the structured grid', mn >= 2 ? 2 * REGIONS.length : 'not established');
}
claim('reg_pairs', 'pairs of cells inside a region', (REGIONS[0].length * (REGIONS[0].length - 1)) / 2);
claim('reg_rest', 'cells outside a region', 81 - REGIONS[0].length);

/* the settling pairs of every region, kept: the sampler below draws from them */
const PAIRS = REGIONS.map((U) => {
  const out = [];
  for (let a = 0; a < U.length; a++) for (let b = a + 1; b < U.length; b++) {
    const p = Int8Array.from(canon);
    for (const j of U) if (j !== U[a] && j !== U[b]) p[j] = 0;
    if (solve9(p, 2, 0).n === 1) out.push([U[a], U[b]]);
  }
  return out;
});
{
  const counts = PAIRS.map((L) => L.length);
  claim('reg_pins', 'pairs inside a region that settle it', counts[0]);
  check('all nine regions have the same number of settling pairs', new Set(counts).size, 1);
  claim('pair_space', 'ways to give every region one of its settling pairs',
    groupDigits(counts.reduce((a, b) => a * b, 1)));
}

/* ---- 5b. the 3x3 Latin squares, counted without a sudoku solver ---- */
{
  const latin = (fixCorner) => {
    let n = 0;
    for (let code = 0; code < 19683; code++) {
      const a = []; let t = code;
      for (let i = 0; i < 9; i++) { a.push(t % 3); t = (t / 3) | 0; }
      if (fixCorner && a[0] !== 0) continue;
      let ok = true;
      for (let r = 0; r < 3 && ok; r++) {
        let m = 0; for (let c = 0; c < 3; c++) m |= 1 << a[r * 3 + c];
        if (m !== 7) ok = false;
      }
      for (let c = 0; c < 3 && ok; c++) {
        let m = 0; for (let r = 0; r < 3; r++) m |= 1 << a[r * 3 + c];
        if (m !== 7) ok = false;
      }
      if (ok) n++;
    }
    return n;
  };
  const l12 = latin(false), l4 = latin(true);
  claim('latin12', '3x3 Latin squares on three symbols', l12);
  claim('latin4', 'of those, with one entry fixed', l4);
  /* the two instruments have to agree: the region counts come from the sudoku
     solver on the whole grid, these come from enumerating 3x3 arrays */
  {
    const p = Int8Array.from(canon);
    for (const i of REGIONS[0]) p[i] = 0;
    check('the Latin-square count matches the region withdrawal', solve9(p, 1e6, 1).n, l12);
    const q = Int8Array.from(canon);
    for (const i of REGIONS[0]) if (i !== REGIONS[0][0]) q[i] = 0;
    check('the fixed-entry count matches a region keeping one clue', solve9(q, 1e6, 1).n, l4);
  }
}

/* ---- 5c. automorphisms: exhaust the positional group for three grids ---- */
{
  const perm3 = [];
  (function perm(a, k) {
    if (k === 3) { perm3.push(a.slice()); return; }
    for (let i = k; i < 3; i++) { [a[k], a[i]] = [a[i], a[k]]; perm(a, k + 1); [a[k], a[i]] = [a[i], a[k]]; }
  })([0, 1, 2], 0);
  const RP = [];
  for (const bands of perm3) for (const x of perm3) for (const y of perm3) for (const z of perm3) {
    const inner = [x, y, z], p = [];
    for (let bi = 0; bi < 3; bi++) for (const r of inner[bi]) p.push(bands[bi] * 3 + r);
    RP.push(p);
  }
  check('the positional row moves number 6 x 6^3', RP.length, 1296);

  let tried = 0;
  const autSplit = (g) => {
    const n = [0, 0];                              /* [without transpose, with transpose] */
    const rowsUsed = new Set(), colsUsed = new Set(), perRow = {};
    const map = new Int8Array(10);
    for (const rp of RP) for (const cp of RP) for (const T of [0, 1]) {
      map.fill(0);
      for (let c = 0; c < 9; c++) map[g[rp[0] * 9 + cp[c]]] = T ? g[c * 9] : g[c];
      let ok = true;
      for (let r = 0; r < 9 && ok; r++) for (let c = 0; c < 9; c++) {
        if (map[g[rp[r] * 9 + cp[c]]] !== (T ? g[c * 9 + r] : g[r * 9 + c])) { ok = false; break; }
      }
      tried++;
      if (ok) {
        n[T]++;
        if (!T) { rowsUsed.add(rp.join('')); colsUsed.add(cp.join('')); perRow[rp.join('')] = (perRow[rp.join('')] || 0) + 1; }
      }
    }
    return { n, total: n[0] + n[1], rowsUsed, colsUsed, perRow };
  };
  const autCount = (g) => autSplit(g).total;

  /* the comparison grid, rebuilt from the rule the page prints */
  const maxGrid = [];
  for (let R = 0; R < 9; R++) {
    const band = (R / 3) | 0, i = R % 3;
    for (let C = 0; C < 9; C++) {
      const stack = (C / 3) | 0, j = C % 3;
      maxGrid.push(3 * ((stack + i) % 3) + ((j + band) % 3) + 1);
    }
  }
  check('the comparison grid is a legal completed sudoku with one completion',
    solve9(Int8Array.from(maxGrid), 2, 0).n, 1);
  check('the comparison grid is not the shipped Figure 10 string',
    maxGrid.join('') !== CANON, true);

  /* Figure 10 transposed, first two bands swapped, every digit d -> d+1 */
  const rowMap = [3, 4, 5, 0, 1, 2, 6, 7, 8];
  const shuffled = [];
  for (let R = 0; R < 9; R++) for (let C = 0; C < 9; C++) shuffled.push((canon[C * 9 + rowMap[R]] % 9) + 1);
  check('the transformed copy is a legal completed sudoku', solve9(Int8Array.from(shuffled), 2, 0).n, 1);

  const sCanon = autSplit(Array.from(canon));
  const nCanon = sCanon.total;
  const nMax = autCount(maxGrid);
  const nImg = autCount(shuffled);
  /* the structure the README describes, asserted rather than asserted-at */
  check('no automorphism of Figure 10 involves a transposition', sCanon.n[1], 0);
  check('Figure 10: distinct row moves among its automorphisms', sCanon.rowsUsed.size, 18);
  check('Figure 10: distinct column moves among its automorphisms', sCanon.colsUsed.size, 6);
  check('Figure 10: every such row move pairs with exactly three column moves',
    new Set(Object.values(sCanon.perRow)).size === 1 && Object.values(sCanon.perRow)[0] === 3, true);
  claim('aut_pos', 'positional moves tried per grid', groupDigits(tried / 3));
  claim('aut_canon', 'automorphisms of Figure 10', nCanon);
  claim('aut_max', 'automorphisms of the comparison grid', nMax);
  claim('aut_img', 'automorphisms of the transformed copy', nImg);
  check('the automorphism count is invariant under an equivalence transformation', nImg, nCanon);
  check('Figure 10 is NOT in the class realising the maximum the paper reports', nCanon !== nMax, true);
  check("the page no longer calls Figure 10 the most symmetric grid",
    !/most symmetric\s+one there is/.test(html), true);
  check('the page quotes the paper on where 648 comes from',
    /largest automorphism group occurring has order 648/.test(html), true);
}

/* ---- 5d. the settling-pair sampler, same stream as the page ---- */
{
  const m = html.match(/var SAMPLE_N = (\d+), SAMPLE_SEED = (\d+);/);
  check('the page declares its sample size and seed', !!m, true);
  const N = m ? +m[1] : 0, SEED = m ? +m[2] : 0;
  /* mulberry32, written out again here rather than imported */
  let a = SEED;
  const rnd = () => {
    a |= 0; a = (a + 0x6D2B79F5) | 0;
    let t = Math.imul(a ^ (a >>> 15), 1 | a);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
  let hits = 0;
  for (let k = 0; k < N; k++) {
    const p = new Int8Array(81);
    for (let s = 0; s < 9; s++) {
      const L = PAIRS[s], pr = L[Math.floor(rnd() * L.length)];
      p[pr[0]] = canon[pr[0]]; p[pr[1]] = canon[pr[1]];
    }
    if (solve9(p, 2, 0).n === 1) hits++;
  }
  claim('samp_trials', 'draws in the sample', groupDigits(N));
  claim('samp_hits', 'proper puzzles among them', hits);
  if (hits === 0) claim('samp_bound', 'rule-of-three limit, one in n', groupDigits(Math.round(N / 3)));
  else check('the page prints a measured rate, not a rule-of-three bound', printed('samp_bound') === null, true);

  /* GOOD18 must lie inside the space the sampler draws from, or the sample is
     answering a different question than the sentence it sits under */
  const g18 = parse(GOOD18);
  const inSpace = REGIONS.every((U, s) => {
    const kept = U.filter((i) => g18[i] !== 0);
    return kept.length === 2 && PAIRS[s].some(([x, y]) => x === kept[0] && y === kept[1]);
  });
  check('the proper 18 lies inside the sampled space', inSpace, true);

  /* the long offline run is a citation to a recorded artefact, not a rerun */
  const long = JSON.parse(readFileSync(resolve(HERE, 'longrun.json'), 'utf8'));
  const citedTrials = (html.match(/data-cited="longtrials"[^>]*>([^<]*)</) || [])[1];
  const citedHits = (html.match(/data-cited="longhits"[^>]*>([^<]*)</) || [])[1];
  check('the page cites the recorded long-run trial count', commas(citedTrials), String(long.trials));
  check('the page cites the recorded long-run hit count', commas(citedHits), String(long.hits));
  check('the recorded long run used the same seed as the sample', long.seed, SEED);
  check('the sample is a prefix of the long run', long.trials >= N, true);
  check('the long run is flagged on the page as not rerun in the tab',
    /not rerun in this tab/.test(html), true);
}

/* ---- 6. the two 18-clue certificates ------------------------------- */
function clueCount(s) { return [...s].filter((ch) => ch !== '0').length; }
function perRegion(s) {
  const c = new Array(9).fill(0);
  for (let i = 0; i < 81; i++) if (s[i] !== '0') c[regionOf(i)]++;
  return c;
}
function agreesWithCanon(s) {
  for (let i = 0; i < 81; i++) if (s[i] !== '0' && s[i] !== CANON[i]) return false;
  return true;
}

claim('near18_clues', 'clues in the near miss', clueCount(NEAR18));
claim('near18_min', 'fewest clues in any region of the near miss', Math.min(...perRegion(NEAR18)));
claim('near18_sols', 'completions of the near miss (full enumeration)', solve9(parse(NEAR18), 1e6, 1).n);
check('the near miss agrees with Figure 10 everywhere it speaks', agreesWithCanon(NEAR18), true);
{
  /* the page's headline claim about the near miss: each of its nine pairs
     would settle its own region if the rest of the grid were handed over */
  let allSettle = true;
  for (const U of REGIONS) {
    const kept = U.filter((i) => NEAR18[i] !== '0');
    if (kept.length !== 2) { allSettle = false; continue; }
    const p = Int8Array.from(canon);
    for (const j of U) if (!kept.includes(j)) p[j] = 0;
    if (solve9(p, 2, 0).n !== 1) allSettle = false;
  }
  check('every pair in the near miss settles its own region', allSettle, true);
}

claim('good18_clues', 'clues in the proper 18', clueCount(GOOD18));
claim('good18_sols', 'completions of the proper 18', solve9(parse(GOOD18), 3, 0).n);
check('the proper 18 agrees with Figure 10 everywhere it speaks', agreesWithCanon(GOOD18), true);
check('the proper 18 has exactly two clues in every region', new Set(perRegion(GOOD18)).size === 1 && perRegion(GOOD18)[0] === 2, true);
{
  let broke = 0;
  const p = parse(GOOD18);
  for (let i = 0; i < 81; i++) {
    if (!p[i]) continue;
    const q = Int8Array.from(p); q[i] = 0;
    if (solve9(q, 2, 0).n >= 2) broke++;
  }
  claim('good18_del', 'deletions of the proper 18 leaving 2 or more', broke);
}
{
  /* the lower bound, exercised: any 17 clues on this grid must fail */
  const p = parse(GOOD18);
  let allFail = true;
  for (let i = 0; i < 81; i++) {
    if (!p[i]) continue;
    const q = Int8Array.from(p); q[i] = 0;
    if (solve9(q, 2, 0).n === 1) allFail = false;
  }
  check('no 17-clue subset of the proper 18 is itself proper', allFail, true);
}

/* ---- 7. structural checks on the page ------------------------------ */
check('page ships a canonical link', /rel="canonical" href="https:\/\/artwaste\.land\/strata\/sudoku-16-clue\/"/.test(html), true);
check('page ships JSON-LD', /application\/ld\+json/.test(html), true);
check('page ships OG and Twitter cards', /property="og:image"/.test(html) && /name="twitter:card"/.test(html), true);
check('page has the closing script, body and html tags', /<\/script>\s*<\/body>\s*<\/html>/.test(html), true);
check('page guards prefers-reduced-motion by slowing, not zeroing',
  /prefers-reduced-motion: reduce/.test(html) && /reduce \? 5200 : 1500/.test(html), true);
/* The footer carries three citation links (doi.org, arxiv.org, afjarvis.org.uk).
   Those are navigations a reader chooses, not subresources, and they issue no
   request on load. What the house rule forbids is a third-party SUBRESOURCE, so
   that is what this checks, and the name says so. */
check('page loads no third-party subresource (src, stylesheet or script href)',
  !/(src|href)="https?:\/\/(?!artwaste\.land)/.test(
    html.replace(/<script type="application\/ld\+json">[\s\S]*?<\/script>/g, '')
        .replace(/<meta[^>]*>/g, '')
        .replace(/<footer[\s\S]*?<\/footer>/g, '')), true);
check('the only off-site hrefs are citation links in the footer',
  (html.match(/href="https?:\/\/(?!artwaste\.land)[^"]*"/g) || [])
    .every((h) => /doi\.org|arxiv\.org|afjarvis\.org\.uk/.test(h)), true);

/* ---- 8. the honesty rule, enforced mechanically ---------------------- */
{
  /* The check panel says every styled number carries data-claim or data-cited.
     That sentence is the one that licenses a reader to trust the figures, so it
     is tested rather than asserted. */
  /* markup only: the inline script builds selector strings that look like
     attributes, and they are not printed numbers */
  const markup = html.replace(/<script[\s\S]*?<\/script>/g, '');
  const spans = markup.match(/<span class="num[^"]*"[^>]*>/g) || [];
  const naked = spans.filter((s) => !/data-(claim|cited)=/.test(s));
  check(`every styled number carries data-claim or data-cited (${spans.length} spans)`, naked.length, 0);
  if (naked.length) for (const s of naked) failures.push('  naked number span: ' + s);

  /* and every data-claim on the page is one the audit and this script settle */
  const claimIds = [...markup.matchAll(/data-claim="([^"]+)"/g)].map((m) => m[1]);
  const dupes = claimIds.filter((id, i) => claimIds.indexOf(id) !== i);
  check('no data-claim id is used twice', dupes.length, 0);
  const audited = [...html.matchAll(/claim\('([a-z0-9_]+)'/g)].map((m) => m[1]);
  check('every printed data-claim is registered with the in-tab audit',
    claimIds.every((id) => audited.includes(id)), true);
  check('every printed data-claim is recomputed by this script',
    claimIds.every((id) => VERIFIED.has(id)), true);
  for (const id of claimIds) if (!VERIFIED.has(id)) failures.push('  data-claim never recomputed here: ' + id);

  /* the cited figures are declared, and each one appears where it is declared */
  const citedIds = new Set([...markup.matchAll(/data-cited="([^"]+)"/g)].map((m) => m[1]));
  check('the cited figures are the declared set',
    [...citedIds].sort().join(','),
    ['N0', 'classes', 'corehours', 'firstversion', 'longhits', 'longtrials',
     'procyears', 'scs6', 'scs8', 'scs9'].join(','));
}

/* ---- 9. the social card the head points at must exist ---------------- */
{
  const og = (html.match(/property="og:image" content="https:\/\/artwaste\.land(\/[^"]+)"/) || [])[1];
  check('the head names an og:image', !!og, true);
  check(`the og image exists on disk (${og})`, existsSync(resolve(HERE, '../../public' + og)), true);
}

/* ---- 10. the board a reader actually sees ---------------------------- */
/*
  Everything above this line reads the shipped HTML as text and recomputes the
  numbers written into it. That is a check on the file. It is not a check on the
  page: the boards here are built by the page's own script at load, so every
  digit a reader sees passed through code no assertion above has ever run.

  Added 2026-08-12 after the corpus-wide sweep in
  research/verifier-independence/screen.mjs, which changed the last digit of
  every number this page renders and watched this verifier stay green through
  all 3,360 of them. See /strata/the-engine-and-the-eye/ for the measurement and
  for why a browser is the only instrument that can close this.
*/
{
  const MIME = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript', '.mjs': 'text/javascript',
    '.css': 'text/css', '.json': 'application/json', '.svg': 'image/svg+xml', '.png': 'image/png',
    '.woff2': 'font/woff2', '.ico': 'image/x-icon' };
  const PUBLIC = resolve(HERE, '../../public');
  const server = http.createServer((req, res) => {
    let p;
    try { p = decodeURIComponent(new URL(req.url, 'http://localhost').pathname); }
    catch { res.writeHead(400); res.end(); return; }
    if (p.endsWith('/')) p += 'index.html';
    const file = join(PUBLIC, p);
    if (!file.startsWith(PUBLIC + sep) || !existsSync(file) || !statSync(file).isFile()) {
      res.writeHead(404); res.end('not here'); return;
    }
    res.writeHead(200, { 'content-type': MIME[extname(file)] || 'application/octet-stream' });
    res.end(readFileSync(file));
  });
  await new Promise((r) => server.listen(0, '127.0.0.1', r));
  const { chromium } = await import('playwright');
  const browser = await chromium.launch({ args: ['--no-sandbox'] });
  try {
    const page = await browser.newPage();
    const jsErrors = [];
    page.on('pageerror', (e) => jsErrors.push(String(e.message).slice(0, 140)));
    await page.goto(`http://127.0.0.1:${server.address().port}/strata/sudoku-16-clue/`, { waitUntil: 'load' });
    await page.waitForSelector('#board-17 .cell');
    const readBoard = () => page.$$eval('#board-17 .cell', (els) => els.map((e) => e.textContent.trim()));

    /* before the completion is asked for, the board is exactly the givens */
    const shownGivens = await readBoard();
    check('the rendered board shows exactly the puzzle\'s clues',
      shownGivens.filter((t) => t !== '').length, givens17.length);
    check('every rendered clue is the digit the shipped puzzle string has there',
      shownGivens.every((t, i) => (puz17[i] ? t === String(puz17[i]) : t === '')), true);

    /* and with it asked for, every one of the 81 cells is the completion this
       script derived for itself, not the one the page derived for itself */
    await page.click('#btn-solve');
    await page.waitForTimeout(250);
    const shownSolved = await readBoard();
    const sol = r17.sols[0];
    const wrong = shownSolved.map((t, i) => [i, t, String(sol[i])]).filter(([, t, w]) => t !== w);
    check(`all 81 cells a reader sees are this script's own completion${wrong.length ? ` (first disagreement at cell ${wrong[0][0]}: screen "${wrong[0][1]}", independent "${wrong[0][2]}")` : ''}`,
      wrong.length, 0);

    /* the readout beside the board states the clue count in words a reader reads */
    const ro = (await page.textContent('#ro-17')) || '';
    check('the readout beside the board names the clue count',
      new RegExp(`\\b${givens17.length}\\b`).test(ro), true);
    check('no JavaScript error while the page built its boards', jsErrors.length, 0);
  } finally {
    await browser.close();
    server.close();
  }
}

/* ---- verdict -------------------------------------------------------- */
console.log('');
console.log('NOT rerun here: the 5,472,730,538-class exhaustive census for 16-clue puzzles.');
console.log('That result is cited to McGuire, Tugemann and Civario (about 7.1 million core hours)');
console.log('and this script makes no attempt to reproduce it.');
console.log('');
const total = pass + fail;
if (fail) {
  console.log(`${fail} of ${total} checks FAILED:`);
  for (const f of failures) console.log('  - ' + f);
  process.exit(1);
}
console.log(`${pass}/${total} checks passed`);
process.exit(0);
