#!/usr/bin/env node
/**
 * verify-the-shape-of-an-ending.mjs
 *
 * The page at /strata/the-shape-of-an-ending/ makes exactly one claim of its own:
 * that ordering thirteen mathematical endings by the SIZE of the object a skeptic
 * must check gives a different ordering from sorting the same members by HOW LONG
 * the question stayed open. Everything else on the page is attributed to the layer
 * it links to.
 *
 * So this script does not restate the page's table. It reads the shipped HTML,
 * pulls out the RAW figures (page counts, edge counts, published file sizes, and
 * the literal text of the four objects the page is physically holding), rebuilds
 * both axes from scratch with its own arithmetic, and then tests the claim with a
 * DIFFERENT formula from the one the browser uses: the page computes Spearman as
 * Pearson-on-ranks, this file computes it from sum of squared rank differences.
 * If the two agree, two independent routes reached the same number.
 *
 * It also runs the page's own robustness promises:
 *   - the ordering does not change anywhere in the characters-per-page slider range;
 *   - the conclusion survives moving the one card whose start date is only a bound.
 *
 * Run:  node research/the-shape-of-an-ending/verify-the-shape-of-an-ending.mjs
 * Exit non-zero on any failure. No dependencies, no network.
 */

import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, '..', '..');
const PAGE = path.join(ROOT, 'public/strata/the-shape-of-an-ending/index.html');
const STRATA = path.join(ROOT, 'src/content/strata');

let failures = 0;
const pass = (m) => console.log(`  ok    ${m}`);
const fail = (m) => { console.error(`  FAIL  ${m}`); failures++; };
const ok = (cond, m) => (cond ? pass(m) : fail(m));
const head = (m) => console.log(`\n${m}`);

/* ------------------------------------------------------------------ the page */
if (!fs.existsSync(PAGE)) { console.error(`missing page: ${PAGE}`); process.exit(1); }
const html = fs.readFileSync(PAGE, 'utf8');

/* The verifier's OWN constants. They are deliberately typed here rather than read
   from the page, and then compared with the page's: if either side drifts, the
   comparison below goes red instead of both quietly agreeing on a new number. */
const V = { PAGE_YEAR: 2026, DEFAULT_BPP: 2000, LOG_LO: 1.5, LOG_HI: 14.5, YR_LO: 0, YR_HI: 120 };

head('1. the page declares the same axis geometry this verifier assumes');
for (const [k, want] of Object.entries(V)) {
  const m = html.match(new RegExp(`\\b${k}\\s*=\\s*(-?[0-9.]+)`));
  if (!m) { fail(`page does not declare ${k}`); continue; }
  ok(Number(m[1]) === want, `${k} = ${want} in both the page and this verifier`);
}

/* ------------------------------------------------------ rows out of the markup */
function decodeEntities(s) {
  return s
    .replace(/&lt;/g, '<').replace(/&gt;/g, '>')
    .replace(/&quot;/g, '"').replace(/&#39;/g, "'")
    .replace(/&#(\d+);/g, (_, d) => String.fromCodePoint(Number(d)))
    .replace(/&amp;/g, '&');
}
function attrs(tag) {
  const out = {};
  for (const m of tag.matchAll(/([a-z-]+)="([^"]*)"/g)) out[m[1]] = m[2];
  return out;
}

const rowTags = [...html.matchAll(/<div class="row"([\s\S]*?)>\s*<div class="rname"><a href="([^"]+)">([^<]+)<\/a>/g)];
if (rowTags.length === 0) { console.error('no rows found in the page'); process.exit(1); }

const rows = rowTags.map(([, attrBlob, href, title]) => {
  const a = attrs(attrBlob);
  return {
    slug: a['data-slug'],
    href,
    title,
    kind: a['data-kind'],
    flag: a['data-flag'],
    check: a['data-check'],
    pages: a['data-pages'] ? Number(a['data-pages']) : null,
    pagesLo: a['data-pages-lo'] ? Number(a['data-pages-lo']) : null,
    pagesHi: a['data-pages-hi'] ? Number(a['data-pages-hi']) : null,
    edges: a['data-edges'] ? Number(a['data-edges']) : null,
    maxVertex: a['data-max-vertex'] ? Number(a['data-max-vertex']) : null,
    fixedBytes: a['data-bytes'] ? Number(a['data-bytes']) : null,
    posed: a['data-posed'] === 'none' ? null : Number(a['data-posed']),
    posedBound: a['data-posed-bound'] === 'true',
    open: a['data-ended'] === 'open',
    ended: (a['data-ended'] === 'open' || a['data-ended'] === 'none') ? null : Number(a['data-ended'])
  };
});

head('2. every member links to a stratum that exists');
ok(rows.length === 13, `the rail carries 13 rows (found ${rows.length})`);
for (const r of rows) {
  const md = path.join(STRATA, `${r.slug}.md`);
  ok(fs.existsSync(md), `src/content/strata/${r.slug}.md exists`);
  ok(r.href === `/strata/${r.slug}/`, `${r.slug}: href matches its slug`);
}
{
  const slugs = new Set(rows.map((r) => r.slug));
  ok(slugs.size === rows.length, 'no member appears twice');
}

head('3. the hazard the spec named: this page is not Past the Last Case');
ok(/href="\/strata\/past-the-last-case\/"/.test(html),
  'the page links to past-the-last-case');
ok(fs.existsSync(path.join(STRATA, 'past-the-last-case.md')),
  'past-the-last-case.md exists');
ok(/logical<\/b>[\s\S]{0,220}physical<\/b>/.test(html),
  'the page states the logical / physical difference in one sentence');

/* ------------------------------------------------- the four measured payloads */
head('4. the four measured sizes are byte counts of text this file is holding');
const payloads = new Map();
for (const m of html.matchAll(/<code class="payload" data-payload-for="([^"]+)">([\s\S]*?)<\/code>/g)) {
  payloads.set(m[1], decodeEntities(m[2]));
}
for (const r of rows.filter((x) => x.kind === 'payload')) {
  const p = payloads.get(r.slug);
  ok(typeof p === 'string' && p.length > 0, `${r.slug}: the object is printed on the page`);
  ok(p === p.trim(), `${r.slug}: the payload has no stray leading or trailing space`);
}
{
  // structural checks on what each payload actually IS, so a corrupted object
  // cannot pass as a plausible byte count.
  const sites = payloads.get('weaire-phelan');
  ok((sites.match(/\(/g) || []).length === 8, 'Weaire-Phelan: exactly 8 sites are printed');
  ok(sites.split(/\s+/).every((s) => /^\(\d,\d,\d\)$/.test(s)),
    'Weaire-Phelan: every site is an integer triple');

  const crit = payloads.get('bhargava-290').split(', ').map(Number);
  ok(crit.length === 29, 'Bhargava-Hanke: exactly 29 critical integers');
  ok(crit[0] === 1 && crit[28] === 290, 'Bhargava-Hanke: the list runs 1 to 290');
  ok(crit.every((v, i) => i === 0 || v > crit[i - 1]), 'Bhargava-Hanke: strictly increasing');

  const z = payloads.get('zagier-involution');
  ok(z.includes('x^2 + 4yz = p'), 'Zagier: the invariant is present');
  ok((z.match(/\|->/g) || []).length === 2, 'Zagier: both involutions are present');
  ok(z.trim().endsWith('also has a fixed point.'), 'Zagier: the sentence is complete');

  const eqs = payloads.get('robbins-eqp').split('; ');
  ok(eqs.length === 17, `EQP: 2 inputs plus 15 derived equations (found ${eqs.length})`);
  ok(eqs.every((e) => e.split('=').length === 2), 'EQP: every line is one equation');
  ok(eqs.every((e) => (e.match(/\(/g) || []).length === (e.match(/\)/g) || []).length),
    'EQP: every equation is balanced');
}

/* ------------------------------------------------------------- the size axis */
function sizeBytes(r, bpp) {
  switch (r.kind) {
    case 'payload': return Buffer.byteLength(payloads.get(r.slug), 'utf8');
    case 'pages':   return r.pages * bpp;
    case 'range':   return Math.sqrt(r.pagesLo * bpp * r.pagesHi * bpp);
    case 'edges':   return r.edges * (String(r.maxVertex).length * 2 + 2);
    case 'fixed':   return r.fixedBytes;
    default:        return null;
  }
}
function yearsOpen(r) {
  if (r.posed === null) return null;
  return (r.open ? V.PAGE_YEAR : r.ended) - r.posed;
}
const posSize = (b) => Math.max(0, Math.min(100,
  (Math.log10(b) - V.LOG_LO) / (V.LOG_HI - V.LOG_LO) * 100));
const posYears = (y) => Math.max(0, Math.min(100,
  (y - V.YR_LO) / (V.YR_HI - V.YR_LO) * 100));

head('5. every axis position is recomputed from the raw figure');
const sized = rows.filter((r) => sizeBytes(r, V.DEFAULT_BPP) !== null);
ok(sized.length === 10, `10 members carry a size (found ${sized.length})`);
ok(rows.filter((r) => r.kind === 'none').length === 3,
  '3 members are marked as carrying no object at all');
for (const r of sized) {
  const b = sizeBytes(r, V.DEFAULT_BPP);
  const p = posSize(b);
  ok(Number.isFinite(b) && b > 0, `${r.slug}: size resolves to ${Math.round(b)} bytes`);
  ok(p > 0 && p < 100, `${r.slug}: lands strictly inside the drawn axis at ${p.toFixed(1)}%`);
}
{
  const bs = sized.map((r) => sizeBytes(r, V.DEFAULT_BPP));
  const span = Math.log10(Math.max(...bs) / Math.min(...bs));
  ok(Math.floor(span) === 12, `the size axis spans ${span.toFixed(1)} orders of magnitude`);
  ok(/twelve orders of\s+magnitude|twelve orders of magnitude/.test(html),
    'the page says twelve orders of magnitude, and it is twelve');
  const asc = [...sized].sort((a, b2) => sizeBytes(a, V.DEFAULT_BPP) - sizeBytes(b2, V.DEFAULT_BPP));
  ok(asc.map((r) => r.slug).join() === sized.map((r) => r.slug).join(),
    'the rows are written in ascending order of size, as the page claims');
}

head('6. years open is recomputed from the two dates on each card');
const dated = rows.filter((r) => yearsOpen(r) !== null);
ok(dated.length === 12, `12 members carry both dates (found ${dated.length})`);
ok(rows.filter((r) => r.posed === null).length === 1,
  'exactly one member has no dates at all (the 290 theorem preprint)');
for (const r of dated) {
  const y = yearsOpen(r);
  ok(y > 0 && y < V.YR_HI, `${r.slug}: ${r.posed} to ${r.open ? V.PAGE_YEAR : r.ended} is ${y} years`);
  ok(posYears(y) >= 0 && posYears(y) <= 100, `${r.slug}: years position is on the drawn axis`);
}
ok(rows.filter((r) => r.open).length === 2, 'two members are still open');

/* -------------------------------------------------- the claim, computed twice */
function ranks(vals) {                       // ascending, average ranks on ties
  const idx = vals.map((_, i) => i).sort((a, b) => vals[a] - vals[b]);
  const r = new Array(vals.length);
  let i = 0;
  while (i < idx.length) {
    let j = i;
    while (j + 1 < idx.length && vals[idx[j + 1]] === vals[idx[i]]) j++;
    const avg = (i + j) / 2 + 1;
    for (let k = i; k <= j; k++) r[idx[k]] = avg;
    i = j + 1;
  }
  return r;
}
/** Spearman from the sum of squared rank differences. Valid only without ties,
 *  which is asserted before it is used. This is NOT the formula the page runs. */
function spearmanFromD2(xs, ys) {
  const n = xs.length;
  const rx = ranks(xs), ry = ranks(ys);
  const d2 = rx.reduce((s, v, i) => s + (v - ry[i]) ** 2, 0);
  return { rho: 1 - (6 * d2) / (n * (n * n - 1)), d2, rx, ry, n };
}
/** Pearson on ranks. The page's route, reimplemented here to cross-check. */
function spearmanFromPearson(xs, ys) {
  const n = xs.length, rx = ranks(xs), ry = ranks(ys), m = (n + 1) / 2;
  let num = 0, dx = 0, dy = 0;
  for (let i = 0; i < n; i++) {
    num += (rx[i] - m) * (ry[i] - m);
    dx += (rx[i] - m) ** 2;
    dy += (ry[i] - m) ** 2;
  }
  return num / Math.sqrt(dx * dy);
}
function correlationSet(bpp) {
  return rows.filter((r) => sizeBytes(r, bpp) !== null && yearsOpen(r) !== null && !r.open);
}

head('7. THE CLAIM: the two rank orderings are not the same ordering');
const set = correlationSet(V.DEFAULT_BPP);
const sizes = set.map((r) => sizeBytes(r, V.DEFAULT_BPP));
const years = set.map(yearsOpen);
ok(set.length === 9, `9 members carry both a size and a years figure (found ${set.length})`);
ok(new Set(sizes).size === sizes.length, 'no ties in the size ordering');
ok(new Set(years).size === years.length, 'no ties in the years ordering');

const s = spearmanFromD2(sizes, years);
const pearsonRho = spearmanFromPearson(sizes, years);
ok(Math.abs(s.rho - pearsonRho) < 1e-12,
  `two independent formulas agree on rho (${s.rho.toFixed(6)})`);

const sizeOrder = set.map((r) => r.slug).sort((a, b) =>
  sizeBytes(set.find((r) => r.slug === a), V.DEFAULT_BPP) -
  sizeBytes(set.find((r) => r.slug === b), V.DEFAULT_BPP));
const yearOrder = set.map((r) => r.slug).sort((a, b) =>
  yearsOpen(set.find((r) => r.slug === a)) - yearsOpen(set.find((r) => r.slug === b)));
ok(sizeOrder.join() !== yearOrder.join(),
  'the two orderings differ, which is the whole claim of the page');
ok(s.rho < 1 - 1e-9, `rho is strictly below 1 (rho = ${s.rho.toFixed(4)}, sum d^2 = ${s.d2})`);

console.log('');
console.log(`  Spearman rho = ${s.rho.toFixed(4)}   (n = ${s.n}, sum d^2 = ${s.d2})`);
console.log('  rank by size            rank by years open');
for (let i = 0; i < s.n; i++) {
  console.log(`   ${String(i + 1).padStart(2)} ${sizeOrder[i].padEnd(32)} ${String(i + 1).padStart(2)} ${yearOrder[i]}`);
}
console.log('');

head('8. the finding does not depend on the characters-per-page convention');
{
  let stable = true, worstRho = -Infinity, bestRho = Infinity;
  for (let bpp = 1000; bpp <= 4000; bpp += 100) {
    const t = correlationSet(bpp);
    const order = t.map((r) => r.slug).sort((a, b) =>
      sizeBytes(t.find((r) => r.slug === a), bpp) - sizeBytes(t.find((r) => r.slug === b), bpp));
    if (order.join() !== sizeOrder.join()) stable = false;
    const rr = spearmanFromD2(t.map((r) => sizeBytes(r, bpp)), t.map(yearsOpen)).rho;
    worstRho = Math.max(worstRho, rr);
    bestRho = Math.min(bestRho, rr);
  }
  ok(stable, 'the size ordering is identical for every convention from 1,000 to 4,000');
  ok(Math.abs(worstRho - bestRho) < 1e-12,
    `rho is constant across the whole slider range (${bestRho.toFixed(4)})`);
  ok(worstRho < 1 - 1e-9, 'and never reaches 1, so the orderings never coincide');
}

head('9. the finding does not depend on the one start date that is only a bound');
{
  const bp = set.find((r) => r.slug === 'boolean-pythagorean');
  ok(bp && bp.posedBound, 'boolean-pythagorean is flagged on the page as a bounded start date');
  // Re-rank with that card moved to the TOP of the years ordering, which is the
  // most hostile place for the claim: it is already the largest by size.
  const yearsAlt = set.map((r) => (r.slug === 'boolean-pythagorean' ? 999 : yearsOpen(r)));
  const alt = spearmanFromD2(sizes, yearsAlt);
  ok(alt.rho < 1 - 1e-9,
    `even then the orderings differ (rho = ${alt.rho.toFixed(4)})`);
  console.log(`        with that card ranked longest-open instead: rho = ${alt.rho.toFixed(4)}`);
}

head('10. the arithmetic the prose states about the uncomfortable middle');
{
  ok(477 + 743 === 1220, '477 + 743 = 1220 pages of Aschbacher and Smith');
  ok(/477 and 743/.test(html), 'the page prints the two volume lengths');
  ok(2004 - 1983 === 21, '1983 to 2004 is twenty one years');
  ok(/twenty\s+one years/.test(html), 'the page says twenty one years, and it is twenty one');
  const fsg = rows.find((r) => r.slug === 'finite-simple-groups');
  ok(fsg.check === 'neither', 'the classification is the only card marked as checked by neither');
  ok(rows.filter((r) => r.check === 'neither').length === 1, 'and it is the only one');
  const mid = posSize(sizeBytes(fsg, V.DEFAULT_BPP));
  const lo = Math.min(...sized.map((r) => posSize(sizeBytes(r, V.DEFAULT_BPP))));
  const hi = Math.max(...sized.map((r) => posSize(sizeBytes(r, V.DEFAULT_BPP))));
  ok(mid > lo && mid < hi,
    `it sits in the middle of the axis, not at either end (${mid.toFixed(1)}% of ${lo.toFixed(1)} to ${hi.toFixed(1)})`);
  const ends = [...sized].sort((a, b) => sizeBytes(a, V.DEFAULT_BPP) - sizeBytes(b, V.DEFAULT_BPP));
  ok(['hand', 'machine'].includes(ends[0].check) && ['hand', 'machine'].includes(ends[ends.length - 1].check),
    'both ends of the size axis are cards a person or a machine can finish checking');
}

head('11. negative controls: a corrupted object must NOT keep its byte count');
{
  const real = Buffer.byteLength(payloads.get('bhargava-290'), 'utf8');
  const dropped = Buffer.byteLength(payloads.get('bhargava-290').replace(', 290', ''), 'utf8');
  ok(dropped !== real, 'dropping 290 from the critical list changes the measured size');

  const fake = { ...rows.find((r) => r.slug === 'cap-set-polynomial'), pages: 5000 };
  ok(posSize(sizeBytes(fake, V.DEFAULT_BPP)) !== posSize(sizeBytes(rows.find((r) => r.slug === 'cap-set-polynomial'), V.DEFAULT_BPP)),
    'inflating a page count moves that card along the axis');

  const identical = spearmanFromD2([1, 2, 3, 4, 5], [10, 20, 30, 40, 50]);
  ok(Math.abs(identical.rho - 1) < 1e-12,
    'the correlation routine returns exactly 1 on two identical orderings');
  const reversed = spearmanFromD2([1, 2, 3, 4, 5], [50, 40, 30, 20, 10]);
  ok(Math.abs(reversed.rho + 1) < 1e-12, 'and exactly -1 on two reversed orderings');
}

head('12. the page does not print a conclusion it has not computed');
{
  ok(!/rho\s*=\s*-?0?\.\d/.test(html.replace(/toFixed\(2\)/g, '')),
    'no hard-typed rho appears anywhere in the shipped HTML');
  ok(/id="rho"[^>]*>&rho;<\/p>/.test(html),
    'the rho readout ships empty and is filled by computation');
  ok(/not the same ordering/.test(html), 'the page states the claim it computes');
  ok(/not statistically significant/.test(html),
    'the page names the limit of nine points rather than overclaiming');
}

head('13. every flag the rows carry has a marker shape and a legend entry');
{
  const flags = new Set(rows.map((r) => r.flag));
  ok([...flags].sort().join() === 'estimated,measured,none,published',
    `the rows carry exactly four flags (${[...flags].sort().join(', ')})`);
  // A figure the page did NOT measure must not draw the same marker as one it did.
  ok(/\.dot\.est\{[^}]*rotate\(45deg\)/.test(html), 'estimated draws a rotated square (diamond)');
  ok(/\.dot\.pub\{[^}]*border-radius:2px/.test(html), 'published draws an unrotated square');
  ok(/m\.flag === 'estimated' \? ' est' : \(m\.flag === 'published' \? ' pub' : ''\)/.test(html),
    'the renderer maps estimated to .est and published to .pub');
  ok(/<em>quoted<\/em>/.test(html), 'the value column marks a quoted size as quoted');
  const legend = (html.match(/<div class="legend">[\s\S]*?<\/div>/) || [''])[0];
  ok(/a disc means/.test(legend), 'the legend names the disc');
  ok(/a diamond means/.test(legend), 'the legend names the diamond');
  ok(/a square means/.test(legend), 'the legend names the square');
  ok(/class="swatch o"/.test(legend), 'the legend names the hollow ring');
  const pub = rows.filter((r) => r.flag === 'published');
  ok(pub.length === 2, `exactly two sizes are quoted rather than measured (${pub.length})`);
  const bySize = [...sized].sort((a, b) => sizeBytes(b, V.DEFAULT_BPP) - sizeBytes(a, V.DEFAULT_BPP));
  ok(bySize.slice(0, 2).every((r) => r.flag === 'published'),
    'and they are the two largest cards, which is why the shape has to differ');
  // The three with no object are off the track entirely, not parked at its small end.
  ok(!/dot none/.test(html), 'no marker is drawn on the track for a member with no object');
  ok(/class="swatch o"><\/i><em>' \+\s*\(axis === 'size'/.test(html),
    'the hollow ring is rendered in the value column instead');
}

head('14. the years axis really does span less than one order of magnitude');
{
  const ys = rows.map(yearsOpen).filter((y) => y !== null);
  const ylo = Math.min(...ys), yhi = Math.max(...ys);
  const orders = Math.log10(yhi / ylo);
  ok(orders < 1, `years span ${orders.toFixed(2)} orders (${ylo} to ${yhi}), which is less than one`);
  ok(/spans less than one/.test(html), 'the page says less than one, not one');
  ok(!/Years is drawn linearly, because it spans one\./.test(html),
    'the old rounded-up "spans one" sentence is gone');
  // the three static fallbacks in the hint must equal what the browser will compute
  const g = (id) => {
    const m = html.match(new RegExp(`id="${id}"[^>]*>([^<]*)<`));
    return m ? m[1].trim() : null;
  };
  ok(g('yr-lo') === String(ylo), `#yr-lo fallback is ${ylo}`);
  ok(g('yr-hi') === String(yhi), `#yr-hi fallback is ${yhi}`);
  ok(g('yr-ratio') === (yhi / ylo).toFixed(1), `#yr-ratio fallback is ${(yhi / ylo).toFixed(1)}`);
}

head('15. the payoff sentence names the right card and the right cost');
{
  // BLOCKER, found by audit: the page used to say "the largest can be checked by a
  // machine in hours". Heule, Kullmann and Marek report about 16,000 CPU hours for
  // the check. That is ~1.8 CPU-years, and it was only ~20 wall-clock hours because
  // it ran on 800 cores. Both halves of the old sentence are asserted dead here.
  ok(!/can be checked by a machine in hours/.test(html),
    'the "checked by a machine in hours" claim is gone');
  ok(!/the tiniest ending can be checked by hand/.test(html),
    'the "tiniest ending ... about a minute" misattribution is gone');
  const smallest = [...sized].sort((a, b) => sizeBytes(a, V.DEFAULT_BPP) - sizeBytes(b, V.DEFAULT_BPP))[0];
  ok(smallest.slug === 'weaire-phelan',
    `the smallest object on the axis is ${smallest.slug} at ${sizeBytes(smallest, V.DEFAULT_BPP)} bytes`);
  const payoff = (html.match(/The colours are the argument[\s\S]*?<\/p>/) || [''])[0];
  ok(/Zagier/.test(payoff) && /about a minute/.test(payoff),
    'the minute is attributed to Zagier by name, not to the smallest card');
  ok(/Weaire and Phelan/.test(payoff) && /an afternoon/.test(payoff),
    'and the smallest card gets its own act, an afternoon, as its readout says');

  // the checking cost, and the arithmetic the page does on it
  ok(/about 16,000 CPU\s+hours/.test(html) || /about 16,000 CPU hours/.test(html),
    'the page prints the authors\' 16,000 CPU hours for checking');
  ok(/about 13,000 CPU/.test(html), 'and the 13,000 CPU hours to regenerate the proof');
  ok(/16,000 CPU hours"/.test(html) && /35,000 hours and the verification time about/.test(html),
    'both figures are quoted verbatim from the paper in the sources footer');
  ok(Math.round(16000 / 800) === 20, '16,000 CPU hours over 800 cores is 20 hours');
  ok(/about 20 hours/.test(html), 'and the page says about 20 hours');
  ok((16000 / (24 * 365.25)).toFixed(1) === '1.8', '16,000 CPU hours on one core is 1.8 years');
  ok(/about 1\.8 years/.test(html), 'and the page says about 1.8 years');
  ok(35000 / 800 === 43.75, '35,000 CPU hours over 800 cores is 43.75 hours');
  ok(/43\.75 hours/.test(html), 'and the page shows that division reproducing the "about 2 days"');
}

head('16. the authors\' hedge travels with the figure it hedges');
{
  const biggest = [...sized].sort((a, b) => sizeBytes(b, V.DEFAULT_BPP) - sizeBytes(a, V.DEFAULT_BPP))[0];
  const tag = html.match(new RegExp(`<div class="row" data-slug="${biggest.slug}"[\\s\\S]*?>`));
  ok(tag && /data-qualifier="almost"/.test(tag[0]),
    `${biggest.slug} carries the authors' "almost" beside its raw figure`);
  ok(sizeBytes(biggest, V.DEFAULT_BPP) === 2e14,
    'the stored figure is exactly 200 TB, which is why the hedge is needed');
  ok(/function sizeLabel/.test(html), 'the page has one printer for a member size');
  for (const call of ['sizeLabel(lo,', 'sizeLabel(hi,', 'sizeLabel(m, b)', 'sizeLabel(m, sizeBytes(m, bpp))']) {
    ok(html.includes(call), `sizeLabel is used at ${call}`);
  }
  ok(!/fmtBytes\(Math\.min/.test(html) && !/fmtBytes\(Math\.max/.test(html),
    'the lede no longer prints a member size through the unhedged formatter');
}

head('17. the two Weaire-Phelan comparisons are kept apart');
{
  const A15 = 18.57752, KELVIN = 18.581656367;
  const margin = (KELVIN - A15) / KELVIN * 100;
  ok(margin.toFixed(3) === '0.022', `the flat-face margin is ${margin.toFixed(4)} percent`);
  ok(/0\.022 percent/.test(html), 'the page prints 0.022 percent for the flat-face inequality');
  ok(/about 0\.3 percent/.test(html), 'and 0.3 percent for the published relaxed result');
  ok(/18\.57752/.test(html) && /18\.581656367/.test(html), 'both explicit costs are on the page');
  ok(/not the same number/.test(html) && /different\s+comparisons|two different area comparisons/.test(html),
    'the page says in so many words that these are two different comparisons');
  ok(margin * 13 < 0.3 && margin * 14 > 0.3,
    'and they differ by about a factor of thirteen, which is why welding them would mislead');
}

head('18. accessible names contain their visible labels, and the outline is clean');
{
  // WCAG 2.5.3: voice control says the words it can see.
  for (const id of ['scrub', 'bpp', 'pick']) {
    const vis = html.match(new RegExp(`<label[^>]*for="${id}"[^>]*>([\\s\\S]*?)</label>`));
    ok(!!vis, `${id} has a visible <label for>`);
    // the visible NAME is everything before the live value the label also carries
    const visText = vis[1].replace(/<[^>]*>/g, ' ').replace(/&middot;/g, '·')
      .split('·')[0].replace(/\s+/g, ' ').trim();
    const tag = html.match(new RegExp(`<(?:input|select)[^>]*id="${id}"[\\s\\S]*?>`));
    const al = tag && tag[0].match(/aria-label="([^"]*)"/);
    if (!al) { pass(`${id}: no aria-label, so the visible label IS the accessible name`); continue; }
    ok(al[1].startsWith(visText),
      `${id}: aria-label "${al[1]}" starts with the visible "${visText}"`);
  }
  ok(!/id="pick"[^>]*aria-label/.test(html), 'the select carries no competing aria-label');
  ok(!/aria-label="Walk the size axis/.test(html) && !/aria-label="Walk the years axis/.test(html),
    'neither runtime aria-label reintroduces a name the visible label does not contain');
  ok(/s\.setAttribute\('aria-label', 'Walk the axis, /.test(html),
    'the runtime relabel keeps the visible words');

  // one polite live region, on a node that changes only with the selection
  ok(!/class="readout" id="readout"[^>]*aria-live/.test(html),
    'the readout container is not a live region');
  ok(/id="ro-title" role="status" aria-live="polite"/.test(html),
    'the live region is the title, which changes only when the selection changes');
  ok(/if \(t\.textContent !== m\.title\) t\.textContent = m\.title;/.test(html),
    'and the title is written only when it actually differs');
  ok(!/id="ro-scale"[^>]*aria-live/.test(html),
    'the scale line, rewritten on every drag event, is not announced');

  // heading outline: h1 then h2, no orphan h4 between them
  const levels = [...html.matchAll(/<h([1-6])[\s>]/g)].map((m) => Number(m[1]));
  ok(!levels.includes(4), 'no h4 sits in the outline (the readout title is not a heading)');
  ok(levels[0] === 1 && levels[1] === 2, `the outline starts h1 then h2 (found h${levels[0]}, h${levels[1]})`);
  for (let i = 1; i < levels.length; i++) {
    if (levels[i] > levels[i - 1] + 1) fail(`heading level jumps h${levels[i - 1]} to h${levels[i]}`);
  }
  pass('no heading level is skipped');
}

head('19. --faint carries reading matter, so it must clear the AA contrast floor');
{
  const tok = (n) => (html.match(new RegExp(`--${n}:(#[0-9a-f]{6})`, 'i')) || [])[1];
  const lin = (c) => { c /= 255; return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4; };
  const lum = (h) => 0.2126 * lin(parseInt(h.slice(1, 3), 16)) +
                     0.7152 * lin(parseInt(h.slice(3, 5), 16)) +
                     0.0722 * lin(parseInt(h.slice(5, 7), 16));
  const ratio = (a, b) => {
    const [x, y] = [lum(a), lum(b)].sort((p, q) => q - p);
    return (x + 0.05) / (y + 0.05);
  };
  const faint = tok('faint');
  ok(!!faint, `--faint is declared (${faint})`);
  for (const [name, bg] of [['--bg', tok('bg')], ['--panel', tok('panel')],
                            ['--panel2', tok('panel2')], ['the check panel', '#0b1109'],
                            ['the payload block', '#07070b']]) {
    const r = ratio(faint, bg);
    ok(r >= 4.5, `--faint on ${name} is ${r.toFixed(2)}:1, at or above the 4.5:1 AA floor`);
  }
  ok(!/color:\s*#6d6a64/.test(html),
    'the failing #6d6a64 does not survive as a hard-coded inline colour');
  // every hard-coded colour: value in the document must also clear the floor
  for (const m of html.matchAll(/color:\s*(#[0-9a-f]{6})\b/gi)) {
    const r = Math.max(ratio(m[1], tok('bg')), 0);
    if (m[1].toLowerCase() === tok('bg').toLowerCase()) continue;
    ok(r >= 4.5, `inline colour ${m[1]} is ${r.toFixed(2)}:1 on --bg`);
  }
}

head('20. the one date with no journal behind it is cited on the page');
{
  const bunk = rows.find((r) => r.slug === 'the-other-bunk-wins');
  ok(bunk.ended === 2024, 'the-other-bunk-wins ends in 2024, before its 2025 journal date');
  ok(/arXiv:2410\.02545/.test(html), 'the page names the preprint that justifies 2024');
  ok((html.match(/3 October 2024/g) || []).length >= 2,
    'and prints its submission date, in the date table and in the sources footer');
  ok(/13 June 2025/.test(html), 'the journal date is still on the page too');
}

console.log('');
if (failures) {
  console.error(`FAILED: ${failures} check${failures === 1 ? '' : 's'} did not pass.`);
  process.exit(1);
}
console.log('PASS: every linked layer exists, both axes recompute from the raw figures,');
console.log('      and the two rank orderings differ by two independent routes.');
