#!/usr/bin/env node
/**
 * verify-lower-than-when-you-last-looked.mjs
 *
 * Recomputes every number /strata/lower-than-when-you-last-looked/ shows, using the SAME
 * module the page imports (public/strata/lower-than-when-you-last-looked/oem.js), and
 * appends one line per run to research/lower-than-when-you-last-looked/record.jsonl.
 *
 *   node research/lower-than-when-you-last-looked/verify-lower-than-when-you-last-looked.mjs
 *   … --offline     skip everything that needs tonight's file (documented, not the default)
 *   … --no-record   do not append to record.jsonl
 *   … --no-browser  skip the stage that opens the page in a real browser
 *
 * WHAT IT IS BUILT NOT TO DO, which is the point.
 *
 * A page reporting "85 of 85 checks passing" on its success path and nothing on its refusal
 * path has tested the half that was never going to fail. So a bit under half the assertions
 * here are NEGATIVE CONTROLS: a deliberately stale file that freshness() must reject, an
 * ephemeris with NASA's burn block cut out of it that the interpolator must refuse to cross,
 * an averaging window straddling a burn that must not return a mean, a fabricated claim
 * outcome the scorer must mark failed, and a reflected orbit whose ascending nodes must come
 * out equal to the original's descending ones. Each control doctors the DATA the instrument
 * reads. None of them touches the instrument or the result list.
 *
 * Network: this fetches nasa-public-data.s3.amazonaws.com, which serves no robots.txt
 * (HTTP 404, verified 2026-08-14T23:55:55Z, recorded in README.md). It prefers this site's
 * own /api/feed/nasa-iss-oem proxy when that is reachable, which is the exact path the page
 * takes. celestrak.org is not fetched by anything here; see README.md for why.
 */

import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import * as O from '../../public/strata/lower-than-when-you-last-looked/oem.js';

const HERE = path.dirname(fileURLToPath(import.meta.url));
const PAGE = path.join(HERE, '../../public/strata/lower-than-when-you-last-looked');
const DATA = path.join(PAGE, 'data');
const RECORD = path.join(HERE, 'record.jsonl');
const OFFLINE = process.argv.includes('--offline');
const NO_RECORD = process.argv.includes('--no-record');
const NO_BROWSER = process.argv.includes('--no-browser') || OFFLINE;

const UA = 'ArtificialWasteland/1.0 (+https://artwaste.land)';
const PROXY = 'https://artwaste.land/api/feed/nasa-iss-oem';
const UPSTREAM = 'https://nasa-public-data.s3.amazonaws.com/iss-coords/current/ISS_OEM/ISS.OEM_J2K_EPH.txt';

/* Windows and constants the page uses. Kept in step by an assertion, not by hope. */
const WMIN = 600, WMAX = 14400;
const SIGMA_REF_M = 57.3, SIGMA_NOW_M = 13.7;
const FLOOR_M = 3 * Math.hypot(SIGMA_REF_M, SIGMA_NOW_M);

let pass = 0, fail = 0;
const failures = [];
function ok(name, cond, detail = '') {
  if (cond) { pass++; console.log(`  ok   ${name}${detail ? '  ' + detail : ''}`); }
  else { fail++; failures.push(name + (detail ? ' :: ' + detail : '')); console.log(`  FAIL ${name}  ${detail}`); }
}
function near(name, got, want, tol, unit = '') {
  ok(name, Math.abs(got - want) <= tol, `got ${got}${unit}, want ${want}${unit} +/- ${tol}${unit}`);
}
const head = (s) => console.log(`\n${s}`);

const readJSON = (f) => JSON.parse(fs.readFileSync(path.join(DATA, f), 'utf8'));

/* ══ 0. the shipped page and the module agree about what exists ══════════════ */

head('0. the shipped page, read as a file');
const html = fs.readFileSync(path.join(PAGE, 'index.html'), 'utf8');
const js = fs.readFileSync(path.join(PAGE, 'page.js'), 'utf8');
const htmlIds = new Set([...html.matchAll(/\sid="([a-z0-9-]+)"/g)].map((m) => m[1]));
const jsIds = new Set([...js.matchAll(/\$\('([a-z0-9-]+)'\)/g)].map((m) => m[1]));
const orphans = [...jsIds].filter((i) => !htmlIds.has(i));
ok('every element page.js writes into exists in index.html', orphans.length === 0, orphans.join(', '));
ok('the page loads its data through /api/feed, never an upstream', !/fetch\(\s*['"`]https?:/.test(js) && js.includes("fetchFeed('nasa-iss-oem')"));
ok('the page has no inline script other than the JSON-LD block',
  [...html.matchAll(/<script(?![^>]*\bsrc=)[^>]*>/g)].every((m) => /application\/ld\+json/.test(m[0])));
ok('the JSON-LD block parses as JSON', (() => {
  const m = html.match(/<script type="application\/ld\+json">([\s\S]*?)<\/script>/);
  try { JSON.parse(m[1]); return true; } catch { return false; }
})());
/* Two separate claims, and they used to be one regex that coupled them by accident: the module
   this page is nothing without has to be loaded (the silent-no-JS trap), and the document has to
   close. The site-wide "how this layer is checked" block is injected after the script tag, so
   asserting that they are adjacent asserted something about a shared footer instead. */
ok('the page loads its module rather than leaving the reader a silent shell',
  /<script type="module" src="\/strata\/lower-than-when-you-last-looked\/page\.js"><\/script>/.test(html));
ok('the page closes its tags', /<\/body>\s*<\/html>\s*$/.test(html.trimEnd() + '\n'));
ok('no em dashes in the page or its modules',
  !html.includes('—') && !js.includes('—') && !fs.readFileSync(path.join(PAGE, 'oem.js'), 'utf8').includes('—'));
ok('the command the page prints is a file that exists',
  fs.existsSync(path.join(HERE, 'verify-lower-than-when-you-last-looked.mjs')));
ok('the window bounds in the page match the ones asserted here',
  js.includes(`const WMIN = ${WMIN}, WMAX = ${WMAX};`));
ok('the noise floor in the page matches the one asserted here',
  js.includes(`const SIGMA_REF_M = ${SIGMA_REF_M}, SIGMA_NOW_M = ${SIGMA_NOW_M};`));

/* ══ 1. the committed fixtures ══════════════════════════════════════════════ */

head('1. the committed fixtures parse, and are NASA lines rather than ours');
const vintDoc = readJSON('anchor-vintages.json');
const burnDoc = readJSON('reference-burn.json');
const archDoc = readJSON('archive-series.json');
ok('five vintages of the anchor instant', vintDoc.editions.length === 5);
ok('every vintage slice is a verbatim CCSDS OEM header plus rows',
  vintDoc.editions.every((e) => e.text.startsWith('CCSDS_OEM_VERS = 2.0') && /\nCOMMENT ISS first asc\. node/.test(e.text)));
ok('every vintage records the sha256 and byte count of the full file it was cut from',
  vintDoc.editions.every((e) => /^[0-9a-f]{64}$/.test(e.full_sha256) && e.full_bytes > 500000));
ok('the reboost slice carries NASA creation date, url and sha256',
  /^\d{4}-\d{2}-\d{2}T/.test(burnDoc.creation_date) && /^[0-9a-f]{64}$/.test(burnDoc.full_sha256));
ok('the archive series covers more than 700 editions', archDoc.rows.length > 700, `${archDoc.rows.length} rows`);

/* ══ 2. ANCHOR LEG 2: NASA against NASA, for one instant ════════════════════ */

head('2. anchor leg two: five editions publishing the same instant');
const T = Date.parse(vintDoc.anchor_instant + 'Z') / 1000;

/* The single most checkable thing on this page: a row of numbers NASA published and dated
   before this page existed, compared byte for byte with the committed slice. */
const PUBLISHED_2026_08_12 = '2026-08-14T12:00:00.000 6591.423537599330 -25.300909490443 -1658.182372159850 1.44582938859969 4.89314287640386 5.71444321522743';
const PUBLISHED_2026_08_14 = '2026-08-14T12:00:00.000 6591.121591909850 -26.472747757342 -1659.480071887710 1.44781932873404 4.89309645966469 5.71394513519510';

const vint = vintDoc.editions.map((e) => {
  const eph = O.parseOEM(e.text);
  const per = O.nodalPeriod(O.ascendingNodes(eph)).median;
  const st = O.stateAt(eph, T, { allowFine: true });
  const m = O.meanSMA(eph, T + per, per, { allowFine: true });
  const row = eph.states.find((s) => s.iso === vintDoc.anchor_instant);
  return { e, eph, per, st: st.ok ? st.state : null, a: m.ok ? m.mean : null, row: row ? row.raw : null };
});
const truth = vint[vint.length - 1];
ok('the 2026-08-12 edition\'s row for the anchor instant is byte for byte what NASA published',
  vint.find((v) => v.e.creation_date.startsWith('2026-08-12')).row === PUBLISHED_2026_08_12);
ok('the 2026-08-14 edition\'s row for the anchor instant is byte for byte what NASA published',
  truth.row === PUBLISHED_2026_08_14);

const vm = Math.hypot(truth.st.vx, truth.st.vy, truth.st.vz);
const rt = Math.hypot(truth.st.x, truth.st.y, truth.st.z);
const legs = [];
for (const v of vint.slice(0, -1)) {
  const dx = v.st.x - truth.st.x, dy = v.st.y - truth.st.y, dz = v.st.z - truth.st.z;
  const sep = Math.hypot(dx, dy, dz);
  const along = (dx * truth.st.vx + dy * truth.st.vy + dz * truth.st.vz) / vm;
  const dRad = Math.hypot(v.st.x, v.st.y, v.st.z) - rt;
  legs.push({ lead: v.e.lead_days, sep_km: sep, along_frac: along / sep, d_radius_m: dRad * 1000, da_m: (v.a - truth.a) * 1000, created: v.e.creation_date });
}
legs.sort((a, b) => a.lead - b.lead);
near('2 day lead: position error', +legs[0].sep_km.toFixed(3), 1.774, 0.001, ' km');
near('4 day lead: position error', +legs[1].sep_km.toFixed(3), 12.452, 0.001, ' km');
near('9 day lead: position error', +legs[2].sep_km.toFixed(3), 52.798, 0.001, ' km');
near('14 day lead: position error', +legs[3].sep_km.toFixed(3), 104.527, 0.001, ' km');
near('2 day lead: semi-major axis error', +legs[0].da_m.toFixed(1), -13.7, 0.1, ' m');
near('14 day lead: semi-major axis error', +legs[3].da_m.toFixed(1), -161.5, 0.2, ' m');
ok('the position error is essentially all along track', legs.every((l) => Math.abs(l.along_frac) > 0.999),
  legs.map((l) => (100 * l.along_frac).toFixed(2) + '%').join(' '));
ok('the position error grows monotonically with prediction lead',
  legs.every((l, i) => i === 0 || l.sep_km > legs[i - 1].sep_km));
const ratio = legs[3].sep_km * 1000 / Math.abs(legs[3].da_m);
ok('semi-major axis is hundreds of times better determined than position at the same lead',
  ratio > 400 && ratio < 900, `factor ${ratio.toFixed(0)}`);
ok('the page states that ratio rather than a position or an altitude',
  /reports a change in semi-major axis and never an altitude/.test(html.replace(/\s+/g, ' ')));

/* THE HONEST VERSION OF THE SAME COMPARISON, which the page used to get wrong by two orders of
   magnitude. It said a page quoting an altitude "would be quoting a number its own publisher
   revises by tens of kilometres". It would not: the hundred kilometres is a timing error, and
   the publisher's HEIGHT revision at the same lead is a third of a kilometre. The page now
   prints the radial column and the like-for-like factor, and here is the check on both. */
near('14 day lead: the part of the disagreement that is HEIGHT', +legs[3].d_radius_m.toFixed(0), -347, 2, ' m');
near('2 day lead: the part of the disagreement that is HEIGHT', +legs[0].d_radius_m.toFixed(0), -28, 2, ' m');
{
  const heightFactor = Math.abs(legs[3].d_radius_m) / Math.abs(legs[3].da_m);
  ok('semi-major axis beats height by about two, not by six hundred, and the page says two',
    heightFactor > 1.5 && heightFactor < 3, `factor ${heightFactor.toFixed(2)}`);
  ok('the page no longer claims the publisher revises an altitude by tens of kilometres',
    !/revises by tens of kilometres/.test(html.replace(/\s+/g, ' ')));
  ok('and it gives the three real reasons for reporting semi-major axis instead',
    /swings about twenty kilometres every ninety-three minutes/.test(html.replace(/\s+/g, ' ')) &&
    /needs a reference surface whose definition NASA does not publish/.test(html.replace(/\s+/g, ' ')) &&
    html.includes('id="a2-radial-ratio"'));
  ok('the height column is rendered from the fixtures rather than typed into the HTML',
    /of it height, m/.test(html) && /Math\.hypot\(d\.st\.x, d\.st\.y, d\.st\.z\) - rt/.test(js));
}

/* NEGATIVE CONTROL. The claim is that the SPREAD is real, not that any difference will do.
   Compare the truth edition against itself through the same code: it must be exactly zero. */
{
  const dz = O.stateAt(truth.eph, T, { allowFine: true }).state;
  const self = Math.hypot(dz.x - truth.st.x, dz.y - truth.st.y, dz.z - truth.st.z);
  ok('control: the truth edition differenced against itself is exactly zero', self === 0, `${self}`);
}

/* ══ 3. the reboost, and what a burn buys ═══════════════════════════════════ */

head('3. the reboost this page measures from');
const refEph = O.parseOEM(burnDoc.text);
const refFine = refEph.fine[0];
ok('NASA marks the burn by dropping to fine sampling', !!refFine && refFine.n > 200, `${refFine ? refFine.n : 0} samples`);
const burnStart = refEph.states[refFine.i0].t, burnEnd = refEph.states[refFine.i1].t;
const refPer = O.nodalPeriod(O.ascendingNodes(refEph)).median;
const tRef = burnEnd + WMAX;
const refEv = refEph.events.find((e) => e.dv_ms > 0);
ok('the event table names the burn and its delta-v', !!refEv && refEv.dv_ms > 0, refEv ? `${refEv.name} ${refEv.dv_ms} m/s at ${refEv.iso}` : '');
const aPre = O.meanSMA(refEph, burnStart, refPer);
const aRef = O.meanSMA(refEph, tRef, refPer);
ok('a mean is available on each side of the burn', aPre.ok && aRef.ok);
const stepM = (aRef.mean - aPre.mean) * 1000;
const nMotion = Math.sqrt(O.MU / aPre.mean ** 3);
const impM = 2 * refEv.dv_ms / 1000 / nMotion * 1000;
near('measured step across the 2026-07-01 burn', +stepM.toFixed(1), 1925.0, 0.5, ' m');
near('two-body prediction 2 dv / n', +impM.toFixed(1), 1952.6, 0.5, ' m');
ok('the two-body prediction is good to a few percent, so the page does not claim a finite-burn shortfall',
  Math.abs(stepM / impM - 1) < 0.05, `ratio ${(stepM / impM).toFixed(3)}`);
ok('the page prints the ratio as a measurement rather than the intuition',
  /the ratio\s*\n?\s*above is the measurement rather than the intuition/.test(html.replace(/\s+/g, ' ')) || /measurement rather than the intuition/.test(html));

/* The reference endpoint is NASA's MODEL of the burn. Check it against the editions NASA
   published afterwards, and use that disagreement as the uncertainty rather than inventing one. */
const later = archDoc.rows.filter((r) => r.t > burnEnd && r.t < burnEnd + 13 * 86400).map((r) => ({ t: r.t, a: r.a }));
const fit = O.fitDecay(later);
ok('at least four editions follow the burn inside a fortnight', later.length >= 4, `${later.length}`);
ok('they fall on a line whose slope beats its own uncertainty', fit.ok && fit.reportable,
  fit.ok ? `${fit.slope_m_per_day.toFixed(1)} +/- ${fit.slope_err_m_per_day.toFixed(1)} m/day, rms ${fit.rms_m.toFixed(1)} m` : '');
const extrap = later[0].a + (fit.slope_m_per_day / 1000 / 86400) * (tRef - later[0].t);
const sigmaRef = Math.abs((aRef.mean - extrap) * 1000);
near('the modelled post-burn value against the later editions run back to it', +sigmaRef.toFixed(1), SIGMA_REF_M, 0.3, ' m');
ok('that disagreement is what the page uses as the reference uncertainty',
  Math.abs(sigmaRef - SIGMA_REF_M) < 0.3);
near('the noise floor the page prints', +FLOOR_M.toFixed(0), 177, 1, ' m');

/* ══ 4. NEGATIVE CONTROLS: the interpolator, on doctored data ═══════════════ */

head('4. negative controls: doctor the DATA, never the code');

/* CONTROL A. Cut NASA's finely sampled burn block out of the ephemeris TEXT so the burn now
   hides inside an ordinary coarse gap. The same unmodified stateAt() must refuse, and it must
   refuse because it found the event in NASA's own table, not because it was told. */
{
  const a = refEph.states[refFine.i0], b = refEph.states[refFine.i1];
  const mid = refEph.states[refFine.i0 + Math.floor(refFine.n / 2)];
  const kept = burnDoc.text.split('\n').filter((line) => {
    const m = line.match(/^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3})\s/);
    if (!m) return true;
    const t = Date.parse(m[1] + 'Z') / 1000;
    return !(t > a.t && t < b.t);
  }).join('\n');
  const doctored = O.parseOEM(kept);
  ok('the doctored file really lost the burn block', doctored.fine.length === 0 && doctored.states.length < refEph.states.length,
    `${refEph.states.length - doctored.states.length} rows removed`);
  const guarded = O.stateAt(doctored, mid.t);
  ok('CONTROL: the same stateAt() refuses to interpolate across the hidden burn',
    guarded.ok === false && guarded.error === 'crosses_event', JSON.stringify(guarded));
  const anyway = O.stateAt(doctored, mid.t, { allowFine: true });
  const errKm = Math.hypot(anyway.state.x - mid.x, anyway.state.y - mid.y, anyway.state.z - mid.z);
  ok('CONTROL: the refusal is load-bearing, because interpolating anyway is wrong by kilometres',
    errKm > 1, `${errKm.toFixed(1)} km, against a headline measured in metres`);

  /* And the positive half of the same control: on the UNdoctored file, at a coasting instant,
     the same call must succeed. A guard that refused everything would also pass the test above. */
  const coast = O.stateAt(refEph, refEph.states[3].t + 120);
  ok('CONTROL, positive half: the same call succeeds on a coasting arc', coast.ok === true);
}

/* CONTROL B. An averaging window that straddles the burn must not return a mean. Without this
   guard the window ending one hour after the burn reports a 1332 m step where the truth is 1924. */
{
  const bad = O.meanSMA(refEph, burnEnd + 3600, refPer);
  ok('CONTROL: a window straddling the burn is refused', bad.ok === false && bad.error === 'window_crosses_event', JSON.stringify(bad));
  const badAnyway = O.meanSMA(refEph, burnEnd + 3600, refPer, { allowFine: true });
  const wrongStep = (badAnyway.mean - aPre.mean) * 1000;
  ok('CONTROL: and it would have been wrong by hundreds of metres', Math.abs(wrongStep - stepM) > 400,
    `${wrongStep.toFixed(0)} m against the true ${stepM.toFixed(0)} m`);
}

/* CONTROL C. HTTP 200 IS NOT FRESHNESS. Rewrite the CREATION_DATE of a genuinely old file to
   this minute, leaving the data untouched. That is precisely the failure two other feeds in
   this wave shipped: a recent header over data that stopped. freshness() must still refuse. */
{
  const nowIso = new Date().toISOString().replace('Z', '');
  const faked = burnDoc.text.replace(/CREATION_DATE\s*=.*/, `CREATION_DATE  = ${nowIso}`);
  const fakeEph = O.parseOEM(faked);
  const fr = O.freshness(fakeEph, Date.now() / 1000);
  ok('CONTROL: a fresh CREATION_DATE over stale data is still refused',
    fr.ok === false && fr.problems.some((p) => /newest state vector in the file/.test(p)), JSON.stringify(fr.problems));
  ok('CONTROL: and the same file with its real, old creation date is refused for both reasons',
    (() => { const f2 = O.freshness(refEph, Date.now() / 1000); return f2.ok === false && f2.problems.length >= 2; })());
}

/* CONTROL C2, and this is the one that caught a real defect. The control above rewrites the
   CREATION_DATE of a file whose HEADER SPAN is also old, so it passes whether freshness() reads
   the data or merely reads the header: it cannot tell the difference, and the version of
   freshness() shipped before this control read only the header. So rewrite the header the OTHER
   way instead. Take a file, move every header date forward so the header claims to cover this
   very moment, and leave the state vectors exactly where they were. That is a file whose header
   is a lie and whose contents are honest, which is the shape of the failure this page is loudest
   about, and it must be refused on the strength of the state vectors alone. */
{
  const nowSec = Date.now() / 1000;
  const iso = (t) => new Date(t * 1000).toISOString().replace('Z', '');
  const FIRST = refEph.states[0].t, LAST = refEph.states[refEph.states.length - 1].t;
  const SHIFT = nowSec - (FIRST + LAST) / 2;
  const dressed = burnDoc.text
    .replace(/CREATION_DATE\s*=.*/, `CREATION_DATE  = ${iso(nowSec - 3600)}`)
    .replace(/\bSTART_TIME\s*=.*/, `START_TIME           = ${iso(nowSec - 2 * 86400)}`)
    .replace(/\bSTOP_TIME\s*=.*/, `STOP_TIME            = ${iso(nowSec + 13 * 86400)}`)
    .replace(/USEABLE_START_TIME\s*=.*/, `USEABLE_START_TIME   = ${iso(nowSec - 2 * 86400)}`)
    .replace(/USEABLE_STOP_TIME\s*=.*/, `USEABLE_STOP_TIME    = ${iso(nowSec + 13 * 86400)}`);
  const de = O.parseOEM(dressed);
  ok('the doctored file really does have a header claiming to cover this moment',
    nowSec >= Date.parse(de.header.useable_start_time + 'Z') / 1000 && nowSec <= Date.parse(de.header.useable_stop_time + 'Z') / 1000,
    `${de.header.useable_start_time} to ${de.header.useable_stop_time}`);
  ok('and its state vectors are untouched and old',
    de.states.length === refEph.states.length && de.states[de.states.length - 1].t < nowSec - 30 * 86400,
    `newest state ${de.states[de.states.length - 1].iso}`);
  const fr = O.freshness(de, nowSec);
  ok('CONTROL: a header dressed to cover this moment over unchanged old data is REFUSED',
    fr.ok === false, JSON.stringify(fr.problems));
  ok('CONTROL: and it is refused on the state vectors, not on the header',
    fr.data_covers_now === false && fr.problems.some((p) => /newest state vector/.test(p)),
    JSON.stringify(fr.problems));
  ok('CONTROL: the header/data disagreement is reported as its own problem',
    fr.problems.some((p) => /header and the data disagree/.test(p)) && fr.header_data_skew_days > 30,
    `skew ${fr.header_data_skew_days} days`);
  /* The positive half. A control that refuses everything is not a control. */
  ok('CONTROL, positive half: the same function passes a file whose header and data agree',
    (() => {
      const shifted = burnDoc.text.split('\n').map((l) => {
        const m = l.match(/^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3})(\s.*)$/);
        if (!m) return l;
        return iso(Date.parse(m[1] + 'Z') / 1000 + SHIFT) + m[2];
      }).join('\n');
      const f = O.freshness(O.parseOEM(shifted.replace(/CREATION_DATE\s*=.*/, `CREATION_DATE  = ${iso(nowSec - 3600)}`)
        .replace(/\bSTART_TIME\s*=.*/, `START_TIME           = ${iso(FIRST + SHIFT)}`)
        .replace(/\bSTOP_TIME\s*=.*/, `STOP_TIME            = ${iso(LAST + SHIFT)}`)
        .replace(/USEABLE_START_TIME\s*=.*/, `USEABLE_START_TIME   = ${iso(FIRST + SHIFT)}`)
        .replace(/USEABLE_STOP_TIME\s*=.*/, `USEABLE_STOP_TIME    = ${iso(LAST + SHIFT)}`)), nowSec);
      return f.ok === true;
    })(), 'the same slice with BOTH its header and its rows moved to now must pass');
}

/* CONTROL D. Reflect the orbit through the equatorial plane in the DATA (negate z and vz on
   every state row). Every ascending node becomes a descending one, so the ascending count of
   the reflected file must equal the descending count of the original, computed here by an
   independent one-line oracle that shares no code with ascendingNodes(). */
{
  const flipped = burnDoc.text.split('\n').map((line) => {
    const f = line.split(/\s+/);
    if (f.length !== 7 || !/^\d{4}-\d{2}-\d{2}T/.test(f[0])) return line;
    const neg = (s) => (s.startsWith('-') ? s.slice(1) : '-' + s);
    return [f[0], f[1], f[2], neg(f[3]), f[4], f[5], neg(f[6])].join(' ');
  }).join('\n');
  const S = refEph.states;
  let descending = 0;
  for (let i = 1; i < S.length; i++) if (S[i - 1].z >= 0 && S[i].z < 0) descending++;
  const asc = O.ascendingNodes(refEph).length;
  const flippedAsc = O.ascendingNodes(O.parseOEM(flipped)).length;
  ok('CONTROL: reflecting the orbit turns every ascending node into a descending one',
    flippedAsc === descending && descending > 0, `reflected ascending ${flippedAsc}, original descending ${descending}, original ascending ${asc}`);
  ok('CONTROL: and the counter is not simply counting every sign change', asc !== asc + descending);
}

/* ══ 5. the window control, which is the largest free choice on the page ════ */

head('5. the averaging window, swept on the reference endpoint alone');
{
  const pts = [];
  for (let W = WMIN; W <= WMAX; W += 60) {
    const m = O.meanSMA(refEph, tRef, W);
    if (m.ok) pts.push({ W, a: m.mean });
  }
  ok('every window from 10 minutes to 4 hours evaluates without crossing the burn', pts.length === (WMAX - WMIN) / 60 + 1, `${pts.length} settings`);
  const as = pts.map((p) => p.a);
  const spread = (Math.max(...as) - Math.min(...as)) * 1000;
  ok('the choice of window moves this one endpoint by more than the noise floor',
    spread > FLOOR_M, `${spread.toFixed(0)} m against a floor of ${FLOOR_M.toFixed(0)} m`);
  const at = (W) => pts.reduce((a, b) => (Math.abs(b.W - W) < Math.abs(a.W - W) ? b : a));
  const one = at(refPer), two = at(2 * refPer);
  const agree = Math.abs(one.a - two.a) * 1000;
  ok('one revolution and two revolutions, entirely different windows, agree to a few metres',
    agree < 30, `${agree.toFixed(1)} m apart`);
  const between = pts.filter((p) => p.W > one.W && p.W < two.W);
  const worst = between.reduce((a, b) => (Math.abs(b.a - one.a) > Math.abs(a.a - one.a) ? b : a));
  const worstM = Math.abs(worst.a - one.a) * 1000;
  ok('while the worst window BETWEEN them is out by hundreds of metres, so averaging longer is not the fix',
    worstM > 20 * agree && worstM > 200, `${worstM.toFixed(0)} m at ${(worst.W / 60).toFixed(0)} min, against ${agree.toFixed(1)} m at two revolutions`);
  ok('and the deviation is still hundreds of metres at the longest window offered',
    Math.abs(pts[pts.length - 1].a - one.a) * 1000 > 100, `${(Math.abs(pts[pts.length - 1].a - one.a) * 1000).toFixed(0)} m at 4 hours`);
  ok('the page pins the window to one nodal revolution and says so',
    /pins the window at one nodal revolution/.test(html.replace(/\s+/g, ' ')));
  ok('and says plainly that averaging longer does not fix it',
    /Averaging (?:<em>)?longer(?:<\/em>)? does not fix it/.test(html.replace(/\s+/g, ' ')));
}

/* ══ 6. six years off one falling object ════════════════════════════════════ */

head('6. the six-year readout, recomputed from the committed series');
function seriesRates(arch, rule) {
  const rows = arch.rows.slice().sort((a, b) => a.t - b.t);
  const uniq = [];
  for (const r of rows) if (!uniq.length || r.t > uniq[uniq.length - 1].t + 60) uniq.push(r);
  const out = [];
  for (let i = 1; i < uniq.length; i++) {
    const A = uniq[i - 1], B = uniq[i];
    const dt = (B.t - A.t) / 86400;
    if (dt < 0.5 || dt > 8) continue;
    const rate = (B.a - A.a) * 1000 / dt;
    const manoeuvred = arch.events.some((e) => e.t > A.t && e.t < B.t);
    const keep = rule === 'events' ? !manoeuvred : (rate > -250 && rate < 0);
    if (keep) out.push({ t: B.t, year: new Date(B.t * 1000).getUTCFullYear(), rate });
  }
  return out;
}
const median = (a) => { const s = a.slice().sort((x, y) => x - y); const m = s.length >> 1; return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2; };
const byYear = {};
{
  const ev = seriesRates(archDoc, 'events'), nv = seriesRates(archDoc, 'naive');
  for (const y of [2021, 2022, 2023, 2024, 2025, 2026]) {
    const a = ev.filter((r) => r.year === y).map((r) => r.rate);
    const b = nv.filter((r) => r.year === y).map((r) => r.rate);
    if (a.length < 8) continue;
    byYear[y] = { n: a.length, median_m_per_day: +median(a).toFixed(1), naive_median: +median(b).toFixed(1) };
  }
  const yrs = Object.keys(byYear).map(Number).sort();
  ok('six years of medians', yrs.length === 6, yrs.join(', '));
  near('2021 median rate of fall', byYear[2021].median_m_per_day, -12.8, 0.1, ' m/day');
  near('2024 median rate of fall', byYear[2024].median_m_per_day, -117.2, 0.1, ' m/day');
  const ms = yrs.map((y) => Math.abs(byYear[y].median_m_per_day));
  const swing = Math.max(...ms) / Math.min(...ms);
  ok('the swing across the cycle is large', swing > 5, `${swing.toFixed(1)} times`);
  ok('the peak year is 2024, the year Solar Cycle 25 peaked',
    yrs.reduce((a, y) => (Math.abs(byYear[y].median_m_per_day) > Math.abs(byYear[a].median_m_per_day) ? y : a), yrs[0]) === 2024);
  ok('the two filters agree on the shape and disagree in detail, as the page says',
    yrs.every((y) => Math.sign(byYear[y].median_m_per_day) === Math.sign(byYear[y].naive_median)) &&
    yrs.some((y) => Math.abs(byYear[y].median_m_per_day - byYear[y].naive_median) > 1));
  ok('no solar index appears anywhere in the calculation',
    !/f10\.?7|sunspot|solar flux/i.test(fs.readFileSync(path.join(PAGE, 'oem.js'), 'utf8')) &&
    !/f10\.?7|sunspot number|solar flux/i.test(js));
  ok('the page refuses to call the correlation an attribution',
    /not a measurement of the thermosphere's temperature and it is not an attribution/.test(html.replace(/\s+/g, ' ')));
  ok('the unusable archive directories are named rather than quietly dropped',
    archDoc.missing_or_unusable.length === 6 && archDoc.missing_or_unusable.includes('2021-07-08'),
    archDoc.missing_or_unusable.join(', '));

  /* THE BUILDER MUST OBEY THE RULE THE PAGE SELLS. rebuild-fixtures.mjs used to pass
     { allowFine: true } for all 714 rows, switching off the refusal this page stages as its
     showpiece in the very code path that builds layer two. Two rows really did average across a
     reboost. This is the assertion that says it cannot happen again, checked against the file
     that shipped rather than against the script's intentions. */
  const builder = fs.readFileSync(path.join(HERE, 'rebuild-fixtures.mjs'), 'utf8');
  ok('the fixture builder does not switch off the burn guard when averaging an archived edition',
    !/meanSMA\([^)]*allowFine/.test(builder), 'allowFine must not appear in the archive builder\'s meanSMA call');
  ok('every shipped archive row carries the window it was averaged over', archDoc.rows.every((r) => r.w && r.t > r.w));
  ok('and NOT ONE of them averages across an event the merged ledger knows about',
    archDoc.rows.every((r) => !archDoc.events.some((e) => e.t > r.w && e.t < r.t && (e.dv === null || e.dv > 0))),
    `${archDoc.rows.length} rows`);
  ok('the rows dropped for straddling a burn are named on the page rather than vanished',
    Array.isArray(archDoc.dropped_across_burn) && archDoc.dropped_across_burn.length >= 2 &&
    html.includes('id="yr-dropped"') && /dropped_across_burn/.test(js),
    (archDoc.dropped_across_burn || []).join(', '));

  /* THE CALIBRATION FIGURES BESIDE THE DATED CLAIM, which nothing checked before. The page
     computes them with O.interReboostRates(); so does the scorer of the standing claim below;
     so does this. If any of the three drifts, this fails. */
  const cal = {};
  for (const y of [2024, 2025, 2026]) {
    const seg = O.interReboostRates(archDoc, { since: Date.UTC(y, 0, 1) / 1000, until: Date.UTC(y + 1, 0, 1) / 1000 });
    cal[y] = { n: seg.length, med: +O.medianOf(seg.map((s) => s.rate_m_per_day)).toFixed(1) };
  }
  near('2024 inter-reboost median, the figure printed beside the claim', cal[2024].med, -124.1, 0.1, ' m/day');
  near('2025 inter-reboost median, the figure printed beside the claim', cal[2025].med, -71.8, 0.1, ' m/day');
  near('2026 inter-reboost median, the figure printed beside the claim', cal[2026].med, -56.5, 0.1, ' m/day');
  ok('the number of 2026 stretches is seven, and the page no longer says eight',
    cal[2026].n === 7 && !/eight inter-reboost stretches/.test(html), `${cal[2026].n} stretches`);
  ok('the page derives those four figures live rather than hard-coding them',
    ['cal-2024', 'cal-2025', 'cal-2026', 'cal-2026-n'].every((i) => html.includes(`id="${i}"`) && js.includes(i.startsWith('cal-2026-n') ? "cal-2026-n" : 'cal-')),
    'the page must print them from interReboostRates()');
}

/* ══ 7. tonight's file ══════════════════════════════════════════════════════ */

head('7. tonight\'s file, the part that is different every time this runs');
let live = null;
if (OFFLINE) {
  console.log('  ..   skipped: --offline was passed, so the live half of this page is unverified');
} else {
  live = await getLive();
  ok('tonight\'s ephemeris was reachable', !!live && !!live.text, live ? `via ${live.via}, ${live.text.length} bytes` : 'unreachable');
}

let liveOut = null, tickOut = null, rhoOut = null;
if (live && live.text) {
  const eph = O.parseOEM(live.text);
  const now = Date.now() / 1000;
  const fr = O.freshness(eph, now);
  ok('the file covers this instant and is inside NASA\'s stated cadence', fr.ok, JSON.stringify(fr.problems));
  ok('the file parsed into thousands of state vectors', eph.states.length > 4000, `${eph.states.length}`);

  /* ANCHOR LEG 1, on tonight's own bytes: an integer with no convention to argue about. */
  const nodes = O.ascendingNodes(eph);
  const d = eph.nodes_declared;
  const declared = d.first && d.last ? d.last.orbit - d.first.orbit + 1 : null;
  ok('ANCHOR LEG 1: our independent node count equals NASA\'s published orbit range exactly',
    declared !== null && nodes.length === declared,
    `counted ${nodes.length}, NASA ${d.last ? d.last.orbit : '?'} - ${d.first ? d.first.orbit : '?'} + 1 = ${declared}`);

  /* The same reflection control, on the live file. */
  {
    const S = eph.states;
    let descending = 0;
    for (let i = 1; i < S.length; i++) if (S[i - 1].z >= 0 && S[i].z < 0) descending++;
    const flipped = live.text.split('\n').map((line) => {
      const f = line.split(/\s+/);
      if (f.length !== 7 || !/^\d{4}-\d{2}-\d{2}T/.test(f[0])) return line;
      const neg = (s) => (s.startsWith('-') ? s.slice(1) : '-' + s);
      return [f[0], f[1], f[2], neg(f[3]), f[4], f[5], neg(f[6])].join(' ');
    }).join('\n');
    ok('CONTROL: reflected ascending nodes equal the original descending nodes on tonight\'s file too',
      O.ascendingNodes(O.parseOEM(flipped)).length === descending, `${descending}`);
  }

  const per = O.nodalPeriod(nodes);
  ok('the nodal period is the ninety-three minutes it has to be', per.median > 5400 && per.median < 5700, `${per.median.toFixed(2)} s`);

  /* THE INTERPOLATION ERROR THE CHECK PANEL STATES AS A MEASUREMENT, actually measured. The page
     says cubic Hermite across an eight-minute span, tested by leaving out every interior sample
     in turn, is wrong by about 1.5 km at the middle, and that the fourth-power scaling of the
     Hermite remainder puts the four-minute spans actually used at about 95 m. Nothing re-ran it
     before this. It is a stated test result, so it gets run. */
  {
    const S = eph.states;
    const errs = [];
    for (let i = 1; i < S.length - 1; i++) {
      if (Math.abs((S[i + 1].t - S[i - 1].t) - 480) > 1) continue;
      const p = O.hermite(S[i - 1], S[i + 1], S[i].t);
      errs.push(Math.hypot(p.x - S[i].x, p.y - S[i].y, p.z - S[i].z));
    }
    errs.sort((a, b) => a - b);
    const med = errs[errs.length >> 1];
    ok('there are thousands of interior samples to leave out', errs.length > 3000, `${errs.length} spans`);
    near('leave-one-out error across an eight-minute span, the figure the page prints',
      +med.toFixed(2), 1.51, 0.1, ' km');
    near('and the same figure divided by sixteen, which is what the page calls about 95 m',
      +(med * 1000 / 16).toFixed(0), 95, 8, ' m');
    ok('the page states that measurement to the precision it can support',
      /wrong by about 1\.5 km at the middle/.test(html.replace(/\s+/g, ' ')) &&
      /about 95 m/.test(html.replace(/\s+/g, ' ')));
  }

  /* The near misses, asserted AS near misses. If one of these ever became exact we would
     want to know, because it would mean we had accidentally guessed NASA's convention. */
  const off0 = nodes[0].t - Date.parse(d.first.epoch + 'Z') / 1000;
  const lon0 = O.nodeLongitude(nodes[0].lan_deg, nodes[0].t);
  ok('the node epoch is close but NOT equal, and the page says so', Math.abs(off0) > 0.2 && Math.abs(off0) < 20, `${off0.toFixed(3)} s`);
  ok('the node longitude is close but NOT equal', Math.abs(lon0 - d.first.lan_deg) > 0.001 && Math.abs(lon0 - d.first.lan_deg) < 1,
    `${(lon0 - d.first.lan_deg).toFixed(5)} deg`);

  /* NASA's printed apogee and perigee heights, which we cannot reproduce and do not print. */
  const evLive = eph.events.filter((e) => e.dv_ms > 0);
  if (evLive.length && eph.fine.length) {
    const f0 = eph.fine[0];
    let rmin = 1e9, rmax = 0;
    for (const s of eph.states) {
      if (s.t < eph.states[f0.i1].t || s.t > eph.states[f0.i1].t + per.median) continue;
      const r = O.radius(s); if (r < rmin) rmin = r; if (r > rmax) rmax = r;
    }
    const ha = rmax - O.RE, hp = rmin - O.RE;
    ok('NASA\'s printed HA and HP are NOT reproducible from the state vectors, as the page states',
      Math.abs(ha - evLive[0].ha_km) > 0.2 || Math.abs(hp - evLive[0].hp_km) > 0.2,
      `ours ${ha.toFixed(2)} / ${hp.toFixed(2)}, NASA ${evLive[0].ha_km} / ${evLive[0].hp_km}`);
    ok('and the page does not print them as the station\'s altitude', !/HA|apogee height of/.test(html) || /does not print them as the station's altitude/.test(html.replace(/\s+/g, ' ')));
  }

  /* THE HEADLINE, at this instant. */
  /* The page's default: one nodal revolution at EACH end, each end using the period measured
     in its own file. The July and August files differ by about 1.4 s of period. */
  const aNow = O.meanSMA(eph, now, per.median);
  const aRefOwn = O.meanSMA(refEph, tRef, refPer);
  const laterBurn = archDoc.events.concat(eph.events.map((e) => ({ n: e.name, t: e.t, iso: e.iso, dv: e.dv_ms })))
    .filter((e) => e.dv > 0 && e.t > burnEnd + 3600 && e.t < now).sort((a, b) => a.t - b.t)[0];
  if (laterBurn) {
    ok('a reboost has happened since the committed reference, and the page refuses rather than reports',
      /cannot tell you the drop any more/.test(js), `${laterBurn.n} at ${laterBurn.iso}`);
    liveOut = { stale_reference: true, later_burn: laterBurn };
  } else if (!aNow.ok) {
    ok('tonight\'s endpoint refused, and the page has a path for that', /cannot be evaluated with a/.test(js), JSON.stringify(aNow));
    liveOut = { refused: aNow };
  } else {
    const drop_m = (aRefOwn.mean - aNow.mean) * 1000;
    const days = (now - tRef) / 86400;
    const rate = drop_m / days;
    ok('the headline is a fall rather than a rise', drop_m > 0, `${drop_m.toFixed(1)} m`);
    ok('the headline is above the page\'s own noise floor, so it is allowed to print a number',
      Math.abs(drop_m) > FLOOR_M, `${drop_m.toFixed(1)} m against ${FLOOR_M.toFixed(0)} m`);
    ok('the implied rate is in the range six years of archive says it should be',
      rate > 15 && rate < 130, `${rate.toFixed(1)} m/day`);

    /* WHAT THE FIFTEEN-SECOND TICK ACTUALLY DOES. The page refreshes the headline every fifteen
       seconds and used to print it to a tenth of a metre beside "about 1.65 m in the hour you
       might spend reading this", which invites the reader to watch the number fall at that rate.
       It does not: the residual ripple in a one-revolution mean is an order of magnitude larger
       than an hour of drag and its sign over a few minutes is a coin toss. This is the assertion
       that says so, and the page now prints the measured ripple rather than an implied one. */
    {
      const vals = [];
      for (let k = 0; k <= 240; k++) {
        const m = O.meanSMA(eph, now - 3600 + k * 15, per.median);
        if (m.ok) vals.push(m.mean * 1000);
      }
      const p2p = Math.max(...vals) - Math.min(...vals);
      let against = 0;
      for (let i = 1; i < vals.length; i++) if (vals[i] > vals[i - 1]) against++;
      const dragHour = rate / 24;
      ok('an hour of the headline can be sampled at the rate the page refreshes it', vals.length > 200, `${vals.length} samples`);
      ok('MEASURED: the ripple in the one-revolution mean is far larger than an hour of drag',
        p2p > 5 * Math.abs(dragHour), `${p2p.toFixed(1)} m of ripple against ${dragHour.toFixed(2)} m of drag per hour`);
      ok('MEASURED: and so the direction of the tick is not the direction of the fall',
        against > 0.25 * (vals.length - 1) && against < 0.75 * (vals.length - 1),
        `${against} of ${vals.length - 1} fifteen-second steps moved the wrong way`);
      ok('the page prints the ripple it measured rather than inviting the reader to watch the tick',
        html.includes('id="headline-ripple"') && /Do not watch the tick/.test(html) && /renderTickHonesty/.test(js));
      ok('and the headline is printed no finer than the metre, which is 177 times finer than its own floor already',
        /setHeadline\(fmt\(h\.drop_m, 0\)\)/.test(js));
      tickOut = { ripple_p2p_m: +p2p.toFixed(1), steps_against: against, of_steps: vals.length - 1, drag_per_hour_m: +dragHour.toFixed(2) };
    }
    ok('the rate agrees with the year\'s median to within a factor of two',
      Math.abs(rate / byYear[new Date(now * 1000).getUTCFullYear()].median_m_per_day) > 0.5 &&
      Math.abs(rate / byYear[new Date(now * 1000).getUTCFullYear()].median_m_per_day) < 2);

    /* The full window sweep, both endpoints, as the reader sees it. */
    const sweep = [];
    for (let W = WMIN; W <= WMAX; W += 60) {
      const r = O.meanSMA(refEph, tRef, W), n = O.meanSMA(eph, now, W);
      if (r.ok && n.ok) sweep.push({ W, m: (r.mean - n.mean) * 1000 });
    }
    const ms = sweep.map((s) => s.m);
    const spread = Math.max(...ms) - Math.min(...ms);
    ok('the window sweep evaluates across the whole slider', sweep.length > 200, `${sweep.length} settings`);
    ok('the window moves the headline by more than the noise floor', spread > FLOOR_M, `${spread.toFixed(0)} m`);

    /* NASA's own forecast of the rate, from the same file, as a second opinion on our own.
       It has to be fitted inside ONE coasting stretch. Fitting the whole file instead is the
       same mistake as averaging across a burn, and this is where it was caught: the whole-file
       fit returns a POSITIVE rate, with a slope that still beats its own uncertainty. A slope
       test on its own would have passed it. So the assertions below test the sign and the
       scatter, and the whole-file fit is kept as a live negative control. */
    const pts = [], coastPts = [];
    let c0 = eph.states[0].t, c1 = eph.states[eph.states.length - 1].t;
    for (const e of eph.events) {
      if (!(e.dv_ms > 0)) continue;
      if (e.t <= now && e.t > c0) c0 = e.t;
      if (e.t > now && e.t < c1) c1 = e.t;
    }
    for (const r of eph.fine) {
      if (eph.states[r.i1].t <= now && eph.states[r.i1].t > c0) c0 = eph.states[r.i1].t;
      if (eph.states[r.i0].t > now && eph.states[r.i0].t < c1) c1 = eph.states[r.i0].t;
    }
    for (const nd of nodes.slice(0, -1)) {
      const m = O.meanSMA(eph, nd.t + per.median, per.median);
      if (!m.ok) continue;
      const pt = { t: nd.t + per.median, a: m.mean };
      pts.push(pt);
      if (pt.t >= c0 && pt.t <= c1) coastPts.push(pt);
    }
    const liveFit = O.fitDecay(coastPts);
    const naiveFit = O.fitDecay(pts);
    ok('NASA\'s own file forecasts a FALL, fitted inside one coasting stretch',
      liveFit.ok && liveFit.reportable && liveFit.slope_m_per_day < 0,
      liveFit.ok ? `${liveFit.slope_m_per_day.toFixed(1)} +/- ${liveFit.slope_err_m_per_day.toFixed(1)} m/day, rms ${liveFit.rms_m.toFixed(1)} m` : '');
    ok('the coasting fit is tight, which is what says it is a fit of one orbit',
      liveFit.ok && liveFit.rms_m < 50, liveFit.ok ? `${liveFit.rms_m.toFixed(1)} m of scatter` : '');
    if (coastPts.length < pts.length) {
      ok('CONTROL: the same fit run across the burn returns a RISING orbit and would have passed a slope test',
        naiveFit.ok && naiveFit.slope_m_per_day > 0 && naiveFit.reportable,
        `${naiveFit.slope_m_per_day.toFixed(1)} +/- ${naiveFit.slope_err_m_per_day.toFixed(1)} m/day, rms ${naiveFit.rms_m.toFixed(0)} m`);
      ok('CONTROL: and its scatter is what gives it away, by more than an order of magnitude',
        naiveFit.rms_m > 10 * liveFit.rms_m, `${naiveFit.rms_m.toFixed(0)} m against ${liveFit.rms_m.toFixed(1)} m`);
      ok('the page shows that comparison rather than only the good fit', /the same fit, run across the burn/.test(html));
    }

    /* THE ONE PHYSICAL CLAIM ON THE PAGE THAT WAS NOT DERIVED FROM ANYTHING. It said the air up
       there is "a hundred trillion times thinner" than the air in this room; inverting the drag
       rate the page itself fits gives under a trillion, so the assertion was out by a factor of
       about a hundred and fifty and the page's own instrument was what falsified it. The figure
       is now computed, by the page and by this check, the same way. */
    if (liveFit.ok && liveFit.slope_m_per_day < 0 && eph.header.mass_kg && eph.header.drag_area_m2 && eph.header.drag_coeff) {
      const hd = eph.header;
      const aKm = coastPts[coastPts.length - 1].a;
      const vCirc = Math.sqrt(O.MU / aKm) * 1000;
      const rho = -(liveFit.slope_m_per_day / 86400) / ((hd.drag_coeff * hd.drag_area_m2 / hd.mass_kg) * vCirc * (aKm * 1000));
      const ratio = 1.225 / rho;
      ok('the thermospheric density inverted from the page\'s own fit lands in the 1e-13 to 1e-11 band',
        rho > 1e-13 && rho < 1e-11, `${rho.toExponential(2)} kg/m3 from ${liveFit.slope_m_per_day.toFixed(1)} m/day, ${hd.mass_kg} kg over ${hd.drag_area_m2} m2 at Cd ${hd.drag_coeff}`);
      ok('which is between a hundred billion and ten trillion times thinner than sea level, and NOT a hundred trillion',
        ratio > 1e11 && ratio < 1e13, `${ratio.toExponential(2)} times`);
      ok('the page no longer asserts a hundred trillion and derives the figure in front of the reader instead',
        !/a hundred trillion times thinner/.test(html) && html.includes('id="air-thin"') && /renderAirDensity/.test(js));
      rhoOut = { rho_kg_m3: rho.toExponential(3), times_thinner_than_sea_level: ratio.toExponential(3) };
    }

    liveOut = {
      creation_date: eph.header.creation_date,
      upstream_last_modified: live.last_modified,
      bytes: live.text.length, via: live.via,
      n_states: eph.states.length,
      nodes_counted: nodes.length, nodes_declared: declared, leg1_exact: nodes.length === declared,
      nodal_period_s: +per.median.toFixed(3),
      a_now_km: +aNow.mean.toFixed(6), a_ref_km: +aRefOwn.mean.toFixed(6),
      nodal_period_ref_s: +refPer.toFixed(3),
      drop_m: +drop_m.toFixed(1), days_since_reboost: +days.toFixed(3),
      rate_m_per_day: +rate.toFixed(2),
      window_spread_m: +spread.toFixed(0),
      nasa_forecast_rate_m_per_day: liveFit.ok ? +liveFit.slope_m_per_day.toFixed(2) : null,
      nasa_forecast_rate_err: liveFit.ok ? +liveFit.slope_err_m_per_day.toFixed(2) : null,
      nasa_forecast_rms_m: liveFit.ok ? +liveFit.rms_m.toFixed(1) : null,
      whole_file_fit_m_per_day: naiveFit.ok ? +naiveFit.slope_m_per_day.toFixed(2) : null,
      whole_file_fit_rms_m: naiveFit.ok ? +naiveFit.rms_m.toFixed(0) : null,
      events: eph.events.map((e) => ({ name: e.name, iso: e.iso, dv_ms: e.dv_ms ?? null })),
    };
  }
}

/* ══ 8. the forward claims, scored ══════════════════════════════════════════ */

head('8. the forward claims');

/**
 * The step across a burn, measured from the archive series, DE-TRENDED.
 *
 * This used to be "the last archive row a day before the burn subtracted from the first row a
 * day after it", and that is not the step: those two rows are four to fourteen days apart and
 * the station falls at forty to sixty metres a day in between. Run the old estimator on the
 * 2026-07-01 burn this page measures directly and it returns 1.418 km against the page's own
 * 1.925 km, an under-read of half a kilometre, which is nearly twice the width of the band the
 * claim is scored against. It would have marked a correct prediction FAILED.
 *
 * So: fit a line through the rows either side, run each line to the burn instant, and difference
 * there. That is the same de-trending the page already does to check NASA's burn model against
 * the editions published after it. It is checked below against the July burn, where the page has
 * an independent measurement from the ephemeris itself.
 */
function stepAcrossBurn(archive, t, { n = 4 } = {}) {
  const rows = archive.rows.slice().sort((a, b) => a.t - b.t);
  const before = rows.filter((r) => r.t < t - 86400).slice(-n);
  const after = rows.filter((r) => r.t > t + 86400).slice(0, n);
  if (before.length < 3 || after.length < 3) return { ok: false, before: before.length, after: after.length };
  const fPre = O.fitDecay(before.map((r) => ({ t: r.t, a: r.a })));
  const fPost = O.fitDecay(after.map((r) => ({ t: r.t, a: r.a })));
  if (!fPre.ok || !fPost.ok) return { ok: false, reason: 'a side would not fit' };
  const preAt = before[0].a + (fPre.slope_m_per_day / 1000 / 86400) * (t - before[0].t);
  const postAt = after[0].a + (fPost.slope_m_per_day / 1000 / 86400) * (t - after[0].t);
  return {
    ok: true, step_km: postAt - preAt,
    naive_step_km: after[0].a - before[before.length - 1].a,
    gap_days: +((after[0].t - before[before.length - 1].t) / 86400).toFixed(2),
    pre_slope: +fPre.slope_m_per_day.toFixed(1), post_slope: +fPost.slope_m_per_day.toFixed(1),
    pre_rows: before.map((r) => r.d), post_rows: after.map((r) => r.d),
  };
}

/** Claim 1: the 2026-08-27 Cygnus reboost steps the mean semi-major axis up by 1.95 to 2.25 km,
 *  and fourteen days later drag has taken back 0.40 to 0.65 km of it. BOTH halves are scored;
 *  the second half used to be printed on the page with nothing anywhere that could score it. */
function scoreBurnClaim(archive, liveEvents) {
  const target = { iso: '2026-08-27T16:53:00.000', lo_km: 1.95, hi_km: 2.25, back_lo: 0.40, back_hi: 0.65 };
  const t = Date.parse(target.iso + 'Z') / 1000;
  const s = stepAcrossBurn(archive, t);
  const planned = (liveEvents || []).find((e) => e.iso === target.iso);
  if (!s.ok) {
    return { claim: 'burn_step', status: 'pending', reason: 'the archive committed with this page does not yet reach far enough either side of the burn', detail: s, still_planned: !!planned };
  }
  return {
    claim: 'burn_step', method: 'de-trended: a line through four archive rows each side, run to the burn instant',
    status: s.step_km >= target.lo_km && s.step_km <= target.hi_km ? 'held' : 'failed',
    step_km: +s.step_km.toFixed(3), naive_step_km: +s.naive_step_km.toFixed(3),
    gap_days: s.gap_days, band: [target.lo_km, target.hi_km],
  };
}

/** The second half of claim 1: how much of the step drag has taken back a fortnight later. */
function scoreGiveBackClaim(archive) {
  const target = { iso: '2026-08-27T16:53:00.000', lo: 0.40, hi: 0.65 };
  const t = Date.parse(target.iso + 'Z') / 1000;
  const rows = archive.rows.slice().sort((a, b) => a.t - b.t);
  const s = stepAcrossBurn(archive, t);
  // The peak is the post-burn line run to the burn; the fortnight point is the archive row
  // nearest t + 14 days, and it must not be on the far side of the NEXT burn.
  const nextBurn = archive.events.filter((e) => e.dv > 0 && e.t > t + 2 * 86400).sort((a, b) => a.t - b.t)[0];
  const window = rows.filter((r) => r.t > t + 13 * 86400 && r.t < t + 15 * 86400 && (!nextBurn || r.t < nextBurn.t));
  if (!s.ok || !window.length) {
    return { claim: 'burn_give_back', status: 'pending', reason: 'the archive does not yet carry an edition fourteen days after the burn on the near side of the next one', have_step: !!s.ok };
  }
  const fPost = O.fitDecay(rows.filter((r) => r.t > t + 86400).slice(0, 4).map((r) => ({ t: r.t, a: r.a })));
  const peak = rows.filter((r) => r.t > t + 86400)[0].a - (fPost.slope_m_per_day / 1000 / 86400) * (rows.filter((r) => r.t > t + 86400)[0].t - t);
  const back = peak - window[0].a;
  return {
    claim: 'burn_give_back', status: back >= target.lo && back <= target.hi ? 'held' : 'failed',
    taken_back_km: +back.toFixed(3), at: window[0].d, band: [target.lo, target.hi],
  };
}

/** Claim 2: the median inter-reboost rate over the year after ship lands in 25 to 65 m/day.
 *  Delegates to O.interReboostRates(), which is what the page prints its calibration from. */
function scoreRateClaim(archive, sinceIso, band = [-65, -25], untilIso = null) {
  const since = Date.parse(sinceIso + 'Z') / 1000;
  const until = untilIso ? Date.parse(untilIso + 'Z') / 1000 : Infinity;
  const seg = O.interReboostRates(archive, { since, until }).map((s) => s.rate_m_per_day);
  if (seg.length < 3) return { claim: 'inter_reboost_rate', status: 'pending', segments: seg.length, since: sinceIso };
  const med = O.medianOf(seg);
  return { claim: 'inter_reboost_rate', status: med >= band[0] && med <= band[1] ? 'held' : 'failed', median_m_per_day: +med.toFixed(1), segments: seg.length, band, since: sinceIso };
}

/* THE SCORER, CALIBRATED AGAINST A BURN THE PAGE MEASURES A DIFFERENT WAY. The July reboost is
   the one place both routes exist: the ephemeris itself gives 1925 m from nodal-revolution means
   either side of the burn block, and the archive scorer sees only one number per edition. If the
   scorer cannot recover the answer on the burn where the truth is known, it is not fit to score
   the burn where it is not. This assertion is the reason the estimator changed. */
{
  const tJul = refEv.t;
  const s = stepAcrossBurn(archDoc, tJul);
  ok('the burn scorer reproduces the July step the ephemeris measures directly, to under 100 m',
    s.ok && Math.abs(s.step_km * 1000 - stepM) < 100,
    s.ok ? `de-trended ${(s.step_km * 1000).toFixed(0)} m against the ephemeris ${stepM.toFixed(0)} m, over a ${s.gap_days} day gap` : JSON.stringify(s));
  ok('CONTROL: and the estimator it replaced does NOT, which is why it was replaced',
    s.ok && Math.abs(s.naive_step_km * 1000 - stepM) > 300,
    s.ok ? `undetrended ${(s.naive_step_km * 1000).toFixed(0)} m against ${stepM.toFixed(0)} m, an under-read of ${((s.step_km - s.naive_step_km) * 1000).toFixed(0)} m across ${s.gap_days} days of drag` : '');
  ok('CONTROL: the correction is larger than the width of the band the claim is scored against',
    s.ok && Math.abs(s.step_km - s.naive_step_km) > (2.25 - 1.95),
    s.ok ? `${((s.step_km - s.naive_step_km) * 1000).toFixed(0)} m against a 300 m band` : '');
}

const claims = [
  scoreBurnClaim(archDoc, liveOut ? liveOut.events : null),
  scoreGiveBackClaim(archDoc),
  scoreRateClaim(archDoc, '2026-08-15'),
];
for (const c of claims) console.log(`  ..   ${c.claim}: ${c.status}  ${JSON.stringify(c)}`);
ok('every forward claim is scored to held, failed or pending, never silently skipped',
  claims.every((c) => ['held', 'failed', 'pending'].includes(c.status)));
ok('both halves of the dated burn claim have a scorer, not just the step',
  claims.some((c) => c.claim === 'burn_step') && claims.some((c) => c.claim === 'burn_give_back'));

/* CONTROL: the scorer must be able to say "failed". A scorer that only ever returns held or
   pending is not a scorer. Feed it a band the archive cannot possibly satisfy. */
{
  const impossible = scoreRateClaim(archDoc, '2021-01-01', [1000, 2000]);
  ok('CONTROL: the rate scorer returns failed when handed a band the data cannot meet',
    impossible.status === 'failed', JSON.stringify(impossible));
  const generous = scoreRateClaim(archDoc, '2021-01-01', [-1000, 0]);
  ok('CONTROL: and returns held when handed one it can', generous.status === 'held', JSON.stringify(generous));

  /* And the same for the burn scorer, which had no failure control at all: score the July burn,
     whose step is known to be 1.925 km, against a band it cannot meet and one it can. */
  const jul = refEv.t;
  const s = stepAcrossBurn(archDoc, jul);
  ok('CONTROL: the burn scorer can say failed, tested on a burn whose step is known',
    s.ok && !(s.step_km >= 5 && s.step_km <= 6), `the July step ${s.step_km.toFixed(3)} km is not in a 5 to 6 km band`);
  ok('CONTROL: and held, on the same burn against the band the page would have claimed',
    s.ok && s.step_km >= 1.85 && s.step_km <= 2.05, `${s.step_km.toFixed(3)} km`);
}

/* Historical scoring of claim 2 over the year before ship, as a calibration of the band. */
{
  const back = scoreRateClaim(archDoc, '2025-08-15', [-65, -25]);
  console.log(`  ..   calibration: the same claim scored over the twelve months BEFORE ship: ${JSON.stringify(back)}`);
}

/* ══ 8b. the page as the reader gets it ═════════════════════════════════════ */
/* Everything above re-derives the numbers. That is worth having and it is not the same as
 * checking the page: a re-derivation stays green if the page renders nothing at all. So this
 * stage serves public/ over a local socket, mocks /api/feed/nasa-iss-oem with tonight's real
 * bytes, opens the page in a real browser, and reads the figures out of the DOM. */

head('8b. the page, opened in a browser and read out of the DOM');
let browserOut = { status: 'skipped' };
let subfloorScale = null;
const refusals = {};
if (NO_BROWSER) {
  console.log('  ..   skipped: --no-browser');
} else if (!live || !live.text) {
  console.log('  ..   skipped: there is no live ephemeris to serve the page');
} else {
  let chromium = null;
  try { ({ chromium } = await import('playwright')); } catch { chromium = null; }
  if (!chromium) {
    browserOut = { status: 'unavailable', reason: 'playwright did not resolve' };
    console.log('  ..   SKIPPED, and this is recorded as a gap rather than a pass: playwright did not resolve, so nothing here has checked what the reader sees');
  } else {
    const http = await import('node:http');
    const PUBLIC = path.join(HERE, '../../public');
    const TYPES = { '.html': 'text/html', '.css': 'text/css', '.js': 'text/javascript', '.json': 'application/json', '.woff2': 'font/woff2', '.svg': 'image/svg+xml', '.ico': 'image/x-icon', '.png': 'image/png' };
    /* FOUR FEEDS, NOT ONE. A stage that serves only the good file tests only the half that was
       never going to fail. `feedMode` is what the served /api/feed returns, and each doctored
       variant is made from tonight's REAL bytes:
         good      exactly what the proxy would return
         down      the proxy failing, which the kit turns into feed.ok === false
         stale     HTTP 200, valid parse, plausible values, every state epoch a year older and
                   the header left byte-identical, which is the failure two other feeds in this
                   wave actually shipped
         subfloor  a Kepler-scaled orbit (r -> kr, v -> v/sqrt(k), so a -> ka exactly) chosen so
                   the drop lands under this page's own 177 m noise floor
       Nothing about the page changes between them. Only the bytes it is given. */
    let feedMode = 'good';
    const shiftYear = (txt, dy) => txt.split('\n').map((l) => {
      const m = l.match(/^(\d{4})(-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}\s)/);
      return m ? (Number(m[1]) + dy) + l.slice(4) : l;
    }).join('\n');
    const keplerScale = (txt, k) => txt.split('\n').map((l) => {
      const f = l.trim().split(/\s+/);
      if (f.length !== 7 || !/^\d{4}-\d{2}-\d{2}T/.test(f[0])) return l;
      const s = Math.sqrt(k);
      return [f[0], ...[1, 2, 3].map((i) => (+f[i] * k).toFixed(12)), ...[4, 5, 6].map((i) => (+f[i] / s).toFixed(14))].join(' ');
    }).join('\n');
    const FEEDS = {
      good: () => live.text,
      nofixture: () => live.text,   // the feed is fine; a committed fixture is 404
      stale: () => shiftYear(live.text, -1),
      subfloor: null, // filled in below, once the scale needed is known
    };
    const srv = http.createServer((req, res) => {
      let p = decodeURIComponent(req.url.split('?')[0]);
      if (p.startsWith('/api/feed/nasa-iss-oem')) {
        if (feedMode === 'down') { res.writeHead(502, { 'content-type': 'application/json' }); return res.end(JSON.stringify({ ok: false, key: 'nasa-iss-oem', error: 'upstream_502' })); }
        res.writeHead(200, { 'content-type': 'application/json' });
        return res.end(JSON.stringify({ ok: true, key: 'nasa-iss-oem', upstream: UPSTREAM, licence: 'NASA/JSC/FOD/TOPO. US Government work.', cadence: 'About three times a week.', fetched_at: new Date().toISOString(), upstream_last_modified: live.last_modified, text: FEEDS[feedMode]() }));
      }
      if (feedMode === 'nofixture' && p.endsWith('/data/reference-burn.json')) { res.writeHead(404); return res.end('404'); }
      if (p.endsWith('/')) p += 'index.html';
      try {
        const b = fs.readFileSync(path.join(PUBLIC, p));
        res.writeHead(200, { 'content-type': TYPES[path.extname(p)] || 'application/octet-stream' });
        res.end(b);
      } catch { res.writeHead(404); res.end('404'); }
    });
    /* The scale that puts the drop just under the floor. A closed form would be k = 1 + (drop -
       90 m)/a, since a -> ka exactly under this transform; it is not used, because the trapezoid
       interpolates its two endpoints and cubic Hermite mixes positions (scaled by k) with
       velocities (scaled by 1/sqrt k), so the mean is only approximately scaled. Rather than
       assume, the scale is SEARCHED against the same meanSMA the page runs, and then asserted
       to have landed under the floor before the browser is ever pointed at it. */
    {
      const nowK = Date.now() / 1000;
      const aRefK = O.meanSMA(refEph, tRef, refPer).mean;
      const dropAt = (k) => {
        const e = O.parseOEM(keplerScale(live.text, k));
        const p = O.nodalPeriod(O.ascendingNodes(e));
        const m = O.meanSMA(e, nowK, p.median);
        return m.ok ? (aRefK - m.mean) * 1000 : NaN;
      };
      let lo = 1, hi = 1 + (liveOut ? liveOut.drop_m : 2000) / 1000 / 6797 * 1.5, k = hi;
      for (let i = 0; i < 24; i++) {
        k = (lo + hi) / 2;
        const d = dropAt(k);
        if (!Number.isFinite(d)) break;
        if (d > 90) lo = k; else hi = k;
        if (Math.abs(d - 90) < 5) break;
      }
      const landed = dropAt(k);
      ok('the sub-floor control really does put the drop under this page\'s own noise floor',
        Number.isFinite(landed) && Math.abs(landed) < FLOOR_M,
        `Kepler scale ${k.toFixed(9)} leaves a drop of ${landed.toFixed(0)} m against a ${FLOOR_M.toFixed(0)} m floor`);
      FEEDS.subfloor = () => keplerScale(live.text, k);
      subfloorScale = { k: +k.toFixed(9), drop_m: +landed.toFixed(1) };
    }
    const port = 8700 + (process.pid % 90);
    await new Promise((r) => srv.listen(port, r));
    const browser = await chromium.launch();
    try {
      const pg = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
      const errs = [];
      pg.on('pageerror', (e) => errs.push(String(e)));
      pg.on('console', (m) => { if (m.type() === 'error') errs.push(m.text()); });
      await pg.goto(`http://localhost:${port}/strata/lower-than-when-you-last-looked/`, { waitUntil: 'networkidle' });
      await pg.waitForTimeout(1500);
      const read = async (id) => (await pg.textContent('#' + id)) || '';
      const num = (s) => parseFloat(String(s).replace(/,/g, '').replace(/[^0-9.eE+-]/g, ' ').trim().split(/\s+/)[0]);

      ok('the page threw no JavaScript errors', errs.length === 0, errs.slice(0, 3).join(' | '));
      const domCount = (await read('a1-counted')).trim();
      ok('the ANCHOR the reader sees is the count this verifier computed',
        liveOut && String(liveOut.nodes_counted) === domCount, `DOM "${domCount}", here ${liveOut ? liveOut.nodes_counted : '?'}`);
      ok('the reader sees the anchor verdict as an exact match', (await read('a1-verdict')).includes('exact match'));
      const domDrop = num(await read('headline-num'));
      ok('the headline the reader sees is the headline this verifier computed, to under a metre',
        liveOut && Number.isFinite(domDrop) && Math.abs(domDrop - liveOut.drop_m) < 1,
        `DOM ${domDrop} m, here ${liveOut ? liveOut.drop_m : '?'} m`);
      /* The headline is deliberately printed to the metre and the check panel's arithmetic to a
         tenth, so the strict test is not "these two strings agree to 0.15 m". It is two tests:
         the panel's own subtraction has to be internally consistent to the millimetre, and it
         has to round to the headline. A stale panel fails the second by hundreds of metres. */
      const arith = await read('ck-arith');
      const parts = arith.match(/([\d.]+) km minus ([\d.]+) km = ([\d.-]+) km = ([\d.-]+) m/);
      ok('the check panel prints an internally consistent subtraction',
        !!parts && Math.abs((+parts[1] - +parts[2]) - +parts[3]) < 1e-6 && Math.abs(+parts[3] * 1000 - +parts[4]) < 0.06, arith);
      ok('and it rounds to the headline the reader sees, so it cannot be a stale one',
        !!parts && Math.abs(Math.round(+parts[4]) - domDrop) < 1, `panel ${parts ? parts[4] : '?'} m, headline ${domDrop} m`);
      ok('the reader is told whether the source moved since last time',
        /first time this browser|has NOT been rewritten|has been rewritten|cannot be determined/.test(await read('visit')));
      ok('the freshness verdict is rendered', (await read('fresh-verdict')).trim().length > 0);
      ok('the five vintage rows rendered', await pg.evaluate(() => document.querySelectorAll('#a2-body tr').length) === 5);
      ok('six annual rows rendered', await pg.evaluate(() => document.querySelectorAll('#yr-body tr').length) === 6);
      ok('both charts drew', await pg.evaluate(() => !!document.querySelector('#sweep svg') && !!document.querySelector('#series svg')));
      ok('every readout has been filled in, none left as a placeholder',
        await pg.evaluate(() => [...document.querySelectorAll('.stat .v, .num, .big')].every((e) => e.textContent.trim() !== '?')));
      /* The figures the page derives in prose rather than in a stat box. Each of these replaced
         something that used to be typed into the HTML, so "it still says ?" is exactly the
         regression to catch. */
      {
        const derived = await pg.evaluate((ids) => Object.fromEntries(ids.map((i) => [i, (document.getElementById(i) || {}).textContent])),
          ['air-thin', 'headline-ripple', 'a2-along', 'a2-radial', 'a2-radial-ratio', 'cal-2024', 'cal-2025', 'cal-2026', 'cal-2026-n', 'yr-dropped', 'ck-sigmaref']);
        ok('every figure the page derives in prose is filled in, not left as a placeholder',
          Object.values(derived).every((v) => typeof v === 'string' && v.trim() !== '' && v.trim() !== '?'), JSON.stringify(derived));
        ok('the reader is shown seven 2026 stretches and the calibration medians this run computed',
          derived['cal-2026-n'] === '7' && derived['cal-2026'] === '56.5' && derived['cal-2025'] === '71.8' && derived['cal-2024'] === '124.1',
          `${derived['cal-2026-n']} / ${derived['cal-2026']} / ${derived['cal-2025']} / ${derived['cal-2024']}`);
        ok('the height column and the like-for-like factor are rendered, not asserted in prose',
          /^-?\d+ m$/.test(derived['a2-radial'].trim()) && Math.abs(parseFloat(derived['a2-radial-ratio']) - 2.1) < 0.5,
          `${derived['a2-radial']}, factor ${derived['a2-radial-ratio']}`);
      }

      // The differential control, driven the way a reader drives it.
      await pg.click('#interp-run');
      await pg.waitForTimeout(400);
      const interp = await read('interp-out');
      ok('the reader can run the interpolation control and it refuses', /refuses: crosses_event/.test(interp), interp.slice(0, 120));
      ok('and it reports the size of the error the refusal prevents', /km from where NASA says/.test(interp));
      ok('the control did not report a guard failure', !/THE GUARD FAILED/.test(interp));

      // The window control, driven the way a reader drives it.
      const before = num(await read('headline-num'));
      await pg.locator('#win').evaluate((e) => { e.value = '900'; e.dispatchEvent(new Event('input', { bubbles: true })); });
      await pg.waitForTimeout(500);
      const after = num(await read('headline-num'));
      ok('dragging the window really moves the number the reader sees',
        Math.abs(after - before) > FLOOR_M, `${before} m at one revolution, ${after} m at fifteen minutes`);
      /* THE SECOND VACUOUS SETTING, driven. At fifteen minutes the arithmetic still returns a
         confident-looking number and the slab used to print it in the page's own voice with
         nothing beside it. The refusal has to be AT the number, not three paragraphs away. */
      const offBox = (await read('headline-box')).trim();
      ok('at a window that is not a whole revolution the slab disowns its own number, at the number',
        /That is your window, not this page's/.test(offBox) && /nodal revolutions/.test(offBox), offBox.slice(0, 160));
      ok('and it says how far off that setting is from the defensible one',
        /At one whole revolution the same data read/.test(offBox));
      await pg.click('#win-reset');
      await pg.waitForTimeout(500);
      ok('and the reset control puts it back', Math.abs(num(await read('headline-num')) - before) < 5);
      ok('with the disowning notice gone once it is back on one revolution',
        !/That is your window/.test((await read('headline-box')).trim()));

      // The one thing a re-derivation can never see.
      const overflow = {};
      for (const width of [390, 768, 1440]) {
        await pg.setViewportSize({ width, height: 900 });
        await pg.waitForTimeout(250);
        overflow[width] = await pg.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
      }
      ok('no horizontal overflow at 390, 768 or 1440 px', Object.values(overflow).every((v) => v <= 0), JSON.stringify(overflow));
      await pg.setViewportSize({ width: 1440, height: 1000 });

      /* ── THE HALF THAT WAS NEVER DRIVEN ───────────────────────────────────────
         Everything above is the success path. This page's whole argument is about what it does
         when the data are bad, and until now not one of those paths was exercised end to end:
         the three assertions that mentioned refusal were regex tests on page.js source, inside
         branches that never ran. So the feed is broken three different ways and the page is
         reloaded against each, and what the reader would actually see is read out of the DOM. */
      const load = async (mode) => {
        feedMode = mode;
        const e2 = [];
        pg.removeAllListeners('pageerror');
        pg.on('pageerror', (x) => e2.push(String(x)));
        await pg.goto(`http://localhost:${port}/strata/lower-than-when-you-last-looked/?feed=${mode}`, { waitUntil: 'networkidle' });
        await pg.waitForTimeout(1200);
        return {
          errs: e2,
          headline: (await read('headline-num')).trim(),
          box: (await read('headline-box')).trim(),
          fresh: (await read('fresh-verdict')).trim(),
          prov: (await read('prov')).trim(),
        };
      };

      const down = await load('down');
      ok('REFUSAL, feed unreachable: the reader is told there is no number, not shown an old one',
        /no number/i.test(down.headline), `headline "${down.headline}"`);
      ok('REFUSAL, feed unreachable: and the page says why in a sentence, not a spinner',
        /could not be fetched/.test(down.box) && /not going to show you an old one/.test(down.box), down.box.slice(0, 120));
      ok('REFUSAL, feed unreachable: the page still throws no error', down.errs.length === 0, down.errs.slice(0, 2).join(' | '));

      const stale = await load('stale');
      ok('REFUSAL, HTTP 200 over year-old data: the freshness verdict is refused',
        /refused/i.test(stale.fresh), `verdict "${stale.fresh}"`);
      ok('REFUSAL, HTTP 200 over year-old data: no number is printed',
        /no number/i.test(stale.headline), `headline "${stale.headline}"`);
      ok('REFUSAL, HTTP 200 over year-old data: and the reason names the DATA, not the header',
        /newest state vector in the file/.test(stale.box), stale.box.slice(0, 200));
      ok('REFUSAL, HTTP 200 over year-old data: the page names the trap it just caught',
        /arrived with HTTP 200 and parsed cleanly/.test(stale.box));

      const sub = await load('subfloor');
      ok('REFUSAL, drop under the noise floor: the page says too soon to tell instead of a number',
        /too soon to tell/i.test(sub.headline), `headline "${sub.headline}"`);
      ok('REFUSAL, drop under the noise floor: and prints the floor it is refusing against',
        /noise floor of 177 m/.test(sub.box), sub.box.slice(0, 200));
      ok('REFUSAL, drop under the noise floor: the anchor and freshness still ran, so this is a refusal and not a crash',
        /fresh/i.test(sub.fresh) && sub.errs.length === 0, `verdict "${sub.fresh}", ${sub.errs.length} errors`);

      /* The quietest failure on this page, and the only one that used to look like work in
         progress: a committed fixture 404s, getJSON() swallows it, and the headline reads
         "measuring" forever with no error anywhere. */
      const nofix = await load('nofixture');
      ok('REFUSAL, a committed fixture missing: the headline does not sit on "measuring" forever',
        !/measuring/i.test(nofix.headline) && /no number/i.test(nofix.headline), `headline "${nofix.headline}"`);
      ok('REFUSAL, a committed fixture missing: the page names the file that did not load',
        /reference-burn\.json/.test(nofix.box), nofix.box.slice(0, 160));
      ok('REFUSAL, a committed fixture missing: and calls it a broken deployment rather than a gap',
        /broken deployment/.test(nofix.box) && nofix.errs.length === 0, `${nofix.errs.length} page errors`);

      /* The positive half of all four: put the good feed back and the page prints a number
         again. A page that refused everything would have passed every assertion above. */
      const again = await load('good');
      ok('CONTROL, positive half: with the real feed restored the page prints a number again',
        Number.isFinite(num(again.headline)) && Math.abs(num(again.headline) - domDrop) < 5,
        `back to ${again.headline} m`);

      Object.assign(refusals, {
        feed_down: down.headline, stale_200: stale.headline, stale_verdict: stale.fresh,
        under_floor: sub.headline, missing_fixture: nofix.headline,
        restored: again.headline, subfloor_scale: subfloorScale,
      });

      browserOut = { status: 'ran', dom_drop_m: domDrop, dom_nodes: domCount, page_errors: errs.length, overflow, refusals };
    } finally {
      await browser.close();
      srv.close();
    }
  }
}

/* ══ 9. the record ══════════════════════════════════════════════════════════ */

head('9. the record');
const line = {
  run_at: new Date().toISOString(),
  slug: 'lower-than-when-you-last-looked',
  mode: OFFLINE ? 'offline' : 'live',
  pass_at_write: pass, fail_at_write: fail,
  note: 'pass_at_write is the count at the moment this line was composed; the run appends two more assertions after it, about this file.',
  anchor_leg1: liveOut && liveOut.leg1_exact !== undefined
    ? { counted: liveOut.nodes_counted, declared: liveOut.nodes_declared, exact: liveOut.leg1_exact }
    : { note: 'requires tonight\'s file; not run' },
  anchor_leg2: legs.map((l) => ({ lead_days: +l.lead.toFixed(3), pos_err_km: +l.sep_km.toFixed(3), sma_err_m: +l.da_m.toFixed(1), along_frac: +l.along_frac.toFixed(5) })),
  reference: {
    burn: refEv ? { name: refEv.name, iso: refEv.iso, dv_ms: refEv.dv_ms } : null,
    burn_seconds: +(burnEnd - burnStart).toFixed(1),
    measured_step_m: +stepM.toFixed(1),
    two_body_step_m: +impM.toFixed(1),
    a_ref_km: +aRef.mean.toFixed(6),
    sigma_ref_m: +sigmaRef.toFixed(1),
  },
  live: liveOut,
  tick: tickOut,
  air_density: rhoOut,
  browser: browserOut,
  years: byYear,
  claims,
  noise_floor_m: +FLOOR_M.toFixed(0),
  fixtures: {
    anchor_vintages_built: vintDoc.built_at,
    reference_burn_built: burnDoc.built_at,
    archive_series_built: archDoc.built_at,
    archive_rows: archDoc.rows.length,
  },
  failures: failures.length ? failures : undefined,
};

if (!NO_RECORD) {
  fs.appendFileSync(RECORD, JSON.stringify(line) + '\n');
  console.log(`  ok   appended one line to ${path.relative(process.cwd(), RECORD)}`);
}

/* The record must stay readable by a stranger, so it is checked as a file, not trusted. */
if (fs.existsSync(RECORD)) {
  const lines = fs.readFileSync(RECORD, 'utf8').trim().split('\n').filter(Boolean);
  let good = true, prev = '';
  for (const l of lines) {
    try { const o = JSON.parse(l); if (o.run_at < prev) good = false; prev = o.run_at; } catch { good = false; }
  }
  ok('record.jsonl is valid JSONL in non-decreasing time order', good, `${lines.length} lines`);
}

/* ══ done ═══════════════════════════════════════════════════════════════════ */

console.log(`\n${pass} passed, ${fail} failed.`);
if (fail) { console.log('FAILURES:\n  ' + failures.join('\n  ')); process.exit(1); }
process.exit(0);

/* ── the one place this file touches a network ───────────────────────────── */
async function getLive() {
  // Prefer our own proxy, which is the path the page itself takes.
  try {
    const r = await fetch(PROXY, { headers: { Accept: 'application/json' } });
    if (r.ok) {
      const b = await r.json();
      if (b.ok && b.text) return { text: b.text, last_modified: b.upstream_last_modified, via: 'artwaste.land/api/feed' };
    }
  } catch { /* fall through to the upstream the proxy would have used */ }
  try {
    const r = await fetch(UPSTREAM, { headers: { 'User-Agent': UA } });
    if (!r.ok) return null;
    return { text: await r.text(), last_modified: r.headers.get('Last-Modified'), via: 'upstream directly (the proxy was unreachable)' };
  } catch { return null; }
}
