#!/usr/bin/env node
// verify.mjs: the check behind the stratum "It Depends, and Here Is On What"
// (/strata/the-conditional-horse/).
//
//   node research/the-conditional-horse/verify.mjs
//
// WHAT THIS CHECKS, and what it deliberately does not.
//
// The page answers six questions about horses. Most of
// what it says is a reading of the veterinary and behavioural literature, and no
// program can check whether a paper says what a page claims it says: that was
// done by hand, by two adversarial audits per section, and the sources are named
// on the page so a reader can go and disagree. What a program CAN check is the
// part where this page does arithmetic in front of a reader, and that is what is
// here. Six things:
//
//   1. THE FIGURES ARE DECLARED. Every figure in figures.json carries a source
//      and a confidence tier, no figure is left provisional, and no tier is
//      invented. Not every number on the page is a figure: counts, dates and
//      some figures are typed into the prose by hand, and section 2 does not read them.
//   2. THE PAGE PRINTS WHAT THE FIGURES SAY. The numbers the prose takes from
//      figures.json are wrapped in data-fig, and this reads the shipped index.html
//      and compares each one against figures.json. This is the coupling: if someone
//      edits a tagged number and not the data, or the data and not the sentence, the
//      check goes red. Most verifiers in this corpus re-derive a fact without
//      ever looking at the page; this one looks at the page.
//   3. THE VISUAL FIELD DOES NOT CLOSE, BY A STATED AMOUNT. The three figures
//      textbooks print together about the horse are not independent: for two
//      laterally placed eyes, T = 2M - B. Run the canonical set through that
//      identity and it comes up tens of degrees short, which is the section's
//      finding. This asserts the gap is real and is the size the page says.
//   4. THE ONE-SOURCE TEST DISCRIMINATES. Positive and negative controls: a
//      single synthetic voice must pass it and a pair of voices at the published
//      whinny frequencies must fail it. A test that cannot fail measures nothing,
//      so this proves it can do both before the page uses it on a real recording.
//   5. THE ARITHMETIC IS RIGHT. Worked cases for the hoof budget, the sleep
//      budget and the sight line, against values computed by hand in the comments.
//   6. THE MEDIA HAS ITS PAPERS. Every self-hosted asset carries creator, title,
//      institution, a verbatim rights statement, a record URL and a retrieval
//      date, and its licence is one this project is allowed to use.
//
// It imports the page's own engine from public/, which the site serves at
// /strata/the-conditional-horse/engine.mjs. The check and the page cannot drift
// apart, because they are the same file.

import { readFileSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import * as E from '../../public/strata/the-conditional-horse/engine.mjs';

const HERE = dirname(fileURLToPath(import.meta.url));
const PAGE = join(HERE, '../../public/strata/the-conditional-horse');

let pass = 0, fail = 0;
const ok = (name, cond, detail = '') => {
  if (cond) { pass++; console.log(`  ok    ${name}${detail ? `  [${detail}]` : ''}`); }
  else { fail++; console.log(`  FAIL  ${name}${detail ? `  [${detail}]` : ''}`); }
};
const near = (a, b, tol) => Number.isFinite(a) && Number.isFinite(b) && Math.abs(a - b) <= tol;
const head = (s) => console.log(`\n${s}\n${'-'.repeat(s.length)}`);

const FIG = JSON.parse(readFileSync(join(PAGE, 'figures.json'), 'utf8'));
const HTML = readFileSync(join(PAGE, 'index.html'), 'utf8');

// Every key the page's six sections need. Named here so a half-populated data file
// fails as a list of what is missing rather than as a stack trace, and so nothing
// can ship with a section quietly unsourced.
const REQUIRED = [
  'hoof.growth', 'hoof.wear', 'hoof.wallLength', 'hoof.capsuleMonths', 'hoof.cycleDays',
  'hoof.trimThreshold', 'hoof.shoeWearReduction', 'hoof.metabolicCost',
  'eye.panoramic', 'eye.monocular', 'eye.binocular', 'eye.residual', 'eye.monocularNeeded',
  'sleep.total', 'sleep.remNeed', 'sleep.remBout', 'sleep.recumbentTypical', 'sleep.recumbentThreshold',
  'voice.f0', 'voice.g0', 'voice.measuredDeviation', 'voice.oneVoiceDeviation', 'voice.twoVoiceDeviation',
  'mane.studies', 'mane.erectRows', 'mane.fallingRows',
  'police.mountedEyeHeight', 'police.footEyeHeight', 'police.crowdHeight', 'police.engagementRatio',
];
const absent = REQUIRED.filter((k) => !FIG.figures[k]);
if (absent.length) {
  console.error(`verify: figures.json is missing ${absent.length} required figure(s):`);
  for (const k of absent) console.error(`  - ${k}`);
  console.error('\nThe page cannot ship until every section names its sources.');
  process.exit(1);
}

// ─────────────────────────────────────────────────────────────────────────────
head('1. the figures are declared, sourced, and not provisional');

const TIERS = new Set(Object.keys(FIG.meta.tiers));
const figs = Object.entries(FIG.figures);
ok('figures.json carries figures at all', figs.length > 0, `${figs.length} figures`);

const provisional = figs.filter(([, v]) => v.provisional);
ok('no figure is still marked provisional', provisional.length === 0,
  provisional.length ? provisional.map(([k]) => k).join(', ') : 'all settled');

const unsourced = figs.filter(([, v]) => !v.source || !String(v.source).trim());
ok('every figure names a source', unsourced.length === 0,
  unsourced.length ? unsourced.map(([k]) => k).join(', ') : `${figs.length}/${figs.length}`);

const badTier = figs.filter(([, v]) => !TIERS.has(v.tier));
ok('every figure carries a declared confidence tier', badTier.length === 0,
  badTier.length ? badTier.map(([k]) => `${k}=${k[1]?.tier}`).join(', ') : [...TIERS].join('/'));

const badRange = figs.filter(([, v]) =>
  v.low != null && v.high != null && !(v.low <= v.typical && v.typical <= v.high));
ok('every stated typical value lies inside its own published range', badRange.length === 0,
  badRange.length ? badRange.map(([k]) => k).join(', ') : 'all inside');

const tierCount = {};
for (const [, v] of figs) tierCount[v.tier] = (tierCount[v.tier] ?? 0) + 1;
console.log(`        tiers: ${Object.entries(tierCount).map(([k, n]) => `${n} ${k}`).join(', ')}`);

// ─────────────────────────────────────────────────────────────────────────────
head('2. the page prints what the figures say');

// Every number the prose takes from figures.json is wrapped as
// <span data-fig="key" data-dp="n">value</span>; an untagged number is not read here.
// A page that says one thing and a data file that says another is exactly the
// failure this project claims not to have, and it is cheap to make impossible.
// Attribute order varies as prose is edited, so each reference is picked up whole
// and then read apart. An order-sensitive pattern here would silently stop
// checking the numbers it could not parse, which is the worst way for a gate to fail.
const refs = [...HTML.matchAll(/<span ([^>]*data-fig="[^"]+"[^>]*)>([^<]*)</g)].map((m) => {
  const attrs = m[1];
  const get = (n) => (attrs.match(new RegExp(n + '="([^"]*)"')) ?? [])[1];
  return { key: get('data-fig'), dp: get('data-dp'), part: get('data-part'), shown: m[2] };
});
ok('the page carries data-fig references', refs.length > 0, `${refs.length} references`);

let mismatched = 0, unknown = 0;
for (const { key, dp, part, shown } of refs) {
  const f = FIG.figures[key];
  if (!f) { unknown++; console.log(`  FAIL  unknown figure key in the page: ${key}`); fail++; continue; }
  const want = part ? f[part] : f.typical;
  if (want == null) {
    unknown++;
    console.log(`  FAIL  ${key} has no ${part ?? 'typical'} value in figures.json`);
    fail++; continue;
  }
  const places = dp != null ? Number(dp) : 0;
  const printed = String(want.toFixed ? want.toFixed(places) : want);
  const seen = shown.trim().replace(/,/g, '');
  if (seen !== printed) {
    mismatched++;
    console.log(`  FAIL  ${key}${part ? '.' + part : ''}: page says "${seen}", figures.json says "${printed}"`);
    fail++;
  }
}
ok('every tagged number in the prose matches its figure', mismatched === 0 && unknown === 0,
  `${refs.length - mismatched - unknown}/${refs.length} agree`);

// The index at the top of the page promises the reader six questions, each with a
// section that answers it. A promise a reader acts on by clicking is worth
// checking: every entry must name its question once, in order, and its link must
// land on a section whose heading is that same question.
//
// Until 2026-09-23 this block asserted instead that fourteen search phrasings of
// those questions, two misspellings among them, appeared on the page verbatim.
// That was scaffolding aimed at search engines, and it had leaked into the prose
// as headings and asides about spelling. It came out at the human's word: a page
// that is explicitly about its own search optimisation was never the goal.
const QUESTIONS = [
  ['q1', 'Why do horses need horseshoes?'],
  ['q2', 'Why do horses wear blinders?'],
  ['q3', 'Why do horses sleep standing up?'],
  ['q4', 'Why do horses neigh?'],
  ['q5', 'Why do horses have manes?'],
  ['q6', 'Why do police use horses?'],
];
const textOf = (s) => s.replace(/<[^>]+>/g, '').replace(/&#39;|&rsquo;|&apos;/g, "'")
  .replace(/&amp;/g, '&').replace(/\s+/g, ' ').trim();
const indexNav = (HTML.match(/<nav class="index[^"]*"[^>]*>([\s\S]*?)<\/nav>/) ?? [])[1] ?? '';
const entries = [...indexNav.matchAll(/<a href="#(q\d+)">\s*<span class="q">([\s\S]*?)<\/span>/g)]
  .map((m) => [m[1], textOf(m[2])]);
ok('the index lists the six questions, once each, in order',
  JSON.stringify(entries) === JSON.stringify(QUESTIONS),
  entries.map(([id, q]) => `${id} ${q}`).join(' | ') || 'no index found');

// A section holds nested <section> instruments, so it cannot be cut out by
// matching to its closing tag. Its own heading is the first <h2> after it opens.
const misdirected = QUESTIONS.filter(([id, q]) => {
  const at = HTML.indexOf(`<section class="q col" id="${id}">`);
  if (at < 0) return true;
  const h2 = (HTML.slice(at).match(/<h2[^>]*>([\s\S]*?)<\/h2>/) ?? [])[1];
  return !h2 || textOf(h2) !== q;
});
ok('every entry in the index lands on the section that answers it', misdirected.length === 0,
  misdirected.length ? misdirected.map(([id]) => id).join(', ') : `${QUESTIONS.length}/${QUESTIONS.length}`);

// ─────────────────────────────────────────────────────────────────────────────
head('3. the visual field: the three published numbers do not close, and by how much');

{
  // The geometry first, on its own, with no horse in it. Two arcs of width M
  // centred at plus and minus A degrees: the union is M + 2A and the frontal
  // intersection is M - 2A. Equivalently, in the units the literature uses,
  // T = 2M - B. These are identities, and they are what makes the published set
  // checkable at all.
  ok('arc union of two disjoint arcs adds up',
    near(E.extent(E.unionArcs([E.arcFrom(0, 40), E.arcFrom(180, 40)])), 80, 1e-9));
  ok('arc union of two overlapping arcs does not double count',
    near(E.extent(E.unionArcs([E.arcFrom(0, 90), E.arcFrom(45, 90)])), 135, 1e-9));
  ok('subtracting an arc from the whole circle leaves the rest',
    near(E.extent(E.subtractArcs([[0, 360]], [E.arcFrom(180, 30)])), 330, 1e-9));

  const M = FIG.figures['eye.monocular'].typical;
  const B = FIG.figures['eye.binocular'].typical;
  const pubPan = FIG.figures['eye.panoramic'].typical;
  const A = (M - B) / 2;
  const f = E.visualField(M, A);

  ok('the closed form T = M + 2A holds in the arc model', near(f.panoramicDeg, M + 2 * A, 1e-9),
    `${f.panoramicDeg.toFixed(1)} deg`);
  ok('and it is the same statement as T = 2M - B', near(f.panoramicDeg, 2 * M - B, 1e-9),
    `${(2 * M - B).toFixed(1)} deg`);
  ok('the frontal binocular wedge comes out at the published overlap',
    near(f.binocularFrontDeg, B, 1e-9), `${f.binocularFrontDeg.toFixed(1)} deg`);
  ok('the blind arc behind is what is left over',
    near(f.blindDeg, 360 - f.panoramicDeg, 1e-9), `${f.blindDeg.toFixed(1)} deg`);

  // THE FINDING. The three figures the textbooks and reviews print side by side
  // are not independent measurements: any two fix the third. Run the published
  // set through the identity and it does not close. The page says so, and this
  // asserts the gap is really there and really that size, so the claim on the
  // page is checked rather than asserted.
  const c = E.fieldConsistency({ panoramicDeg: pubPan, monocularDeg: M, binocularDeg: B });
  ok('the canonical published triad does NOT close', !c.closes,
    `published total ${pubPan}, implied ${c.impliedPanoramic.toFixed(1)}, short by ${c.residualDeg.toFixed(1)} deg`);
  ok('the gap is the size the page states',
    near(c.residualDeg, FIG.figures['eye.residual'].typical, 0.51),
    `${c.residualDeg.toFixed(1)} vs stated ${FIG.figures['eye.residual'].typical}`);
  ok('the monocular field the published total would need is larger than the published monocular field',
    c.monocularNeededForPanoramic > FIG.figures['eye.monocular'].typical,
    `needs ${c.monocularNeededForPanoramic.toFixed(1)}, published ${FIG.figures['eye.monocular'].typical}`);
  ok('and larger than every value in the published monocular RANGE except its extreme',
    c.monocularNeededForPanoramic > FIG.figures['eye.monocular'].low,
    `needs ${c.monocularNeededForPanoramic.toFixed(1)}, range ${FIG.figures['eye.monocular'].low} to ${FIG.figures['eye.monocular'].high}`);

  // Worked by hand, so a reader can check the checker:
  //   M = 195, B = 65  ->  T = 2*195 - 65 = 325, which is 25 short of 350.
  //   To reach 350 with B = 65 you need M = (350 + 65) / 2 = 207.5.
  const hand = E.fieldConsistency({ panoramicDeg: 350, monocularDeg: 195, binocularDeg: 65 });
  ok('worked by hand: 195 and 65 imply 325', near(hand.impliedPanoramic, 325, 1e-9));
  ok('worked by hand: 350 would need a monocular field of 207.5',
    near(hand.monocularNeededForPanoramic, 207.5, 1e-9));
  ok('worked by hand: or a binocular overlap of 40', near(hand.binocularNeededForPanoramic, 40, 1e-9));

  // Every device on the page must remove a bounded arc or declare that it removes
  // none, and must say, in its own row, that nobody has measured it.
  const deviceProblems = [];
  for (const d of FIG.devices) {
    if (!d.tier || !TIERS.has(d.tier)) deviceProblems.push(`${d.id} has no declared tier`);
    if (!d.source) deviceProblems.push(`${d.id} has no source`);
    if (!d.measured) deviceProblems.push(`${d.id} does not say whether it has been measured`);
    if (!d.targets) deviceProblems.push(`${d.id} does not say what it targets`);
    if (d.cuts.length) {
      const worn = E.wearDevice(f, d.cuts);
      if (!(worn.lostDeg > 0)) deviceProblems.push(`${d.id} claims a cut and removes nothing`);
      if (worn.panoramicDeg < 0) deviceProblems.push(`${d.id} removes more than exists`);
    }
  }
  ok('every eye covering is declared, sourced, and honest about being unmeasured',
    deviceProblems.length === 0,
    deviceProblems.length ? deviceProblems.join('; ') : `${FIG.devices.length} devices`);
  const unmeasured = FIG.devices.filter((d) => /never|not measured|none/i.test(d.measured)).length;
  console.log(`        ${unmeasured}/${FIG.devices.length} devices have no published measurement of what they remove`);
}

head('4. the two-voices test can pass, can fail, and says the same about the real recording');

{
  const SR = 44100;

  // POSITIVE CONTROL. One harmonic stack with heavy vibrato. However far the
  // pitch slides, the whole stack slides with it, so the ratio between any two
  // of its components is a fixed whole number.
  const one = E.synthVibrato({
    sampleRate: SR, seconds: 2, voices: [{ f0: 560, depth: 0.06, rateHz: 5, harmonics: 9 }],
  });
  const lockOne = E.harmonicLock(one, SR);
  ok('POSITIVE CONTROL: one synthesised voice locks', lockOne.locked === true,
    `mean deviation ${lockOne.meanDeviation.toFixed(4)}, ratio ${lockOne.ratioMin.toFixed(2)} to ${lockOne.ratioMax.toFixed(2)}, ${lockOne.n} frames`);
  ok('and it locks hard, not marginally', lockOne.meanDeviation < 0.02,
    `${lockOne.meanDeviation.toFixed(4)}`);
  ok('the page prints that control correctly',
    near(lockOne.meanDeviation, FIG.figures['voice.oneVoiceDeviation'].typical, 0.0015),
    `${lockOne.meanDeviation.toFixed(4)} vs printed ${FIG.figures['voice.oneVoiceDeviation'].typical}`);

  // NEGATIVE CONTROL. Two stacks sliding independently.
  const two = E.synthVibrato({
    sampleRate: SR, seconds: 2,
    voices: [
      { f0: 560, depth: 0.06, rateHz: 5, harmonics: 6 },
      { f0: 1750, depth: 0.10, rateHz: 3.1, phase: 1.2, harmonics: 3, gain: 0.8 },
    ],
  });
  const lockTwo = E.harmonicLock(two, SR);
  ok('NEGATIVE CONTROL: two independent voices do not lock', lockTwo.locked === false,
    `mean deviation ${lockTwo.meanDeviation.toFixed(4)}, ratio ${lockTwo.ratioMin.toFixed(2)} to ${lockTwo.ratioMax.toFixed(2)}`);
  ok('the page prints that control correctly',
    near(lockTwo.meanDeviation, FIG.figures['voice.twoVoiceDeviation'].typical, 0.01),
    `${lockTwo.meanDeviation.toFixed(4)} vs printed ${FIG.figures['voice.twoVoiceDeviation'].typical}`);
  ok('the two controls are far apart, so the test measures something',
    lockTwo.meanDeviation / lockOne.meanDeviation > 20,
    `${(lockTwo.meanDeviation / lockOne.meanDeviation).toFixed(0)} times`);

  // THE REAL RECORDING, through the same code, off the bytes the site serves.
  // Read unconditionally on purpose. An existsSync guard would turn a missing
  // file into a quiet failed assertion, and the source mirror's prover discovers
  // a check's real dependencies by watching what it throws ENOENT on. A guard
  // here would hide this file from the recipe a reader is handed.
  const wavPath = join(PAGE, 'media/whinny-briefer-2015.wav');
  {
    const wav = E.decodeWav(readFileSync(wavPath));
    ok('the recording decodes as published: mono, 44.1 kHz',
      wav.sampleRate === 44100 && wav.channels === 1, `${wav.sampleRate} Hz, ${wav.channels} channel`);
    const lockReal = E.harmonicLock(wav.samples, wav.sampleRate);
    ok('the real whinny does NOT lock', lockReal.locked === false,
      `mean deviation ${lockReal.meanDeviation.toFixed(4)}, ratio ${lockReal.ratioMin.toFixed(2)} to ${lockReal.ratioMax.toFixed(2)}, ${lockReal.n} frames`);
    ok('and the page prints the figure this run measures',
      near(lockReal.meanDeviation, FIG.figures['voice.measuredDeviation'].typical, 0.01),
      `${lockReal.meanDeviation.toFixed(4)} vs printed ${FIG.figures['voice.measuredDeviation'].typical}`);
    ok('the real recording sits with the two-voice control, not the one-voice control',
      Math.abs(lockReal.meanDeviation - lockTwo.meanDeviation)
      < Math.abs(lockReal.meanDeviation - lockOne.meanDeviation),
      `real ${lockReal.meanDeviation.toFixed(3)}, two-voice ${lockTwo.meanDeviation.toFixed(3)}, one-voice ${lockOne.meanDeviation.toFixed(3)}`);
  }

  // The FFT itself, against a signal whose spectrum is known exactly.
  const tone = new Float64Array(1024);
  for (let i = 0; i < 1024; i++) tone[i] = Math.sin((2 * Math.PI * 1000 * i) / 8000);
  const p = E.spectralPeaks(E.magnitudeSpectrum(tone), 8000, { maxPeaks: 3 });
  ok('the FFT finds a pure tone where it was put', p.length >= 1 && near(p[0].f, 1000, 12),
    `${p[0] ? p[0].f.toFixed(1) : 'nothing'} Hz`);
}

head('5. the arithmetic, against cases worked by hand');

{
  // HOOF. Malone and Davies' shod Quarter Horse mares: growth 0.197 mm/day, wear
  // 0.059 mm/day, an 80 mm dorsal wall, a 42-day cycle.
  //   net per day    = 0.197 - 0.059                 = 0.138 mm/day
  //   over the cycle = 0.138 * 42                    = 5.796 mm
  //   per month      = 0.138 * 30.436875             = 4.200 mm
  //   capsule        = 80 / 0.197                    = 406.1 days = 13.34 months
  const h = E.hoofBudget({ growthMmPerDay: 0.197, wearMmPerDay: 0.059, wallLengthMm: 80, cycleDays: 42 });
  ok('hoof: net rate', near(h.netMmPerDay, 0.138, 1e-12), `${h.netMmPerDay.toFixed(4)} mm/day`);
  ok('hoof: growth over a 42-day cycle', near(h.netMmOverCycle, 0.138 * 42, 1e-9),
    `${h.netMmOverCycle.toFixed(4)} mm`);
  ok('hoof: the per-month conversion', near(h.netMmPerMonth, 0.138 * E.DAYS_PER_MONTH, 1e-9),
    `${h.netMmPerMonth.toFixed(3)} mm/month`);
  ok('hoof: whole-capsule replacement', near(h.capsuleDays, 80 / 0.197, 1e-9),
    `${h.capsuleDays.toFixed(1)} days, ${h.capsuleMonths.toFixed(2)} months`);
  ok('hoof: a surplus is called a surplus', h.verdict === 'surplus');
  // Florence and McDonnell's high-wear semi-feral ponies: the published deficit case.
  const h2 = E.hoofBudget({ growthMmPerDay: 0.35, wearMmPerDay: 0.52, wallLengthMm: 80, cycleDays: 42 });
  ok('hoof: wear above growth is a deficit', h2.verdict === 'deficit',
    `${h2.netMmPerDay.toFixed(3)} mm/day, ${h2.netMmPerMonth.toFixed(2)} mm/month`);
  const h3 = E.hoofBudget({ growthMmPerDay: 0.25, wearMmPerDay: 0.25, wallLengthMm: 80, cycleDays: 42 });
  ok('hoof: equal rates balance', h3.verdict === 'balanced');
  ok('hoof: a balanced budget never reaches a threshold',
    !Number.isFinite(h3.daysToReach(5)) || h3.daysToReach(5) === Infinity);

  // The published growth rate and the published wall length must together imply
  // a replacement time inside the separately published replacement range. Two
  // independent measurements of the same animal, made to agree.
  const g = FIG.figures['hoof.growth'], L = FIG.figures['hoof.wallLength'], R = FIG.figures['hoof.capsuleMonths'];
  const impliedFast = L.typical / g.high / E.DAYS_PER_MONTH;
  const impliedSlow = L.typical / g.low / E.DAYS_PER_MONTH;
  ok('published growth and wall length bracket the published replacement time',
    impliedFast <= R.typical && impliedSlow >= R.typical,
    `implied ${impliedFast.toFixed(1)} to ${impliedSlow.toFixed(1)} months, published ${R.typical}`);

  // SLEEP. Thirty minutes of lying down, against a stated need of forty minutes
  // of paradoxical sleep.
  //   occupancy = 40 / 30 = 1.3333..., i.e. 133 per cent of the lying-down time
  //   shortfall = 40 - 30 = 10 minutes
  const s = E.sleepBudget({ remNeedMin: 40, recumbentMin: 30, remBoutMin: 3.72 });
  ok('sleep: the occupancy that thirty minutes would need', near(s.occupancy, 4 / 3, 1e-9),
    `${(s.occupancy * 100).toFixed(1)} per cent`);
  ok('sleep: and it is therefore not possible', s.feasible === false);
  ok('sleep: the shortfall', near(s.shortfallMin, 10, 1e-9), `${s.shortfallMin} min`);
  ok('sleep: bouts needed at the published bout length', near(s.boutsNeeded, 40 / 3.72, 1e-9),
    `${s.boutsNeeded.toFixed(2)}`);
  const s0 = E.sleepBudget({ remNeedMin: 40, recumbentMin: 0, remBoutMin: 3.72 });
  ok('sleep: a horse that never lies down gets none of this stage',
    s0.remPossibleMin === 0 && !s0.feasible);
  const s9 = E.sleepBudget({ remNeedMin: 40, recumbentMin: 120, remBoutMin: 3.72 });
  ok('sleep: ample recumbency makes it possible and does not overshoot',
    s9.feasible && near(s9.remPossibleMin, 40, 1e-9) && near(s9.shortfallMin, 0, 1e-9));

  // And the same arithmetic on the PUBLISHED pair, which is the section's claim.
  const pub = E.sleepBudget({
    remNeedMin: FIG.figures['sleep.remNeed'].typical,
    recumbentMin: FIG.figures['sleep.recumbentThreshold'].typical,
    remBoutMin: FIG.figures['sleep.remBout'].typical,
  });
  ok('THE FINDING: the welfare threshold cannot hold the paradoxical sleep it was derived from',
    pub.feasible === false,
    `${FIG.figures['sleep.remNeed'].typical} min of REM into ${FIG.figures['sleep.recumbentThreshold'].typical} min of lying down needs ${(pub.occupancy * 100).toFixed(0)} per cent of it`);
  ok('and the page prints that percentage',
    near(pub.occupancy * 100, FIG.figures['sleep.occupancyAtThreshold'].typical, 0.6),
    `${(pub.occupancy * 100).toFixed(1)} vs printed ${FIG.figures['sleep.occupancyAtThreshold'].typical}`);
  ok('even the lowest published paradoxical-sleep figure fills most of the threshold',
    E.sleepBudget({ remNeedMin: FIG.figures['sleep.remNeed'].low, recumbentMin: 30, remBoutMin: 3.72 }).occupancy > 0.7,
    `${(E.sleepBudget({ remNeedMin: FIG.figures['sleep.remNeed'].low, recumbentMin: 30, remBoutMin: 3.72 }).occupancy * 100).toFixed(0)} per cent`);

  // SIGHT LINE. Eye at 2.90 m, heads at 1.70 m, nearest at 2.0 m.
  //   d = 2.0 * 2.90 / (2.90 - 1.70) = 5.80 / 1.20 = 4.8333... m
  const sl = E.sightLine({ eyeHeightM: 2.90, obstacleHeightM: 1.70, nearestObstacleM: 2.0 });
  ok('sight line: the ground reappears where similar triangles say',
    near(sl.seesGroundAtM, 2.0 * 2.9 / 1.2, 1e-9), `${sl.seesGroundAtM.toFixed(4)} m`);
  const flat = E.sightLine({ eyeHeightM: 1.65, obstacleHeightM: 1.70, nearestObstacleM: 2.0 });
  ok('sight line: below the crowd there is no solution at any distance',
    flat.canSeeOver === false && flat.seesGroundAtM === Infinity);
  const equal = E.sightLine({ eyeHeightM: 1.70, obstacleHeightM: 1.70, nearestObstacleM: 2.0 });
  ok('sight line: exactly level with the crowd is still no solution', equal.canSeeOver === false);
  ok('sight line: raising the eye brings the ground nearer',
    E.sightLine({ eyeHeightM: 3.0, obstacleHeightM: 1.7, nearestObstacleM: 2 }).seesGroundAtM
    < E.sightLine({ eyeHeightM: 2.5, obstacleHeightM: 1.7, nearestObstacleM: 2 }).seesGroundAtM);
}

// ─────────────────────────────────────────────────────────────────────────────
head('6. the comparative table, and the evidence audit');

{
  const s = E.maneSummary(FIG.equids);
  ok('every equid row names a source', s.unsourced.length === 0,
    s.unsourced.length ? s.unsourced.join(', ') : `${s.total} rows`);
  ok('the table holds the number of rows the page claims',
    s.total === FIG.meta.equidRows, `${s.total} rows against ${FIG.meta.equidRows} claimed`);
  ok('every mane form is one the table declares',
    FIG.equids.every((r) => ['erect', 'falling', 'variable'].includes(r.mane)));
  ok('the mane counts add up', s.erect + s.falling + s.variable === s.total,
    `${s.erect} erect, ${s.falling} falling, ${s.variable} variable`);
  ok('and the page prints those counts',
    s.erect === FIG.figures['mane.erectRows'].typical && s.falling === FIG.figures['mane.fallingRows'].typical);
  ok('THE FINDING: not one of the offered explanations has ever been tested',
    E.evidenceSummary(FIG.maneHypotheses).tested === FIG.figures['mane.studies'].typical,
    `${E.evidenceSummary(FIG.maneHypotheses).tested} tested of ${FIG.maneHypotheses.length}`);

  const es = E.evidenceSummary(FIG.maneHypotheses);
  ok('every mane hypothesis carries an evidence tier',
    FIG.maneHypotheses.every((h) => ['tested', 'indirect', 'untested'].includes(h.tier)),
    `${es.tested} tested, ${es.indirect} indirect, ${es.untested} untested`);
  ok('every mane hypothesis says what would settle it',
    FIG.maneHypotheses.every((h) => h.wouldBeTestedBy && h.whatExists));
}

// ─────────────────────────────────────────────────────────────────────────────
head('7. the media has its papers');

{
  const mediaPath = join(PAGE, 'media/media.json');
  {
    const M = JSON.parse(readFileSync(mediaPath, 'utf8'));
    // Written as the institutions actually write them, which is not uniformly.
    // Wellcome says "Public Domain Mark", Erfgoed Leiden says "CC-0" with a
    // hyphen, Commons says "Creative Commons Attribution 2.0". A pattern that
    // only knows the tidy spellings silently passes the ones it cannot read.
    const ALLOWED = [
      /public domain/i, /\bCC[ -]?0\b/i, /Creative Commons Zero/i,
      /\bCC[ -]BY\b(?!-NC|-ND)/i, /Creative Commons Attribution(?!-NonCommercial|-NoDerivs)/i,
    ];
    const REFUSED = [/non-?commercial/i, /\bNC\b/, /NoDeriv/i, /\bND\b/, /all rights reserved/i];
    const need = ['what', 'creator', 'title', 'institution', 'rights', 'recordUrl', 'retrieved', 'alt'];
    let bad = [];
    for (const a of M.assets) {
      if (a.error) { bad.push(`${a.file}: did not download`); continue; }
      for (const k of need) if (!a[k] || !String(a[k]).trim()) bad.push(`${a.file}: no ${k}`);
      if (a.rights && !ALLOWED.some((r) => r.test(a.rights))) bad.push(`${a.file}: rights not in the allowed set`);
      if (a.rights && REFUSED.some((r) => r.test(a.rights))) bad.push(`${a.file}: a refused licence term`);
      if (a.kind !== 'audio' && a.bytes > 400_000) bad.push(`${a.file}: ${Math.round(a.bytes / 1024)} KB is over budget`);
    }
    ok('every asset carries the full provenance block and a licence we may use',
      bad.length === 0, bad.length ? bad.slice(0, 5).join('; ') : `${M.assets.length} assets`);
    const total = M.assets.reduce((t, a) => t + (a.bytes ?? 0), 0);
    ok('the page carries its media rather than hotlinking it, at a sane weight',
      total > 0 && total < 4 * 1024 * 1024, `${(total / 1024 / 1024).toFixed(2)} MiB`);
    const inPage = M.assets.filter((a) => HTML.includes(`media/${a.file}`)).length;
    console.log(`        ${inPage}/${M.assets.length} assets are actually referenced by the page`);
  }
}

// ─────────────────────────────────────────────────────────────────────────────
console.log(`\n${pass + fail} checks, ${pass} passed, ${fail} failed.`);
if (fail) {
  console.error('verify: FAILED. The page must not ship in this state.');
  process.exit(1);
}
console.log('verify: ok. Every number the page tags as a figure is the number figures.json declares,');
console.log('and every derivation it shows a reader reproduces here.');
