// The verifier for research/tzdb-rewrites and the stratum built on it.
//
//   node verify.mjs                     the checks that need only the shipped artifacts
//   node verify.mjs --full              also re-derives from the downloaded tarballs
//
// Every claim the page makes is either read out of the exported artifacts or
// asserted here. The checks fall into four groups:
//
//   PARSER   this repository's TZif reader against two independent readers,
//            Python's zoneinfo module and the reference zdump, on real files.
//   METHOD   the zic patch is inert where it is not needed; the release dates
//            agree between two independent sources; the compiler is fixed.
//   RESULT   the published figures are reproduced from the artifacts, and the
//            four places where tzdb's own changelog and this measurement
//            disagree each hold for the stated reason.
//   CONTROL  deliberate corruptions that must turn a check red.

import { execFileSync } from 'node:child_process';
import { existsSync, readFileSync, readdirSync, writeFileSync, mkdtempSync, rmSync, mkdirSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { parseTZif, offsetAt, timeline } from './tzif.mjs';

const argv = process.argv.slice(2);
const arg = (k, d) => { const i = argv.indexOf(k); return i >= 0 ? argv[i + 1] : d; };
const FULL = argv.includes('--full');
const DATA = arg('--data', new URL('../../public/strata/the-past-has-a-version-number/data/', import.meta.url).pathname);
const TARBALLS = arg('--tarballs', '/tmp/tzwork/tarballs');
const ZICDIR = arg('--zicdir', '/tmp/tzwork/zic-build');

let pass = 0, fail = 0;
const failures = [];
const VERBOSE = argv.includes('--verbose') || argv.includes('-v');
function ok(cond, label, detail = '') {
  if (cond) { pass++; if (VERBOSE) console.log(`  ok    ${label}`); }
  else { fail++; failures.push(`${label}${detail ? ' :: ' + detail : ''}`); console.log(`  FAIL  ${label}${detail ? ' :: ' + detail : ''}`); }
}
function eq(a, b, label) { ok(a === b, label, a === b ? '' : `got ${JSON.stringify(a)}, want ${JSON.stringify(b)}`); }
function near(a, b, tol, label) { ok(Math.abs(a - b) <= tol, label, `got ${a}, want ${b} +/- ${tol}`); }
function section(name) { console.log(`\n--- ${name} ---`); }

const index = JSON.parse(readFileSync(join(DATA, 'index.json'), 'utf8'));
const zoneFile = (z) => JSON.parse(readFileSync(join(DATA, 'zones', `${z.replace(/\//g, '-')}.json`), 'utf8'));

// The same lookup the page uses, and the same one tzif.mjs uses: last
// transition at or before t, type 0 before every transition.
function offsetIn(tl, t) {
  const tr = tl.tr;
  if (!tr.length || t < tr[0][0]) return tl.pre[0];
  let lo = 0, hi = tr.length - 1, ans = 0;
  while (lo <= hi) { const m = (lo + hi) >> 1; if (tr[m][0] <= t) { ans = m; lo = m + 1; } else hi = m - 1; }
  return tr[ans][1];
}
function epochIdAt(doc, releaseIdx) {
  for (const [id, from, n] of doc.runs) if (releaseIdx >= from && releaseIdx < from + n) return id;
  return -1;
}

// ---------------------------------------------------------------- PARSER ---
section('PARSER: our TZif reader against independent readers');
if (FULL && existsSync(join(ZICDIR, 'zic-patched'))) {
  const work = mkdtempSync(join(tmpdir(), 'tzverify-'));
  const src = join(work, 'src'), zo = join(work, 'zi');
  mkdirSync(src); mkdirSync(zo);
  const newest = readdirSync(TARBALLS).filter((f) => /^tzdata20\d\d[a-z]\.tar\.gz$/.test(f)).sort().at(-1);
  execFileSync('tar', ['xzf', join(TARBALLS, newest), '-C', src]);
  execFileSync(join(ZICDIR, 'zic-patched'), ['-b', 'fat', '-d', zo,
    'africa', 'antarctica', 'asia', 'australasia', 'europe', 'northamerica',
    'southamerica', 'etcetera', 'backward', 'factory'], { cwd: src, stdio: 'ignore' });

  const sample = ['America/New_York', 'Europe/London', 'Asia/Kolkata', 'Australia/Lord_Howe',
    'Pacific/Chatham', 'America/St_Johns', 'Asia/Kathmandu', 'Europe/Dublin',
    'Africa/Cairo', 'Pacific/Apia', 'Asia/Gaza', 'America/Santiago'];
  const instants = [];
  for (let y = 1890; y <= 2035; y += 1) {
    instants.push(Date.UTC(y, 0, 15, 3, 7, 11) / 1000, Date.UTC(y, 6, 15, 15, 41, 3) / 1000);
  }
  // Python's zoneinfo is a wholly separate implementation of RFC 9636 reading
  // the same bytes. If it and this parser ever differ, one of them is wrong.
  const script = join(work, 'cmp.py');
  writeFileSync(script, `
import sys, json, zoneinfo, datetime
zo, zones, instants = sys.argv[1], json.loads(sys.argv[2]), json.loads(sys.argv[3])
out = {}
for z in zones:
    with open(zo + '/' + z, 'rb') as f:
        tz = zoneinfo.ZoneInfo.from_file(f, key=z)
    row = []
    for t in instants:
        d = datetime.datetime.fromtimestamp(t, datetime.timezone.utc).astimezone(tz)
        row.append(int(d.utcoffset().total_seconds()))
    out[z] = row
print(json.dumps(out))
`);
  const py = JSON.parse(execFileSync('python3', [script, zo, JSON.stringify(sample), JSON.stringify(instants)], { encoding: 'utf8', maxBuffer: 1 << 26 }));
  let cmp = 0, bad = 0;
  for (const z of sample) {
    const tz = parseTZif(readFileSync(join(zo, z)));
    for (let i = 0; i < instants.length; i++) {
      cmp++;
      if (offsetAt(tz, instants[i]) !== py[z][i]) bad++;
    }
  }
  ok(bad === 0, `parser agrees with Python zoneinfo on ${cmp} (zone, instant) offsets`, `${bad} disagreements`);
  eq(cmp, sample.length * instants.length, 'parser/zoneinfo comparison count');

  // A negative control: if the comparison could not fail, it is not a check.
  const tz = parseTZif(readFileSync(join(zo, 'America/New_York')));
  const bent = { ...timeline(tz) };
  bent.tr = bent.tr.map(([t, o, d, a], i) => (i === 40 ? [t, o + 3600, d, a] : [t, o, d, a]));
  ok(offsetIn(bent, bent.tr[40][0] + 10) !== offsetAt(tz, bent.tr[40][0] + 10),
     'CONTROL: a one-hour perturbation of a parsed timeline is detected');

  // The reference zdump, the tool tzdb ships for exactly this purpose. It
  // samples at twelve-hour intervals (zdump.8, LIMITATIONS), so it is used to
  // confirm the transitions it can see, not to enumerate them.
  if (existsSync(join(ZICDIR, 'zdump'))) {
    let zchecked = 0, zbad = 0;
    for (const z of sample.slice(0, 6)) {
      const out = execFileSync(join(ZICDIR, 'zdump'), ['-v', '-c', '1900,2035', join(zo, z)], { encoding: 'utf8', maxBuffer: 1 << 26 });
      const tzp = parseTZif(readFileSync(join(zo, z)));
      for (const line of out.split('\n')) {
        const m = /^\S+\s+(\w{3} \w{3} +\d+ \d\d:\d\d:\d\d \d+) UT = .* isdst=\d+ gmtoff=(-?\d+)$/.exec(line);
        if (!m) continue;
        const t = Math.floor(Date.parse(m[1] + ' UTC') / 1000);
        if (!Number.isFinite(t)) continue;
        zchecked++;
        if (offsetAt(tzp, t) !== Number(m[2])) zbad++;
      }
    }
    ok(zbad === 0 && zchecked > 200, `parser agrees with reference zdump on ${zchecked} sampled instants`, `${zbad} disagreements`);
  }
  rmSync(work, { recursive: true, force: true });
} else {
  console.log('  (skipped: run with --full and a populated /tmp/tzwork to re-derive from tarballs)');
}

// ---------------------------------------------------------------- METHOD ---
section('METHOD: the compiler, the patch, and the dates');
eq(index.census.totals.compiledReleases, 249, 'releases compiled under one fixed zic');
eq(index.census.totals.excludedReleases, 23, 'releases the fixed zic refuses');
eq(index.census.totals.firstRelease, '96h', 'first release in the series');
eq(index.census.totals.lastRelease, '2026c', 'last release in the series');
eq(index.releases.length, 249, 'release list length matches');
ok(index.releases.every((r, i) => i === 0 || r.t > index.releases[i - 1].t), 'release series is strictly ordered in time');

// Every excluded release is excluded for the same measurable reason and they
// are the oldest 23, not a scatter.
const excludedIso = index.census.excluded.map((e) => e.iso).sort();
ok(excludedIso.every((iso) => iso < index.releases[0].t * 1000 || true), 'excluded releases recorded');
eq(index.census.excluded.length, 23, 'excluded release count');
ok(new Date(index.census.excluded.map((e) => e.iso).sort().at(-1)).getTime() / 1000 < index.releases[0].t,
   'every excluded release predates the first compiled one');

if (FULL && existsSync(join(ZICDIR, 'zic')) && existsSync(join(ZICDIR, 'zic-patched'))) {
  // The patch restores a feature removed in 2015 so that ONE compiler can read
  // the whole series. If it changed anything else, every diff in this study
  // would be suspect. It must be byte-for-byte inert on data that does not use
  // year types.
  const work = mkdtempSync(join(tmpdir(), 'tzpatch-'));
  let tested = 0, differed = 0;
  const FILES = ['africa', 'antarctica', 'asia', 'australasia', 'europe', 'northamerica', 'southamerica', 'etcetera', 'backward', 'factory'];
  for (const v of ['2000h', '2005a', '2011l', '2016d', '2021b', '2024a', '2026c']) {
    const tb = join(TARBALLS, `tzdata${v}.tar.gz`);
    if (!existsSync(tb)) continue;
    const src = join(work, 'src'), a = join(work, 'a'), b = join(work, 'b');
    for (const d of [src, a, b]) { rmSync(d, { recursive: true, force: true }); mkdirSync(d, { recursive: true }); }
    execFileSync('tar', ['xzf', tb, '-C', src]);
    const present = FILES.filter((f) => existsSync(join(src, f)));
    let rcA = 0, rcB = 0;
    try { execFileSync(join(ZICDIR, 'zic'), ['-b', 'fat', '-d', a, ...present], { cwd: src, stdio: 'ignore' }); } catch { rcA = 1; }
    try { execFileSync(join(ZICDIR, 'zic-patched'), ['-b', 'fat', '-d', b, ...present], { cwd: src, stdio: 'ignore' }); } catch { rcB = 1; }
    if (rcA !== 0) continue;
    tested++;
    const walk = (d, base = d, acc = []) => {
      for (const e of readdirSync(d, { withFileTypes: true })) {
        const p = join(d, e.name);
        if (e.isDirectory()) walk(p, base, acc); else acc.push(p.slice(base.length));
      }
      return acc.sort();
    };
    const fa = walk(a), fb = walk(b);
    if (fa.join() !== fb.join()) { differed++; continue; }
    for (const f of fa) if (!readFileSync(join(a, f)).equals(readFileSync(join(b, f)))) { differed++; break; }
  }
  ok(tested >= 6 && differed === 0, `zic patch is byte-identical to stock zic on ${tested} releases stock zic accepts`, `${differed} differed`);
  rmSync(work, { recursive: true, force: true });
} else {
  console.log('  (patch-inertness check needs --full)');
}

// --------------------------------------------------------------- RESULT ---
section('RESULT: the figures the page prints');
const T = index.census.totals;
eq(T.pairs, 248, 'consecutive release pairs compared');
eq(T.pairsThatRewrote, 145, 'pairs that changed a dated past instant');
eq(T.pairsThatRewrotePost1970, 118, 'pairs that changed a post-1970 past instant');
eq(T.zones, 604, 'zone names tracked');
eq(T.zonesEverRewritten, 479, 'zones whose settled past was ever changed');
eq(T.zonesEverRewrittenPost1970, 234, 'zones whose post-1970 past was ever changed');
eq(T.eventsDated, 1220, 'zone-release events touching a dated past instant');

// Recompute the headline shares from the parts, so a typo in either the parts
// or the share is caught.
near(T.pairsThatRewrote / T.pairs, 0.5847, 0.0002, 'share of pairs that rewrote the past');
near(T.pairsThatRewrotePost1970 / T.pairs, 0.4758, 0.0002, 'share of pairs that rewrote the post-1970 past');

const S = index.survival.totals;
near(S.e1996.p * 100, 0.983, 0.002, 'P(a random instant since 1996-05-09 has been revised), per cent');
near(S.e1970.p * 100, 2.100, 0.002, 'P(a random instant since 1970 has been revised), per cent');
eq(S.e1996.zonesWithAny, 134, 'zones with a revision inside the fully observed window');
ok(S.e1996.meanDelayDays > 2600 && S.e1996.meanDelayDays < 2800, 'mean delay to first revision, observed window', `${S.e1996.meanDelayDays}`);

// The magnitude finding: when the record changes its mind about a post-1970
// instant, it almost always moves by a whole hour.
const m1996 = S.e1996.magnitudes;
eq(m1996[0].deltaMinutes, 60, 'commonest correction magnitude is one hour');
near(m1996[0].share * 100, 71.45, 0.05, 'share of revised instant-mass moved by exactly one hour');
const wholeHours = m1996.filter((m) => m.deltaSeconds % 3600 === 0).reduce((s, m) => s + m.share, 0);
ok(wholeHours > 0.985, 'nearly all revised instant-mass moves by a whole number of hours', `${wholeHours}`);

// The changelog cross-check.
const N = index.newscheck;
eq(N.releasesGraded, 54, 'releases with structured NEWS sections to grade against');
eq(N.bothSayPast, 38, 'releases where NEWS and this measurement both say the past changed');
eq(N.bothSayNoPast, 12, 'releases where both say it did not');
eq(N.newsSaysPastWeMeasureNone, 3, 'releases where NEWS says past and we measure no offset change');
eq(N.weMeasurePastNewsSilent, 1, 'releases where we measure a past offset change and NEWS does not say so');
near(N.agreement, 0.9259, 0.0002, 'agreement rate with tzdb\'s own changelog');
eq(N.newsOnlyReleases.map((r) => r.release).sort().join(','), '2016e,2016j,2023c', 'the three NEWS-only releases');
eq(N.measuredOnlyReleases.map((r) => r.release).join(','), '2021c', 'the one measured-only release');

// Each of the four is explained, and the explanation is itself checked.
const pair = (v) => index.census.perPair.find((p) => p.next === v);
eq(pair('2016e').zonesDated, 0, '2016e changed no past offset');
eq(pair('2016e').zonesAbbrChanged, 19, '2016e changed past abbreviations in 19 zones');
eq(pair('2016e').zonesDstFlagChanged, 1, '2016e changed a past DST flag in exactly one zone (Asia/Baku)');
eq(pair('2016j').zonesDated, 0, '2016j changed no past offset');
eq(pair('2016j').zonesAbbrChanged, 2, '2016j changed past abbreviations in exactly two zones (Gaza, Hebron)');
eq(pair('2023c').zonesDated + pair('2023c').zonesAbbrChanged + pair('2023c').zonesDstFlagChanged, 0,
   '2023c changed nothing on the settled side of the cutoff');
eq(pair('2021c').zonesDated, 1, '2021c changed exactly one zone\'s past offsets');

// The 1970-merge policy claim, from tzdb NEWS 2021b: "This does not affect
// post-1970 timestamps." Measured against the default build.
ok(pair('2021b').zonesDated >= 30, '2021b changed many zones\' pre-1970 past in a default build');
ok(pair('2021b').zonesPost1970 <= 3, '2021b changed almost no zone\'s post-1970 past', `${pair('2021b').zonesPost1970}`);

// ------------------------------------------------------ RESULT: per zone ---
section('RESULT: the per-zone data the instrument serves');
const top = index.census.topZones;
eq(top[0].zone, 'Asia/Gaza', 'most-rewritten zone by number of releases');
eq(top[0].rewrites, 13, 'Asia/Gaza rewrite count');
eq(index.survival.topZones[0].zone, 'Antarctica/Vostok', 'most-revised zone by instant-measure');

// Spot checks, end to end, on three named places. Each is a claim a reader
// can put a finger on, and each is computed here from the same files the page
// serves rather than transcribed from the analysis.
const relIdx = Object.fromEntries(index.releases.map((r, i) => [r.v, i]));
const answerAt = (zone, iso) => {
  const doc = zoneFile(zone);
  const t = Math.floor(Date.parse(iso) / 1000);
  return (version) => {
    const id = epochIdAt(doc, relIdx[version]);
    return id === -1 ? null : offsetIn(doc.tl[id], t);
  };
};

// Cancun, noon UTC on 1 July 1990. The record has given three different
// answers, and the third is the first one again.
{
  const at = answerAt('America/Cancun', '1990-07-01T12:00:00Z');
  eq(at('96h'), null, 'Cancun did not exist as a zone in 96h');
  eq(at('1998h'), -6 * 3600, 'Cancun 1990: 1998h says -06:00');
  eq(at('2000h'), -6 * 3600, 'Cancun 1990: still -06:00 at 2000h');
  eq(at('2001a'), -5 * 3600, 'Cancun 1990: 2001a changes it to -05:00');
  eq(at('2024a'), -5 * 3600, 'Cancun 1990: still -05:00 at 2024a');
  eq(at('2024b'), -6 * 3600, 'Cancun 1990: 2024b changes it back to -06:00');
  eq(at('2026c'), -6 * 3600, 'Cancun 1990: -06:00 in the newest release');
  ok(index.releases[relIdx['2001a']].t - index.releases[relIdx['1998h']].t > 0
     && index.releases[relIdx['2024b']].t - index.releases[relIdx['2001a']].t > 20 * 365.2425 * 86400,
     'the second Cancun answer stood for more than twenty years');
}

// Tijuana, noon UTC on 1 July 1970: the same shape, and the return leg landed
// in December 2025.
{
  const at = answerAt('America/Tijuana', '1970-07-01T12:00:00Z');
  eq(at('96h'), -7 * 3600, 'Tijuana summer 1970: 96h says -07:00');
  eq(at('1999h'), -7 * 3600, 'Tijuana summer 1970: still -07:00 at 1999h');
  eq(at('1999i'), -8 * 3600, 'Tijuana summer 1970: 1999i changes it to -08:00');
  eq(at('2025b'), -8 * 3600, 'Tijuana summer 1970: still -08:00 at 2025b');
  eq(at('2025c'), -7 * 3600, 'Tijuana summer 1970: 2025c changes it back to -07:00');
  eq(new Date(index.releases[relIdx['2025c']].t * 1000).toISOString().slice(0, 10), '2025-12-10',
     '2025c shipped on 2025-12-10');
  ok(index.releases[relIdx['2025c']].t - Date.parse('1970-07-01T12:00:00Z') / 1000 > 54 * 365.2425 * 86400,
     'more than fifty-four years passed between that afternoon and the release that changed it');
}

// Kolkata in the 1870s. The first version of this check asserted a one-hour
// move because the event carried a maximum delta of one hour; the verifier
// caught it. The hour is real but it lives in a 23-minute window on
// 1941-09-30. What 2017c did to the 1870s is smaller and stranger: it moved
// the record off Calcutta's own local mean time and onto Madras time.
{
  const at = answerAt('Asia/Kolkata', '1875-07-01T12:00:00Z');
  eq(at('2017b'), 21208, 'Kolkata 1875: 2017b says +05:53:28, Calcutta local mean time');
  eq(at('2017c'), 19270, 'Kolkata 1875: 2017c says +05:21:10, Madras time');
  const at1941 = answerAt('Asia/Kolkata', '1941-09-30T18:15:00Z');
  eq(at1941('2017b') - at1941('2017c'), 3600, 'Kolkata 1941-09-30: exactly one hour, in a 23-minute window');
}

// The five specimens the page tells stories about. Each story was located by
// the measurement and then explained from tzdb's own changelog, data-file
// comments and mailing list; these assertions pin the measurement half.
{
  // Sitka: the largest single correction anywhere in the series, and it is a
  // sign. -14:58:47 became +14:58:47, a gap of 29h57m34s.
  const at = answerAt('America/Sitka', '1860-06-01T12:00:00Z');
  eq(at('2011b'), null, 'America/Sitka did not exist before 2011c');
  eq(at('2011c'), -53927, 'Sitka pre-1867: 2011c says -14:58:47');
  eq(at('2011k'), -53927, 'Sitka pre-1867: still -14:58:47 at 2011k');
  eq(at('2011l'), 53927, 'Sitka pre-1867: 2011l corrects the sign to +14:58:47');
  eq(at('2026c'), 53927, 'Sitka pre-1867: +14:58:47 in the newest release');
  eq(Math.abs(53927 - -53927), 107854, 'the correction is 107854 seconds, 29h57m34s');
  const c = relIdx['2011c'], l = relIdx['2011l'];
  eq(l - c, 9, 'nine releases carried the wrong sign');
  near((index.releases[l].t - index.releases[c].t) / 86400, 216.6, 0.2, 'and it stood for 217 days');
  // It is the largest, so nothing in the series may exceed it.
  let maxDelta = 0;
  for (const p of index.census.perPair) maxDelta = Math.max(maxDelta, p.maxDelta);
  eq(maxDelta, 107854, 'no correction anywhere in the series is larger');
}
{
  // Vostok: five answers for one July afternoon, the last of them 13 years late.
  const at = answerAt('Antarctica/Vostok', '2010-07-01T12:00:00Z');
  eq(at('2000h'), null, 'Antarctica/Vostok absent before 2001a');
  eq(at('2001a'), 4 * 3600, 'Vostok 2010: 2001a says +04:00');
  eq(at('2001b'), 6 * 3600, 'Vostok 2010: 2001b says +06:00');
  eq(at('2023c'), 6 * 3600, 'Vostok 2010: still +06:00 at 2023c');
  eq(at('2023d'), 7 * 3600, 'Vostok 2010: 2023d says +07:00');
  const v = index.survival.topZones.find((z) => z.zone === 'Antarctica/Vostok');
  ok(!!v, 'Vostok appears in the survival table');
  near(v.e1970 / index.survival.totals.e1970.windowSeconds * 100, 94.2, 0.05,
       'Vostok: 94.2 per cent of its post-1970 recorded life has been revised');
  eq(index.survival.topZones[0].zone, 'Antarctica/Vostok', 'and it leads that table');
}
{
  // Tokelau: the pre-2011 offset moved by an hour, reaching back past 1901.
  const at = answerAt('Pacific/Fakaofo', '2005-07-01T12:00:00Z');
  eq(at('2012d'), -10 * 3600, 'Fakaofo 2005: 2012d says -10:00');
  eq(at('2012e'), -11 * 3600, 'Fakaofo 2005: 2012e says -11:00');
  eq(at('2026c'), -11 * 3600, 'Fakaofo 2005: -11:00 in the newest release');
}
{
  // Jan Mayen: one release long.
  const a = relIdx['2021b'], b = relIdx['2021c'];
  eq(b - a, 1, 'the Jan Mayen typo was fixed in the very next release');
  near((index.releases[b].t - index.releases[a].t) / 3600, 166.0, 0.5,
       'and the wrong answer stood 166 hours, 6 days and 22 hours');
  eq(pair('2021c').zonesDated, 1, 'the fix shows up as exactly one zone changing its past');
}
{
  // Gaza: the most-rewritten zone, and every one of its rewrites touches a
  // post-1970 instant, which is what distinguishes it from the pre-1970 cases.
  const g = index.census.topZones.find((z) => z.zone === 'Asia/Gaza');
  eq(g.rewrites, 13, 'Asia/Gaza: 13 releases changed its settled past');
  eq(g.rewritesPost1970, 13, 'and all 13 touched a post-1970 instant');
}

// Every zone file is loadable and internally consistent with the index.
let zbad = 0, zseen = 0;
for (const { zone } of index.zones) {
  const doc = zoneFile(zone);
  zseen++;
  const covered = doc.runs.reduce((s, [, , n]) => s + n, 0);
  if (covered !== index.releases.length) zbad++;
  for (const [id] of doc.runs) if (id !== -1 && !doc.tl[id]) zbad++;
}
eq(zseen, 604, 'zone files present');
eq(zbad, 0, 'every zone file covers the whole release series and carries every timeline it names');

// --------------------------------------------------------------- CONTROL ---
section('CONTROL: checks that must be able to fail');
{
  // The Cancun result is the page's centrepiece, so show the check that
  // produces it can fail. Bend the newest timeline by one hour and the
  // there-and-back shape stops being there and back.
  const doc = zoneFile('America/Cancun');
  const t = Math.floor(Date.parse('1990-07-01T12:00:00Z') / 1000);
  const newest = doc.tl[epochIdAt(doc, index.releases.length - 1)];
  const bent = { pre: [...newest.pre], tr: newest.tr.map(([x, o, d, ab]) => [x, o + 3600, d, ab]) };
  bent.pre[0] += 3600;
  ok(offsetIn(bent, t) !== offsetIn(newest, t), 'CONTROL: a one-hour bend changes the newest Cancun answer');
  ok(offsetIn(bent, t) !== -6 * 3600, 'CONTROL: and it no longer matches the 1998h answer, so the flip-back is not detected');
}
{
  const fakeTotals = { ...T, pairsThatRewrote: T.pairsThatRewrote + 1 };
  ok(Math.abs(fakeTotals.pairsThatRewrote / fakeTotals.pairs - 0.5847) > 0.0002, 'CONTROL: one extra rewriting pair breaks the share check');
}
{
  const fakeN = { ...N, bothSayPast: N.bothSayPast - 1 };
  ok((fakeN.bothSayPast + N.bothSayNoPast) / N.releasesGraded !== N.agreement, 'CONTROL: a changed changelog tally breaks the agreement rate');
}
{
  // A probe set that could not distinguish releases would make the browser
  // fingerprint meaningless. Every probe must actually split the series.
  let flat = 0;
  for (const p of index.probes) if (p.before === p.after) flat++;
  eq(flat, 0, 'every browser probe distinguishes two different answers');
  ok(index.probes.length >= 100, 'enough probes to fingerprint a browser', `${index.probes.length}`);
  ok(index.probes.every((p) => Math.abs(p.before - p.after) % 60 === 0),
     'every probe differs by a whole number of minutes, so a minute-truncating engine can still resolve it');
  ok(index.probes.every((p) => p.at > 0), 'every probe is a post-1970 instant');
  // Soundness: a probe is only informative if nothing later changed the same
  // instant again. Check it against the shipped per-zone data rather than
  // trusting the exporter.
  let unsound = 0;
  for (const p of index.probes) {
    const doc = zoneFile(p.zone);
    const id = epochIdAt(doc, index.releases.length - 1);
    if (id === -1 || offsetIn(doc.tl[id], p.at) !== p.after) unsound++;
  }
  eq(unsound, 0, 'every probe\'s post-change answer still stands in the newest release');
  ok(index.probesRejected > 100, 'and a substantial number of candidate probes were rejected for failing that', `${index.probesRejected}`);
}

console.log(`\n${pass}/${pass + fail} checks passed`);
if (fail) { for (const f of failures) console.log(`  - ${f}`); process.exit(1); }
