#!/usr/bin/env node
// verify-free-fall-weightless.mjs: recompute everything "Weight Is the Table, Not the Earth"
// prints, from the forward model and the page's own shipped code, and refuse to exit 0 on any
// disagreement.
//
//   node research/free-fall-weightless/verify-free-fall-weightless.mjs
//
// What this is for. The page reports a number about the reader's own hardware, and the reader
// has no second instrument to check it with. Everything that makes that honest is structural:
// one estimator, run on traces whose answers were fixed before it existed, with the tolerance
// declared in advance. This file is the part of that structure that runs offline.
//
// Five things it does that a verifier can be written without, and should not be:
//
//   1. It REGENERATES all nine traces from the forward model, in memory, and compares their
//      sha256 with the committed bytes. A doctored specimen is a doctored anchor, and a
//      verifier that reads the committed file and grades against it grades nothing.
//   2. It loads the PAGE'S OWN fall.js and limits.js and runs those, not a copy. A verifier
//      carrying its own reimplementation checks the reimplementation.
//   3. It STRING-MATCHES every figure against public/strata/free-fall-weightless/index.html
//      and against the frontmatter, including the meta description and the JSON-LD. A number
//      recomputed but never compared to what the reader sees is a number nobody checked.
//   4. It asserts the REFUSALS, one branch at a time. A measurement page is likeliest to lie
//      where it should have declined.
//   5. It proves the checks CAN FAIL: a constant estimator over the same slate, and a
//      deliberately loosened threshold over the same limits, both of which must break the
//      assertions above. A green check that cannot go red is decoration.
//
// It reads public/, never dist/.
import { readFileSync, existsSync, statSync } from 'node:fs';
import { createHash } from 'node:crypto';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { execFileSync } from 'node:child_process';
import {
  SLATE, bufferOf, truthOf, loweringTruth, impactAmplitude, simulateKey, payloadOfSpec,
  G_N, ACC_QUANTUM, GYRO_QUANTUM, GYRO_QUANTUM_DEG, R_CHIP, R_ZERO, INERTIA, eulerRate,
  dragCoefficient,
} from './make-specimens.mjs';

const HERE = dirname(fileURLToPath(import.meta.url));
const ROOT = join(HERE, '..', '..');
const PAGE = join(ROOT, 'public/strata/free-fall-weightless');
const SPECS = join(PAGE, 'specimens');
const GATE = join(HERE, 'gate');
const MD = join(ROOT, 'src/content/strata/free-fall-weightless.md');
const CASE = join(ROOT, 'research/anchor-wave/cases/free-fall-weightless.json');

// ── the ledger ───────────────────────────────────────────────────────────────
const results = [];
let failed = 0;
function check(name, cond, detail) {
  const pass = !!cond;
  if (!pass) failed++;
  results.push({ name, pass, detail: detail || '' });
  console.log(`${pass ? '  ok  ' : '  FAIL'}  ${name}${detail && !pass ? '  <- ' + detail : ''}`);
  return pass;
}
function near(a, b, tol) { return typeof a === 'number' && isFinite(a) && Math.abs(a - b) <= tol; }
function section(s) { console.log(`\n${s}`); }

// ── load the page's own code, exactly as shipped ─────────────────────────────
// fall.js and limits.js are UMD: given a `module` they populate module.exports, given a
// `window` they hang themselves off AW. Running them through Function() is how this file gets
// the SAME bytes the browser gets, rather than a node-flavoured copy of them.
function loadUmd(path) {
  const mod = { exports: {} };
  new Function('module', 'exports', readFileSync(path, 'utf8'))(mod, mod.exports);
  return mod.exports;
}
const F = loadUmd(join(PAGE, 'fall.js'));
const LIM = loadUmd(join(PAGE, 'limits.js'));

const HTML = readFileSync(join(PAGE, 'index.html'), 'utf8');
const INSTRUMENT = readFileSync(join(PAGE, 'instrument.js'), 'utf8');
const FALLSRC = readFileSync(join(PAGE, 'fall.js'), 'utf8');
const MDSRC = readFileSync(MD, 'utf8');
const CASESRC = JSON.parse(readFileSync(CASE, 'utf8'));

// The payload shape the page builds, from a trace file. Seven arrays of numbers and nothing
// else: the same seven the live listener produces.
function payloadOf(path) {
  const d = JSON.parse(readFileSync(path, 'utf8'));
  const n = d.samples.length;
  const p = { times: new Array(n), ax: new Array(n), ay: new Array(n), az: new Array(n),
    wx: new Array(n), wy: new Array(n), wz: new Array(n) };
  for (let i = 0; i < n; i++) {
    const s = d.samples[i];
    p.times[i] = s.t; p.ax[i] = s.x; p.ay[i] = s.y; p.az[i] = s.z;
    p.wx[i] = s.gx; p.wy[i] = s.gy; p.wz[i] = s.gz;
  }
  return p;
}
const pathOfKey = (k) => join(SLATE[k].where === 'gate' ? GATE : SPECS, SLATE[k].file);
const P = {};
for (const k of Object.keys(SLATE)) P[k] = payloadOf(pathOfKey(k));
const est = (k, o) => F.estimate(P[k], o || {});

// The page's own rendering of a number, so a string match is against the reader's characters.
const fmt = (v, n) => (typeof v === 'number' && isFinite(v)) ? v.toFixed(n === undefined ? 4 : n) : '--';
const inHtml = (s) => HTML.includes(s);
// Prose in this page is hard-wrapped, so a sentence that reads as one line to the reader is
// several in the file. Whitespace-insensitive matching for prose, exact matching for figures.
const squash = (s) => s.replace(/\s+/g, ' ');
const FLATHTML = squash(HTML);
const FLATMD = squash(MDSRC);
const FLATINST = squash(INSTRUMENT);
const inProse = (s) => FLATHTML.includes(squash(s));
const inMd = (s) => FLATMD.includes(squash(s));
const inPageJs = (s) => FLATINST.includes(squash(s));

console.log('verify: Weight Is the Table, Not the Earth (free-fall-weightless)\n' +
  'every number the page prints, recomputed from the forward model and the page\'s own code.');

// ── 1. the files ─────────────────────────────────────────────────────────────
section('1. the file list');
for (const f of ['index.html', 'fall.js', 'limits.js', 'instrument.js']) {
  check(`public/strata/free-fall-weightless/${f} exists`, existsSync(join(PAGE, f)));
}
for (const f of ['make-specimens.mjs', 'verify-free-fall-weightless.mjs', 'README.md']) {
  check(`research/free-fall-weightless/${f} exists`, existsSync(join(HERE, f)));
}
check('the gate case exists', existsSync(CASE));
check('the frontmatter entry exists', existsSync(MD));

// ── 2. the specimens regenerate, byte for byte ───────────────────────────────
section('2. the nine traces, regenerated from the model and hashed');
let totalBytes = 0;
for (const key of Object.keys(SLATE)) {
  const made = bufferOf(key);
  const onDisk = readFileSync(pathOfKey(key));
  totalBytes += onDisk.length;
  const a = createHash('sha256').update(made).digest('hex');
  const b = createHash('sha256').update(onDisk).digest('hex');
  check(`${key} regenerates to the committed bytes`, a === b, `${a.slice(0, 12)} vs ${b.slice(0, 12)}`);
}
check('nine traces in all', Object.keys(SLATE).length === 9);
check('seven of them ship with the page',
  Object.values(SLATE).filter((s) => s.where === 'specimens').length === 7);
check('two of them belong to the live-sensor gate',
  Object.values(SLATE).filter((s) => s.where === 'gate').length === 2);
check('the page says so: nine traces, seven shipped, two for the gate',
  inProse('All nine traces, seven shipped with the page and two used by the live-sensor gate'));
check('the specimen budget is met (under 3 MB)', totalBytes < 3 * 1024 * 1024,
  `${(totalBytes / 1024).toFixed(1)} kB`);

// ── 3. the estimator cannot know what it is looking at ───────────────────────
section('3. one estimator, with nothing in it that can tell the traces apart');
// The grep the page's own header promises. Scoped to the estimate() body, because the file's
// prose necessarily uses these words.
const bodyStart = FALLSRC.indexOf('function estimate(payload, opts)');
const bodyEnd = FALLSRC.indexOf('function gFromHeight');
check('estimate() and gFromHeight() were both found in fall.js', bodyStart > 0 && bodyEnd > bodyStart);
const BODY = FALLSRC.slice(bodyStart, bodyEnd)
  .split('\n').filter((l) => !/^\s*\/\//.test(l)).join('\n');
for (const word of ['specimen', 'control', 'anchor', 'expected', 'truth', 'role', 'source']) {
  check(`the word "${word}" appears nowhere in estimate()`, !BODY.includes(word));
}
// Better than a grep: hand it the answer and check the answer changes nothing.
const spiked = Object.assign({}, P['drop-tumbling'], {
  truth: 0.32, expected: 0.32, role: 'anchor', isControl: true, id: 'drop-tumbling',
});
check('an answer smuggled onto the payload changes nothing',
  F.estimate(spiked, {}).value === est('drop-tumbling').value);
check('the page loads limits.js as a separate file, so the verifier grades with the page\'s rule',
  inHtml('src="./limits.js"') && INSTRUMENT.includes('AW.limits.classify'));

// ── 4. the slate: two known fall times, recovered ────────────────────────────
section('4. the slate');
const SLATE_TOL = 0.040;
const anchor = est('drop-tumbling');
const control = est('drop-flat-cm');
check('the anchor is not refused', !anchor.refused, anchor.refused && anchor.refused.reason);
check('the control is not refused', !control.refused, control.refused && control.refused.reason);
check(`the anchor's true fall time is 0.3200 s by construction`, SLATE['drop-tumbling'].tFall === 0.3200);
check(`the control's true fall time is 0.1800 s by construction`, SLATE['drop-flat-cm'].tFall === 0.1800);
check('the estimator recovers the anchor inside 0.040 s',
  near(anchor.value, 0.3200, SLATE_TOL), `got ${fmt(anchor.value)}`);
check('the estimator recovers the control inside 0.040 s',
  near(control.value, 0.1800, SLATE_TOL), `got ${fmt(control.value)}`);
check('the anchor\'s own error bar is no wider than the tolerance it is judged against',
  anchor.uncertainty <= SLATE_TOL, String(anchor.uncertainty));
check('the control\'s own error bar is no wider than that tolerance',
  control.uncertainty <= SLATE_TOL, String(control.uncertainty));
check('the two truths are separable: 0.140 s apart against 0.080 s of total slack',
  Math.abs(0.3200 - 0.1800) > 2 * SLATE_TOL);
check('the page states the two truths', inHtml('<strong>0.3200 s</strong>') && inHtml('<strong>0.1800 s</strong>'));
check('the page states the gap and the slack', inHtml('0.140 s apart') && inHtml('sum to 0.080 s'));
check('the page states the tolerance', inHtml('&#177;0.040 s'));
check('and the instrument declares that same tolerance', INSTRUMENT.includes('tol: 0.040'));

// ── 5. the headline figures ──────────────────────────────────────────────────
section('5. the headline, on the drop the page ships');
const d0 = anchor.diagnostics;
check('the fall time reads 0.3199 s', fmt(d0.tFall, 4) === '0.3199', fmt(d0.tFall, 4));
check('the page prints 0.3199 s', inHtml('<strong>0.3199 s</strong>'));
check('the interior mean, as a fraction of this phone\'s own resting reading, is 0.0595',
  fmt(d0.frac, 4) === '0.0595', fmt(d0.frac, 4));
check('the page prints 0.0595', inHtml('<strong>0.0595</strong>'));
check('the meta description prints the same 0.0595',
  inHtml('0.0595 of its own resting value'));
check('the window opened at 0.75 of resting', d0.openLevel === 0.75 * d0.gRest);
check('the page prints the 0.75', inHtml('<strong>0.75</strong> of resting'));
check('the answer is more than twelve times smaller than the threshold that made the window',
  0.75 / d0.frac > 12, String(0.75 / d0.frac));
check('the page says "more than twelve times smaller"', inHtml('more than twelve times smaller'));
// This one is true by construction of the window scan and CANNOT go red; it is named for what
// it asserts rather than for the property it used to be titled after, and the property itself
// is established by the check under it, which can.
check('the interior lies wholly below the level that opened the window',
  d0.interiorMax < d0.openLevel && d0.nInterior >= 5);
// What the window rule does NOT guarantee, and therefore what has to be measured: WHERE inside
// that bound the answer lands. A rule that selected for smallness could not have returned the
// hand-lowering's number through the identical code, at any threshold the slider reaches.
{
  let worst = Infinity, at = null;
  for (const of_ of [0.40, 0.50, 0.60, 0.70, 0.75, 0.80, 0.85, 0.90, 0.95]) {
    const a = est('drop-tumbling', { openFrac: of_ }), b = est('lowering-by-hand', { openFrac: of_ });
    const ratio = b.diagnostics.frac / a.diagnostics.frac;
    if (ratio < worst) { worst = ratio; at = of_; }
  }
  check('and the interior was never selected for being small: the lowering beats the drop by more ' +
    'than a factor of four at every threshold in the slider\'s range',
    worst > 4, `worst ${fmt(worst, 3)} at openFrac ${at}`);
}
check('the resting reading is a plateau of this phone\'s own, not 9.80665',
  d0.gRest !== G_N && d0.gRest > 9 && d0.gRest < 10.5, fmt(d0.gRest, 4));
check('the reading step is measured off the record as 0.1 m/s^2', d0.readingStep === ACC_QUANTUM);
check('the resolution floor is sqrt(3)/2 of one step',
  near(d0.resolutionFloor, ACC_QUANTUM * Math.sqrt(3) / 2, 1e-12));

// A point or a bound, and the record decides which. A drop clean enough to put every interior
// reading on one grid point has no mean this hardware can express, and 0.0000 printed to four
// places would be the reading step wearing a lab coat. The page argues this two screens later
// about the ratio's interval; the headline has to obey it too.
check('the spun drop is separated from zero, so its ratio is a point: 0.0595',
  d0.interiorPinned && d0.meanLo95 > 0);
check('and its 95 per cent interval is 0.0429 to 0.0762',
  fmt(d0.fracLo95, 4) === '0.0429' && fmt(d0.fracHi95, 4) === '0.0762',
  `${fmt(d0.fracLo95, 4)} to ${fmt(d0.fracHi95, 4)}`);
check('the page prints that interval beside the 0.0595',
  inProse('with a 95 per cent interval of <strong>0.0429 to 0.0762</strong>'));
for (const k of ['drop-flat-cm', 'drop-barely-spun']) {
  const d = est(k).diagnostics;
  check(`${k} lands wholly on one grid point, so it is NOT separated from zero`,
    !d.interiorPinned && d.interiorMean === 0, fmt(d.interiorMean, 4));
  check(`and all it supports is a bound: below ${fmt(d.fracHi95, 4)} of resting`, d.fracHi95 > 0);
}
check('so the live headline quotes a bound exactly when the interval reaches zero',
  inPageJs("d.interiorPinned") && inPageJs("'below ' + fmt(d.fracHi95, 4) + ' of your own resting reading'"));

// ── 6. the five traces the estimator is not allowed to be right about ────────
section('6. the five limits, graded by the page\'s own rule');
check('limits.js declares five traces', LIM.LIMITS.length === 5);
for (const L of LIM.LIMITS) {
  const v = LIM.classify(L, est(L.id));
  check(`${L.id}: ${v.verdict}`, v.ok, v.got);
}
const low = est('lowering-by-hand');
check('the hand-lowering does open and close a window, like a drop does',
  !low.refused && low.diagnostics.nInterior >= 5);
check('and it lands hard enough to register a landing, like a drop does', low.diagnostics.landed);
check('it is turned down on the number alone: 0.3832 of resting',
  fmt(low.diagnostics.frac, 4) === '0.3832', fmt(low.diagnostics.frac, 4));
check('the page prints 0.3832', inHtml('<strong>0.3832</strong>'));
check('the meta description prints it rounded to 0.38', inHtml('turns down a hand-lowering at 0.38'));
check('0.3832 is above the 0.25 cutoff the page names', low.diagnostics.frac > 0.25);
check('the page names the 0.25 cutoff', inHtml('against a cutoff of 0.25'));
check('the cutoff is a reachable slider that goes past 0.3832',
  /id="c-ff"[^>]*max="0.50"/.test(HTML) && 0.50 > low.diagnostics.frac);
check('and the page says so, with the number', inProse('drag <em>not free fall above</em> past <strong>0.3832</strong>'));
// The lowering's window is the analytic 0.75g crossing pair of the generating function, and
// the estimator has never seen that function.
const LT = loweringTruth(SLATE['lowering-by-hand']);
check('the closed form puts the two 0.75 g crossings 0.3463 s apart', fmt(LT.windowSeconds, 4) === '0.3463');
check('the estimator recovers that window to four decimal places without knowing it',
  fmt(low.diagnostics.tFall, 4) === fmt(LT.windowSeconds, 4),
  `${fmt(low.diagnostics.tFall, 4)} vs ${fmt(LT.windowSeconds, 4)}`);
const lift = est('lift-descent');
check('the lift descent is refused for having no window at all',
  lift.refused && lift.refused.reason === 'no-window');
check('its least reading is 8.55 m/s^2', fmt(lift.diagnostics.minA, 2) === '8.55', fmt(lift.diagnostics.minA, 2));
check('which is 0.874 of its own resting reading',
  fmt(lift.diagnostics.minFrac, 3) === '0.874', fmt(lift.diagnostics.minFrac, 3));
check('the page prints both', inHtml('<strong>8.55 m/s&#178;</strong>') && inHtml('<strong>0.874</strong>'));
check('the generator held that plateau at 0.88 g for 1.8 s',
  SLATE['lift-descent'].frac === 0.88 && SLATE['lift-descent'].tPlateau === 1.80);
check('0.88 g is 8.6299 m/s^2, and the minimum sits just under it from the wobble and the noise',
  fmt(0.88 * G_N, 4) === '8.6299' && lift.diagnostics.minA < 0.88 * G_N);
const clip = est('drop-clipped');
check('the clipped drop is detected as saturated', clip.diagnostics.saturated);
// The rail was PUT at exactly two g. What the trace carries is that rail after the 0.1 m/s^2
// reading grid, which is 19.6 and not 19.6133, and the page now says which is which.
check('the generator put the rail at exactly two g, 19.6133 m/s^2',
  SLATE['drop-clipped'].railMs2 === 2 * G_N && fmt(2 * G_N, 4) === '19.6133');
check('and the reading grid puts every sample of it on 19.6',
  clip.diagnostics.railAt === 19.6, String(clip.diagnostics.railAt));
check('the page distinguishes the rail from the reading',
  inProse('the rail was put at exactly two g, which is 19.6133, and the') &&
  inProse('0.1 reading grid puts every sample of it on 19.6'));
check('the impulse route on it would have read 0.805 of resting',
  fmt(clip.diagnostics.impulseRatio, 3) === '0.805', fmt(clip.diagnostics.impulseRatio, 3));
check('where the same drop unclipped reads 1.066',
  fmt(d0.impulseRatio, 3) === '1.066', fmt(d0.impulseRatio, 3));
check('the page prints 19.6, 0.805 and 1.066',
  inHtml('<strong>19.6 m/s&#178;</strong>') && inHtml('<strong>0.805</strong>') && inHtml('<strong>1.066</strong>'));
check('so the saturation refusal is not decorative: it changes the number by more than 20 per cent',
  (d0.impulseRatio - clip.diagnostics.impulseRatio) / d0.impulseRatio > 0.20);
check('the clipped drop keeps its fall time and its null anyway',
  near(clip.diagnostics.tFall, 0.3200, SLATE_TOL) && clip.diagnostics.freeFall);
const slow = est('drop-slow-stream');
check('the 18 Hz stream is refused', slow.refused && slow.refused.reason === 'rate-too-low');
check('and its refusal prints the sample arithmetic', /readings a second/.test(slow.refused.detail) &&
  /per cent on the fall time/.test(slow.refused.detail));
check('18 Hz is genuinely below the 25 Hz floor the page names',
  slow.diagnostics.rate < 25 && SLATE['drop-slow-stream'].hz === 18);

// ── 7. the threshold sweep ───────────────────────────────────────────────────
section('7. the sweep: an event has edges, a slope does not');
const OPENS = [0.40, 0.50, 0.60, 0.70, 0.75, 0.80, 0.85, 0.90, 0.95];
let dropT = new Set(), dropF = new Set(), lowLo = Infinity, lowHi = -Infinity;
for (const of_ of OPENS) {
  const a = est('drop-tumbling', { openFrac: of_ });
  const b = est('lowering-by-hand', { openFrac: of_ });
  dropT.add(fmt(a.value, 4)); dropF.add(fmt(a.diagnostics.frac, 4));
  lowLo = Math.min(lowLo, b.value); lowHi = Math.max(lowHi, b.value);
}
check('the drop\'s fall time is one value across the whole drag', dropT.size === 1, [...dropT].join(','));
check('and that value is 0.3199 s', [...dropT][0] === '0.3199');
check('the drop\'s ratio is also one value across the whole drag', dropF.size === 1, [...dropF].join(','));
check('and that value is 0.0595', [...dropF][0] === '0.0595');
check('the lowering\'s window runs from 0.1933 s', fmt(lowLo, 4) === '0.1933', fmt(lowLo, 4));
check('to 0.4218 s', fmt(lowHi, 4) === '0.4218', fmt(lowHi, 4));
check('the page prints 0.1933 and 0.4218',
  inHtml('<strong>0.1933 s</strong>') && inHtml('<strong>0.4218 s</strong>'));
check('the lowering moves by more than a factor of a thousand more than the drop does',
  (lowHi - lowLo) > 1000 * 1e-4 && dropT.size === 1);
check('the slider covers exactly that range', /id="c-open"[^>]*min="0.40"[^>]*max="0.95"/.test(HTML));
// The size of "less precise", which the page states above the buttons rather than leaving as
// an adjective: a drop's window does not move, a lowering's moves by fourteen readings.
const lowSpan = lowHi - lowLo;
const lowRate = est('lowering-by-hand').diagnostics.rate;
check('the hand-lowering\'s window moves by 0.2285 s across that drag', fmt(lowSpan, 4) === '0.2285', fmt(lowSpan, 4));
check('which is about fourteen whole readings at the rate that trace arrived',
  Math.round(lowSpan * lowRate) === 14, String(lowSpan * lowRate));
// The window is the obvious thing to sweep, but the number the page REPORTS from the no-drop
// path is the ratio, and a re-derivation of this claim argued that ratio is the more precise of
// the two because the factory scale cancels in it. It cancels in both. What does not cancel is
// that a slope has no edges: swept over the same range, the drop's ratio does not move at the
// fifth decimal and the lowering's moves by 0.18, which is a quarter of its own value.
const dropFracs = [], lowFracs = [];
for (const of_ of OPENS) {
  const a = est('drop-tumbling', { openFrac: of_ }), b = est('lowering-by-hand', { openFrac: of_ });
  if (!a.refused) dropFracs.push(a.diagnostics.frac);
  if (!b.refused) lowFracs.push(b.diagnostics.frac);
}
check('the drop\'s ratio does not move across the whole drag, to five decimal places',
  Math.max(...dropFracs) - Math.min(...dropFracs) < 1e-5,
  fmt(Math.max(...dropFracs) - Math.min(...dropFracs), 6));
check('the lowering\'s runs from 0.2789 to 0.4632, so a quarter of that answer is the threshold',
  fmt(Math.min(...lowFracs), 4) === '0.2789' && fmt(Math.max(...lowFracs), 4) === '0.4632' &&
  (Math.max(...lowFracs) - Math.min(...lowFracs)) / est('lowering-by-hand').diagnostics.frac > 0.4,
  `${fmt(Math.min(...lowFracs), 4)} to ${fmt(Math.max(...lowFracs), 4)}`);
check('and the page prints both ends of that, not only the window',
  inProse('<strong>0.2789</strong>') && inProse('<strong>0.4632</strong>'));
check('the page states both, above the buttons, as the cost of the no-drop path',
  inProse('<strong>0.2285 s</strong> as the threshold is dragged across its range, about fourteen whole readings'));

// ── 8. the lever arm, which is the point ─────────────────────────────────────
section('8. the lever arm: the leftover predicted from a second sensor');
const rTrue = Math.hypot(R_CHIP[0], R_CHIP[1], R_CHIP[2]) * 100;
check('the chip was placed at (2.10, -0.80, 0.40) cm from the centre of mass',
  R_CHIP[0] === 0.0210 && R_CHIP[1] === -0.0080 && R_CHIP[2] === 0.0040);
check('which is 2.2825 cm', fmt(rTrue, 4) === '2.2825', fmt(rTrue, 4));
check('the page prints that offset and its magnitude',
  inHtml('(2.10, &minus;0.80, 0.40) cm') && inHtml('<strong>2.2825 cm</strong>'));
const L0 = d0.lever;
check('the fit on the spun drop returns 2.32 cm', fmt(L0.cm, 2) === '2.32', fmt(L0.cm, 2));
check('with a 95 per cent interval of 2.08 to 2.56 cm',
  fmt(L0.loCm, 2) === '2.08' && fmt(L0.hiCm, 2) === '2.56', `${fmt(L0.loCm, 2)} to ${fmt(L0.hiCm, 2)}`);
check('the page prints 2.32, 2.08 and 2.56',
  inHtml('<strong>2.32 cm</strong>') && inHtml('<strong>2.08</strong>') && inHtml('<strong>2.56 cm</strong>'));
check('and that interval covers the truth it was never told', L0.loCm <= rTrue && rTrue <= L0.hiCm);
check('the fit explains more than 98 per cent of what the accelerometer read inside the fall',
  L0.explained > 0.98, fmt(L0.explained, 4));
check('over three equations per interior reading and three unknowns',
  L0.rows === 3 * d0.nInterior && L0.params === 3);
// ── what the gyroscope supplies, and what it does not ────────────────────────
// The sentence this page shipped for a while was that the leftover is predicted from the
// gyroscope alone, before it is looked at. It is false: r is a three-parameter least squares
// fit TO the accelerometer's own readings. The check that stood under that sentence tested two
// substrings of fall.js and would have stayed green with the accelerometer wired into the fit,
// which is exactly what is happening. So: the substring test keeps only the name it can carry,
// and the claim itself is now tested by moving the accelerometer and watching the answer move.
check('every entry of the design matrix is built from omega and alpha only',
  BODY.includes('w[0] * w[0] - w2') && BODY.includes('wx[i + 1] - wx[i - 1]'));
check('but the fit is NOT parameter-free: scale the accelerometer by 1.1 and the fitted lever arm ' +
  'scales by exactly 1.1, because the accelerometer sets the three free numbers', (() => {
    const t = P['drop-tumbling'];
    const scaled = Object.assign({}, t, {
      ax: t.ax.map((v) => v * 1.1), ay: t.ay.map((v) => v * 1.1), az: t.az.map((v) => v * 1.1),
    });
    const a = est('drop-tumbling').diagnostics.lever.cm;
    const b = F.estimate(scaled, {}).diagnostics.lever.cm;
    return Math.abs(b / a - 1.1) < 1e-6;
  })());
check('and the length it returns follows the chip: double the offset in the generator and the fit ' +
  'doubles, halve it and the fit halves, each interval covering its own truth', (() => {
    for (const mult of [2, 0.5]) {
      const spec = Object.assign({}, SLATE['drop-tumbling'], { r: R_CHIP.map((v) => v * mult), seed: 9101 });
      const L = F.estimate(payloadOfSpec(spec), {}).diagnostics.lever;
      const truth = rTrue * mult;
      if (!L.reportable || L.loCm > truth || L.hiCm < truth) return false;
    }
    return true;
  })());
check('the page says which sensor supplies what, in those terms, rather than claiming a prediction',
  inProse('three numbers fitted by least squares to the accelerometer\'s own') &&
  inProse('Take the accelerometer away and there is no') &&
  inProse('<strong>51 equations against 3 unknowns</strong>'));
check('51 equations against 3 unknowns is what the fit actually ran',
  L0.rows === 51 && L0.params === 3, `${L0.rows} rows, ${L0.params} params`);
check('the three fitted components come back at (2.13, -0.83, 0.41) cm', (() => {
  const v = L0.rVec.map((x) => fmt(x * 100, 2));
  return v[0] === '2.13' && v[1] === '-0.83' && v[2] === '0.41';
})(), L0.rVec.map((x) => fmt(x * 100, 3)).join(', '));
check('each within a millimetre of where the chip was put',
  L0.rVec.every((x, i) => Math.abs(x - R_CHIP[i]) < 0.001));
check('the page prints those three components and the 98.6 per cent',
  inHtml('(2.13, &minus;0.83, 0.41) cm') && inHtml('<strong>98.6 per cent</strong>') &&
  fmt(100 * L0.explained, 1) === '98.6');
const bare = est('drop-barely-spun');
const Lb = bare.diagnostics.lever;
check('the barely spun drop of the same phone reports no value at all', !Lb.pinned && Lb.reportable);
check('only an upper bound of 7.64 cm', fmt(Lb.hiCm, 2) === '7.64', fmt(Lb.hiCm, 2));
check('the page prints below 7.64 cm', inHtml('<strong>below 7.64 cm</strong>'));
check('its mean spin was 0.43 rad/s', fmt(Lb.omegaMean, 2) === '0.43', fmt(Lb.omegaMean, 2));
check('the page prints 0.43 rad/s', inProse('a mean of 0.43 rad/s'));
check('at that spin the term being fitted is under the reading step',
  Lb.omegaMean * Lb.omegaMean * (rTrue / 100) < ACC_QUANTUM,
  String(Lb.omegaMean * Lb.omegaMean * (rTrue / 100)));
check('the page says exactly that', inProse('the term being fitted is under the reading step'));
const flat = control.diagnostics.lever;
check('the chip-at-the-centre drop returns 0.00 cm', fmt(flat.cm, 2) === '0.00', fmt(flat.cm, 2));
check('within plus or minus 0.61 cm', fmt(flat.halfCm, 2) === '0.61', fmt(flat.halfCm, 2));
check('the page prints 0.00 cm and 0.61', inHtml('<strong>0.00 cm, 95 per cent within &#177;0.61 cm</strong>'));
check('that interval covers zero', flat.loCm <= 0 && flat.hiCm >= 0);
check('and excludes 2.2825 by more than a factor of three', rTrue / flat.halfCm > 3, String(rTrue / flat.halfCm));
check('the page says "factor of three"', inProse('by more than a factor of three'));
check('the generator put that chip at the centre of mass exactly',
  R_ZERO[0] === 0 && R_ZERO[1] === 0 && R_ZERO[2] === 0 && SLATE['drop-flat-cm'].r === R_ZERO);
check('the spun and barely spun traces are the same phone, same chip, different flick',
  SLATE['drop-tumbling'].r === R_CHIP && SLATE['drop-barely-spun'].r === R_CHIP &&
  SLATE['drop-tumbling'].tFall === SLATE['drop-barely-spun'].tFall);
// The physics the second layer rests on, checked rather than asserted: with three different
// principal moments, a torque-free tumble does not hold omega constant, so alpha is not zero
// and the alpha x r column of the fit is not dead weight.
const eu = eulerRate([1, 2, 3]);
check('the inertia tensor has three different principal moments',
  INERTIA.x !== INERTIA.y && INERTIA.y !== INERTIA.z && INERTIA.x !== INERTIA.z);
check('so a torque-free tumble has a non-zero angular acceleration',
  Math.hypot(eu[0], eu[1], eu[2]) > 1);

// ── 8a. the second explanation for a big reading, which is not the reader's arm ──
section('8a. what rotation alone could account for');
// A reading too big for a fall has TWO explanations, and this page used to print only one of
// them: "Your arm took 73 per cent of its weight away and kept the rest." The other is a
// genuine fall spun hard enough that the chip's own lever arm accounts for the reading, and the
// page asks the reader to spin it. The gyroscope is what separates them, by bounding the
// leftover: |omega x (omega x r) + alpha x r| <= (|omega|^2 + |alpha|)|r|.
const PHONE_HALF_DIAGONAL = Math.hypot(0.170, 0.080) / 2;
check('the ceiling on |r| is an upper bound on a real handset: a 170 by 80 mm phone has a 94 mm half-diagonal',
  F.DEFAULTS.rCeiling >= PHONE_HALF_DIAGONAL && F.DEFAULTS.rCeiling === 0.10,
  fmt(PHONE_HALF_DIAGONAL, 4));
check('on the hand-lowering the gyroscope leaves the arm as the only explanation',
  low.diagnostics.spinExplainsInterior === false &&
  low.diagnostics.spinCeiling < 0.1 * low.diagnostics.interiorMean,
  `ceiling ${fmt(low.diagnostics.spinCeiling, 4)} vs interior ${fmt(low.diagnostics.interiorMean, 4)}`);
// The traces this needs do not ship: a tenth specimen would have changed every count on the
// page. They are generated here from the same forward model, at the same 0.3200 s fall.
const spinSpec = (rad) => Object.assign({}, SLATE['drop-tumbling'],
  { omega: [0.59, -0.72, 0.37].map((v) => v / Math.hypot(0.59, -0.72, 0.37) * rad), seed: 9001 });
const spun = {};
for (const rad of [15, 18, 20]) spun[rad] = F.estimate(payloadOfSpec(spinSpec(rad)), {});
check('a genuine 0.3200 s fall spun at 15 rad/s is still read as free fall',
  spun[15].diagnostics.freeFall && near(spun[15].value, 0.3200, SLATE_TOL), fmt(spun[15].diagnostics.frac, 4));
check('at 18 rad/s the same fall is graded NOT FREE FALL, at 0.2678 of resting',
  !spun[18].diagnostics.freeFall && fmt(spun[18].diagnostics.frac, 4) === '0.2678',
  fmt(spun[18].diagnostics.frac, 4));
check('so the not-free-fall branch is reachable by a real drop, not only by a hand',
  SLATE['drop-tumbling'].tFall === 0.3200 && near(spun[18].value, 0.3200, SLATE_TOL));
check('and the gyroscope says so: rotation alone could account for the whole interior there',
  spun[18].diagnostics.spinExplainsInterior === true,
  `ceiling ${fmt(spun[18].diagnostics.spinCeiling, 2)} vs interior ${fmt(spun[18].diagnostics.interiorMean, 2)}`);
check('at 20 rad/s the spin closes the window early: 0.2862 s against a true 0.3200',
  fmt(spun[20].value, 4) === '0.2862' && 0.3200 - spun[20].value > spun[20].uncertainty,
  fmt(spun[20].value, 4));
check('and the estimator calls that fall time a lower bound rather than printing an interval that misses',
  spun[20].diagnostics.fallTimeIsLowerBound === true);
check('no shipped trace is flagged that way, so no figure on this page rests on it',
  ['drop-tumbling', 'drop-flat-cm', 'drop-barely-spun', 'lowering-by-hand', 'drop-clipped']
    .every((k) => est(k).diagnostics.fallTimeIsLowerBound === false));
check('the page carries both sentences: the arm when the gyroscope excludes the spin, and neither when it does not',
  inPageJs('Something was still holding it:') &&
  inPageJs('This page will not tell you which of two things that was.') &&
  inPageJs('or it was genuinely falling and you spun it hard enough'));
check('and the page warns the reader off the spin that breaks it, with this handset\'s own figure',
  inProse('Past <strong>2.87 turns a second</strong> on the drop this page ships') &&
  inProse('This page will not call any of that your arm.'));
check('the old accusation is gone from the page', !INSTRUMENT.includes('Your arm took '));

// ── 8b. which of the three fitted numbers is actually measured ───────────────
section('8b. the direction the record could not see');
// A blinded re-derivation of this page's claim, written without seeing the page, flagged this
// and it was right. omega x (omega x r) annihilates the component of r lying along omega, and a
// body turning about one fixed axis has alpha = 0, so a wrist flick leaves one of the three
// numbers unrecoverable however long the fall lasts. The interval this page used to quote was
// the delta-method width ALONG r-hat, which is the width of the BEST-supported direction: it
// could be tight around a length that was wrong by a factor. It now quotes the widest the
// confidence region reaches in any direction, from the eigenvalues of the fit's own covariance.
// Everything here is that claim, measured on the page's own code.
check('on the shipped tumble the worst-supported direction is barely worse than the fitted one',
  fmt(L0.worstCm, 2) === '0.24' && L0.worstCm >= L0.alongCm && L0.spreadRatio < 12,
  `worst ${fmt(L0.worstCm, 3)}, along r-hat ${fmt(L0.alongCm, 3)}, spread ${fmt(L0.spreadRatio, 2)}`);
check('and it is the worst direction the page quotes, not the width along the fit',
  Math.abs(L0.hiCm - (L0.cm + L0.worstCm)) < 1e-9 && Math.abs(L0.loCm - (L0.cm - L0.worstCm)) < 1e-9);
// The spin the page's own instruction produces, generated here at 150 noise seeds. None ship.
const AXIS = { n: 0, oldPoint: 0, oldCovered: 0, newPoint: 0, covered: 0, oldVals: [] };
for (let k = 0; k < 150; k++) {
  const spec = Object.assign({}, SLATE['drop-tumbling'], { omega: [8.90, 0, 0], seed: 10000 + k * 13, seconds: 3.2 });
  const r = F.estimate(payloadOfSpec(spec), {});
  if (r.refused || !r.diagnostics.freeFall) continue;
  const L = r.diagnostics.lever;
  if (!L.reportable) continue;
  AXIS.n++;
  if (L.loCm <= rTrue && rTrue <= L.hiCm) AXIS.covered++;
  if (L.pinned) AXIS.newPoint++;
  // The rule this page used to apply, recomputed from the same fit rather than from a second run.
  if (L.cm - L.alongCm > 0) {
    AXIS.oldPoint++;
    AXIS.oldVals.push(L.cm);
    if (L.cm - L.alongCm <= rTrue && rTrue <= L.cm + L.alongCm) AXIS.oldCovered++;
  }
}
AXIS.oldVals.sort((a, b) => a - b);
const axisMedian = AXIS.oldVals[AXIS.oldVals.length >> 1];
check('a phone spun about ONE axis at 8.9 rad/s still fits, 150 times out of 150', AXIS.n === 150);
check('the old rule printed a point value on 17 of them', AXIS.oldPoint === 17, String(AXIS.oldPoint));
check('with a median of 5.5 cm against a truth of 2.2825', fmt(axisMedian, 1) === '5.5', fmt(axisMedian, 3));
check('and it was right about seven of those seventeen', AXIS.oldCovered === 7, String(AXIS.oldCovered));
check('the rule this page now applies prints none of them', AXIS.newPoint === 0, String(AXIS.newPoint));
check('and its bound covers the truth on 148 of the 150', AXIS.covered === 148, String(AXIS.covered));
check('the page prints all four of those figures',
  inProse('<td>17 of 150 drops</td>') && inProse('<td>5.5 cm</td>') &&
  inProse('on 7 of those 17') && inProse('on 148 of all 150'));
// And the same 150 seeds on the tumble the page ships, which must NOT be refused.
const TUMBLE = { n: 0, pinned: 0, covered: 0 };
for (let k = 0; k < 150; k++) {
  const r = F.estimate(payloadOfSpec(Object.assign({}, SLATE['drop-tumbling'], { seed: 10000 + k * 13, seconds: 3.2 })), {});
  if (r.refused) continue;
  const L = r.diagnostics.lever;
  if (!L.reportable) continue;
  TUMBLE.n++;
  if (L.pinned) TUMBLE.pinned++;
  if (L.loCm <= rTrue && rTrue <= L.hiCm) TUMBLE.covered++;
}
check('the stricter rule costs the shipped tumble nothing: 150 of 150 still give a length',
  TUMBLE.n === 150 && TUMBLE.pinned === 150, `${TUMBLE.pinned} of ${TUMBLE.n}`);
check('and 146 of those 150 intervals cover 2.2825, which is what 95 per cent means',
  TUMBLE.covered === 146, String(TUMBLE.covered));
check('the page states that cost and that coverage',
  inProse('the point value survives all 150 seeds and covers the truth on 146 of them'));
// The blind direction is not a statistical curiosity, it is the spin axis. That is checkable.
const axisOne = F.estimate(payloadOfSpec(Object.assign({}, SLATE['drop-tumbling'],
  { omega: [8.90, 0, 0], seed: 10000, seconds: 3.2 })), {}).diagnostics.lever;
check('on a single-axis spin the unseen direction IS the axis, to a tenth of a degree',
  axisOne.unseenDeg < 0.1, fmt(axisOne.unseenDeg, 4) + ' degrees');
check('on the shipped tumble it is nothing like it, because a tumble sweeps omega around',
  L0.unseenDeg > 5, fmt(L0.unseenDeg, 2) + ' degrees');
check('the page says the angle comes back within a tenth of a degree',
  inProse('within a tenth of a\n    degree of the axis the phone was turning about'));
// A fit that lands outside the case is not a chip position however tight its interval is. The
// branch cannot be reached by a physically larger chip offset -- a 12 cm arm puts 9.5 m/s^2 on
// the sensor and the window never opens -- so it is exercised by moving the bound instead.
check('a fitted arm larger than the case is refused whatever its interval says',
  (() => {
    const L = F.estimate(P['drop-tumbling'], { rCeiling: 0.01 }).diagnostics.lever;
    return L.reportable && !L.pinned && L.cm > 1 &&
      /further out than the 1 cm this instrument allows/.test(L.why);
  })());
check('and at the shipped bound the same drop is not refused',
  est('drop-tumbling').diagnostics.lever.pinned === true && F.DEFAULTS.rCeiling === 0.10);
// The gyroscope's own scale error, which the fitted length inherits twice over.
check('the fitted length goes as 1/s^2 in the gyroscope scale factor: 2 per cent fast reads 3.9 per cent short',
  (() => {
    const t = P['drop-tumbling'];
    const base = est('drop-tumbling').diagnostics.lever.cm;
    for (const s2 of [1.01, 1.02, 1.03, 0.98, 0.97]) {
      const q = Object.assign({}, t, { wx: t.wx.map((v) => v * s2), wy: t.wy.map((v) => v * s2), wz: t.wz.map((v) => v * s2) });
      const got = F.estimate(q, {}).diagnostics.lever.cm / base;
      if (Math.abs(got - 1 / (s2 * s2)) > 2e-3) return false;
    }
    const two = F.estimate(Object.assign({}, t, { wx: t.wx.map((v) => v * 1.02), wy: t.wy.map((v) => v * 1.02), wz: t.wz.map((v) => v * 1.02) }), {})
      .diagnostics.lever.cm / base;
    return fmt(100 * (1 - two), 1) === '3.9';
  })());
check('the page states that, and the 6.2 per cent at 3 per cent slow',
  inProse('reports the chip 3.9 per cent closer in') && inProse('6.2 per cent further out'));

// ── 8c. the air the specimens do not have ────────────────────────────────────
section('8c. air, which every real drop has and no trace here does');
// The forward model sets the centre of mass to exactly zero proper acceleration through the
// fall. That is true in a vacuum. The re-derivation called this the biggest omission on the
// page and it was right, so the arithmetic is here and the estimator is put in front of it.
const AIR = { rho: 101325 * 0.0289652 / (8.314462618 * 293.15), Cd: 1.1, m: 0.190 };
const SLAB = { a: 0.160, b: 0.075, c: 0.008 };
const SURF = 2 * (SLAB.a * SLAB.b + SLAB.b * SLAB.c + SLAB.c * SLAB.a);
const AREA_TUMBLE = SURF / 4;            // Cauchy: the mean projected area of a convex body
const AREA_FACE = SLAB.a * SLAB.b;
const kTumble = dragCoefficient({ area: AREA_TUMBLE });
const kFace = dragCoefficient({ area: AREA_FACE });
const vT = (k) => Math.sqrt(G_N / k);
check('air density is PM/RT for dry air at 20 C and one atmosphere, 1.204 kg/m^3',
  fmt(AIR.rho, 3) === '1.204', fmt(AIR.rho, 5));
check('the mean projected area of the tumbling slab is a quarter of its surface, 69.4 cm^2',
  fmt(AREA_TUMBLE * 1e4, 1) === '69.4' && fmt(AREA_FACE * 1e4, 0) === '120', fmt(AREA_TUMBLE * 1e4, 2));
check('so the terminal speeds are 20.1 m/s tumbling and 15.3 m/s flat-on',
  fmt(vT(kTumble), 1) === '20.1' && fmt(vT(kFace), 1) === '15.3',
  `${fmt(vT(kTumble), 2)} / ${fmt(vT(kFace), 2)}`);
const vEnd = G_N * SLATE['drop-tumbling'].tFall;
check('a half-metre drop ends at 3.14 m/s', fmt(vEnd, 2) === '3.14', fmt(vEnd, 3));
check('at which the sensor reads 0.24 m/s^2 tumbling and 0.41 flat-on, two to four whole grid steps',
  fmt(G_N * (vEnd / vT(kTumble)) ** 2, 2) === '0.24' && fmt(G_N * (vEnd / vT(kFace)) ** 2, 2) === '0.41',
  `${fmt(G_N * (vEnd / vT(kTumble)) ** 2, 4)} / ${fmt(G_N * (vEnd / vT(kFace)) ** 2, 4)}`);
check('both are above the 0.1 m/s^2 the browser reports in', G_N * (vEnd / vT(kTumble)) ** 2 > ACC_QUANTUM);
check('the page prints the terminal speeds, the areas and the two readings',
  inProse('<strong>69.4 cm&#178;</strong>') && inProse('<strong>20.1 m/s</strong>') &&
  inProse('120 cm&#178; and 15.3 m/s') && inProse('<strong>0.24 m/s&#178;</strong>') &&
  inProse('<strong>0.41</strong>') && inProse('1.204 kg/m&#179;'));
check('and names the drag coefficient as the assumption it is',
  inProse('is an assumption rather than a measurement') && AIR.Cd === 1.1);
// What that does to this estimator, at three heights, twenty noise seeds each.
const dragRun = (tFall, dragK) => {
  const v = [];
  let covered = 0;
  for (let s2 = 0; s2 < 20; s2++) {
    const r = F.estimate(payloadOfSpec(Object.assign({}, SLATE['drop-tumbling'],
      { tFall, dragK, seed: 30000 + s2 * 23, seconds: 3.4 })), {});
    if (r.refused) continue;
    const L = r.diagnostics.lever;
    if (!L.reportable) continue;
    v.push(L.cm);
    if (L.loCm <= rTrue && rTrue <= L.hiCm) covered++;
  }
  return { mean: v.reduce((x, y) => x + y, 0) / v.length, covered: covered, n: v.length };
};
const DRAG = {};
for (const [tf, label] of [[0.2258, '25'], [0.3200, '50'], [0.4284, '90']]) {
  DRAG[label] = { dry: dragRun(tf, 0), wet: dragRun(tf, kTumble) };
}
check('no shipped trace carries drag: every one of the nine has the centre of mass at exactly zero',
  Object.values(SLATE).every((s2) => !s2.dragK));
check('with air in it the fit comes back SHORT, and worse the longer the drop',
  DRAG['25'].wet.mean < DRAG['25'].dry.mean && DRAG['50'].wet.mean < DRAG['25'].wet.mean * 1.02 &&
  DRAG['90'].wet.mean < DRAG['50'].wet.mean,
  ['25', '50', '90'].map((k) => `${k}cm ${fmt(DRAG[k].wet.mean, 3)}`).join(' '));
check('25 cm: 2.22 cm dry, 2.21 with air, 3 per cent low, still covering on 19 of 20',
  fmt(DRAG['25'].dry.mean, 2) === '2.22' && fmt(DRAG['25'].wet.mean, 2) === '2.21' &&
  DRAG['25'].wet.covered === 19, `${fmt(DRAG['25'].wet.mean, 3)}, ${DRAG['25'].wet.covered}/20`);
check('50 cm: 2.31 dry, 2.08 with air, 9 per cent low, covering on 20 of 20',
  fmt(DRAG['50'].dry.mean, 2) === '2.31' && fmt(DRAG['50'].wet.mean, 2) === '2.08' &&
  DRAG['50'].wet.covered === 20, `${fmt(DRAG['50'].wet.mean, 3)}, ${DRAG['50'].wet.covered}/20`);
check('90 cm: 2.29 dry, 1.67 with air, 27 per cent low, and the interval covers on 1 of 20',
  fmt(DRAG['90'].dry.mean, 2) === '2.29' && fmt(DRAG['90'].wet.mean, 2) === '1.67' &&
  DRAG['90'].wet.covered === 1, `${fmt(DRAG['90'].wet.mean, 3)}, ${DRAG['90'].wet.covered}/20`);
check('the air itself is half a per cent at 25 cm and the whole 27 at 90, which the page says',
  fmt(100 * (1 - DRAG['25'].wet.mean / DRAG['25'].dry.mean), 1) === '0.5' &&
  fmt(100 * (1 - DRAG['90'].wet.mean / DRAG['90'].dry.mean), 0) === '27' &&
  inProse('the air for about half a per cent') && inProse('At 90 cm the air accounts for all 27.'),
  `${fmt(100 * (1 - DRAG['25'].wet.mean / DRAG['25'].dry.mean), 2)} / ${fmt(100 * (1 - DRAG['90'].wet.mean / DRAG['90'].dry.mean), 2)}`);
check('the percentages the page prints are those means against 2.2825',
  fmt(100 * (1 - DRAG['25'].wet.mean / rTrue), 0) === '3' &&
  fmt(100 * (1 - DRAG['50'].wet.mean / rTrue), 0) === '9' &&
  fmt(100 * (1 - DRAG['90'].wet.mean / rTrue), 0) === '27');
check('the fall time does not move at all, with air or without',
  fmt(F.estimate(payloadOfSpec(Object.assign({}, SLATE['drop-tumbling'], { dragK: kTumble })), {}).value, 4) === '0.3199' &&
  fmt(d0.tFall, 4) === '0.3199');
check('the page prints that table and the height it implies',
  inProse('<td>2.21 cm</td>') && inProse('<td>2.08 cm</td>') && inProse('<td>1.67 cm</td>') &&
  inProse('<td class="bad">1 of 20</td>') &&
  inProse('the height that is\n      best for'));
check('the zero-g offset is quoted from the data sheet, with its document number',
  inProse('<strong>&#177;20 mg</strong>') && inProse('BST-BMA456-DS000-09 revision 3.6') &&
  fmt(0.020 * G_N, 3) === '0.196' && fmt(Math.sqrt(3) * 0.020 * G_N, 2) === '0.34');
check('and the page says where that offset hides at rest and why free fall shows it',
  inProse('at rest the magnitude only carries\n    the part of the offset lying along gravity'));

// ── 8d. the rotation channel, and the one blunder that looks like an answer ──
section('8d. degrees per second, radians per second');
// DeviceMotionEvent.rotationRate is in degrees a second; the Generic Sensor Gyroscope is in
// radians. The live-sensor gate injects through the Generic Sensor path and cannot reach
// devicemotion at all, so the conversion on the iOS path is the one line on this page that
// nothing runs. Both halves of that are tested here: what the estimator does if the units are
// wrong, and whether the shipped conversion is right.
const degPayload = (() => {
  const t = P['drop-tumbling'], k = 180 / Math.PI;
  return Object.assign({}, t, { wx: t.wx.map((v) => v * k), wy: t.wy.map((v) => v * k), wz: t.wz.map((v) => v * k) });
})();
const degRes = F.estimate(degPayload, {});
check('degrees fed to the estimator as radians produce a beautifully consistent wrong answer',
  (() => {
    const naive = F.estimate(degPayload, { omegaCeiling: 1e9 }).diagnostics.lever;
    // 0.0005 cm, pinned, and explaining 95 per cent of the interior: no residual, no wide
    // interval, no complaint. 3283 times too small, which is 57.2958 squared.
    return naive.pinned && fmt(naive.cm, 4) === '0.0005' && naive.explained > 0.94 &&
      est('drop-tumbling').diagnostics.lever.cm / naive.cm > 1000;
  })(), 'that is why the bound below exists');
check('the page quotes that collapse as three orders of magnitude rather than as 57.3 squared',
  inProse('the length collapses by three orders of magnitude') &&
  inProse('comes back as <strong>0.0005 cm</strong>') &&
  // The exponent is exact; the factor is not, because alpha scales as s where the centripetal
  // term scales as s squared, so the two columns do not scale together.
  !inProse('out by a factor of 3283'));
check('so the estimator bounds the rotation channel instead of trusting it',
  F.DEFAULTS.omegaCeiling === 50 && degRes.diagnostics.gyroSane === false);
check('it reports no lever arm from that record', degRes.diagnostics.lever.reportable === false);
check('and names the mistake rather than the reader',
  /degrees per second being read as radians/.test(degRes.diagnostics.lever.why) &&
  /57\.3/.test(degRes.diagnostics.lever.why));
check('it attributes nothing to a hand either, because a wrong omega bounds nothing',
  degRes.diagnostics.spinCeiling === null);
check('the ceiling sits above the fastest drop this page will still call a fall, and well below the blunder',
  F.DEFAULTS.omegaCeiling > 2.5 * 17.9 && F.DEFAULTS.omegaCeiling < 0.15 * (180 / Math.PI) *
  est('drop-tumbling').diagnostics.omegaInterior && est('drop-tumbling').diagnostics.gyroSane === true,
  `${F.DEFAULTS.omegaCeiling} vs 17.9 reportable and ${fmt((180 / Math.PI) * est('drop-tumbling').diagnostics.omegaInterior, 0)} blundered`);
check('and every shipped trace passes it',
  Object.keys(SLATE).every((k) => {
    const r = F.estimate(P[k], {});
    return r.refused || r.diagnostics.gyroSane !== false;
  }));
check('the page explains the hazard and the bound',
  inProse('no hand\n      turns a phone at eight revolutions a second'));
// The conversion itself, lifted out of the shipped file and run. A substring match would pass
// on a conversion that was missing, doubled or inverted; this does not.
function liftFunction(src, name) {
  const at = src.indexOf('function ' + name);
  if (at < 0) return null;
  const open = src.indexOf('{', at);
  let depth = 0;
  for (let j = open; j < src.length; j++) {
    if (src[j] === '{') depth++;
    else if (src[j] === '}') { depth--; if (depth === 0) return src.slice(at, j + 1); }
  }
  return null;
}
const startGyroSrc = liftFunction(INSTRUMENT, 'startGyro');
check('startGyro lifts out of instrument.js whole', !!startGyroSrc && startGyroSrc.includes('rotationRate'));
check('and run against a synthetic DeviceMotionEvent it converts degrees to radians, on all three axes',
  (() => {
    const win = { DeviceMotionEvent: function () {}, handlers: {},
      addEventListener: function (k, f) { win.handlers[k] = f; }, removeEventListener: function () {} };
    const made = new Function('window', 'performance', startGyroSrc + '\nreturn startGyro(60);')(
      win, { now: () => 0 });
    if (!win.handlers.devicemotion) return false;
    // W3C DeviceOrientation: alpha turns about z, beta about x, gamma about y, all in deg/s.
    win.handlers.devicemotion({ rotationRate: { alpha: 57.29577951308232, beta: 114.59155902616465, gamma: -28.647889756541161 } });
    const g = made.latest;
    return Math.abs(g.z - 1) < 1e-9 && Math.abs(g.x - 2) < 1e-9 && Math.abs(g.y + 0.5) < 1e-9 &&
      made.source === 'DeviceMotionEvent rotationRate';
  })());
check('a missing or doubled conversion would fail that, which is the point',
  (() => {
    const broken = startGyroSrc.replace('const D = Math.PI / 180;', 'const D = 1;');
    const win = { DeviceMotionEvent: function () {}, handlers: {},
      addEventListener: function (k, f) { win.handlers[k] = f; }, removeEventListener: function () {} };
    const made = new Function('window', 'performance', broken + '\nreturn startGyro(60);')(win, { now: () => 0 });
    win.handlers.devicemotion({ rotationRate: { alpha: 57.29577951308232, beta: 0, gamma: 0 } });
    return Math.abs(made.latest.z - 1) > 0.5;
  })());

// ── 9. g, and which route is a measurement ───────────────────────────────────
section('9. the two routes to g');
const hTrue = 0.5 * G_N * SLATE['drop-tumbling'].tFall ** 2;
check('the anchor drop implies a height of 0.5021 m at standard gravity', fmt(hTrue, 4) === '0.5021');
const gh = F.gFromHeight(hTrue, 0.03, d0.tFall, d0.uFall);
check('feeding that height back through g = 2h/t^2 returns g', near(gh.g, G_N, 0.05), fmt(gh.g, 4));
check('and the reported interval covers the standard value',
  gh.g - 1.96 * gh.u <= G_N && G_N <= gh.g + 1.96 * gh.u);
check('the fall time is the dominant term in that budget, and it enters twice',
  2 * d0.uFall / d0.tFall > 0.03 / hTrue, `${fmt(2 * d0.uFall / d0.tFall, 4)} vs ${fmt(0.03 / hTrue, 4)}`);
check('with no height typed in there is no g at all', F.gFromHeight(0, 0.03, 0.32, 0.017) === null);
check('the page says the height route is the only absolute one',
  inPageJs('This route uses the accelerometer only as a stopwatch'));
check('the impulse identity is exact in the generator: the whole-event mean is g_n',
  near(impactAmplitude(0.32, 0.12), Math.PI * G_N * (0.32 + 0.06) / (2 * 0.12), 1e-12));
check('the measured whole-event average sits within 7 per cent of the resting reading',
  Math.abs(d0.impulseRatio - 1) < 0.07, fmt(d0.impulseRatio, 4));
check('and it runs high rather than low on a tumbling drop, because a magnitude counts rotation',
  d0.impulseRatio > 1);
check('the page labels the impulse route a consistency check, not a measurement of g',
  inPageJs('CONSISTENCY CHECK and not') && inProse('reported as a consistency check'));
check('the page refuses to call the rest plateau a measurement of gravity',
  inProse('It is not a measurement of local gravity from the rest plateau.'));
check('standard gravity is quoted as the defined value it is',
  inProse('980.665 cm/s&#178;') && G_N === 9.80665 && inPageJs('9.80665 m/s'));

// ── 9a. the two edges, and which of them is the problem ─────────────────────
section('9a. the release edge, which is one-signed and outside the interval');
// The window opens when support has fallen by a QUARTER, not when it has gone. Every shipped
// trace releases between one reading and the next, which is what a hand that opens cleanly
// does. A hand that lets go slowly opens the window early, and since g goes as 1/t^2 the error
// doubles and never changes sign. The interval this page quotes on t covers the sampling and
// nothing else, so this one is stated separately rather than folded in.
const RELEASE = {};
for (const ramp of [0, 0.02, 0.04, 0.06]) {
  const ts = [];
  let slow = 0, maxRel = 0;
  for (let s2 = 0; s2 < 20; s2++) {
    const r = F.estimate(payloadOfSpec(Object.assign({}, SLATE['drop-tumbling'],
      { releaseRamp: ramp, seed: 40000 + s2 * 31, seconds: 3.4 })), {});
    if (r.refused) continue;
    ts.push(r.value);
    if (r.diagnostics.slowRelease) slow++;
    maxRel = Math.max(maxRel, 1000 * r.diagnostics.releaseSeconds);
  }
  const tMean = ts.reduce((a, b) => a + b, 0) / ts.length;
  // The height the reader would measure: from where the phone was when the fingers started to
  // open, which includes the head start the ramp gives it.
  const h = G_N * ramp * ramp / 6 + (G_N * ramp / 2) * 0.32 + 0.5 * G_N * 0.32 * 0.32;
  RELEASE[ramp] = { t: tMean, slow: slow, n: ts.length, maxRel: maxRel, g: 2 * h / (tMean * tMean) };
}
check('a clean release costs nothing: 0.3198 s against a true 0.3200, and g comes back at 9.82',
  fmt(RELEASE[0].t, 4) === '0.3198' && fmt(RELEASE[0].g, 2) === '9.82', fmt(RELEASE[0].t, 5));
check('20 ms of fingers: 0.3368 s and g 4 per cent low',
  fmt(RELEASE[0.02].t, 4) === '0.3368' && fmt(RELEASE[0.02].g, 2) === '9.42' &&
  fmt(100 * (1 - RELEASE[0.02].g / G_N), 0) === '4', fmt(RELEASE[0.02].g, 3));
check('40 ms: 0.3583 s and g 10 per cent low',
  fmt(RELEASE[0.04].t, 4) === '0.3583' && fmt(RELEASE[0.04].g, 2) === '8.84' &&
  fmt(100 * (1 - RELEASE[0.04].g / G_N), 0) === '10', fmt(RELEASE[0.04].g, 3));
check('60 ms: 0.3853 s and g 17 per cent low',
  fmt(RELEASE[0.06].t, 4) === '0.3853' && fmt(RELEASE[0.06].g, 2) === '8.11' &&
  fmt(100 * (1 - RELEASE[0.06].g / G_N), 0) === '17', fmt(RELEASE[0.06].g, 3));
check('every one of those is LOW, never high: the error has one sign',
  RELEASE[0.02].g < G_N && RELEASE[0.04].g < RELEASE[0.02].g && RELEASE[0.06].g < RELEASE[0.04].g);
check('and it is bigger than the interval the page quotes for the sampling',
  Math.abs(RELEASE[0.04].t - 0.32) > d0.uFall, `${fmt(RELEASE[0.04].t - 0.32, 4)} vs ${fmt(d0.uFall, 4)}`);
check('the instrument times its own release and flags it: 0 of 20 clean, 5 at 20 ms, 20 at 40 and 60',
  RELEASE[0].slow === 0 && RELEASE[0.02].slow === 5 && RELEASE[0.04].slow === 20 && RELEASE[0.06].slow === 20,
  [0, 0.02, 0.04, 0.06].map((r) => RELEASE[r].slow).join(' '));
check('a clean release never came within a reading of the flag, so it has no false alarms to give',
  fmt(RELEASE[0].maxRel, 1) === '9.9' && RELEASE[0].maxRel < 1000 * d0.dt,
  `${fmt(RELEASE[0].maxRel, 2)} ms against ${fmt(1000 * d0.dt, 2)} between readings`);
check('no shipped trace is flagged, because every one of them releases between two readings',
  ['drop-tumbling', 'drop-flat-cm', 'drop-barely-spun', 'drop-clipped']
    .every((k) => est(k).diagnostics.slowRelease === false && est(k).diagnostics.releaseReadings === 0));
check('the page prints that table', inProse('<td>0.3368 s</td>') && inProse('<td>0.3853 s</td>') &&
  inProse('9.42, 4 per cent low') && inProse('8.11, 17 per cent low') &&
  inProse('never exceeded 9.9 ms'));
check('and the live readout says it in the g route rather than only in the prose',
  inPageJs('SLOW RELEASE: the reading took') && inPageJs('fall time is LONG and this g is LOW'));
// The other edge, checked and found harmless, which is worth knowing because the safety
// instruction pushes the reader toward the softest landing available.
const soft = {};
for (const tImpact of [0.04, 0.12, 0.25]) {
  const ts = [];
  for (let s2 = 0; s2 < 12; s2++) {
    const r = F.estimate(payloadOfSpec(Object.assign({}, SLATE['drop-tumbling'],
      { tImpact, seed: 20000 + s2 * 17, seconds: 3.6 })), {});
    if (!r.refused) ts.push(r.value);
  }
  soft[tImpact] = ts.reduce((a, b) => a + b, 0) / ts.length;
}
check('the LANDING edge is not the problem: a 0.12 s contact moves the fall time by under a millisecond',
  Math.abs(soft[0.12] - soft[0.04]) < 0.001 && Math.abs(soft[0.12] - 0.32) < 0.002,
  `${fmt(soft[0.04], 5)} vs ${fmt(soft[0.12], 5)}`);
check('it takes a landing that lasts a quarter of a second, a 30 cm sink, before that edge moves at all',
  soft[0.25] - soft[0.12] > 0.010, fmt(soft[0.25] - soft[0.12], 4));
check('so the page tells the reader to open their fingers rather than to land harder',
  inProse('Open your fingers; do not lower them.') &&
  inProse('Do not throw.'));

// ── 10. the refusals ─────────────────────────────────────────────────────────
section('10. the refusal paths, one branch at a time');
const refuse = (p, o) => { const r = F.estimate(p, o || {}); return r.refused ? r.refused.reason : 'NOT REFUSED'; };
check('no readings at all', refuse(null) === 'too-few-readings');
check('too few readings', refuse({ times: [0, 1], ax: [1, 1], ay: [0, 0], az: [0, 0] }) === 'too-few-readings');
{
  const n = 300, t = [], ax = [], ay = [], az = [], w = [];
  for (let i = 0; i < n; i++) { t.push(i / 60); ax.push(8 * Math.sin(i)); ay.push(8 * Math.cos(1.7 * i)); az.push(8 * Math.sin(0.3 * i)); w.push(0); }
  check('nothing that looks like a phone held still',
    refuse({ times: t, ax, ay, az, wx: w, wy: w, wz: w }) === 'no-rest-plateau');
}
check('a stream too slow to place the edges', refuse(P['drop-slow-stream']) === 'rate-too-low');
check('a descent that never lets go', refuse(P['lift-descent']) === 'no-window');
check('a fall too short to hold an interior',
  refuse(P['drop-flat-cm'], { trim: 2, minInterior: 12 }) === 'interior-too-short');
check('a stream with no gyroscope gets a fall time but no lever arm', (() => {
  const p = Object.assign({}, P['drop-tumbling'], { wx: [], wy: [], wz: [] });
  const r = F.estimate(p, {});
  return !r.refused && !r.diagnostics.lever.reportable &&
    r.diagnostics.lever.why.includes('no gyroscope');
})());
check('a window that is not a fall gets no lever arm either',
  !low.diagnostics.lever.reportable && low.diagnostics.lever.why.includes('was not a fall'));
check('every refusal carries a reason code and a detail sentence', (() => {
  for (const p of [null, P['drop-slow-stream'], P['lift-descent']]) {
    const r = F.estimate(p, {});
    if (!r.refused || !r.refused.reason || !(r.refused.detail || '').length > 20) return false;
  }
  return true;
})());
check('the page carries the desktop refusal copy',
  inPageJs('This browser exposes no motion sensor') && inPageJs('This browser exposes no accelerometer'));
check('and the iOS permission copy, naming the exact setting',
  inPageJs('Settings, Safari, Motion and Orientation Access'));
check('and says the sensor APIs need a secure context',
  inPageJs('secure context: ') && inPageJs('the sensor APIs will refuse without it'));
check('and does not claim the gate injected the DeviceMotionEvent path',
  inProse('It does not reach the older') && inProse('it would be dishonest to imply otherwise'));

// ── 11. every free choice, swept ─────────────────────────────────────────────
section('11. the free choices, swept over their whole advertised range');
const GRID = { openFrac: [0.40, 0.55, 0.70, 0.75, 0.85, 0.95], freeFallFrac: [0.10, 0.25, 0.50],
  impactExcess: [2, 3.5, 6], trim: [0, 1, 2], stencil: ['central', 'forward'], fitBias: [0, 1] };
let combos = 0, badSlate = [], badLever = [];
for (const openFrac of GRID.openFrac) for (const freeFallFrac of GRID.freeFallFrac)
  for (const impactExcess of GRID.impactExcess) for (const trim of GRID.trim)
    for (const stencil of GRID.stencil) for (const fitBias of GRID.fitBias) {
      const o = { openFrac, freeFallFrac, impactExcess, trim, stencil, fitBias };
      combos++;
      const a = est('drop-tumbling', o), b = est('drop-flat-cm', o);
      if (a.refused || !near(a.value, 0.3200, SLATE_TOL) || !(a.uncertainty <= SLATE_TOL)) badSlate.push(['anchor', JSON.stringify(o)]);
      if (b.refused || !near(b.value, 0.1800, SLATE_TOL) || !(b.uncertainty <= SLATE_TOL)) badSlate.push(['control', JSON.stringify(o)]);
      if (!a.refused) {
        const L = a.diagnostics.lever;
        if (!L.reportable || L.loCm > rTrue || L.hiCm < rTrue) badLever.push(JSON.stringify(o));
      }
    }
check(`the anchor and the control survive all ${combos} settings of the five sliders and two switches`,
  badSlate.length === 0, badSlate.slice(0, 3).map((x) => x.join(' ')).join(' | '));
check('and the lever arm interval covers 2.2825 cm at every one of them',
  badLever.length === 0, badLever.slice(0, 3).join(' | '));
for (const mr of [10, 15, 20, 25, 30, 35, 40]) {
  const r = est('drop-slow-stream', { minRateHz: mr });
  if (mr === 10) check('the 18 Hz stream is refused at every setting of the rate floor, including the lowest',
    !!r.refused, r.refused ? r.refused.reason : 'not refused');
}
check('the 18 Hz stream is refused at all seven rate settings',
  [10, 15, 20, 25, 30, 35, 40].every((mr) => !!est('drop-slow-stream', { minRateHz: mr }).refused));
check('and limits.js accepts both refusal reasons it can honestly give',
  LIM.LIMITS.find((L) => L.id === 'drop-slow-stream').expect.length === 2);
// A constant offset and a slowly turning centripetal term look alike over a third of a second,
// and with the worst direction of the region quoted rather than the width along the fit, that
// stops being a widening and becomes a refusal. Which is the honest answer: a drop this short
// cannot have both.
check('fitting a free zero offset costs the spun drop its lever arm outright', (() => {
  const L = est('drop-tumbling', { fitBias: 1 }).diagnostics.lever;
  return fmt(L.loCm, 2) === '0.34' && fmt(L.hiCm, 2) === '4.35' && !L.pinned;
})(), fmt(est('drop-tumbling', { fitBias: 1 }).diagnostics.lever.hiCm, 3));
check('and widens the null drop\'s bound from 0.61 cm to 4.72', (() => {
  const L = est('drop-flat-cm', { fitBias: 1 }).diagnostics.lever;
  return fmt(L.halfCm, 2) === '4.72';
})(), fmt(est('drop-flat-cm', { fitBias: 1 }).diagnostics.lever.halfCm, 3));
check('the page says so on the switch itself',
  inProse('2.08 to\n      2.56 cm becomes 0.34 to 4.35, and a bound is all that survives'));
check('the page names every one of those choices in the estimator\'s defaults',
  ['openFrac', 'impactExcess', 'freeFallFrac', 'trim', 'restSeconds', 'restSd', 'restOmega',
    'restFloor', 'minRateHz', 'minInterior', 'railRun', 'fitBias', 'stencil', 'settleBand',
    'bootstraps'].every((k) => k in F.DEFAULTS));
check('and echoes them on the page rather than hiding them', inHtml('id="choices-echo"'));
check('the sliders ship on the estimator\'s own defaults',
  /id="c-open"[^>]*value="0.75"/.test(HTML) && F.DEFAULTS.openFrac === 0.75 &&
  /id="c-ff"[^>]*value="0.25"/.test(HTML) && F.DEFAULTS.freeFallFrac === 0.25 &&
  /id="c-impact"[^>]*value="3.5"/.test(HTML) && F.DEFAULTS.impactExcess === 3.5 &&
  /id="c-trim"[^>]*value="1"/.test(HTML) && F.DEFAULTS.trim === 1 &&
  /id="c-rate"[^>]*value="25"/.test(HTML) && F.DEFAULTS.minRateHz === 25);

// ── 12. the two grids, measured rather than assumed ──────────────────────────
section('12. the rounding grids Chromium applies');
const qa = (v) => Math.round(v / ACC_QUANTUM) * ACC_QUANTUM;
const qw = (v) => (Math.round((v * 180 / Math.PI) / GYRO_QUANTUM_DEG) * GYRO_QUANTUM_DEG) * Math.PI / 180;
check('9.81 lands on 9.8', fmt(qa(9.81), 1) === '9.8');
check('0.2079 lands on 0.2', fmt(qa(0.2079), 1) === '0.2');
check('-3.14159 lands on -3.1', fmt(qa(-3.14159), 1) === '-3.1');
check('0.04 lands on 0', qa(0.04) === 0);
check('the accelerometer grid is about 1 per cent of g', near(ACC_QUANTUM / G_N, 0.0102, 0.0002));
check('0.2079 rad/s is 11.9118 deg/s', fmt(0.2079 * 180 / Math.PI, 4) === '11.9118');
check('which rounds to 11.9 deg/s and comes back as 0.20769418 rad/s', fmt(qw(0.2079), 8) === '0.20769418');
check('-8.9 rad/s comes back as -8.899433856', fmt(qw(-8.9), 9) === '-8.899433856');
check('3.3333 rad/s comes back as 3.33357887', fmt(qw(3.3333), 8) === '3.33357887');
check('0.01 rad/s comes back as 0.010471976', fmt(qw(0.01), 9) === '0.010471976');
check('the gyroscope grid is pi/1800 = 0.001745 rad/s',
  fmt(GYRO_QUANTUM, 6) === '0.001745' && GYRO_QUANTUM === Math.PI / 1800);
check('the page prints all of those, exactly',
  inHtml('9.81 -> 9.8') && inHtml('0.2079 -> 0.2') && inHtml('-3.14159 -> -3.1') && inHtml('0.04 -> 0') &&
  inHtml('0.2079 rad/s -> 0.20769418 rad/s') && inHtml('-8.9 -> -8.899433856') &&
  inHtml('3.3333 -> 3.33357887') && inHtml('0.01 -> 0.010471976') &&
  inHtml('0.2079 rad/s = 11.9118 deg/s') && inHtml('pi/1800 = 0.001745 rad/s'));
check('the shipped traces carry both grids', (() => {
  const doc = JSON.parse(readFileSync(pathOfKey('drop-tumbling'), 'utf8'));
  const onAccGrid = doc.samples.every((s) => Math.abs(s.x / ACC_QUANTUM - Math.round(s.x / ACC_QUANTUM)) < 1e-6);
  const onGyroGrid = doc.samples.every((s) => Math.abs(s.gx / GYRO_QUANTUM - Math.round(s.gx / GYRO_QUANTUM)) < 1e-6);
  return onAccGrid && onGyroGrid;
})());
check('and the estimator finds that grid from the data alone', d0.readingStep === ACC_QUANTUM);

// ── 13. what the page says it is not ─────────────────────────────────────────
section('13. the scale comparison, and the claim it refuses to make');
const ETA = Math.hypot(2.3, 1.5) * 1e-15;
check('MICROSCOPE\'s stat and syst added in quadrature are 2.7e-15', fmt(ETA * 1e15, 1) === '2.7');
check('the page prints that combined bound', inHtml('2.7 &times; 10<sup>&minus;15</sup>'));
check('a phone reads in steps of one part in 98 of its own resting reading',
  Math.round(G_N / ACC_QUANTUM) === 98);
check('the page prints the 98', inHtml('one part in <strong>98</strong>'));
check('so MICROSCOPE is twelve orders of magnitude finer, not fourteen',
  Math.floor(Math.log10((ACC_QUANTUM / G_N) / ETA)) === 12,
  String(Math.log10((ACC_QUANTUM / G_N) / ETA)));
check('the page says twelve orders of magnitude', inHtml('<strong>twelve orders of magnitude</strong>'));
check('the page states the published MICROSCOPE result verbatim',
  inHtml('&minus;1.5 &#177; 2.3(stat) &#177; 1.5(syst)'));
check('and labels it a different experiment', inProse('as a different experiment rather'));
check('the page refuses the equivalence-principle framing outright',
  inProse('It is not a test of the equivalence principle.'));
check('and says why: one material, not two', inProse('both silicon on the same die'));
check('the page does not re-litigate gravity in space, it links the page that does',
  inHtml('href="/strata/moon-cannonball/"') && inProse('It is not a claim about space.'));
check('the page says it measures no person and no health quantity',
  inProse('It is not about your body.'));
check('nothing on the page claims a discovery', !/we (?:have )?discovered|for the first time/i.test(HTML));

// ── 14. the safety instruction, which comes before the button ────────────────
section('14. the instruction, and the path that needs no drop at all');
const safetyAt = HTML.indexOf('class="safety"');
const buttonAt = HTML.indexOf('id="btn-drop"');
check('the instruction block exists', safetyAt > 0);
check('and sits above the button, not under it', safetyAt < buttonAt);
check('it names bedding and rules out a hard floor',
  inProse('over a bed, a duvet, or a thick cushion') && inProse('Never over a hard floor'));
check('it caps the height well under a metre', inHtml('well under a metre'));
check('it rules out throwing', inHtml('Do not throw.'));
check('it asks for the case to stay on', inHtml('Keep the phone in its case'));
// The instruction is right and the justification it used to carry was false: a longer fall DOES
// read more precisely, because the edge error is one reading interval whatever the height, and
// the page prints that improvement back to the reader in route (a)'s error budget. So the page
// now states the trade and refuses it on safety grounds, and the arithmetic it quotes is checked
// here rather than asserted there.
{
  const dt = 1 / 60;
  const tOf = (h) => Math.sqrt(2 * h / G_N);
  check('a 25 cm drop gives the fall time 14.8 per cent of the error on g',
    fmt(100 * 2 * dt / tOf(0.25), 1) === '14.8', fmt(100 * 2 * dt / tOf(0.25), 1));
  check('and a 90 cm drop 7.8 per cent, so height genuinely buys precision',
    fmt(100 * 2 * dt / tOf(0.90), 1) === '7.8', fmt(100 * 2 * dt / tOf(0.90), 1));
  check('the page prints both figures rather than claiming nothing improves',
    inProse('from 25 cm that is 14.8 per cent, from 90 cm it') && inProse('is 7.8 per cent'));
  check('and still refuses the trade on safety grounds, over a hard floor',
    inProse('What this page will not do is') && inProse('trade that against a phone over a hard floor'));
  check('20 to 30 cm is twelve to fifteen readings at 60 Hz, and 20 cm still clears what the interior needs',
    Math.floor(tOf(0.20) * 60) === 12 && Math.floor(tOf(0.30) * 60) === 14 &&
    Math.floor(tOf(0.20) * 60) >= F.DEFAULTS.minInterior + 2 * F.DEFAULTS.trim,
    `${Math.floor(tOf(0.20) * 60)} to ${Math.ceil(tOf(0.30) * 60)} readings vs ${F.DEFAULTS.minInterior + 2 * F.DEFAULTS.trim} needed`);
  check('and the page says so where it names the height',
    inProse('at sixty readings a second that is a fall') &&
    inProse('twelve to fifteen readings long, against the five it needs inside the window'));
  check('the shipped anchor is a longer drop than the page asks for, and the page admits it',
    fmt(0.5 * G_N * SLATE['drop-tumbling'].tFall ** 2 * 100, 0) === '50' &&
    inProse('is a <strong>50 cm</strong> drop, longer than the safety box above will ask anyone'));
}
check('there is a second button that never lets go of the phone', inHtml('id="btn-lower"'));
check('and it is offered inside the instruction as the alternative',
  inProse('take the second button instead'));
check('the page says plainly which path is the precise one',
  inProse('<strong>A drop</strong> gives the clean measurement') &&
  inProse('It is genuinely less precise, and here is the size of that'));
check('and that the no-drop path still measures something real of the reader\'s',
  inProse('gives a real measurement too, of a different thing'));
check('the hand-lowering path runs the same capture and the same estimator',
  inProse('Both buttons run the same capture and the same estimator.') &&
  (INSTRUMENT.match(/record\('a drop'|record\('a hand-lowering'/g) || []).length === 2);
check('and the shipped hand-lowering trace shows what that path returns: a number, not a refusal',
  !low.refused && low.diagnostics.frac > 0 && !low.diagnostics.freeFall);

// ── 15. the live path is the reader's path ───────────────────────────────────
section('15. the live path, and the gate case');
check('captureLive is defined once', (INSTRUMENT.match(/async function captureLive/g) || []).length === 1);
check('the reader\'s buttons reach the sensor only through it: two call sites, one function',
  (INSTRUMENT.match(/await captureLive\(/g) || []).length === 2 &&
  (INSTRUMENT.match(/captureLive\(/g) || []).length === 4);
check('probeLive calls that same captureLive and the same tryMeasure',
  /probeLive: async function \(o\) \{\s*try \{ return await inst\.tryMeasure\(await captureLive\(/.test(INSTRUMENT));
check('and there is no second estimator anywhere in the page',
  (INSTRUMENT.match(/F\.estimate\(/g) || []).length >= 1 && !INSTRUMENT.includes('function estimate'));
// The arming rule used to cover the headline and nothing else: the figures, the lever arm and
// the two routes to g called the estimator on the reader's payload directly, so a NOT ARMED
// slate still printed the reader's centimetres. One decision now feeds every panel.
check('the reader\'s own record reaches the estimator in exactly one place',
  (INSTRUMENT.match(/F\.estimate\(reader\.payload/g) || []).length === 1);
check('and that place refuses before it estimates, on the kit\'s own arming rule',
  /function shown\s*\(\)\s*\{\s*const armed = inst\.armed\(\);\s*if \(!armed\) return \{ notArmed:[\s\S]{0,200}?F\.estimate\(reader\.payload/
    .test(INSTRUMENT));
check('every panel goes through that one decision: the figures, the lever arm and the g routes',
  !INSTRUMENT.includes('shownResult') && (INSTRUMENT.match(/= shown\(\);/g) || []).length === 2 &&
  /if \(S\.notArmed\) \{ el\.textContent = NOT_ARMED_COPY/.test(INSTRUMENT));
check('and a disarmed page reports nothing at all, the shipped drop included',
  inPageJs('so nothing is reported here: not yours, and not the') &&
  inProse('not your ratio, not your centimetres, not your g, and not the') &&
  inProse('shipped drop\'s either'));
check('the gate case names this page and the motion sensor',
  CASESRC.sensor === 'motion' && CASESRC.path === '/strata/free-fall-weightless/');
check('its unit is the one the instrument reports', CASESRC.unit === 's' && INSTRUMENT.includes("unit: 's'"));
for (const side of ['anchor', 'control']) {
  check(`the ${side} injection file exists`, existsSync(join(ROOT, CASESRC.inject[side].file)));
}
const gA = est('inject-a'), gB = est('inject-b');
check('injection A carries a 0.4000 s fall by construction', SLATE['inject-a'].tFall === 0.4000);
check('injection B carries a 0.1600 s fall by construction', SLATE['inject-b'].tFall === 0.1600);
check('the two injections have genuinely different true answers',
  SLATE['inject-a'].tFall !== SLATE['inject-b'].tFall);
check('the estimator reads A as the case file expects',
  near(gA.value, CASESRC.inject.anchor.expect, CASESRC.inject.anchor.tol), fmt(gA.value));
check('the estimator reads B as the case file expects',
  near(gB.value, CASESRC.inject.control.expect, CASESRC.inject.control.tol), fmt(gB.value));
check('and the two expectations are further apart than the tolerances can bridge',
  Math.abs(CASESRC.inject.anchor.expect - CASESRC.inject.control.expect) >
  CASESRC.inject.anchor.tol + CASESRC.inject.control.tol);
check('the gate contract is published on window before load finishes',
  inPageJs('window.__awAnchor') && inPageJs("slug: 'free-fall-weightless'") &&
  inPageJs("sensor: 'motion'"));

// ── 16. proof that the checks above can fail ─────────────────────────────────
section('16. the control on the control: these checks can go red');
// (a) a constant estimator, of exactly the kind the kit's stubProbe runs on the page.
const stub = () => ({ value: 0.3200, uncertainty: 0.004 });
check('a constant estimator returning 0.3200 passes the anchor', near(stub().value, 0.3200, SLATE_TOL));
check('and fails the control, so it can never arm', !near(stub().value, 0.1800, SLATE_TOL));
// (b) the same, on the flagship: a constant lever arm is wrong on two of the three drops.
check('a constant lever arm of 2.32 cm is refuted by the chip-at-the-centre drop',
  !(flat.loCm <= 2.32 && 2.32 <= flat.hiCm));
check('and by the barely spun drop, which supports no value at all', !Lb.pinned);
// (c) loosen the threshold and the lift descent stops being refused, which is what makes the
// refusal a claim about the trace rather than about the code.
const liftLoose = est('lift-descent', { openFrac: 0.95 });
check('at a 0.95 threshold the lift descent does open a window',
  !liftLoose.refused, liftLoose.refused && liftLoose.refused.reason);
check('so the no-window refusal at 0.75 is a fact about the trace, not a property of the code',
  LIM.classify(LIM.LIMITS[2], liftLoose).ok === false);
check('but even then it is not called free fall: 0.88 of resting is not a fall',
  !liftLoose.diagnostics.freeFall);
// (d) raise the cutoff and the hand-lowering stops being turned down.
check('at a 0.50 cutoff the hand-lowering is admitted, which is the slider doing the work',
  est('lowering-by-hand', { freeFallFrac: 0.50 }).diagnostics.freeFall === true);
check('and limits.js grades that as a failure of the row rather than silently passing it',
  LIM.classify(LIM.LIMITS[1], est('lowering-by-hand', { freeFallFrac: 0.50 })).ok === false);
// (e) a doctored trace must break the hash check.
check('a single altered reading breaks the regeneration hash', (() => {
  const doc = JSON.parse(readFileSync(pathOfKey('drop-tumbling'), 'utf8'));
  doc.samples[100].x += 0.1;
  const h = createHash('sha256').update(Buffer.from(JSON.stringify(doc))).digest('hex');
  return h !== createHash('sha256').update(bufferOf('drop-tumbling')).digest('hex');
})());
// (f) and the window rule itself: if the interior were selected for being small, the lowering
// could not have returned 0.3832. It is the number the estimator was not free to choose.
check('the lowering\'s interior mean is far above anything a "select the small samples" rule could return',
  low.diagnostics.interiorMean > 3 && low.diagnostics.interiorMean < low.diagnostics.openLevel,
  fmt(low.diagnostics.interiorMean, 4));

// ── 17. the frontmatter and the shareable surface ────────────────────────────
section('17. the frontmatter, the dek, the plain card and the JSON-LD');
const fmBlock = MDSRC.split('---')[1] || '';
const field = (k) => {
  const m = new RegExp('^' + k + ': *"?([\\s\\S]*?)"?$', 'm').exec(fmBlock);
  return m ? m[1] : '';
};
check('seam is physical, which is in the closed vocabulary', /^seam: "physical"$/m.test(fmBlock));
check('href marks it immersive', /^href: "\/strata\/free-fall-weightless\/"$/m.test(fmBlock));
check('it is not a draft', /^draft: false$/m.test(fmBlock));
const plain = field('plain');
check('the plain card is at most 420 characters', plain.length <= 420, String(plain.length));
check('and at most three sentences', (plain.match(/[.!?](\s|$)/g) || []).length <= 3);
check('and says what the instrument cannot do', plain.includes('It cannot get gravity from the resting reading'));
const seoTitle = field('seoTitle');
check('the seo title is under about 60 characters', seoTitle.length <= 60, String(seoTitle.length));
for (const slug of ['the-string-that-beats-seconds', 'is-centrifugal-force-real', 'moon-cannonball', 'the-falling-cat']) {
  check(`relates target ${slug} exists`, existsSync(join(ROOT, 'src/content/strata', slug + '.md')));
}
check('there are four relates edges, each with a note',
  (fmBlock.match(/^ {2}- to: /gm) || []).length === 4 &&
  (fmBlock.match(/^ {4}note: /gm) || []).length === 4);
check('no em dash anywhere in the page source', !HTML.includes('—') && !INSTRUMENT.includes('—') &&
  !FALLSRC.includes('—') && !readFileSync(join(PAGE, 'limits.js'), 'utf8').includes('—'));
check('nor in the frontmatter entry', !MDSRC.includes('—'));
// The dek and the body of the .md must not outrun the apparatus.
check('the dek claims two recovered fall times and five further traces',
  inMd('recovers two synthesised fall times it was never told') && inMd('on five further traces'));
check('and the count is right: two slate specimens and five limits',
  LIM.LIMITS.length === 5 && INSTRUMENT.includes("id: 'drop-tumbling', role: 'anchor'") &&
  INSTRUMENT.includes("id: 'drop-flat-cm', role: 'control'"));
check('the dek\'s breakdown of the five is what the estimator actually does', (() => {
  const outright = LIM.LIMITS.filter((L) => L.want === 'refuse').length;
  const number = LIM.LIMITS.filter((L) => L.want === 'not-free-fall').length;
  const sat = LIM.LIMITS.filter((L) => L.want === 'saturated').length;
  const unpinned = LIM.LIMITS.filter((L) => L.want === 'unpinned').length;
  return outright === 2 && number === 1 && sat === 1 && unpinned === 1;
})());
check('the .md body\'s lever-arm figures match the fit',
  inMd('pins the offset to 2.32 cm with a 95 per cent interval of 2.08 to 2.56 against a true 2.2825') &&
  inMd('only an upper bound of 7.64 cm') && inMd('comes back at 0.00 cm within \u00b10.61'));
check('and the .md body carries the single-axis failure too, not only the page',
  inMd('the old rule printed a confident number on 17 of them and was right about seven') &&
  inMd('blind to the part of `r` lying along'));
check('the plain card does not promise gravity from the rest plateau',
  !/measures (?:local )?gravity/i.test(plain));
const ld = JSON.parse((/<script type="application\/ld\+json">([\s\S]*?)<\/script>/.exec(HTML) || [, '{}'])[1]);
check('the JSON-LD parses as JSON', !!ld['@type']);
check('and its headline is the page\'s own title', ld.headline === 'Weight Is the Table, Not the Earth');
check('and its url is the canonical one', ld.url === 'https://artwaste.land/strata/free-fall-weightless/');
check('the JSON-LD description names the slate and the five refusals',
  ld.description.includes('recovers two synthesised drops with exact fall times') &&
  ld.description.includes('refuses five traces it cannot honestly read'));

// ── the surfaces a reader sees WITHOUT opening the page ──────────────────────
// This is where the defect lived. The body said "the fit accounts for 98.6 per cent ... over 51
// equations and 3 unknowns" and every shareable surface said the leftover was predicted from
// the gyroscope alone, before it was looked at. Whoever never opens the page sees only the
// second one, so the surfaces are enumerated here and swept, rather than one of them being
// spot-checked against a blacklist of two phrases.
const attr = (re) => (re.exec(HTML) || [, ''])[1];
const SURFACES = {
  'the meta description': attr(/<meta name="description" content="([\s\S]*?)"/),
  'the og:description': attr(/<meta property="og:description" content="([\s\S]*?)"/),
  'the twitter:description': attr(/<meta name="twitter:description" content="([\s\S]*?)"/),
  'the JSON-LD description': ld.description,
  'the dek': field('dek'),
  'the plain card': plain,
  'the live lever-arm readout': (/setText\('lever-detail',([\s\S]*?)\);/.exec(INSTRUMENT) || [, ''])[1],
  'the lever figure overlay': (/g\.fillText\('dots:([\s\S]*?)',/.exec(INSTRUMENT) || [, ''])[1],
  'the lever canvas label': attr(/<canvas id="fig-lever" aria-label="([\s\S]*?)"/),
  'the lever figcaption': (/<figcaption>([\s\S]*?)<\/figcaption>/g.exec(HTML) || [, ''])[1],
};
for (const [name, text] of Object.entries(SURFACES)) {
  check(`${name} exists and is not empty`, typeof text === 'string' && text.length > 20, String(text).slice(0, 40));
}
// Claims the apparatus does not support. Every one of these was on a surface of this page.
const BANNED = [
  [/from the gyroscope alone/i, 'the lever arm is not obtained from the gyroscope alone'],
  [/before it is looked at/i, 'nothing is predicted before it is looked at'],
  [/gyroscope[^.]{0,80}predicts[^.]{0,80}accelerometer/i, 'the gyroscope does not predict the accelerometer'],
  [/predicted, to the centimetre/i, 'the centimetres are fitted, not predicted'],
  [/measures (?:local )?gravity|your local gravity/i, 'the rest plateau is a calibration, not gravity'],
];
for (const [name, text] of Object.entries(SURFACES)) {
  for (const [re, why] of BANNED) {
    check(`${name} does not claim what the apparatus cannot do (${why})`, !re.test(String(text)),
      (re.exec(String(text)) || [''])[0]);
  }
}
// And the positive half: a surface that promises the reader centimetres has to say they are fitted.
for (const [name, text] of Object.entries(SURFACES)) {
  const s = String(text);
  if (!/centimetre|\bcm\b|distance (?:to|from)/i.test(s)) continue;
  check(`${name} promises centimetres, so it names them as a fit`,
    /fit|fitted|fitting|three numbers|least squares|lever arm/i.test(s), s.slice(0, 60));
}
check('and the page admits, on the page, that no real handset trace is shipped',
  inProse('no real handset trace is shipped anywhere on this page') &&
  inProse('<strong>No real handset trace is shipped.</strong> Every specimen is synthesised.'));
check('which is true: all nine regenerate from the forward model, so none came off a phone',
  Object.keys(SLATE).every((k) => !!SLATE[k].hz && !!bufferOf(k).length));
check('the title, the H1 and the frontmatter title agree',
  inHtml('<title>Weight Is the Table, Not the Earth</title>') &&
  inHtml('<h1>Weight Is the Table, Not the Earth</h1>') &&
  /^title: "Weight Is the Table, Not the Earth"$/m.test(fmBlock));
check('the MICROSCOPE figure is quoted with the confidence the paper states it at',
  inProse('quoted in the paper at 1&sigma; in statistical errors') &&
  inProse('at that same 1&sigma;'));
check('and the footer cites the DOI for the bound the body actually prints',
  inHtml('2.7&#215;10<sup>&minus;15</sup> bound quoted above') &&
  inHtml('2.7 &times; 10<sup>&minus;15</sup>') && fmt(Math.hypot(2.3, 1.5), 1) === '2.7');
check('the 0.1 m/s^2 step is attributed to the browser that applies it, not to phones in general',
  inProse('A phone in Chrome reads in steps of 0.1 m/s&#178;') &&
  inProse('both numbers above are that') && inProse('browser\'s, measured on the Generic Sensor path'));

// ── 18. the page as a document ───────────────────────────────────────────────
section('18. the page as a document');
check('it closes its tags', HTML.trim().endsWith('</html>') && HTML.includes('</body>'));
const opens = (HTML.match(/<script\b/g) || []).length;
const closes = (HTML.match(/<\/script>/g) || []).length;
check('every script tag is closed', opens === closes && opens >= 5, `${opens} open, ${closes} close`);
check('it loads the kit, the estimator, the limits and the page, in that order',
  HTML.indexOf('/_kit/anchor.js') < HTML.indexOf('/_kit/sensors.js') &&
  HTML.indexOf('/_kit/sensors.js') < HTML.indexOf('./fall.js') &&
  HTML.indexOf('./fall.js') < HTML.indexOf('./limits.js') &&
  HTML.indexOf('./limits.js') < HTML.indexOf('./instrument.js'));
check('there is no inline script other than the JSON-LD block',
  (HTML.match(/<script(?![^>]*src=)(?![^>]*application\/ld\+json)/g) || []).length === 0);
for (const f of ['fall.js', 'limits.js', 'instrument.js']) {
  let ok = true, why = '';
  try { execFileSync(process.execPath, ['--check', join(PAGE, f)], { stdio: 'pipe' }); }
  catch (e) { ok = false; why = String(e.stderr || e).slice(0, 160); }
  check(`node --check passes on ${f}`, ok, why);
}
check('the page\'s own scripts make no third-party request', (() => {
  const src = FALLSRC + INSTRUMENT + readFileSync(join(PAGE, 'limits.js'), 'utf8');
  const urls = src.match(/https?:\/\/[^\s'"`)]+/g) || [];
  return urls.length === 0;
})());
// The only absolute URLs in the document are the site's own, the schema.org vocabulary
// identifier and the site's own social profile, all of them inside metadata. None is fetched.
check('and the document references no third-party host', (() => {
  const urls = HTML.match(/https?:\/\/[^\s'"`)]+/g) || [];
  const allow = ['https://artwaste.land', 'https://schema.org', 'https://bsky.app/profile/artwaste.land'];
  return urls.every((u) => allow.some((a) => u.startsWith(a)));
})());
check('the readouts are live regions', /id="live-out"[^>]*role="status"[^>]*aria-live/.test(HTML) &&
  /id="g-out"[^>]*role="status"[^>]*aria-live/.test(HTML));
check('the canvases carry labels', (HTML.match(/<canvas[^>]*aria-label=/g) || []).length === 2);
check('every control has a label', (HTML.match(/<label for="/g) || []).length >= 9);
check('reduced motion is honoured', inHtml('@media (prefers-reduced-motion: reduce)'));
check('the fonts are the self-hosted ones', inHtml('href="/fonts/fonts.css"') && !inHtml('fonts.googleapis'));
check('wide tables scroll inside their own box rather than the page',
  (HTML.match(/class="scroll"/g) || []).length >= 4 && inHtml('.scroll { overflow-x:auto'));
check('the page names this verifier by its real filename',
  inHtml('node research/free-fall-weightless/verify-free-fall-weightless.mjs') &&
  existsSync(join(HERE, 'verify-free-fall-weightless.mjs')));
check('the page tells the reader nothing they record leaves the tab',
  inProse('Nothing recorded here is transmitted anywhere.'));
check('and that the streams are stopped when a recording ends',
  inPageJs('gy.stop()') && inProse('are stopped the moment it ends'));

// ── 19. the score sentence the page states about this file ───────────────────
section('19. the sentence this page states about this verifier');
const claimed = (/<strong id="score-claim">(\d+)\/(\d+) checks<\/strong>/.exec(HTML) || [])[1];
const claimedDen = (/<strong id="score-claim">(\d+)\/(\d+) checks<\/strong>/.exec(HTML) || [])[2];
const total = results.length + 1;
check(`the page states this verifier's score, and it is ${total}/${total}`,
  Number(claimed) === total && Number(claimedDen) === total,
  `page says ${claimed}/${claimedDen}, this run is ${failed === 0 ? total : total - failed}/${total}`);

// ── the tally ────────────────────────────────────────────────────────────────
const passed = results.filter((r) => r.pass).length;
console.log('');
if (failed) {
  console.log(`FAILURES (${failed}):`);
  for (const r of results) if (!r.pass) console.log(`  - ${r.name}${r.detail ? '  <- ' + r.detail : ''}`);
}
console.log(`${passed}/${results.length} checks passed`);
process.exit(failed ? 1 : 0);
