// verify-what-light.mjs: the reverse light finder at /tools/what-light/, checked
// offline, with no network.
//
//   node verify-what-light.mjs        (about a minute; the last family drives a
//                                      real browser over a local static server)
//
// The tool takes a stranger's own observation and names a real object in the
// world from it. Several things have to be true for that to be honest, and each
// is a family below.
//
// A NOTE ON THE SHAPE OF THIS FILE, because the shape was the bug.
//
// An earlier version of it printed 174/174 while: the shipped ranking comparator
// was reversed; the shipped tier test was inverted; the load-bearing "the light
// must print ALL the colours you name" rule was flipped to "any of them"; the
// geographic-range constant printed on the page was changed from 2.03 to 2.13;
// and the latitude bound in decodeQuery was deleted. Five real mutations, zero
// failures. Three habits caused that, and all three are corrected here rather
// than only their instances:
//
//   * ASSERTIONS THAT CANNOT FAIL. `ok(Array.isArray(conf), ...)` asserts an
//     array is an array. Every count is now compared against a recount.
//   * A MEASUREMENT OF A COPY. measure-find.mjs kept its own duplicate of the
//     comparator, so no measurement here could see the shipped one. The
//     comparators now live in find.mjs, findCandidates takes the name of one,
//     and family 4b asserts the ORDER findCandidates itself returns.
//   * A VERIFIER THAT NEVER LOADED THE PAGE. Everything was checked through the
//     module boundary, so a render() that mishandled a refusal printed "NaN
//     candidates" to a reader while every check here passed. Family 12 serves
//     public/ and reads the rendered DOM in Chromium.
//
//   1. THE PAGE RUNS THE RESEARCHED ENGINE. engine.mjs and find.mjs under
//      public/tools/what-light/ are byte-for-byte the files under
//      research/list-of-lights/. If they could drift, every number the page prints
//      would be about a different instrument from the one checked here.
//   2. THE SHIPPED CORPUS IS THE REAL CORPUS. The page downloads a slimmed,
//      columnar payload rather than the 16.7 MB source. Every field of every one
//      of the 40,559 records is decoded and compared against lights.json. A
//      compression that quietly loses a light is a tool that quietly cannot find
//      it.
//   3. THE INDEX AGREES WITH BRUTE FORCE. GridIndex.within was silently dropping
//      19.34% of true neighbours at 25 km until a few hours before this file was
//      written, and it survived because the verifier that was supposed to catch
//      it compared nothing. This one compares, over sampled query points, against
//      an exhaustive great-circle scan of the whole corpus.
//   4. REAL QUERIES RETURN REAL ANSWERS. Observers are placed at known offsets
//      from known lights and the light has to come back, with a bearing, a
//      distance and two ranges that an independent recomputation agrees with.
//   5. IT REFUSES RATHER THAN GUESSES. No position, nothing observed, a light
//      with no printed period, a light with no way to compute visibility, a
//      position inside the United States gap: each has to produce a refusal with
//      a reason, not an empty list and not a number.
//   6. THE PAGE'S FIGURES COME FROM THE FILES. Every count and every accuracy
//      figure is re-derived here from lights.json and from a re-run of the
//      simulation at the same seed, and has to match the shipped artifacts. The
//      page must carry no competing hand-typed copy.
//   7. THE URL IS THE WHOLE QUERY. States encode to links and those links decode
//      back to the same state, including the edge values.
import { readFileSync, existsSync, statSync } from 'fs';
import { createServer } from 'http';
import { extname } from 'path';
import {
  GridIndex, haversineKm, geographicRangeNm, KM_PER_NM, litAt, parseCharacteristic,
} from './research/list-of-lights/engine.mjs';
import {
  decodeCorpus, findCandidates, confusableNear, confusable, flashSignature, ambiguousWithin,
  visibility, usGapRegion, regionCensus, gapVerdict, US_GAP_REGIONS, encodeQuery, decodeQuery,
  EXCLUSION, CORPUS_FIELDS, MARGINAL_FACTOR, DEFAULT_TOL, CONFUSABLE_RADIUS_KM, SAME_STRUCTURE_KM,
  scheduleOf, bearingDeg, RANKERS, DEFAULT_RANK,
  FLASH_RANGE, LAT_RANGE, LNG_RANGE, EYE_RANGE_M, TOL_RANGE_PCT, QUERY_BOUNDS,
  SHORTLIST_CARDS, HORIZON_MARKS, INDEX_CHECK_PLAN,
} from './research/list-of-lights/find.mjs';
import { runMeasurement, TIMING_KEYS } from './research/list-of-lights/measure-find.mjs';

const ROOT = new URL('./', import.meta.url).pathname;
const TOOL = ROOT + 'public/tools/what-light/';
const LAB = ROOT + 'research/list-of-lights/';

let pass = 0, fail = 0;
const log = [];
const ok = (c, m) => { (c ? pass++ : fail++); log.push(`  ${c ? '✓' : '✗ FAIL'} ${m}`); };
const fmt = (n) => Number(n).toLocaleString('en-US');

const page = readFileSync(TOOL + 'index.html', 'utf8');

// ── family 1: the page runs the researched engine ───────────────────────────
log.push('\n[1] the page runs the engine the study runs (byte for byte):');
for (const f of ['engine.mjs', 'find.mjs']) {
  const a = existsSync(TOOL + f) ? readFileSync(TOOL + f) : null;
  const b = readFileSync(LAB + f);
  ok(a !== null && a.equals(b), `${f} in the tool is identical to research/list-of-lights/${f}`);
}
ok(/from '\.\/engine\.mjs'/.test(page), 'the page imports engine.mjs from its own directory');
ok(/from '\.\/find\.mjs'/.test(page), 'the page imports find.mjs from its own directory');
{
  // The study page and the tool must share one engine, or the same light would
  // blink differently in two places on the same site.
  const strat = ROOT + 'public/strata/some-lights-are-only-themselves/engine.mjs';
  ok(existsSync(strat) && readFileSync(strat).equals(readFileSync(LAB + 'engine.mjs')),
    'the study page at /strata/some-lights-are-only-themselves/ ships that same engine.mjs');
}

// ── family 2: the shipped corpus is the real corpus ─────────────────────────
log.push('\n[2] the payload the browser downloads decodes back to the source corpus:');
const SRC = JSON.parse(readFileSync(LAB + 'lights.json', 'utf8'));
const packed = JSON.parse(readFileSync(TOOL + 'lights.json', 'utf8'));
const L = decodeCorpus(packed);
// Read here rather than in family 6 because families above it need the search
// radius the page actually uses. A query run at a radius the page never uses is
// a query about a different tool.
const META = JSON.parse(readFileSync(TOOL + 'meta.json', 'utf8'));
const MEASURE = JSON.parse(readFileSync(TOOL + 'measurement.json', 'utf8'));
const META_RADIUS = META.search.maxEffectiveKm;
const MEASURE_TWO_COLOUR_PRESENT = !!(MEASURE.withTwoColours && MEASURE.withTwoColours.n > 0);
ok(L.length === SRC.length, `${fmt(L.length)} lights decoded, against ${fmt(SRC.length)} in lights.json`);
{
  const r5 = (v) => Math.round(v * 1e5) / 1e5;
  let bad = 0; let first = null;
  for (let i = 0; i < SRC.length; i++) {
    const a = SRC[i], b = L[i];
    for (const f of CORPUS_FIELDS) {
      let want = a[f];
      if (f === 'lat' || f === 'lon') want = r5(want);
      if (f === 'name' || f === 'structure') want = (want || '').trim() || null;
      if (JSON.stringify(want) !== JSON.stringify(b[f])) {
        bad++; if (!first) first = `${a.id}.${f}: ${JSON.stringify(want)} vs ${JSON.stringify(b[f])}`;
        break;
      }
    }
  }
  ok(bad === 0, `every field of all ${fmt(SRC.length)} records survives the round trip${first ? ` (first mismatch ${first})` : ''}`);
  const bytes = readFileSync(TOOL + 'lights.json').length;
  const srcBytes = readFileSync(LAB + 'lights.json').length;
  ok(bytes < srcBytes / 2, `the shipped payload is ${(bytes / 1048576).toFixed(2)} MiB against ${(srcBytes / 1048576).toFixed(2)} MiB for the source`);
  ok(!/"remarks"|"region"|"vol"/.test(packed.fields.join(',')), 'the fields the tool never reads were dropped rather than shipped and ignored');
}

// ── family 3: the index agrees with brute force ─────────────────────────────
log.push('\n[3] the grid index agrees with an exhaustive great-circle scan:');
const INDEX = new GridIndex(L, 25);
{
  // Sampled deterministically across the whole corpus, including the high
  // latitudes where the old index failed worst.
  let checked = 0, mismatches = 0, worst = null;
  // The radii and the sample size are INDEX_CHECK_PLAN, which is also what the
  // page prints in prose about this check. The plan is executed, not described.
  for (const radiusKm of INDEX_CHECK_PLAN.radiiKm) {
    for (let k = 0; k < INDEX_CHECK_PLAN.perRadius; k++) {
      const q = L[Math.floor((k * 7919 + radiusKm * 104729) % L.length)];
      const got = new Set(INDEX.within(q.lat, q.lon, radiusKm));
      const want = new Set();
      for (let j = 0; j < L.length; j++) if (haversineKm(q, L[j]) <= radiusKm) want.add(j);
      checked++;
      if (got.size !== want.size || [...want].some((j) => !got.has(j))) {
        mismatches++;
        if (!worst) worst = `${q.id} at ${radiusKm} km: index ${got.size}, brute force ${want.size}`;
      }
    }
  }
  ok(mismatches === 0, `${checked} radius queries at ${INDEX_CHECK_PLAN.radiiKm.join(', ')} km (the last is the tool's own default) match brute force exactly${worst ? ` (first ${worst})` : ''}`);
  ok(checked === INDEX_CHECK_PLAN.radiiKm.length * INDEX_CHECK_PLAN.perRadius,
    `and the plan the page prints, ${INDEX_CHECK_PLAN.radiiKm.length} radii by ${INDEX_CHECK_PLAN.perRadius} points, is the plan that ran: ${checked} queries`);

  // THE SEAM. The index had no antimeridian wrap until recently: a query at
  // longitude 179.9 could not see a light at -179.9 fifteen kilometres away. The
  // sample above draws its origins from the corpus and will almost never land
  // there, so the seam is walked deliberately, at latitudes where the corpus has
  // something on both sides of it.
  let seamChecked = 0, seamBad = 0, seamNote = null, seamCrossed = 0;
  for (const lat of [-16.13, -17.4, -17.83, -18.99, 0, 51.3, 65.0, -45.0]) {
    for (const lon of [179.9, -179.9, 180, -180, 179.999]) {
      for (const radiusKm of [25, 110]) {
        const got = new Set(INDEX.within(lat, lon, radiusKm));
        const want = new Set();
        for (let j = 0; j < L.length; j++) if (haversineKm({ lat, lon }, L[j]) <= radiusKm) want.add(j);
        seamChecked++;
        // did this query have to cross the line to be right?
        if ([...want].some((j) => L[j].lon * lon < 0)) seamCrossed++;
        if (got.size !== want.size || [...want].some((j) => !got.has(j))) {
          seamBad++;
          if (!seamNote) seamNote = `${lat},${lon} at ${radiusKm} km: index ${got.size}, brute force ${want.size}`;
        }
      }
    }
  }
  ok(seamBad === 0 && seamCrossed > 0,
    `${seamChecked} queries sat on the antimeridian and ${seamCrossed} of them had neighbours on the far side of it; all match brute force${seamNote ? ` (first ${seamNote})` : ''}`);

  // And the check that the check is real: a deliberately broken index must fail it.
  const broken = new GridIndex(L, 25);
  broken.within = function (lat, lon, r) { return GridIndex.prototype.within.call(this, lat, lon, r * 0.5); };
  const q = L[12345];
  ok(broken.within(q.lat, q.lon, 25).length < INDEX.within(q.lat, q.lon, 25).length,
    'a deliberately narrowed index returns fewer neighbours, so the comparison above can fail');
}

// ── family 4: real queries over real records ────────────────────────────────
log.push('\n[4] observers placed at known offsets from known lights get those lights back:');
{
  const EYE = 5;
  const offset = (lat, lon, dKm, brg) => {
    const dLat = dKm / 111.19492664455873;
    const r = brg * Math.PI / 180;
    return { lat: lat + dLat * Math.cos(r), lon: lon + (dLat * Math.sin(r)) / Math.max(0.02, Math.cos(lat * Math.PI / 180)) };
  };
  // Five real lights spread across five volumes, picked deterministically as the
  // longest-range light with a printed schedule in each of five countries.
  // Five countries on four continents, each with at least one long-range light
  // whose record prints its own flash and eclipse times. Iceland is deliberately
  // not here: it has 271 lights and not one of them prints a schedule at that
  // size, which is the corpus being uneven rather than the tool being wrong.
  const wanted = ['FRANCE', 'JAPAN', 'BRAZIL', 'NEW ZEALAND', 'NORWAY'];
  const picks = [];
  for (const c of wanted) {
    const cands = L.filter((l) => l.country.startsWith(c) && l.period != null && l.phases.length
      && l.rangeNm != null && l.rangeNm >= 15 && l.heightM != null && l.heightM >= 20);
    if (!cands.length) continue;
    cands.sort((a, b) => (b.rangeNm - a.rangeNm) || a.id.localeCompare(b.id));
    picks.push(cands[0]);
  }
  ok(picks.length === wanted.length, `${picks.length} real lights selected from ${wanted.length} countries`);

  for (const l of picks) {
    const idx = L.indexOf(l);
    const geo = geographicRangeNm(l.heightM, EYE);
    const effKm = Math.min(l.rangeNm, geo) * KM_PER_NM;
    const dKm = effKm * 0.6;
    const at = offset(l.lat, l.lon, dKm, 217);
    const fs = flashSignature(l);
    const res = findCandidates(
      { colours: [l.colours[0]], flashes: fs.steady ? 'steady' : fs.many ? 'many' : fs.count, period: l.period },
      { lat: at.lat, lon: at.lon }, 120,
      { lights: L, index: INDEX, tol: DEFAULT_TOL, eyeHeightM: EYE, limit: 40 },
    );
    const hit = res.candidates.findIndex((c) => c.i === idx);
    const name = (l.name || l.id).replace(/^-+/, '').trim();
    ok(hit >= 0, `${name} (${l.country}, ${l.head.replace(/\n/g, ' ')} ${l.period}s) is found from ${dKm.toFixed(1)} km away, at rank ${hit + 1} of ${res.candidates.length}`);
    if (hit < 0) continue;
    const c = res.candidates[hit];
    // and the numbers it reports have to be the numbers, recomputed here
    ok(Math.abs(c.distKm - haversineKm({ lat: at.lat, lon: at.lon }, l)) < 1e-9,
      `  its reported distance ${c.distKm.toFixed(2)} km is the great-circle distance`);
    ok(Math.abs(c.bearing - bearingDeg({ lat: at.lat, lon: at.lon }, l)) < 1e-9,
      `  its reported bearing ${c.bearing.toFixed(1)}° is the great-circle bearing`);
    ok(Math.abs(c.vis.geoNm - 2.03 * (Math.sqrt(l.heightM) + Math.sqrt(EYE))) < 1e-9,
      `  its geographic range ${c.vis.geoNm.toFixed(1)} nm is 2.03 (root height + root eye) for a ${l.heightM} m light and a ${EYE} m eye`);
    ok(c.vis.effectiveNm === Math.min(l.rangeNm, c.vis.geoNm),
      `  it is limited by ${c.vis.limitedBy === 'horizon' ? 'the horizon' : 'the lamp'} at ${c.vis.effectiveNm.toFixed(1)} nm, the smaller of ${l.rangeNm} and ${c.vis.geoNm.toFixed(1)}`);
    // the animation runs the record's own printed schedule
    const sched = scheduleOf(l);
    ok(sched && sched.source === 'printed',
      `  its strip runs the flash and eclipse times printed in the record, not a reconstruction`);
    ok(Math.abs(sched.total - l.period) < 0.51,
      `  and that printed schedule totals ${sched.total} s against a printed period of ${l.period} s`);
  }

  // Beyond its own reach, the same light must not be offered as in range.
  const l = picks[0];
  const geo = geographicRangeNm(l.heightM, EYE);
  const effKm = Math.min(l.rangeNm, geo) * KM_PER_NM;
  const far = offset(l.lat, l.lon, effKm * 1.6, 217);
  const fs0 = flashSignature(l);
  const resFar = findCandidates(
    { colours: [l.colours[0]], flashes: fs0.count, period: l.period },
    { lat: far.lat, lon: far.lon }, 120, { lights: L, index: INDEX, eyeHeightM: EYE },
  );
  ok(!resFar.candidates.some((c) => c.i === L.indexOf(l)),
    `from ${(effKm * 1.6).toFixed(0)} km, past 1.25 times its own limits, ${(l.name || l.id).trim()} is not offered at all`);
  const mid = offset(l.lat, l.lon, effKm * 1.1, 217);
  const resMid = findCandidates(
    { colours: [l.colours[0]], flashes: fs0.count, period: l.period },
    { lat: mid.lat, lon: mid.lon }, 120, { lights: L, index: INDEX, eyeHeightM: EYE },
  );
  const midHit = resMid.candidates.find((c) => c.i === L.indexOf(l));
  ok(midHit && midHit.tier === 'marginal',
    'and just past them it is offered, labelled marginal, rather than dropped or presented as in range');

  // Eye height is not decoration: raising it must raise the geographic range.
  const low = visibility(l, 10, 2).geoNm, high = visibility(l, 10, 20).geoNm;
  ok(high > low, `an eye at 20 m sees ${high.toFixed(1)} nm where an eye at 2 m sees ${low.toFixed(1)} nm`);
}

// ── family 4b: the order the page shows is the order that was measured ──────
//
// This family exists because reversing the shipped comparator to
// `b.distKm - a.distKm`, and separately inverting its tier test, changed the
// order of every shortlist a reader sees and moved nothing in this file. The
// cause was that the only sort anyone checked was a hand-copied duplicate inside
// measure-find.mjs. So: the rule is RESTATED here in words rather than imported,
// and findCandidates' own output is held against it.
log.push('\n[4b] the shortlist comes back in the order the ranking rule specifies:');
{
  // The shipped rule, written out again from the page's own description of it:
  // inside its printed limits before past them, then the closest rhythm, then
  // the nearest. If this agreed with the code by importing the code it would be
  // a function agreeing with itself.
  const outOfOrder = (list) => {
    for (let k = 1; k < list.length; k++) {
      const a = list[k - 1], b = list[k];
      const ta = a.tier === 'in-range' ? 0 : 1;
      const tb = b.tier === 'in-range' ? 0 : 1;
      if (ta !== tb) { if (ta > tb) return `${k}: a marginal candidate is above an in-range one`; continue; }
      const pa = a.periodErr == null ? 0 : a.periodErr;
      const pb = b.periodErr == null ? 0 : b.periodErr;
      if (pa !== pb) { if (pa > pb) return `${k}: period error ${pa} is above ${pb}`; continue; }
      if (a.distKm > b.distKm) return `${k}: ${a.distKm.toFixed(2)} km is above ${b.distKm.toFixed(2)} km`;
    }
    return null;
  };

  // Queries chosen to produce long, mixed shortlists: harbours, and one place
  // deliberately picked because it returns more candidates than the page shows.
  const PROBES = [
    ['a crowded Korean harbour', 35.48002, 129.42868, [], null, 5],
    ['off the Cornish coast', 50.152, -5.064, ['W'], null, null],
    ['the Newfoundland pair', 49.7078, -54.8, ['W'], null, 5],
    ['Sydney Harbour', -33.85, 151.28, [], null, 4],
    ['the Fiji seam', -16.13, 179.9, ['W'], null, null],
    ['Bergen', 60.39, 5.2, [], 1, 10],
  ];
  let ordered = 0, longest = 0;
  for (const [what, lat, lon, colours, flashes, period] of PROBES) {
    const res = findCandidates({ colours, flashes, period }, { lat, lon }, META_RADIUS,
      { lights: L, index: INDEX, eyeHeightM: 5, limit: 40 });
    const bad = res.ok ? outOfOrder(res.candidates) : 'refused';
    longest = Math.max(longest, res.candidates.length);
    if (!bad) ordered++;
    ok(!bad, `${what}: ${res.candidates.length} candidates, in the stated order${bad ? ` (${bad})` : ''}`);
  }
  ok(longest >= 20, `and at least one probe returns a long shortlist (${longest}), so the ordering has something to get wrong`);

  // The rank option is really wired: a different rule has to produce a different
  // order somewhere, or `rank` is decoration and the measurement measures one
  // rule three times.
  {
    let differs = 0;
    for (const [, lat, lon, colours, flashes, period] of PROBES) {
      const a = findCandidates({ colours, flashes, period }, { lat, lon }, META_RADIUS,
        { lights: L, index: INDEX, eyeHeightM: 5, limit: 40, rank: 'nearest' });
      const b = findCandidates({ colours, flashes, period }, { lat, lon }, META_RADIUS,
        { lights: L, index: INDEX, eyeHeightM: 5, limit: 40, rank: 'range' });
      if (JSON.stringify(a.candidates.map((c) => c.i)) !== JSON.stringify(b.candidates.map((c) => c.i))) differs++;
    }
    ok(differs > 0, `asking for a different ranking rule really changes the order (${differs} of ${PROBES.length} probes)`);
    ok(findCandidates({ colours: ['W'], flashes: null, period: 3 }, { lat: 50.152, lon: -5.064 }, META_RADIUS,
      { lights: L, index: INDEX, rank: 'not-a-rule' }).reason === 'no-ranker',
      'and an unknown ranking rule is a refusal, not a shortlist in an unspecified order');
    ok(Object.keys(RANKERS).includes(DEFAULT_RANK) && DEFAULT_RANK === 'nearest',
      `the rule that ships by default is ${DEFAULT_RANK}, and it is one of the ${Object.keys(RANKERS).length} measured`);
  }

  // measure-find.mjs must not have grown a second sort back.
  {
    const mf = readFileSync(LAB + 'measure-find.mjs', 'utf8');
    ok(/import \{[^}]*RANKERS[^}]*\} from '\.\/find\.mjs'/.test(mf),
      'measure-find.mjs imports the comparators from find.mjs rather than defining its own');
    ok(!/\.sort\(RANKERS/.test(mf) && !/list\.sort\(/.test(mf),
      'and it does not sort the candidate list itself: it asks findCandidates for the order, by name');
    ok(/limit: 40, rank/.test(mf), 'and it passes the ranking rule through to findCandidates');
  }
}

// ── family 4c: the multi-colour rule, which nothing used to exercise ────────
//
// "the light must print ALL the colours you name" is the documented rule and it
// is load-bearing: a sectored Fl.W.R.G. shows plain white from inside its white
// sector, so the list may print MORE than you see and never less. The reviewer
// changed `colours.every` to `colours.some` and every check here stayed green,
// because every query the file built named exactly one colour.
log.push('\n[4c] naming two colours means the record prints both, not either:');
{
  const at = (l, dKm) => ({ lat: l.lat + dKm / 111.19, lon: l.lon });
  const near = (l, obs, dKm = 1) => findCandidates(obs, at(l, dKm), 60,
    { lights: L, index: INDEX, eyeHeightM: 5 });

  // A light that prints exactly one colour, close enough to be well inside its
  // own range. Asking for that colour AND another must not return it.
  const mono = L.find((l) => (l.colours || []).length === 1 && l.colours[0] === 'W'
    && l.period != null && l.rangeNm != null && l.rangeNm >= 10 && l.heightM != null && l.heightM >= 20);
  ok(!!mono, 'the corpus holds a plain white light to test against');
  if (mono) {
    const fs = flashSignature(mono);
    const flashes = fs.steady ? 'steady' : fs.many ? 'many' : fs.count;
    const one = near(mono, { colours: ['W'], flashes, period: mono.period });
    ok(one.candidates.some((c) => L[c.i].id === mono.id),
      `${(mono.name || mono.id).trim()} (${mono.colours.join('.')}) is found when you say white`);
    const two = near(mono, { colours: ['W', 'R'], flashes, period: mono.period });
    ok(!two.candidates.some((c) => L[c.i].id === mono.id) && two.excluded.colour > 0,
      '  and is NOT found when you say white AND red, because it prints no red: this is the check that fails under "any of them"');
  }

  // A light that really does print two colours must answer to both of them.
  const duo = L.find((l) => (l.colours || []).length >= 2
    && l.colours.includes('W') && l.colours.includes('R')
    && l.period != null && l.rangeNm != null && l.rangeNm >= 10 && l.heightM != null && l.heightM >= 15);
  ok(!!duo, 'the corpus holds a light printing both white and red');
  if (duo) {
    const fs = flashSignature(duo);
    const flashes = fs.steady ? 'steady' : fs.many ? 'many' : fs.count;
    const both = near(duo, { colours: ['W', 'R'], flashes, period: duo.period });
    ok(both.candidates.some((c) => L[c.i].id === duo.id),
      `${(duo.name || duo.id).trim()} (${duo.colours.join('.')}) is found when you name both of its colours`);
    const three = near(duo, { colours: ['W', 'R', 'Vi'], flashes, period: duo.period });
    ok(!three.candidates.some((c) => L[c.i].id === duo.id),
      '  and is not found when you add a colour it does not print');
  }

  // And across the whole corpus, at population scale: every light returned by a
  // two-colour query prints both colours. Under `.some` this is false for many.
  {
    let queries = 0, returned = 0, violations = 0;
    for (const l of L) {
      if ((l.colours || []).length < 2 || l.period == null || l.rangeNm == null || l.rangeNm < 8 || l.heightM == null) continue;
      if (queries >= 40) break;
      queries++;
      const want = l.colours.slice(0, 2);
      const res = near(l, { colours: want, flashes: null, period: l.period });
      for (const c of res.candidates) {
        returned++;
        if (!want.every((x) => (L[c.i].colours || []).includes(x))) violations++;
      }
    }
    ok(queries >= 20 && returned > 0 && violations === 0,
      `${queries} two-colour queries returned ${returned} candidates and every one of them prints both colours (${violations} that do not)`);
  }

  // The measurement now runs a two-colour population too, so the rule is inside
  // the numbers on the page rather than only inside this file.
  ok(MEASURE_TWO_COLOUR_PRESENT, 'and the measurement on the page includes a two-colour observer population');
}

// ── family 4d: "these were not silently dropped" is an arithmetic claim ──────
//
// The set-aside panel says so many records lie within the radius and then lists
// where each one went. That is a claim with two halves, and both are checkable:
// `searched` must be the true number of records inside the circle, and every one
// of them must end up either in the candidate list or under a named exclusion.
// The claim went false once already, when the index was dropping neighbours at
// the antimeridian, and nothing here noticed.
log.push('\n[4d] every record inside the search circle is accounted for by name:');
{
  const PLACES = [
    ['off the Cornish coast', 50.152, -5.064],
    ['a crowded Korean harbour', 35.48002, 129.42868],
    ['the Newfoundland coast', 49.7078, -54.8],
    ['the Fiji seam, east side', -16.13, 179.9],
    ['the Fiji seam, west side', -17.274, -179.9],
    ['Bergen', 60.39, 5.2],
    ['Sydney', -33.85, 151.28],
  ];
  let bad = 0, note = null, totalSearched = 0;
  for (const [what, lat, lon] of PLACES) {
    for (const obs of [{ colours: ['W'], flashes: null, period: 5 }, { colours: [], flashes: null, period: 10 }]) {
      const res = findCandidates(obs, { lat, lon }, META_RADIUS, { lights: L, index: INDEX, eyeHeightM: 5, limit: 40 });
      if (!res.ok) { bad++; note = note || `${what} refused`; continue; }
      // half one: searched is the true count inside the circle
      let brute = 0;
      for (let j = 0; j < L.length; j++) if (haversineKm({ lat, lon }, L[j]) <= META_RADIUS) brute++;
      if (res.searched !== brute) { bad++; note = note || `${what}: searched ${res.searched}, brute force ${brute}`; continue; }
      totalSearched += brute;
      // half two: matched plus every named exclusion is all of them
      const setAside = Object.values(res.excluded).reduce((a, b) => a + b, 0);
      if (res.total + setAside !== res.searched) {
        bad++;
        note = note || `${what}: ${res.total} matched + ${setAside} set aside is not ${res.searched} searched`;
      }
      // and every exclusion key the code can emit has a sentence on the page
      for (const k of Object.keys(res.excluded)) {
        if (!EXCLUSION[k]) { bad++; note = note || `${what}: exclusion "${k}" has no sentence`; }
      }
    }
  }
  ok(bad === 0, `${PLACES.length * 2} queries over ${fmt(totalSearched)} in-circle records: searched equals a brute-force count, and matched plus named exclusions equals searched${note ? ` (first ${note})` : ''}`);
  ok(/were not silently dropped/.test(page), 'and the page makes that claim, so it is falsifiable');

  // The claim that "the shortlist is cut" is stated: the numbers must be real.
  {
    const res = findCandidates({ colours: [], flashes: null, period: 5 }, { lat: 35.48002, lon: 129.42868 },
      META_RADIUS, { lights: L, index: INDEX, eyeHeightM: 5, limit: SHORTLIST_CARDS });
    ok(res.total > SHORTLIST_CARDS, `a real query returns more candidates (${res.total}) than the page can print (${SHORTLIST_CARDS}), so the cut is not hypothetical`);
    ok(res.shown === SHORTLIST_CARDS && res.hidden === res.total - SHORTLIST_CARDS
      && res.candidates.length === res.shown,
      `and the query layer reports the cut: ${res.shown} shown, ${res.hidden} hidden, of ${res.total}`);
    ok(HORIZON_MARKS < SHORTLIST_CARDS, `the horizon draws fewer still (${HORIZON_MARKS} of ${SHORTLIST_CARDS}), which is the second cut the page has to state`);
    ok(new RegExp(`slice\\(0, HORIZON_MARKS\\)`).test(page) && /limit: SHORTLIST_CARDS/.test(page),
      'and both cuts are made from the shared constants rather than from numbers typed into the page');
  }
}

// ── family 4e: a tie is found and named rather than resolved ────────────────
//
// The page used to promise "it will not tell you the answer when the answer is a
// coin toss" and then badge one of two indistinguishable lights as candidate A.
log.push('\n[4e] two candidates that cannot be told apart are found as a tie:');
{
  const res = findCandidates({ colours: ['W'], flashes: null, period: 5 }, { lat: 49.7078, lon: -54.8 },
    META_RADIUS, { lights: L, index: INDEX, eyeHeightM: 5, limit: SHORTLIST_CARDS });
  ok(res.ok && res.total >= 2, `the Newfoundland query returns ${res.total} candidates`);
  const ties = ambiguousWithin(res.candidates);
  const names = res.candidates.map((c) => (c.light.name || c.light.id).replace(/^-+/, '').trim());
  ok(ties[0] && ties[0].length >= 1,
    `the TOP candidate (${names[0]}) is tied with ${ties[0] ? ties[0].length : 0} other in the same shortlist, so ranking it first is not an identification`);
  if (ties[0] && ties[0].length) {
    const other = ties[0][0];
    ok(names[other.at] === 'Surgeon Cove Point.' || /Surgeon Cove/.test(names[other.at]),
      `  and the light it is tied with is ${names[other.at]}`);
    ok(Math.abs(other.distKm - haversineKm(res.candidates[0].light, res.candidates[other.at].light)) < 1e-9
      && other.distKm > CONFUSABLE_RADIUS_KM,
      `  they are ${other.distKm.toFixed(1)} km apart, which is MORE than the ${CONFUSABLE_RADIUS_KM} km confusability radius: this is the pair the local count cannot see`);
    // and the 10 km count really does miss it, which is why the sentence had to change
    ok(confusableNear(res.candidates[0].light, { lights: L, index: INDEX }).length === 0,
      '  the 10 km confusability count for that light is 0, so a sentence built from it must not speak for the shortlist');
  }
  // The relation is symmetric and excludes a light from itself.
  {
    const sym = ties.every((list, i) => list.every((t) => ties[t.at].some((u) => u.at === i)));
    ok(sym, 'the tie relation is symmetric: if A cannot be told from B, B cannot be told from A');
    ok(ties.every((list, i) => list.every((t) => t.at !== i)), 'and nothing is tied with itself');
  }
  // Lights on one structure are not a tie, which is the same rule confusableNear uses.
  {
    let pairsOnOneStructure = 0;
    for (const c of res.candidates) {
      for (const d of res.candidates) {
        if (c === d) continue;
        if (haversineKm(c.light, d.light) < SAME_STRUCTURE_KM) pairsOnOneStructure++;
      }
    }
    const found = ties.flat().filter((t) => t.distKm < SAME_STRUCTURE_KM).length;
    ok(found === 0, `two lights on one structure are not reported as a tie (${pairsOnOneStructure} such pairs in this shortlist, ${found} reported)`);
  }
  // A shortlist with no tie must report none, or the check is one that cannot fail.
  {
    const clean = findCandidates({ colours: ['W'], flashes: 1, period: 3 }, { lat: 50.152, lon: -5.064 },
      META_RADIUS, { lights: L, index: INDEX, eyeHeightM: 3, limit: SHORTLIST_CARDS });
    ok(ambiguousWithin(clean.candidates).every((t) => t.length === 0),
      'and the Lizard query, which returns one light, reports no tie at all');
  }
}

// ── family 5: the refusals ──────────────────────────────────────────────────
log.push('\n[5] handed something it cannot answer, it refuses and says why:');
{
  const somewhere = { lat: 50.15, lon: -5.06 };
  const obs = { colours: ['W'], flashes: 2, period: 10 };

  // EVERY reason the query layer can return, each with the input that produces
  // it, and each one required to carry total: 0 rather than undefined. That last
  // clause is the whole of defect one: render() printed `res.total` for a
  // refusal it did not recognise and the reader got "NaN candidates".
  const REASON_CASES = [
    ['no-position', () => findCandidates(obs, null, 120, { lights: L, index: INDEX }), 'no position at all'],
    ['no-position', () => findCandidates(obs, { lat: 95, lon: 0 }, 120, { lights: L, index: INDEX }), 'a latitude of 95 degrees, refused rather than clamped'],
    ['no-position', () => findCandidates(obs, { lat: 0, lon: 181 }, 120, { lights: L, index: INDEX }), 'a longitude of 181 degrees'],
    ['no-position', () => findCandidates(obs, { lat: NaN, lon: 0 }, 120, { lights: L, index: INDEX }), 'a latitude that is not a number'],
    ['no-observation', () => findCandidates({ colours: [], flashes: null, period: null }, somewhere, 120, { lights: L, index: INDEX }), 'a position but nothing observed'],
    ['no-radius', () => findCandidates(obs, somewhere, 0, { lights: L, index: INDEX }), 'a search radius of zero'],
    ['no-radius', () => findCandidates(obs, somewhere, -5, { lights: L, index: INDEX }), 'a negative search radius'],
    ['no-corpus', () => findCandidates(obs, somewhere, 120, {}), 'no corpus to search'],
    ['no-ranker', () => findCandidates(obs, somewhere, 120, { lights: L, index: INDEX, rank: 'whatever' }), 'a ranking rule that does not exist'],
  ];
  const seenReasons = new Set();
  for (const [want, run, what] of REASON_CASES) {
    const r = run();
    seenReasons.add(want);
    ok(r.ok === false && r.reason === want && r.total === 0 && Array.isArray(r.candidates) && r.candidates.length === 0,
      `${what}: refuses with reason ${want}, and reports total 0 rather than undefined (got ${r.reason}, total ${r.total})`);
  }
  ok(findCandidates(obs, somewhere, 120, { lights: L, index: INDEX }).ok === true,
    'and with a position, an observation, a radius and a corpus, it answers');
  // The page must carry a sentence for every one of these, or a refusal falls
  // through to the summary line again. Checked against the page source.
  for (const reason of seenReasons) {
    ok(new RegExp(`'${reason}':`).test(page), `the page has a refusal panel written for ${reason}`);
  }
  ok(/function refusalFor\(/.test(page) && /has no\s*\n?\s*sentence for/.test(page),
    'and an unknown reason still produces a refusal, so a reason added later cannot print NaN either');

  // A light with no printed period must be excluded WITH ITS REASON when a
  // period is given, and must become findable again when one is not.
  const noPeriod = L.find((l) => l.period == null && l.rangeNm != null && l.rangeNm >= 10 && l.heightM != null && l.heightM >= 15);
  ok(!!noPeriod, `the corpus contains lights with no printed period (${noPeriod ? noPeriod.id : 'none'})`);
  if (noPeriod) {
    const geo = geographicRangeNm(noPeriod.heightM, 5);
    const dKm = Math.min(noPeriod.rangeNm, geo) * KM_PER_NM * 0.5;
    const at = { lat: noPeriod.lat + dKm / 111.19, lon: noPeriod.lon };
    const fs = flashSignature(noPeriod);
    const flashes = fs.steady ? 'steady' : fs.many ? 'many' : fs.count;
    const withPeriod = findCandidates({ colours: [noPeriod.colours[0]], flashes, period: 8 }, at, 120,
      { lights: L, index: INDEX, eyeHeightM: 5 });
    ok(!withPeriod.candidates.some((c) => L[c.i].id === noPeriod.id) && withPeriod.excluded.noPeriod > 0,
      `given a stopwatch reading, ${noPeriod.id} is excluded and counted under "${EXCLUSION.noPeriod}"`);
    const withoutPeriod = findCandidates({ colours: [noPeriod.colours[0]], flashes, period: null }, at, 120,
      { lights: L, index: INDEX, eyeHeightM: 5 });
    ok(withoutPeriod.candidates.some((c) => L[c.i].id === noPeriod.id),
      'and with no stopwatch reading given, the same light is a candidate again');
  }

  // A light with neither a range nor a height cannot be placed above or below
  // the horizon, and unknown must not be treated as visible.
  const blind = L.find((l) => l.rangeNm == null && l.heightM == null && l.period != null);
  ok(!!blind, 'the corpus contains lights with neither a printed range nor a printed height');
  if (blind) {
    const v = visibility(blind, 1, 5);
    ok(v.effectiveNm === null && v.inSight === null,
      `${blind.id} has no computable visibility, and the answer is null rather than true or false`);
    const at = { lat: blind.lat + 0.005, lon: blind.lon };
    const fs = flashSignature(blind);
    const res = findCandidates(
      { colours: [blind.colours[0]], flashes: fs.steady ? 'steady' : fs.many ? 'many' : fs.count, period: blind.period },
      at, 120, { lights: L, index: INDEX, eyeHeightM: 5 },
    );
    ok(!res.candidates.some((c) => L[c.i].id === blind.id) && res.excluded.noVisibility > 0,
      'standing 500 m from it, it is still set aside as unknown rather than assumed visible, and counted');
  }

  // The United States gap, which is the refusal that matters most.
  const usProbes = [
    ['San Francisco Bay', 37.82, -122.48],
    ['Chicago, Lake Michigan', 41.89, -87.6],
    ['Key West', 24.55, -81.8],
    ['Chesapeake Bay', 37.0, -76.0],
    ['Cape Cod', 41.7, -70.0],
    ['Honolulu', 21.3, -157.86],
    ['Puget Sound', 47.6, -122.4],
    // Attu, the westernmost United States soil in the world, at longitude
    // +173. The Alaska box stopped at -180, so this got no panel at all: just a
    // bare empty result, which is exactly the misreading the panel exists to
    // prevent, on the coast where it matters most.
    ['Attu, the western Aleutians', 52.85, 173.18],
    ['Kiska, the western Aleutians', 51.97, 177.5],
  ];
  for (const [name, lat, lon] of usProbes) {
    const r = usGapRegion(lat, lon);
    ok(!!r, `${name} is detected as inside the United States gap (${r ? r.name : 'NOT DETECTED'})`);
  }
  for (const [name, lat, lon] of [
    ['Brest, France', 48.38, -4.5], ['Sydney', -33.85, 151.28], ['Bergen', 60.39, 5.2],
    // The western Aleutian box must not reach the Russian coast. A single box
    // wrapped through the antimeridian would have, and would have told a reader
    // off Chukotka that they were on the coast of Alaska: a new false sentence
    // in place of a missing one.
    ['Anadyr, Chukotka', 64.73, 177.5], ['Wrangel Island, Russia', 71.0, 179.5],
    ['Petropavlovsk, Kamchatka', 52.9, 158.6],
  ]) {
    ok(usGapRegion(lat, lon) === null, `${name} is not flagged as a United States gap`);
  }
  {
    const attu = usGapRegion(52.85, 173.18);
    ok(!!attu && /Aleutian/.test(attu.name), `Attu falls in "${attu ? attu.name : 'NO BOX AT ALL, which is the defect'}"`);
    const av = attu ? gapVerdict(attu, L) : null;
    ok(!!av && av.kind === 'empty' && av.total === 0,
      `and that box is reported as empty because it is: ${av ? av.total : 'no box'} records inside it, so the reader is told the book does not cover their water rather than handed a blank`);
  }
  {
    const sf = usGapRegion(37.82, -122.48);
    const c = regionCensus(sf, L);
    ok(c.us === 0, `and the census is counted, not asserted: ${c.total} records inside the California box, ${c.us} of them under a UNITED STATES heading`);
    const usAll = L.filter((l) => /^UNITED STATES/.test(l.country)).length;
    ok(usAll < 20, `the whole corpus holds ${usAll} US-headed records out of ${fmt(L.length)}`);

    // The verdict is a function of the census, and the census disagrees with the
    // flat sentence in one place. This is the check for that place.
    ok(gapVerdict(usGapRegion(41.89, -87.6), L).kind === 'empty',
      'Lake Michigan is reported as empty, because it is: no records at all in the box');
    const sfv = gapVerdict(sf, L);
    ok(sfv.kind === 'neighbours' && sfv.local === 0,
      `San Francisco is reported as neighbours only: ${sfv.total} records in the box, none of them United States`);
    const pr = gapVerdict(usGapRegion(18.4, -66.1), L);
    ok(pr.kind === 'listed' && pr.local > 0,
      `Puerto Rico is reported as LISTED, ${pr.local} records under its own heading, because NGA does list it`);
    ok(!/There is no United States coverage/.test(page) && !/no United States coverage,/.test(page),
      'and the page therefore does not carry the flat sentence "there is no United States coverage", which is false in San Juan');
  }
}

// ── family 6: the page prints the files ─────────────────────────────────────
log.push('\n[6] every figure on the page is re-derived here and has to match:');
{
  const n = L.length;
  const pct = (x) => Math.round((10000 * x) / n) / 100;
  const noPeriod = SRC.filter((l) => l.period == null).length;
  const noHeight = SRC.filter((l) => l.heightM == null).length;
  const noRange = SRC.filter((l) => l.rangeNm == null).length;
  const noVis = SRC.filter((l) => l.heightM == null && l.rangeNm == null).length;
  const findable = SRC.filter((l) => l.period != null && l.rangeNm != null && l.rangeNm >= 5 && l.heightM != null).length;
  ok(META.corpus.lights === n, `meta.json says ${fmt(META.corpus.lights)} lights and the corpus holds ${fmt(n)}`);
  ok(META.gaps.noPeriod === noPeriod && META.gaps.noPeriodPct === pct(noPeriod),
    `no printed period: ${fmt(noPeriod)} (${pct(noPeriod)}%), recounted from lights.json`);
  ok(META.gaps.noHeight === noHeight && META.gaps.noHeightPct === pct(noHeight),
    `no printed height: ${fmt(noHeight)} (${pct(noHeight)}%)`);
  ok(META.gaps.noRange === noRange && META.gaps.noRangePct === pct(noRange),
    `no printed range: ${fmt(noRange)} (${pct(noRange)}%)`);
  ok(META.gaps.noVisibility === noVis && META.gaps.noVisibilityPct === pct(noVis),
    `neither, so visibility is unknown: ${fmt(noVis)} (${pct(noVis)}%)`);
  ok(META.gaps.findable === findable && META.gaps.findablePct === pct(findable),
    `findable at all: ${fmt(findable)} (${pct(findable)}%)`);
  ok(META.us.headed === SRC.filter((l) => /^UNITED STATES/.test(l.country)).length,
    `US-headed records: ${META.us.headed}`);
  {
    let disagree = 0;
    for (const r of META.us.regions) {
      const v = gapVerdict({ lat: r.lat, lon: r.lon, local: r.local }, SRC);
      if (v.total !== r.total || v.us !== r.us || v.local !== r.localCount || v.kind !== r.kind) {
        disagree++;
        ok(false, `region verdict for ${r.name} disagrees with a recount (${r.kind} ${r.total}/${r.localCount} vs ${v.kind} ${v.total}/${v.local})`);
      }
    }
    ok(disagree === 0, `all ${META.us.regions.length} United States boxes, their counts and their verdicts, agree with a recount of the corpus`);
    ok(META.us.regions.length === US_GAP_REGIONS.length, 'and every box in the code is in the file the page reads');
    const heads = new Map();
    for (const l of SRC) {
      if (/^(UNITED STATES|PUERTO RICO|ALASKA|HAWAII|VIRGIN ISLANDS|GUAM|AMERICAN SAMOA)/.test(l.country)) {
        heads.set(l.country, (heads.get(l.country) || 0) + 1);
      }
    }
    ok(JSON.stringify(META.us.headings) === JSON.stringify(Array.from(heads.entries()).sort((a, b) => b[1] - a[1])),
      `the headings naming United States soil are recounted and match: ${META.us.headings.map(([k, n]) => `${k} ${n}`).join(', ')}`);
    ok(META.us.emptyBoxes === META.us.regions.filter((r) => r.kind === 'empty').length
      && META.us.listedBoxes === META.us.regions.filter((r) => r.kind === 'listed').length,
      `${META.us.emptyBoxes} boxes hold nothing and ${META.us.listedBoxes} are listed under their own heading`);
  }

  const build = JSON.parse(readFileSync(LAB + 'build-report.json', 'utf8'));
  ok(META.corpus.rawRows === build.rawRows && META.corpus.unparsed === build.dropped.unparsed
    && META.corpus.racon === build.dropped.racon && META.corpus.sectorOnly === build.dropped.sectorOnly,
    `the build accounting on the page is the build report: ${fmt(build.rawRows)} rows in, ${build.dropped.unparsed} unparsed, ${build.dropped.racon} racons, ${build.dropped.sectorOnly} direction lights`);
  ok(build.kept === n, 'and the report agrees with the corpus it produced');

  // The accuracy figures: re-run the same simulation at the same seed.
  const fresh = runMeasurement();
  const strip = (o) => JSON.parse(JSON.stringify(o, (k, v) => (TIMING_KEYS.includes(k) ? undefined : v)));
  ok(JSON.stringify(strip(fresh.headline)) === JSON.stringify(strip(MEASURE.headline)),
    `the headline accuracy reproduces at seed ${fresh.seed}: ${fresh.headline.inShortlistPct}% in the shortlist, ${fresh.headline.rankedFirstPct}% ranked first, median list ${fresh.headline.shortlistMedian}`);
  for (const k of Object.keys(fresh.byTolerance)) {
    if (JSON.stringify(strip(fresh.byTolerance[k])) !== JSON.stringify(strip(MEASURE.byTolerance[k]))) {
      ok(false, `the tolerance sweep at ${k} does not reproduce`);
    }
  }
  ok(Object.keys(fresh.byTolerance).every((k) => JSON.stringify(strip(fresh.byTolerance[k])) === JSON.stringify(strip(MEASURE.byTolerance[k]))),
    `the whole tolerance sweep reproduces, all ${Object.keys(fresh.byTolerance).length} settings`);
  ok(JSON.stringify(strip(fresh.byRanking)) === JSON.stringify(strip(MEASURE.byRanking))
    && JSON.stringify(strip(fresh.hardCut)) === JSON.stringify(strip(MEASURE.hardCut)),
    'the ranking comparison and the hard-cut comparison reproduce');
  // The claim the default rests on, checked rather than asserted.
  const best = Object.entries(fresh.byRanking).sort((a, b) => b[1].rankedFirstPct - a[1].rankedFirstPct)[0][0];
  ok(best === 'nearest', `the ranking rule that ships is the one that scored best (${best}, ${fresh.byRanking[best].rankedFirstPct}%)`);
  ok(fresh.headline.inShortlistPct > fresh.hardCut.inShortlistPct,
    `the marginal tier earns its keep: ${fresh.headline.inShortlistPct}% against ${fresh.hardCut.inShortlistPct}% with a hard cut at the printed range`);
  ok(fresh.defaultTolerance === DEFAULT_TOL,
    `the tolerance measured as the default (${fresh.defaultTolerance}) is the one the code uses`);

  // EVERY FIGURE ON THE PAGE IS A SLOT, AND THE TEXT SITTING IN THE SLOT BEFORE
  // JAVASCRIPT RUNS MUST ALREADY BE THE RIGHT ANSWER. Otherwise a reader with no
  // JavaScript, or a crawler that does not execute it, reads a number the page
  // itself would have corrected, which is the quietest way to be wrong.
  const slots = {
    'n-lights': fmt(META.corpus.lights),
    'm-recall': `${MEASURE.headline.inShortlistPct}%`,
    'm-median': String(MEASURE.headline.shortlistMedian),
    'f-noperiod': `${META.gaps.noPeriodPct}%`,
    'f-novis': `${META.gaps.noVisibilityPct}%`,
    'f-confradius': String(CONFUSABLE_RADIUS_KM),
    'f-rawrows': fmt(META.corpus.rawRows),
    'f-kept': fmt(META.corpus.lights),
    'f-racon': fmt(META.corpus.racon),
    'f-sector': fmt(META.corpus.sectorOnly),
    'f-unparsed': fmt(META.corpus.unparsed),
    'f-unparsedpct': `${META.corpus.unparsedPct}%`,
    // Figures that used to be typed into the prose. The page claimed no figure on
    // it was typed by hand while carrying at least four that were, and the
    // reviewer proved it by changing the printed 2.03 to 2.13 with no effect.
    'f-geocoef': String(META.geographicRange.coefficient),
    'f-samestructure': String(META.confusability.sameStructureM),
    'f-confradius2': String(CONFUSABLE_RADIUS_KM),
    'f-confradius3': String(CONFUSABLE_RADIUS_KM),
    'f-searchradius': fmt(Math.round(META.search.maxEffectiveKm)),
    'f-marginal': String(MARGINAL_FACTOR),
    'f-flashmax': String(FLASH_RANGE[1]),
    'f-flashmax2': String(FLASH_RANGE[1]),
    'f-idxradii': String(INDEX_CHECK_PLAN.radiiKm.length),
    'f-idxmin': String(Math.min(...INDEX_CHECK_PLAN.radiiKm)),
    'f-idxmax': String(Math.max(...INDEX_CHECK_PLAN.radiiKm)),
    'f-idxqueries': fmt(INDEX_CHECK_PLAN.radiiKm.length * INDEX_CHECK_PLAN.perRadius),
    'f-idxshare': `${Math.round(10000 * INDEX_CHECK_PLAN.radiiKm.length * INDEX_CHECK_PLAN.perRadius / META.corpus.lights) / 100}%`,
  };
  let slotsOk = 0;
  for (const [id, value] of Object.entries(slots)) {
    const m = new RegExp(`<(b|span) id="${id}">([^<]*)</\\1>`).exec(page);
    if (!m) { ok(false, `the page has no slot for ${id}`); continue; }
    if (m[2] !== value) { ok(false, `the static text in ${id} is "${m[2]}" but the file says "${value}"`); continue; }
    slotsOk++;
  }
  ok(slotsOk === Object.keys(slots).length,
    `all ${slotsOk} figures on the page match the artifacts before any JavaScript runs, and are rewritten from them after`);
  // And they really are rewritten, so a corpus change moves the page.
  for (const id of Object.keys(slots)) {
    if (!new RegExp(`set\\('${id}'`).test(page)) ok(false, `${id} is never written from the data at runtime`);
  }
  ok(Object.keys(slots).every((id) => new RegExp(`set\\('${id}'`).test(page)),
    'and every one of them is filled from meta.json or measurement.json at runtime');
  const usDetail = /<span id="us-detail">([^<]*)<\/span>/.exec(page);
  ok(usDetail && new RegExp(`\\b${META.us.headed}\\b`).test(usDetail[1]),
    `the United States sentence in the header carries the counted figure (${META.us.headed})`);

  // The geographic-range coefficient is not typed anywhere: it is what the
  // engine returns for a one metre lamp seen from sea level.
  ok(Math.abs(META.geographicRange.coefficient - geographicRangeNm(1, 0)) < 1e-9,
    `the coefficient the page prints, ${META.geographicRange.coefficient}, is what engine.mjs returns for a 1 m lamp and a 0 m eye`);
  ok(!/2\.03 [×x]/.test(page.replace(/<span id="f-geocoef">[^<]*<\/span>/, 'SLOT')),
    'and it appears on the page only inside that slot, never as a second typed copy');
  ok(META.confusability.sameStructureM === Math.round(SAME_STRUCTURE_KM * 1000),
    `the 50 m same-structure figure the page prints is ${SAME_STRUCTURE_KM} km from the code, converted`);
  ok(META.confusability.radiusKm === CONFUSABLE_RADIUS_KM,
    'and the confusability radius in meta.json is the constant the code uses');
}

// ── family 6b: the prior-art claims match what was actually seen ────────────
log.push('\n[6b] the prior-art section quotes the evidence file, not a memory of it:');
{
  const PA = JSON.parse(readFileSync(LAB + 'prior-art.json', 'utf8'));
  const mr = PA.items.find((i) => i.id === 'marineradar');
  ok(!!mr, 'the evidence file records the marineradar.com check');
  ok(page.includes(mr.found.searchAriaLabel),
    `the page quotes the site's own search control label verbatim: "${mr.found.searchAriaLabel}"`);
  ok(page.includes(String(mr.found.claimedLights)) || page.includes(fmt(mr.found.claimedLights)),
    `the page prints the ${fmt(mr.found.claimedLights)} lights that site claims, which is fewer than our ${fmt(L.length)}`);
  ok(mr.found.characteristicSearch === false && /not a reverse lookup/.test(page),
    'the conclusion on the page is the conclusion in the evidence: a forward directory, not a reverse lookup');
  ok(mr.found.coversUnitedStates === true && /does<\/em> cover the United States/.test(page),
    'and the page says where that site beats this one, rather than only where it loses');
  ok(mr.attempts.some((a) => /403/.test(String(a.result))) && /403/.test(page),
    'the page says the site refused automated fetches, which is why it was opened by hand');
  ok(/prior-art\.json/.test(page), 'the page points at the evidence file so a reader can re-check it');

  // lighthouses.app: 59,000+ USCG aids, free, and it covers the coast this page
  // cannot. It belongs in the list precisely because it beats this tool where
  // this tool is blind, and it does not narrow the hedge because it has no
  // character filter. Both halves of that are in the evidence file.
  const PA2 = JSON.parse(readFileSync(LAB + 'tool-prior-art.json', 'utf8'));
  const la = PA2.items.find((i) => i.id === 'lighthouses-app');
  ok(!!la, 'the evidence file records the lighthouses.app check');
  if (la) {
    ok(page.includes(la.url) || page.includes(la.url.replace(/\/$/, '')),
      `the page links to ${la.url}`);
    ok(page.includes(la.name) && page.includes(la.sectionTitle),
      `and names it as ${la.name}, "${la.sectionTitle}"`);
    ok(page.includes(la.found.claimedLightsText) || page.includes(fmt(la.found.claimedLights)),
      `the page prints the ${la.found.claimedLightsText} aids it carries`);
    ok(page.includes(la.found.source), `and where they come from: the ${la.found.source}`);
    ok(la.found.coversUnitedStates === true && la.found.free === true
      && /it is the better reference/.test(page),
      'and says plainly that on a US shore it is the better reference than this page');
    ok(la.found.characteristicSearch === false && la.found.rhythmFilter === false
      && la.found.periodFilter === false && la.found.colourFilter === false
      && /no filter on character, rhythm, period or colour/.test(page),
      'the conclusion on the page is the conclusion in the evidence: a forward directory with no character filter');
    ok(la.found.searchInputs === 1 && la.found.selectElements === 0
      && /exactly\s*\n?\s*one text input, zero select elements/.test(page),
      `and the page states what was counted: ${la.found.searchInputs} text input, ${la.found.selectElements} selects`);
    ok(page.includes(la.checkedOn), `the page carries the date it was checked, ${la.checkedOn}`);
    ok(/tool-prior-art\.json/.test(page), 'and points at the evidence file for it');
    ok(typeof la.whatWouldFalsifyThis === 'string' && la.whatWouldFalsifyThis.length > 40,
      'the evidence file says what would falsify the claim, which is what makes it a claim');
  }
}

// ── family 7: the URL is the whole query ────────────────────────────────────
log.push('\n[7] the URL grammar round-trips:');
{
  const cases = [
    { lat: 50.152, lng: -5.064, colours: ['W'], flashes: 2, period: 15, eye: 2, tol: 0.2, radiusKm: 110 },
    { lat: -33.851, lng: 151.283, colours: ['R', 'G'], flashes: 'many', period: 4.5, eye: 15, tol: 0.05, radiusKm: 60 },
    { lat: 0, lng: 0, colours: [], flashes: 'steady', period: null, eye: 5, tol: 0.3, radiusKm: null },
    { lat: 60.39, lng: 5.2, colours: ['Bu', 'Or', 'Vi'], flashes: 6, period: 20, eye: 30, tol: 0.15, radiusKm: 25 },
    { lat: -89.9, lng: 179.999, colours: ['Y'], flashes: 1, period: 0.5, eye: 1, tol: 0.25, radiusKm: 1 },
  ];
  for (const c of cases) {
    const q = encodeQuery(c);
    const back = decodeQuery('?' + q);
    const same = back.lat === c.lat && back.lng === c.lng
      && JSON.stringify(back.colours) === JSON.stringify(c.colours)
      && back.flashes === c.flashes
      && (c.period == null ? back.period === null : Math.abs(back.period - c.period) < 1e-9)
      && Math.abs(back.eye - c.eye) < 1e-9
      && Math.abs(back.tol - c.tol) < 1e-9
      && (c.radiusKm == null ? back.radiusKm === null : back.radiusKm === c.radiusKm);
    ok(same, `?${q}`);
  }
  // EVERY NUMERIC BOUND, PUSHED THROUGH. This block exists because the bounds
  // were never exercised with numbers: the reviewer deleted the latitude bound
  // and widened flashes from 12 to 999 and this file stayed green, because the
  // only bad values it ever fed in were words. A bound is only checked by a
  // number just outside it.
  const BOUNDS = [
    ['lat', LAT_RANGE, (v) => `?lat=${v}`, (q) => q.lat],
    ['lng', LNG_RANGE, (v) => `?lng=${v}`, (q) => q.lng],
    ['flashes', FLASH_RANGE, (v) => `?flashes=${v}`, (q) => q.flashes],
    ['eye', EYE_RANGE_M, (v) => `?eye=${v}`, (q) => q.eye],
    ['tol', TOL_RANGE_PCT, (v) => `?tol=${v}`, (q) => (q.tol == null ? null : q.tol * 100)],
  ];
  for (const [name, [lo, hi], mk, get] of BOUNDS) {
    const step = name === 'flashes' ? 1 : Math.max(0.001, (hi - lo) / 1000);
    const inLo = decodeQuery(mk(lo)), inHi = decodeQuery(mk(hi));
    const outLo = decodeQuery(mk(lo - step)), outHi = decodeQuery(mk(hi + step));
    const near = (a, b) => a != null && Math.abs(a - b) < 1e-6;
    ok(near(get(inLo), lo) && near(get(inHi), hi),
      `${name}: the ends of the documented range, ${lo} and ${hi}, are accepted`);
    ok(get(outLo) === null && get(outHi) === null,
      `  and ${lo - step} and ${hi + step}, just outside it, are refused rather than clamped`);
    ok(outLo.rejected.some((r) => r.param === name) && outHi.rejected.some((r) => r.param === name),
      `  and both refusals are reported by name, so the page can say what it did not run`);
  }
  // The specific values the reviewer used, named, so the regression is explicit.
  ok(decodeQuery('?lat=95').lat === null && decodeQuery('?lat=95').rejected.length === 1,
    'a latitude of 95 decodes to null and is reported, not silently accepted');
  ok(decodeQuery('?flashes=999').flashes === null, 'a flash count of 999 decodes to null');
  ok(decodeQuery('?flashes=13').flashes === null, `a flash count of 13 decodes to null, because the corpus tops out at ${FLASH_RANGE[1]}`);
  ok(decodeQuery('?tol=45').tol === null && decodeQuery('?tol=45').rejected[0].allowed === `${TOL_RANGE_PCT[0]} to ${TOL_RANGE_PCT[1]} per cent`,
    'a tolerance of 45 per cent is refused and the refusal names the range it is outside');
  // FLASH_RANGE is not a preference: it is the largest group the book prints.
  {
    let maxCountable = 0;
    for (const l of SRC) {
      const fs = flashSignature(l);
      if (fs.count == null) continue;
      const top = fs.plusLong ? fs.count + 1 : fs.count;
      if (top > maxCountable) maxCountable = top;
    }
    ok(FLASH_RANGE[1] === maxCountable,
      `the top of the flash range, ${FLASH_RANGE[1]}, is the largest countable group anywhere in the corpus, recounted here (${maxCountable})`);
    ok(META.counting.maxCountableFlashes === maxCountable
      && JSON.stringify(META.counting.flashRange) === JSON.stringify(FLASH_RANGE),
      'and meta.json, which the page reads, carries that same recount');
  }

  // CONTROL STATE MUST EQUAL QUERY STATE across the whole documented range.
  // These were two independent lists once: the decoder took flashes 0 to 12 and
  // the button row stopped at 6, so ?flashes=7 ran a filter no control showed.
  {
    const optionValues = [...page.matchAll(/for \(let n = FLASH_RANGE\[0\]; n <= FLASH_RANGE\[1\]; n\+\+\)/g)].length;
    ok(optionValues === 1, 'the flash buttons are generated from FLASH_RANGE rather than typed out');
    ok(/lat\.min = LAT_RANGE\[0\]/.test(page) && /lng\.min = LNG_RANGE\[0\]/.test(page)
      && /eye\.min = EYE_RANGE_M\[0\]/.test(page) && /tol\.min = TOL_RANGE_PCT\[0\]/.test(page),
      'and every numeric control takes its own min and max from the same constants the decoder enforces');
    ok(!/<input type="range" id="tol"[^>]*min="/.test(page) && !/<input type="range" id="tol"[^>]*max="/.test(page),
      'the tolerance slider carries no hard-coded min or max in the markup that could drift from the decoder');
    // The URL table the reader sees is the ranges, rendered.
    const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
    const rows = QUERY_BOUNDS.map((b) => `<tr><td><code>${esc(b.param)}</code></td><td>${esc(b.value)}</td><td>${esc(b.meaning)}</td></tr>`).join('');
    ok(page.includes(rows),
      'the URL table printed in the file is exactly what QUERY_BOUNDS renders, so a reader with no JavaScript reads the enforced ranges');
    ok(/el\('urlRows'\)\.innerHTML = QUERY_BOUNDS\.map\(urlRow\)/.test(page),
      'and it is rewritten from the same constants when the page loads');
    ok(!/an integer, or <code>many<\/code>/.test(page),
      'and the old table row that documented flashes as "an integer" is gone, because it was not one');
  }

  // Garbage in the address bar must not become a confident query.
  const junk = decodeQuery('?lat=abc&lng=999&colour=purple,W&flashes=banana&period=-4&eye=&tol=');
  ok(junk.lat === null, 'a latitude of "abc" decodes to null, not to 0');
  ok(junk.lng === null, 'a longitude of 999 decodes to null, not to 999');
  ok(JSON.stringify(junk.colours) === '["W"]', 'an unknown colour name is dropped and the known one kept');
  ok(junk.flashes === null, 'a flash count of "banana" decodes to null');
  ok(junk.rejected.length === 5 && junk.rejected.map((r) => r.param).join(',') === 'lat,lng,colour,flashes,period',
    `and all five bad parameters are reported by name rather than dropped in silence (${junk.rejected.map((r) => r.param).join(', ')})`);
  ok(decodeQuery('?lat=50&lng=-5&colour=W&flashes=2&period=10&eye=5&tol=20&r=110').rejected.length === 0,
    'a wholly valid query reports nothing rejected, so the report is not a thing that always fires');
  ok(findCandidates({ colours: junk.colours, flashes: junk.flashes, period: junk.period },
    { lat: junk.lat, lon: junk.lng }, 120, { lights: L, index: INDEX }).reason === 'no-position',
    'and a query built from that junk refuses rather than answering about the Gulf of Guinea');
  // Colour codes are case-insensitive on the way in and canonical on the way out.
  ok(JSON.stringify(decodeQuery('?colour=w,r,bu').colours) === '["W","R","Bu"]',
    'lower-case colour codes decode to the canonical spellings');
  // The documented parameter names are the ones the code reads.
  for (const p of ['lat', 'lng', 'colour', 'flashes', 'period', 'eye', 'tol', 'r']) {
    ok(new RegExp(`<code>${p}</code>`).test(page), `the page documents the ${p} parameter`);
  }
  const EXAMPLE = '?lat=50.152&lng=-5.064&colour=W&flashes=1&period=3&eye=3';
  ok(page.includes(EXAMPLE.replace(/&/g, '&amp;')),
    'the worked example printed on the page is the one checked here');
  const ex = decodeQuery(EXAMPLE);
  const exRes = findCandidates({ colours: ex.colours, flashes: ex.flashes, period: ex.period },
    { lat: ex.lat, lon: ex.lng }, META.search.maxEffectiveKm, { lights: L, index: INDEX, eyeHeightM: ex.eye });
  ok(exRes.ok && exRes.total === 1,
    `and it resolves, out of ${fmt(L.length)} lights, to exactly ${exRes.total} candidate`);
  ok(exRes.total >= 1 && /Lizard Point/.test(exRes.candidates[0].light.name || ''),
    `which is ${exRes.total ? (exRes.candidates[0].light.name || '').trim() : 'nothing'}, the name the page prints next to that link`);
  ok(/Lizard Point/.test(page), 'and the page does print that name, so the claim is falsifiable');
}

// ── the grammar of what a person can count ──────────────────────────────────
log.push('\n[8] the flash grammar matches what a person standing in the dark would count:');
{
  const sig = (head, period) => flashSignature({
    rhythm: parseCharacteristic(head).rhythm,
    groups: parseCharacteristic(head).groups,
    period,
  });
  const cases = [
    ['Fl.W.', 1, false, false, 'one flash'],
    ['Fl.(2)W.', 2, false, false, 'a group of two'],
    ['Fl.(2+1)W.R.', 3, false, false, 'two then one is three flashes to a counter'],
    ['Oc.W.', 1, false, false, 'one eclipse counts as one'],
    ['Iso.W.', 1, false, false, 'isophase, one on and one off'],
    ['F.W.', 0, false, true, 'a fixed light never goes out'],
    ['Q.W.', null, true, false, 'quick with no group is too fast to count'],
    ['V.Q.W.', null, true, false, 'very quick likewise'],
    ['Q.(6)+L.Fl.W.', 6, false, false, 'the south cardinal: six quick flashes, and a long one after'],
    ['Mo.(A)W.', 2, false, false, 'Morse A is dot dash, which is two flashes'],
    ['Mo.(U)W.', 3, false, false, 'Morse U is dot dot dash, which is three'],
  ];
  for (const [head, count, many, steady, why] of cases) {
    const s = sig(head, 10);
    ok(s.count === count && s.many === many && s.steady === steady, `${head} counts as ${count === null ? 'uncountable' : count}: ${why}`);
  }
  ok(sig('Q.(6)+L.Fl.W.', 15).plusLong === true,
    'and the cardinal mark accepts a count of seven too, because the long flash is easy to include');
  // In a real query, a south cardinal must answer to both 6 and 7.
  const card = L.find((l) => l.rhythm === 'Q+LFl' && l.period != null && l.rangeNm != null && l.rangeNm >= 5 && l.heightM != null);
  if (card) {
    const at = { lat: card.lat + 0.01, lon: card.lon };
    for (const n of [6, 7]) {
      const r = findCandidates({ colours: [card.colours[0]], flashes: n, period: card.period }, at, 60,
        { lights: L, index: INDEX });
      ok(r.candidates.some((c) => L[c.i].id === card.id), `a real ${card.head.replace(/\n/g, ' ')} answers to a count of ${n}`);
    }
  }
}

// ── the confusability count is the study's own ──────────────────────────────
log.push('\n[9] the confusability count is the published definition, not a new one:');
{
  const a = { multiple: 1, rhythm: 'Fl', groups: [2], period: 10, colours: ['W'] };
  const b = { multiple: 1, rhythm: 'Fl', groups: [2], period: 10, colours: ['W', 'R', 'G'] };
  const c = { multiple: 1, rhythm: 'Fl', groups: [2], period: 10, colours: ['R'] };
  const d = { multiple: 1, rhythm: 'Fl', groups: [2], period: 12, colours: ['W'] };
  const e = { multiple: 2, rhythm: 'Fl', groups: [2], period: 10, colours: ['W'] };
  ok(confusable(a, b), 'a plain white light and a sectored light that shows white are confusable');
  ok(!confusable(a, c), 'a white light and a red one are not');
  ok(!confusable(a, d), 'the same rhythm at a different printed period is not');
  ok(!confusable(a, e), 'and two lanterns are not one lantern');
  // Against the study's own analysis constants. The 50 m exclusion used to be
  // regexed out of analyze.mjs here and then written as a literal 0.05 in the
  // brute-force path below, which is two numbers that could drift while this
  // file said they agreed. The constant is now imported and used in both.
  ok(CONFUSABLE_RADIUS_KM === 10, 'the radius is the study headline radius, 10 km');
  const analyze = readFileSync(LAB + 'analyze.mjs', 'utf8');
  const m = /const SAME_STRUCTURE_KM = ([0-9.]+);/.exec(analyze);
  ok(m && Number(m[1]) === SAME_STRUCTURE_KM,
    `the same-structure exclusion the tool imports (${SAME_STRUCTURE_KM * 1000} m) is the number in the study's analyze.mjs (${m ? Number(m[1]) * 1000 : '?'} m)`);
  // A real light, counted, and cross-checked by brute force, using the SAME
  // constants in both paths.
  const probe = L.find((l) => l.period != null && l.rangeNm != null && l.rangeNm >= 15 && confusableNear(l, { lights: L, index: INDEX }).length >= 1);
  ok(!!probe, 'the corpus contains lights with a confusable neighbour within 10 km');
  if (probe) {
    const viaIndex = confusableNear(probe, { lights: L, index: INDEX }).length;
    let brute = 0;
    for (const o of L) {
      if (o.id === probe.id) continue;
      const dist = haversineKm(probe, o);
      if (dist >= SAME_STRUCTURE_KM && dist <= CONFUSABLE_RADIUS_KM && confusable(probe, o)) brute++;
    }
    ok(viaIndex === brute && brute > 0, `${(probe.name || probe.id).trim()}: ${viaIndex} confusable neighbours by index, ${brute} by exhaustive scan`);
  }
  // And the radius really bites: a wider one has to find at least as many, and
  // somewhere in the corpus strictly more, or the radius is decoration.
  {
    let widerFound = 0, widerCases = 0;
    for (let k = 0; k < 4000 && widerCases < 300; k++) {
      const l = L[(k * 6151) % L.length];
      if (l.period == null) continue;
      widerCases++;
      const at10 = confusableNear(l, { lights: L, index: INDEX }).length;
      const at40 = confusableNear(l, { lights: L, index: INDEX, radiusKm: 40 }).length;
      if (at40 < at10) { widerFound = -1; break; }
      if (at40 > at10) widerFound++;
    }
    ok(widerFound > 0,
      `widening the confusability radius from ${CONFUSABLE_RADIUS_KM} km to 40 km finds strictly more twins for ${widerFound} of 300 sampled lights, which is why a 10 km count cannot speak for a 110 km shortlist`);
  }
}

// ── the page's own honesty surface ──────────────────────────────────────────
log.push('\n[10] the page says the things it must say, where they can be seen:');
{
  const head = page.slice(0, page.indexOf('</header>'));
  ok(/Not for navigation/i.test(head), 'NOT FOR NAVIGATION appears above the fold, in the header');
  ok(/no United States coverage|not cover United States|There is no United States coverage/i.test(head),
    'the absence of United States coverage appears above the fold too');
  ok(/foreign/i.test(head), 'and the header says why: Pub. 110-116 is the foreign list');
  ok(/USCG Light List|navcen\.uscg\.gov/.test(page), 'the page sends a US reader to the list that does cover them');
  ok(/does not model land|not modelled|Land is\s*\n?\s*not modelled/i.test(page), 'the page says it does not model land');
  ok(/meteorological visibility of 10/.test(page), 'and that nominal range assumes a 10 nautical mile visibility');
  ok(/verify-what-light\.mjs/.test(page), 'the page names the check that makes it checkable');
  ok(existsSync(ROOT + 'verify-what-light.mjs'), 'and that file exists, so the instruction it prints runs');
  ok(page.includes('${MARGINAL_FACTOR}×') && /import \{[\s\S]*?MARGINAL_FACTOR/.test(page),
    `the marginal factor of ${MARGINAL_FACTOR} is printed on the page from the constant the code uses, so the two cannot drift apart`);
  ok(/chosen by judgement rather than measured/.test(page),
    'and is labelled as the one number here not arrived at by measurement');
  const noComments = page.replace(/<!--[\s\S]*?-->/g, '');
  ok(!/\u2014/.test(noComments), 'the page carries no em dashes (the house rule)');
  ok(!/\u2014/.test(readFileSync(LAB + 'find.mjs', 'utf8')), 'nor does find.mjs, nor the corpus builder');
  ok(!/\u2014/.test(readFileSync(LAB + 'build-tool-corpus.mjs', 'utf8'))
    && !/\u2014/.test(readFileSync(LAB + 'measure-find.mjs', 'utf8'))
    && !/\u2014/.test(readFileSync(LAB + 'tool-prior-art.json', 'utf8'))
    && !/\u2014/.test(readFileSync(TOOL + 'meta.json', 'utf8'))
    && !/\u2014/.test(readFileSync(TOOL + 'measurement.json', 'utf8')),
    'and nor do the artifacts the page prints from, which reach the reader as prose');
  ok(/home-banner\.js/.test(page), 'the page ends with the site banner script');
  ok(/rel="canonical" href="https:\/\/artwaste\.land\/tools\/what-light\/"/.test(page), 'the canonical URL is set');
  ok(/"@type":"WebApplication"/.test(page), 'and the page carries a WebApplication description for machines');

  // SENTENCES THAT WERE TRUE OF AN EARLIER VERSION AND ARE NOT TRUE NOW. Each of
  // these was a specific overclaim; each is asserted gone, because a deleted
  // sentence that quietly comes back is the same defect twice.
  const RETIRED = [
    [/If you have matched the rhythm, you have matched the light/,
      'the confusability line no longer concludes "you have matched the light" from a 10 km sample'],
    [/It will not tell you the answer when the answer is a coin toss/,
      'the page no longer promises to withhold coin-toss answers in a form it did not implement'],
    [/Each candidate is drawn\s*\n?\s*at its real bearing/,
      'the horizon caption no longer says EVERY candidate is drawn when only the first few are'],
    [/no figure\s*\n?\s*on this page is typed by hand/,
      'and the page no longer claims no figure on it is typed by hand in those words'],
  ];
  for (const [re, why] of RETIRED) ok(!re.test(page), why);
  // What replaced them has to be present, or "asserted gone" is just deletion.
  ok(/is an ordering and not an identification/.test(page),
    'the tie is described in the words the code actually prints');
  ok(/This list is cut/.test(page) && /are not on this\s*\n?\s*page at all/.test(page),
    'the shortlist cut is stated on the page');
  ok(/inside their own advertised range/.test(page) && /which are by\s*\n?\s*construction <em>outside<\/em> their advertised range/.test(page),
    'and the lede says in the same breath that the marginal tier is outside that range, rather than 700 words later');
  ok(/That is a sample and not a\s*\n?\s*proof/.test(page),
    'the index claim in the footer is narrowed to the sample that is actually taken');

  // The social card. It was pointing at the site's generic image while a card
  // made for this tool sat unused, so every share of this page showed something
  // else's picture.
  const CARD = ROOT + 'public/media/tool-what-light.png';
  ok(existsSync(CARD), 'the tool has its own social card on disk at /media/tool-what-light.png');
  ok(/<meta property="og:image" content="https:\/\/artwaste\.land\/media\/tool-what-light\.png" \/>/.test(page),
    'og:image points at it rather than at the site default');
  ok(/<meta property="og:image:width" content="1280" \/>/.test(page)
    && /<meta property="og:image:height" content="800" \/>/.test(page),
    'og:image:width and og:image:height are 1280 by 800');
  ok(/"image":\{"@type":"ImageObject","url":"https:\/\/artwaste\.land\/media\/tool-what-light\.png","width":1280,"height":800\}/.test(page),
    'and the JSON-LD image is the same file at the same size');
  ok(/<meta name="twitter:image" content="https:\/\/artwaste\.land\/media\/tool-what-light\.png" \/>/.test(page),
    'so is the twitter card image');
  {
    // The declared size has to be the real one's aspect ratio, or the card is
    // cropped by every reader of the tag. PNG header: width and height are
    // big-endian 32-bit at bytes 16 and 20.
    const buf = readFileSync(CARD);
    const w = buf.readUInt32BE(16), h = buf.readUInt32BE(20);
    ok(w / h === 1280 / 800, `the file is ${w} by ${h}, which is the declared 1280 by 800 ratio exactly`);
  }
}

// ── a whole worked answer, end to end ───────────────────────────────────────
log.push('\n[11] one whole answer, end to end, as a reader would get it:');
{
  // Lizard Point, the light at the southern tip of Britain, from a boat off the
  // Cornish coast. Everything below is read out of the record.
  const lizard = L.filter((l) => /LIZARD/i.test(l.name || '') && l.rangeNm != null && l.rangeNm >= 20)[0];
  ok(!!lizard, 'the corpus holds the Lizard');
  if (lizard) {
    const eye = 3;
    const geo = geographicRangeNm(lizard.heightM, eye);
    const dKm = 20;
    const at = { lat: lizard.lat - dKm / 111.19, lon: lizard.lon };
    const fs = flashSignature(lizard);
    const res = findCandidates(
      { colours: [lizard.colours[0]], flashes: fs.count, period: lizard.period },
      at, 120, { lights: L, index: INDEX, eyeHeightM: eye, tol: DEFAULT_TOL },
    );
    const hit = res.candidates.find((c) => L[c.i].id === lizard.id);
    ok(!!hit, `${(lizard.name || '').trim()} (${lizard.head.replace(/\n/g, ' ')} ${lizard.period}s, ${lizard.rangeNm} nm, ${lizard.heightM} m) is returned from 20 km south of it`);
    if (hit) {
      ok(res.candidates.indexOf(hit) === 0, `  and it is first of ${res.candidates.length}`);
      ok(Math.abs(hit.bearing - 0) < 1 || Math.abs(hit.bearing - 360) < 1, `  bearing ${hit.bearing.toFixed(1)}°, which is due north of the observer as placed`);
      ok(hit.vis.geoNm !== null && Math.abs(hit.vis.geoNm - geo) < 1e-9, `  geographic range ${geo.toFixed(1)} nm for an eye ${eye} m up`);
      const sched = scheduleOf(lizard);
      ok(sched !== null, '  it has a schedule to animate');
      // The light must actually be lit some of the time and dark some of the time.
      let lit = 0;
      for (let t = 0; t < lizard.period * 4; t += 0.05) if (litAt(sched, t)) lit++;
      const frac = lit / (lizard.period * 4 / 0.05);
      ok(frac > 0 && frac < 1, `  and it is lit ${(frac * 100).toFixed(0)}% of the time, so the strip on screen is a rhythm and not a solid bar`);
      // This used to read ok(Array.isArray(conf), ...): an assertion that an
      // array is an array, which no change to the count could ever fail. The
      // count is now held against an exhaustive scan.
      const conf = confusableNear(lizard, { lights: L, index: INDEX });
      let bruteConf = 0;
      for (const o of L) {
        if (o.id === lizard.id) continue;
        const d = haversineKm(lizard, o);
        if (d >= SAME_STRUCTURE_KM && d <= CONFUSABLE_RADIUS_KM && confusable(lizard, o)) bruteConf++;
      }
      ok(conf.length === bruteConf && conf.length === 0,
        `  confusable neighbours within ${CONFUSABLE_RADIUS_KM} km: ${conf.length} by index, ${bruteConf} by exhaustive scan, and it is nought`);
    }
  }
}

// ── family 12: a real browser, and what the reader actually sees ────────────
//
// THE MISSING FAMILY. Everything above drives the query layer through the module
// boundary. The page can import that layer and still print something else, and it
// did: findCandidates correctly refused a typed latitude of 95 with
// reason 'no-position', render() special-cased only 'no-observation', and the
// reader got "searching 0 records within 110 km ... NaN candidates" with no
// refusal panel and nothing in the console. Every check above passed while that
// was on screen. So this family serves public/ over HTTP, loads the page in
// Chromium, and reads the rendered DOM.
log.push('\n[12] a real browser loads the page and the reader sees what is claimed:');
{
  const MIME = {
    '.html': 'text/html; charset=utf-8', '.mjs': 'text/javascript', '.js': 'text/javascript',
    '.json': 'application/json', '.css': 'text/css', '.svg': 'image/svg+xml',
    '.png': 'image/png', '.woff2': 'font/woff2', '.woff': 'font/woff',
  };
  const server = createServer((req, res) => {
    let p = decodeURIComponent(new URL(req.url, 'http://localhost').pathname);
    if (p.endsWith('/')) p += 'index.html';
    const file = ROOT + 'public' + p;
    if (!file.startsWith(ROOT + 'public/') || !existsSync(file) || !statSync(file).isFile()) {
      res.writeHead(404); res.end('not here'); return;
    }
    res.writeHead(200, { 'content-type': MIME[extname(file)] || 'application/octet-stream' });
    res.end(readFileSync(file));
  });
  await new Promise((r) => server.listen(0, '127.0.0.1', r));
  const BASE = `http://127.0.0.1:${server.address().port}/tools/what-light/`;

  const { chromium } = await import('playwright');
  const browser = await chromium.launch({ args: ['--no-sandbox'] });
  const ctx = await browser.newContext();
  try {
    /** Load a query, wait for the corpus, and hand back the rendered page. */
    const open = async (query) => {
      const pg = await ctx.newPage();
      const errors = [];
      pg.on('pageerror', (e) => errors.push(String(e)));
      pg.on('console', (msg) => { if (msg.type() === 'error') errors.push('console: ' + msg.text()); });
      await pg.goto(BASE + query, { waitUntil: 'load' });
      await pg.waitForFunction(() => window.__WHATLIGHT && window.__WHATLIGHT.lights(), null, { timeout: 90000 });
      await pg.waitForTimeout(250);
      return { pg, errors };
    };
    const textOf = (pg, sel) => pg.$eval(sel, (n) => n.textContent.replace(/\s+/g, ' ').trim()).catch(() => null);

    // 1. THE WORKED EXAMPLE. The page says this link resolves to exactly one
    //    light, the Lizard. A reader who follows it must see that.
    {
      const { pg, errors } = await open('?lat=50.152&lng=-5.064&colour=W&flashes=1&period=3&eye=3');
      const summary = await textOf(pg, '#results .summary');
      const cards = await pg.locator('#results .cand').count();
      const first = await textOf(pg, '#results .cand .nm');
      ok(cards === 1 && /Lizard Point/.test(first || ''),
        `the deep link on the page renders exactly ${cards} card and it is ${first}`);
      ok(/\b1 candidate\b/.test(summary || ''), `  and the summary line says "1 candidate": ${summary}`);
      ok(!/NaN/.test(await textOf(pg, '#results') || ''), '  with no NaN anywhere in the result');
      ok(errors.length === 0, `  and no page errors (${errors.join('; ') || 'none'})`);
      // the animation is real: the strip canvas has ink in it
      const painted = await pg.evaluate(() => {
        const cv = document.querySelector('canvas.stripcv');
        if (!cv) return null;
        const d = cv.getContext('2d').getImageData(0, 0, cv.width, cv.height).data;
        let lit = 0;
        for (let i = 0; i < d.length; i += 4) if (d[i] + d[i + 1] + d[i + 2] > 200) lit++;
        return lit;
      });
      ok(painted !== null && painted > 0, `  and its schedule strip is actually drawn (${painted} lit pixels)`);
      await pg.close();
    }

    // 2. A TYPED LATITUDE OF 95. The defect itself, reproduced through the
    //    controls rather than through the URL, because the URL path was fine.
    {
      const { pg, errors } = await open('');
      await pg.fill('#lat', '95');
      await pg.fill('#lng', '0');
      await pg.click('#go');
      await pg.waitForTimeout(300);
      const body = await textOf(pg, '#results');
      ok(!/NaN/.test(body || ''), 'typing a latitude of 95 and pressing the button prints no NaN');
      ok(await pg.locator('#results .refusal').count() >= 1,
        '  it produces a refusal panel rather than a summary line');
      // The wording changed on 2026-08-06 when every control was routed through
      // decodeQuery: an out-of-range latitude is now REJECTED at the control and
      // named there, so state never holds it and the results panel says the
      // honest thing about the state it does hold. Both halves are asserted.
      ok(/no position, no answer|not a position on this planet/.test(body || ''),
        '  which says, of the state that actually ran, that there is no position in it');
      const note = await textOf(pg, '#rejected');
      ok(/lat\s*=\s*95/.test(note || '') && /not used/i.test(note || ''),
        '  and the control itself names the 95 as the value it would not take',
        (note || '').trim().slice(0, 70));
      ok(!/candidate/.test(body || ''), '  and does not report a candidate count at all');
      ok(await pg.locator('#results .cand').count() === 0, '  and renders no candidate cards');
      ok(errors.length === 0, `  with nothing in the console (${errors.join('; ') || 'none'})`);
      await pg.close();
    }

    // 3. THE FIJI SEAM. An observer at longitude +179.9 and the answer at
    //    -179.954: the case the index could not see at all until the seam fix.
    {
      const { pg, errors } = await open('?lat=-16.13&lng=179.9&colour=W&flashes=2&period=25&eye=5');
      const first = await textOf(pg, '#results .cand .nm');
      const body = await textOf(pg, '#results');
      ok(/Cape Undu/.test(first || ''),
        `across the antimeridian, the page names ${first}, which sits at longitude -179.954`);
      ok(/15\.\d km/.test(body || ''), '  at the distance the engine computes, about 15.6 km');
      ok(errors.length === 0, `  with no page errors (${errors.join('; ') || 'none'})`);
      await pg.close();
    }

    // 4. THE NEWFOUNDLAND PAIR. Two Fl.W. 5s lights 29.6 km apart, identical on
    //    every axis a person can measure. The page used to print "nothing within
    //    10 km is confusable with this one, you have matched the light" on both.
    {
      const { pg, errors } = await open('?lat=49.7078&lng=-54.8&colour=W&period=5&eye=5');
      const body = await textOf(pg, '#results');
      ok(/coin toss/.test(body || ''), 'the ambiguous Newfoundland pair is announced as a coin toss');
      ok(/Long Point/.test(body || '') && /Surgeon Cove Point/.test(body || ''),
        '  and both lights are named in that panel');
      ok(/29\.6 km apart/.test(body || ''), '  with the distance between them, 29.6 km');
      ok(/is an ordering and not an identification/.test(body || ''),
        '  and the sentence that the ranking is not an identification');
      ok(!/you have matched the light/.test(body || ''),
        '  and the old claim "you have matched the light" appears nowhere on the rendered page');
      ok(/That is a check on its own neighbourhood only/.test(body || ''),
        '  while the 10 km count is still shown, scoped to what it checked');
      const tiedCards = await pg.locator('#results .cand', { hasText: 'cannot be told apart' }).count();
      ok(tiedCards >= 2, `  and ${tiedCards} of the cards themselves say they cannot be told apart`);
      ok(errors.length === 0, `  with no page errors (${errors.join('; ') || 'none'})`);
      await pg.close();
    }

    // 5. THE 48-CANDIDATE CUT. 48 match, 24 cards render, 14 are drawn. All
    //    three numbers have to be on screen.
    {
      const { pg, errors } = await open('?lat=35.48002&lng=129.42868&period=5&eye=5');
      const body = await textOf(pg, '#results');
      const cards = await pg.locator('#results .cand').count();
      const expected = findCandidates({ colours: [], flashes: null, period: 5 },
        { lat: 35.48002, lon: 129.42868 }, META_RADIUS,
        { lights: L, index: INDEX, eyeHeightM: 5, limit: SHORTLIST_CARDS });
      ok(new RegExp(`\\b${expected.total} candidates\\b`).test(body || ''),
        `the crowded query reports ${expected.total} candidates, the number the query layer returns`);
      ok(cards === SHORTLIST_CARDS, `  and renders ${cards} cards`);
      ok(new RegExp(`This list is cut.*?${expected.total} records`).test(body || '')
        && new RegExp(`${expected.hidden} are not on this page at all`).test(body || ''),
        `  and says so: ${expected.shown} shown, ${expected.hidden} not on the page at all`);
      ok(new RegExp(`The first ${HORIZON_MARKS} candidates of ${expected.total} are drawn`).test(body || ''),
        `  and the horizon caption says only the first ${HORIZON_MARKS} are drawn`);
      const marks = await pg.evaluate(() => {
        const cv = document.querySelector('#horizon');
        return cv ? cv.width > 0 : false;
      });
      ok(marks, '  and the horizon canvas is really there and sized');
      ok(errors.length === 0, `  with no page errors (${errors.join('; ') || 'none'})`);
      await pg.close();
    }

    // 6. CONTROL STATE EQUALS QUERY STATE, read off the rendered controls.
    {
      const { pg } = await open(`?lat=50.152&lng=-5.064&colour=W,R&flashes=${FLASH_RANGE[1]}&period=3&eye=${EYE_RANGE_M[1]}&tol=${TOL_RANGE_PCT[1]}`);
      const pressed = await pg.$$eval('#flashes button[aria-pressed="true"]', (ns) => ns.map((n) => n.textContent));
      ok(pressed.length === 1 && pressed[0] === String(FLASH_RANGE[1]),
        `?flashes=${FLASH_RANGE[1]}, the top of the range, presses exactly one button and it reads "${pressed[0]}"`);
      const colours = await pg.$$eval('#colours button[aria-pressed="true"]', (ns) => ns.length);
      ok(colours === 2, '  two colours in the URL press two colour buttons');
      ok(await pg.inputValue('#tol') === String(TOL_RANGE_PCT[1])
        && await textOf(pg, '#tolv') === `${TOL_RANGE_PCT[1]}%`,
        `  the tolerance slider and its label both read ${TOL_RANGE_PCT[1]}%`);
      ok(await pg.inputValue('#eye') === String(EYE_RANGE_M[1]), `  and the eye height reads ${EYE_RANGE_M[1]}`);
      ok(await pg.inputValue('#lat') === '50.152', '  and the latitude box holds the latitude from the link');
      await pg.close();
    }
    {
      // and out of range: refused, named, and the controls agree with the query
      const { pg } = await open('?lat=50.152&lng=-5.064&colour=W&period=3&eye=3&tol=45&flashes=99');
      const body = await textOf(pg, '#results');
      ok(/part of that link was not run/.test(body || ''),
        'a link asking for tol=45 and flashes=99 says which parts of it were not run');
      ok(/tol=45 was not run/.test(body || '') && /flashes=99 was not run/.test(body || ''),
        '  naming both parameters');
      ok(await pg.inputValue('#tol') === String(Math.round(DEFAULT_TOL * 100))
        && await textOf(pg, '#tolv') === `${Math.round(DEFAULT_TOL * 100)}%`,
        `  the slider and its label both read ${Math.round(DEFAULT_TOL * 100)}%, which is the tolerance the query actually ran at`);
      ok(/at ±20%:/.test(body || ''), '  and the summary line agrees with the slider');
      ok(await pg.locator('#flashes button[aria-pressed="true"]').count() === 1
        && (await pg.$$eval('#flashes button[aria-pressed="true"]', (ns) => ns[0].textContent)) === "didn't count",
        '  and the flash row shows "didn\'t count", which is what was run');
      await pg.close();
    }

    // 7. THE UNITED STATES GAP, on the coast that had none. A reader at Attu
    //    used to get a bare empty result.
    {
      const { pg } = await open('?lat=52.85&lng=173.18&colour=W&period=10&eye=5');
      const body = await textOf(pg, '#results');
      ok(/western Aleutians/.test(body || ''),
        'a reader at Attu, west of the antimeridian, gets the United States gap panel');
      ok(/this book holds nothing at all where you are/.test(body || ''),
        '  and it says the book holds nothing there, rather than leaving an empty list to be misread');
      ok(/USCG Light List/.test(body || ''), '  and points them at the list that does cover them');
      await pg.close();
    }

    // 8. And the page's static figures survive the round trip into the DOM: the
    //    number in the file and the number after JavaScript runs must agree.
    {
      const { pg } = await open('');
      for (const id of ['n-lights', 'f-geocoef', 'f-samestructure', 'f-flashmax', 'f-marginal', 'f-confradius']) {
        const shown = await textOf(pg, `#${id}`);
        const inFile = new RegExp(`<(b|span) id="${id}">([^<]*)</\\1>`).exec(page);
        ok(inFile && shown === inFile[2],
          `#${id} reads "${shown}" in the browser and "${inFile ? inFile[2] : '?'}" in the file`);
      }
      const rows = await pg.$$eval('#urlRows tr', (ns) => ns.length);
      ok(rows === QUERY_BOUNDS.length, `the URL table renders ${rows} rows, one per documented parameter`);
      await pg.close();
    }
    // ⚠ A TYPED OUT-OF-RANGE VALUE. The page promises twice that a value outside a
    // range is "rejected and named on screen, never quietly rounded into range".
    // The eye box used to substitute the default silently while still displaying
    // what the reader typed, so the summary said 5 m and the box said 50. Every
    // control now takes the same route a link takes, through decodeQuery, and
    // whatever it rejects is named. Checked in the browser because the defect
    // lived entirely in a listener.
    for (const [param, badValue, allowed] of [['eye', '50', '1 to 30'], ['eye', '0.5', '1 to 30']]) {
      const pg = await ctx.newPage();
      await pg.goto(BASE + '?lat=50.152&lng=-5.064&period=3', { waitUntil: 'networkidle' });
      await pg.waitForTimeout(1200);
      await pg.fill('#' + param, badValue);
      await pg.waitForTimeout(400);
      const seen = await pg.evaluate(() => ({
        note: (document.getElementById('rejected') || {}).textContent || '',
        box: (document.getElementById('eye') || {}).value,
      }));
      ok(seen.note.includes(badValue) && seen.note.toLowerCase().includes('not used'),
        `a typed ${param}=${badValue} is named on screen as not used, rather than quietly replaced`,
        seen.note.trim().slice(0, 70));
      ok(seen.box === badValue,
        `  and the box still shows what the reader typed, so they can correct it`);
      await pg.close();
    }
    {
      // and the complaint goes away when they fix it
      const pg = await ctx.newPage();
      await pg.goto(BASE + '?lat=50.152&lng=-5.064&period=3', { waitUntil: 'networkidle' });
      await pg.waitForTimeout(1200);
      await pg.fill('#eye', '50'); await pg.waitForTimeout(300);
      await pg.fill('#eye', '20'); await pg.waitForTimeout(300);
      const note = await pg.evaluate(() => (document.getElementById('rejected') || {}).textContent || '');
      ok(note.trim() === '', 'the complaint clears the moment the control is corrected');
      await pg.close();
    }

  } finally {
    await browser.close();
    server.close();
  }
}

console.log('WHAT LIGHT IS THAT: offline verification of /tools/what-light/');
console.log(log.join('\n'));
console.log(`\n${pass}/${pass + fail} checks passed.`);
if (fail > 0) { console.log('\nVERIFICATION FAILED'); process.exit(1); }
console.log('\nALL CHECKS PASS');
