#!/usr/bin/env node
import fs from 'node:fs';
import vm from 'node:vm';

const PAGE = new URL('../../public/strata/casimir-lifshitz/index.html', import.meta.url);
const html = fs.readFileSync(PAGE, 'utf8');
let passed = 0;
let failed = 0;
let assertions = 0;

function check(name, condition, detail = '') {
  assertions += 1;
  if (condition) {
    passed += 1;
    console.log(`PASS ${String(assertions).padStart(3, '0')}  ${name}${detail ? `  ${detail}` : ''}`);
  } else {
    failed += 1;
    console.error(`FAIL ${String(assertions).padStart(3, '0')}  ${name}${detail ? `  ${detail}` : ''}`);
  }
}

function near(actual, expected, rel = 1e-11, abs = 0) {
  return Number.isFinite(actual) && Math.abs(actual - expected) <= Math.max(abs, rel * Math.max(Math.abs(expected), 1e-300));
}

function differs(actual, expected, rel = 1e-8, abs = 0) {
  return !near(actual, expected, rel, abs);
}

console.log('CASIMIR-LIFSHITZ INDEPENDENT VERIFIER');
console.log('Node', process.version);

// Independent constants. These are entered separately from the page engine.
const PI = Math.PI;
const H = 6.62607015e-34;
const C = 299792458;
const KB = 1.380649e-23;
const EV = 1.602176634e-19;
const G0 = 9.80665;
const HBAR = H / (2 * PI);

function idealPressure(a, constants = { hbar: HBAR, c: C }, exponent = 4, sign = -1, denominator = 240) {
  return sign * PI * PI * constants.hbar * constants.c / (denominator * a ** exponent);
}

function idealEnergy(a) {
  return -PI * PI * HBAR * C / (720 * a ** 3);
}

function cutoffIndependent(lambda, count = 2000, halfZero = true, continuumFactor = 6) {
  let sum = halfZero ? 1 / lambda ** 3 : 2 / lambda ** 3;
  let correction = 0;
  for (let n = 1; n <= count; n += 1) {
    const term = Math.exp(-lambda * n) * (n * n / lambda + 2 * n / lambda ** 2 + 2 / lambda ** 3);
    const y = term - correction;
    const next = sum + y;
    correction = (next - sum) - y;
    sum = next;
  }
  const continuum = continuumFactor / lambda ** 4;
  return { sum, continuum, difference: sum - continuum, ratio: (sum - continuum) / (-1 / 360) };
}

// This Gauss-Legendre constructor mirrors roots explicitly. The page walks all roots.
function gaussLegendreIndependent(n) {
  const x = new Array(n);
  const w = new Array(n);
  const half = Math.ceil(n / 2);
  for (let i = 0; i < half; i += 1) {
    let z = Math.cos(PI * (i + 0.75) / (n + 0.5));
    let previous;
    let derivative = 0;
    do {
      let p0 = 1;
      let p1 = z;
      for (let degree = 2; degree <= n; degree += 1) {
        const p2 = ((2 * degree - 1) * z * p1 - (degree - 1) * p0) / degree;
        p0 = p1;
        p1 = p2;
      }
      const pn = n === 1 ? z : p1;
      const pnm1 = n === 1 ? 1 : p0;
      derivative = n * (z * pn - pnm1) / (z * z - 1);
      previous = z;
      z -= pn / derivative;
    } while (Math.abs(z - previous) > 2e-16);
    const weight = 2 / ((1 - z * z) * derivative * derivative);
    x[i] = -z;
    x[n - 1 - i] = z;
    w[i] = weight;
    w[n - 1 - i] = weight;
  }
  return { x, w };
}

const MATERIALS = {
  vacuum: { osc: [] },
  low: { osc: [[2, 0.15], [0.3, 6]] },
  mid: { osc: [[4, 0.15], [1, 6]] },
  high: { osc: [[7, 0.15], [2, 6]] },
  crossA: { osc: [[8, 0.12], [1, 7]] },
  crossM: { osc: [[10, 0.12], [2.2, 7]] },
  crossB: { osc: [[3, 0.12], [4, 7]] },
  drude: { osc: [[1.5, 4]], drude: [8, 0.035] }
};

function angularFrequency(ev) {
  return ev * EV / HBAR;
}

function epsilonIndependent(model, xi, strengthFactor = 1, resonanceFactor = 1) {
  if (model.drude && xi === 0) return Infinity;
  let result = 1;
  if (model.drude) {
    const wp = angularFrequency(model.drude[0]);
    result += wp * wp / (xi * (xi + angularFrequency(model.drude[1])));
  }
  model.osc.forEach(([strength, ev]) => {
    result += strength * strengthFactor / (1 + (xi / angularFrequency(ev * resonanceFactor)) ** 2);
  });
  return result;
}

function zeroTM(eBody, eMedium) {
  if (!Number.isFinite(eBody)) return 1;
  if (!Number.isFinite(eMedium)) return -1;
  return (eBody - eMedium) / (eBody + eMedium);
}

function reflectionProducts(a, y, xi, e1, em, e2, n, flipSecondTM = false) {
  if (n === 0) {
    const first = zeroTM(e1, em);
    const second = zeroTM(e2, em) * (flipSecondTM ? -1 : 1);
    return { tm: first * second, te: 0 };
  }
  const qm = y / (2 * a);
  const k2 = Math.max(0, qm * qm - em * (xi / C) ** 2);
  const q1 = Math.sqrt(k2 + e1 * (xi / C) ** 2);
  const q2 = Math.sqrt(k2 + e2 * (xi / C) ** 2);
  const r1tm = (e1 * qm - em * q1) / (e1 * qm + em * q1);
  let r2tm = (e2 * qm - em * q2) / (e2 * qm + em * q2);
  if (flipSecondTM) r2tm *= -1;
  const r1te = (qm - q1) / (qm + q1);
  const r2te = (qm - q2) / (qm + q2);
  return { tm: r1tm * r2tm, te: r1te * r2te };
}

function bandIndependent(a, m1, mm, m2, T, n, options = {}) {
  const nodes = options.nodes || gaussLegendreIndependent(options.order || 96);
  const span = options.span || 36;
  const xiFactor = options.xiFactor || 1;
  const xi = 2 * PI * n * KB * T / HBAR * xiFactor;
  const e1 = epsilonIndependent(m1, xi, options.strengthFactor || 1, options.resonanceFactor || 1);
  const em = epsilonIndependent(mm, xi, options.strengthFactor || 1, options.resonanceFactor || 1);
  const e2 = epsilonIndependent(m2, xi, options.strengthFactor || 1, options.resonanceFactor || 1);
  const y0 = n === 0 ? 0 : 2 * a * Math.sqrt(em) * xi / C;
  const upper = y0 + span;
  let integral = 0;
  for (let j = 0; j < nodes.x.length; j += 1) {
    const y = (upper + y0) / 2 + (upper - y0) * nodes.x[j] / 2;
    const r = reflectionProducts(a, y, xi, e1, em, e2, n, options.flipSecondTM);
    const decay = Math.exp(-y);
    const teTerm = options.omitTE ? 0 : r.te * decay / (1 - r.te * decay);
    integral += nodes.w[j] * y * y * (r.tm * decay / (1 - r.tm * decay) + teTerm);
  }
  integral *= (upper - y0) / 2;
  const zeroWeight = options.zeroWeight === undefined ? 0.5 : options.zeroWeight;
  const pressure = -KB * T / (8 * PI * a ** 3) * (n === 0 ? zeroWeight : 1) * integral * (options.weightScale || 1);
  return { n, xi, epsilon: [e1, em, e2], y0, pressure };
}

const GL96 = gaussLegendreIndependent(96);
const GL48I = gaussLegendreIndependent(48);

function pressureIndependent(a, m1, mm, m2, T = 293.15, options = {}) {
  const nMax = options.nMax === undefined ? 160 : options.nMax;
  const bands = [];
  let pressure = 0;
  const shared = { ...options, nodes: options.nodes || GL96 };
  for (let n = 0; n <= nMax; n += 1) {
    const band = bandIndependent(a, m1, mm, m2, T, n, shared);
    bands.push(band);
    pressure += band.pressure;
  }
  return { pressure, bands, tailProxy: Math.abs(bands.at(-1).pressure) / (Math.abs(pressure) || 1) };
}

function logGrid(lo, hi, count) {
  return Array.from({ length: count }, (_, i) => lo * (hi / lo) ** (i / (count - 1)));
}

function findRootsIndependent(m1, mm, m2, T = 293.15, options = {}) {
  const points = logGrid(50e-9, 1000e-9, 41).map(a => ({ a, pressure: pressureIndependent(a, m1, mm, m2, T, options).pressure }));
  const roots = [];
  for (let i = 1; i < points.length; i += 1) {
    if (points[i - 1].pressure * points[i].pressure < 0) {
      let left = points[i - 1].a;
      let right = points[i].a;
      let pl = points[i - 1].pressure;
      let pr = points[i].pressure;
      for (let j = 0; j < 20; j += 1) {
        const mid = (left + right) / 2;
        const pm = pressureIndependent(mid, m1, mm, m2, T, options).pressure;
        if (pl * pm <= 0) {
          right = mid;
          pr = pm;
        } else {
          left = mid;
          pl = pm;
        }
      }
      roots.push({ a: (left + right) / 2, leftPressure: pl, rightPressure: pr, kind: pr < pl ? 'stable' : 'unstable' });
    }
  }
  return { points, roots };
}

console.log('\nIDEAL LAW');
const p100 = idealPressure(100e-9);
const p1000 = idealPressure(1e-6);
const e100 = idealEnergy(100e-9);
check('Planck constant is the exact SI value', H === 6.62607015e-34);
check('speed of light is the exact SI value', C === 299792458);
check('Boltzmann constant is the exact SI value', KB === 1.380649e-23);
check('electronvolt conversion is the exact SI value', EV === 1.602176634e-19);
check('derived hbar matches reference digits', near(HBAR, 1.0545718176461565e-34, 2e-16), sci(HBAR));
check('100 nm ideal pressure is signed and correct', near(p100, -13.001257732443657, 2e-15), `${p100} Pa`);
check('1 micrometre ideal pressure is signed and correct', near(p1000, -0.0013001257732443657, 2e-15), `${p1000} Pa`);
check('decade in distance changes pressure by 10,000', near(p100 / p1000, 10000, 2e-15));
check('halving distance multiplies magnitude by 16', near(Math.abs(idealPressure(200e-9) / idealPressure(400e-9)), 16, 2e-15));
check('ideal energy at 100 nm is correct', near(e100, -4.3337525774812187e-7, 2e-15), `${e100} J/m2`);
check('pressure and energy obey P = 3E/a', near(p100, 3 * e100 / 100e-9, 2e-15));
check('1 cm2 force at 100 nm is correct', near(p100 * 1e-4, -0.0013001257732443658, 2e-15));
check('weight-equivalent uses conventional g0', near(Math.abs(p100 * 1e-4) / G0, 0.00013257593298877455, 2e-15));

console.log('\nREGULATED MODE DIFFERENCE');
const cut1 = cutoffIndependent(0.1);
const cut2 = cutoffIndependent(0.2);
const cutSmall = cutoffIndependent(0.04);
check('Euler-Maclaurin finite coefficient is -1/360', near(-1 / 360, -0.002777777777777778, 2e-16));
check('lambda 0.1 regulated difference', near(cut1.difference, -0.0027738120043068193, 3e-10), `${cut1.difference}`);
check('lambda 0.1 ratio to limit', near(cut1.ratio, 0.9985723215504549, 3e-10));
check('lambda 0.2 regulated difference', near(cut2.difference, -0.0027619443694675283, 3e-10));
check('smaller regulator moves closer to limit', Math.abs(cut1.ratio - 1) < Math.abs(cut2.ratio - 1));
check('lambda 0.04 is within 0.03 percent of limit', Math.abs(cutSmall.ratio - 1) < 3e-4, `${cutSmall.ratio}`);
check('2,000 modes and 1,500 modes agree at lambda 0.1', near(cut1.difference, cutoffIndependent(0.1, 1500).difference, 0, 1e-12));
check('omitting zero half-weight is detectable', differs(cutoffIndependent(0.1, 2000, false).difference, cut1.difference, 1e-4));

console.log('\nQUADRATURE AND RESPONSE');
const sumW = GL96.w.reduce((a, b) => a + b, 0);
const moment = power => GL96.x.reduce((sum, x, i) => sum + GL96.w[i] * x ** power, 0);
check('96-point weights integrate one', near(sumW, 2, 2e-14));
check('96-point nodes integrate x', near(moment(1), 0, 0, 2e-15));
check('96-point nodes integrate x squared', near(moment(2), 2 / 3, 2e-14));
check('96-point nodes integrate x to fourth', near(moment(4), 2 / 5, 2e-14));
check('all quadrature weights are positive', GL96.w.every(w => w > 0));
check('quadrature nodes are mirror symmetric', GL96.x.every((x, i) => near(x, -GL96.x.at(-1 - i), 0, 2e-15)));
check('vacuum epsilon is exactly one', epsilonIndependent(MATERIALS.vacuum, 7e14) === 1);
check('low model static epsilon is 3.3', near(epsilonIndependent(MATERIALS.low, 0), 3.3, 2e-15));
check('high model static epsilon is 10', near(epsilonIndependent(MATERIALS.high, 0), 10, 2e-15));
check('crossing medium static epsilon is 13.2', near(epsilonIndependent(MATERIALS.crossM, 0), 13.2, 2e-15));
check('one oscillator contributes half strength at its resonance', near(epsilonIndependent({ osc: [[4, 0.15]] }, angularFrequency(0.15)), 3, 2e-15));
check('dielectric response approaches one at high xi', epsilonIndependent(MATERIALS.high, angularFrequency(1000)) < 1.001);
check('Drude static response is infinite', epsilonIndependent(MATERIALS.drude, 0) === Infinity);
check('Drude response is finite above zero', Number.isFinite(epsilonIndependent(MATERIALS.drude, angularFrequency(0.1))));

console.log('\nLIFSHITZ BANDS AND PRESSURES');
const xi1 = 2 * PI * KB * 293.15 / HBAR;
check('first Matsubara angular frequency', near(xi1, 241144237618286.2, 2e-15), `${xi1} rad/s`);
check('first Matsubara energy', near(HBAR * xi1 / EV, 0.15872402055016657, 2e-15), `${HBAR * xi1 / EV} eV`);
check('Matsubara energy is linear in temperature', near((2 * PI * KB * 350 / HBAR) / xi1, 350 / 293.15, 2e-15));
check('ordered static dielectrics give negative TM product', zeroTM(10, 6) * zeroTM(3.3, 6) < 0);
check('like static dielectrics give positive TM product', zeroTM(10, 1) * zeroTM(10, 1) > 0);
check('Drude metal against finite medium has TM coefficient one', zeroTM(Infinity, 3) === 1);

const rep100 = pressureIndependent(100e-9, MATERIALS.high, MATERIALS.mid, MATERIALS.low);
const att100 = pressureIndependent(100e-9, MATERIALS.high, MATERIALS.vacuum, MATERIALS.mid);
const cross100 = pressureIndependent(100e-9, MATERIALS.crossA, MATERIALS.crossM, MATERIALS.crossB);
const cross500 = pressureIndependent(500e-9, MATERIALS.crossA, MATERIALS.crossM, MATERIALS.crossB);
check('broadband model is repulsive at 100 nm', rep100.pressure > 0, `${rep100.pressure} Pa`);
check('vacuum model is attractive at 100 nm', att100.pressure < 0, `${att100.pressure} Pa`);
check('crossing model is repulsive at 100 nm', cross100.pressure > 0, `${cross100.pressure} Pa`);
check('crossing model is attractive at 500 nm', cross500.pressure < 0, `${cross500.pressure} Pa`);
check('broadband zero mode is repulsive', rep100.bands[0].pressure > 0);
check('crossing zero mode is attractive', cross100.bands[0].pressure < 0);
check('crossing nonzero bands sum to repulsion at 100 nm', cross100.bands.slice(1).reduce((sum, band) => sum + band.pressure, 0) > 0);
check('swapping the two bodies leaves pressure invariant', near(rep100.pressure, pressureIndependent(100e-9, MATERIALS.low, MATERIALS.mid, MATERIALS.high).pressure, 2e-13));
check('last retained term is small at 500 nm', cross500.tailProxy < 1e-12, `${cross500.tailProxy}`);
const cross500Long = pressureIndependent(500e-9, MATERIALS.crossA, MATERIALS.crossM, MATERIALS.crossB, 293.15, { nMax: 240, span: 44 });
check('longer tail agrees at 500 nm', near(cross500.pressure, cross500Long.pressure, 2e-10), `${cross500.pressure - cross500Long.pressure} Pa`);

console.log('\nEQUILIBRIUM SEARCH');
const independentCurve = findRootsIndependent(MATERIALS.crossA, MATERIALS.crossM, MATERIALS.crossB, 293.15);
check('constructed crossing has exactly one root', independentCurve.roots.length === 1);
const independentRoot = independentCurve.roots[0];
check('root lies between 200 and 500 nm', independentRoot.a > 200e-9 && independentRoot.a < 500e-9, `${independentRoot.a * 1e9} nm`);
check('root bracket has opposite signs', independentRoot.leftPressure * independentRoot.rightPressure <= 0);
check('root is stable under the page convention', independentRoot.kind === 'stable');
check('stable root has repulsion on smaller-gap side', independentRoot.leftPressure > 0);
check('stable root has attraction on larger-gap side', independentRoot.rightPressure < 0);
check('20 bisections narrow even the widest grid bracket below 100 femtometres', Math.abs(independentRoot.rightPressure - independentRoot.leftPressure) > 0 && 1000e-9 * (1 - (50 / 1000) ** (1 / 40)) / 2 ** 20 < 1e-13);

console.log('\nSOURCE RECORD');
const SOURCE = {
  munday: { rangeNm: [20, 300], dataSets: 50, lowForcePn: 10, year: 2009 },
  svetovoy: { wavelengthUm: [0.14, 33], plasmaEv: [6.8, 8.4], forceReductionPercent: [5, 14], distanceNm: 100, year: 2008 }
};
check('Munday plotted range transcription', html.includes('data-source="munday.range">20 to 300 nm</span>'));
check('Munday data-set count transcription', html.includes('data-source="munday.sets">50 data sets</span>'));
check('Munday low-force statement transcription', html.includes('data-source="munday.limit">10 pN</span>'));
check('Svetovoy wavelength range transcription', html.includes('data-source="svetovoy.range">0.14 to 33 micrometres</span>'));
check('Svetovoy plasma range transcription', html.includes('data-source="svetovoy.plasma">6.8 to 8.4 eV</span>'));
check('Svetovoy force range transcription', html.includes('data-source="svetovoy.force">5 to 14 percent</span>'));
check('source record keeps the comparison distance at 100 nm', SOURCE.svetovoy.distanceNm === 100 && html.includes('than a customary handbook-response prediction'));
check('Munday source record year is 2009', SOURCE.munday.year === 2009 && html.includes('<em>Nature</em> 457 (2009)'));
check('Svetovoy source record year is 2008', SOURCE.svetovoy.year === 2008 && html.includes('<em>Physical Review B</em> 77 (2008)'));

console.log('\nPAGE-COUPLING');
const engineMatch = html.match(/<script data-engine="casimir">([\s\S]*?)<\/script>/);
check('shipped page contains one extractable engine script', Boolean(engineMatch));
let pageEngine;
if (engineMatch) {
  const context = vm.createContext({ console });
  vm.runInContext(engineMatch[1], context, { filename: 'casimir-page-engine.js' });
  pageEngine = context.CasimirEngine;
}
check('shipped engine exports its API', Boolean(pageEngine && pageEngine.pressure && pageEngine.curve));

if (pageEngine) {
  const pageModels = keyList => keyList.map(k => pageEngine.cloneModel(pageEngine.MATERIALS[k], 1, 1));
  const pageRep = pageModels(pageEngine.PRESETS.repel);
  const pageAtt = pageModels(pageEngine.PRESETS.attract);
  const pageCross = pageModels(pageEngine.PRESETS.cross);
  check('page ideal pressure matches independent 100 nm result', near(pageEngine.idealPressure(100e-9), p100, 2e-15));
  check('page ideal energy matches independent 100 nm result', near(pageEngine.idealEnergy(100e-9), e100, 2e-15));
  check('page force and mass state match independent result', near(pageEngine.idealState(100e-9, 1e-4).massEquivalent, Math.abs(p100 * 1e-4) / G0, 2e-15));
  check('page cutoff sum matches independent result', near(pageEngine.cutoff(0.1, 2000).sum, cut1.sum, 2e-15));
  check('page cutoff difference matches independent result', near(pageEngine.cutoff(0.1, 2000).difference, cut1.difference, 0, 2e-11));
  const pageGL = pageEngine.gaussLegendre(48);
  check('page quadrature weights sum to two', near(Array.from(pageGL.w).reduce((a, b) => a + b, 0), 2, 2e-14));
  check('page vacuum epsilon matches independent result', pageEngine.epsilon(pageEngine.MATERIALS.vacuum, xi1) === 1);
  check('page high static epsilon matches independent result', near(pageEngine.epsilon(pageEngine.MATERIALS.high, 0), epsilonIndependent(MATERIALS.high, 0), 2e-15));
  check('page Drude zero response matches independent result', pageEngine.epsilon(pageEngine.MATERIALS.drude, 0) === Infinity);
  const pageXi1 = pageEngine.bandPressure(100e-9, pageCross[0], pageCross[1], pageCross[2], 293.15, 1).xi;
  check('page first Matsubara frequency matches independent result', near(pageXi1, xi1, 2e-15));
  const pageRep100 = pageEngine.pressure(100e-9, pageRep[0], pageRep[1], pageRep[2], 293.15, 160);
  const pageAtt100 = pageEngine.pressure(100e-9, pageAtt[0], pageAtt[1], pageAtt[2], 293.15, 160);
  const pageCross100 = pageEngine.pressure(100e-9, pageCross[0], pageCross[1], pageCross[2], 293.15, 160);
  const pageCross500 = pageEngine.pressure(500e-9, pageCross[0], pageCross[1], pageCross[2], 293.15, 160);
  check('page repulsive pressure matches independent higher-order quadrature', near(pageRep100.pressure, rep100.pressure, 1e-8), `${pageRep100.pressure - rep100.pressure} Pa`);
  check('page attractive pressure matches independent higher-order quadrature', near(pageAtt100.pressure, att100.pressure, 1e-8), `${pageAtt100.pressure - att100.pressure} Pa`);
  check('page crossing pressure at 100 nm matches independent higher-order quadrature', near(pageCross100.pressure, cross100.pressure, 1e-8));
  check('page crossing pressure at 500 nm matches independent higher-order quadrature', near(pageCross500.pressure, cross500.pressure, 1e-8));
  check('page zero-band sign matches independent result', Math.sign(pageCross100.bands[0].pressure) === Math.sign(cross100.bands[0].pressure));
  check('page first-band value matches independent higher-order quadrature', near(pageCross100.bands[1].pressure, cross100.bands[1].pressure, 1e-8, 1e-10), `${pageCross100.bands[1].pressure - cross100.bands[1].pressure} Pa`);
  const pageCurve = pageEngine.curve(pageCross[0], pageCross[1], pageCross[2], 293.15);
  check('page curve finds the same number of roots', pageCurve.roots.length === independentCurve.roots.length);
  check('page root agrees with independent root within 0.02 nm', near(pageCurve.roots[0].a, independentRoot.a, 0, 0.02e-9), `${pageCurve.roots[0].a * 1e9} vs ${independentRoot.a * 1e9} nm`);
  check('page root classification matches independent result', pageCurve.roots[0].kind === independentRoot.kind);
  check('page source count matches separate record', pageEngine.SOURCE_RECORD.munday.dataSets === SOURCE.munday.dataSets);
  check('page source plasma span matches separate record', JSON.stringify(Array.from(pageEngine.SOURCE_RECORD.svetovoy.plasmaEv)) === JSON.stringify(SOURCE.svetovoy.plasmaEv));
}

check('page ends with load-bearing closing tags', /<\/script>\s*<\/body>\s*<\/html>\s*$/.test(html));
check('page contains no remote script request', !/<script[^>]+src=["']https?:/i.test(html));
check('page contains no remote stylesheet request', !/<link[^>]+href=["']https?:[^"']+["'][^>]*rel=["']stylesheet/i.test(html) && !/<link[^>]+rel=["']stylesheet["'][^>]+href=["']https?:/i.test(html));
check('page has no literal em dash', !html.includes(String.fromCodePoint(0x2014)));
check('page exposes reduced-motion handling', html.includes('prefers-reduced-motion:reduce') && html.includes('prefers-reduced-motion: reduce'));

console.log('\nMUTATION SWEEP');
let mutationsAttempted = 0;
let mutationsCaught = 0;
function mutation(name, condition, detail = '') {
  mutationsAttempted += 1;
  if (condition) {
    mutationsCaught += 1;
    check(`mutation caught: ${name}`, true, detail);
  } else {
    check(`mutation escaped: ${name}`, false, detail);
  }
}

mutation('Planck constant increased by one percent', differs(idealPressure(100e-9, { hbar: HBAR * 1.01, c: C }), p100, 1e-6));
mutation('speed of light reduced by one percent', differs(idealPressure(100e-9, { hbar: HBAR, c: C * 0.99 }), p100, 1e-6));
mutation('distance exponent changed from four to three', differs(idealPressure(100e-9, undefined, 3), p100, 1e-6));
mutation('pressure sign flipped', idealPressure(100e-9, undefined, 4, 1) > 0);
mutation('ideal denominator changed from 240 to 239', differs(idealPressure(100e-9, undefined, 4, -1, 239), p100, 1e-6));
mutation('zero mode lost its half weight in cutoff sum', differs(cutoffIndependent(0.1, 2000, false).difference, cut1.difference, 1e-6));
mutation('continuum integral coefficient changed', differs(cutoffIndependent(0.1, 2000, true, 5).difference, cut1.difference, 1e-6));
mutation('oscillator strength increased', differs(epsilonIndependent(MATERIALS.high, xi1, 1.02), epsilonIndependent(MATERIALS.high, xi1), 1e-5));
mutation('oscillator resonance shifted', differs(epsilonIndependent(MATERIALS.high, xi1, 1, 1.03), epsilonIndependent(MATERIALS.high, xi1), 1e-5));
const badXi = bandIndependent(100e-9, MATERIALS.crossA, MATERIALS.crossM, MATERIALS.crossB, 293.15, 1, { xiFactor: 1 / (2 * PI), nodes: GL48I });
mutation('Matsubara frequency lost its 2 pi', differs(badXi.pressure, cross100.bands[1].pressure, 1e-4));
const badZero = pressureIndependent(500e-9, MATERIALS.crossA, MATERIALS.crossM, MATERIALS.crossB, 293.15, { zeroWeight: 1 });
mutation('zero Matsubara term given full weight', differs(badZero.pressure, cross500.pressure, 1e-4));
const flipped = pressureIndependent(100e-9, MATERIALS.high, MATERIALS.mid, MATERIALS.low, 293.15, { flipSecondTM: true });
mutation('second TM reflection orientation flipped', Math.sign(flipped.pressure) !== Math.sign(rep100.pressure));
const noTE = pressureIndependent(100e-9, MATERIALS.high, MATERIALS.mid, MATERIALS.low, 293.15, { omitTE: true });
mutation('all nonzero TE bands omitted', differs(noTE.pressure, rep100.pressure, 1e-4));
const badWeights = pressureIndependent(100e-9, MATERIALS.high, MATERIALS.mid, MATERIALS.low, 293.15, { weightScale: 1.01 });
mutation('quadrature weights scaled by one percent', differs(badWeights.pressure, rep100.pressure, 1e-5));
const shortIntegral = pressureIndependent(100e-9, MATERIALS.high, MATERIALS.mid, MATERIALS.low, 293.15, { span: 5 });
mutation('dimensionless integral stopped at five', differs(shortIntegral.pressure, rep100.pressure, 1e-4));
const shortSum = pressureIndependent(100e-9, MATERIALS.high, MATERIALS.mid, MATERIALS.low, 293.15, { nMax: 20 });
mutation('Matsubara sum stopped at index twenty', differs(shortSum.pressure, rep100.pressure, 1e-4));
mutation('stable root relabeled unstable', independentRoot.kind !== 'unstable');

console.log(`\nMUTATIONS CAUGHT ${mutationsCaught}/${mutationsAttempted}`);
check('mutation sweep caught every attempted fault', mutationsCaught === mutationsAttempted);
check('verifier contains at least 40 independent assertions', assertions >= 40, `${assertions} assertions executed`);

console.log(`\nRESULT ${passed} passed, ${failed} failed, ${assertions} total assertions`);
if (failed > 0) process.exitCode = 1;

function sci(value) {
  return Number(value).toExponential(12);
}
