/* verify-the-wind-that-hasnt-arrived-yet.mjs
 *
 * Recomputes every number the stratum shows, from the same wind.js the page imports,
 * and asserts the paths where the page REFUSES as hard as the paths where it succeeds.
 *
 *   node research/the-wind-that-hasnt-arrived-yet/verify-the-wind-that-hasnt-arrived-yet.mjs
 *   ...           --append     also append this run's line to record.jsonl
 *   ...           --offline    skip the live re-derivation (checks still run)
 *
 * The sections, in the order they run:
 *   A. PROVENANCE. The page's committed data file is re-derived, number for number, from
 *      the gzipped NOAA bytes committed beside it, whose sha256 is printed. A doctored
 *      data file fails here.
 *   B. THE INVERSION, WHICH IS THE ANCHOR. The recovered constant, its scatter, its
 *      standard error, and the differential controls. Each control feeds a DIFFERENT
 *      COLUMN OF REAL DATA to the SAME unmodified invert(); none of them touches the
 *      result.
 *   C. THE REFUSAL. spdf.gsfc.nasa.gov names this class of client by name and disallows
 *      the OMNI archive to it. This section PARSES the served robots.txt, asserts that
 *      the group naming us disallows that path, asserts that the naive readings which
 *      got it wrong say the opposite, and asserts that not one byte from that host
 *      remains in the page or its research directory.
 *   D. FRESHNESS, WITH A NEGATIVE CONTROL. The staleness check is fed a deliberately
 *      stale fixture and must fail on it, because a check that cannot fail is not one.
 *   E. THE REFUSAL PATHS. No active spacecraft, dead feed, featureless wind, ephemeris
 *      gap. Each must produce a refusal rather than a number.
 *   F. THE PAGE. Every id page.js writes to exists in index.html, the closing tags are
 *      there, the JSON-LD parses as JSON, and the page says which claim it is making.
 *   G. LIVE. Re-derive the constant on today's feed and compare it to the committed one.
 *      A drifting constant is not a failure, it is news, and it goes in the record.
 *
 * WHAT LEFT THIS FILE ON 2026-08-15, and it was six checks: the 2003 anchor out of NASA's
 * OMNI archive, and the re-derivation of its data file. The archive is refused to us by
 * name (section C), so the bytes were deleted and the checks went with them. They are not
 * commented out. A check kept alive against data we may not hold is not a check.
 */

import fs from 'node:fs';
import path from 'node:path';
import zlib from 'node:zlib';
import crypto from 'node:crypto';
import { fileURLToPath } from 'node:url';

const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, '..', '..');
const PAGE = path.join(ROOT, 'public', 'strata', 'the-wind-that-hasnt-arrived-yet');
const W = await import(path.join(PAGE, 'wind.js'));

const ARGS = new Set(process.argv.slice(2));
let fails = 0, checks = 0;
const ok = (name, cond, extra = '') => {
  checks++;
  if (!cond) fails++;
  console.log(`${cond ? '  ok' : 'FAIL'}  ${name}${extra ? '   ' + extra : ''}`);
};
const near = (a, b, eps) => a != null && b != null && Math.abs(a - b) <= eps;
const head = (s) => console.log('\n' + s + '\n' + '-'.repeat(s.length));

const baked = JSON.parse(fs.readFileSync(path.join(PAGE, 'data', 'baked-window.json'), 'utf8'));
const indexHtml = fs.readFileSync(path.join(PAGE, 'index.html'), 'utf8');
const pageJs = fs.readFileSync(path.join(PAGE, 'page.js'), 'utf8');
const windJs = fs.readFileSync(path.join(PAGE, 'wind.js'), 'utf8');

/* ══ A. PROVENANCE ═════════════════════════════════════════════════════════ */
head('A. the committed data file is re-derivable from the committed NOAA bytes');

const UP = path.join(HERE, 'upstream');
function gunzipJson(f) {
  const raw = zlib.gunzipSync(fs.readFileSync(path.join(UP, f)));
  return { raw, sha: crypto.createHash('sha256').update(raw).digest('hex'), json: JSON.parse(raw.toString('utf8')) };
}
const upProp = gunzipJson('propagated-solar-wind-7day.2026-08-14T2355Z.json.gz');
const upEph = gunzipJson('rtsw_ephemerides_1h.2026-08-14T2355Z.json.gz');

ok('propagated bytes match the sha256 the page prints', upProp.sha === baked.propagated.sha256, upProp.sha.slice(0, 16));
ok('ephemeris bytes match the sha256 the page prints', upEph.sha === baked.ephemerides.sha256, upEph.sha.slice(0, 16));
ok('propagated byte count matches', upProp.raw.length === baked.propagated.bytes, `${upProp.raw.length}`);

/* Re-derive the baked arrays straight from the NOAA bytes and compare element by element. */
const liveFramesFromUpstream = W.framesFromLive(upProp.json);
const bakedFrames = W.framesFromBaked(baked);
ok('row count survives the bake', liveFramesFromUpstream.length === bakedFrames.length,
  `${liveFramesFromUpstream.length} rows`);
let bakeDrift = 0, worstField = '';
for (let i = 0; i < Math.min(liveFramesFromUpstream.length, bakedFrames.length); i++) {
  const a = liveFramesFromUpstream[i], b = bakedFrames[i];
  for (const [k, eps] of [['t', 0], ['dt', 0], ['vx', 1e-9], ['speed', 1e-9], ['density', 1e-9], ['bz', 1e-9], ['bt', 1e-9]]) {
    if (Math.abs(a[k] - b[k]) > eps) { bakeDrift++; worstField = k; }
  }
}
ok('every baked number equals the NOAA byte it came from', bakeDrift === 0,
  bakeDrift ? `${bakeDrift} mismatches, e.g. ${worstField}` : 'all 7 fields, all rows');

const upstreamEphem = W.ephemFromLive(upEph.json);
const bakedEphem = W.ephemFromBaked(baked);
ok('the same spacecraft survive the bake',
  JSON.stringify(Object.keys(upstreamEphem).sort()) === JSON.stringify(Object.keys(bakedEphem).sort()),
  Object.keys(bakedEphem).sort().join(', '));
let ephDrift = 0;
for (const s of Object.keys(bakedEphem)) {
  const a = upstreamEphem[s], b = bakedEphem[s];
  if (!a || a.t.length !== b.t.length) { ephDrift++; continue; }
  for (let i = 0; i < a.t.length; i++) {
    if (a.t[i] !== b.t[i] || a.x[i] !== b.x[i] || a.y[i] !== b.y[i] || a.z[i] !== b.z[i]) ephDrift++;
  }
  if (a.active !== b.active) ephDrift++;
}
ok('every baked ephemeris row equals the NOAA byte it came from', ephDrift === 0, `${ephDrift} mismatches`);

/* ══ B. THE INVERSION ══════════════════════════════════════════════════════ */
head('B. the inversion, and the controls that must break it');

const active = W.activeSource(bakedEphem);
ok('exactly one spacecraft is marked active, and it is read not typed', active === 'SOLAR1', `active = ${active}`);
ok('the retired spacecraft is genuinely absent from the feed', !('DSCOVR' in bakedEphem),
  `feed carries ${Object.keys(bakedEphem).join(', ')}`);
ok('page.js does not hard-code a spacecraft name in its logic',
  !/['"`](DSCOVR|SOLAR1|ACE|IMAP)['"`]\s*[;,)\]]/.test(pageJs.replace(/\/\*[\s\S]*?\*\//g, '')),
  'it reads the active flag');

const headline = W.invert(bakedFrames, bakedEphem, { component: 'vx' });
ok('the headline inversion uses nearly every published row', headline.n >= 9900,
  `${headline.n} of ${bakedFrames.length}, ${headline.skippedNoEphem} skipped for no ephemeris cover`);
ok('recovered distance is 204,357 km', near(headline.meanKm, 204357, 3), `${headline.meanKm.toFixed(1)} km`);
ok('scatter is about 121 km', near(headline.sdKm, 121.1, 2), `${headline.sdKm.toFixed(1)} km`);
ok('that is 32.076 mean Earth radii', near(headline.reMean, 32.076, 0.002), headline.reMean.toFixed(4));
ok('that is 32.040 equatorial Earth radii', near(headline.reEq, 32.040, 0.002), headline.reEq.toFixed(4));
ok("it lands on NOAA's printed 32 Re to better than a quarter of one per cent",
  Math.abs(headline.reEq - 32) / 32 < 0.0025, `off by ${((headline.reEq - 32) / 32 * 100).toFixed(3)} %`);

/* A RELATIVE tolerance is the wrong instrument for a mean over ten thousand rows, and using
   only that one is how a page ends up saying "the arithmetic found 32" about a number its own
   data rejects. The SEM is 1.2 km and a flat 32 equatorial radii is 257 km away, so the page is
   required to say 32.04 and to print the significance rather than round in prose. */
const sigmaEq = Math.abs(headline.meanKm - 32 * W.R_EQ) / headline.semKm;
ok('the standard error of the mean is about 1.2 km', near(headline.semKm, 1.21, 0.05),
  `${headline.semKm.toFixed(2)} km over ${headline.n} rows`);
ok('and at that resolution the target is MEASURABLY NOT a flat 32 Re', sigmaEq > 50,
  `${(headline.meanKm - 32 * W.R_EQ).toFixed(0)} km from 32 equatorial radii, ${sigmaEq.toFixed(0)} standard errors`);
ok('the page prints that significance rather than only the relative agreement',
  /standard errors/.test(indexHtml) && /headline-sem/.test(indexHtml) && /semKm/.test(pageJs),
  'the SEM is on the page, not just in this file');

/* THE CONSTANT DRIFTS INSIDE THE COMMITTED WINDOW. Day means move by tens of km while each
   day's own standard error is a few km, so this is structure and not quantisation. A page
   quoting one mean to the kilometre has to show it, and the record's drift alarm has to be
   able to see something this size. */
const dayRuns = W.dailyMeans(bakedFrames, bakedEphem, { component: 'vx' }).filter((d) => d.n > 100);
const dayLo = Math.min(...dayRuns.map((d) => d.meanKm)), dayHi = Math.max(...dayRuns.map((d) => d.meanKm));
const worstSem = Math.max(...dayRuns.map((d) => d.semKm));
ok('the recovered constant drifts between days by far more than a day\'s own error',
  dayHi - dayLo > 8 * worstSem,
  `${dayRuns.length} days, ${dayLo.toFixed(1)} to ${dayHi.toFixed(1)} km (${(dayHi - dayLo).toFixed(1)} km apart), worst day SEM ${worstSem.toFixed(2)} km`);
ok('and the page prints that drift instead of one mean with no error bar', /drift-line/.test(indexHtml) && /dailyMeans/.test(pageJs));

const biased = W.invert(bakedFrames, bakedEphem, { component: 'vx', secondBias: 0.5 });
ok('correcting for whole-second truncation moves it to 204,167 km', near(biased.meanKm, 204167, 3),
  `${biased.meanKm.toFixed(1)} km, ${biased.reEq.toFixed(4)} equatorial Re`);
ok('the two rounding readings straddle 32 Re and disagree by about 190 km',
  near(headline.meanKm - biased.meanKm, 190, 12) && (headline.reEq - 32) * (biased.reEq - 32) > 0,
  `${(headline.meanKm - biased.meanKm).toFixed(0)} km apart`);

/* THE CONTROLS. Each hands invert() a different column of REAL data, or a different real
   spacecraft's REAL orbit. Nothing is appended to a result list; nothing is special-cased
   inside invert(). A control that "passed" by being labelled would pass here too, so what
   is asserted is that the answer gets WORSE by a stated factor. */
const cSpeed = W.invert(bakedFrames, bakedEphem, { component: 'speed' });
ok('CONTROL: advecting with the speed magnitude blows the scatter up ~78x',
  cSpeed.sdKm / headline.sdKm > 60, `${cSpeed.sdKm.toFixed(0)} km vs ${headline.sdKm.toFixed(0)} km, ${(cSpeed.sdKm / headline.sdKm).toFixed(0)}x`);
ok('CONTROL: and it no longer lands on 32 Re', Math.abs(cSpeed.reEq - 32) > 0.5, cSpeed.reEq.toFixed(3));

const cAce = W.invert(bakedFrames, bakedEphem, { spacecraft: 'ACE' });
const cImap = W.invert(bakedFrames, bakedEphem, { spacecraft: 'IMAP' });
ok("CONTROL: ACE's orbit gives 41.4 Re with 11,759 km of scatter",
  near(cAce.reMean, 41.405, 0.02) && near(cAce.sdKm, 11759, 60), `${cAce.reMean.toFixed(3)} Re, ${cAce.sdKm.toFixed(0)} km`);
ok("CONTROL: IMAP's orbit gives 33.9 Re with 1,108 km of scatter",
  near(cImap.reMean, 33.933, 0.02) && near(cImap.sdKm, 1108, 30), `${cImap.reMean.toFixed(3)} Re, ${cImap.sdKm.toFixed(0)} km`);
ok('CONTROL: the active spacecraft is the ONLY one that gives a sharp answer',
  headline.sdKm < cAce.sdKm / 8 && headline.sdKm < cImap.sdKm / 5,
  'so the arithmetic alone identifies which monitor drives the product');

const gapped = W.invert(bakedFrames, bakedEphem, { component: 'vx', maxGapS: 3600 });
ok('the ephemeris gaps did not make the number', near(gapped.sdKm, headline.sdKm, 4),
  `${gapped.sdKm.toFixed(1)} km over ${gapped.n} tight-bracket rows vs ${headline.sdKm.toFixed(1)} km over ${headline.n}`);

const leads = bakedFrames.map((f) => f.dt / 60).sort((a, b) => a - b);
ok('the lead is not "about an hour"', near(leads[0], 44.8, 0.2) && near(leads[leads.length - 1], 83.8, 0.2),
  `${leads[0].toFixed(1)} to ${leads[leads.length - 1].toFixed(1)} min, median ${leads[Math.floor(leads.length / 2)].toFixed(1)}`);
ok('the monitor sits outside the 40 Re where flat delay is trusted, all week',
  headline.yMinKm / W.R_MEAN > 40,
  `Y_GSE ${(headline.yMinKm / W.R_MEAN).toFixed(1)} to ${(headline.yMaxKm / W.R_MEAN).toFixed(1)} Re`);

/* ══ C. THE REFUSAL ═══════════════════════════════════════════════════════ */
head('C. the archive this page is refused, and the bytes that had to go');

/* This section exists because the page got this wrong once, publicly, and the error was
   not a research failure but an INSTRUMENT failure: the file was read to line 37 of 635,
   and later re-read by a parser that filtered to `User-agent: *` and discarded every group
   that named an agent specifically. A parser that discards the case where you are named by
   name cannot find the case where you are named by name.

   So the check is not "does the README mention robots.txt". It parses the served file and
   asks it the question directly, and it carries as its negative controls the two readings
   that got the wrong answer. */

const ROBOTS_FILE = path.join(HERE, 'robots', 'spdf.gsfc.nasa.gov.robots.txt');
const ROBOTS = fs.readFileSync(ROBOTS_FILE, 'utf8');
/* The exact URL path the deleted anchor was built from. */
const OMNI_PATH = '/pub/data/omni/high_res_omni/monthly_1min/omni_min200303.asc';

/* RFC 9309 grouping: consecutive User-agent lines share the rules that follow the run.
   A line whose content is commented out is not a rule, which is the whole point of the
   `#Disallow: /pub/data/` in the wildcard group. Path matching here is PREFIX ONLY, so
   wildcard patterns like `/*.cdf` are not matched: that under-reports disallows and can
   therefore only make the assertion below harder to pass, never easier. */
function parseRobots(txt) {
  const groups = [];
  let cur = null, collectingAgents = false;
  for (const raw of txt.split(/\r?\n/)) {
    const line = raw.replace(/#.*$/, '').trim();
    if (!line) continue;
    const m = /^([A-Za-z-]+)\s*:\s*(.*)$/.exec(line);
    if (!m) continue;
    const field = m[1].toLowerCase(), value = m[2].trim();
    if (field === 'user-agent') {
      if (!collectingAgents) { cur = { agents: [], rules: [] }; groups.push(cur); collectingAgents = true; }
      cur.agents.push(value.toLowerCase());
    } else if (field === 'disallow' || field === 'allow') {
      if (!cur) continue;
      collectingAgents = false;
      cur.rules.push({ allow: field === 'allow', path: value });
    }
  }
  return groups;
}
function robotsVerdict(txt, agent, urlPath) {
  const groups = parseRobots(txt);
  const a = agent.toLowerCase();
  const named = groups.filter((g) => g.agents.includes(a));
  const use = named.length ? named : groups.filter((g) => g.agents.includes('*'));
  let best = null;
  for (const g of use) {
    for (const r of g.rules) {
      if (!r.path || r.path.includes('*')) continue;
      if (!urlPath.startsWith(r.path)) continue;
      if (!best || r.path.length > best.path.length) best = r;
    }
  }
  return { via: named.length ? 'a group that names us' : 'the wildcard group', allowed: !best || best.allow, rule: best };
}

const groups = parseRobots(ROBOTS);
const ourGroup = groups.find((g) => g.agents.includes('claude'));
const ROBOT_LINES = ROBOTS.replace(/\n$/, '').split('\n').length;
ok('the served robots.txt is kept beside this page as evidence of the refusal',
  fs.existsSync(ROBOTS_FILE) && ROBOT_LINES > 600 && /Ultimate AI Block List/.test(ROBOTS),
  `${ROBOT_LINES} lines, and it is the file itself, not a description of it`);
ok('and the page states that length correctly, since the length is half the point',
  new RegExp(`${ROBOT_LINES} lines`).test(indexHtml),
  `the page says "${ROBOT_LINES} lines" and the file has ${ROBOT_LINES}`);
ok('it names this class of client by name, in one group with the other AI clients',
  ourGroup != null && ['anthropic', 'gpt', 'ccbot', 'crawl4ai'].every((t) => ourGroup.agents.includes(t)),
  ourGroup ? `${ourGroup.agents.length} user-agent tokens share those rules` : 'no group names Claude');
const verdictUs = robotsVerdict(ROBOTS, 'Claude', OMNI_PATH);
ok('and the group that names us DISALLOWS the path the deleted anchor came from',
  verdictUs.allowed === false && verdictUs.rule && verdictUs.rule.path === '/pub/data/',
  `${OMNI_PATH} -> Disallow: ${verdictUs.rule && verdictUs.rule.path} via ${verdictUs.via}`);

/* NEGATIVE CONTROL ONE: the wildcard group says the opposite. This is not a curiosity, it
   is the trap: a crawler that is not named may read that archive, and the file says so on
   purpose, with the author's own comment. A check that only ever consulted `User-agent: *`
   would pass while we broke the rule. */
const verdictWild = robotsVerdict(ROBOTS, 'SomeGenericCrawler', OMNI_PATH);
ok('NEGATIVE CONTROL: a client the file does not name is ALLOWED that same path',
  verdictWild.allowed === true && verdictWild.via === 'the wildcard group',
  'the distinction is deliberate: the wildcard Disallow is commented out with a note saying so');

/* NEGATIVE CONTROL TWO: the instrument that produced the original error, reproduced. */
const first37 = ROBOTS.split('\n').slice(0, 37).join('\n');
ok('NEGATIVE CONTROL: reading only the first 37 lines returns "permitted", which is how this happened',
  robotsVerdict(first37, 'Claude', OMNI_PATH).allowed === true,
  'head -37 on a 635-line robots.txt is not reading a robots.txt');

/* AND THE BYTES ARE GONE. A refusal that leaves the data in the repository is a disclosure,
   not a refusal. */
ok('the anchor data file the page used to ship is deleted',
  !fs.existsSync(path.join(PAGE, 'data', 'anchor-2003-03-30.json')));
ok('the committed OMNI day-slice is deleted too',
  !fs.existsSync(path.join(UP, 'omni_min200303_doy089.asc.gz')));
{
  const ships = [];
  const walk = (dir) => {
    for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
      const f = path.join(dir, e.name);
      if (e.isDirectory()) walk(f); else ships.push(f);
    }
  };
  walk(PAGE);
  walk(path.join(HERE, 'upstream'));
  const fromSpdf = ships.filter((f) => /omni|spdf/i.test(path.basename(f)));
  ok('nothing under the page directory or the committed upstream came from that host',
    fromSpdf.length === 0,
    fromSpdf.length ? 'still present: ' + fromSpdf.join(', ') : `${ships.length} files, all NOAA SWPC`);
  ok('the page ships exactly one data file, and it is NOAA\'s',
    fs.readdirSync(path.join(PAGE, 'data')).join(',') === 'baked-window.json',
    fs.readdirSync(path.join(PAGE, 'data')).join(', '));
}
ok('the code that read the archive is gone from wind.js, not commented out',
  !/^\s*export function (anchorBallistic|retargetShift|findRotation|matchesPaper)/m.test(windJs) &&
  !/anchor\.bz_gsm|anchor\.bsn_x/.test(windJs),
  'four functions removed with the data they needed');
ok('and page.js no longer fetches or renders it',
  !/anchor-2003-03-30|findRotation|matchesPaper|drawAnchorBz/.test(pageJs),
  'the only data file it fetches is baked-window.json');
/* Asserted against the imported MODULE rather than against this file's own text, because a
   check that greps its own source for a symbol finds the grep. Any surviving call would
   throw; this says the functions are not there to call. */
ok('the module no longer exports that arithmetic at all',
  ['anchorBallistic', 'retargetShift', 'findRotation', 'matchesPaper'].every((n) => W[n] === undefined),
  'so no check anywhere can quietly resurrect it');

/* THE PAGE HAS TO SAY IT. Deleting quietly and moving on would leave a reader with no way
   to know the page ever had a stronger check, which is the version of this that flatters
   us most. */
ok('the page tells the reader what was removed and why, in its own words',
  /Ultimate AI Block List/.test(indexHtml) && /635 lines/.test(indexHtml) &&
  /has been deleted/i.test(indexHtml) && /Anthropic/.test(indexHtml),
  'the sources block and refusal 3 both carry it');
ok('and it does not claim to have reproduced the published 2008 result',
  !/It reproduces/i.test(indexHtml) && !/reproduces the published/i.test(indexHtml) &&
  /(cited as literature|published result, cited|cited rather than reproduced)/i.test(indexHtml),
  'Mailyan et al. is cited with its DOI, and named as literature this page did not verify');
ok('the DOI is printed beside the citation, so the claim is checkable by a stranger',
  /10\.5194\/angeo-26-2383-2008/.test(indexHtml), 'doi:10.5194/angeo-26-2383-2008');

/* ══ D. FRESHNESS, WITH A NEGATIVE CONTROL ════════════════════════════════ */
head('D. HTTP 200 is not freshness, and the check is shown failing');

const nowFixture = Date.UTC(2026, 7, 15, 0, 0, 0) / 1000;
const fresh = W.freshness(nowFixture - 120, nowFixture, 60);
ok('a two-minute-old one-minute feed passes', fresh.ok && fresh.verdict === 'current', `lag ${fresh.lagS}s`);

/* NEGATIVE CONTROL: the real stale product on the same NOAA host. geospace_pred_est_kp_1_hour.json
   returns HTTP 200 with 86 well-formed rows whose newest time tag is 2024-06-18T16:39:00Z. A
   freshness check that cannot fail on THAT is not a check. */
const deadKpNewest = Date.UTC(2024, 5, 18, 16, 39, 0) / 1000;
const staleV = W.freshness(deadKpNewest, nowFixture, 3600);
ok('NEGATIVE CONTROL: the real stale SWPC product is caught', !staleV.ok && staleV.verdict === 'stale',
  `${(staleV.lagS / 86400).toFixed(0)} days behind, allowed ${(staleV.allowedS / 3600).toFixed(0)} h`);
ok('NEGATIVE CONTROL: a feed with no readable timestamp is refused, not passed',
  !W.freshness(null, nowFixture, 60).ok, 'verdict "unreadable"');
ok('NEGATIVE CONTROL: a timestamp from the future is refused too',
  !W.freshness(nowFixture + 7200, nowFixture, 60).ok, 'a clock ahead of ours is not "fresh"');
/* Kp time-tags the START of a three-hour bin that is not finished yet, so measuring its age
   from the tag declared a healthy feed stale every three hours by construction. That is worse
   than a cosmetic bug: the one panel whose job is to catch a genuinely dead product cried wolf
   on a live one. The bin span is stated rather than absorbed into a fatter tolerance, so the
   dead-product control below still has to pass on the same code. */
{
  const binStart = nowFixture - 3 * 3600 - 600;      // a bin that ENDED ten minutes ago
  ok('a just-completed Kp bin is current, not stale',
    W.freshness(binStart, nowFixture, 10800, 2, 10800).verdict === 'current',
    `tagged ${(3 * 3600 + 600) / 60} min ago, but its bin closed 10 min ago`);
  ok('NEGATIVE CONTROL: the bin-span allowance does not rescue a genuinely old Kp bin',
    !W.freshness(nowFixture - 86400, nowFixture, 10800, 2, 10800).ok,
    'a day-old bin is still stale with the same allowance');
  ok('the page passes the bin span rather than widening the tolerance',
    /10800\)/.test(pageJs) && /binSpanS/.test(fs.readFileSync(path.join(PAGE, 'wind.js'), 'utf8')));
}

ok('the committed window itself would now be flagged stale, and the page says so',
  !W.freshness(bakedFrames[bakedFrames.length - 1].t, Date.now() / 1000, 60).ok,
  'which is why it is labelled a dated window and not "now"');

/* ══ E. THE REFUSAL PATHS ═════════════════════════════════════════════════ */
head('E. the paths where the page must refuse');

const noActive = {};
for (const [k, v] of Object.entries(bakedEphem)) noActive[k] = { ...v, active: false };
ok('REFUSAL: no spacecraft marked active means no spacecraft is named',
  W.activeSource(noActive) === null, 'activeSource returns null rather than guessing');
const twoActive = { ...noActive, SOLAR1: { ...bakedEphem.SOLAR1, active: true }, ACE: { ...bakedEphem.ACE, active: true } };
ok('REFUSAL: two spacecraft marked active is also a refusal, not a coin toss',
  W.activeSource(twoActive) === null);
ok('REFUSAL: an inversion with no ephemeris returns an error, not a zero',
  W.invert(bakedFrames, {}, { spacecraft: 'NOPE' }).error != null);
ok('REFUSAL: an inversion with no rows returns an error, not a mean of nothing',
  W.invert([], bakedEphem, {}).error === 'no usable rows');
ok('REFUSAL: a position outside the ephemeris span is null, never extrapolated',
  W.positionAt(bakedEphem.SOLAR1, bakedEphem.SOLAR1.t[0] - 7200) === null &&
  W.positionAt(bakedEphem.SOLAR1, bakedEphem.SOLAR1.t[bakedEphem.SOLAR1.t.length - 1] + 7200) === null);
ok('REFUSAL: advect() refuses a target the parcel is already past',
  W.advect(1000, 5000, -400) === null && W.advect(1.5e6, 2e5, 0) === null);

/* THE PAGE'S OWN REFUSAL, NOT JUST THE MODULE'S. Section E used to assert refusals only on
   pure functions, so the DOM refusal was real but untested, and a thrown fetch (offline, DNS,
   blocked) skipped it entirely: provenance, the visit line and the freshness table rendered
   empty while the countdown label still promised a countdown. Both failure modes now go
   through one renderer, and that is what is asserted here. */
{
  const refusal = /function renderRefusal\(([\s\S]*?)\n}/.exec(pageJs);
  ok('the page has ONE refusal renderer, used by more than one failure path', refusal != null);
  const body = refusal ? refusal[1] : '';
  for (const slot of ['now-numbers', 'claim-block', 'countdown', 'countdown-label', 'prov', 'visit-line', 'freshness-body']) {
    ok(`REFUSAL: the renderer clears or explains ${slot}`, body.includes(slot));
  }
  ok('REFUSAL: a thrown fetch reaches that renderer, not a bare sentence',
    /loadLive\(\)\.catch\(\s*\(e\)\s*=>\s*renderRefusal/.test(pageJs),
    'the offline path and the error-body path are the same refusal');
  ok('REFUSAL: hiding actually hides, despite the author stylesheet setting display',
    /\[hidden\]\{display:none ?!important\}/.test(indexHtml),
    '.grid{display:grid} would otherwise beat the user agent\'s [hidden] rule');
}

/* The vacuous setting: a featureless wind must produce no claim at all. Fed a synthetic
   dead-flat wind, the gate MUST stay shut; fed a real step, it MUST open. */
const flat = bakedFrames.slice(-120).map((f, i) => ({ ...f, t: bakedFrames[bakedFrames.length - 120].t + i * 60, density: 5, speed: 400 }));
const flatGate = W.pressureStep(flat, { spanMin: 60, windowMin: 10, thresholdNPa: 1.0 });
ok('REFUSAL: a featureless wind fires no claim', !flatGate.fired && flatGate.stepNPa === 0,
  flatGate.reason);
/* The step is planted at minute 90 of 120, i.e. INSIDE the 60-minute window the gate
   looks at, so it is the gate that has to find it and not the slicing. */
const stepped = flat.map((f, i) => (i >= 90 ? { ...f, density: 14 } : f));
const openGate = W.pressureStep(stepped, { spanMin: 60, windowMin: 10, thresholdNPa: 1.0 });
ok('NEGATIVE CONTROL: the same gate opens on a real pressure step', openGate.fired,
  `${openGate.stepNPa.toFixed(2)} nPa over ${((openGate.toT - openGate.fromT) / 60).toFixed(0)} min`);
const liveGate = W.pressureStep(bakedFrames, { spanMin: 60, windowMin: 10, thresholdNPa: 1.0 });
ok('the gate state on the committed window is reported either way', typeof liveGate.fired === 'boolean',
  liveGate.fired ? `open, ${liveGate.stepNPa.toFixed(2)} nPa` : `shut, largest step ${liveGate.stepNPa.toFixed(2)} nPa`);

/* The circular comparison. It MUST agree, and agreeing is the point: it proves nothing. */
{
  /* The wind feed runs past the end of the hourly orbit file, so the page uses the newest
     wind row the orbit file actually covers. Same rule here. */
  const covered = bakedFrames.slice().reverse().find((q) => W.positionAt(bakedEphem.SOLAR1, q.t));
  ok('there is a newest wind row the orbit file covers, and it is found not assumed', covered != null,
    covered ? W.utcStamp(covered.t) : 'none');
  const pos = W.positionAt(bakedEphem.SOLAR1, covered.t);
  const ours = W.advect(pos.x, headline.meanKm, covered.vx);
  ok('the circular comparison agrees to under 2 seconds, which is why it is refused',
    Math.abs(ours - covered.dt) < 2, `${(ours - covered.dt).toFixed(2)} s difference, guaranteed by construction`);
  ok('the page does not silently extrapolate the orbit past its last row',
    W.lastFix(bakedEphem.SOLAR1).extrapolated === true && /extrapolated/.test(pageJs),
    'the last published fix is labelled as such');
}

/* ══ F. THE PAGE ══════════════════════════════════════════════════════════ */
head('F. the page itself');

ok('index.html closes script, body and html', /<\/body>\s*<\/html>\s*$/.test(indexHtml.trim()));
ok('the module script tag is present and points at page.js', /<script type="module" src="\.\/page\.js"><\/script>/.test(indexHtml));
const ld = /<script type="application\/ld\+json">([\s\S]*?)<\/script>/.exec(indexHtml);
let ldOk = false;
try { ldOk = !!JSON.parse(ld[1]).headline; } catch (e) { ldOk = false; }
ok('the JSON-LD block parses as JSON', ldOk);
ok('canonical, og:url and twitter card are present',
  /rel="canonical" href="https:\/\/artwaste\.land\/strata\/the-wind-that-hasnt-arrived-yet\/"/.test(indexHtml) &&
  /og:url/.test(indexHtml) && /twitter:card/.test(indexHtml));
ok('the page self-hosts its fonts', /\/fonts\/fonts\.css/.test(indexHtml));
/* This was an `A || B` where B only looked for `src=`, so a <link rel=stylesheet href="https://cdn…">
   would have passed it green on B alone. One test, and it is the strict one: no fetching
   attribute may point off-origin. Prose <a href> links are stripped first because a citation is
   not a request. */
{
  const withoutProseLinks = indexHtml.replace(/<a\b[^>]*>/g, '');
  const offOrigin = [...withoutProseLinks.matchAll(/\b(src|href|srcset|action|data|poster)\s*=\s*["'](https?:)?\/\/([^"']+)/gi)]
    .filter((m) => !/^artwaste\.land/.test(m[3]));
  ok('no third-party request is possible from the page', offOrigin.length === 0,
    offOrigin.length ? 'off-origin: ' + offOrigin.map((m) => m[0].slice(0, 60)).join(' | ') : 'every fetching attribute is same-origin or relative');
  /* And the check must be able to fail: prove it on a doctored copy. */
  ok('NEGATIVE CONTROL: the same test catches a planted third-party stylesheet',
    [...(indexHtml + '<link rel="stylesheet" href="https://cdn.example.com/x.css">').replace(/<a\b[^>]*>/g, '')
      .matchAll(/\b(src|href|srcset|action|data|poster)\s*=\s*["'](https?:)?\/\/([^"']+)/gi)]
      .filter((m) => !/^artwaste\.land/.test(m[3])).length === 1,
    'the old `A || B` form passed this planted case');
}
ok('the page fetches only through /api/feed via the shared kit',
  /from '\/_kit\/livefeed\.js'/.test(pageJs) && !/fetch\(\s*['"`]https?:/.test(pageJs));

/* every id page.js writes to must exist in the HTML, or a number silently vanishes */
const ids = new Set();
for (const m of pageJs.matchAll(/(?:txt|html)\(\s*'([a-z0-9-]+)'/g)) ids.add(m[1]);
for (const m of pageJs.matchAll(/\$\(\s*'([a-z0-9-]+)'\s*\)/g)) ids.add(m[1]);
for (const m of pageJs.matchAll(/(?:txt|html)\(\s*outPrefix \+ '(-[a-z]+)'/g)) {
  ids.add('baked' + m[1]); ids.add('live' + m[1]);
}
ids.add('baked-hist'); ids.add('live-hist');
const missing = [...ids].filter((id) => !new RegExp(`id="${id}"`).test(indexHtml));
ok('every element page.js writes to exists in index.html', missing.length === 0,
  missing.length ? 'missing: ' + missing.join(', ') : `${ids.size} ids`);

ok('a reduced-motion guard is present', /prefers-reduced-motion/.test(pageJs));
ok('the live readouts are aria-live status regions',
  (indexHtml.match(/role="status"/g) || []).length >= 4);
ok('the refusals are on the page, not only in this file',
  /refuses to tell you/i.test(indexHtml) && /geomagnetic latitude, not geographic/.test(indexHtml));

/* THE ANCHOR PANEL. The page's anchor is now the recovery itself, and the one thing it must
   not do is let ten thousand rows of precision stand in for a test of the method. So the
   panel is required to carry BOTH halves: the published claim it recovers, and the sentence
   saying what recovering it does not show. */
{
  const anchorPanel = /<section class="check" aria-labelledby="anchor">([\s\S]*?)<\/section>/.exec(indexHtml);
  ok('the anchor panel exists and quotes the published claim it recovers',
    anchorPanel != null && /32 Re at the\s*\n?\s*upstream boundary/.test(anchorPanel[1]) &&
    /prose/i.test(anchorPanel[1]),
    'NOAA states it in words; the feed does not contain it');
  for (const id of ['anc-km', 'anc-re', 'anc-sd', 'anc-sem', 'anc-ctrl-v', 'anc-ctrl-sc', 'anchor-verdict']) {
    ok(`the anchor panel's ${id} is filled by the same invert() the reader can break`,
      anchorPanel != null && anchorPanel[1].includes(`id="${id}"`) && pageJs.includes(`'${id}'`));
  }
  ok('the panel carries both controls, so the recovery is not a single unbroken number',
    anchorPanel != null && /CONTROL: wrong velocity component/.test(anchorPanel[1]) &&
    /CONTROL: wrong spacecraft/.test(anchorPanel[1]));
  /* The load-bearing sentence. It is generated in page.js, so it is asserted there. */
  ok('the anchor verdict says what the recovery does NOT establish, in the same breath',
    /And what it does not/.test(pageJs) && /not a test of whether what they do is <em>right<\/em>/.test(pageJs) &&
    /evidence about the arithmetic, not about the wind/.test(pageJs),
    'a recovery of what NOAA does is not a test of whether NOAA is right');
  ok('and the body says it too, outside the panel',
    /It says what their pipeline does\. It cannot say whether the pipeline is/.test(indexHtml));
  /* The dropped forward claim, on the page and not only in the record. */
  ok('the page says the forward claim was dropped, and gives both reasons',
    /dropped/i.test(indexHtml) && /Nothing measures the wind at 32 Re/.test(indexHtml) &&
    /refuses this client by name|disallows this client by name|refused/i.test(indexHtml),
    'no instrument at the boundary, and the archive that would test the method is refused');
  ok('and it no longer promises a scorer anywhere',
    !/scored_later/.test(indexHtml) && !/will keep saying <code>pending<\/code>/.test(indexHtml) &&
    !/<code>pending<\/code>/.test(indexHtml),
    'the word pending is gone from the page, because it implied a wait');
}
/* The 32 Re boundary is a model's upstream edge, not Earth and not the bow shock. The only
   place that phrase is allowed to appear is in the sentence disclaiming it. */
/* THE RULE, AND WHERE IT WAS BEING BROKEN. The old test grepped two exact strings, neither of
   which any of the four violations used: the JSON-LD said "reaching Earth's magnetosphere", the
   Twitter card asserted a frozen 56 minutes, and the meta description and the stratum's own
   frontmatter said "touching Earth's field". The shareable surface is where most readers meet a
   page, so it is checked as a surface, on a family of phrasings rather than two literals. */
{
  const BAD = /(arriv\w+|reach\w+|touch\w+|hit\w+|get\w*)\s+(at\s+)?(Earth'?s?\b(?!\s+radi)|the\s+magnetosphere|Earth'?s\s+field)/i;
  const meta = [...indexHtml.matchAll(/<meta[^>]+(?:name|property)="(description|og:description|og:title|twitter:description|twitter:title)"[^>]*content="([^"]*)"/g)]
    .map((m) => [m[1], m[2]]);
  const ldRaw = /<script type="application\/ld\+json">([\s\S]*?)<\/script>/.exec(indexHtml);
  const ldObj = ldRaw ? JSON.parse(ldRaw[1]) : {};
  const front = fs.readFileSync(path.join(ROOT, 'src', 'content', 'strata', 'the-wind-that-hasnt-arrived-yet.md'), 'utf8').split(/^---$/m)[1] || '';
  const surface = [
    ...meta,
    ['json-ld description', ldObj.description || ''],
    ['json-ld headline', ldObj.headline || ''],
    ['frontmatter', front],
  ];
  const offenders = surface.filter(([, v]) => BAD.test(v)).map(([k]) => k);
  ok('nothing on the SHAREABLE surface says the wind arrives at Earth', offenders.length === 0,
    offenders.length ? 'offending: ' + offenders.join(', ') : `${surface.length} shareable fields checked, including the stratum frontmatter`);
  ok('NEGATIVE CONTROL: that test catches the wording it was written for',
    BAD.test("The solar wind reaching Earth's magnetosphere was measured upstream") &&
    BAD.test("the wind touching Earth's field right now") &&
    !BAD.test('a boundary 32 Earth radii out'),
    'the two phrasings that were live on this page until 2026-08-15');
  ok('the body still says "arrives at Earth" only inside its own disclaimer',
    !/arrives at Earth|hits the magnetosphere/i.test(indexHtml.replace(/never\s+says "arrives at Earth"/g, '')));
  /* The Twitter card carried a hard-coded "about 56 minutes" on a page whose thesis is that
     this quantity is not a constant. No shareable field may state a lead in minutes that the
     page computes live, unless it states the range the committed week actually shows. */
  const frozenLead = surface.filter(([, v]) => /\b(about|around)\s+\d+(\.\d+)?\s+minutes?\b/i.test(v)).map(([k]) => k);
  ok('no shareable field freezes the transit time into a single number', frozenLead.length === 0,
    frozenLead.length ? 'offending: ' + frozenLead.join(', ') : 'the lead is quoted as a measured range or not at all');
}
ok('the page prints the source\'s own last-modified, via provenance()',
  /provenance\(/.test(pageJs) && /visitSentence\(/.test(pageJs) && /sinceYourLastVisit\(/.test(pageJs));
/* PROSE ARITHMETIC. The page's dismissal of the 32-Re-is-not-Earth gap was inherited from the
   scouting brief and was wrong by a factor of ten: "the extra 20 Re is worth roughly half a
   minute at 400 km/s" only reproduces if an Earth radius is 637 km. It is minutes, not seconds,
   and it is the same size as the discrepancy the literature reports for this method, so the
   sentence had been making the page's own worst systematic look negligible. Recomputed here,
   from the same constants the module uses. */
{
  const minutesFor = (re, v) => (re * W.R_MEAN) / v / 60;
  ok('the boundary offset is minutes, not seconds',
    near(minutesFor(18, 400), 4.78, 0.02) && near(minutesFor(22, 400), 5.84, 0.02),
    `${minutesFor(18, 400).toFixed(2)} min to the bow shock at 14 Re, ${minutesFor(22, 400).toFixed(2)} min to the magnetopause at 10 Re`);
  ok('the page prints the right order of magnitude for it, and the right distances',
    /about five minutes, not thirty\s*\n?\s*seconds/i.test(indexHtml) && /4\.8 minutes/.test(indexHtml) &&
    /full 22 Re to the magnetopause is\s*\n?\s*5\.8/.test(indexHtml) &&
    !/extra 20 Re is worth roughly half a minute/.test(indexHtml),
    'both hops recomputed from R_MEAN rather than typed');
  /* The comparison this sentence makes is now to a CITED number, not to a number this page
     computes, so what is asserted is that the cited figure is the one being compared to and
     that the page attributes it. 51 minus 46 is the paper's own arithmetic. */
  ok('and it compares itself to the published discrepancy, attributed',
    Math.abs(minutesFor(18, 400) - (51 - 46)) < 0.5 && /Mailyan and colleagues/.test(indexHtml),
    `${minutesFor(18, 400).toFixed(2)} min of boundary offset against the 5 min Mailyan et al. report for flat delay`);
  /* Two 2024 minutes (17:05, 17:12) were asserted for the Gannon storm out of a month file that
     is not committed. Only the cited ground SSC survives. */
  ok('no uncomputable minute is asserted for the 2024 Gannon event',
    !/17:05|17:12/.test(indexHtml) && !/17:05|17:12/.test(pageJs) && /17:08/.test(indexHtml),
    'only the SSC minute Lawrence et al. publish, which is cited');
  ok('and no GFZ-versus-NOAA figure is stated, since GFZ is never fetched',
    !/\d+\s+of\s+the\s+\d+\s+bins/.test(pageJs) && !/\d+\s+of\s+the\s+\d+\s+bins/.test(indexHtml),
    'the revision is named as a gap and not quantified');
  ok('the transit-time range in the live sentence is computed, not typed',
    !/44\.8 to 83\.8/.test(pageJs) && /S\.leadMin/.test(pageJs),
    'it reads the same committed window the panel below prints');
  ok('the OG card the page points at exists',
    fs.existsSync(path.join(ROOT, 'public', 'og', 'the-wind-that-hasnt-arrived-yet.png')),
    'og:image, twitter:image and the JSON-LD image all name it');
  const frontMatter = fs.readFileSync(path.join(ROOT, 'src', 'content', 'strata', 'the-wind-that-hasnt-arrived-yet.md'), 'utf8').split(/^---$/m)[1] || '';
  const plain = /^plain:\s*"([\s\S]*?)"\s*$/m.exec(frontMatter);
  ok('the stratum carries a plain: placard, within the 420-character gate',
    plain != null && plain[1].length <= 420, plain ? `${plain[1].length} chars` : 'missing');
}

const EMDASH = String.fromCharCode(8212);   // written this way so this file has none either
ok('no em dash anywhere in the page or its module',
  !indexHtml.includes(EMDASH) && !pageJs.includes(EMDASH) && !fs.readFileSync(path.join(PAGE, 'wind.js'), 'utf8').includes(EMDASH),
  'publish.sh gates on it');

/* ══ G. LIVE ══════════════════════════════════════════════════════════════ */
head('G. today\'s feed');

let live = null;
if (!ARGS.has('--offline')) {
  try {
    const [p, e] = await Promise.all([
      fetch('https://services.swpc.noaa.gov/products/geospace/propagated-solar-wind.json'),
      fetch('https://services.swpc.noaa.gov/json/rtsw/rtsw_ephemerides_1h.json'),
    ]);
    if (p.ok && e.ok) {
      const lf = W.framesFromLive(await p.json());
      const le = W.ephemFromLive(await e.json());
      const r = W.invert(lf, le, { component: 'vx' });
      const newest = lf.length ? lf[lf.length - 1] : null;
      /* Tolerance 15, not 3: this product's newest row is typically 5 to 7 minutes old
         because of processing latency, which is not the same thing as staleness. The
         number is stated here and on the page rather than tuned until it passed. */
      const fr = W.freshness(newest ? newest.t : null, Date.now() / 1000, 60, 15);
      live = {
        fetched_at: new Date().toISOString(),
        active_source: W.activeSource(le),
        sources_in_feed: Object.keys(le).sort(),
        rows: r.n,
        recovered_km: r.meanKm == null ? null : +r.meanKm.toFixed(1),
        recovered_sd_km: r.sdKm == null ? null : +r.sdKm.toFixed(1),
        re_mean: r.reMean == null ? null : +r.reMean.toFixed(4),
        re_equatorial: r.reEq == null ? null : +r.reEq.toFixed(4),
        control_speed_magnitude_sd_km: +W.invert(lf, le, { component: 'speed' }).sdKm.toFixed(1),
        control_ACE_sd_km: le.ACE ? +W.invert(lf, le, { spacecraft: 'ACE' }).sdKm.toFixed(1) : null,
        control_IMAP_sd_km: le.IMAP ? +W.invert(lf, le, { spacecraft: 'IMAP' }).sdKm.toFixed(1) : null,
        newest_row_utc: newest ? W.utcStamp(newest.t) : null,
        freshness: fr.verdict,
        lead_minutes: newest ? +(newest.dt / 60).toFixed(2) : null,
        parcel: newest ? {
          measured_utc: W.utcStamp(newest.t),
          predicted_arrival_utc: W.utcStamp(newest.t + newest.dt),
          bz_gsm_nT: newest.bz,
          density_cm3: newest.density,
          speed_km_s: newest.speed,
          dynamic_pressure_nPa: +W.dynamicPressure(newest.density, newest.speed).toFixed(3),
        } : null,
        gate: (() => { const g = W.pressureStep(lf, { spanMin: 60, windowMin: 10, thresholdNPa: 1.0 }); return { fired: g.fired, step_nPa: g.stepNPa == null ? null : +g.stepNPa.toFixed(3), reason: g.reason }; })(),
      };
      ok('the live feed is current against its own newest row', fr.ok, `${(fr.lagS / 60).toFixed(1)} min behind`);
      ok('the active spacecraft is still exactly one, read from the flag', live.active_source != null, live.active_source);
      /* Tolerance 150 km, not 400. The window's own day-to-day means move by about 50 km, so a
         400 km gate could not have seen a change several times larger than anything the data
         does on its own, and a drift alarm that cannot detect the drift already in the record
         is not an alarm. 150 km leaves three times the observed day-to-day movement as headroom
         while still being able to fire on a real change of boundary. */
      ok('the recovered constant has not drifted from the committed one',
        near(r.meanKm, headline.meanKm, 150),
        `${r.meanKm.toFixed(1)} km today vs ${headline.meanKm.toFixed(1)} km committed, ${(r.meanKm - headline.meanKm).toFixed(1)} km apart; the committed week's own day means span ${(dayHi - dayLo).toFixed(1)} km`);
    } else {
      console.log(`  --  upstream returned ${p.status}/${e.status}; live section skipped, checks above stand`);
    }
  } catch (err) {
    console.log(`  --  no network (${err.message}); live section skipped, checks above stand`);
  }
} else {
  console.log('  --  --offline requested; live section skipped');
}

/* ══ the record ═══════════════════════════════════════════════════════════ */
const RECORD = path.join(HERE, 'record.jsonl');
/* The line is BUILT on every run and only WRITTEN under --append, so its shape can be
   asserted below on a plain run too. It used to be built inside the append branch, which
   meant nothing checked what a record line said unless the run happened to write one. */
const line = {
  id: 'run-' + new Date().toISOString().replace(/[-:.]/g, '').slice(0, 15) + 'Z',
  kind: 'verifier-run',
  run_utc: new Date().toISOString(),
  checks, failures: fails,
  committed_window: {
    first: baked.propagated.first, last: baked.propagated.last,
    rows: headline.n,
    recovered_km: +headline.meanKm.toFixed(1),
    recovered_sd_km: +headline.sdKm.toFixed(1),
    recovered_sem_km: +headline.semKm.toFixed(2),
    sigma_from_flat_32_re_eq: +(Math.abs(headline.meanKm - 32 * W.R_EQ) / headline.semKm).toFixed(0),
    day_mean_spread_km: +(dayHi - dayLo).toFixed(1),
    re_mean: +headline.reMean.toFixed(4), re_equatorial: +headline.reEq.toFixed(4),
    truncation_corrected_km: +biased.meanKm.toFixed(1),
    control_speed_magnitude_sd_km: +cSpeed.sdKm.toFixed(1),
    control_ACE_sd_km: +cAce.sdKm.toFixed(1),
    control_IMAP_sd_km: +cImap.sdKm.toFixed(1),
    active_source: active,
  },
  anchor: {
    /* The anchor is now same-source: a value NOAA states in prose, recovered from NOAA's
       numbers by a route that never read the prose. Recorded as what it is. */
    published_claim: '32 Re, stated in prose on the Geospace Global Geomagnetic Activity Plot product page',
    recovered_km: +headline.meanKm.toFixed(1),
    recovered_re_equatorial: +headline.reEq.toFixed(4),
    recovered_re_mean: +headline.reMean.toFixed(4),
    relative_offset_from_flat_32_re_eq: +((headline.reEq - 32) / 32).toFixed(6),
    establishes: 'what NOAA propagates to, recovered from their own feed',
    does_not_establish: 'whether flat advection is the right method; reproducing the arithmetic is evidence about the arithmetic, not about the wind',
  },
  live,
  /* WITHDRAWN 2026-08-15. This block used to read {status: "pending"} and name a scorer.
     There is no scorer and there cannot be one through a permitted route: nothing measures
     the wind at the 32 Re boundary, so the only available comparison is NOAA's own tag,
     which is the same advection and agrees by construction; and the archive that would
     have tested the METHOD is disallowed to this client by name. "Pending" implied a wait.
     "Dropped" is the true word. */
  forward_claim: {
    status: 'dropped',
    dropped_at: '2026-08-15',
    was: 'a dated arrival minute at the 32 Re model boundary, written down to be graded later',
    why_unscoreable: 'No instrument sits at the model boundary, so the predicted minute cannot be observed by anyone; the only available comparison is NOAA\'s own propagated tag, which is the same flat advection on the same inputs and agrees by construction.',
    blocked_route: 'The independent test of the METHOD needs the same parcel caught at a second spacecraft further downstream. That archive is under /pub/data/ on spdf.gsfc.nasa.gov, whose robots.txt names Claude and Anthropic among 423 user-agent tokens in a group disallowing that path.',
    scorer_implemented: false,
  },
};

const recLines = fs.existsSync(RECORD) ? fs.readFileSync(RECORD, 'utf8').trim().split('\n').filter(Boolean) : [];
head('the record');
ok('record.jsonl exists and every line is valid JSON', recLines.length > 0 && recLines.every((l) => { try { JSON.parse(l); return true; } catch (e) { return false; } }),
  `${recLines.length} lines`);
ok('the ship-time line is present and is the first one',
  recLines.length > 0 && JSON.parse(recLines[0]).kind === 'ship',
  recLines.length ? JSON.parse(recLines[0]).run_utc : 'none');
{
  const rows = recLines.map((l) => JSON.parse(l));
  /* This alarm used to read `committed_window.recovered_km`, which is computed from a frozen
     file and therefore CANNOT move unless somebody edits the committed data. It reported
     "a drifting value would mean NOAA changed something" about a number that is 204356.9 on
     every line and always will be. That is the wrong half of the record: what can actually
     move is the LIVE re-derivation, so the alarm watches that, and the frozen half is asserted
     to be frozen, which is the only thing it can honestly tell us. */
  const frozen = rows.map((r) => (r.committed_window || {}).recovered_km).filter((x) => x != null);
  const frozenSpread = frozen.length > 1 ? Math.max(...frozen) - Math.min(...frozen) : 0;
  ok('the committed window is reproduced identically by every run, as a frozen file must be',
    frozenSpread === 0,
    `${frozen.length} runs, all ${frozen[0]} km. This detects a doctored data file, NOT a change at NOAA.`);
  const liveConsts = rows.map((r) => (r.live || {}).recovered_km).filter((x) => x != null);
  const liveSpread = liveConsts.length > 1 ? Math.max(...liveConsts) - Math.min(...liveConsts) : 0;
  ok('the LIVE re-derivation has not drifted across the recorded runs, which is the half that can',
    liveConsts.length < 2 || liveSpread < 300,
    liveConsts.length < 2
      ? `${liveConsts.length} live run recorded so far, so there is nothing to compare yet and this check says so rather than passing quietly`
      : `${liveConsts.length} live runs, spread ${liveSpread.toFixed(1)} km. A drifting value here would mean NOAA changed something.`);

  /* THE LINE THIS RUN WOULD WRITE. Asserted whether or not --append was passed, because the
     shape of the record is part of what the page claims and it should not go unchecked on
     the runs that do not write. */
  ok('the line this run would append says the forward claim is DROPPED, not pending',
    line.forward_claim.status === 'dropped' && line.forward_claim.scorer_implemented === false &&
    !('scored_later' in line),
    'the word "pending" implied a wait; there is no scorer to wait for');
  ok('and it records the anchor as a recovery, with what it does not establish attached',
    /not about the wind/.test(line.anchor.does_not_establish) &&
    near(line.anchor.recovered_re_equatorial, 32.04, 0.002),
    `${line.anchor.recovered_km} km, ${line.anchor.recovered_re_equatorial} equatorial Re`);
  /* The correction line written when the OMNI bytes were deleted, and the rule it sets for
     every line after it. Vacuous until the first post-correction run appends, and the extra
     says how many lines it is actually testing rather than reporting a silent pass. */
  const corrections = rows.filter((r) => r.kind === 'correction' && /spdf/i.test(JSON.stringify(r)));
  const dropAt = corrections.length ? corrections[corrections.length - 1].run_utc : null;
  const after = rows.filter((r) => r.kind === 'verifier-run' && dropAt && r.run_utc > dropAt);
  ok('every verifier run recorded since that correction says dropped, and none says pending',
    dropAt != null && after.every((r) => r.forward_claim && r.forward_claim.status === 'dropped' && !r.scored_later),
    dropAt == null ? 'no correction line found, which is itself a failure'
      : `${after.length} run${after.length === 1 ? '' : 's'} recorded after ${dropAt}; the ${rows.filter((r) => r.scored_later).length} earlier lines that say pending are left standing, because the record is append-only`);
}

/* Appended LAST, after every check has run, so the count in the record is the count the
   run actually produced rather than the count so far. */
if (ARGS.has('--append')) {
  line.checks = checks; line.failures = fails;
  fs.appendFileSync(RECORD, JSON.stringify(line) + '\n');
  console.log(`\nappended one line to ${path.relative(ROOT, RECORD)}`);
}

console.log(`\n${checks - fails}/${checks} checks passed.`);
process.exit(fails ? 1 : 0);
