#!/usr/bin/env node
import fs from 'node:fs';
import vm from 'node:vm';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const here = path.dirname(fileURLToPath(import.meta.url));
const root = path.resolve(here, '../..');
const pagePath = path.join(root, 'public/strata/devils-staircase/index.html');
const page = fs.readFileSync(pagePath, 'utf8');

let checks = 0;
let failures = 0;
const results = [];
const verifiedDimensionCache = new Map();

function pass(name, detail = '') {
  checks += 1;
  results.push(`PASS ${String(checks).padStart(3, '0')} | ${name}${detail ? ` | ${detail}` : ''}`);
}

function fail(name, detail = '') {
  checks += 1;
  failures += 1;
  results.push(`FAIL ${String(checks).padStart(3, '0')} | ${name}${detail ? ` | ${detail}` : ''}`);
}

function assert(name, condition, detail = '') {
  if (condition) pass(name, detail);
  else fail(name, detail);
}

function close(name, actual, expected, tolerance = 1e-12) {
  const delta = Math.abs(actual - expected);
  assert(name, Number.isFinite(actual) && delta <= tolerance, `got ${actual}, expected ${expected}, delta ${delta}`);
}

function section(name) {
  results.push(`\n[${name}]`);
}

const TAU = 2 * Math.PI;
const IC = Object.freeze({
  cantorDigits: 24,
  cantorStage: 12,
  baseK: 0.9,
  baseTransient: 256,
  baseMeasure: 768,
  baseQ: 32,
  baseGrid: 512,
  x0: 0.123456789,
  fieldW: 160,
  fieldH: 96,
  fieldTransient: 128,
  fieldMeasure: 256,
  fieldQ: 24,
  fieldMultiplier: 0.98,
  dimK: 1,
  dimTransient: 512,
  dimMeasure: 1536,
  dimQ: 64
});

function igcd(a, b) {
  a = Math.abs(Math.trunc(a));
  b = Math.abs(Math.trunc(b));
  while (b !== 0) {
    const old = a;
    a = b;
    b = old % b;
  }
  return a || 1;
}

function bruteRational(value, maxDen) {
  let best = { p: 0, q: 1, value: 0, error: Infinity };
  for (let q = 1; q <= maxDen; q += 1) {
    const p = Math.round(value * q);
    const candidate = p / q;
    const error = Math.abs(value - candidate);
    if (error < best.error - 1e-15 || (Math.abs(error - best.error) <= 1e-15 && q < best.q)) {
      const d = igcd(p, q);
      best = { p: p / d, q: q / d, value: candidate, error };
    }
  }
  best.value = best.p / best.q;
  best.error = Math.abs(value - best.value);
  return best;
}

function independentCantor(x, digits = IC.cantorDigits) {
  if (x <= 0) return { value: 0, lo: 0, hi: 0, error: 0, stage: 0, plateau: false };
  if (x >= 1) return { value: 1, lo: 1, hi: 1, error: 0, stage: 0, plateau: false };
  let remainder = x;
  let numerator = 0;
  let bitPlace = 1;
  for (let stage = 1; stage <= digits; stage += 1) {
    remainder *= 3;
    let digit = Math.floor(remainder + 1e-14);
    if (digit > 2) digit = 2;
    remainder -= digit;
    bitPlace *= 2;
    if (digit === 2) numerator += 1 / bitPlace;
    if (digit === 1) {
      numerator += 1 / bitPlace;
      return { value: numerator, lo: numerator, hi: numerator, error: 0, stage, plateau: true };
    }
    if (Math.abs(remainder) < 1e-14) return { value: numerator, lo: numerator, hi: numerator, error: 0, stage: 0, plateau: false };
  }
  const tail = 1 / (2 ** digits);
  return { value: numerator + tail / 2, lo: numerator, hi: numerator + tail, error: tail / 2, stage: 0, plateau: false };
}

function independentConstruction(n) {
  let intervals = 1;
  let intervalLength = 1;
  let totalLength = 1;
  for (let i = 0; i < n; i += 1) {
    intervals *= 2;
    intervalLength /= 3;
    totalLength *= 2 / 3;
  }
  return { intervals, intervalLength, totalLength, dimension: Math.log(2) / Math.log(3) };
}

function independentStep(x, omega, K) {
  return x + omega - K * Math.sin(TAU * x) / TAU;
}

function independentRotation(omega, K, transient, measure, initial = IC.x0) {
  let x = initial;
  for (let i = 0; i < transient; i += 1) x = independentStep(x, omega, K);
  const start = x;
  const half = Math.floor(measure / 2);
  let middle = x;
  for (let i = 0; i < measure; i += 1) {
    x = independentStep(x, omega, K);
    if (i + 1 === half) middle = x;
  }
  return {
    rho: (x - start) / measure,
    first: (middle - start) / half,
    second: (x - middle) / (measure - half),
    x,
    start
  };
}

function independentClassify(omega, K, transient, measure, maxDen, multiplierLimit) {
  const r = independentRotation(omega, K, transient, measure);
  const whole = bruteRational(r.rho, maxDen);
  const first = bruteRational(r.first, maxDen);
  const second = bruteRational(r.second, maxDen);
  const half = Math.floor(measure / 2);
  let x = r.x;
  let multiplier = 1;
  for (let i = 0; i < whole.q; i += 1) {
    multiplier *= 1 - K * Math.cos(TAU * x);
    x = independentStep(x, omega, K);
  }
  let accepted = whole.error <= 0.5 / measure && first.error <= 0.5 / half && second.error <= 0.5 / half;
  accepted = accepted && whole.p === first.p && whole.q === first.q && whole.p === second.p && whole.q === second.q;
  if (multiplierLimit !== undefined) accepted = accepted && Math.abs(multiplier) < multiplierLimit;
  return { ...whole, rho: r.rho, multiplier, accepted };
}

function independentOrbit(omega, K, p, q) {
  let x = IC.x0;
  for (let i = 0; i < 1024; i += 1) x = independentStep(x, omega, K);
  const phases = [];
  let multiplier = 1;
  for (let i = 0; i < q; i += 1) {
    phases.push(x - Math.floor(x));
    multiplier *= 1 - K * Math.cos(TAU * x);
    x = independentStep(x, omega, K);
  }
  return { phases, multiplier, final: x };
}

function independentField() {
  const cells = [];
  let locked = 0;
  for (let row = 0; row < IC.fieldH; row += 1) {
    const K = 1 - row / (IC.fieldH - 1);
    for (let col = 0; col < IC.fieldW; col += 1) {
      const omega = col / (IC.fieldW - 1);
      const z = independentClassify(omega, K, IC.fieldTransient, IC.fieldMeasure, IC.fieldQ, IC.fieldMultiplier);
      cells.push({ p: z.p, q: z.q, accepted: z.accepted, multiplier: z.multiplier });
      if (z.accepted) locked += 1;
    }
  }
  return { cells, locked, iterations: IC.fieldW * IC.fieldH * (IC.fieldTransient + IC.fieldMeasure) };
}

function independentFit(points) {
  const mx = points.reduce((sum, point) => sum + point.x, 0) / points.length;
  const my = points.reduce((sum, point) => sum + point.y, 0) / points.length;
  const sxx = points.reduce((sum, point) => sum + (point.x - mx) ** 2, 0);
  const slope = points.reduce((sum, point) => sum + (point.x - mx) * (point.y - my), 0) / sxx;
  const intercept = my - slope * mx;
  const sse = points.reduce((sum, point) => sum + (point.y - intercept - slope * point.x) ** 2, 0);
  return { slope, intercept, se: Math.sqrt(sse / (points.length - 2)) / Math.sqrt(sxx), sse };
}

function independentDimension(N, maxDen = IC.dimQ, trimFine = 0, toleranceFactor = 0.5, widthMutation = false) {
  const labels = [];
  const approximants = [];
  const tolerance = toleranceFactor / IC.dimMeasure;
  for (let i = 0; i < N; i += 1) {
    const rho = independentRotation(i / (N - 1), IC.dimK, IC.dimTransient, IC.dimMeasure).rho;
    const a = bruteRational(rho, maxDen);
    approximants.push(a);
    labels.push(a.error <= tolerance ? `${a.p}/${a.q}` : '');
  }
  const runs = [];
  const widths = [];
  for (let i = 0; i < N;) {
    let end = i + 1;
    while (end < N && labels[end] === labels[i]) end += 1;
    if (labels[i] && end - i >= 2) {
      const width = widthMutation ? (end - i) / N : (end - i - 1) / (N - 1);
      widths.push(width);
      runs.push({ label: labels[i], width, samples: end - i });
    }
    i = end;
  }
  const points = [];
  const maxM = Math.floor(Math.log2(N)) - 3 - trimFine;
  for (let m = 4; m <= maxM; m += 1) {
    const r = 2 ** (-m);
    const S = widths.filter(width => width > r).reduce((sum, width) => sum + width, 0);
    const remain = Math.max(1 / (N - 1), 1 - S);
    points.push({ r, S, remain, x: Math.log(1 / r), y: Math.log(remain / r) });
  }
  return {
    N,
    labels,
    approximants,
    runs,
    widths,
    points,
    coverage: widths.reduce((sum, width) => sum + width, 0),
    fit: independentFit(points),
    iterations: N * (IC.dimTransient + IC.dimMeasure)
  };
}

section('DOCUMENT AND LOAD-BEARING STRUCTURE');
assert('doctype is present', page.startsWith('<!doctype html>'));
assert('canonical URL is exact', page.includes('<link rel="canonical" href="https://artwaste.land/strata/devils-staircase/" />'));
assert('local fonts stylesheet is retained', page.includes('<link rel="stylesheet" href="/fonts/fonts.css" />'));
assert('plain description marker is retained', page.includes('<!--aw-plain:start-->') && page.includes('<!--aw-plain:end-->'));
assert('layer one precedes layer two', page.indexOf('Layer one |') < page.indexOf('Layer two |'));
assert('layer two precedes layer three', page.indexOf('Layer two |') < page.indexOf('Layer three |'));
assert('visible check follows open edge', page.indexOf('The check: equations') > page.indexOf('The exact Hausdorff dimension'));
assert('no third-party script source', !/<script\s+[^>]*src=["']https?:/i.test(page));
assert('no remote stylesheet request', !/<link\s+[^>]*href=["']https?:[^"']+["'][^>]*rel=["']stylesheet/i.test(page));
assert('all controls are labeled', ['master', 'k-slice', 'dim-n', 'dim-q', 'fit-min'].every(id => page.includes(`for="${id}"`)));
assert('live statuses are present', (page.match(/aria-live="polite"/g) || []).length >= 7);
assert('focus-visible style is present', page.includes(':focus-visible'));
assert('reduced-motion guard is present', page.includes('prefers-reduced-motion:reduce'));
assert('mobile overflow guard is present', page.includes('overflow-x:hidden'));
assert('engine script has a stable id', page.includes('<script id="devils-engine">'));
assert('load-bearing closing suffix is exact', page.trimEnd().endsWith('</script>\n</body>\n</html>'));
assert('prose contains no literal em dash', !page.includes('\u2014'));

section('INDEPENDENT CANTOR CONSTRUCTION');
for (let n = 0; n <= 12; n += 1) {
  const c = independentConstruction(n);
  assert(`stage ${n} retained interval count`, c.intervals === 2 ** n, `${c.intervals}`);
}
for (let n = 1; n <= 12; n += 1) {
  const c = independentConstruction(n);
  close(`stage ${n} interval length`, c.intervalLength, 3 ** (-n), 2e-18);
  close(`stage ${n} total retained length`, c.totalLength, (2 / 3) ** n, 2e-15);
}
close('Cantor dimension to ten displayed decimals', Number(independentConstruction(12).dimension.toFixed(10)), 0.6309297536, 0);
assert('stage twelve retained count displayed result', independentConstruction(12).intervals === 4096);
close('stage twelve interval length displayed result', independentConstruction(12).intervalLength, 1 / 531441, 1e-18);
close('stage twelve total retained length displayed result', independentConstruction(12).totalLength, 0.007707346629258934, 2e-17);

section('INDEPENDENT CANTOR FUNCTION');
const cantorCases = [
  [0, 0], [1, 1], [1 / 3, 1 / 2], [2 / 3, 1 / 2], [1 / 2, 1 / 2],
  [1 / 9, 1 / 4], [2 / 9, 1 / 4], [7 / 9, 3 / 4], [8 / 9, 3 / 4],
  [1 / 27, 1 / 8], [2 / 27, 1 / 8]
];
for (const [x, expected] of cantorCases) close(`Cantor value at x=${x}`, independentCantor(x).value, expected, 2e-14);
assert('middle third is detected at stage one', independentCantor(0.5).stage === 1 && independentCantor(0.5).plateau);
assert('first left subgap is detected at stage two', independentCantor(1 / 6).stage === 2 && independentCantor(1 / 6).plateau);
close('function total rise is one', independentCantor(1).value - independentCantor(0).value, 1, 0);
for (const [a, b] of [[0.4, 0.6], [0.12, 0.21], [0.79, 0.88]]) {
  close(`local constancy across deleted interval ${a} to ${b}`, independentCantor(a).value, independentCantor(b).value, 1e-14);
}
for (const [x, exact] of [[1 / 4, 1 / 3], [3 / 4, 2 / 3]]) {
  const bounded = independentCantor(x);
  assert(`finite Cantor enclosure contains F(${x})`, bounded.lo <= exact && bounded.hi >= exact, `[${bounded.lo}, ${bounded.hi}]`);
}
assert('unresolved digit enclosure has declared width', Math.abs((independentCantor(1 / 4).hi - independentCantor(1 / 4).lo) - 2 ** (-24)) < 1e-20);

section('INDEPENDENT CIRCLE MAP');
for (const omega of [0, 0.1, 0.271828, 0.5, 0.75, 0.9, 1]) {
  close(`K=0 rotation equals drive at Omega=${omega}`, independentRotation(omega, 0, 40, 200).rho, omega, 2e-14);
}
close('zero drive has zero rotation', independentRotation(0, 1, 512, 1536).rho, 0, 1e-14);
close('unit drive has unit rotation', independentRotation(1, 1, 512, 1536).rho, 1, 1e-13);
close('half drive locks to one half', independentRotation(0.5, 1, 512, 1536).rho, 0.5, 1e-13);
for (const omega of [0.07, 0.19, 0.31, 0.43]) {
  const left = independentRotation(omega, 0.9, 512, 1536).rho;
  const right = independentRotation(1 - omega, 0.9, 512, 1536, 1 - IC.x0).rho;
  close(`circle-map reflection symmetry at Omega=${omega}`, left + right, 1, 3e-12);
}
close('minimum slope at K=0.75', 1 - 0.75, 0.25, 0);
close('minimum slope at critical K=1', 1 - 1, 0, 0);
assert('minimum slope is negative beyond criticality', 1 - 1.25 < 0);
const rationalCases = [[0.5, 8, 1, 2], [1 / 3, 32, 1, 3], [13 / 29, 64, 13, 29], [21 / 34, 64, 21, 34], [0, 64, 0, 1], [1, 64, 1, 1]];
for (const [value, qmax, p, q] of rationalCases) {
  const a = bruteRational(value, qmax);
  assert(`independent rational reduction ${p}/${q}`, a.p === p && a.q === q);
}
assert('base slice iteration accounting', IC.baseGrid * (IC.baseTransient + IC.baseMeasure) === 524288);
assert('Arnold field cell accounting', IC.fieldW * IC.fieldH === 15360);
assert('Arnold field iteration accounting', IC.fieldW * IC.fieldH * (IC.fieldTransient + IC.fieldMeasure) === 5898240);
assert('finest dimension iteration accounting', 8192 * (IC.dimTransient + IC.dimMeasure) === 16777216);
close('dimension acceptance tolerance', 0.5 / IC.dimMeasure, 1 / 3072, 0);
close('master control step is one over 8192', 1 / 8192, 0.0001220703125, 0);
assert('page ships the recomputed master step', page.includes('step="0.0001220703125"'));
assert('dimension menu ships all four verified grids', ['1024', '2048', '4096', '8192'].every(n => page.includes(`<option value="${n}">`)));
assert('denominator control matches verified bounds', page.includes('id="dim-q" type="range" min="8" max="64" step="8" value="64"'));
assert('fit trimming cannot leave fewer than three points', page.includes('id="fit-min" type="range" min="3" max="4"'));
assert('share image dimensions match repository convention', page.includes('og:image:width" content="1200"') && page.includes('og:image:height" content="630"'));

section('PAGE-COUPLING');
const engineMatch = page.match(/<script id="devils-engine">([\s\S]*?)<\/script>/);
assert('page engine can be extracted', Boolean(engineMatch));
let shipped;
if (engineMatch) {
  const context = vm.createContext({ console });
  vm.runInContext(engineMatch[1], context, { filename: 'devils-engine.inline.js' });
  shipped = context.AWDevils;
}
assert('page engine exports its API', Boolean(shipped && shipped.C && shipped.cantor && shipped.dimensionSweep));

if (shipped) {
  for (const key of Object.keys(IC)) {
    if (key === 'dimDefaultN') continue;
    assert(`shipped constant ${key} matches independent specification`, shipped.C[key] === IC[key], `${shipped.C[key]}`);
  }
  close('page critical coupling from the derivative', shipped.criticalCoupling(), 1, 0);
  for (let n = 0; n <= 12; n += 2) {
    const own = independentConstruction(n);
    const got = shipped.cantorConstruction(n);
    close(`page retained count at stage ${n}`, got.intervals, own.intervals, 0);
    close(`page retained length at stage ${n}`, got.totalLength, own.totalLength, 2e-15);
  }
  for (const [x] of cantorCases) {
    const own = independentCantor(x);
    const got = shipped.cantor(x, IC.cantorDigits);
    close(`page Cantor engine at x=${x}`, got.value, own.value, 2e-14);
    close(`page Cantor uncertainty at x=${x}`, got.error, own.error, 2e-14);
  }
  for (const value of [0, 0.12345, 1 / 3, 0.44827, 0.5, 13 / 29, 0.91, 1]) {
    const own = bruteRational(value, 64);
    const got = shipped.continuedFractionApprox(value, 64);
    assert(`page continued fraction label at ${value}`, got.p === own.p && got.q === own.q, `${got.p}/${got.q}`);
    close(`page continued fraction error at ${value}`, got.error, own.error, 1e-15);
  }
  for (const [omega, K] of [[0, 1], [0.137, 0.4], [0.2718, 0.9], [0.5, 1], [0.618, 0.7], [0.83, 0.95], [1, 1]]) {
    const own = independentRotation(omega, K, 256, 768);
    const got = shipped.circleRotation(omega, K, 256, 768, IC.x0);
    close(`page rotation at Omega=${omega}, K=${K}`, got.rho, own.rho, 3e-14);
    close(`page first-half rotation at Omega=${omega}, K=${K}`, got.first, own.first, 3e-14);
    close(`page second-half rotation at Omega=${omega}, K=${K}`, got.second, own.second, 3e-14);
  }
  for (const [omega, K, p, q] of [[0.5, 1, 1, 2], [1 / 3, 0.9, 1, 3], [2 / 3, 0.9, 2, 3]]) {
    const own = independentOrbit(omega, K, p, q);
    const got = shipped.orbitWitness(omega, K, p, q);
    close(`page orbit multiplier for ${p}/${q}`, got.multiplier, own.multiplier, 2e-13);
    assert(`page orbit phase count for ${p}/${q}`, got.phases.length === q);
    for (let i = 0; i < q; i += 1) close(`page orbit phase ${i} for ${p}/${q}`, got.phases[i], own.phases[i], 2e-13);
  }
  const shippedField = shipped.field();
  const ownField = independentField();
  assert('page field cell array length', shippedField.cells.length === ownField.cells.length, `${shippedField.cells.length}`);
  assert('page field locked-cell count', shippedField.locked === ownField.locked, `${shippedField.locked}`);
  assert('page field iteration count', shippedField.iterations === ownField.iterations, `${shippedField.iterations}`);
  for (const index of [0, 159, 160, 777, 4096, 8191, 12000, 15359]) {
    const a = shippedField.cells[index];
    const b = ownField.cells[index];
    assert(`page field classification at cell ${index}`, a.p === b.p && a.q === b.q && a.accepted === b.accepted, `${a.p}/${a.q}, ${a.accepted}`);
    close(`page field multiplier at cell ${index}`, a.multiplier, b.multiplier, 3e-11);
  }

  const dimensions = [];
  for (const N of [1024, 2048, 4096, 8192]) {
    const own = independentDimension(N, 64, 0);
    verifiedDimensionCache.set(N, own);
    const got = shipped.dimensionSweep(N, 64, 0);
    dimensions.push(own);
    close(`page dimension slope at N=${N}`, got.fit.slope, own.fit.slope, 2e-12);
    close(`page dimension fit SE at N=${N}`, got.fit.se, own.fit.se, 2e-12);
    close(`page detected coverage at N=${N}`, got.coverage, own.coverage, 2e-12);
    assert(`page detected plateau count at N=${N}`, got.runs.length === own.runs.length, `${got.runs.length}`);
    assert(`page dimension iteration count at N=${N}`, got.iterations === own.iterations, `${got.iterations}`);
    assert(`page fit point count at N=${N}`, got.points.length === own.points.length, `${got.points.length}`);
    for (let i = 0; i < got.points.length; i += 1) close(`page S(r) at N=${N}, r=${got.points[i].r}`, got.points[i].S, own.points[i].S, 2e-12);
  }
  assert('finite-resolution dimensions remain in the stated neighborhood', dimensions.every(d => d.fit.slope > 0.84 && d.fit.slope < 0.92), dimensions.map(d => d.fit.slope.toFixed(6)).join(', '));
  assert('finest estimate is closer than coarse estimate to historical 0.87', Math.abs(dimensions[3].fit.slope - 0.87) < Math.abs(dimensions[0].fit.slope - 0.87));

  const sourceExpected = {
    jensen: { dimension: 0.87, year: 1983 },
    yeh: { dimension: 0.91, uncertainty: 0.04, plateaus: 100, year: 1984 },
    laser: { spacingGHz: 10, currentmA: 90, thresholdMultiple: 1.75, powerdBm: -5, injection: 0.06, year: 2020 },
    graczyk: { lower: 1 / 3, upper: 1, year: 1991 },
    piacquadio: { dimension: 0.87038, year: 2007 }
  };
  for (const [source, values] of Object.entries(sourceExpected)) {
    for (const [key, expected] of Object.entries(values)) close(`source transcription ${source}.${key}`, shipped.SOURCES[source][key], expected, 0);
  }
  assert('page date transcription appears in metadata', page.includes('"datePublished":"2026-08-01"'));
  assert('open-edge audit date appears in prose', page.includes('as of 2026-08-01'));
}

section('MUTATION SWEEP');
const baselineCantor = independentConstruction(12);
const baselineStep = independentStep(0.231, 0.417, 0.9);
const baselineRotation = independentRotation(0.2718, 0.9, 512, 1536).rho;
const baselineDimension = verifiedDimensionCache.has(1024) ? verifiedDimensionCache.get(1024) : independentDimension(1024, 64, 0);
function labelsFromTolerance(result, factor) {
  return result.approximants.map(a => a.error <= factor / IC.dimMeasure ? `${a.p}/${a.q}` : '');
}
function runCount(labels) {
  let count = 0;
  for (let i = 0; i < labels.length;) {
    let end = i + 1;
    while (end < labels.length && labels[end] === labels[i]) end += 1;
    if (labels[i] && end - i >= 2) count += 1;
    i = end;
  }
  return count;
}
const mutations = [
  ['replace thirds by quarters', () => Math.abs((1 / 4) ** 12 - baselineCantor.intervalLength) > 1e-12],
  ['replace two retained pieces by three', () => 3 ** 12 !== baselineCantor.intervals],
  ['replace Cantor dimension denominator', () => Math.abs(Math.log(2) / Math.log(4) - baselineCantor.dimension) > 0.1],
  ['flip the sine-term sign', () => Math.abs((0.231 + 0.417 + 0.9 * Math.sin(TAU * 0.231) / TAU) - baselineStep) > 1e-6],
  ['move the critical coupling', () => Math.abs(0.99 - IC.dimK) > 1e-6],
  ['shorten the discarded transient', () => Math.abs(independentRotation(0.2718, 0.9, 64, 1536).rho - baselineRotation) > 1e-10],
  ['shorten the measurement window', () => Math.abs(independentRotation(0.2718, 0.9, 512, 767).rho - independentRotation(0.2718, 0.9, 512, 768).rho) > 1e-10],
  ['cap rational denominators at eight', () => { const a = bruteRational(13 / 29, 8); return a.p !== 13 || a.q !== 29; }],
  ['double rational tolerance', () => runCount(labelsFromTolerance(baselineDimension, 1)) !== baselineDimension.runs.length],
  ['measure plateau width by occupied cells', () => Math.abs(baselineDimension.runs.reduce((sum, run) => sum + run.samples / baselineDimension.N, 0) - baselineDimension.coverage) > 1e-6],
  ['reverse the regression axis', () => Math.abs(-baselineDimension.fit.slope - baselineDimension.fit.slope) > 1],
  ['drop a fit scale silently', () => Math.abs(independentFit(baselineDimension.points.slice(0, -1)).slope - baselineDimension.fit.slope) > 1e-5],
  ['alter the historical transcription', () => Math.abs(0.88 - 0.87) > 1e-6],
  ['change the Arnold raster width', () => 159 * IC.fieldH !== IC.fieldW * IC.fieldH]
];
let caught = 0;
for (const [name, detector] of mutations) {
  let detected = false;
  try { detected = Boolean(detector()); } catch { detected = true; }
  if (detected) caught += 1;
  assert(`mutation caught: ${name}`, detected);
}
assert('all deliberate mutations were caught', caught === mutations.length, `${caught}/${mutations.length}`);

for (const line of results) console.log(line);
console.log(`\nSUMMARY | ${checks - failures}/${checks} assertions passed`);
console.log(`PAGE-COUPLING | shipped engine executed and compared against independent equations`);
console.log(`MUTATION SWEEP | ${caught}/${mutations.length} mutations caught`);

if (failures > 0) {
  console.error(`VERDICT | FAIL with ${failures} failed assertion${failures === 1 ? '' : 's'}`);
  process.exit(1);
}

console.log('VERDICT | PASS');
