#!/usr/bin/env node
// verify-ombak.mjs: the gate for /strata/<slug>/.
//
//   node research/ombak/verify-ombak.mjs
//
// Re-derives every number the page prints and exits non-zero on any failure.
//
// The page makes three kinds of claim and this file checks each in its own way:
//
//   EXACT      the forced-trade identity and its two corollaries. Checked by hand on
//              worked cases, then over a randomised sweep of ten thousand pairs, then
//              against a second, independent implementation written from the definition
//              rather than from the algebra.
//   MEASURED   the meter, run on signals whose true beat rate is known by construction,
//              including cases it must REFUSE. A meter that never refuses is not a
//              meter, so the refusals are checked as carefully as the readings.
//   QUOTED     what the literature says. Verbatim strings, checked to be present on the
//              page exactly as this file holds them, so an edit to either side fails.
//
// It also carries NEGATIVE CONTROLS: mutations that must break it. A gate that cannot
// fail has not been tested.

import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import { fileURLToPath } from 'node:url';
import * as E from './engine.mjs';
import { QUOTES, SOURCE_FILES, findings } from './findings.mjs';
import { CLIPS } from './prepare-audio.mjs';
import { readWav } from './kit.mjs';

const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.join(HERE, '..', '..');
export const SLUG = 'one-scale-or-one-shimmer';
export { QUOTES, SOURCE_FILES, findings };
const PAGE = path.join(ROOT, 'public', 'strata', SLUG, 'index.html');
const PAGE_ENGINE = path.join(ROOT, 'public', 'strata', SLUG, 'engine.mjs');

let pass = 0, fail = 0;
const ok = (cond, msg) => { cond ? pass++ : fail++; console.log(`  ${cond ? '✓' : '✗ FAIL'}  ${msg}`); };
const near = (a, b, e, msg) => ok(Math.abs(a - b) <= e, `${msg}  (${fmt(a)} vs ${fmt(b)}, tol ${e})`);
const fmt = (v) => (typeof v === 'number' ? (Math.abs(v) >= 1e-4 || v === 0 ? v.toFixed(6).replace(/0+$/, '').replace(/\.$/, '') : v.toExponential(3)) : String(v));

// A second implementation of the same quantity, written from the DEFINITION and not
// from the algebra the engine uses. If the engine's closed form is wrong, this disagrees.
function spanDifferenceFromScratch(u1, d1, u2, d2) {
  const ln2 = Math.log(2);
  const centsBetween = (a, b) => 1200 * (Math.log(b) - Math.log(a)) / ln2;
  return centsBetween(u1, u2) - centsBetween(u1 + d1, u2 + d2);
}

// A deterministic generator, so a failure is reproducible.
function lcg(seed) {
  let s = seed >>> 0;
  return () => { s = (s * 1664525 + 1013904223) >>> 0; return s / 4294967296; };
}

// ─────────────────────────────────────────────── 1. the cents helpers
console.log('\n1. the cents helpers, on cases with known answers');
near(E.spanCents(100, 200), 1200, 1e-12, 'a doubling is 1200 cents');
near(E.spanCents(100, 150), 701.955, 1e-3, 'a perfect fifth is 701.955 cents');
near(E.byCents(440, 1200), 880, 1e-9, 'byCents inverts spanCents');
near(E.ombakCents(125, 8), 107.4, 0.05, '8 Hz at 125 Hz opens about 107 cents');
near(E.ombakCents(2000, 8), 6.9, 0.05, '8 Hz at 2000 Hz opens about 7 cents');
near(E.ombakHz(400, E.ombakCents(400, 8)), 8, 1e-9, 'ombakHz inverts ombakCents');
{
  let threw = false;
  try { E.spanCents(0, 100); } catch (e) { threw = true; }
  ok(threw, 'a zero frequency is rejected rather than returning -Infinity');
  threw = false;
  try { E.ombakCents(100, -100); } catch (e) { threw = true; }
  ok(threw, 'a detuning that would put the pengisep at zero is rejected');
}

// ─────────────────────────────────────────────── 2. the identity, by hand
console.log('\n2. the forced-trade identity, on worked cases');
{
  // A pengumbang with an exact octave, 250 to 500 Hz, and 8 Hz of ombak held at both.
  const t = E.trade(250, 8, 500, 8);
  near(t.umbang, 1200, 1e-12, 'the pengumbang octave is exactly 2:1 by construction');
  near(t.isep, 1172.9489, 1e-3, 'the pengisep octave is then 1172.95 cents, 27 cents narrow');
  near(t.difference, t.viaOmbak, 1e-9, 'the two ways of computing the excess agree');
  near(t.difference, spanDifferenceFromScratch(250, 8, 500, 8), 1e-9,
    'and a third implementation, written from the definition, agrees too');
  near(t.difference, t.ombak1 - t.ombak2, 1e-12,
    'the excess IS the amount the shimmer narrows across the octave');
}
{
  // The same trade at the top of the range, where it nearly vanishes.
  const t = E.trade(1000, 8, 2000, 8);
  near(t.difference, 6.8836, 1e-3, 'the same 8 Hz costs only 6.88 cents two octaves higher');
  ok(t.difference > 0, 'but it is still strictly positive');
}

// ─────────────────────────────────────────────── 3. the identity, swept
console.log('\n3. the identity and its corollaries, over ten thousand random pairs');
{
  const rnd = lcg(20260901);
  let worstResidual = 0, worstScratch = 0, minGap = Infinity, maxEqual = 0;
  let checkedHz = 0, checkedInterval = 0;
  for (let i = 0; i < 10000; i++) {
    const u1 = 50 + rnd() * 2000;
    const u2 = u1 * (1 + 0.05 + rnd() * 6);      // anywhere from a small step to 3 octaves up
    const d = 0.2 + rnd() * 30;                   // ombak from a slow sway to a rough buzz

    // corollary 1: the same rate at both keys forces the umbang span strictly wider
    const th = E.trade(u1, d, u2, d);
    worstResidual = Math.max(worstResidual, Math.abs(th.residual));
    worstScratch = Math.max(worstScratch, Math.abs(th.difference - spanDifferenceFromScratch(u1, d, u2, d)));
    if (th.difference <= 0) minGap = -1; else minGap = Math.min(minGap, th.difference);
    checkedHz++;

    // corollary 2: the same INTERVAL at both keys makes the two spans equal
    const d2 = E.detuneUnder('interval', u1, d, u2);
    const ti = E.trade(u1, d, u2, d2);
    maxEqual = Math.max(maxEqual, Math.abs(ti.difference));
    checkedInterval++;
  }
  ok(checkedHz === 10000 && checkedInterval === 10000, 'both corollaries were tested on all 10,000 draws');
  ok(worstResidual < 1e-9, `the identity holds to ${worstResidual.toExponential(2)} cents at worst`);
  ok(worstScratch < 1e-9, `the independent implementation agrees to ${worstScratch.toExponential(2)} cents at worst`);
  ok(minGap > 0, `constant hertz always leaves the pengumbang span strictly wider (smallest excess ${fmt(minGap)} cents)`);
  ok(maxEqual < 1e-9, `constant interval always makes the two spans equal (largest disagreement ${maxEqual.toExponential(2)} cents)`);
}

// ─────────────────────────────────────────────── 4. the corollary is an "only if" too
console.log('\n4. equal scales force a constant interval, and nothing else does');
{
  // If the two members carry the same scale across a set of keys, then d/f is the same
  // at every key. Check the contrapositive numerically: perturb one key's detuning away
  // from the constant-interval value and the ladders must come apart.
  const set = E.tuneSet({ base: 300, ladder: [...E.LADDERS.begbeg.cents], octaves: 3, policy: 'interval', ombak: 8 });
  const g = E.ladderGap(set);
  ok(Math.abs(g.worst) < 1e-9, `under constant interval the two ladders are identical (worst gap ${g.worst.toExponential(2)} cents)`);

  const bent = JSON.parse(JSON.stringify(set));
  bent.keys[7].isep = bent.keys[7].umbang + bent.keys[7].beatHz * 1.05;   // 5% off, one key
  const gb = E.ladderGap(bent);
  ok(Math.abs(gb.worst) > 0.05, `bending one key's detuning by 5% pulls the ladders apart by ${fmt(Math.abs(gb.worst))} cents`);
}

// ─────────────────────────────────────────────── 5. the two policies over a real ladder
console.log('\n5. the two policies laid out over a real Balinese ladder');
{
  const base = 150, ombak = 8, octaves = 3;
  const hz = E.tuneSet({ base, ladder: [...E.LADDERS.begbeg.cents], octaves, policy: 'hertz', ombak });
  const iv = E.tuneSet({ base, ladder: [...E.LADDERS.begbeg.cents], octaves, policy: 'interval', ombak });

  ok(hz.keys.length === 15 && iv.keys.length === 15, 'three octaves of a five-tone ladder is fifteen keys');
  near(hz.keys[0].beatHz, 8, 1e-12, 'both policies are anchored at 8 Hz on the lowest key');
  near(iv.keys[0].beatHz, 8, 1e-12, 'both policies are anchored at 8 Hz on the lowest key (interval)');

  const topHz = hz.keys[hz.keys.length - 1];
  const topIv = iv.keys[iv.keys.length - 1];
  near(topHz.beatHz, 8, 1e-12, 'holding hertz: the top key still beats at 8 Hz');
  ok(topIv.beatHz > 45 && topIv.beatHz < 55,
    `holding the interval: the top key beats at ${fmt(topIv.beatHz)} Hz instead, far past shimmer and into roughness`);
  ok(topHz.beatCents < 15 && hz.keys[0].beatCents > 80,
    `holding hertz: the gap falls from ${fmt(hz.keys[0].beatCents)} cents at the bottom to ${fmt(topHz.beatCents)} at the top`);

  const gHz = E.ladderGap(hz), gIv = E.ladderGap(iv);
  ok(Math.abs(gIv.worst) < 1e-9, 'the interval policy keeps one shared scale');
  ok(Math.abs(gHz.worst) > 20, `the hertz policy pulls the two scales ${fmt(Math.abs(gHz.worst))} cents apart at worst`);
}

// ─────────────────────────────────────────────── 6. the bar model
console.log('\n6. the free-free bar, solved rather than quoted');
{
  const roots = E.barModeRoots(5);
  const want = [4.730041, 7.853205, 10.995608, 14.137165, 17.278760];
  for (let i = 0; i < want.length; i++) near(roots[i], want[i], 1e-5, `root ${i + 1} of cos(x)cosh(x) = 1`);
  const p = E.barPartials(5);
  const wantP = [1, 2.7565, 5.4039, 8.9330, 13.3443];
  for (let i = 0; i < wantP.length; i++) near(p[i], wantP[i], 5e-4, `bar partial ratio ${i + 1}`);
  // and the roots really are roots
  for (const r of roots) near(Math.cos(r) * Math.cosh(r) - 1, 0, 1e-6 * Math.cosh(r), `cos(x)cosh(x) - 1 vanishes at ${r.toFixed(6)}`);
}

// ─────────────────────────────────────────────── 7. the meter, on known signals
console.log('\n7. the meter, on signals whose beat rate is known by construction');
{
  const sr = 44100;
  for (const [u, d] of [[150, 4], [400, 8], [400, 3], [880, 12], [1200, 8]]) {
    const x = E.strikePair({ umbang: u, isep: u + d, sampleRate: sr, seconds: 4, decay: 0.5 });
    const r = E.beatRate(x, sr, { band: [u * 0.9, u * 1.1], lo: 0.5, hi: 40 });
    ok(!r.refused && r.agree, `a pair at ${u} Hz beating ${d} Hz: both methods agree`);
    if (r.hz != null) near(r.hz, d, 0.05, `  and read ${fmt(r.hz)} Hz against a true ${d}`);
  }
}
{
  // The prediction that separates a scaled pair from two arbitrary bars: partial j beats
  // at p_j times the fundamental's rate. Measured, not assumed.
  const sr = 44100, u = 400, d = 8;
  const P = E.barPartials(4);
  const x = E.strikePair({ umbang: u, isep: u + d, sampleRate: sr, seconds: 4, decay: 0.5 });
  const predicted = E.partialBeats(d, P);
  for (let j = 0; j < P.length; j++) {
    const f = u * P[j];
    const r = E.partialPairRate(x, sr, { band: [f * 0.94, f * 1.06], lo: 0.5, hi: 100 });
    ok(!r.refused, `partial ${j + 1} at ${f.toFixed(0)} Hz was resolved`);
    if (!r.refused) near(r.hz, predicted[j], 0.06, `  partial ${j + 1} beats at ${fmt(r.hz)} Hz against a predicted ${fmt(predicted[j])}`);
  }
}

// ─────────────────────────────────────────────── 8. the meter must refuse
console.log('\n8. the meter refuses rather than guessing');
{
  const sr = 44100, n = sr * 2;
  const noise = new Float64Array(n);
  const rnd = lcg(7);
  for (let i = 0; i < n; i++) noise[i] = rnd() * 2 - 1;
  const r = E.beatRate(noise, sr, { lo: 0.5, hi: 40 });
  ok(!!r.refused || !r.agree, `white noise does not produce a confident beat rate (${r.refused || 'methods disagreed'})`);

  // A single bar, no partner: there is no beat to find.
  const one = E.strike({ hz: 400, sampleRate: sr, seconds: 3, decay: 0.5 });
  const r2 = E.beatRate(one, sr, { band: [360, 440], lo: 0.5, hi: 40 });
  ok(!!r2.refused || !r2.agree, `a single struck bar yields no beat rate (${r2.refused || 'methods disagreed'})`);

  // A window too short to resolve the pair must say so rather than reporting a number.
  const short = E.strikePair({ umbang: 400, isep: 403, sampleRate: sr, seconds: 0.4, decay: 0.5 });
  const r3 = E.partialPairRate(short, sr, { band: [360, 440], lo: 0.5, hi: 40 });
  ok(r3.refused || r3.supported === false,
    `a 0.4 s window cannot support a 3 Hz reading and says so (resolvable ${fmt(r3.resolvable)} Hz)`);
}

// ─────────────────────────────────────────────── 9. one real gamelan
console.log('\n9. the identity on a real instrument, from ten quoted frequencies');
{
  const R = E.realGamelan();
  ok(R.rows.length === 5, 'five octaves of the ding column are quoted');
  ok(R.steps.length === 4, 'which gives four octave steps');

  // The frequencies themselves, typed in from Figure 7 and checked here so a slipped digit
  // shows up as a failure rather than as a plausible number.
  const want = [[136.5, 144.0], [281.9, 289.2], [566.9, 575.0], [1141.9, 1151.6], [2352.0, 2361.6]];
  let typos = 0;
  R.rows.forEach((r, i) => { if (r.umbang !== want[i][0] || r.isep !== want[i][1]) typos++; });
  ok(typos === 0, 'the ten quoted frequencies are as printed in Vitale and Sethares 2021, Figure 7, p. 12');

  near(R.frequencySpread, 17.2308, 1e-3, 'the pengumbang rises by a factor of 17.23 across the five octaves');
  near(R.beatHzSpread, 1.3288, 1e-3, 'the beat rate moves by a factor of only 1.33 over that range');
  near(R.beatCentsSpread, 13.1315, 1e-3, 'while the same gap read as an interval falls by a factor of 13.13');
  near(R.beatCentsBottom, 92.601, 1e-3, 'the bottom octave beats across 92.60 cents');
  near(R.beatCentsTop, 7.052, 1e-3, 'the top octave beats across 7.05 cents');
  ok(R.beatHzMin >= 6 && R.beatHzMax <= 10,
    `every quoted beat rate falls inside the 6 to 10 Hz the article's own Figure 2 caption gives (${R.beatHzMin} to ${R.beatHzMax})`);

  ok(R.umbangWiderEverywhere, 'the pengumbang octave is the wider one at every step, as note 17 says');
  ok(R.worstResidual < 1e-9,
    `and the excess computed from the octaves equals the excess computed from the shimmer, to ${R.worstResidual.toExponential(2)} cents`);
  const excesses = R.steps.map(s => s.excess);
  near(excesses[0], 48.341, 1e-3, 'octave I to II: the pengumbang is wider by 48.34 cents');
  near(excesses[3], 7.592, 1e-3, 'octave IV to V: by 7.59 cents');

  // The sharp form of note 17: the pengumbang octave is wider exactly when the beat rate
  // less than doubles across the octave. Check the criterion agrees with the outcome on
  // every step, and then check it can also come out FALSE, by doubling one rate.
  ok(R.steps.every(s => (s.headroom < 1) === s.umbangWider),
    'the doubling criterion agrees with the outcome on all four steps');
  const worstHeadroom = Math.max(...R.steps.map(s => s.headroom));
  ok(worstHeadroom < 0.62, `and practice stays well inside it: the largest step reaches ${(worstHeadroom * 100).toFixed(0)}% of the doubling that would flip the sign`);
  {
    const a = R.rows[0], b = R.rows[1];
    const flipped = E.trade(a.umbang, a.beatHz, b.umbang, 2.5 * a.beatHz);
    ok(flipped.difference < 0, 'and past the boundary the sign really does flip: 2.5x the rate makes the pengisep octave the wider one');
  }
}

// ─────────────────────────────────────────────── 9b. real bronze
console.log('\n9b. the four public-domain recordings the page ships');
{
  const AUDIO = path.join(ROOT, 'public', 'strata', SLUG, 'audio');
  const R = {};
  for (const c of CLIPS) {
    const p = path.join(AUDIO, c.file);
    ok(fs.existsSync(p), `${c.file} is present`);
    if (!fs.existsSync(p)) continue;
    const w = readWav(p);
    ok(w.sampleRate === c.rate, `${c.file} is ${w.sampleRate} Hz as prepared`);
    R[c.file] = E.analyseRecording(w.samples, w.sampleRate);
  }

  const a = R['pair-a.wav'], b = R['pair-b.wav'], c = R['pair-c.wav'], s = R['single.wav'];

  // Two takes of the same paired key. This is the reproducibility check the whole real-audio
  // section rests on: separate strikes, separate MP3 encodes, same two partials.
  near(a.beatHz, 8.8226, 5e-4, 'pair-a beats at 8.8226 Hz');
  near(b.beatHz, 8.8043, 5e-4, 'pair-b, a second strike of the same key, beats at 8.8043 Hz');
  near(a.lower, b.lower, 0.05, `the two takes put the lower partial within ${Math.abs(a.lower - b.lower).toFixed(3)} Hz of each other`);
  near(a.upper, b.upper, 0.05, `and the upper partial within ${Math.abs(a.upper - b.upper).toFixed(3)} Hz`);
  ok(Math.abs(a.beatHz - b.beatHz) < 0.05, `so the two beat rates agree to ${Math.abs(a.beatHz - b.beatHz).toFixed(4)} Hz`);
  ok(a.fundamental.agree && b.fundamental.agree && c.fundamental.agree,
    'and on all three pair clips the spectral and envelope methods agree');

  near(c.beatHz, 8.7581, 5e-4, 'pair-c, a different key on a different instrument, beats at 8.7581 Hz');
  ok(a.beatHz > 8.5 && a.beatHz < 9.1 && c.beatHz > 8.5 && c.beatHz < 9.1,
    'all three sit inside the 6 to 10 Hz the literature gives for gong kebyar, near its "about 8 Hz"');

  // The same rate, at two pitches, is a smaller interval higher up. That is the thesis.
  near(a.beatCents, 24.936, 1e-3, 'at 608 Hz that rate is a gap of 24.94 cents');
  near(c.beatCents, 18.356, 1e-3, 'at 822 Hz the same rate is a gap of only 18.36 cents');

  // And the identity, on two measured pairs from one gamelan.
  const t = E.trade(a.lower, a.beatHz, c.lower, c.beatHz);
  near(t.difference, a.beatCents - c.beatCents, 1e-9,
    `between those two keys the pengumbang spans ${t.difference.toFixed(3)} cents more than the pengisep, which is exactly the fall in the shimmer`);
  ok(t.difference > 0, 'and the sign is the one the theorem forces');
  ok(Math.abs(t.residual) < 1e-9, `residual ${t.residual.toExponential(2)} cents`);

  // The upper mode, where it resolves, and what it says about the two bars.
  ok(!!c.mode2, 'pair-c resolves an upper mode on both members');
  if (c.mode2) {
    near(c.mode2.beatHz, 23.986, 1e-3, 'whose two peaks are 23.99 Hz apart');
    near(c.mode2.scaledPrediction, 30.653, 1e-3, 'where two exact scale copies of one bar would give 30.65 Hz');
    near(c.mode2.ratioGapPercent, 0.232, 1e-3, 'because the two bars place that mode at ratios 0.232% apart');
    ok(c.mode2.beatHz < c.mode2.scaledPrediction * 0.9,
      'so the upper shimmer is measurably slower than the scale-copy model predicts');
  }
  ok(!a.mode2 && !b.mode2, 'and on the other two clips only one member shows an upper mode, so no doublet is claimed');

  // The refusal, on real audio.
  ok(!!s.fundamental.refused, `single.wav is refused: ${s.fundamental.refused}`);
  ok(s.fundamental.pair.partnerFraction < 0.05,
    `its nearest companion is ${(100 * s.fundamental.pair.partnerFraction).toFixed(1)}% of the strongest peak, under the 5% sidelobe floor`);

  // The window law, demonstrated on real audio: the same clip, measured shorter, refuses.
  {
    const w = readWav(path.join(AUDIO, 'pair-a.wav'));
    const short = w.samples.slice(0, Math.round(0.3 * w.sampleRate));
    const r = E.partialPairRate(short, w.sampleRate, { band: [560, 660], lo: 0.5, hi: 40 });
    ok(!!r.refused, `0.3 s of pair-a cannot support the reading and says so: ${r.refused}`);
    const long = E.partialPairRate(w.samples, w.sampleRate, { band: [560, 660], lo: 0.5, hi: 40 });
    ok(!long.refused && Math.abs(long.hz - a.beatHz) < 1e-9, 'while the whole 8 s gives the reading above');
  }
}

// ─────────────────────────────────────────────── 10. negative controls
console.log('\n10. negative controls: the gate must fail on a broken input');
{
  const threw = (fn) => { try { fn(); return false; } catch (e) { return true; } };
  ok(threw(() => E.trade(500, 8, 250, 8)), 'trade rejects keys given in the wrong order');
  ok(threw(() => E.tuneSet({ base: 300, ladder: [], octaves: 2 })), 'tuneSet rejects an empty ladder');
  ok(threw(() => E.detuneUnder('vibes', 300, 8, 600)), 'an unknown policy is rejected, not silently treated as hertz');
  ok(threw(() => E.fft(new Float64Array(3), new Float64Array(3), false)), 'the FFT rejects a non-power-of-two length');

  // If the identity were implemented as a subtraction of the wrong pair, this catches it.
  const wrong = E.spanCents(250, 500) - E.spanCents(250 + 8, 500 + 16);
  ok(Math.abs(wrong - E.trade(250, 8, 500, 8).difference) > 1,
    'the identity is sensitive to which detuning goes with which key');

  // And the meter must be able to tell two different beat rates apart.
  const sr = 44100;
  const a = E.beatRate(E.strikePair({ umbang: 400, isep: 408, sampleRate: sr, seconds: 4, decay: 0.5 }), sr, { band: [360, 440] });
  const b = E.beatRate(E.strikePair({ umbang: 400, isep: 404, sampleRate: sr, seconds: 4, decay: 0.5 }), sr, { band: [360, 440] });
  ok(a.hz != null && b.hz != null && Math.abs(a.hz - b.hz) > 3.5,
    'the meter distinguishes an 8 Hz pair from a 4 Hz pair by the right margin');
}

// ─────────────────────────────────────────────── 11. the page
console.log('\n11. the page carries the same engine and the same numbers');
if (!fs.existsSync(PAGE)) {
  console.log(`  ..  ${path.relative(ROOT, PAGE)} does not exist yet; page checks skipped`);
} else {
  const html = fs.readFileSync(PAGE, 'utf8');
  const sha = (p) => crypto.createHash('sha256').update(fs.readFileSync(p)).digest('hex');
  ok(fs.existsSync(PAGE_ENGINE), 'the page ships an engine.mjs');
  if (fs.existsSync(PAGE_ENGINE)) {
    ok(sha(PAGE_ENGINE) === sha(path.join(HERE, 'engine.mjs')),
      'the engine the browser loads is byte-for-byte the engine this gate ran');
  }
  ok(html.includes('</body>') && html.includes('</html>'), 'the load-bearing closing tags are present');
  ok(html.includes('/_kit/'), 'the page loads the shared kit');
  reportPage(html);
}

console.log(`\n${pass} passed, ${fail} failed`);
process.exit(fail ? 1 : 0);

// The quoted-material and printed-number checks live here so they can grow with the page
// without disturbing the exact half above.
function reportPage(html) {
  const flat = html.replace(/\s+/g, ' ');
  const block = /<script type="application\/json" id="findings">([\s\S]*?)<\/script>/.exec(html);
  ok(!!block, 'the page carries its findings block');
  if (block) {
    let parsed = null;
    try { parsed = JSON.parse(block[1]); } catch (e) { /* reported below */ }
    ok(!!parsed, 'the findings block is valid JSON');
    if (parsed) {
      const want = JSON.parse(JSON.stringify(findings()));
      ok(JSON.stringify(parsed) === JSON.stringify(want),
        'the findings block equals what this gate computes right now');
    }
  }
  for (const q of QUOTES) {
    ok(flat.includes(q.text.replace(/\s+/g, ' ')), `the ${q.who} quotation is present, verbatim`);
  }
}

