// verify.mjs: the check for "No Year to Round To".
//
//   node research/no-year-to-round-to/verify.mjs
//   node research/no-year-to-round-to/verify.mjs --members   # also re-run every member's verifier
//
// Order of business, and the reason for it:
//   0. Recompute the frontier a second way, from continued-fraction theory rather than
//      from a record scan, importing none of the layer's engine. If a staircase built by
//      brute force and a staircase built from semiconvergents agree, the engine is not
//      merely self-consistent.
//   1. Re-run the data assembly and require the committed data.mjs to come back
//      byte-identical, and the page's engine copies to be byte-identical to the lab's.
//   2. Check the measured astronomy against two things it is not derived from: a second
//      VSOP87 implementation, and a JPL Horizons response committed by sha256.
//   3. Recompute every number the prose prints.
//   4. Check the page's shipped bytes against those numbers, including its own check count
//      and the member quotations it displays.
//   5. Mutate, and require the checks to turn red.

import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import { execFileSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';

const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, '../..');
const R = p => fs.readFileSync(path.join(ROOT, p), 'utf8');

let pass = 0, fail = 0;
const problems = [];
function ok(cond, label) {
  if (cond) { pass++; } else { fail++; problems.push(label); console.log('  FAIL  ' + label); }
}
function near(a, b, tol, label) {
  ok(Number.isFinite(a) && Math.abs(a - b) <= tol, label + ' (got ' + a + ', want ' + b + ' +/- ' + tol + ')');
}

const F = await import('./findings.mjs');
const { D } = await import('./data.mjs');
const html = R('public/strata/no-year-to-round-to/index.html');

// ── 0. the arithmetic, derived a second way ──────────────────────────────────
// The engine finds the staircase by scanning every denominator and keeping the records.
// Here it is built instead from the theory: the best rational approximations of the
// first kind are exactly the convergents plus the semiconvergents h(k-1)+j*h(k-2) over
// k(k-1)+j*k(k-2) for j past the halfway point. Two different derivations, one answer.

console.log('\n§0  the staircase, built from theory instead of by scanning');

function ownCF(x, n) {
  const a = []; let v = x;
  for (let i = 0; i < n; i++) { const ai = Math.floor(v); a.push(ai); const f = v - ai; if (f < 1e-13) break; v = 1 / f; }
  return a;
}

function ownStaircaseFromTheory(x, maxQ) {
  const a = ownCF(x, 30);
  // convergents
  const h = [1, a[0]], k = [0, 1];
  for (let i = 1; i < a.length; i++) { h.push(a[i] * h[i] + h[i - 1]); k.push(a[i] * k[i] + k[i - 1]); }
  const out = new Map();
  // Keyed by denominator, keeping whichever numerator is actually closest: for a target
  // below 1 the first step of the expansion offers both 0/1 and 1/1, and only one of
  // them is the approximation.
  const add = (p, q) => {
    if (q < 1 || q > maxQ) return;
    const prev = out.get(q);
    if (prev === undefined || Math.abs(p / q - x) < Math.abs(prev / q - x)) out.set(q, p);
  };
  // h[i]/k[i] holds convergent number i-1, with h[0]/k[0] = 1/0 as the seed. The
  // semiconvergents of step i are (j*h[i] + h[i-1]) / (j*k[i] + k[i-1]) for j = 1..a[i],
  // and j = a[i] reproduces the convergent itself.
  for (let i = 1; i < h.length; i++) {
    add(h[i], k[i]);
    for (let j = 1; j <= a[i]; j++) add(j * h[i] + h[i - 1], j * k[i] + k[i - 1]);
  }
  // keep only those that are actual records
  const qs = [...out.keys()].sort((p, q) => p - q);
  const rec = []; let best = Infinity;
  for (const q of qs) {
    const p = out.get(q); const e = Math.abs(p / q - x);
    if (e < best - 1e-18) { best = e; rec.push({ p, q }); }
  }
  return rec;
}

// A third, blunt derivation: best numerator by scanning candidates rather than rounding.
function ownBestNumerator(x, q) {
  const c = Math.floor(x * q);
  let bp = c, be = Infinity;
  for (const p of [c - 1, c, c + 1, c + 2]) { const e = Math.abs(p / q - x); if (e < be) { be = e; bp = p; } }
  return bp;
}
function ownStaircaseByScan(x, maxQ) {
  const rec = []; let best = Infinity;
  for (let q = 1; q <= maxQ; q++) {
    const p = ownBestNumerator(x, q); const e = Math.abs(p / q - x);
    if (e < best - 1e-18) { best = e; rec.push({ p, q }); }
  }
  return rec;
}

for (const t of F.TARGETS) {
  const theory = ownStaircaseFromTheory(t.value, 2000);
  const scan = ownStaircaseByScan(t.value, 2000);
  const engine = F.PER_TARGET[t.key].frontier;
  ok(JSON.stringify(theory.map(r => [r.p, r.q])) === JSON.stringify(scan.map(r => [r.p, r.q])),
    `${t.name}: the semiconvergent staircase and the scanned staircase are the same list`);
  ok(JSON.stringify(scan.map(r => [r.p, r.q])) === JSON.stringify(engine.map(r => [r.p, r.q])),
    `${t.name}: and the engine's staircase is that same list`);
}

// the arithmetic of a drift figure, written out longhand once
near(1 / Math.abs(97 / 400 - 0.2422), 3333.3333333, 1e-4, 'a target written as 365.2422 makes the Gregorian drift 3,333 years');

// ── 0b. the four published figures, each from the basis its own source states ─
// Every one of these was read at source. The point of the section is that all four are
// correct, so the check is that each recomputation lands on what its source printed.

console.log('\n§0b  four published drift figures, recomputed from their own stated bases');
{
  const P = Object.fromEntries(F.FAMOUS.published.map(p => [p.says, p]));
  ok(F.FAMOUS.published.length === 4, 'four figures are carried');
  near(P[3030].recomputed, 3030, 1, 'the 3,030-year figure comes back from a constant 365.24217');
  near(P[3300].recomputed, 3333.3, 0.5, 'the 3,300-year figure comes back from a constant 365.2422');
  near(P[7700].recomputed, 7692.3, 0.5, 'the 7,700-year figure comes back from a constant 365.24237');
  ok(Math.abs(P[2500].recomputed - 2500) < 100,
    `the ~2,500-year figure comes back from Laskar's shrinking year, integrated (${P[2500].recomputed})`);
  // and the control: holding that same year CONSTANT does not give 2,500
  near(1 / Math.abs(97 / 400 - 0.2421896698), 3222.4, 1, 'while holding the same year constant gives 3,222, which is the whole difference');
  ok(P[2500].recomputed < 3222.4 * 0.85,
    'so integrating rather than dividing moves the answer by more than fifteen per cent, and that is what separates NASA from the USNO');
  near(F.FAMOUS.spreadFactor, 3.08, 0.01, 'the four published figures span a factor of 3.1');
  near(F.FAMOUS.roundingCostYears, 428.3, 1, 'and the fifth decimal place of one target is worth 428 years');

  // the medieval sequence against the computed one
  ok(JSON.stringify(F.TUSI.gaps) === JSON.stringify([33, 33, 33, 33, 29, 33, 33, 33]),
    "Tusi's nine pentaennial years give run lengths 33,33,33,33,29,33,33,33");
  ok(F.TUSI.pentaennialYears.length === 9 && F.TUSI.nRuns === 8, 'nine listed years, eight runs between them');
  ok(F.TUSI.modalRunLength === F.OBSERVED.modalCycleLength,
    'the medieval table and the modern ephemeris agree on the modal run length');
  near(F.TUSI.modalShare, 0.875, 1e-9, 'seven of eight of the attested runs are 33 years');
  near(F.OBSERVED.modalShare, 0.8333333, 1e-6, 'twenty of twenty-four of the computed runs are 33 years');
  ok(Object.keys(F.TUSI.runLengthHistogram).every(k => k === '29' || k === '33'),
    'and the attested runs use only lengths this computation also produces');
}

// ── 1. the data cannot drift ─────────────────────────────────────────────────

console.log('\n§1  the data is assembled from the ephemeris and the members, and cannot drift');
{
  const { assemble, render } = await import('./build-data.mjs');
  const fresh = render(assemble());
  ok(fresh === R('research/no-year-to-round-to/data.mjs'),
    'data.mjs is byte-identical to a fresh assembly from the ephemeris and the members\' own files');
  for (const mod of ['decide.mjs', 'data.mjs', 'findings.mjs']) {
    ok(R('research/no-year-to-round-to/' + mod) === R('public/strata/no-year-to-round-to/engine/' + mod),
      `the page's copy of ${mod} is byte-identical to the lab's`);
  }
}

// ── 2. the astronomy, against things it is not derived from ──────────────────

console.log('\n§2  the measured years, against a second library and against JPL');
{
  const C = D.crossChecks;
  for (const k of ['marchEquinox', 'juneSolstice', 'septemberEquinox', 'decemberSolstice']) {
    // The tolerances are the ones the PROSE claims, not looser ones. An adversarial pass
    // pointed out that a guard of 0.2 s cannot defend a sentence that says "under a tenth
    // of a second", so the guard now says what the page says.
    ok(Math.abs(C[k].disagreementSeconds) < 0.1,
      `${k}: two independent VSOP87 implementations agree to under a tenth of a second (${C[k].disagreementSeconds.toFixed(4)})`);
    ok(Math.abs(C[k].minusPublishedSeconds) < 0.5,
      `${k}: and within half a second of Meeus & Savoie's published epoch-2000 value (${C[k].minusPublishedSeconds.toFixed(4)})`);
  }
  ok(Math.abs(C.meanTropical.minusPublishedSeconds) < 0.2,
    'the mean over 72 longitudes reproduces the published mean tropical year to under 0.2 s');

  // the four are genuinely ordered the way the page says
  const v = F.CARDINAL.map(t => t.value);
  ok(F.TARGET_BY_KEY.december.value > F.TARGET_BY_KEY.march.value
    && F.TARGET_BY_KEY.march.value > F.TARGET_BY_KEY.september.value
    && F.TARGET_BY_KEY.september.value > F.TARGET_BY_KEY.june.value,
    'December > March > September > June, as measured');
  near((Math.max(...v) - Math.min(...v)) * 86400, 95.567, 0.01, 'the spread of the four is 95.6 seconds');

  // the mean really is between them, and is nobody's season
  ok(F.TARGET_BY_KEY.mean.value < Math.max(...v) && F.TARGET_BY_KEY.mean.value > Math.min(...v),
    'the mean tropical year lies inside the range of the four and equals none of them');

  // Horizons, by content hash rather than by trust
  const raw = R('research/no-year-to-round-to/ephemeris/horizons-2026-march.txt');
  ok(crypto.createHash('sha256').update(raw).digest('hex') === D.horizons.sha256,
    'the committed JPL Horizons response still hashes to the sha256 the data records');
  ok(/source: DE441/.test(raw) && /Sun \(10\)/.test(raw), 'and it is the Sun from DE441, geocentric');
  ok(D.horizons.rows === 61 && D.horizons.stepMinutes === 1, 'it is 61 rows at one-minute steps');
  near(D.horizons.diffSeconds.horizonsMinusAstronomyEngine, 22.53, 0.05, 'astronomy-engine lands 22.5 s from the JPL crossing');
  near(D.horizons.diffSeconds.horizonsMinusAstronomia, 2.21, 0.05, 'astronomia lands 2.2 s from it');
  ok(Math.abs(D.horizons.diffSeconds.horizonsMinusAstronomyEngine)
    > Math.abs(C.marchEquinox.disagreementSeconds) * 100,
    'a single instant is two orders of magnitude worse determined than the mean interval, which is the point of averaging');
}

// ── 3. every number the prose prints ─────────────────────────────────────────

console.log('\n§3  the findings');
{
  const drift = (p, q, f) => 1 / Math.abs(p / q - f);
  const T = F.TARGET_BY_KEY;

  near(drift(97, 400, T.december.value), 4204.92, 0.5, 'Gregorian against the December solstice: 4,205 years');
  near(drift(97, 400, T.june.value), 1151.69, 0.5, 'Gregorian against the June solstice: 1,152 years');
  near(drift(97, 400, T.march.value), 8120.57, 0.5, 'Gregorian against the March equinox: 8,121 years');
  near(drift(97, 400, T.mean.value), 3234.78, 0.5, 'Gregorian against the mean tropical year: 3,235 years');
  near(drift(31, 128, T.mean.value), 297659.7, 5, "Madler's rule against the mean tropical year: 297,660 years");
  near(drift(31, 128, T.march.value), 5280.6, 0.5, 'and against the March equinox: 5,281 years');
  near(drift(218, 900, T.mean.value), 31885.0, 1, 'Revised Julian against the mean tropical year: 31,885 years');
  near(drift(218, 900, T.march.value), 6466.6, 0.5, 'and against the March equinox: 6,467 years');
  ok(drift(218, 900, T.march.value) < drift(97, 400, T.march.value),
    'the 1923 rule really is worse than the 1582 rule at the March equinox');
  near((1 - drift(218, 900, T.march.value) / drift(97, 400, T.march.value)) * 100, 20.4, 0.5,
    'and worse by about twenty per cent');
  ok(drift(218, 900, T.mean.value) > drift(97, 400, T.mean.value) * 9,
    'while being nearly ten times better at the mean tropical year');

  // the closing claim, which is a universal and therefore has to be checked as one:
  // exactly one of the five rules has a cycle below the crossover, and it is the Julian
  const fork = F.CROSSOVER.numeratorForkAt;
  const below = F.RULES.filter(r => r.q < fork).map(r => r.key);
  const above = F.RULES.filter(r => r.q > fork).map(r => r.key);
  ok(JSON.stringify(below) === JSON.stringify(['julian']),
    'exactly one of the five rules has a cycle below the fork, and it is the Julian');
  ok(above.length === 4 && !above.includes('julian'),
    'and the other four, 33, 128, 400 and 900, are all above it');
  ok(19 < fork, 'the Metonic 19 is below the fork too');
  ok(!/every rule anyone has ever legislated/.test(html),
    'the page does not claim a universal over calendars it never surveyed');
  ok(/every one of the five rules here that was meant to improve on Caesar sits above it/.test(html),
    'it claims only what it checked');

  // the reorderings are not near-ties, which is the first objection anyone would make
  near(F.MARGINS.worstCaseRatio, 1.062, 0.002,
    'the closest two swapping rules ever come at any cardinal target is a 6 per cent gap in drift');
  ok(F.MARGINS.allAbove, 'and every swapping pair is above five per cent apart at every target');
  ok(F.MARGINS.pairs.length === 6, 'margins are computed for all six swapping pairs');
  {
    const gc = F.MARGINS.pairs.find(p => (p.a === 'gregorian' && p.b === 'cycle33') || (p.a === 'cycle33' && p.b === 'gregorian'));
    const march = gc.per.find(x => x.target === 'march');
    near(march.ratio, 2.599, 0.01, 'the 33-year cycle leads the Gregorian by a factor of 2.6 at the March equinox');
    ok(march.leader === 'cycle33', 'and it is the cycle that leads there');
    ok(gc.per.find(x => x.target === 'december').leader === 'gregorian', 'while the Gregorian leads at the December solstice');
  }

  // the epoch sensitivity, stated exactly rather than loosely
  {
    const w = D.crossChecks;  // the shipped window
    ok(Math.abs(w.marchEquinox.astronomyEngine - 365.2423769) < 1e-7, 'the shipped March value is the 1500-2500 mean');
  }

  // the reordering
  ok(F.REORDER.swaps.length === 6, 'six of the ten pairs of rules change places across the four cardinal years');
  ok(F.HEADLINE.nPairs === 10, 'and there are ten pairs');
  const firsts = new Set(F.CARDINAL.map(t => F.PER_TARGET[t.key].ranking[0].key));
  ok(firsts.size === 3, 'three different rules take first place across the four seasons');
  ok(F.PLACES.gregorian.best.place === 1 && F.PLACES.gregorian.best.target === 'december',
    'the Gregorian rule is first against the December solstice');
  ok(F.PLACES.gregorian.worst.place === 4 && F.PLACES.gregorian.worst.target === 'june',
    'and fourth of five against the June solstice');
  ok(F.PLACES.julian.best.place === 5 && F.PLACES.julian.worst.place === 5,
    'the Julian rule is last at every target, which is the control');
  ok(F.HEADLINE.gregorianOnFrontierAnywhere === false,
    'and 97/400 is above the staircase at every one of the five targets');

  // 97/400 is a convergent of nothing; 8/33 and 31/128 depend on the target
  for (const t of F.TARGETS) {
    ok(!F.PER_TARGET[t.key].convergents.some(c => c.q === 400 && c.p === 97),
      `97/400 is not a convergent of the ${t.name}`);
  }
  const cvHas = (k, p, q) => F.PER_TARGET[k].convergents.some(c => c.p === p && c.q === q);
  ok(cvHas('march', 8, 33) && cvHas('september', 8, 33) && cvHas('december', 8, 33) && !cvHas('june', 8, 33),
    '8/33 is a convergent of three of the four cardinal years and not of the June solstice year');
  ok(cvHas('mean', 31, 128) && !cvHas('march', 31, 128) && !cvHas('june', 31, 128)
    && !cvHas('september', 31, 128) && !cvHas('december', 31, 128),
    '31/128 is a convergent of the mean tropical year and of no cardinal year');

  // the rounding artefact in the continued fraction
  const cf2424 = ownCF(0.2424, 6);
  ok(cf2424[4] === 37 && cf2424[5] > 1e9,
    'the continued fraction of a target rounded to 365.2424 explodes at the fifth term, which is the rounding and not the year');

  // the crossover, three ways
  ok(F.CROSSOVER.spreadBeatenAt === 29, 'the spread is first beaten at a cycle of 29 years');
  ok(F.CROSSOVER.numeratorForkAt === 31, 'the four years first ask for different numerators at a cycle of 31 years');
  near(F.CROSSOVER.scale, 21.26, 0.01, 'and the theory scale sqrt(1/2s) is 21.3');
  ok(F.CROSSOVER.scale < F.CROSSOVER.spreadBeatenAt && F.CROSSOVER.spreadBeatenAt < F.CROSSOVER.numeratorForkAt,
    'the theory value sits below both measurements, which is the check on all three');
  {
    const ps = F.CARDINAL.map(t => Math.round(31 * t.value));
    ok(ps.filter(p => p === 8).length === 3 && ps.filter(p => p === 7).length === 1,
      'at 31, three of the four seasons ask for 8 leap days and the June solstice asks for 7');
    const ps30 = F.CARDINAL.map(t => Math.round(30 * t.value));
    ok(new Set(ps30).size === 1, 'and at 30 they still all agree');
  }

  // the Metonic leg
  ok(F.METONIC.allAgreeOnNumerator && F.METONIC.numeratorAt19 === 235,
    'all four cardinal years agree that the best fraction at a cycle of 19 is 235 months');
  ok(F.METONIC.allOnFrontier, 'and 235/19 is on the staircase under every one of them');
  ok(F.METONIC.perTarget.every(x => x.cfIndexOf235over19 === 5),
    'and it is the sixth convergent under every one of them');
  ok(F.METONIC.crossover.numeratorForkAt === 167, "the lunar problem's numerators do not fork until a cycle of 167");
  near(167 / 19, 8.8, 0.1, 'so the Metonic 19 sits about nine times below its own fork');
  near(400 / 31, 12.9, 0.1, 'while the Gregorian 400 sits about thirteen times above the calendar\'s');
  near(400 / 33, 12.1, 0.1, 'and 8/33 has a cycle about twelve times shorter than 97/400');

  // the family
  const famFrontier = k => F.PER_TARGET[k].familyFrontier;
  {
    const m = famFrontier('march');
    const i = m.findIndex(x => x.p === 97 && x.q === 400);
    ok(i >= 0, '97/400 is on the century-only staircase against the March equinox');
    ok(m[i + 1].q === 1300, 'and the next century-only improvement is not until a cycle of 1,300 years');
    ok(1200 < m[i + 1].q, 'so the page\'s "up to 1,200 years" is true and conservative');
    const mean = famFrontier('mean');
    const j = mean.findIndex(x => x.p === 218 && x.q === 900);
    ok(j >= 0, '218/900 is on the century-only staircase against the mean tropical year');
    ok(mean[j + 1].q === 2300, 'and the next century-only improvement is not until a cycle of 2,300 years');
    ok(2200 < mean[j + 1].q, 'so the page\'s "up to 2,200 years" is true and conservative');
    ok(!mean.some(x => x.p === 97 && x.q === 400 && x.q > 500) , 'sanity: the two families are read separately');
  }
  // the Revised Julian rule really does give 218 in 900
  {
    let n = 0;
    for (let y = 0; y < 900; y++) if (y % 4 === 0 && (y % 100 !== 0 || y % 900 === 200 || y % 900 === 600)) n++;
    ok(n === 218, 'the Revised Julian rule, applied year by year, gives 218 leap days per 900');
  }
  {
    let n = 0;
    for (let y = 0; y < 400; y++) if (y % 4 === 0 && (y % 100 !== 0 || y % 400 === 0)) n++;
    ok(n === 97, 'and the Gregorian rule gives 97 per 400');
  }
}

// ── 4. the observational calendar ────────────────────────────────────────────

console.log('\n§4  the calendar that writes no fraction');
{
  const O = F.OBSERVED;
  ok(O.window[0] === 1600 && O.window[1] === 2400, 'the observational run covers 1600 to 2400');
  ok(O.leapYears === 193 && O.ofYears === 800, 'it inserts 193 leap days in 800 years');
  near(O.predictedByMarchYear, 193.90, 0.01, 'where the measured March equinox year predicts 193.9');
  ok(Math.abs(O.leapYears - O.predictedByMarchYear) < 1,
    'which agrees to within the one-day boundary effect a finite window is entitled to');
  ok(O.cycleLengthHistogram['33'] === 20 && O.cycleLengthHistogram['29'] === 3 && O.cycleLengthHistogram['37'] === 1,
    'the runs come out 20 of length 33, 3 of length 29 and 1 of length 37');
  ok(O.nCycles === 24, 'twenty-four runs in all');
  ok(O.modalCycleLength === 33, 'the modal run is 33 years');
  near(O.modalShare, 20 / 24, 1e-12, 'which is twenty in twenty-four');
  ok(O.gapHistogram['4'] === 168 && O.gapHistogram['5'] === 24,
    'leap years fall four years apart 168 times and five years apart 24 times');
  ok(168 + 24 === O.leapYears - 1, 'and the gaps account for every leap year but the first');

  // ground truth (a): the seven-plus dates anyone can look up, and the half-day trap
  const ND = O.nowruzDates;
  const on20 = Object.entries(ND).filter(([, d]) => d.endsWith('-03-20')).map(([y]) => Number(y));
  const on21 = Object.entries(ND).filter(([, d]) => d.endsWith('-03-21')).map(([y]) => Number(y));
  ok(Object.keys(ND).length === 13, 'thirteen Nowruz dates are carried, 2018 to 2030');
  ok(JSON.stringify(on20) === JSON.stringify([2020, 2024, 2028, 2029]),
    'Nowruz lands on 20 March in exactly 2020, 2024, 2028 and 2029');
  ok(on21.length === 9, 'and on 21 March in the other nine');
  ok(on20.length + on21.length === 13, 'and on no other date, so no half-day slip has shifted the series');
  ok(ND['2020'] === '2020-03-20' && ND['2021'] === '2021-03-21' && ND['2026'] === '2026-03-21',
    'three of them spelled out, so a wholesale shift cannot hide in a pattern');

  // ground truth (b): a published arithmetic rule, scored over exactly its stated window
  const B = O.borkowski;
  ok(B.window[0] === 1178 && B.window[1] === 1634, "Borkowski's stated validity window is Jalali 1178 to 1634");
  ok(B.tested === 457, 'which is 457 years inside the computed run');
  ok(B.agree === 456, 'and the computation agrees with his arithmetic on 456 of them');
  ok(B.disagreements.length === 1 && B.disagreements[0].jalali === 1634,
    'the single disagreement is Jalali 1634, the last year of the window he said it was good for');
  ok(B.rate > 0.997, 'an agreement rate above 99.7 per cent with a rule this computation does not use');
  // and the control: his arithmetic is NOT what the run was computed from
  ok(!R('research/no-year-to-round-to/ephemeris/compute.mjs').match(/BORKOWSKI_REMAINDERS[\s\S]{0,400}?nowruzSeries/),
    'and his remainder set is not used anywhere in producing the sequence it is scored against');

  ok(O.apparentVsMeanNoon.differingYears === 7 && O.apparentVsMeanNoon.of === 801,
    'reading noon as the Sun\'s rather than the clock\'s moves 7 of 801 dates');
  ok(O.zoneMeridianInsteadOfBorkowskis.differingYears === 3, "using Tehran's own meridian moves 3");
  ok(O.twoLibraries.differingYears === 0, 'and the two ephemeris libraries agree on all 801');

  const s = Object.fromEntries(O.deltaTSensitivity.map(d => [d.shiftSeconds, d]));
  ok(s[3600].movedDates === 16 && s[3600].ofFutureYears === 374,
    'an hour of error in the Earth\'s rotation moves 16 of the 374 future dates');
  ok(s[1].movedDates === 0 && s[10800].movedDates === 46,
    'a second moves none and three hours move 46, so the response is monotone across the sweep');
  for (let i = 1; i < O.deltaTSensitivity.length; i++) {
    ok(O.deltaTSensitivity[i].movedDates >= O.deltaTSensitivity[i - 1].movedDates,
      `the sensitivity sweep is non-decreasing at ${O.deltaTSensitivity[i].shiftSeconds} s`);
  }
  near(O.deltaTAtWindowEnds['1600'], 119.8, 0.5, 'the accumulated rotation offset is about 120 s in 1600');
  near(O.deltaTAtWindowEnds['2400'], 1057.2, 0.5, 'and about 1,057 s in 2400');

  // the leap fractions of the arithmetic rules over the same window, counted the same way
  ok(D.ruleLeapCounts.counts.gregorian.leapYears === 194 && D.ruleLeapCounts.counts.julian.leapYears === 200,
    'over the same window the Gregorian rule inserts 194 leap days and the Julian 200');
}

// ── 5. the page's shipped bytes ──────────────────────────────────────────────

console.log('\n§5  the page says what the numbers say');
{
  const lit = (needle, why) => ok(html.includes(needle), why + ' [missing: ' + needle + ']');

  lit('365.2423769', 'the page prints the measured March equinox year');
  lit('365.2416317', 'and the June solstice year');
  lit('365.2420170', 'and the September equinox year');
  lit('365.2427378', 'and the December solstice year');
  lit('365.2421909', 'and the mean over all longitudes');
  lit('365.242374', 'and Meeus & Savoie\'s published March value beside it');
  lit('0.0011061', 'the spread in days');
  lit('95.6', 'and in seconds');
  lit('22.5', 'the JPL comparison for the first library');
  lit('2.2', 'and for the second');
  lit('4,205', 'the Gregorian drift against the December solstice');
  lit('1,152', 'and against the June solstice');
  lit('8,121', 'and against the March equinox');
  lit('3,235', 'and against the mean tropical year');
  lit('2,574', 'the recomputation of the NASA figure');
  lit('3,030', 'the recomputation of the Wikipedia mean-tropical figure');
  lit('3,333', 'the recomputation of the USNO figure');
  lit('7,692', 'the recomputation of the Meeus & Savoie equinox figure');
  lit('428', 'the price of the fifth decimal place');
  lit('33, 33, 33, 33, 29, 33, 33, 33', "Tusi's run lengths, written out");
  lit('87.5', 'the attested modal share');
  lit('83.3', 'and the computed one');
  lit('Every one of them is right.', 'the page says the four published figures are all correct rather than picking one');
  lit('297,660', "Madler's rule against the mean");
  lit('5,281', 'and against the March equinox');
  lit('31,885', 'the Revised Julian against the mean');
  lit('6,467', 'and against the March equinox');
  lit('twenty per cent worse', 'the comparison the two reforms make');
  lit('six of the ten pairs', 'the reordering count');
  lit('These are reorderings of things that are genuinely apart.', 'the near-tie objection is answered on the page');
  lit('365.2423893', 'the five-hundred-year-window value, so the epoch sensitivity is exact rather than loose');
  lit('1.1', 'and the size of that shift');
  lit('Ask the four seasons how many leap days to insert.', 'the fork is operable rather than only stated');
  ok(/id="forkq"/.test(html) && /type="range"/.test(html), 'the fork control is a real slider');
  ok(/id="fork-verdict"[^>]*aria-live/.test(html), 'and its verdict announces itself');
  lit('22806269381', 'the continued-fraction term that is rounding rather than astronomy');
  lit('167', 'the lunar fork');
  lit('1,200', 'the range over which 97/400 is the family optimum');
  lit('2,200', 'and the range for 218/900');
  lit('193', 'the observational leap count');
  lit('193.9', 'and what the March equinox year predicts');
  lit('23,560', "the member layer's measurement count");
  lit('1,057', 'the accumulated rotation offset in 2400');
  lit('456', "the agreement count against Borkowski's arithmetic");
  lit('457', 'out of');
  lit('1634', 'and the Jalali year the single disagreement falls on');
  lit('the last year of the window he said it was good for', 'the page says where the disagreement lands');
  lit('Julian day numbers run from noon and civil days from midnight', 'the half-day trap is named on the page');

  // the words that must match the counts
  lit('Twenty-four runs in eight hundred years. Twenty of them are 33 years long, three are 29 and one is 37.',
    'the cycle sentence is written out in words and the words match the histogram');
  lit('Cycle <span class="num">896</span>, where it closes.', 'the close of the transition is stated in the prose');
  lit('Past 896 they never agree again, at any cycle length, ever.', 'and what it means is stated plainly');
  lit('The numbers move and the structure does not', 'the window robustness is stated');

  // the member quotations must be what the members actually say
  const norm = s => s.replace(/<[^>]+>/g, '').replace(/&mdash;/g, '—').replace(/&hellip;/g, '…')
    .replace(/&asymp;/g, '≈').replace(/&nbsp;/g, ' ').replace(/\s+/g, ' ').trim();
  const span = id => {
    const m = html.match(new RegExp('<span id="' + id + '">([\\s\\S]*?)</span>'));
    return m ? norm(m[1]) : null;
  };
  ok(span('q-calendar') === norm(D.members.theYearThatWontDivide.cardNote),
    'the opening blockquote matches that member\'s own card, verbatim');
  ok(norm(D.members.theMachineMadeOfMonths.cardNote).includes(span('q-gears')),
    'the gear blockquote is a verbatim span of that member\'s own card');
  ok(span('q-whichyear') === norm(D.members.theYearThatWontDivide.whichYear),
    'the which-year blockquote matches that member\'s shipped paragraph, verbatim');
  ok(span('q-drift') === norm(D.members.theYearThatWontDivide.driftClaim),
    'the drift blockquote matches that member\'s shipped sentence, verbatim');
  ok(span('q-nineteen') === norm(D.members.theMachineMadeOfMonths.nineteen),
    'the nineteen blockquote matches that member\'s shipped sentence, verbatim');

  // ── the coupling that was missing ─────────────────────────────────────────
  // Section 5 used to be a hand-written list of html.includes() calls. An adversarial
  // pass falsified 73 numbers on the shipped page one at a time and 69 of them went
  // straight through, because anything not on the list was invisible. So instead of
  // listing literals, pull EVERY figure the page marks as a number back out of the
  // shipped bytes and require each one to be something the lab actually computed.
  // A number on the page and nowhere in the computation is now a red layer.
  {
    const marked = [...html.matchAll(/<span class="num">([^<]+)<\/span>/g)].map(m => m[1].trim());
    ok(marked.length > 40, `the page marks ${marked.length} figures as numbers`);

    // the register: every value the lab computes, rendered the way a page would print it
    const reg = new Set();
    const add = v => {
      if (v === null || v === undefined || !Number.isFinite(Number(v))) return;
      const n = Number(v);
      for (const d of [0, 1, 2, 3, 4, 5, 6, 7]) {
        reg.add(n.toFixed(d));
        reg.add(Number(n.toFixed(d)).toLocaleString('en-US'));
        reg.add(Number(n.toFixed(d)).toLocaleString('en-US', { minimumFractionDigits: d }));
      }
      reg.add(String(n));
    };
    const walk = (o, depth = 0) => {
      if (depth > 6 || o === null || o === undefined) return;
      if (typeof o === 'number') return add(o);
      if (typeof o === 'string') return;
      if (Array.isArray(o)) return o.forEach(x => walk(x, depth + 1));
      if (typeof o === 'object') return Object.values(o).forEach(x => walk(x, depth + 1));
    };
    // everything the lab computes, plus the plain integers the prose legitimately uses
    walk({ T: F.TARGETS, P: F.PER_TARGET, C: F.CROSSOVER, TR: F.TRANSITION, R: F.REORDER,
           PL: F.PLACES, M: F.METONIC, O: F.OBSERVED, FA: F.FAMOUS, TU: F.TUSI,
           MA: F.MARGINS, W: F.WINDOWS, H: F.HEADLINE, D });
    for (const r of F.RULES) { add(r.p); add(r.q); add(r.p / r.q); }
    for (const t of F.TARGETS) { add(365 + t.value); add(t.value * 86400); }
    add(F.CROSSOVER.spread * 86400); add(F.CROSSOVER.spread);
    add(1 / Math.abs(97 / 400 - 0.2421896698));           // the constant-year control
    for (const n of [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 17, 19, 20, 22, 26, 29, 30, 31, 33,
                     45, 46, 96, 100, 128, 200, 235, 295, 300, 400, 600, 622, 900, 1079, 1178, 1200,
                     1582, 1600, 1634, 1858, 1923, 2018, 2026, 2029, 2030, 2200, 2255, 2400, 2500, 21.3]) add(n);
    // ranges the prose quotes off the window table
    for (const r of F.WINDOWS.rows) { add(r.gregorianMarch); add(r.gregorianDecember); add(r.cycle33March); }

    const unaccounted = marked.filter(m => !reg.has(m) && !reg.has(m.replace(/,/g, '')));
    ok(unaccounted.length === 0,
      'every figure the page marks as a number is one the lab computed' +
      (unaccounted.length ? ' [unaccounted: ' + unaccounted.join(' | ') + ']' : ''));
  }

  // the kicker counts the members, and the count is the object's, not a typed word
  {
    const WORDS = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight'];
    const n = Object.keys(D.members).length;
    ok(html.toLowerCase().includes(WORDS[n] + ' layers'),
      `the kicker says "${WORDS[n]} layers" and the assembly carries ${n} members`);
    const md = R('src/content/strata/no-year-to-round-to.md');
    for (const m of Object.values(D.members)) ok(md.includes('to: ' + m.slug), `${m.slug} is a declared relates edge`);
    for (const foil of ['the-common-measure', 'why-february-has-28-days']) {
      ok(md.includes('to: ' + foil), `${foil} is declared as a foil rather than left implicit`);
    }
    ok(md.includes('A declared foil, because the algorithm this page runs is that one\'s subject'),
      'and the continued-fraction layer is named as owning the algorithm this page borrows');
  }

  // and every member's verifier is where this layer says it is
  for (const m of Object.values(D.members)) {
    ok(fs.existsSync(path.join(ROOT, m.verifier)), `${m.slug}'s verifier exists at ${m.verifier}`);
    ok(fs.existsSync(path.join(ROOT, m.pageSource)), `${m.slug}'s shipped page exists`);
  }

  // house rules
  ok(!/cdn|googleapis|unpkg|jsdelivr|fonts\.google/i.test(html), 'no third-party host is contacted');
  ok(/role="status"/.test(html) && /aria-live/.test(html), 'the live readouts announce themselves');
  ok(/prefers-reduced-motion/.test(html), 'reduced motion is respected');
  ok(/:focus-visible/.test(html), 'focus is visible');
  ok(/aria-pressed/.test(html), 'the toggles report their state');
  ok(/<canvas/.test(html), 'the figures are canvases rather than pictures of canvases');
  ok(html.trimEnd().endsWith('</html>'), 'the closing tags are present, which they load-bearingly are');
  ok(!/we are the first|nobody has noticed|no one has (?:ever )?linked|unstated anywhere\.|never been (?:published|computed)/i.test(html),
    'the page claims no bare priority; the guard now catches the phrasing this page itself used');
  ok(/arXiv:2605\.02239/.test(html) && /re-derivation/.test(html),
    'and the prior computation of section 1 is cited, in the body and not only in a list');
  ok(/Bromberg/.test(html), 'and the lead it could not close is named as a lead');
  ok(/Attribution, held loosely on purpose/.test(html),
    'the contested historical attribution is disclosed rather than asserted');
  ok(/no direct documentary evidence that the 1079 reform adopted a fixed 33-year cycle/.test(html),
    'and says plainly that the 33-year attribution is undocumented');
  ok(/specialists disagree/.test(html), 'and that specialists disagree rather than picking a side');
  ok(/is the bull's own claim about its authority/.test(html),
    "the bull's Nicaea claim is attributed to the bull rather than asserted as history");
  ok(/reconstructed rather than recovered/.test(html),
    'the Antikythera gear caveat is stated');
  ok(/<h3[^>]*>Sources<\/h3>/.test(html), 'the page carries a sources list');
  for (const s of ['Meeus and D. Savoie', 'Borkowski', 'Akrami', 'Heydari-Malayeri', 'Gajic', 'Freeth', 'Viik',
                   'arXiv:1111.4926', 'astro-ph/0409620', 'Inter gravissimas', 'DE441']) {
    ok(html.includes(s), `the sources list names ${s}`);
  }
  // Borkowski's rule is quoted verbatim and is the rule actually implemented
  ok(/12:00 of the Teheran mean time/.test(html), "Borkowski's rule is quoted verbatim");
  {
    const c = R('research/no-year-to-round-to/ephemeris/compute.mjs');
    ok(c.includes('BORKOWSKI_MERIDIAN = 3.425 * 15'),
      'the implementation takes Teheran mean time as Borkowski does, from his own 3.425 hours');
    ok(/'ae-borkowski-mean'/.test(c) && c.indexOf("'ae-borkowski-mean'") < c.indexOf("'ae-zone-mean'"),
      'and that reading is the headline variant, with the time-zone meridian as a perturbation of it');
    ok(html.includes('3.425 hours'), 'and the page quotes the figure he uses');
    ok(html.includes('51.375 degrees east'), 'and converts it');
  }
  // Madler's date
  ok(F.RULE_BY_KEY.madler.year === '1858', "Madler's rule is dated 1858, the Das Inland publication, not the 1864 Russian report");
  ok(/Das Inland<\/em> at Tartu in 1858/.test(html), 'and the page says where and when');
  {
    const bodyOnly = html.replace(/<blockquote[\s\S]*?<\/blockquote>/g, '');
    ok(!bodyOnly.includes('—'), "no em dash in this layer's own prose");
  }
}

// ── 6. mutations ─────────────────────────────────────────────────────────────

console.log('\n§6  mutations');
let caught = 0;
const MUTATIONS = 10;
function mutation(label, fn) {
  let red = false;
  try { red = fn() === false; } catch { red = true; }
  if (red) { caught++; console.log('  caught: ' + label); }
  else { fail++; problems.push('MUTATION NOT CAUGHT: ' + label); console.log('  MISSED: ' + label); }
}
mutation('the four years are all the same length', () => {
  const v = F.CARDINAL.map(t => t.value);
  return Math.max(...v) - Math.min(...v) === 0;
});
mutation('97/400 is a convergent of the March equinox year after all', () =>
  F.PER_TARGET.march.convergents.some(c => c.p === 97 && c.q === 400));
mutation('the fork is at 30 rather than 31', () => F.CROSSOVER.numeratorForkAt === 30);
mutation('the Gregorian rule is first against the June solstice', () =>
  F.PER_TARGET.june.ranking[0].key === 'gregorian');
mutation('the Revised Julian rule beats the Gregorian at the March equinox', () =>
  1 / Math.abs(218 / 900 - F.TARGET_BY_KEY.march.value) > 1 / Math.abs(97 / 400 - F.TARGET_BY_KEY.march.value));
mutation('the observational runs are 29 years long more often than 33', () =>
  F.OBSERVED.cycleLengthHistogram['29'] > F.OBSERVED.cycleLengthHistogram['33']);
mutation('a rounded 365.2424 target does not give exactly ten thousand years', () =>
  Math.abs(1 / Math.abs(97 / 400 - 0.2424) - 10000) > 1e-6);
mutation("the Borkowski disagreement falls in the middle of his window rather than at its edge", () =>
  F.OBSERVED.borkowski.disagreements.some(d => d.jalali > 1200 && d.jalali < 1600));
mutation('Nowruz lands on 22 March somewhere in the 2018 to 2030 run', () =>
  Object.values(F.OBSERVED.nowruzDates).some(d => d.endsWith('-03-22')));
mutation('the staircases from theory and from scanning differ somewhere', () => {
  for (const t of F.TARGETS) {
    const a = JSON.stringify(ownStaircaseFromTheory(t.value, 2000).map(r => [r.p, r.q]));
    const b = JSON.stringify(ownStaircaseByScan(t.value, 2000).map(r => [r.p, r.q]));
    if (a !== b) return true;
  }
  return false;
});

// ── 7. optionally, the members' own verifiers ────────────────────────────────

// Counted separately, so the headline tally the page prints does not depend on which
// mode this was run in. A failure here still turns the whole run red.
let memberChecks = 0, memberFails = 0;
if (process.argv.includes('--members')) {
  console.log('\n§7  the members\' own checks, re-run');
  for (const m of Object.values(D.members)) {
    memberChecks++;
    try {
      const out = execFileSync('node', [m.verifier], { cwd: ROOT, encoding: 'utf8', timeout: 240000 });
      const tail = out.trim().split('\n').filter(Boolean).slice(-2).join(' | ');
      console.log('  green  ' + m.slug + ': ' + tail.slice(0, 110));
    } catch (e) {
      memberFails++; fail++; problems.push(`${m.slug}: its own verifier did not come back green`);
      console.log('  FAIL   ' + m.slug + ': its own verifier did not come back green');
    }
  }
  console.log(`  ${memberChecks - memberFails}/${memberChecks} member verifiers green`);
}

// ── tally ────────────────────────────────────────────────────────────────────

const total = pass;   // the members' own runs are tallied separately, above
console.log('\n' + '-'.repeat(64));
console.log('ASSERTIONS ' + pass + '   FAILURES ' + fail + '   MUTATIONS CAUGHT ' + caught + '/' + MUTATIONS);
if (problems.length) { console.log('\nproblems:'); problems.forEach(p => console.log('  - ' + p)); }

const claimed = html.match(/Offline: (\d+) checks/);
if (!claimed) {
  console.log('\nthe page does not print a check count');
  process.exitCode = 1;
} else if (Number(claimed[1]) !== total) {
  console.log('\nthe page says "Offline: ' + claimed[1] + ' checks" and this run made ' + total + '.');
  console.log('Update public/strata/no-year-to-round-to/index.html to say ' + total + '.');
  process.exitCode = 1;
} else {
  console.log('the page\'s printed count of ' + total + ' checks matches this run.');
}
if (fail > 0) process.exitCode = 1;
