#!/usr/bin/env node
/* verify-the-breath-the-mountain-half-hears.mjs
 *
 * Recomputes every number the page shows, from the same upstreams, through the same module
 * (public/strata/the-breath-the-mountain-half-hears/co2.js, imported unchanged), and appends
 * one line per run to research/the-breath-the-mountain-half-hears/record.jsonl.
 *
 * What is different about this verifier, and why:
 *
 *  - IT TESTS THE REFUSALS. This page's most common state is "the source has not moved".
 *    A verifier that only checked the happy path would be testing the half that was never
 *    going to fail. So the freshness gate is run against the real, live, four-years-dead
 *    daily file and MUST refuse it; the visit sentence is exercised on all four branches;
 *    an empty feed, an unparseable NOAA page and a too-short window each have an assertion.
 *
 *  - IT TESTS THE INSTRUMENT WITH A PLANT. A synthetic Scripps-format CSV with a known
 *    amplitude and a known growth is handed to the SAME parser and the SAME decomposition
 *    as Alert and the South Pole. The plant enters the data, never the result list.
 *
 *  - IT TESTS THE PROSE. The literal amplitudes typed into the page's opening paragraph are
 *    extracted from index.html and checked against what the live files say today. A prose
 *    number that has drifted away from the live one is the quietest lie this page could tell.
 *
 * Usage:
 *   node research/the-breath-the-mountain-half-hears/verify-the-breath-the-mountain-half-hears.mjs
 *   ... --no-record     run every check but do not append to the record
 *   ... --offline       use research/.../raw/*.csv instead of the network (fixtures only)
 *
 * Exits 0 only when every check passes.
 */
import { readFileSync, existsSync, appendFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import * as C from '../../public/strata/the-breath-the-mountain-half-hears/co2.js';

const HERE = dirname(fileURLToPath(import.meta.url));
const PAGE = join(HERE, '..', '..', 'public', 'strata', 'the-breath-the-mountain-half-hears');
const DATA = join(PAGE, 'data');
const RECORD = join(HERE, 'record.jsonl');
const SLUG = 'the-breath-the-mountain-half-hears';
const args = process.argv.slice(2);
const OFFLINE = args.includes('--offline');
const NO_RECORD = args.includes('--no-record');
const UA = 'ArtificialWasteland/1.0 (+https://artwaste.land; verifier, one run)';
const PROXY = process.env.AW_ORIGIN || 'https://artwaste.land';

let pass = 0; const failures = [];
function ok(label, cond, detail = '') {
  if (cond) { pass++; return true; }
  failures.push(`${label}${detail ? ` :: ${detail}` : ''}`);
  return false;
}
const near = (a, b, tol) => Number.isFinite(a) && Number.isFinite(b) && Math.abs(a - b) <= tol;

/* ── intake ───────────────────────────────────────────────────────────────── */

const UPSTREAM = {
  'insitu-monthly': 'https://keelinglabsites.ucsd.edu/websitedataco2/monthly_in_situ_co2_mlo.csv',
  'insitu-weekly': 'https://keelinglabsites.ucsd.edu/websitedataco2/weekly_in_situ_co2_mlo.csv',
  landing: 'https://gml.noaa.gov/ccgg/trends/',
  daily: 'https://keelinglabsites.ucsd.edu/websitedataco2/daily_in_situ_co2_mlo.csv',
};
const RAW = {
  'insitu-monthly': 'monthly_in_situ_co2_mlo.csv',
  'insitu-weekly': 'weekly_in_situ_co2_mlo.csv',
  landing: 'noaa_index.html',
  daily: 'daily_in_situ_co2_mlo.csv',
};

const via = { route: null, notes: [] };

/** Prefer the same route the page takes (our own worker). Fall back to the upstream, and say
 *  in the record which one was used, because a verifier that quietly changed route would be
 *  checking a different thing from the one the reader sees. */
/** The upstream URL a given request is asking for, so a wrong answer can be detected. */
function wantedUrl(kind, params) {
  return kind === 'flask'
    ? `https://keelinglabsites.ucsd.edu/websitedataco2/monthly_flask_co2_${params.station}.csv`
    : UPSTREAM[kind];
}

async function grab(kind, params = {}) {
  if (OFFLINE) {
    const f = join(HERE, 'raw', RAW[kind] || `${kind}.csv`);
    if (!existsSync(f)) return { ok: false, error: 'no fixture' };
    return { ok: true, text: readFileSync(f, 'utf8'), upstream_last_modified: null, route: 'fixture' };
  }
  const qs = new URLSearchParams(params).toString();
  const key = kind === 'landing' ? 'noaa-co2-landing' : 'scripps-co2';
  // THE DAILY FILE IS DELIBERATELY NOT ALLOWLISTED. Asking the worker for it does not fail; it
  // returns a DIFFERENT file at HTTP 200 (the monthly flask default), which parsed to zero
  // daily rows and crashed this verifier on `null.toFixed()` before it could print a pass
  // count or write a record line. That meant the whole run only ever completed on the fallback
  // route, so the live negative control had never once gone through the page's own path.
  // The negative control goes straight upstream, and every other request now checks that the
  // file it got back is the file it asked for.
  if (kind !== 'daily' && via.route !== 'upstream') {
    try {
      const r = await fetch(`${PROXY}/api/feed/${key}${qs ? '?' + qs : ''}`,
        { headers: { Accept: 'application/json', 'User-Agent': UA } });
      const b = await r.json();
      const want = wantedUrl(kind, params);
      if (r.ok && b.ok && b.upstream === want) { via.route = via.route || 'proxy'; return { ...b, route: 'proxy' }; }
      if (r.ok && b.ok && b.upstream !== want) {
        via.notes.push(`proxy answered ${kind} with ${b.upstream} when ${want} was asked for; used the upstream instead`);
      }
    } catch { /* fall through */ }
  }
  const url = wantedUrl(kind, params);
  try {
    const r = await fetch(url, { headers: { 'User-Agent': UA } });
    if (!r.ok) return { ok: false, error: `http_${r.status}` };
    via.route = 'upstream';
    return { ok: true, text: await r.text(), upstream_last_modified: r.headers.get('last-modified'), route: 'upstream' };
  } catch (e) { return { ok: false, error: String(e && e.message) }; }
}

const now = new Date();
const snapshot = JSON.parse(readFileSync(join(DATA, 'noaa-growth-rate-snapshot.json'), 'utf8'));
const trapFix = JSON.parse(readFileSync(join(DATA, 'daily-file-trap.json'), 'utf8'));
const ctx = JSON.parse(readFileSync(join(DATA, 'context-quotes.json'), 'utf8'));
const html = readFileSync(join(PAGE, 'index.html'), 'utf8');

/* ── 1. the committed snapshot, which can rot silently ───────────────────── */

const snapAge = (now - new Date(snapshot.fetched_at)) / 86400000;
ok('snapshot: NOAA growth table has 60+ years', snapshot.table.length >= 60, `${snapshot.table.length}`);
ok('snapshot: table is contiguous', snapshot.table.every((r, i, a) => i === 0 || r.year === a[i - 1].year + 1));
ok('snapshot: 2024 growth is 3.33 as NOAA prints it',
  snapshot.table.find((r) => r.year === 2024)?.growth === 3.33);
ok('snapshot: NOAA recipe quoted verbatim and mentions November-February',
  /November-February/.test(snapshot.recipe_verbatim || ''));
ok('snapshot: uncertainty note quoted and states 0.11 ppm/yr',
  /0\.11 ppm\/yr/.test(snapshot.uncertainty_verbatim || ''));
ok('snapshot: eruption note quoted', /Maunakea/.test(snapshot.eruption_verbatim || ''));
ok('snapshot: taken from a robots-permitted path', /\/ccgg\/trends\/gr\.html$/.test(snapshot.url));
ok('snapshot: NOT taken from a disallowed path',
  !/\/webdata\/|\/aftp\//.test(snapshot.url));
ok('snapshot: fresher than one year, or a human must re-take it', snapAge <= 365, `${snapAge.toFixed(0)} days old`);

/* ── 2. no disallowed host appears anywhere in the shipped page ──────────── */

const pjs = readFileSync(join(PAGE, 'page.js'), 'utf8');
const cjs = readFileSync(join(PAGE, 'co2.js'), 'utf8');

// A disallowed path may be NAMED in prose (the page explains why it is not fetched) but must
// never appear as something the browser would load. So the test is about links and fetches,
// not about the characters.
for (const [f, src] of [['index.html', html], ['page.js', pjs], ['co2.js', cjs]]) {
  ok(`${f}: no link or script pointing at a disallowed NOAA tree`,
    ![...src.matchAll(/(?:src|href)\s*=\s*["']([^"']+)/g)].some((m) => /gml\.noaa\.gov\/(webdata|aftp)/.test(m[1])));
  ok(`${f}: no scheme-qualified URL into a disallowed NOAA tree`,
    !/https?:\/\/(?:[a-z.]*\.)?gml\.noaa\.gov\/(webdata|aftp)/.test(src));
  // Resource loads only. A canonical link and the JSON-LD's own url field are metadata, not
  // requests, and must not be confused for one.
  ok(`${f}: no third-party script or stylesheet is loaded`,
    ![...src.matchAll(/<script[^>]+src=["'](https?:[^"']+)/g)].length
    && ![...src.matchAll(/<link[^>]+rel=["'](?:stylesheet|preload|prefetch|modulepreload)["'][^>]*href=["'](https?:[^"']+)/g)].length);
}
// The page's ONLY network calls: fetchFeed() against allowlisted keys, and same-origin JSON.
// Every feed request on the page goes through fetchFeedSafe(), which wraps the kit's
// fetchFeed() so that a network-level rejection becomes a rendered refusal instead of an
// unhandled throw. Both spellings are collected so the allowlist check cannot be bypassed by
// renaming the wrapper.
const feedKeys = [...pjs.matchAll(/fetchFeed(?:Safe)?\(\s*['"]([^'"]+)['"]/g)].map((m) => m[1]);
ok('page: at least one feed is actually fetched', feedKeys.length >= 3, feedKeys.join(','));
ok('page: every feed key is one this build was issued',
  feedKeys.every((k) => ['scripps-co2', 'noaa-co2-landing'].includes(k)), [...new Set(feedKeys)].join(','));
// The raw kit call must appear exactly once, inside the wrapper. If a later edit calls
// fetchFeed() directly again, that call can throw past main() and strand the page on
// "Loading" forever, which is the failure this wrapper exists to prevent.
// Comments discuss fetchFeed() by name, so the count has to be taken on code rather than on
// characters, or the prose about the wrapper reads as a second call to it.
const pjsCode = pjs.replace(/\/\*[\s\S]*?\*\//g, '').replace(/^\s*\/\/.*$/gm, '');
ok('page: the kit\'s fetchFeed is called in exactly one place, the safe wrapper',
  (pjsCode.match(/[^A-Za-z]fetchFeed\(/g) || []).length === 1,
  `${(pjsCode.match(/[^A-Za-z]fetchFeed\(/g) || []).length} direct calls`);
ok('page: a failed load retracts every region that says it is loading',
  /retractLoading\(/.test(pjs) && /LOADING_REGIONS/.test(pjs));
const bareFetches = [...pjs.matchAll(/[^A-Za-z_]fetch\(\s*([^;]{0,60})/g)].map((m) => m[1].trim());
ok('page: the only bare fetch is same-origin committed JSON',
  bareFetches.length > 0 && bareFetches.every((a) => a.startsWith('new URL(`./data/')),
  bareFetches.join(' | '));
ok('page: the frozen daily file is never fetched, only labelled',
  !bareFetches.some((a) => /daily_in_situ/.test(a)) && !/fetchFeed\([^)]*daily/.test(pjs));

/* ── 3. the live feeds ───────────────────────────────────────────────────── */

const mFeed = await grab('insitu-monthly', { series: 'insitu-monthly' });
const wFeed = await grab('insitu-weekly', { series: 'insitu-weekly' });
const lFeed = await grab('landing', { page: 'mauna-loa' });

ok('feed: Scripps monthly in-situ answered', mFeed.ok, mFeed.error || '');
if (!mFeed.ok) { report(null); process.exit(1); }

const monthly = C.parseScrippsCsv(mFeed.text);
const weekly = wFeed.ok ? C.parseScrippsWeekly(wFeed.text) : null;
const landing = lFeed.ok ? C.parseNoaaLanding(lFeed.text) : null;

ok('monthly: parsed 800+ rows', monthly.rows.length >= 800, `${monthly.rows.length}`);
ok('monthly: carries its own archive stamp', !!monthly.stampArchiveDate, monthly.stampArchive || 'none');
ok('monthly: carries a "through" stamp', !!monthly.stampThroughDate, monthly.stampThrough || 'none');
ok('monthly: the missing sentinel -99.99 is never treated as a reading',
  C.realRows(monthly, 'co2').every((r) => r.co2 > 250 && r.co2 < 600));
ok('monthly: file header records Scripps own eruption gap handling',
  /Dec 2022 through Feb 2023|MKO/.test(monthly.headerText));

const newest = C.newestReal(monthly, 'co2');
const fresh = C.freshness({
  newestDataDate: C.monthDate(newest.yr, newest.mn), now,
  maxAgeDays: 120, label: 'scripps monthly',
  httpLastModified: mFeed.upstream_last_modified,
});
/* The GATE is what this verifier is entitled to assert, not the weather.
 *
 * This used to assert `fresh.ok` outright, which fails the moment Scripps is slow — a world
 * condition the page renders honestly and loudly. A red verifier for a state the page handles
 * correctly teaches whoever runs it next to ignore red. So the hard assertion is that the
 * gate's verdict agrees with the measured age and its own ceiling, in both directions, and the
 * staleness of the day is recorded as an observation instead. */
ok('freshness: the gate\'s verdict agrees with the age it measured, in both directions',
  fresh.ok === (fresh.ageDays <= fresh.maxAgeDays && fresh.ageDays >= -C.FUTURE_TOLERANCE_DAYS),
  `age ${fresh.ageDays.toFixed(1)}, ceiling ${fresh.maxAgeDays}, verdict ${fresh.verdict}`);
if (!fresh.ok) {
  via.notes.push(`the live monthly file is ${fresh.ageDays.toFixed(1)} days old, past the page's `
    + `${fresh.maxAgeDays}-day ceiling. The page is rendering its stale-file refusal. This is the `
    + 'source having stopped, not the page having broken.');
}
ok('freshness: the file has not gone so quiet that the page has nothing to report at all',
  fresh.ageDays < 400, `newest ${newest.yr}-${newest.mn} is ${fresh.ageDays.toFixed(1)} days old`);

const archiveAge = monthly.stampArchiveDate ? (now - monthly.stampArchiveDate) / 86400000 : null;

/* ── 4. THE NEGATIVE CONTROL: the gate must be able to refuse ────────────── */

const dailyFeed = await grab('daily');
let trapLive = null;
if (dailyFeed.ok) {
  const dp = C.parseScrippsDaily(dailyFeed.text);
  // The parse has to be checked BEFORE anything reads a number off it. When the worker served
  // the wrong file this yielded zero rows, and the first `.toFixed()` on the resulting null
  // took the whole run down before it could report or record.
  if (dp.real.length > 10000) {
    trapLive = C.freshness({
      newestDataDate: dp.newestRealDate, now, maxAgeDays: 14, label: 'daily (live)',
      httpLastModified: dailyFeed.upstream_last_modified,
    });
    ok('NEGATIVE CONTROL: the live daily file returns data at all', true, `${dp.real.length}`);
    ok('NEGATIVE CONTROL: the same gate REFUSES the live daily file', trapLive.ok === false,
      `age ${trapLive.ageDays?.toFixed(0)} days`);
    ok('NEGATIVE CONTROL: its HTTP header is far newer than its newest datum',
      trapLive.headerLeadDays > 1000, `${trapLive.headerLeadDays?.toFixed(0)} days ahead`);
  } else {
    ok('NEGATIVE CONTROL: the live daily file returns data at all', false,
      `parsed ${dp.real.length} readings, so this is not the daily file`);
    via.notes.push('the daily fetch returned something that is not the daily file');
  }
} else {
  via.notes.push('the live daily file could not be fetched, so the negative control ran on the committed excerpt only');
}
// The committed excerpt the PAGE runs the gate over, checked the same way.
const trapParsed = C.parseScrippsDaily(`${trapFix.excerpt_head}\n${trapFix.excerpt_tail}`);
const trapGate = C.freshness({
  newestDataDate: trapParsed.newestRealDate, now, maxAgeDays: 14, label: 'daily (excerpt)',
  httpLastModified: trapFix.http.last_modified,
});
ok('NEGATIVE CONTROL: the committed excerpt is refused too', trapGate.ok === false);
ok('NEGATIVE CONTROL: the excerpt agrees with the whole file it came from',
  !trapLive || trapParsed.newestReal.date === trapFix.last_real.date);
ok('NEGATIVE CONTROL: the gate ACCEPTS a fixture that is fresh, so it is not simply always refusing',
  C.freshness({ newestDataDate: new Date(now.getTime() - 3 * 86400000), now, maxAgeDays: 14, label: 'x' }).ok === true);
ok('NEGATIVE CONTROL: an undated file is refused rather than assumed fresh',
  C.freshness({ newestDataDate: null, now, maxAgeDays: 14, label: 'x' }).ok === false);
// THE GATE IS TWO-SIDED. `ageDays <= maxAgeDays` accepted any negative age, so a file carrying
// next year's rows read as "-304 days old, inside the ceiling, accepted" on the page whose
// declared top hazard is staleness dressed as freshness. Future data is a broken file.
{
  const future = C.freshness({ newestDataDate: new Date(now.getTime() + 300 * 86400000), now, maxAgeDays: 120, label: 'x' });
  ok('NEGATIVE CONTROL: a FUTURE-dated file is refused, not treated as extra fresh', future.ok === false,
    `age ${future.ageDays?.toFixed(0)} days, verdict ${future.verdict}`);
  ok('NEGATIVE CONTROL: and it is refused for being impossible, not merely stale',
    /future/i.test(future.reason) && future.future === true);
  ok('NEGATIVE CONTROL: a file dated a few hours ahead is still accepted, so the floor is not brittle',
    C.freshness({ newestDataDate: new Date(now.getTime() + 3600000), now, maxAgeDays: 120, label: 'x' }).ok === true);
}
ok('the page never asks the worker for a daily series',
  ![...pjs.matchAll(/fetchFeed\([^)]*\)/g)].some((m) => /daily/i.test(m[0])));

/* ── 5. THE ANCHOR ───────────────────────────────────────────────────────── */

const growth = C.noaaGrowthRecipe(monthly, { column: 'adjustedFilled' });
const anchor = C.compareToPublished(growth, snapshot.table);
const anchorUnfilled = C.compareToPublished(C.noaaGrowthRecipe(monthly, { column: 'adjusted' }), snapshot.table);

ok('ANCHOR: every year NOAA prints is reproducible from Scripps', anchor.n === snapshot.table.length,
  `${anchor.n} of ${snapshot.table.length}`);
ok('ANCHOR: mean absolute error is inside NOAA\'s own stated 0.11 ppm/yr uncertainty',
  anchor.mae <= 0.11, `mae ${anchor.mae.toFixed(4)}`);

// THE SPLICE. NOAA's monthly Mauna Loa product IS Scripps data before April 1974, so those
// years are a series compared with itself and must not be allowed to flatter the headline.
const SPLICE_END = 1974;
const maeOf = (ps) => (ps.length ? ps.reduce((a, p) => a + Math.abs(p.error), 0) / ps.length : null);
const pre = anchor.pairs.filter((p) => p.year < SPLICE_END);
const post = anchor.pairs.filter((p) => p.year >= SPLICE_END);
const preMae = maeOf(pre), postMae = maeOf(post);
ok('SPLICE: the pre-1974 years agree far too well to be two instruments',
  preMae < 0.02 && preMae * 5 < postMae, `pre ${preMae?.toFixed(4)} vs post ${postMae?.toFixed(4)}`);
ok('SPLICE: the INDEPENDENT years alone are still inside NOAA\'s stated 0.11 ppm/yr',
  postMae <= 0.11, `${post.length} years, mae ${postMae?.toFixed(4)}`);
ok('SPLICE: the page leads with the independent subset, not the flattering average',
  /Independent years compared/.test(pjs) && /SPLICE_END = 1974/.test(pjs));
ok('SPLICE: the page marks the spliced rows in its own table', /SPLICE_END \? ' <span class="warn">\*/.test(pjs));
ok('ANCHOR: worst year is inside 0.5 ppm/yr', anchor.max <= 0.5, `max ${anchor.max.toFixed(3)}`);
ok('ANCHOR: at least 60 of the years land inside 0.2 ppm/yr',
  anchor.within(0.2) >= 60, `${anchor.within(0.2)} of ${anchor.n}`);
ok('ANCHOR: 2024 lands on NOAA\'s printed 3.33',
  near(anchor.pairs.find((p) => p.year === 2024)?.computed, 3.33, 0.02));
ok('ANCHOR: the result does not depend on the gap-filling choice',
  near(anchor.mae, anchorUnfilled.mae, 0.02), `${anchor.mae.toFixed(4)} vs ${anchorUnfilled.mae.toFixed(4)}`);

// The alternatives must MISS. If a naive method reproduced the table too, the anchor would be
// evidence of nothing, because any arithmetic would have passed it.
const alts = {};
for (const k of ['annual-mean-difference', 'december-to-december', 'january-to-january']) {
  const cmp = C.compareToPublished(C.naiveGrowthRates(monthly, k), snapshot.table);
  alts[k] = { n: cmp.n, mae: cmp.mae, max: cmp.max };
  ok(`ANCHOR CONTROL: "${k}" misses NOAA's table by more than the recipe does`,
    cmp.mae > anchor.mae * 1.5, `mae ${cmp.mae.toFixed(3)} vs ${anchor.mae.toFixed(3)}`);
}

/* ── 6. the seven stations, and the plant ────────────────────────────────── */

const stations = {};
for (const s of C.STATIONS) {
  const f = await grab('flask', { series: 'flask', station: s.code });
  if (!f.ok) { stations[s.code] = { error: f.error }; ok(`station ${s.code}: feed answered`, false, f.error); continue; }
  const parsed = C.parseScrippsCsv(f.text);
  const res = C.stationResult(parsed, { window: null });
  const nr = C.newestReal(parsed, 'co2');
  stations[s.code] = {
    lat: s.lat, elev: s.elev,
    stamp: parsed.stampArchive,
    newest: nr ? { yr: nr.yr, mn: nr.mn, co2: nr.co2 } : null,
    span: res.span, n: res.n,
    meanAmplitude: res.meanAmplitude,
    perDecade: res.perDecade, se: res.perDecadeSe, t: res.t,
    peakMonth: res.peakMonth.month, troughMonth: res.troughMonth.month,
  };
  ok(`station ${s.code}: at least 20 complete years`, res.n >= 20, `${res.n}`);
  ok(`station ${s.code}: amplitude is a positive, physical number`,
    res.meanAmplitude > 0 && res.meanAmplitude < 40, `${res.meanAmplitude?.toFixed(2)}`);
  ok(`station ${s.code}: the fit tail is not read as data`,
    res.span[1] <= nr.yr, `amplitudes end ${res.span[1]}, newest reading ${nr.yr}`);
  // Every counted year, on the real file, must rest on twelve real observations. This is the
  // assertion the hand-built fixtures above cannot make, and it is the one that would have
  // caught La Jolla counting 1964, a year whose twelve months are all NaN in column 5.
  const realPerYear = new Map();
  for (const row of parsed.rows) {
    if (!realPerYear.has(row.yr)) realPerYear.set(row.yr, 0);
    if (row.co2 !== null) realPerYear.set(row.yr, realPerYear.get(row.yr) + 1);
  }
  const modelled = res.years.filter((y) => (realPerYear.get(y.year) || 0) < 12).map((y) => y.year);
  ok(`station ${s.code}: no counted year rests on gap-filled months`,
    modelled.length === 0, modelled.length ? `${modelled.length} modelled years, e.g. ${modelled.slice(0, 5).join(', ')}` : '');
  stations[s.code].modelledYearsCounted = modelled.length;
}

// The ladder, which is the page's central physical claim.
const amp = (c) => stations[c] && stations[c].meanAmplitude;
ok('LADDER: the northern high-latitude stations have the largest cycles',
  amp('ptb') > amp('ljo') && amp('alt') > amp('ljo'));
// CONTROL ONE, and the direction of the surprise, not just the inequality. The page used to
// claim La Jolla contradicted a latitude story while La Jolla is 13.4 degrees FURTHER north
// than Mauna Loa, which is what a latitude story predicts. The genuine non-monotonicity is
// Alert, eleven degrees north of Point Barrow and quieter, so that is what gets asserted.
ok('CONTROL ONE: Alert is FURTHER north than Point Barrow',
  C.STATIONS.find((s) => s.code === 'alt').lat > C.STATIONS.find((s) => s.code === 'ptb').lat);
ok('CONTROL ONE: and yet Alert has the SMALLER cycle, so latitude does not order the ladder',
  amp('alt') < amp('ptb'), `alt ${amp('alt')?.toFixed(2)} vs ptb ${amp('ptb')?.toFixed(2)}`);
ok('LADDER: La Jolla at 32.9N has a LARGER cycle than Mauna Loa at 19.5N',
  amp('ljo') > amp('mlo'), `${amp('ljo')?.toFixed(2)} vs ${amp('mlo')?.toFixed(2)}`);
// ... which is NOT a counterexample to latitude, and the page must not sell it as one.
ok('NOT A CONTROL: La Jolla is further from the equator than Mauna Loa, and the page says so',
  C.STATIONS.find((s) => s.code === 'ljo').lat > C.STATIONS.find((s) => s.code === 'mlo').lat);
ok('NOT A CONTROL: no page text claims La Jolla is closer to the equator or further from the forests',
  !/closer to the equator/i.test(pjs + html + readFileSync(join(HERE, '..', '..', 'src', 'content', 'strata', `${SLUG}.md`), 'utf8'))
  && !/further from the forests/i.test(pjs));
ok('LADDER: Cape Kumukahi, same latitude as Mauna Loa and 3,394 m lower, has a larger cycle',
  amp('kum') > amp('mlo'), `${amp('kum')?.toFixed(2)} vs ${amp('mlo')?.toFixed(2)}`);
ok('LADDER: the two Hawaiian stations really are at the same latitude',
  Math.abs(C.STATIONS.find((s) => s.code === 'kum').lat - C.STATIONS.find((s) => s.code === 'mlo').lat) < 0.2);
ok('LADDER: the South Pole cycle is the smallest', amp('spo') < amp('sam') && amp('spo') < amp('mlo'));
/* THE MODE IS NOT ALWAYS A MODE. The ladder prints a peak month per station, and at some
 * windows the annual peak months tie exactly. Taking the first-inserted key printed a
 * confident month where the data has no single answer, under a caption reading "the most
 * common month in the window". modeOf now reports ties and the page renders them. */
/* Asserted on constructed input, because whether any live station ties today is an accident of
 * the data. An earlier version of this check read `tied.length === 1 || isTie === true`, which
 * is true of every possible return value and therefore tested nothing. */
{
  const yrs = (months) => months.map((m, i) => ({ year: 1990 + i, peakMonth: m }));
  const tie = C.modeMonths(yrs([2, 4, 2, 4, 3]), 'peakMonth');
  ok('MODE: an exact tie is reported as a tie, not resolved by insertion order',
    tie.isTie === true && tie.tied.join(',') === '2,4' && tie.count === 2,
    `month ${tie.month}, tied ${tie.tied.join('/')}, ${tie.count}/${tie.of}`);
  const clear = C.modeMonths(yrs([5, 5, 5, 4]), 'peakMonth');
  ok('MODE: a real mode is NOT reported as a tie, so the flag means something',
    clear.isTie === false && clear.month === 5 && clear.count === 3 && clear.of === 4);
  ok('MODE: the winning count and the total ride along, so a thin plurality cannot look decisive',
    clear.plurality === 0.75 && C.modeMonths(yrs([1, 2, 3, 4]), 'peakMonth').plurality === 0.25);
  ok('MODE: an empty window yields no month rather than a guess',
    C.modeMonths([], 'peakMonth').month === null);
  ok('MODE: the page renders the count and the tie rather than a bare month',
    /monthCell\(/.test(pjs) && /isTie/.test(pjs));
}

ok('PHASE: the southern stations are in antiphase with the northern ones',
  stations.spo.peakMonth >= 8 && stations.spo.peakMonth <= 10 && stations.ptb.peakMonth >= 4 && stations.ptb.peakMonth <= 6,
  `spo peaks month ${stations.spo?.peakMonth}, ptb peaks month ${stations.ptb?.peakMonth}`);
ok('GROWTH: Point Barrow amplitude growth is detected over the full record',
  stations.ptb.t > 5 && stations.ptb.perDecade > 0.8, `${stations.ptb.perDecade?.toFixed(3)} t=${stations.ptb.t?.toFixed(1)}`);
ok('GROWTH: Alert and La Jolla are detected too',
  stations.alt.t > 2 && stations.ljo.t > 2);
ok('GROWTH: no claim of southern amplitude growth is made on a t below 3',
  stations.spo.t < 3, `spo t=${stations.spo.t?.toFixed(2)}`);

// THE PLANT. It enters as DATA. Nothing below knows.
const PLANT = { amplitude0: 5, growthPerDecade: 1, startYear: 1960, endYear: 2024 };
const plantCsv = C.syntheticStationCsv(PLANT);
const plantParsed = C.parseScrippsCsv(plantCsv);
const plantRes = C.stationResult(plantParsed, { window: null });
// What the generator planted, over exactly the years the decomposition could use. Computed
// from the generator's own parameters rather than typed, so the expectation cannot drift.
const plantExpectedMean = (() => {
  let s = 0, k = 0;
  for (let y = plantRes.span[0]; y <= plantRes.span[1]; y++) {
    s += PLANT.amplitude0 + PLANT.growthPerDecade * (y - PLANT.startYear) / 10; k++;
  }
  return s / k;
})();
ok('PLANT: the synthetic file survives the SAME parser as a real station',
  plantParsed.rows.length > 700 && !!plantParsed.stampArchive);
ok('PLANT: the decomposition recovers the planted growth of 1.000 ppm/decade',
  near(plantRes.perDecade, 1.0, 0.01), `${plantRes.perDecade?.toFixed(5)}`);
ok('PLANT: it recovers the planted mean amplitude',
  near(plantRes.meanAmplitude, plantExpectedMean, 0.01),
  `recovered ${plantRes.meanAmplitude?.toFixed(4)}, planted ${plantExpectedMean.toFixed(4)}`);
const plantFlat = C.stationResult(C.parseScrippsCsv(C.syntheticStationCsv({ amplitude0: 5, growthPerDecade: 0 })), { window: null });
ok('PLANT CONTROL: a planted station with NO growth is reported as having none',
  Math.abs(plantFlat.perDecade) < 0.01, `${plantFlat.perDecade?.toFixed(5)}`);
ok('PLANT CONTROL: a planted constant cycle recovers its exact size',
  near(plantFlat.meanAmplitude, 5.0, 0.01), `${plantFlat.meanAmplitude?.toFixed(4)}`);

/* ── 7. THE VACUOUS SETTING, which must stay vacuous ─────────────────────── */

const vac = [];
for (const [code, w] of [['mlo', [1990, 2010]], ['mlo', [2005, 2024]], ['mlo', [1985, 2010]],
  ['ptb', [1990, 2010]], ['ptb', [2005, 2024]]]) {
  const f = await grab('flask', { series: 'flask', station: code });
  if (!f.ok) continue;
  const r = C.stationResult(C.parseScrippsCsv(f.text), { window: w });
  vac.push({ code, window: w, perDecade: r.perDecade, se: r.perDecadeSe, t: r.t, n: r.n, significant: r.significant });
}
const mloVac = vac.filter((v) => v.code === 'mlo');
const ptbVac = vac.filter((v) => v.code === 'ptb');
ok('VACUOUS: at Mauna Loa, none of the three short windows detects the trend',
  mloVac.length === 3 && mloVac.every((v) => !v.significant),
  mloVac.map((v) => `${v.window.join('-')} t=${v.t?.toFixed(2)}`).join(', '));
// Point Barrow detects the trend where Mauna Loa cannot, but it is NOT immune: on fully
// measured years the 2005-2024 window leaves it 15 years and it goes quiet too. That is
// asserted rather than smoothed over, because the page now makes the point that vacuity is a
// property of the window and not only of the station.
ok('VACUOUS: at Point Barrow, the 1990-2010 window DOES detect what Mauna Loa cannot',
  ptbVac.find((v) => v.window[0] === 1990)?.significant === true,
  ptbVac.map((v) => `${v.window.join('-')} t=${v.t?.toFixed(2)}`).join(', '));
ok('VACUOUS: Point Barrow is not magic either, and the shortest window silences it too',
  ptbVac.find((v) => v.window[0] === 2005)?.significant === false,
  ptbVac.map((v) => `${v.window.join('-')} t=${v.t?.toFixed(2)}`).join(', '));
ok('VACUOUS: Point Barrow beats Mauna Loa on the window where both are measurable',
  Math.abs(ptbVac.find((v) => v.window[0] === 1990)?.t) > Math.abs(mloVac.find((v) => v.window[0] === 1990)?.t));
ok('VACUOUS: a window with too few years yields no slope rather than a wrong one',
  C.stationResult(C.parseScrippsCsv(mFeed.text), { window: [2024, 2025] }).perDecade === null);

/* ── 8. the refusal paths the reader can reach ───────────────────────────── */

ok('REFUSAL: an empty feed body parses to nothing rather than to a number',
  C.parseScrippsCsv('').rows.length === 0 && C.newestReal(C.parseScrippsCsv(''), 'co2') === null);
ok('REFUSAL: an unreadable NOAA landing page reports ok:false, not a silent zero',
  C.parseNoaaLanding('<html><body>they redesigned it</body></html>').ok === false);
ok('REFUSAL: a NOAA landing page that IS readable is read',
  !landing || landing.ok === true, landing ? JSON.stringify(landing) : 'feed down');
ok('REFUSAL: a stamp in a shape Scripps does not write returns null rather than a guess',
  C.parseScrippsStamp('2026-06-03') === null && C.parseScrippsStamp('03-Xyz-2026') === null);
ok('REFUSAL: a partial year cannot fake a small cycle',
  C.yearlyAmplitudes([{ yr: 2020, mn: 1, anomaly: 1, measured: true }, { yr: 2020, mn: 2, anomaly: -1, measured: true }]).length === 0);

/* THE FILLED-COLUMN TRAP, asserted on the REAL data path rather than on a hand-built array.
 *
 * Scripps' column 9 fills gaps from column 7, which their own header describes as a spline
 * "plus 4-harmonic functions with linear gain" — a model whose seasonal amplitude grows
 * linearly in time, which is exactly what this page measures. Because the filled column has no
 * gaps inside a station's observed span, a twelve-month rule applied to it never drops
 * anything, so the page's "partial years are dropped, not interpolated" used to be false in
 * effect: La Jolla counted 67 years of which 47 rested on fewer than twelve real observations
 * and seven contained none at all. The rule now requires MEASURED months, and these checks
 * fail if that ever regresses. */
{
  const fullYear = (yr, measured) => Array.from({ length: 12 }, (_, i) =>
    ({ yr, mn: i + 1, anomaly: i < 6 ? i : 11 - i, measured }));
  ok('FILLED TRAP: a fully MEASURED year is counted',
    C.yearlyAmplitudes(fullYear(2000, true)).length === 1);
  ok('FILLED TRAP: a fully MODELLED year is dropped, not counted',
    C.yearlyAmplitudes(fullYear(2000, false)).length === 0);
  const mixed = fullYear(2000, true); mixed[3].measured = false;
  ok('FILLED TRAP: one filled month is enough to drop the year',
    C.yearlyAmplitudes(mixed).length === 0);
}

// The four visit branches, including the wording this page leans on hardest.
const fakeStore = (init) => { const m = new Map(Object.entries(init)); return { getItem: (k) => (m.has(k) ? m.get(k) : null), setItem: (k, v) => m.set(k, v) }; };
const kit = await import('../../public/_kit/livefeed.js');
const feedStub = { ok: true, key: 'scripps-co2', upstream_last_modified: 'Wed, 03 Jun 2026 16:02:16 GMT' };
ok('VISIT: a first visit says so', kit.sinceYourLastVisit(feedStub, fakeStore({})).status === 'first');
ok('VISIT: an unchanged source is reported as unchanged',
  kit.sinceYourLastVisit(feedStub, fakeStore({ 'aw-livefeed:scripps-co2': feedStub.upstream_last_modified })).status === 'same');
ok('VISIT: a moved source is reported as moved',
  kit.sinceYourLastVisit(feedStub, fakeStore({ 'aw-livefeed:scripps-co2': 'Tue, 04 Mar 2026 09:00:00 GMT' })).status === 'moved');
ok('VISIT: with no storage the answer is "cannot tell", never "unchanged"',
  kit.sinceYourLastVisit(feedStub, null).status === 'unknown');
ok('VISIT: the "nothing new to tell you yet" wording is the one that ships',
  /nothing new to tell you yet/.test(kit.visitSentence({ status: 'same', stamp: 'x' })));
ok('PAGE: renders visitSentence rather than wording it itself',
  /visitSentence\(/.test(readFileSync(join(PAGE, 'page.js'), 'utf8')));
ok('PAGE: renders provenance(), which is mandatory in this wave',
  /provenance\(/.test(readFileSync(join(PAGE, 'page.js'), 'utf8')));
// sinceYourLastVisit RECORDS as a side effect, so calling it twice in one load tells a
// first-time reader they have been here before. The page must compute it once and cache it.
// Tests the property, not one spelling of it: the recording call is assigned in exactly one
// place and that place is guarded by the cache check.
ok('VISIT: the page computes the visit status once per load and caches it',
  /if \(!state\.seen\)/.test(pjs)
  && (pjs.match(/state\.seen = sinceYourLastVisit/g) || []).length === 1,
  `${(pjs.match(/state\.seen = sinceYourLastVisit/g) || []).length} assignments`);

/* WHICH CLOCK THE VISIT LINE RIDES.
 *
 * The page argues at length that the HTTP Last-Modified header is untrustworthy, and cites the
 * host migration that gave all seven station files a new header on one day with not one new
 * observation between them. The returning-reader sentence was nevertheless driven by that same
 * header, so a repeat of that touch would have made this page tell every reader the numbers had
 * changed while every number was identical. It now compares the archive stamp written inside
 * the file, which is the clock the page says it trusts. */
ok('VISIT: the returning-reader check rides the in-file archive stamp, not the HTTP header',
  /stampArchive/.test(pjs) && /archive-stamp/.test(pjs));
ok('VISIT: and the page names which clock answered, rather than leaving it implicit',
  /visitClock/.test(pjs));

/* ── 9. the prose, checked against the live files ────────────────────────── */

const dekLiterals = [
  ['ptb', /17\.9 parts per million at Point Barrow/, amp('ptb'), 17.9],
  ['ljo', /11\.7 at a pier/, amp('ljo'), 11.7],
  ['mlo', /7\.0 at Mauna Loa/, amp('mlo'), 7.0],
  ['spo', /1\.2 at the South Pole/, amp('spo'), 1.2],
];
for (const [code, re, live, printed] of dekLiterals) {
  ok(`PROSE: the opening paragraph still says ${printed} for ${code}`, re.test(html));
  ok(`PROSE: ${code}'s printed ${printed} still matches the live files`, near(live, printed, 0.3),
    `printed ${printed}, live ${live?.toFixed(3)}`);
}
// The wrapped entry carries the same literals to the homepage and the RSS feed, where they
// are read by people who never open the page. They get checked against the live files too.
const md = readFileSync(join(HERE, '..', '..', 'src', 'content', 'strata', `${SLUG}.md`), 'utf8');
for (const [code, re, live, printed] of [
  ['ptb', /17\.9 parts per million at Point Barrow/, amp('ptb'), 17.9],
  ['alt', /16\.1 at Alert/, amp('alt'), 16.1],
  ['ljo', /11\.7 at a pier/, amp('ljo'), 11.7],
  ['mlo', /7\.0 at Mauna Loa/, amp('mlo'), 7.0],
  ['sam', /1\.8 in Samoa/, amp('sam'), 1.8],
  ['spo', /1\.2 at the South Pole/, amp('spo'), 1.2],
]) {
  ok(`WRAPPED ENTRY: still prints ${printed} for ${code}`, re.test(md));
  ok(`WRAPPED ENTRY: ${code}'s ${printed} still matches the live files`, near(live, printed, 0.3),
    `printed ${printed}, live ${live?.toFixed(3)}`);
}
ok('WRAPPED ENTRY: the dek states the monthly cadence', /moves monthly|once a month/.test(md));
ok('WRAPPED ENTRY: no em dash', !md.includes('\u2014'));
// This said `>= 2` under a label promising four, which is a check that cannot fail for the
// reason its name gives. It counts four.
ok('WRAPPED ENTRY: declares the four relates edges', (md.match(/^\s+- to: /gm) || []).length === 4,
  `${(md.match(/^\s+- to: /gm) || []).length} edges`);

ok('PROSE: the meta description does not call this series daily or hourly',
  !/\b(daily|hourly|every day)\b/i.test((/<meta name="description" content="([^"]*)"/.exec(html) || [, ''])[1]));
ok('PROSE: the page states the monthly cadence in its own dek',
  /moves about once a month/.test(html));
ok('PROSE: no em dash in the page prose', !html.includes('—'));

/* ── 10. the forward claim, and its score ────────────────────────────────── */

const drops = C.peakToTroughDrops(monthly, { firstYear: 2010, lastYear: 2025 });
const dropStats = C.meanSd(drops.map((d) => d.drop));
const season = C.seasonSoFar(monthly, newest.yr);
const predictedMin = season ? season.peakValue - dropStats.mean : null;
ok('CLAIM: the method has at least 12 complete years behind it', drops.length >= 12, `${drops.length}`);
ok('CLAIM: the predicted minimum is below this year\'s peak', predictedMin < season.peakValue);
ok('CLAIM: the trough month is September more often than October',
  drops.filter((d) => d.troughMonth === 9).length > drops.filter((d) => d.troughMonth === 10).length);

// THE CLAIM AS SHIPPED, fixed on 2026-08-15 and not allowed to move.
const SHIPPED_CLAIM = {
  stated_on: '2026-08-15',
  scale: 'Scripps 2012 SIO manometric mole fraction scale, monthly_in_situ_co2_mlo.csv column 5',
  year: 2026,
  predicted_min_ppm: 425.93,
  tolerance_ppm: 0.50,
  predicted_trough_month: 9,
  month_confidence: 0.69,
  from: { peak_month: 5, peak_ppm: 432.00, mean_drop: 6.069, sd: 0.497, n_years: 16 },
};
// Score it the moment the data can score it, and record the outcome either way.
let claimScore = { status: 'pending', reason: 'the 2026 autumn trough is not published yet' };
const y2026 = C.realRows(monthly, 'co2').filter((r) => r.yr === SHIPPED_CLAIM.year);
const autumnPublished = y2026.some((r) => r.mn >= 10);
if (autumnPublished) {
  let trough = y2026[0];
  for (const r of y2026) if (r.co2 < trough.co2) trough = r;
  const err = trough.co2 - SHIPPED_CLAIM.predicted_min_ppm;
  claimScore = {
    status: 'scored',
    observed_min_ppm: trough.co2, observed_month: trough.mn,
    value_error_ppm: err,
    value_held: Math.abs(err) <= SHIPPED_CLAIM.tolerance_ppm,
    month_held: trough.mn === SHIPPED_CLAIM.predicted_trough_month,
    months_published: y2026.map((r) => r.mn),
  };
}
ok('CLAIM: the shipped claim is scored or explicitly pending, never quietly dropped',
  claimScore.status === 'scored' || claimScore.status === 'pending');

// A check that cannot fail is not a check. The first version of this line asserted `true` with a
// comment saying the drift was recorded below, which tested nothing. The drift is a real number
// and gets a real assertion. It is pinned to the CLAIM's year rather than to the newest year in
// the file, so it keeps meaning the same thing after 2026 ends.
const claimSeason = C.seasonSoFar(monthly, SHIPPED_CLAIM.year);
const claimRecomputed = claimSeason ? claimSeason.peakValue - dropStats.mean : null;
const claimDrift = claimRecomputed === null ? null : claimRecomputed - SHIPPED_CLAIM.predicted_min_ppm;
ok('CLAIM: the peak the shipped claim was built on is still the peak in the file',
  !!claimSeason && claimSeason.peakMonth === SHIPPED_CLAIM.from.peak_month,
  claimSeason ? `peak now ${claimSeason.peakMonth} at ${claimSeason.peakValue}` : 'no rows for the claim year');
ok('CLAIM: the shipped prediction is still what this same code recomputes from the live file',
  claimDrift !== null && Math.abs(claimDrift) <= SHIPPED_CLAIM.tolerance_ppm,
  `drift ${claimDrift === null ? 'n/a' : claimDrift.toFixed(3)} ppm, tolerance ${SHIPPED_CLAIM.tolerance_ppm}`);
ok('CLAIM: the number of complete years behind the method has not silently changed',
  dropStats.n === SHIPPED_CLAIM.from.n_years, `${dropStats.n} years, shipped with ${SHIPPED_CLAIM.from.n_years}`);

/* THE CLAIM MUST NOT RE-AIM ITSELF.
 *
 * The page read the claim's year off the newest row in the live file, so a file that had
 * reached 2027 made it print "The 2027 seasonal minimum will be ..." underneath the sentence
 * "It is stated on 15 August 2026, before the data exists" and above "it does not get to
 * move". The shipped claim simply disappeared and a new one wore its dateline. The year and
 * the window are constants in page.js now, and these assertions are what keep them constant. */
ok('CLAIM: the page pins the claim year to a constant, not to the newest row in the file',
  /const CLAIM = \{/.test(pjs) && new RegExp(`year: ${SHIPPED_CLAIM.year}\\b`).test(pjs),
  'page.js must carry a CLAIM constant naming the shipped year');
ok('CLAIM: the page no longer derives the claim year from the data',
  !/year: newest\.yr/.test(pjs));
ok('CLAIM: the page\'s claim window matches the one the shipped claim was built from',
  /firstYear: 2010/.test(pjs) && /lastYear: 2025/.test(pjs));
ok('CLAIM: the page scores the claim once the data can score it, rather than restating it',
  /autumnPublished/.test(pjs) && /valueHeld/.test(pjs));
// The page must carry the shipped FIGURE frozen too, and score against it. Scoring against a
// live recomputation would let the claim follow the data and then declare itself correct.
ok('CLAIM: the page freezes the shipped figure and tolerance, matching this verifier',
  new RegExp(`predictedMinPpm: ${SHIPPED_CLAIM.predicted_min_ppm}`).test(pjs)
  && new RegExp(`tolerancePpm: ${SHIPPED_CLAIM.tolerance_ppm.toFixed(2)}`).test(pjs),
  'page.js CLAIM must carry the same frozen figure the record does');
ok('CLAIM: the score is taken against the frozen figure, not the live recomputation',
  /error: trough\.co2 - CLAIM\.predictedMinPpm/.test(pjs));

/* ── 11. the record ──────────────────────────────────────────────────────── */

function report(line) {
  const total = pass + failures.length;
  for (const f of failures) console.error(`FAIL  ${f}`);
  console.log(`\n${pass}/${total} checks passed for ${SLUG}${failures.length ? `, ${failures.length} FAILED` : ''}.`);
  if (line) console.log(`record: ${RECORD}`);
}

const line = {
  run_at: now.toISOString(),
  slug: SLUG,
  route: via.route || 'unknown',
  notes: via.notes,
  pass, fail: failures.length,
  failures: failures.slice(0, 12),
  scripps: {
    monthly_stamp_archive: monthly.stampArchive,
    monthly_stamp_through: monthly.stampThrough,
    monthly_stamp_age_days: archiveAge === null ? null : +archiveAge.toFixed(2),
    http_last_modified: mFeed.upstream_last_modified || null,
    newest_month: `${newest.yr}-${String(newest.mn).padStart(2, '0')}`,
    newest_ppm: newest.co2,
    newest_site: newest.sta,
    newest_age_days: +fresh.ageDays.toFixed(2),
    fresh_verdict: fresh.verdict,
    weekly_stamp_archive: weekly ? weekly.stampArchive : null,
    newest_week: weekly ? (weekly.rows.filter((r) => r.ppm !== null).slice(-1)[0] || null) : null,
    year_peak_month: season ? season.peakMonth : null,
    year_peak_ppm: season ? season.peakValue : null,
    drawdown_so_far_ppm: season ? +season.drawdownSoFar.toFixed(3) : null,
    drawdown_is_published: season ? season.hasPostPeak : null,
  },
  noaa: landing && landing.ok ? {
    month: landing.month, ppm: landing.ppm, last_updated: landing.lastUpdated,
    prior_year_month: landing.priorYearMonth, prior_year_ppm: landing.priorYearPpm,
    months_ahead_of_scripps: (() => {
      const m = /([A-Z][a-z]+)\s+(\d{4})/.exec(landing.month || '');
      if (!m) return null;
      const mi = C.MONTH_NAMES.indexOf(m[1]);
      return mi < 0 ? null : (+m[2] * 12 + mi) - (newest.yr * 12 + (newest.mn - 1));
    })(),
    same_month_offset_ppm: null,
    offset_note: "The month-by-month Scripps minus NOAA offset is NOT computed. NOAA's monthly file is under gml.noaa.gov/webdata/, which robots.txt disallows and this project does not fetch. When the landing page's month coincides with Scripps' newest month, same_month_offset_ppm is filled in; otherwise it stays null rather than comparing two different months.",
  } : { error: lFeed.error || 'unparseable' },
  anchor: {
    published_years: snapshot.table.length,
    compared: anchor.n,
    mae: +anchor.mae.toFixed(5),
    max: +anchor.max.toFixed(4),
    within_0_1: anchor.within(0.1),
    within_0_2: anchor.within(0.2),
    independent_from: SPLICE_END,
    independent_n: post.length,
    independent_mae: +postMae.toFixed(5),
    spliced_n: pre.length,
    spliced_mae: +preMae.toFixed(5),
    recent: anchor.pairs.slice(-2).map((p) => ({ year: p.year, published: p.published, computed: +p.computed.toFixed(4), error: +p.error.toFixed(4) })),
    unfilled_mae: +anchorUnfilled.mae.toFixed(5),
    alternatives_that_miss: alts,
    snapshot_sha256: snapshot.sha256,
    snapshot_age_days: +snapAge.toFixed(2),
  },
  trap: (() => {
    const src = trapLive && Number.isFinite(trapLive.ageDays) ? trapLive : trapGate;
    const num = (v) => (Number.isFinite(v) ? +v.toFixed(1) : null);
    return {
      live_fetched: !!trapLive,
      data_age_days: num(src.ageDays),
      header_lead_days: num(src.headerLeadDays),
      refused: (trapLive ? !trapLive.ok : true) && !trapGate.ok,
    };
  })(),
  stations,
  plant: {
    growth_planted: PLANT.growthPerDecade, growth_recovered: +plantRes.perDecade.toFixed(6),
    amplitude_planted: +plantExpectedMean.toFixed(5), amplitude_recovered: +plantRes.meanAmplitude.toFixed(5),
    flat_planted: 0.0, flat_recovered: +plantFlat.perDecade.toFixed(6),
    flat_amplitude_planted: 5.0, flat_amplitude_recovered: +plantFlat.meanAmplitude.toFixed(5),
  },
  vacuous: vac.map((v) => ({ ...v, perDecade: v.perDecade === null ? null : +v.perDecade.toFixed(4), se: v.se === null ? null : +v.se.toFixed(4), t: v.t === null ? null : +v.t.toFixed(3) })),
  forward_claim: {
    ...SHIPPED_CLAIM,
    today: {
      peak_month: claimSeason ? claimSeason.peakMonth : null,
      peak_ppm: claimSeason ? claimSeason.peakValue : null,
      mean_drop: +dropStats.mean.toFixed(4),
      sd: +dropStats.sd.toFixed(4),
      n_years: dropStats.n,
      recomputed_min_ppm: claimRecomputed === null ? null : +claimRecomputed.toFixed(3),
      sep_count: drops.filter((d) => d.troughMonth === 9).length,
      oct_count: drops.filter((d) => d.troughMonth === 10).length,
    },
    claim_drift_ppm: claimDrift === null ? null : +claimDrift.toFixed(3),
    score: claimScore,
  },
};

if (!NO_RECORD) appendFileSync(RECORD, JSON.stringify(line) + '\n');
report(NO_RECORD ? null : line);   // report() names the record file only when it wrote to it
process.exit(failures.length ? 1 : 0);
