#!/usr/bin/env node
// verify-ppg-pulse.mjs: recompute every number /strata/ppg-pulse/ prints, then try to break it.
//
//   node research/ppg-pulse/verify-ppg-pulse.mjs
//
// It reads public/, never the built output, and it runs the page's OWN modules: dsp.js, wfdb.js and
// ppg.js are executed in a vm sandbox exactly as the browser loads them, so there is no
// second implementation here that could be right while the shipped one is wrong. The declared
// truths and tolerances are parsed out of the shipped instrument.js rather than restated, so
// a tolerance widened on the page turns this red.
//
// Roughly half of what follows is negative on purpose. A verifier that only watches the
// estimator agree with itself proves nothing, so this one replaces the estimator with a
// constant, disables the half-harmonic test, removes the repeat gate, feeds the refusal paths
// signals built to trigger them, and requires each of those to fail in the specific place it
// is supposed to fail.
import { readFileSync, existsSync } from 'node:fs';
import { join, dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { createHash } from 'node:crypto';
import vm from 'node:vm';
import { build } from './make-specimens.mjs';

const HERE = dirname(fileURLToPath(import.meta.url));
const ROOT = resolve(HERE, '../..');
const PAGE = join(ROOT, 'public/strata/ppg-pulse');
const SPEC = join(PAGE, 'specimens');
const SLUG = 'ppg-pulse';

let pass = 0, fail = 0;
const ok = (cond, msg, detail) => {
  if (cond) { pass++; console.log('  ok    ' + msg); }
  else { fail++; console.log('  FAIL  ' + msg + (detail === undefined ? '' : '  [' + detail + ']')); }
};
const near = (a, b, tol, msg) => ok(Math.abs(a - b) <= tol, msg, 'got ' + a + ', want ' + b + ' +- ' + tol);
const section = (s) => console.log('\n' + s);

// ── the shipped modules, exactly as the browser loads them ───────────────────
const sandbox = { window: {}, console, performance };
vm.createContext(sandbox);
for (const f of ['public/_kit/dsp.js', 'public/_kit/anchor.js', 'public/strata/ppg-pulse/wfdb.js', 'public/strata/ppg-pulse/ppg.js']) {
  vm.runInContext(readFileSync(join(ROOT, f), 'utf8'), sandbox, { filename: f });
}
const AW = sandbox.window.AW;
const P = AW.ppg, W = AW.wfdb, ANCHOR = AW.anchor;

const html = readFileSync(join(PAGE, 'index.html'), 'utf8');
const instrumentJs = readFileSync(join(PAGE, 'instrument.js'), 'utf8');
const md = readFileSync(join(ROOT, 'src/content/strata', SLUG + '.md'), 'utf8');
const caseJson = JSON.parse(readFileSync(join(ROOT, 'research/anchor-wave/cases', SLUG + '.json'), 'utf8'));
const specs = JSON.parse(readFileSync(join(SPEC, 'synth-specs.json'), 'utf8'));
const bundleMeta = JSON.parse(readFileSync(join(SPEC, 'butppg-sample.json'), 'utf8'));
const bundleBin = new Uint8Array(readFileSync(join(SPEC, 'butppg-sample.bin')));

// Where each recording was taken and what its subject was doing, from the dataset's own
// subject file, which this page ships beside the annotation file. Site is 0 ear / 1 finger,
// motion is 0 rest and 1 to 7 an artefact the authors induced deliberately.
const subjectInfo = (() => {
  const raw = readFileSync(join(SPEC, 'subject-info.csv'), 'utf8').replace(/^﻿/, '');
  const lines = raw.split(/\r?\n/).filter((l) => l.trim());
  const head = lines[0].split(',').map((x) => x.trim());
  const iSite = head.indexOf('Ear/finger'), iMot = head.indexOf('Motion');
  const site = {}, motion = {};
  for (const l of lines.slice(1)) {
    const p = l.split(',');
    site[p[0].trim()] = p[iSite].trim();
    motion[p[0].trim()] = p[iMot].trim();
  }
  return { head, site, motion, rows: lines.length - 1 };
})();

const record = (id) => W.payload(W.decode(readFileSync(join(SPEC, id + '_PPG.hea'), 'utf8'), new Uint8Array(readFileSync(join(SPEC, id + '_PPG.dat')))));
const synth = (id) => { const f = P.synthFrames(specs.specimens[id].frames); return P.assemble(f.times, f.rows); };
const has = (needle, what) => ok(html.includes(needle), (what || 'the page prints') + ' "' + needle + '"');

// ══════════════════════════════════════════════════════════════════════════════
section('1. the specimens regenerate, byte for byte');
{
  const want = JSON.parse(readFileSync(join(HERE, 'hashes.json'), 'utf8'));
  const built = build(SPEC, join(HERE, 'gate'));
  for (const k of Object.keys(want.synth)) {
    ok(JSON.stringify(want.synth[k]) === JSON.stringify(built.synth[k]),
      'synthesised specimen ' + k + ' regenerates to the recorded digest');
  }
  for (const k of Object.keys(want.y4m)) {
    ok(want.y4m[k].sha256 === built.y4m[k].sha256, 'injected video ' + k + ' regenerates to the recorded sha256');
  }
  let n = 0;
  for (const k of Object.keys(want.downloaded)) {
    const p = join(SPEC, k);
    ok(existsSync(p) && createHash('sha256').update(readFileSync(p)).digest('hex') === want.downloaded[k],
      'downloaded file ' + k + ' still hashes to what was recorded');
    n++;
  }
  ok(n >= 11, 'every downloaded file is covered by a hash (' + n + ')');
}

// ══════════════════════════════════════════════════════════════════════════════
section('2. the declared slate, read out of the shipped page');
// Parse the truths from instrument.js so a number edited there, and nowhere else, turns this red.
function declaredSpecimens() {
  const out = [];
  const re = /id:\s*'([\w-]+)',\s*role:\s*'(anchor|control)'[\s\S]{0,400}?value:\s*([\d.]+),\s*tol:\s*([\d.]+)/g;
  let m;
  while ((m = re.exec(instrumentJs))) out.push({ id: m[1], role: m[2], value: Number(m[3]), tol: Number(m[4]) });
  return out;
}
const declared = declaredSpecimens();
ok(declared.length === 3, 'three specimens are declared on the page', JSON.stringify(declared));
{
  const byId = Object.fromEntries(declared.map((d) => [d.id, d]));
  ok(byId['butppg-133007'] && byId['butppg-133007'].role === 'anchor' && byId['butppg-133007'].value === 54,
    'the anchor is Brno 133007 at 54 bpm');
  ok(byId['butppg-140067'] && byId['butppg-140067'].role === 'control' && byId['butppg-140067'].value === 82,
    'the control is Brno 140067 at 82 bpm');
  ok(byId['synth-trap'] && byId['synth-trap'].role === 'control' && byId['synth-trap'].value === 72,
    'the second control is the synthesised trap at 72 bpm');

  // The separation rule, applied here rather than trusted: no single constant may satisfy an
  // anchor and a control at once.
  for (const a of declared.filter((d) => d.role === 'anchor')) {
    for (const c of declared.filter((d) => d.role === 'control')) {
      ok(Math.abs(a.value - c.value) > a.tol + c.tol,
        'anchor ' + a.id + ' and control ' + c.id + ' are separable (' + Math.abs(a.value - c.value) + ' > ' + (a.tol + c.tol) + ')');
    }
  }

  // And the published references really are what the shipped annotation file says.
  const csv = readFileSync(join(SPEC, 'quality-hr-ann.csv'), 'utf8').replace(/^﻿/, '');
  const rows = csv.split(/\r?\n/).filter((l) => l.trim()).slice(1).map((l) => l.split(','));
  const ann = Object.fromEntries(rows.map((r) => [r[0].trim(), { q: Number(r[1]), hr: Number(r[2]) }]));
  ok(ann['133007'] && ann['133007'].hr === 54 && ann['133007'].q === 1,
    'the annotation file gives 133007 a reference of 54 bpm and quality 1');
  ok(ann['140067'] && ann['140067'].hr === 82 && ann['140067'].q === 1,
    'the annotation file gives 140067 a reference of 82 bpm and quality 1');
  ok(ann['130078'] && ann['130078'].q === 0,
    'the annotation file gives the refusal specimen 130078 quality 0, so somebody other than us called it unusable');
}

// ══════════════════════════════════════════════════════════════════════════════
section('3. the estimator recovers each declared answer');
const anchorEst = P.estimate(record('133007'));
const controlEst = P.estimate(record('140067'));
const trapAsm = synth('synth-trap');
const trapEst = P.estimate(trapAsm.payload);
{
  ok(!anchorEst.refused, 'the anchor is not refused');
  near(anchorEst.value, 54.70, 0.02, 'anchor 133007 measures 54.70 bpm');
  ok(Math.abs(anchorEst.value - 54) <= 3.0, 'and that is inside the declared tolerance of 3.0');
  ok(anchorEst.uncertainty <= 3.0, 'its own interval (' + anchorEst.uncertainty.toFixed(2) + ') is no wider than the tolerance');
  near(controlEst.value, 82.90, 0.02, 'control 140067 measures 82.90 bpm');
  ok(Math.abs(controlEst.value - 82) <= 3.0, 'and that is inside the declared tolerance of 3.0');
  near(trapEst.value, 72.006, 0.01, 'the trap measures 72.006 bpm');

  // per-channel figures the page tabulates for the anchor
  const ch = Object.fromEntries(anchorEst.diagnostics.channels.map((c) => [c.name, c]));
  near(ch.R.dc, 238.19, 0.02, 'anchor red channel sits at DC 238.19 of 255');
  near(ch.G.dc, 52.86, 0.02, 'anchor green channel at DC 52.86');
  near(ch.B.dc, 35.18, 0.02, 'anchor blue channel at DC 35.18');
  near(ch.R.modPercent, 0.040, 0.002, 'anchor red fractional pulse 0.040 per cent');
  near(ch.G.modPercent, 0.178, 0.002, 'anchor green fractional pulse 0.178 per cent');
  near(ch.B.modPercent, 0.267, 0.002, 'anchor blue fractional pulse 0.267 per cent');
  ok(ch.R.modPercent < ch.G.modPercent && ch.R.modPercent < ch.B.modPercent,
    'red carries the smallest fractional pulse and the largest level, which is the page\'s claim about contact geometry');
}

// ══════════════════════════════════════════════════════════════════════════════
section('4. the harmonic trap, and the naive estimator failing it');
{
  const naive = P.naiveEstimate(trapAsm.payload);
  near(naive.value, 144.001, 0.01, 'an argmax of the spectrum reports 144.001 bpm for this specimen');
  ok(Math.abs(naive.value - 2 * 72) < 0.5, 'which is twice the true rate, to within half a bpm');
  ok(Math.abs(naive.value - 72) > 1.5, 'and is far outside the tolerance the page declares for it');
  const hs = specs.specimens['synth-trap'].frames.harmonics;
  ok(hs[1].amp > hs[0].amp, 'the generator really was given a larger second harmonic than fundamental');
  near(hs[1].amp / hs[0].amp, 1.67, 0.01, 'the ratio the page prints, 1.67, is the generator\'s own');
  const d = trapEst.diagnostics.channels[0];
  near(d.subRatio, 0.539, 0.005, 'the half-rate line stands at 0.539 of the peak');
  ok(d.subRatio >= P.CFG.subharmonicRatio, 'above the ' + P.CFG.subharmonicRatio + ' the test requires');
  near(d.alternation, 0.317, 0.005, 'the peak heights alternate by 0.317');
  ok(d.alternation >= P.CFG.subharmonicAlternation, 'above the ' + P.CFG.subharmonicAlternation + ' the test requires');
  ok(trapEst.diagnostics.halved === true, 'and the fundamental test actually fired on this specimen');

  // NEGATIVE: disable the half-harmonic test and the trap must be reported at twice the rate.
  const blunt = Object.assign({}, P.CFG, { subharmonicRatio: 9e9 });
  const per = trapAsm.payload.channels.map((c) => P.channelRate(trapAsm.payload.times, c.values, blunt));
  ok(per.every((r) => !r.refused && Math.abs(r.bpm - 144.001) < 0.5),
    'NEGATIVE: with the half-harmonic test switched off, every channel reports 144 bpm');
}

// ══════════════════════════════════════════════════════════════════════════════
section('5. the free choice that moves the answer');
{
  const pl = record('133007');
  const out = {};
  for (const padding of ['reflect', 'zero']) {
    const cfg = Object.assign({}, P.CFG, { detrendPadding: padding });
    out[padding] = pl.channels.map((c) => P.channelRate(pl.times, c.values, cfg).bpm);
  }
  near(out.reflect[0], 54.75, 0.02, 'reflect padding, red: 54.75 bpm');
  near(out.reflect[1], 54.72, 0.02, 'reflect padding, green: 54.72 bpm');
  near(out.reflect[2], 54.70, 0.02, 'reflect padding, blue: 54.70 bpm');
  near(out.zero[0], 41.08, 0.02, 'zero padding, red: 41.08 bpm');
  near(out.zero[1], 48.60, 0.02, 'zero padding, green: 48.60 bpm');
  near(out.zero[2], 48.95, 0.02, 'zero padding, blue: 48.95 bpm');
  const worst = Math.max.apply(null, out.reflect.map((v, i) => Math.abs(v - out.zero[i])));
  near(worst, 13.7, 0.05, 'the worst swing between the two conventions is 13.7 bpm');
  ok(P.CFG.detrendPadding === 'reflect', 'and the shipped default is the reflect convention');
}

// ══════════════════════════════════════════════════════════════════════════════
section('6. the refusal paths, which is where a measurement page lies');
{
  const r1 = P.estimate(record('130078'));
  ok(r1.refused && !('value' in r1), 'quality-0 record 130078 returns NO value at all, not a hidden one');
  ok(r1.refused.reason === 'peak-at-band-edge', 'and names its reason: ' + r1.refused.reason);
  const stillAsm = synth('synth-still');
  const r2 = P.estimate(stillAsm.payload);
  ok(r2.refused && !('value' in r2), 'still, dark frames return NO value');
  ok(r2.refused.reason === 'gate-failed', 'and name which gates failed');

  // Signals built to hit each refusal branch in turn.
  const flat = { times: Array.from({ length: 300 }, (_, i) => i / 30), channels: ['R', 'G', 'B'].map((n) => ({ name: n, values: new Float64Array(300).fill(100) })) };
  const rf = P.estimate(flat);
  ok(rf.refused && !('value' in rf), 'an identically flat record is refused');
  const slow = { times: Array.from({ length: 120 }, (_, i) => i / 10), channels: flat.channels };
  ok(P.estimate(slow).refused.reason === 'frame-rate-too-low', 'a 10 fps record is refused for frame rate');
  const short = { times: Array.from({ length: 60 }, (_, i) => i / 30), channels: flat.channels };
  ok(P.estimate(short).refused.reason === 'record-too-short', 'a 2 s record is refused for length');
  const oneCh = { times: flat.times, channels: [flat.channels[0]] };
  ok(P.estimate(oneCh).refused.reason === 'too-few-channels', 'a single-channel record is refused: the cross-channel gate cannot run');
  ok(P.estimate({ times: [], channels: [] }).refused.reason === 'no-signal', 'an empty record is refused');

  // NEGATIVE: without the repeat gate, a record the page refuses comes back with a number.
  const held = bundleMeta.records.find((r) => r.id === '148023');
  if (held) {
    const pay = W.fromBundle(held, bundleBin);
    const loose = Object.assign({}, P.CFG, { repeatMin: -1 });
    const perLoose = pay.channels.map((c) => P.channelRate(pay.times, c.values, loose));
    ok(perLoose.every((r) => !r.refused), 'NEGATIVE: record 148023 does produce a rate when the gates are loosened');
  }
}

// ══════════════════════════════════════════════════════════════════════════════
section('7. the control on the control: a constant must not arm');
{
  const mk = (estimate) => ANCHOR.instrument({
    id: 'ppg-verify', quantity: 'pulse rate', unit: 'bpm', estimate,
    specimens: [
      { id: 'a', role: 'anchor', truth: { value: 54, tol: 3.0, why: 'as declared on the shipped page' }, load: () => record('133007') },
      { id: 'b', role: 'control', truth: { value: 82, tol: 3.0, why: 'as declared on the shipped page' }, load: () => record('140067') },
      { id: 'c', role: 'control', truth: { value: 72, tol: 1.5, why: 'as declared on the shipped page' }, load: () => trapAsm.payload },
    ],
  });
  const real = mk(P.estimate);
  await real.runAll();
  ok(real.armed(), 'the real estimator arms this slate');

  for (const [name, k] of [['the anchor\'s 54', 54], ['the control\'s 82', 82], ['the mean of the three', (54 + 82 + 72) / 3]]) {
    const stub = mk(() => ({ value: k, uncertainty: 0.1 }));
    await stub.runAll();
    ok(!stub.armed(), 'NEGATIVE: a constant estimator returning ' + name + ' does not arm');
  }
  const probe = await ANCHOR.stubProbe(real);
  ok(probe.armed === false, 'the page\'s own stub probe does not arm');
  ok(probe.rows.some((r) => r.role === 'control' && r.pass === false), 'and it fails on a control specifically');
  ok(probe.rows.some((r) => r.role === 'anchor' && r.pass === true), 'while sailing through the anchor, which is the whole point');
}

// ══════════════════════════════════════════════════════════════════════════════
section('8. the held-out sweep, recomputed');
let sweep;
{
  const rows = bundleMeta.records.filter((r) => r.split === 'held').map((rec) => {
    const e = P.estimate(W.fromBundle(rec, bundleBin));
    return { rec, e, err: e.refused ? null : e.value - rec.hrRef };
  });
  const acc = rows.filter((r) => !r.e.refused);
  const good = acc.filter((r) => Math.abs(r.err) <= 5);
  const bad = acc.filter((r) => Math.abs(r.err) > 5);
  const q1acc = acc.filter((r) => r.rec.quality === 1);
  const q1ref = rows.filter((r) => r.e.refused && r.rec.quality === 1);
  sweep = { n: rows.length, accept: acc.length, refuse: rows.length - acc.length, good: good.length, bad: bad.length, q1ref: q1ref.length };

  ok(rows.length === 100, 'the held-out split holds 100 records');
  ok(acc.length === 15, 'the gate accepts 15 of them', String(acc.length));
  ok(rows.length - acc.length === 85, 'and refuses 85');
  ok(good.length === 13, '13 of the accepted are within 5 bpm of the electrocardiogram reference');
  ok(bad.length === 2, 'and 2 are not');
  ok(q1ref.length === 24, 'it also refuses 24 records the annotators called usable');
  ok(q1acc.every((r) => Math.abs(r.err) <= 2.2001),
    'every accepted record the annotators also called usable is within 2.2 bpm',
    q1acc.map((r) => r.rec.id + ':' + r.err.toFixed(1)).join(' '));
  ok(bad.every((r) => r.rec.quality === 0), 'both wrong answers are on records the annotators called unusable');
  const ids = bad.map((r) => r.rec.id).sort().join(',');
  ok(ids === '148023,149040', 'the two are 148023 and 149040', ids);

  // Stratified, because the headline hides two things the page now says out loud: the gate is
  // partly declining a measurement SITE nobody reading this will use, and the 57.8 bpm miss is
  // a record made while its subject was walking, which is a condition the reader can see.
  const at = (r) => ({ site: subjectInfo.site[r.rec.id], motion: subjectInfo.motion[r.rec.id] });
  const ear = rows.filter((r) => at(r).site === '0');
  const earAcc = ear.filter((r) => !r.e.refused);
  const artefact = rows.filter((r) => at(r).motion !== '0');
  const fr = rows.filter((r) => at(r).site === '1' && at(r).motion === '0');
  const frAcc = fr.filter((r) => !r.e.refused);
  const frGood = frAcc.filter((r) => Math.abs(r.err) <= 5);
  const frWorst = Math.max.apply(null, frAcc.map((r) => Math.abs(r.err)));
  ok(ear.length === 9, '9 of the held-out hundred are ear recordings', String(ear.length));
  ok(earAcc.length === 0, 'and the gate accepted none of them', String(earAcc.length));
  ok(artefact.length === 24, '24 of the hundred were made under an induced artefact', String(artefact.length));
  ok(fr.length === 69, '69 are a finger at rest', String(fr.length));
  ok(frAcc.length === 14 && frGood.length === 13,
    'of which the gate accepted 14 and 13 were within 5 bpm', frAcc.length + '/' + frGood.length);
  near(frWorst, 5.9, 0.05, 'and the worst miss among those is 5.9 bpm, not 57.8');
  const walker = bad.find((r) => r.rec.id === '148023');
  ok(subjectInfo.motion[walker.rec.id] === '3',
    'the 57.8 bpm miss, 148023, carries motion code 3, which the dataset defines as walking',
    subjectInfo.motion[walker.rec.id]);
  ok(rows.some((r) => r.rec.id === '133007' && !r.e.refused),
    'and the page\'s own anchor 133007 is one of the accepted held-out records, which the page now says');
  const woAnchor = acc.filter((r) => r.rec.id !== '133007');
  ok(woAnchor.length === 14 && woAnchor.filter((r) => Math.abs(r.err) <= 5).length === 12,
    'without it the headline is 14 accepted and 12 good, which is the figure the page prints beside it');

  // the stratified figures, as the page prints them in prose
  ok(fr.length - frAcc.length === 55 && (fr.length - frAcc.length) > (rows.length - acc.length) / 2,
    'and it refuses 55 finger-at-rest records, which is most of the 85 refusals: the refusals are NOT mostly ears and walking',
    String(fr.length - frAcc.length));
  const sfigs = { 'fig-held-ear': ear.length, 'fig-held-earaccept': earAcc.length,
    'fig-held-artefact': artefact.length, 'fig-held-fr': fr.length,
    'fig-held-fracc': frAcc.length, 'fig-held-frgood': frGood.length,
    'fig-held-frrefused': fr.length - frAcc.length };
  for (const [k, want] of Object.entries(sfigs)) {
    const m = html.match(new RegExp('id="' + k + '"[^>]*>([^<]*)<'));
    ok(m && Number(m[1].replace(/[^0-9.]/g, '')) === want, 'the page prints ' + want + ' for ' + k, m ? m[1] : 'not found');
  }
  {
    const m = html.match(/id="fig-held-frworst"[^>]*>([^<]*)</);
    ok(m && Math.abs(Number(m[1]) - frWorst) < 0.05, 'and prints the finger-at-rest worst miss to a tenth', m ? m[1] : 'not found');
  }

  // The half-harmonic test, over all 200 records rather than the held half. The page used to
  // print a typed 16 here, which is the count you get only if you also require all three
  // channels to have produced a rate; nothing computed it and nothing checked it.
  let hRec = 0, hCh = 0, hWorse = 0, hAccepted = 0;
  for (const rec of bundleMeta.records) {
    const pay = W.fromBundle(rec, bundleBin);
    let any = false;
    for (const c of pay.channels) {
      const r = P.channelRate(pay.times, c.values, P.CFG);
      if (r.halved === true) {
        any = true; hCh++;
        if (Math.abs(r.bpm - rec.hrRef) > Math.abs(r.naiveBpm - rec.hrRef)) hWorse++;
      }
    }
    if (any) { hRec++; if (!P.estimate(pay).refused) hAccepted++; }
  }
  ok(hCh === 27 && hRec === 20, 'the half-harmonic test fires on 27 channels in 20 of the 200 records', hCh + '/' + hRec);
  ok(hWorse === 26, 'and on 26 of those 27 channels it moved the rate AWAY from the reference', String(hWorse));
  ok(hAccepted === 0, 'while none of those 20 records survived the quality gates, so no printed number moved');
  for (const [k, want] of Object.entries({ 'fig-halved-ch': hCh, 'fig-halved-rec': hRec, 'fig-halved-worse': hWorse })) {
    const m = html.match(new RegExp('id="' + k + '"[^>]*>([^<]*)<'));
    ok(m && Number(m[1].replace(/[^0-9]/g, '')) === want, 'the page prints ' + want + ' for ' + k, m ? m[1] : 'not found');
  }
  ok(!/moved a channel's rate on 16 of them/.test(html), 'NEGATIVE: the unchecked typed count of 16 is gone');

  // ── how often the condition the trap guards against actually occurs ────────
  // The trap proves the estimator survives a second harmonic taller than the fundamental. The
  // page used to assert that this happens "often", which nothing here measured and which its
  // own corpus contradicts. Measure it: the power at twice each record's manually verified
  // rate over the power at that rate, on every channel of all 200 shipped records.
  {
    const qMeta = JSON.parse(readFileSync(join(SPEC, 'butppg-qrs.json'), 'utf8'));
    const qBin = new Uint8Array(readFileSync(join(SPEC, 'butppg-qrs.bin')));
    const byId = Object.fromEntries(qMeta.records.map((r) => [r.id, r]));
    const HALF = 0.05;
    const ratios = [], accRatios = [];
    let dominant = 0, dominantAccepted = 0;
    for (const rec of bundleMeta.records) {
      const pay = W.fromBundle(rec, bundleBin);
      const accepted = !P.estimate(pay).refused;
      const hr = W.medianHr(W.annFromBundle(byId[rec.id], qBin, qMeta.fs).rrMs);
      if (hr === null) continue;
      const f0 = hr / 60;
      if (2 * f0 > P.CFG.bandHiHz) continue;
      for (const ch of pay.channels) {
        const r = P.channelRate(pay.times, ch.values, P.CFG);
        if (r.refused) continue;
        const spec = P.spectrumOf(r.detrended, P.CFG.gridHz);
        const peak = (hz) => {
          const k0 = Math.max(1, Math.round((hz - HALF) / spec.hzPerBin));
          const k1 = Math.min(spec.mag.length - 1, Math.round((hz + HALF) / spec.hzPerBin));
          let m = 0;
          for (let k = k0; k <= k1; k++) if (spec.mag[k] > m) m = spec.mag[k];
          return m;
        };
        const a1 = peak(f0), a2 = peak(2 * f0);
        if (!(a1 > 0)) continue;
        const ratio = (a2 * a2) / (a1 * a1);
        ratios.push(ratio);
        if (accepted) accRatios.push(ratio);
        if (ratio > 1) { dominant++; if (accepted) dominantAccepted++; }
      }
    }
    ratios.sort((a, b) => a - b);
    accRatios.sort((a, b) => a - b);
    const mid = ratios.length % 2 ? ratios[(ratios.length - 1) / 2] : 0.5 * (ratios[ratios.length / 2 - 1] + ratios[ratios.length / 2]);
    ok(ratios.length === 432, '432 channel-records have twice their reference rate inside the search band', String(ratios.length));
    near(100 * mid, 10.4, 0.5, 'the second harmonic carries a median of 10.4 per cent of the fundamental\'s power');
    ok(dominant === 20, 'it is the taller line on 20 of the 432', String(dominant));
    ok(dominantAccepted === 0, 'and on none of the records these gates accept', String(dominantAccepted));
    ok(accRatios[accRatios.length - 1] < 0.30,
      'the largest ratio anywhere among accepted records is under 30 per cent (' + (100 * accRatios[accRatios.length - 1]).toFixed(0) + '), nowhere near a doubling',
      String(accRatios.length));
    for (const [k, wantVal] of Object.entries({ 'fig-harm-n': 432, 'fig-harm-dom': 20, 'fig-harm-domacc': 0 })) {
      const m = html.match(new RegExp('id="' + k + '"[^>]*>([^<]*)<'));
      ok(m && Number(m[1].replace(/[^0-9.]/g, '')) === wantVal, 'the page prints ' + wantVal + ' for ' + k, m ? m[1] : 'not found');
    }
    ok(!/Often more energy than at the heart rate itself/.test(html),
      'NEGATIVE: the unmeasured claim that the second harmonic often outruns the fundamental is gone');
    ok(!/the single commonest bug in code that reads a pulse off a camera/.test(html),
      'NEGATIVE: and so is the unfalsifiable claim about what the commonest bug in other people\'s code is');
    ok(/rare enough here that the specimen demonstrating it had to be manufactured/.test(html),
      'the page says instead that the specimen has to be synthetic BECAUSE the case is rare here');
  }
  const worst = Math.max.apply(null, acc.map((r) => Math.abs(r.err)));
  near(worst, 57.8, 0.1, 'the worst error among accepted records is 57.8 bpm');
  const b148 = bad.find((r) => r.rec.id === '148023');
  near(b148.e.value, 44.2, 0.1, '148023 is reported at 44.2 bpm against a reference of 102');
  const b149 = bad.find((r) => r.rec.id === '149040');
  near(b149.e.value, 83.1, 0.1, '149040 is reported at 83.1 bpm against a reference of 89');

  // the channel comparison the page tabulates
  const meanMod = { R: 0, G: 0, B: 0 }, meanDc = { R: 0, G: 0, B: 0 }, wins = { R: 0, G: 0, B: 0 };
  for (const r of acc) {
    let best = r.e.diagnostics.channels[0];
    for (const c of r.e.diagnostics.channels) { meanMod[c.name] += c.modPercent / acc.length; meanDc[c.name] += c.dc / acc.length; if (c.modPercent > best.modPercent) best = c; }
    wins[best.name]++;
  }
  near(meanMod.R, 0.128, 0.002, 'mean fractional pulse in red across the accepted records: 0.128 per cent');
  near(meanMod.G, 0.713, 0.002, 'in green: 0.713 per cent');
  near(meanMod.B, 0.747, 0.002, 'in blue: 0.747 per cent');
  near(meanDc.R, 240.4, 0.1, 'mean red level 240.4 of 255');
  ok(wins.B === 11 && wins.G === 4 && wins.R === 0, 'blue carries the largest fractional pulse in 11 of 15, green in 4, red in none',
    JSON.stringify(wins));

  // the fitting split is what the thresholds were chosen on, and it must still be a split
  const fit = bundleMeta.records.filter((r) => r.split === 'fit');
  ok(fit.length === 100, 'the fitting split holds 100 records');
  ok(!fit.some((r) => bundleMeta.records.filter((x) => x.split === 'held').some((h) => h.id === r.id)),
    'and no record appears in both halves');
  ok(bundleMeta.sample.seed === 20260817 && bundleMeta.sample.size === 200,
    'the sample is the declared 200 drawn with the declared seed');
}

// ══════════════════════════════════════════════════════════════════════════════
section('8b. the OTHER reference the dataset ships, decoded here');
// The page's accuracy figure hangs on the words "the electrocardiogram reference", and BUT PPG
// ships that reference twice: the HR column of quality-hr-ann.csv, and per-record beat marks
// its own ANNOTATORS file calls "reference QRS complex annotations from ECG, manually
// verified". They do not always agree, and where they differ they move this page's own
// headline. Everything below is decoded from the shipped bytes by the shipped wfdb.js.
let refs = null;
{
  const qMeta = JSON.parse(readFileSync(join(SPEC, 'butppg-qrs.json'), 'utf8'));
  const qBin = new Uint8Array(readFileSync(join(SPEC, 'butppg-qrs.bin')));
  const byId = Object.fromEntries(qMeta.records.map((r) => [r.id, r]));
  const beats = (id) => W.annFromBundle(byId[id], qBin, qMeta.fs);
  const hrOf = (id) => W.medianHr(beats(id).rrMs);

  ok(qMeta.fs === 1000, 'the annotations are on the 1000 Hz electrocardiogram clock');
  ok(qMeta.records.length === 201,
    'the bundle carries the 200 sampled records plus the named control, which fell outside the draw',
    String(qMeta.records.length));
  ok(createHash('sha256').update(qBin).digest('hex') === qMeta.binSha256,
    'and the packed bytes hash to what the index says');
  ok(bundleMeta.records.every((r) => byId[r.id] !== undefined), 'every sampled record has its annotations');

  // The anchor's marks, to the millisecond, against a hand-read of the file's own bytes.
  const a = beats('133007');
  ok(a.beats === 9, 'the anchor 133007 carries 9 manually verified beats', String(a.beats));
  const want = [1104, 1098, 1116, 1113, 1083, 1105, 1098, 1084];
  ok(a.rrMs.length === want.length && a.rrMs.every((v, i) => Math.abs(v - want[i]) < 1e-6),
    'and its intervals are 1104, 1098, 1116, 1113, 1083, 1105, 1098, 1084 ms',
    a.rrMs.map((v) => v.toFixed(1)).join(','));
  near(hrOf('133007'), 54.50, 0.01, 'so the dataset\'s own marks put it at 54.50 bpm against the column\'s integer 54');
  near(hrOf('140067'), 82.19, 0.01, 'and the control 140067 at 82.19 against its column\'s 82');

  // NEGATIVE: the SKIP escape is doing work. These files store every interval over 1023
  // samples as a 59<<10 escape followed by a 32-bit interval, and a reader that treats the
  // escape as an ordinary annotation gets a different, wrong answer. If this passes, the
  // decoder above is not merely echoing the bytes.
  const naiveDecode = (bytes) => {
    const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
    const out = [];
    let t = 0;
    for (let i = 0; i * 2 + 1 < bytes.byteLength; i++) {
      const w = view.getUint16(i * 2, true), code = w >> 10, ival = w & 0x3FF;
      if (code === 0 && ival === 0) break;
      t += ival;
      if (code === 1) out.push(t);
    }
    return out;
  };
  const raw = qBin.subarray(byId['133007'].offset, byId['133007'].offset + byId['133007'].bytes);
  const naive = naiveDecode(raw);
  ok(naive.length !== a.beats || naive.some((v, i) => Math.abs(v / 1000 - a.times[i]) > 1e-9),
    'NEGATIVE: a reader that ignores the long-interval escape gets a different answer, so the escape handling is load-bearing',
    naive.join(','));

  // How often the two references disagree, and where.
  const rows = bundleMeta.records.map((r) => ({
    id: r.id, split: r.split, quality: r.quality, csv: r.hrRef, qrs: hrOf(r.id),
    site: subjectInfo.site[r.id],
  })).map((r) => Object.assign(r, { d: Math.abs(r.qrs - r.csv) }));
  const off5 = rows.filter((r) => r.d > 5);
  const early = rows.filter((r) => Number(r.id) < 142000);
  const late = rows.filter((r) => Number(r.id) >= 142000);
  const ear = rows.filter((r) => r.site === '0');
  const worstRow = rows.reduce((x, y) => (y.d > x.d ? y : x));
  refs = { off5: off5.length, n: rows.length };
  ok(rows.length === 200, 'both references exist for all 200 sampled records');
  ok(off5.length === 44, 'the two disagree by more than 5 bpm on 44 of them', String(off5.length));
  ok(rows.filter((r) => r.d > 10).length === 21, 'and by more than 10 bpm on 21', String(rows.filter((r) => r.d > 10).length));
  near(worstRow.d, 43.2, 0.1, 'the worst disagreement is 43.2 bpm');
  ok(worstRow.id === '142025', 'on record 142025', worstRow.id);
  ok(early.length === 123 && early.filter((r) => r.d > 5).length === 0,
    'none of the 123 records with an ID below 142000 disagree at all',
    early.length + '/' + early.filter((r) => r.d > 5).length);
  ok(late.length === 77 && late.filter((r) => r.d > 5).length === 44,
    'and 44 of the 77 at or above 142000 do, so the disagreement is a block of the database rather than noise',
    late.length + '/' + late.filter((r) => r.d > 5).length);
  ok(ear.length === 21 && ear.filter((r) => r.d > 5).length === 0,
    'no ear recording in the sample disagrees, which is the confound worth naming: blocks 142 and up are all fingers',
    ear.length + '/' + ear.filter((r) => r.d > 5).length);
  ok(rows.filter((r) => r.split === 'held' && r.d > 5).length === 15,
    '15 of the held-out hundred the page quotes are affected');
  // Mostly, but not entirely, records the annotators called unusable. The three exceptions are
  // worth keeping in the verifier rather than rounding away: a quality-1 label means annotators
  // reading the PPG alone landed within 5 bpm of the HR column, so a quality-1 record whose
  // column disagrees with its own beat marks by more than 5 bpm is a case where the label and
  // the marks cannot both be describing the same rate.
  ok(off5.filter((r) => r.quality === 0).length === 41 && off5.filter((r) => r.quality === 1).length === 3,
    '41 of the 44 disagreeing records are ones the annotators called unusable, and 3 are not',
    off5.filter((r) => r.quality === 1).map((r) => r.id).join(','));

  // What that does to the page's own accuracy figure.
  const accepted = bundleMeta.records.filter((r) => r.split === 'held')
    .map((rec) => ({ rec, e: P.estimate(W.fromBundle(rec, bundleBin)) }))
    .filter((r) => !r.e.refused);
  const errCsv = accepted.map((r) => r.e.value - r.rec.hrRef);
  const errQrs = accepted.map((r) => r.e.value - hrOf(r.rec.id));
  const goodCsv = errCsv.filter((e) => Math.abs(e) <= 5).length;
  const goodQrs = errQrs.filter((e) => Math.abs(e) <= 5).length;
  ok(goodCsv === 13, 'scored against the HR column, 13 of the 15 accepted records are good', String(goodCsv));
  ok(goodQrs === 14, 'scored against the manually verified marks, 14 are', String(goodQrs));
  near(Math.max(...errCsv.map(Math.abs)), 57.8, 0.1, 'worst miss against the column, 57.8 bpm');
  near(Math.max(...errQrs.map(Math.abs)), 61.6, 0.1, 'worst miss against the marks, 61.6 bpm');
  const flipped = accepted.filter((r, i) => (Math.abs(errCsv[i]) <= 5) !== (Math.abs(errQrs[i]) <= 5));
  ok(flipped.length === 1 && flipped[0].rec.id === '149040',
    'and exactly one record changes verdict between them: 149040',
    flipped.map((r) => r.rec.id).join(','));
  near(hrOf('149040'), 81.0, 0.1, '149040\'s marks give 81.0 bpm where its column says 89, and the page reported 83.1');

  // the four figures the page prints in prose
  for (const [k, wantVal] of Object.entries({ 'fig-ref-off': 44, 'fig-ref-n': 200, 'fig-ref-good-csv': 13, 'fig-ref-good-qrs': 14 })) {
    const m = html.match(new RegExp('id="' + k + '"[^>]*>([^<]*)<'));
    ok(m && Number(m[1].replace(/[^0-9.]/g, '')) === wantVal, 'the page prints ' + wantVal + ' for ' + k, m ? m[1] : 'not found');
  }
  has('reference QRS complex annotations from ECG, manually verified', 'the page quotes the dataset\'s own description of these marks:');
  ok(existsSync(join(SPEC, 'ANNOTATORS')) &&
    readFileSync(join(SPEC, 'ANNOTATORS'), 'utf8').includes('manually verified'),
    'and ships the ANNOTATORS file that sentence comes from');
  ok(/cannot tell you which of the two the authors intended and does not guess/.test(instrumentJs),
    'the page refuses to adjudicate between the two references rather than quietly picking the flattering one');
  ok(/wherever the column is off, the label inherits it/.test(instrumentJs),
    'and says the quality label inherits the column it is defined against');

  // NEGATIVE, and this is the one that matters: the marks must reach the SCORING and never
  // the estimator. If a future edit hands them to estimate(), this fails.
  ok(/P\.estimate\(W\.fromBundle\(rec, bin\)\)/.test(instrumentJs),
    'the sweep still hands the estimator nothing but the decoded signal');
  ok(!/estimate\([^)]*qrs/i.test(instrumentJs) && !/estimate\([^)]*hrRef/.test(instrumentJs),
    'and no reference of either kind is passed into it');

  // Ten seconds is not five minutes, measured on the same marks.
  const q1f = bundleMeta.records
    .filter((r) => r.quality === 1 && subjectInfo.site[r.id] === '1')
    .map((r) => P.rmssdOf(beats(r.id).rrMs))
    .filter((v) => v !== null)
    .sort((x, y) => x - y);
  const med = 0.5 * (q1f[q1f.length / 2 - 1] + q1f[q1f.length / 2]);
  ok(q1f.length === 64, 'the sample holds 64 finger recordings the annotators called usable', String(q1f.length));
  near(med, 30.3, 0.1, 'their ten-second RMSSD has a median of 30.3 ms');
  const below19 = q1f.filter((v) => v < 19).length / q1f.length;
  const belowFloor = q1f.filter((v) => v < P.gridFloorMs(30)).length / q1f.length;
  near(100 * below19, 28.1, 0.1, 'and 28 per cent of them fall below the 19 ms bottom of the published span');
  near(100 * belowFloor, 40.6, 0.1, 'with 41 per cent below the 23.6 ms a 30 fps grid would invent');
  ok(/ten seconds is not five minutes/i.test(instrumentJs),
    'the page says a ten-second window is a different measurement from the five-minute one the norms rest on');
  ok(html.includes('id="short-window"'), 'and carries the live line that measures it');
}

// ══════════════════════════════════════════════════════════════════════════════
section('9. the frame grid floor, and the limits of the closed form');
{
  near(P.gridFloorMs(30), 23.57, 0.01, 'sqrt(h^2/2) at 30 fps is 23.57 ms');
  near(P.gridFloorMs(60), 11.79, 0.01, 'at 60 fps, 11.79 ms');
  near(P.gridFloorMs(120), 5.89, 0.01, 'at 120 fps, 5.89 ms');
  near(P.gridFloorMs(240), 2.95, 0.01, 'at 240 fps, 2.95 ms');
  near(1000 / 30, 33.333, 0.001, 'the frame spacing at 30 fps is 33.33 ms');

  // the closed form against the actual rounding, over many seeds
  const MEAN = 833.3333333333334;
  const roundedAt = (trueMs, fps) => {
    const got = [];
    for (const seed of [3, 11, 29, 47, 71, 97]) {
      const rr = P.rrSeries({ meanMs: MEAN, rmssdMs: trueMs, beats: 600, seed });
      const t = [0];
      for (const v of rr.rrMs) t.push(t[t.length - 1] + v / 1000);
      got.push(P.rmssdOf(P.diffsMs(P.quantiseTimes(t, fps))));
    }
    return got.reduce((a, b) => a + b, 0) / got.length;
  };
  for (const trueMs of [20, 30, 50, 80]) {
    const r = roundedAt(trueMs, 30), p = P.predictedRmssdMs(trueMs, 30);
    ok(Math.abs(r - p) <= 1.0,
      'at a true ' + trueMs + ' ms the closed form (' + p.toFixed(2) + ') matches the actual rounding (' + r.toFixed(2) + ') to within 1 ms');
  }
  // and the documented breakdown below about 15 ms
  const r5 = roundedAt(5, 30), p5 = P.predictedRmssdMs(5, 30);
  near(p5, 24.1, 0.05, 'at a true 5 ms the closed form predicts 24.1 ms');
  near(r5, 15.7, 0.3, 'while the actual rounding, averaged over 6 seeds of 600 beats, gives about 15.7 ms');
  ok(p5 - r5 > 5, 'so the model overstates the damage below a true 15 ms');

  // The paragraph beside the panel used to quote 15.7 and tell the reader to compare it with
  // the panel's own rounded row, which runs ONE series of 300 beats at seed 3 and shows 18.69.
  // A number the reader is told to check on the same screen has to be the number on that
  // screen, so pin the panel's own configuration here as well, and require the page to carry
  // both figures and to say which is which.
  const panelRounded = (trueMs, fps) => {
    const rr = P.rrSeries({ meanMs: MEAN, rmssdMs: trueMs, beats: 300, seed: 3 });
    const t = [0];
    for (const v of rr.rrMs) t.push(t[t.length - 1] + v / 1000);
    return P.rmssdOf(P.diffsMs(P.quantiseTimes(t, fps)));
  };
  near(panelRounded(5, 30), 18.69, 0.02, 'the panel itself, one 300-beat series at seed 3, shows 18.69 ms there');
  ok(/beats:\s*300/.test(instrumentJs) && /seed:\s*3\b/.test(instrumentJs),
    'and 300 beats at seed 3 is what the shipped panel actually runs');
  ok(html.includes('18.7'), 'the page quotes the panel\'s own 18.7 rather than only the six-seed average');
  ok(/six independent runs of 600 beats/.test(html),
    'and says the 15.7 is an average over six runs of 600 beats, not what one run shows');

  // The maths above is a property of the formula. It says nothing about whether the READER is
  // ever told, and the slider goes down to a true 4 ms, well inside the region where the closed
  // form is wrong. So assert the page carries the live line that says so, and that the line is
  // driven by the two computed values rather than typed as prose.
  ok(html.includes('id="rm-model"'), 'the panel carries a live line about the closed form\'s own range');
  ok(/min="4"/.test(html) && /id="rm-true-in"/.test(html),
    'the true-RMSSD slider reaches 4 ms, which is inside the breakdown region, so that line is reachable');
  ok(instrumentJs.includes('rm-model') && /left its own range/.test(instrumentJs),
    'and it names the closed form leaving its range rather than showing the gap without comment');
  ok(/stop being independent/.test(instrumentJs),
    'naming the assumption that fails: the rounding errors stop being independent');
  ok(/r\.predicted/.test(instrumentJs) && /r\.rounded/.test(instrumentJs) && /Math\.abs\(gap\)/.test(instrumentJs),
    'and it quotes the computed prediction and the computed rounding, so it cannot drift from them');

  // parabolic refinement: it removes the floor on a clean signal and stops helping with noise
  const runPipeline = (trueMs, fps, noiseFrac) => {
    const amp = 150 * 0.02, na = [], re = [];
    for (const seed of [3, 11, 29]) {
      const rr = P.rrSeries({ meanMs: MEAN, rmssdMs: trueMs, beats: 300, seed });
      const seconds = rr.rrMs.reduce((a, b) => a + b, 0) / 1000;
      const sig = P.synthSignal({ seconds, fps, rrMs: rr.rrMs, dc: 150, gain: 0.02, noiseLsb: noiseFrac * amp, seed: 5, quantise: false });
      const bt = P.beatTimes(sig.values, fps, 1000 / MEAN);
      ok(bt.count === rr.rrMs.length, 'the beat picker finds every beat (' + bt.count + ' of ' + rr.rrMs.length + ') at ' + fps + ' fps, noise ' + noiseFrac);
      na.push(P.rmssdOf(P.diffsMs(bt.naive)));
      re.push(P.rmssdOf(P.diffsMs(bt.refined)));
    }
    const m = (a) => a.reduce((x, y) => x + y, 0) / a.length;
    return { naive: m(na), refined: m(re) };
  };
  const clean = runPipeline(20, 30, 0);
  ok(Math.abs(clean.naive - P.predictedRmssdMs(20, 30)) <= 1.2,
    'on a clean signal the frame-locked measurement matches the closed form (' + clean.naive.toFixed(2) + ')');
  ok(Math.abs(clean.refined - 20) <= 0.6,
    'and parabolic refinement recovers the true 20 ms almost exactly (' + clean.refined.toFixed(2) + ')');
  const noisy = runPipeline(20, 30, 0.10);
  ok(noisy.refined > P.gridFloorMs(30),
    'with noise at 10 per cent of the pulse amplitude the refined value (' + noisy.refined.toFixed(1) +
    ') is WORSE than the floor it was meant to remove, which is the page\'s second claim');
  const noisyFast = runPipeline(20, 240, 0.10);
  ok(noisyFast.refined > 0.5 * noisy.refined,
    'and an eightfold faster camera does not rescue it (' + noisyFast.refined.toFixed(1) + ' at 240 fps)');

  // ── the floor is not a floor, which is what the page used to say it was ────
  // A PERFECTLY steady heart is the case the closed form is derived for and the case its
  // independence assumption cannot survive: the beats march around the grid in lockstep. Where
  // the interval is a whole number of frames every rounding error is identical and the measured
  // RMSSD is exactly zero. This is the correction the blinded re-derivation found, and it is
  // checked here at every rate rather than at the flattering ones.
  const steady = (bpm, fps, beats) => {
    const R = 60 / bpm, t = [];
    for (let k = 0; k < (beats || 300); k++) t.push(k * R);
    return P.rmssdOf(P.diffsMs(P.quantiseTimes(t, fps)));
  };
  for (const bpm of [50, 60, 72, 75, 90, 100, 120]) {
    const frames = (60 / bpm) * 30;
    ok(Math.abs(frames - Math.round(frames)) < 1e-9 && steady(bpm, 30) < 1e-9,
      'at ' + bpm + ' bpm a beat is exactly ' + frames + ' frames at 30 fps, and the invented RMSSD is 0.00, not 23.57',
      steady(bpm, 30).toFixed(3));
  }
  ok(steady(54, 30) > P.gridFloorMs(30),
    'while at 54 bpm the same steady heart reads ABOVE the closed form (' + steady(54, 30).toFixed(2) + '), so the miss goes both ways');
  {
    const vals = [];
    for (let bpm = 40; bpm <= 200 + 1e-9; bpm += 0.02) vals.push(steady(bpm, 30));
    const sorted = vals.slice().sort((a, b) => a - b);
    const mid = sorted.length % 2 ? sorted[(sorted.length - 1) / 2] : 0.5 * (sorted[sorted.length / 2 - 1] + sorted[sorted.length / 2]);
    near(mid, P.gridFloorMs(30), 0.15, 'across 40 to 200 bpm the MEDIAN of that sweep is the closed form, which is its honest status');
    ok(sorted[0] < 1e-9, 'its minimum is 0.00 ms');
    ok(sorted[sorted.length - 1] > 33, 'its maximum is above 33 ms', sorted[sorted.length - 1].toFixed(2));
    const near10 = vals.filter((v) => Math.abs(v - P.gridFloorMs(30)) <= 0.1 * P.gridFloorMs(30)).length / vals.length;
    ok(near10 < 0.25, 'and fewer than a quarter of rates land within a tenth of it (' + (100 * near10).toFixed(0) + ' per cent)');
    const below = vals.filter((v) => v < 0.5 * P.gridFloorMs(30)).length / vals.length;
    near(100 * below, 12.4, 1.0, 'while 12 per cent come in below half of it');
  }
  ok(html.includes('id="comb-canvas"') && html.includes('id="comb-out"'),
    'the page draws that whole curve rather than quoting the one number');
  ok(/Except that 23.6 is a typical value, not a floor/.test(html),
    'and says in a heading that the number is a typical value rather than a bound');
  ok(!/can never report less than the frame grid/.test(html),
    'NEGATIVE: the old claim that a frame-locked reading can never come in under the grid is gone');
  ok(!/biased upward, never downward/.test(html),
    'NEGATIVE: and so is "biased upward, never downward", which the page\'s own panel refutes below 15 ms');
  ok(/typically manufactures about 23.6 ms|usually manufactures about 23.6|typically invents about 23.6/.test(html + md),
    'the dek and the social cards say "typically" rather than stating the floor flat');
}

// ══════════════════════════════════════════════════════════════════════════════
section('10. the real person, from an electrocardiogram we did not record');
let ecgRmssd = null;
{
  const ecg = W.decode(readFileSync(join(SPEC, '133007_ECG.hea'), 'utf8'), new Uint8Array(readFileSync(join(SPEC, '133007_ECG.dat'))));
  ok(ecg.fs === 1000, 'the shipped electrocardiogram is sampled at 1000 Hz');
  ok(ecg.channels[0].values.length === 10000, 'and runs for 10000 samples, exactly 10 s');
  const q = P.qrsDetect(ecg.channels[0].values, ecg.fs);
  ok(q.beats === 9, 'nine beats are detected in that window');
  const rmssd = P.rmssdOf(q.rrMs);
  ecgRmssd = rmssd;
  near(rmssd, 17.48, 0.02, 'the RMSSD of the eight intervals between them is 17.48 ms');

  // Three stages, kept apart on purpose. The page used to print two rows and hand the whole
  // 1.56 ms improvement to parabolic refinement, which is the technique it had just cited the
  // Task Force for. It is not what did the work: relocating each mark onto the R wave at the
  // nearest INTEGER SAMPLE is, and the parabola then moves the answer by 0.08 ms, upward. At
  // 1000 Hz the sample grid can only contribute sqrt(h^2/2) = 0.71 ms to a beat time, so a
  // parabola cannot be worth 1.5 ms of RMSSD here and the old row label was arithmetically
  // impossible as well as wrong.
  const coarse = P.rmssdOf(q.coarseRrMs), onSample = P.rmssdOf(q.sampleRrMs);
  near(coarse, 19.04, 0.02, 'the beat detector\'s own marks give 19.04 ms');
  near(onSample, 17.40, 0.02, 'moving each mark onto the R wave, to the nearest sample, gives 17.40 ms');
  near(rmssd - onSample, 0.08, 0.02, 'and the parabola on top of that is worth 0.08 ms, upward');
  ok(Math.abs(rmssd - onSample) < 0.2 * Math.abs(coarse - onSample),
    'so the relocation carries the improvement and the parabola is a rounding detail at 1000 Hz');
  near(P.gridFloorMs(ecg.fs), 0.71, 0.01, 'sqrt(h^2/2) at 1000 Hz is 0.71 ms, which bounds what the parabola could win');
  ok(/moved onto the R wave, to the nearest sample/.test(instrumentJs),
    'and the page prints all three rows rather than crediting the parabola with the difference');
  ok(rmssd < P.gridFloorMs(30),
    'and 17.48 ms is BELOW the 23.57 ms a 30 fps camera manufactures from nothing, which is the page\'s headline');
  const se = rmssd / Math.sqrt(2 * (q.rrMs.length - 1));
  near(se, 4.67, 0.05, 'its standard error on eight intervals is about 4.67 ms');
  ok(rmssd + se < P.gridFloorMs(30), 'and even one standard error above it still sits under the floor');
  // A median of an EVEN number of intervals is the average of the middle two. Taking the
  // upper one instead, which this page did until 2026-08-17, moved the printed rate by
  // 0.13 bpm and made it disagree with the dataset's own manually verified marks by more
  // than the marks disagree with the published integer.
  const sorted = [...q.rrMs].sort((a, b) => a - b);
  const med = 0.5 * (sorted[sorted.length / 2 - 1] + sorted[sorted.length / 2]);
  near(60000 / med, 54.48, 0.02, 'the median interval gives 54.48 bpm, against a published reference of 54');
  near(60000 / Math.max(...q.rrMs), 53.74, 0.02, 'the slowest beat is 53.74 bpm');
  near(60000 / Math.min(...q.rrMs), 55.45, 0.02, 'the fastest is 55.45 bpm, so the true rate is a range');
  // stability of the detector's own free choice
  const alt = [0.25, 0.3, 0.4, 0.45].map((threshold) => P.rmssdOf(P.qrsDetect(ecg.channels[0].values, ecg.fs, { threshold }).rrMs));
  ok(alt.every((v) => Math.abs(v - rmssd) < 0.01), 'and the answer does not move when the detector threshold does');

  // ── which way the light moves, which is the first claim the page makes ──────
  // The same two files settle it. For each R wave, find the lowest point of the light in the
  // next 0.8 s. A dip about a pulse transit time after the R wave means the arriving blood
  // takes light out; if the light rose with the pulse instead, these minima would sit about
  // half a beat further on. The page shipped that sentence backwards until 2026-08-17 and the
  // shipped specimens had the answer in them the whole time.
  const pl = record('133007');
  const dip = (chIndex) => {
    const r = P.channelRate(pl.times, pl.channels[chIndex].values, P.CFG);
    const y = r.detrended, hz = P.CFG.gridHz;
    const t0 = pl.times[0] + (r.resampled.length - y.length) / hz;
    const lags = [];
    for (const tr of q.times) {
      let bi = -1, bv = Infinity;
      for (let i = 0; i < y.length; i++) {
        const t = t0 + i / hz;
        if (t > tr && t <= tr + 0.8 && y[i] < bv) { bv = y[i]; bi = i; }
      }
      if (bi >= 0) lags.push((t0 + bi / hz - tr) * 1000);
    }
    lags.sort((a, b) => a - b);
    return lags;
  };
  const dipR = dip(0);
  ok(dipR.length === q.beats, 'every one of the 9 beats has a light minimum in the 0.8 s after it', String(dipR.length));
  const medDip = dipR[dipR.length >> 1];
  near(medDip, 311, 2, 'the red channel bottoms out a median of 311 ms after the R wave');
  ok(medDip > 150 && medDip < 500, 'which is a pulse transit time to a fingertip');
  const sortedRr = [...q.rrMs].sort((a, b) => a - b);
  const beatMs = sortedRr[sortedRr.length >> 1];
  ok(medDip < beatMs / 2, 'and less than half a beat (' + (beatMs / 2).toFixed(0) +
    ' ms), which is where those minima would sit if the light ROSE as the blood arrived');
  ok(pl.channels[0].values.reduce((a, b) => a + b, 0) / pl.channels[0].values.length > 200,
    'the shipped channels are light levels out of 255, red brightest, as light that has been through flesh requires');

  // ── the same ten seconds, from marks this page did not make ────────────────
  // The page's one real RMSSD came from its own detector, which is a free choice nobody
  // checked. The dataset ships manually verified marks for this record; they are the second
  // instrument, and they must agree.
  {
    const qMeta = JSON.parse(readFileSync(join(SPEC, 'butppg-qrs.json'), 'utf8'));
    const qBin = new Uint8Array(readFileSync(join(SPEC, 'butppg-qrs.bin')));
    const entry = qMeta.records.find((r) => r.id === '133007');
    const anno = W.annFromBundle(entry, qBin, qMeta.fs);
    const annoRmssd = P.rmssdOf(anno.rrMs);
    near(annoRmssd, 16.90, 0.02, 'the dataset\'s own marks give this person 16.90 ms over the same ten seconds');
    ok(Math.abs(annoRmssd - rmssd) < 0.6,
      'which agrees with this page\'s detector (' + rmssd.toFixed(2) + ') to better than 0.6 ms, well inside the 4.7 ms standard error',
      Math.abs(annoRmssd - rmssd).toFixed(3));
    ok(annoRmssd < P.gridFloorMs(30),
      'and it too sits below the 23.57 ms a 30 fps grid typically invents, so the page\'s headline does not depend on whose marks you use');
    const gap = Math.max(...anno.rrMs.map((v, i) => Math.abs(v - q.rrMs[i])));
    near(gap, 1.03, 0.05, 'no interval differs from ours by more than 1.03 ms');
    ok(html.includes('manually verified beat marks'), 'and the page prints that row rather than only its own detector');
  }

  // ── what a 30 fps grid actually does to THESE beat times ───────────────────
  // The page used to say a camera "could not have found this number and would have reported a
  // larger one". Over the frame phases a shutter could actually land on, it reports a larger
  // number most of the time and a smaller one often enough to matter, and the spread is the
  // finding. This is the vacuity check the blinded re-derivation asked for, executed.
  {
    const h = 1 / 30, out = [];
    for (let k = 0; k < 2000; k++) {
      const phase = ((k + 0.5) / 2000) * h;
      out.push(P.rmssdOf(P.diffsMs(P.quantiseTimes(q.times.map((t) => t + phase), 30))));
    }
    out.sort((a, b) => a - b);
    const mid = 0.5 * (out[out.length / 2 - 1] + out[out.length / 2]);
    ok(out[0] < 1e-9, 'over 2000 frame phases the smallest answer is 0.00 ms');
    near(out[out.length - 1], 47.1, 0.2, 'the largest is 47.1 ms');
    near(mid, 30.9, 0.2, 'and the median is 30.9, well above the person\'s real 17.5');
    const above = out.filter((v) => v > rmssd).length / out.length;
    near(100 * above, 89, 2, 'the camera reads high on 89 per cent of phases, which is most but nothing like all of them');
    ok(above < 1, 'so "it would have reported a larger one" was false, and the page no longer says it');
    ok(!/could not have found this number/.test(html) && !/could not have found this number/.test(instrumentJs),
      'NEGATIVE: that sentence is gone from the page and from the code that renders it');
    ok(/not a number at all/.test(instrumentJs) && /phase of the frame clock/.test(instrumentJs),
      'and what replaced it is the measured spread, named as a spread');
  }
}

// ══════════════════════════════════════════════════════════════════════════════
section('11. the dataset counts, re-derived rather than typed');
let corpus;
{
  const csv = readFileSync(join(SPEC, 'quality-hr-ann.csv'), 'utf8').replace(/^﻿/, '');
  const lines = csv.split(/\r?\n/).filter((l) => l.trim());
  const rows = lines.slice(1).map((l) => l.split(','));

  // The second file, and the reason it now ships. 830 usable out of 3888 was being read to the
  // reader as "four out of five attempts by people trying their best failed", and every part of
  // that sentence was wrong: half the recordings are of an EAR, 1164 were made under an artefact
  // the authors induced on purpose, and among the finger-at-rest recordings the failure rate is
  // 65 per cent rather than 79. None of that is visible in quality-hr-ann.csv, which is exactly
  // why a verifier that only re-derived 3888 and 830 could stay green under a false sentence.
  const { site, motion } = subjectInfo;
  ok(subjectInfo.head.includes('Ear/finger') && subjectInfo.head.includes('Motion'),
    'the shipped subject file names its site and motion columns', subjectInfo.head.join('|'));
  ok(subjectInfo.rows === 3888, 'and carries a row for every one of the 3888 recordings', String(subjectInfo.rows));

  const id = (r) => r[0].trim();
  corpus = {
    total: rows.length,
    usable: rows.filter((r) => Number(r[1]) === 1).length,
    ear: rows.filter((r) => site[id(r)] === '0').length,
    artefact: rows.filter((r) => motion[id(r)] !== undefined && motion[id(r)] !== '0').length,
    fingerRest: rows.filter((r) => site[id(r)] === '1' && motion[id(r)] === '0').length,
    fingerRestBad: rows.filter((r) => site[id(r)] === '1' && motion[id(r)] === '0' && Number(r[1]) !== 1).length,
  };
  ok(corpus.total === 3888, 'the shipped annotation file holds 3888 recordings', String(corpus.total));
  ok(corpus.usable === 830, 'of which 830 are labelled usable for heart rate estimation', String(corpus.usable));
  ok(corpus.ear === 1962, '1962 of the recordings are of an ear, not a finger', String(corpus.ear));
  ok(rows.filter((r) => site[id(r)] === '1').length === 1926, 'and 1926 are of a finger');
  ok(corpus.artefact === 1164, '1164 were made under an induced artefact rather than at rest', String(corpus.artefact));
  ok(corpus.fingerRest === 1354, '1354 recordings are a finger at rest', String(corpus.fingerRest));
  ok(corpus.fingerRestBad === 877, 'and 877 of those 1354 are labelled unusable', String(corpus.fingerRestBad));
  const frFail = corpus.fingerRestBad / corpus.fingerRest;
  ok(frFail > 0.63 && frFail < 0.67,
    'so the finger-at-rest failure rate is ' + (100 * frFail).toFixed(1) + ' per cent, between 63 and 67, which is what the page says',
    String(frFail));
  ok(frFail < 0.75, 'NEGATIVE: it is NOT the four in five the page used to claim, and this assertion would have caught that');
  const pool = rows.filter((r) => Number(r[0]) >= 130000).length;
  ok(pool === bundleMeta.pool && pool === 2094, 'and the declared v2 pool of 2094 is what the file actually contains');

  // the figures the corpus paragraph prints, against what the two files hold
  const cfigs = { 'fig-corpus-total': corpus.total, 'fig-corpus-usable': corpus.usable,
    'fig-corpus-ear': corpus.ear, 'fig-corpus-motion': corpus.artefact,
    'fig-corpus-fr': corpus.fingerRest, 'fig-corpus-fr-bad': corpus.fingerRestBad };
  for (const [k, want] of Object.entries(cfigs)) {
    const m = html.match(new RegExp('id="' + k + '"[^>]*>([^<]*)<'));
    ok(m && Number(m[1].replace(/[^0-9]/g, '')) === want, 'the page prints ' + want + ' for ' + k, m ? m[1] : 'not found');
  }
  ok(!/four out of\s+five attempts/.test(html.replace(/\s+/g, ' ')),
    'NEGATIVE: the "four out of five attempts" sentence is gone from the page');
}

// ══════════════════════════════════════════════════════════════════════════════
section('12. what the reader actually sees');
{
  has('23.6', 'the floor'); has('33.33', 'the frame spacing');
  has('17.5', 'the real RMSSD'); has('54 bpm', 'the anchor reference');
  has('19 to 75', 'the span of published study averages'); has('21,438', 'the review\'s sample');
  has('44 studies'); has('the average reported RMSSD was 42 ms');

  // The Nunan/Shaffer numbers are cross-STUDY statistics: Table 6's columns are "Mean (SD),
  // Range, Studies" and the RMSSD row reads 42 (15), 19-75, 15. The page used to present that
  // as "the healthy adult range ... with a mean of 42 and a standard deviation of 15", which
  // is a distribution of people, and then said the fabricated floor sits inside it. Different
  // and weaker claim. These three assertions hold the page to the version the source supports.
  ok(/study averages themselves ran from 19 to\s+75 ms/.test(html.replace(/\s+/g, ' ')),
    'the page says 19 to 75 is the spread of study averages');
  ok(/spread of study averages\s+rather than a range that individual people occupy/.test(html.replace(/\s+/g, ' ')),
    'and says plainly that it is not a range individual people occupy');
  ok(!/healthy adult range for RMSSD/i.test(html) && !/standard deviation of 15/.test(html),
    'NEGATIVE: the per-person reading of those numbers is gone from the page');
  has('3,888'); has('830');
  has('57.8 bpm', 'the worst held-out error');
  has('5.58', 'the widest published limit of agreement');
  has('5.52'); has('0.29 bpm', 'the narrowest');
  has('r = 0.98 to 1', 'the published correlation range');
  has('24.1 ms'); has('15.7');
  has('53.7 to 55.5', 'the anchor\'s own rate range');
  has('6.0 bpm', 'the raw spectral bin');
  has('21434-21445', 'the Verkruysse pages');
  has('1043-1065', 'the Task Force pages');
  has('10.13026/tn53-8153', 'the dataset DOI');
  has('Creative Commons Attribution 4.0');

  // the figures the page prints in prose and then audits against its own live sweep
  const figs = { 'fig-held-n': sweep.n, 'fig-held-accept': sweep.accept, 'fig-held-refuse': sweep.refuse,
    'fig-held-good': sweep.good, 'fig-held-bad': sweep.bad, 'fig-held-q1refused': sweep.q1ref };
  for (const [id, want] of Object.entries(figs)) {
    const m = html.match(new RegExp('id="' + id + '"[^>]*>([^<]*)<'));
    ok(m && Number(m[1].replace(/[^0-9.]/g, '')) === want,
      'the page prints ' + want + ' for ' + id, m ? m[1] : 'not found');
  }

  // Gate thresholds quoted in prose must be the ones the shipped estimator uses, and each
  // has to be matched IN ITS OWN SENTENCE. "html.includes('4.0')" was satisfied by the phrase
  // "Creative Commons Attribution 4.0 International" further down the page, so half of that
  // check was free: it could not have noticed the SNR threshold disappearing from the prose.
  const flat = html.replace(/\s+/g, ' ');
  ok(/agree with each other to within 3\.0 bpm/.test(flat) && P.CFG.spreadMaxBpm === 3.0,
    'the cross-channel limit is quoted in its own sentence and is the one in CFG');
  ok(/in band signal to noise must reach 4\.0/.test(flat) && P.CFG.snrMin === 4.0,
    'the SNR limit is quoted in its own sentence and is the one in CFG');
  ok(/modulation index,[^.]*must stay under 3\.0 per cent/.test(flat) && P.CFG.modMaxPercent === 3.0,
    'the modulation limit is quoted in its own sentence and is the one in CFG');
  // and AC is DEFINED where it is used, because peak-to-peak and fundamental amplitude differ
  // by a factor of nearly 3 on the anchor's blue channel and put the gate in different places.
  ok(/amplitude of the fundamental over the channel's mean level/.test(flat),
    'and the sentence says which AC it means, rather than leaving the gate\'s operating point undefined');
  ok(/AC is the amplitude of the fundamental/.test(flat) && /peak to peak swing of the same detrended trace is 0\.737/.test(flat),
    'the channel table says the same thing and shows what the other convention would have given');
  ok(/one beat later at 0\.35 or better/.test(flat) && P.CFG.repeatMin === 0.35,
    'the repeat limit is quoted in its own sentence and is the one in CFG');

  // the shareable surface, where an abandoned claim survives longest
  const meta = html.match(/<meta name="description" content="([^"]+)"/)[1];
  const og = html.match(/<meta property="og:description" content="([^"]+)"/)[1];
  const ld = JSON.parse(html.match(/<script type="application\/ld\+json">([\s\S]*?)<\/script>/)[1]);
  const dek = (md.match(/^dek:\s*"([\s\S]*?)"\s*$/m) || [])[1] || '';
  const plain = (md.match(/^plain:\s*"([\s\S]*?)"\s*$/m) || [])[1] || '';
  const seoTitle = (md.match(/^seoTitle:\s*"([^"]*)"/m) || [])[1] || '';
  const title = (md.match(/^title:\s*"([^"]*)"/m) || [])[1] || '';

  // THE SHAREABLE SURFACE, where an abandoned claim survives longest, and where this page
  // leaked. What used to stand here was /23\.6|invents|frame grid/, called "carries the claim
  // the page actually supports" — but "invents" is a word in the TITLE, so any text derived
  // from the title passed whatever else it said. It passed a plain card reading "a 30 frames a
  // second camera invents more of it than a resting heart has": unscoped, about people in
  // general, and contradicted by this page's own cited average of 42 ms. So test the property
  // instead. Pin the numbers to what was just computed, require the person's figure to be
  // scoped to the shipped recording wherever it appears, and forbid the shape of sentence that
  // leaked: a comparison against hearts, adults or people at large.
  const floorStr = P.gridFloorMs(30).toFixed(1);
  const personStr = ecgRmssd.toFixed(1);
  const GENERAL = /than (?:a|an|the|most|any|your|their)\s+(?:own\s+|real\s+|resting\s+|healthy\s+|average\s+|typical\s+|normal\s+)*(?:heart|hearts|adult|adults|person|people|reader)\b/i;
  for (const [name, text] of [['meta description', meta], ['og:description', og], ['the JSON-LD description', ld.description], ['the dek', dek], ['the plain card', plain]]) {
    ok(text.includes(floorStr), name + ' carries the floor this page just computed, ' + floorStr + ' ms');
    ok(!/\b1[0-9]\.[0-9]\b/.test(text) || text.includes(personStr),
      name + ' quotes the electrocardiogram figure as the computed ' + personStr + ' ms or not at all');
    ok(!text.includes(personStr) || /recording/.test(text),
      name + ' scopes that figure to the shipped recording rather than to a person in general');
    ok(!GENERAL.test(text), 'NEGATIVE: ' + name + ' compares the floor against no heart, adult or person at large');
    ok(!/actually has|really has|a resting heart has/i.test(text),
      'NEGATIVE: ' + name + ' claims no personal parameter from a ten second window');
    ok(!/diagnos|screen|fitness|health check|medical grade|accurate to/i.test(text.replace(/diagnoses nothing/gi, '')),
      'NEGATIVE: ' + name + ' does not imply diagnosis, screening or a fitness assessment');
    ok(!/—/.test(text), name + ' has no em dash');
  }
  ok(/not a medical device|diagnoses nothing/i.test(meta) && /not a medical device|diagnoses nothing/i.test(og),
    'both social descriptions say plainly that it is not a medical device');
  ok(plain.length <= 420, 'the plain card is within 420 characters (' + plain.length + ')');
  // Split on sentence-ending punctuation followed by a space, the way the corpus-wide gate in
  // scripts/check-plain-placards.mjs does. Splitting on every "." counted "23.6 ms" as two
  // sentences, which would have pushed a correct card over the limit and invited the fix of
  // deleting the number rather than the fix of counting properly.
  const plainSentences = plain.split(/(?<=[.!?])\s+/).filter((s) => s.trim()).length;
  ok(plainSentences <= 3, 'and within three sentences (' + plainSentences + ')');
  ok(seoTitle.length <= 60, 'the seoTitle is within 60 characters (' + seoTitle.length + ')');
  ok(ld.headline === title, 'the JSON-LD headline is the poetic title');
  ok(ld.name === seoTitle, 'and its name is the seoTitle');
  ok(md.includes('seam: "life"'), 'the seam is life');
  ok(!/—/.test(dek + plain), 'neither the dek nor the plain card carries an em dash');

  // the medical-device statement must sit beside the readout, not in a footnote
  const readoutAt = html.indexOf('id="live-value"');
  const warnAt = html.indexOf('not a medical device');
  ok(warnAt >= 0 && warnAt < readoutAt, 'the "not a medical device" statement appears BEFORE the live readout in the document');
  for (const word of ['blood oxygen', 'irregular rhythm', 'blood pressure', 'stress score']) {
    has(word, 'the page names what it will not attempt:');
  }
  // This assertion used to end in "|| true", which made it unconditionally true: it printed
  // as a green check while testing nothing, beside the one word a not-a-medical-device page
  // most needs never to put next to a number. Aimed at the phrases that matter, and allowed
  // to fail.
  const readoutRegion = html.slice(readoutAt, readoutAt + 4000);
  ok(!/\b(normal|abnormal|healthy|unhealthy)\s+(range|reading|result|for you|for your age)\b/i.test(readoutRegion),
    'no "normal range" or "healthy reading" within 4000 characters of the live readout');
  ok(!/your (?:heart|health|fitness|recovery) is\b/i.test(readoutRegion),
    'and nothing near the readout tells the reader what their heart or health IS');
  // and the check itself must be able to fail: the same test, run against a sentence of the
  // shape it forbids, has to come back false.
  ok(/\b(normal|abnormal|healthy|unhealthy)\s+(range|reading|result|for you|for your age)\b/i.test('this is a normal reading for you'),
    'NEGATIVE: that test does fire on a sentence of the shape it forbids');

  // a path printed on the page is an instruction
  for (const rel of ['research/ppg-pulse/verify-ppg-pulse.mjs', 'scripts/check-live-sensor.mjs']) {
    ok(html.includes(rel) ? existsSync(join(ROOT, rel)) : true, 'the command the page prints points at a real file: ' + rel);
  }

  // no third-party requests, in any shape, from the page's script content
  const scripts = [...html.matchAll(/<script(?![^>]*type="application\/ld\+json")[^>]*>([\s\S]*?)<\/script>/g)].map((m) => m[1]).join('\n');
  const jsFiles = ['instrument.js', 'ppg.js', 'wfdb.js'].map((f) => readFileSync(join(PAGE, f), 'utf8')).join('\n');
  const foreign = /(https?:)?\/\/(?!127\.0\.0\.1|localhost)[a-z0-9.-]+\.[a-z]{2,}/i;
  ok(!foreign.test(scripts), 'no absolute URL to another origin in the page\'s inline script content');
  ok(!foreign.test(jsFiles.replace(/^\s*\/\/.*$/gm, '')), 'nor in its sibling modules outside comments');
  const srcs = [...html.matchAll(/<script[^>]+src="([^"]+)"/g)].map((m) => m[1]);
  ok(srcs.every((s) => s.startsWith('/') || s.startsWith('./')), 'every script tag loads a same-origin path', srcs.join(' '));
  ok(!/<link[^>]+href="https?:\/\/(?!artwaste\.land)/i.test(html), 'no stylesheet or font from another origin');

  // the first physical claim on the page, which shipped backwards until 2026-08-17
  ok(!/more blood in your finger between beats/i.test(html + md),
    'NEGATIVE: "more blood in your finger between beats than during them" is gone from the page and its frontmatter');
  ok(/more blood into the finger/i.test(html) && /the level dips/i.test(html),
    'the page states the direction the right way round');
  ok(/id="phase-out"/.test(html) && /renderPhase/.test(instrumentJs),
    'and checks it against the shipped electrocardiogram rather than only asserting it');

  // the torch, where an absolute historical claim shipped and was falsified by a 2023 commit
  ok(!/no iPhone ever has/i.test(html), 'NEGATIVE: the "no iPhone ever has" claim is gone');
  ok(!/iOS has never implemented torch/i.test(instrumentJs), 'and gone from the code comment that repeated it');
  ok(/applyConstraints/.test(html) || /on the camera track itself/.test(html),
    'the page names the route it does NOT take rather than blaming the platform');
  ok(/9c0b105d80212675839a00325b58df55f408f1c0/.test(html),
    'and cites the WebKit commit that added torch support, by hash');

  // a heading is a claim too: "thirteen" was the floor of 13.7, not its rounding
  ok(/One word, fourteen beats a minute/.test(html),
    'the heading rounds the measured 13.7 bpm rather than truncating it');

  // the share card the head tags promise has to exist
  const og2 = (html.match(/<meta property="og:image" content="([^"]+)"/) || [])[1] || '';
  if (og2) {
    const rel = og2.replace(/^https:\/\/artwaste\.land/, '');
    ok(existsSync(join(ROOT, 'public', rel.replace(/^\//, ''))),
      'the og:image the page promises exists on disk: ' + rel);
  }

  // structure
  ok(html.includes('</main>') && html.includes('</body>') && html.includes('</html>'), 'the page closes its tags');
  ok((html.match(/<script/g) || []).length === (html.match(/<\/script>/g) || []).length, 'and its script tags are balanced');
  ok(/role="status"/.test(html) && /aria-live/.test(html), 'the readouts are announced to a screen reader');
  ok(/prefers-reduced-motion/.test(html), 'and reduced motion is honoured');
}

// ══════════════════════════════════════════════════════════════════════════════
section('12b. the reader\'s own control, and the two citations that own this claim');
{
  ok(/steps of <b>2 bpm<\/b>/.test(instrumentJs) || /steps of \*\*2 bpm/.test(instrumentJs),
    'the wrist count states its own resolution: a whole number of beats in 30 s moves in 2 bpm steps');
  ok(/one beat miscounted is 2 bpm/.test(instrumentJs),
    'and says what one miscounted beat costs, so a 2 bpm agreement is not read as confirmation');
  ok(/inside that step, so this is agreement to the resolution of the count and no finer/.test(instrumentJs),
    'and says so in the branch where the two numbers agree, which is the branch where it matters');

  // The direction of this effect is published, and one of the papers disagrees with the page
  // about whether 30 Hz is enough. Both are cited, and the disagreement is on the page rather
  // than in a footnote nobody wrote.
  has('10.1088/1361-6579/aa5efa', 'the page cites Choi and Shin 2017 by DOI:');
  has('10.1016/j.ijcard.2012.03.119', 'and Schafer and Vagedes 2013 by DOI:');
  ok(/may be potentially as reliable as that derived from the analysis of the/.test(html),
    'quoting Choi and Shin\'s own conclusion, which is the one that cuts against this page');
  ok(/real tension with the number above and\s+this page is not going to hide it/.test(html.replace(/\s+/g, ' ').replace(/ /g, ' ')) ||
     /real tension with the number above/.test(html),
    'and naming it as a tension rather than burying it');
  ok(/short-term\s+variability is somewhat overestimated by PRV/.test(html.replace(/\s+/g, ' ')),
    'and quoting the review that says pulse intervals are not the heart\'s own intervals');
  ok(/does not lead anywhere better in the end/.test(html),
    'so the frame-rate buttons are not sold as a route to the true number');

  // The licence has to name every redistributed file, or the "indicate if changes were made"
  // condition is satisfied for some of them and silently not for the rest. This is the check
  // that would have caught shipping the beat annotations without adding them to it.
  const lic = readFileSync(join(SPEC, 'LICENCE'), 'utf8');
  const fromDataset = ['133007_PPG.hea', '133007_PPG.dat', '133007_ECG.hea', '133007_ECG.dat',
    '140067_PPG.hea', '140067_PPG.dat', '130078_PPG.hea', '130078_PPG.dat',
    'butppg-sample.bin', 'butppg-sample.json', 'butppg-qrs.bin', 'butppg-qrs.json',
    'quality-hr-ann.csv', 'subject-info.csv', 'ANNOTATORS'];
  for (const f of fromDataset) {
    const named = lic.includes(f) || (/^\d{6}_/.test(f) && /names begin with a six digit record ID/.test(lic));
    ok(named, 'the licence file accounts for ' + f);
  }
  ok(/Creative Commons Attribution 4.0 International/.test(lic) && /10.13026\/tn53-8153/.test(lic),
    'and names the licence and the DOI it applies to');
  ok(/only the container/.test(lic),
    'and says what was changed, which for the packed bundles is the container and nothing else');
}

// ══════════════════════════════════════════════════════════════════════════════
section('13. the live-sensor case file describes files that exist and cannot be bridged');
{
  ok(caseJson.sensor === 'camera' && caseJson.path === '/strata/ppg-pulse/', 'the case names this page and the camera');
  for (const k of ['anchor', 'control']) ok(existsSync(join(ROOT, caseJson.inject[k].file)), 'the injected ' + k + ' file exists');
  const a = caseJson.inject.anchor, c = caseJson.inject.control;
  ok(Math.abs(a.expect - c.expect) > a.tol + c.tol,
    'the two injected rates are further apart (' + Math.abs(a.expect - c.expect) + ') than the tolerances allow (' + (a.tol + c.tol) + ')');
  ok(a.expect === specs.injections['inject-a'].bpm && c.expect === specs.injections['inject-b'].bpm,
    'and they are the rates the generator was actually given');
  for (const [id, spec] of Object.entries(specs.injections)) {
    const framesPerBeat = (60 / spec.bpm) * spec.fps;
    ok(Math.abs(framesPerBeat - Math.round(framesPerBeat)) < 1e-9,
      id + ' holds a whole number of frames per beat (' + framesPerBeat + '), so Chromium\'s loop cannot splice mid-beat');
  }
  // probeLive must reach the same capture the reader's button reaches
  ok(/probeLive[\s\S]{0,400}captureLive\(/.test(instrumentJs), 'probeLive captures through captureLive(), the reader\'s own path');
  ok((instrumentJs.match(/AW\.sensors\.captureFrames\(/g) || []).length === 2,
    'and there is only one capture implementation on the page (the two calls are the constrained attempt and its fallback)');
  // the estimator must not be able to tell what it is looking at
  const est = instrumentJs.match(/estimate:\s*([^,\n]+)/);
  ok(est && est[1].trim() === 'P.estimate', 'the slate hands AW.anchor the shipped estimator itself, unwrapped', est && est[1]);
  ok(!/isSpecimen|isControl|payload\.expected|payload\.truth|payload\.id\b/.test(readFileSync(join(PAGE, 'ppg.js'), 'utf8')),
    'and the estimator reads nothing that could tell it what it is looking at');
}

console.log('\n' + pass + ' passed, ' + fail + ' failed');
process.exit(fail ? 1 : 0);
