#!/usr/bin/env node
/* verify-six-months-behind-the-sun.mjs
 *
 * Recomputes every number the page shows, by importing the page's OWN arithmetic module
 * (public/strata/six-months-behind-the-sun/sunspots.js) unchanged. There is deliberately
 * no second implementation of the smoother in here: a verifier that re-derives the answer
 * its own way can agree with the page while both are wrong about what the page ships.
 * What this file adds is independence of SOURCE (it fetches the upstreams directly, not
 * through our worker) and independence of BRANCH (it asserts the refusal paths, which a
 * reader with a working network never sees).
 *
 * Usage:
 *   node research/six-months-behind-the-sun/verify-six-months-behind-the-sun.mjs
 *   ... --no-write     run the checks, do not append to record.jsonl
 *   ... --quiet        only the summary line
 *
 * Exits 0 only if every check passes. Appends one JSON object to record.jsonl on every
 * run, pass or fail, including the outcome of the page's two dated forward claims.
 */

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

const HERE = dirname(fileURLToPath(import.meta.url));
const ROOT = join(HERE, '..', '..');
const RECORD = join(HERE, 'record.jsonl');

const SS = await import(join(ROOT, 'public/strata/six-months-behind-the-sun/sunspots.js'));

const ARGS = process.argv.slice(2);
const NO_WRITE = ARGS.includes('--no-write');
const QUIET = ARGS.includes('--quiet');

// The four upstreams, and the ONLY four. These are exactly the entries this page is
// allowlisted for in worker.js. robots.txt evidence for both hosts, with the UTC time it
// was read, is in ./README.md; neither host disallows these paths.
const UPSTREAMS = {
  'silso-monthly': 'https://www.sidc.be/SILSO/DATA/SN_m_tot_V2.0.csv',
  'silso-smoothed': 'https://www.sidc.be/SILSO/DATA/SN_ms_tot_V2.0.csv',
  'swpc-solar-cycle-observed': 'https://services.swpc.noaa.gov/json/solar-cycle/observed-solar-cycle-indices.json',
  'swpc-solar-cycle-predicted': 'https://services.swpc.noaa.gov/json/solar-cycle/solar-cycle-25-predicted.json',
};
const UA = 'artwaste.land verifier (non-commercial research archive; hello@artwaste.land)';

// ── a check harness that counts, and that cannot pass by not running ──────────────
let passed = 0;
const failures = [];
function check(name, cond, detail) {
  if (cond) { passed++; if (!QUIET) console.log(`  ok   ${name}${detail ? '  [' + detail + ']' : ''}`); }
  else { failures.push({ name, detail: detail || '' }); console.log(`  FAIL ${name}  ${detail || ''}`); }
}
const near = (a, b, tol) => a !== null && a !== undefined && Math.abs(a - b) <= tol;

// ── fetch ─────────────────────────────────────────────────────────────────────────
async function pull(url) {
  const res = await fetch(url, { headers: { 'User-Agent': UA } });
  if (!res.ok) throw new Error(`HTTP ${res.status} for ${url}`);
  const ctype = res.headers.get('content-type') || '';
  const body = await res.text();
  const out = {
    ok: true, upstream: url,
    upstream_last_modified: res.headers.get('last-modified'),
    fetched_at: new Date().toISOString(),
    content_type: ctype, bytes: Buffer.byteLength(body),
  };
  if (ctype.includes('json')) out.data = JSON.parse(body); else out.text = body;
  return out;
}

const runAt = new Date().toISOString();
// The month this machine thinks it is, passed into buildReport exactly as the page passes
// the reader's. It is the one input that does not come from the bytes, and it is what makes
// "the source stopped publishing" a detectable state rather than an invisible one.
const NOW_YM = runAt.slice(0, 7);
if (!QUIET) console.log(`six-months-behind-the-sun verifier, ${runAt}\n`);

// Declared before the first possible call to finish(). They used to be `const`s several
// hundred lines below it, so the refusal path threw a ReferenceError instead of writing
// its refusal line to the record: a branch that could only run by crashing.
let scoredClaims = [];
let revisions = [];

let feeds;
try {
  const keys = Object.keys(UPSTREAMS);
  const got = await Promise.all(keys.map((k) => pull(UPSTREAMS[k])));
  feeds = Object.fromEntries(keys.map((k, i) => [k, got[i]]));
} catch (e) {
  console.error(`\nCould not fetch the sources: ${e.message}`);
  console.error('This verifier deliberately has no offline fallback. A cached copy would let it');
  console.error('pass while the live page was broken, which is the one failure mode it exists to');
  console.error('prevent. Re-run it with a network.');
  process.exit(2);
}

// ── 1. THE ANCHOR ────────────────────────────────────────────────────────────────
// SILSO's own article: the Cycle 25 maximum "was reached in October 2024 and is 161 ...
// versus 159 for September and 157 for November 2024". Those are the three published,
// dated figures this instrument has to reproduce before it says anything unpublished.
const rep = SS.buildReport(feeds, { nowYm: NOW_YM });
check('report builds from live bytes', rep.ok === true, rep.ok ? '' : rep.refusal);
if (!rep.ok) { finish(null); }

check('SILSO monthly file parsed', rep.counts.monthlyRows > 3000, `${rep.counts.monthlyRows} rows`);
check('SILSO smoothed file parsed', rep.counts.smoothedRows > 3000, `${rep.counts.smoothedRows} rows`);
check('no unparseable lines', rep.counts.parseErrors === 0, `${rep.counts.parseErrors} rejected`);

const spot = Object.fromEntries(rep.spots.map((s) => [s.ym, s]));
check('ANCHOR 2024-10 rounds to SILSO published 161', spot['2024-10'] && spot['2024-10'].whole === 161,
  spot['2024-10'] ? `ours ${spot['2024-10'].ours.toFixed(5)}` : 'missing');
check('ANCHOR 2024-09 rounds to SILSO published 159', spot['2024-09'] && spot['2024-09'].whole === 159,
  spot['2024-09'] ? `ours ${spot['2024-09'].ours.toFixed(5)}` : 'missing');
check('ANCHOR 2024-11 rounds to SILSO published 157', spot['2024-11'] && spot['2024-11'].whole === 157,
  spot['2024-11'] ? `ours ${spot['2024-11'].ours.toFixed(5)}` : 'missing');
for (const ym of ['1958-03', '2014-04', '2024-09', '2024-10', '2024-11']) {
  const s = spot[ym];
  check(`ANCHOR ${ym} matches SILSO's own smoothed file to 0.1`, s && near(s.ours, s.published, 0.1),
    s ? `ours ${s.ours.toFixed(4)} vs published ${s.published}` : 'missing');
}
check('every published smoothed month reproduced', rep.anchor.disagreements.length === 0,
  `${rep.anchor.compared} compared, ${rep.anchor.disagreements.length} disagreements above ${rep.anchor.tol}`);
// SILSO publishes to one decimal, so a full-precision recomputation can differ from the
// printed value by at most half of the last digit. Anything above that would be a real
// disagreement about the arithmetic rather than about how many digits to print.
check('largest single difference is SILSO rounding, not a discrepancy', rep.anchor.maxAbsDiff <= 0.0500001,
  `max ${rep.anchor.maxAbsDiff.toFixed(6)}, and half of SILSO's last printed digit is 0.05`);
check('the comparison covered thousands of months, not a handful', rep.anchor.compared > 3000,
  `${rep.anchor.compared}`);

// ── 2. THE DIFFERENTIAL CONTROL ──────────────────────────────────────────────────
// The plant goes into the DATA ARRAY the smoother iterates, inside buildReport, before
// any comparison runs. Nothing is appended to a result list. If the comparator cannot be
// made to fail, its agreement means nothing.
{
  const doctored = SS.buildReport(feeds, { nowYm: NOW_YM, inject: { ym: '2024-04', delta: 10 } });
  check('CONTROL a planted +10 in 2024-04 is caught by the same comparator',
    doctored.ok && doctored.anchor.disagreements.length > 0,
    `${doctored.anchor.disagreements.length} disagreements appear`);
  check('CONTROL the plant reaches the headline maximum too, not just the comparator',
    doctored.settled && !near(doctored.settled.value, rep.settled.value, 1e-9),
    `clean ${rep.settled.value.toFixed(4)} vs doctored ${doctored.settled.value.toFixed(4)}`);
  check('CONTROL a plant far from the forward window leaves the forward constant alone',
    doctored.forward && rep.forward && near(doctored.forward.constant, rep.forward.constant, 1e-12),
    'the plant propagates exactly 6 months either side, and no further');
  // A plant INSIDE the forward claim's own 13-term window must move its pinned constant,
  // and by exactly the weight that month carries: 2026-01 sits one month from 2026-02, so
  // it enters with weight 1 out of 12.
  {
    const inWindow = SS.buildReport(feeds, { nowYm: NOW_YM, inject: { ym: rep.forward.targetYm, delta: 12 } });
    check('CONTROL a plant inside the forward window moves the pinned constant by its exact weight',
      inWindow.forward && near(inWindow.forward.constant - rep.forward.constant, 12 / 12, 1e-9),
      `moved by ${(inWindow.forward.constant - rep.forward.constant).toFixed(6)} for a plant of 12 at weight 1/12`);
  }
  check('CONTROL one wrong month corrupts thirteen smoothed values',
    doctored.anchor.disagreements.length >= 12 && doctored.anchor.disagreements.length <= 13,
    `${doctored.anchor.disagreements.length}`);
  const tiny = SS.buildReport(feeds, { nowYm: NOW_YM, inject: { ym: '2024-04', delta: 0.5 } });
  check('CONTROL a sub-tolerance plant of +0.5 is correctly NOT flagged',
    tiny.ok && tiny.anchor.disagreements.length === 0,
    'the comparator is not merely noisy');
  const clean = SS.buildReport(feeds, { nowYm: NOW_YM, inject: { ym: '2024-04', delta: 0 } });
  check('CONTROL a zero-magnitude plant leaves the report identical',
    clean.anchor.disagreements.length === 0 && near(clean.settled.value, rep.settled.value, 1e-12), '');
}

// ── 3. THE REFUSAL PATHS ─────────────────────────────────────────────────────────
// The half a reader with a working network never sees, and therefore the half most likely
// to be a lie. Each is asserted through the same buildReport the page renders.
{
  const down = SS.buildReport({ ...feeds, 'silso-monthly': { ok: false, error: 'http_502' } });
  check('REFUSAL one dead feed refuses the whole report', down.ok === false && down.refusal === 'feeds unavailable', down.refusal);
  check('REFUSAL the refusal names the dead key', /silso-monthly/.test(down.sentence), '');
  check('REFUSAL the refusal carries no numbers at all',
    down.anchor === undefined && down.settled === undefined && down.forward === undefined, '');

  const allDown = SS.buildReport({});
  check('REFUSAL every feed dead still refuses cleanly', allDown.ok === false && allDown.missing.length === 4, '');

  const junk = SS.buildReport({ ...feeds, 'silso-smoothed': { ok: true, text: 'not,a,silso,file\n\n' } });
  check('REFUSAL a well-formed response with the wrong shape refuses',
    junk.ok === false && junk.refusal === 'source unparseable', junk.refusal);

  // The other host gets the same treatment, and it needs it more: NOAA can answer 200 with
  // an empty array or a renamed field, and a page that carried on would print a cross-host
  // agreement measured over zero months.
  const emptyObs = SS.buildReport({ ...feeds, 'swpc-solar-cycle-observed': { ok: true, data: [] } }, { nowYm: NOW_YM });
  check('REFUSAL an empty NOAA observed file refuses instead of agreeing about nothing',
    emptyObs.ok === false && emptyObs.refusal === 'source unparseable', emptyObs.refusal || 'built anyway');
  const renamed = SS.buildReport({
    ...feeds,
    'swpc-solar-cycle-observed': { ok: true, data: feeds['swpc-solar-cycle-observed'].data.map((r) => { const c = { ...r, timetag: r['time-tag'] }; delete c['time-tag']; return c; }) },
  }, { nowYm: NOW_YM });
  check('REFUSAL a renamed time-tag field refuses rather than parsing to nothing',
    renamed.ok === false && renamed.refusal === 'source unparseable', renamed.refusal || 'built anyway');
  const emptyPred = SS.buildReport({ ...feeds, 'swpc-solar-cycle-predicted': { ok: true, data: [] } }, { nowYm: NOW_YM });
  check('REFUSAL an empty NOAA forecast file refuses too',
    emptyPred.ok === false && emptyPred.refusal === 'source unparseable', emptyPred.refusal || 'built anyway');

  // THE STALE SOURCE. Everything else this verifier checks is internal, and a frozen
  // publisher passes all of it: both files stop together, the lag stays at six months, the
  // smoother still reproduces every published value. Only the clock can catch it, so the
  // clock is an input and this is its negative control.
  check('CLOCK the live data is not stale against this machine\'s clock',
    rep.clock && rep.clock.monthsBehind !== null && rep.clock.monthsBehind <= rep.clock.staleAfter,
    rep.clock ? `newest monthly ${rep.clock.newestMonthlyYm} is ${rep.clock.monthsBehind} months behind ${rep.clock.nowYm}` : 'no clock reading');
  const frozen = SS.buildReport(feeds, { nowYm: SS.ymAdd(NOW_YM, 12) });
  check('CLOCK the same bytes a year later are refused as stale',
    frozen.ok === false && frozen.refusal === 'source stale',
    frozen.ok ? 'built a report from a year-old source' : `${frozen.clock.monthsBehind} months behind`);
  const stillFresh = SS.buildReport(feeds, { nowYm: SS.ymAdd(NOW_YM, 1) });
  check('CLOCK and one month later is NOT refused, so the guard is not merely trigger-happy',
    stillFresh.ok === true, stillFresh.ok ? '' : stillFresh.refusal);

  // The fetch layer sits in page.js, which cannot be imported here (it needs a DOM), so
  // this is a source-level assertion rather than an executed one, and it is named as such:
  // fetchFeed converts an HTTP error into a refusal object but REJECTS on a network-level
  // failure, and an unhandled rejection there kills the page before the refusal can render.
  const pageSrc = readFileSync(join(ROOT, 'public/strata/six-months-behind-the-sun/page.js'), 'utf8');
  check('SOURCE CHECK page.js catches a rejected fetch so the refusal path can still render',
    /fetchFeed\(k\)\.catch\(/.test(pageSrc) && /\)\(\)\.catch\(/.test(pageSrc),
    'both the per-feed rejection and a throw during rendering are caught');

  // And the case that matters most for a page that promises movement: the source has NOT
  // moved. buildReport is deterministic in its inputs, so identical bytes must give an
  // identical report. If they did not, the page's "nothing has changed" line would be a lie.
  const again = SS.buildReport(feeds, { nowYm: NOW_YM });
  check('REFUSAL identical bytes give an identical report (so "nothing has changed" is checkable)',
    JSON.stringify(stable(again)) === JSON.stringify(stable(rep)), '');
}

// ── 4. THE FRONTIER AND THE SENTINEL ─────────────────────────────────────────────
check('the smoothed frontier lags the monthly series by exactly six months',
  rep.frontier.lagMonths === 6, `${rep.frontier.lagMonths} months`);
check('SILSO leaves exactly six months at the sentinel after its frontier',
  rep.frontier.blanksAfter.length === 6, rep.frontier.blanksAfter.join(','));
check('the record also opens with six sentinel months, for the same reason',
  rep.frontier.blanksBefore.length === 6, rep.frontier.blanksBefore.join(','));
check('the sentinel was never read as a value of -1 sunspots',
  rep.provisional.every((p) => p.knownSum > 0 && p.pinned > 0), '');
for (const p of rep.provisional) {
  check(`provisional ${p.ym} has a known window weight below 12`, p.knownWeight < 12 && p.knownWeight > 0,
    `${p.knownWeight} of 12, waiting on ${p.missing.map((m) => m.ym).join(',')}`);
  check(`provisional ${p.ym} pinned value is a floor, not an estimate`, p.pinned <= p.mean + 1e-9,
    `pinned ${p.pinned.toFixed(3)} <= mean ${p.mean.toFixed(3)}`);
}

// ── 5. THE MOVING MAXIMUM ────────────────────────────────────────────────────────
check('the Cycle 25 maximum settles in October 2024', rep.settled && rep.settled.ym === '2024-10',
  rep.settled ? `${rep.settled.ym} = ${rep.settled.value.toFixed(4)}` : 'none');
check('the settled maximum is 160.9 to one decimal', near(rep.settled.value, 160.9, 0.05),
  rep.settled.value.toFixed(4));
// EXACTLY twelve, not "at least ten". The page prints the word "twelve" in its dek, its
// meta description, its OG and Twitter cards, its JSON-LD and the corpus summary, and a
// loose lower bound here would let a SILSO revision move the measurement to eleven or
// thirteen while every one of those surfaces went on saying twelve and this file stayed
// green. If this check fails, the prose is what needs changing.
check('the announced maximum moved on exactly twelve consecutive monthly updates, as the shipped prose says',
  rep.streak && rep.streak.moves.length === 12, `${rep.streak.moves.length} consecutive moves`);
check('every step of that run was upward', rep.streak.moves.every((m, i, a) => i === 0 || m.argmaxValue > a[i - 1].argmaxValue), '');
// The last move IS the settle, so eleven announcements were later overtaken and the
// twelfth was right. The page used to say all twelve were wrong; this is the check that
// keeps it from saying so again.
check('the last move in the run is the one that landed on the settled month',
  rep.streak.moves[rep.streak.moves.length - 1].argmaxYm === rep.settled.ym,
  `${rep.streak.moves[rep.streak.moves.length - 1].argmaxYm} = ${rep.settled.ym}`);
check('and exactly eleven announcements before it named a month that did not hold',
  rep.streak.moves.slice(0, -1).every((m) => m.argmaxYm !== rep.settled.ym)
  && rep.streak.moves.length - 1 === 11,
  `${rep.streak.moves.length - 1} superseded announcements, then the twelfth stuck`);
// The page says those eleven were "too low and too early every time". Upward was already
// asserted; earlier was not, and half a shipped sentence pinned is the pattern this file is
// supposed to be free of.
check('and each of the eleven named a month EARLIER than the one that stuck, as the page says',
  rep.streak.moves.slice(0, -1).every((m) => m.argmaxYm < rep.settled.ym && m.argmaxValue < rep.settled.value),
  'too low and too early, both halves measured');
check('the run began from a state where the maximum had STALLED',
  rep.streak.startedFrom && rep.streak.startedFrom.argmaxYm !== rep.streak.moves[0].argmaxYm, 'so "it moves every month" is also false');
check('the maximum has held still since it settled', rep.streak.heldFor >= 12,
  `${rep.streak.heldFor} monthly updates without moving`);
check('the replay never announces a month it could not have smoothed yet',
  rep.replay.every((s) => s.argmaxYm <= s.smoothableTo && SS.ymDiff(s.dataThrough, s.smoothableTo) === 6), '');

// ── 6. THE SECOND HOST ───────────────────────────────────────────────────────────
check('NOAA republishes SILSO\'s monthly number identically',
  rep.swpc.crossHost.disagreements.length === 0,
  `${rep.swpc.crossHost.compared} months, max diff ${rep.swpc.crossHost.maxAbsDiff}`);
check('the 2019 panel forecast peaks at 115.267 in 2025-07, out of NOAA\'s own file',
  rep.swpc.panelPeak && rep.swpc.panelPeak.ym === '2025-07' && near(rep.swpc.panelPeak.value, 115.267, 0.001),
  rep.swpc.panelPeak ? `${rep.swpc.panelPeak.value} at ${rep.swpc.panelPeak.ym}` : 'missing');
check('SWPC\'s own smoothed number peaks in the same month as SILSO\'s',
  rep.swpc.peaks['swpc-smoothed'].ym === rep.settled.ym,
  `${rep.swpc.peaks['swpc-smoothed'].value} vs ${rep.settled.value.toFixed(1)}`);
check('the smoothed 10.7 cm radio flux peaks in the same month too',
  rep.swpc.peaks['f107-smoothed'].ym === rep.settled.ym, `${rep.swpc.peaks['f107-smoothed'].value} sfu`);
check('the two official smoothed sunspot numbers differ by more than 4 percent at the peak',
  Math.abs(rep.settled.value / rep.swpc.peaks['swpc-smoothed'].value - 1) > 0.04,
  `${(rep.settled.value / rep.swpc.peaks['swpc-smoothed'].value * 100 - 100).toFixed(1)}%`);
check('and the ratio between them is not a constant',
  (() => {
    const ms = rep.swpc.drift.filter((d) => d.median !== null).map((d) => d.median);
    return ms.length >= 3 && (Math.max(...ms) / Math.min(...ms) - 1) > 0.05;
  })(),
  rep.swpc.drift.map((d) => `${d.from}:${d.median === null ? 'n/a' : d.median.toFixed(4)}`).join(' '));
check('the monthly peak is a different month from the smoothed peak',
  rep.swpc.peaks['silso-monthly'].ym !== rep.settled.ym,
  `monthly ${rep.swpc.peaks['silso-monthly'].value} in ${rep.swpc.peaks['silso-monthly'].ym}`);

// ── 7. THE SCOREBOARD, INCLUDING WHAT IT REFUSES ────────────────────────────────
const cell = (o, f) => rep.matrix.find((m) => m.observedId === o && m.forecastId === f);
{
  const c = cell('silso-smoothed', 'panel-2019');
  check('the 2019 panel is scored in its own currency', c.verdict === 'scored', c.verdict);
  check('the 2019 panel missed high by about 40 percent', near(c.error, 0.396, 0.01), `${(c.error * 100).toFixed(1)}%`);
  check('the observed maximum is outside the panel\'s published 105 to 125 band', c.inBand === false, '');

  const n = cell('silso-smoothed', 'noaa-2023');
  check('NOAA\'s 2023 revision is scored on containment, not an invented midpoint',
    n.verdict === 'band only' && n.forecastPeak === null, n.verdict);
  check('and the observed maximum landed INSIDE its 137 to 173 range', n.inBand === true, '');
  check('and INSIDE its January to October 2024 window', n.monthInWindow === true, '');

  const b = cell('silso-smoothed', 'bhowmik-nandy-2018');
  check('a yearly-mean forecast is refused against a smoothed series', b.verdict === 'refused' && b.reason === 'statistic mismatch', b.reason);
  check('and the refusal prices the mistake it declined to make', typeof b.wouldHavePrinted === 'number',
    `would have printed ${(b.wouldHavePrinted * 100).toFixed(1)}%`);
  check('and it names the file it would have needed', /SN_y_tot/.test(b.detail), '');

  const u = cell('f107-smoothed', 'panel-2019');
  check('a cross-unit pairing prints no percentage at all', u.verdict === 'refused' && u.reason === 'different units' && u.wouldHavePrinted === null, '');

  // McIntosh et al. 2020 quote an amplitude of SSN=233 without naming the statistic in that
  // sentence. Footnote 1 of the same paper names it: "Throughout, we quote the smoothed
  // sunspot number for maxima". So it is scored, in that currency, and the tempting
  // "ambiguous, score it both ways" reading is the one thing this page must not do, because
  // the other reading is 23 points of percentage kinder to the forecast.
  const a1 = cell('silso-smoothed', 'mcintosh-2020');
  const a2 = cell('silso-monthly', 'mcintosh-2020');
  check('McIntosh 2020 is scored in the statistic its own footnote names, not called ambiguous',
    a1.verdict === 'scored' && a1.forecastStatistic === 'smoothed-ssn', a1.verdict);
  check('and it missed high by about 31 percent against the smoothed maximum', near(a1.error, -0.309, 0.01),
    `${(a1.error * 100).toFixed(1)}%`);
  check('and the observed maximum is OUTSIDE its own 204 to 254 band', a1.inBand === false, '');
  check('the wrong-currency pairing is refused rather than scored', a2.verdict === 'refused' && a2.reason === 'statistic mismatch', a2.reason);
  check('and the refusal prices exactly how much the wrong currency would have flattered it',
    typeof a2.wouldHavePrinted === 'number' && a2.wouldHavePrinted - a1.error > 0.2,
    `refused ${(a2.wouldHavePrinted * 100).toFixed(1)}% against the monthly peak versus the honest ${(a1.error * 100).toFixed(1)}%`);
  check('and that flattering reading would have put the forecast INSIDE the band it actually missed',
    rep.swpc.peaks['silso-monthly'].value >= 204 && rep.swpc.peaks['silso-monthly'].value <= 254,
    `monthly peak ${rep.swpc.peaks['silso-monthly'].value} sits inside 204 to 254; the smoothed maximum ${rep.settled.value.toFixed(1)} does not`);

  // The revision. Scoring the 2020 statement without it would imply the authors never moved.
  const rv = cell('silso-smoothed', 'mcintosh-2023');
  check('the same authors\' 2023 downward revision is on the scoreboard too',
    rv && rv.verdict === 'scored' && rv.forecastPeak === 184, rv ? rv.verdict : 'missing');
  check('the revision cut the miss by more than half but still landed outside its own 167 to 201 band',
    Math.abs(rv.error) < Math.abs(a1.error) / 2 + 0.02 && rv.inBand === false,
    `${(rv.error * 100).toFixed(1)}% versus ${(a1.error * 100).toFixed(1)}% for the 2020 statement`);

  // The statistic decides every verdict above, so every forecast has to say where its
  // statistic came from, including the one whose own release does not name it.
  check('every forecast on the scoreboard carries the evidence for which statistic it is in',
    SS.FORECASTS.every((f) => typeof f.statisticBasis === 'string' && f.statisticBasis.length > 80),
    `${SS.FORECASTS.length} forecasts, all with a stated basis`);
  check('and the one whose release does not name its own statistic says so',
    /never says "smoothed"/.test(SS.FORECASTS.find((f) => f.id === 'noaa-2023').statisticBasis), '');

  const scoredCells = rep.matrix.filter((m) => m.verdict === 'scored' || m.verdict === 'band only');
  check('most pairings the reader can select refuse to produce a headline number',
    scoredCells.length < rep.matrix.length / 2, `${scoredCells.length} of ${rep.matrix.length} produce one`);
  check('every scored cell has matching statistics on both sides',
    scoredCells.every((m) => m.observedStatistic === m.forecastStatistic), '');
}

// ── 8. THE FORWARD CLAIM, and its arithmetic ────────────────────────────────────
const fw = rep.forward;
check('there is a forward claim to make', !!fw, fw ? fw.targetYm : 'none');
check('the forward target is the first month SILSO left blank', fw.targetYm === rep.frontier.blanksAfter[0], fw.targetYm);
check('exactly one term of its 13-term window is still missing', fw.terms.length === 1, fw.terms.map((t) => t.ym).join(','));
check('that term enters with coefficient 1/24', near(fw.terms[0].coefficient, 1 / 24, 1e-12),
  `${fw.terms[0].coefficient}`);
check('the pinned constant equals the known sum over 12', near(fw.constant, fw.knownSum / 12, 1e-12),
  `${fw.knownSum} / 12 = ${fw.constant.toFixed(5)}`);
check('the bracket for a monthly mean of 40 to 140 is under 4.2 sunspots wide',
  fw.bracket.hi - fw.bracket.lo < 4.2, `${fw.bracket.lo.toFixed(3)} to ${fw.bracket.hi.toFixed(3)}`);
check('the naive-persistence central estimate lies inside that bracket',
  fw.central > fw.bracket.lo && fw.central < fw.bracket.hi, fw.central.toFixed(3));
// The identity itself, checked against the smoother rather than trusted: if the missing
// month were exactly X, the full 13-term mean would be constant + X/24.
{
  const parsed = SS.parseSilso(feeds['silso-monthly'].text).rows;
  const probe = 100;
  const withProbe = parsed.concat([{
    y: Number(fw.terms[0].ym.slice(0, 4)), m: Number(fw.terms[0].ym.slice(5)), ym: fw.terms[0].ym,
    decimal: 0, value: probe, defined: true, sd: 0, n: 0, definitive: false,
  }]);
  const i = withProbe.findIndex((r) => r.ym === fw.targetYm);
  const full = SS.smoothedAt(withProbe, i);
  check('the pinned identity reproduces the full smoother when the missing month is supplied',
    near(full, fw.constant + probe / 24, 1e-9),
    `smoother ${full === null ? 'null' : full.toFixed(6)} vs identity ${(fw.constant + probe / 24).toFixed(6)}`);
}

// ── 9. SCORING THE CLAIMS MADE ON EARLIER RUNS ──────────────────────────────────
// This is what makes the page falsifiable rather than merely fresh. Every previous line
// of the record that made a claim is looked up in TODAY's data and graded, held or not.
const previous = readRecord();
{
  const publishedSmoothed = SS.parseSilso(feeds['silso-smoothed'].text).rows;
  const pub = new Map(publishedSmoothed.filter((r) => r.defined).map((r) => [r.ym, r.value]));
  const monthly = new Map(SS.parseSilso(feeds['silso-monthly'].text).rows.filter((r) => r.defined).map((r) => [r.ym, r.value]));

  for (const line of previous) {
    if (!line.forward || line.forward.resolved) continue;
    const t = line.forward.target;
    const nowPublished = pub.get(t);
    if (nowPublished === undefined) continue;                 // still open, nothing to grade
    const terms = line.forward.terms || [];
    const haveAll = terms.every((x) => monthly.has(x.ym));
    if (!haveAll) continue;
    const predicted = terms.reduce((a, x) => a + x.coefficient * monthly.get(x.ym), line.forward.constant);
    const held = Math.abs(predicted - nowPublished) <= 0.05;
    scoredClaims.push({
      id: 'pinned-identity', claimed_on: line.run, target: t,
      predicted: round(predicted, 5), published: nowPublished, diff: round(predicted - nowPublished, 5),
      inputs: terms.map((x) => ({ ym: x.ym, monthly: monthly.get(x.ym) })),
      held,
      note: held ? 'the identity held'
        : 'the identity failed, which means SILSO revised at least one of the monthly means that were already in the sum when the claim was made',
    });
    check(`FORWARD CLAIM from ${line.run} for ${t}: ${held ? 'held' : 'FAILED'}`, held,
      `predicted ${predicted.toFixed(3)}, SILSO published ${nowPublished}`);
  }

  // The standing claim about the maximum, graded on every run from the day it was written.
  for (const line of previous) {
    if (!line.claims) continue;
    const c = line.claims.find((x) => x.id === 'argmax-stable');
    if (!c) continue;
    const held = rep.settled.ym === c.ym && Math.abs(rep.settled.value - c.value) <= 0.5;
    scoredClaims.push({
      id: 'argmax-stable', claimed_on: line.run, claimed: { ym: c.ym, value: c.value },
      observed: { ym: rep.settled.ym, value: round(rep.settled.value, 4) }, held,
    });
    check(`STANDING CLAIM from ${line.run}: the maximum is still ${c.value} in ${c.ym}`, held,
      `now ${rep.settled.value.toFixed(4)} in ${rep.settled.ym}`);
    break;   // one is enough; the oldest is the strongest statement
  }
}

// ── 10. REVISION WATCH ──────────────────────────────────────────────────────────
// Did SILSO change a monthly value it had already published? The page cannot see this;
// only the record can, by comparing today against the last line written.
{
  const last = previous.length ? previous[previous.length - 1] : null;
  if (last && last.monthly_trailing) {
    const before = new Map(last.monthly_trailing.map((r) => [r.ym, r]));
    for (const r of rep.trailing) {
      const b = before.get(r.ym);
      if (!b) continue;
      if (Math.abs(b.value - r.value) > 1e-9 || b.definitive !== r.definitive) {
        revisions.push({ ym: r.ym, was: b.value, now: r.value, was_definitive: b.definitive, now_definitive: r.definitive });
      }
    }
    if (!QUIET && revisions.length) console.log(`  note SILSO revised ${revisions.length} previously reported monthly values since the last run`);
  }
}

finish(rep);

// ── the record ──────────────────────────────────────────────────────────────────
function finish(r) {
  const line = {
    run: runAt,
    checks: { passed, failed: failures.length, failures: failures.map((f) => f.name) },
    upstream_last_modified: Object.fromEntries(Object.entries(feeds).map(([k, v]) => [k, v.upstream_last_modified])),
    upstream_bytes: Object.fromEntries(Object.entries(feeds).map(([k, v]) => [k, v.bytes])),
  };
  if (r && r.ok) {
    line.frontier = { ym: r.frontier.ym, value: r.frontier.value, lag_months: r.frontier.lagMonths, newest_monthly: r.frontier.newestMonthlyYm, newest_monthly_value: r.frontier.newestMonthlyValue };
    line.anchor = {
      compared: r.anchor.compared, disagreements: r.anchor.disagreements.length,
      max_abs_diff: round(r.anchor.maxAbsDiff, 6),
      spot: Object.fromEntries(r.spots.map((s) => [s.ym, { ours: round(s.ours, 6), published: s.published }])),
    };
    line.provisional = r.provisional.map((p) => ({ ym: p.ym, known_weight: p.knownWeight, pinned: round(p.pinned, 5), mean: round(p.mean, 4), waiting_on: p.missing.map((m) => m.ym) }));
    line.argmax = { ym: r.settled.ym, value: round(r.settled.value, 5) };
    line.streak = { moves: r.streak.moves.length, from: r.streak.startedFrom.argmaxYm, settled_on: r.streak.settledOn, held_for: r.streak.heldFor };
    line.monthly_trailing = r.trailing;
    line.provisional_from = r.provisionalFrom;
    line.swpc = {
      panel_peak: r.swpc.panelPeak,
      peaks: Object.fromEntries(Object.entries(r.swpc.peaks).map(([k, v]) => [k, v ? { ym: v.ym, value: round(v.value, 4) } : null])),
      cross_host: { compared: r.swpc.crossHost.compared, disagreements: r.swpc.crossHost.disagreements.length, max_abs_diff: r.swpc.crossHost.maxAbsDiff },
      drift: r.swpc.drift.map((d) => ({ from: d.from, to: d.to, n: d.n, median: round(d.median, 5) })),
    };
    line.scoreboard = r.matrix.map((m) => ({
      observed: m.observedId, forecast: m.forecastId, verdict: m.verdict,
      error: m.error === undefined ? null : round(m.error, 5),
      in_band: m.inBand === undefined ? null : m.inBand,
      month_in_window: m.monthInWindow === undefined ? null : m.monthInWindow,
      would_have_printed: m.wouldHavePrinted === undefined ? null : round(m.wouldHavePrinted, 5),
    }));
    line.forward = {
      target: r.forward.targetYm,
      constant: round(r.forward.constant, 6),
      known_sum: r.forward.knownSum, known_weight: r.forward.knownWeight,
      terms: r.forward.terms.map((t) => ({ ym: t.ym, coefficient: t.coefficient })),
      bracket_40_140: [round(r.forward.bracket.lo, 4), round(r.forward.bracket.hi, 4)],
      central_naive_persistence: round(r.forward.central, 4),
      resolved: false,
      resolves: 'the first days of the month after the missing term is published',
    };
    line.claims = [
      { id: 'pinned-identity', target: r.forward.targetYm, statement: `SILSO's published 13-month smoothed value for ${r.forward.targetYm} will equal ${round(r.forward.constant, 5)} + SN(${r.forward.terms[0].ym})/24, to within 0.05` },
      { id: 'argmax-stable', ym: r.settled.ym, value: round(r.settled.value, 4), statement: `the Cycle 25 maximum of the SILSO 13-month smoothed series remains ${round(r.settled.value, 1)} in ${r.settled.ym}, to within 0.5` },
    ];
  } else {
    line.refusal = r ? r.refusal : 'report did not build';
  }
  if (scoredClaims.length) line.claims_scored = scoredClaims;
  if (revisions.length) line.revisions_since_last_run = revisions;

  if (!NO_WRITE) appendFileSync(RECORD, JSON.stringify(line) + '\n');

  console.log(`\n${failures.length === 0 ? 'PASS' : 'FAIL'}  ${passed} checks passed, ${failures.length} failed`);
  if (failures.length) for (const f of failures) console.log(`  - ${f.name} ${f.detail}`);
  if (!NO_WRITE) console.log(`  record: appended 1 line to research/six-months-behind-the-sun/record.jsonl`);
  process.exit(failures.length === 0 ? 0 : 1);
}

function readRecord() {
  if (!existsSync(RECORD)) return [];
  return readFileSync(RECORD, 'utf8').split('\n').filter((l) => l.trim()).map((l) => {
    try { return JSON.parse(l); } catch { return null; }
  }).filter(Boolean);
}
function round(x, n) { return (x === null || x === undefined) ? null : Math.round(x * 10 ** n) / 10 ** n; }
/** Strip the parts of a report that hold function references, for deep comparison. */
function stable(r) {
  return { anchor: r.anchor, frontier: r.frontier, settled: r.settled, provisional: r.provisional, matrix: r.matrix, trailing: r.trailing };
}
