#!/usr/bin/env node
// verify-the-rounding-you-were-allowed.mjs — the browser pass (Tier B).
//
// The offline mirror (research/the-rounding-you-were-allowed/verify.mjs) checks
// the arithmetic on the command line. This file checks what a visitor actually
// receives: that the modules load over HTTP, that the reference the browser runs
// agrees value for value with the reference Node runs, that the instruments
// repaint, that the census the browser measures lands where the committed
// engines land, and that every figure written into the prose is the figure the
// modules produce.
//
// It also replays the golden traces through the browser's own copy of the
// shared reduction and requires the recovered divergence counts to match, and
// then corrupts one of them and requires the browser to notice. That last pair
// is the only thing standing between this file and a check that cannot fail.
//
//   node verify-the-rounding-you-were-allowed.mjs
//
// Serves dist/ if the site has been built and public/ otherwise, so the file
// works before and after the orchestrator's build.

import { chromium } from 'playwright';
import { createServer } from 'node:http';
import { readFileSync, existsSync } from 'node:fs';
import { extname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import * as R from './public/strata/the-rounding-you-were-allowed/reference.mjs';
import * as U from './public/strata/the-rounding-you-were-allowed/ulp.mjs';
import * as C from './public/strata/the-rounding-you-were-allowed/chaos.mjs';
import * as D from './public/strata/the-rounding-you-were-allowed/data.js';

const ROOT = new URL('./', import.meta.url).pathname;
// public/ FIRST, not dist/. Everything this file imports comes from public/, and
// serving dist/ ahead of it means one half of this verifier reads one build and
// the other half reads another: during a rebuild that produced a browser showing
// 9.96% while Node asserted 7.50%, and neither half was wrong about its own copy.
// dist/ stays as a fallback so site-wide assets resolve after a build.
const ROOTS = [join(ROOT, 'public'), join(ROOT, 'dist')].filter((p) => existsSync(p));
const SLUG = 'the-rounding-you-were-allowed';

const PAGE_FILES = ['index.html', 'page.js', 'data.js', 'reference.mjs', 'ulp.mjs', 'chaos.mjs'];
// Informational, not a check: dist/ is whatever the last build left behind and
// the orchestrator rebuilds it at consolidation. What matters, and what IS
// checked below, is that the bytes the browser received are the bytes Node
// imported.
if (existsSync(join(ROOT, 'dist'))) {
  const drift = PAGE_FILES.filter((f) => {
    const a = join(ROOT, 'dist', 'strata', SLUG, f);
    return !existsSync(a) || !readFileSync(a).equals(readFileSync(join(ROOT, 'public', 'strata', SLUG, f)));
  });
  if (drift.length) console.log(`note: dist/ is behind public/ on ${drift.join(', ')}; public/ is what is served and verified here`);
}

const TYPES = {
  '.html': 'text/html', '.css': 'text/css', '.js': 'text/javascript', '.mjs': 'text/javascript',
  '.woff2': 'font/woff2', '.woff': 'font/woff', '.png': 'image/png', '.webp': 'image/webp',
  '.svg': 'image/svg+xml', '.ico': 'image/x-icon', '.json': 'application/json', '.txt': 'text/plain',
};

const server = createServer((req, res) => {
  let p = decodeURIComponent(req.url.split('?')[0]);
  if (p.endsWith('/')) p += 'index.html';
  for (const root of ROOTS) {
    try {
      const buf = readFileSync(join(root, p));
      res.writeHead(200, { 'content-type': TYPES[extname(p)] || 'application/octet-stream' });
      res.end(buf);
      return;
    } catch { /* try the next root */ }
  }
  res.writeHead(404); res.end('404');
});
const PORT = 8291;
await new Promise((r) => server.listen(PORT, r));
const URL_ = `http://localhost:${PORT}/strata/${SLUG}/`;

let fails = 0;
const failed = [];
const ok = (n, c, x = '') => {
  if (!c) { fails++; failed.push(n); }
  console.log(`${c ? '  ok  ' : 'FAIL  '}${n}${x ? '   · ' + x : ''}`);
};

const browser = await chromium.launch();

{
  // The one assertion that closes the split: fetch each file over the same HTTP
  // the browser used and require it to be byte-identical to the file Node
  // imported. If the serving order ever put another build first, this fails.
  const mismatched = [];
  for (const f of PAGE_FILES) {
    const res = await fetch(`http://localhost:${PORT}/strata/${SLUG}/${f}`);
    const served = Buffer.from(await res.arrayBuffer());
    if (!served.equals(readFileSync(join(ROOT, 'public', 'strata', SLUG, f)))) mismatched.push(f);
  }
  ok('every file the browser is served is byte-identical to the file this verifier imported',
    mismatched.length === 0, mismatched.join(', ') || `${PAGE_FILES.length} files identical`);
}

// ---------------------------------------------------------------------------
// pass 1: the page as a visitor gets it
// ---------------------------------------------------------------------------
const page = await browser.newPage({ viewport: { width: 1200, height: 1000 } });
const errs = [];
page.on('pageerror', (e) => errs.push(String(e)));
page.on('console', (m) => { if (m.type() === 'error') errs.push(m.text()); });
const external = [];
page.on('request', (r) => {
  const u = new URL(r.url());
  if (u.hostname !== 'localhost' && u.protocol !== 'data:') external.push(r.url());
});

await page.goto(URL_, { waitUntil: 'networkidle' });
await page.waitForFunction(() => window.__rounding && window.__rounding.ready === true, null, { timeout: 40000 });

ok('no JS errors on load', errs.length === 0, errs.join(' | '));
ok('no third-party requests', external.length === 0, external.join(' '));
ok('the shared modules loaded over HTTP as real modules',
  await page.evaluate(() => typeof window.__rounding.R.correctlyRounded === 'function'
    && typeof window.__rounding.U.reduce === 'function'
    && typeof window.__rounding.C.divergence === 'function'));

// The operable base: a stranger sees a true thing without pressing anything.
{
  const opened = await page.textContent('#one-opened');
  const verdict = await page.textContent('#verdict1');
  ok('the page opens on an argument THIS engine gets wrong, found rather than hard-coded',
    /walked the list until it found one/.test(opened) && /double(s)? too (high|low)/.test(verdict),
    verdict.slice(0, 90));
  const arg = await page.inputValue('#x1');
  const wrongHere = U.ulpDiff(Math.exp(Number(arg)), R.correctlyRounded('exp', Number(arg), 160).value);
  ok('and Node agrees that argument is one this V8 gets wrong',
    wrongHere !== 0, `exp(${arg}) is off by ${wrongHere}`);
  const highlighted = await page.$$eval('#bits1 .diff', (n) => n.length);
  ok('the differing hex digits are highlighted on load', highlighted > 0, `${highlighted} highlighted`);
}

// ---------------------------------------------------------------------------
// the browser's reference against Node's, value for value
// ---------------------------------------------------------------------------
{
  const fns = D.FUNCTIONS;
  const browserRef = await page.evaluate(({ fns }) => {
    const out = {};
    for (const f of fns) {
      const xs = window.__rounding.U.args(f, 120);
      out[f] = xs.map((x) => window.__rounding.U.hex(window.__rounding.R.correctlyRounded(f, x, 160).value)).join('');
    }
    return out;
  }, { fns });
  let agree = 0, total = 0;
  for (const f of fns) {
    const xs = U.args(f, 120);
    const theirs = U.unpackHex(browserRef[f]);
    for (let i = 0; i < xs.length; i++) {
      total++;
      if (Object.is(R.correctlyRounded(f, xs[i], 160).value, theirs[i])) agree++;
    }
  }
  ok(`the browser's reference equals Node's on all ${total} values`, agree === total, `${agree} / ${total}`);
}

// ---------------------------------------------------------------------------
// the golden traces, replayed through the BROWSER's copy of the reduction
// ---------------------------------------------------------------------------
{
  const ENGINE_KEYS = ['chromium', 'firefox', 'webkit', 'node', 'glibc'];
  const inBrowser = await page.evaluate(({ keys }) => {
    const { U, data, rebuilt } = window.__rounding;
    const out = {};
    for (const k of keys) {
      out[k] = {};
      for (const f of data.FUNCTIONS) {
        const want = U.unpackHex(data.REFERENCE[f]);
        out[k][f] = U.reduce(rebuilt[k][f], want);
      }
    }
    return out;
  }, { keys: ENGINE_KEYS });

  let mismatch = 0;
  for (const k of ENGINE_KEYS) {
    for (const f of D.FUNCTIONS) {
      const want = U.unpackHex(D.REFERENCE[f]);
      const raw = JSON.parse(readFileSync(join(ROOT, 'research', SLUG, 'data', `trace-${k}.json`), 'utf8'));
      const here = U.reduce(U.unpackHex(raw.values[f]), want);
      const there = inBrowser[k][f];
      if (here.differing !== there.differing || here.maxUlp !== there.maxUlp) mismatch++;
    }
  }
  ok('GOLDEN TRACE: every committed trace replays in the browser to the same divergence count Node gets from the raw file',
    mismatch === 0, `${ENGINE_KEYS.length * D.FUNCTIONS.length} engine-function pairs`);

  ok('GOLDEN TRACE: the sqrt control replays to exactly zero in the browser, in all five engines',
    ENGINE_KEYS.every((k) => inBrowser[k].sqrt.differing === 0));
  ok('GOLDEN TRACE: at least one replayed trace is NOT zero, so the replay is not blind',
    ENGINE_KEYS.some((k) => D.FUNCTIONS.some((f) => inBrowser[k][f].differing > 0)));

  // the corruption that MUST be caught, run inside the browser
  const caught = await page.evaluate(() => {
    const { U, data, rebuilt } = window.__rounding;
    const want = U.unpackHex(data.REFERENCE.sqrt);
    const clean = U.reduce(rebuilt.chromium.sqrt, want);
    const dirty = rebuilt.chromium.sqrt.slice();
    const idx = [4, 40, 400];
    for (const i of idx) dirty[i] = U.fromBits(U.toBits(dirty[i]) + 1n);
    const red = U.reduce(dirty, want);
    return { cleanDiff: clean.differing, dirtyDiff: red.differing, dirtyMax: red.maxUlp };
  });
  ok('GOLDEN TRACE, THE ONE THAT MUST FAIL: corrupting three sqrt values in the browser is caught, exactly three',
    caught.cleanDiff === 0 && caught.dirtyDiff === 3 && caught.dirtyMax === 1, JSON.stringify(caught));

  const digests = await page.evaluate(() => {
    const { U, data, rebuilt } = window.__rounding;
    let good = 0, total = 0;
    for (const k of Object.keys(rebuilt)) {
      for (const f of data.FUNCTIONS) { total++; if (U.fnv1a64(U.packHex(rebuilt[k][f])) === data.ENGINES[k].digests[f]) good++; }
    }
    return { good, total };
  });
  ok('PROVENANCE: every trace the browser rebuilt hashes to the digest of the raw lab file',
    digests.good === digests.total, `${digests.good} / ${digests.total}`);
  for (const k of ENGINE_KEYS) {
    const raw = JSON.parse(readFileSync(join(ROOT, 'research', SLUG, 'data', `trace-${k}.json`), 'utf8'));
    ok(`PROVENANCE: ${k}'s shipped digest is the hash of the committed raw trace`,
      D.FUNCTIONS.every((f) => D.ENGINES[k].digests[f] === U.fnv1a64(raw.values[f])));
  }
}

// ---------------------------------------------------------------------------
// the in-page check panel
// ---------------------------------------------------------------------------
{
  const head = await page.textContent('#checkhead');
  const m = head.match(/(\d+)\s*\/\s*(\d+) checks pass/);
  ok('the check panel rendered a score', !!m, head.trim().slice(0, 140));
  if (m) {
    ok(`the check panel passes all ${m[2]} of its checks`, m[1] === m[2], head.trim().slice(0, 200));
    ok('the check panel carries at least 30 checks', Number(m[2]) >= 30, m[2]);
  }
  const items = await page.$$eval('#checklist li', (ls) => ls.map((l) => l.textContent));
  ok('the check list is itemised, one line per check', items.length >= 30, String(items.length));
  ok('the check panel includes negative controls that must come back dirty',
    items.filter((t) => /MUST (FAIL|reject|catch)/.test(t)).length >= 2,
    items.filter((t) => /MUST (FAIL|reject|catch)/.test(t)).length + ' found');
  ok('the check panel includes OFFLINE results the browser cannot redo',
    items.filter((t) => /OFFLINE:/.test(t)).length >= 3);
  ok('the check panel node is a polite live region',
    await page.getAttribute('#checkhead', 'aria-live') === 'polite');
}

// ---------------------------------------------------------------------------
// every figure in the prose, matched as a string against the recomputed value
// ---------------------------------------------------------------------------
{
  const text = await page.textContent('main');
  const pct = (r, d = 1) => (100 * r).toFixed(d) + '%';
  const commas = (n) => n.toLocaleString('en-US');
  const deep = D.CENSUSDEEP.engines;
  const expect = [
    ['the deep exp rate for the fdlibm engines', pct(deep.chromium.byFunction.exp.rate, 2)],
    ['the cbrt substitution artefact', pct(D.CONTROLS.c5_cbrt_substitution_artefact.substitutionRate)],
    ['the real cbrt rate', pct(D.CONTROLS.c5_cbrt_substitution_artefact.properRate)],
    ["Chromium's deep sin count", String(deep.chromium.byFunction.sin.differing)],
    ["Chromium's deep sin rate", pct(deep.chromium.byFunction.sin.rate, 2)],
    ['the predicted separation step', D.CHAOS.predictedSteps.toFixed(1)],
    ['the measured median separation', String(D.CHAOS.separation.median)],
    ['the measured Lyapunov exponent', D.CHAOS.lyapunov.mean.toFixed(6)],
    ['the exact ln 2', Math.LN2.toFixed(6)],
    ['the cross-check comparison count', commas(D.CROSSCHECK.comparisons)],
    ['the hardest margin found offline', String(D.HARDTOROUND.hardest.exp.marginBits)],
    ['the glibc tan divergence count', String(deep.glibc.byFunction.tan.differing)],
    ['the committed sample size', commas(D.N)],
    ['the deep sample size', commas(D.CENSUSDEEP.n)],
    ["the consensus value of pow(pi, -100)", D.ENGINES.chromium.probes['Math.pow(Math.PI, -100)'].str],
    ["the older value of pow(pi, -100)", D.ENGINES.node.probes['Math.pow(Math.PI, -100)'].str],
    // P3 carried these three as hand-typed literals in an apparatus paragraph
    // that stands next to a note about four other hand-typed figures.
    ['the deep cbrt rate for the system libraries, in P3', pct(deep.glibc.byFunction.cbrt.rate)],
    ['the deep cbrt rate for the fdlibm engines, in P3', pct(deep.chromium.byFunction.cbrt.rate)],
    ['the 15th edition clause for sqrt', D.SPEC.editions.es2024.sectionNumbers.sqrt],
    ['the 16th edition clause for sqrt', D.SPEC.editions.es2025.sectionNumbers.sqrt],
    // the sentence in section 3 points AT the census table, so it has to carry
    // the number that is in the census table and not the deeper one
    ['the 1,000-argument exp rate the census table shows', pct(D.SUMMARY.accuracy.chromium.exp.rate)],
    ['the system-library exp rate, in the dek', pct(deep.webkit.byFunction.exp.rate, 3)],
    ['the year of the first edition', String(D.SPECFIRSTEDITION.publishedYear)],
    ['the first-edition clause number', D.SPECFIRSTEDITION.clause],
    ...D.TANREALULP.departures.map((d, i) => [`real-ulp adjudication ${i + 1}`, d.realUlps.toFixed(3)]),
  ];
  for (const [what, s] of expect) ok(`the prose states ${what} as the recomputed value`, text.includes(s), s);

  let deltas = 0;
  for (const k of Object.keys(D.ENGINES)) for (const f of D.FUNCTIONS) deltas += D.ENGINES[k].deltas[f].length;
  ok('the prose states the shipped departure count', text.includes(commas(deltas)), commas(deltas));

  // Section 3 used to say the zero row was "not a lucky accident of hardware"
  // one clause before recording that the pull request's rationale was that the
  // engines already did it. The zero is IEEE 754's; the clause change is the
  // standard catching up.
  ok('section 3 puts the hardware guarantee before the clause change, not after it',
    /required to be correctly rounded since 1985/.test(text)
    && !/not a lucky accident of hardware/.test(text)
    && !/It is a decision, taken in a pull request/.test(text));
  ok('the two verbatim spec quotes are in the DOM',
    text.includes('some latitude is allowed in the choice of approximation algorithms')
    && text.includes('they are encouraged to strive to approximate the ideal'));
  ok('the 15th-edition sqrt step is quoted verbatim', text.includes(D.SPEC.editions.es2024.quotes.sqrtStep));
  ok('the 16th-edition sqrt step is quoted verbatim', text.includes(D.SPEC.editions.es2025.quotes.sqrtStep));
  ok("the glibc manual's own caveat is quoted verbatim", text.includes(D.GLIBC.quotes.tableIsFromTests));
  ok('the Firefox source comment is quoted verbatim against the committed copy of the file',
    text.includes(D.FIREFOX.powComment), `${D.FIREFOX.powComment.length} chars`);
  ok('and altering one digit inside that quotation would be caught', (() => {
    const tampered = D.FIREFOX.powComment.replace('1.9275814160560204e-50', '1.9275814160560205e-50');
    return tampered !== D.FIREFOX.powComment && !text.includes(tampered);
  })());
  ok('the pref defaults on the page are the ones in the source', (() => {
    const p = D.FIREFOX.pref;
    return text.includes(p.name) && text.includes(`defaults to ${p.windows} on Windows`)
      && text.includes(`${p.other} on every other platform`);
  })(), `${D.FIREFOX.pref.windows} / ${D.FIREFOX.pref.other}`);
  // The two-camp count and the factor range were hand-typed literals inside
  // otherwise-computed sentences, and both were wrong: seven where the answer is
  // six, and a range that excluded the real minimum and the real maximum at once.
  // The margin is the second correction to the same sentence: six became four
  // once a function had to beat three sigma of the difference between two counts
  // before joining a camp. Sine entered on 36 against 35 of 20,000 and cosine on
  // 26 against 23, and the factor range began at 1.0x, which is a way of writing
  // "no difference" that reads like a finding.
  {
    const SYS = ['webkit', 'glibc'], FD = ['chromium', 'firefox', 'node'];
    const clears = (a, b) => a - b > 3 * Math.sqrt(a + b);
    const worse = [], reversed = [], tied = [], indecisive = [];
    let lo = Infinity, hi = 0, loF = null, hiF = null;
    for (const f of D.FUNCTIONS) {
      const sys = Math.max(...SYS.map((k) => deep[k].byFunction[f].differing));
      const sysMin = Math.min(...SYS.map((k) => deep[k].byFunction[f].differing));
      const fd = FD.map((k) => deep[k].byFunction[f].differing);
      const fdMin = Math.min(...fd), fdMax = Math.max(...fd);
      if (fdMin === fdMax && fdMin === sys && sys === sysMin) { tied.push(f); continue; }
      if (clears(fdMin, sys)) {
        worse.push(f);
        for (const v of fd) { const r = v / sysMin; if (r < lo) { lo = r; loF = f; } if (r > hi) { hi = r; hiF = f; } }
      } else if (clears(sysMin, fdMax)) reversed.push(f);
      else indecisive.push(f);
    }
    const fac = (r) => (r < 10 ? r.toFixed(2) : r.toFixed(1));
    ok('Node counts four functions where every fdlibm engine is decisively worse, one reversal, one tie and two undecided',
      worse.length === 4 && reversed.join(',') === 'cbrt' && tied.join(',') === 'sqrt'
      && indecisive.join(',') === 'sin,cos',
      `${worse.join(',')} | ${reversed.join(',')} | ${tied.join(',')} | ${indecisive.join(',')}`);
    ok('and the two undecided ones are undecided because the whole difference is inside the noise',
      indecisive.every((f) => {
        const a = Math.min(...FD.map((k) => deep[k].byFunction[f].differing));
        const b = Math.max(...SYS.map((k) => deep[k].byFunction[f].differing));
        return a - b <= 3 * Math.sqrt(a + b);
      }),
      indecisive.map((f) => `${f} ${Math.min(...FD.map((k) => deep[k].byFunction[f].differing))} vs ${Math.max(...SYS.map((k) => deep[k].byFunction[f].differing))}`).join(', '));
    ok('and section 2 prints that count rather than the old seven or the old six',
      text.includes(`less accurate of the two on ${worse.length} of the ${D.FUNCTIONS.length} functions`)
      && !text.includes('seven functions out of eight'),
      `${worse.length} of ${D.FUNCTIONS.length}`);
    ok('and the factor range on the page is the measured range, at both ends',
      text.includes(`${fac(lo)} on ${loF}`) && text.includes(`${fac(hi)} on ${hiF}`),
      `${fac(lo)} on ${loF} to ${fac(hi)} on ${hiF}`);
    ok('and no factor of about one is being printed as evidence of a difference',
      lo > 2, `smallest factor ${fac(lo)} on ${loF}`);
    ok('and prediction P2 in the apparatus carries the same two figures',
      text.includes(`On ${worse.length} of the ${D.FUNCTIONS.length} functions the fdlibm engines are the less accurate ones`)
      && text.includes(`${fac(lo)} to ${fac(hi)}`),
      `${fac(lo)} to ${fac(hi)}`);
    ok('and the old range is not on the page anywhere',
      !text.includes('between twenty and a hundred and fifty'));

    // The camps are a claim about how many distinct answers exist. On sine and
    // cosine there are more than two, and the page has to say so where a reader
    // will meet the census, not only in the apparatus.
    const sets = (f) => {
      const ks = Object.keys(D.ENGINES);
      const p = Object.fromEntries(ks.map((k) => [k, k]));
      const find = (x) => (p[x] === x ? x : (p[x] = find(p[x])));
      for (const key of Object.keys(D.SUMMARY.agreement)) {
        const [a, b] = key.split('/');
        if (D.SUMMARY.agreement[key][f].differing === 0) p[find(a)] = find(b);
      }
      return new Set(ks.map(find)).size;
    };
    const WORDS = { 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five' };
    ok('sqrt is one answer across all five engines, and sine and cosine are more than two',
      sets('sqrt') === 1 && sets('sin') > 2 && sets('cos') > 2,
      D.FUNCTIONS.map((f) => `${f} ${sets(f)}`).join(', '));
    ok('and section 2 states those counts in the same words the page computes them in',
      D.FUNCTIONS.filter((f) => sets(f) > 2)
        .every((f) => text.includes(`${WORDS[sets(f)]} distinct answers to ${f}`)),
      D.FUNCTIONS.filter((f) => sets(f) > 2).map((f) => `${f} ${WORDS[sets(f)]}`).join(', '));
    ok('and the page no longer says the census is two maths libraries full stop',
      !text.includes('That is two maths libraries'));
  }

  // The apparatus prints the machines: the caption of the census table points at
  // "the date in the apparatus", and there used not to be one.
  {
    const machines = await page.textContent('#machinetable');
    ok('the apparatus names each engine version, so the reader can tell which V8 "Node" means',
      Object.keys(D.ENGINES).every((k) => machines.includes(D.ENGINES[k].ua)),
      Object.keys(D.ENGINES).filter((k) => !machines.includes(D.ENGINES[k].ua)).join(',') || 'all five');
    ok('the apparatus prints the capture date the census caption points at',
      text.includes(D.ENGINES.chromium.capturedAt.replace('T', ' ').slice(0, 19)),
      D.ENGINES.chromium.capturedAt);
    ok('and the deep census date beside it', text.includes(D.CENSUSDEEP.capturedAt.replace('T', ' ').slice(0, 19)));
    ok('every trace records the same host, and the page says which',
      Object.keys(D.ENGINES).every((k) => D.ENGINES[k].host === 'linux-x64') && machines.includes('linux-x64'));
    ok('a user agent claiming a platform the run was not on is contradicted rather than repeated',
      !/Macintosh/.test(D.ENGINES.webkit.ua) || /not the platform it ran on/.test(text));
  }

  // The OFFLINE figures now carry the departure lists they are counts of.
  {
    ok('every deep census count equals the length of the departure list behind it',
      Object.keys(D.ENGINES).every((k) => D.FUNCTIONS.every(
        (f) => D.CENSUSDEEP.departureCounts[k][f] === deep[k].byFunction[f].differing)),
      `${Object.keys(D.ENGINES).length * D.FUNCTIONS.length} cells`);
    ok('the departure file the page names is committed',
      existsSync(join(ROOT, D.CENSUSDEEP.departuresFile)), D.CENSUSDEEP.departuresFile);
    ok('the page says plainly that the OFFLINE figures are read rather than recomputed here',
      /A file is not a measurement/.test(text));
    ok('and no longer claims that everything above is recomputed in your browser',
      !text.includes('Everything above that is a number is recomputed below'));
  }

  ok('no placeholder ellipsis survived into the prose', !/^\s*…\s*$/m.test(text));
  ok('the prose contains no em dash', !/—/.test(text), (text.match(/—/g) || []).length + ' found');
}

// ---------------------------------------------------------------------------
// the census table on screen, and the reader's own column
// ---------------------------------------------------------------------------
{
  const before = await page.$$eval('#censustable tbody tr', (rs) => rs.map((r) => r.children[6].textContent));
  ok('the reader column claims nothing before the reader presses anything',
    before.every((t) => t === 'not yet'), before.join(' '));

  await page.click('#runcensus');
  await page.waitForFunction(() => window.__rounding.you.census !== null, null, { timeout: 120000 });
  const after = await page.$$eval('#censustable tbody tr', (rs) => rs.map((r) => r.children[6].textContent));
  ok('running the census fills the reader column', after.every((t) => /%$/.test(t)), after.join(' '));

  const mine = await page.evaluate(() => {
    const o = {};
    for (const [f, r] of Object.entries(window.__rounding.you.census)) o[f] = { differing: r.differing, n: r.n, maxUlp: r.maxUlp };
    return o;
  });
  ok('the reader column shows sqrt as exactly zero, the control, measured live',
    mine.sqrt.differing === 0 && mine.sqrt.n === D.N, JSON.stringify(mine.sqrt));
  ok('the reader column is NOT zero everywhere, so the live measurement is not blind',
    D.FUNCTIONS.some((f) => f !== 'sqrt' && mine[f].differing > 0),
    D.FUNCTIONS.filter((f) => mine[f].differing > 0).join(','));
  ok('this Chromium matches the committed Chromium column, since it is the same engine',
    D.FUNCTIONS.every((f) => mine[f].differing === D.SUMMARY.accuracy.chromium[f].differing),
    D.FUNCTIONS.map((f) => `${f}:${mine[f].differing}/${D.SUMMARY.accuracy.chromium[f].differing}`).join(' '));

  const latMeasured = await page.$$eval('#lattable tbody tr',
    (rs) => rs.filter((r) => /wrong on/.test(r.children[4].textContent)).length);
  ok('the latitude table picks up the reader measurement too, rather than going stale',
    latMeasured === D.FUNCTIONS.length, `${latMeasured} of ${D.FUNCTIONS.length} rows`);

  const rerun = await page.evaluate(() => window.__rounding.rerunChecks());
  const m2 = rerun.match(/(\d+)\s*\/\s*(\d+) checks pass/);
  ok('the check panel still passes after the reader column is filled', m2 && m2[1] === m2[2], rerun.slice(0, 120));
  ok('filling the reader column ADDS checks rather than replacing them', m2 && Number(m2[2]) >= 30, m2 && m2[2]);
}

// ---------------------------------------------------------------------------
// the instruments actually move
// ---------------------------------------------------------------------------
{
  const paint = () => page.evaluate(() => {
    const cv = document.getElementById('chaoscv');
    const g = cv.getContext('2d').getImageData(0, 0, cv.width, cv.height).data;
    let sum = 0; const seen = new Set();
    for (let i = 0; i < g.length; i += 4 * 97) { sum += g[i] + g[i + 1] + g[i + 2] + g[i + 3]; seen.add(`${g[i]},${g[i + 1]},${g[i + 2]}`); }
    return { sum, colours: seen.size };
  });
  const p1 = await paint();
  ok('the trajectory canvas paints more than a flat field', p1.colours > 2 && p1.sum > 0, JSON.stringify(p1));
  await page.selectOption('#chaospair', { index: 5 });
  await page.waitForTimeout(120);
  const p2 = await paint();
  ok('choosing a different disagreement repaints the canvas', p2.sum !== p1.sum, `${p1.sum} then ${p2.sum}`);

  const kv = await page.textContent('#chaoskv');
  ok('the trajectory readout names an outcome rather than always printing a step',
    /separated at step \d+|ANNIHILATED at step \d+|neither separated/.test(kv), kv.slice(0, 120));

  await page.click('#chaossweep');
  await page.waitForFunction(() => document.getElementById('chaossweepout').textContent.length > 40, null, { timeout: 120000 });
  const sweep = await page.textContent('#chaossweepout');
  ok('the sweep reports separations, annihilations and the Lyapunov exponent',
    /separated/.test(sweep) && /annihilated/.test(sweep) && /Lyapunov/.test(sweep), sweep.slice(0, 200));
  ok('the sweep median matches the lab', sweep.includes(`median at step ${D.CHAOS.separation.median}`), sweep.slice(0, 160));
}

{
  // instrument 1: a refusal really is reachable, and it declines to print a value
  await page.fill('#x1', '2.5');
  await page.evaluate(() => { const s = document.getElementById('prec1'); s.value = '56'; s.dispatchEvent(new Event('input')); });
  await page.waitForTimeout(80);
  const refused = await page.textContent('#verdict1');
  ok('dropping the working precision reaches a real refusal, and no number is printed',
    /REFUSED/.test(refused) && !/is \d+ double/.test(refused), refused.slice(0, 120));
  await page.evaluate(() => { const s = document.getElementById('prec1'); s.value = '160'; s.dispatchEvent(new Event('input')); });
  await page.waitForTimeout(80);
  const decided = await page.textContent('#verdict1');
  ok('raising it again decides the same argument', !/REFUSED/.test(decided), decided.slice(0, 120));

  // and the hunt finds a real disagreement in this engine
  await page.selectOption('#fn1', 'exp');
  await page.waitForTimeout(60);
  await page.click('#huntbtn');
  await page.waitForTimeout(400);
  const hunted = await page.textContent('#verdict1');
  ok('the hunt finds an argument this engine gets wrong', /double(s)? too (high|low)/.test(hunted), hunted.slice(0, 120));
  const shown = await page.$$eval('#bits1 .diff', (n) => n.length);
  ok('the differing bits are highlighted in the 64-bit view', shown > 0, `${shown} highlighted`);

  // sqrt, the control, in the same instrument
  await page.selectOption('#fn1', 'sqrt');
  await page.waitForTimeout(60);
  await page.click('#huntbtn');
  await page.waitForTimeout(2000);
  const sq = await page.textContent('#verdict1');
  ok('the same hunt on sqrt walks every argument and finds nothing',
    /got every one of them right/.test(sq), sq.slice(0, 140));

  // THE VACUOUS SETTING. The slider's minimum is a position at which the
  // reference decides nothing, and the hunt used to report that as a clean
  // sweep in the green class. Drive the real control to the real minimum and
  // require the page to refuse instead. This is the one assertion in this file
  // that a previous version of the page would have failed.
  const min = await page.getAttribute('#prec1', 'min');
  ok('the working-bits slider really can be dragged to 54', min === '54', String(min));
  await page.selectOption('#fn1', 'exp');
  await page.evaluate((v) => { const s2 = document.getElementById('prec1'); s2.value = v; s2.dispatchEvent(new Event('input')); }, min);
  await page.waitForTimeout(80);
  await page.click('#huntbtn');
  await page.waitForFunction(() => document.getElementById('verdict1').textContent.length > 40, null, { timeout: 120000 });
  const vac = await page.textContent('#verdict1');
  ok('at the slider minimum the hunt REFUSES rather than declaring the engine clean',
    /REFUSED/.test(vac) && !/got every one of them right/.test(vac) && !/every one right/.test(vac),
    vac.slice(0, 160));
  ok('and it says how many arguments it actually judged there',
    /could not decide a single one/.test(vac), vac.slice(0, 90));
  const cls = await page.getAttribute('#verdict1', 'class');
  ok('and it is not painted as a passing result', !/ ok$| ok /.test(cls || ''), String(cls));
  await page.evaluate(() => { const s2 = document.getElementById('prec1'); s2.value = '160'; s2.dispatchEvent(new Event('input')); });
  await page.waitForTimeout(80);

  // THE SECOND VACUOUS SETTING, and it needs no slider: an argument at which no
  // conforming implementation is allowed to differ. Zero, an overflow, and a
  // perfect square all used to print "your engine is exactly right here" in the
  // green class, which is a fact about ECMA-262 wearing the clothes of a
  // measurement. Each is driven here, at the page's own default precision.
  for (const [fn, x, why] of [
    ['exp', '0', 'a pinned boundary value'],
    ['sin', '0', 'a pinned boundary value'],
    ['exp', '1000', 'an overflow to infinity'],
    ['exp', '-1000', 'an underflow to zero'],
    ['sqrt', '4', 'a perfect square'],
    ['cbrt', '8', 'a perfect cube'],
  ]) {
    await page.selectOption('#fn1', fn);
    await page.fill('#x1', x);
    await page.waitForTimeout(120);
    const v = await page.textContent('#verdict1');
    const c = await page.getAttribute('#verdict1', 'class');
    ok(`Math.${fn}(${x}) is disclosed as ${why} rather than scored as a pass`,
      /NOTHING MEASURED HERE/.test(v) && !/\bok\b/.test(c || ''), `${(c || '').trim()} · ${v.slice(0, 80)}`);
  }
  await page.selectOption('#fn1', 'exp');
  await page.fill('#x1', '1.4141');
  await page.waitForTimeout(120);
  const ordinary = await page.textContent('#verdict1');
  ok('CONTROL, MUST NOT FIRE: an ordinary argument is still scored normally',
    !/NOTHING MEASURED HERE/.test(ordinary), ordinary.slice(0, 90));
}

{
  await page.click('#runtmd');
  await page.waitForFunction(() => /hardest one found/.test(document.getElementById('tmdstatus').textContent), null, { timeout: 120000 });
  const bars = await page.$$eval('#tmdbars .bar', (b) => b.length);
  ok('the margin histogram draws a measured and a predicted bar per margin', bars >= 16, String(bars));
  const widths = await page.$$eval('#tmdbars .fill',
    (f) => f.slice(0, 8).map((x) => Math.round(x.getBoundingClientRect().width)));
  ok('the histogram bars have real width rather than collapsing to nothing',
    widths.every((w) => w > 0) && widths[0] > 50, widths.join(' '));
  ok('the measured and predicted bars halve together, which is the whole claim',
    widths[0] / widths[2] > 1.5 && widths[0] / widths[2] < 2.6
    && widths[1] / widths[3] > 1.8 && widths[1] / widths[3] < 2.2,
    `measured ${widths[0]}/${widths[2]}, predicted ${widths[1]}/${widths[3]}`);
  const tmd = await page.textContent('#tmdstatus');
  ok('the margin readout names the hardest argument it found', /x = /.test(tmd), tmd.slice(0, 160));

  await page.click('#runstair');
  await page.waitForFunction(() => document.querySelectorAll('#stairtable tbody tr').length >= 10, null, { timeout: 180000 });
  const stair = await page.$$eval('#stairtable tbody tr', (rs) => rs.map((r) => [...r.children].map((c) => c.textContent)));
  ok('the refusal staircase falls to zero as the precision rises',
    Number(stair[0][1]) > 0 && Number(stair[stair.length - 1][1]) === 0,
    `${stair[0][0]} bits: ${stair[0][1]}; ${stair[stair.length - 1][0]} bits: ${stair[stair.length - 1][1]}`);
}

{
  // the latitude table, and the toggle
  const rows = await page.$$eval('#lattable tbody tr', (rs) => rs.length);
  ok('the latitude table lists every function the standard names', rows >= 23, String(rows));
  const note26 = await page.textContent('#latnote');
  ok('the 17th edition note says sqrt is NOT on the list', /Math\.sqrt is NOT among them/.test(note26), note26);
  await page.click('#editionbtns button');
  await page.waitForTimeout(80);
  const note24 = await page.textContent('#latnote');
  ok('switching to the 15th edition flips that sentence', /Math\.sqrt IS among them/.test(note24), note24);

  const sig = await page.textContent('#signote');
  ok('the signature panel names how many probes actually separate engines',
    /of the \d+ rows split the engines/.test(sig), sig.slice(0, 140));
  ok('the signature panel states plainly that it stores and sends nothing',
    /stores nothing and sends nothing/.test(sig));
}

// ---------------------------------------------------------------------------
// layout
// ---------------------------------------------------------------------------
// Each breakpoint gets a FRESH page loaded at that width, and is measured both
// before and after the census fills a whole extra column. An earlier version of
// this block resized a page that had been laid out at 1200px and then poked at
// for a minute, and it passed 390px green while a phone loading the page cold
// scrolled sideways by 73 pixels. A resize is not a load.
for (const w of [360, 390, 768, 1200, 1440]) {
  const vp = await browser.newPage({ viewport: { width: w, height: 900 } });
  await vp.goto(URL_, { waitUntil: 'networkidle' });
  await vp.waitForFunction(() => window.__rounding && window.__rounding.ready === true, null, { timeout: 40000 });
  const measure = () => vp.evaluate(() => {
    const doc = document.documentElement.scrollWidth;
    const win = window.innerWidth;
    const wide = [];
    if (doc > win + 1) {
      for (const n of document.querySelectorAll('main *')) {
        const r = n.getBoundingClientRect();
        // an element inside its own scrolling container is fine: its layout box
        // sticks out but the page does not
        let scrolls = false;
        for (let p = n.parentElement; p; p = p.parentElement) {
          if (getComputedStyle(p).overflowX === 'auto' || getComputedStyle(p).overflowX === 'scroll') { scrolls = true; break; }
        }
        if (!scrolls && r.right > win + 1) wide.push(`${n.tagName}.${(n.className || '').toString().split(' ')[0]}@${Math.round(r.right)}`);
      }
    }
    return { doc, win, wide: wide.slice(0, 6) };
  });
  const cold = await measure();
  ok(`no horizontal overflow at ${w}px on a cold load`, cold.doc <= cold.win + 1,
    `${cold.doc} vs ${cold.win} ${cold.wide.join(' ')}`);

  await vp.click('#runcensus');
  await vp.waitForFunction(() => window.__rounding.you.census !== null, null, { timeout: 240000 });
  const warm = await measure();
  ok(`no horizontal overflow at ${w}px after the census adds a column`, warm.doc <= warm.win + 1,
    `${warm.doc} vs ${warm.win} ${warm.wide.join(' ')}`);
  await vp.close();
}
await page.close();

// ---------------------------------------------------------------------------
// pass 2: reduced motion
// ---------------------------------------------------------------------------
{
  const rm = await browser.newPage({ viewport: { width: 900, height: 900 }, reducedMotion: 'reduce' });
  const e2 = [];
  rm.on('pageerror', (e) => e2.push(String(e)));
  rm.on('console', (m) => { if (m.type() === 'error') e2.push(m.text()); });
  await rm.goto(URL_, { waitUntil: 'networkidle' });
  await rm.waitForFunction(() => window.__rounding && window.__rounding.ready === true, null, { timeout: 40000 });
  ok('the page loads clean under prefers-reduced-motion: reduce', e2.length === 0, e2.join(' | '));
  const head = await rm.textContent('#checkhead');
  const m = head.match(/(\d+)\s*\/\s*(\d+) checks pass/);
  ok('the check panel still passes under reduced motion', m && m[1] === m[2], head.slice(0, 120));
  const painted = await rm.evaluate(() => {
    const cv = document.getElementById('chaoscv');
    const g = cv.getContext('2d').getImageData(0, 0, cv.width, cv.height).data;
    let s = 0; for (let i = 0; i < g.length; i += 401) s += g[i];
    return s;
  });
  ok('a representative static frame is painted under reduced motion', painted > 0, String(painted));
  await rm.close();
}

// ---------------------------------------------------------------------------
// accessibility floor
// ---------------------------------------------------------------------------
{
  const a11y = await browser.newPage({ viewport: { width: 1100, height: 900 } });
  await a11y.goto(URL_, { waitUntil: 'networkidle' });
  await a11y.waitForFunction(() => window.__rounding && window.__rounding.ready === true, null, { timeout: 40000 });
  const audit = await a11y.evaluate(() => {
    const controls = [...document.querySelectorAll('input,select')];
    const unlabelled = controls.filter((n) => !(
      (n.id && document.querySelector(`label[for="${n.id}"]`))
      || n.getAttribute('aria-label')
      || n.closest('label')));
    const labelled = unlabelled.length === 0;
    return {
      labelled,
      unlabelled: unlabelled.map((n) => n.tagName + '#' + (n.id || '(no id)')),
      liveRegions: document.querySelectorAll('[aria-live="polite"]').length,
      pressed: document.querySelectorAll('[aria-pressed]').length,
      canvasHidden: [...document.querySelectorAll('canvas')].every((c) => c.getAttribute('aria-hidden') === 'true'),
      captions: document.querySelectorAll('table caption').length,
      h1: document.querySelectorAll('h1').length,
      h2: document.querySelectorAll('main h2').length,
      lang: document.documentElement.lang,
      focusRule: [...document.styleSheets].some((s) => {
        try { return [...s.cssRules].some((r) => /focus-visible/.test(r.cssText)); } catch { return false; }
      }),
    };
  });
  ok('every control has a real label or aria-label', audit.labelled, audit.unlabelled.join(' '));
  ok('readouts are polite live regions', audit.liveRegions >= 5, String(audit.liveRegions));
  ok('toggles carry aria-pressed', audit.pressed >= 3, String(audit.pressed));
  ok('canvases whose values are duplicated in text are aria-hidden', audit.canvasHidden);
  ok('every table carries a caption', audit.captions >= 5, String(audit.captions));
  ok('exactly one h1', audit.h1 === 1);
  ok('the page has numbered sections', audit.h2 >= 7, String(audit.h2));
  ok('the document declares its language', audit.lang === 'en');
  ok('a focus-visible rule is present', audit.focusRule);

  const kb = await a11y.evaluate(() => {
    const b = document.getElementById('runtmd');
    b.focus();
    return document.activeElement === b;
  });
  ok('buttons take keyboard focus', kb);
  await a11y.close();
}

// ---------------------------------------------------------------------------
// head and chrome
// ---------------------------------------------------------------------------
{
  const html = readFileSync(join(ROOT, 'public', 'strata', SLUG, 'index.html'), 'utf8');
  const need = [
    ['charset', /<meta charset="utf-8"/],
    ['viewport', /name="viewport"/],
    ['canonical', new RegExp(`rel="canonical" href="https://artwaste\\.land/strata/${SLUG}/"`)],
    ['theme-color', /name="theme-color"/],
    ['fonts stylesheet', /href="\/fonts\/fonts\.css"/],
    ['home banner', /src="\/media\/home-banner\.js"/],
    ['twitter summary_large_image', /content="summary_large_image"/],
    ['ld+json Article', /"@type":"Article"/],
    ['og image 1200x630', /og:image:width" content="1200"[\s\S]*og:image:height" content="630"/],
  ];
  for (const [what, re] of need) ok(`head carries ${what}`, re.test(html));
  ok('nine og tags', (html.match(/property="og:/g) || []).length >= 9, String((html.match(/property="og:/g) || []).length));
  ok('four twitter tags', (html.match(/name="twitter:/g) || []).length >= 4, String((html.match(/name="twitter:/g) || []).length));
  ok('three favicon links', (html.match(/rel="(icon|apple-touch-icon)"/g) || []).length >= 3);
  ok('the closing tags are present', /<\/script>\s*<\/body>\s*<\/html>\s*$/.test(html.trim() + '\n'));
  const t = html.match(/<title>([^<]*)<\/title>/)[1];
  ok('the search-facing title leads with the query and is about 60 characters',
    t.length >= 30 && t.length <= 72, `${t.length}: ${t}`);
  const desc = html.match(/name="description" content="([^"]*)"/)[1];
  ok('the meta description is the dek', desc.length > 120);
}

// ---------------------------------------------------------------------------
// the reproduce trail, and the frontmatter
// ---------------------------------------------------------------------------
{
  const md = join(ROOT, 'src', 'content', 'strata', `${SLUG}.md`);
  ok('the frontmatter file exists', existsSync(md));
  if (existsSync(md)) {
    const s = readFileSync(md, 'utf8');
    ok('frontmatter: draft flipped to false by the orchestrator at landing', /^draft: false$/m.test(s));
    ok('frontmatter tags include immersive and interactive', /"immersive"/.test(s) && /"interactive"/.test(s));
    ok('frontmatter href points at the page', s.includes(`href: "/strata/${SLUG}/"`));
    const plain = s.match(/^plain: "([\s\S]*?)"\n/m);
    ok('plain is present and inside the length rule', plain && plain[1].length >= 90 && plain[1].length <= 420,
      plain ? String(plain[1].length) : 'missing');
    ok('plain has no em dash and at most three sentences',
      plain && !/—/.test(plain[1]) && (plain[1].match(/\.\s|\.$/g) || []).length <= 3);
    const relates = (s.match(/^\s+- to: /gm) || []).length;
    ok('between two and five relates edges', relates >= 2 && relates <= 5, String(relates));

    // The dek is published prose and is held to the page's rule: every figure in
    // it is matched as a string against the recomputed value.
    const dek = s.match(/^dek: "([\s\S]*?)"\n/m)[1];
    const deep = D.CENSUSDEEP.engines;
    const pctD = (r, d) => (100 * r).toFixed(d) + '%';
    const dekFigures = [
      ['the fdlibm exp rate', pctD(deep.chromium.byFunction.exp.rate, 2)],
      ['the system-library exp rate', pctD(deep.webkit.byFunction.exp.rate, 3)],
      ['the deep sample size', D.CENSUSDEEP.n.toLocaleString('en-US')],
      ['the committed value count', (D.N * D.FUNCTIONS.length).toLocaleString('en-US')],
      // spelled out in the dek, because honest-numbers reads a bare digit beside
      // a corpus noun as a claim the site is making about itself
      ['the latitude list length', ({ 21: 'twenty-one', 22: 'twenty-two', 23: 'twenty-three', 24: 'twenty-four' })[D.SPEC.editions.es2026.latitudeList.length] || String(D.SPEC.editions.es2026.latitudeList.length)],
      ['the median separation', String(D.CHAOS.separation.median)],
      ['the predicted separation', D.CHAOS.predictedSteps.toFixed(2)],
      ['the annihilation count', String(D.CHAOS.annihilated.n)],
      ['the pairs measured', String(D.CHAOS.argsWhereExpDiffers)],
      ['the cross-check size', D.CROSSCHECK.comparisons.toLocaleString('en-US')],
      ['the function count', String(D.FUNCTIONS.length)],
    ];
    for (const [what, v] of dekFigures) {
      ok(`the dek states ${what} as the recomputed value`, dek.includes(v), v);
    }
    ok('the dek names the clause the quotes come from', dek.includes('21.3.2'));
    ok('the dek has no em dash', !/—/.test(dek));
    // The shareable surface is where a retracted claim survives longest, because
    // nothing on the page renders it. Both of these were true in the dek after
    // the body had stopped saying them.
    ok('the dek does not credit the zero sqrt row to the JavaScript standard',
      !/the reason is a one-line change/.test(dek) && /IEEE 754/.test(dek));
    ok('and neither does plain', plain && !/because the standard was changed in 2025 to require it/.test(plain[1])
      && /IEEE 754/.test(plain[1]));
    const nTwo = D.FUNCTIONS.filter((f) => {
      const ks = Object.keys(D.ENGINES);
      const p = Object.fromEntries(ks.map((k) => [k, k]));
      const find = (x) => (p[x] === x ? x : (p[x] = find(p[x])));
      for (const key of Object.keys(D.SUMMARY.agreement)) {
        const [a, b] = key.split('/');
        if (D.SUMMARY.agreement[key][f].differing === 0) p[find(a)] = find(b);
      }
      return new Set(ks.map(find)).size === 2;
    }).length;
    const NUM = { 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight' };
    ok('the dek scopes the two-camp claim to the functions where it holds, and counts them',
      !/They fall into two camps and the camps are the wrong way round/.test(dek)
      && dek.includes(`On ${NUM[nTwo]} of the eight functions`),
      `${NUM[nTwo]} of eight return exactly two distinct answers`);
    for (const [what, re] of [
      ['the meta description', /name="description" content="([^"]*)"/],
      ['the og description', /property="og:description" content="([^"]*)"/],
      ['the twitter description', /name="twitter:description" content="([^"]*)"/],
      ['the JSON-LD description', /"description":"([^"]*)"/],
    ]) {
      const pageHtml = readFileSync(join(ROOT, 'public', 'strata', SLUG, 'index.html'), 'utf8');
      const m = pageHtml.match(re);
      ok(`${what} makes no sqrt claim the body has retracted`,
        m && !/standard was changed in 2025/.test(m[1]) && !/two maths libraries/.test(m[1]),
        m ? m[1].slice(0, 60) : 'missing');
    }

    const plainTxt = plain ? plain[1] : '';
    ok('plain uses no selling words', !/\b(amazing|stunning|incredible|revolutionary|must-see)\b/i.test(plainTxt));
    ok('plain has no unescaped double quote', !/[^\\]"/.test(plainTxt));
  }
  for (const f of ['verify.mjs', '00-spec-quotes.mjs', '01-capture-traces.mjs', '02-reference-table.mjs',
    '03-cross-check-python.mjs', '04-census.mjs', '05-negative-controls.mjs', '06-hard-to-round.mjs',
    '07-one-bit-becomes-everything.mjs', '08-build-page-data.mjs', '09-glibc-table.mjs',
    '10-deep-census.mjs', '11-firefox-source.mjs', '12-tan-real-ulp.mjs', '13-first-edition.mjs',
    'pyref.py', 'README.md', 'PREDICTIONS.md',
    'data/census-deep-departures.json', 'data/tan-real-ulp.json', 'data/spec-first-edition.json']) {
    ok(`research/${SLUG}/${f} exists`, existsSync(join(ROOT, 'research', SLUG, f)));
  }
  for (const f of ['reference.mjs', 'ulp.mjs', 'chaos.mjs', 'page.js', 'data.js', 'index.html']) {
    ok(`public/strata/${SLUG}/${f} exists`, existsSync(join(ROOT, 'public', 'strata', SLUG, f)));
  }
}

await browser.close();
server.close();

console.log(`\n${fails === 0 ? 'PASS' : 'FAIL'}: ${fails} failing`);
if (fails) { console.log('failures:'); for (const f of failed) console.log('  - ' + f); }
process.exit(fails === 0 ? 0 : 1);
