#!/usr/bin/env node
// verify-lightest-in-the-middle-of-a-step.mjs
//
//   node research/lightest-in-the-middle-of-a-step/verify-lightest-in-the-middle-of-a-step.mjs
//
// Recomputes every number the page prints, from the closed forms and the sources, and exits
// non-zero on any disagreement. It reads public/, never dist/, because a verifier that reads
// a build output can pass on a page nobody shipped.
//
// It does four things a value-checking verifier would not:
//
//   1. It REGENERATES every specimen from make-specimens.mjs and compares sha256 against the
//      committed file, so a doctored specimen is caught rather than trusted.
//   2. It loads the page's REAL scripts (public/_kit/dsp.js, anchor.js and the page's own
//      gait.js) into a browser-shaped sandbox and runs the identical estimate(). There is no
//      second implementation of the physics in this file to drift away from the first.
//   3. It tests that the checks CAN FAIL: a constant estimator must not arm the slate, and
//      each of the four refusals must turn into a number when its gate is removed. A gate that
//      would refuse anyway is not doing the work the page says it does.
//   4. It string-matches the rendered figures against the page's own HTML, the frontmatter,
//      the meta tags and the JSON-LD, because nothing else in this repo asserts about what the
//      reader actually sees.
import { readFileSync, existsSync, statSync } from 'node:fs';
import { createHash } from 'node:crypto';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import vm from 'node:vm';
import * as S from './make-specimens.mjs';
import { estimatorCodeSha } from './fukuchi-probe.mjs';

const HERE = dirname(fileURLToPath(import.meta.url));
const ROOT = join(HERE, '..', '..');
const SLUG = 'lightest-in-the-middle-of-a-step';
const PAGE = join(ROOT, 'public/strata', SLUG);

let pass = 0, fail = 0;
const failures = [];
function ok(cond, msg, detail) {
  if (cond) { pass++; return true; }
  fail++; failures.push(msg + (detail ? '  [' + detail + ']' : ''));
  console.log('  x FAIL  ' + msg + (detail ? '  [' + detail + ']' : ''));
  return false;
}
function near(got, want, tol, msg) {
  return ok(typeof got === 'number' && isFinite(got) && Math.abs(got - want) <= tol,
    msg, 'got ' + (typeof got === 'number' ? got.toPrecision(8) : String(got)) + ', want ' + want + ' +/- ' + tol);
}
function head(t) { console.log('\n' + t); }

// ── load the page's own code, in a browser-shaped sandbox ────────────────────
const sandbox = { console: { log() {}, warn() {}, error() {} } };
vm.createContext(sandbox);
sandbox.window = sandbox;                       // window.AW and AW are the same object, as in a browser
for (const f of ['public/_kit/dsp.js', 'public/_kit/anchor.js', join('public/strata', SLUG, 'gait.js')]) {
  vm.runInContext(readFileSync(join(ROOT, f), 'utf8'), sandbox, { filename: f });
}
const AW = sandbox.window.AW;
const G = AW.gait.G;

const html = readFileSync(join(PAGE, 'index.html'), 'utf8');
const instrumentJs = readFileSync(join(PAGE, 'instrument.js'), 'utf8');
const gaitJs = readFileSync(join(PAGE, 'gait.js'), 'utf8');
const md = readFileSync(join(ROOT, 'src/content/strata', SLUG + '.md'), 'utf8');
const cite = JSON.parse(readFileSync(join(HERE, 'citations.json'), 'utf8'));
const gateCase = JSON.parse(readFileSync(join(ROOT, 'research/anchor-wave/cases', SLUG + '.json'), 'utf8'));

// The page's prose is wrapped and indented, so text is matched against a whitespace-flattened
// copy. Nothing else is normalised: a quotation still has to be there character for character.
const flat = html.replace(/\s+/g, ' ');
const inPage = (s, msg) => ok(flat.includes(s.replace(/\s+/g, ' ')), msg,
  'page does not contain: ' + JSON.stringify(s.slice(0, 90)));

function loadTrace(path) {
  const d = JSON.parse(readFileSync(path, 'utf8'));
  const n = d.samples.length;
  const times = new Array(n), x = new Array(n), y = new Array(n), z = new Array(n);
  for (let i = 0; i < n; i++) { const s = d.samples[i]; times[i] = s.t; x[i] = s.x; y[i] = s.y; z[i] = s.z; }
  return { times, x, y, z, source: 'shipped specimen', nominalHz: d.hz, quantum: d.quantum };
}
const sha = (p) => createHash('sha256').update(readFileSync(p)).digest('hex');

// ═══ 1. the specimens regenerate byte for byte ═══════════════════════════════
head('1. every shipped specimen regenerates from its closed form, byte for byte');
const before = {};
for (const key of Object.keys(S.SLATE)) before[key] = existsSync(S.pathOf(key)) ? sha(S.pathOf(key)) : null;
const regen = S.writeAll();
let totalBytes = 0;
for (const key of Object.keys(S.SLATE)) {
  totalBytes += regen[key].bytes;
  ok(before[key] !== null && before[key] === regen[key].sha256,
    'specimen ' + key + ' matches its regenerated sha256',
    before[key] === null ? 'missing on disk' : before[key] + ' vs ' + regen[key].sha256);
}
ok(totalBytes < 3 * 1024 * 1024, 'the shipped specimens are inside the 3 MB budget',
  (totalBytes / 1024).toFixed(1) + ' kB');

// ═══ 2. the closed forms are what they claim ═════════════════════════════════
head('2. the generator truths are exact and analytic, not fitted');
near(S.P(0), 1, 1e-12, 'the vertical shape P has value exactly 1 at mid-stance');
let maxP = -Infinity, argmax = 0;
for (let i = 0; i <= 200000; i++) { const v = S.P(i / 200000); if (v > maxP) { maxP = v; argmax = i / 200000; } }
near(maxP, 1, 1e-9, 'and 1 is its maximum over the whole step');
ok(argmax < 1e-4 || argmax > 1 - 1e-4, 'and that maximum sits at mid-stance', 'argmax ' + argmax);
let meanP = 0; const NQ = 200000;
for (let i = 0; i < NQ; i++) meanP += S.P((i + 0.5) / NQ);
near(meanP / NQ, 0, 1e-9, 'and its mean over a whole step is exactly 0, so mean(a_v) is exactly g');
near(S.truthOf('walk-vault-0222'), 1.40 * 1.40 / (G * 0.90), 1e-12,
  'the anchor dip is v^2/(gR) with v = 1.400 m/s and R = 0.900 m');
near(S.truthOf('walk-vault-0118'), 0.95 * 0.95 / (G * 0.78), 1e-12,
  'the control dip is v^2/(gR) with v = 0.950 m/s and R = 0.780 m');
near(Math.abs(S.truthOf('walk-vault-0222') - S.truthOf('walk-vault-0118')), 0.1041, 0.0005,
  'the two truths are the 0.104 apart the page claims');
ok(0.025 + 0.025 < Math.abs(S.truthOf('walk-vault-0222') - S.truthOf('walk-vault-0118')),
  'and the declared tolerances sum to less than that gap, so no constant satisfies both');
near(S.truthOf('hand-swing'), 0.30 * Math.cos(35 * Math.PI / 180), 1e-12,
  'the hand-swing truth is amplitude times the cosine of its tilt');

// 2b. THE LEFT-RIGHT ASYMMETRY the control specimen carries, and the three properties that
// let it be added without moving the answer by one part in a trillion. A real body has this
// and a synthesised one does not; the estimator refused real walking until it did.
for (const k of [-2, -1, 0, 1, 2, 3]) {
  ok(Math.abs(S.A(k)) < 1e-15, 'the asymmetry A is exactly zero at mid-stance phi = ' + k,
    S.A(k).toExponential(2));
}
let meanA = 0; const NA = 200000;
for (let i = 0; i < NA; i++) meanA += S.A((i + 0.5) / NA);
near(meanA / NA, 0, 1e-9, 'and its mean over a step is exactly zero, so mean(a_v) is still exactly g');
let meanA2 = 0;
for (let i = 0; i < NA; i++) meanA2 += S.A(1 + (i + 0.5) / NA);
near(meanA2 / NA, 0, 1e-9, 'over the NEXT step too, which is the one it pushes the other way');
for (const p of [0.13, 0.37, 0.61, 0.88]) {
  near(S.A(p + 1), -S.A(p), 1e-12, 'A(phi + 1) = -A(phi) at phi = ' + p + ': one step up, the next down');
}
ok(S.SLATE['walk-vault-0118'].asym > 0 && !S.SLATE['walk-vault-0222'].asym,
  'the control walk carries that asymmetry and the anchor does not, so the slate covers both kinds of body');
ok(S.SLATE['inject-b'].asym > 0, 'and so does one of the two traces the live-sensor gate injects');
// The dip really is still exactly g(1 - d) at mid-stance with the asymmetry added: scan a
// whole stride of the control's own world function and find the minimum.
{
  const key = 'walk-vault-0118', s = S.SLATE[key], d = S.truthOf(key);
  const w = S.walkWorld({ d: d, fStep: 1, ax: s.ax, ay: s.ay, asym: s.asym });
  let lo = Infinity, argLo = 0;
  for (let i = 0; i <= 400000; i++) { const phi = 2 * i / 400000; const v = w(phi).z; if (v < lo) { lo = v; argLo = phi; } }
  near(lo / S.G, 1 - d, 1e-9, 'with the asymmetry in, the vertical minimum over a whole stride is still exactly g(1 - d)');
  ok(Math.abs(argLo - Math.round(argLo)) < 1e-4, 'and it still sits exactly at a mid-stance', 'at phi ' + argLo.toFixed(5));
}

// ═══ 3. the identical estimator on every shipped signal ══════════════════════
head('3. the page\'s own estimate(), unmodified, on every shipped signal');
const est = (key, opts) => AW.gait.estimate(loadTrace(S.pathOf(key)), opts);
const results = {};
for (const key of ['walk-vault-0222', 'walk-vault-0118', 'hand-swing', 'inject-a', 'inject-b']) {
  const r = est(key);
  results[key] = r;
  const truth = S.truthOf(key);
  ok(!r.refused, 'it returns a number for ' + key, r.refused && r.refused.reason);
  if (r.refused) continue;
  near(r.value, truth, 0.025, key + ' recovers its exact truth inside the declared tolerance');
  ok(Math.abs(r.value - truth) <= r.uncertainty,
    'and inside its OWN reported interval, which is the harder test',
    'error ' + (r.value - truth).toFixed(5) + ' vs interval ' + r.uncertainty.toFixed(5));
  ok(r.uncertainty <= 0.025, 'and the claimed interval is no wider than the tolerance it is judged against');
}
// The estimator's own bias, measured rather than assumed: the page states about 2 per cent low.
for (const key of ['walk-vault-0222', 'walk-vault-0118']) {
  const rel = (results[key].value - S.truthOf(key)) / S.truthOf(key);
  ok(rel < 0 && Math.abs(rel) < 0.05,
    'the known low bias on ' + key + ' is low and under 5 per cent, as the page says',
    (100 * rel).toFixed(2) + ' per cent');
}
// The page's step figure is drawn from the array estimate() read the dip off, so the picture
// and the number cannot disagree. Assert the coupling holds numerically.
for (const key of ['walk-vault-0222', 'walk-vault-0118']) {
  const g = results[key].diagnostics;
  ok(Array.isArray(g.ensemble) && g.ensemble.length === 200,
    key + ' hands back the 200-point average step the figure is drawn from');
  const at = (p) => { const x = p * 200, i = Math.floor(x), f = x - i;
    return g.ensemble[Math.min(199, i)] * (1 - f) + g.ensemble[Math.min(199, i + 1)] * f; };
  near(1 - at(g.midStancePhase), results[key].value, 0.002,
    'and the marked point on that curve is the reported dip for ' + key);
  ok(Math.min.apply(null, g.ensemble) > 0.6 && Math.max.apply(null, g.ensemble) < 1.4,
    'the drawn step stays inside a plausible 0.6 to 1.4 body weights for ' + key);
}
near(results['walk-vault-0222'].diagnostics.stepHz, S.SLATE['walk-vault-0222'].fStep, 0.02,
  'the reported step rate matches the generator, to 0.02 Hz');
near(results['walk-vault-0118'].diagnostics.stepHz, S.SLATE['walk-vault-0118'].fStep, 0.02,
  'and so does the control\'s');
// A ratio has two ends and they are different numbers. The control's step rate is 21 per cent
// BELOW the anchor's; the anchor's is 27 per cent above the control's. The page carried the
// second figure under the first sentence, which is the same base-swap the whole page teaches
// against, so both are pinned here and the printed one has to be the one that is true.
{
  const fa = S.SLATE['walk-vault-0222'].fStep, fc = S.SLATE['walk-vault-0118'].fStep;
  near(100 * (1 - fc / fa), 21.2, 0.2, 'the control\'s step rate is 21 per cent below the anchor\'s');
  near(100 * (fa / fc - 1), 26.9, 0.2, 'and the anchor\'s is 27 per cent above the control\'s');
  ok(instrumentJs.includes('a step rate 21 per cent lower (1.532 Hz against 1.944'),
    'and the slate\'s own printed reason says 21 per cent lower, with both rates beside it');
  ok(!/step rate 27 per cent lower/.test(instrumentJs),
    'not 27 per cent lower, which is the other end of the same ratio');
}
ok(results['walk-vault-0222'].diagnostics.nSteps >= 12, 'the anchor yields at least the 12-step minimum');
ok(results['walk-vault-0118'].diagnostics.nSteps >= 12, 'and so does the asymmetric control');
// 3b. THE SLATE COVERS BOTH PERIODS. A gait repeats at the stride, not necessarily at the
// step, and this page refused every walker whose waveform came back after two steps until
// 2026-08-17. One specimen of each kind, or the fix is untested.
ok(results['walk-vault-0222'].diagnostics.repeatsAt === 'step',
  'the symmetric anchor\'s waveform repeats at one step', results['walk-vault-0222'].diagnostics.repeatsAt);
ok(results['walk-vault-0118'].diagnostics.repeatsAt === 'stride',
  'the asymmetric control\'s repeats at one STRIDE, which is what a real body does',
  results['walk-vault-0118'].diagnostics.repeatsAt);
ok(results['inject-b'].diagnostics.repeatsAt === 'stride',
  'and so does the trace the live-sensor gate injects second, so the browser path runs it too');
inPage('it carries a left-right asymmetry, so its waveform repeats at the stride rather than at the step',
  'and the slate panel tells the reader that one of the two walks is asymmetric');
{
  const rel = (results['walk-vault-0118'].value - S.truthOf('walk-vault-0118')) / S.truthOf('walk-vault-0118');
  ok(readFileSync(join(HERE, 'README.md'), 'utf8').includes('about 1.8 and 3.6 per cent'),
    'the README states the two recovery biases the estimator actually has',
    (100 * rel).toFixed(2) + ' per cent on the control');
  near(100 * rel, -3.6, 0.15, 'and the control\'s is the 3.6 per cent it names');
}
// 3c. THE MID-STANCE SEARCH WINDOW IS A READER-FACING SLIDER. Sweep its whole range on every
// shipped walk: every setting that reports must report the SAME number, to the last bit, or
// the reader is setting their own answer with a control the page hands them.
const WINDOWS = [];
for (let w = 0.20; w <= 0.9001; w += 0.05) WINDOWS.push(Number(w.toFixed(2)));
ok(WINDOWS.length === 15 && WINDOWS[0] === 0.2 && WINDOWS[14] === 0.9,
  'the sweep covers the slider\'s full range in its own 0.05 steps', WINDOWS.join(' '));
for (const key of ['walk-vault-0222', 'walk-vault-0118', 'inject-a', 'inject-b', 'hand-swing']) {
  const vals = new Set();
  for (const w of WINDOWS) { const r = est(key, { dipWindow: w }); if (!r.refused) vals.add(r.value.toFixed(12)); }
  ok(vals.size === 1, 'every window setting from 0.20 to 0.90 returns one identical value on ' + key,
    [...vals].join(' / '));
}
// 3d. THE WHOLE CONTROL PANEL, not just that one slider. The page hands the reader seven
// sliders and re-runs everything on every move. The question this section exists to answer is
// whether any reachable combination makes the slate VACUOUS: a setting where a constant would
// satisfy it, or where arming stops meaning the estimator recovered two different exact
// answers. Sample the seven ranges one at a time, then a deterministic sample of the whole
// grid, and assert at every point that a constant does not pass and that anything that DOES
// arm is within its declared tolerance of both truths.
{
  const ranges = {
    resampleHz: [30, 35, 40, 45, 50, 60, 70, 85, 100],
    dipWindow: [0.2, 0.35, 0.5, 0.6, 0.75, 0.9],
    gravityStrides: [1, 2, 3, 4, 5],
    smoothHalf: [1, 2, 3, 4, 5, 6],
    stepTol: [0.05, 0.15, 0.25, 0.35, 0.5],
    flightG: [0.05, 0.15, 0.25, 0.4, 0.6],
    biasRel: [0, 0.02, 0.04, 0.06],
  };
  const keys = Object.keys(ranges);
  const cases = [];
  for (const k of keys) for (const v of ranges[k]) cases.push({ [k]: v });
  let seed = 12345;
  const rnd = () => { seed = (seed * 1103515245 + 12345) & 0x7fffffff; return seed / 0x7fffffff; };
  for (let i = 0; i < 24; i++) {
    const o = {};
    for (const k of keys) o[k] = ranges[k][Math.floor(rnd() * ranges[k].length)];
    cases.push(o);
  }
  const tA = S.truthOf('walk-vault-0222'), tB = S.truthOf('walk-vault-0118'), TOL = 0.025;
  let nArmed = 0, worst = 0, constantArmed = 0, worstAt = '';
  for (const o of cases) {
    const ra = est('walk-vault-0222', o), rb = est('walk-vault-0118', o);
    const pa = !ra.refused && Math.abs(ra.value - tA) <= TOL;
    const pb = !rb.refused && Math.abs(rb.value - tB) <= TOL;
    if (pa && pb) {
      nArmed++;
      const e = Math.max(Math.abs(ra.value - tA), Math.abs(rb.value - tB));
      if (e > worst) { worst = e; worstAt = JSON.stringify(o); }
    }
    if (Math.abs(0.2221 - tA) <= TOL && Math.abs(0.2221 - tB) <= TOL) constantArmed++;
  }
  ok(cases.length >= 60, 'the slider sweep covers every range one at a time plus a sample of the grid',
    cases.length + ' settings');
  ok(constantArmed === 0,
    'at NO reachable setting of the seven sliders can one constant satisfy both anchors', String(constantArmed));
  ok(nArmed > 0.5 * cases.length, 'most settings still arm, so the page is usable across its own controls',
    nArmed + ' of ' + cases.length);
  ok(worst <= TOL, 'and every setting that arms is inside the declared tolerance on BOTH exact truths',
    worst.toFixed(5) + ' at ' + worstAt);
  inPage('It does not decide: swept from 0.20 to 0.90 on all 328 real walking trials and on every shipped walk, it never once produces two different numbers',
    'and the page says that about the one slider a reader would suspect first');
  inPage('no setting of any of them lets a constant pass the slate',
    'and says the sweep found no setting where a constant arms');
}
// and the reason it is identical: the minimum is genuinely interior, and in the middle.
for (const key of ['walk-vault-0222', 'walk-vault-0118', 'inject-a', 'inject-b']) {
  const p = results[key].diagnostics.midStancePhase;
  ok(Math.abs(p - 0.5) < 0.02, 'mid-stance on ' + key + ' is found within 2 per cent of the middle of the step',
    p.toFixed(4));
}

head('4. the four signals whose correct answer is a refusal');
const REFUSALS = { 'run-flight': 'running', 'fidget-no-gait': 'no-rhythm',
  'still-table': 'no-rhythm', 'walk-slow-stream': 'rate-too-low' };
for (const key of Object.keys(REFUSALS)) {
  const r = est(key);
  ok(r.refused && r.refused.reason === REFUSALS[key],
    key + ' is refused with reason "' + REFUSALS[key] + '"',
    r.refused ? r.refused.reason : 'returned ' + r.value);
  ok(r.refused && typeof r.refused.detail === 'string' && r.refused.detail.length > 40,
    'and the refusal says in plain words what it cannot do');
}

// ═══ 5. the checks can fail ══════════════════════════════════════════════════
head('5. mutation tests: every check on this page is shown going red');
// 5a. the kit's own stub probe, which is what the page shows the reader.
const specimens = [
  { id: 'walk-vault-0222', role: 'anchor', truth: { value: S.truthOf('walk-vault-0222'), tol: 0.025, why: 'exact by construction from the generator' }, load: () => loadTrace(S.pathOf('walk-vault-0222')) },
  { id: 'walk-vault-0118', role: 'control', truth: { value: S.truthOf('walk-vault-0118'), tol: 0.025, why: 'exact by construction from the generator' }, load: () => loadTrace(S.pathOf('walk-vault-0118')) },
];
const real = AW.anchor.instrument({ id: 'v', quantity: 'dip', unit: 'g',
  estimate: (p) => AW.gait.estimate(p), specimens });
await real.runAll();
ok(real.armed(), 'the real estimator arms this slate', real.blockedBecause());
const stub = await AW.anchor.stubProbe(real);
ok(stub.armed === false, 'a constant estimator does NOT arm the same slate');
ok(stub.rows.some((r) => r.role === 'control' && r.pass === false),
  'and it fails specifically on the control, not on the anchor');
ok(stub.rows.some((r) => r.role === 'anchor' && r.pass === true),
  'while sailing through the anchor, which is exactly why one anchor alone proves nothing');

// 5b. an estimator that returns the strongest spectral peak, the other obvious cheat.
const peakInst = AW.anchor.instrument({ id: 'v2', quantity: 'dip', unit: 'g', specimens,
  estimate: (p) => {
    const u = AW.dsp.resampleToUniform(p.times, p.z, 50);
    const d = AW.dsp.dominantFrequency(AW.dsp.detrend(u.samples), 50, { lo: 0.5, hi: 4.5, minProminence: 1 });
    return d.refused ? { refused: d.refused } : { value: d.hz / 10, uncertainty: 0.01 };
  } });
await peakInst.runAll();
ok(peakInst.armed() === false, 'an estimator that reports a scaled spectral peak does not arm either');

// 5b-ii. an estimator that refuses everything passes both halves of the limits panel, so it
// has to be shown failing the slate. The kit counts a refusal on a declared specimen as a
// failure; assert that, rather than assuming it.
const refuseInst = AW.anchor.instrument({ id: 'v3', quantity: 'dip', unit: 'g', specimens,
  estimate: () => ({ refused: { reason: 'always', detail: 'this estimator refuses everything it is ever handed' } }) });
await refuseInst.runAll();
ok(refuseInst.armed() === false, 'an estimator that refuses EVERYTHING does not arm the slate either');

// 5b-iii. THE MUTATION THAT MATTERS MOST: put back the rule this page carried until
// 2026-08-17, which required the waveform to repeat at one STEP, and watch the control go
// red. The mutant is made by patching the page's own source and running it in a fresh
// sandbox, so this is the real code path, not a re-implementation of it.
{
  const live = "const repeatsAt = agreeStep <= o.agreeFrac ? 'step' : (agreeStride <= o.agreeFrac ? 'stride' : null);";
  const old = "const repeatsAt = agreeStep <= o.agreeFrac ? 'step' : null;";
  ok(gaitJs.includes(live), 'gait.js accepts a repeat at one step OR one stride');
  const mutantSrc = gaitJs.replace(live, old);
  ok(mutantSrc !== gaitJs, 'and the step-only mutation of that line is a real change to the file');
  const mbox = { console: { log() {}, warn() {}, error() {} } };
  vm.createContext(mbox); mbox.window = mbox;
  vm.runInContext(readFileSync(join(ROOT, 'public/_kit/dsp.js'), 'utf8'), mbox);
  vm.runInContext(mutantSrc, mbox, { filename: 'gait.js (step-only mutant)' });
  const mut = (key) => mbox.window.AW.gait.estimate(loadTrace(S.pathOf(key)));
  const mc = mut('walk-vault-0118');
  ok(mc.refused && mc.refused.reason === 'no-gait',
    'the step-only rule REFUSES the asymmetric control, which is how this page used to treat real walkers',
    mc.refused ? mc.refused.reason : 'returned ' + mc.value.toFixed(4));
  const ma = mut('walk-vault-0222');
  ok(!ma.refused, 'while still passing the symmetric anchor, which is why the slate never caught it');
  const mi = mut('inject-b');
  ok(mi.refused, 'and it refuses the second live-gate injection too, so the browser gate would go red as well');
}

// 5c. each refusal gate, removed, must turn its refusal into a number. A gate that would
// refuse anyway is decoration and the page's third column would be a lie.
const ALL_OFF = { minProminence: 0, minCorrelation: 0, agreeFrac: 9, stabilityFrac: 9,
  runFrac: 1.01, dMin: 0, dMax: 9, minRateHz: 1, minSteps: 3, maxGapMs: 1e9, minSeconds: 1,
  phaseTol: 9, dipMustBeInterior: false };
// the page's own gates-off object has to be the same set, or its third column is not this one
ok(/phaseTol: 9, dipMustBeInterior: false/.test(instrumentJs),
  'the page\'s "every gate switched off" object turns off the two dip rules as well');
const bare = {};
for (const key of Object.keys(REFUSALS)) {
  const r = est(key, ALL_OFF);
  bare[key] = r;
  ok(!r.refused, 'with every gate off, ' + key + ' returns a number instead of refusing',
    r.refused && r.refused.reason);
}
ok(!bare['fidget-no-gait'].refused && bare['fidget-no-gait'].value > 0.15 && bare['fidget-no-gait'].value < 0.40,
  'and the jiggled phone becomes a perfectly plausible-looking walk, which is the whole point',
  bare['fidget-no-gait'].refused ? 'refused' : bare['fidget-no-gait'].value.toFixed(4));
ok(!bare['run-flight'].refused && bare['run-flight'].value > 1.0,
  'the run becomes a dip above the ceiling at which walking is impossible',
  bare['run-flight'].refused ? 'refused' : bare['run-flight'].value.toFixed(4));
const slowRel = (bare['walk-slow-stream'].value - S.truthOf('walk-slow-stream')) / S.truthOf('walk-slow-stream');
ok(slowRel < -0.04 && slowRel > -0.12,
  'and the 15 Hz stream reads about 7 per cent low against an answer we know exactly, which is what the rate floor prevents',
  (100 * slowRel).toFixed(2) + ' per cent');

// 5c-ii. the two dip rules are not decoration either: with only the RHYTHM gates removed,
// each of the three signals that is not a walk is caught a second time, by the shape of its
// own average step. Turn those two off as well and the numbers come back.
const RHYTHM_OFF = { minProminence: 0, minCorrelation: 0, agreeFrac: 9, stabilityFrac: 9,
  runFrac: 1.01, dMin: 0, dMax: 9, minSteps: 3 };
for (const key of ['fidget-no-gait', 'still-table', 'run-flight']) {
  const r = est(key, RHYTHM_OFF);
  ok(r.refused && (r.refused.reason === 'dip-off-centre' || r.refused.reason === 'dip-at-window-edge'),
    'with the rhythm gates off, ' + key + ' is still refused, on the shape of its average step',
    r.refused ? r.refused.reason : 'returned ' + r.value.toFixed(4));
  const r2 = est(key, Object.assign({}, RHYTHM_OFF, { phaseTol: 9, dipMustBeInterior: false }));
  ok(!r2.refused, 'and turning the two dip rules off as well lets ' + key + ' through with a number',
    r2.refused && r2.refused.reason);
}
// The interior rule exists because a minimum at the window's edge is a number the reader
// sets with a slider. Show the estimator refusing rather than reporting one.
{
  const p = loadTrace(S.pathOf('fidget-no-gait'));
  const off = AW.gait.estimate(p, Object.assign({}, RHYTHM_OFF, { phaseTol: 9, dipMustBeInterior: false }));
  const wide = AW.gait.estimate(p, Object.assign({}, RHYTHM_OFF, { phaseTol: 9, dipMustBeInterior: false, dipWindow: 0.2 }));
  ok(!off.refused && !wide.refused && Math.abs(off.value - wide.value) > 0.02,
    'with those rules off, the jiggled phone\'s answer moves with the window slider between 0.6 and 0.2, which is what they prevent',
    off.refused || wide.refused ? 'refused' : off.value.toFixed(4) + ' vs ' + wide.value.toFixed(4));
}

// 5d. the estimator must not be able to see an answer even when one is bolted to the payload.
const clean = est('walk-vault-0222').value;
const leaky = AW.gait.estimate(Object.assign({}, loadTrace(S.pathOf('walk-vault-0222')), {
  id: 'walk-vault-0118', role: 'control', expected: S.truthOf('walk-vault-0118'),
  truth: { value: S.truthOf('walk-vault-0118'), tol: 0.025 }, isControl: true, isSpecimen: true,
})).value;
ok(clean === leaky, 'attaching the answers to the payload does not move the estimate by one bit',
  clean + ' vs ' + leaky);
// and the same, as a source scan with comments and strings removed.
const codeOnly = gaitJs
  .replace(/\/\*[\s\S]*?\*\//g, ' ').replace(/(^|[^:])\/\/[^\n]*/g, '$1 ')
  .replace(/'(?:[^'\\]|\\.)*'/g, "''").replace(/"(?:[^"\\]|\\.)*"/g, '""');
for (const bad of ['isControl', 'isSpecimen', 'expected', 'truth', '.role', 'specimenId']) {
  ok(!codeOnly.includes(bad), 'gait.js executable code contains no reference to ' + bad);
}

// ═══ 6. Kram, Domingo and Ferris 1997, Table 1 ═══════════════════════════════
head('6. the published table, recomputed from the paper\'s own stated method');
const T = cite.kram1997.table1.rows;
const L = cite.kram1997.legLength.mean, gE = cite.kram1997.gravityConstantUsed.value;
const frAt1g = T[0][3];
ok(T.length === 7, 'the transcribed table has the paper\'s seven gravity levels');
ok(cite.kram1997.subjects.n === 9, 'nine subjects');
near(L, 0.89, 1e-9, 'mean leg length 0.89 m');
near(cite.kram1997.legLength.sd, 0.043, 1e-9, 'with a standard deviation of 0.043 m');
near(gE, 9.81, 1e-9, 'and the paper\'s own 9.81 m/s^2 for normal gravity');
// The predicted-speed column is not a measurement: it is sqrt(Fr(1g) * g * L). All seven.
for (const row of T) {
  const [g, v, , , , pred] = row;
  const recomputed = Math.sqrt(frAt1g * g * gE * L);
  near(recomputed, pred, 0.005,
    'predicted transition speed at ' + g + ' g recomputes to the printed ' + pred + ' m/s');
}
// The Froude column is a mean of per-subject values, so recomputing it from the mean speed and
// the mean leg length agrees closely but not exactly. Assert that, rather than pretending it does.
const recomputedFr = T.map(([g, v]) => v * v / (g * gE * L));
for (let i = 0; i < T.length; i++) {
  ok(Math.abs(recomputedFr[i] - T[i][3]) <= 0.06,
    'Froude at ' + T[i][0] + ' g recomputes to within 0.06 of the printed ' + T[i][3],
    recomputedFr[i].toFixed(4));
}
// AND HERE IS WHY IT IS NOT EXACT, to the last digit. The Froude number is quadratic in
// speed, so the mean of nine subjects' Froude numbers is not the Froude number of their mean
// speed: it carries their variance too. Recover the s.d. from the printed s.e.m. (times the
// square root of nine) and the whole column comes back to 0.006 at every level. The naive
// route misses by ten times that, worst at the low-gravity rows the second layer is built on,
// and the page now says both numbers out loud beside the table.
const sdOf = (sem) => sem * Math.sqrt(cite.kram1997.subjects.n);
const froudeWithVariance = T.map(([g, v, vSem]) => (v * v + sdOf(vSem) * sdOf(vSem)) / (g * gE * L));
let worstNaive = 0, worstVar = 0;
for (let i = 0; i < T.length; i++) {
  worstNaive = Math.max(worstNaive, Math.abs(recomputedFr[i] - T[i][3]));
  worstVar = Math.max(worstVar, Math.abs(froudeWithVariance[i] - T[i][3]));
  ok(Math.abs(froudeWithVariance[i] - T[i][3]) <= 0.006,
    'the printed Froude at ' + T[i][0] + ' g is (mean^2 + s.d.^2)/(gL) to within 0.006',
    froudeWithVariance[i].toFixed(4) + ' vs printed ' + T[i][3]);
}
near(worstVar, 0.006, 0.0015, 'the variance-carrying route\'s worst miss over the whole column is the 0.006 the page prints');
near(worstNaive, 0.052, 0.002, 'and the mean-speed route\'s worst miss is the 0.052 the page prints');
ok(worstNaive > 8 * worstVar, 'the mean-speed route is nearly ten times worse, which is why the page names the difference');
near(recomputedFr[6], 1.078, 0.002, 'at 0.1 g the mean-speed route gives the 1.078 the page quotes against a printed 1.13');
inPage('The Froude column is not the Froude number of those mean speeds',
  'the page says so where the table is printed');
inPage('reproduces all seven\n        printed values to within <strong>0.006</strong>',
  'and prints the number the variance-carrying route achieves');
// The drift the reader is being asked to look at is a drift in FROUDE NUMBER, and the table's
// last column is a drift in SPEED. Printing 11 per cent beside the Froude column would halve
// the thing the page is showing.
near(100 * (T[4][3] / T[0][3] - 1), 24.4, 0.6,
  'the Froude number drifts 24 per cent from 1.0 g to 0.4 g, not the 11 per cent in the speed column');
inPage('a drift of 24 per cent across a 2.5-fold change', 'and the page states that drift where it makes the claim');
inPage('it is a difference in <em>speed</em>', 'and says what the last column of the table actually is');
ok(recomputedFr.slice(0, 5).every((f) => f >= 0.44 && f <= 0.56),
  'from 1.0 g down to 0.4 g the recomputed Froude number stays inside 0.44 to 0.56');
ok(recomputedFr[5] > 0.7 && recomputedFr[6] > 1.0,
  'and at 0.2 g and 0.1 g it breaks out of that band, the second one above the ceiling of 1',
  recomputedFr[5].toFixed(3) + ' and ' + recomputedFr[6].toFixed(3));
// Seven gravity levels, six of them simulated: 1.0 g is the normal-gravity condition the springs
// are not carrying, and the protocol sentence on page 823 says so in as many words ("After
// completing the process at 1.0 g, we repeated the entire procedure at 0.8, 0.6, 0.5, 0.4, 0.2
// and 0.1 g").
const proto = cite.kram1997.protocol;
ok(proto.levels.length === 7 && proto.simulatedLevels.length === 6,
  'the protocol records seven gravity levels of which six are simulated');
ok(proto.levels.every((g, i) => g === T[i][0]), 'and they are the seven rows of Table 1, in order',
  proto.levels.join(' '));
ok(proto.levels[0] === 1.0 && !proto.simulatedLevels.includes(1.0),
  'with normal gravity excluded from the simulated ones');
inPage('at seven gravity levels: normal gravity first, then six simulated ones down to a tenth of normal',
  'and the page counts them that way rather than calling all seven simulated');
ok(!/seven simulated gravity levels/.test(flat) && !/seven\s+simulated\s+gravity\s+levels/.test(md),
  'neither the page nor the .md body calls the normal-gravity condition a simulated one');
// How BIG the constant-Froude band is. This is a ratio of gravity levels and of nothing else in
// the table, and it is the load-bearing number in the "a tautology cannot break" argument, so it
// is pinned here in both directions. The page carried "fourfold" until it was recomputed: no
// quantity in the paper is fourfold (the levels span tenfold, the band 2.5, the transition speed
// over the band 1.42, the Froude number over the whole set 2.5).
const bandLevels = T.slice(0, 5).map((r) => r[0]);
near(bandLevels[0] / bandLevels[4], 2.5, 1e-12,
  'the constant-Froude band runs 1.0 g to 0.4 g, which is a 2.5-fold change in gravity');
near(T[0][0] / T[6][0], 10, 1e-12, 'while the levels tested span a tenfold range, 1.0 g to 0.1 g');
near(T[0][1] / T[4][1], 1.424, 0.002, 'and the transition speed over that band moves only 1.42-fold');
inPage('2.5-fold', 'the page states the band as 2.5-fold');
inPage('The levels tested run a tenfold range', 'and separates the band from the span of the experiment');
const flatMd = md.replace(/\s+/g, ' ');
ok(!/four-?fold/i.test(flat) && !/four-?fold/i.test(flatMd),
  'and neither the page nor the .md body, dek or relates notes calls any of it fourfold');
inPage('change in gravity, 1.0 g down to 0.4 g', 'the rendered sentence names the levels beside the multiple');
ok(flatMd.includes('a 2.5-fold change in gravity'), 'and so does the .md body');
ok(flatMd.includes('the invariance held from 1.0 g down to 0.4 g'),
  'and the relates note to the-exponent-that-bends, which is a shareable surface, names the levels rather than a multiple');
// The percentage column, to within one point (the printed mean speeds are rounded).
for (let i = 1; i < T.length; i++) {
  const [g, v, , , , pred, pct] = T[i];
  const got = 100 * (v - Math.sqrt(frAt1g * g * gE * L)) / Math.sqrt(frAt1g * g * gE * L);
  ok(Math.abs(got - pct) <= 1.05,
    'the difference from prediction at ' + g + ' g recomputes to within one point of the printed ' + pct + ' per cent',
    got.toFixed(2));
}
// The paper's own limb-swing repair.
const lc = cite.kram1997.limbSwingCorrection;
near(0.2 + lc.limbG, lc.effectiveG, 1e-9, 'the limb-swing repair adds 0.16 g to the 0.2 g condition, giving 0.36 g');
near(T[5][1] * T[5][1] / (lc.effectiveG * gE * L), lc.adjustedFroude, 0.005,
  'and the adjusted Froude number at 0.2 g recomputes to the paper\'s 0.44');
ok(Math.abs(T[5][1] * T[5][1] / (lc.effectiveG * gE * L) - frAt1g) < 0.01,
  'which is within 0.01 of the 0.45 measured at normal gravity, as the paper says');
// The page's slider adds ONE constant limb-swing acceleration at every gravity level, which is
// this page's simplification of a calculation the authors did per level and did not tabulate.
// Assert both that it reproduces their one printed value and that the page says it is ours.
const corrected = (limbG) => T.map(([g, v]) => v * v / ((g + limbG) * gE * L));
const at016 = corrected(0.16);
near(at016[5], lc.adjustedFroude, 0.005, 'the slider at 0.16 g reproduces the paper\'s printed 0.44 at the 0.2 g condition');
ok(at016.every((f) => f > 0.35 && f < 0.47),
  'and at that setting the whole curve flattens into a band around 0.4, low-gravity points included',
  at016.map((f) => f.toFixed(2)).join(' '));
const at0 = corrected(0);
for (let i = 0; i < T.length; i++) {
  near(at0[i], recomputedFr[i], 1e-12, 'with the slider at zero, level ' + T[i][0] + ' g is the uncorrected Froude number');
}
ok(at0[6] > 1, 'and the break above the ceiling is back at 0.1 g', at0[6].toFixed(3));
inPage('constant limb-swing acceleration at every level, which is our simplification',
  'the page says the single constant is ours, not the authors\' per-level calculation');
inPage('open symbols in their Fig. 3', 'and names what the authors actually did instead');
// The figure plots the reader's dip on the same axis as Kram's transition Froude numbers, and
// those are Froude numbers on two different lengths. The caption has to name the one line that
// needs the caveat, which is the line the caption used to leave out.
inPage('Green, once you have recorded a walk: your own mid-stance dip',
  'the caption names the reader\'s own line on the reduced-gravity figure');
inPage('every other mark on this figure is a Froude number on trochanter height, so the green line is drawn here for scale and not as a like-for-like comparison',
  'and carries the radius caveat on the mark that needs it');
ok(!/take it up toward 0\.45/.test(flat),
  'and the prose no longer invites the reader to walk their dip up to a number on a different length');

// ═══ 7. Alexander's law, and why no number here comes from cadence ═══════════
head('7. the cadence route, and the reason it is not used');
near(Math.pow(1.05, 5) - 1, 0.2763, 0.001,
  'a 5 per cent cadence error is a 1.05^5 Froude error, which is the 28 per cent the page states');
ok(Math.round(100 * (Math.pow(1.05, 5) - 1)) === 28, 'and it rounds to exactly 28');
ok(!/stepHz[^;]*value/.test(gaitJs.replace(/\s+/g, ' ')),
  'no reported value in gait.js is computed from the step rate');
ok(gaitJs.includes('no number here is derived from cadence'),
  'and gait.js says so where a reader of the code will find it');
// The same square, in the other place it bites. A ratio of Froude numbers is NOT a ratio of
// speeds: 0.45 against a ceiling of 1.0 is sqrt(0.45) = 0.67 of the ceiling SPEED, not 0.45 of
// it and emphatically not "less than half" of it. The page asserted the halving in prose until
// this was recomputed, which was the same dimensionless-versus-absolute conflation it teaches
// against, so both the arithmetic and the wording are pinned here.
const vCeil = Math.sqrt(1.0 * gE * L), vTrans = T[0][1];
near(Math.sqrt(frAt1g), 0.6708, 0.0005, 'sqrt(0.45) is 0.67, so the transition sits at two-thirds of the ceiling speed');
near(vCeil, 2.954, 0.005, 'the ceiling speed on the paper\'s own leg length is sqrt(1.0 g L) = 2.95 m/s');
near(vTrans / vCeil, Math.sqrt(recomputedFr[0]), 1e-12,
  'the measured 1.98 m/s over that ceiling is the square root of the recomputed Froude number, exactly');
near(vTrans / vCeil, Math.sqrt(frAt1g), 0.001,
  'and within a thousandth of sqrt(0.45); the gap is the paper rounding its mean Froude number to two places',
  (vTrans / vCeil).toFixed(6) + ' vs ' + Math.sqrt(frAt1g).toFixed(6));
ok(vTrans / vCeil > 0.6, 'which is not "less than half", the sentence this page used to carry',
  (vTrans / vCeil).toFixed(4));
inPage('√0.45 = 0.67', 'the page prints the square root rather than the ratio of the Froude numbers');
inPage('2.95 m/s', 'and the ceiling speed it belongs to');
inPage('run at about two-thirds of the speed at which walking becomes mechanically impossible',
  'and words the gap as two-thirds');
ok(flatMd.includes('run at about two-thirds of the speed at which walking becomes mechanically impossible'),
  'and the .md body says the same thing');
ok(!/less than half the speed/i.test(flat) && !/less than half the speed/i.test(flatMd),
  'neither surface says "less than half the speed" anywhere');

// ═══ 7b. the other route, and the direction of the ratio ═════════════════════
head('7b. the two routes to a Froude number, and which way up their ratio goes');
// The panel that lets the reader's own dip argue with a tape measure and a stopwatch is the
// page's only bridge between its quantity and Kram's 0.45, and it is one reciprocal away from
// telling every reader the wrong thing about their own body. It shipped inverted until this
// check existed: d/Fr printed under the label R_eff/L.
//
//     d  = v^2/(g R_eff)   ->   Fr / d = R_eff / L
//     Fr = v^2/(g L)            d / Fr = L / R_eff   (the reciprocal)
//
// Construct a body whose vault radius is LONGER than its leg, which is the case the reciprocal
// gets backwards in the interesting direction, and assert the printed function recovers it.
const Rk = 1.20, Lk = 0.90, vk = 1.40;
const dK = vk * vk / (G * Rk), frK = vk * vk / (G * Lk);
near(dK, 0.16653, 0.00005, 'a 1.40 m/s walk on a 1.20 m vault radius has a dip of 0.1665');
near(frK, 0.22207, 0.00005, 'and a textbook Froude number of 0.2221 on a 0.90 m leg');
near(AW.gait.vaultRadiusRatio(dK, frK), Rk / Lk, 1e-12,
  'vaultRadiusRatio recovers R_eff/L = 1.333 from that known radius and leg length');
near(dK / frK, Lk / Rk, 1e-12, 'while d/Fr is the reciprocal, L/R_eff = 0.750');
ok(Math.abs(AW.gait.vaultRadiusRatio(dK, frK) - dK / frK) > 0.5,
  'and the two differ by more than half on this case, so the assertion can actually fail',
  (Rk / Lk).toFixed(3) + ' vs ' + (dK / frK).toFixed(3));
ok(AW.gait.vaultRadiusRatio(dK, frK) > 1 && dK / frK < 1,
  'a vault radius longer than the leg comes back longer, not shorter, which is what the bug did');
for (const [d0, f0] of [[0, 0.2], [0.2, 0], [-0.1, 0.2], [NaN, 0.2]]) {
  ok(Number.isNaN(AW.gait.vaultRadiusRatio(d0, f0)),
    'and it refuses to invent a ratio from a non-positive or unreadable input (' + d0 + ', ' + f0 + ')');
}
ok(instrumentJs.includes('AW.gait.vaultRadiusRatio('),
  'the panel prints that function rather than dividing inline where nothing can test it');
ok(!/readerDip\s*\/\s*fr\b/.test(instrumentJs),
  'and nothing in instrument.js divides the dip by the Froude number');
ok(/'ratio Fr\/d = R_eff\/L: ' \+ fmt\(AW\.gait\.vaultRadiusRatio\(state\.readerDip, fr\), 3\)/.test(instrumentJs),
  'the label the reader sees names the same quantity the function returns');
inPage('Fr/d = R_eff/L', 'the prose states the direction of the ratio');
inPage('which would report a vault radius longer than your leg as one shorter',
  'and warns about the reciprocal in the words of the failure it would cause');

// ═══ 8. the numbers the page prints, matched against the page ════════════════
head('8. every published figure, string-matched against the rendered page');
for (const row of T) {
  const [g, v, vSem, fr, frSem, pred] = row;
  inPage(g.toFixed(1) + ' g', 'the ' + g + ' g row is on the page');
  inPage(v.toFixed(2) + ' ± ' + vSem.toFixed(3) + ' m/s', 'transition speed ' + v + ' with its standard error');
  inPage(fr.toFixed(2) + ' ± ' + frSem.toFixed(2), 'Froude ' + fr + ' with its standard error');
  inPage(pred.toFixed(2) + ' m/s', 'predicted speed ' + pred);
}
inPage('0.89 ± 0.043 m', 'the mean leg length and its spread');
inPage('greater trochanter', 'and how leg length was defined');
inPage('nine subjects', 'the sample size, in words');
inPage('Above a Froude number of 1.0, walking is impossible for this simple inverted-pendulum model.',
  'the ceiling quotation, verbatim');
inPage('The ratio of the centripetal and gravitational forces (mv2/L)/(mg) reduces to the dimensionless Froude number (v2/gL).',
  'the Froude definition quotation, verbatim');
inPage('only predicts the maximum walking speed (Froude number=1.0)', 'the "only predicts" quotation, verbatim');
inPage('we are aware of no satisfactory model that predicts a priori that the transition should occur at a Froude number of 0.5.',
  'the "no satisfactory model" quotation, verbatim');
for (const q of cite.kram1997.quotations) {
  ok(flat.includes(q.text.replace(/\s+/g, ' ')) || q.text.startsWith('In general'),
    'quotation from page ' + q.page + ' is either on the page verbatim or held in citations.json only');
}
// Page numbers are facts about a real document too. The Froude definition the page quotes is
// the Summary's wording, and the Summary is printed on the article's opening page.
const froudeQuote = cite.kram1997.quotations.find((q) => q.text.startsWith('The ratio of the centripetal'));
ok(froudeQuote && froudeQuote.page === 821,
  'citations.json places the quoted Froude definition on page 821, where the Summary is printed',
  froudeQuote && String(froudeQuote.page));
ok(froudeQuote && /page 822 carries a differently worded sentence/i.test(froudeQuote.where || ''),
  'and records the different wording page 822 actually carries, so the two cannot be confused again');
inPage('the definition of the Froude number quoted above is from the Summary, page 821',
  'and the page tells the reader which page that quotation is on');
ok(Number(cite.kram1997.pages.split('-')[0]) === 821, 'which is the article\'s own opening page');
inPage('10.1242/jeb.200.4.821', 'the DOI of the primary source');
inPage('10.1038/261129a0', 'the DOI of the Alexander source');
// The DOI was asserted and the title was not, so the rendered citation drifted from
// citations.json and from Crossref by one inserted article ("Estimates of THE speeds of
// dinosaurs"). A title is a fact about a real paper like any other.
ok(cite.alexander1976.title === 'Estimates of speeds of dinosaurs',
  'citations.json carries the Crossref title for DOI 10.1038/261129a0', cite.alexander1976.title);
inPage('"' + cite.alexander1976.title + '"', 'and the rendered citation is that title, character for character');
ok(!/Estimates of the speeds of dinosaurs/i.test(flat), 'with no inserted article');
inPage(cite.kram1997.title, 'the primary source\'s title is the one in citations.json too');
inPage('821 to 826', 'the page range of the primary source');
// The count behind "approximately 0.5", on a page whose next sentence calls quoting 0.5 as a
// measurement fabricated precision. Five reports, four groups: Alexander appears twice.
const fh = cite.kram1997.froudeApproximatelyHalf;
ok(fh.citedAs.length === fh.reportCount && fh.reportCount === 5,
  'the approximately-0.5 sentence cites five earlier reports', String(fh.citedAs.length));
ok(new Set(fh.citedAs.map((c) => c.split(',')[0].trim())).size === fh.groupCount && fh.groupCount === 4,
  'from four distinct groups, because Alexander appears twice',
  fh.citedAs.join(' | '));
inPage('citing five earlier reports from four other groups', 'and the page counts them that way');
ok(!/citing five other groups/.test(flat), 'and does not call them five groups');
// Local gravity: the deviation from standard gravity either side, and the whole equator-to-pole
// spread, are different numbers and the page had been using the first as the second.
const ng = cite.standardGravity.normalGravityFormula;
near(100 * (ng.pole - ng.equator) / cite.standardGravity.value, 0.53, 0.01,
  'normal gravity spans about half a per cent from equator to pole');
near(100 * (ng.equator - cite.standardGravity.value) / cite.standardGravity.value, -0.27, 0.01,
  'and sits about a quarter of a per cent below standard gravity at the equator');
near(100 * (ng.pole - cite.standardGravity.value) / cite.standardGravity.value, 0.26, 0.01,
  'and about a quarter of a per cent above it at the pole');
near(ng.equator, 9.7803, 0.00005, 'the equator value the page prints is the formula\'s, rounded');
near(ng.pole, 9.8322, 0.00005, 'and so is the polar one');
inPage('9.7803 m/s² at the equator to 9.8322 m/s² at the poles: about a quarter of a per cent either side of the definition, and half a per cent end to end',
  'and the page attaches the right words to each of the two numbers');
ok(!/ranges over about 0\.3 per cent/.test(flat), 'the one-sided deviation is no longer quoted as the whole spread');
// The Table 1 caption mixes an S.E.M. table with an S.D. leg length. Say which is which.
ok(cite.kram1997.legLength.spread === 'S.D.', 'citations.json records the leg-length spread as a standard deviation');
inPage('0.89 ± 0.043 m S.D.', 'and the caption labels it S.D. where it prints it');
inPage('that spread is a standard deviation, not a standard error',
  'and says so in words, because the rest of that caption is standard errors');
inPage('fifth power', 'the fifth-power consequence of the cadence route');
inPage('28 per cent', 'and the 28 per cent it produces');
inPage('0.1 m/s²', 'the browser\'s accelerometer quantisation');
inPage('9.80665', 'standard gravity, stated as a definition');
inPage('0.104', 'the separation between the two anchor truths');
inPage('n = 1', 'the honest sample size of a reader\'s own measurement');
inPage('1.90 Hz', 'the hand-swing specimen\'s frequency');
inPage('35 degrees', 'and its tilt');
inPage('15 readings a second', 'the degraded-stream specimen\'s rate');
near(1 - 1.4 * 1.4 / (G * L), 0.7754, 0.001,
  'the 0.78 of standing weight in the lede is 1 - 1.4^2/(g x 0.89), recomputed');
inPage('0.78 of standing weight', 'and the page states it as 0.78');
inPage('0.89 m mean leg length', 'attributed to the published leg length rather than asserted');

// ═══ 9. the instrument's own declared numbers agree with the generator ═══════
head('9. the page\'s declared truths agree with the generator, to the last digit');
ok(instrumentJs.includes('value: ' + S.truthOf('walk-vault-0222').toFixed(7)),
  'instrument.js declares the anchor truth as ' + S.truthOf('walk-vault-0222').toFixed(7));
ok(instrumentJs.includes('value: ' + S.truthOf('walk-vault-0118').toFixed(7)),
  'and the control truth as ' + S.truthOf('walk-vault-0118').toFixed(7));
ok(instrumentJs.includes('expect: ' + S.truthOf('hand-swing').toFixed(7)),
  'and the hand-swing truth as ' + S.truthOf('hand-swing').toFixed(7));
const kramInJs = instrumentJs.match(/\{ g: ([\d.]+), v: ([\d.]+), vSem: ([\d.]+), fr: ([\d.]+), frSem: ([\d.]+), pred: ([\d.]+)/g) || [];
ok(kramInJs.length === 7, 'instrument.js carries all seven table rows for the live figure', 'found ' + kramInJs.length);
for (let i = 0; i < T.length; i++) {
  const m = kramInJs[i].match(/[\d.]+/g).map(Number);
  ok(m[0] === T[i][0] && m[1] === T[i][1] && m[2] === T[i][2] && m[3] === T[i][3] && m[4] === T[i][4] && m[5] === T[i][5],
    'row ' + T[i][0] + ' g in instrument.js matches citations.json exactly', kramInJs[i]);
}

// ═══ 10. the gate case, and the two injected answers ═════════════════════════
head('10. the live-sensor gate case is real and separable');
ok(gateCase.sensor === 'motion' && gateCase.path === '/strata/' + SLUG + '/', 'the case points at this page');
for (const which of ['anchor', 'control']) {
  const f = join(ROOT, gateCase.inject[which].file);
  ok(existsSync(f), 'the injected ' + which + ' trace exists at ' + gateCase.inject[which].file);
}
near(gateCase.inject.anchor.expect, S.truthOf('inject-a'), 1e-6, 'the injected anchor expectation is the generator truth');
near(gateCase.inject.control.expect, S.truthOf('inject-b'), 1e-6, 'the injected control expectation is the generator truth');
const gap = Math.abs(gateCase.inject.anchor.expect - gateCase.inject.control.expect);
ok(gap > gateCase.inject.anchor.tol + gateCase.inject.control.tol,
  'the two injected answers are further apart than the tolerances can bridge',
  gap.toFixed(4) + ' vs ' + (gateCase.inject.anchor.tol + gateCase.inject.control.tol));
ok(Math.abs(results['inject-a'].value - gateCase.inject.anchor.expect) <= gateCase.inject.anchor.tol,
  'and offline the estimator already lands inside the anchor tolerance');
ok(Math.abs(results['inject-b'].value - gateCase.inject.control.expect) <= gateCase.inject.control.tol,
  'and inside the control tolerance');

// ═══ 11. the shareable surface says only what the page supports ══════════════
head('11. the dek, the plain card, the meta tags and the JSON-LD');
const fm = md.slice(0, md.indexOf('\n---', 4) + 4);
const field = (k) => { const m = fm.match(new RegExp('^' + k + ': "([\\s\\S]*?)"$', 'm')); return m ? m[1] : null; };
const dek = field('dek'), plain = field('plain'), seoTitle = field('seoTitle');
ok(plain !== null && plain.length <= 420, 'the plain card is inside 420 characters', plain && String(plain.length));
ok(plain !== null && (plain.match(/[.!?]/g) || []).length <= 3, 'and inside three sentences');
ok(plain.includes('cannot'), 'and it says what the instrument cannot do, which is the house pattern');
ok(fm.includes('seam: "life"'), 'the seam is the closed-vocabulary "life"');
ok(fm.includes('href: "/strata/' + SLUG + '/"'), 'the href marks it immersive and points here');
ok(seoTitle !== null && seoTitle.length <= 62, 'the seoTitle is short enough for a result page', seoTitle && String(seoTitle.length));
ok(html.includes('<title>' + seoTitle + '</title>'), 'and the page title is the same string');
for (const claim of ['no speed', 'no leg length']) {
  ok(dek.includes(claim) || html.includes(claim), 'the shareable surface carries the "' + claim + '" limit');
}
ok(!dek.includes('confirm') && !dek.includes('proves'), 'the dek claims no confirmation of anything');
ok(!/\b(diagnos|fall risk|patient|clinical norm)/i.test(dek + plain),
  'and neither the dek nor the plain card carries any medical framing');
ok(!/\b(diagnosis|diagnose|diagnostic test|fall risk|patient population norm)/i.test(html),
  'nor does the page');
ok(html.includes('no comparison to any patient') || html.includes('Nothing here is a norm'),
  'the page states the no-health-reading limit explicitly');
const ld = JSON.parse(html.match(/<script type="application\/ld\+json">([\s\S]*?)<\/script>/)[1]);
ok(ld['@type'] === 'Article' && ld.url === 'https://artwaste.land/strata/' + SLUG + '/',
  'the JSON-LD parses and points at the canonical URL');
ok(ld.headline === 'Lightest in the Middle of a Step', 'and its headline is the reader-facing title');
ok(/refuses four signals/.test(ld.description) && /it gets wrong/.test(ld.description),
  'and its description carries the refusals and the wrong answer, not only the good news');
const metaDesc = html.match(/<meta name="description" content="([^"]*)"/)[1];
ok(metaDesc.includes('Froude') && metaDesc.includes('wrong on purpose'),
  'the meta description matches what the page actually does');
// The cards used to state a flat identity ("the deficit IS your Froude number") while the
// body treats the radius it is on as load-bearing ("this page has not measured it on anybody",
// "Kram's 0.45 is a different quantity"). A card is a claim made where the qualifier cannot be
// read, so every card carries the qualifier itself.
const ogDesc = html.match(/<meta property="og:description" content="([^"]*)"/)[1];
const twDesc = html.match(/<meta name="twitter:description" content="([^"]*)"/)[1];
for (const [what, text] of [['meta description', metaDesc], ['og:description', ogDesc],
  ['twitter:description', twDesc], ['the dek', dek], ['the plain card', plain], ['the JSON-LD', ld.description]]) {
  ok(/radius (your|the) (own )?body (actually )?vaults on|effective vault radius|body's effective vault radius|no leg length/.test(text),
    what + ' says which radius the Froude number is on, or that no leg length is in it', text.slice(0, 110));
}
ok(/not on your leg length|rather than on your leg length|not on the leg length/.test(dek + ' ' + ogDesc + ' ' + twDesc),
  'and the cards say out loud that it is not the leg length, which is the quantity Kram\'s 0.45 uses');
ok(/cannot tell a rhythmic swing/.test(twDesc + ' ' + plain),
  'the twitter card and the plain card both ship the failure mode, not only the result');
for (const rel of ['the-jerk-that-skips-your-brain', 'no-absolute-loudness', 'kapitza-pendulum', 'the-exponent-that-bends']) {
  ok(fm.includes('to: ' + rel), 'relates edge to ' + rel + ' is declared');
  ok(existsSync(join(ROOT, 'src/content/strata', rel + '.md')), 'and ' + rel + ' exists in the corpus');
}

// ═══ 12. the page's own structure ════════════════════════════════════════════
head('12. the page closes its tags, makes no third-party request, and runs its own scripts');
ok(/<\/script>\s*<\/body>\s*<\/html>\s*$/.test(html.trimEnd() + '\n') || html.trimEnd().endsWith('</html>'),
  'the document ends with a closed html element');
ok((html.match(/<script/g) || []).length === (html.match(/<\/script>/g) || []).length,
  'every script tag is closed');
ok(html.includes('</body>') && html.includes('</html>'), 'body and html are closed');
const scriptBodies = [...html.matchAll(/<script(?![^>]*src=)([^>]*)>([\s\S]*?)<\/script>/g)];
ok(scriptBodies.length === 1 && /application\/ld\+json/.test(scriptBodies[0][1]),
  'the only inline script is the JSON-LD block, which is parsed as JSON above',
  'found ' + scriptBodies.length);
const srcs = [...html.matchAll(/<script[^>]*src="([^"]+)"/g)].map((m) => m[1]);
// The site's chrome generators (nearby-layers, site-bar, way-out, plain-cards) append their
// own script and style to every shipped page after a build. An assertion that counts ALL
// script tags is therefore testing the generators, not this page, and goes red for a reason
// that has nothing to do with whether the instrument is honest. Count the page's OWN scripts,
// and require that anything else is site chrome rather than a stranger.
const OWN = ['/_kit/dsp.js', '/_kit/anchor.js', '/_kit/sensors.js', './gait.js', './instrument.js'];
const chrome = srcs.filter((x) => !OWN.includes(x));
ok(srcs.filter((x) => OWN.includes(x)).length === OWN.length,
  'the page loads its own five scripts', srcs.join(' '));
ok(chrome.every((x) => /^\/(media|_kit)\//.test(x)),
  'and anything else it loads is the site\'s own chrome, not a third party', chrome.join(' ') || 'none');
for (const s of srcs) ok(!/^https?:/.test(s), 'script src ' + s + ' is same-origin');
for (const f of ['/_kit/dsp.js', '/_kit/anchor.js', '/_kit/sensors.js', './gait.js', './instrument.js']) {
  ok(srcs.includes(f), 'it loads ' + f);
}
// No absolute URL to another origin anywhere in the page's own script content, in any shape.
const foreign = [];
for (const js of [gaitJs, instrumentJs]) {
  for (const m of js.matchAll(/https?:\/\/[^\s'"`)]+/g)) foreign.push(m[0]);
}
ok(foreign.length === 0, 'neither script file contains an absolute URL of any kind', foreign.join(' '));
const linkHrefs = [...html.matchAll(/<link[^>]*href="([^"]+)"/g)].map((m) => m[1]);
for (const h of linkHrefs) {
  ok(!/^https?:/.test(h) || h.startsWith('https://artwaste.land/'),
    'stylesheet or icon ' + h + ' is same-origin');
}
ok(html.includes('/fonts/fonts.css'), 'fonts are self-hosted from /fonts/fonts.css');
// The share card the head, the twitter tags and the JSON-LD all point at has to exist, at the
// size they declare. This page shipped pointing at a 404 until the generator was run.
const ogUrl = html.match(/<meta property="og:image" content="([^"]+)"/)[1];
ok(ogUrl === 'https://artwaste.land/og/' + SLUG + '.png', 'og:image points at this slug\'s card', ogUrl);
const ogFile = join(ROOT, 'public/og', SLUG + '.png');
ok(existsSync(ogFile), 'and that card exists in public/og/, so the share preview is not a 404');
if (existsSync(ogFile)) {
  const png = readFileSync(ogFile);
  ok(png.slice(1, 4).toString('latin1') === 'PNG', 'it really is a PNG');
  const wPx = png.readUInt32BE(16), hPx = png.readUInt32BE(20);
  ok(wPx === 1200 && hPx === 630, 'at the 1200 x 630 the meta tags declare', wPx + ' x ' + hPx);
}
ok(html.includes('"image":"' + ogUrl + '"'), 'and the JSON-LD names the same image as the head');
ok((html.match(new RegExp(ogUrl.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g')) || []).length === 3,
  'og:image, twitter:image and the JSON-LD all name it, and nothing else does');
ok(html.includes('prefers-reduced-motion'), 'reduced motion is honoured');
ok(html.includes('aria-live'), 'the live readout is announced to assistive technology');
ok(html.includes(':focus-visible'), 'focus is visible');
// Every panel that rewrites itself in response to the reader's own input announces that it
// changed; the one thing that must NOT be announced is the once-a-second capture countdown,
// which would read twenty to forty numbers aloud during the window this page has just told the
// reader to walk and not look at the screen.
for (const id of ['kine-out', 'placement-out']) {
  ok(new RegExp('id="' + id + '"[^>]*role="status"[^>]*aria-live="polite"').test(html),
    'the input-driven panel ' + id + ' is a polite live region');
}
for (const id of ['limit-summary', 'slate-verdict', 'stub-verdict']) {
  ok(new RegExp('id="' + id + '"[^>]*role="status"').test(html),
    'the slider-driven panel behind ' + id + ' announces one summary line rather than a whole table');
}
const liveOutStart = html.indexOf('id="live-out"');
const liveOutEnd = html.indexOf('</div>', liveOutStart);
ok(liveOutStart > 0 && !html.slice(liveOutStart, liveOutEnd).includes('id="live-count"'),
  'the ticking countdown sits outside the polite live region');
ok(/id="live-count"[^>]*aria-hidden="true"/.test(html),
  'and is hidden from assistive technology, so only the start and the finished reading are spoken');
for (const id of ['live-out', 'slate-rows', 'limit-rows', 'stub-out', 'fig-step', 'fig-kram',
  'placement-out', 'kine-out', 'choices-echo', 'caps-out', 'swing-number', 'swing-truth']) {
  ok(html.includes('id="' + id + '"'), 'the page has the element instrument.js writes to: ' + id);
}
// The arming gate has to cover EVERYTHING derived from the reader's own signal, not only the
// headline. An earlier build routed the figures and the diagnostics table around inst.armed():
// with the slate disarmed the readout said "No number." while the same screen still showed the
// reader's dip, its interval, their step rate and both figures drawn from it.
const redraw = instrumentJs.slice(instrumentJs.indexOf('function redrawFigures'));
ok(/return state\.lastPayload !== null && inst\.armed\(\)/.test(instrumentJs),
  'readerShowable() is exactly "there is a record AND the slate is armed"');
ok(/showReader \? state\.lastPayload : inst\$\.anchorPayload/.test(redraw),
  'the step figure falls back to the anchor specimen when the slate is not armed');
ok(/readerShowable\(\) \? state\.readerDip : null/.test(redraw),
  'and the reduced-gravity figure draws no reader line when the slate is not armed');
ok(!/ensembleOf\(state\.lastPayload/.test(instrumentJs),
  'nothing calls the estimator on the reader\'s payload around the gate');
const refusalBranch = instrumentJs.slice(instrumentJs.indexOf('if (result.refused) {'),
  instrumentJs.indexOf('const d = result.value'));
for (const [needle, what] of [["tb0.innerHTML = ''", 'the diagnostics table'],
  ['state.readerDip = null', 'the stored dip'],
  ['state.records = {}', 'the accepted records, when the slate itself is what refused']]) {
  ok(refusalBranch.includes(needle), 'a refusal clears ' + what, 'missing: ' + needle);
}
ok(/if \(r\.refused \|\| !r\.diagnostics\) return null/.test(instrumentJs),
  'and a broken estimator empties the figure instead of throwing out of boot()');
// A browser with no accelerometer is an absent instrument, not a failed one, on both paths.
ok((instrumentJs.match(/'no-sensor'/g) || []).length === 2,
  'NotSupportedError is reported as no-sensor by the button and by the gate contract alike',
  'found ' + (instrumentJs.match(/'no-sensor'/g) || []).length);
// The gate contract.
ok(instrumentJs.includes('window.__awAnchor'), 'the page publishes the live-sensor gate contract');
for (const k of ['runSlate', 'stubProbe', 'probeLive']) ok(instrumentJs.includes(k + ':'), 'the contract carries ' + k);
ok((instrumentJs.match(/AW\.sensors\.captureMotion/g) || []).length === 1,
  'there is exactly ONE call to the sensor in the whole page, so probeLive cannot differ from the reader\'s button');
ok(/probeLive[\s\S]{0,240}captureLive/.test(instrumentJs),
  'and probeLive goes through it by the same captureLive the button uses');
const instrCode = instrumentJs.replace(/\/\*[\s\S]*?\*\//g, ' ').replace(/(^|[^:])\/\/[^\n]*/g, '$1 ');
ok((instrCode.match(/captureLive\(/g) || []).length === 3,
  'captureLive is defined once and called from exactly two places: the button and probeLive',
  'found ' + (instrCode.match(/captureLive\(/g) || []).length + ' occurrences in executable code');

// ═══ 13. the verifier's own instructions are real ════════════════════════════
head('13. what the page tells the reader to run');
const cmd = 'node research/' + SLUG + '/verify-' + SLUG + '.mjs';
ok(html.includes(cmd), 'the page prints the command to run this verifier, character for character');
ok(existsSync(join(ROOT, 'research', SLUG, 'verify-' + SLUG + '.mjs')), 'and that file exists');
ok(existsSync(join(HERE, 'make-specimens.mjs')), 'the specimen generator the page names exists');
ok(html.includes('research/' + SLUG + '/make-specimens.mjs'), 'and the page names it by its real path');
ok(existsSync(join(HERE, 'README.md')), 'the research README exists');
ok(statSync(join(PAGE, 'index.html')).size > 20000, 'the page is a full stratum, not a stub');
// The README's specimen table must not confuse the generator's truth with the estimator's
// output on the one signal this page gets wrong; both numbers are real and they are different.
const readme = readFileSync(join(HERE, 'README.md'), 'utf8');
ok(/true vertical swing amplitude 0\.2457456/.test(readme),
  'the README calls 0.2457456 the true vertical swing amplitude, not the estimator\'s answer');
ok(/the estimator returns about 0\.2396/.test(readme), 'and gives the estimator\'s actual answer separately');
near(results['hand-swing'].value, 0.2396, 0.0006,
  'which is what the estimator really returns on the shipped hand-swing specimen');
inPage('against a true swing amplitude of', 'and the page words the same distinction for the reader');

// ═══ 14. the estimator over real human walking ═══════════════════════════════
// The page ships no third-party data, and every specimen on it is synthesised. That is what
// let a defect through: a synthesised walker is left-right symmetric and a real one is not.
// fukuchi-probe.mjs runs THIS estimator over 328 real treadmill trials dressed as phones and
// writes fukuchi-probe.json; every sentence the page says about real walking is checked
// against that file here, and every summary line in the file is recomputed from its own rows,
// so neither the page nor the file can drift on its own.
head('14. the estimator over real force-plate walking, and every number the page states about it');
const probePath = join(HERE, 'fukuchi-probe.json');
ok(existsSync(probePath), 'the real-walking probe result file is committed beside this verifier');
ok(existsSync(join(HERE, 'fukuchi-probe.mjs')), 'and so is the script that produced it');
ok(existsSync(join(HERE, 'fukuchi-trials.json')), 'and the trial metadata it reads');
ok(existsSync(join(HERE, 'fukuchi-fetch.py')), 'and the script that pulls the traces out of the archive');
{
  const zd = JSON.parse(readFileSync(join(HERE, 'fukuchi-zipdir.json'), 'utf8'));
  ok(zd.members.length === 328 && zd.members.every((m) => /^WBDS\d+walkT\d+grf\.txt$/.test(m.name)),
    'the committed zip directory names all 328 treadmill force files and nothing else',
    String(zd.members.length));
  ok(zd.members.every((m) => typeof m.lho === 'number' && typeof m.csz === 'number' && typeof m.usz === 'number'),
    'with the offsets a range request needs, and no file content');
  const meta = JSON.parse(readFileSync(join(HERE, 'fukuchi-trials.json'), 'utf8'));
  const named = new Set(meta.trials.map((t) => t.name));
  ok(zd.members.every((m) => named.has(m.name)),
    'every member it names is a trial the metadata describes, so the probe can be re-run end to end');
}
const probe = JSON.parse(readFileSync(probePath, 'utf8'));
// A RECORDING OF A DIFFERENT ESTIMATOR WOULD BE A LIE ABOUT THIS ONE. The file carries the
// sha256 of gait.js with its comments stripped, so any change to the executable estimator
// turns this red until the probe is re-run. Comments are excluded on purpose: gait.js quotes
// these results in its own header. If this fails, re-run fukuchi-probe.mjs over the dataset
// (fukuchi-fetch.py pulls the 328 members out of the archive by HTTP range request) and
// update the sentences on the page that quote it.
ok(probe.estimatorCodeSha === estimatorCodeSha(ROOT),
  'the recorded run was made by the estimator that ships today',
  'file ' + String(probe.estimatorCodeSha).slice(0, 12) + ', gait.js ' + estimatorCodeSha(ROOT).slice(0, 12));
ok(probe.rows.length === probe.trials && probe.trials >= 300,
  'the probe covers all ' + probe.trials + ' treadmill walking trials in the dataset', String(probe.rows.length));
const accP = probe.rows.filter((r) => r.refused === null);
ok(accP.length === probe.accepted, 'its accepted count is what its own rows say', accP.length + ' vs ' + probe.accepted);
const strideP = accP.filter((r) => r.repeatsAt === 'stride').length;
ok(strideP === probe.repeatsAtStride, 'and so is its stride count', strideP + ' vs ' + probe.repeatsAtStride);
ok(strideP > 0.2 * accP.length,
  'a large share of real walking repeats at the stride rather than the step, which is the whole point',
  strideP + ' of ' + accP.length);
const ordinaryP = probe.rows.filter((r) => r.v >= 1.0);
const ordinaryAcc = ordinaryP.filter((r) => r.refused === null).length;
ok(ordinaryP.length === probe.ordinaryOrFaster.trials && ordinaryAcc === probe.ordinaryOrFaster.accepted,
  'the ordinary-speed tally is what the rows say', ordinaryAcc + '/' + ordinaryP.length);
ok(ordinaryAcc >= 0.95 * ordinaryP.length,
  'the estimator now accepts at least 95 per cent of trials at 1.0 m/s or faster',
  ordinaryAcc + ' of ' + ordinaryP.length);
// THE VACUITY TEST ON REAL SIGNALS. The page hands the reader a slider that sets where
// mid-stance is looked for. On no real trial does moving it produce a second answer.
ok(probe.rows.every((r) => r.windowValues <= 1),
  'no real trial returns two different numbers across the slider\'s whole 0.20 to 0.90 range',
  probe.rows.filter((r) => r.windowValues > 1).length + ' trials do');
ok(probe.rows.some((r) => r.windowRefusals > 0),
  'while some settings do refuse, which is the alternative to reporting a window-set number');
// The rule this page carried until 2026-08-17 refused every stride-repeating record. Its
// refusal count follows from the same rows: everything refused now, plus everything accepted
// now whose waveform repeats at the stride.
const oldRuleRefused = probe.refused + strideP;
ok(oldRuleRefused > 0.4 * probe.trials,
  'the step-only rule this page used to carry refused ' + oldRuleRefused + ' of ' + probe.trials + ' real trials',
  (100 * oldRuleRefused / probe.trials).toFixed(0) + ' per cent');
inPage('it refuses <strong>' + oldRuleRefused + ' of the\n        ' + probe.trials + '</strong>',
  'and the page prints that number, as what today\'s estimator does with the old rule put back');
ok(!/that rule refused <strong>/.test(html),
  'and does not claim the count was measured on the code as it stood, which is a different number');
inPage('<strong>' + ordinaryAcc + ' of the ' + ordinaryP.length + ' trials at 1.0 m/s or faster</strong>',
  'and the number it accepts now');
inPage(probe.trials + ' real treadmill walking trials', 'and how many real trials it was run over');
// Every refusal that remains is a slow walk; if that ever stops being true the page's account
// of its own limits is wrong.
const fastRefusals = probe.rows.filter((r) => r.refused && r.v >= 1.0).length;
ok(fastRefusals <= 0.05 * ordinaryP.length,
  'almost every remaining refusal is a walk slower than 1 m/s',
  fastRefusals + ' refusals at 1.0 m/s or faster');
// And the one number this gives the page that it could not get any other way: the ratio
// between the dip and the textbook Froude number, on real bodies rather than on the reader.
const reffTrials = accP.filter((r) => r.Fr >= 0.10);
ok(reffTrials.length === probe.reffOverLTrials, 'the R_eff/L tally is what the rows say');
const medReff = AW.gait.median(reffTrials.map((r) => r.ReffOverL));
near(medReff, probe.medianReffOverL, 0.0001, 'and its median is what the file says');
// 28 of the 328 trials are flagged in the metadata as having been walked with a hand on the
// treadmill rail, which bleeds weight out of the force trace. Rather than argue about whether
// to drop them, measure what they do: the median moves by less than 0.01 either way.
{
  const noHands = reffTrials.filter((r) => r.hands === 'No').map((r) => r.ReffOverL);
  const hands = reffTrials.filter((r) => r.hands === 'Yes').map((r) => r.ReffOverL);
  ok(hands.length > 0, 'the probe records which trials were walked holding the handrail', String(hands.length));
  ok(Math.abs(AW.gait.median(noHands) - medReff) <= 0.02,
    'and dropping them moves the reported median by less than 0.02, so the flag is recorded and not load-bearing',
    AW.gait.median(noHands).toFixed(4) + ' without them vs ' + medReff.toFixed(4) + ' with');
}
ok(medReff > 0.6 && medReff < 1.1,
  'the effective vault radius comes out under a leg length on real walkers, as the page says it might',
  medReff.toFixed(3));
inPage('median <strong>' + probe.medianReffOverL.toFixed(2) + '</strong>',
  'and the page states that median where it discusses the two routes');
ok(probe.licence === 'CC BY 4.0' && /figshare/.test(probe.dataset),
  'the probe records the dataset it read and its licence');
ok(!existsSync(join(PAGE, 'specimens', 'fukuchi.json')),
  'and no trace from that dataset is redistributed on this page');
inPage('Fukuchi', 'the page cites the dataset it made those statements from');

// ── the score ────────────────────────────────────────────────────────────────
// The page prints this verifier's total in its own footer. Asserting it here is what stops
// that number drifting the moment a check is added: this is the last check, so the total it
// compares against is pass + fail + itself.
const claim = html.match(/id="score-claim">(\d+)\/(\d+) checks</);
ok(claim !== null && claim[1] === claim[2] && Number(claim[1]) === pass + fail + 1,
  'the count the page prints is this verifier\'s own total, ' + (pass + fail + 1),
  claim ? 'page says ' + claim[1] + '/' + claim[2] : 'no score claim found in the page');
console.log('\n' + (fail ? 'FAILURES:\n  ' + failures.join('\n  ') + '\n' : ''));
console.log(`${pass + fail} checks, ${fail} failures`);
process.exit(fail ? 1 : 0);
