#!/usr/bin/env node
// Offline checker for /strata/map-projection-ranking/.
//
//   node research/map-projection-ranking/verify-map-projection-ranking.mjs
//
// Three halves, in this order.
//  1. Independent recomputation.  Closed forms by tanh-sinh quadrature and by
//     hand-reduced series, Table 1 re-parsed from the shipped verbatim excerpt,
//     the composites re-added, and a Monte Carlo written with a different
//     generator and a different derivative stencil from the page's.
//  2. Execution of the shipped page engine, extracted from index.html, with
//     every published quantity compared against half one.
//  3. Mutation tests that corrupt inputs and coefficients on purpose and
//     assert the checks go red.
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/map-projection-ranking/index.html');
const mdPath = path.join(root, 'src/content/strata/map-projection-ranking.md');
const dataDir = path.join(here, 'data');
const html = fs.readFileSync(pagePath, 'utf8');

let checks = 0;
let failures = 0;
let quiet = false;

function report(ok, label, detail = '') {
  checks += 1;
  if (!ok) failures += 1;
  if (!quiet) {
    console.log(`${ok ? 'PASS' : 'FAIL'} ${String(checks).padStart(3, '0')}  ${label}${detail ? `  ${detail}` : ''}`);
  }
  return ok;
}
function truth(v, label, detail = '') { return report(Boolean(v), label, detail); }
function equal(a, b, label) { return report(Object.is(a, b), label, `actual=${a} expected=${b}`); }
function close(a, b, tol, label) {
  const ok = Number.isFinite(a) && Number.isFinite(b) && Math.abs(a - b) <= tol;
  return report(ok, label, `actual=${a} expected=${b} tol=${tol}`);
}

// =========================================================== half one =====
const PI = Math.PI;

// tanh-sinh (double exponential) quadrature.  A different scheme from the
// page's graded Gauss-Legendre, and one that eats the endpoint log singularity.
// The abscissa complement 1 - tanh(u) is formed directly so that a node one
// part in 10^300 from the endpoint still lands there, which is what lets the
// logarithmic singularity at the pole be integrated at all.
function tanhSinh(f, a, b, h = 1 / 1024, tMax = 4.2) {
  const d = (b - a) / 2;
  let total = 0;
  for (let i = -Math.round(tMax / h); i <= Math.round(tMax / h); i += 1) {
    const t = i * h;
    const u = (PI / 2) * Math.sinh(t);
    const ch = Math.cosh(u);
    if (!Number.isFinite(ch) || ch > 1e150) continue;
    const w = (PI / 2) * Math.cosh(t) / (ch * ch);
    if (!Number.isFinite(w) || w === 0) continue;
    // 1 - tanh(|u|) without cancellation
    const e = Math.exp(-2 * Math.abs(u));
    const gap = (2 * e) / (1 + e);
    const point = u >= 0 ? b - d * gap : a + d * gap;
    const value = f(point);
    if (Number.isFinite(value)) total += w * value;
  }
  return total * h * d;
}

// Uniform-area expectation of an even function of latitude.
function expectation(g) {
  return tanhSinh((phi) => g(phi) * Math.cos(phi), 0, PI / 2);
}

const indepMeanLogCos = expectation((phi) => -Math.log(Math.cos(phi)));
const indepSecondLogCos = expectation((phi) => Math.pow(Math.log(Math.cos(phi)), 2));
const indepTanMean = expectation((phi) => Math.tan(phi));

// Hand-reduced closed forms, written out again here.
const closedMean = 1 - Math.LN2;
const closedSecond = 2 - 2 * Math.LN2 + Math.LN2 * Math.LN2 - (PI * PI) / 12;
const closedEqcI = Math.sqrt(closedSecond);
const closedEqcA = Math.sqrt(1 - (PI * PI) / 12);
const closedMercFS = 2 / PI;

close(indepMeanLogCos, closedMean, 1e-12, 'E[-ln cos phi] by tanh-sinh equals 1 - ln 2');
close(indepSecondLogCos, closedSecond, 1e-11, 'E[(ln cos phi)^2] by tanh-sinh equals 2 - 2ln2 + ln^2 2 - pi^2/12');
close(Math.sqrt(indepSecondLogCos - indepMeanLogCos ** 2), closedEqcA, 1e-11,
  'equirectangular A equals sqrt(1 - pi^2/12)');
close(indepTanMean, 1, 1e-12, 'E[|tan phi|] over uniform area equals 1');
close(indepTanMean * (2 / PI), closedMercFS, 1e-12, 'Mercator F = S = 2/pi');

// The identity that makes the printed pair inconsistent, checked pointwise.
{
  let worst = 0;
  for (let i = 1; i < 400; i += 1) {
    const phi = (PI / 2) * (i / 400);
    const eqc = Math.log(1 / Math.cos(phi));
    const merc = Math.log(1 / (Math.cos(phi) * Math.cos(phi)));
    worst = Math.max(worst, Math.abs(merc - 2 * eqc));
  }
  close(worst, 0, 1e-14, 'ln(ab) for Mercator is exactly twice ln(ab) for equirectangular, pointwise');
}

// ---- Table 1, re-parsed from the shipped verbatim excerpt, independently ----
const verbatim = fs.readFileSync(path.join(dataDir, 'table1-verbatim.txt'), 'utf8');
function reparseTable() {
  const out = [];
  for (const raw of verbatim.split('\n')) {
    const line = raw.trim();
    if (!line || /^Projection\s/.test(line) || /^Table 1/.test(line)) continue;
    const parts = line.split(/\s+/);
    const nums = [];
    while (parts.length && /^-?\d+(\.\d+)?$/.test(parts[parts.length - 1]) && nums.length < 6) {
      nums.unshift(parts.pop());
    }
    if (nums.length !== 6 || !parts.length) continue;
    out.push({ projection: parts.join(' '), printed: nums, values: nums.map(Number) });
  }
  return out;
}
const indepTable = reparseTable();
equal(indepTable.length, 27, 'Table 1 re-parses to 27 rows');

const rankedVerbatim = fs.readFileSync(path.join(dataDir, 'ranked-list-verbatim.txt'), 'utf8');
const indepRanked = rankedVerbatim.split('\n')
  .map((l) => l.match(/^\s*(\d+)\.\s+(.*)\s+\(([0-9.]+)\)\s*$/))
  .filter(Boolean)
  .map((m) => ({ rank: Number(m[1]), projection: m[2].trim(), printed: m[3], value: Number(m[3]) }));
equal(indepRanked.length, 6, 'the ranked list re-parses to 6 entries');

const N_PRINTED = [0.51, 0.41, 0.64, 0.60, 0.449, 0.25];
function sigma(values, normalizers, weights) {
  let total = 0;
  for (let i = 0; i < 6; i += 1) {
    const w = weights ? weights[i] : 1;
    if (!w) continue;
    const r = values[i] / normalizers[i];
    total += w * r * r;
  }
  return total;
}
const indepByName = Object.create(null);
indepTable.forEach((r) => { indepByName[r.projection] = r; });

const readd = indepRanked.map((r) => {
  const key = r.projection === 'Winkel-Tripel (Times Atlas)' ? 'Winkel-Tripel (Times)' : r.projection;
  const row = indepByName[key];
  return { name: key, diff: sigma(row.values, N_PRINTED, null) - r.value };
});
const reproduced = readd.filter((r) => Math.abs(r.diff) < 5e-5);
equal(reproduced.length, 4, 'four of the six published composites re-add from the printed components');
const failedNames = readd.filter((r) => Math.abs(r.diff) >= 5e-5).map((r) => r.name).sort();
equal(failedNames.join(' | '), 'Kavrayskiy VII | Winkel-Tripel (Times)',
  'the two that do not re-add are Kavrayskiy VII and the Times Atlas Winkel Tripel');
close(readd.find((r) => r.name === 'Winkel-Tripel').diff, 0, 5e-5,
  'the headline 4.5629 re-adds from its own printed components');

// The printed area cells cannot both be roundings of one pair.
{
  const eqc = Number(indepByName.Equirectangular.printed[1]);
  const merc = Number(indepByName.Mercator.printed[1]);
  const lo = 2 * (eqc - 0.005);
  const hi = 2 * (eqc + 0.005);
  truth(hi <= merc - 0.005 || lo >= merc + 0.005,
    'twice the printed equirectangular A cannot round to the printed Mercator A',
    `[${lo.toFixed(4)}, ${hi.toFixed(4)}) vs [${(merc - 0.005).toFixed(4)}, ${(merc + 0.005).toFixed(4)})`);
  equal(Number(closedEqcA.toFixed(2)), 0.42, 'the exact equirectangular A rounds to 0.42, not the printed 0.41');
  equal(Number((2 * closedEqcA).toFixed(2)), merc, 'the exact Mercator A rounds to the printed value');
  equal(Number(closedMercFS.toFixed(2)), Number(indepByName.Mercator.printed[2]),
    'the exact Mercator F rounds to the printed value');
}

// ---- independent Monte Carlo: different generator, different stencil ------
function lcg(seed) {
  let s = BigInt(seed) & 0xffffffffffffffffn;
  return function next() {
    s = (s * 6364136223846793005n + 1442695040888963407n) & 0xffffffffffffffffn;
    return Number(s >> 11n) / 9007199254740992;
  };
}
const INDEP_MAPS = {
  eqc: (l, p) => [l, p],
  // ln tan(pi/4 + phi/2) rather than the page's asinh(tan phi)
  merc: (l, p) => [l, Math.log(Math.tan(PI / 4 + p / 2))],
  // Mollweide by bisection rather than by Newton
  moll: (l, p) => {
    const target = PI * Math.sin(p);
    let lo = -PI / 2;
    let hi = PI / 2;
    for (let i = 0; i < 60; i += 1) {
      const mid = (lo + hi) / 2;
      if (2 * mid + Math.sin(2 * mid) < target) lo = mid; else hi = mid;
    }
    const t = (lo + hi) / 2;
    return [(2 * Math.SQRT2 / PI) * l * Math.cos(t), Math.SQRT2 * Math.sin(t)];
  },
  wintri: (l, p) => {
    const a = Math.acos(Math.max(-1, Math.min(1, Math.cos(p) * Math.cos(l / 2))));
    const k = a === 0 ? 1 : a / Math.sin(a);
    return [(2 * Math.cos(p) * Math.sin(l / 2) * k + l * (2 / PI)) / 2, (Math.sin(p) * k + p) / 2];
  }
};
function indepMeasure(key, n, shrink, seed, h = 1e-5) {
  const fn = INDEP_MAPS[key];
  const rand = lcg(seed);
  let s2 = 0; let a1 = 0; let a2 = 0; let fs = 0; let sk = 0; let used = 0;
  const at = (lam, phi) => fn(lam, phi);
  for (let i = 0; i < n; i += 1) {
    let lam = -PI + 2 * PI * rand();
    let phi = Math.asin(2 * rand() - 1);
    lam *= shrink; phi *= shrink;
    const az = 2 * PI * rand();
    const cp = Math.cos(phi); const sp = Math.sin(phi);
    const cl = Math.cos(lam); const sl = Math.sin(lam);
    const P = [cp * cl, cp * sl, sp];
    const Nn = [-sp * cl, -sp * sl, cp];
    const Ee = [-sl, cl, 0];
    const move = (t, tau) => {
      const ct = Math.cos(tau); const st = Math.sin(tau);
      const q = [P[0] * ct + t[0] * st, P[1] * ct + t[1] * st, P[2] * ct + t[2] * st];
      const raw = Math.atan2(q[1], q[0]);
      const L = lam + Math.atan2(Math.sin(raw - lam), Math.cos(raw - lam));
      return at(L, Math.asin(Math.max(-1, Math.min(1, q[2]))));
    };
    const np = move(Nn, h); const nm = move(Nn, -h);
    const ep = move(Ee, h); const em = move(Ee, -h);
    const jn = [(np[0] - nm[0]) / (2 * h), (np[1] - nm[1]) / (2 * h)];
    const je = [(ep[0] - em[0]) / (2 * h), (ep[1] - em[1]) / (2 * h)];
    const aa = jn[0] ** 2 + jn[1] ** 2;
    const bb = je[0] ** 2 + je[1] ** 2;
    const ab = jn[0] * je[0] + jn[1] * je[1];
    const disc = Math.sqrt(Math.max(0, (aa - bb) ** 2 + 4 * ab * ab));
    const major = Math.sqrt(Math.max(0, (aa + bb + disc) / 2));
    const minor = Math.sqrt(Math.max(0, (aa + bb - disc) / 2));
    const dir = [Nn[0] * Math.cos(az) + Ee[0] * Math.sin(az),
      Nn[1] * Math.cos(az) + Ee[1] * Math.sin(az),
      Nn[2] * Math.cos(az) + Ee[2] * Math.sin(az)];
    // second-order stencil, deliberately different from the page's fourth order
    const m1 = move(dir, -h); const p1 = move(dir, h); const mid = at(lam, phi);
    const vx = (p1[0] - m1[0]) / (2 * h); const vy = (p1[1] - m1[1]) / (2 * h);
    const ax = (p1[0] - 2 * mid[0] + m1[0]) / (h * h);
    const ay = (p1[1] - 2 * mid[1] + m1[1]) / (h * h);
    const v2 = vx * vx + vy * vy;
    const lr = Math.log(major / minor);
    const la = Math.log(major * minor);
    const fl = (vx * ay - vy * ax) / v2;
    const skw = (vx * ax + vy * ay) / v2;
    if (![lr, la, fl, skw].every(Number.isFinite)) continue;
    s2 += lr * lr; a1 += la; a2 += la * la; fs += Math.abs(fl); sk += Math.abs(skw); used += 1;
  }
  const meanA = a1 / used;
  return {
    I: Math.sqrt(s2 / used),
    A: Math.sqrt(Math.max(0, a2 / used - meanA * meanA)),
    F: fs / used,
    S: sk / used,
    used
  };
}

const indepEqc = indepMeasure('eqc', 120000, 1, 20260801);
close(indepEqc.I, closedEqcI, 0.006, 'independent Monte Carlo reaches the exact equirectangular I');
close(indepEqc.A, closedEqcA, 0.006, 'independent Monte Carlo reaches the exact equirectangular A');
const indepMerc = indepMeasure('merc', 120000, 1, 20260801);
close(indepMerc.I, 0, 1e-6, 'independent Monte Carlo gives Mercator I = 0');
close(indepMerc.A, 2 * closedEqcA, 0.012, 'independent Monte Carlo reaches the exact Mercator A');
close(indepMerc.A / indepEqc.A, 2, 1e-6,
  'the measured Mercator to equirectangular area ratio is two to the accuracy of the stencil');
close(indepMerc.F, closedMercFS, 0.03, 'independent Monte Carlo reaches 2/pi for Mercator flexion');

// ---- committed records ---------------------------------------------------
const scores = JSON.parse(fs.readFileSync(path.join(dataDir, 'scores.json'), 'utf8'));
const elig = JSON.parse(fs.readFileSync(path.join(dataDir, 'proj-eligibility.json'), 'utf8'));
const screen = JSON.parse(fs.readFileSync(path.join(dataDir, 'stencil-screen.json'), 'utf8'));
const jsProj = JSON.parse(fs.readFileSync(path.join(dataDir, 'js-vs-proj.json'), 'utf8'));

equal(elig.meta.operations, elig.ledger.length, 'the eligibility ledger covers every operation in the build');
truth(jsProj.meta.max_abs_deviation < 1e-11,
  'every browser forward map agrees with PROJ to better than 1e-11',
  `worst ${jsProj.meta.max_abs_deviation.toExponential(2)} on ${jsProj.meta.worst_map}`);
const sensitive = Object.keys(screen.screen).filter((k) => !screen.screen[k].smooth).sort();
equal(sensitive.join(','), 'eck1,eck2,robin,vandg',
  'the stencil screen flags exactly the four non-smooth implementations');
sensitive.forEach((k) => {
  truth(!(k in scores.literal), `${k} is excluded from the scored set`);
});
truth(Object.keys(scores.literal).length >= 60, 'at least sixty configurations were scored',
  `${Object.keys(scores.literal).length} scored`);
// B is constant, so its weight cannot reorder anything.  Assert the claim.
truth(Object.values(scores.literal).every((r) => r.B === 0.25),
  'every scored row carries B = 0.25, which is why the page calls that column vacuous for ranking');

// The offline PROJ pipeline and the exact closed forms must agree.
close(scores.literal.eqc.I, closedEqcI, 0.004, 'the offline PROJ run reaches the exact equirectangular I');
close(scores.literal.eqc.A, closedEqcA, 0.004, 'the offline PROJ run reaches the exact equirectangular A');
close(scores.literal.merc.A, 2 * closedEqcA, 0.008, 'the offline PROJ run reaches the exact Mercator A');
close(scores.literal.merc.I, 0, 1e-5, 'the offline PROJ run gives Mercator I = 0');

// The Winkel Tripel distance is the number that does not come back.
{
  const printedD = Object.fromEntries(indepTable.map((r) => [r.projection, r.values[4]]));
  const pairs = [
    ['eqc', 'Equirectangular'], ['gall', 'Gall Stereographic'], ['kav7', 'Kavrayskiy VII'],
    ['sinu', 'Sinusoidal'], ['moll', 'Mollweide'], ['hammer', 'Hammer'], ['cea@45', 'Gall-Peters'],
    ['eck4', 'Eckert IV'], ['eck6', 'Eckert VI'], ['mill', 'Miller'], ['merc', 'Mercator']
  ];
  const gaps = pairs.map(([k, n]) => Math.abs(scores.literal[k].D - printedD[n]));
  const worstOther = Math.max(...gaps);
  const wintriGap = Math.abs(scores.literal.wintri.D - printedD['Winkel-Tripel']);
  truth(worstOther < 0.005, 'every other printed distance comes back within 0.005',
    `worst ${worstOther.toFixed(5)}`);
  truth(wintriGap > 2 * worstOther, 'the Winkel Tripel distance gap dwarfs the rest',
    `wintri ${wintriGap.toFixed(5)} vs worst other ${worstOther.toFixed(5)}`);
}

// =========================================================== half two =====
function extractScript(id) {
  const m = html.match(new RegExp(`<script[^>]*id="${id}"[^>]*>([\\s\\S]*?)</script>`));
  if (!m) throw new Error(`no script with id ${id}`);
  return m[1];
}
const engineSource = extractScript('mpr-engine');
const uiSource = extractScript('mpr-ui');
truth(engineSource.trim().length > 3000, 'the page ships an inline engine', `${engineSource.length} bytes`);
truth(uiSource.trim().length > 3000, 'the page ships an inline interface script', `${uiSource.length} bytes`);
truth(/<\/script>\s*<\/body>\s*<\/html>\s*$/.test(html), 'the document closes script, body and html');

function loadEngine(source = engineSource) {
  const sandbox = { console, Math, Number, JSON, Object, Array, isFinite, BigInt };
  sandbox.globalThis = sandbox;
  vm.createContext(sandbox);
  vm.runInContext(source, sandbox, { filename: 'mpr-engine' });
  return sandbox.MPR;
}
const PAGE = loadEngine();
truth(PAGE && PAGE.MAPS && PAGE.analytic, 'the page engine loads and exports its interface');

// Every quantity the page prints, compared with half one.
{
  const a1 = PAGE.analytic(1);
  close(a1.eqcI, closedEqcI, 1e-12, 'page engine quadrature matches the closed-form equirectangular I');
  close(a1.eqcA, closedEqcA, 1e-12, 'page engine quadrature matches the closed-form equirectangular A');
  close(a1.mercA, 2 * closedEqcA, 1e-12, 'page engine quadrature matches the closed-form Mercator A');
  close(a1.mercFS, closedMercFS, 1e-12, 'page engine quadrature matches 2/pi');
  close(a1.eqcMeanLogArea, closedMean, 1e-12, 'page engine mean log area matches 1 - ln 2');
  equal(a1.boundary, 0.25, 'page engine boundary term is one quarter');

  const a2 = PAGE.analytic(0.995);
  close(a2.eqcI, tanhSinh((p) => Math.pow(Math.log(Math.cos(0.995 * p)), 2) * Math.cos(p), 0, PI / 2) ** 0.5,
    1e-10, 'page engine reproduces the contracted equirectangular I under independent quadrature');
  equal(Number(a2.eqcI.toFixed(2)), 0.51, 'the contracted equirectangular I rounds to the printed 0.51');
  equal(Number(a2.eqcA.toFixed(2)), 0.41, 'the contracted equirectangular A rounds to the printed 0.41');
  truth(Number(a2.mercA.toFixed(2)) !== 0.84, 'the contracted Mercator A does not round to the printed 0.84',
    `${a2.mercA.toFixed(4)}`);
  truth(Number(a2.mercFS.toFixed(2)) !== 0.64, 'the contracted Mercator F does not round to the printed 0.64',
    `${a2.mercFS.toFixed(4)}`);
}

// No contraction factor reproduces all four printed cells at once.
{
  let best = 0;
  for (let i = 0; i <= 150; i += 1) {
    const k = 0.97 + (0.03 * i) / 150;
    const a = PAGE.analytic(k);
    let hit = 0;
    if (Number(a.eqcI.toFixed(2)) === 0.51) hit += 1;
    if (Number(a.eqcA.toFixed(2)) === 0.41) hit += 1;
    if (Number(a.mercA.toFixed(2)) === 0.84) hit += 1;
    if (Number(a.mercFS.toFixed(2)) === 0.64) hit += 1;
    best = Math.max(best, hit);
  }
  equal(best, 2, 'no contraction factor in [0.97, 1] reproduces more than two of the four exact cells');
}

// Page engine Monte Carlo against the independent one and against PROJ.
{
  const pageEqc = PAGE.measureLocal('eqc', 120000, 1, 20260801);
  close(pageEqc.I, closedEqcI, 0.006, 'page engine Monte Carlo reaches the exact equirectangular I');
  close(pageEqc.A, closedEqcA, 0.006, 'page engine Monte Carlo reaches the exact equirectangular A');
  const pageMerc = PAGE.measureLocal('merc', 120000, 1, 20260801);
  close(pageMerc.A / pageEqc.A, 2, 1e-6, 'the page engine also gives the factor of two');
  close(pageMerc.F, closedMercFS, 0.03, 'page engine reaches 2/pi for Mercator flexion');

  ['eqc', 'merc', 'moll', 'wintri'].forEach((key) => {
    const mine = indepMeasure(key, 120000, 0.995, 314159);
    const theirs = PAGE.measureLocal(key, 120000, 0.995, 271828);
    close(theirs.I, mine.I, 0.02, `page and independent engines agree on I for ${key}`);
    close(theirs.A, mine.A, 0.02, `page and independent engines agree on A for ${key}`);
    close(theirs.F, mine.F, 0.05, `page and independent engines agree on F for ${key}`);
    close(theirs.S, mine.S, 0.06, `page and independent engines agree on S for ${key}`);
  });

  // and against the offline PROJ-driven run
  ['eqc', 'merc', 'moll', 'wintri', 'kav7', 'gall', 'sinu', 'hammer', 'eck4', 'mill'].forEach((key) => {
    const theirs = PAGE.measureLocal(key, 150000, 0.995, 90210);
    const ref = scores.shrink[key];
    close(theirs.I, ref.I, 0.02, `page engine agrees with the offline PROJ run on I for ${key}`);
    close(theirs.A, ref.A, 0.02, `page engine agrees with the offline PROJ run on A for ${key}`);
    close(theirs.F, ref.F, 0.05, `page engine agrees with the offline PROJ run on F for ${key}`);
  });
  const pageD = PAGE.measureDistance('wintri', 400000, 1, 4242);
  close(pageD.D, scores.literal.wintri.D, 0.004,
    'page engine distance for the Winkel Tripel agrees with the offline run');
  truth(Math.abs(pageD.D - 0.374) > 0.005,
    'and it still does not reach the printed 0.374', `${pageD.D.toFixed(5)}`);
}

// The shipped data islands must equal the committed records.
function island(id) {
  const m = html.match(new RegExp(`<script[^>]*id="${id}"[^>]*>([\\s\\S]*?)</script>`));
  return JSON.parse(m[1]);
}
const shippedTable = island('data-table1');
const shippedLedger = island('data-ledger');
const shippedElig = island('data-eligibility');
equal(shippedTable.table1.length, indepTable.length, 'the shipped Table 1 has the re-parsed row count');
truth(shippedTable.table1.every((r, i) => r.projection === indepTable[i].projection
  && r.printed.join(' ') === indepTable[i].printed.join(' ')),
'every shipped Table 1 row equals the independently re-parsed row');
equal(shippedLedger.rows.length, Object.keys(scores.literal).length,
  'the shipped ledger has one row per scored configuration');
truth(shippedLedger.rows.every((row) => {
  const ref = scores.shrink[row.k];
  return Math.abs(row.shr[0] - ref.I) < 5e-7 && Math.abs(row.shr[4] - ref.D) < 5e-7;
}), 'every shipped ledger row matches the committed measurement file');
equal(shippedElig.ledger.length, elig.ledger.length, 'the shipped eligibility ledger is complete');
truth(shippedElig.ledger.filter((r) => r.stage === 'E').length === sensitive.length,
  'the shipped ledger records the stencil-screen exclusions at stage E');

// Ranking machinery, recomputed here and compared with the page engine.
{
  const rows = shippedLedger.rows.map((r) => ({ key: r.k, name: r.n, values: r.shr, errors: r.shre }));
  const weights = [1, 1, 1, 1, 1, 1];
  const mine = rows.map((r) => ({ key: r.key, score: sigma(r.values, N_PRINTED, weights) }))
    .sort((a, b) => a.score - b.score);
  const theirs = PAGE.rank(rows, N_PRINTED, weights);
  equal(theirs[0].key, mine[0].key, 'page engine and independent ranking agree on the leader');
  close(theirs[0].score, mine[0].score, 1e-12, 'and on the leading score');
  truth(theirs.every((row, i) => row.key === mine[i].key), 'the whole ordering agrees');

  // B is constant, so any weight on it shifts every score by the same amount.
  const heavyB = PAGE.rank(rows, N_PRINTED, [1, 1, 1, 1, 1, 9]);
  truth(heavyB.every((row, i) => row.key === theirs[i].key),
    'changing the boundary weight leaves the ordering untouched, as the page states');
  const shapeOnly = PAGE.rank(rows, N_PRINTED, [1, 0, 1, 0, 0, 0]);
  truth(shapeOnly[0].key !== theirs[0].key || shapeOnly[1].key !== theirs[1].key,
    'changing a weight that is not vacuous does move the ordering');

  const frontier = PAGE.paretoFrontier(rows, [true, true, true, true, true, false]);
  const undominated = frontier.filter((f) => !f.dominated).length;
  truth(undominated >= 1 && undominated < rows.length,
    'the Pareto frontier is a proper non-empty subset', `${undominated} of ${rows.length}`);
  truth(frontier.find((f) => f.key === theirs[0].key).dominated === false,
    'the composite leader is undominated, which it must be for a positive weighting');
}

// Head tags and the entry, with the date read from the record rather than typed.
const md = fs.readFileSync(mdPath, 'utf8');
const fm = md.split('---')[1];
const mdDate = (fm.match(/^date:\s*(\S+)/m) || [])[1];
truth(Boolean(mdDate), 'the entry declares a date');
truth(html.includes(`"datePublished":"${mdDate}"`), 'the page JSON-LD datePublished matches the entry date', mdDate);
truth(html.includes(`"dateModified":"${mdDate}"`), 'the page JSON-LD dateModified matches the entry date');
truth(/seam:\s*"groundtruth"/.test(fm), 'the entry is filed under the groundtruth seam');
truth(/draft:\s*false/.test(fm), 'the entry is not a draft');
{
  const slugs = [...fm.matchAll(/^\s+- to:\s*(\S+)/gm)].map((m) => m[1]);
  truth(slugs.length >= 2 && slugs.length <= 4, 'the entry declares two to four related slugs', slugs.join(', '));
  slugs.forEach((slug) => {
    truth(fs.existsSync(path.join(root, 'src/content/strata', `${slug}.md`)), `related slug ${slug} exists`);
  });
}
truth(!/—/.test(html.replace(/<script type="application\/json"[\s\S]*?<\/script>/g, '')),
  'the page prose carries no em dash');
truth(!/—/.test(md), 'the entry carries no em dash');
truth(html.includes('rel="canonical" href="https://artwaste.land/strata/map-projection-ranking/"'),
  'the page declares its canonical URL');
truth(!/https?:\/\/(?!artwaste\.land|arxiv\.org|doi\.org|www\.physics\.drexel\.edu|proj\.org|schema\.org)[^"']+/.test(
  html.replace(/<script type="application\/json"[\s\S]*?<\/script>/g, '').replace(/<script id="mpr-[\s\S]*?<\/script>/g, '')
), 'the page makes no third-party request');

// =========================================================== half three ===
function expectRed(label, fn) {
  const before = { checks, failures };
  quiet = true;
  let threw = false;
  try { fn(); } catch (e) { threw = true; }
  quiet = false;
  const newFailures = failures - before.failures;
  const wentRed = threw || newFailures > 0;
  checks = before.checks;
  failures = before.failures;
  report(wentRed, `mutation: ${label}`, wentRed ? 'check went red as required' : 'check stayed green, which is a defect');
}

expectRed('corrupting the printed normalizers breaks the composite re-add', () => {
  const bad = N_PRINTED.slice();
  bad[1] = 0.42;
  const d = sigma(indepByName['Winkel-Tripel'].values, bad, null) - 4.5629;
  close(d, 0, 5e-5, 'inner');
});
expectRed('corrupting a printed Table 1 cell breaks the pointwise doubling verdict', () => {
  const merc = 0.82;
  const eqc = Number(indepByName.Equirectangular.printed[1]);
  truth(2 * (eqc + 0.005) <= merc - 0.005 || 2 * (eqc - 0.005) >= merc + 0.005, 'inner');
});
expectRed('a single quadrature panel misses the closed form', () => {
  const source = engineSource.replace('QUAD_PANELS: 48', 'QUAD_PANELS: 1');
  const bad = loadEngine(source);
  close(bad.analytic(1).eqcA, closedEqcA, 1e-12, 'inner');
});
expectRed('replacing the Mercator ordinate breaks the exact factor of two', () => {
  const source = engineSource.replace('Math.asinh(Math.tan(p))', 'Math.tan(p)');
  const bad = loadEngine(source);
  const e = bad.measureLocal('eqc', 40000, 1, 7);
  const m = bad.measureLocal('merc', 40000, 1, 7);
  close(m.A / e.A, 2, 1e-9, 'inner');
});
expectRed('sampling latitude uniformly instead of by area breaks the exact anchors', () => {
  const source = engineSource.replace('var phi = Math.asin(2 * rand() - 1);', 'var phi = PI * (rand() - 0.5);');
  const bad = loadEngine(source);
  const e = bad.measureLocal('eqc', 60000, 1, 11);
  close(e.I, closedEqcI, 0.02, 'inner');
});
expectRed('halving the velocity stencil denominator inflates the flexion', () => {
  const source = engineSource.replace(/\(12 \* h\)/g, '(6 * h)');
  const bad = loadEngine(source);
  const m = bad.measureLocal('merc', 40000, 1, 11);
  close(m.F, closedMercFS, 0.05, 'inner');
});
expectRed('replacing the equirectangular ordinate breaks its closed form', () => {
  const source = engineSource.replace('fn: function (l, p) { return [l, p]; }', 'fn: function (l, p) { return [l, Math.sin(p)]; }');
  const bad = loadEngine(source);
  const e = bad.measureLocal('eqc', 40000, 1, 11);
  close(e.A, closedEqcA, 0.02, 'inner');
});
expectRed('dropping the mean removal from the distance error changes it', () => {
  const source = engineSource.replace(
    'return { D: Math.sqrt(Math.max(0, sq / used - mean * mean)), meanLog: mean, used: used };',
    'return { D: Math.sqrt(Math.max(0, sq / used)), meanLog: mean, used: used };'
  );
  const bad = loadEngine(source);
  close(bad.measureDistance('eqc', 60000, 1, 3).D, scores.literal.eqc.D, 0.01, 'inner');
});
expectRed('corrupting a ledger row is caught by the data island comparison', () => {
  const rows = JSON.parse(JSON.stringify(shippedLedger.rows));
  rows[0].shr[0] += 0.01;
  truth(rows.every((row) => Math.abs(row.shr[0] - scores.shrink[row.k].I) < 5e-7), 'inner');
});
expectRed('a wrong publication date is caught', () => {
  truth(html.includes('"datePublished":"1999-01-01"'), 'inner');
});
expectRed('claiming a stencil-sensitive projection was scored is caught', () => {
  truth(!('robin' in scores.literal) && 'vandg' in scores.literal, 'inner');
});

console.log(`\n${checks - failures} of ${checks} checks passed`);
if (failures) {
  console.error(`${failures} FAILED`);
  process.exit(1);
}
process.exit(0);
