#!/usr/bin/env node
/* verify-five-days-wide.mjs
 *
 *   node research/five-days-wide/verify-five-days-wide.mjs
 *   ... --live      also fetch tonight's series and score the forward claim against it
 *   ... --record    append this run to research/five-days-wide/record.jsonl
 *                   (and mirror it to public/strata/five-days-wide/data/ledger.jsonl,
 *                    which is the copy the page reads)
 *
 * Every number the page prints is recomputed here out of the SAME module the page
 * imports, public/strata/five-days-wide/icecore.js. There is no second implementation of
 * the trailing mean anywhere in this repository, so this file cannot accidentally agree
 * with the page by both being wrong in different ways; it can only agree with it by both
 * being wrong in the same way. The defence against that is that the anchors are external:
 * four quantities NSIDC printed, on fixed dates, that our arithmetic has to land on.
 *
 * The five things this file is really for:
 *
 *   1. THE ANCHOR. NSIDC's published record minimum (3.39 on 2012-09-17) and 2025 minimum
 *      (4.60 on 2025-09-10) must both fall out of OUR five-day trailing mean computed from
 *      the primitive unsmoothed dailies, on the printed digits and the printed dates. So
 *      must the September monthly extent and area for 2025 and 2012. If any of those stops
 *      landing, the page's instrument has changed and the page must say so, not tune.
 *
 *   2. THE SENTINEL, WITH A REAL DIFFERENTIAL CONTROL. NSIDC's smoothing_window=0 endpoint
 *      returns -1.0 for a missing day. A -1.0 is planted INTO THE DATA of a year that has
 *      none, and the same unmodified analyseYear() that would report a real minimum has to
 *      refuse to report it, while the naive path has to find it. Both directions are
 *      asserted, because a guard that is never shown catching anything has not been tested.
 *
 *   3. RULE 3b: HTTP 200 IS NOT FRESHNESS. The newest row INSIDE the data is compared to
 *      the clock, and the assertion has a negative control: a deliberately stale fixture,
 *      a future-dated fixture and an empty fixture must each be refused.
 *
 *   4. THE REFUSAL PATHS. Feed down, all-sentinel year, unparseable body, vacuous window.
 *      A run that only exercises the success path has tested the half that never fails.
 *
 *   5. THE RECORD. One append-only line per run, so a returning reader can catch tonight's
 *      number having been different, and can catch NSIDC silently revising a past day.
 */

import { readFileSync, existsSync, appendFileSync, writeFileSync, mkdirSync } from 'node:fs';
import { execFileSync } from 'node:child_process';
import { dirname, join } 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', 'five-days-wide');
const HARVEST = join(HERE, 'snapshot', 'nsidc-harvest.json');
const HISTORY = join(PAGE, 'data', 'history.json');
const RECORD = join(HERE, 'record.jsonl');
const LEDGER = join(PAGE, 'data', 'ledger.jsonl');

const ice = await import(join(PAGE, 'icecore.js'));

const LIVE = process.argv.includes('--live');
const DO_RECORD = process.argv.includes('--record');
const FEED_BASE = process.env.AW_FEED_BASE || 'https://artwaste.land';
const UPSTREAM = 'https://nsidc.org/api/seaiceservice';

let checks = 0, fails = 0, warns = 0;
const ok = (name, cond, extra = '') => {
  checks++; if (!cond) fails++;
  console.log(`${cond ? '  ok  ' : 'FAIL  '}${name}${extra ? '   ' + extra : ''}`);
};
/* A WARNING is for a fact about our own deployment rather than about the page's
 * arithmetic: the reader-facing worker route not serving does not make a single number
 * on this page wrong, and it must not be silently swallowed either. So it prints loudly,
 * it goes into the ledger line where a stranger can see it, and it does not fail the run.
 * Set AW_EXPECT_WORKER=1 once the allowlist entry in FEED-REQUEST.md has been applied and
 * deployed, and it becomes a hard check like any other. */
const EXPECT_WORKER = process.env.AW_EXPECT_WORKER === '1';
const warn = (name, cond, extra = '') => {
  if (EXPECT_WORKER) return ok(name, cond, extra);
  if (!cond) warns++;
  console.log(`${cond ? '  ok  ' : 'WARN  '}${name}${extra ? '   ' + extra : ''}`);
  return cond;
};
const near = (a, b, eps) => Number.isFinite(a) && Number.isFinite(b) && Math.abs(a - b) <= eps;
const f3 = (x) => (Number.isFinite(x) ? x.toFixed(3) : 'n/a');
const f4 = (x) => (Number.isFinite(x) ? x.toFixed(4) : 'n/a');

const harvest = JSON.parse(readFileSync(HARVEST, 'utf8'));
/** The seasons the forward claim is fitted on, read from the committed snapshot. */
const fcYears = () => (JSON.parse(readFileSync(HISTORY, 'utf8')).forward || {}).fit_years || [];
const history = JSON.parse(readFileSync(HISTORY, 'utf8'));
const rec = (url) => harvest.records[url];
const snap = (url) => { const r = rec(url); return r && r.status === 200 ? r.data : null; };
const rawUrl = (k, h, y) => `${UPSTREAM}/${k}/${h}/data/${y}?index=date`;
const smUrl = (k, h, y, w) => `${UPSTREAM}/${k}/${h}/filled_averaged_data/${y}?index=date&smoothing_window=${w}`;

/* ══ A. the files the page is made of ═══════════════════════════════════════ */
console.log('\n== A. the shipped files ==');
{
  for (const f of ['icecore.js', 'page.js']) {
    let good = true, err = '';
    try { execFileSync(process.execPath, ['--check', join(PAGE, f)], { stdio: 'pipe' }); }
    catch (e) { good = false; err = String(e.stderr || e).slice(0, 160); }
    ok(`A1 ${f} parses`, good, err);
  }
  const html = readFileSync(join(PAGE, 'index.html'), 'utf8');
  ok('A2 index.html closes its body and html', /<\/body>\s*<\/html>/.test(html));
  ok('A2 index.html loads page.js as a module', /<script type="module" src="\.\/page\.js"><\/script>/.test(html));
  const ld = html.match(/<script type="application\/ld\+json">([\s\S]*?)<\/script>/);
  let ldOk = false, ldErr = '';
  try { const o = JSON.parse(ld[1]); ldOk = o['@type'] === 'Article' && o.url.endsWith('/strata/five-days-wide/'); }
  catch (e) { ldErr = String(e).slice(0, 120); }
  ok('A3 the JSON-LD block is valid JSON and points at this page', ldOk, ldErr);

  // rule 4 of the build brief: no em dashes in our own prose. The house publish gate
  // blocks on it, so catching it here is cheaper than catching it at the land.
  const files = ['index.html', 'page.js', 'icecore.js'].map((f) => [f, readFileSync(join(PAGE, f), 'utf8')]);
  files.push(['five-days-wide.md', readFileSync(join(ROOT, 'src', 'content', 'strata', 'five-days-wide.md'), 'utf8')]);
  for (const [name, text] of files) {
    const n = (text.match(/\u2014/g) || []).length;
    ok(`A4 ${name} contains no em dash`, n === 0, n ? `${n} found` : '');
  }
  ok('A5 no page code names the disallowed host', !files.some(([, t]) => t.includes('noaadata.apps.nsidc.org') && !t.includes('Disallow')));

  /* A6 THE CHECK THAT WAS MISSING, and the reason this page shipped wrong.
   *
   * The page asked the worker for `series=data` and for smoothing windows 10, 15, 21 and 31.
   * worker.js had no `series` parameter and its smoothing_window enum stopped at 7. The
   * worker DROPS an unknown parameter and SUBSTITUTES the default for an out-of-enum value,
   * both silently, so every one of those requests came back HTTP 200 with a well-formed body
   * that was the wrong series. The page rendered NSIDC's five-day smoothed series under the
   * label "the lowest single day actually observed", its flagship result evaluated to 0 of 47
   * instead of 16, and the whole verifier stayed green because nothing here compared the two
   * files. Every check in section I is live-only and this failure did not need the network to
   * be visible: it is two literals in two files that have to agree.
   *
   * So this reads the actual FEEDS table out of worker.js and the actual constants out of
   * page.js and asserts they line up. It runs in the default offline run.
   */
  const workerSrc = readFileSync(join(ROOT, 'worker.js'), 'utf8');
  const entry = workerSrc.slice(workerSrc.indexOf('"nsidc-seaice": {'));
  const spec = entry.slice(0, entry.indexOf('\n  },') + 5);
  ok('A6 worker.js has an nsidc-seaice allowlist entry at all', spec.includes('build:') && spec.length > 200, `${spec.length} chars`);

  const pageSrc = readFileSync(join(PAGE, 'page.js'), 'utf8');
  const asked = [...pageSrc.matchAll(/^\s*\?\s*\{([^}]*)\}\s*$|feedParams\([\s\S]*?return[\s\S]*?;/gm)];
  // the params page.js actually puts on the wire, read from feedParams' two return branches
  const fp = pageSrc.slice(pageSrc.indexOf('function feedParams('));
  const fpBody = fp.slice(0, fp.indexOf('\n}\n'));
  const pageParams = [...new Set([...fpBody.matchAll(/\b(kind|hemisphere|year|series|smoothing_window|index)\b\s*[:,}]/g)].map((m) => m[1]))];
  const missing = pageParams.filter((p) => !new RegExp(`\\n\\s*${p}:\\s*\\{`).test(spec));
  ok('A6 every parameter page.js sends is one worker.js will forward rather than silently drop',
    missing.length === 0, missing.length ? `worker.js has no rule for: ${missing.join(', ')}` : `${pageParams.join(', ')}`);

  const enumOf = (name) => {
    const m = spec.match(new RegExp(`${name}:\\s*\\{[^}]*values:\\s*\\[([^\\]]*)\\]`));
    return m ? m[1].split(',').map((s) => s.trim().replace(/^"|"$/g, '')).filter(Boolean) : null;
  };
  const wWindows = enumOf('smoothing_window');
  const pWindows = (pageSrc.match(/const WINDOWS = \[([^\]]*)\]/) || [, ''])[1]
    .split(',').map((s) => s.trim()).filter(Boolean);
  const unreachable = pWindows.filter((w) => !wWindows || !wWindows.includes(w));
  ok('A6 every smoothing window the page offers as a button is one the worker will actually pass through',
    unreachable.length === 0,
    unreachable.length
      ? `the page offers ${unreachable.join(', ')} and the worker would silently serve its default instead, labelling a window-${(enumOf('smoothing_window') || []).length ? spec.match(/smoothing_window:[\s\S]*?def:\s*"(\d+)"/)[1] : '?'} number as those`
      : `page ${pWindows.join(' ')} against worker ${wWindows.join(' ')}`);
  ok('A6 the worker still refuses smoothing_window=1, which returns HTTP 500 upstream',
    !!wWindows && !wWindows.includes('1'), wWindows ? wWindows.join(' ') : 'no enum found');
  const wSeries = enumOf('series');
  ok('A6 the worker can reach BOTH the primitive series and the derived one',
    !!wSeries && wSeries.includes('data') && wSeries.includes('filled_averaged_data'), wSeries ? wSeries.join(' ') : 'no series param');
  ok('A6 the worker builds /data/ for series=data rather than always building the smoothed path',
    /p\.series === "data"/.test(spec) && /\/data\/\$\{p\.year\}/.test(spec));

  /* A7 the page must not render a response it did not ask for. This is the runtime half of
   * A6, and it is what turns a substituted parameter into a refusal instead of a headline. */
  ok('A7 page.js compares the worker\'s echoed params and upstream URL against what it asked for',
    /function verifyServed\(/.test(pageSrc) && /feed\.upstream !== want/.test(pageSrc) && /const served = verifyServed\(/.test(pageSrc));
  ok('A7 ... and refuses rather than rendering on a mismatch',
    /if \(!served\.ok\)[\s\S]{0,400}return \{\s*\n?\s*ok: false/.test(pageSrc));
}

/* ══ B. the arithmetic, against truths that do not come from this repo ══════ */
console.log('\n== B. the arithmetic ==');
{
  // B1 a trailing mean of a straight line lags it by exactly (w-1)/2 steps.
  const line = [];
  for (let i = 0; i < 40; i++) line.push({ date: ice.addDays('2000-01-01', i), value: 10 - 0.1 * i, interpolated: false });
  const tm = ice.trailingMean(line, 5, false);
  const at20 = tm[20].value, true20 = line[20].value;
  ok('B1 a 5-day trailing mean of a falling straight line sits exactly 2 steps behind it',
    near(at20 - true20, 0.2, 1e-12), `lag ${f4(at20 - true20)} on a slope of 0.1 per day`);

  // B2 the first w-1 days get no value at all, because they have no window.
  ok('B2 the first 4 days of a 5-day trailing mean are null', tm.slice(0, 4).every((p) => p.value === null) && tm[4].value !== null);

  // B3 linear fill is exactly linear.
  const sparse = [{ date: '2000-01-01', value: 8 }, { date: '2000-01-05', value: 4 }];
  const filled = ice.fillDaily(sparse);
  ok('B3 fillDaily interpolates linearly and marks what it invented',
    filled.length === 5 && near(filled[2].value, 6, 1e-12) && filled[2].interpolated === true && filled[0].interpolated === false,
    filled.map((p) => p.value).join(','));

  // B4 window 0 or 1 is the identity.
  ok('B4 window 1 returns the series unchanged', ice.trailingMean(line, 1, false).every((p, i) => p.value === line[i].value));

  // B5 competition ranking with a genuine tie.
  const r = ice.rankAscending({ a: 1, b: 2, c: 2, d: 3 });
  ok('B5 tied values share a rank and the next rank skips', r.a === 1 && r.b === 2 && r.c === 2 && r.d === 4, JSON.stringify(r));

  // B6 dates, against arithmetic anyone can check.
  ok('B6 2012-09-16 is day 260 of a leap year', ice.dayOfYear('2012-09-16') === 260);
  ok('B6 there are 366 days from 2012-01-01 to 2013-01-01', ice.daysBetween('2012-01-01', '2013-01-01') === 366);
  ok('B6 day-of-year 256.4 in 2026 rounds to 13 September', ice.isoFromDoy(2026, 256.4) === '2026-09-13');
}

/* ══ C. THE ANCHOR: four published quantities, from the primitives ═════════ */
console.log('\n== C. the anchor: NSIDC in print, against our arithmetic on their dailies ==');
const A = {};
for (const y of [2007, 2012, 2025, 2026]) {
  const o = snap(rawUrl('extent', 'north', y));
  A[y] = o ? ice.analyseYear(o, { window: 5 }) : null;
  ok(`C0 the primitive daily extent series for ${y} is in the committed harvest`, !!(A[y] && A[y].ok));
}
{
  // C1 the record. NSIDC prose: "3.39 million square kilometers ... September 17, 2012".
  ok('C1 our five-day mean of the 2012 dailies bottoms out at the PUBLISHED 3.39',
    near(A[2012].smoothMin.value, 3.39, 0.005), `ours ${f4(A[2012].smoothMin.value)}`);
  ok('C1 ... on the PUBLISHED date, 2012-09-17', A[2012].smoothMin.date === '2012-09-17', A[2012].smoothMin.date);

  // C2 the 2025 minimum. NSIDC post of 2025-09-17: "4.60 ... September 10, 2025".
  ok('C2 our five-day mean of the 2025 dailies bottoms out at the PUBLISHED 4.60',
    near(A[2025].smoothMin.value, 4.60, 0.005), `ours ${f4(A[2025].smoothMin.value)}`);
  ok('C2 ... on the PUBLISHED date, 2025-09-10', A[2025].smoothMin.date === '2025-09-10', A[2025].smoothMin.date);

  // C3 the monthly anchors, a different KIND of published quantity out of the same code.
  const monthlyCases = [
    ['September 2025 monthly extent', 'extent', 2025, '2025-09', 4.747],
    ['September 2025 monthly area', 'area', 2025, '2025-09', 3.076],
    ['September 2012 monthly extent', 'extent', 2012, '2012-09', 3.566],
    ['September 2012 monthly area', 'area', 2012, '2012-09', 2.406],
  ];
  for (const [label, kind, year, ym, published] of monthlyCases) {
    const o = snap(rawUrl(kind, 'north', year));
    const m = o ? ice.monthlyMean(ice.cleanSeries(o).points, ym) : { ok: false };
    ok(`C3 ${label}: mean of the dailies reproduces NSIDC's published ${published}`,
      m.ok && near(m.value, published, 0.0006), m.ok ? `ours ${f4(m.value)} over ${m.have} days` : 'not in harvest');
    // and the monthly endpoint itself agrees with the number NSIDC printed
    const mo = snap(`${UPSTREAM}/monthly/${kind}/north/data/?start_date=${ym}-01&end_date=${ym}-30`);
    ok(`C3 ... and NSIDC's own monthly endpoint returns ${published}`, !!mo && near(Number(mo[ym]), published, 1e-9), mo ? String(mo[ym]) : 'not in harvest');
  }

  // C4 the raw minima, which are the numbers the page reports as "the lowest day".
  const rawCases = [[2012, 3.340, '2012-09-16'], [2025, 4.543, '2025-09-08'], [2007, 4.147, '2007-09-14']];
  for (const [y, v, d] of rawCases) {
    ok(`C4 ${y} lowest single day observed is ${v} on ${d}`,
      near(A[y].rawMin.value, v, 1e-9) && A[y].rawMin.date === d, `${f3(A[y].rawMin.value)} on ${A[y].rawMin.date}`);
  }

  // C5 our recomputed five-day series against NSIDC's own, day by day, both years.
  for (const y of [2012, 2025]) {
    const theirs = snap(smUrl('extent', 'north', y, 5));
    const ag = ice.agreement(A[y].smoothed, theirs);
    ok(`C5 ${y}: our recomputed five-day mean never differs from NSIDC's by more than 0.001 on any day`,
      ag.maxDiff <= 0.0011, `${ag.agree}/${ag.compared} identical at 3 dp, max ${f4(ag.maxDiff)} on ${ag.maxDiffDate}`);
    const theirMin = ice.minimumOf(ice.cleanSeries(theirs).points);
    ok(`C5 ${y}: our five-day MINIMUM equals NSIDC's own, value and date`,
      near(A[y].smoothMin.value, theirMin.value, 0.0006) && A[y].smoothMin.date === theirMin.date,
      `ours ${f4(A[y].smoothMin.value)} on ${A[y].smoothMin.date}, theirs ${f3(theirMin.value)} on ${theirMin.date}`);
  }

  // C6 the honest exception, asserted rather than smoothed over. 2007 is the one anchor year
  // where our recomputation and NSIDC's disagree at the third decimal. We assert the size of
  // the disagreement so it cannot quietly grow, and the page prints it.
  {
    const theirs = ice.minimumOf(ice.cleanSeries(snap(smUrl('extent', 'north', 2007, 5))).points);
    const gap = A[2007].smoothMin.value - theirs.value;
    ok('C6 2007 is the known third-decimal disagreement, same date, and it is not larger than that',
      A[2007].smoothMin.date === theirs.date && Math.abs(gap) <= 0.0011,
      `ours ${f4(A[2007].smoothMin.value)}, NSIDC ${f3(theirs.value)}, gap ${f4(gap)} on ${theirs.date}`);

    /* C6b THE STATED CAUSE, TESTED INSTEAD OF ASSUMED.
     *
     * The page attributed those disagreements to NSIDC rounding each daily value to three
     * decimals before averaging, and asserted only that the page CONTAINED that sentence,
     * which is a check on our own prose rather than on the world. The claim was false: every
     * published value already carries at most three decimals, so the rounding step named as
     * "the entire source" of the disagreement does nothing at all. This measures it, in both
     * directions, and it is a real negative control on the explanation. If NSIDC ever starts
     * publishing a fourth decimal, this fails and the page's new wording has to be revisited
     * rather than quietly becoming true again for a different reason.
     */
    for (const y of [2007, 2012, 2025]) {
      const o = snap(rawUrl('extent', 'north', y));
      const probe = ice.isRound3Inert(o);
      const withR = ice.analyseYear(o, { window: 5, round3: true });
      const without = ice.analyseYear(o, { window: 5, round3: false });
      let changed = 0;
      for (let i = 0; i < withR.smoothed.length; i++) if (withR.smoothed[i].value !== without.smoothed[i].value) changed++;
      ok(`C6b ${y}: rounding to three decimals changes NOTHING, so it cannot be the cause of the disagreement`,
        probe.inert && changed === 0 && withR.smoothMin.value === without.smoothMin.value,
        `${probe.over} of ${probe.total} published values carry a 4th decimal; toggling round3 changes ${changed} of ${withR.smoothed.length} days`);
    }
    // and the disagreement runs BOTH ways, which is not what a missing rounding step looks like
    {
      const theirsObj = snap(smUrl('extent', 'north', 2012, 5));
      const map = new Map(Object.entries(theirsObj).map(([d, v]) => [d, Number(v)]));
      let hi = 0, lo = 0;
      for (const p of A[2012].smoothed) {
        if (p.value === null) continue;
        const t = map.get(p.date);
        if (!Number.isFinite(t) || t <= 0) continue;
        const a = Math.round(p.value * 1000) / 1000, b = Math.round(t * 1000) / 1000;
        if (a > b) hi++; else if (a < b) lo++;
      }
      ok('C6b the residual disagreement runs in BOTH directions, so it is not a rounding step we are missing',
        hi > 0 && lo > 0, `2012: ${hi} days ours-high, ${lo} days ours-low`);
    }
    ok('C6b the page states the measured fact rather than the assumed cause',
      (() => {
        const h = readFileSync(join(PAGE, 'index.html'), 'utf8');
        return h.includes('cannot tell you why') &&
          h.includes('rounding them is arithmetically a no-op') &&
          !h.includes('That is the entire source of the 0.001 disagreements');
      })());
  }

  /* C7 WHAT OUR GAP FILL COSTS, and the rule that keeps it out of every reported number.
   *
   * icecore.js claimed linear interpolation was "what reproducing their published series
   * requires". It is not what NSIDC does: the v4 user guide gives a one-sided backfill that
   * averages days BEFORE the gap and refuses past three missing days. In the every-other-day
   * SMMR years our recomputation is therefore not their series, and the page had disclosed
   * only the flattering half of that ("for 1988 onwards this makes no difference at all").
   * These two checks pin both halves: the divergence is real and bounded, and no figure the
   * page reports is exposed to it.
   */
  {
    const gapYears = [], cleanYears = [];
    for (let y = 1979; y <= 2025; y++) {
      const o = snap(rawUrl('extent', 'north', y)), t = snap(smUrl('extent', 'north', y, 5));
      if (!o || !t) continue;
      const a = ice.analyseYear(o, { window: 5 });
      if (!a.ok) continue;
      const ag = ice.agreement(a.smoothed, t);
      (a.interpolated > 0 ? gapYears : cleanYears).push({ y, interp: a.interpolated, ag, min: a.smoothMin, theirs: ice.minimumOf(ice.cleanSeries(t).points) });
    }
    const worstClean = cleanYears.slice().sort((x, z) => z.ag.maxDiff - x.ag.maxDiff)[0];
    const worstGap = gapYears.slice().sort((x, z) => z.ag.maxDiff - x.ag.maxDiff)[0];
    ok('C7 in gap-free years our five-day mean tracks NSIDC\'s to under 0.001 on every single day',
      cleanYears.length >= 38 && worstClean.ag.maxDiff <= 0.0011,
      `${cleanYears.length} years, worst ${worstClean.y} at ${f4(worstClean.ag.maxDiff)}`);
    ok('C7 NEGATIVE CONTROL: in the gap years it does NOT, and the page says so instead of averaging it away',
      gapYears.length === 9 && worstGap.ag.maxDiff > 0.02,
      `${gapYears.length} gap years, worst ${worstGap.y} at ${f4(worstGap.ag.maxDiff)}, agreeing on only ${worstGap.ag.agree} of ${worstGap.ag.compared} days`);
    const wrongDate = gapYears.filter((g) => g.min.date !== g.theirs.date).map((g) => g.y);
    ok('C7 ... including putting the annual minimum on a different DATE in exactly these years',
      wrongDate.join(',') === '1981,1983,1985', wrongDate.join(',') || 'none');
    // THE RULE: nothing the page reports may rest on that. Every anchor, fit and live year is gap-free.
    const exposed = [2007, 2012, 2025, 2026, ...fcYears()].filter((y) => {
      const o = snap(rawUrl('extent', 'north', y));
      if (!o) return false;
      const a = ice.analyseYear(o, { window: 5 });
      return a.ok && a.interpolated > 0;
    });
    ok('C7 THE RULE: no year this page reports a recomputed mean for has a single interpolated day',
      exposed.length === 0, exposed.length ? `EXPOSED: ${exposed.join(', ')}` : 'anchors, fit years and the live season are all gap-free');
    ok('C7 icecore.js no longer claims linear interpolation is what reproducing NSIDC requires',
      (() => {
        const t = readFileSync(join(PAGE, 'icecore.js'), 'utf8');
        return !t.includes('which is what reproducing their published series requires') &&
          t.includes('It is not NSIDC\'s gap rule') && t.includes('the code will not compute an average');
      })());
  }
}

/* ══ D. THE FLAGSHIP: one parameter, sixteen years re-ranked ════════════════ */
console.log('\n== D. the flagship ==');
const D = (() => {
  const rawBy = {}, rawD = {}, smBy = {}, smD = {};
  for (let y = 1979; y <= 2025; y++) {
    const r = snap(rawUrl('extent', 'north', y)), s = snap(smUrl('extent', 'north', y, 5));
    if (!r || !s) continue;
    const ra = ice.analyseYear(r, { window: 5 });
    const sa = ice.analyseYear(s, { window: 1 });
    if (!ra.ok || !sa.ok) continue;
    rawBy[y] = ra.rawMin.value; rawD[y] = ra.rawMin.date;
    smBy[y] = sa.rawMin.value; smD[y] = sa.rawMin.date;
  }
  return { shift: ice.rankShift(rawBy, smBy, rawD, smD), rawBy, rawD, smBy, smD };
})();
{
  const s = D.shift;
  ok('D1 all 47 complete years, 1979 to 2025, are present', s.years === 47, `${s.years}`);
  ok('D2 exactly 16 of them change their all-time rank between the two settings',
    s.moved === 16, `${s.moved}: ${s.movedYears.join(' ')}`);
  const pr = ice.podium(D.rawBy, D.rawD, 12), ps = ice.podium(D.smBy, D.smD, 12);
  const at = (p, n) => (p.find((x) => x.rank === n) || {}).year;
  // The quantity ranked here is the ANNUAL DAILY MINIMUM. It is not "the third lowest
  // September", which is a different published series (the September monthly mean), and the
  // syndicated copy of this page said September. D3b is the control that keeps the two apart.
  ok('D3 third lowest ANNUAL MINIMUM is 2016 unsmoothed and 2007 smoothed',
    at(pr, 3) === 2016 && at(ps, 3) === 2007, `${at(pr, 3)} / ${at(ps, 3)}`);
  ok('D3 sixth is 2023 unsmoothed and 2024 smoothed', at(pr, 6) === 2023 && at(ps, 6) === 2024, `${at(pr, 6)} / ${at(ps, 6)}`);
  ok('D3 tenth is 2025 unsmoothed and 2008 smoothed', at(pr, 10) === 2025 && at(ps, 10) === 2008, `${at(pr, 10)} / ${at(ps, 10)}`);

  /* D3b NEGATIVE CONTROL ON THE WORDING. The September MONTHLY mean ranks differently, and
   * it has no smoothing_window at all, so on that series nothing this page is about happens:
   * 2007 is third under every setting and 2016 is seventh. Calling the finding "the third
   * lowest September" therefore states something false about a series NSIDC also publishes
   * and this page also fetches. Asserted here so the phrase cannot come back. */
  {
    const sept = [];
    for (let y = 1979; y <= 2025; y++) {
      const o = snap(rawUrl('extent', 'north', y));
      if (!o) continue;
      const m = ice.monthlyMean(ice.cleanSeries(o).points, `${y}-09`);
      if (m.ok) sept.push([y, m.value]);
    }
    sept.sort((a, b) => a[1] - b[1]);
    const rankOf = (y) => sept.findIndex((r) => r[0] === y) + 1;
    ok('D3b on the September MONTHLY series 2007 is third and 2016 is seventh, which is why this page never calls its finding "the third lowest September"',
      rankOf(2007) === 3 && rankOf(2016) === 7,
      `2007 is ${rankOf(2007)}, 2016 is ${rankOf(2016)}, over ${sept.length} complete Septembers`);
    const md = readFileSync(join(ROOT, 'src', 'content', 'strata', 'five-days-wide.md'), 'utf8');
    const html = readFileSync(join(PAGE, 'index.html'), 'utf8');
    ok('D3b neither the page nor its syndicated copy calls the ranked quantity a September',
      !/third[- ]lowest September/i.test(md) && !/third[- ]lowest September/i.test(html),
      /third[- ]lowest September/i.test(md) ? 'still in the .md' : 'clear');
  }

  /* D3c HOW BIG IS A FLIP? The page reported "sixteen of forty-seven change rank" in its
   * headline, its meta description, its og:description and its JSON-LD, and printed not one
   * of the gaps those flips rest on. A count without a magnitude is the cheapest way to make
   * a small effect sound large, and NSIDC's own user guide says single extent values have
   * "uncertain significance". So the magnitudes are now derived, printed and pinned here. */
  {
    const pairs = ice.discordantPairs(D.rawBy, D.smBy);
    const widest = pairs[0], narrowest = pairs[pairs.length - 1];
    ok('D3c the 16 moving years reduce to exactly 11 pairs of years swapping over',
      pairs.length === 11, `${pairs.length} discordant pairs`);
    ok('D3c NO rank flip in the whole record rests on more than 0.05 million km2',
      widest.rawGap < 0.05, `widest ${f4(widest.rawGap)} (${widest.lower} against ${widest.higher}); narrowest ${f4(narrowest.rawGap)}`);
    ok('D3c most of them rest on less than the width of a rounding step in the published values',
      pairs.filter((p) => p.rawGap <= 0.014).length >= 8,
      `${pairs.filter((p) => p.rawGap <= 0.014).length} of ${pairs.length} at or under 0.014`);
    ok('D3c the committed snapshot carries those gaps so the page can print them beside the count',
      Array.isArray(history.discordant) && history.discordant.length === pairs.length &&
      near(history.discordant[0].rawGap, widest.rawGap, 1e-12));
    ok('D3c the page prints them rather than only the count',
      readFileSync(join(PAGE, 'index.html'), 'utf8').includes('id="flip-size"') &&
      readFileSync(join(PAGE, 'page.js'), 'utf8').includes('the entire evidence the swap rests on'));
  }

  /* D3d DOES THE ORDERING "SETTLE DOWN" AT A WIDE WINDOW? The page asserted that it does,
   * in prose, as the causal story of its own vacuous-setting section, and nothing measured
   * it. It does not. Measured on the gap-free years (where our trailing mean IS NSIDC's to
   * 0.0008, so the sweep is about the window and not about our interpolation), the ordering
   * churns MORE per extra day of window at the wide end than at the narrow end. */
  {
    const sw = history.windowSweep;
    ok('D3d the committed snapshot carries a measured window sweep at all', !!sw && sw.rows.length >= 8, sw ? `${sw.years} years, ${sw.rows.length} windows` : 'absent');
    const at2 = (w) => sw.rows.find((r) => r.window === w);
    // recompute it here from the harvest rather than trusting the snapshot
    const sweepYears = [];
    for (let y = sw.from; y <= sw.to; y++) if (snap(rawUrl('extent', 'north', y))) sweepYears.push(y);
    const minsAt = (w) => {
      const by = {};
      for (const y of sweepYears) {
        const a = ice.analyseYear(snap(rawUrl('extent', 'north', y)), { window: Math.max(w, 1) });
        by[y] = (w <= 1 ? a.rawMin : ice.minimumOf(a.smoothed)).value;
      }
      return by;
    };
    const m0 = minsAt(0), m7 = minsAt(7), m15 = minsAt(15), m21 = minsAt(21), m31 = minsAt(31), m5 = minsAt(5);
    const churn5to7 = ice.rankChurn(m5, m7).changed;
    const churn15to21 = ice.rankChurn(m15, m21).changed;
    ok('D3d recomputed: the ordering is STABLE between windows 5 and 7',
      churn5to7 === 0 && churn5to7 === at2(7).rerankedVsPreviousWindow, `${churn5to7} years change rank`);
    ok('D3d recomputed: and it is NOT stable between 15 and 21, which is the opposite of settling down',
      churn15to21 >= 8 && churn15to21 === at2(21).rerankedVsPreviousWindow, `${churn15to21} years change rank`);
    ok('D3d the count of years displaced from the unsmoothed ordering GROWS with the window rather than shrinking',
      ice.rankChurn(m0, m31).changed > ice.rankChurn(m0, m5).changed,
      `w5 displaces ${ice.rankChurn(m0, m5).changed}, w15 ${ice.rankChurn(m0, m15).changed}, w31 ${ice.rankChurn(m0, m31).changed} of ${sweepYears.length}`);
    ok('D3d the false mechanism is gone from the page and the measurement is there instead',
      (() => {
        const h = readFileSync(join(PAGE, 'index.html'), 'utf8');
        return !h.includes('the ordering settles down') && h.includes('id="sweep-chart"') &&
          h.includes('A correction, kept in place of what it replaced');
      })());
  }
  ok('D4 the record year itself does NOT move: 2012 is first on both', at(pr, 1) === 2012 && at(ps, 1) === 2012);
  ok('D5 the smoothed minimum is never lower than the unsmoothed one, in any of the 47 years',
    s.rows.every((r) => r.smoothValue >= r.rawValue - 1e-9),
    `mean gap ${f4(s.meanValueGap)}, max ${f4(s.maxValueGap)}`);
  // D5b The obvious companion claim, that the smoothed minimum never falls EARLIER, is
  // FALSE, and the page says so rather than rounding it off. In a season with two nearly
  // equal troughs the five-day mean can settle on the first of them while the single
  // lowest day belongs to the second. It happens in 3 of the 47 years, and 1997 pulls the
  // two dates 20 days apart. This assertion pins the exceptions so they cannot grow
  // silently and cannot be quietly dropped.
  const earlier = s.rows.filter((r) => r.dateGap < 0).map((r) => r.year);
  ok('D5b the smoothed minimum CAN fall earlier, and does in exactly these 3 years',
    earlier.length === 3 && earlier.join(',') === '1989,1993,2002',
    `${earlier.join(' ')}; mean over all 47 is still ${s.meanDateGap.toFixed(2)} days later`);
  const widest = s.rows.slice().sort((a, b) => Math.abs(b.dateGap) - Math.abs(a.dateGap))[0];
  ok('D5b the widest disagreement between the two dates is 1997, 20 days',
    widest.year === 1997 && widest.dateGap === 20,
    `${widest.year}: ${widest.rawDate} unsmoothed against ${widest.smoothDate} smoothed`);
  ok('D5b the page states this exception rather than claiming the date always moves later',
    readFileSync(join(PAGE, 'index.html'), 'utf8').includes('id="date-exception"'));

  // D6 THE ASSERTION THE WHOLE PAGE HANGS ON. No reported minimum, on either series, in
  // any of the 47 years, may be below 1.0 million km2. If a sentinel ever reaches a
  // reported number this fails loudly instead of publishing -1.0 as a world record.
  const lowest = Math.min(...s.rows.map((r) => Math.min(r.rawValue, r.smoothValue)));
  ok('D6 no reported minimum in any year is below the 1.0 million km2 sentinel floor',
    lowest >= ice.MIN_PLAUSIBLE, `lowest reported anywhere: ${f3(lowest)} (2012)`);

  // D7 history.json, which is what the page actually renders, matches this derivation.
  ok('D7 the committed history.json the page renders agrees with this recomputation',
    history.shift.moved === s.moved &&
    history.shift.years === s.years &&
    history.shift.movedYears.join(',') === s.movedYears.join(','),
    `${history.shift.moved} of ${history.shift.years}`);
  ok('D7 ... including every value, to the third decimal',
    s.rows.every((r) => {
      const h = history.shift.rows.find((x) => x.year === r.year);
      return h && near(h.rawValue, r.rawValue, 1e-9) && near(h.smoothValue, r.smoothValue, 1e-9);
    }));
}

/* ══ E. THE SENTINEL, WITH THE PLANT ENTERING THE REAL DOMAIN ══════════════ */
console.log('\n== E. the missing-day sentinel, and the control on the guard ==');
{
  // E1 the real thing first. 1980's smoothing_window=0 response genuinely carries 183 of
  // them, because SMMR observed every other day.
  const o1980 = snap(smUrl('extent', 'north', 1980, 0));
  const c1980 = ice.cleanSeries(o1980);
  const naive1980 = ice.naiveMinimum(o1980);
  ok('E1 NSIDC really does return -1.0 for missing days at smoothing_window=0',
    c1980.sentinels === 183, `${c1980.sentinels} of ${Object.keys(o1980).length} keys in 1980`);
  ok('E1 a naive minimum over that response reports the record as -1.000',
    near(naive1980.value, -1.0, 1e-9), `naive says ${f3(naive1980.value)} on ${naive1980.date}`);
  ok('E1 the guard refuses that naive result', !ice.assertPlausible(naive1980).ok, ice.assertPlausible(naive1980).reason);
  const guarded1980 = ice.minimumOf(c1980.points);
  ok('E1 the guarded path reports a real Arctic minimum instead',
    guarded1980.value >= ice.MIN_PLAUSIBLE && guarded1980.value < 9, `${f3(guarded1980.value)} on ${guarded1980.date}`);

  // E2 THE PLANT. 2012's primitive series has no sentinels at all. Doctor the DATA, not
  // the code and not the result list, then run the SAME analyseYear the page runs on
  // every real year. The question that catches a fake control: does the planted object
  // get found by the same code that would report a real one? Here it does, because there
  // is only one code path and the plant is upstream of all of it.
  const real2012 = snap(rawUrl('extent', 'north', 2012));
  const doctored = { ...real2012 };
  for (const d of ['2012-09-15', '2012-09-16', '2012-09-17']) doctored[d] = ice.SENTINEL;

  const cleanRun = ice.analyseYear(real2012, { window: 5 });
  const plantedRun = ice.analyseYear(doctored, { window: 5 });     // same function, same options

  ok('E2 with nothing planted, 2012 reports the real record', cleanRun.ok && near(cleanRun.rawMin.value, 3.34, 1e-9));
  ok('E2 the plant is visible to the intake: three sentinels counted where the real year had none',
    cleanRun.sentinels === 0 && plantedRun.sentinels === 3, `${cleanRun.sentinels} then ${plantedRun.sentinels}`);
  ok('E2 the SAME analyseYear never reports the planted -1.0 as a minimum',
    plantedRun.ok && plantedRun.rawMin.value >= ice.MIN_PLAUSIBLE, `reported ${f3(plantedRun.rawMin.value)} on ${plantedRun.rawMin.date}`);
  ok('E2 and it reports the next real day instead of the doctored one',
    plantedRun.rawMin.date !== '2012-09-16' && plantedRun.rawMin.value > 3.34, `${f3(plantedRun.rawMin.value)} on ${plantedRun.rawMin.date}`);
  ok('E2 NEGATIVE CONTROL: the naive path, given the same doctored object, DOES report -1.000',
    near(ice.naiveMinimum(doctored).value, -1.0, 1e-9), `so the plant is findable, and the guard is what stopped it`);

  // E3 the refusal end of the same control: a year where every day is a sentinel must be
  // refused outright rather than reported as anything.
  const allSentinel = Object.fromEntries(Object.keys(real2012).map((d) => [d, ice.SENTINEL]));
  const refused = ice.analyseYear(allSentinel, { window: 5 });
  ok('E3 a year that is entirely sentinels is refused, not reported', !refused.ok && refused.error === 'empty', JSON.stringify(refused).slice(0, 90));

  // E4 the guard is not merely never triggered: hand it a value below the floor directly.
  ok('E4 assertPlausible rejects 0.9 and accepts 3.34',
    !ice.assertPlausible({ date: 'x', value: 0.9 }).ok && ice.assertPlausible({ date: 'x', value: 3.34 }).ok);
}

/* ══ F. RULE 3b: HTTP 200 IS NOT FRESHNESS ═════════════════════════════════ */
console.log('\n== F. freshness, checked inside the data, with negative controls ==');
{
  const nowIso = new Date().toISOString();
  const cur = A[2026];
  const newest = cur.points[cur.points.length - 1];
  const f = ice.freshness(newest.date, nowIso);
  ok('F1 the committed 2026 snapshot has a dated newest row', !!newest.date, `${newest.date} = ${f3(newest.value)}`);
  ok('F1 freshness is judged on that row, not on the status code or the header',
    ['fresh', 'stale', 'refuse'].includes(f.status), `${f.status}, ${f.lagDays} days behind ${nowIso.slice(0, 10)}`);

  // NEGATIVE CONTROLS. Each of these is a well-formed 200 response that a page trusting
  // the status code would render as tonight's number.
  const stale = ice.freshness('2026-06-01', '2026-08-15T00:00:00Z');
  ok('F2 NEGATIVE CONTROL: a well-formed series whose newest row is 75 days old is REFUSED',
    stale.status === 'refuse', `${stale.lagDays} days: ${stale.reason.slice(0, 70)}`);
  const warn = ice.freshness('2026-08-10', '2026-08-15T00:00:00Z');
  ok('F2 NEGATIVE CONTROL: five days behind is flagged stale rather than passed as fresh', warn.status === 'stale', `${warn.lagDays} days`);
  const future = ice.freshness('2027-01-01', '2026-08-15T00:00:00Z');
  ok('F2 NEGATIVE CONTROL: a future-dated newest row is refused', future.status === 'refuse');
  const none = ice.freshness(null, '2026-08-15T00:00:00Z');
  ok('F2 NEGATIVE CONTROL: no dated row at all is refused', none.status === 'refuse');
  const good = ice.freshness('2026-08-13', '2026-08-15T00:00:00Z');
  ok('F3 POSITIVE CONTROL: two days behind, which is NSIDC’s stated lag, passes', good.status === 'fresh', `${good.lagDays} days`);

  // F4 the sibling trap this wave found twice: a stale row hidden behind a fresh header.
  const r2026 = rec(rawUrl('extent', 'north', 2026));
  ok('F4 the header is recorded alongside the data so the two can be compared',
    Object.prototype.hasOwnProperty.call(r2026, 'last_modified'),
    r2026.last_modified ? `Last-Modified ${r2026.last_modified}` : 'the service sends no Last-Modified at all, which the page states rather than substituting its fetch time');
}

/* ══ G. the refusal paths ══════════════════════════════════════════════════ */
console.log('\n== G. the refusal paths ==');
{
  ok('G1 an unparseable body is refused', !ice.analyseYear('not json at all').ok);
  ok('G1 an array is refused rather than iterated as an object', !ice.analyseYear([1, 2, 3]).ok);
  ok('G1 an empty object is refused', !ice.analyseYear({}).ok);
  ok('G2 a series of nulls is refused', !ice.analyseYear({ '2012-09-16': null, '2012-09-17': null }).ok);
  ok('G3 keys that are not dates are dropped rather than parsed', ice.cleanSeries({ foo: 3.1, '2012-09-16': 3.34 }).points.length === 1);

  // G4 the vacuous setting. At a three-week window the minimum is dragged so far up that
  // the comparison the page is built on stops being about ice. This is asserted from real
  // fetched data, and the page has to be marking it as illustration rather than result.
  const w5 = ice.minimumOf(ice.cleanSeries(snap(smUrl('extent', 'north', 2012, 5))).points);
  const w31 = snap(smUrl('extent', 'north', 2012, 31));
  if (w31) {
    const m31 = ice.minimumOf(ice.cleanSeries(w31).points);
    ok('G4 at window 31 the 2012 minimum is dragged more than 0.15 above the published one',
      m31.value - w5.value > 0.15, `${f3(w5.value)} at window 5, ${f3(m31.value)} at window 31, ${ice.daysBetween(w5.date, m31.date)} days later`);
  } else {
    ok('G4 the wide-window evidence is in the harvest', false, 'window 31 was not fetched');
  }
  const js = readFileSync(join(PAGE, 'page.js'), 'utf8');
  ok('G4 the page marks only windows 0 and 5 as carrying published meaning',
    /PUBLISHED_MEANING\s*=\s*\{\s*\n\s*0:/.test(js) && /\n\s*5:/.test(js) && !/\n\s*10:\s*\[/.test(js));
  ok('G4 the page treats windows of 15 days and wider as illustration only', /VACUOUS_FROM\s*=\s*15/.test(js));
  ok('G5 the page never offers smoothing_window=1, which returns HTTP 500 upstream',
    /const WINDOWS = \[0, 2,/.test(js) && !/const WINDOWS = \[0, 1,/.test(js));
  const r500 = rec(smUrl('extent', 'north', 2012, 1));
  ok('G5 ... and that 500 is recorded rather than asserted', !!r500 && r500.status === 500, r500 ? `status ${r500.status}` : 'not probed');
}

/* ══ H. the forward claim ══════════════════════════════════════════════════ */
console.log('\n== H. the forward claim ==');
const fc = history.forward;
{
  const yrs = fc.fit_years;
  const hist = {};
  for (const y of yrs) {
    const o = snap(rawUrl('extent', 'north', y));
    if (o) hist[y] = ice.analyseYear(o, { window: 5 });
  }
  const rows = ice.ratioClimatology(hist, '08-13', yrs);
  const sum = ice.summariseRatios(rows);
  const anchor = ice.cleanSeries(snap(rawUrl('extent', 'north', 2026))).points.find((p) => p.date === '2026-08-13');
  const proj = ice.projectMinimum(anchor.value, 2026, sum);

  ok('H1 the anchor value the claim is built on is the one NSIDC served', near(anchor.value, fc.anchor_value, 1e-9), `${f3(anchor.value)} on 2026-08-13`);
  ok('H2 the claim re-derives from the harvest to the committed figure',
    near(proj.value, fc.raw.projection.value, 1e-9) && proj.date === fc.raw.projection.date,
    `${f3(proj.value)} on ${proj.date}, interval ${f3(proj.lo)} to ${f3(proj.hi)}`);
  ok('H3 it was fitted on 15 seasons and its spread is not degenerate',
    sum.n === 15 && sum.ratioSd > 0.01 && sum.doySd > 1, `ratio ${f4(sum.ratioMean)} sd ${f4(sum.ratioSd)}, doy ${sum.doyMean.toFixed(1)} sd ${sum.doySd.toFixed(1)}`);
  ok('H4 the stated hazard is true: 2025, the only complete AMSR2 year, sits in the top third of the fitted ratios',
    (() => { const r25 = rows.find((r) => r.year === 2025); const above = rows.filter((r) => r.ratio > r25.ratio).length; return r25 && above <= 5; })(),
    `2025 ratio ${f4((rows.find((r) => r.year === 2025) || {}).ratio)} against a mean of ${f4(sum.ratioMean)}`);
  ok('H5 the five-day version of the claim runs higher and later than the unsmoothed one, as the page says it must',
    fc.five_day.projection.value > fc.raw.projection.value && fc.five_day.projection.date > fc.raw.projection.date,
    `${f3(fc.five_day.projection.value)} on ${fc.five_day.projection.date} against ${f3(fc.raw.projection.value)} on ${fc.raw.projection.date}`);

  const scored = ice.scoreClaim(fc.raw.projection, { ...A[2026].rawMin, last: A[2026].last }, '2026-09-30');
  ok('H6 the claim is scored on every run and reports honestly that it is still open',
    scored.status === 'open', `${scored.note}; running lowest ${f3(scored.runningMin)} on ${scored.runningDate}`);
  ok('H7 a settled season would be scored rather than left open',
    ice.scoreClaim(fc.raw.projection, { date: '2026-09-14', value: 4.40, last: '2026-10-15' }, '2026-09-30').status === 'held' &&
    ice.scoreClaim(fc.raw.projection, { date: '2026-09-14', value: 3.10, last: '2026-10-15' }, '2026-09-30').status === 'failed');

  /* H8 THE SECONDARY CLAIM, which the page prints as scoreable and nothing checked. H1 to H7
   * covered the Arctic minimum only; the Antarctic maximum appeared in the verifier exactly
   * once, inside the construction of the ledger line. A published claim with no assertion
   * behind it is a claim nobody has read. */
  const so = fc.south;
  {
    const rows = [];
    for (const y of fc.fit_years) {
      const o = snap(rawUrl('extent', 'south', y));
      if (!o) continue;
      const c = ice.cleanSeries(o);
      const at = c.points.find((p) => p.date === `${y}-08-13`);
      const mx = ice.maximumOf(c.points);
      if (at && mx) rows.push({ year: y, anchor: at.value, min: mx.value, date: mx.date, ratio: mx.value / at.value, doy: ice.dayOfYear(mx.date) });
    }
    const sum = ice.summariseRatios(rows);
    const anchor = ice.cleanSeries(snap(rawUrl('extent', 'south', 2026))).points.find((p) => p.date === '2026-08-13');
    const proj = anchor && sum ? ice.projectMinimum(anchor.value, 2026, sum) : null;
    ok('H8 the Antarctic secondary claim re-derives from the harvest to the committed figure',
      !!proj && near(proj.value, so.projection.value, 1e-9) && proj.date === so.projection.date &&
      near(proj.lo, so.projection.lo, 1e-9) && near(proj.hi, so.projection.hi, 1e-9),
      proj ? `${f3(proj.value)} on ${proj.date}, interval ${f3(proj.lo)} to ${f3(proj.hi)}` : 'not derivable');
    ok('H8 it was fitted on the same 15 seasons and its spread is not degenerate',
      sum && sum.n === 15 && sum.ratioSd > 0.005 && sum.doySd > 1,
      sum ? `n ${sum.n}, ratio ${f4(sum.ratioMean)} sd ${f4(sum.ratioSd)}, doy ${sum.doyMean.toFixed(1)} sd ${sum.doySd.toFixed(1)}` : 'no summary');
    ok('H8 it is a MAXIMUM and therefore runs above its own anchor, unlike the Arctic claim',
      !!proj && proj.value > anchor.value && so.projection.value > so.anchor_value,
      `anchor ${f3(anchor.value)} on 2026-08-13, projected max ${f3(so.projection.value)}`);
  }
}

/* ══ K. the contracts the page documents, which have to exist as code ═══════ */
console.log('\n== K. documented behaviour, asserted as behaviour ==');
{
  /* K1 THE REFUSAL THE PAGE PROMISED AND DID NOT IMPLEMENT. icecore.js documented that
   * refuseDays "is where it stops reporting a live number at all". What the page did was
   * compute freshness and then render four live numbers regardless, changing only a sentence.
   * mayReportLive() is that contract as code; these assert it exists, that it says no in the
   * refuse case, and that page.js actually calls it before rendering. */
  ok('K1 mayReportLive says no exactly when freshness refuses',
    ice.mayReportLive(ice.freshness('2026-08-13', '2026-08-15T00:00:00Z')) === true &&
    ice.mayReportLive(ice.freshness('2026-08-10', '2026-08-15T00:00:00Z')) === true &&
    ice.mayReportLive(ice.freshness('2026-06-01', '2026-08-15T00:00:00Z')) === false &&
    ice.mayReportLive(ice.freshness('2027-01-01', '2026-08-15T00:00:00Z')) === false &&
    ice.mayReportLive(ice.freshness(null, '2026-08-15T00:00:00Z')) === false);
  {
    const js = readFileSync(join(PAGE, 'page.js'), 'utf8');
    ok('K1 page.js calls it and returns before rendering any live figure',
      /if \(!ice\.mayReportLive\(fresh\)\)/.test(js) && /withheld/.test(js));
  }

  /* K2 "NOTHING HAS CHANGED SINCE YOUR LAST VISIT", which the syndicated copy promised the
   * page would say "in those words" and which was unreachable: _kit/livefeed.js answers it
   * from the upstream's Last-Modified, and this service sends none, so the only branch that
   * could ever run was 'unknown'. The newest data date answers it properly. */
  ok('K2 the data-date comparison distinguishes first, same, moved and backwards',
    ice.sinceLastVisitByDataDate('2026-08-13', null).status === 'first' &&
    ice.sinceLastVisitByDataDate('2026-08-13', '2026-08-13').status === 'same' &&
    ice.sinceLastVisitByDataDate('2026-08-13', '2026-08-11').status === 'moved' &&
    ice.sinceLastVisitByDataDate('2026-08-13', '2026-08-11').days === 2 &&
    ice.sinceLastVisitByDataDate('2026-08-11', '2026-08-13').status === 'retreated' &&
    ice.sinceLastVisitByDataDate(null, '2026-08-13').status === 'unknown');
  ok('K2 the "same" case really does say it in those words, so the syndicated promise is keepable',
    /nothing new to tell you yet/.test(ice.dataDateSentence(ice.sinceLastVisitByDataDate('2026-08-13', '2026-08-13'))) &&
    /has not published a newer day/.test(ice.dataDateSentence(ice.sinceLastVisitByDataDate('2026-08-13', '2026-08-13'))));
  ok('K2 NEGATIVE CONTROL: the header route on THIS feed can only ever answer "unknown"',
    (() => {
      const r = rec(rawUrl('extent', 'north', 2026));
      return r && !r.last_modified;
    })(), 'the service sends no Last-Modified, which is why the page does not answer from one');
  ok('K2 page.js answers from the data date and does not print the header sentence as if it worked',
    /ice\.dataDateSentence\(visitByData\(/.test(readFileSync(join(PAGE, 'page.js'), 'utf8')));

  /* K3 the pole hole, which decides whether "roughly a third was open water" survives. */
  ok('K3 the pole hole sizes match the user guide table, by era',
    ice.poleHoleArea('1980-06-01') === 1.19 && ice.poleHoleArea('1987-08-20') === 1.19 &&
    ice.poleHoleArea('1987-08-21') === 0.31 && ice.poleHoleArea('2007-12-31') === 0.31 &&
    ice.poleHoleArea('2008-01-01') === 0.029 && ice.poleHoleArea('2012-09-16') === 0.029);
  {
    const e = ice.cleanSeries(snap(rawUrl('extent', 'north', 2012))).points.find((p) => p.date === '2012-09-16');
    const a = ice.cleanSeries(snap(rawUrl('area', 'north', 2012))).points.find((p) => p.date === '2012-09-16');
    const open = (e.value - a.value) - ice.poleHoleArea('2012-09-16');
    ok('K3 "roughly a third was open water" survives subtracting the unseen pole hole',
      open / e.value > 0.30 && open / e.value < 0.36,
      `extent ${f3(e.value)}, area ${f3(a.value)}, gap ${f3(e.value - a.value)}, less pole hole leaves ${f3(open)} = ${(100 * open / e.value).toFixed(1)}%`);
  }

  /* K4 the quotations, which are the only hardcoded numbers on the page. A misquotation
   * inside quotation marks is a different kind of error from a wrong number and it had one:
   * NSIDC's caveat ends "derived from other studies", not "other sources". */
  {
    const h = readFileSync(join(PAGE, 'index.html'), 'utf8');
    ok('K4 NSIDC\'s citation caveat is quoted as written: "studies", not "sources"',
      h.includes('comparing with values derived from other studies') &&
      !h.includes('comparing with values derived from other sources'));
    ok('K4 robots.txt is described as it reads: four /user paths, not /user/*',
      h.includes('/user/register') && h.includes('/user/logout') && !h.includes('<span class="mono">/user/*</span>'));
    ok('K4 the crawl delay is not claimed to be satisfied by a cache TTL',
      !h.includes('The crawl delay is honoured by the worker caching each') &&
      h.includes('a cache TTL bounds how OFTEN we') );
  }

  /* K5 the reader-facing check panel must not contain a check that cannot fail. */
  {
    const js = readFileSync(join(PAGE, 'page.js'), 'utf8');
    const pushes = [...js.matchAll(/state\.checks\.push\(\{[\s\S]{0,400}?\}\)/g)].map((m) => m[0]);
    // `ok: false` is legitimate and there are three of them: they sit inside refusal
    // branches, where the check genuinely did not pass and is reporting so. `ok: true` is
    // never legitimate, because it is a row that says "pass" before anything is examined.
    const trivial = pushes.filter((p) => /\bok:\s*true\s*[,}]/.test(p));
    ok('K5 no row in the reader\'s own check panel is a hardcoded pass',
      trivial.length === 0,
      trivial.length ? trivial.map((t) => (t.match(/name: '([^']{0,60})/) || [, '?'])[1]).join(' | ') : `${pushes.length} rows, ${pushes.filter((p) => /ok: false/.test(p)).length} of them hardcoded FAILURES inside refusal branches`);
    ok('K5 the three that used to be hardcoded or unfailable now assert something that can fail',
      !/ok: earlier\.length > 0/.test(js) && !/ok: d > 0\.5/.test(js) &&
      !/scored against the live season on every load', ok: true/.test(js));
  }
}

/* ══ I. live ═══════════════════════════════════════════════════════════════ */
let live = null;
if (LIVE) {
  console.log('\n== I. live ==');
  const tryFetch = async (url, label) => {
    try {
      const res = await fetch(url, { headers: { Accept: 'application/json', 'User-Agent': 'ArtificialWasteland/1.0 (+https://artwaste.land) verifier' } });
      if (!res.ok) return { ok: false, error: `http_${res.status}`, label };
      return { ok: true, body: await res.json(), headers: { lastModified: res.headers.get('Last-Modified') }, label };
    } catch (e) { return { ok: false, error: String(e).slice(0, 100), label }; }
  };

  /* THE CHECK THAT WAS NOT THERE. This used to accept any date-keyed object from the worker
   * as "the primitive series", and that is exactly how the page shipped serving NSIDC's
   * five-day smoothed series under the label "the lowest single day actually observed". A
   * 200 with a well-formed body is not evidence that the body is the series you asked for.
   * So: the worker has to echo back the params it used and the upstream URL it built, and
   * both have to match what was requested, before anything downstream trusts the object. */
  const wantParams = { kind: 'extent', hemisphere: 'north', year: '2026', series: 'data' };
  const wantUpstream = rawUrl('extent', 'north', 2026);
  const viaWorker = await tryFetch(`${FEED_BASE}/api/feed/nsidc-seaice?kind=extent&hemisphere=north&year=2026&series=data`, 'worker');
  let route = 'worker', obj = null, feed = null, workerNote = 'served';
  const served = (() => {
    if (!viaWorker.ok || !viaWorker.body || !viaWorker.body.ok) return { ok: false, why: 'no usable body' };
    const b = viaWorker.body, got = b.params || {};
    const bad = Object.entries(wantParams).filter(([k, v]) => String(got[k]) !== String(v))
      .map(([k, v]) => `${k}: asked ${v}, served ${got[k] === undefined ? 'DROPPED' : got[k]}`);
    if (b.upstream !== wantUpstream) bad.push(`upstream: expected ${wantUpstream}, got ${b.upstream}`);
    return { ok: bad.length === 0, why: bad.join('; ') };
  })();
  const workerAnswered = viaWorker.ok && viaWorker.body && viaWorker.body.ok &&
    viaWorker.body.data && !Array.isArray(viaWorker.body.data);
  /* The two failures are not the same failure and must not share a severity.
   *
   *   NOT DEPLOYED (404, unreachable, upstream_error) is a fact about OUR deployment. It
   *   makes no number on this page wrong: the page's refusal path fires and says honestly
   *   that the source could not be reached. That stays a warning, loud and in the ledger.
   *
   *   DEPLOYED AND ANSWERING WITH THE WRONG THING is a fact about the page being false. It
   *   is strictly worse than being down, because a refusal is honest and a substituted
   *   series is not, and it is what actually happened. That is a hard failure, always,
   *   regardless of AW_EXPECT_WORKER. */
  if (workerAnswered) {
    ok('I0a the worker served the series that was ASKED FOR rather than a silently substituted one',
      served.ok, served.ok ? `params echoed intact; upstream ${viaWorker.body.upstream}` : served.why);
  }
  if (workerAnswered && served.ok) {
    obj = viaWorker.body.data; feed = viaWorker.body;
  } else {
    // nsidc.org is a permitted host (robots.txt read 2026-08-15T00:26:07Z, /api/ not
    // disallowed). The verifier is not a reader's browser, so falling back to the
    // upstream is legitimate; it is recorded in the ledger as route "direct" so nobody
    // can mistake it for the reader's path having worked.
    const direct = await tryFetch(rawUrl('extent', 'north', 2026), 'direct');
    route = 'direct';
    if (direct.ok) { obj = direct.body; feed = { upstream_last_modified: direct.headers.lastModified }; }
    workerNote = viaWorker.ok ? JSON.stringify(viaWorker.body).slice(0, 120) : viaWorker.error;
    warn('I0 the worker route, which is the route a reader takes, is serving this feed', false,
      `worker said ${workerNote}; fell back to the permitted upstream directly. See research/five-days-wide/FEED-REQUEST.md.`);
  }
  if (obj) {
    const a = ice.analyseYear(obj, { window: 5 });
    ok('I1 the live series parses and passes the guard', a.ok, a.ok ? `${a.observed} days, newest ${a.last}` : a.reason);
    if (a.ok) {
      const newest = a.points[a.points.length - 1];
      const f = ice.freshness(newest.date, new Date().toISOString());
      ok('I2 the newest row inside the live data is inside NSIDC’s stated lag', f.status === 'fresh', `${newest.date}, ${f.lagDays} days behind`);
      ok('I3 no live minimum is below the sentinel floor', a.rawMin.value >= ice.MIN_PLAUSIBLE && a.smoothMin.value >= ice.MIN_PLAUSIBLE, `${f3(a.rawMin.value)} / ${f3(a.smoothMin.value)}`);
      // revision detection: is anything the harvest recorded now different?
      const before = ice.cleanSeries(snap(rawUrl('extent', 'north', 2026))).points;
      const now = new Map(a.points.map((p) => [p.date, p.value]));
      const revised = before.filter((p) => now.has(p.date) && Math.abs(now.get(p.date) - p.value) > 1e-9)
        .map((p) => ({ date: p.date, was: p.value, now: now.get(p.date) }));
      const added = a.points.filter((p) => !before.some((q) => q.date === p.date)).map((p) => p.date);
      /* I4 used to read `ok(..., true, ...)`. The condition was the literal true, so this row
       * printed a pass while the run behind it reported 225 of 225 days of the year "revised"
       * and the smoothing delta jumping from 0.0006 to 0.1502, which is total corruption of
       * the live series with zero failing assertions. What can actually fail: a genuine
       * revision is rare and small, so wholesale disagreement with the harvest means we are
       * comparing two different series rather than watching NSIDC edit one.
       *
       * The threshold is deliberately loose (a tenth of the year, or any revision bigger than
       * a tenth of a million km2). It is not trying to catch NSIDC republishing a day. It is
       * trying to catch us fetching something else and calling it a revision, which is what
       * happened, and which the page then printed as an accusation against a named institution. */
      const bulk = revised.length > before.length * 0.10;
      const huge = revised.filter((r) => Math.abs(r.now - r.was) > 0.10);
      ok('I4 the live series is the same series the harvest recorded, so a difference means revision rather than a different endpoint',
        !bulk && huge.length === 0,
        `${added.length} new day(s) ${added.join(',') || '(none)'}; ${revised.length} of ${before.length} days differ` +
        (huge.length ? `; ${huge.length} by more than 0.10, largest ${f4(Math.max(...huge.map((r) => Math.abs(r.now - r.was))))} on ${huge[0].date}` : ''));
      /* I5 the differential the whole page rests on, through the READER'S route: the two
       * settings must return different objects. If the allowlist ever collapses them again,
       * this fails instead of the page quietly printing one under the other's label. */
      const w0 = await tryFetch(`${FEED_BASE}/api/feed/nsidc-seaice?kind=extent&hemisphere=north&year=2012&series=filled_averaged_data&smoothing_window=0`, 'w0');
      const w5 = await tryFetch(`${FEED_BASE}/api/feed/nsidc-seaice?kind=extent&hemisphere=north&year=2012&series=filled_averaged_data&smoothing_window=5`, 'w5');
      const w31 = await tryFetch(`${FEED_BASE}/api/feed/nsidc-seaice?kind=extent&hemisphere=north&year=2012&series=filled_averaged_data&smoothing_window=31`, 'w31');
      const minOf = (r) => (r.ok && r.body && r.body.ok && r.body.data) ? ice.minimumOf(ice.cleanSeries(r.body.data).points) : null;
      const m0 = minOf(w0), m5 = minOf(w5), m31 = minOf(w31);
      ok('I5 through the reader\'s own route, windows 0, 5 and 31 return three DIFFERENT series',
        !!m0 && !!m5 && !!m31 && near(m0.value, 3.340, 0.001) && near(m5.value, 3.387, 0.001) && near(m31.value, 3.552, 0.001),
        m0 && m5 && m31 ? `${f3(m0.value)} ${m0.date} / ${f3(m5.value)} ${m5.date} / ${f3(m31.value)} ${m31.date}` : 'one or more did not answer');
      ok('I5 ... and window 31 is genuinely reachable rather than being window 5 under another label',
        !!m31 && !!m5 && Math.abs(m31.value - m5.value) > 0.15 && (w31.body || {}).params &&
        String(((w31.body || {}).params || {}).smoothing_window) === '31',
        w31.body ? `worker echoed smoothing_window=${(w31.body.params || {}).smoothing_window}, upstream ${w31.body.upstream}` : 'no body');
      live = { route, feed, a, newest, fresh: f, revised, added, workerNote };
    }
  } else {
    ok('I1 a live series could be fetched at all', false, 'neither the worker nor the upstream answered');
  }
}

/* ══ the record ════════════════════════════════════════════════════════════ */
const source = live ? live.a : A[2026];
const newestPoint = source.points[source.points.length - 1];
const nsidcSm2026 = snap(smUrl('extent', 'north', 2026, 5));
const ourSmoothOnNewest = (source.smoothed.find((p) => p.date === newestPoint.date) || {}).value;
const theirSmoothOnNewest = nsidcSm2026 ? Number(nsidcSm2026[newestPoint.date]) : null;
const southSnap = snap(rawUrl('extent', 'south', 2026));
const areaSnap = snap(rawUrl('area', 'north', 2026));
const scored = ice.scoreClaim(fc.raw.projection, { ...source.rawMin, last: source.last }, '2026-09-30');

const previous = existsSync(RECORD)
  ? readFileSync(RECORD, 'utf8').trim().split('\n').filter(Boolean).map((l) => { try { return JSON.parse(l); } catch { return null; } }).filter(Boolean)
  : [];
const prev = previous.length ? previous[previous.length - 1] : null;

const line = {
  run_utc: new Date().toISOString(),
  route: live ? live.route : 'committed snapshot',
  harvested_at: harvest.harvested_at,
  newest_data_date: newestPoint.date,
  newest_extent_north: newestPoint.value,
  newest_area_north: areaSnap ? (ice.cleanSeries(areaSnap).points.find((p) => p.date === newestPoint.date) || {}).value ?? null : null,
  newest_extent_south: southSnap ? (ice.cleanSeries(southSnap).points.find((p) => p.date === newestPoint.date) || {}).value ?? null : null,
  freshness: live ? live.fresh.status : ice.freshness(newestPoint.date, new Date().toISOString()).status,
  lag_days: ice.freshness(newestPoint.date, new Date().toISOString()).lagDays,
  upstream_last_modified: live && live.feed ? (live.feed.upstream_last_modified ?? null) : (rec(rawUrl('extent', 'north', 2026)) || {}).last_modified ?? null,
  ytd_raw_min: source.rawMin,
  ytd_smooth_min: { date: source.smoothMin.date, value: Math.round(source.smoothMin.value * 1000) / 1000 },
  our_smoothed_on_newest: Number.isFinite(ourSmoothOnNewest) ? Math.round(ourSmoothOnNewest * 1e6) / 1e6 : null,
  nsidc_smoothed_on_newest: Number.isFinite(theirSmoothOnNewest) ? theirSmoothOnNewest : null,
  smoothing_delta: (Number.isFinite(ourSmoothOnNewest) && Number.isFinite(theirSmoothOnNewest))
    ? Math.round((ourSmoothOnNewest - theirSmoothOnNewest) * 1e6) / 1e6 : null,
  new_days: prev && prev.newest_data_date ? ice.daysBetween(prev.newest_data_date, newestPoint.date) : null,
  revised_days: live ? live.revised : [],
  rank_shift: { moved: D.shift.moved, of: D.shift.years },
  claim_status: scored.status,
  claim_detail: scored.status === 'open'
    ? { running_min: scored.runningMin, running_date: scored.runningDate, series_reaches: source.last }
    : { observed: scored.observedValue, on: scored.observedDate, in_value: scored.inValue, in_date: scored.inDate },
  sensor_break: ice.SENSOR_BREAK,
  worker_route: live ? (live.route === 'worker' ? 'serving' : `not serving: ${live.workerNote}`) : 'not attempted',
  // checks/fails/warns are filled in AFTER J1 and J2 run, below. They used to be captured
  // here, two assertions before the end, so every committed ledger line and every record
  // line understated the run by exactly two: the file said 96 while the run printed 98.
  checks: null, fails: null, warns: null,
};

ok('J1 the record line carries a newest data date, both minima and the claim status',
  !!line.newest_data_date && !!line.ytd_raw_min && !!line.ytd_smooth_min && !!line.claim_status);
ok('J2 no number in the record line is below the sentinel floor',
  line.ytd_raw_min.value >= ice.MIN_PLAUSIBLE && line.ytd_smooth_min.value >= ice.MIN_PLAUSIBLE);

line.checks = checks; line.fails = fails; line.warns = warns;

if (DO_RECORD) {
  appendFileSync(RECORD, JSON.stringify(line) + '\n');
  mkdirSync(dirname(LEDGER), { recursive: true });
  const all = readFileSync(RECORD, 'utf8');
  writeFileSync(LEDGER, all);          // the page reads this copy; it is the same bytes
  console.log(`\nappended to ${RECORD} and mirrored to ${LEDGER}`);
}

console.log(`\n${checks - fails}/${checks} checks passed${fails ? `, ${fails} FAILED` : ''}${warns ? `, ${warns} WARNING about our own deployment (see FEED-REQUEST.md)` : ''}`);
console.log(JSON.stringify(line));
process.exit(fails ? 1 : 0);
