#!/usr/bin/env node
// verify.mjs — the offline mirror (Tier A).
//
// Everything the page claims, re-derived on the command line from the committed
// files, by importing the SAME modules the page imports. No copy of any rule
// lives here. What lives here is the ground truth of the golden traces: which
// engine produced each file, and what the reduction is required to say about it.
//
//   node research/the-rounding-you-were-allowed/verify.mjs
//
// Exits 0 only if every check passes.

import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { execFileSync } from 'node:child_process';
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 HERE = path.dirname(fileURLToPath(import.meta.url));
const DATA = path.join(HERE, 'data');
const PAGE = path.join(HERE, '..', '..', 'public', 'strata', 'the-rounding-you-were-allowed');
const read = (f) => JSON.parse(fs.readFileSync(path.join(DATA, f), 'utf8'));

let pass = 0, fail = 0;
const fails = [];
const ok = (name, cond, detail) => {
  if (cond) { pass++; console.log(`  ok   ${name}${detail ? '  · ' + detail : ''}`); }
  else { fail++; fails.push(name); console.log(`  FAIL ${name}${detail ? '  · ' + detail : ''}`); }
};
const section = (s) => console.log(`\n· ${s} ·`);

const HTML = fs.readFileSync(path.join(PAGE, 'index.html'), 'utf8');
const PAGE_JS = fs.readFileSync(path.join(PAGE, 'page.js'), 'utf8');
const ENGINE_KEYS = ['chromium', 'firefox', 'webkit', 'node', 'glibc'];

// ---------------------------------------------------------------------------
section('the instrument can return a positive');
ok('the page HTML is substantial', HTML.length > 20000, `${HTML.length} bytes`);
ok('a string known to be present is found', HTML.includes('The Rounding Your Browser Was Allowed to Get Wrong'));
ok('a string known to be absent is not found', !HTML.includes('zzzz-not-present-zzzz'));
ok('page.js imports the shared reference rather than defining its own',
  /from '\.\/reference\.mjs'/.test(PAGE_JS) && !/function bfExp/.test(PAGE_JS));
ok('page.js imports the shared reduction rather than defining its own',
  /from '\.\/ulp\.mjs'/.test(PAGE_JS) && !/function reduce\s*\(/.test(PAGE_JS));

// ---------------------------------------------------------------------------
section('the reference, against things that cannot be argued with');
const W = 160;
ok('pi rounds to Math.PI', R.bfToDouble(R.PI(W), W, 16).value === Math.PI);
ok('ln 2 rounds to Math.LN2', R.bfToDouble(R.LN2(W), W, 16).value === Math.LN2);
ok('exp(0) is 1', R.correctlyRounded('exp', 0, W).value === 1);
ok('log(1) is 0', R.correctlyRounded('log', 1, W).value === 0);
ok('sqrt is exact on 20 perfect squares',
  Array.from({ length: 20 }, (_, i) => (i + 1) ** 2).every((n) => R.crSqrt(n) === i0(n)));
function i0(n) { return Math.round(Math.sqrt(n)); }
ok('cbrt is exact on 20 perfect cubes',
  Array.from({ length: 20 }, (_, i) => (i + 1) ** 3).every((n) => R.crCbrt(n) === Math.round(Math.cbrt(n))));
ok('cbrt(100) is 4.641588833612779, not the double below it',
  R.crCbrt(100) === 4.641588833612779 && R.crCbrt(100) !== 4.641588833612778);
{
  // the correctly-rounded cbrt(100) settled again here, by exact BigInt cubing
  // of the midpoint, so this file does not simply believe reference.mjs
  const lo = 4.641588833612778, hi = 4.641588833612779;
  const bl = R.bfFromDouble(lo, 200), bh = R.bfFromDouble(hi, 200);
  const mid = R.bfScale(R.bfAdd(bl, bh, 400), -1);
  const cube = R.bfMul(R.bfMul(mid, mid, 400), mid, 400);
  ok('the midpoint between the two candidates cubes to less than 100, so the upper one is correct',
    R.bfCmpAbs(cube, R.bfFromDouble(100, 400)) < 0);
}

{
  // The tie branch of bfToDouble is unreachable from every function this layer
  // measures: the true value of a transcendental is irrational, so it never
  // lands exactly on the boundary between two doubles, and sqrt and cbrt take
  // a different path entirely. That makes it code nothing tests, and a mutation
  // run on this file proved it: changing ties-to-even to ties-away passed all
  // 117 checks. So the branch is driven directly here, on a value constructed
  // to sit exactly halfway.
  const tie = (d) => {
    const hi = U.fromBits(U.toBits(d) + 1n);
    return { mid: R.bfScale(R.bfAdd(R.bfFromDouble(d, 300), R.bfFromDouble(hi, 300), 300), -1), lo: d, hi };
  };
  let toEven = 0, total = 0;
  const wrong = [];
  for (const d of [1, 1 + Number.EPSILON, 2, 3, 0.1, 1024.5, 1e-8, 12345.6789, -7.5]) {
    const t = tie(d);
    const got = R.bfToDouble(t.mid, 300, 16).value;
    const want = (U.toBits(t.lo) & 1n) === 0n ? t.lo : t.hi;
    total++;
    if (Object.is(got, want)) toEven++; else wrong.push(`${d}: got ${got}, ties-to-even wants ${want}`);
  }
  ok('an exact tie rounds to the even significand, on every constructed case',
    toEven === total, `${toEven} / ${total} ${wrong.join('; ')}`);
  ok('and an exact tie is reported as NOT decided, because at finite precision it means the precision ran out',
    [1, 3, 0.1].every((d) => R.bfToDouble(tie(d).mid, 300, 16).exact === false));
  ok('a value clearly on one side of the boundary is decided',
    R.bfToDouble(R.bfFromDouble(1.5, 300), 300, 16).exact === true);
}

// ---------------------------------------------------------------------------
section('the cross-check against a second, unrelated implementation');
const XC = read('cross-check.json');
ok(`${XC.comparisons} comparisons against CPython and exact rationals`, XC.disagreements === 0,
  `${XC.disagreements} disagreements, ${XC.python}`);
ok('the cross-check covered every function this layer measures, with nothing left over',
  [...XC.seriesFunctions, ...XC.exactFunctions].slice().sort().join(',') === D.FUNCTIONS.slice().sort().join(','),
  `${XC.seriesFunctions.join(',')} + ${XC.exactFunctions.join(',')}`);
ok('atan is among them, which it was not until an audit noticed the page said it was',
  XC.seriesFunctions.includes('atan'));
ok('and the comparison count is the function count times the sample size, not an average over whatever finished',
  XC.comparisons === (XC.seriesFunctions.length + XC.exactFunctions.length) * XC.n,
  `${XC.comparisons} = ${XC.seriesFunctions.length + XC.exactFunctions.length} x ${XC.n}`);
{
  // Not read from the file. The second opinion is RE-RUN here, from pyref.py,
  // against the reference this process just imported. Reading cross-check.json
  // and reporting "0 disagreements" is a check on a file, not on an arithmetic.
  const REF0 = JSON.parse(fs.readFileSync(path.join(DATA, 'reference.json'), 'utf8'));
  const argsHex = {};
  for (const f of REF0.functions) argsHex[f] = U.args(f, REF0.n).map(U.hex);
  const py = JSON.parse(execFileSync('python3', ['-c', fs.readFileSync(path.join(HERE, 'pyref.py'), 'utf8')], {
    input: JSON.stringify({ prec: XC.decimalDigits, series: XC.seriesFunctions, exact: XC.exactFunctions, args: argsHex }),
    maxBuffer: 1 << 28,
  }).toString());
  let agree = 0, total = 0;
  const off = [];
  for (const f of [...XC.seriesFunctions, ...XC.exactFunctions]) {
    const mine = U.unpackHex(REF0.values[f]);
    const theirs = U.unpackHex(py[f]);
    for (let i = 0; i < mine.length; i++) { total++; if (Object.is(mine[i], theirs[i])) agree++; else if (off.length < 3) off.push(`${f}[${i}]`); }
  }
  ok(`the second opinion RE-RUN here, not read: ${total} values recomputed in CPython at ${XC.decimalDigits} digits`,
    agree === total && total === XC.comparisons, `${agree} / ${total} ${off.join(' ')}`);
  ok('CONTROL, MUST FAIL: the same comparison against a shifted reference disagrees on nearly everything', (() => {
    const mine = U.unpackHex(REF0.values.exp).map((v) => U.fromBits(U.toBits(v) + 1n));
    const theirs = U.unpackHex(py.exp);
    return mine.filter((v, i) => Object.is(v, theirs[i])).length < mine.length * 0.01;
  })());
}

// ---------------------------------------------------------------------------
section('the golden traces: ground truth, provenance, and replay');
const REF = read('reference.json');
for (const k of ENGINE_KEYS) {
  const t = read(`trace-${k}.json`);
  // NOT `t.ua.length > 10`. That is a check whose right-hand side is a size,
  // and it passed happily on a trace whose user agent claims Macintosh while
  // the process ran on linux-x64. The host is the field the README calls the
  // ground truth, so the host is what is asserted.
  ok(`${k}: the committed trace ran on the one host this layer claims`,
    t.host === 'linux-x64' && /^\d{4}-\d{2}-\d{2}T/.test(t.capturedAt), `${t.host}, ${t.capturedAt}`);
  ok(`${k}: the trace names the build that made it, specifically enough to identify a version`,
    typeof t.ua === 'string' && /\d+\.\d+/.test(t.ua), t.ua.slice(0, 58));
  ok(`${k}: the trace holds ${REF.n} values for each of ${REF.functions.length} functions`,
    REF.functions.every((f) => t.values[f].length === REF.n * 16));
  ok(`${k}: the shipped page data rebuilds this trace byte for byte`, (() => {
    for (const f of REF.functions) {
      const rebuilt = U.packHex(U.decodeDeltas(U.unpackHex(REF.values[f]), D.ENGINES[k].deltas[f]));
      if (rebuilt !== t.values[f]) return false;
    }
    return true;
  })());
  ok(`${k}: every shipped digest is the hash of the raw captured file`,
    REF.functions.every((f) => D.ENGINES[k].digests[f] === U.fnv1a64(t.values[f])));
}
ok('the traces really are different files, not one file copied five times', (() => {
  const seen = new Set(ENGINE_KEYS.map((k) => read(`trace-${k}.json`).values.exp));
  return seen.size >= 2;
})(), `${new Set(ENGINE_KEYS.map((k) => read(`trace-${k}.json`).values.exp)).size} distinct exp traces`);
ok('the arguments file matches the generator the page uses',
  read('arguments.json').values.exp.every((h, i) => U.unhex(h) === U.args('exp', REF.n)[i]));

// the whole reference table, recomputed here rather than read
{
  let same = 0, total = 0;
  for (const f of REF.functions) {
    const xs = U.args(f, REF.n);
    const want = U.unpackHex(REF.values[f]);
    for (let i = 0; i < xs.length; i++) {
      total++;
      if (Object.is(R.correctlyRounded(f, xs[i], REF.workingBits).value, want[i])) same++;
    }
  }
  ok(`the committed reference table recomputes exactly, all ${total} values`, same === total, `${same} / ${total}`);
}

// ---------------------------------------------------------------------------
section('the reduction can fail, and does, on traces built to make it fail');
const CTRL = read('controls.json');
for (const [name, c] of Object.entries(CTRL)) ok(`control ${name}`, c.ok === true, c.expect);
{
  // the controls are re-run here from scratch, not read out of the file
  const refSqrt = U.unpackHex(REF.values.sqrt);
  ok('CONTROL re-run: sqrt is clean in all five engines',
    ENGINE_KEYS.every((k) => U.reduce(U.unpackHex(read(`trace-${k}.json`).values.sqrt), refSqrt).differing === 0));
  const bumped = refSqrt.slice();
  const idx = [1, 2, 3, 5, 8, 13, 21, 34, 55, 89];
  for (const i of idx) bumped[i] = U.fromBits(U.toBits(bumped[i]) + 1n);
  const red = U.reduce(bumped, refSqrt);
  ok('CONTROL re-run, MUST catch: ten bumped sqrt entries are found, exactly ten, all at +1',
    red.differing === 10 && red.maxUlp === 1 && red.meanSigned === 10 / REF.n,
    `${red.differing} found, max ${red.maxUlp}`);
  const mis = U.reduce(U.unpackHex(REF.values.exp), U.unpackHex(REF.values.sin));
  ok('CONTROL re-run, MUST reject: exp offered as sin', mis.rate > 0.99 && mis.maxUlp > 1e12);
  const rng = U.lcg(999331);
  const noise = refSqrt.map(() => Math.exp(rng() * 40 - 20));
  ok('CONTROL re-run, MUST reject: noise', U.reduce(noise, refSqrt).rate > 0.99);
  ok('CONTROL: a refusal is excluded from the denominator, never counted as agreement',
    U.reduce([1, 2], [1, 9], { refused: [false, true] }).n === 1);
  ok('CONTROL: with no refusals the same call counts both', U.reduce([1, 2], [1, 9]).n === 2);
}

// ---------------------------------------------------------------------------
section('the census the page prints');
for (const f of REF.functions) {
  for (const k of ENGINE_KEYS) {
    const set = new Set(REF.refused[f]);
    const want = U.unpackHex(REF.values[f]);
    const r = U.reduce(U.unpackHex(read(`trace-${k}.json`).values[f]), want, { refused: want.map((_, i) => set.has(i)) });
    if (r.rate !== D.SUMMARY.accuracy[k][f].rate || r.maxUlp !== D.SUMMARY.accuracy[k][f].maxUlp) {
      ok(`census ${k}/${f}`, false, `${r.rate}/${r.maxUlp} vs shipped ${D.SUMMARY.accuracy[k][f].rate}/${D.SUMMARY.accuracy[k][f].maxUlp}`);
    }
  }
}
ok(`all ${ENGINE_KEYS.length * REF.functions.length} census cells recompute to the shipped values`,
  !fails.some((n) => n.startsWith('census ')));
ok('sqrt is zero in every engine: the control the whole census leans on',
  ENGINE_KEYS.every((k) => D.SUMMARY.accuracy[k].sqrt.differing === 0));
ok('at least one function is NOT zero, so the census is not uniformly blind',
  ENGINE_KEYS.some((k) => REF.functions.some((f) => D.SUMMARY.accuracy[k][f].differing > 0)));
ok('WebKit and glibc agree on every committed value',
  REF.functions.every((f) => D.SUMMARY.agreement['webkit/glibc'][f].differing === 0));
// "differing > 0" was the whole of this check, which is the weakest sentence a
// check can make. The claim the page prints is a partition: which engines return
// identical bits for each function, and how many distinct answers that leaves.
// That is asserted here, function by function, against the pairwise table.
{
  const sets = (f) => {
    const p = Object.fromEntries(ENGINE_KEYS.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);
    }
    const g = {};
    for (const k of ENGINE_KEYS) (g[find(k)] = g[find(k)] || []).push(k);
    return Object.values(g).map((v) => v.join('+')).sort();
  };
  ok('sqrt is one answer across all five engines', sets('sqrt').length === 1, sets('sqrt').join(' | '));
  ok('exp, log, tan, atan and cbrt are exactly two answers, and the same two every time',
    ['exp', 'log', 'tan', 'atan', 'cbrt'].every((f) =>
      sets(f).join(' | ') === 'chromium+firefox+node | webkit+glibc'),
    ['exp', 'log', 'tan', 'atan', 'cbrt'].map((f) => `${f}: ${sets(f).join(' | ')}`).join('; '));
  ok('sine and cosine are NOT two answers: the three fdlibm-labelled engines split',
    sets('sin').length > 2 && sets('cos').length > 2,
    `sin: ${sets('sin').join(' | ')}; cos: ${sets('cos').join(' | ')}`);
  ok('and on cosine the newest V8 lands with the system library rather than with the other two',
    sets('cos').some((g) => g.includes('chromium') && g.includes('glibc'))
    && !sets('cos').some((g) => g.includes('chromium') && g.includes('firefox')),
    sets('cos').join(' | '));
  ok('CONTROL, MUST come back as one group: the partition collapses if every pair is called equal', (() => {
    const p = Object.fromEntries(ENGINE_KEYS.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('/'); p[find(a)] = find(b); }
    return new Set(ENGINE_KEYS.map(find)).size === 1;
  })());
}

// ---------------------------------------------------------------------------
section('the standard, as fetched');
const SPEC = read('spec-quotes.json');
ok('the 15th edition has sqrt on the latitude list', SPEC.editions.es2024.sqrtInLatitudeList === true);
ok('the 16th edition does not', SPEC.editions.es2025.sqrtInLatitudeList === false);
ok('the 17th edition does not', SPEC.editions.es2026.sqrtInLatitudeList === false);
ok('sqrt is the only name that left the list between the 15th and the 17th', (() => {
  const gone = SPEC.editions.es2024.latitudeList.filter((n) => !SPEC.editions.es2026.latitudeList.includes(n));
  const added = SPEC.editions.es2026.latitudeList.filter((n) => !SPEC.editions.es2024.latitudeList.includes(n));
  return gone.length === 1 && gone[0] === 'sqrt' && added.length === 0;
})());
// Section 3 used to say the zero row was "not a lucky accident of hardware" and
// then, one clause later, that the pull request's rationale was that every
// engine already did it. IEEE 754 is why the row is zero; ECMA-262 caught up.
ok('the page credits IEEE 754 for the zero row and the clause change for the permission',
  /required to be correctly rounded since 1985/.test(HTML)
  && !/not a lucky accident of hardware/.test(HTML));
ok('the 15th edition sqrt step is implementation-approximated',
  /implementation-approximated/.test(SPEC.editions.es2024.quotes.sqrtStep));
ok('the 16th edition sqrt step is the Number value for the square root',
  /^Return \u{1D53D}\(the square root of ℝ\(n\)\)\.$/u.test(SPEC.editions.es2025.quotes.sqrtStep),
  SPEC.editions.es2025.quotes.sqrtStep);
ok('exp is still implementation-approximated in the 17th edition',
  /implementation-approximated/.test(SPEC.editions.es2026.quotes.expStep));
for (const [k, e] of Object.entries(SPEC.editions)) {
  ok(`${k}: the quoted latitude sentence is intact`,
    e.quotes.latitude.endsWith('some latitude is allowed in the choice of approximation algorithms.'));
  ok(`${k}: the fdlibm recommendation is intact`,
    e.quotes.fdlibm.includes('freely distributable mathematical library from Sun Microsystems'));
  ok(`${k}: the sha256 of the fetched document is recorded`, /^[0-9a-f]{64}$/.test(e.sha256));
}
ok('the clause number for sqrt moved, and the page uses the right one per edition',
  SPEC.editions.es2024.sectionNumbers.sqrt === '21.3.2.32' &&
  SPEC.editions.es2026.sectionNumbers.sqrt === '21.3.2.33');
ok('the page prints the 15th edition clause number beside the 15th edition quote',
  HTML.includes('21.3.2.32'));
{
  // How old is the sentence? The dek said thirty years and nobody had looked.
  const S1 = read('spec-first-edition.json');
  ok('the first edition was fetched, and its sha256 is recorded',
    /^[0-9a-f]{64}$/.test(S1.sha256) && S1.publishedYear === 1997, `${S1.bytes} bytes, ${S1.sha256.slice(0, 16)}`);
  ok('the latitude sentence is in the 1997 text, word for word',
    S1.quotes.latitude.includes('some latitude is allowed in the choice of approximation algorithms'),
    `clause ${S1.clause}`);
  ok('the 1997 list named ten functions, against twenty-three now',
    S1.latitudeList.length === 10 && SPEC.editions.es2026.latitudeList.length === 23,
    S1.latitudeList.join(','));
  ok('of those ten, exactly one has left the list since, and it is sqrt', (() => {
    const gone = S1.latitudeList.filter((n) => !SPEC.editions.es2026.latitudeList.includes(n));
    return gone.length === 1 && gone[0] === 'sqrt';
  })());
  ok('the page no longer claims the sentence is thirty years old',
    !/there for thirty years/.test(HTML) && HTML.includes('since the first edition'));
}

// ---------------------------------------------------------------------------
section('measured against published');
const GL = read('glibc-bounds.json');
const DEEP = read('census-deep.json');
ok('the glibc table was fetched from the manual matching the installed library',
  GL.glibcManualVersion === '2.39' && read('trace-glibc.json').libc.includes('2.39'),
  GL.glibcManualVersion + ' / ' + read('trace-glibc.json').libc);
ok('the fetched section is 19.7', /19\.7/.test(GL.section), GL.section);
for (const f of REF.functions) {
  const pub = GL.x86_64[f];
  const m = DEEP.engines.glibc.byFunction[f].maxUlp;
  if (pub === '-') continue;
  ok(`glibc ${f}: measured ${m} whole doubles is inside the published ${pub} ulps`, m - 0.5 < Number(pub));
}
ok('glibc sqrt: no published entry, and zero measured', GL.x86_64.sqrt === '-' && DEEP.engines.glibc.byFunction.sqrt.differing === 0);
ok('glibc tan: no published entry, and NON-zero measured, which the page states',
  GL.x86_64.tan === '-' && DEEP.engines.glibc.byFunction.tan.differing > 0,
  `${DEEP.engines.glibc.byFunction.tan.differing} of ${DEEP.engines.glibc.byFunction.tan.n}`);
ok("the manual's own caveat about its table is quoted on the page",
  GL.quotes.tableIsFromTests.includes('due to the large search space'));
{
  const withBound = REF.functions.filter((f) => GL.x86_64[f] !== '-');
  ok('the prose counts the functions that carry a published bound, and gets it right',
    withBound.length === 6 && HTML.includes('Six of the eight functions carry a published number'),
    withBound.join(','));
  ok('no function with a published bound was measured outside it',
    withBound.every((f) => DEEP.engines.glibc.byFunction[f].maxUlp - 0.5 < Number(GL.x86_64[f])));
  const unbounded = REF.functions.filter((f) => GL.x86_64[f] === '-');
  ok('exactly two functions carry no published bound, and exactly one of those is not zero',
    unbounded.length === 2
    && unbounded.filter((f) => DEEP.engines.glibc.byFunction[f].differing > 0).join(',') === 'tan',
    unbounded.join(','));
  ok('the page no longer marks an unbounded function as EXCEEDING a bound it does not have',
    !PAGE_JS.includes("pubNum === null) { mark = 'EXCEEDS"));
}

// ---------------------------------------------------------------------------
section('the real error behind the integer distance');
{
  const TU = read('tan-real-ulp.json');
  const xs = U.args('tan', REF.n);
  const glibc = U.unpackHex(read('trace-glibc.json').values.tan);
  const want = U.unpackHex(REF.values.tan);
  ok('the four figures the page prints are an artifact, not a sentence',
    TU.departures.length > 0 && TU.departures.every((d) => typeof d.realUlps === 'number'),
    `${TU.departures.length} adjudications at ${TU.workingBits} bits and ${TU.decimalDigits} decimal digits`);
  ok('every adjudicated index really is a departure in the committed glibc trace',
    TU.departures.every((d) => !Object.is(glibc[d.i], want[d.i])));
  ok('the adjudication list is complete: it holds every glibc/tan departure in the sample',
    TU.departures.length === want.filter((v, i) => !Object.is(glibc[i], v)).length);
  ok('each figure recomputes here, digit for digit, through the shared reference',
    TU.departures.every((d) => Number(R.realUlpError('tan', xs[d.i], glibc[d.i], TU.workingBits).toFixed(6)) === d.realUlps),
    TU.departures.map((d) => d.realUlps.toFixed(6)).join(' '));
  ok('and the two arithmetics that produced them agreed',
    TU.maxDisagreementBetweenArithmetics < 1e-6 && TU.departures.every((d) => d.realUlps === d.realUlpsPython));
  ok('every one is over half an ulp and under one and a half, which is what one whole double means',
    TU.departures.every((d) => d.realUlps > 0.5 && d.realUlps < 1.5));
  ok('CONTROL, MUST come out UNDER half an ulp: an argument where glibc agreed', (() => {
    const i = want.findIndex((v, j) => Object.is(glibc[j], v));
    return R.realUlpError('tan', xs[i], glibc[i], TU.workingBits) < 0.5;
  })());
  ok('the four figures are nowhere typed into the page', !/0\.501, 0\.502, 0\.514 and 0\.520/.test(PAGE_JS));
}

// ---------------------------------------------------------------------------
// The deep census used to travel as a summary and nothing else. An audit forged
// two of its counts, re-ran both verifiers and the in-page panel, and every one
// of them stayed green. This is the block that would now catch it: the whole
// 20,000-argument reference is recomputed from scratch, each engine's run is
// rebuilt from its committed departures and hashed, the summary is re-reduced
// from the rebuild, and then glibc and Node are re-run live over the same
// 20,000 arguments and required to come back identical.
section('the deep census, replayed rather than believed (this takes about a minute)');
{
  const DD = read('census-deep-departures.json');
  ok('the departures file describes the same run as the summary',
    DD.n === DEEP.n && DD.workingBits === DEEP.workingBits && DD.capturedAt === DEEP.capturedAt
    && DD.host === DEEP.host, `${DD.n} args, host ${DD.host}, ${DD.capturedAt}`);

  const t0 = Date.now();
  const deepRef = {}, deepRefused = {};
  for (const f of REF.functions) {
    const xs = U.args(f, DEEP.n);
    let acc = '';
    const refd = [];
    for (let i = 0; i < xs.length; i++) {
      const r = R.correctlyRounded(f, xs[i], DEEP.workingBits);
      acc += U.hex(r.value);
      if (!r.exact) refd.push(i);
    }
    deepRef[f] = acc;
    deepRefused[f] = refd;
  }
  ok(`the 20,000-argument reference recomputes to the digest committed beside it, all ${REF.functions.length} functions`,
    REF.functions.every((f) => U.fnv1a64(deepRef[f]) === DD.referenceDigest[f]),
    `${((Date.now() - t0) / 1000).toFixed(1)} s`);
  ok('and the deep reference refused nothing at 160 bits, which the page states',
    REF.functions.every((f) => deepRefused[f].length === 0));

  const rebuilt = {};
  const badDigest = [], badSummary = [];
  for (const k of ENGINE_KEYS) {
    rebuilt[k] = {};
    for (const f of REF.functions) {
      const want = U.unpackHex(deepRef[f]);
      const run = U.decodeDeltas(want, DD.engines[k].departures[f]);
      rebuilt[k][f] = run;
      if (U.fnv1a64(U.packHex(run)) !== DD.engines[k].digest[f]) badDigest.push(`${k}/${f}`);
      const set = new Set(deepRefused[f]);
      const r = U.reduce(run, want, { refused: want.map((_, i) => set.has(i)) });
      const s = DEEP.engines[k].byFunction[f];
      if (r.n !== s.n || r.differing !== s.differing || r.rate !== s.rate || r.maxUlp !== s.maxUlp) {
        badSummary.push(`${k}/${f} ${r.differing}/${r.maxUlp} vs ${s.differing}/${s.maxUlp}`);
      }
    }
  }
  ok(`every deep run rebuilds to the digest of the raw captured values, all ${ENGINE_KEYS.length * REF.functions.length}`,
    badDigest.length === 0, badDigest.join(' '));
  ok(`every deep census cell re-reduces from the rebuilt run, all ${ENGINE_KEYS.length * REF.functions.length}`,
    badSummary.length === 0, badSummary.join(' '));

  ok('CONTROL, MUST FAIL: moving one departure changes the count the summary claims', (() => {
    const want = U.unpackHex(deepRef.tan);
    const forged = DD.engines.glibc.departures.tan.slice(0, -1);
    const run = U.decodeDeltas(want, forged);
    return U.reduce(run, want).differing !== DEEP.engines.glibc.byFunction.tan.differing;
  })());
  ok('CONTROL, MUST FAIL: a rebuilt run with one value bumped no longer hashes to its digest', (() => {
    const run = rebuilt.chromium.exp.slice();
    run[12345] = U.fromBits(U.toBits(run[12345]) + 1n);
    return U.fnv1a64(U.packHex(run)) !== DD.engines.chromium.digest.exp;
  })());

  // The ground truth. The rebuild above proves the summary agrees with the
  // departure list; only re-running the engine proves the departure list agrees
  // with the engine. Two of the five can be re-run right here.
  {
    const nodeVals = {};
    const JS = { exp: Math.exp, log: Math.log, sin: Math.sin, cos: Math.cos, tan: Math.tan, atan: Math.atan, cbrt: Math.cbrt, sqrt: Math.sqrt };
    for (const f of REF.functions) nodeVals[f] = U.packHex(U.args(f, DEEP.n).map((x) => JS[f](x)));
    ok('GROUND TRUTH: this Node, re-run over all 20,000 arguments, reproduces the committed node column byte for byte',
      REF.functions.every((f) => nodeVals[f] === U.packHex(rebuilt.node[f])),
      `${DEEP.engines.node.ua}`);
  }
  try {
    const py = `
import sys, json, math, struct
req = json.load(sys.stdin)
FN = {'exp': math.exp, 'log': math.log, 'sin': math.sin, 'cos': math.cos,
      'tan': math.tan, 'atan': math.atan, 'cbrt': math.cbrt, 'sqrt': math.sqrt}
def hx(v): return struct.pack('>d', v).hex()
def un(h): return struct.unpack('>d', bytes.fromhex(h))[0]
out = {}
for name in req['fns']:
    out[name] = ''.join(hx(FN[name](un(h))) for h in req['args'][name])
json.dump(out, sys.stdout)
`;
    const argsHex = {};
    for (const f of REF.functions) argsHex[f] = U.args(f, DEEP.n).map(U.hex);
    const got = JSON.parse(execFileSync('python3', ['-c', py], {
      input: JSON.stringify({ args: argsHex, fns: REF.functions }), maxBuffer: 1 << 28,
    }).toString());
    ok('GROUND TRUTH: glibc, re-run through python3 over all 20,000 arguments, reproduces the committed glibc column byte for byte',
      REF.functions.every((f) => got[f] === U.packHex(rebuilt.glibc[f])),
      REF.functions.filter((f) => got[f] !== U.packHex(rebuilt.glibc[f])).join(',') || 'all eight identical');
    ok('GROUND TRUTH: and that re-run is not vacuous, because glibc really does depart on tan',
      U.reduce(U.unpackHex(got.tan), U.unpackHex(deepRef.tan)).differing === DEEP.engines.glibc.byFunction.tan.differing,
      `${DEEP.engines.glibc.byFunction.tan.differing} departures found again`);
  } catch (e) {
    ok('GROUND TRUTH: glibc re-runs through python3', false, String(e && e.message).slice(0, 120));
  }
}

// ---------------------------------------------------------------------------
section('the dilemma');
const HARD = read('hard-to-round.json');
{
  const h = HARD.histogram.exp;
  const ratios = [];
  for (let k = 2; k <= 8; k++) if (h[k] && h[k + 1]) ratios.push(h[k] / h[k + 1]);
  ok('the margin histogram halves, step after step',
    ratios.every((r) => r > 1.6 && r < 2.5), ratios.map((r) => r.toFixed(2)).join(' '));
  ok('the staircase falls to zero refusals by 72 working bits',
    HARD.staircase.exp['72'].refused === 0 && HARD.staircase.exp['60'].refused > 0,
    `60 bits: ${HARD.staircase.exp['60'].refused}, 72 bits: 0`);
  ok('the committed reference at 160 bits refused nothing, and that is stated',
    REF.functions.every((f) => REF.refused[f].length === 0));
}
{
  // The working-bits slider reaches 54, and at 54 the reference decides nothing
  // at all. The hunt in section 1 used to skip every refusal and then announce,
  // in the green class, that the engine had got all thousand right: a reader-
  // reachable setting where the page's central comparison was true by
  // construction. The arithmetic fact is asserted here; the browser pass drives
  // the real slider to the real minimum and requires the refusal copy.
  const lowest = 54;
  let judged = 0;
  for (const x of U.args('exp', REF.n)) if (R.correctlyRounded('exp', x, lowest).exact) judged++;
  ok(`at the slider's lowest position (${lowest} bits) the reference decides 0 of ${REF.n} arguments`,
    judged === 0, `${judged} judged`);
  // The walk itself is in the shared module, so this is the same code the page
  // runs, not a description of it.
  const h = R.huntForDisagreement('exp', U.args('exp', REF.n), lowest);
  ok('the shared walk reports 0 judged and 1,000 refused there, rather than a clean sweep',
    h.judged === 0 && h.refused === REF.n && h.found === null,
    `found ${h.found}, judged ${h.judged}, refused ${h.refused}`);
  ok('and the page branches on that count before it says anything about your engine',
    PAGE_JS.includes('huntVerdict') && /h\.judged === 0/.test(PAGE_JS));
  const hi = R.huntForDisagreement('exp', U.args('exp', REF.n), 160);
  ok('CONTROL: at 160 bits the same walk judges every argument and DOES find a disagreement',
    hi.judged > 0 && hi.refused === 0 && hi.found !== null, `found exp(${hi.found}) at index ${hi.index}`);
  ok('CONTROL: and on sqrt at 160 bits it judges every argument and finds none, which is the control row',
    (() => { const s2 = R.huntForDisagreement('sqrt', U.args('sqrt', REF.n), 160);
      return s2.judged === REF.n && s2.refused === 0 && s2.found === null; })());
  let judgedHigh = 0;
  for (const x of U.args('exp', 200)) if (R.correctlyRounded('exp', x, 160).exact) judgedHigh++;
  ok('while at the census precision it decides every one, so the refusal is about the precision',
    judgedHigh === 200);
}
ok('the reference refuses at low precision and does not at high', (() => {
  const x = U.args('exp', 1)[0];
  return !R.correctlyRounded('exp', x, 56).exact && R.correctlyRounded('exp', x, 160).exact;
})());
{
  // The precision slider is the page's one reader-configurable comparison, so
  // the question is whether a reader can move it to a position where the
  // reference is CONFIDENT AND WRONG. That is the failure that matters: a
  // refusal is honest, but a wrong value delivered with a verdict would have
  // the page accusing a correct engine. Every position the slider can reach is
  // swept, and every answer it calls exact is checked against 260 bits.
  let confident = 0, wrong = 0;
  const first = [];
  for (let W = 54; W <= 240; W += 2) {
    for (const f of ['exp', 'log', 'sin', 'cos', 'tan', 'atan']) {
      for (const x of U.args(f, 40)) {
        const r = R.correctlyRounded(f, x, W);
        if (!r.exact) continue;
        const truth = R.correctlyRounded(f, x, 260);
        if (!truth.exact) continue;
        confident++;
        if (!Object.is(r.value, truth.value)) { wrong++; if (first.length < 3) first.push(`${f}(${x}) at W=${W}`); }
      }
    }
  }
  ok('no slider position produces a confident wrong answer: the refusal budget is not decorative',
    wrong === 0, `${confident} confident answers swept, ${wrong} wrong ${first.join('; ')}`);
  ok('and the sweep really did reach positions where it refuses, so it is not vacuous', (() => {
    let refusals = 0;
    for (const x of U.args('exp', 200)) if (!R.correctlyRounded('exp', x, 60).exact) refusals++;
    return refusals > 0;
  })());
}

// ---------------------------------------------------------------------------
section('one bit becomes the whole trajectory');
const CH = read('chaos.json');
ok('the predicted separation step is arithmetic, not a stored number',
  Math.abs(CH.predictedSteps - Math.log2(0.1 * 4503599627370498)) < 1e-9, CH.predictedSteps.toFixed(4));
// A tolerance of three steps is a tolerance of a factor of eight in the starting
// gap, on an observable whose 74 samples span four steps end to end and whose
// median therefore carries a sampling error near a fifth of a step. It could not
// have failed for any reason worth catching. The prediction is a LOWER bound by
// construction: separation is only observable at whole steps and only once the
// threshold is passed, so discretisation can delay the crossing and cannot bring
// it forward. That is the shape asserted here, and it fails in both directions.
ok('the measured median separation sits above the prediction, by less than two steps',
  CH.separation.median >= CH.predictedSteps && CH.separation.median - CH.predictedSteps < 2,
  `median ${CH.separation.median}, predicted ${CH.predictedSteps.toFixed(2)}, `
  + `spread ${CH.separation.min} to ${CH.separation.max} over ${CH.separation.n} pairs`);
ok('and every individual pair separated within one step of that spread',
  CH.separation.max - CH.separation.min <= 4 && CH.separation.min >= Math.floor(CH.predictedSteps) - 1,
  `${CH.separation.min} to ${CH.separation.max}`);
ok('the measured Lyapunov exponent is ln 2 to four decimals',
  Math.abs(CH.lyapunov.mean - Math.LN2) < 5e-4, `${CH.lyapunov.mean} vs ${Math.LN2}`);
ok('annihilation is reported as its own outcome and is not zero',
  CH.annihilated.n > 0 && CH.annihilated.n + CH.separation.n + CH.separation.never === CH.argsWhereExpDiffers,
  `${CH.separation.n} separated, ${CH.annihilated.n} annihilated, ${CH.separation.never} neither`);
ok('two identical seeds never separate, and the module says so rather than guessing',
  C.divergence(0.3, 0.3, 200, 0.1).separated === null);
ok('the seed map spans the interval rather than crowding the critical point', (() => {
  const s = [0.1, 5, 1e9, 1e-9, 123.456].map(C.seedFrom);
  return Math.max(...s) - Math.min(...s) > 0.5 && s.every((v) => v > 0 && v < 1);
})());
ok('the trajectories in the lab replay identically here', (() => {
  const a = U.decodeDeltas(U.unpackHex(REF.values.exp), D.ENGINES.chromium.deltas.exp);
  const b = U.decodeDeltas(U.unpackHex(REF.values.exp), D.ENGINES.webkit.deltas.exp);
  let n = 0;
  for (let i = 0; i < a.length; i++) if (!Object.is(a[i], b[i])) n++;
  return n === CH.argsWhereExpDiffers;
})(), `${CH.argsWhereExpDiffers} disagreements`);

// ---------------------------------------------------------------------------
section('the signature');
{
  const probe = 'Math.pow(Math.PI, -100)';
  const vals = new Set(ENGINE_KEYS.map((k) => read(`trace-${k}.json`).probes[probe].hex));
  ok('the probe split the five engines into exactly two values', vals.size === 2, [...vals].join(' '));
  const [a, b] = [...vals].map(U.unhex);
  ok('the two values are one double apart', Math.abs(U.ulpDiff(a, b)) === 1);
  // Deliberately NOT a check on the static HTML: both doubles are written into
  // the DOM at runtime from the committed source file, which is the fix for a
  // mutation that changed a digit inside the hand-typed blockquote and passed.
  // The browser pass checks the rendered text; this checks the chain behind it.
  ok('neither double is typed into the HTML, so neither can drift there',
    !HTML.includes('1.9275814160560206e-50') && !HTML.includes('1.9275814160560204e-50'));
  ok('both reach the page from data.js, through the committed comment and the committed probes',
    D.FIREFOX.powCommentDoubles.includes('1.9275814160560206e-50')
    && D.FIREFOX.powCommentDoubles.includes('1.9275814160560204e-50')
    && [...vals].map((h) => String(U.unhex(h))).sort().join(' ')
       === D.FIREFOX.powCommentDoubles.slice().sort().join(' '));
  const FF = read('firefox-source.json');
  ok('the comment committed from the Firefox source names exactly two doubles',
    FF.powCommentDoubles.length === 2, FF.powCommentDoubles.join(' '));
  // Re-extract from the comment TEXT rather than trusting the extracted list
  // beside it. Without this, a digit altered inside the quotation passes every
  // check, which a mutation run demonstrated.
  {
    const fromText = [...FF.powComment.matchAll(/\d\.\d+e-\d+/g)].map((m) => m[0]);
    ok('and the doubles re-extracted from the quoted text are exactly that list',
      fromText.join(' ') === FF.powCommentDoubles.join(' '),
      `text says ${fromText.join(' ')}, list says ${FF.powCommentDoubles.join(' ')}`);
    ok('and every double in the quoted text is one an engine actually returned',
      fromText.every((d) => [...vals].map((h) => String(U.unhex(h))).includes(d)),
      fromText.join(' '));
  }
  ok('and they are exactly the two the five engines returned',
    FF.powCommentDoubles.slice().sort().join(' ') === [...vals].map((h) => String(U.unhex(h))).sort().join(' '));
  ok('the page quotes the comment from the committed copy rather than from memory',
    PAGE_JS.includes('FIREFOX.powComment') && !HTML.includes('bionic'),
    'the blockquote is filled at runtime, so a typed digit cannot drift into it');
  ok('the pref defaults were read from StaticPrefList.yaml, and they differ by platform',
    FF.pref.windows === 'false' && FF.pref.other === 'true',
    `Windows ${FF.pref.windows}, elsewhere ${FF.pref.other}`);
  // The committed pref comment has the tail of the PREVIOUS pref's comment
  // bled into it, from a fixed-length lookback that walked past the blank line
  // between two entries. Nothing renders it, and this is what keeps it that
  // way: the moment it appears on the page it becomes a misquotation.
  ok('the pref comment field, which is known to have a neighbouring comment bled into it, is never rendered',
    !PAGE_JS.includes('pref.comment') && !HTML.includes('This allows tests to exercise the cache'),
    'the page describes the pref in its own words and reads only the two defaults');
  ok('and the extraction that produced it stops at the block boundary now',
    fs.readFileSync(path.join(HERE, '11-firefox-source.mjs'), 'utf8').includes('ends this pref\'s block'));
  ok('the recorded source sizes are labelled as character counts, not bytes',
    Object.values(FF.files).every((f) => typeof f.chars === 'number' && f.bytes === undefined),
    Object.entries(FF.files).map(([k, v]) => `${k.split('/').pop()} ${v.chars}`).join(', '));
  ok('exactly sin, cos and tan sit behind that pref',
    FF.prefGated.join(',') === 'cos,sin,tan', FF.prefGated.join(','));
  ok('pow does not: it calls the platform library', FF.powGoesThroughPlatformLibm === true);
  // The page used to add "everything else on the latitude list calls fdlibm
  // unconditionally", which is a claim about twenty-three routines drawn from a
  // file searched for two things, and false besides: Math.random is on that list
  // and approximates nothing.
  ok('the page does not claim what the rest of the latitude list is computed with',
    !/Everything else on the latitude list calls fdlibm/.test(PAGE_JS)
    && /was not read out of this file/.test(PAGE_JS));
  ok('and it says out loud that Math.random is on the list it quotes',
    /Math\.random/.test(HTML) && SPEC.editions.es2026.latitudeList.includes('random'),
    SPEC.editions.es2026.latitudeList.filter((n) => n === 'random').join(''));
  ok('sqrt(2) discloses nothing across the five',
    new Set(ENGINE_KEYS.map((k) => read(`trace-${k}.json`).probes['Math.sqrt(2)'].hex)).size === 1);
}

// ---------------------------------------------------------------------------
section('the page itself');
ok('the reproduce command named on the page exists',
  fs.existsSync(path.join(HERE, 'verify.mjs')) &&
  fs.existsSync(path.join(HERE, '..', '..', 'verify-the-rounding-you-were-allowed.mjs')));
for (const s of ['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']) {
  ok(`the page names ${s} and it exists`, HTML.includes(s) && fs.existsSync(path.join(HERE, s)));
}
ok('there is exactly one copy of the reference engine in the tree', (() => {
  const hits = [];
  const walk = (dir) => {
    for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
      if (e.name === 'node_modules' || e.name === '.git' || e.name === 'dist') continue;
      const p = path.join(dir, e.name);
      if (e.isDirectory()) walk(p);
      else if (e.name === 'reference.mjs') hits.push(p);
    }
  };
  walk(path.join(HERE, '..', '..'));
  return hits.length === 1;
})());
ok('no em dash in the page prose', !/—/.test(HTML.replace(/em dash/g, '')),
  (HTML.match(/—/g) || []).length + ' found');
// This assertion used to read "the frontmatter file exists and is a draft for
// now" and tested for `draft: true`. That was a transitional guard written while
// the page was still unpublished, and it expired the same day: the draft flag was
// flipped to false in b4dd5ca6a (2026-08-07), which left the verifier asserting a
// state the page had already left. It failed from that day until 2026-08-21, when
// the corpus-wide sweep finally surfaced it.
//
// A check that goes stale the moment the thing it guards succeeds is worse than
// no check, so this now asserts the durable pair instead: the frontmatter exists,
// it is published rather than a draft, and its href is the very page directory
// the 183 checks above were read from. That last clause is the one with teeth. It
// means this verifier cannot be pointed at one page while the entry ships another.
const FRONTMATTER = fs.readFileSync(
  path.join(HERE, '..', '..', 'src', 'content', 'strata', 'the-rounding-you-were-allowed.md'), 'utf8');
ok('the frontmatter file exists and is published, not a draft',
  /^draft:\s*false\s*$/m.test(FRONTMATTER),
  (FRONTMATTER.match(/^draft:.*$/m) || ['no draft key'])[0]);
ok('the frontmatter href is the page directory these checks read',
  (FRONTMATTER.match(/^href:\s*"([^"]+)"/m) || [])[1] === '/strata/' + path.basename(PAGE) + '/',
  (FRONTMATTER.match(/^href:\s*"([^"]+)"/m) || [, 'no href'])[1] + ' vs /strata/' + path.basename(PAGE) + '/');

// ---------------------------------------------------------------------------
console.log(`\n${pass} / ${pass + fail} checks pass`);
if (fail) { console.log('\nfailures:'); for (const f of fails) console.log('  - ' + f); }
process.exit(fail === 0 ? 0 : 1);
