#!/usr/bin/env node
// verify-when-the-room-becomes-the-sound.mjs
// ─────────────────────────────────────────────────────────────────────────────
// The check behind /strata/when-the-room-becomes-the-sound/.
//
// Five independent jobs, in this order:
//
//   1. THE EVIDENCE IS WHAT IT SAYS IT IS. The survey's audio archive is
//      committed whole; its SHA-256 is asserted, every entry's CRC-32 is checked
//      against the archive's own table, and the format of every one of the 270
//      recordings is read back and compared with what the page claims about them.
//   2. RE-MEASURE FROM THE AUDIO. A deterministic sample of spaces is measured
//      again straight from the zip and compared with the committed table. This is
//      the step that would catch the analysis having been edited after its
//      artifacts were written.
//   3. RE-DERIVE THE AGGREGATES WITH THIS FILE'S OWN ARITHMETIC. Every headline
//      figure (the profiles, the quartiles, the variance decomposition, the
//      time-weighted acoustics, the counts) is recomputed here from the per-space
//      table, using medians and regressions written out below rather than
//      imported, so agreeing with results.json is a comparison and not a
//      tautology.
//   4. THE ENGINE THE PAGE RUNS IS THE ENGINE THAT MEASURED. Byte-for-byte.
//      And the closed loop: build a room from its numbers, measure the result,
//      and require the numbers back.
//   5. READ THE SHIPPED BYTES. Every figure the page prints is asserted against
//      the artifacts it prints them from, because a page can be wrong in a way
//      its data file is not.
//
//   node verify-when-the-room-becomes-the-sound.mjs
//
// Offline, about a minute, from a clean checkout. No network, no tools beyond
// Node itself.
// ─────────────────────────────────────────────────────────────────────────────

import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import { fileURLToPath } from 'node:url';
import { readZip, readEntry, crc32 } from './research/natural-reverberation/zipread.mjs';
import { readWav } from './research/natural-reverberation/wav.mjs';
import { measureIR } from './research/natural-reverberation/measure.mjs';
import { synthesiseIR, warpProfile } from './research/natural-reverberation/synth.mjs';
import { gaussianKurtosisBound, gaussianOnset, kurtosisDirect, fft, nextPow2 } from './research/natural-reverberation/dsp.mjs';

const ROOT = path.dirname(fileURLToPath(import.meta.url));
const R = (p) => path.join(ROOT, p);
const SLUG = 'when-the-room-becomes-the-sound';
const LAB = 'research/natural-reverberation';

let pass = 0, fail = 0, skip = 0;
const ok = (cond, label, detail) => {
  if (cond) { pass++; console.log(`  ✓ ${label}`); }
  else { fail++; console.log(`  ✗ ${label}${detail ? '  ... ' + detail : ''}`); }
};
const eq = (got, want, label) => ok(got === want, label, `got ${JSON.stringify(got)}, want ${JSON.stringify(want)}`);
const near = (got, want, tol, label) =>
  ok(Number.isFinite(got) && Math.abs(got - want) <= tol, label, `got ${got}, want ${want} ± ${tol}`);
const section = (s) => console.log(`\n── ${s} ` + '─'.repeat(Math.max(0, 62 - s.length)));

const RESULTS = JSON.parse(fs.readFileSync(R(`${LAB}/data/results.json`), 'utf8'));
const SPACES = JSON.parse(fs.readFileSync(R(`${LAB}/data/spaces.json`), 'utf8'));
const PAGE = R(`public/strata/${SLUG}/index.html`);
const html = fs.existsSync(PAGE) ? fs.readFileSync(PAGE, 'utf8') : null;
const DATA_JS = R(`public/strata/${SLUG}/data.js`);

console.log('WHEN THE ROOM BECOMES THE SOUND / verification\n');

// ─── this file's own arithmetic, deliberately not imported ───────────────────

const med = (a) => {
  const s = a.filter((v) => Number.isFinite(v)).slice().sort((x, y) => x - y);
  if (!s.length) return NaN;
  const m = s.length >> 1;
  return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2;
};
const qtl = (a, q) => {
  const s = a.filter((v) => Number.isFinite(v)).slice().sort((x, y) => x - y);
  if (!s.length) return NaN;
  const pos = (s.length - 1) * q, lo = Math.floor(pos), hi = Math.ceil(pos);
  return lo === hi ? s[lo] : s[lo] + (s[hi] - s[lo]) * (pos - lo);
};
const avg = (a) => a.reduce((x, y) => x + y, 0) / a.length;
const r2of = (xs, ys) => {
  const mx = avg(xs), my = avg(ys);
  let sxy = 0, sxx = 0, syy = 0;
  for (let i = 0; i < xs.length; i++) { sxy += (xs[i] - mx) * (ys[i] - my); sxx += (xs[i] - mx) ** 2; syy += (ys[i] - my) ** 2; }
  return { r2: (sxy * sxy) / (sxx * syy), slope: sxy / sxx };
};

// ═══ 1. THE EVIDENCE ═════════════════════════════════════════════════════════
section('1. the evidence is what it says it is');

const zipBytes = fs.readFileSync(R(`${LAB}/data/Audio.zip`));
const metaBytes = fs.readFileSync(R(`${LAB}/data/IRdata.js`));
const zipSha = crypto.createHash('sha256').update(zipBytes).digest('hex');
eq(zipSha, RESULTS.source.audioSha256, 'the committed archive matches the SHA-256 on the record');
eq(crypto.createHash('sha256').update(metaBytes).digest('hex'), RESULTS.source.metadataSha256,
   'the committed metadata matches its SHA-256');

const zip = readZip(zipBytes);
const wavNames = zip.names.filter((n) => n.startsWith('Audio/') && n.endsWith('.wav')).sort();
eq(wavNames.length, RESULTS.census.audioFiles, 'the archive holds the number of recordings claimed');

// Every entry decompressed and CRC-checked against the archive's own table.
let crcOk = 0;
const formats = new Set();
const lengths = [];
for (const n of wavNames) {
  const buf = readEntry(zip, n); // throws on CRC mismatch
  crcOk++;
  const w = readWav(buf);
  formats.add(`${w.channels}ch/${w.bits}bit/${w.sampleRate}Hz`);
  lengths.push(w.samples.length / w.sampleRate);
}
eq(crcOk, wavNames.length, 'every recording decompresses and passes its stored CRC-32');
eq([...formats].join(','), '1ch/24bit/32000Hz', 'every recording is mono 24-bit at 32 kHz, as the page says');
ok(crc32(Buffer.from('123456789')) === 0xcbf43926, 'the CRC-32 implementation matches its published check value');

near(Math.max(...lengths), 2.0, 0.01, 'the longest recording is two seconds (they are trimmed)');
ok(Math.min(...lengths) < 0.11, 'the shortest is under 110 ms', `min ${Math.min(...lengths).toFixed(3)} s`);

// The three counts of one survey.
const stripIndex = (n) => n.replace(/^h?\d+_/, '');
const metaText = metaBytes.toString('utf8');
const meta = JSON.parse(metaText.slice(metaText.indexOf('[')).replace(/;\s*$/, ''));
eq(meta.length, RESULTS.census.metadataEntries, 'the metadata lists the number of spaces claimed');
eq(RESULTS.census.paperSays, 271, 'the paper is recorded as saying 271');
const audioSet = new Set(wavNames.map((n) => stripIndex(path.basename(n, '.wav'))));
const metaSet = new Set(meta.map((m) => stripIndex(m.Name)));
const onlyMeta = [...metaSet].filter((n) => !audioSet.has(n)).sort();
const onlyAudio = [...audioSet].filter((n) => !metaSet.has(n)).sort();
eq(onlyMeta.join('|'), RESULTS.census.inMetadataNotInAudio.join('|'), 'the two spaces in the metadata but not the audio are the two named');
eq(onlyAudio.length, 0, 'no recording is missing from the metadata once index prefixes are stripped');
ok(RESULTS.census.audioFiles < RESULTS.census.paperSays && RESULTS.census.paperSays < RESULTS.census.metadataEntries,
   'the three published counts are 270 < 271 < 272, in that order');

// ═══ 2. RE-MEASURE FROM THE AUDIO ════════════════════════════════════════════
section('2. re-measure a sample straight from the archive');

const byName = new Map(SPACES.map((s) => [s.name, s]));
eq(SPACES.length, wavNames.length, 'the committed table has one row per recording');

// A deterministic spread: every 27th recording, so the sample cannot be curated.
const sampleIdx = [];
for (let i = 0; i < wavNames.length; i += 27) sampleIdx.push(i);
let bandChecks = 0, bandAgree = 0;
for (const i of sampleIdx) {
  const name = path.basename(wavNames[i], '.wav');
  const row = byName.get(name);
  const w = readWav(readEntry(zip, wavNames[i]));
  const m = measureIR(w.samples, w.sampleRate);
  const gotBB = Number.isFinite(m.rt60Broadband) ? Number(m.rt60Broadband.toFixed(4)) : null;
  ok(gotBB === row.rt60Broadband, `${name}: broadband reverberation time re-measures identically`,
     `got ${gotBB}, table ${row.rt60Broadband}`);
  for (let b = 0; b < m.bands.octave.length; b++) {
    const got = m.bands.octave[b].rt60 === null ? null : Number(m.bands.octave[b].rt60.toFixed(4));
    bandChecks++;
    if (got === row.octave[b].rt60) bandAgree++;
  }
}
eq(bandAgree, bandChecks, `every octave band of the ${sampleIdx.length} sampled spaces re-measures identically`);

// The Gaussian-onset threshold is derived, not quoted.
near(gaussianKurtosisBound(320), 3.54, 0.005, "the survey's 3.54 kurtosis bound falls out of 3 + 1.96√(24/320)");
{
  // And the running form of the kurtosis agrees with the slow, obvious one.
  const w = readWav(readEntry(zip, wavNames[0]));
  const direct = kurtosisDirect(w.samples, 1000, 320);
  ok(Number.isFinite(direct) && direct > 0, 'the direct kurtosis of a window is finite and positive');
  const g = gaussianOnset(w.samples, w.sampleRate);
  near(g.bound, gaussianKurtosisBound(320), 1e-12, 'the onset routine uses that same bound');
  ok(g.tGauss !== null && g.tGauss > 0 && g.tGauss < 0.5, 'the first recording reaches Gaussian statistics inside half a second');
}

// The FFT is what it claims to be: a round trip returns the input.
{
  const n = 1024;
  const re = new Float64Array(n), im = new Float64Array(n);
  for (let i = 0; i < n; i++) re[i] = Math.sin(i * 0.1) + 0.3 * Math.cos(i * 0.37);
  const orig = Float64Array.from(re);
  fft(re, im, -1); fft(re, im, +1);
  let worst = 0;
  for (let i = 0; i < n; i++) worst = Math.max(worst, Math.abs(re[i] / n - orig[i]));
  ok(worst < 1e-10, 'the FFT round-trips to within 1e-10', `worst ${worst}`);
  eq(nextPow2(4097), 8192, 'nextPow2 does what it says');
}

// ═══ 3. RE-DERIVE THE AGGREGATES ═════════════════════════════════════════════
section('3. re-derive every headline figure from the per-space table');

const measured = SPACES.filter((s) => Number.isFinite(s.rt60Broadband));
eq(measured.length, RESULTS.spacesMeasured, 'the count of spaces with a reverberation time');
eq(SPACES.length - measured.length, RESULTS.spacesUnmeasurable, 'the count of spaces without one');

// Band census.
const census = { t30: 0, t20: 0, rejected: 0, unmeasurable: 0 };
for (const s of SPACES) for (const b of s.octave) {
  if (b.basis === 'T30') census.t30++;
  else if (b.basis === 'T20') census.t20++;
  else if (b.basis === 'rejected') census.rejected++;
  else census.unmeasurable++;
}
eq(census.t30, RESULTS.bandCensus.t30, 'octave bands measured with a 30 dB fit');
eq(census.t20, RESULTS.bandCensus.t20, 'octave bands measured with a 20 dB fit');
eq(census.t30 + census.t20, RESULTS.bandCensus.measured, 'the two add to the measured total');
eq(census.rejected, RESULTS.bandCensus.rejected, 'octave bands refused');
eq(census.unmeasurable, RESULTS.bandCensus.unmeasurable, 'octave bands with nothing to fit at all');
eq(census.t30 + census.t20 + census.rejected + census.unmeasurable, SPACES.length * 8,
   'the census accounts for every band of every space');

// Claim 1: the Gaussian tail.
const tg = SPACES.map((s) => s.tGauss).filter((v) => v !== null);
near(med(tg) * 1000, RESULTS.claim1_gaussianTail.medianMs, 0.05, 'claim 1: median onset of Gaussian statistics');
near(tg.filter((v) => v < 0.05).length / tg.length, RESULTS.claim1_gaussianTail.fractionUnder50ms, 5e-4,
     'claim 1: the share under 50 ms');
ok(RESULTS.claim1_gaussianTail.fractionUnder50ms > 0.5,
   'claim 1 holds: most spaces are Gaussian inside 50 ms, as the paper states');
eq(RESULTS.claim1_gaussianTail.nNeverGaussian, 0, 'claim 1: no recording fails to reach Gaussian statistics');

// Claim 2: exponential decay.
const poly = SPACES.filter((s) => s.polyFit);
for (const d of [1, 5]) {
  near(med(poly.map((s) => s.polyFit[d])), RESULTS.claim2_exponentialDecay.medianVarianceExplained[String(d)], 5e-5,
       `claim 2: median variance explained by degree ${d}`);
}
near(med(poly.map((s) => s.polyFit[5] - s.polyFit[1])), RESULTS.claim2_exponentialDecay.medianGainDegree5OverDegree1,
     5e-5, 'claim 2: the median gain of degree 5 over a straight line');
ok(RESULTS.claim2_exponentialDecay.medianGainDegree5OverDegree1 < 0.05,
   'claim 2 holds: four extra parameters buy under five percentage points');

// Claim 3: the frequency dependence, on the balanced set.
const OCT = RESULTS.method.octaveCentresHz;
const lowIdx = OCT.map((f, i) => i).filter((i) => OCT[i] >= 125 && OCT[i] <= 8000);
const lowRows = measured.filter((s) => lowIdx.every((i) => s.octave[i].rt60 !== null));
eq(lowRows.length, RESULTS.claim3_frequencyDependence.lowBalanced.spaces,
   'claim 3: the balanced set is the spaces measured in every band from 125 Hz to 8 kHz');
const lowProf = lowIdx.map((i) => med(lowRows.map((s) => s.octave[i].rt60)));
RESULTS.claim3_frequencyDependence.lowBalanced.profile.forEach((p, k) => {
  near(lowProf[k], p.median, 5e-5, `claim 3: balanced median at ${p.f} Hz`);
});
const topK = lowProf.indexOf(Math.max(...lowProf));
eq(OCT[lowIdx[topK]], RESULTS.claim3_frequencyDependence.lowBalanced.peakHz, 'claim 3: the profile peaks where the record says');
ok(OCT[lowIdx[topK]] >= 200 && OCT[lowIdx[topK]] <= 2000, 'claim 3 holds: the peak is inside 200-2000 Hz');
ok(lowProf[0] < lowProf[topK] && lowProf[lowProf.length - 1] < lowProf[topK],
   'claim 3 holds: the profile falls on BOTH sides of that peak');
ok(RESULTS.claim3_frequencyDependence.lowBalanced.fallsBothSides === true, 'and the record says so too');

// The inverted end of the slider: the page must not call it impossible, because it
// is not. This assertion exists because an earlier draft of that sentence said "no
// room in the survey does" and four of them do.
{
  const iv = RESULTS.claim3_frequencyDependence.invertedProfiles;
  const rows = measured.map((s) => s.cochlear.filter((b) => b.rt60 !== null)).filter((v) => v.length >= 8);
  const strict = rows.filter((v) => {
    const top = v.reduce((a, b) => (b.rt60 > a.rt60 ? b : a));
    const bot = v.reduce((a, b) => (b.rt60 < a.rt60 ? b : a));
    return top.f >= 4000 && bot.f >= 250 && bot.f <= 4000;
  }).length;
  eq(rows.length, iv.n, 'the population for the inverted-profile count');
  eq(strict, iv.strict, 'the number of surveyed spaces whose profile really is inverted');
  ok(iv.strict > 0, 'and it is not zero, so the page may not say the shape is impossible');
  eq(iv.strictExamples.length, iv.strict, 'every inverted space is named');
}

// Claim 4: more reverberant spaces, stronger frequency dependence.
const spreads = RESULTS.claim4_moreReverbMoreDependence.quartiles.map((q) => q.logSpread);
ok(spreads.every((v, i) => i === 0 || v >= spreads[i - 1] - 1e-9),
   'claim 4 holds: the spread of the profile rises across every quartile', spreads.join(' → '));
const qMedians = RESULTS.claim4_moreReverbMoreDependence.quartiles.map((q) => q.medianRt60Broadband);
ok(qMedians.every((v, i) => i === 0 || v > qMedians[i - 1]), 'claim 4: the quartiles are ordered by reverberation');

// Claim 5: outdoors.
const outdoor = SPACES.filter((s) => s.outdoor && Number.isFinite(s.rt60Broadband));
const indoor = SPACES.filter((s) => !s.outdoor && Number.isFinite(s.rt60Broadband));
near(med(outdoor.map((s) => s.rt60Broadband)), RESULTS.claim5_outdoorShorterNotDifferent.outdoor.medianRt60, 5e-5,
     'claim 5: the outdoor median');
near(med(indoor.map((s) => s.rt60Broadband)), RESULTS.claim5_outdoorShorterNotDifferent.indoor.medianRt60, 5e-5,
     'claim 5: the indoor median');
ok(RESULTS.claim5_outdoorShorterNotDifferent.outdoor.medianRt60 < RESULTS.claim5_outdoorShorterNotDifferent.indoor.medianRt60,
   'claim 5 holds in its first half: outdoors is shorter');
ok(RESULTS.claim5_outdoorShorterNotDifferent.outdoor.bandsUsed < RESULTS.claim5_outdoorShorterNotDifferent.indoor.bandsUsed,
   'claim 5: and the page is right that the outdoor comparison rests on fewer bands');

// Agreement with the published per-space figures.
const pairs = measured.filter((s) => s.published && s.published.T0 > 0);
eq(pairs.length, RESULTS.agreementWithPublished.n, 'the number of spaces comparable with the published table');
const ratios = pairs.map((s) => s.rt60Broadband / s.published.T0);
near(med(ratios), RESULTS.agreementWithPublished.medianRatio, 5e-5, 'the median ratio to their published figure');
const fitPub = r2of(pairs.map((s) => Math.log(s.published.T0)), pairs.map((s) => Math.log(s.rt60Broadband)));
near(fitPub.r2, RESULTS.agreementWithPublished.logLogR2, 5e-5, 'the log-log agreement with their figures');
near(ratios.filter((r) => r > 1 / 1.3 && r < 1.3).length / ratios.length,
     RESULTS.agreementWithPublished.fractionWithin30pct, 5e-4, 'the share within 30% of their figure');

// The two estimators, and the two filterbanks.
const estR = [];
for (const s of measured) for (const b of s.cochlear) if (b.rt60 !== null && b.rt60Env !== null && b.rt60Env > 0) estR.push(b.rt60 / b.rt60Env);
eq(estR.length, RESULTS.agreementBetweenEstimators.nBands, 'the number of bands with both estimators');
near(med(estR), RESULTS.agreementBetweenEstimators.medianRatio, 5e-5, 'backward integration against the envelope fit');
ok(RESULTS.agreementBetweenEstimators.fractionWithin30pct > RESULTS.agreementWithPublished.fractionWithin30pct,
   'our two estimators agree with each other more closely than with their published table');
ok(RESULTS.agreementBetweenFilterbanks.fractionWithin20pct > 0.9,
   'the octave and cochlear banks agree in over 90% of spaces');

// The Gaussian-onset column disagreement, stated as a measurement.
const gpairs = SPACES.filter((s) => s.published && s.tGauss !== null);
const fitG = r2of(gpairs.map((s) => s.published.Tgs), gpairs.map((s) => s.tGauss));
near(fitG.r2, RESULTS.agreementOnGaussianOnset.r2, 5e-5, 'the published onset column does not track our recomputation');
ok(RESULTS.agreementOnGaussianOnset.r2 < 0.1, 'and the disagreement is near-total, not marginal');
const theirTgs = gpairs.map((s) => s.published.Tgs);
eq(theirTgs.filter((v) => v === 0).length, RESULTS.agreementOnGaussianOnset.theirValuesAtZero,
   'the count of published onsets at exactly zero');
ok(Math.max(...theirTgs) * 1000 > RESULTS.agreementOnGaussianOnset.paperStatedRangeMs[1],
   'the published column reaches outside the range the paper states for its own responses');
ok(med(gpairs.map((s) => s.tGauss)) * 1000 < 50,
   "our own median is inside the paper's stated 'about 50 ms or less'");

// The reverberation of an ordinary hour.
const wRows = measured.filter((s) => s.nTexts > 0);
const L = RESULTS.livedAcoustics;
eq(wRows.length, L.nSpaces, 'the number of spaces carrying a sample count');
eq(wRows.reduce((a, s) => a + s.nTexts, 0), L.totalTexts, 'the total number of sampled moments');
near(med(wRows.map((s) => s.rt60Broadband)), L.unweightedMedian, 5e-5, 'the median ROOM');
{
  const sorted = [...wRows].sort((a, b) => a.rt60Broadband - b.rt60Broadband);
  const tot = sorted.reduce((a, s) => a + s.nTexts, 0);
  let acc = 0, wm = null;
  for (const s of sorted) { acc += s.nTexts; if (wm === null && acc >= 0.5 * tot) wm = s.rt60Broadband; }
  near(wm, L.weightedMedian, 5e-5, 'the median MOMENT, weighted by where the moments happened');
}
near(wRows.filter((s) => s.rt60Broadband < 0.5).reduce((a, s) => a + s.nTexts, 0) / L.totalTexts,
     L.shareUnderHalfSecond, 5e-5, 'the share of moments in a space under half a second');
near([...wRows].sort((a, b) => b.nTexts - a.nTexts).slice(0, 5).reduce((a, s) => a + s.nTexts, 0) / L.totalTexts,
     L.shareInTop5, 5e-5, 'the share of moments in the five most-sampled rooms');
ok(L.weightedMedian < L.unweightedMedian,
   'the weighting moves the answer: a life is spent in rooms deader than the average room');
eq(L.excludedForUnreadableCount.filter((n) => !/\d+tx/.test(n)).length, 3,
   'three filenames carry no readable sample count and are excluded');

// The variance decomposition, recomputed here from the same core bands.
{
  const freqs = SPACES[0].cochlear.map((b) => b.f);
  const core = freqs.map((f, i) => i).filter((i) => freqs[i] >= 250 && freqs[i] <= 8000);
  const rows = [];
  for (const s of measured) {
    const raw = core.map((i) => s.cochlear[i].rt60);
    if (raw[0] === null || raw[raw.length - 1] === null) continue;
    const have = raw.filter((v) => v !== null && v > 0).length;
    if (have / raw.length < 0.8) continue;
    const out = raw.slice();
    let bad = false;
    for (let i = 0; i < out.length; i++) {
      if (out[i] > 0) continue;
      let lo = i - 1; while (lo >= 0 && !(out[lo] > 0)) lo--;
      let hi = i + 1; while (hi < out.length && !(raw[hi] > 0)) hi++;
      if (lo < 0 || hi >= out.length) { bad = true; break; }
      const fi = Math.log(freqs[core[i]]), fl = Math.log(freqs[core[lo]]), fh = Math.log(freqs[core[hi]]);
      out[i] = Math.exp(Math.log(out[lo]) * (1 - (fi - fl) / (fh - fl)) + Math.log(raw[hi]) * ((fi - fl) / (fh - fl)));
    }
    if (!bad) rows.push(out.map(Math.log));
  }
  eq(rows.length, RESULTS.shapeAnalysis.n, 'the shape analysis population');
  const d = rows[0].length;
  const grand = avg(rows.flat());
  const shape = new Float64Array(d);
  for (const r of rows) { const rm = avg(r); for (let j = 0; j < d; j++) shape[j] += (r[j] - rm) / rows.length; }
  let tot = 0, afterLevel = 0, afterShape = 0;
  for (const r of rows) {
    const rm = avg(r);
    for (let j = 0; j < d; j++) {
      tot += (r[j] - grand) ** 2;
      afterLevel += (r[j] - rm) ** 2;
      afterShape += (r[j] - rm - shape[j]) ** 2;
    }
  }
  const dec = RESULTS.shapeAnalysis.decomposition;
  near((tot - afterLevel) / tot, dec.shareFromOverallLevel, 5e-5, 'the share of variation that is a room\'s overall level');
  near((afterLevel - afterShape) / afterLevel, dec.shareOfShapeVarianceFromSharedShape, 5e-5,
       'the share of the SHAPE that is one shape shared by every room');
  near(afterShape / tot, dec.shareIdiosyncratic, 5e-5, 'the share that is a room being only itself');
  near(Math.exp(Math.max(...shape) - Math.min(...shape)), RESULTS.shapeAnalysis.meanShapeRatio, 5e-4,
       'the shared shape spans the ratio claimed, longest band to shortest');
  ok(dec.shareFromOverallLevel > 0.5, 'most of everything is one number per room');
  // The shared shape must actually slope downward with frequency, or the story is wrong.
  ok(shape[0] > shape[d - 1], 'the shared shape rings longer at the bottom than at the top');
}

// ═══ 4. THE ENGINE, AND THE CLOSED LOOP ══════════════════════════════════════
section('4. the page runs the engine that did the measuring');

for (const f of ['dsp.mjs', 'measure.mjs', 'synth.mjs']) {
  const a = fs.readFileSync(R(`${LAB}/${f}`));
  const b = fs.existsSync(R(`public/strata/${SLUG}/${f}`)) ? fs.readFileSync(R(`public/strata/${SLUG}/${f}`)) : null;
  ok(b !== null && a.equals(b), `${f} shipped to the page is byte-identical to the one that measured`);
}

// The closed loop: numbers → room → measurement → the same numbers.
{
  const targets = ['h015_Bedroom_174txts', 'h007_Bathroom_Small_41txts', 'h019_MITCampus_Atrium_1txts'];
  for (const name of targets) {
    const s = byName.get(name);
    if (!s) { skip++; console.log(`  ~ ${name} not in the table (skipped)`); continue; }
    const out = synthesiseIR({
      freqs: s.cochlear.map((b) => b.f),
      rt60s: s.cochlear.map((b) => b.rt60),
      tailEnergy: s.cochlear.map((b) => b.eLate),
      directEnergy: s.cochlear.map((b) => b.eEarly),
      fs: 32000, warp: 1, seed: 20260804,
    });
    const m = measureIR(out.samples, 32000);
    const rs = [];
    for (let i = 0; i < s.cochlear.length; i++) {
      const target = s.cochlear[i].rt60, got = m.bands.cochlear[i].rt60;
      if (target && got && !out.filled[i]) rs.push(got / target);
    }
    ok(rs.length >= 8, `${name}: the rebuilt room is measurable in at least 8 of its measured bands`, `got ${rs.length}`);
    const ratio = med(rs);
    ok(ratio > 0.85 && ratio < 1.15, `${name}: rebuilt from its numbers, it measures back at ${ratio.toFixed(3)}× the target`);
  }
}

// The warp is a shape control, not a volume control: it must leave the geometric
// mean of the profile alone, which is what makes the slider a fair experiment.
{
  const s = byName.get('h015_Bedroom_174txts');
  const prof = s.cochlear.map((b) => b.rt60).filter((v) => v > 0);
  const gm = (a) => Math.exp(avg(a.map(Math.log)));
  for (const w of [-1, 0, 0.5, 1, 2]) {
    const warped = warpProfile(prof, w).filter((v) => v > 0);
    near(gm(warped), gm(prof), gm(prof) * 1e-9, `warp ${w} leaves the overall reverberation time untouched`);
  }
  const inverted = warpProfile(prof, -1);
  const asIs = warpProfile(prof, 1);
  const lo = 0, hi = prof.length - 1;
  ok((asIs[lo] - asIs[hi]) * (inverted[lo] - inverted[hi]) < 0,
     'warp -1 really does turn the profile over: the low-to-high difference changes sign');
  const flat = warpProfile(prof, 0);
  ok(Math.max(...flat) / Math.min(...flat) - 1 < 1e-9, 'warp 0 makes every band decay at the same rate');
}

// ═══ 5. READ THE SHIPPED BYTES ═══════════════════════════════════════════════
section('5. the page and its data file say what the artifacts say');

if (!html) { fail++; console.log('  ✗ the page is missing'); }
else {
  ok(fs.existsSync(DATA_JS), 'the page ships its data file');
  const dataText = fs.readFileSync(DATA_JS, 'utf8');
  const packed = JSON.parse(dataText.replace(/^window\.REVERB_DATA = /, '').replace(/;\s*$/, ''));

  eq(packed.spaces.length, SPACES.length, 'the shipped data carries every space');
  eq(packed.census.audioFiles, RESULTS.census.audioFiles, 'the shipped census matches the lab census');
  eq(packed.claims.frequencyDependence.lowBalanced.peakHz, RESULTS.claim3_frequencyDependence.lowBalanced.peakHz,
     'the shipped peak frequency matches');
  eq(packed.lived.weightedMedian, RESULTS.livedAcoustics.weightedMedian, 'the shipped weighted median matches');
  eq(packed.shape.decomposition.shareFromOverallLevel, RESULTS.shapeAnalysis.decomposition.shareFromOverallLevel,
     'the shipped variance decomposition matches');
  eq(packed.source.audioSha256, RESULTS.source.audioSha256, 'the shipped provenance hash matches the archive');

  // Every per-space profile the page will rebuild a room from must be the
  // measurement, to the precision it was rounded at.
  let profileRows = 0, profileAgree = 0;
  for (const p of packed.spaces) {
    const s = byName.get(p.n);
    for (let i = 0; i < p.r.length; i++) {
      profileRows++;
      const want = s.cochlear[i].rt60 === null ? null : Number(s.cochlear[i].rt60.toPrecision(4));
      if (p.r[i] === want) profileAgree++;
    }
  }
  eq(profileAgree, profileRows, 'every shipped band matches the measured table');

  // Figures written into the page's own prose, rather than computed at runtime.
  ok(/Traer, J\. &amp;amp; McDermott|Traer, J\. &amp; McDermott/.test(html), 'the page cites the survey by name');
  ok(html.includes('10.1073/pnas.1612524113'), 'the page carries the DOI');
  ok(html.includes('CC BY 4.0'), 'the page states the licence the audio is released under');
  ok(/270 impulse responses/.test(html), 'the page says 270 impulse responses');
  eq(RESULTS.census.audioFiles, 270, 'and 270 is the number of recordings there are');
  ok(html.includes('3 + 1.96'), 'the page shows the derivation of the 3.54 threshold rather than quoting it');
  // The paper's own statistics, quoted on the page, must be quoted as statistics.
  for (const q of ['t(21) = 1.52, P = 0.14', '-0.45, P = 0.66', '-0.87, P = 0.40']) {
    ok(html.includes(q), `the page carries the survey's own null statistic ${q}`);
  }
  ok(/twenty-two listeners/.test(html), 'and attributes it to their twenty-two listeners, not to the reader');
  ok(html.includes('sixty-six numbers'), 'the page describes a room as sixty-six numbers');
  ok(!/no room in the survey does/.test(html), 'the page does not claim the inverted shape is unrecorded');
  ok(/rare rather than impossible/.test(html) || html.includes('id="inverted"'),
     'the page carries the counted rarity of the inverted shape');
  eq(RESULTS.method.cochlearBands * 2, 66, 'and 33 bands x 2 numbers each is sixty-six');
  ok(!/—/.test(html.replace(/&mdash;/g, '')), 'no em dash in the page prose');

  // The page must not promise the reader an experimental result of its own.
  ok(html.includes('demonstration, not evidence'),
     'the page marks the reader\'s own listening as a demonstration, not as evidence');
  ok(html.includes('never leaves'), 'the page states that a recorded voice stays in the browser');

  // The markdown entry.
  const md = fs.readFileSync(R(`src/content/strata/${SLUG}.md`), 'utf8');
  ok(md.includes(`href: "/strata/${SLUG}/"`), 'the stratum entry points at the page');
  ok(md.includes('verify-when-the-room-becomes-the-sound.mjs'), 'the stratum entry names this verifier');
  for (const [label, v] of [['728', RESULTS.bandCensus.rejected + RESULTS.bandCensus.unmeasurable],
                            ['2,160', SPACES.length * 8],
                            ['77', RESULTS.claim3_frequencyDependence.lowBalanced.spaces],
                            ['0.347', RESULTS.livedAcoustics.weightedMedian],
                            ['87.3', RESULTS.livedAcoustics.shareUnderHalfSecond * 100],
                            ['38.4', RESULTS.livedAcoustics.shareInTop5 * 100]]) {
    ok(md.includes(label), `the dek's figure ${label} is present`);
    ok(Math.abs(Number(String(v)) - Number(label.replace(/,/g, ''))) < 0.06,
       `and ${label} is what the artifacts say`, `artifact ${v}`);
  }
}

// ─── verdict ─────────────────────────────────────────────────────────────────
console.log(`\n${'═'.repeat(66)}`);
console.log(`  ${pass} passed, ${fail} failed${skip ? `, ${skip} skipped` : ''}`);
console.log(`${'═'.repeat(66)}\n`);
process.exit(fail ? 1 : 0);
