#!/usr/bin/env node
// Verifier for the stratum page "Fifty Shots to a Guaranteed Hit".
//
//   node research/fifty-shots-to-a-guaranteed-hit/verify-fifty-shots-to-a-guaranteed-hit.mjs
//   node research/fifty-shots-to-a-guaranteed-hit/verify-fifty-shots-to-a-guaranteed-hit.mjs --mutate
//
// What this is: the page's evidence that it is not lying. It recomputes, from
// scratch and through independent code paths, every quantity the page displays,
// reproduces the independent anchors, prints its check COUNT, and exits
// non-zero on any failure or on zero checks. It reads the source tree only;
// it never reads a build or dist directory.
//
// Anchors used (stated again in the output):
//   A. Closed-form placement counts 20 * (11 - L), derived by hand, cross-checked
//      against a brute-force enumerator written differently from the engine's.
//   B. Explicit hand-constructed fleet witnesses that dodge named 43/48/49-shot
//      sets, validated by an independent legality checker, alongside complete
//      adversarial searches that visit every branch.
//   C. The domino tiling certificate behind the tightness of fifty.
//   D. Monte Carlo invariants plus aggregate recomputation from raw samples.

import { readFileSync, writeFileSync, rmSync, existsSync } from 'node:fs';
import { fileURLToPath, pathToFileURL } from 'node:url';
import path from 'node:path';
import * as E from './engine.mjs';

const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, '..', '..');
const HTML_PATH = path.join(ROOT, 'public', 'strata',
  'fifty-shots-to-a-guaranteed-hit', 'index.html');
const PAGE_SEED = 20260901; // must match the page's default seed box

// The site's own origin. A <link rel="canonical"> is REQUIRED by convention to
// carry the full absolute URL of the page, so the same-origin rule for link
// hrefs means "root-relative, or an absolute URL on exactly this origin", never
// "starts with a slash". The previous form of this check demanded a leading
// slash from every href and thereby failed on the page's correct canonical tag;
// the page was right and the check was wrong, so the check was narrowed here,
// not the page loosened. Protocol-relative hrefs ("//host/...") are still
// rejected: they inherit whatever scheme the page was loaded over and can
// silently point off-site.
const SITE_ORIGIN = 'https://artwaste.land';
const CANONICAL_URL = SITE_ORIGIN + '/strata/fifty-shots-to-a-guaranteed-hit/';

let passed = 0, failed = 0;
const failures = [];

function check(name, cond, detail = '') {
  if (cond) { passed++; } else { failed++; failures.push(name + (detail ? ' :: ' + detail : '')); }
  return Boolean(cond);
}
function eq(a, b) { return JSON.stringify(a) === JSON.stringify(b); }
function close(a, b, tol) {
  return Math.abs(a - b) <= tol * Math.max(1, Math.abs(a), Math.abs(b));
}
function throws(fn, cls) {
  try { fn(); return false; } catch (e) { return cls ? e instanceof cls || e.name === cls : true; }
}

// ─────────────────────────────────────────────────────────────────────────────
// Section 1. Unit tests of the small pure helpers, hand-worked cases FIRST.
// ─────────────────────────────────────────────────────────────────────────────
function sectionHelpers() {
  console.log('--- section 1: hand-worked helper tests ---');

  check('colourOf(0,0) = 0', E.colourOf(0, 0) === 0);
  check('colourOf(0,1) = 1', E.colourOf(0, 1) === 1);
  check('colourOf(9,9) = 0', E.colourOf(9, 9) === 0);
  check('colourOf(3,4) = 1', E.colourOf(3, 4) === 1);
  check('colourOf(4,7) = 1', E.colourOf(4, 7) === 1);

  check('inBounds corners', E.inBounds(0, 0) && E.inBounds(9, 9));
  check('inBounds rejects outside', !E.inBounds(10, 0) && !E.inBounds(0, -1) && !E.inBounds(1.5, 1));

  check('key(0,0)=0', E.key(0, 0) === 0);
  check('key(9,9)=99', E.key(9, 9) === 99);
  check('key(7,2)=72', E.key(7, 2) === 72);
  check('unkey(34)=[3,4]', eq(E.unkey(34), [3, 4]));
  let rt = true;
  for (let k = 0; k < 100; k++) { const [r, c] = E.unkey(k); if (E.key(r, c) !== k) rt = false; }
  check('key/unkey round-trip over all 100 squares', rt);

  check('neighbours corner', eq(E.neighbours(0, 0), [[0, 1], [1, 0]]));
  check('neighbours top edge', eq(E.neighbours(0, 5), [[0, 6], [1, 5], [0, 4]]));
  check('neighbours centre', eq(E.neighbours(4, 4), [[3, 4], [4, 5], [5, 4], [4, 3]]));
  check('neighbours far corner', eq(E.neighbours(9, 9), [[8, 9], [9, 8]]));

  for (let L = 2; L <= 10; L++) {
    check('placementsForLength(' + L + ') = 20*(11-' + L + ')',
      E.placementsForLength(L).length === 20 * (11 - L),
      'got ' + E.placementsForLength(L).length);
  }
  check('placementsForLength(1) throws RangeError', throws(() => E.placementsForLength(1), RangeError));
  check('placementsForLength(11) throws RangeError', throws(() => E.placementsForLength(11), RangeError));
  check('placementsForLength(2.5) throws RangeError', throws(() => E.placementsForLength(2.5), RangeError));

  // structural spot checks: straight, contiguous, in-bounds
  let structOk = true;
  for (const L of [2, 3, 4, 5]) {
    const ps = E.placementsForLength(L);
    for (const p of ps.slice(0, 5)) {
      if (p.cells.length !== L) structOk = false;
      for (let i = 1; i < p.cells.length; i++) {
        const d = Math.abs(p.cells[i][0] - p.cells[i - 1][0]) +
                  Math.abs(p.cells[i][1] - p.cells[i - 1][1]);
        if (d !== 1) structOk = false;
        if (!E.inBounds(p.cells[i][0], p.cells[i][1])) structOk = false;
      }
    }
  }
  check('sampled placements are straight, contiguous, in-bounds', structOk);

  check('placementColourCounts horizontal 3 at (2,3) = [1,2]',
    eq(E.placementColourCounts({ cells: [[2, 3], [2, 4], [2, 5]] }), [1, 2]));
  check('placementColourCounts vertical 2 at (0,1) = [1,1]',
    eq(E.placementColourCounts({ cells: [[0, 1], [1, 1]] }), [1, 1]));
  check('placementColourCounts horizontal 5 at (4,4) = [3,2]',
    eq(E.placementColourCounts({ cells: [[4, 4], [4, 5], [4, 6], [4, 7], [4, 8]] }), [3, 2]));

  check('minColourRequirement standard = 7', E.minColourRequirement([2, 3, 3, 4, 5]) === 7);
  check('minColourRequirement [2] = 1', E.minColourRequirement([2]) === 1);
  check('minColourRequirement [5] = 2', E.minColourRequirement([5]) === 2);
  check('minColourRequirement [3,4] = 3', E.minColourRequirement([3, 4]) === 3);
  check('minColourRequirement [10] = 5', E.minColourRequirement([10]) === 5);
  check('minColourRequirement [1] = 0', E.minColourRequirement([1]) === 0);
  check('minColourRequirement [2,2] = 2', E.minColourRequirement([2, 2]) === 2);
  check('minColourRequirement([]) throws', throws(() => E.minColourRequirement([]), RangeError));
  check('minColourRequirement([0]) throws', throws(() => E.minColourRequirement([0]), RangeError));

  check('forcedContactShots standard = 44', E.forcedContactShots([2, 3, 3, 4, 5]) === 44);
  check('forcedContactShots [2] = 50', E.forcedContactShots([2]) === 50);
  check('forcedContactShots [3,3] = 49', E.forcedContactShots([3, 3]) === 49);
  check('forcedContactShots [3,4] = 48', E.forcedContactShots([3, 4]) === 48);
  check('forcedContactShots [5] = 49', E.forcedContactShots([5]) === 49);
  check('forcedContactShots [10] = 46', E.forcedContactShots([10]) === 46);
  check('forcedContactShots [1] = Infinity', E.forcedContactShots([1]) === Infinity);
  check('forcedContactShots [1,2] = Infinity', E.forcedContactShots([1, 2]) === Infinity);

  const s0 = E.shotsOfColour(0), s1 = E.shotsOfColour(1);
  check('shotsOfColour(0) has 50 squares', s0.length === 50);
  check('shotsOfColour(1) has 50 squares', s1.length === 50);
  check('shotsOfColour(0) all colour 0', s0.every(([r, c]) => E.colourOf(r, c) === 0));
  check('shotsOfColour(1) all colour 1', s1.every(([r, c]) => E.colourOf(r, c) === 1));
  check('shotsOfColour(0) starts (0,0) ends (9,9)', eq(s0[0], [0, 0]) && eq(s0[49], [9, 9]));
  check('shotsOfColour(1) starts (0,1) ends (9,8)', eq(s1[0], [0, 1]) && eq(s1[49], [9, 8]));
  check('shotsOfColour(0) row-major ascending keys',
    s0.every((sq, i) => i === 0 || E.key(sq[0], sq[1]) > E.key(s0[i - 1][0], s0[i - 1][1])));
  check('shotsOfColour(2) throws RangeError', throws(() => E.shotsOfColour(2), RangeError));

  const tg = E.dominoTiling();
  check('dominoTiling has 50 dominoes', tg.length === 50);
  check('every domino is an adjacent pair',
    tg.every(([[r1, c1], [r2, c2]]) =>
      Math.abs(r1 - r2) + Math.abs(c1 - c2) === 1));
  check('every domino spans both colours',
    tg.every(([[r1, c1], [r2, c2]]) => E.colourOf(r1, c1) !== E.colourOf(r2, c2)));
  const seen = new Set();
  tg.forEach((d) => d.forEach(([r, c]) => seen.add(E.key(r, c))));
  check('dominoes cover all 100 squares exactly once', seen.size === 100);

  const g1 = E.makeRng(1), g1b = E.makeRng(1), g2 = E.makeRng(2);
  const a1 = Array.from({ length: 8 }, () => g1());
  const a1b = Array.from({ length: 8 }, () => g1b());
  const a2 = Array.from({ length: 8 }, () => g2());
  check('makeRng deterministic for same seed', eq(a1, a1b));
  check('makeRng seed-sensitive', !eq(a1, a2));
  let inRange = true;
  const gr = E.makeRng(7);
  for (let i = 0; i < 2000; i++) { const x = gr(); if (!(x >= 0 && x < 1)) inRange = false; }
  check('makeRng draws in [0,1) over 2000 draws', inRange);
  check('makeRng coerces negative seeds without throwing', typeof E.makeRng(-5) === 'function');

  check('histogram hand case [1,2,2,4] over [1,5] x2 = [3,1]',
    eq(E.histogram([1, 2, 2, 4], 1, 5, 2).counts, [3, 1]));
  check('histogram hi is inclusive: [5] over [1,5] x2 = [0,1]',
    eq(E.histogram([5], 1, 5, 2).counts, [0, 1]));
  check('histogram width is exact', E.histogram([1], 1, 5, 2).width === 2);
  check('histogram rejects out-of-range sample', throws(() => E.histogram([0], 1, 5, 2), RangeError));
  check('histogram rejects hi <= lo', throws(() => E.histogram([1, 2], 3, 1, 2), RangeError));
  check('histogram rejects bins < 1', throws(() => E.histogram([1], 1, 5, 0), RangeError));

  // pigeonhole helper used by the tightness argument, hand-worked
  const doms = [[[0, 0], [0, 1]], [[0, 2], [0, 3]]];
  const intact = (openKeys, ds) => {
    for (const d of ds) if (d.every(([r, c]) => openKeys.has(E.key(r, c)))) return d;
    return null;
  };
  check('pigeonhole: full-open board leaves first domino',
    eq(intact(new Set([E.key(0, 0), E.key(0, 1), E.key(0, 2), E.key(0, 3)]), doms), [[0, 0], [0, 1]]));
  check('pigeonhole: one cell of each domino shot leaves none',
    intact(new Set([E.key(0, 0), E.key(0, 2)]), doms) === null);
  check('pigeonhole: second domino intact when only its pair survives',
    eq(intact(new Set([E.key(0, 0), E.key(0, 2), E.key(0, 3)]), doms), [[0, 2], [0, 3]]));
}

// ─────────────────────────────────────────────────────────────────────────────
// Section 2. Independent anchors.
// ─────────────────────────────────────────────────────────────────────────────

// Brute-force placement enumerator, deliberately written differently from the
// engine's: walk L steps in each of the four compass directions from every
// square, canonicalise, dedupe. Anchor A's second method.
function brutePlacements(L) {
  const seen = new Map();
  for (let r = 0; r < E.SIZE; r++) {
    for (let c = 0; c < E.SIZE; c++) {
      for (const [dr, dc] of [[0, 1], [0, -1], [1, 0], [-1, 0]]) {
        const cells = [];
        let ok = true;
        for (let i = 0; i < L; i++) {
          const rr = r + dr * i, cc = c + dc * i;
          if (!E.inBounds(rr, cc)) { ok = false; break; }
          cells.push([rr, cc]);
        }
        if (!ok) continue;
        const canon = cells.map((x) => x.join(',')).sort().join(';');
        if (!seen.has(canon)) seen.set(canon, { r: cells[0][0], c: cells[0][1], horiz: dr === 0, cells });
      }
    }
  }
  return [...seen.values()];
}

// Independent fleet-legality checker: does not use any engine placement code.
// ships: array of cell-arrays; wanted: multiset of expected lengths.
function validateFleet(ships, wanted, shotKeySet) {
  if (ships.length !== wanted.length) return false;
  const lens = ships.map((s) => s.length).sort((a, b) => a - b);
  if (!eq(lens, [...wanted].sort((a, b) => a - b))) return false;
  const used = new Set();
  for (const cells of ships) {
    for (let i = 0; i < cells.length; i++) {
      const [r, c] = cells[i];
      if (!E.inBounds(r, c)) return false;
      if (shotKeySet.has(E.key(r, c))) return false;
      const k = E.key(r, c);
      if (used.has(k)) return false;
      used.add(k);
      if (i > 0) {
        const d = Math.abs(r - cells[i - 1][0]) + Math.abs(c - cells[i - 1][1]);
        if (d !== 1) return false;
      }
    }
    // straightness: all rows equal or all columns equal
    const rowsSame = cells.every(([r]) => r === cells[0][0]);
    const colsSame = cells.every(([, c]) => c === cells[0][1]);
    if (!rowsSame && !colsSame) return false;
  }
  return true;
}

function sectionAnchors() {
  console.log('--- section 2: independent anchors ---');

  // Anchor A: closed-form counts + brute-force cross-enumeration + both-colours.
  let total = 0, bothAll = true;
  for (const L of [2, 3, 4, 5]) {
    const ps = E.placementsForLength(L);
    const bf = brutePlacements(L);
    total += ps.length;
    const canon = (p) => p.cells.map((x) => x.join(',')).sort().join(';');
    const setA = new Set(ps.map(canon));
    const setB = new Set(bf.map(canon));
    check('anchor A: engine and brute-force enumerators agree for L=' + L,
      setA.size === setB.size && [...setA].every((k) => setB.has(k)),
      'engine ' + setA.size + ' vs brute ' + setB.size);
    for (const p of ps) {
      const [d, l] = E.placementColourCounts(p);
      if (!(d > 0 && l > 0)) bothAll = false;
    }
  }
  check('anchor A: all 600 placements touch both colours', bothAll);
  check('anchor A: total placements = 600', total === 600, 'got ' + total);
  console.log('    anchor A provenance: closed form 20*(11-L), derived by hand; second method is a');
  console.log('    brute-force compass-walk enumerator written independently above.');

  // Named shot sets. OPEN7 is the seven dark squares left open by the 43-shot
  // dodge set; a full legal standard fleet fits on exactly these seven dark
  // squares plus light squares (hand-constructed witness below).
  const OPEN7 = [[0, 2], [0, 4], [1, 1], [1, 3], [2, 2], [3, 1], [4, 2]];
  const S0 = E.shotsOfColour(0);
  const minus = (set, opens) =>
    set.filter((s) => !opens.some((o) => o[0] === s[0] && o[1] === s[1]));
  const S43 = minus(S0, OPEN7);
  check('43-shot dodge set really has 43 squares', S43.length === 43);

  // Anchor B, part 1: complete adversarial searches.
  const r50 = E.findFleetPlacementAvoiding(E.STANDARD_FLEET, S0);
  check('anchor B: no fleet survives the 50 dark squares (complete search)',
    r50.fits === false && r50.witness === null);
  check('anchor B: 50-shot search visited > 0 placements', r50.nodes > 0);
  console.log('    anchor B: counterexample search vs 50 dark shots exhausted at ' + r50.nodes + ' placement trials.');

  const r44 = E.findFleetPlacementAvoiding(E.STANDARD_FLEET, S0.slice(0, 44));
  check('anchor B: no fleet survives 44 dark squares (complete search)', r44.fits === false);
  console.log('    anchor B: counterexample search vs 44 dark shots exhausted at ' + r44.nodes + ' placement trials.');

  // Independent route for the 44 result: pure arithmetic. 44 dark shots leave
  // 6 open dark squares; the fleet needs R = 7 of each colour. 6 < 7.
  const openDark = 50 - 44;
  const R = E.minColourRequirement(E.STANDARD_FLEET);
  check('anchor B: counting route agrees 44 forces contact (open ' + openDark + ' < R ' + R + ')',
    openDark < R);

  const r43 = E.findFleetPlacementAvoiding(E.STANDARD_FLEET, S43);
  check('anchor B: the 43-shot dodge set CAN be dodged (complete search finds a witness)',
    r43.fits === true && Array.isArray(r43.witness) && r43.witness.length === 5);
  console.log('    anchor B: 43-shot dodge search found a witness after ' + r43.nodes + ' placement trials.');

  // Anchor B, part 2: hand-constructed witnesses, validated independently.
  const W43 = [
    [[0, 1], [0, 2], [0, 3], [0, 4], [0, 5]],   // carrier, dark at (0,2),(0,4)
    [[1, 0], [1, 1], [1, 2], [1, 3]],           // battleship, dark at (1,1),(1,3)
    [[2, 1], [2, 2], [2, 3]],                   // submarine, dark at (2,2)
    [[3, 0], [3, 1], [3, 2]],                   // submarine, dark at (3,1)
    [[4, 1], [4, 2]]                            // destroyer, dark at (4,2)
  ];
  const keySet = (shots) => new Set(shots.map(([r, c]) => E.key(r, c)));
  check('anchor B: hand-built standard-fleet witness is legal and dodges all 43 shots',
    validateFleet(W43, [2, 3, 3, 4, 5], keySet(S43)));
  check('anchor B: engine search witness also passes the independent validator',
    validateFleet(r43.witness.map((p) => p.cells), [2, 3, 3, 4, 5], keySet(S43)));

  // Sharpness for every preset: forced at 51-R, dodgeable at 50-R with a
  // hand-built witness on a named open set.
  const presets = [
    { name: 'lone destroyer', fl: [2], open: [[0, 0]],
      witness: [[[0, 0], [0, 1]]] },
    { name: 'two submarines', fl: [3, 3], open: [[0, 2], [2, 2]],
      witness: [[[0, 1], [0, 2], [0, 3]], [[1, 2], [2, 2], [3, 2]]] },
    { name: 'cruiser and battleship', fl: [3, 4], open: [[0, 2], [1, 1], [1, 3]],
      witness: [[[0, 1], [0, 2], [0, 3]], [[1, 0], [1, 1], [1, 2], [1, 3]]] },
    { name: 'lone carrier', fl: [5], open: [[0, 2], [0, 4]],
      witness: [[[0, 1], [0, 2], [0, 3], [0, 4], [0, 5]]] },
    { name: 'standard fleet', fl: [2, 3, 3, 4, 5], open: OPEN7, witness: W43 }
  ];
  for (const pr of presets) {
    const Rf = E.minColourRequirement(pr.fl);
    const forced = 51 - Rf;
    const shotsForced = S0.slice(0, forced);
    const shotsDodge = minus(S0, pr.open);
    const rf = E.findFleetPlacementAvoiding(pr.fl, shotsForced);
    const rd = E.findFleetPlacementAvoiding(pr.fl, shotsDodge);
    check('preset "' + pr.name + '": complete search finds NO survivor at ' + forced + ' dark shots',
      rf.fits === false, 'nodes ' + rf.nodes);
    check('preset "' + pr.name + '": complete search FINDS a dodge at ' + (forced - 1) + ' dark shots',
      rd.fits === true, 'nodes ' + rd.nodes);
    check('preset "' + pr.name + '": hand-built dodge witness validates independently',
      validateFleet(pr.witness, pr.fl, keySet(shotsDodge)));
    console.log('    anchor B: ' + pr.name + ' forced at ' + forced +
      ' (search: no survivor, ' + rf.nodes + ' trials); dodge at ' + (forced - 1) +
      ' confirmed (' + rd.nodes + ' trials).');
  }

  // Anchor C: the domino certificate and the universal tightness of fifty.
  const tiling = E.dominoTiling();
  const cover = new Set();
  let adjOk = true;
  for (const d of tiling) {
    if (Math.abs(d[0][0] - d[1][0]) + Math.abs(d[0][1] - d[1][1]) !== 1) adjOk = false;
    for (const [r, c] of d) cover.add(E.key(r, c));
  }
  check('anchor C: tiling is 50 adjacent dominoes covering all 100 squares',
    tiling.length === 50 && adjOk && cover.size === 100);
  // The destroyer alone needs exactly fifty: with 49 shots, 51 squares are open,
  // some domino is wholly open (pigeonhole over the 50 dominoes), and a destroyer
  // fits in it. Confirmed concretely for the named 49-shot set:
  const S49 = S0.slice(1); // dark squares minus (0,0): 49 shots
  const openKeys = new Set();
  for (let k = 0; k < 100; k++) if (!S49.some(([r, c]) => E.key(r, c) === k)) openKeys.add(k);
  check('anchor C: 49 shots leave exactly 51 open squares', openKeys.size === 51);
  let intact = null;
  for (const d of tiling) {
    if (d.every(([r, c]) => openKeys.has(E.key(r, c)))) { intact = d; break; }
  }
  check('anchor C: some domino is wholly open after any 49 of THESE shots', intact !== null);
  const rd49 = E.findFleetPlacementAvoiding([2], S49);
  check('anchor C: destroyer dodges the named 49-shot set (search agrees with pigeonhole)',
    rd49.fits === true);
  const r50d = E.findFleetPlacementAvoiding([2], S0);
  check('anchor C: destroyer survives NOTHING against the full 50 (search agrees)',
    r50d.fits === false);
  console.log('    anchor C provenance: domino tiling built and checked live; the implication');
  console.log('    "51 open squares among 50 dominoes leave a whole domino" is the pigeonhole');
  console.log('    lemma, unit-tested by hand above; the destroyer searches agree concretely.');

  // Anchor D: Monte Carlo, invariants plus aggregate recomputation.
  const mc = E.comparePolicies(PAGE_SEED, 2000, E.STANDARD_FLEET, 0);
  check('anchor D: sample counts match n', mc.parity.samples.length === 2000 && mc.hybrid.samples.length === 2000);
  check('anchor D: all samples are integers',
    mc.parity.samples.every(Number.isInteger) && mc.hybrid.samples.every(Number.isInteger));
  check('anchor D: pure parity never finishes before 50 + R = 57 shots',
    mc.parity.min >= 57, 'min ' + mc.parity.min);
  check('anchor D: hybrid never finishes before 17 shots (the fleet is 17 squares)',
    mc.hybrid.min >= 17, 'min ' + mc.hybrid.min);
  check('anchor D: both policies bounded above by 150 shots',
    mc.parity.max <= 150 && mc.hybrid.max <= 150,
    'maxima ' + mc.parity.max + ', ' + mc.hybrid.max);
  check('anchor D: standard errors positive', mc.parity.se > 0 && mc.hybrid.se > 0 && mc.diff.se > 0);
  check('anchor D: means within a sane band of each other',
    Math.abs(mc.parity.mean - mc.hybrid.mean) <= 30,
    'means ' + mc.parity.mean + ', ' + mc.hybrid.mean);

  // second-method recomputation of the aggregates from raw samples
  let sumP = 0, sumH = 0, minP = Infinity, maxP = -Infinity;
  for (const x of mc.parity.samples) { sumP += x; if (x < minP) minP = x; if (x > maxP) maxP = x; }
  for (const x of mc.hybrid.samples) sumH += x;
  let sumD = 0;
  for (let i = 0; i < 2000; i++) sumD += mc.hybrid.samples[i] - mc.parity.samples[i];
  check('anchor D: parity mean recomputed independently', close(sumP / 2000, mc.parity.mean, 1e-9));
  check('anchor D: hybrid mean recomputed independently', close(sumH / 2000, mc.hybrid.mean, 1e-9));
  check('anchor D: paired diff mean recomputed independently', close(sumD / 2000, mc.diff.mean, 1e-9));
  check('anchor D: parity min/max recomputed independently', minP === mc.parity.min && maxP === mc.parity.max);

  const mcA = E.comparePolicies(PAGE_SEED, 120, E.STANDARD_FLEET, 0);
  const mcB = E.comparePolicies(PAGE_SEED, 120, E.STANDARD_FLEET, 0);
  check('anchor D: Monte Carlo is deterministic for a fixed seed', eq(mcA, mcB));
  const mcC = E.comparePolicies(PAGE_SEED + 1, 120, E.STANDARD_FLEET, 0);
  check('anchor D: different seed gives a different stream', !eq(mcA, mcC));
  console.log('    anchor D provenance: invariants derived from the policy definitions;');
  console.log('    aggregates recomputed from raw samples by a second loop. Summary at seed ' +
    PAGE_SEED + ', n=2000:');
  console.log('      parity mean ' + mc.parity.mean.toFixed(3) + ' ± ' + mc.parity.se.toFixed(3) +
    '  (min ' + mc.parity.min + ', max ' + mc.parity.max + ')');
  console.log('      hybrid mean ' + mc.hybrid.mean.toFixed(3) + ' ± ' + mc.hybrid.se.toFixed(3) +
    '  (min ' + mc.hybrid.min + ', max ' + mc.hybrid.max + ')');
  console.log('      paired diff ' + mc.diff.mean.toFixed(3) + ' ± ' + mc.diff.se.toFixed(3));
}

// ─────────────────────────────────────────────────────────────────────────────
// Section 3. Coupling to the shipped page.
// ─────────────────────────────────────────────────────────────────────────────
// Same-origin rule for link hrefs, stated once so the rule and its reason sit
// together: a link is acceptable iff it is root-relative (and not
// protocol-relative, which would inherit the page scheme and could point
// anywhere), or iff it is an absolute URL on exactly SITE_ORIGIN. The one
// absolute href the page carries is its rel="canonical", which SEO convention
// requires to be fully qualified; that is why the rule admits absolute
// same-origin URLs instead of demanding a leading slash from every href.
function isSameOriginHref(h) {
  if (h.startsWith('//')) return false;           // protocol-relative: reject
  if (h.startsWith('/')) return true;             // root-relative: accept
  return h === SITE_ORIGIN || h.startsWith(SITE_ORIGIN + '/');
}

function sectionHtml() {
  console.log('--- section 3: page coupling ---');
  check('page file exists at public/strata/fifty-shots-to-a-guaranteed-hit/index.html',
    existsSync(HTML_PATH));
  if (!existsSync(HTML_PATH)) return;
  const html = readFileSync(HTML_PATH, 'utf8');

  check('page contains no em dash (U+2014)', !html.includes('\u2014'));
  check('page contains no en dash (U+2013)', !html.includes('\u2013'));

  const dekCount = html.split('__DEK__').length - 1;
  check('page carries zero __DEK__ placeholders (meta description, og, twitter, json-ld all filled)',
    dekCount === 0, 'found ' + dekCount);

  const srcs = [...html.matchAll(/<script[^>]*\ssrc=["']([^"']+)["']/g)].map((m) => m[1]);
  check('only external script is the same-origin home banner',
    srcs.length === 1 && srcs[0] === '/media/home-banner.js', JSON.stringify(srcs));
  const links = [...html.matchAll(/<link[^>]*\shref=["']([^"']+)["']/g)].map((m) => m[1]);
  const offsite = links.filter((h) => !isSameOriginHref(h));
  check('every link href is same-origin (root-relative, or absolute on ' + SITE_ORIGIN + ')',
    offsite.length === 0, JSON.stringify(offsite));
  // The canonical tag is the one href allowed to be absolute; pin it exactly so
  // the exemption cannot quietly widen into "any artwaste.land-ish URL".
  const canon = [...html.matchAll(/<link[^>]*\srel=["']canonical["'][^>]*\shref=["']([^"']+)["']/g)].map((m) => m[1]);
  check('page carries exactly one canonical link, pinned to the page URL',
    canon.length === 1 && canon[0] === CANONICAL_URL, JSON.stringify(canon));

  check('page carries the aw-wayout marker block', html.includes('<!--aw-wayout:start-->'));
  check('exactly one polite live region',
    html.split('aria-live="polite"').length - 1 === 1);
  check('page defines no prefers-color-scheme block', !html.includes('prefers-color-scheme'));
  check('page title present', html.includes('<title>') && html.includes('Fifty Shots'));
  check('page prints the verifier command that resolves to this file',
    html.includes('research/fifty-shots-to-a-guaranteed-hit/verify-fifty-shots-to-a-guaranteed-hit.mjs'));
  check('page prose states the forty-four refinement', html.includes('forty-four'));
  check('page prose states the fifty guarantee', html.toLowerCase().includes('fifty'));
}

// ─────────────────────────────────────────────────────────────────────────────
// Section 4. --mutate: corrupt the engine, confirm the corruption lands and
// the checks go red, then restore. Exits non-zero if any mutation fails to
// change any verdict.
// ─────────────────────────────────────────────────────────────────────────────
function miniSuite(M) {
  let p = 0, f = 0;
  const t = (cond) => { if (cond) p++; else f++; };
  const safe = (fn) => { try { fn(); } catch { f++; } };
  safe(() => t(M.placementsForLength(2).length === 180));
  safe(() => t(M.placementsForLength(3).length === 160));
  safe(() => t(M.placementsForLength(5).length === 120));
  safe(() => t(M.colourOf(0, 0) === 0 && M.colourOf(0, 1) === 1 && M.colourOf(3, 4) === 1));
  safe(() => t(M.minColourRequirement([2, 3, 3, 4, 5]) === 7));
  safe(() => t(M.forcedContactShots([2, 3, 3, 4, 5]) === 44));
  safe(() => t(M.shotsOfColour(0).length === 50));
  safe(() => t(M.dominoTiling().length === 50));
  safe(() => t(M.findFleetPlacementAvoiding([2, 3, 3, 4, 5], M.shotsOfColour(0)).fits === false));
  safe(() => t(M.histogram([1, 2, 2, 4], 1, 5, 2).counts[0] === 3));
  return { p, f };
}

async function runMutations() {
  console.log('--- section 4: mutation testing ---');
  const srcPath = path.join(HERE, 'engine.mjs');
  const src = readFileSync(srcPath, 'utf8');
  const tmpPath = path.join(HERE, 'engine.__mutant__.mjs');
  const mutations = [
    { name: 'SIZE 10 -> 9', from: 'export const SIZE = 10;', to: 'export const SIZE = 9;' },
    { name: 'colour parity inverted', from: 'return (r + c) & 1;', to: 'return (r + c + 1) & 1;' },
    { name: 'floor(L/2) -> ceil(L/2) in colour requirement',
      from: 'total += Math.floor(L / 2);', to: 'total += Math.ceil(L / 2);' }
  ];
  let allLanded = true;
  for (const mut of mutations) {
    if (!src.includes(mut.from)) {
      console.log('  MUTATION TARGET NOT FOUND: ' + mut.name);
      allLanded = false;
      continue;
    }
    const mutated = src.replace(mut.from, mut.to);
    if (mutated === src) {
      console.log('  MUTATION DID NOT CHANGE BYTES: ' + mut.name);
      allLanded = false;
      continue;
    }
    writeFileSync(tmpPath, mutated);
    try {
      const mod = await import(pathToFileURL(tmpPath).href);
      const { p, f } = miniSuite(mod);
      if (f > 0) {
        console.log('  LANDED: ' + mut.name + ' -> ' + f + ' of ' + (p + f) + ' mini-checks went red');
      } else {
        console.log('  BLIND SPOT: ' + mut.name + ' changed nothing (all ' + p + ' mini-checks still pass)');
        allLanded = false;
      }
    } catch (e) {
      console.log('  LANDED (import fails): ' + mut.name + ' -> ' + e.message);
    } finally {
      rmSync(tmpPath, { force: true });
    }
  }
  if (!allLanded) {
    console.log('MUTATION RUN FAILED: at least one corruption did not change any verdict.');
    process.exitCode = 1;
  } else {
    console.log('MUTATION RUN PASSED: every corruption landed and was caught.');
  }
}

// ─────────────────────────────────────────────────────────────────────────────
async function main() {
  if (process.argv.includes('--mutate')) {
    await runMutations();
    return;
  }
  sectionHelpers();
  sectionAnchors();
  sectionHtml();

  console.log('');
  console.log('ANCHORS USED:');
  console.log('  A. closed-form placement counts 20*(11-L), hand-derived, cross-checked');
  console.log('     against an independently written brute-force enumerator;');
  console.log('  B. complete adversarial searches (branch-exhaustive DFS, trial counts');
  console.log('     printed) plus hand-constructed fleet witnesses validated by an');
  console.log('     independent legality checker;');
  console.log('  C. the domino tiling certificate and the pigeonhole lemma behind the');
  console.log('     exactness of the fifty bound;');
  console.log('  D. Monte Carlo invariants and aggregate recomputation from raw samples');
  console.log('     at seed ' + PAGE_SEED + '.');
  console.log('');
  console.log('CHECKS: ' + passed + ' passed, ' + failed + ' failed (' + (passed + failed) + ' total)');
  if (failures.length) {
    console.log('FAILURES:');
    for (const f of failures) console.log('  - ' + f);
  }
  if (failed > 0 || passed === 0) process.exitCode = 1;
}

main().catch((e) => {
  console.error('VERIFIER CRASHED: ' + (e && e.stack ? e.stack : e));
  process.exit(1);
});
