#!/usr/bin/env node
/* verify-the-example-in-the-rulebook-moved.mjs
 *
 * Recomputes every number the stratum shows, offline where it can and against the live
 * service where it must, and appends one line to record.jsonl.
 *
 * It imports the page's own modules rather than reimplementing them, so the page and the
 * verifier cannot drift apart. Where importing the page's code would make a check circular,
 * the check is done a second, independent way inside this file and the two are compared:
 *
 *   - the 68 input peaks are RE-PARSED out of Bulletin 17C's text layer and diffed against
 *     the transcription the page ships, so a typo in the transcription fails here;
 *   - the Pearson III frequency factor is recomputed by a completely different algorithm
 *     (bisection on the regularised incomplete gamma, no Newton, no Lanczos-reuse) and the
 *     two are required to agree to 1e-9;
 *   - the published quantiles are re-parsed out of table 10-5's own text.
 *
 * NEGATIVE CONTROLS, because a suite of checks that cannot fail has tested nothing:
 *   - Wilson-Hilferty, run on the identical moments, MUST miss the published table.
 *   - The weighted skew 17C's prose names MUST miss the published table.
 *   - A payload shifted 400 days into the past MUST be refused by the freshness test.
 *   - A synthetic peak planted in the RAW PAYLOAD the parser iterates MUST be found by the
 *     same unmodified code that finds a real one, and MUST NOT be found when it is planted
 *     one day outside the water year being asked for.
 *
 * Usage:
 *   node research/the-example-in-the-rulebook-moved/verify-the-example-in-the-rulebook-moved.mjs
 *   ... --offline        skip everything that needs the network (recorded as skipped, not passed)
 *   ... --refetch-pdf    also re-download the 29 MB anchor PDF and re-extract table 10-2
 *   ... --no-record      do not append to record.jsonl
 *
 * No dependencies. --refetch-pdf additionally wants pdftotext on PATH.
 */

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

const HERE = dirname(fileURLToPath(import.meta.url));
const ROOT = join(HERE, '..', '..');
const PAGE = join(ROOT, 'public', 'strata', 'the-example-in-the-rulebook-moved');

const argv = process.argv.slice(2);
const OFFLINE = argv.includes('--offline');
const REFETCH_PDF = argv.includes('--refetch-pdf');
const NO_RECORD = argv.includes('--no-record');

const UA = 'ArtificialWasteland/1.0 (+https://artwaste.land; stratum verifier, a handful of requests per run)';

// ── the page's own modules ──────────────────────────────────────────────────────────
const lp3 = await import(join(PAGE, 'lp3.js'));
const series = await import(join(PAGE, 'series.js'));
const openyear = await import(join(PAGE, 'openyear.js'));

const {
  fit, q1pct, frequencyFactor, logMoments, bootstrapCI, breakEvenPeak, breakEvenCrossings,
  chanceInYears, gammaP, AEPS,
} = lp3;
const {
  BOOK_PEAKS, BOOK_VALUES, DERIVED_PEAKS, OVERLAP_CONTROL, PUBLISHED_105, PUBLISHED_MOMENTS,
  B17B_APPENDIX_3, GAUGE, CLOSED_PEAKS, CLOSED_VALUES, CLOSED_DATED, RECORD_EDITS,
} = series;
const {
  parseIv, annualMaximum, latest, freshness, waterYearOf, openWaterYearFromData, rankAmong,
  FRESHNESS_FLAG_HOURS, FRESHNESS_REFUSE_HOURS, OBSERVED_MAX_GAP_MINUTES,
} = openyear;

// ── harness ─────────────────────────────────────────────────────────────────────────
let passed = 0, failed = 0, skipped = 0;
const failures = [];
const ok = (name, cond, extra = '') => {
  if (cond) { passed++; console.log(`  ok   ${name}${extra ? '   ' + extra : ''}`); }
  else { failed++; failures.push(name); console.log(`FAIL   ${name}${extra ? '   ' + extra : ''}`); }
  return !!cond;
};
const skip = (name, why) => { skipped++; console.log(`  skip ${name}   (${why})`); };
const near = (a, b, eps) => Number.isFinite(a) && Number.isFinite(b) && Math.abs(a - b) <= eps;
const head = (s) => console.log(`\n== ${s} ==`);
const sha256 = (buf) => createHash('sha256').update(buf).digest('hex');

async function get(url, { text = true } = {}) {
  const res = await fetch(url, { headers: { 'User-Agent': UA, Accept: '*/*' }, redirect: 'follow' });
  const body = text ? await res.text() : Buffer.from(await res.arrayBuffer());
  return { status: res.status, ok: res.ok, bytes: text ? Buffer.byteLength(body) : body.length, body, url: res.url };
}

// ════════════════════════════════════════════════════════════════════════════════════
// 0. THE MODULES LOAD AND EXPORT WHAT THE PAGE IMPORTS
// ════════════════════════════════════════════════════════════════════════════════════
head('the modules the page loads');
ok('lp3.js exports the fitting surface the page uses',
   [fit, q1pct, frequencyFactor, logMoments, bootstrapCI, breakEvenPeak, breakEvenCrossings, chanceInYears].every((f) => typeof f === 'function'));
ok('series.js ships 68 book peaks and 11 derived peaks',
   BOOK_PEAKS.length === 68 && DERIVED_PEAKS.length === 11, `${BOOK_PEAKS.length} + ${DERIVED_PEAKS.length}`);
ok('the closed record is 79 water years, 1947 to 2025 with no gap',
   CLOSED_PEAKS.length === 79 && CLOSED_PEAKS.every((r, i) => r.wy === 1947 + i));
ok('openyear.js exports the derivation, the freshness test and its two thresholds',
   typeof annualMaximum === 'function' && typeof freshness === 'function'
   && FRESHNESS_FLAG_HOURS === 3 && FRESHNESS_REFUSE_HOURS === 24);

// The page writes into ids by hand; a renamed id is a silent blank on the live page.
head('the page and its script still agree about every id');
{
  const html = readFileSync(join(PAGE, 'index.html'), 'utf8');
  const js = readFileSync(join(PAGE, 'page.js'), 'utf8');
  const ids = [...js.matchAll(/\$\('([a-z0-9-]+)'\)/g)].map((m) => m[1]);
  const uniq = [...new Set(ids)];
  const missing = uniq.filter((id) => !new RegExp(`id="${id}"`).test(html));
  ok(`every id page.js writes to exists in index.html (${uniq.length} ids)`, missing.length === 0,
     missing.length ? 'missing: ' + missing.join(', ') : '');
  ok('index.html closes script, body and html (a missing tag silently kills the module)',
     /<\/script>/.test(html) && /<\/body>/.test(html) && /<\/html>/.test(html));
  ok('the page loads page.js as a module and declares no inline script',
     /<script type="module" src="\.\/page\.js"><\/script>/.test(html)
     && !/<script(?![^>]*src=)(?![^>]*application\/ld\+json)/.test(html));
  // The corpus-wide placard injector anchors on the LAST literal body tag in the file. This
  // page's trailing note used to print the closing tags it was talking about, so the block
  // landed inside that comment, ended it early, and rendered developer commentary to every
  // reader as body text. Prose about markup must name tags, not show them.
  const afterHtml = html.slice(html.lastIndexOf('</html>') + '</html>'.length);
  ok('nothing follows the closing html tag but a comment, and that comment contains no literal tag',
     /^\s*(?:<!--[\s\S]*?-->\s*)*$/.test(afterHtml) && !/<\/?(script|body|html|aside|style|div|p)\b/i.test(afterHtml),
     `${afterHtml.trim().length} bytes after the document`);
  ok('the "how this layer is checked" placard sits inside the body, where a reader can see it',
     !html.includes('aw-checkkind:start') || html.indexOf('aw-checkkind:start') < html.lastIndexOf('</body>'));
  ok('the document has exactly one closing body tag', (html.match(/<\/body>/g) || []).length === 1);
  const ld = html.match(/<script type="application\/ld\+json">([\s\S]*?)<\/script>/);
  let ldOk = false;
  try { ldOk = !!JSON.parse(ld[1]).headline; } catch { ldOk = false; }
  ok('the JSON-LD block parses as JSON', ldOk);
}

// ════════════════════════════════════════════════════════════════════════════════════
// 1. THE ANCHOR, RE-PARSED FROM THE DOCUMENT RATHER THAN TRUSTED
// ════════════════════════════════════════════════════════════════════════════════════
head('Bulletin 17C table 10-2, re-parsed from the PDF text layer');

const FIXTURES = join(HERE, 'fixtures');
const T102_SHA = 'cafd1e183fb1ec74fb2cffdc626ead4d2506c2c9b67413ebb842439232e77f79';
const T105_SHA = 'df42e29468e5949852372ecc3b2d8d6bb30d137c7d18839bf172dd5951328f94';
const PDF_SHA = '2ada3990b661ea04e72c1fa8e11524b1828ecc48201cb918728d1a72703359dd';
const PDF_BYTES = 28947874;
const PDF_URL = 'https://pubs.usgs.gov/tm/04/b05/tm4b5.pdf';

function parseTable102(block) {
  const rows = [...block.matchAll(/(\d{4}-\d{2}-\d{2})\s+(\d{4})\s+([\d,]+)/g)]
    .map((m) => ({ date: m[1], wy: Number(m[2]), cfs: Number(m[3].replace(/,/g, '')) }));
  rows.sort((a, b) => a.wy - b.wy);
  return rows;
}
function parseTable105(block) {
  // "0.010   4,957   0.0031   4,131   7,735"
  return [...block.matchAll(/(0\.\d{3})\s+([\d,]+)\s+(0\.\d{4})\s+([\d,]+)\s+([\d,]+)/g)]
    .map((m) => ({
      aep: Number(m[1]), ema: Number(m[2].replace(/,/g, '')), variance: Number(m[3]),
      lower: Number(m[4].replace(/,/g, '')), upper: Number(m[5].replace(/,/g, '')),
    }));
}

const t102Text = readFileSync(join(FIXTURES, 'table-10-2.txt'));
const t105Text = readFileSync(join(FIXTURES, 'table-10-5.txt'));
ok('the committed table 10-2 text block is the one this file was written against',
   sha256(t102Text) === T102_SHA, sha256(t102Text).slice(0, 16));
ok('the committed table 10-5 text block is the one this file was written against',
   sha256(t105Text) === T105_SHA, sha256(t105Text).slice(0, 16));

const parsed102 = parseTable102(t102Text.toString('utf8'));
ok('table 10-2 parses to 68 rows, water years 1947 to 2014, none missing',
   parsed102.length === 68 && parsed102[0].wy === 1947 && parsed102[67].wy === 2014
   && parsed102.every((r, i) => r.wy === 1947 + i), `${parsed102.length} rows`);
{
  const diffs = parsed102.filter((r, i) => r.cfs !== BOOK_PEAKS[i].cfs || r.date !== BOOK_PEAKS[i].date || r.wy !== BOOK_PEAKS[i].wy);
  ok('every one of the 68 peaks and its date matches the transcription the page ships',
     diffs.length === 0, diffs.length ? JSON.stringify(diffs.slice(0, 3)) : '');
}
{
  const parsed105 = parseTable105(t105Text.toString('utf8'));
  ok('table 10-5 parses to the 6 published rows', parsed105.length === 6, `${parsed105.length}`);
  const diffs = parsed105.filter((r, i) => {
    const p = PUBLISHED_105[i];
    return !p || r.aep !== p.aep || r.ema !== p.ema || r.variance !== p.variance || r.lower !== p.lower || r.upper !== p.upper;
  });
  ok('every published quantile, variance and confidence limit matches what the page ships',
     diffs.length === 0, diffs.length ? JSON.stringify(diffs) : '');
}

if (REFETCH_PDF) {
  head('re-downloading the anchor document and re-extracting the table');
  try {
    const r = await get(PDF_URL, { text: false });
    ok('pubs.usgs.gov serves the anchor PDF', r.ok, `HTTP ${r.status}, ${r.bytes} bytes`);
    ok('the PDF is byte-for-byte the edition this page reproduces',
       r.bytes === PDF_BYTES && sha256(r.body) === PDF_SHA, sha256(r.body).slice(0, 16));
    const tmp = join(FIXTURES, '.tm4b5.pdf');
    writeFileSync(tmp, r.body);
    const txt = execFileSync('pdftotext', ['-layout', tmp, '-'], { maxBuffer: 64 * 1024 * 1024 }).toString('utf8');
    const i = txt.indexOf('Table 10–2. U.S. Geological Survey station 01134500');
    const j = txt.indexOf('Table 10–3.', i);
    const fresh = parseTable102(txt.slice(i, j));
    ok('re-extracting from the freshly downloaded PDF gives the same 68 peaks',
       fresh.length === 68 && fresh.every((r2, k) => r2.cfs === BOOK_PEAKS[k].cfs && r2.date === BOOK_PEAKS[k].date));
  } catch (e) {
    ok('the PDF re-extraction path ran', false, String(e && e.message || e));
  }
} else {
  skip('re-downloading the 29 MB anchor PDF and re-extracting table 10-2', 'pass --refetch-pdf');
}

// ════════════════════════════════════════════════════════════════════════════════════
// 2. THE FREQUENCY FACTOR, CHECKED TWO WAYS
// ════════════════════════════════════════════════════════════════════════════════════
head('the Pearson III frequency factor against Bulletin 17B appendix 3 (1982)');
{
  let worst = 0, n = 0;
  for (const row of B17B_APPENDIX_3.rows) {
    for (let j = 0; j < B17B_APPENDIX_3.skews.length; j++) {
      const ours = frequencyFactor(row.p, B17B_APPENDIX_3.skews[j]);
      worst = Math.max(worst, Math.abs(ours - row.k[j]));
      n++;
    }
  }
  ok(`all ${n} tabulated K values reproduce to better than 5e-5`, worst < 5e-5, `worst ${worst.toExponential(2)}`);
  ok('the check covers negative skew as well as positive, through the mirrored branch',
     near(frequencyFactor(0.01, -0.4), 2.02933, 5e-5) && near(frequencyFactor(0.01, -0.5), 1.95472, 5e-5),
     'K(1%,-0.4)=2.02933 and K(1%,-0.5)=1.95472, both from 17B by reflection');
}

head('and against a second, independent implementation written in this file');
{
  // Deliberately a different algorithm: plain bisection on the regularised incomplete
  // gamma, no Newton step, no shared starting value. If lp3's inverse were subtly wrong,
  // this would not share the error.
  const gammaQuantileByBisection = (a, p) => {
    let lo = 0, hi = Math.max(2 * a, 10);
    while (gammaP(a, hi) < p) hi *= 2;
    for (let i = 0; i < 200; i++) {
      const mid = (lo + hi) / 2;
      if (gammaP(a, mid) < p) lo = mid; else hi = mid;
    }
    return (lo + hi) / 2;
  };
  const kIndependent = (p, g) => {
    const a = 4 / (g * g);
    const y = g > 0 ? gammaQuantileByBisection(a, 1 - p) : gammaQuantileByBisection(a, p);
    return g > 0 ? (y - a) / Math.sqrt(a) : -(y - a) / Math.sqrt(a);
  };
  let worst = 0;
  for (const g of [0.05, 0.2, 0.397, 0.421, 0.6, 1.2, -0.3, -0.9, -3.0]) {
    for (const p of [0.5, 0.1, 0.02, 0.01, 0.002]) {
      worst = Math.max(worst, Math.abs(frequencyFactor(p, g) - kIndependent(p, g)));
    }
  }
  ok('45 (skew, probability) pairs agree between the two implementations to 1e-9',
     worst < 1e-9, `worst ${worst.toExponential(2)}`);
}

// ════════════════════════════════════════════════════════════════════════════════════
// 3. THE ANCHOR REPRODUCTION, AND THE THINGS THAT MUST FAIL IT
// ════════════════════════════════════════════════════════════════════════════════════
head("the anchor: 17C's own method on 17C's own printed peaks");
const A = fit(BOOK_VALUES);
ok('n = 68', A.n === 68);
ok(`mean of the base-10 logs rounds to the printed ${PUBLISHED_MOMENTS.mean}`,
   Number(A.mean.toFixed(4)) === PUBLISHED_MOMENTS.mean, A.mean.toFixed(6));
ok(`standard deviation rounds to the printed ${PUBLISHED_MOMENTS.sd}`,
   Number(A.sd.toFixed(4)) === PUBLISHED_MOMENTS.sd, A.sd.toFixed(6));
ok(`station skew rounds to the printed ${PUBLISHED_MOMENTS.stationSkew}`,
   Number(A.skew.toFixed(3)) === PUBLISHED_MOMENTS.stationSkew, A.skew.toFixed(6));

let anchorHits = 0, anchorWorst = 0;
for (let i = 0; i < PUBLISHED_105.length; i++) {
  const pub = PUBLISHED_105[i], ours = A.q[i].value;
  const hit = Math.round(ours) === pub.ema;
  if (hit) anchorHits++;
  anchorWorst = Math.max(anchorWorst, Math.abs(ours - pub.ema) / pub.ema);
  ok(`AEP ${(pub.aep * 100).toFixed(1)}%: ours ${ours.toFixed(2)} rounds to the printed ${pub.ema}`, hit);
}
ok('all six of table 10-5 reproduce', anchorHits === 6, `${anchorHits} of 6`);
ok('worst discrepancy is under one hundredth of a percent', anchorWorst < 1e-4,
   `${(anchorWorst * 100).toFixed(4)}%`);

head('negative controls: three plausible implementations that MUST miss');
{
  const wh = fit(BOOK_VALUES, { method: 'wh' });
  const whHits = wh.q.filter((q, i) => Math.round(q.value) === PUBLISHED_105[i].ema).length;
  ok('Wilson-Hilferty, on identical moments, does NOT reproduce table 10-5',
     whHits < 6, `${whHits} of 6, and at the 1 percent AEP it gives ${wh.q[3].value.toFixed(2)} against 4,957`);

  const wtd = fit(BOOK_VALUES, { skew: PUBLISHED_MOMENTS.weightedSkew });
  const wtdHits = wtd.q.filter((q, i) => Math.round(q.value) === PUBLISHED_105[i].ema).length;
  // What this check may and may not conclude. It shows table 10-5 is NOT reproduced by the
  // weighted skew 17C's own prose names for it. It does not show which run produced the
  // table: the document contains a station-skew run too (figure 10-3), and 17C's EMA under
  // weighted skew could simply depart from the moment fit. An earlier version of this line
  // said "so the table came from the station skew", which is a conclusion the arithmetic
  // does not carry, and the page said the same thing in stronger words.
  ok("the weighted skew 17C's prose names does NOT reproduce table 10-5, so text and table are inconsistent",
     wtdHits === 0, `${wtdHits} of 6, 1 percent AEP ${wtd.q[3].value.toFixed(2)}`);
  ok('and the page states that as an inconsistency rather than as a verdict about which run made the table',
     !/caption under the document's own figure quietly confirms/.test(readFileSync(join(PAGE, 'index.html'), 'utf8'))
     && /text and the table disagree|not what the skew\s+its own text names produces/.test(readFileSync(join(PAGE, 'index.html'), 'utf8').replace(/\s+/g, ' ')));

  // The other tempting mistake: applying 17B's 1 + 6.51/n + 20.2/n^2 factor to the skew.
  const biased = A.skew * (1 + 6.51 / A.n + 20.2 / (A.n * A.n));
  const bh = fit(BOOK_VALUES, { skew: biased });
  const bhHits = bh.q.filter((q, i) => Math.round(q.value) === PUBLISHED_105[i].ema).length;
  ok('a bias-corrected skew does NOT reproduce table 10-5 either, which is how we know it does not belong here',
     bhHits === 0, `skew would be ${biased.toFixed(4)} instead of ${A.skew.toFixed(4)}, 1 percent AEP ${bh.q[3].value.toFixed(2)}`);
}

// ════════════════════════════════════════════════════════════════════════════════════
// 4. THE HEADLINE, AND EVERYTHING THE PAGE PRINTS BESIDE IT
// ════════════════════════════════════════════════════════════════════════════════════
head('the fit on the record as it stands');
const B = fit(CLOSED_VALUES);
ok('n = 79 closed water years', B.n === 79);
ok('the 1 percent AEP is 5,119 ft3/s', Math.round(B.q[3].value) === 5119, B.q[3].value.toFixed(3));
ok('the headline moved up from the published 4,957',
   B.q[3].value > PUBLISHED_105[3].ema, `+${(B.q[3].value - PUBLISHED_105[3].ema).toFixed(1)} ft3/s, +${(100 * (B.q[3].value - PUBLISHED_105[3].ema) / PUBLISHED_105[3].ema).toFixed(1)}%`);
{
  const largest = Math.max(...CLOSED_VALUES);
  ok('the estimate is an extrapolation past the whole record',
     B.q[3].value > largest, `${(B.q[3].value / largest).toFixed(3)} times the largest observed (${largest} ft3/s)`);
}
ok('dropping the single July 2024 peak moves the estimate by about 300 ft3/s',
   near(B.q[3].value - q1pct(CLOSED_PEAKS.filter((r) => r.wy !== 2024).map((r) => r.cfs)), 300, 5),
   `${(B.q[3].value - q1pct(CLOSED_PEAKS.filter((r) => r.wy !== 2024).map((r) => r.cfs))).toFixed(1)} ft3/s`);

head('the wobble the page prints, and the trend it refuses to draw');
{
  const marks = [1990, 2000, 2014, 2018, 2020, 2024, 2025];
  const vals = marks.map((y) => q1pct(CLOSED_PEAKS.filter((r) => r.wy <= y).map((r) => r.cfs)));
  console.log('       ' + marks.map((y, i) => `${y}:${vals[i].toFixed(0)}`).join('  '));
  ok('the series through 2014 reproduces the published 4,957 exactly (it is the same 68 peaks)',
     Math.round(vals[2]) === 4957);
  let monotone = true;
  for (let i = 1; i < vals.length; i++) if (vals[i] < vals[i - 1]) monotone = false;
  ok('the estimate does NOT climb monotonically, so the page is right to call it a wobble', !monotone);
}

head('the bootstrap, and its determinism');
{
  const b1 = bootstrapCI(CLOSED_VALUES, 0.01, 4000);
  const b2 = bootstrapCI(CLOSED_VALUES, 0.01, 4000);
  ok('the same seed gives byte-identical limits on two runs, so the page and this file agree',
     b1.lower === b2.lower && b1.upper === b2.upper, `${b1.lower.toFixed(0)} to ${b1.upper.toFixed(0)}`);
  ok('the bootstrap interval contains the point estimate',
     b1.lower < B.q[3].value && B.q[3].value < b1.upper);
  ok("ours is NARROWER than 17C's published band, which is why the page does not claim to reproduce it",
     (b1.upper / b1.lower) < (PUBLISHED_105[3].upper / PUBLISHED_105[3].lower),
     `ours ${(b1.upper / b1.lower).toFixed(2)}x against 17C's ${(PUBLISHED_105[3].upper / PUBLISHED_105[3].lower).toFixed(2)}x`);
}

head('the break-even, which is not unique');
const CROSS = breakEvenCrossings(CLOSED_VALUES);
{
  ok('there is more than one peak size that leaves the estimate unchanged',
     CROSS.crossings.length > 1, CROSS.crossings.map((v) => v.toFixed(2)).join(', '));
  const be = breakEvenPeak(CLOSED_VALUES);
  ok('breakEvenPeak returns the largest of them', be === CROSS.crossings[CROSS.crossings.length - 1], be.toFixed(3));
  ok('just above it the estimate rises, just below it falls',
     q1pct(CLOSED_VALUES.concat([be + 50])) > B.q[3].value && q1pct(CLOSED_VALUES.concat([be - 50])) < B.q[3].value);
  const above = CLOSED_VALUES.filter((v) => v > be).length;
  ok(`the page's "how often has a year exceeded it" count is 7 of 79`, above === 7, `${above} of ${CLOSED_VALUES.length}`);
}

head('the two halves of the forward claim, and why the second does not follow from the first');
{
  // The page used to say the peak coming in below the break-even meant the recomputed 1
  // percent AEP would "therefore" be below tonight's. It does not: the difference curve is
  // not monotone, and between the first two crossings a peak is below the break-even and
  // still raises the estimate. This measures that band instead of assuming either way.
  const be = CROSS.crossings[CROSS.crossings.length - 1];
  let worstX = null, worstD = 0;
  if (CROSS.crossings.length >= 2) {
    for (let x = Math.ceil(CROSS.crossings[0]); x <= Math.floor(CROSS.crossings[1]); x += 1) {
      const d = q1pct(CLOSED_VALUES.concat([x])) - B.q[3].value;
      if (d > worstD) { worstD = d; worstX = x; }
    }
  }
  ok('a peak BELOW the break-even can still raise the 1 percent AEP, so half two is not implied by half one',
     worstX !== null && worstD > 0 && worstX < be,
     worstX === null ? 'no band found' : `+${worstD.toFixed(2)} ft3/s at ${worstX} ft3/s, break-even ${be.toFixed(0)}`);
  const editAlt = q1pct(CLOSED_PEAKS.map((r) => {
    const e = RECORD_EDITS.rows.find((x) => x.wy === r.wy);
    return e ? e.served : r.cfs;
  }));
  ok('and that wobble is larger than the record edit this page calls consequential, so it is a hazard rather than a curiosity',
     worstD > Math.abs(editAlt - B.q[3].value),
     `${worstD.toFixed(2)} ft3/s against the edit's ${Math.abs(editAlt - B.q[3].value).toFixed(2)}`);
  {
    const html = readFileSync(join(PAGE, 'index.html'), 'utf8').replace(/\s+/g, ' ');
    ok('the page states the claim as two halves scored separately, with no "therefore" between them',
       /Both halves are scored separately/.test(html) && !/will therefore be/.test(html));
  }
}

head('layer one: the mortgage arithmetic');
ok('30 years on a 1 percent floodplain is a 26 percent chance of at least one',
   near(chanceInYears(0.01, 30) * 100, 26.03, 0.05), (chanceInYears(0.01, 30) * 100).toFixed(2) + '%');
ok('1 year is exactly 1 percent', near(chanceInYears(0.01, 1), 0.01, 1e-12));
ok('70 years is just over half', chanceInYears(0.01, 70) > 0.5);

// ════════════════════════════════════════════════════════════════════════════════════
// 5. THE OPEN-YEAR TRAP
// ════════════════════════════════════════════════════════════════════════════════════
head("the trap: appending an open water year's running maximum");
{
  const oct1 = fit(CLOSED_VALUES.concat([8]));
  const oct1wh = fit(CLOSED_VALUES.concat([8]), { method: 'wh' });
  ok('a running maximum of 8 ft3/s drives the skew of the logs below -5',
     oct1.skew < -5, oct1.skew.toFixed(3));
  ok('the exact fit then reports a hundred-year flood roughly HALF the honest one, which is the dangerous direction',
     oct1.q[3].value < B.q[3].value * 0.6, `${oct1.q[3].value.toFixed(0)} against ${B.q[3].value.toFixed(0)}`);
  ok('a negative skew gives the fitted distribution a hard upper bound below a flood the river has already had',
     oct1.upperBound !== null && oct1.upperBound < Math.max(...CLOSED_VALUES),
     `ceiling ${oct1.upperBound.toFixed(0)} ft3/s against an observed ${Math.max(...CLOSED_VALUES)}`);
  ok('Wilson-Hilferty on the identical data goes the other way by more than a factor of ten',
     oct1wh.q[3].value / oct1.q[3].value > 10,
     `${oct1wh.q[3].value.toFixed(0)} against ${oct1.q[3].value.toFixed(0)}, a factor of ${(oct1wh.q[3].value / oct1.q[3].value).toFixed(0)}`);
  ok('the two frequency factors agree to better than 0.1 percent on the real record, so this is not a general disagreement',
     Math.abs(fit(CLOSED_VALUES, { method: 'wh' }).q[3].value - B.q[3].value) / B.q[3].value < 1e-3,
     `${fit(CLOSED_VALUES, { method: 'wh' }).q[3].value.toFixed(1)} against ${B.q[3].value.toFixed(1)}`);
  ok('the guard the page ships is simply not to append it: the shipped fit is on closed years only',
     fit(CLOSED_VALUES).n === 79);
}

head('the second vacuous setting: a record too short to fit');
{
  let threw = false;
  try { logMoments([1000, 2000]); } catch { threw = true; }
  ok('fewer than three peaks throws rather than returning a skew', threw);
  // Read the floor off the CONTROL the page ships, not off the data. Counting
  // CLOSED_PEAKS.filter(wy >= 2016) asserts a property of the record and would keep passing
  // if index.html's slider were changed to max="1990" tomorrow.
  const sinceMax = readFileSync(join(PAGE, 'index.html'), 'utf8')
    .match(/id="since"[^>]*?max="(\d{4})"/);
  const floorYear = sinceMax ? Number(sinceMax[1]) : null;
  ok("the page's start-year slider really does stop at 2016", floorYear === 2016, `max="${floorYear}"`);
  const shortest = CLOSED_PEAKS.filter((r) => r.wy >= floorYear).length;
  ok('and that floor leaves 10 water years, which is where the skew estimator is still usable',
     shortest === 10, `${shortest} years`);
  const swing = [1990, 2000, 2010, 2016].map((y) => q1pct(CLOSED_PEAKS.filter((r) => r.wy >= y).map((r) => r.cfs)));
  ok('and the floor is needed: at 10 years the estimate is already far from the full-record value',
     Math.abs(swing[3] - B.q[3].value) > 300, `10-year fit ${swing[3].toFixed(0)} against ${B.q[3].value.toFixed(0)}`);
}

head("the first vacuous setting: today's flow as a return period");
{
  ok('a positive skew gives the fitted distribution of ANNUAL MAXIMA a hard lower bound',
     B.lowerBound !== null && B.lowerBound > 300 && B.lowerBound < 400, `${B.lowerBound.toFixed(1)} ft3/s`);
  ok('an ordinary August discharge sits below that bound, so there is no return period to print at all',
     32 < B.lowerBound, 'a typical mid-August flow at this gauge is around 30 ft3/s');
  ok('the page never converts a live reading into a return period',
     !/return\s*period/i.test(readFileSync(join(PAGE, 'page.js'), 'utf8').replace(/will not tell you[\s\S]{0,900}/g, '')));
}

// ════════════════════════════════════════════════════════════════════════════════════
// 6. THE DERIVATION, AND ITS DIFFERENTIAL CONTROL
// ════════════════════════════════════════════════════════════════════════════════════
const IV = (site, s, e) =>
  `https://waterservices.usgs.gov/nwis/iv/?format=json&sites=${site}&startDT=${s}&endDT=${e}&parameterCd=00060`;
const IV_PERIOD = (site, days) =>
  `https://waterservices.usgs.gov/nwis/iv/?format=json&sites=${site}&parameterCd=00060&siteStatus=all&period=P${days}D`;

const upstream = { reachable: null, requests: 0, bytes: 0, statuses: [] };
async function iv(url) {
  const r = await get(url);
  upstream.requests++; upstream.bytes += r.bytes; upstream.statuses.push(r.status);
  if (upstream.reachable === null) upstream.reachable = r.ok;
  else upstream.reachable = upstream.reachable && r.ok;
  if (!r.ok) return { ok: false, status: r.status, bytes: r.bytes };
  return { ok: true, status: r.status, bytes: r.bytes, json: JSON.parse(r.body) };
}

let overlapHits = null, derivedHits = null, openYear = null, live = null, fresh = null;

/**
 * Gaps between consecutive readings inside one water year. The page's two freshness
 * thresholds are justified by these numbers, so they are MEASURED on every run rather than
 * compared against each other: the old check here was `24 * 60 > 975`, two hardcoded
 * literals that could not fail whatever the gauge did.
 */
function gapStats(points, wy) {
  const inYear = points.filter((p) => waterYearOf(p.at) === wy);
  let span = 0, blanked = 0, max = 0, maxAt = null, eights = 0, overDay = 0;
  for (let i = 1; i < inYear.length; i++) {
    const d = (Date.parse(inYear[i].at) - Date.parse(inYear[i - 1].at)) / 60000;
    if (!Number.isFinite(d) || d <= 0) continue;
    span += d;
    if (d > max) { max = d; maxAt = inYear[i - 1].at; }
    if (d === 480) eights++;
    if (d > 1440) overDay++;
    blanked += Math.max(0, d - FRESHNESS_FLAG_HOURS * 60);
  }
  return { wy, n: inYear.length, intervals: Math.max(0, inYear.length - 1), spanMinutes: span,
           maxGapMinutes: max, maxGapAfter: maxAt, eightHourGaps: eights, gapsOverADay: overDay,
           blankedByThreeHourRule: span ? blanked / span : null };
}
const historicalGaps = [];
let gapReport = null;

if (OFFLINE) {
  skip('the nine-year derivation control against the live service', '--offline');
  skip('re-deriving the eleven modern peaks against the live service', '--offline');
  skip('reading the open water year', '--offline');
} else {
  head('THE DERIVATION CONTROL: nine water years the book printed and the feed still carries');
  overlapHits = 0;
  for (const row of OVERLAP_CONTROL) {
    const r = await iv(IV(GAUGE.site, `${row.wy - 1}-10-01`, `${row.wy}-09-30`));
    if (!r.ok) { ok(`water year ${row.wy} fetched`, false, `HTTP ${r.status}`); continue; }
    const p = parseIv(r.json);
    historicalGaps.push(gapStats(p.points, row.wy));
    const m = annualMaximum(p.points, row.wy);
    const good = m && m.cfs === row.book && m.at.slice(0, 10) === row.bookDate && m.at === row.at;
    if (good) overlapHits++;
    ok(`WY${row.wy}: max of the 15-minute record is ${m ? m.cfs : 'null'} ft3/s, the book prints ${row.book}`,
       good, m ? `${m.at}, ${m.points} readings, ${r.bytes} bytes` : '');
  }
  ok('all nine overlap years agree with the rulebook on value AND date AND quarter hour',
     overlapHits === OVERLAP_CONTROL.length, `${overlapHits} of ${OVERLAP_CONTROL.length}`);

  head('the eleven modern peaks, re-derived from the service on this run');
  derivedHits = 0;
  for (const row of DERIVED_PEAKS) {
    const r = await iv(IV(GAUGE.site, `${row.wy - 1}-10-01`, `${row.wy}-09-30`));
    if (!r.ok) { ok(`water year ${row.wy} fetched`, false, `HTTP ${r.status}`); continue; }
    const p = parseIv(r.json);
    historicalGaps.push(gapStats(p.points, row.wy));
    const m = annualMaximum(p.points, row.wy);
    const good = m && m.cfs === row.cfs && m.at === row.at && m.points === row.points && m.qual === row.qual;
    if (good) derivedHits++;
    ok(`WY${row.wy}: ${m ? m.cfs : 'null'} ft3/s, ${m ? m.points : 0} readings`, good,
       m && m.cfs !== row.cfs ? `THE RECORD HAS BEEN REVISED: page ships ${row.cfs}, service now serves ${m.cfs}` : '');
  }
  ok('every modern peak the page ships still comes back identical from the service',
     derivedHits === DERIVED_PEAKS.length, `${derivedHits} of ${DERIVED_PEAKS.length}`);

  // ── what the gauge has ACTUALLY done, across every water year this run already fetched ──
  // The page used to say the 24-hour refusal was "longer than the largest gap this gauge has
  // ever produced". It is not, and the counterexamples are in payloads this verifier was
  // already downloading for another purpose, so measuring them costs nothing but the loop.
  head('the largest gap in each historical water year, which is where the "ever" claim died');
  {
    const worst = historicalGaps.slice().sort((a, b) => b.maxGapMinutes - a.maxGapMinutes);
    for (const g of worst.slice(0, 6)) {
      console.log(`       WY${g.wy}: largest gap ${(g.maxGapMinutes / 1440).toFixed(1)} days` +
                  ` after ${g.maxGapAfter}, ${g.gapsOverADay} gaps over a day long`);
    }
    ok('at least one historical water year contains a gap longer than the refusal threshold, so "longer than the gauge has ever gone quiet" would be false',
       worst.length > 0 && worst[0].maxGapMinutes > FRESHNESS_REFUSE_HOURS * 60,
       `largest is WY${worst[0].wy}, ${(worst[0].maxGapMinutes / 1440).toFixed(1)} days`);
    ok('the longest of them is the 131-day water year 2008 outage the page names',
       worst.length > 0 && worst[0].wy === 2008 && Math.round(worst[0].maxGapMinutes / 1440) === 131,
       `WY${worst[0].wy}, ${(worst[0].maxGapMinutes / 1440).toFixed(2)} days`);
    const y2015 = historicalGaps.find((g) => g.wy === 2015);
    const y2006 = historicalGaps.find((g) => g.wy === 2006);
    ok('the 70-day water year 2015 outage the page names is in the record',
       y2015 && Math.round(y2015.maxGapMinutes / 1440) === 70 && y2015.maxGapAfter.startsWith('2014-12-29'),
       y2015 ? `${(y2015.maxGapMinutes / 1440).toFixed(2)} days after ${y2015.maxGapAfter}` : 'not fetched');
    ok('and so are the 45-day water year 2006 outage and its 21 gaps over a day long',
       y2006 && Math.round(y2006.maxGapMinutes / 1440) === 45 && y2006.gapsOverADay === 21,
       y2006 ? `${(y2006.maxGapMinutes / 1440).toFixed(2)} days, ${y2006.gapsOverADay} gaps over a day` : 'not fetched');
    const html = readFileSync(join(PAGE, 'index.html'), 'utf8');
    const js = readFileSync(join(PAGE, 'page.js'), 'utf8');
    const oy = readFileSync(join(PAGE, 'openyear.js'), 'utf8');
    ok('and no shipped file claims the threshold is above anything the gauge has ever done',
       ![html, js].some((t) => /largest gap this gauge has ever produced|above anything the gauge has ever done/.test(t))
       && !/refuse threshold is set\s*\n?\s*\* above the largest gap the gauge has actually produced/.test(oy));
  }
}

head('the differential control: a planted reading must be found by the SAME code, and only where it is');
{
  // Doctor the DATA the parser iterates, never the result list. The synthetic reading goes
  // into the raw WaterML body exactly where a real one lives, and is then found (or not)
  // by the unmodified parseIv + annualMaximum path the page uses.
  const skeleton = (points) => ({
    value: {
      timeSeries: [{
        sourceInfo: { siteName: 'MOOSE RIVER AT VICTORY, VT' },
        variable: { variableCode: [{ value: '00060' }], unit: { unitCode: 'ft3/s' } },
        values: [{ value: points }],
      }],
    },
  });
  const real = [
    { value: '1200', qualifiers: ['A'], dateTime: '2011-04-01T12:00:00.000-04:00' },
    { value: '3140', qualifiers: ['A'], dateTime: '2010-10-01T23:00:00.000-04:00' },
    { value: '900', qualifiers: ['A'], dateTime: '2011-06-01T12:00:00.000-04:00' },
  ];
  const base = annualMaximum(parseIv(skeleton(real)).points, 2011);
  ok('the undoctored control returns the real maximum', base.cfs === 3140 && base.points === 3, `${base.cfs} at ${base.at}`);

  const inside = real.concat([{ value: '9999', qualifiers: ['P'], dateTime: '2011-05-05T09:15:00.000-04:00' }]);
  const found = annualMaximum(parseIv(skeleton(inside)).points, 2011);
  ok('a peak planted INSIDE water year 2011 is found by the same unmodified code path',
     found.cfs === 9999 && found.at === '2011-05-05T09:15:00.000-04:00' && found.points === 4,
     `${found.cfs} at ${found.at}`);

  // Negative control. One day the other side of the water-year boundary and it must vanish.
  const outside = real.concat([{ value: '9999', qualifiers: ['P'], dateTime: '2011-10-05T09:15:00.000-04:00' }]);
  const notFound = annualMaximum(parseIv(skeleton(outside)).points, 2011);
  ok('the same planted peak dated one water year later is NOT found, so the year filter is real',
     notFound.cfs === 3140 && notFound.points === 3, `${notFound.cfs}, ${notFound.points} readings`);
  ok('and it IS found when water year 2012 is the one asked for',
     annualMaximum(parseIv(skeleton(outside)).points, 2012).cfs === 9999);

  // USGS's no-data sentinel must be dropped, not treated as a discharge of minus a million.
  const sentinel = real.concat([{ value: '-999999', qualifiers: ['P'], dateTime: '2011-07-07T00:00:00.000-04:00' }]);
  const withSentinel = parseIv(skeleton(sentinel));
  ok('the -999999 no-data sentinel is dropped rather than parsed as a discharge',
     withSentinel.points.length === 3 && withSentinel.points.every((p) => p.cfs > 0));

  // Water years are read off the local date characters, never through a Date object.
  ok('30 September and 1 October fall in different water years',
     waterYearOf('2011-09-30T23:45:00.000-04:00') === 2011 && waterYearOf('2011-10-01T00:00:00.000-04:00') === 2012);

  // The daylight-saving fall-back repeats the local hour 01:00 to 01:45, and the repeat
  // arrives stamped -05:00 while the first pass was stamped -04:00. Sorted as STRINGS they
  // interleave and `latest()` returns a reading up to 45 minutes stale for that one hour.
  const dst = [
    { value: '10', qualifiers: ['A'], dateTime: '2025-11-02T01:00:00.000-04:00' },
    { value: '11', qualifiers: ['A'], dateTime: '2025-11-02T01:30:00.000-04:00' },
    { value: '12', qualifiers: ['A'], dateTime: '2025-11-02T01:00:00.000-05:00' },
    { value: '13', qualifiers: ['A'], dateTime: '2025-11-02T01:30:00.000-05:00' },
  ];
  const sorted = parseIv(skeleton(dst)).points;
  ok('the repeated daylight-saving hour comes back in absolute-time order, not string order',
     sorted.map((p) => p.cfs).join(',') === '10,11,12,13' && latest(sorted).cfs === 13,
     sorted.map((p) => p.cfs).join(','));
  let monotoneTime = true;
  for (let i = 1; i < sorted.length; i++) if (Date.parse(sorted[i].at) < Date.parse(sorted[i - 1].at)) monotoneTime = false;
  ok('so no inter-sample gap is negative, which is how the bug was found in the real record', monotoneTime);
}

head('the differential control on the FIT: a planted peak must enter the array the fit iterates');
{
  const planted = 9000;
  const before = fit(CLOSED_VALUES);
  const after = fit(CLOSED_VALUES.concat([planted]));   // the DATA is doctored, not the result
  ok('n goes up by exactly one', after.n === before.n + 1);
  // Recomputed here from first principles rather than by calling the module again.
  const logs = CLOSED_VALUES.concat([planted]).map((v) => Math.log10(v));
  const mean = logs.reduce((s, v) => s + v, 0) / logs.length;
  ok('the mean of the logs is the mean of the logs including the planted value',
     near(after.mean, mean, 1e-12), after.mean.toFixed(9));
  ok('a 9,000 ft3/s year raises the hundred-year flood, as it must, being far above the break-even',
     after.q[3].value > before.q[3].value, `${before.q[3].value.toFixed(0)} to ${after.q[3].value.toFixed(0)}`);
  ok('a 2,000 ft3/s year LOWERS it, which is the counterintuitive half and is also arithmetic',
     q1pct(CLOSED_VALUES.concat([2000])) < before.q[3].value,
     `${q1pct(CLOSED_VALUES.concat([2000])).toFixed(1)}`);
}

// ════════════════════════════════════════════════════════════════════════════════════
// 7. HTTP 200 IS NOT FRESHNESS
// ════════════════════════════════════════════════════════════════════════════════════
head('the freshness test, and the fixtures built to break it');
{
  const mk = (isoList) => isoList.map((at, i) => ({ cfs: 10 + i, at, qual: 'P' }));
  const now = Date.parse('2026-08-15T12:00:00.000Z');
  const shift = (h) => new Date(now - h * 3600e3).toISOString().replace('Z', '-00:00');

  ok('a payload whose newest reading is minutes old reads as current',
     freshness(mk([shift(3), shift(0.4)]), now).state === 'current');
  ok('a payload five hours old is FLAGGED but not refused, because this gauge routinely goes that quiet',
     freshness(mk([shift(9), shift(5)]), now).state === 'flag');
  ok('a payload 400 days old is REFUSED, however well-formed and however green the status code',
     freshness(mk([shift(24 * 401), shift(24 * 400)]), now).state === 'refuse');
  ok('an empty payload is refused rather than treated as a zero',
     freshness([], now).state === 'refuse');
  ok('an unparseable timestamp is refused rather than becoming NaN hours old',
     freshness([{ cfs: 1, at: 'not a date', qual: '' }], now).state === 'refuse');
  // The two thresholds are ORDERED here and JUSTIFIED below. What used to stand in this
  // place was `FRESHNESS_REFUSE_HOURS * 60 > OBSERVED_MAX_GAP_MINUTES`: two literals from the
  // same file compared against each other, which never touches the gauge and so cannot fail
  // however the gauge behaves. The real measurement is made against the live payload in "the
  // gap histogram" section below, and against every historical water year this run fetches.
  ok('the flag threshold sits below the refusal threshold', FRESHNESS_FLAG_HOURS < FRESHNESS_REFUSE_HOURS,
     `flag ${FRESHNESS_FLAG_HOURS} h, refuse ${FRESHNESS_REFUSE_HOURS} h`);

  // The refusal path the page takes when the worker itself fails.
  const dead = parseIv({ nope: true });
  ok('a body that is not WaterML is refused by the parser rather than yielding an empty record',
     dead.ok === false && dead.points.length === 0);
}

// ════════════════════════════════════════════════════════════════════════════════════
// 8. THE OPEN WATER YEAR AND THE FORWARD CLAIM
// ════════════════════════════════════════════════════════════════════════════════════
const CLAIM = {
  stated: '2026-08-15',
  closes: '2026-09-30',
  breakEven: breakEvenPeak(CLOSED_VALUES),
  // The threshold the PAGE prints, not a rounded neighbour of it. This was 5,120, a figure
  // inherited from the blocked api.waterdata route that no fit on the page uses, and a
  // WY2026 peak landing between 5,119.40 and 5,120.00 would have been scored "held" here
  // while failing the claim as the page words it. Take it from the same function the page
  // takes it from.
  ceiling1pct: q1pct(CLOSED_VALUES),
  part1: 'water year 2026 annual peak, taken as the maximum of the 15-minute discharge record, below the break-even',
  part2: `the 1 percent AEP recomputed on water years 1947 to 2026 below ${q1pct(CLOSED_VALUES).toFixed(2)} ft3/s, the value the page prints`,
};
let claimState = { status: 'not_scoreable', reason: 'offline' };

if (!OFFLINE) {
  head('the open water year, read the way the page reads it');
  const r = await iv(IV_PERIOD(GAUGE.site, 365));
  ok('waterservices.usgs.gov answered', r.ok, `HTTP ${r.status}, ${r.bytes} bytes`);
  if (r.ok) {
    const p = parseIv(r.json);
    ok('the payload parses to a usable discharge series', p.ok && p.points.length > 1000, `${p.points.length} readings`);
    fresh = freshness(p.points, Date.now());
    ok('the newest reading inside the data is not stale',
       fresh.state !== 'refuse', `${fresh.newest}, ${fresh.ageHours.toFixed(2)} h old, state ${fresh.state}`);
    // ── the gap histogram, which is what actually justifies flag-at-3 and refuse-at-24 ──
    const g = gapStats(p.points, openWaterYearFromData(p.points));
    console.log(`       WY${g.wy}: ${g.intervals} intervals, largest gap ${g.maxGapMinutes} min` +
                ` after ${g.maxGapAfter}, ${g.eightHourGaps} eight-hour gaps,` +
                ` ${(100 * g.blankedByThreeHourRule).toFixed(2)}% of the span past the 3 h flag`);
    ok('the largest gap in the CURRENT water year is shorter than the refusal threshold, so the page does not refuse on healthy data',
       g.maxGapMinutes < FRESHNESS_REFUSE_HOURS * 60,
       `${g.maxGapMinutes} min against ${FRESHNESS_REFUSE_HOURS * 60} min`);
    ok('OBSERVED_MAX_GAP_MINUTES is still the measured maximum of this water year, not a stale literal',
       g.maxGapMinutes === OBSERVED_MAX_GAP_MINUTES,
       `measured ${g.maxGapMinutes}, shipped ${OBSERVED_MAX_GAP_MINUTES}`);
    ok('a three-hour refusal really would have blanked a large fraction of the year, which is why there are two thresholds',
       g.blankedByThreeHourRule > 0.05,
       `${(100 * g.blankedByThreeHourRule).toFixed(2)}% of the water year so far`);
    ok('the flag threshold is shorter than the routine gaps it exists to announce',
       FRESHNESS_FLAG_HOURS * 60 < g.maxGapMinutes && g.eightHourGaps > 20,
       `${g.eightHourGaps} gaps of exactly 8 hours`);
    gapReport = g;

    live = latest(p.points);
    openYear = openWaterYearFromData(p.points);
    ok("the open water year read off the data's own local timestamps is 2026", openYear === 2026, String(openYear));
    const max = annualMaximum(p.points, openYear);
    ok('water year 2026 has a running maximum in the window the page requests', !!max,
       max ? `${max.cfs} ft3/s at ${max.at}, qualifier ${max.qual}` : '');
    if (max) {
      const rk = rankAmong(max.cfs, CLOSED_VALUES);
      ok('its rank among the closed record is computed and printable', rk.rank >= 1 && rk.of === 80, `${rk.rank} of ${rk.of}`);
      ok('the running maximum is provisional, and the page says so', /P/.test(max.qual), max.qual);

      // instantaneous versus daily mean, from the same 15-minute data
      const day = max.at.slice(0, 10);
      const same = p.points.filter((q) => q.at.slice(0, 10) === day).map((q) => q.cfs);
      const mean = same.reduce((s, v) => s + v, 0) / same.length;
      ok('the daily mean of the peak day understates the instantaneous peak by more than 10 percent',
         (max.cfs - mean) / max.cfs > 0.1,
         `instantaneous ${max.cfs}, mean of ${same.length} readings ${mean.toFixed(0)}, ${(100 * (max.cfs - mean) / max.cfs).toFixed(0)}% lower`);

      // scoring
      const closed = Date.now() > Date.parse(CLAIM.closes + 'T23:59:59-04:00');
      if (!closed) {
        claimState = {
          status: 'pending', closes: CLAIM.closes, peak_to_date: max.cfs, peak_at: max.at,
          break_even: CLAIM.breakEven, would_be_1pct: q1pct(CLOSED_VALUES.concat([max.cfs])),
          on_track: max.cfs < CLAIM.breakEven,
        };
        ok('the claim is not scoreable yet, and the record says pending rather than passing',
           claimState.status === 'pending', `peak to date ${max.cfs} against a break-even of ${CLAIM.breakEven.toFixed(0)}`);
      } else {
        const withIt = q1pct(CLOSED_VALUES.concat([max.cfs]));
        const p1 = max.cfs < CLAIM.breakEven;
        const p2 = withIt < CLAIM.ceiling1pct;
        claimState = {
          status: p1 && p2 ? 'held' : 'failed', part1_held: p1, part2_held: p2,
          final_peak: max.cfs, final_peak_at: max.at, recomputed_1pct: withIt, break_even: CLAIM.breakEven,
        };
        console.log(`       CLAIM ${claimState.status.toUpperCase()}: peak ${max.cfs}, recomputed 1% AEP ${withIt.toFixed(1)}`);
        ok('the claim has been scored and the outcome recorded either way', true, claimState.status);
      }
    }
  } else {
    claimState = { status: 'not_scoreable', reason: `waterservices returned HTTP ${r.status}` };
  }
}

if (upstream.reachable === false) {
  head('REPORTABLE EVENT');
  console.log('       waterservices.usgs.gov did not answer. USGS permits intentional degradation of this');
  console.log('       service from August 2026 and decommissions it in Q1 2027, and its replacement is the');
  console.log('       one path this project will not fetch. This is recorded as an event, not swallowed.');
}

// ════════════════════════════════════════════════════════════════════════════════════
// 9. THE RECORD EDITING ITSELF
// ════════════════════════════════════════════════════════════════════════════════════
head('the two rows that changed under the book');
{
  const swapped = CLOSED_PEAKS.map((r) => {
    const e = RECORD_EDITS.rows.find((x) => x.wy === r.wy);
    return e ? e.served : r.cfs;
  });
  const alt = q1pct(swapped);
  ok('substituting the served values moves the hundred-year flood by about 1 ft3/s',
     near(alt - B.q[3].value, 0.8, 0.6), `${B.q[3].value.toFixed(2)} to ${alt.toFixed(2)}`);
  ok('the shipped fit uses the BOOK values, so nothing on the page depends on the disallowed route',
     B.q[3].value !== alt && CLOSED_PEAKS.find((r) => r.wy === 1995).cfs === 4536);
  ok('the recorded observation is dated and names the route it came from',
     RECORD_EDITS.observedAt === '2026-08-15' && /ogcapi/.test(RECORD_EDITS.route) && /disallowed/.test(RECORD_EDITS.routeStatus));
}

// ════════════════════════════════════════════════════════════════════════════════════
// 10. THE RECORD FILE
// ════════════════════════════════════════════════════════════════════════════════════
const seriesHash = createHash('sha256')
  .update(CLOSED_PEAKS.map((r) => `${r.wy}:${r.cfs}`).join(','))
  .digest('hex');

const row = {
  run: new Date().toISOString(),
  checks: { passed, failed, skipped, failures },
  upstream: {
    host: GAUGE.upstreamHost,
    // First-class, not an error path: this service is being decommissioned in Q1 2027 and
    // its replacement is disallowed. The day it stops answering is the thing to have on file.
    answered: upstream.reachable,
    requests: upstream.requests,
    bytes: upstream.bytes,
    statuses: [...new Set(upstream.statuses)],
    decommission: GAUGE.decommission,
  },
  gaps: gapReport === null ? null : {
    open_year: gapReport,
    historical_worst: historicalGaps.length
      ? historicalGaps.slice().sort((a, b) => b.maxGapMinutes - a.maxGapMinutes).slice(0, 5)
        .map((g) => ({ wy: g.wy, max_gap_minutes: g.maxGapMinutes, after: g.maxGapAfter, gaps_over_a_day: g.gapsOverADay }))
      : null,
    years_measured: historicalGaps.length,
    years_with_a_gap_over_a_day: historicalGaps.filter((g) => g.gapsOverADay > 0).length,
  },
  record: {
    n: CLOSED_PEAKS.length,
    span: `${CLOSED_PEAKS[0].wy}-${CLOSED_PEAKS[CLOSED_PEAKS.length - 1].wy}`,
    sha256: seriesHash,
    overlap_control: overlapHits === null ? null : `${overlapHits}/${OVERLAP_CONTROL.length}`,
    derived_reverified: derivedHits === null ? null : `${derivedHits}/${DERIVED_PEAKS.length}`,
  },
  anchor: {
    published_1pct: PUBLISHED_105[3].ema,
    ours_1pct: Number(A.q[3].value.toFixed(4)),
    hits: `${anchorHits}/6`,
    worst_pct: Number((anchorWorst * 100).toFixed(5)),
    moments: { mean: Number(A.mean.toFixed(6)), sd: Number(A.sd.toFixed(6)), skew: Number(A.skew.toFixed(6)) },
  },
  fit: {
    moments: { mean: Number(B.mean.toFixed(6)), sd: Number(B.sd.toFixed(6)), skew: Number(B.skew.toFixed(6)) },
    quantiles: Object.fromEntries(AEPS.map((p, i) => [String(p), Number(B.q[i].value.toFixed(2))])),
    lower_bound: Number(B.lowerBound.toFixed(2)),
    break_even_crossings: CROSS.crossings.map((v) => Number(v.toFixed(2))),
  },
  open_year: openYear === null ? null : {
    wy: openYear,
    running_max: claimState.peak_to_date ?? claimState.final_peak ?? null,
    running_max_at: claimState.peak_at ?? claimState.final_peak_at ?? null,
    provisional: true,
  },
  live: live === null ? null : {
    discharge_cfs: live.cfs, at: live.at, qualifier: live.qual,
    newest_age_hours: fresh ? Number(fresh.ageHours.toFixed(3)) : null,
    freshness_state: fresh ? fresh.state : null,
    upstream_sends_last_modified: false,
  },
  claim: claimState,
};

if (!NO_RECORD) {
  const path = join(HERE, 'record.jsonl');
  if (!existsSync(HERE)) mkdirSync(HERE, { recursive: true });
  appendFileSync(path, JSON.stringify(row) + '\n');
  console.log(`\nappended one line to ${path}`);
} else {
  console.log('\n--no-record: not appending');
}

console.log(`\n${failed === 0 ? 'ALL CHECKS PASSED' : failed + ' CHECK(S) FAILED'}   ${passed} passed, ${failed} failed, ${skipped} skipped\n`);
process.exit(failed === 0 ? 0 : 1);
