#!/usr/bin/env node
/* verify-where-the-catalogue-stops-listening.mjs
 *
 *   node research/where-the-catalogue-stops-listening/verify-where-the-catalogue-stops-listening.mjs
 *   ... --live      also fetch tonight's catalogue through the site's own worker and score
 *                   the forward claims against it
 *   ... --record    append this run to research/<slug>/record.jsonl
 *
 * This recomputes every number the page shows, out of the SAME modules the page imports.
 * It does not re-implement the estimators: if akiFit() were wrong, this file would be
 * wrong in the same way, so the estimator checks below are against closed-form truths and
 * against planted populations whose exponent is known, not against a second copy.
 *
 * The four things it is really for:
 *   1. THE ANCHOR. The committed Global CMT derived list, fitted by the page's own
 *      estimator, must land on Taroni (2025)'s published 1.02 +/- 0.03. If it ever stops
 *      landing there, the page's instrument changed and the page must say so. The anchor's
 *      catalogue is closed, so nothing about the world can move this number. It has moved
 *      once, across a declared correction to the derivation (see ANCHOR_PARSE_REVISION);
 *      moving without one is a defect and I2b fails on it.
 *   2. THE PLANTED CONTROL. A population with exactly ONE true exponent, put through the
 *      catalogue's own editorial rule about which magnitude scale is preferred, must come
 *      back out of the page's unmodified analyse() as several different exponents. And the
 *      NEGATIVE control, the same subsetting with a magnitude-INDEPENDENT label, must not.
 *   3. THE REFUSAL PATHS. Feed down, too few events, no crossover, vacuous comparison.
 *      Each is asserted, because a page that only tests its success path has tested the
 *      half that was never going to fail.
 *   4. THE RECORD. One append-only line per run, so a returning reader can catch tonight's
 *      number having been different, and can catch the anchor having moved when it must not.
 */

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

const HERE = dirname(fileURLToPath(import.meta.url));
const PAGE = join(HERE, '..', '..', 'public', 'strata', 'where-the-catalogue-stops-listening');

const { akiFit, maxCurvature, goodnessOfFit, bPositive, seededRandom, drawMagnitudes, roundToGrid, histogram, sha256Hex } = await import(join(PAGE, 'bvalue.js'));
const { parseCsv, parseCatalogue, detectBinWidth, magFamily, shareByBin, crossover, analyse, disjointWindows, plantedCatalogue, freshness, catalogueFingerprint, pastWindow, overdispersion, PAST_WINDOW, FRESHNESS_MAX_AGE_DAYS } = await import(join(PAGE, 'catalogue.js'));
const { feedState, fitState, vacuityVerdict, overlapCaution, scoreClaims, freshnessVerdict, dataVisitSentence, CLAIMS, CLAIM_DATE, SHIPPED_B_ALL } = await import(join(PAGE, 'narrate.js'));
const { ANCHOR } = await import(join(PAGE, 'anchor-gcmt.js'));

// Bumped ONLY when the derivation of the anchor changes. The anchor's catalogue is closed,
// so the anchor moving without this string moving is a defect (see I2 / I2b).
//   2026-08-15-ndk-cols-43-47: fixed TWO faults in build-anchor.mjs, found in review.
//   (1) it read the NDK hypocentral depth from cols 44-48, which truncated 105.2 km to 5.2
//       and admitted 209 deep events to a shallow-only cut (hypocentral 1.0278 -> 1.0229);
//   (2) it fitted the 0.1-rounded variant with dM = 0, omitting the binning correction at
//       the one place it is mandatory, which read 1.1699 instead of 1.0309 and which the
//       page then reported to readers as a rounding effect. See C4/C4b.
const ANCHOR_PARSE_REVISION = '2026-08-15-ndk-cols-43-47';

const LIVE = process.argv.includes('--live');
const RECORD = process.argv.includes('--record');
const RECORD_PATH = join(HERE, 'record.jsonl');
const SNAP_GLOBAL = join(HERE, 'snapshot-global-2026-08-15.csv');
const SNAP_SOCAL = join(HERE, 'snapshot-socal-2026-08-15.csv');
const FEED_BASE = process.env.AW_FEED_BASE || 'https://artwaste.land';

let fails = 0, checks = 0;
const ok = (name, cond, extra = '') => {
  checks++; if (!cond) fails++;
  console.log(`${cond ? '  ok  ' : 'FAIL  '}${name}${extra ? '   ' + extra : ''}`);
};
const near = (a, b, eps) => Number.isFinite(a) && Number.isFinite(b) && Math.abs(a - b) <= eps;
const f4 = (x) => (Number.isFinite(x) ? x.toFixed(4) : 'n/a');

/* ══ A. the estimators, against truths that do not depend on this repo ═══════ */
console.log('\n— A. estimators —');
{
  // A1. Aki's ML estimator recovers a known exponent from a large draw.
  const rnd = seededRandom(11);
  const mags = drawMagnitudes(400000, 1.0, 4.0, rnd);
  const fit = akiFit(mags, 4.0, 0);
  ok('A1 akiFit recovers a planted b = 1.000 on 400,000 continuous magnitudes',
    near(fit.bUnbiased, 1.0, 4 * fit.sigmaAki), `got ${f4(fit.bUnbiased)} +/- ${f4(fit.sigmaAki)}`);

  // A2. the binning correction is worth about 12% on THIS draw (the assertion below prints
  // the exact figure) and is applied, not assumed away. Three different numbers for this
  // effect are quoted around this repo and they are three different quantities, not a
  // contradiction: 12.4% on the synthetic draw here, 15.7% on tonight's real global
  // catalogue (which the page computes live rather than hardcoding), and 13.5% on the
  // anchor's rounded GCMT list (C4b). The size depends on the population.
  // The draw starts well BELOW the cutoff so that the bin at the cutoff is fully
  // populated, which is the situation the -dM/2 correction is for: an event reported as
  // 4.5 on a 0.1 grid really had a magnitude somewhere in [4.45, 4.55).
  const rnd2 = seededRandom(12);
  const cont = drawMagnitudes(400000, 1.0, 4.0, rnd2);
  const grid = cont.map((m) => roundToGrid(m, 0.1));
  const right = akiFit(grid, 4.5, 0.1);
  const wrong = akiFit(grid, 4.5, 0.0);
  ok('A2 with dM = 0.1 the gridded draw recovers b = 1.000',
    near(right.bUnbiased, 1.0, 4 * right.sigmaAki), `got ${f4(right.bUnbiased)} +/- ${f4(right.sigmaAki)}`);
  ok('A2 with dM = 0 the SAME gridded draw is biased high by more than 5 per cent',
    wrong.bUnbiased > 1.05, `got ${f4(wrong.bUnbiased)}, an error of ${((wrong.bUnbiased - 1) * 100).toFixed(1)}%`);

  // A3/A4/A5. the three published corrections are exactly what they say.
  const small = akiFit(drawMagnitudes(500, 1.2, 5.0, seededRandom(13)), 5.0, 0);
  ok('A3 Ogata-Yamashina correction is exactly b*(n-1)/n',
    near(small.bUnbiased, small.b * (small.n - 1) / small.n, 1e-12));
  ok('A4 Aki sigma is exactly b/sqrt(n)', near(small.sigmaAki, small.b / Math.sqrt(small.n), 1e-12));
  {
    const sel = drawMagnitudes(500, 1.2, 5.0, seededRandom(13)).filter((m) => m >= 5.0);
    const mean = sel.reduce((s, m) => s + m, 0) / sel.length;
    const v = sel.reduce((s, m) => s + (m - mean) ** 2, 0) / (sel.length * (sel.length - 1));
    ok('A5 Shi-Bolt sigma is exactly 2.30*b^2*sqrt(var)',
      near(small.sigmaShiBolt, 2.30 * small.b * small.b * Math.sqrt(v), 1e-12));
  }

  // A6. the refusal paths of the estimator itself.
  const few = akiFit([5, 5.1, 5.2], 5.0, 0);
  ok('A6 akiFit REFUSES on too few events rather than returning a number',
    few.ok === false && few.reason === 'too_few_events', `n=${few.n}`);
  const flat = akiFit(new Array(50).fill(5.0), 5.0, 0);
  ok('A6 akiFit REFUSES on a degenerate (zero-spread) sample',
    flat.ok === false && flat.reason === 'degenerate_mean');
  ok('A6 goodnessOfFit REFUSES on a catalogue too small to sweep',
    goodnessOfFit([5, 5.1, 5.2]).ok === false);

  // A7. MAXC finds a planted mode.
  const bent = [...drawMagnitudes(50000, 1.0, 2.0, seededRandom(14))].filter((m) => {
    // delete events below 2.6 with a probability that rises as you go down: a planted Mc
    return m >= 2.6 || Math.random === null;
  });
  const withRolloff = bent.concat(drawMagnitudes(4000, 1.0, 2.3, seededRandom(15)).filter((m) => m < 2.6));
  const mc = maxCurvature(withRolloff, 0.1);
  ok('A7 maxCurvature finds the planted roll-off, not the bottom of the data',
    mc.ok && mc.mc >= 2.5 && mc.mc <= 2.7, `MAXC = ${mc.mc}`);

  // A8. b-positive recovers the same exponent on a clean catalogue.
  const seq = drawMagnitudes(200000, 1.0, 4.0, seededRandom(16));
  const bp = bPositive(seq, { dMc: 0, dM: 0 });
  ok('A8 b-positive recovers a planted b = 1.000 with no completeness magnitude at all',
    near(bp.bUnbiased, 1.0, 4 * bp.sigmaAki), `got ${f4(bp.bUnbiased)} +/- ${f4(bp.sigmaAki)} on ${bp.n} pairs`);

  // A9. van der Elst's claim, made checkable: transient incompleteness biases Aki and not b-positive.
  const clean = drawMagnitudes(120000, 1.0, 3.0, seededRandom(17));
  const transient = clean.map((m, i) => ((i % 1000) < 400 && m < 4.0 ? null : m)).filter((m) => m !== null);
  const akiBiased = akiFit(transient, 3.0, 0);
  const bpRobust = bPositive(transient, { dMc: 0, dM: 0 });
  ok('A9 a transient loss of small events biases the Aki fit away from the truth',
    Math.abs(akiBiased.bUnbiased - 1.0) > 10 * akiBiased.sigmaAki, `Aki says ${f4(akiBiased.bUnbiased)}`);
  ok('A9 the SAME transiently incomplete list leaves b-positive much closer to the truth',
    Math.abs(bpRobust.bUnbiased - 1.0) < Math.abs(akiBiased.bUnbiased - 1.0) / 2, `b-positive says ${f4(bpRobust.bUnbiased)}`);
}

/* ══ B. parsing, which is where a catalogue page silently lies ══════════════ */
console.log('\n— B. parsing and classification —');
{
  const csv = 'time,mag,magType,place\n2026-01-01T00:00:00Z,4.5,mb,"5 km N of Ende, Indonesia"\n2026-01-02T00:00:00Z,,mb,"no magnitude"\n';
  const g = parseCsv(csv);
  ok('B1 the CSV reader keeps a quoted comma inside one field',
    g[1][3] === '5 km N of Ende, Indonesia', JSON.stringify(g[1][3]));
  const p = parseCatalogue(csv);
  ok('B2 rows with no magnitude are dropped and COUNTED, not silently ignored',
    p.ok && p.rows.length === 1 && p.dropped === 1, `rows=${p.rows.length} dropped=${p.dropped}`);
  ok('B3 a response with the wrong columns is refused, not guessed at',
    parseCatalogue('a,b,c\n1,2,3\n').ok === false);
  const fam = ['mb', 'mww', 'mwr', 'mw', 'ml', 'md', 'ms', 'mh'].map(magFamily).join(',');
  ok('B4 magType families classify as documented', fam === 'mb,mw,mw,mw,ml,other,other,other', fam);
  ok('B5 detectBinWidth calls a 0.1-grid catalogue gridded',
    detectBinWidth([{ mag: 4.5 }, { mag: 4.6 }, { mag: 5.0 }]).dM === 0.1);
  ok('B5 detectBinWidth calls a continuous catalogue continuous',
    detectBinWidth([{ mag: 4.5123 }, { mag: 0.29 }, { mag: 1.7771 }]).dM === 0);
}

/* ══ C. the anchor: a figure somebody else published, nine months ago ═══════ */
console.log('\n— C. the anchor (Taroni 2025, Global CMT) —');
const anchorFits = {};
{
  const pub = ANCHOR.published;
  for (const key of ['hypocentral', 'centroid', 'hypocentralRounded']) {
    const mags = ANCHOR.magnitudes[key];
    const fit = akiFit(mags, ANCHOR.cuts.minMw, ANCHOR.variants[key].dM);
    anchorFits[key] = fit;
    const rec = ANCHOR.variants[key];
    ok(`C1 the committed ${key} list refits to its own recorded value`,
      fit.n === rec.n && near(fit.bUnbiased, rec.bUnbiased, 1e-9) && near(fit.sigmaAki, rec.sigmaAki, 1e-9),
      `N=${fit.n} b=${f4(fit.bUnbiased)}`);
    ok(`C2 the ${key} reproduction lands inside the published sigma of ${pub.b} +/- ${pub.sigma}`,
      Math.abs(fit.bUnbiased - pub.b) < pub.sigma,
      `residual ${(fit.bUnbiased - pub.b).toFixed(4)} against a published sigma of ${pub.sigma}`);
  }
  // C3 once asserted that the published count sat BETWEEN the two depth conventions. It only
  // ever did because build-anchor.mjs read the hypocentral depth from NDK cols 44-48 instead
  // of 43-47 and let 209 deep earthquakes into a shallow-only cut. Both conventions in fact
  // fall SHORT of the published count, and that unexplained ~8% gap is the honest story.
  ok('C3 NEITHER depth convention reproduces the published count: both fall short of it',
    anchorFits.centroid.n < pub.n && anchorFits.hypocentral.n < pub.n,
    `centroid ${anchorFits.centroid.n} and hypocentral ${anchorFits.hypocentral.n}, both under ${pub.n}`);
  // C3b tests the DERIVATION, which nothing else here can see. Every other anchor check
  // refits the committed list and would stay green under any parse bug that produced a
  // plausible list -- which is exactly what happened. These are four records copied verbatim
  // from jan23.ndk (whose sha256 is in ANCHOR.sources), with depths legible by eye; the deep
  // ones are the ones the cols 44-48 bug truncated into the shallow cut (105.2 -> 5.2).
  // Column readers imported from the build script, so there is no second implementation of
  // them here either. The NDK files themselves are not redistributed, hence the literals.
  const { hypoDepthOf, centDepthOf } = await import(join(HERE, 'build-anchor.mjs'));
  const ndkCases = [
    // line 1 of a record                                                              hypo   cent line 3
    ['PDEW 2023/01/01 03:16:19.1  -6.73  155.19  78.8 0.0 5.4 SOLOMON ISLANDS         ', 78.8,
     'CENTROID:     -0.9 0.1  -6.92 0.01  155.07 0.01  48.4  0.6 FREE S-20230331203527', 48.4],
    ['PDEW 2023/01/01 16:24:27.6 -25.21  178.51 595.7 0.0 5.1 SOUTH OF FIJI ISLANDS   ', 595.7,
     'CENTROID:      0.5 0.5 -25.32 0.05  178.65 0.05 610.5  3.8 FREE S-20230509230610', 610.5],
    ['PDEW 2023/01/09 17:47:35.0  -7.06  130.01 105.2 0.0 7.6 TANIMBAR ISLANDS REG., I', 105.2,
     'CENTROID:     12.3 0.1  -7.19 0.00  130.03 0.00  92.4  0.2 FREE S-20230331220459', 92.4],
    ['PDEW 2023/01/01 18:26:42.8 -56.27 -123.47  10.0 0.0 5.8 SOUTHERN EAST PACIFIC RI', 10.0,
     'CENTROID:      3.4 0.1 -55.80 0.00 -124.18 0.01  21.0  0.5 FREE S-20230331204151', 21.0],
  ];
  ok('C3b the NDK hypocentral depth is read from cols 43-47, so deep events read as deep',
    ndkCases.every(([l1, want]) => hypoDepthOf(l1) === want),
    ndkCases.map(([l1, want]) => `${want}->${hypoDepthOf(l1)}`).join(' '));
  ok('C3c a 3-digit depth does not truncate into the shallow cut (the cols 44-48 bug)',
    ndkCases.filter(([, d]) => d > 50).every(([l1]) => hypoDepthOf(l1) > 50)
      && hypoDepthOf(ndkCases[2][0]) === 105.2,
    `105.2 km reads as ${hypoDepthOf(ndkCases[2][0])} (the bug read 5.2 and passed it as shallow)`);
  ok('C3d the NDK centroid depth is read from cols 48-53, not the longitude uncertainty',
    ndkCases.every(([, , l3, want]) => centDepthOf(l3) === want),
    ndkCases.map(([, , l3, want]) => `${want}->${centDepthOf(l3)}`).join(' '));
  /* C4. The free choice that turned out NOT to matter, and the omitted correction that did.
   *
   * This pair used to be a single check asserting that rounding the magnitudes onto the
   * catalogue's own 0.1 grid "breaks the reproduction". It did not. What broke it was that
   * build-anchor.mjs fitted that gridded list with dM = 0 -- the Utsu/Bender correction
   * this whole page insists on, omitted exactly where it is mandatory. The old check was
   * green because it was scoring a bug, and it asserted the opposite of A2 above, which
   * proves on a synthetic draw that a gridded list fitted with dM = 0 is biased high.
   * Both halves are now asserted, from the committed rounded list, so neither can drift.
   */
  const rFit = anchorFits.hypocentralRounded;
  ok('C4 rounding Mw to 0.1 before the cut, fitted with ITS OWN dM = 0.1, still reproduces the published b',
    ANCHOR.variants.hypocentralRounded.dM === 0.1 && Math.abs(rFit.bUnbiased - pub.b) < pub.sigma,
    `rounded gives ${f4(rFit.bUnbiased)} on N=${rFit.n} against ${pub.b} +/- ${pub.sigma}`);
  const rNo = akiFit(ANCHOR.magnitudes.hypocentralRounded, ANCHOR.cuts.minMw, 0);
  ok('C4b the SAME rounded list with the binning correction omitted misses the published b by more than 3 sigma',
    Math.abs(rNo.bUnbiased - pub.b) > 3 * pub.sigma,
    `dM = 0 gives ${f4(rNo.bUnbiased)}, ${((rNo.bUnbiased - pub.b) / pub.sigma).toFixed(1)} published sigmas out -- a bug, not a free choice`);
  ok('C4c and that is the recorded negative result, refit from the committed list rather than asserted',
    rNo.n === ANCHOR.variants.hypocentralRoundedNoCorrection.n
      && near(rNo.bUnbiased, ANCHOR.variants.hypocentralRoundedNoCorrection.bUnbiased, 1e-9));
  // C4d. EVERY variant the artifact quotes must have been refitted above from a list
  // committed beside it. A variant added later with no list -- an assertion rather than an
  // artifact -- turns this red instead of sliding by unnoticed.
  const refitted = { ...anchorFits, hypocentralRoundedNoCorrection: rNo };
  ok('C4d every fit quoted in the artifact was re-derived here from magnitudes committed beside it',
    Object.keys(ANCHOR.variants).every((k) => {
      const got = refitted[k], want = ANCHOR.variants[k];
      return got && got.n === want.n && near(got.bUnbiased, want.bUnbiased, 1e-9);
    }),
    `${Object.keys(ANCHOR.variants).length} variants, all refit from ${Object.keys(ANCHOR.magnitudes).length} committed lists`);
  ok('C5 the anchor artifact carries its own provenance (source files, byte counts, hashes)',
    Array.isArray(ANCHOR.sources) && ANCHOR.sources.length === 37 && ANCHOR.sources.every((s) => /^[0-9a-f]{64}$/.test(s.sha256)),
    `${ANCHOR.sources.length} source files`);
  ok('C6 the anchor carries the two citations Global CMT asks for',
    ANCHOR.gcmt_citations.length === 2 && ANCHOR.gcmt_citations[0].includes('Dziewonski') && ANCHOR.gcmt_citations[1].includes('Ekstrom'));
}

/* ══ D. the planted control, entering the SAME analyse() as tonight ═════════ */
console.log('\n— D. the planted control —');
let controlSummary = null;
{
  // POSITIVE: one true exponent, split by a rule that depends on magnitude.
  const planted = plantedCatalogue({ n: 40000, bTrue: 1.0, mMin: 4.0, crossoverM: 5.2, sharpness: 0.35, scaleSlope: 1.0, seed: 20260815 });
  const got = analyse(planted.rows, { mc: 4.5, dM: 0.1, binWidth: 0.1 });
  const sepPos = Math.abs(got.fits.mb.bUnbiased - got.fits.mw.bUnbiased) / Math.max(got.fits.mb.sigmaAki, got.fits.mw.sigmaAki);
  ok('D1 the planted rows are fitted by the same analyse() the live panel calls',
    got.fits.all.ok && got.fits.mb.ok && got.fits.mw.ok);
  ok('D2 the WHOLE planted catalogue still recovers its one true exponent b = 1.000',
    near(got.fits.all.bUnbiased, 1.0, 4 * got.fits.all.sigmaAki), `all: ${f4(got.fits.all.bUnbiased)}`);
  ok('D3 mb-only comes out far too STEEP because the rule took its large events away',
    got.fits.mb.bUnbiased > 1.0 + 10 * got.fits.mb.sigmaAki, `mb-only: ${f4(got.fits.mb.bUnbiased)}`);
  ok('D4 Mw-only comes out far too SHALLOW because the rule never gave it small events',
    got.fits.mw.bUnbiased < 1.0 - 10 * got.fits.mw.sigmaAki, `Mw-only: ${f4(got.fits.mw.bUnbiased)}`);
  ok('D5 the crossover the page reports is found in the planted data near where it was planted',
    got.crossover.ok && Math.abs(got.crossover.bin - 5.2) <= 0.3, `found at ${got.crossover.ok ? got.crossover.bin : 'none'}`);

  // NEGATIVE: the SAME subsetting, with a label that does not depend on magnitude.
  // If merely splitting a catalogue in two produced this effect, this control would fail.
  const flat = plantedCatalogue({ n: 40000, bTrue: 1.0, mMin: 4.0, crossoverM: 5.2, sharpness: 1e6, scaleSlope: 1.0, seed: 20260816 });
  const gotFlat = analyse(flat.rows, { mc: 4.5, dM: 0.1, binWidth: 0.1 });
  const sepNeg = Math.abs(gotFlat.fits.mb.bUnbiased - gotFlat.fits.mw.bUnbiased) / Math.max(gotFlat.fits.mb.sigmaAki, gotFlat.fits.mw.sigmaAki);
  ok('D6 NEGATIVE CONTROL: with a magnitude-INDEPENDENT label the two subsets agree',
    sepNeg < 4, `separation ${sepNeg.toFixed(1)} sigma (mb ${f4(gotFlat.fits.mb.bUnbiased)}, Mw ${f4(gotFlat.fits.mw.bUnbiased)})`);
  ok('D7 the differential is large: magnitude-dependent labelling separates the subsets at least 20x further',
    sepPos > 20 * Math.max(sepNeg, 1), `${sepPos.toFixed(1)} sigma against ${sepNeg.toFixed(1)} sigma`);
  ok('D8 NEGATIVE CONTROL: with a magnitude-independent label there is no crossover to find',
    gotFlat.crossover.ok === false, gotFlat.crossover.reason || '');
  controlSummary = {
    bTrue: 1.0, all: got.fits.all.bUnbiased, mb: got.fits.mb.bUnbiased, mw: got.fits.mw.bUnbiased,
    separation_sigma: sepPos, negative_control_separation_sigma: sepNeg,
  };
}

/* ══ E. the refusal paths a reader can actually reach ═══════════════════════ */
console.log('\n— E. refusal paths —');
{
  const down = feedState({ ok: false, error: 'upstream_error' });
  ok('E1 a dead feed produces a refusal that mentions no cached number',
    down.state === 'down' && /nothing rather than a number/.test(down.line) && !/\d\.\d\d/.test(down.line));
  ok('E2 a feed that answers with almost nothing is also refused',
    feedState({ ok: true, text: 'time,mag\n' }).state === 'empty');
  ok('E3 a healthy feed is not refused', feedState({ ok: true, text: 'x'.repeat(500) }).state === 'ok');
  const tooFew = fitState(akiFit([5, 5.1], 5.0, 0), 'the mb subset');
  ok('E4 a subset too small to fit prints a refusal naming the count, not a number',
    tooFew.ok === false && /only 2 events/.test(tooFew.line), tooFew.line.slice(0, 60));
  const vac = vacuityVerdict({ rollingN: 7700, recentN: 1900, priorN: 1900, sharedEvents: 0, bRecent: 1.20, bPrior: 1.205, sigmaRecent: 0.03, sigmaPrior: 0.03, days: 90 });
  ok('E5 two disjoint windows that agree are reported as having nothing to say',
    vac.verdict === 'indistinguishable' && /nothing to tell you tonight/.test(vac.line));
  const moved = vacuityVerdict({ rollingN: 7700, recentN: 1900, priorN: 1900, sharedEvents: 0, bRecent: 1.05, bPrior: 1.35, sigmaRecent: 0.03, sigmaPrior: 0.03, days: 90 });
  ok('E6 two disjoint windows that really differ are reported as moved', moved.verdict === 'moved' && moved.inSigmas > 2);
  /* E6b/E6c. The separation arithmetic itself, against the closed form. The difference of
   * two independent estimates carries the sigmas in QUADRATURE; this used to divide by
   * max(sigma), which inflates every verdict by up to 1.4x and pushed borderline pairs over
   * the line. And the measured overdispersion must WIDEN the bar, never narrow it. */
  const q = vacuityVerdict({ rollingN: 100, recentN: 50, priorN: 50, sharedEvents: 0, bRecent: 1.0, bPrior: 1.2, sigmaRecent: 0.03, sigmaPrior: 0.04, days: 90 });
  ok('E6b the separation of two estimates uses the sigmas in quadrature, not the larger one',
    near(q.inFormalSigmas, 0.2 / Math.sqrt(0.03 ** 2 + 0.04 ** 2), 1e-12),
    `${q.inFormalSigmas.toFixed(3)} sigma, against ${(0.2 / 0.04).toFixed(3)} if the larger sigma alone were used`);
  const wide = vacuityVerdict({ rollingN: 100, recentN: 50, priorN: 50, sharedEvents: 0, bRecent: 1.0, bPrior: 1.2, sigmaRecent: 0.03, sigmaPrior: 0.04, days: 90, dispersion: 2 });
  ok('E6c a measured overdispersion widens the bar and so makes the verdict harder, not easier',
    near(wide.inSigmas, q.inFormalSigmas / 2, 1e-12) && wide.inSigmas < q.inSigmas,
    `${q.inSigmas.toFixed(2)} sigma unwidened, ${wide.inSigmas.toFixed(2)} at a measured factor of 2`);
  const none = vacuityVerdict({ rollingN: 10, recentN: 4, priorN: 2, sharedEvents: 0, bRecent: NaN, bPrior: NaN, sigmaRecent: 0, sigmaPrior: 0, days: 90 });
  ok('E7 windows too thin to fit produce "no honest before-and-after", not a fabricated one', none.verdict === 'unavailable');
  ok('E8 the overlap caution states the real overlap of a 365-day window seen a week later',
    /358 of its 365 days/.test(overlapCaution(365, 7)), overlapCaution(365, 7).slice(0, 70));

  /* ── E9-E12. THE STALENESS GATE, WITH ITS NEGATIVE CONTROL ──────────────────
   * A feed can answer 200, with the right columns, plausible magnitudes and a fresh
   * Last-Modified, and still be describing last year. Nothing else in this file would
   * notice: every fit would be made and every panel would render. The only thing that
   * knows how current a catalogue is, is the catalogue. Driven here with a well-formed
   * row list whose newest event is 400 days old, which is exactly the shape of the
   * failure this gate exists for.
   */
  const mkRows = (newestDaysAgo, refMs) => {
    const rows = [];
    for (let i = 0; i < 300; i++) {
      rows.push({ timeMs: refMs - (newestDaysAgo + i) * 86400000, mag: 4.5 + (i % 20) / 10, magType: 'mb', family: 'mb', id: 'e' + i, updated: '' });
    }
    return rows;
  };
  const refMs = Date.UTC(2026, 7, 15);
  const stale = freshness(mkRows(400, refMs), refMs);
  const staleV = freshnessVerdict(stale);
  ok('E9 a well-formed catalogue whose newest earthquake is 400 days old is called stale',
    stale.ok === false && staleV.ok === false && Math.round(stale.ageDays) === 400,
    `age ${stale.ageDays.toFixed(1)} days against a limit of ${stale.maxAgeDays}`);
  ok('E10 the staleness refusal says so in words and quotes no b-value',
    /not current/.test(staleV.headline) && /fitting nothing/.test(staleV.line) && !/b = /.test(staleV.line));
  const fresh = freshness(mkRows(0.25, refMs), refMs);
  ok('E11 NEGATIVE CONTROL: a current catalogue is NOT called stale, so the gate is not just always-on',
    fresh.ok === true && freshnessVerdict(fresh).ok === true,
    `age ${fresh.ageHours.toFixed(1)} hours`);
  ok('E12 a catalogue whose newest event is just past the limit trips it, so the threshold is real',
    freshness(mkRows(FRESHNESS_MAX_AGE_DAYS + 0.1, refMs), refMs).ok === false
      && freshness(mkRows(FRESHNESS_MAX_AGE_DAYS - 0.1, refMs), refMs).ok === true,
    `limit ${FRESHNESS_MAX_AGE_DAYS} days`);

  /* E13/E14. "Has it moved since your last visit", asked of the DATA. The HTTP
   * Last-Modified this source sends is regenerated per request (a query for a closed
   * window in 2020 comes back stamped with the current second), so a page keyed on it
   * reports "moved" on every visit including one where nothing arrived. */
  const rowsA = mkRows(0.25, refMs);
  const fpA = catalogueFingerprint(rowsA);
  const fpB = catalogueFingerprint(rowsA.concat([{ timeMs: refMs, mag: 5.0, magType: 'mb', family: 'mb', id: 'new1', updated: '' }]));
  ok('E13 an unchanged catalogue fingerprints identically, so a revisit can honestly say "nothing new"',
    fpA.key === catalogueFingerprint(rowsA.slice()).key
      && /has NOT changed/.test(dataVisitSentence({ status: 'same', current: fpA })));
  ok('E14 one added earthquake changes the fingerprint, so a real change is still caught',
    fpA.key !== fpB.key && /HAS changed/.test(dataVisitSentence({ status: 'moved', current: fpB, previous: fpA })),
    `${fpA.key} then ${fpB.key}`);
}

/* ══ F. the southern California support panel (committed snapshot) ═════════ */
console.log('\n— F. the completeness panel, on the committed southern California snapshot —');
let socalSummary = null;
{
  const socal = parseCatalogue(readFileSync(SNAP_SOCAL, 'utf8'));
  ok('F1 the snapshot parses', socal.ok && socal.rows.length > 10000, `N=${socal.rows.length}`);
  const bw = detectBinWidth(socal.rows);
  ok('F2 southern California magnitudes are CONTINUOUS, so dM = 0 is the right correction',
    bw.dM === 0 && bw.fractionOnTenths < 0.2, `${(bw.fractionOnTenths * 100).toFixed(1)}% sit on a 0.1 grid`);
  const mags = socal.rows.map((r) => r.mag);
  const mc = maxCurvature(mags, 0.1);
  const gftC = goodnessOfFit(mags, { mode: 'cumulative', dM: 0, maxMc: 3.0 });
  const gftI = goodnessOfFit(mags, { mode: 'incremental', dM: 0, maxMc: 3.0 });
  const rules = {
    MAXC: mc.mc,
    'MAXC+0.2': Math.round((mc.mc + 0.2) * 10) / 10,
    'GFT 90% (cumulative)': gftC.mc90,
    'GFT 95% (cumulative)': gftC.mc95,
    'GFT 90% (incremental)': gftI.mc90,
  };
  const bs = {};
  for (const [name, m] of Object.entries(rules)) bs[name] = m === null ? null : akiFit(mags, m, 0);
  for (const [name, m] of Object.entries(rules)) {
    console.log(`        ${name.padEnd(24)} Mc = ${m === null ? 'no answer' : m}    b = ${bs[name] ? f4(bs[name].bUnbiased) : '—'}${bs[name] ? ' +/- ' + f4(bs[name].sigmaAki) : ''}`);
  }
  const answered = Object.values(rules).filter((m) => m !== null);
  ok('F3 the published rules do not agree on the completeness magnitude',
    new Set(answered).size > 1, `answers: ${answered.join(', ')}`);
  const fitted = Object.values(bs).filter(Boolean);
  const spread = Math.max(...fitted.map((f) => f.bUnbiased)) - Math.min(...fitted.map((f) => f.bUnbiased));
  const worstSigma = Math.max(...fitted.map((f) => f.sigmaAki));
  ok('F4 the b-values that follow are separated by more than 5 formal sigmas',
    spread / worstSigma > 5, `spread ${spread.toFixed(3)} against the largest sigma ${worstSigma.toFixed(3)} = ${(spread / worstSigma).toFixed(1)} sigma`);
  ok('F5 the two residual conventions of ONE named rule disagree about where its answer is',
    gftC.mc90 !== gftI.mc90 || (gftC.mc95 === null) !== (gftI.mc95 === null),
    `90%: cumulative ${gftC.mc90} vs incremental ${gftI.mc90}; 95%: cumulative ${gftC.mc95} vs incremental ${gftI.mc95} (incremental peaks at R = ${gftI.best.R.toFixed(2)}%)`);
  const bp = bPositive(mags, { dMc: 0.1, dM: 0 });
  ok('F6 b-positive answers on the same list without being given a completeness magnitude',
    bp.ok, `${f4(bp.bUnbiased)} +/- ${f4(bp.sigmaAki)} on ${bp.n} pairs`);
  ok('F7 southern California has NO magnitude-scale crossover, so that panel correctly refuses there',
    crossover(shareByBin(socal.rows, 0.1)).ok === false);
  socalSummary = {
    n: socal.rows.length, dM: bw.dM,
    mc_rules: rules,
    b_by_rule: Object.fromEntries(Object.entries(bs).map(([k, v]) => [k, v ? +v.bUnbiased.toFixed(4) : null])),
    sigma_by_rule: Object.fromEntries(Object.entries(bs).map(([k, v]) => [k, v ? +v.sigmaAki.toFixed(4) : null])),
    b_positive: +bp.bUnbiased.toFixed(4), b_positive_sigma: +bp.sigmaAki.toFixed(4), b_positive_pairs: bp.n,
    gft_incremental_peak_R: +gftI.best.R.toFixed(2),
  };
}

/* ══ G. the flagship, on tonight's catalogue (live) or the committed snapshot ═ */
console.log('\n— G. the magnitude-scale mixture —');
let source = { kind: 'snapshot', label: 'the committed snapshot of 2026-08-15', fetched_at: null, upstream_last_modified: null, upstream: null };
let text = readFileSync(SNAP_GLOBAL, 'utf8');
if (LIVE) {
  const url = `${FEED_BASE}/api/feed/usgs-quakes-region?region=global&days=365&minmag=4.5`;
  try {
    const res = await fetch(url, { headers: { Accept: 'application/json' } });
    const body = await res.json();
    const st = feedState(body);
    if (st.state === 'ok') {
      text = body.text;
      source = { kind: 'live', label: 'the live feed', fetched_at: body.fetched_at, upstream_last_modified: body.upstream_last_modified, upstream: body.upstream };
      console.log(`        live feed ok, fetched_at ${body.fetched_at}`);
    } else {
      console.log(`        live feed refused (${st.headline}); falling back to the committed snapshot and RECORDING that`);
      source.live_attempt_failed = st.headline;
    }
  } catch (e) {
    console.log(`        live feed unreachable (${e.message}); falling back to the committed snapshot and RECORDING that`);
    source.live_attempt_failed = String(e.message);
  }
}

const cat = parseCatalogue(text);
ok('G1 the catalogue parses and holds events', cat.ok && cat.rows.length > 100, `N=${cat.rows.length}, ${cat.dropped} rows dropped for having no magnitude`);
const bwG = detectBinWidth(cat.rows);
ok('G2 the global catalogue is reported on a 0.1 grid, so dM = 0.1 is the right correction',
  bwG.dM === 0.1, `${(bwG.fractionOnTenths * 100).toFixed(1)}% sit on the grid`);

const MC = 4.5;
const A = analyse(cat.rows, { mc: MC, dM: bwG.dM, binWidth: 0.1 });
const fAll = A.fits.all, fMb = A.fits.mb, fMw = A.fits.mw;
console.log(`        all magnitude types  N = ${String(fAll.n).padStart(5)}   b = ${f4(fAll.bUnbiased)} +/- ${f4(fAll.sigmaAki)} (Aki) / ${f4(fAll.sigmaShiBolt)} (Shi-Bolt)`);
console.log(`        mb only              N = ${String(fMb.n).padStart(5)}   b = ${f4(fMb.bUnbiased)} +/- ${f4(fMb.sigmaAki)}`);
console.log(`        Mw family only       N = ${String(fMw.n).padStart(5)}   b = ${f4(fMw.bUnbiased)} +/- ${f4(fMw.sigmaAki)}`);

ok('G3 all three fits are made from ONE event list, with nothing filtered but the label',
  fMb.n + fMw.n + (A.counts.total - fMb.n - fMw.n) === A.counts.total);
const sepLive = Math.abs(fMb.bUnbiased - fMw.bUnbiased) / Math.max(fMb.sigmaAki, fMw.sigmaAki);
ok('G4 the mb-only and Mw-only fits are separated by more than 10 formal sigmas',
  sepLive > 10, `${sepLive.toFixed(1)} sigma`);
ok('G5 the mixture sits between the two subsets, which is what a stitch of two scales does',
  fAll.bUnbiased > Math.min(fMb.bUnbiased, fMw.bUnbiased) && fAll.bUnbiased < Math.max(fMb.bUnbiased, fMw.bUnbiased),
  `${f4(fMw.bUnbiased)} < ${f4(fAll.bUnbiased)} < ${f4(fMb.bUnbiased)}`);
ok('G6 a crossover exists and it is where the reported b stops being an mb measurement',
  A.crossover.ok, A.crossover.ok ? `Mw family becomes the majority at magnitude ${A.crossover.bin}` : A.crossover.reason);

// the sweep the reader drags, and the claim it supports: each subset is only sane where it
// owns the catalogue.
const sweep = [];
for (let m = 4.5; m <= 6.5 + 1e-9; m = Math.round((m + 0.5) * 10) / 10) {
  const a = analyse(cat.rows, { mc: m, dM: bwG.dM, binWidth: 0.1 });
  sweep.push({
    mc: m,
    all: a.fits.all.ok ? +a.fits.all.bUnbiased.toFixed(4) : null,
    mb: a.fits.mb.ok ? +a.fits.mb.bUnbiased.toFixed(4) : null,
    mw: a.fits.mw.ok ? +a.fits.mw.bUnbiased.toFixed(4) : null,
    n: a.fits.all.n,
  });
}
console.log('        cutoff sweep: ' + sweep.map((s) => `${s.mc}:${s.all ?? '—'}`).join('  '));
const mwLow = sweep[0].mw, mwHigh = sweep.find((s) => s.mc === 5.5)?.mw;
ok('G7 the Mw-only fit changes by more than 0.3 between a cutoff below the crossover and one above it',
  Number.isFinite(mwLow) && Number.isFinite(mwHigh) && Math.abs(mwHigh - mwLow) > 0.3,
  `Mw-only: ${mwLow} at 4.5, ${mwHigh} at 5.5`);
ok('G8 above the crossover the mixture and the Mw-only fit converge, because they are the same events',
  (() => { const s = sweep.find((x) => x.mc === 6.0); return s && Number.isFinite(s.all) && Number.isFinite(s.mw) && Math.abs(s.all - s.mw) < 0.1; })(),
  (() => { const s = sweep.find((x) => x.mc === 6.0); return `at 6.0 the mixture is ${s.all} and Mw-only is ${s.mw}`; })());
/* G9. The label used to say "within its own error bar" while the code allowed THREE of
 * them: at Mc 6.0 sigma_Aki is about 0.085, so it passed for any mixture b between 0.765
 * and 1.275, a plus-or-minus 25 per cent window presented as corroboration. The tolerance
 * now matches the words. The comparison is also confounded and the extra text says so:
 * different magnitude range, different span, different catalogue. */
{
  const s = sweep.find((x) => x.mc === 6.0);
  const a6 = analyse(cat.rows, { mc: 6.0, dM: bwG.dM });
  ok('G9 and where the catalogue is one scale, the fit agrees with the anchor within its own error bar',
    Math.abs(s.all - ANCHOR.published.b) < a6.fits.all.sigmaAki,
    `mixture ${f4(s.all)} at Mc 6.0 +/- ${f4(a6.fits.all.sigmaAki)} against the anchor's published ${ANCHOR.published.b}; `
    + 'not a like-for-like test (Mc 6.0 on one year of ComCat against Mw >= 6.5 over 44 years of GCMT)');
}

// the disjoint windows: the vacuity handled in the instrument, not in a footnote.
const nowMs = cat.rows.length ? cat.rows[cat.rows.length - 1].timeMs : Date.now();
const dw = disjointWindows(cat.rows, { nowMs, days: 90 });
const bRecent = akiFit(dw.recent.map((r) => r.mag), MC, bwG.dM);
const bPrior = akiFit(dw.prior.map((r) => r.mag), MC, bwG.dM);
const odG = overdispersion(cat.rows, { days: 90, mc: MC, dM: bwG.dM });
const vv = vacuityVerdict({
  rollingN: cat.rows.length, recentN: dw.recent.length, priorN: dw.prior.length, sharedEvents: dw.sharedEvents,
  bRecent: bRecent.ok ? bRecent.bUnbiased : NaN, bPrior: bPrior.ok ? bPrior.bUnbiased : NaN,
  sigmaRecent: bRecent.ok ? bRecent.sigmaAki : 0, sigmaPrior: bPrior.ok ? bPrior.sigmaAki : 0, days: 90,
  dispersion: odG.ok ? odG.factor : 1,
});
ok('G10 the two 90-day windows the page compares really are disjoint', dw.sharedEvents === 0, `${dw.sharedEvents} events in common`);
ok('G10b the widening factor the verdict uses is measured on this catalogue, and never narrows the bar',
  odG.ok && odG.factor >= 1,
  odG.ok ? `${odG.windows} disjoint 90-day windows scatter by ${f4(odG.sdObserved)} against a mean formal sigma of ${f4(odG.meanFormalSigma)}: factor ${odG.factor.toFixed(2)}` : odG.reason);
console.log(`        ${vv.line}`);

/* G11. THE PINNED PAST WINDOW. This used to be derived from the newest event in tonight's
 * feed ("182 to 365 days before it"), so it slid forward on every run: the record's first
 * line covered 2025-08-14 to 2026-02-13 and the next run covered 2025-08-15 to 2026-02-14.
 * The column is sold as the way to catch a number that changed underneath the page, and it
 * could not do that, because any movement conflated catalogue revision with a wholly
 * different set of earthquakes. It is now fixed calendar dates, identical on every run. */
const pw = pastWindow(cat.rows);
const bPast = pw.covered ? akiFit(pw.events.map((r) => r.mag), MC, bwG.dM) : { ok: false, reason: 'window_not_covered' };
ok('G11 the pinned past window is covered by this query and still fits, so a later run compares like with like',
  pw.covered && bPast.ok,
  pw.covered ? `b = ${f4(bPast.bUnbiased)} on N = ${bPast.n} for the fixed window ${PAST_WINDOW.from} to ${PAST_WINDOW.to}` : 'the trailing query no longer reaches back to the pinned window');
ok('G11b the past window is pinned to fixed dates, not derived from tonight\'s newest event',
  /^\d{4}-\d{2}-\d{2}$/.test(PAST_WINDOW.from) && /^\d{4}-\d{2}-\d{2}$/.test(PAST_WINDOW.to)
    && pw.fromMs === Date.parse(PAST_WINDOW.from + 'T00:00:00Z'),
  `${PAST_WINDOW.from} to ${PAST_WINDOW.to}, the same window on every run`);

/* G13. The freshness gate, on the catalogue actually being fitted here.
 * The reference clock is the LIVE fetch time when running live, and the snapshot's own
 * date when running against the committed snapshot. That fixture is deliberately frozen,
 * so scoring it against today's clock would turn this red a few days after the wave lands,
 * for the one reason that is not a defect. Live, the reference is the real fetch and the
 * gate is the real gate. */
const SNAPSHOT_DATE_UTC = Date.parse('2026-08-15T12:00:00Z');
const refClock = source.kind === 'live' && source.fetched_at ? Date.parse(source.fetched_at) : SNAPSHOT_DATE_UTC;
const frG = freshness(cat.rows, refClock);
ok('G13 the catalogue being fitted is current, judged by its newest earthquake and not by a header',
  frG.ok, `newest event ${frG.ageDays === null ? 'n/a' : frG.ageDays.toFixed(2)} days before the ${source.kind === 'live' ? 'fetch' : "snapshot's own date"} (limit ${FRESHNESS_MAX_AGE_DAYS})`);

const magsHash = await sha256Hex(cat.rows.map((r) => r.mag).sort((a, b) => a - b).map((m) => m.toFixed(2)).join(','));
ok('G12 the exact magnitude list that was fitted is hashed, so a later run can prove it changed',
  /^[0-9a-f]{64}$/.test(magsHash), magsHash.slice(0, 16) + '...');

/* ══ J. the shipped page, read as text ═════════════════════════════════════
 * A verifier that only re-derives the maths cannot go red when the PAGE is wrong. These
 * checks read the files that actually ship and assert that the page has no second copy of
 * anything checked above.
 */
console.log('\n— J. coupling to the shipped page —');
{
  const html = readFileSync(join(PAGE, 'index.html'), 'utf8');
  const js = readFileSync(join(PAGE, 'page.js'), 'utf8');
  const scripts = [...html.matchAll(/<script([^>]*)>/g)].map((m) => m[1]);
  // The CLAIM is that none of this page's own logic runs inline, so nothing can drift from
  // the modules this verifier checks. The original assertion tested an exact script
  // INVENTORY instead, which is a different thing: the site's chrome generators
  // (nearby-layers, site-bar, way-out, plain-cards) inject shared scripts into every shipped
  // page at consolidation, and the check went red for a page that had not changed. Asserting
  // an incidental byte order rather than the property is the failure this corpus documented
  // on 2026-08-09, so this now tests the claim and tolerates site chrome.
  const own = scripts.filter((a) => !/src="\/(media|_kit|tv|os-assets)\//.test(a));
  const inlineOwn = own.filter((a) => !/\bsrc=/.test(a) && !/application\/ld\+json/.test(a));
  ok('J1 none of the page\'s own logic is inline: its only own scripts are the JSON-LD block and the module',
    inlineOwn.length === 0
      && own.some((a) => /application\/ld\+json/.test(a))
      && own.some((a) => /type="module"/.test(a) && /src="\.\/page\.js"/.test(a)),
    `own: ${own.join(' | ')}   (site chrome ignored: ${scripts.length - own.length})`);
  try { JSON.parse(html.split('<script type="application/ld+json">')[1].split('</script>')[0]); ok('J2 the JSON-LD block is valid JSON', true); }
  catch (e) { ok('J2 the JSON-LD block is valid JSON', false, e.message); }
  ok('J3 the page imports the same four modules this verifier imports',
    ['./bvalue.js', './catalogue.js', './narrate.js', './anchor-gcmt.js'].every((m) => js.includes(`from '${m}'`)));
  ok('J4 the page fetches only through the shared kit, never an upstream host directly',
    js.includes("from '/_kit/livefeed.js'") && !/https?:\/\/(?!artwaste)/.test(js.replace(/^\s*\*.*$/gm, '')),
    'no third-party URL in page.js outside comments');
  // The page must not carry its own copy of the estimator: exactly one file may contain
  // the Aki formula, and it is the one whose behaviour section A above proved.
  const akiFormula = /1\s*\/\s*\(LN10\s*\*|1\s*\/\s*\(Math\.(LN10|log\(10\))/;
  ok('J5 only bvalue.js contains the Aki formula, so the page cannot drift from the verifier',
    !akiFormula.test(js) && !akiFormula.test(readFileSync(join(PAGE, 'catalogue.js'), 'utf8')) && akiFormula.test(readFileSync(join(PAGE, 'bvalue.js'), 'utf8')));
  ok('J6 the page prints a command that exists',
    html.includes('verify-where-the-catalogue-stops-listening.mjs') && existsSync(join(HERE, 'verify-where-the-catalogue-stops-listening.mjs')));
  ok('J7 the anchor artifact ships beside the page and is a module, not a fetch',
    existsSync(join(PAGE, 'anchor-gcmt.js')) && statSync(join(PAGE, 'anchor-gcmt.js')).size > 10000);
}

/* ══ H. the forward claims ═════════════════════════════════════════════════ */
console.log('\n— H. the forward claims —');
let shippedBAll = null;
if (existsSync(RECORD_PATH)) {
  const first = readFileSync(RECORD_PATH, 'utf8').split('\n').filter(Boolean)[0];
  if (first) { try { shippedBAll = JSON.parse(first).global?.b_all ?? null; } catch { /* ignore */ } }
}
const observations = {
  bMb: fMb.ok ? fMb.bUnbiased : NaN, sigmaMb: fMb.ok ? fMb.sigmaAki : NaN,
  bMw: fMw.ok ? fMw.bUnbiased : NaN, sigmaMw: fMw.ok ? fMw.sigmaAki : NaN,
  bAll: fAll.ok ? fAll.bUnbiased : NaN, bAllShipped: shippedBAll ?? SHIPPED_B_ALL,
  crossoverBin: A.crossover.ok ? A.crossover.bin : NaN,
};
const today = new Date().toISOString().slice(0, 10);
const scored = scoreClaims(observations, today);
for (const s of scored) console.log(`        ${s.id.padEnd(20)} ${s.verdict.padEnd(8)} value ${s.value === null ? 'n/a' : (+s.value).toFixed(4)} ${s.unit || ''} (threshold ${s.threshold}), would hold today: ${s.would_hold_today}`);
ok('H1 every forward claim is scored, with a verdict and a running value', scored.length === CLAIMS.length && scored.every((s) => s.verdict));
ok(`H2 before ${CLAIM_DATE} the verdicts are pending, not quietly counted as wins`,
  today >= CLAIM_DATE || scored.every((s) => s.verdict === 'pending'));
/* H3. The browser cannot read record.jsonl, so C3's shipped comparison value is a constant
 * in narrate.js. It used to score against tonight's OWN value in the browser, which made
 * the reader's copy of C3 a claim that could not fail: it read 0.000 and "would hold" on
 * every visit forever. Now that the constant is load-bearing, it has to be pinned to the
 * record or the page and the verifier are scoring two different claims. */
ok('H3 the shipped mixture b the browser scores C3 against is line one of the record',
  shippedBAll === null || near(SHIPPED_B_ALL, shippedBAll, 1e-9),
  `narrate.js says ${SHIPPED_B_ALL}, record line one says ${shippedBAll}`);

/* ══ I. the record ═════════════════════════════════════════════════════════ */
console.log('\n— I. the record —');
const line = {
  run_utc: new Date().toISOString(),
  source: source.kind,
  source_label: source.label,
  feed_fetched_at: source.fetched_at,
  upstream_last_modified: source.upstream_last_modified,
  upstream: source.upstream,
  live_attempt_failed: source.live_attempt_failed ?? null,
  query: 'usgs-quakes-region region=global days=365 minmag=4.5 eventtype=earthquake (built inside worker.js)',
  global: {
    n: A.counts.total, dM: bwG.dM, mc: MC,
    n_mb: A.counts.mb, n_mw: A.counts.mw,
    b_all: fAll.ok ? +fAll.bUnbiased.toFixed(4) : null,
    sigma_aki_all: fAll.ok ? +fAll.sigmaAki.toFixed(4) : null,
    sigma_shibolt_all: fAll.ok ? +fAll.sigmaShiBolt.toFixed(4) : null,
    b_mb: fMb.ok ? +fMb.bUnbiased.toFixed(4) : null, sigma_aki_mb: fMb.ok ? +fMb.sigmaAki.toFixed(4) : null,
    b_mw: fMw.ok ? +fMw.bUnbiased.toFixed(4) : null, sigma_aki_mw: fMw.ok ? +fMw.sigmaAki.toFixed(4) : null,
    separation_sigma: +sepLive.toFixed(2),
    crossover_bin: A.crossover.ok ? A.crossover.bin : null,
    sweep,
    magnitudes_sha256: magsHash,
  },
  disjoint_90d: {
    shared_events: dw.sharedEvents,
    b_recent: bRecent.ok ? +bRecent.bUnbiased.toFixed(4) : null, n_recent: dw.recent.length,
    b_prior: bPrior.ok ? +bPrior.bUnbiased.toFixed(4) : null, n_prior: dw.prior.length,
    verdict: vv.verdict, in_sigmas: Number.isFinite(vv.inSigmas) ? +vv.inSigmas.toFixed(2) : null,
  },
  closed_past_window: {
    from: PAST_WINDOW.from, to: PAST_WINDOW.to, pinned: true, covered: pw.covered,
    b: bPast.ok ? +bPast.bUnbiased.toFixed(4) : null, n: bPast.ok ? bPast.n : 0,
  },
  freshness: {
    newest_event_utc: frG.newestMs === null ? null : new Date(frG.newestMs).toISOString(),
    age_days: frG.ageDays === null ? null : +frG.ageDays.toFixed(3),
    max_age_days: FRESHNESS_MAX_AGE_DAYS, ok: frG.ok,
  },
  overdispersion: odG.ok
    ? { days: odG.days, windows: odG.windows, sd_observed: +odG.sdObserved.toFixed(4), mean_formal_sigma: +odG.meanFormalSigma.toFixed(4), factor: +odG.factor.toFixed(3) }
    : { reason: odG.reason, factor: 1 },
  anchor: {
    published_b: ANCHOR.published.b, published_sigma: ANCHOR.published.sigma, published_n: ANCHOR.published.n,
    hypocentral_b: +anchorFits.hypocentral.bUnbiased.toFixed(4), hypocentral_n: anchorFits.hypocentral.n,
    centroid_b: +anchorFits.centroid.bUnbiased.toFixed(4), centroid_n: anchorFits.centroid.n,
    residual_hypocentral: +(anchorFits.hypocentral.bUnbiased - ANCHOR.published.b).toFixed(4),
    residual_centroid: +(anchorFits.centroid.bUnbiased - ANCHOR.published.b).toFixed(4),
    parse_revision: ANCHOR_PARSE_REVISION,
  },
  socal: socalSummary,
  planted_control: {
    b_true: controlSummary.bTrue,
    b_all: +controlSummary.all.toFixed(4), b_mb: +controlSummary.mb.toFixed(4), b_mw: +controlSummary.mw.toFixed(4),
    separation_sigma: +controlSummary.separation_sigma.toFixed(1),
    negative_control_separation_sigma: +controlSummary.negative_control_separation_sigma.toFixed(1),
  },
  claims: scored,
  checks_run: 0, checks_failed: 0,
};

if (RECORD) {
  const before = existsSync(RECORD_PATH) ? readFileSync(RECORD_PATH, 'utf8').split('\n').filter(Boolean).length : 0;
  line.checks_run = checks + 4; line.checks_failed = fails;
  appendFileSync(RECORD_PATH, JSON.stringify(line) + '\n');
  const after = readFileSync(RECORD_PATH, 'utf8').split('\n').filter(Boolean);
  ok('I1 the record grew by exactly one line and every line still parses',
    after.length === before + 1 && after.every((l) => { try { JSON.parse(l); return true; } catch { return false; } }),
    `${after.length} lines`);
  // I2. The anchor's catalogue is closed, so the anchor must not move -- but it is allowed
  // to move ONCE per correction of the derivation, and only if the correction is declared in
  // the record itself. On 2026-08-15 review found build-anchor.mjs reading the NDK
  // hypocentral depth from cols 44-48 instead of 43-47; fixing it moved hypocentral b from
  // 1.0278 to 1.0229. Lines written before that carry no parse_revision. The baseline is
  // therefore the first line written under TONIGHT's revision, and drift is measured against
  // that. A moved anchor with no declared revision change is still a failure, which is the
  // thing this check exists to catch.
  const lines = after.map((l) => JSON.parse(l));
  const sameRev = lines.filter((l) => l.anchor && l.anchor.parse_revision === ANCHOR_PARSE_REVISION);
  const baseline = sameRev[0];
  const priorRevs = [...new Set(lines.map((l) => (l.anchor && l.anchor.parse_revision) || 'pre-revision-tracking'))];
  /* `after` already contains the line just appended, so on the FIRST run under a revision
   * sameRev has exactly one member and this check compares tonight's line against itself:
   * green, and vacuous, precisely when the anchor is least established. It now says so out
   * loud instead. Committing a line under the current revision is what arms it. */
  if (sameRev.length < 2) {
    ok('I2 SKIPPED and declared: the anchor-drift check needs a committed line under this revision to compare against',
      false, `only ${sameRev.length} line(s) carry ${ANCHOR_PARSE_REVISION}, so there is nothing yet to have drifted FROM. Commit this line and the check arms itself.`);
  } else {
    ok('I2 the ANCHOR has not moved since the first run under this parse revision',
      baseline.anchor.hypocentral_b === line.anchor.hypocentral_b
        && baseline.anchor.centroid_b === line.anchor.centroid_b,
      `baseline ${baseline.anchor.hypocentral_b} (${baseline.run_utc}), tonight ${line.anchor.hypocentral_b}, across ${sameRev.length} lines under ${ANCHOR_PARSE_REVISION}`);
  }
  ok('I2b any anchor value differing from line one is explained by a declared parse revision',
    JSON.parse(after[0]).anchor.hypocentral_b === line.anchor.hypocentral_b || priorRevs.length > 1,
    priorRevs.length > 1
      ? `anchor moved across a declared correction; revisions on record: ${priorRevs.join(', ')}`
      : 'anchor unchanged since line one');
  ok('I3 the record carries the sha256 of the exact magnitude list, so drift is provable',
    typeof line.global.magnitudes_sha256 === 'string' && line.global.magnitudes_sha256.length === 64);
} else {
  console.log('        (not appending: pass --record to write a line to record.jsonl)');
  console.log('        ' + JSON.stringify(line).slice(0, 220) + '...');
  checks += 4;
}

console.log(`\n${fails === 0 ? 'PASS' : 'FAIL'}  ${checks - fails}/${checks} checks passed  (source: ${source.label})`);
process.exit(fails === 0 ? 0 : 1);
