#!/usr/bin/env node
/* research/tight-connection/verify.mjs — attack the tool.
 *
 * Seven families, and only the first is a unit test:
 *
 *   1  the codec round-trips, including the values that break a naive varint
 *   2  the committed payload is internally consistent, on EVERY leg rather than
 *      a sample, because a sample is where a broken encoder hides
 *   3  the join counts what it claims, on hand-built days whose answer is known
 *      by arithmetic, including the day-boundary cases
 *   4  the page says what the code does: the refusal table, the sources, the
 *      bound, the dash rule, the card's real pixels
 *   5  a SECOND derivation from the raw federal record, by code that never sees
 *      the payload, compared date by date. This is the only family that could
 *      catch the whole pipeline being wrong, and it is why the others are not
 *      enough on their own
 *   6  negative controls: the checks are shown failing on purpose, so that a
 *      green run means something
 *   7  the page prints this suite's own count, and it has to match
 *
 *   node research/tight-connection/verify.mjs             # families 1-4, 6, 7
 *   node research/tight-connection/verify.mjs --fetch     # adds family 5 (~36 MB)
 *   node research/tight-connection/verify.mjs --selftest  # prove the harness reports a failure
 */
import fs from 'node:fs';
import path from 'node:path';
import zlib from 'node:zlib';
import { execFileSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import {
  decodeIndex, decodeShard, readDays, connect, boundFromInbound, curve, marks, byMonth,
  readVarint, writeVarint, zig, zag, parseFlight, hhmm, dayToDate, gapBetween,
  MAGIC, VERSION, OPERATED, CANCELLED, DIVERTED_LATE, DIVERTED_AWAY,
} from '../../public/tools/tight-connection/engine.mjs';

const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, '../..');
const TOOL = path.join(ROOT, 'public/tools/tight-connection');
const DATA = path.join(TOOL, 'data');
const FETCH = process.argv.includes('--fetch');
const SELFTEST = process.argv.includes('--selftest');

let pass = 0, fail = 0;
const failures = [];
const log = [];
const section = (t) => log.push(`\n  ${t}`);
const ok = (cond, msg) => {
  if (cond) { pass++; log.push(`    ok   ${msg}`); }
  else { fail++; failures.push(msg); log.push(`    FAIL ${msg}`); }
};
const eq = (a, b, msg) => ok(a === b, `${msg}  (got ${JSON.stringify(a)}, want ${JSON.stringify(b)})`);

const asBuf = (p) => { const b = fs.readFileSync(p); return b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength); };

/* ================= 1. the codec ================= */
section('1 - the codec');
{
  for (const v of [0, 1, 127, 128, 129, 255, 256, 16383, 16384, 100000, 4294967295]) {
    const out = []; writeVarint(out, v);
    const [back, at] = readVarint(Uint8Array.from(out), 0);
    ok(back === v && at === out.length, `varint round-trips ${v} in ${out.length} byte(s)`);
  }
  const multi = [];
  for (const v of [3, 300, 70000]) writeVarint(multi, v);
  let p = 0; const got = [];
  for (let i = 0; i < 3; i++) { const [v, q] = readVarint(Uint8Array.from(multi), p); got.push(v); p = q; }
  eq(JSON.stringify(got), '[3,300,70000]', 'varints decode in sequence without drift');

  for (const v of [0, -1, 1, -63, 64, -1000, 1000, -32768, 32767]) {
    eq(zag(zig(v)), v, `zigzag round-trips ${v}`);
    ok(zig(v) >= 0, `zigzag of ${v} is non-negative, so it can be written as a varint`);
  }

  eq(JSON.stringify(parseFlight('DL 1234')), '{"carrier":"DL","number":1234}', 'parseFlight reads "DL 1234"');
  eq(JSON.stringify(parseFlight('dl1234')), '{"carrier":"DL","number":1234}', 'parseFlight is case and space insensitive');
  eq(JSON.stringify(parseFlight('B6 0072')), '{"carrier":"B6","number":72}', 'parseFlight strips leading zeros and allows a digit in the code');
  eq(parseFlight('Delta 1234'), null, 'parseFlight refuses a name it cannot key on');
  eq(parseFlight('DL'), null, 'parseFlight refuses a carrier with no number');
  eq(parseFlight('1234'), null, 'parseFlight refuses a bare number');
  eq(hhmm(0), '00:00', 'hhmm at midnight');
  eq(hhmm(1439), '23:59', 'hhmm at the last minute of the day');
  eq(dayToDate(0, '2025-07-01'), '2025-07-01', 'dayToDate at the epoch');
  eq(dayToDate(364, '2025-07-01'), '2026-06-30', 'dayToDate across a year, leap rules and all');
  eq(gapBetween(1400, 40), 80, 'gapBetween wraps around midnight');
  eq(gapBetween(600, 700), 100, 'gapBetween inside one day');
}

/* ================= 2. the committed payload ================= */
section('2 - the committed payload');
ok(fs.existsSync(path.join(DATA, 'index.bin')), 'the index is committed at data/index.bin');
const IDX = decodeIndex(asBuf(path.join(DATA, 'index.bin')));
const H = IDX.header;
const shardFiles = fs.readdirSync(path.join(DATA, 's')).filter((f) => f.endsWith('.bin'));
{
  const raw = fs.readFileSync(path.join(DATA, 'index.bin'));
  eq(new DataView(asBuf(path.join(DATA, 'index.bin'))).getUint32(0, false), MAGIC, 'the index carries the magic');
  eq(new Uint8Array(asBuf(path.join(DATA, 'index.bin')))[4], VERSION, 'the index carries the version the decoder expects');
  ok(zlib.gzipSync(raw, { level: 9 }).length < 40_000, `the first load is ${(zlib.gzipSync(raw, { level: 9 }).length / 1000).toFixed(0)} kB gzipped`);
  ok(H.windowStart < H.windowEnd, 'the window runs forwards');
  ok(H.carriers.length >= 8, `${H.carriers.length} marketing carriers are covered`);
  ok(H.legs > 20000, `${H.legs.toLocaleString()} legs are in the payload`);
  ok(shardFiles.length > 100, `${shardFiles.length} shards were written`);
  eq((H.shards || []).length, shardFiles.length, 'the index lists exactly the shards that exist on disk');
  eq((H.shards || []).filter((n) => !shardFiles.includes(n + '.bin')).length, 0,
    'every shard the index names is really there, so the page never asks for one that is not');
  ok(!IDX.hasShard('DL', 99999) && IDX.hasShard(H.carriers[0], 1) !== undefined,
    'the index can answer "not in the record" without a request, which is what keeps a mistyped flight number out of the browser console');

  let legsSeen = 0, daysSeen = 0;
  let badDays = 0, badOrder = 0, badRange = 0, badStatus = 0, badSched = 0, badPlace = 0, badFloor = 0, badTail = 0;
  let biggestGz = 0, biggestName = '';
  for (const f of shardFiles) {
    const carrier = f.slice(0, f.indexOf('-'));
    const buf = asBuf(path.join(DATA, 's', f));
    const gz = zlib.gzipSync(Buffer.from(buf), { level: 9 }).length;
    if (gz > biggestGz) { biggestGz = gz; biggestName = f; }
    const dir = decodeShard(buf, H, carrier);
    let end = dir.blocksAt;
    for (const rec of dir.legs) {
      legsSeen++;
      const d = readDays(buf, dir.blocksAt, rec.offset);
      daysSeen += d.n;
      if (d.n !== rec.days) badDays++;
      if (d.n < H.minDays) badFloor++;
      for (let i = 1; i < d.n; i++) if (d.day[i] <= d.day[i - 1]) badOrder++;
      for (let i = 0; i < d.n; i++) {
        if (d.day[i] < 0 || d.day[i] > 400) badRange++;
        if (d.st[i] > 3) badStatus++;
        if (Math.abs(d.arr[i]) > 1000 || Math.abs(d.dep[i]) > 1000) badRange++;
        if (d.st[i] === CANCELLED || d.st[i] === DIVERTED_AWAY) { if (d.arr[i] !== 0) badStatus++; }
      }
      if (!(rec.schedDep >= 0 && rec.schedDep < 1440 && rec.schedArr >= 0 && rec.schedArr < 1440)) badSched++;
      if (!rec.origin || !rec.dest || rec.origin.length !== 3 || rec.dest.length !== 3 || rec.origin === rec.dest) badPlace++;
      end = Math.max(end, d.end);
    }
    if (end !== buf.byteLength) badTail++;
  }
  eq(legsSeen, H.legs, 'every leg the header counts is present in a shard and decodes');
  eq(daysSeen, H.daysCovered, 'the day series together hold exactly the flights the header claims');
  /* Note d233a7 (2026-09-04): the page printed header.rows (7,784,304) as the
     flight count while the day series, covered plus dropped, hold 7,784,303. The
     month totals resolve every flight to dead or arrived, so their sum is an
     independent count of the same set, and the page must print that set. */
  {
    let resolved = 0;
    for (const v of Object.values(H.monthTotals)) resolved += v[1] + v[3];
    eq(H.daysCovered + H.daysDropped, resolved,
      'every flight in the day series, kept or dropped, is one the month totals resolve to cancelled, diverted or arrived');
  }
  eq(badDays, 0, 'every leg\'s day count matches its directory entry');
  eq(badOrder, 0, 'every day series is strictly ascending in date');
  eq(badRange, 0, 'every date and every delay is inside the range the format allows');
  eq(badStatus, 0, 'every status is one of the four, and a flight that never arrived carries no arrival delay');
  eq(badSched, 0, 'every scheduled time is a real time of day');
  eq(badPlace, 0, 'every leg names two different three-letter airports');
  eq(badFloor, 0, `no leg below the stated floor of ${H.minDays} days survived into the payload`);
  eq(badTail, 0, 'every shard is read to its last byte, so nothing is silently unreachable');
  ok(biggestGz < 200_000, `the biggest shard is ${biggestName} at ${(biggestGz / 1000).toFixed(0)} kB gzipped`);

  ok(Object.keys(H.airportMeta).length > 200, `${Object.keys(H.airportMeta).length} airports carry a name and a city`);
  ok(H.examples.length >= 3, `${H.examples.length} worked examples ship with the index`);
  for (const e of H.examples) {
    const a = look(e.inbound), b = look(e.outbound);
    ok(a.some((x) => x.rec.dest === e.hub) && b.some((x) => x.rec.origin === e.hub),
      `example ${e.label} resolves to two legs that meet at ${e.hub}`);
    ok(e.inbound !== e.outbound, `example ${e.label} is a connection, not one through-flight`);
  }
}

function look(tag) {
  const p = parseFlight(tag);
  const f = path.join(DATA, 's', `${p.carrier}-${Math.floor(p.number / H.shardSize)}.bin`);
  if (!fs.existsSync(f)) return [];
  const buf = asBuf(f);
  const dir = decodeShard(buf, H, p.carrier);
  return dir.find(p.number).map((rec) => ({ rec, days: readDays(buf, dir.blocksAt, rec.offset) }));
}

/* ================= 3. the arithmetic ================= */
section('3 - the arithmetic');
{
  /* Two hand-built flights. Day 0: inbound 10 late, onward 0 -> 60+0-10 = 50.
     Day 1: inbound 30 late, onward 20 late -> 60+20-30 = 50. Day 2: inbound
     cancelled. Day 3: onward cancelled. Day 4: inbound 5 early, onward 5 early
     -> 60-5+5 = 60. Day 5: inbound only. */
  const mk = (rec, rows) => ({
    rec,
    days: {
      n: rows.length,
      day: Int32Array.from(rows.map((r) => r[0])),
      st: Uint8Array.from(rows.map((r) => r[1])),
      arr: Int16Array.from(rows.map((r) => r[2])),
      dep: Int16Array.from(rows.map((r) => r[3])),
    },
  });
  const inRec = { carrier: 'ZZ', flightNumber: 1, origin: 'AAA', dest: 'BBB', schedDep: 600, schedArr: 700, arrivesNextDay: 0, days: 6 };
  const outRec = { carrier: 'ZZ', flightNumber: 2, origin: 'BBB', dest: 'CCC', schedDep: 760, schedArr: 900, arrivesNextDay: 0, days: 5 };
  const A = mk(inRec, [[0, OPERATED, 10, 0], [1, OPERATED, 30, 0], [2, CANCELLED, 0, 0], [3, OPERATED, 0, 0], [4, OPERATED, -5, 0], [5, OPERATED, 0, 0]]);
  const B = mk(outRec, [[0, OPERATED, 0, 0], [1, OPERATED, 0, 20], [2, OPERATED, 0, 0], [3, CANCELLED, 0, 0], [4, OPERATED, 0, -5]]);

  let r = connect(A, B, 60, 45);
  eq(r.paired, 4, 'the join pairs only the dates both flights appear and the onward one operated');
  eq(r.onwardGone, 1, 'a day the onward flight did not operate is set aside, not counted as a miss');
  eq(r.unmatched, 1, 'a day only one of the two flew is set aside');
  eq(r.inboundGone, 1, 'a day the inbound never arrived is counted as a miss');
  eq(r.missed, 1, 'at 45 minutes needed, only the cancelled day misses');
  eq(r.made, 3, 'the other three days make it');

  r = connect(A, B, 60, 55);
  eq(r.missed, 3, 'at 55 minutes needed, the two 50-minute days join the cancelled one');
  ok(r.misses.every((m) => m.available === null || m.available < 55), 'every listed miss really is short');
  ok(r.kept.every((k) => k.available >= 55), 'every day counted as made really had the time');

  /* the onward flight's own lateness is what the one-flight method throws away */
  const bound = boundFromInbound(A, 60, 45);
  ok(bound.mode === 'bound', 'the one-flight mode names itself');
  const dayOne = connect(A, B, 60, 40).kept.find((k) => k.day === 1);
  ok(dayOne && dayOne.available === 50, 'a day where the onward flight was 20 late gives 20 minutes back');
  ok(boundFromInbound(A, 60, 40).misses.some((m) => m.day === 1),
    'and the one-flight method calls that same day a miss, which is exactly the error it makes');

  /* monotone in need */
  let prev = -1, mono = true;
  for (let need = 0; need <= 120; need++) { const m = connect(A, B, 60, need).missed; if (m < prev) mono = false; prev = m; }
  ok(mono, 'the miss count never falls as you need more ground time');

  /* a redeye: the onward flight is on the next calendar day */
  const night = { ...inRec, schedDep: 1380, schedArr: 300, arrivesNextDay: 1 };
  const N = mk(night, [[0, OPERATED, 0, 0], [1, OPERATED, 0, 0]]);
  const M = mk({ ...outRec, schedDep: 400 }, [[1, OPERATED, 0, 0], [2, OPERATED, 0, 0]]);
  eq(connect(N, M, 60, 45).paired, 2, 'a redeye is joined to the onward flight on the following date');
  eq(connect(A, B, 60, 45).paired, 4, 'a daytime flight is not shifted');

  /* a connection that itself crosses midnight */
  const lateArr = { ...inRec, schedArr: 1400, arrivesNextDay: 0 };
  const L = mk(lateArr, [[0, OPERATED, 0, 0]]);
  const nextDay = mk({ ...outRec, schedDep: 60 }, [[1, OPERATED, 0, 0]]);
  eq(connect(L, nextDay, 100, 45).paired, 1, 'a connection over midnight finds the onward flight on the next date');

  /* a diversion that reached the airport counts at how late it really was */
  const D = mk(inRec, [[0, DIVERTED_LATE, 200, 0]]);
  const E = mk(outRec, [[0, OPERATED, 0, 0]]);
  eq(connect(D, E, 60, 45).missed, 1, 'a diversion that arrived three hours late is a miss, not a gap in the data');
  const F = mk(inRec, [[0, DIVERTED_AWAY, 0, 0]]);
  eq(connect(F, E, 60, 45).inboundGone, 1, 'a diversion that never got there is counted as never having arrived');

  const c = curve(connect(A, B, 60, 45), 120);
  ok(c.every((p, i, arr) => i === 0 || p.missed >= arr[i - 1].missed), 'the curve is non-decreasing');
  ok(c.every((p) => p.made + p.missed === 4), 'the curve conserves the day count at every point');
  eq(marks(connect(A, B, 60, 45)).length, 4, 'the drawing gets one mark per paired date, and no date twice');

  const rr = connect(A, B, 60, 55);
  const bm = byMonth(rr, 55, '2025-07-01');
  eq(bm.reduce((a, m) => a + m.n, 0), rr.paired, 'the month strip holds every paired date and no more');
  eq(bm.reduce((a, m) => a + m.missed, 0), rr.missed, 'and the misses it colours are exactly the misses counted');
  ok(bm.every((m) => m.missed <= m.n), 'no month claims more misses than it has days');
  ok(bm.every((m, i, arr) => i === 0 || m.month > arr[i - 1].month), 'the months come out in order');
}

/* ================= 4. the page ================= */
section('4 - the page');
const html = fs.readFileSync(path.join(TOOL, 'index.html'), 'utf8');
const app = fs.readFileSync(path.join(TOOL, 'app.mjs'), 'utf8');
const engine = fs.readFileSync(path.join(TOOL, 'engine.mjs'), 'utf8');
{
  const MUST_SAY = [
    ['United States domestic flights only', 'the page leads with the coverage limit'],
    ['It counts.', 'the page says plainly that it counts rather than models'],
    ['upper bound', 'the page names what the one-flight fallback is'],
    ['17.06 per cent where the truth is 12.74', 'the page states the measured error of the method it rejected'],
    ['gate', 'the page names gate arrival rather than landing'],
    ['nothing is uploaded', 'the page says nothing is uploaded'],
    ['Prior art, stated plainly', 'the page carries the prior-art section'],
    ['minimum connection time', 'the prior art names the incumbent it differs from'],
    ['FlightStats', 'the prior art names the free tool that does publish cancellations'],
    ['month-by-month strip', 'the page points the seasonality caveat at the chart that answers it'],
    ['Bureau of Transportation Statistics', 'the source is named on the page'],
    ['14 CFR Part 234', 'the reporting rule is cited'],
    ['not endorsed by', 'the page disclaims any endorsement by the Department'],
  ];
  /* A reader sees the static prose AND the prose fillProse() writes, so both
     count as "the page says it". */
  const said = (html + '\n' + app)
    .replace(/<\/?(b|em|i|strong|code|span|a)\b[^>]*>/g, '')   /* a reader does not see the markup */
    .toLowerCase().replace(/\s+/g, ' ');
  for (const [needle, why] of MUST_SAY) ok(said.includes(needle.toLowerCase()), why);

  /* The flight count the scope line prints is the day-series total, not the
     raw row count (note d233a7): run the page's own template against the header. */
  {
    const m = app.match(/const flights = ([^;]+);/);
    const flightsPrinted = m ? Function('h', `return ${m[1]};`)(H) : NaN;
    ok(m && /\$\{flights\.toLocaleString\(\)\} flights, of which/.test(app) && flightsPrinted === H.daysCovered + H.daysDropped,
      `the scope line's flight count is the flights the day series hold (${(H.daysCovered + H.daysDropped).toLocaleString()}), not the raw row count (${H.rows.toLocaleString()})`);
  }

  const prose = html.replace(/<script[\s\S]*?<\/script>/g, '').replace(/<style[\s\S]*?<\/style>/g, '');
  ok(!/[—–]/.test(prose), 'the page carries no em dashes and no en dashes');
  ok(!/[—–]/.test(app), 'the page script carries none either');

  const keys = [...app.matchAll(/^\s{2}(\w+): \['/gm)].map((m) => m[1]);
  ok(keys.length >= 9, `${keys.length} refusal reasons are enumerated as data`);
  ok(app.includes('Object.entries(REFUSALS)'), 'the prose list of refusals is rendered from the same table the code uses');
  ok(app.includes("if (kind !== 'loading') clearURL();"),
    'a refusal clears the query, except while the record is still arriving, when there is no answer to invalidate');
  ok(app.includes('const BOOT_QUERY'), 'the link a reader arrives on is read before anything can clear it');
  ok(/function applyState\(\)|async function applyState\(\)/.test(app), 'there is a single applyState gate');
  ok((app.match(/applyState\)/g) || []).length >= 2, 'the controls are wired through it');
  ok(!app.includes('pushState'), 'state uses replaceState, so Back leaves the tool rather than walking its edits');
  ok(app.includes('me !== generation'), 'a slow shard for an old keystroke cannot overwrite a newer answer');

  ok(html.includes('<link rel="canonical" href="https://artwaste.land/tools/tight-connection/" />'), 'the canonical URL is correct');
  ok(html.includes('/media/home-banner.js'), 'the page carries the canonical top bar');
  ok(html.includes('aw-wayout'), 'the page carries the canonical way out');
  ok(html.includes('prefers-reduced-motion'), 'the page honours reduced motion');
  ok(html.includes('aria-live'), 'the answer is announced to a screen reader');
  ok(html.includes('role="img"') && html.includes('aria-labelledby'), 'the drawings carry a described role');
  /* This scanned the WHOLE file and therefore read the JSON-LD block, where
     schema.org is a vocabulary IRI and bsky.app is this project's own profile in
     `sameAs`. Neither is a link a reader can follow or a resource a browser
     fetches, so the suite was red on an assertion whose own name it satisfied —
     152 of 153, on a page that tells the reader to run it. Noted on the tending
     board 2026-09-04 (row 55) and repaired here. The exclusion is itself checked
     immediately below, so it cannot become a place to hide a third-party host. */
  const ldBlocks = html.match(/<script type="application\/ld\+json">[\s\S]*?<\/script>/g) || [];
  let outside = html;
  for (const b of ldBlocks) outside = outside.replace(b, '');
  ok(!/https?:\/\/(?!artwaste\.land|www\.transtats|ourairports|www\.gpo)/.test(outside.replace(/https:\/\/artwaste\.land/g, '')),
    'the page links out only to the sources it names');
  {
    const hosts = new Set((ldBlocks.join('').match(/https?:\/\/([a-z0-9.-]+)/gi) || [])
      .map((u) => u.replace(/^https?:\/\//i, '').toLowerCase()));
    const allowed = new Set(['schema.org', 'artwaste.land', 'bsky.app']);
    const stray = [...hosts].filter((h) => !allowed.has(h));
    ok(stray.length === 0, `the metadata block names only schema.org, this site and its own profile${stray.length ? ' — found ' + stray.join(', ') : ''}`);
  }
  /* THE SHORT-HOST TRAP. layover.artwaste.land serves this page at "/", so any
     relative reference resolves against "/" and 404s: the page loads, the module
     never runs, and nothing on screen says so. Caught live on the short host the
     day it was provisioned, which is why it is a check and not a comment. */
  ok(!/<script[^>]+src="\.\//.test(html), 'no script tag is loaded by a relative path');
  ok(!/(?:href|src)="\.\//.test(html), 'nothing on the page is referenced by a relative path');
  ok(!/from '\.\//.test(app) && !/from "\.\//.test(app), 'the page script imports by an absolute path');
  ok(!/fetch\(\s*[`'"]\.\//.test(app), 'the page script fetches by an absolute path');
  ok(app.includes("const HOME = '/tools/tight-connection'"), 'and it keeps that path in one place rather than spelling it out per call');
  ok(!/<script[^>]+src="(?!\/)/.test(html), 'the page loads no script from anywhere but this site');

  const og = path.join(ROOT, 'public/media/tool-tight-connection.png');
  if (fs.existsSync(og)) {
    const p = fs.readFileSync(og);
    const w = p.readUInt32BE(16), h = p.readUInt32BE(20);
    ok(w === 2560 && h === 1600, `the card is a ${w} by ${h} PNG, twice the declared 1280 by 800, so it is not upscaled`);
  } else ok(false, 'the card exists at public/media/tool-tight-connection.png');

  ok(engine.includes('WHY BOTH FLIGHTS AND NOT JUST THE INBOUND'),
    'the engine records why it joins two flights, so the next reader does not undo it');

  /* The one number the whole design rests on is a measurement, and it lives in a
     committed file with the script that produced it. The page may not drift from
     it, and neither may the engine's own note. */
  const me = fs.readFileSync(path.join(HERE, 'method-error.md'), 'utf8');
  ok(fs.existsSync(path.join(HERE, 'method-error.py')), 'the script behind that measurement is committed beside it');
  const row = me.match(/\| ORD \| \*\*45 to 59\*\* \| ([\d.]+)% \| \*\*([\d.]+)%\*\* \| \*\*([\d.]+)%\*\*/);
  ok(!!row, 'method-error.md carries the ORD 45 to 59 row in a form this check can read');
  if (row) {
    const [, industry, scheduled, truth] = row;
    ok(said.includes(`${scheduled} per cent where the truth is ${truth}`),
      `the page quotes the measured pair (${scheduled} against ${truth}) exactly as the run recorded it`);
    ok(said.includes(industry), `the page also quotes the industry figure (${industry}) from the same run`);
    ok(Number(scheduled) - Number(truth) > Number(industry) - Number(truth),
      'and the measurement really does say the scheduled-departure method is further from the truth than the industry one');
    ok(engine.includes(`${scheduled}% against a`) && engine.includes(`true ${truth}%`),
      'the engine\'s own note carries the same two numbers, so a future reader is not told a different story by the code');
  }
}

/* ================= 5. a second derivation from the record ================= */
section('5 - a second derivation from the federal record');
if (!FETCH) {
  log.push('    --   skipped (pass --fetch to download one month and re-derive it; about 36 MB)');
} else {
  const [y, m] = H.windowEnd.split('-').map(Number);
  const url = `https://transtats.bts.gov/PREZIP/On_Time_Marketing_Carrier_On_Time_Performance_Beginning_January_2018_${y}_${m}.zip`;
  const tmp = path.join(HERE, `.verify-${y}-${m}.zip`);
  if (!fs.existsSync(tmp)) {
    const r = await fetch(url, { headers: { 'user-agent': 'ArtificialWasteland-verify/1.0 (https://artwaste.land)' } });
    ok(r.ok, `the record for ${y}-${m} is still published where the page says it is`);
    fs.writeFileSync(tmp, Buffer.from(await r.arrayBuffer()));
  } else ok(true, `the record for ${y}-${m} is present locally`);

  const csv = execFileSync('unzip', ['-p', tmp, '*.csv'], { maxBuffer: 1 << 30 }).toString('utf8');
  const lines = csv.split('\n');
  const head = lines[0].split(',').map((s) => s.replace(/^"|"$/g, ''));
  const C = Object.fromEntries(['FlightDate', 'IATA_Code_Marketing_Airline', 'Flight_Number_Marketing_Airline',
    'Origin', 'Dest', 'Cancelled', 'Diverted', 'ArrDelay', 'DepDelay', 'DivReachedDest', 'DivArrDelay', 'Duplicate']
    .map((k) => [k, head.indexOf(k)]));
  ok(Object.values(C).every((i) => i >= 0), 'the raw record still carries every column this pipeline reads');

  const cut = (line) => {
    const out = []; let cur = '', q = false;
    for (let i = 0; i < line.length; i++) {
      const ch = line[i];
      if (q) { if (ch === '"') q = false; else cur += ch; }
      else if (ch === '"') q = true;
      else if (ch === ',') { out.push(cur); cur = ''; }
      else cur += ch;
    }
    out.push(cur); return out;
  };
  const truth = new Map();
  for (let i = 1; i < lines.length; i++) {
    if (!lines[i]) continue;
    const f = cut(lines[i]);
    if ((f[C.Duplicate] || '').toUpperCase() === 'Y') continue;
    const key = `${f[C.IATA_Code_Marketing_Airline]}|${f[C.Flight_Number_Marketing_Airline]}|${f[C.Origin]}|${f[C.Dest]}`;
    const day = Math.round((Date.parse(f[C.FlightDate] + 'T00:00:00Z') - Date.parse(H.epoch + 'T00:00:00Z')) / 86400000);
    const cancelled = f[C.Cancelled] && f[C.Cancelled] !== '0.00' && f[C.Cancelled] !== '0';
    const diverted = f[C.Diverted] && f[C.Diverted] !== '0.00' && f[C.Diverted] !== '0';
    const dep = f[C.DepDelay] === '' ? 0 : Math.round(Number(f[C.DepDelay]));
    let st, arr = 0;
    if (cancelled) st = CANCELLED;
    else if (diverted) {
      const reached = f[C.DivReachedDest] && f[C.DivReachedDest] !== '0.00' && f[C.DivReachedDest] !== '0';
      if (reached && f[C.DivArrDelay] !== '') { st = DIVERTED_LATE; arr = Math.round(Number(f[C.DivArrDelay])); }
      else st = DIVERTED_AWAY;
    } else {
      if (f[C.ArrDelay] === '') continue;
      st = OPERATED; arr = Math.round(Number(f[C.ArrDelay]));
    }
    if (!truth.has(key)) truth.set(key, new Map());
    truth.get(key).set(day, { st, arr: clamp(arr), dep: clamp(dep) });
  }
  function clamp(v) { return Math.max(-1000, Math.min(1000, v)); }
  ok(truth.size > 20000, `re-derived ${truth.size.toLocaleString()} legs for ${y}-${m} from the raw record`);

  let compared = 0, rows = 0, mism = 0, missingRows = 0;
  const bad = [];
  for (const f of shardFiles) {
    const carrier = f.slice(0, f.indexOf('-'));
    const buf = asBuf(path.join(DATA, 's', f));
    const dir = decodeShard(buf, H, carrier);
    for (const rec of dir.legs) {
      const t = truth.get(`${carrier}|${rec.flightNumber}|${rec.origin}|${rec.dest}`);
      if (!t) continue;
      compared++;
      const d = readDays(buf, dir.blocksAt, rec.offset);
      const mine = new Map();
      for (let i = 0; i < d.n; i++) mine.set(d.day[i], { st: d.st[i], arr: d.arr[i], dep: d.dep[i] });
      for (const [day, want] of t) {
        rows++;
        const got = mine.get(day);
        if (!got) { missingRows++; if (bad.length < 3) bad.push(`${carrier}${rec.flightNumber} ${rec.origin}-${rec.dest} day ${day} absent from the payload`); continue; }
        if (got.st !== want.st || got.arr !== want.arr || got.dep !== want.dep) {
          mism++;
          if (bad.length < 3) bad.push(`${carrier}${rec.flightNumber} ${rec.origin}-${rec.dest} day ${day}: payload ${got.st}/${got.arr}/${got.dep} vs record ${want.st}/${want.arr}/${want.dep}`);
        }
      }
    }
  }
  ok(compared > 10000, `${compared.toLocaleString()} legs and ${rows.toLocaleString()} flight-days were re-derived and compared`);
  eq(missingRows, 0, `every date in the raw record is present in the payload${bad.length ? ' - ' + bad[0] : ''}`);
  eq(mism, 0, `every re-derived status and delay agrees with the payload${bad.length ? ' - ' + bad.join('; ') : ''}`);
  fs.rmSync(tmp, { force: true });
}

/* ================= 6. the checks, shown failing on purpose ================= */
section('6 - the checks, shown failing on purpose');
{
  const ex = H.examples[0];
  const A = look(ex.inbound).find((x) => x.rec.dest === ex.hub);
  const B = look(ex.outbound).find((x) => x.rec.origin === ex.hub);
  const good = connect(A, B, ex.gap, 45);
  ok(good.paired > 100, 'the undoctored pair produces a real count');

  /* doctor one arrival delay and confirm the answer moves */
  const A2 = { rec: A.rec, days: { ...A.days, arr: Int16Array.from(A.days.arr) } };
  let flipped = 0;
  for (let i = 0; i < A2.days.n; i++) if (A2.days.st[i] === OPERATED && A2.days.arr[i] < 200) { A2.days.arr[i] = 900; flipped++; }
  const wrecked = connect(A2, B, ex.gap, 45);
  ok(wrecked.missed > good.missed, `making every arrival nine hours late raises the miss count from ${good.missed} to ${wrecked.missed}, so the count is driven by the data and not by the shape of the code`);
  ok(flipped > 0, 'the mutation actually changed something');

  /* a payload whose totals do not add up must be visible */
  const fake = { cum: null, n: 3, day: Int32Array.from([0, 1, 1]), st: Uint8Array.from([0, 0, 0]), arr: Int16Array.from([0, 0, 0]), dep: Int16Array.from([0, 0, 0]) };
  let ascending = true;
  for (let i = 1; i < fake.n; i++) if (fake.day[i] <= fake.day[i - 1]) ascending = false;
  ok(!ascending, 'a day series with a repeated date fails the ascending check, so that check can fail');

  const bad1 = Buffer.from(fs.readFileSync(path.join(DATA, 'index.bin')).subarray(0, 64)); bad1[0] ^= 0xff;
  let threw = false;
  try { decodeIndex(bad1.buffer.slice(bad1.byteOffset, bad1.byteOffset + 64)); } catch { threw = true; }
  ok(threw, 'the decoder refuses an index whose magic does not match rather than reading it as numbers');

  const bad2 = Buffer.from(fs.readFileSync(path.join(DATA, 'index.bin')).subarray(0, 64)); bad2[4] = 99;
  threw = false;
  try { decodeIndex(bad2.buffer.slice(bad2.byteOffset, bad2.byteOffset + 64)); } catch { threw = true; }
  ok(threw, 'the decoder refuses an index written by a different version of the format');

  /* the must-say list has to be able to fail */
  ok(!html.toLowerCase().includes('this tool is never wrong'), 'the must-say check runs against the real page text, and a sentence that is not there is not found');

  if (SELFTEST) {
    log.push('    --   --selftest: forcing one failure so the harness is seen to report it');
    ok(false, 'DELIBERATE FAILURE (--selftest): this run must exit non-zero');
  }
}

/* ================= 7. the count on the page ================= */
section('7 - the count this suite prints');
{
  const claimed = app.match(/const CHECKS = (\d+);/);
  const extra = app.match(/const CHECKS_FETCH = (\d+);/);
  if (claimed && extra) {
    const want = Number(claimed[1]) + (FETCH ? Number(extra[1]) : 0);
    eq(want, pass + fail + 1, `the number of checks the page prints is the number this suite runs${FETCH ? ', including the six the second derivation adds' : ''}`);
  } else ok(false, 'app.mjs declares CHECKS and CHECKS_FETCH, the counts this suite runs, and prints them on the page');
}

console.log('TIGHT CONNECTION: offline verification of /tools/tight-connection/');
console.log(log.join('\n'));
console.log(`\n${pass}/${pass + fail} checks passed.`);
if (fail > 0) {
  console.log('\nfailures:');
  for (const f of failures) console.log('  - ' + f);
  console.log('\nVERIFICATION FAILED');
  process.exit(1);
}
console.log('\nALL CHECKS PASS');
