#!/usr/bin/env node
import fs from 'node:fs';
import path from 'node:path';
import vm from 'node:vm';
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/kosterlitz-thouless/index.html');
const html = fs.readFileSync(pagePath, 'utf8');
let checks = 0;
let failures = 0;

function report(ok, label, detail = '') {
  checks += 1;
  const mark = ok ? 'PASS' : 'FAIL';
  console.log(`${mark} ${String(checks).padStart(3, '0')}  ${label}${detail ? `  ${detail}` : ''}`);
  if (!ok) failures += 1;
  return ok;
}

function equal(actual, expected, label) {
  return report(Object.is(actual, expected), label, `actual=${actual} expected=${expected}`);
}

function close(actual, expected, tolerance, label) {
  const ok = Number.isFinite(actual) && Number.isFinite(expected) && Math.abs(actual - expected) <= tolerance;
  return report(ok, label, `actual=${actual} expected=${expected} tol=${tolerance}`);
}

function truth(value, label, detail = '') {
  return report(Boolean(value), label, detail);
}

const I = Object.freeze({
  tau: 2 * Math.PI,
  n: 64,
  windTolerance: 1e-6,
  dl: 0.01,
  maxSteps: 1200,
  bisections: 32,
  temperatureLow: 0.2,
  temperatureHigh: 2,
  escapeY: 1,
  fitCount: 40,
  fitTMin: 0.01,
  fitTMax: 0.16,
  heliumMass: 6.646476989e-27,
  boltzmann: 1.380649e-23,
  hbar: 1.054571817e-34,
  monteCarloBeta: 1.1199,
  hsiehTemperature: 0.8935,
  hsiehError: 0.0001,
  jhaTemperature: 0.89290,
  jhaError: 0.00005
});

function independentWrap(angle) {
  let answer = angle;
  while (answer > Math.PI) answer -= I.tau;
  while (answer <= -Math.PI) answer += I.tau;
  return answer;
}

function independentPhase(x, y, positive, negative) {
  const a = Math.atan2(y - positive.y, x - positive.x);
  const b = Math.atan2(y - negative.y, x - negative.x);
  return independentWrap(a - b);
}

function independentField(positive, negative, n = I.n) {
  const rows = Array.from({ length: n }, () => Array(n));
  for (let y = 0; y < n; y += 1) {
    for (let x = 0; x < n; x += 1) rows[y][x] = independentPhase(x, y, positive, negative);
  }
  return rows;
}

function independentDifference(field, x0, y0, x1, y1) {
  return independentWrap(field[y1][x1] - field[y0][x0]);
}

function independentPlaquettes(field) {
  let positive = 0;
  let negative = 0;
  let zero = 0;
  let maxResidual = 0;
  for (let y = 0; y < field.length - 1; y += 1) {
    for (let x = 0; x < field.length - 1; x += 1) {
      const sum = independentDifference(field, x, y, x + 1, y)
        + independentDifference(field, x + 1, y, x + 1, y + 1)
        + independentDifference(field, x + 1, y + 1, x, y + 1)
        + independentDifference(field, x, y + 1, x, y);
      const raw = sum / I.tau;
      const rounded = Math.round(raw);
      maxResidual = Math.max(maxResidual, Math.abs(raw - rounded));
      if (rounded === 1) positive += 1;
      else if (rounded === -1) negative += 1;
      else zero += 1;
    }
  }
  return { positive, negative, zero, maxResidual };
}

function independentLoop(field, loop) {
  const h = Math.max(3, Math.min(30, Math.round(loop.h)));
  const cx = Math.max(h, Math.min(field.length - 1 - h, Math.round(loop.cx)));
  const cy = Math.max(h, Math.min(field.length - 1 - h, Math.round(loop.cy)));
  const x0 = cx - h;
  const x1 = cx + h;
  const y0 = cy - h;
  const y1 = cy + h;
  let sum = 0;
  let edges = 0;
  for (let x = x0; x < x1; x += 1) { sum += independentDifference(field, x, y0, x + 1, y0); edges += 1; }
  for (let y = y0; y < y1; y += 1) { sum += independentDifference(field, x1, y, x1, y + 1); edges += 1; }
  for (let x = x1; x > x0; x -= 1) { sum += independentDifference(field, x, y1, x - 1, y1); edges += 1; }
  for (let y = y1; y > y0; y -= 1) { sum += independentDifference(field, x0, y, x0, y - 1); edges += 1; }
  const raw = sum / I.tau;
  return { sum, raw, charge: Math.round(raw), residual: Math.abs(raw - Math.round(raw)), edges };
}

function independentRates(K, y) {
  const inverseStiffnessRate = 4 * Math.PI ** 3 * y ** 2;
  return {
    K: -inverseStiffnessRate * K ** 2,
    y: (2 - Math.PI * K) * y
  };
}

function independentRK4(K, y, step = I.dl) {
  const first = independentRates(K, y);
  const second = independentRates(K + first.K * step / 2, y + first.y * step / 2);
  const third = independentRates(K + second.K * step / 2, y + second.y * step / 2);
  const fourth = independentRates(K + third.K * step, y + third.y * step);
  return {
    K: K + step * (first.K + 2 * second.K + 2 * third.K + fourth.K) / 6,
    y: y + step * (first.y + 2 * second.y + 2 * third.y + fourth.y) / 6
  };
}

function independentRun(K0, y0, options = {}) {
  const step = options.step ?? I.dl;
  const maximum = options.maximum ?? I.maxSteps;
  const threshold = options.threshold ?? I.escapeY;
  let K = K0;
  let y = y0;
  let escaped = false;
  let steps = 0;
  for (; steps < maximum; steps += 1) {
    ({ K, y } = independentRK4(K, y, step));
    if (!Number.isFinite(K) || !Number.isFinite(y) || y >= threshold) {
      escaped = true;
      steps += 1;
      break;
    }
  }
  return { K, y, escaped, steps, l: steps * step };
}

function independentTemperatureRun(temperature, muOverJ) {
  return independentRun(1 / temperature, Math.exp(-muOverJ / temperature));
}

function independentCritical(muOverJ) {
  let low = I.temperatureLow;
  let high = I.temperatureHigh;
  for (let iteration = 0; iteration < I.bisections; iteration += 1) {
    const midpoint = (low + high) / 2;
    const result = independentTemperatureRun(midpoint, muOverJ);
    const score = result.escaped ? -1 : result.K - 2 / Math.PI;
    if (score > 0) low = midpoint;
    else high = midpoint;
  }
  const temperature = (low + high) / 2;
  return { temperature, low, high, run: independentTemperatureRun(temperature, muOverJ) };
}

function independentRegression(points) {
  const xMean = points.reduce((sum, point) => sum + point.x, 0) / points.length;
  const yMean = points.reduce((sum, point) => sum + point.y, 0) / points.length;
  const covariance = points.reduce((sum, point) => sum + (point.x - xMean) * (point.y - yMean), 0);
  const variance = points.reduce((sum, point) => sum + (point.x - xMean) ** 2, 0);
  const slope = covariance / variance;
  const intercept = yMean - slope * xMean;
  const residual = points.reduce((sum, point) => sum + (point.y - intercept - slope * point.x) ** 2, 0);
  const total = points.reduce((sum, point) => sum + (point.y - yMean) ** 2, 0);
  return { slope, intercept, r2: 1 - residual / total };
}

function independentSweep(muOverJ) {
  const critical = independentCritical(muOverJ);
  const points = [];
  for (let index = 0; index < I.fitCount; index += 1) {
    const t = I.fitTMin + (I.fitTMax - I.fitTMin) * index / (I.fitCount - 1);
    const temperature = critical.temperature * (1 + t);
    const run = independentTemperatureRun(temperature, muOverJ);
    if (run.escaped) points.push({ t, x: 1 / Math.sqrt(t), y: run.l, xi: Math.exp(run.l) });
  }
  return { critical, points, fit: independentRegression(points) };
}

function independentHeliumJump() {
  return (2 * I.heliumMass ** 2 * I.boltzmann) / (Math.PI * I.hbar ** 2);
}

console.log('\nSTRUCTURE AND DISPLAY COVERAGE');
truth(html.endsWith('</script>\n</body>\n</html>\n'), 'load-bearing closing tags are the final bytes');
truth(!html.includes(String.fromCodePoint(0x2014)), 'page contains no forbidden dash glyph');
truth(!/<(?:script|img)[^>]+src=["']https?:/i.test(html), 'page has no remote script or image request');
truth(!/<link[^>]+rel=["'](?:stylesheet|preload)["'][^>]+href=["']https?:/i.test(html), 'page has no remote stylesheet or preload request');
equal((html.match(/<canvas\b/g) || []).length, 3, 'three local canvases are shipped');
truth(html.includes('@media(prefers-reduced-motion:reduce)'), 'reduced-motion guard is present');
truth(html.includes(':focus-visible'), 'visible keyboard focus rule is present');
truth((html.match(/role="status"/g) || []).length >= 2, 'both instrument statuses are live');

const displayedNames = [...new Set([...html.matchAll(/data-live="([^"]+)"/g)].map(match => match[1]).filter(name => !name.includes('+')))].sort();
const independentlyCoveredNames = [
  'bisect-count','critical-pik','escape-y','eta','fit-count','fit-t-max','fit-t-min','grid-size',
  'hbar','he-mass','helium-jump','hsieh-temp','jha-temp','jump-k','kb','max-rk4','mc-beta',
  'mc-temp','mc-temp-long','naive-tc','phase-evals','plaquettes','rg-step','rg-steps','temp-hi',
  'temp-lo','wind-tol'
].sort();
equal(displayedNames.join(','), independentlyCoveredNames.join(','), 'every data-live number has an independent verifier route');
truth(html.includes('2005') && html.includes('2013') && html.includes('2020'), 'open-edge source years are named');
truth(html.includes('2026-08-01'), 'open-edge status date is explicit');
truth(html.includes('1970') && html.includes('1971') && html.includes('1973') && html.includes('1977'), 'historical source years are named');

console.log('\nINDEPENDENT TOPOLOGY CHECKS');
close(independentWrap(0), 0, 0, 'zero wraps to zero');
close(independentWrap(3 * Math.PI), Math.PI, 1e-15, 'positive three pi wraps to positive pi');
close(independentWrap(-3 * Math.PI), Math.PI, 1e-15, 'negative three pi follows the interval convention');
close(independentWrap(7.25), independentWrap(7.25 + 8 * Math.PI), 1e-14, 'wrap is periodic');
const positive = { x: 21.5, y: 31.5 };
const negative = { x: 42.5, y: 31.5 };
const independentDefaultField = independentField(positive, negative);
const independentCharges = independentPlaquettes(independentDefaultField);
equal(I.n * I.n, 4096, 'phase evaluation count');
equal((I.n - 1) ** 2, 3969, 'plaquette count');
equal(independentCharges.positive, 1, 'one positive plaquette defect');
equal(independentCharges.negative, 1, 'one negative plaquette defect');
equal(independentCharges.zero, 3967, 'all other plaquettes have zero winding');
equal(independentCharges.positive - independentCharges.negative, 0, 'total lattice charge cancels');
truth(independentCharges.maxResidual < 1e-12, 'plaquette integer residual is numerical noise', `residual=${independentCharges.maxResidual}`);
const independentPositiveLoop = independentLoop(independentDefaultField, { cx: 22, cy: 31, h: 8 });
const independentNegativeLoop = independentLoop(independentDefaultField, { cx: 43, cy: 31, h: 8 });
const independentBothLoop = independentLoop(independentDefaultField, { cx: 32, cy: 31, h: 22 });
const independentNeitherLoop = independentLoop(independentDefaultField, { cx: 8, cy: 8, h: 5 });
equal(independentPositiveLoop.charge, 1, 'loop around positive core gives plus one');
equal(independentNegativeLoop.charge, -1, 'loop around negative core gives minus one');
close(independentBothLoop.charge, 0, 0, 'loop around both cores cancels');
equal(independentNeitherLoop.charge, 0, 'loop around neither core gives zero');
equal(independentPositiveLoop.edges, 64, 'default one-core loop edge count');
equal(independentBothLoop.edges, 176, 'both-core loop edge count');
equal(independentNeitherLoop.edges, 40, 'empty loop edge count');
truth(independentPositiveLoop.residual < I.windTolerance, 'one-core loop passes stated rounding tolerance');
equal(8 * 30, 240, 'maximum allowed loop has at most 240 edges');

console.log('\nINDEPENDENT FLOW AND DISPLAYED NUMBERS');
const rates = independentRates(1, 0.1);
close(rates.K, -4 * Math.PI ** 3 * 0.01, 1e-15, 'stiffness derivative follows inverse-stiffness equation');
close(rates.y, (2 - Math.PI) * 0.1, 1e-15, 'fugacity derivative follows scaling dimension');
const oneStep = independentRK4(1.2, Math.exp(-2.4));
truth(oneStep.K < 1.2, 'one RK4 step lowers stiffness for nonzero fugacity');
truth(oneStep.y < Math.exp(-2.4), 'chosen cold-side first step lowers fugacity');
const independentChosen = independentRun(1.2, Math.exp(-2.4));
equal(independentChosen.escaped, false, 'default selected trajectory enters bound-pair basin');
equal(independentChosen.steps, 1200, 'bound trajectory reaches finite integration cutoff');
close(independentChosen.l, 12, 1e-14, 'finite flow cutoff is ell max equals twelve');
const independentHot = independentTemperatureRun(1.2, 2);
equal(independentHot.escaped, true, 'hot trajectory reaches order-one fugacity');
truth(independentHot.l < 12, 'hot trajectory escapes before the cutoff');
const independentCold = independentTemperatureRun(0.6, 2);
equal(independentCold.escaped, false, 'cold trajectory remains in bound basin');
const independentTc = independentCritical(2);
truth(independentTc.temperature > 0.83 && independentTc.temperature < 0.84, 'finite-cutoff shooting temperature is bracketed', `Tc=${independentTc.temperature}`);
truth(independentTc.high - independentTc.low < 5e-10, '32 bisections narrow the temperature bracket', `width=${independentTc.high - independentTc.low}`);
close(independentTc.run.K, 2 / Math.PI, 2e-9, 'shooting endpoint reaches two over pi at finite cutoff');
const independentEssential = independentSweep(2);
equal(independentEssential.points.length, 40, 'all 40 requested temperatures reach escape threshold');
close(independentEssential.points[0].t, 0.01, 1e-15, 'fit window begins at stated reduced temperature');
close(independentEssential.points.at(-1).t, 0.16, 1e-15, 'fit window ends at stated reduced temperature');
truth(independentEssential.points[0].xi > independentEssential.points.at(-1).xi, 'correlation length grows toward the transition');
truth(independentEssential.fit.slope > 0, 'essential-singularity fit has positive amplitude');
truth(independentEssential.fit.r2 > 0.99, 'computed escape scales are nearly linear in inverse square root t', `R2=${independentEssential.fit.r2}`);
close(Math.PI * (2 / Math.PI), 2, 1e-15, 'critical pi K is two');
close(2 / Math.PI, 0.6366197723675814, 1e-15, 'universal dimensionless stiffness jump');
close(1 / (2 * Math.PI * (2 / Math.PI)), 0.25, 1e-15, 'critical correlation exponent is one quarter');
const helium = independentHeliumJump();
truth(helium > 3.48e-8 && helium < 3.50e-8, 'helium areal-density slope lies in recomputed narrow bracket', `value=${helium}`);
close(helium / 10, 3.491e-9, 5e-13, 'SI to gram per square centimetre conversion');
close(Math.PI / 2, 1.5707963267948966, 1e-15, 'naive bare-stiffness temperature');
const reciprocalTemperature = 1 / I.monteCarloBeta;
close(reciprocalTemperature, 0.892936869363336, 1e-15, 'Monte Carlo inverse temperature reciprocal');
truth(Math.abs(Math.PI / 2 - reciprocalTemperature) > 0.67, 'naive and square-lattice benchmark are materially different');
equal(I.bisections + I.fitCount, 72, 'one sweep launches 72 RG integrations');
equal((I.bisections + I.fitCount) * I.maxSteps, 86400, 'maximum RK4 step budget per sweep');
truth(I.hsiehTemperature - I.hsiehError > I.jhaTemperature + I.jhaError, '2013 and 2020 quoted one-sigma intervals do not overlap');

console.log('\nPAGE-COUPLING: EXECUTE THE SHIPPED PAGE ENGINE');
const engineMatch = html.match(/<script id="kt-engine">([\s\S]*?)<\/script>/);
truth(engineMatch, 'page engine script is extractable');
const context = vm.createContext({ console });
vm.runInContext(engineMatch[1], context, { filename: 'kosterlitz-thouless-page-engine.js' });
const P = context.KTEngine;
truth(P && typeof P.essentialSweep === 'function', 'shipped engine executed and exported its API');
equal(P.C.N, I.n, 'page grid size matches independent input');
equal(P.C.DL, I.dl, 'page RK4 step matches independent input');
equal(P.C.MAX_STEPS, I.maxSteps, 'page flow cutoff matches independent input');
equal(P.C.BISECT, I.bisections, 'page bisection count matches independent input');
equal(P.C.FIT_COUNT, I.fitCount, 'page fit sample count matches independent input');
equal(P.C.MC_BETA, I.monteCarloBeta, 'page source transcription beta matches checked input');
close(P.wrap(-3 * Math.PI), independentWrap(-3 * Math.PI), 1e-15, 'page wrap convention matches independent wrap');
const pageField = P.phaseField(positive, negative, I.n);
close(pageField[17 * I.n + 9], independentDefaultField[17][9], 1e-15, 'page phase sample matches independent field');
close(pageField[50 * I.n + 55], independentDefaultField[50][55], 2e-15, 'second page phase sample matches independent field');
const pageCharges = P.plaquetteCharges(pageField, I.n);
equal(pageCharges.positive, independentCharges.positive, 'page positive defect count matches');
equal(pageCharges.negative, independentCharges.negative, 'page negative defect count matches');
equal(pageCharges.zero, independentCharges.zero, 'page zero plaquette count matches');
const pagePositiveLoop = P.loopWinding(pageField, I.n, { cx: 22, cy: 31, h: 8 });
const pageBothLoop = P.loopWinding(pageField, I.n, { cx: 32, cy: 31, h: 22 });
close(pagePositiveLoop.sum, independentPositiveLoop.sum, 1e-13, 'page one-core wrapped sum matches');
equal(pagePositiveLoop.charge, independentPositiveLoop.charge, 'page one-core integer matches');
close(pageBothLoop.charge, independentBothLoop.charge, 0, 'page both-core cancellation matches');
const pageStep = P.rk4(1.2, Math.exp(-2.4), I.dl);
close(pageStep.K, oneStep.K, 1e-15, 'page RK4 stiffness step matches');
close(pageStep.y, oneStep.y, 1e-15, 'page RK4 fugacity step matches');
const pageChosen = P.trajectory(1.2, 2.4);
close(pageChosen.K, independentChosen.K, 2e-14, 'page full chosen stiffness trajectory matches');
close(pageChosen.y, independentChosen.y, 2e-14, 'page full chosen fugacity trajectory matches');
equal(pageChosen.escaped, independentChosen.escaped, 'page chosen flow classification matches');
const pageCritical = P.locateCritical(2);
close(pageCritical.tc, independentTc.temperature, 2e-13, 'page 32-step shooting temperature matches');
close(pageCritical.run.K, independentTc.run.K, 2e-12, 'page separatrix endpoint matches');
const pageSweep = P.essentialSweep(2);
equal(pageSweep.points.length, independentEssential.points.length, 'page fitted escape count matches');
close(pageSweep.points[0].xi, independentEssential.points[0].xi, 2e-12, 'page largest correlation length matches');
close(pageSweep.points.at(-1).xi, independentEssential.points.at(-1).xi, 2e-12, 'page smallest correlation length matches');
close(pageSweep.fit.slope, independentEssential.fit.slope, 2e-12, 'page essential amplitude fit matches');
close(pageSweep.fit.intercept, independentEssential.fit.intercept, 2e-12, 'page fit intercept matches');
close(pageSweep.fit.r2, independentEssential.fit.r2, 2e-12, 'page fit R squared matches');
const pageDerived = P.derived();
close(pageDerived.jumpK, 2 / Math.PI, 1e-15, 'page universal jump matches');
close(pageDerived.eta, 0.25, 1e-15, 'page eta matches');
close(pageDerived.heliumJump, helium, 1e-20, 'page helium conversion matches');
close(pageDerived.naiveTc, Math.PI / 2, 1e-15, 'page naive temperature matches');
close(pageDerived.mcTemp, reciprocalTemperature, 1e-15, 'page Monte Carlo reciprocal matches');
equal(pageDerived.phaseEvaluations, 4096, 'page phase evaluation count matches');
equal(pageDerived.plaquettes, 3969, 'page plaquette count matches');
equal(pageDerived.maxRK4, 86400, 'page maximum work count matches');

console.log('\nMUTATION SWEEP: PROVE THE CHECKS CAN FAIL');
let mutationsAttempted = 0;
let mutationsCaught = 0;
function mutation(label, detected) {
  mutationsAttempted += 1;
  const caught = Boolean(detected);
  if (caught) mutationsCaught += 1;
  report(caught, `mutation caught: ${label}`);
}

mutation('use an unwrapped edge difference', (() => {
  const z = { x0: 14, x1: 30, y0: 23, y1: 39 };
  let rawSum = 0;
  for (let x = z.x0; x < z.x1; x += 1) rawSum += independentDefaultField[z.y0][x + 1] - independentDefaultField[z.y0][x];
  for (let y = z.y0; y < z.y1; y += 1) rawSum += independentDefaultField[y + 1][z.x1] - independentDefaultField[y][z.x1];
  for (let x = z.x1; x > z.x0; x -= 1) rawSum += independentDefaultField[z.y1][x - 1] - independentDefaultField[z.y1][x];
  for (let y = z.y1; y > z.y0; y -= 1) rawSum += independentDefaultField[y - 1][z.x0] - independentDefaultField[y][z.x0];
  return Math.abs(rawSum - independentPositiveLoop.sum) > 6;
})());
mutation('reverse the inspection-loop orientation', -independentPositiveLoop.charge !== independentPositiveLoop.charge);
mutation('drop the antivortex field', independentPlaquettes(independentField(positive, { x: 1e9, y: 1e9 })).negative !== 1);
mutation('move the positive core outside its preset loop', independentLoop(independentField({ x: 55.5, y: 55.5 }, negative), { cx: 22, cy: 31, h: 8 }).charge !== 1);
mutation('round every wrapped edge before summing', (() => {
  const loop = { x0: 14, x1: 30, y0: 23, y1: 39 };
  let alteredSum = 0;
  for (let x = loop.x0; x < loop.x1; x += 1) alteredSum += Math.round(independentDifference(independentDefaultField, x, loop.y0, x + 1, loop.y0));
  for (let y = loop.y0; y < loop.y1; y += 1) alteredSum += Math.round(independentDifference(independentDefaultField, loop.x1, y, loop.x1, y + 1));
  for (let x = loop.x1; x > loop.x0; x -= 1) alteredSum += Math.round(independentDifference(independentDefaultField, x, loop.y1, x - 1, loop.y1));
  for (let y = loop.y1; y > loop.y0; y -= 1) alteredSum += Math.round(independentDifference(independentDefaultField, loop.x0, y, loop.x0, y - 1));
  return Math.abs(alteredSum - independentPositiveLoop.sum) > 0.1;
})());
mutation('replace 4 pi cubed by 4 pi squared', Math.abs((-4 * Math.PI ** 2 * 0.01) - rates.K) > 0.1);
mutation('flip the fugacity scaling sign', Math.abs((Math.PI * 1.2 - 2) * Math.exp(-2.4) - independentRates(1.2, Math.exp(-2.4)).y) > 0.01);
mutation('use Euler instead of RK4', (() => {
  const r = independentRates(1.2, Math.exp(-2.4));
  return Math.abs((1.2 + I.dl * r.K) - oneStep.K) > 1e-8;
})());
mutation('double the RG step', (() => {
  const altered = independentRun(1.2, Math.exp(-2.4), { step: 0.02, maximum: 600 });
  return Math.abs(altered.K - independentChosen.K) > 1e-7;
})());
mutation('halve the finite flow cutoff', (() => {
  const altered = independentRun(1.2, Math.exp(-2.4), { maximum: 600 });
  return Math.abs(altered.K - independentChosen.K) > 1e-5;
})());
mutation('set the escape threshold to one half', (() => {
  const altered = independentRun(1 / 1.2, Math.exp(-2 / 1.2), { threshold: 0.5 });
  return altered.l !== independentHot.l;
})());
mutation('use fugacity exp(+mu/T)', independentRun(1 / 0.6, Math.exp(2 / 0.6)).escaped !== independentCold.escaped);
mutation('stop shooting after eight bisections', (I.temperatureHigh - I.temperatureLow) / 2 ** 8 > 1e-3);
mutation('fit against inverse t instead of inverse square root t', (() => {
  const altered = independentRegression(independentEssential.points.map(point => ({ x: 1 / point.t, y: point.y })));
  return Math.abs(altered.r2 - independentEssential.fit.r2) > 1e-3;
})());
mutation('drop one temperature from the sweep', independentEssential.points.slice(1).length !== I.fitCount);
mutation('omit the factor two in the universal jump', Math.abs(1 / Math.PI - 2 / Math.PI) > 0.3);
mutation('use eta equals one over pi K', Math.abs(1 / (Math.PI * (2 / Math.PI)) - 0.25) > 0.2);
mutation('omit one helium mass factor', Math.abs(2 * I.heliumMass * I.boltzmann / (Math.PI * I.hbar ** 2) - helium) > helium);
mutation('use Planck h in place of hbar', (() => {
  const h = 2 * Math.PI * I.hbar;
  return Math.abs(2 * I.heliumMass ** 2 * I.boltzmann / (Math.PI * h ** 2) - helium) > helium * 0.9;
})());
mutation('mistake beta for temperature', Math.abs(I.monteCarloBeta - reciprocalTemperature) > 0.2);
mutation('call the bare balance the square-lattice answer', Math.abs(Math.PI / 2 - reciprocalTemperature) > 0.67);
mutation('claim the two quoted numerical intervals overlap', I.hsiehTemperature - I.hsiehError > I.jhaTemperature + I.jhaError);

console.log(`\nMUTATIONS CAUGHT ${mutationsCaught}/${mutationsAttempted}`);
console.log(`ASSERTIONS ${checks}, FAILURES ${failures}`);
if (failures > 0 || mutationsCaught !== mutationsAttempted) process.exitCode = 1;
