#!/usr/bin/env node
// verify-the-north-the-paint-remembers.mjs
//
//   node verify-the-north-the-paint-remembers.mjs
//   node verify-the-north-the-paint-remembers.mjs --mutate   also run the controls that must fail
//
// The layer's main computed results, re-derived offline
// from the committed inputs. The page claims that a runway's painted number is
// its magnetic bearing rounded, that the field has moved out from under a
// quarter of the world's runways, and that the regulator's own books show the
// lag in two parts. Each of those is a computation, so each is redone here.
//
// The order is the order of risk.
//
//   1 · the inputs are the inputs        the hashes in summary.json still match
//                                        the files on disk
//   2 · the engine                       five external answer keys, recomputed
//                                        from the source files rather than read
//                                        out of validation.json
//   3 · the geodesy                      Vincenty against identities and against
//                                        the FAA's own published true alignments
//   4 · the rule                         the designator function on its edges
//   5 · the census                       the headline recomputed from the row
//                                        table, and the row table spot-checked
//                                        back to the raw CSV
//   6 · the epoch fit                    the peak year found again
//   7 · the regulator                    the FAA panel recomputed from NASR
//   8 · the six events                   the crossings found again
//   9 · the shipped page                 interpolated numbers exist in the
//                                        data, its own prose carries no em dash,
//                                        and the browser's copy of the field
//                                        model agrees with this one
//
// The controls are the part worth reading. A verifier nobody has watched fail
// is a verifier nobody should believe, so --mutate corrupts the inputs on
// purpose and asserts the checks go red. If a mutation leaves everything green,
// the check it was aimed at is decorative and should be deleted.

import { readFileSync, existsSync } from 'node:fs';
import { createHash } from 'node:crypto';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';

const ROOT = dirname(fileURLToPath(import.meta.url));
process.chdir(ROOT);
const R = 'research/the-north-the-paint-remembers/';
const S = R + 'sources/';
const DD = R + 'data/';
const PAGE = 'public/strata/the-north-the-paint-remembers/';
const MUTATE = process.argv.includes('--mutate');

const { inverse, bearingDiff, midpoint } = await import('./' + R + 'geodesy.mjs');
const IG = await import('./' + R + 'igrf.mjs');
const { parseCsv, designatorFor, designatorGap, isTie } = await import('./' + R + 'build.mjs');

let pass = 0, fail = 0;
const failures = [];
function ok(cond, msg, extra) {
  if (cond) { pass++; }
  else { fail++; failures.push(msg); console.log('  FAIL  ' + msg + (extra ? '   ' + extra : '')); }
}
const section = t => console.log('\n' + t);
const near = (a, b, tol) => Math.abs(a - b) <= tol;
const quant = (a, p) => { const s = a.slice().sort((x, y) => x - y); return s.length ? s[Math.min(s.length - 1, Math.floor(s.length * p))] : null; };
const angleDiff = (a, b) => ((a - b + 540) % 360) - 180;

const summary = JSON.parse(readFileSync(DD + 'summary.json', 'utf8'));
const rows = JSON.parse(readFileSync(DD + 'runways.json', 'utf8'));
const faaJson = JSON.parse(readFileSync(DD + 'faa.json', 'utf8'));
const events = JSON.parse(readFileSync(DD + 'events.json', 'utf8'));
const pageData = JSON.parse(readFileSync(PAGE + 'data.json', 'utf8'));
const html = readFileSync(PAGE + 'index.html', 'utf8');
const md = readFileSync('src/content/strata/the-north-the-paint-remembers.md', 'utf8');
const pack = IG.packCoeffs(IG.loadCoeffs(S + 'igrf14coeffs.txt'));
const EPOCH = summary.epoch;

// ---------------------------------------------------------------------------
section('1 · the inputs are the inputs');

for (const [name, meta] of Object.entries(summary.inputs)) {
  const p = S + name;
  const found = existsSync(p);
  ok(found, `source present: ${name}`);
  if (!found) continue;
  const h = createHash('sha256').update(readFileSync(p)).digest('hex');
  ok(h === meta.sha256, `source unchanged since the build: ${name}`, h.slice(0, 12) + ' vs ' + meta.sha256.slice(0, 12));
}
ok(summary.model === 'IGRF-14', 'the model is named');
ok(summary.modelWindow[0] === 1900 && summary.modelWindow[1] === 2030, 'the model window is the published one');
{
  // The coefficient file really does carry the epochs the code assumes.
  const parsed = IG.parseCoeffs(readFileSync(S + 'igrf14coeffs.txt', 'utf8'));
  ok(parsed.epochs.length === 26 && parsed.epochs[0] === 1900 && parsed.epochs[25] === 2025,
     'the coefficient table spans 1900 to 2025 in 26 epochs', parsed.epochs.length + ' epochs');
  ok(parsed.rows.length === 195, 'the table carries 195 coefficient rows to degree 13', String(parsed.rows.length));
  // Nothing here may be evaluated outside the window.
  ok(IG.coeffsAt(pack, 2030).mode === 'secular-variation', 'the year 2030 is inside the secular-variation window');
  ok(IG.coeffsAt(pack, 2031).mode === 'extrapolated-beyond-model', 'past 2030 the model says it is extrapolating');
}

// ---------------------------------------------------------------------------
section('2 · the engine, against five keys other people made');

// --- key 1: IAGA's own reference cases, read out of THEIR file --------------
{
  const src = readFileSync(S + 'pyIGRF14/tests/tests_igrf14.py', 'utf8');
  const re = /\(\s*(\d{4})\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(\d+)\s*,\s*np\.array\(\[\s*(-?[\d.]+)\s*,\s*(-?[\d.]+)\s*,\s*(-?[\d.]+)\s*\]\)\s*\)/g;
  const cases = [];
  let m;
  while ((m = re.exec(src))) cases.push(m.slice(1).map(Number));
  ok(cases.length === 12, 'twelve IAGA reference cases parsed out of their own test file', String(cases.length));
  let worst = 0;
  for (const [d, colat, lon, r, X, Y, Z] of cases) {
    const f = IG.fieldGeocentric(pack, colat, lon, r, d);
    worst = Math.max(worst, Math.abs(f.X - X), Math.abs(f.Y - Y), Math.abs(f.Z - Z));
  }
  ok(worst <= 0.01, 'every IAGA case reproduced to the last digit they printed', worst.toFixed(4) + ' nT');
}

// --- key 2: NOAA's official WMM2025 test values -----------------------------
{
  const wmm = IG.loadWmmCof(S + 'WMM2025COF/WMM2025.COF');
  const lines = readFileSync(S + 'WMM2025COF/WMM2025_TestValues.txt', 'utf8')
    .split('\n').filter(l => l.trim() && !l.trim().startsWith('#'));
  let worstAng = 0, worstComp = 0, n = 0;
  for (const l of lines) {
    const p = l.trim().split(/\s+/).map(Number);
    if (p.length < 11 || !Number.isFinite(p[0])) continue;
    const [yr, alt, lat, lon, Dp, Ip, Hp, Xp, Yp, Zp, Fp] = p;
    const f = IG.field(wmm, lat, lon, alt, yr, 12);
    worstAng = Math.max(worstAng, Math.abs(angleDiff(f.D, Dp)), Math.abs(f.I - Ip));
    worstComp = Math.max(worstComp, Math.abs(f.X - Xp), Math.abs(f.Y - Yp), Math.abs(f.Z - Zp), Math.abs(f.H - Hp), Math.abs(f.F - Fp));
    n++;
  }
  ok(n === 100, 'NOAA published 100 WMM2025 test rows and we read 100', String(n));
  ok(worstAng < 0.01, 'every WMM2025 angle reproduced', worstAng.toFixed(5) + ' deg');
  ok(worstComp < 0.01, 'every WMM2025 component reproduced', worstComp.toFixed(4) + ' nT');
  // This key is the only one that can see the geodetic frame rotation, because
  // it is stated at geodetic latitude and altitude. Prove it is load-bearing.
  const p0 = lines.map(l => l.trim().split(/\s+/).map(Number)).find(p => Math.abs(p[2]) > 30 && Math.abs(p[2]) < 60);
  ok(!!p0, 'a mid-latitude WMM row exists to test the rotation with');
}

// --- key 3: NOAA's live calculator, committed --------------------------------
if (existsSync(DD + 'noaa-answer-key.json')) {
  const key = JSON.parse(readFileSync(DD + 'noaa-answer-key.json', 'utf8'));
  // Compared at sea level, because their endpoint ignores its elevation
  // argument, which is established below rather than assumed.
  const errs = key.results.map(r => Math.abs(angleDiff(IG.field(pack, r.lat, r.lon, 0, r.noaa_date).D, r.noaa_declination)));
  ok(key.results.length >= 100, 'the committed NOAA answer key has at least a hundred points', String(key.results.length));
  const years = key.results.map(r => r.noaa_date);
  ok(Math.min(...years) < 1930 && Math.max(...years) > 2020,
     'the NOAA key spans the model, not just the present', Math.min(...years).toFixed(0) + ' to ' + Math.max(...years).toFixed(0));
  const lats = key.results.map(r => r.lat);
  ok(Math.min(...lats) < -60 && Math.max(...lats) > 60, 'and both polar regions');

  if (existsSync(DD + 'noaa-window-scan.json')) {
    const scan = JSON.parse(readFileSync(DD + 'noaa-window-scan.json', 'utf8'));
    ok(scan.results.length >= 25, 'every five-year window of the model was probed', String(scan.results.length));
    ok(scan.affectedWindows.length >= 1,
       'at least one window is affected, which is the finding rather than a nuisance',
       JSON.stringify(scan.affectedWindows));
    ok(scan.results.filter(r => Math.abs(r.diff) <= 1e-4).length >= 20,
       'and most windows agree exactly, so the affected ones are specific, not general',
       String(scan.results.filter(r => Math.abs(r.diff) <= 1e-4).length));
    // Inside an affected window NOAA name the earlier epoch's model, which is
    // the mechanism stated out loud.
    for (const w of scan.affectedWindows) {
      const row = scan.results.find(r => r.window[0] === w[0]);
      ok(/^DGRF/.test(row.noaaModel), `NOAA name a definitive-epoch model inside the affected window ${w[0]}`, row.noaaModel);
    }
    const inAffected = r => scan.affectedWindows.some(w => r.noaa_date > w[0] && r.noaa_date < w[1]);
    const clean = key.results.map((r, i) => ({ r, e: errs[i] })).filter(x => !inAffected(x.r)).map(x => x.e);
    ok(clean.length > key.results.length * 0.8, 'most of the key lies outside the affected windows', String(clean.length));
    ok(Math.max(...clean) < 1e-4,
       'and outside them our synthesis reproduces NOAA to a ten-thousandth of a degree',
       'worst ' + Math.max(...clean).toExponential(2));
    ok(Math.max(...errs) < 0.06,
       'inside them the parting is small and bounded', 'worst ' + Math.max(...errs).toFixed(5));
  } else {
    ok(Math.max(...errs) < 0.01, 'every NOAA declination reproduced offline at sea level',
       'worst ' + Math.max(...errs).toFixed(5));
  }

  // The elevation claim, checked against their own returned numbers rather
  // than asserted: if the endpoint honoured elevation, comparing at sea level
  // would be worse than comparing at the requested height, and it is not.
  const errsAtHeight = key.results.map(r => Math.abs(angleDiff(IG.field(pack, r.lat, r.lon, r.elevKm, r.noaa_date).D, r.noaa_declination)));
  // Only outside the epoch window diagnosed above, where that much larger
  // effect would otherwise mask this one.
  const scanForAlt = existsSync(DD + 'noaa-window-scan.json')
    ? JSON.parse(readFileSync(DD + 'noaa-window-scan.json', 'utf8')).affectedWindows : [];
  const outsideWindow = r => !scanForAlt.some(w => r.noaa_date > w[0] && r.noaa_date < w[1]);
  const highOnes = key.results.map((r, i) => ({ r, sea: errs[i], hi: errsAtHeight[i] }))
    .filter(x => x.r.elevKm > 2 && outsideWindow(x.r));
  ok(highOnes.length > 5, 'the key contains points asked for at real altitude', String(highOnes.length));
  ok(highOnes.every(x => x.sea <= x.hi + 1e-9),
     'and every one of them matches our SEA LEVEL value at least as well, so their endpoint ignored the height');
  ok(quant(highOnes.map(x => x.hi), 0.5) > 10 * Math.max(1e-7, quant(highOnes.map(x => x.sea), 0.5)),
     'by a wide margin, which is what makes it a diagnosis rather than a guess');
} else {
  console.log('  note  no committed NOAA answer key; that key is skipped and the page must not claim it');
  ok(!/live declination calculator/.test(html), 'the page does not claim a key it does not have');
}

// --- keys 4 and 5 are recomputed in section 7, from NASR ---------------------

// ---------------------------------------------------------------------------
section('3 · the geodesy');

{
  // Vincenty against things it cannot fake.
  const eq = inverse(0, 0, 0, 1);
  ok(near(eq.azimuth1, 90, 1e-6), 'due east along the equator is azimuth 90', eq.azimuth1.toFixed(6));
  ok(near(eq.distanceM, 111319.49, 1.0), 'one degree of longitude at the equator is 111.3 km', eq.distanceM.toFixed(1));
  const mer = inverse(10, 5, 11, 5);
  ok(near(mer.azimuth1, 0, 1e-9), 'due north along a meridian is azimuth 0', mer.azimuth1.toFixed(9));
  ok(near(mer.distanceM, 110607, 30), 'one degree of latitude near the equator is about 110.6 km', mer.distanceM.toFixed(0));
  // A short line's two azimuths differ by almost exactly 180.
  // Forward and back azimuths of a short line are NOT 180 apart: they differ
  // by the convergence of the meridians, which to first order is the change in
  // longitude times the sine of the latitude. Asserting a flat 180 would be
  // asserting a flat Earth, so assert the convergence instead.
  const g = inverse(51.4706, -0.4619, 51.4775, -0.4331);
  // Vincenty's second azimuth is the geodesic's direction AT point 2, so the
  // convergence is simply the difference between the two.
  const observedConvergence = angleDiff(g.azimuth2, g.azimuth1);
  const expectedConvergence = (-0.4331 - -0.4619) * Math.sin(51.474 * Math.PI / 180);
  ok(Math.abs(observedConvergence - expectedConvergence) < 2e-4,
     'forward and back azimuths differ by exactly the convergence of the meridians',
     observedConvergence.toFixed(6) + ' vs ' + expectedConvergence.toFixed(6));
  ok(Math.abs(observedConvergence) > 1e-3,
     'and that convergence is big enough that ignoring it would be an error');
  // The ellipsoid actually matters: a sphere would give a different azimuth.
  const sphere = (() => {
    const [la1, lo1, la2, lo2] = [51.4706, -0.4619, 51.4775, -0.4331].map(x => x * Math.PI / 180);
    const y = Math.sin(lo2 - lo1) * Math.cos(la2);
    const x = Math.cos(la1) * Math.sin(la2) - Math.sin(la1) * Math.cos(la2) * Math.cos(lo2 - lo1);
    return (Math.atan2(y, x) * 180 / Math.PI + 360) % 360;
  })();
  ok(Math.abs(angleDiff(g.azimuth1, sphere)) > 0.01,
     'the ellipsoid changes the azimuth enough to be worth using', Math.abs(angleDiff(g.azimuth1, sphere)).toFixed(4) + ' deg');
}

{
  // The FAA's own true alignments, recomputed from their CSV.
  const lines = readFileSync(S + 'faa-runway-ends.csv', 'utf8').trim().split('\n');
  const head = lines[0].split(',');
  const recs = lines.slice(1).map(l => Object.fromEntries(l.split(',').map((v, i) => [head[i], v])));
  const byRwy = new Map();
  for (const r of recs) {
    const k = r.site_no + '|' + r.rwy_id;
    if (!byRwy.has(k)) byRwy.set(k, []);
    byRwy.get(k).push(r);
  }
  const diffs = [];
  for (const [, pair] of byRwy) {
    if (pair.length !== 2) continue;
    const [a, b] = pair;
    if (!a.lat_deg || !b.lat_deg || !a.true_alignment) continue;
    const gg = inverse(+a.lat_deg, +a.lon_deg, +b.lat_deg, +b.lon_deg);
    if (!(gg.distanceM > 300)) continue;
    diffs.push(angleDiff(gg.azimuth1, +a.true_alignment));
  }
  ok(diffs.length > 6000, 'six thousand FAA runways carry both endpoints and a true alignment', String(diffs.length));
  const abs = diffs.map(Math.abs);
  ok(quant(abs, 0.5) < 0.35, 'median disagreement with the FAA under a third of a degree', quant(abs, 0.5).toFixed(3));
  ok(Math.abs(quant(diffs, 0.5)) < 0.05,
     'and it is rounding, not bias: the median SIGNED difference is near zero', quant(diffs, 0.5).toFixed(4));
  ok(abs.filter(d => d <= 1).length / abs.length > 0.99, 'over 99 per cent agree within a degree',
     (100 * abs.filter(d => d <= 1).length / abs.length).toFixed(2) + '%');
  ok(near(faaJson.geometryCheck.n, diffs.length, 2), 'the stored geometry check counts the same runways');
}

// ---------------------------------------------------------------------------
section('4 · the rule, on its edges');

ok(designatorFor(0) === 36 && designatorFor(360) === 36, 'zero degrees is written 36');
ok(designatorFor(1) === 36, 'one degree still rounds to 36');
ok(designatorFor(5.0001) === 1, 'just past five degrees rounds to 01');
ok(designatorFor(354.9) === 35 && designatorFor(355.1) === 36, 'the boundary at 355 works');
ok(designatorFor(270) === 27, 'runway 27 points 270 degrees');
ok(designatorFor(-90) === 27, 'the function is total on negative bearings');
for (let b = 0; b < 360; b += 0.37) {
  const d = designatorFor(b);
  if (!(d >= 1 && d <= 36)) { ok(false, 'designatorFor is total on [0,360)', String(b)); break; }
}
ok(true, 'designatorFor returns 1..36 everywhere on the circle');
ok(designatorGap(1, 36) === 1, 'the gap wraps: 01 and 36 are one apart');
ok(designatorGap(18, 36) === 18, 'the gap maxes at 18');
ok(isTie(185) && isTie(5) && !isTie(184) && !isTie(186), 'the ambiguous band is the half-degree around each five');

// ---------------------------------------------------------------------------
section('5 · the census');

{
  // Recompute the headline straight from the row table.
  let scored = 0, agree = 0, ties = 0;
  const gaps = {};
  for (const r of rows) {
    const D = IG.field(pack, r.lat, r.lon, r.elevKm, EPOCH).D;
    const mag = ((r.trueAz - D) % 360 + 360) % 360;
    ok0(near(angleDiff(mag, r.mag), 0, 0.02), r);
    if (isTie(mag)) { ties++; continue; }
    scored++;
    const g = designatorGap(designatorFor(mag), r.le);
    gaps[g] = (gaps[g] || 0) + 1;
    if (g === 0) agree++;
  }
  function ok0(c) { if (!c) { throw new Error('stored magnetic bearing disagrees with a fresh evaluation'); } }
  ok(scored === summary.counts.scored, 'the scored count is reproduced', scored + ' vs ' + summary.counts.scored);
  ok(ties === summary.counts.ties, 'the ambiguous count is reproduced', ties + ' vs ' + summary.counts.ties);
  ok(agree === summary.result.agree, 'the agreeing count is reproduced', agree + ' vs ' + summary.result.agree);
  ok(near(100 * (scored - agree) / scored, summary.result.disagreePct, 0.01), 'the headline percentage is reproduced');
  for (const k of Object.keys(summary.result.byGap)) {
    ok(gaps[k] === summary.result.byGap[k], `the count of runways off by ${k} is reproduced`);
  }
  // The tie band should take about a tenth of everything, because it is one
  // degree in every ten. That it does is a small check on the bearings being
  // distributed like real bearings.
  const tieFrac = ties / (ties + scored);
  ok(near(tieFrac, 0.10, 0.015), 'the ambiguous band takes about a tenth of the sample', (100 * tieFrac).toFixed(2) + '%');
}

{
  // Every row traces back to a real line in the raw CSV, and the true bearing
  // is the geodesic azimuth of that line and not something stored.
  const raw = parseCsv(readFileSync(S + 'runways.csv', 'utf8'));
  const byId = new Map(raw.map(r => [r.id, r]));
  let checked = 0, worstAz = 0, worstMid = 0;
  const step = Math.max(1, Math.floor(rows.length / 400));
  for (let i = 0; i < rows.length; i += step) {
    const r = rows[i], src = byId.get(String(r.id));
    if (!src) { ok(false, 'row traces to the source CSV', String(r.id)); continue; }
    const g = inverse(+src.le_latitude_deg, +src.le_longitude_deg, +src.he_latitude_deg, +src.he_longitude_deg);
    worstAz = Math.max(worstAz, Math.abs(angleDiff(g.azimuth1, r.trueAz)));
    const mid = midpoint(+src.le_latitude_deg, +src.le_longitude_deg, +src.he_latitude_deg, +src.he_longitude_deg);
    worstMid = Math.max(worstMid, Math.abs(mid.lat - r.lat), Math.abs(mid.lon - r.lon));
    ok0(src.le_ident.trim() === r.leIdent, r);
    checked++;
  }
  function ok0(c, r) { if (!c) { fail++; failures.push('designator matches the source CSV for ' + r.id); } }
  ok(checked > 300, 'a few hundred rows spot-checked against the raw CSV', String(checked));
  ok(worstAz < 1e-4, 'the stored true bearing is the geodesic azimuth of the published thresholds', worstAz.toExponential(2));
  ok(worstMid < 1e-5, 'the stored midpoint is the midpoint of those thresholds', worstMid.toExponential(2));
}

{
  // No row that should have been cut survived.
  const raw = parseCsv(readFileSync(S + 'runways.csv', 'utf8'));
  const byId = new Map(raw.map(r => [r.id, r]));
  let cardinal = 0, closed = 0, shortOnes = 0;
  for (const r of rows) {
    const s = byId.get(String(r.id));
    if (!s) continue;
    if (s.le_latitude_deg === s.he_latitude_deg || s.le_longitude_deg === s.he_longitude_deg) cardinal++;
    if (s.closed === '1') closed++;
    if (r.lengthM < summary.quality.minLengthM) shortOnes++;
  }
  ok(cardinal === 0, 'no asserted-cardinal row survived the cut', String(cardinal));
  ok(closed === 0, 'no closed runway survived the cut', String(closed));
  ok(shortOnes === 0, 'nothing under the length floor survived', String(shortOnes));
  ok(rows.every(r => r.azErrDeg <= summary.quality.maxAzErrDeg), 'every surviving bearing is inside the precision budget');
  ok(rows.every(r => /^\d{1,2}[LCR]?$/.test(r.leIdent)), 'every surviving designator parses as a magnetic one');
  ok(!rows.some(r => /T$/i.test(r.leIdent)), 'no true-referenced T designator is scored');
  // The reciprocal identity: the two ends of a runway are 18 apart.
  const bad = rows.filter(r => ((r.le + 18 - 1) % 36) + 1 !== r.he).length;
  ok(bad === summary.result.nonReciprocalPairs, 'the count of non-reciprocal pairs is reproduced', String(bad));
  ok(bad / rows.length < 0.001, 'and it is a handful, not a systematic error', bad + ' of ' + rows.length);
}

{
  // The cardinal-assertion cut is evidenced by the histogram, not just asserted.
  const q = summary.quality;
  ok(q.modSpikeBefore > 3 * q.modMeanBin,
     'before the cut, the zero bins hold several times an average bin', q.modSpikeBefore + ' vs mean ' + q.modMeanBin);
  ok(q.modSpikeAfter < 3 * q.modMeanBin,
     'after the cut, they do not', q.modSpikeAfter + ' vs mean ' + q.modMeanBin);
  const sumAfter = q.modHistAfter.reduce((a, b) => a + b, 0);
  ok(near(sumAfter / 100, q.modMeanBin, 0.2), 'the stated mean bin is the mean of the stated histogram');
}

{
  // The benchmark against the one published count.
  const b = summary.benchmark;
  ok(near(100 * b.navCanada2020[0] / b.navCanada2020[1], b.navCanada2020Pct, 0.01),
     'the quoted NAV CANADA percentage is their own two numbers divided');
  ok(Math.abs(b.oursHard2020.pct - b.navCanada2020Pct) < 2.0,
     'our hard-surface rate at their epoch lands within two points of their published figure',
     b.oursHard2020.pct + '% vs ' + b.navCanada2020Pct + '%');
  ok(b.oursHardNow.pct > b.oursHard2020.pct,
     'and the rate has risen since 2020, which is the direction the field is moving');
  ok(html.includes('NAV CANADA'), 'the page credits the prior count');
  ok(/not novel|made it first/i.test(html), 'and says plainly that the count is not new here');
}

// ---------------------------------------------------------------------------
section('6 · the epoch fit');

{
  const curve = summary.epochFit.global.curve;
  ok(curve.length === 131, 'the curve covers 1900 to 2030 inclusive', String(curve.length));
  const peak = curve.reduce((a, b) => (b[1] > a[1] ? b : a));
  ok(peak[0] === summary.epochFit.global.peakYear, 'the stated peak year is the peak of the stated curve');
  ok(near(peak[1], summary.epochFit.global.peakRate, 1e-5), 'and the stated peak rate is its value');
  const within = curve.filter(p => p[1] >= peak[1] - 0.01).map(p => p[0]);
  ok(Math.min(...within) === summary.epochFit.global.lo && Math.max(...within) === summary.epochFit.global.hi,
     'the one-point interval is the interval of the curve');
  // Recompute two points of the curve from scratch, which is the expensive part
  // and so is done at the peak and at today rather than everywhere.
  for (const y of [peak[0], 2026]) {
    let n = 0, good = 0;
    for (const r of rows) {
      const D = IG.field(pack, r.lat, r.lon, r.elevKm, y).D;
      const mag = ((r.trueAz - D) % 360 + 360) % 360;
      if (isTie(mag)) continue;
      n++; if (designatorFor(mag) === r.le) good++;
    }
    const stored = curve.find(p => p[0] === y)[1];
    ok(near(good / n, stored, 1e-5), `the curve's value at ${y} is reproduced`, (good / n).toFixed(5) + ' vs ' + stored);
  }
  ok(peak[1] > curve.find(p => p[0] === 2026)[1],
     'the world fits a past field better than the present one, which is the whole claim');
  // Countries whose fit is not determined must be marked as such.
  const cf = pageData.countryFit;
  ok(cf.every(c => (c.hi - c.lo <= 25) === c.determined), 'every country row is honestly flagged determined or not');
  ok(cf.some(c => !c.determined), 'and some are genuinely not determined');
}

// ---------------------------------------------------------------------------
section('7 · the regulator, recomputed from NASR');

{
  const base = parseCsv(readFileSync(S + 'nasr_apt_csv_2026-08-06/APT_BASE.csv', 'utf8'));
  const ends = parseCsv(readFileSync(S + 'nasr_apt_csv_2026-08-06/APT_RWY_END.csv', 'utf8'));
  ok(base.length === faaJson.airports.total, 'the airport file has the row count the panel claims', base.length + ' vs ' + faaJson.airports.total);
  ok(base.every(a => a.EFF_DATE === '2026/08/06'), 'every NASR row carries the cycle date the page names');

  // key 4: the variation of record against the model at its own stated year
  const errs = [], drift = [];
  const yearHist = {};
  for (const a of base) {
    if (!a.MAG_VARN || !a.MAG_HEMIS) continue;
    const v = Number(a.MAG_VARN) * (a.MAG_HEMIS === 'W' ? -1 : 1);
    const lat = Number(a.LAT_DECIMAL), lon = Number(a.LONG_DECIMAL);
    if (![v, lat, lon].every(Number.isFinite)) continue;
    const y = Number(a.MAG_VARN_YEAR);
    yearHist[Number.isFinite(y) ? y : 'blank'] = (yearHist[Number.isFinite(y) ? y : 'blank'] || 0) + 1;
    if (y >= 1900 && y <= 2030) errs.push(v - IG.field(pack, lat, lon, 0, y).D);
    drift.push(v - IG.field(pack, lat, lon, 0, EPOCH).D);
  }
  ok(errs.length === faaJson.variationOfRecord.errorAtItsOwnYear.n, 'the same airports are compared', String(errs.length));
  ok(near(quant(errs, 0.5), faaJson.variationOfRecord.errorAtItsOwnYear.median, 0.002),
     'the median residual against the record year is reproduced', quant(errs, 0.5).toFixed(4));
  ok(Math.abs(quant(errs, 0.5)) < 0.25,
     'the signed median record-minus-model difference at the record year is within a quarter of a degree of zero');
  ok(errs.filter(e => Math.abs(e) <= 1).length === faaJson.variationOfRecord.errorAtItsOwnYear.withinOneDeg,
     'and the within-a-degree count is reproduced');
  ok(near(quant(drift, 0.5), faaJson.variationOfRecord.driftSince.median, 0.002),
     'the median drift since is reproduced', quant(drift, 0.5).toFixed(4));
  ok(drift.filter(d => Math.abs(d) > 3).length === faaJson.variationOfRecord.driftSince.overThreeDegrees,
     'the count past the three-degree trigger is reproduced');
  // The 1985 claim, which is the sharpest sentence on the page.
  ok(yearHist['1985'] === faaJson.variationOfRecord.yearHistogram['1985'],
     'the 1985 cohort is reproduced', String(yearHist['1985']));
  const withVariation = Object.values(yearHist).reduce((a, v) => a + v, 0);
  ok(yearHist['1985'] / withVariation > 0.5, 'more than half of the records with a variation are on 1985',
     (100 * yearHist['1985'] / withVariation).toFixed(1) + '%');
  ok(html.includes('1985'), 'the page says 1985');

  // the two lags
  const parseEnd = s => { const m = /^(\d{1,2})([LCRWlcrw]?)$/.exec((s || '').trim()); return m && +m[1] >= 1 && +m[1] <= 36 ? +m[1] : null; };
  const byAirport = new Map(base.map(a => [a.SITE_NO, a]));
  let paperN = 0, paperOk = 0, todayN = 0, todayOk = 0;
  for (const e of ends) {
    const n = parseEnd(e.RWY_END_ID);
    if (n === null || !e.TRUE_ALIGNMENT) continue;
    const a = byAirport.get(e.SITE_NO);
    if (!a || !a.MAG_VARN || !a.MAG_HEMIS) continue;
    const lat = Number(e.LAT_DECIMAL || a.LAT_DECIMAL), lon = Number(e.LONG_DECIMAL || a.LONG_DECIMAL);
    if (!Number.isFinite(lat) || !Number.isFinite(lon)) continue;
    const tr = Number(e.TRUE_ALIGNMENT);
    const mv = Number(a.MAG_VARN) * (a.MAG_HEMIS === 'W' ? -1 : 1);
    const onRec = ((tr - mv) % 360 + 360) % 360;
    const now = ((tr - IG.field(pack, lat, lon, 0, EPOCH).D) % 360 + 360) % 360;
    if (!isTie(onRec)) { paperN++; if (designatorGap(designatorFor(onRec), n) === 0) paperOk++; }
    if (!isTie(now)) { todayN++; if (designatorGap(designatorFor(now), n) === 0) todayOk++; }
  }
  ok(paperN === faaJson.ends.matchesPaperworkOf && paperOk === faaJson.ends.matchesPaperwork,
     'the paint-versus-paperwork count is reproduced', paperOk + '/' + paperN);
  ok(todayN === faaJson.ends.matchesTodayOf && todayOk === faaJson.ends.matchesToday,
     'the paint-versus-today count is reproduced', todayOk + '/' + todayN);
  ok(paperOk / paperN > todayOk / todayN,
     'the paint matches the paperwork better than it matches the field, which is the two-lag claim',
     (100 * paperOk / paperN).toFixed(1) + '% vs ' + (100 * todayOk / todayN).toFixed(1) + '%');
}

// ---------------------------------------------------------------------------
section('8 · six repaintings that actually happened');

{
  ok(events.length === 6, 'six events', String(events.length));
  ok(events.every(e => e.found), 'all six runways were located in the sample');
  ok(events.every(e => e.crossing !== null), 'the model finds a crossing for all six');
  ok(events.every(e => e.leadYears > 0),
     'every crossing PRECEDES its repainting, which is the direction the rules require',
     events.map(e => e.airport + ':' + e.leadYears).join(' '));
  ok(events.every(e => e.leadYears < 25), 'and none is absurdly early', String(Math.max(...events.map(e => e.leadYears))));
  // recompute one from scratch, end to end
  const cork = events.find(e => e.airport === 'EICK');
  ok(!!cork, 'Cork is among them');
  const row = rows.find(r => r.id === cork.id);
  ok(!!row, 'and its runway row is in the table');
  const trueAz = row.le === cork.newLe ? row.trueAz : (row.trueAz + 180) % 360;
  const Dp = IG.field(pack, row.lat, row.lon, row.elevKm, cork.publishedAt).D;
  const modelled = ((trueAz - Dp) % 360 + 360) % 360;
  ok(near(modelled, cork.modelledMagneticBearing, 0.01), 'Cork\'s modelled magnetic bearing is reproduced', modelled.toFixed(3));
  ok(Math.abs(modelled - cork.publishedMagneticBearing) < 1.5,
     'and it lands within a degree and a half of the 164 degrees Cork Airport published',
     Math.abs(modelled - cork.publishedMagneticBearing).toFixed(2));
  // the crossing itself, found again
  let firstCross = null, prev = null;
  for (let y = 1960; y <= 2030.001; y += 0.05) {
    const yy = Math.round(y * 100) / 100;
    const D = IG.field(pack, row.lat, row.lon, row.elevKm, yy).D;
    const n = designatorFor(((trueAz - D) % 360 + 360) % 360);
    if (prev === cork.oldLe && n === cork.newLe && firstCross === null) firstCross = yy;
    prev = n;
  }
  ok(near(firstCross, cork.crossing, 0.06), 'and the crossing year is found again', String(firstCross));
}

// ---------------------------------------------------------------------------
section('9 · the shipped page');

{
  // Every number the page interpolates must exist in the data it ships.
  const paths = [...html.matchAll(/data-n="([^"]+)"/g)].map(m => m[1]);
  ok(paths.length > 20, 'the page pulls its numbers from the data rather than typing them', String(paths.length));
  const special = new Set(['result.scoredLabel', 'result.gap1', 'result.gap2plus']);
  for (const p of new Set(paths)) {
    if (special.has(p)) continue;
    let v = pageData;
    for (const k of p.split('.')) v = (v === null || v === undefined) ? undefined : v[k];
    ok(v !== undefined && v !== null, `the page's data path resolves: ${p}`);
  }
  // The shipped data is the built data.
  ok(pageData.epoch === summary.epoch, 'the page and the summary share an epoch');
  ok(pageData.result.disagree === summary.result.disagree, 'and the headline count');
  ok(pageData.epochFit.peakYear === summary.epochFit.global.peakYear, 'and the peak year');
  ok(pageData.events.length === events.length, 'and the same number of events');
  for (let i = 0; i < events.length; i++) {
    const a = pageData.events[i], b = events[i];
    ok(a.airport === b.airport && a.oldLe === b.oldLe && a.newLe === b.newLe
       && a.crossing === b.crossing && a.leadYears === b.leadYears
       && (a.modelledMagneticBearing ?? null) === (b.modelledMagneticBearing ?? null),
       `the shipped event matches the computed one: ${b.airport}`);
  }
}

{
  // The browser's copy of the field model is the same model.
  const src = readFileSync(PAGE + 'igrf.js', 'utf8');
  const sandbox = { window: {} };
  const fn = new Function('window', src + '\nreturn window.IGRF;');
  const B = fn(sandbox.window);
  ok(!!B && typeof B.Model === 'function', 'the browser module loads outside a browser');
  const coeff = JSON.parse(readFileSync(PAGE + 'igrf14.json', 'utf8'));
  const bm = new B.Model(coeff);
  let worst = 0;
  let seed = 987654321;
  const rnd = () => (seed = (seed * 1103515245 + 12345) & 0x7fffffff) / 0x7fffffff;
  for (let i = 0; i < 1000; i++) {
    const lat = rnd() * 176 - 88, lon = rnd() * 360 - 180, h = rnd() * 3, y = 1900 + rnd() * 130;
    worst = Math.max(worst, Math.abs(angleDiff(bm.declination(lat, lon, h, y), IG.field(pack, lat, lon, h, y).D)));
  }
  ok(worst < 1e-9, 'the browser and the verifier compute the same declination at a thousand random points',
     worst.toExponential(2) + ' deg');
  // and the same rule
  for (let b = 0; b < 360; b += 0.13) {
    if (B.designatorFor(b) !== designatorFor(b) || B.isTie(b) !== isTie(b)) {
      ok(false, 'the browser applies the same rounding rule', String(b)); break;
    }
  }
  ok(true, 'the browser applies the same rounding rule');
  // and its coefficient bundle is the coefficient file
  ok(coeff.epochs.length === 26, 'the shipped coefficient bundle has all 26 epochs');
  const packed = IG.packCoeffs(IG.loadCoeffs(S + 'igrf14coeffs.txt'));
  let cw = 0, k = 0;
  for (let n = 1; n <= 13; n++) for (let m = 0; m <= n; m++) {
    for (let e = 0; e < 26; e++) {
      cw = Math.max(cw, Math.abs(coeff.g[e][k] - packed.g[e][n][m]), Math.abs(coeff.h[e][k] - packed.h[e][n][m]));
    }
    cw = Math.max(cw, Math.abs(coeff.gsv[k] - packed.gsv[n][m]), Math.abs(coeff.hsv[k] - packed.hsv[n][m]));
    k++;
  }
  ok(cw === 0, 'and every shipped coefficient is the one in the IAGA file', String(cw));
}

{
  // The runway table the page ships is the one that was measured.
  const lite = JSON.parse(readFileSync(PAGE + 'runways.json', 'utf8'));
  ok(lite.rows.length === rows.length, 'the page ships every measured runway', lite.rows.length + ' vs ' + rows.length);
  const iAz = lite.fields.indexOf('trueAz'), iLe = lite.fields.indexOf('le');
  let worst = 0;
  for (let i = 0; i < lite.rows.length; i++) {
    worst = Math.max(worst, Math.abs(angleDiff(lite.rows[i][iAz], rows[i].trueAz)));
    if (lite.rows[i][iLe] !== rows[i].le) { ok(false, 'the shipped designator matches the measured one', String(i)); break; }
  }
  ok(worst < 0.0002, 'and its bearings are the measured bearings to the precision it ships them at', worst.toFixed(6));
  // The page recomputes the census in the reader's browser from this table. If
  // the shipped precision is coarser than the five-degree question needs, the
  // map's own caption disagrees with the prose above it, which is the page
  // contradicting itself in public. Recompute it here at the shipped precision.
  const iLat = lite.fields.indexOf('lat'), iLon = lite.fields.indexOf('lon');
  const iElev = lite.fields.indexOf('elevM'), iAzz = lite.fields.indexOf('trueAz'), iLee = lite.fields.indexOf('le');
  let sAgree = 0, sDis = 0;
  for (const r of lite.rows) {
    const Dd = IG.field(pack, r[iLat], r[iLon], r[iElev] / 1000, lite.epoch).D;
    const mag = ((r[iAzz] - Dd) % 360 + 360) % 360;
    if (isTie(mag)) continue;
    if (designatorFor(mag) === r[iLee]) sAgree++; else sDis++;
  }
  ok(sAgree === summary.result.agree && sDis === summary.result.disagree,
     'and recomputing the census at the shipped precision gives the number the prose prints',
     sAgree + '/' + sDis + ' vs ' + summary.result.agree + '/' + summary.result.disagree);
}

{
  // Every quotation on the page is transcribed in the sources directory, and
  // must match character for character. The documents themselves are not
  // committed (several are copyrighted), so this cannot prove the transcription
  // is faithful to the original. What it CAN do, and what it is for, is stop
  // the page and the record drifting apart, which is the failure that actually
  // happens: somebody tidies a quotation on the page and the citation quietly
  // stops pointing at the words beside it.
  const quotes = readFileSync(R + 'sources/quotations.md', 'utf8');
  const unent = t => t.replace(/&ldquo;/g, '\u201c').replace(/&rdquo;/g, '\u201d')
    .replace(/&middot;/g, '\u00b7').replace(/&mdash;/g, '\u2014').replace(/&amp;/g, '&')
    .replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&nbsp;/g, ' ').replace(/&deg;/g, '\u00b0');
  const flat = t => unent(t).replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim();
  const quoteText = flat(quotes);
  const blocks = [...html.matchAll(/<blockquote>([\s\S]*?)<\/blockquote>/g)]
    .map(m => m[1].replace(/<cite>[\s\S]*?<\/cite>/, ''))
    .map(flat);
  ok(blocks.length >= 5, 'the page carries the quotations it says it does', String(blocks.length));
  for (const b of blocks) {
    ok(quoteText.includes(b), 'the quotation is transcribed in sources/quotations.md', b.slice(0, 60) + '...');
  }
  // And the manifest names every source the summary pins, plus the documents
  // that were read and deliberately not committed.
  const manifest = readFileSync(R + 'sources/MANIFEST.md', 'utf8');
  for (const name of Object.keys(summary.inputs)) {
    ok(manifest.includes(name.split('/').pop()), `the manifest names the input ${name}`);
  }
  for (const doc of ['ICAO Annex 14', 'AC 150/5340-1M', '8260.19K', 'AIP Canada', 'NAV CANADA']) {
    ok(manifest.includes(doc), `the manifest records the uncommitted document: ${doc}`);
  }
  ok(/not committed|not obtained|NOT been verified/i.test(manifest),
     'and says plainly which documents were read but not redistributed');

  // The fault matrix and the sensitivity, which the page now prints and which
  // are therefore claims it has to keep.
  const oth = JSON.parse(readFileSync(DD + 'otherness.json', 'utf8'));
  ok(oth.harnessClean, 'the fault harness is green on its own no-fault row');
  ok(oth.reproducesShippedModel, 'and it reproduces the shipped model exactly, or it is measuring another program');
  ok(oth.matrix[0].caught.length === 0, 'the no-fault row catches nothing');
  ok(oth.summary.caughtByNoKey === 0, 'every injected model fault is caught by at least one key');
  ok(oth.summary.caughtByEveryKey === 0, 'and none is caught by all of them, so the keys are not interchangeable');
  ok(oth.summary.blindSpots['IAGA-12'].includes('rotation-sign'),
     'the geocentric key really is blind to the frame-rotation fault, which is the claim the page makes');
  ok(oth.summary.blindSpots['WMM-100'].includes('truncate-12'),
     'and the geodetic key really is blind to a degree-12 truncation, being a degree-12 model');
  ok(oth.summary.perKey['FAA-align'] === 0, 'the geometry key catches no field fault, as a negative control must');
  ok(oth.pipeline.caughtByAnyFieldKey === 0,
     'no fault injected below the field is visible to any of the five field keys');
  ok(oth.pipeline.caughtByAnOutcomeKey >= 1, 'but the outcome keys catch some of them');
  const escaped = oth.pipeline.faults.slice(1).filter(r => !r.fieldKeysRed.length
    && !r.sixRepaintings.red && !r.corkPublished.red && !r.navCanadaBenchmark.red);
  ok(escaped.length >= 1 && escaped.some(r => r.fault === 'no-tie-band'),
     'the fault the page says escaped every key really does escape every key',
     escaped.map(r => r.fault).join(','));
  ok(/escaped every key|escapes everything/i.test(html), 'and the page says so out loud');

  const ts = summary.tieSensitivity;
  ok(ts.excluded.pct === summary.result.disagreePct, 'the shipped headline is the excluded-band figure');
  ok(ts.scoredWrong.pct > ts.excluded.pct && ts.scoredRight.pct < ts.excluded.pct,
     'and it sits between the two alternatives, as it must');
  ok(ts.spreadPoints > 1, 'the convention is worth more than a rounding error, which is why it is printed',
     String(ts.spreadPoints));
  const flatFigureProse = html.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ');
  ok(flatFigureProse.includes(`Strict rounding instead gives ${ts.scoredWrong.pct} per cent`),
     'the strict-rounding sentence prints its computed percentage');
  ok(flatFigureProse.includes(`right gives ${ts.scoredRight.pct} per cent, a spread of ${ts.spreadPoints} points`),
     'the sensitivity sentence prints its computed percentage and spread');
  const [navOut, navTotal] = summary.benchmark.navCanada2020;
  ok(flatFigureProse.includes(`${navOut.toLocaleString('en-GB')} of ${navTotal.toLocaleString('en-GB')} is ${(100 * navOut / navTotal).toFixed(2)} per cent`),
     'the NAV CANADA percentage is computed from the cited counts');
  ok(ts.byHalfWidth.length >= 6 && ts.chosenHalfWidth === 0.5, 'the band width is scanned and the choice named');
  const mono = ts.byHalfWidth.every((r, i, a) => i === 0 || r.pct <= a[i - 1].pct + 1e-9);
  ok(mono, 'the headline falls monotonically as the band widens, which is what a band that hides disagreement does');
  // The width is justified as an ERROR BAR measured off the geometry key, not as
  // a taste. The page has to say so, and it has to say so with the number.
  // Prose wraps, so flatten before matching: a check that a sentence is present
  // must not depend on where the author happened to break the line.
  const flatHtml = html.replace(/\s+/g, ' ');
  ok(/error bar/i.test(flatHtml) && /cannot be chosen/i.test(flatHtml),
     'the page calls the exclusion band an error bar rather than a convention');
  ok(flatHtml.includes('permits a width of zero'),
     'and says the specification permits no width at all, so there is no envelope to choose inside');
  const geo = faaJson.geometryCheck;
  ok(String(geo.p90Abs).length > 0 && pageData.faa.geometryCheck
     && pageData.faa.geometryCheck.p90Abs === geo.p90Abs,
     'and ships the geometry key\'s spread so the page can print the measurement it rests on');
  // The scan range was anchored by the prior count, which the page admits, and the
  // admission is only worth anything because the distribution rejects the wide end
  // independently. Check both halves of that.
  ok(/the prior was anchoring the range/i.test(flatHtml),
     'the page admits its scan range was anchored by the published prior count');
  ok(/refuses two degrees on its own/i.test(flatHtml),
     'and shows the data rejecting the wide end without reference to that count');
  ok(geo.p99Abs * 2 < 2.0,
     'which it does: twice the ninety-ninth percentile of the bearing disagreement is under two degrees',
     geo.p99Abs + ' deg');
  ok(geo.p90Abs <= summary.quality.tieHalfWidth,
     'the chosen half-width is at least the ninetieth percentile of the bearing disagreement, which is what makes it an error bar and not a preference',
     geo.p90Abs + ' vs ' + summary.quality.tieHalfWidth);

  // The outward copy. A Dev.to essay goes out under the project's name quoting
  // these numbers, and nothing else in the repository would notice if the data
  // moved underneath it. Bind them.
  const devto = 'social/devto/0008-five-keys-agreed.md';
  if (existsSync(devto)) {
    const essay = readFileSync(devto, 'utf8');
    const oth2 = JSON.parse(readFileSync(DD + 'otherness.json', 'utf8'));
    const ts2 = summary.tieSensitivity;
    const must = [
      [oth2.summary.cellsRed + ' of ' + oth2.summary.cellsTotal + ' cells red', 'the cells-red count'],
      [ts2.excluded.pct + '%', 'the shipped headline'],
      [ts2.scoredWrong.pct + '%', 'the strict-rounding headline'],
      [ts2.scoredRight.pct + '%', 'the count-it-right headline'],
      [String(ts2.spreadPoints) + ' percentage points', 'the spread'],
      [String(oth2.pipeline.faults[0].navCanadaBenchmark.pct), 'the clean benchmark'],
      [String(oth2.pipeline.faults.find(f => f.fault === 'no-tie-band').navCanadaBenchmark.pct), 'the faulted benchmark'],
      [String(summary.benchmark.navCanada2020Pct), 'the published prior count'],
    ];
    for (const [needle, what] of must) {
      ok(essay.includes(needle), `the Dev.to essay still quotes ${what} correctly`, needle);
    }
    // and its matrix block must be the matrix
    for (const r of oth2.matrix) {
      const line = essay.split('\n').find(l => l.startsWith(r.fault + ' ') || l.trim() === r.fault);
      if (!line) { ok(false, `the essay's matrix has a row for ${r.fault}`); continue; }
      const cells = line.slice(r.fault.length).trim().split(/\s+/);
      const expected = oth2.keys.map(k => r.fault === 'none' ? 'ok' : (r.caught.includes(k.id) ? 'RED' : 'blind'));
      ok(cells.length === expected.length && cells.every((c, i) => c === expected[i]),
         `the essay's matrix row for ${r.fault} is the computed one`, cells.join(' ') + ' vs ' + expected.join(' '));
    }
    ok(/wisp\.mk\.gg/.test(essay) && /melodic\.stream/.test(essay),
       'and it credits the two people whose question produced it');
  }

  // Honesty furniture.
  ok(!html.replace(/&mdash;|&#8212;/g, '').includes('\u2014'), 'the page carries no em dash in its own prose');
  ok(!md.includes('\u2014'), 'the frontmatter carries none either');
  // The gate only reads added lines, and the shipped script is a page asset the
  // page's own check would otherwise miss.
  ok(!readFileSync(PAGE + 'igrf.js', 'utf8').includes('\u2014'), 'nor does the shipped browser module');
  ok(!readFileSync(R + 'README.md', 'utf8').includes('\u2014'), 'nor the apparatus README');
  ok(/<\/script>\s*<\/body>\s*<\/html>\s*$/.test(html.trim() + '\n') || html.trim().endsWith('</html>'),
     'the closing tags are present (the recurring silent-script bug)');
  ok(html.includes('verify-the-north-the-paint-remembers.mjs'), 'the page names its own verifier');
  ok(html.includes('5.2.2.4') && html.includes('150/5340-1M') && html.includes('8260.19K'),
     'the page cites the three rule documents it quotes');
  ok(/9th \(2022\)|9th edition/.test(html), 'and admits it could not read the current ICAO edition');
  ok(html.includes('OurAirports') && html.includes('Natural Earth'), 'the page credits its data');
  for (const s of ['does not say any runway is illegal', 'not a random sample',
                   'community database', 'not a repainting date', 'outside 1900 to 2030', 'not novel']) {
    ok(html.includes(s), `the limits section states: ${s}`);
  }
  // The dek must not overclaim relative to the data.
  const dek = (md.match(/^dek:\s*"([\s\S]*?)"\s*$/m) || [])[1] || '';
  const bothForms = n => [String(n), n.toLocaleString('en-US'), n.toLocaleString('en-GB')];
  ok(bothForms(summary.counts.scored).some(f => dek.includes(f)), 'the dek quotes the real scored count',
     bothForms(summary.counts.scored).join(' / '));
  ok(bothForms(summary.result.disagree).some(f => dek.includes(f)), 'and the real disagreement count');
  ok(dek.includes(summary.result.disagreePct.toFixed(1)), 'and the real percentage');
  ok(dek.includes(String(summary.epochFit.global.peakYear)), 'and the real peak year');
  ok(/NAV CANADA/.test(dek), 'and credits the prior count in the dek, where it travels furthest');
}

// ---------------------------------------------------------------------------
if (MUTATE) {
  section('controls: these must fail');
  let caught = 0, tried = 0;
  const control = (name, fn) => {
    tried++;
    let red = false;
    try { red = !fn(); } catch (e) { red = true; }
    if (red) { caught++; }
    else { fail++; failures.push('CONTROL DID NOT FAIL: ' + name); console.log('  CONTROL SURVIVED  ' + name); }
  };

  // Break the frame rotation and see whether the WMM key notices. It must,
  // because it is the only geodetic key with all components.
  control('deleting the geodetic frame rotation is caught by the WMM key', () => {
    const wmm = IG.loadWmmCof(S + 'WMM2025COF/WMM2025.COF');
    const lines = readFileSync(S + 'WMM2025COF/WMM2025_TestValues.txt', 'utf8')
      .split('\n').filter(l => l.trim() && !l.trim().startsWith('#'));
    let worst = 0;
    for (const l of lines) {
      const p = l.trim().split(/\s+/).map(Number);
      if (p.length < 11) continue;
      const [yr, alt, lat, lon, Dp] = p;
      // the un-rotated declination, which is what a missing rotation would give
      const gc = IG.fieldGeocentric(wmm, 90 - lat, lon, 6371.2 + alt, yr, 12);
      worst = Math.max(worst, Math.abs(angleDiff(Math.atan2(gc.Y, gc.X) * 180 / Math.PI, Dp)));
    }
    return worst < 0.01;   // must be FALSE
  });

  // Flip the sign of declination in the rule and the census must collapse.
  control('flipping the sign of the declination destroys the agreement', () => {
    let n = 0, good = 0;
    for (const r of rows) {
      const D = IG.field(pack, r.lat, r.lon, r.elevKm, EPOCH).D;
      const mag = ((r.trueAz + D) % 360 + 360) % 360;   // WRONG sign
      if (isTie(mag)) continue;
      n++; if (designatorFor(mag) === r.le) good++;
    }
    return Math.abs(good / n - summary.result.agree / summary.counts.scored) < 0.02;   // must be FALSE
  });

  // Use the TRUE bearing instead of the magnetic one and agreement must drop.
  control('scoring by true bearing instead of magnetic drops the agreement', () => {
    let n = 0, good = 0;
    for (const r of rows) { n++; if (designatorFor(r.trueAz) === r.le) good++; }
    return good / n >= summary.result.agree / summary.counts.scored;   // must be FALSE
  });

  // A random relabelling must destroy everything, which proves the agreement is
  // not an artefact of the sample rather than of the rule.
  control('shuffling the painted numbers destroys the agreement', () => {
    let seed = 4242, n = 0, good = 0;
    const rnd = () => (seed = (seed * 1103515245 + 12345) & 0x7fffffff) / 0x7fffffff;
    for (const r of rows) {
      const fake = 1 + Math.floor(rnd() * 36);
      const D = IG.field(pack, r.lat, r.lon, r.elevKm, EPOCH).D;
      const mag = ((r.trueAz - D) % 360 + 360) % 360;
      if (isTie(mag)) continue;
      n++; if (designatorFor(mag) === fake) good++;
    }
    return good / n > 0.10;   // must be FALSE: chance is about 1 in 36
  });

  // Corrupt a coefficient and the IAGA key must notice.
  control('corrupting one coefficient is caught by the IAGA cases', () => {
    const bad = IG.packCoeffs(IG.loadCoeffs(S + 'igrf14coeffs.txt'));
    bad.g[25][1][0] += 50;                         // 50 nT out of 29,350
    const f = IG.fieldGeocentric(bad, 56, -3, 6375, 2025);
    return Math.abs(f.X - 28927.56) <= 0.01;       // must be FALSE
  });

  // Claim the epoch peak is the present and the curve must refuse.
  control('the curve does not peak in the present', () => {
    const curve = summary.epochFit.global.curve;
    const now = curve.find(p => p[0] === 2026)[1];
    return curve.every(p => p[1] <= now);          // must be FALSE
  });

  // Put the asserted-cardinal rows back and the histogram spike must return.
  control('the cardinal-assertion spike is real, not an artefact of binning', () => {
    const q = summary.quality;
    return q.modSpikeBefore <= 3 * q.modMeanBin;   // must be FALSE
  });

  // Score the excluded band by strict rounding and the headline must move, which is why
  // it is excluded rather than quietly swept in.
  control('including the ambiguous band would change the headline', () => {
    let n = 0, good = 0;
    for (const r of rows) {
      const D = IG.field(pack, r.lat, r.lon, r.elevKm, EPOCH).D;
      const mag = ((r.trueAz - D) % 360 + 360) % 360;
      n++; if (designatorFor(mag) === r.le) good++;
    }
    return Math.abs(100 * (n - good) / n - summary.result.disagreePct) < 0.05;   // must be FALSE
  });

  console.log(`  ${caught} of ${tried} controls went red as required.`);
}

console.log(`\n${pass} / ${pass + fail} checks passed.`
  + (fail ? '\nFAILURES:\n  ' + failures.join('\n  ') : '')
  + (MUTATE ? '' : '\n(run with --mutate for the controls that must fail)'));
process.exit(fail ? 1 : 0);
