#!/usr/bin/env node
// verify-every-claim-at-full-strength.mjs: the portal's verifier.
//
//   node research/every-claim-at-full-strength/verify-every-claim-at-full-strength.mjs                every assertion, the
//        browser pass included: headless Chromium drives the page and every card, timeline row, ledger cell, table
//        cell and readout it draws is held to strings this file builds from the raw records (a few seconds)
//   node research/every-claim-at-full-strength/verify-every-claim-at-full-strength.mjs --no-browser   skip that pass
//        (it is also skipped, with a note in the last line, when Playwright is not installed; the gate's machine has it)
//
// The portal carries no claim and no record.json, so there is no --ledger. What it must never do is say something
// the records do not, so this checks, in order:
//   index     the index and the static blocks against the records, by the generator's own --check logic and by an
//             independent scan; and the negative controls: a copied record with a changed verdict, an added record,
//             a removed record and a stale block must each turn the --check red, run as the real CLI on a copy.
//   blocks    every cell of the static table and every kill in the static list, parsed out of the page, against the
//             records and kills.json.
//   kills     kills.json against the wave's own files: SLATE.md, COMPOST.md, README.md and every specs/KILLED-*.md.
//   compute   every aggregate the page prints, recomputed here by code that shares nothing with engine.js, then held
//             against engine.js and against the exact sentences text.js prints.
//   refuse    doctored records the page must refuse, and doctored records the CONTRACT's rules must catch.
//   surface   the head tags, JSON-LD, frontmatter (dek, plain, relates) and every static figure a reader can see.
//   page      closing tags, modules, network, accessibility wiring, em dashes.
// Exits non-zero on any failure.

import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import crypto from 'node:crypto';
import assert from 'node:assert/strict';
import { spawnSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import * as E from '../../public/strata/every-claim-at-full-strength/engine.js';
import * as T from '../../public/strata/every-claim-at-full-strength/text.js';
import * as L from './index-lib.mjs';

const here = path.dirname(fileURLToPath(import.meta.url));
const root = path.resolve(here, '../..');
const SLUG = L.SLUG;
const P = L.paths(root);
const WAVE = path.join(root, 'oversight/waves/2026-09-22-at-full-strength');
const BROWSER = !process.argv.includes('--no-browser');
if (process.argv.includes('--ledger')) {
  console.error('The portal carries no record.json and no ledger of its own; run it without --ledger.');
  process.exit(64);
}

// The site's chrome writers inject marked blocks and the banner script into every page at landing. This verifier
// checks the page's own content, so it reads the page with every such block and that script removed.
const stripChrome = (s) => s.replace(/\s*<!--aw-([a-z-]+):start-->[\s\S]*?<!--aw-\1:end-->/g, '')
  .replace(/\s*<script src="\/media\/home-banner\.js" defer><\/script>/g, '');

const rawHtml = fs.readFileSync(P.html, 'utf8');
const html = stripChrome(rawHtml);
const md = fs.readFileSync(path.join(root, 'src/content/strata', `${SLUG}.md`), 'utf8');
const index = JSON.parse(fs.readFileSync(P.index, 'utf8'));
const kills = JSON.parse(fs.readFileSync(P.kills, 'utf8'));
const EM = String.fromCharCode(0x2014);

const results = [];
function check(group, name, fn) {
  try { fn(); results.push({ group, name, pass: true }); } catch (e) { results.push({ group, name, pass: false, error: e.message }); }
}

// ------------------------------------------------------------------ helpers that share no code with the page
const sha = (b) => crypto.createHash('sha256').update(b).digest('hex');
const ENT = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", middot: '·', nbsp: ' ' };
const decode = (s) => s.replace(/&#(\d+);/g, (_, n) => String.fromCodePoint(Number(n))).replace(/&#x([0-9a-f]+);/gi, (_, n) => String.fromCodePoint(parseInt(n, 16))).replace(/&([a-z]+);/g, (m, n) => (n in ENT ? ENT[n] : m));
const textOf = (h) => decode(h.replace(/<[^>]+>/g, ''));
const norm = (s) => s.replace(/\*\*/g, '').replace(/\s+/g, ' ').trim();
const fm = (() => { const m = /^---\n([\s\S]*?)\n---/.exec(md); if (!m) throw new Error('no frontmatter'); return m[1]; })();
const fmStr = (key) => { const m = new RegExp(`^${key}:\\s*"(.*)"\\s*$`, 'm').exec(fm); return m ? m[1] : null; };
const meta = (attr, name) => { const m = new RegExp(`<meta ${attr}="${name.replace(/[:]/g, '\\:')}" content="([^"]*)"`).exec(html); return m ? decode(m[1]) : null; };
const NUMWORDS = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen', 'twenty', 'twenty-one', 'twenty-two', 'twenty-three', 'twenty-four', 'twenty-five', 'twenty-six', 'twenty-seven', 'twenty-eight', 'twenty-nine', 'thirty'];
function median(xs) { const v = [...xs].sort((a, b) => a - b); const n = v.length; if (!n) return null; return n % 2 ? v[(n - 1) / 2] : (v[n / 2 - 1] + v[n / 2]) / 2; }
function fracYear(iso) { const [y, m, d] = iso.split('-').map(Number); const t = Date.UTC(y, m - 1, d); return y + (t - Date.UTC(y, 0, 1)) / (Date.UTC(y + 1, 0, 1) - Date.UTC(y, 0, 1)); }

// The page's words, typed again here so that a change to text.js or render.js has to be made twice to pass.
const V_ORDER = ['VINDICATED', 'DISSOLVED', 'ARTEFACT', 'OPEN', 'WITHDRAWN'];
const D_ORDER = ['more-data', 'independent-replication', 'instrument', 'analysis', 'contamination', 'perception', 'theory', 'not-yet'];
const D_LABEL = { 'more-data': 'more data', 'independent-replication': 'independent replication', instrument: 'the instrument', analysis: 'the analysis', contamination: 'contamination', perception: 'perception', theory: 'theory', 'not-yet': 'not yet decided' };
const G_ORDER = ['A-injection', 'B-published-sensitivity'];
const G_SHORT = { 'A-injection': 'grade A, injection', 'B-published-sensitivity': 'grade B, published sensitivity' };
const G_LONG = { 'A-injection': 'Grade A: the claimed effect planted into the control’s own data, and the unmodified control rerun', 'B-published-sensitivity': 'Grade B: the control’s power worked out from its authors’ own printed sensitivity, because the control could not be rerun' };
const L_KEYS = ['claim_reproduced', 'control_computed', 'control_can_confirm', 'rendered_figures_asserted', 'choices_are_live', 'planted_fault_caught', 'refusal_asserted', 'provenance_pinned', 'verdict_dated'];
const L_LABEL = { claim_reproduced: 'claim reproduced', control_computed: 'control computed', control_can_confirm: 'control can confirm', rendered_figures_asserted: 'figures asserted', choices_are_live: 'choices live', planted_fault_caught: 'planted fault caught', refusal_asserted: 'refusal asserted', provenance_pinned: 'provenance pinned', verdict_dated: 'verdict dated' };
const SC_LABEL = { scope: 'The verdict’s scope, in the record’s words: ', subject: 'What the verdict is about, in the record’s words: ', narrow_question: 'A narrower question the record also answers: ' };
const DIM_LABEL = { verdict: 'verdict', decided: 'what decided it', grade: 'power grade', field: 'field', decade: 'decade of the claim', settled: 'settled or not' };
const ROUND_WORDS = { 'first-pass': 'First pass, under the strict power rule (before grade B existed)', 'after-grade-b': 'After the grade B rule was added', unlisted: 'Killed, and listed by the slate only among the pages later built' };
const SIDE_WORDS = { claim: 'the claim side', control: 'the control side', both: 'both sides' };
const IDENTITY = 'The CONTRACT ties OPEN, not yet decided and no years to decision together, so this crossing can only fall on its diagonal: it shows that rule holding, not a finding, and a count off the diagonal would be a record breaking it.';
const pl = (n, one, many) => `${n} ${n === 1 ? one : many}`;
const words = (xs) => (xs.length <= 1 ? xs.join('') : xs.length === 2 ? `${xs[0]} and ${xs[1]}` : `${xs.slice(0, -1).join(', ')} and ${xs[xs.length - 1]}`);
const fieldKey = (f) => String(f || '').split('(')[0].trim().toLowerCase() || 'no field given';
const fmt1 = (x) => (Number.isInteger(x) ? String(x) : x.toFixed(1));
const scopesOf = (j) => ['scope', 'subject', 'narrow_question'].filter((k) => typeof j.verdict[k] === 'string' && j.verdict[k].trim()).map((k) => ({ field: k, text: j.verdict[k] }));
const scopeCellOf = (j) => { const sc = scopesOf(j); return sc.length ? sc.map((x) => `${SC_LABEL[x.field]}${x.text}`).join(' ') : 'none stated in the record'; };
const ytdWords = (j) => (j.years_to_decision === 0 ? 'decided in the year of the claim (0 years)' : `decided after ${pl(j.years_to_decision, 'year', 'years')}`);
const verdictLineOf = (j) => `as of ${j.verdict.as_of} · ${j.decided_by === 'not-yet' ? 'not yet decided' : `decided by ${D_LABEL[j.decided_by]} · ${ytdWords(j)}`} · ${G_SHORT[j.power.grade]}`;
const byYT = (a, b) => (a.j.claim.year - b.j.claim.year) || a.j.title.localeCompare(b.j.title, 'en');
// Keys for the six dimensions a reader may cross, and their order, read straight off the raw record.
const DIMS = {
  verdict: { key: (j) => j.verdict.category, order: V_ORDER, label: (k) => String(k) },
  decided: { key: (j) => j.decided_by, order: D_ORDER, label: (k) => D_LABEL[k] },
  grade: { key: (j) => j.power.grade, order: G_ORDER, label: (k) => G_SHORT[k] },
  field: { key: (j) => fieldKey(j.field), order: null, label: (k) => String(k) },
  decade: { key: (j) => Math.floor(j.claim.year / 10) * 10, order: null, label: (k) => `${k}s` },
  settled: { key: (j) => (j.years_to_decision === null ? 'not yet' : 'settled'), order: ['settled', 'not yet'], label: (k) => String(k) },
};
function crossOf(rawRecs, rd, cd) {
  const keys = (D) => { const seen = [...new Set(rawRecs.map((r) => D.key(r.j)))]; return D.order ? D.order.filter((k) => seen.includes(k)) : seen.sort((a, b) => (typeof a === 'number' ? a - b : a.localeCompare(b, 'en'))); };
  const rows = keys(DIMS[rd]), cols = keys(DIMS[cd]);
  const titles = rows.map((rk) => cols.map((ck) => rawRecs.filter((r) => DIMS[rd].key(r.j) === rk && DIMS[cd].key(r.j) === ck).sort(byYT).map((r) => r.j.title)));
  return { rows, cols, titles, counts: titles.map((row) => row.map((t) => t.length)) };
}
const identityPair = (a, b) => [a, b].includes('settled') && (a === 'verdict' || b === 'verdict' || a === 'decided' || b === 'decided');
function crossWords(rawRecs, rd, cd, pick) {
  const ct = crossOf(rawRecs, rd, cd);
  const note = identityPair(rd, cd) ? ` ${IDENTITY}` : '';
  if (pick) { const [i, j] = pick; const t = ct.titles[i][j]; return `${DIMS[rd].label(ct.rows[i])} and ${DIMS[cd].label(ct.cols[j])}: ${pl(t.length, 'claim', 'claims')}, ${words(t)}.${note}`; }
  return `${DIM_LABEL[rd]} against ${DIM_LABEL[cd]}, over ${pl(rawRecs.length, 'claim', 'claims')}. Choose a number to name its claims.${note}`;
}

// ------------------------------------------------------------------ the records, read here independently
const onDisk = [];
for (const dir of fs.readdirSync(P.strata).sort()) {
  const f = path.join(P.strata, dir, 'record.json');
  if (!fs.existsSync(f)) continue;
  const bytes = fs.readFileSync(f);
  let j; try { j = JSON.parse(bytes.toString('utf8')); } catch { onDisk.push({ dir, bad: true }); continue; }
  const isObj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
  if (isObj(j) && isObj(j.claim) && isObj(j.verdict)) onDisk.push({ dir, sha: sha(bytes), j });
}
const raw = onDisk.filter((r) => !r.bad);
const N = raw.length;
const recs = raw.map((r) => E.normalize(r.j, r.dir));

// ================================================================== index
check('index', 'index:generator-check-is-green (the --check logic finds nothing stale)', () => {
  const reasons = L.check(root);
  assert.deepEqual(reasons, []);
});
check('index', 'index:cli-check-exits-zero', () => {
  const r = spawnSync(process.execPath, [path.join(here, 'build-index.mjs'), '--check'], { encoding: 'utf8' });
  assert.equal(r.status, 0, r.stderr);
});
check('index', 'index:independent-scan-matches (same slugs, same SHA-256, nothing unparsable)', () => {
  assert.equal(onDisk.filter((r) => r.bad).length, 0, 'a record.json does not parse');
  assert.deepEqual(index.claims.map((c) => c.slug), raw.map((r) => r.dir));
  for (const c of index.claims) assert.equal(c.sha256, raw.find((r) => r.dir === c.slug).sha, c.slug);
});
check('index', 'index:says-nothing-a-record-does-not (slug, path and digest only)', () => {
  assert.deepEqual(Object.keys(index).sort(), ['about', 'claims', 'rule']);
  for (const c of index.claims) {
    assert.deepEqual(Object.keys(c).sort(), ['record', 'sha256', 'slug']);
    assert.equal(c.record, `/strata/${c.slug}/record.json`);
    assert.match(c.sha256, /^[0-9a-f]{64}$/);
  }
});
check('index', 'index:every-listed-page-exists-and-links-home', () => {
  for (const r of recs) {
    assert.ok(fs.existsSync(path.join(P.strata, r.slug, 'index.html')), `${r.slug} has no page`);
    assert.equal(r.href, `/strata/${r.slug}/`, `${r.slug} href`);
  }
});

// The negative controls run the real CLI on a copy of the tree, so the check that sits in the prebuild is the one
// shown to go red. Each case starts from a fresh copy of the current files.
function tmpTree() {
  const t = fs.mkdtempSync(path.join(os.tmpdir(), 'ecfs-check-'));
  const dst = path.join(t, 'public/strata');
  for (const dir of fs.readdirSync(P.strata)) {
    const f = path.join(P.strata, dir, 'record.json');
    if (fs.existsSync(f)) { fs.mkdirSync(path.join(dst, dir), { recursive: true }); fs.copyFileSync(f, path.join(dst, dir, 'record.json')); }
  }
  fs.mkdirSync(path.join(dst, SLUG), { recursive: true });
  for (const f of ['claims.json', 'index.html', 'kills.json']) fs.copyFileSync(path.join(P.dir, f), path.join(dst, SLUG, f));
  return t;
}
const cli = (t, ...args) => spawnSync(process.execPath, [path.join(here, 'build-index.mjs'), `--root=${t}`, ...args], { encoding: 'utf8' });
function withTree(fn) { const t = tmpTree(); try { return fn(t, path.join(t, 'public/strata')); } finally { fs.rmSync(t, { recursive: true, force: true }); } }
const first = index.claims[0].slug;
const otherVerdict = (v) => (v === 'OPEN' ? 'WITHDRAWN' : 'OPEN');

check('index', 'negative:unchanged-copy-is-green (so the red cases below are about the change)', () => withTree((t) => {
  const r = cli(t, '--check'); assert.equal(r.status, 0, r.stderr);
}));
check('index', 'negative:copied-record-with-changed-verdict-goes-red', () => withTree((t, s) => {
  const src = JSON.parse(fs.readFileSync(path.join(s, first, 'record.json'), 'utf8'));
  const copy = structuredClone(src);
  copy.slug = 'zz-copied-record-negative-control';
  copy.verdict.category = otherVerdict(src.verdict.category);
  fs.mkdirSync(path.join(s, copy.slug));
  fs.writeFileSync(path.join(s, copy.slug, 'record.json'), JSON.stringify(copy, null, 2));
  const r = cli(t, '--check');
  assert.notEqual(r.status, 0, 'the check stayed green with a new record beside the index');
  assert.match(r.stderr, /added without regenerating: zz-copied-record-negative-control/);
}));
check('index', 'negative:changed-verdict-in-place-goes-red', () => withTree((t, s) => {
  const f = path.join(s, first, 'record.json');
  const j = JSON.parse(fs.readFileSync(f, 'utf8'));
  j.verdict.category = otherVerdict(j.verdict.category);
  fs.writeFileSync(f, JSON.stringify(j, null, 2));
  const r = cli(t, '--check');
  assert.notEqual(r.status, 0);
  assert.match(r.stderr, new RegExp(`changed without regenerating: ${first}`));
}));
check('index', 'negative:removed-record-goes-red', () => withTree((t, s) => {
  fs.rmSync(path.join(s, first, 'record.json'));
  const r = cli(t, '--check');
  assert.notEqual(r.status, 0);
  assert.match(r.stderr, new RegExp(`removed without regenerating: ${first}`));
}));
check('index', 'negative:stale-static-table-goes-red', () => withTree((t, s) => {
  const f = path.join(s, SLUG, 'index.html');
  const h = fs.readFileSync(f, 'utf8');
  const i = h.indexOf('<tr data-slug=');
  assert.notEqual(i, -1, 'the static table has no rows to make stale');
  fs.writeFileSync(f, h.slice(0, i) + h.slice(i).replace(/<td>(\d{4})<\/td>/, (m, y) => `<td>${Number(y) + 1}</td>`));
  const r = cli(t, '--check');
  assert.notEqual(r.status, 0);
  assert.match(r.stderr, /ecfs-claims block is stale/);
}));
check('index', 'negative:kills-json-edited-without-regenerating-goes-red', () => withTree((t, s) => {
  const f = path.join(s, SLUG, 'kills.json');
  const k = JSON.parse(fs.readFileSync(f, 'utf8'));
  k.decisions[0].side = k.decisions[0].side === 'claim' ? 'control' : 'claim';
  fs.writeFileSync(f, JSON.stringify(k, null, 2));
  const r = cli(t, '--check');
  assert.notEqual(r.status, 0);
  assert.match(r.stderr, /ecfs-kills block is stale/);
}));
check('index', 'negative:a-half-formed-wave-record-goes-red-instead-of-dropping-out', () => withTree((t, s) => {
  const src = JSON.parse(fs.readFileSync(path.join(s, first, 'record.json'), 'utf8'));
  for (const [slug, edit] of [['zz-verdict-as-a-string', (j) => { j.verdict = j.verdict.category; }], ['zz-claim-missing', (j) => { delete j.claim; }]]) {
    const copy = structuredClone(src);
    copy.slug = slug;
    edit(copy);
    fs.mkdirSync(path.join(s, slug));
    fs.writeFileSync(path.join(s, slug, 'record.json'), JSON.stringify(copy, null, 2));
    const r = cli(t, '--check');
    assert.notEqual(r.status, 0, `${slug}: the check stayed green`);
    assert.match(r.stderr, new RegExp(`${slug}/record\\.json has a (claim|verdict) object but its (verdict|claim) is not an object`));
    assert.notEqual(cli(t).status, 0, `${slug}: the generator wrote an index over it`);
    fs.rmSync(path.join(s, slug), { recursive: true });
  }
}));
check('index', 'negative:regenerating-repairs-the-copy (the write mode is the cure the --check names)', () => withTree((t, s) => {
  const f = path.join(s, first, 'record.json');
  const j = JSON.parse(fs.readFileSync(f, 'utf8'));
  j.verdict.category = otherVerdict(j.verdict.category);
  fs.writeFileSync(f, JSON.stringify(j, null, 2));
  assert.notEqual(cli(t, '--check').status, 0);
  assert.equal(cli(t).status, 0);
  const r = cli(t, '--check');
  assert.equal(r.status, 0, r.stderr);
  const regenerated = fs.readFileSync(path.join(s, SLUG, 'index.html'), 'utf8');
  assert.ok(regenerated.includes(`<td>${j.verdict.category}</td>`), 'the regenerated table carries the changed verdict');
}));

// ================================================================== blocks
const claimsBlock = L.readBlock(html, 'ecfs-claims');
const killsBlock = L.readBlock(html, 'ecfs-kills');
check('blocks', 'blocks:static-table-is-the-generator-output', () => {
  assert.ok(claimsBlock !== null);
  assert.equal(claimsBlock, L.renderClaimsBlock(raw.map((r) => ({ slug: r.dir, json: r.j }))));
});
check('blocks', 'blocks:every-cell-of-the-static-table-against-the-records', () => {
  const rows = [...claimsBlock.matchAll(/<tr data-slug="([^"]+)">([\s\S]*?)<\/tr>/g)];
  assert.equal(rows.length, N, 'one row per record');
  const want = [...raw].sort((a, b) => (a.j.claim.year - b.j.claim.year) || a.j.title.localeCompare(b.j.title, 'en'));
  rows.forEach((m, i) => {
    const r = want[i].j;
    assert.equal(m[1], want[i].dir, `row ${i} order`);
    const cells = [...m[2].matchAll(/<t[hd][^>]*>([\s\S]*?)<\/t[hd]>/g)].map((c) => c[1]);
    assert.equal(cells.length, 9);
    assert.equal(/href="([^"]+)"/.exec(cells[0])[1], r.href);
    assert.equal(textOf(cells[0]), r.title);
    assert.equal(textOf(cells[1]), String(r.claim.year));
    assert.equal(textOf(cells[2]), r.claim.headline_as_printed);
    assert.equal(textOf(cells[3]), r.verdict.category);
    assert.equal(textOf(cells[4]), scopeCellOf(r), `${want[i].dir}: the verdict's own bounds`);
    assert.equal(textOf(cells[5]), r.verdict.as_of);
    assert.equal(textOf(cells[6]), D_LABEL[r.decided_by]);
    assert.equal(textOf(cells[7]), r.years_to_decision === null ? 'open' : String(r.years_to_decision));
    assert.equal(textOf(cells[8]), G_SHORT[r.power.grade]);
  });
});
check('blocks', 'blocks:static-kill-list-is-the-generator-output', () => {
  assert.equal(killsBlock, L.renderKillsBlock(kills, index.claims.map((c) => c.slug)));
});
check('blocks', 'blocks:every-kill-in-the-static-list-against-kills-json', () => {
  const items = [...killsBlock.matchAll(/<li data-side="([^"]+)" data-candidate="([^"]+)">([\s\S]*?)<\/li>/g)];
  assert.equal(items.length, kills.decisions.length);
  items.forEach((m, i) => {
    const d = kills.decisions[i];
    assert.equal(m[1], d.side); assert.equal(m[2], d.candidate);
    assert.equal(textOf(/<b>([\s\S]*?)<\/b>/.exec(m[3])[1]), d.subject);
    assert.equal(textOf(/<p class="obj">([\s\S]*?)<\/p>/.exec(m[3])[1]), `“${d.objection}”`);
    assert.equal(textOf(/<p class="src">([\s\S]*?)<\/p>/.exec(m[3])[1]), `specs/KILLED-${d.candidate}.md`);
    if (d.later_built_as) assert.ok(m[3].includes(d.later_built_as));
  });
});

// ================================================================== kills against the wave's own files
const slate = fs.readFileSync(path.join(WAVE, 'SLATE.md'), 'utf8');
const compost = fs.readFileSync(path.join(WAVE, 'COMPOST.md'), 'utf8');
const readme = fs.readFileSync(path.join(WAVE, 'README.md'), 'utf8');
const killedFiles = fs.readdirSync(path.join(WAVE, 'specs')).filter((f) => /^KILLED-.*\.md$/.test(f)).map((f) => f.slice(7, -3)).sort();
const section = (text, startRe, endRe) => { const a = text.search(startRe); if (a < 0) return ''; const rest = text.slice(a + 1); const b = rest.search(endRe); return b < 0 ? rest : rest.slice(0, b); };
const slateFirst = section(slate, /^## Killed at spec, first pass/m, /^## /m);
const slateAfter = section(slate, /^## Killed at spec, after the grade B rule/m, /^## /m);
const slateSurvived = section(slate, /^## Survived to spec/m, /^## /m);
const tableIds = (sec) => [...sec.matchAll(/^\| ([a-z0-9-]+)(?: \([^)]*\))? \|/gm)].map((m) => m[1]).filter((x) => x !== 'candidate');
const compostKilled = [...section(compost, /^## Killed at spec/m, /^## /m).matchAll(/^- `([a-z0-9-]+)`/gm)].map((m) => m[1]).sort();

check('kills', 'kills:candidates-are-exactly-the-KILLED-files-and-the-compost-list', () => {
  const cands = [...new Set(kills.decisions.map((d) => d.candidate))].sort();
  assert.deepEqual(cands, killedFiles);
  assert.deepEqual(cands, compostKilled);
});
check('kills', 'kills:one-decision-per-slate-kill-row-plus-each-unlisted-kill', () => {
  const rows = [...tableIds(slateFirst), ...tableIds(slateAfter)];
  const unlisted = killedFiles.filter((c) => !rows.includes(c));
  assert.equal(kills.decisions.length, rows.length + unlisted.length);
  assert.deepEqual(kills.decisions.filter((d) => d.round === 'unlisted').map((d) => d.candidate).sort(), unlisted.sort());
});
check('kills', 'kills:rounds-match-the-slate-tables', () => {
  const f = tableIds(slateFirst), a = tableIds(slateAfter);
  for (const d of kills.decisions) {
    if (d.round === 'first-pass') assert.ok(f.includes(d.candidate), `${d.candidate} not in the first-pass table`);
    else if (d.round === 'after-grade-b') assert.ok(a.includes(d.candidate), `${d.candidate} not in the after-grade-B table`);
    else if (d.round === 'unlisted') assert.ok(!f.includes(d.candidate) && !a.includes(d.candidate));
    else throw new Error(`unknown round ${d.round}`);
  }
  for (const c of f) assert.ok(kills.decisions.some((d) => d.candidate === c && d.round === 'first-pass'), `${c} first pass missing`);
  for (const c of a) assert.ok(kills.decisions.some((d) => d.candidate === c && d.round === 'after-grade-b'), `${c} after grade B missing`);
});
check('kills', 'kills:every-objection-is-quoted-word-for-word-from-its-KILLED-file-part', () => {
  for (const d of kills.decisions) {
    let t = fs.readFileSync(path.join(WAVE, 'specs', `KILLED-${d.candidate}.md`), 'utf8');
    if (d.part) {
      const a = d.part.from ? t.indexOf(d.part.from) : 0;
      const b = d.part.to ? t.indexOf(d.part.to) : t.length;
      assert.ok(a >= 0 && b >= 0 && a < b, `${d.candidate}: the named part is not in the file`);
      t = t.slice(a, b);
    }
    assert.ok(norm(t).includes(norm(d.objection)), `${d.candidate} (${d.round}): objection not found verbatim`);
    assert.ok(d.objection.length >= 40, `${d.candidate}: objection too short to stand alone`);
  }
});
check('kills', 'kills:a-twice-killed-candidate-quotes-each-round-from-its-own-part', () => {
  const twice = [...new Set(kills.decisions.map((d) => d.candidate))].filter((c) => kills.decisions.filter((d) => d.candidate === c).length > 1);
  for (const c of twice) {
    const ds = kills.decisions.filter((d) => d.candidate === c);
    assert.ok(ds.every((d) => d.part), `${c}: each round must name its part of the file`);
    assert.notEqual(ds[0].objection, ds[1].objection);
  }
});
check('kills', 'kills:every-subject-is-a-phrase-from-the-readme-or-its-file', () => {
  for (const d of kills.decisions) {
    const hay = norm(readme + ' ' + fs.readFileSync(path.join(WAVE, 'specs', `KILLED-${d.candidate}.md`), 'utf8') + ' ' + d.candidate.replace(/-/g, ' ')).toLowerCase();
    assert.ok(hay.includes(d.subject.toLowerCase()), d.subject);
  }
});
check('kills', 'kills:later-built-as-matches-the-slate-survivor-row', () => {
  for (const d of kills.decisions.filter((x) => x.later_built_as)) {
    const row = slateSurvived.split('\n').find((l) => l.startsWith(`| ${d.candidate} (`) || l.startsWith(`| ${d.candidate} |`));
    assert.ok(row && row.includes(`\`${d.later_built_as}\``), `${d.candidate} -> ${d.later_built_as}`);
    assert.ok(index.claims.some((c) => c.slug === d.later_built_as), `${d.later_built_as} is not in the index`);
  }
});
// When each kill was made, read from the run log, against the minute the slate gives for the grade B rule.
const autopilot = fs.readFileSync(path.join(WAVE, 'supervisor/AUTOPILOT.md'), 'utf8');
const minutes = (hhmm) => { const [h, m] = hhmm.split(':').map(Number); return h * 60 + m; };
const ruleMinute = (() => { const m = /\*\*Rule change, (\d{2}:\d{2})\.\*\*/.exec(slate); return m ? minutes(m[1]) : null; })();
const killMinutes = (c) => [...autopilot.matchAll(new RegExp(`^- (\\d{2}:\\d{2}) WAKE spec ${c}: KILLED ${c}\\b`, 'gm'))].map((m) => minutes(m[1]));
const decisionMinute = (d) => { const same = kills.decisions.filter((x) => x.candidate === d.candidate); return killMinutes(d.candidate)[same.indexOf(d)]; };
const timingOf = (d) => (decisionMinute(d) > ruleMinute ? 'after' : 'before');
check('kills', 'kills:every-kill-is-dated-by-the-run-log-against-the-grade-b-rule', () => {
  assert.ok(ruleMinute !== null, 'SLATE.md no longer dates the rule change');
  for (const d of kills.decisions) {
    const t = decisionMinute(d);
    assert.ok(Number.isInteger(t), `${d.candidate} (${d.round}): no KILLED line in the run log for this decision`);
    if (d.round === 'first-pass') assert.ok(t <= ruleMinute, `${d.candidate} is filed before the rule but was killed after it`);
    else if (d.round === 'after-grade-b') assert.ok(t > ruleMinute, `${d.candidate} is filed after the rule but was killed before it`);
    else {
      assert.ok(d.after_grade_b && typeof d.after_grade_b.value === 'boolean', `${d.candidate}: an unlisted kill must be dated`);
      assert.equal(d.after_grade_b.value, t > ruleMinute, `${d.candidate}: after_grade_b disagrees with the run log`);
      assert.ok(autopilot.includes(d.after_grade_b.kill_logged.replace(/^supervisor\/AUTOPILOT\.md: /, '- ')), `${d.candidate}: the quoted log line is not in the run log`);
      assert.ok(norm(fs.readFileSync(path.join(WAVE, 'specs', `KILLED-${d.candidate}.md`), 'utf8')).includes(norm(d.after_grade_b.file_says)), `${d.candidate}: the quoted file line is not in its file`);
    }
  }
});
check('kills', 'kills:where-a-file-names-its-own-side-the-reading-agrees', () => {
  let named = 0;
  for (const d of kills.decisions) {
    let t = fs.readFileSync(path.join(WAVE, 'specs', `KILLED-${d.candidate}.md`), 'utf8');
    if (d.part) t = t.slice(d.part.from ? t.indexOf(d.part.from) : 0, d.part.to ? t.indexOf(d.part.to) : t.length);
    const says = [...t.matchAll(/\b(claimant|control)[- ]side\b/gi)].map((m) => (m[1].toLowerCase() === 'claimant' ? 'claim' : 'control'));
    if (!says.length) { assert.ok(!d.file_names_side, `${d.candidate}: file_names_side, but the file names no side`); continue; }
    named++;
    for (const side of says) assert.equal(d.side, side, `${d.candidate} (${d.round}): the file names the ${side} side, the page reads ${d.side}`);
    assert.ok(d.file_names_side && norm(t).includes(norm(d.file_names_side)), `${d.candidate}: the file's own words on its side are not kept`);
  }
  assert.equal(named, kills.decisions.filter((d) => d.file_names_side).length);
});
check('kills', 'kills:sides-and-rounds-use-the-declared-vocabulary', () => {
  for (const d of kills.decisions) {
    assert.ok(['claim', 'control', 'both'].includes(d.side));
    assert.ok(d.side in kills.sides);
  }
  assert.ok(!/\b(fraud|fabricat|misconduct)/i.test(JSON.stringify(kills)), 'describe work, never people');
});

// ================================================================== compute: every aggregate, recomputed here
const L2 = E.secondLayer(recs);
// The timeline, laid out here from the raw records: each row's order, words and bar, as fractions of the track.
const endOf = (j) => (j.years_to_decision === null ? fracYear(j.verdict.as_of) : j.claim.year + j.years_to_decision);
function timelineOrder(mode) {
  const rs = raw.map((r) => ({ dir: r.dir, title: r.j.title, open: r.j.years_to_decision === null, start: r.j.claim.year, span: endOf(r.j) - r.j.claim.year }));
  if (mode === 'calendar') rs.sort((a, b) => a.start - b.start || a.title.localeCompare(b.title, 'en'));
  else rs.sort((a, b) => (a.open - b.open) || a.span - b.span || a.title.localeCompare(b.title, 'en'));
  return rs.map((r) => r.dir);
}
function timelineExpect(mode) {
  const lo = mode === 'calendar' ? Math.floor(Math.min(...raw.map((r) => r.j.claim.year)) / 10) * 10 : 0;
  const hi = mode === 'calendar' ? Math.max(...raw.map((r) => endOf(r.j))) : Math.max(1, ...raw.map((r) => endOf(r.j) - r.j.claim.year));
  return timelineOrder(mode).map((dir) => {
    const j = raw.find((r) => r.dir === dir).j;
    const open = j.years_to_decision === null;
    const w = open ? `claimed ${j.claim.year}, open to its as-of date, ${pl(Math.floor(endOf(j) - j.claim.year), 'year', 'years')} so far`
      : j.years_to_decision === 0 ? `claimed ${j.claim.year}, decided within a year of it` : `claimed ${j.claim.year}, decided ${j.claim.year + j.years_to_decision}, ${pl(j.years_to_decision, 'year', 'years')}`;
    const a = mode === 'calendar' ? j.claim.year : 0;
    const b = mode === 'calendar' ? endOf(j) : endOf(j) - j.claim.year;
    return { dir, title: j.title, words: `${j.verdict.category} · ${w}`, open, zero: !open && j.years_to_decision === 0, left: (a - lo) / (hi - lo), width: (b - a) / (hi - lo) };
  });
}
check('compute', 'compute:verdict-counts-and-their-sentence', () => {
  const c = { VINDICATED: 0, DISSOLVED: 0, ARTEFACT: 0, OPEN: 0, WITHDRAWN: 0 };
  for (const r of raw) c[r.j.verdict.category]++;
  assert.deepEqual(L2.verdicts.counts, c);
  assert.equal(L2.verdicts.total, N);
  const s = T.verdictSentence(L2.verdicts);
  assert.equal(s, `Of ${N} claims, ${c.VINDICATED} vindicated, ${c.DISSOLVED} dissolved, ${c.ARTEFACT} ${c.ARTEFACT === 1 ? 'artefact' : 'artefacts'}, ${c.OPEN} open and ${c.WITHDRAWN} withdrawn, each as of its own record’s date.`);
  assert.equal(T.vindicatedSentence(L2.verdicts), `${c.VINDICATED} of ${N} claims were vindicated.`);
});
check('compute', 'compute:years-to-decision-by-what-decided-it', () => {
  const by = {};
  for (const r of raw) if (r.j.years_to_decision !== null) (by[r.j.decided_by] ||= []).push(r.j.years_to_decision);
  const order = ['more-data', 'independent-replication', 'instrument', 'analysis', 'contamination', 'perception', 'theory'];
  const want = order.filter((k) => by[k]).map((k) => ({ k, v: by[k].sort((a, b) => a - b) }));
  assert.deepEqual(L2.years.rows.map((r) => r.decidedBy), want.map((w) => w.k));
  L2.years.rows.forEach((row, i) => {
    assert.deepEqual(row.values, want[i].v);
    assert.equal(row.median, median(want[i].v));
    assert.equal(row.n, want[i].v.length);
  });
  const open = raw.filter((r) => r.j.years_to_decision === null).length;
  assert.equal(L2.years.undecided, open);
  assert.equal(L2.years.decidedN, N - open);
  assert.equal(T.openCountText(L2.years), `${N - open} ${N - open === 1 ? 'claim has' : 'claims have'} a decision year. ${open} ${open === 1 ? 'open claim is' : 'open claims are'} left out of every figure below, because an open claim has no end to measure.`);
  assert.equal(L2.years.axisMax, Math.max(1, ...want.map((w) => w.v[w.v.length - 1])));
  const absent = order.filter((k) => !by[k]);
  assert.deepEqual(L2.years.absent, absent);
});
check('compute', 'compute:looking-again-against-new-evidence', () => {
  const fam = { instrument: 'recheck', analysis: 'recheck', contamination: 'recheck', perception: 'recheck', 'more-data': 'new', 'independent-replication': 'new' };
  const a = raw.filter((r) => fam[r.j.decided_by] === 'recheck' && r.j.years_to_decision !== null).map((r) => r.j.years_to_decision).sort((x, y) => x - y);
  const b = raw.filter((r) => fam[r.j.decided_by] === 'new' && r.j.years_to_decision !== null).map((r) => r.j.years_to_decision).sort((x, y) => x - y);
  const got = L2.families;
  const ra = got.rows.find((r) => r.family === 'recheck'), rb = got.rows.find((r) => r.family === 'new');
  assert.equal(!!ra, a.length > 0); assert.equal(!!rb, b.length > 0);
  if (!a.length || !b.length) { assert.equal(got.separated, null); assert.equal(got.pairs, null); return; }
  assert.deepEqual(ra.values, a); assert.deepEqual(rb.values, b);
  assert.equal(ra.median, median(a)); assert.equal(rb.median, median(b));
  const sep = a[a.length - 1] < b[0] ? 'recheck-sooner' : a[0] > b[b.length - 1] ? 'new-sooner' : 'overlap';
  assert.equal(got.separated, sep);
  let sooner = 0, same = 0, later = 0;
  for (const x of a) for (const y of b) { if (x < y) sooner++; else if (x === y) same++; else later++; }
  assert.deepEqual(got.pairs, { n: a.length * b.length, sooner, same, later });
  const s = T.familySentence(got);
  const span = (v) => (v[0] === v[v.length - 1] ? pl(v[0], 'year', 'years') : `${v[0]} to ${v[v.length - 1]} years`);
  assert.ok(s.includes(`${pl(a.length, 'claim', 'claims')}, ${span(a)}, median ${fmt1(median(a))}.`), s);
  assert.ok(s.includes(`${pl(b.length, 'claim', 'claims')}, ${span(b)}, median ${fmt1(median(b))}.`), s);
  const tail = { 'recheck-sooner': ' In this selection every claim settled by looking again at the original evidence was settled sooner than every claim settled by new evidence.', 'new-sooner': ' In this selection every claim settled by new evidence was settled sooner than every claim settled by looking again at the original evidence.', overlap: ' In this selection the two ranges overlap.' }[sep];
  assert.ok(s.endsWith(`${tail} Pairing each claim settled by looking again with each claim settled by new evidence gives ${pl(a.length * b.length, 'pairing', 'pairings')}: in ${sooner} the first was settled sooner, in ${same} in the same number of years, and in ${later} later.`), s);
});
check('compute', 'compute:the-comparison-rule-says-overlap-and-reversal-when-the-data-do', () => {
  const mk = (slug, decided, ytd) => E.normalize({ slug, title: slug, href: `/strata/${slug}/`, claim: { year: 1990 }, verdict: { category: 'ARTEFACT', as_of: '2026-09-22', sources: ['a', 'b'] }, decided_by: decided, years_to_decision: ytd, power: { grade: 'A-injection' }, ledger: {} }, slug);
  const overlap = E.yearsByFamily([mk('a', 'instrument', 2), mk('b', 'instrument', 20), mk('c', 'more-data', 10)]);
  assert.equal(overlap.separated, 'overlap');
  assert.ok(T.familySentence(overlap).includes(' In this selection the two ranges overlap. Pairing each claim settled by looking again with each claim settled by new evidence gives 2 pairings: in 1 the first was settled sooner, in 0 in the same number of years, and in 1 later.'));
  assert.equal(E.yearsByFamily([mk('a', 'analysis', 2), mk('b', 'analysis', 8), mk('c', 'more-data', 5), mk('d', 'more-data', 10)]).separated, 'overlap', 'interleaved ranges overlap');
  assert.equal(E.yearsByFamily([mk('a', 'analysis', 2), mk('c', 'more-data', 2)]).separated, 'overlap', 'a tie is not sooner');
  const reversed = E.yearsByFamily([mk('a', 'contamination', 30), mk('c', 'independent-replication', 3), mk('d', 'more-data', 4)]);
  assert.equal(reversed.separated, 'new-sooner');
  assert.deepEqual(reversed.rows.find((r) => r.family === 'new').deciders, ['more-data', 'independent-replication']);
  assert.equal(E.yearsByFamily([mk('a', 'instrument', 2)]).separated, null, 'no comparison with one side empty');
});
check('compute', 'compute:grades-and-the-claims-settled-against-their-claimants', () => {
  const A = raw.filter((r) => r.j.power.grade === 'A-injection').length;
  const B = raw.filter((r) => r.j.power.grade === 'B-published-sensitivity').length;
  assert.deepEqual([L2.grades.A, L2.grades.B, L2.grades.other], [A, B, N - A - B]);
  assert.equal(T.gradeSentence(L2.grades).slice(0, `${A} of ${N} controls`.length), `${A} of ${N} controls`);
  assert.ok(T.gradeSentence(L2.grades).includes(`${B} of ${N} could only be trusted`));
  const against = raw.filter((r) => ['DISSOLVED', 'ARTEFACT', 'WITHDRAWN'].includes(r.j.verdict.category));
  const aA = against.filter((r) => r.j.power.grade === 'A-injection').length;
  const aB = against.filter((r) => r.j.power.grade === 'B-published-sensitivity').length;
  assert.deepEqual([L2.against.n, L2.against.A, L2.against.B], [against.length, aA, aB]);
  assert.ok(T.againstSentence(L2.against).startsWith(`Of ${against.length} claims the record settled against the claimants`));
  assert.ok(T.againstSentence(L2.against).includes(`, ${aA} ${aA === 1 ? 'rests' : 'rest'} on a control the page reran`));
  assert.ok(T.againstSentence(L2.against).includes(`and ${aB} on a control trusted`));
});
check('compute', 'compute:ledger-tallies-per-cell-and-no-score-per-page', () => {
  const keys = ['claim_reproduced', 'control_computed', 'control_can_confirm', 'rendered_figures_asserted', 'choices_are_live', 'planted_fault_caught', 'refusal_asserted', 'provenance_pinned', 'verdict_dated'];
  L2.ledger.forEach((t, i) => {
    const k = keys[i];
    const tt = raw.filter((r) => r.j.ledger?.[k]?.value === true).length;
    const ff = raw.filter((r) => r.j.ledger?.[k]?.value === false).length;
    assert.deepEqual([t.key, t.true, t.false, t.absent], [k, tt, ff, N - tt - ff]);
    assert.equal(T.ledgerFootText(t), ff || N - tt - ff ? `${[ff ? `false on ${ff}` : '', N - tt - ff ? `missing on ${N - tt - ff}` : ''].filter(Boolean).join(', ')} of ${N}` : `true on all ${N}`);
  });
  for (const r of recs) assert.equal(r.ledger.length, 9);
  // The no-score rule is held by behaviour and a wider lint in compute:no-score-a-ledger-cell-moves-nothing-but-the-wall.
});
check('compute', 'compute:the-false-cells-sentence-names-every-false-cell', () => {
  const sorted = recs.slice().sort(E.byYearThenTitle);
  const s = T.falseCellsText(sorted);
  let count = 0;
  for (const r of raw) for (const [k, v] of Object.entries(r.j.ledger)) if (v.value === false) { count++; assert.ok(s.includes(`${T.LEDGER_LABEL[k]} on ${r.j.title}`), `${k} on ${r.dir}`); }
  assert.equal((s.match(/ on /g) || []).length, count);
});
check('compute', 'compute:the-contract-rules-against-every-record', () => {
  const byId = Object.fromEntries(L2.rules.map((r) => [r.id, r]));
  const openNotYet = raw.filter((r) => (r.j.verdict.category === 'OPEN') === (r.j.decided_by === 'not-yet')).length;
  assert.deepEqual([byId['open-iff-not-yet'].holding, byId['open-iff-not-yet'].applicable], [openNotYet, N]);
  const gb = raw.filter((r) => r.j.power.grade === 'B-published-sensitivity');
  assert.deepEqual([byId['grade-b-cell-false'].applicable, byId['grade-b-cell-false'].holding], [gb.length, gb.filter((r) => r.j.ledger.control_can_confirm.value === false).length]);
  const two = raw.filter((r) => Array.isArray(r.j.verdict.sources) && r.j.verdict.sources.length >= 2).length;
  assert.equal(byId['two-sources'].holding, two);
  const decided = raw.filter((r) => r.j.years_to_decision !== null);
  assert.equal(byId['decided-by-as-of'].applicable, decided.length);
  assert.equal(byId['decided-by-as-of'].holding, decided.filter((r) => r.j.claim.year + r.j.years_to_decision <= Number(r.j.verdict.as_of.slice(0, 4))).length);
  assert.equal(byId['verdict-vocab'].holding, raw.filter((r) => V_ORDER.includes(r.j.verdict.category)).length);
  assert.equal(byId['decided-vocab'].holding, raw.filter((r) => D_ORDER.includes(r.j.decided_by)).length);
  assert.equal(byId['open-iff-no-years'].holding, raw.filter((r) => (r.j.verdict.category === 'OPEN') === (r.j.years_to_decision === null)).length);
  assert.equal(byId.dated.holding, raw.filter((r) => /^\d{4}-\d{2}-\d{2}$/.test(r.j.verdict.as_of) && !Number.isNaN(fracYear(r.j.verdict.as_of))).length);
  assert.equal(byId['nine-cells'].holding, raw.filter((r) => L_KEYS.every((k) => typeof r.j.ledger?.[k]?.value === 'boolean' && String(r.j.ledger[k].assertion || '').trim())).length);
  assert.equal(byId['href-is-slug'].holding, raw.filter((r) => r.j.href === `/strata/${r.dir}/`).length);
  assert.deepEqual(L2.rules.map((r) => r.id), ['verdict-vocab', 'decided-vocab', 'open-iff-not-yet', 'open-iff-no-years', 'two-sources', 'dated', 'decided-by-as-of', 'grade-b-cell-false', 'nine-cells', 'href-is-slug']);
  for (const rc of L2.rules) assert.equal(T.ruleCountText(rc), rc.applicable ? `holds for ${rc.holding} of ${rc.applicable}` : 'applies to none');
});
check('compute', 'compute:every-arrangement-groups-every-claim-once', () => {
  const keyOf = {
    verdict: (j) => j.verdict.category, decided: (j) => j.decided_by, years: (j) => (j.years_to_decision === null ? 'undecided' : j.years_to_decision),
    field: (j) => String(j.field).split('(')[0].trim().toLowerCase(), grade: (j) => j.power.grade, decade: (j) => Math.floor(j.claim.year / 10) * 10,
  };
  assert.deepEqual(E.ARRANGEMENTS, Object.keys(keyOf));
  for (const by of E.ARRANGEMENTS) {
    const arr = E.arrange(recs, by);
    const want = {};
    for (const r of raw) { const k = keyOf[by](r.j); want[k] = (want[k] || 0) + 1; }
    const got = {};
    for (const g of arr.groups) if (g.items.length) got[g.key] = g.items.length;
    assert.deepEqual(got, want, by);
    assert.equal(arr.groups.reduce((s, g) => s + g.items.length, 0), N);
    const groupsN = Object.keys(want).length;
    assert.ok(T.arrangeReadout(arr).startsWith(`Arranged by ${T.ARRANGEMENT_LABEL[by]}: ${N} claims in ${groupsN} ${groupsN === 1 ? 'group' : 'groups'}.`), by);
    const counts = Object.entries(want);
    const order = {
      verdict: V_ORDER,
      decided: D_ORDER.filter((k) => want[k]),
      years: [...Object.keys(want).filter((k) => k !== 'undecided').map(Number).sort((x, y) => x - y), ...(want.undecided ? ['undecided'] : [])],
      field: counts.sort((x, y) => (y[1] - x[1]) || x[0].localeCompare(y[0], 'en')).map((x) => x[0]),
      grade: G_ORDER.filter((k) => want[k]),
      decade: Object.keys(want).map(Number).sort((x, y) => x - y),
    }[by];
    assert.deepEqual(arr.groups.map((g) => g.key), order, `${by}: group order`);
    for (const g of arr.groups) assert.deepEqual(g.items.map((r) => r.slug), raw.filter((r) => String(keyOf[by](r.j)) === String(g.key)).sort(byYT).map((r) => r.dir), `${by}/${g.key}: order inside the group`);
    if (by === 'verdict') {
      assert.deepEqual(arr.groups.map((g) => g.key), E.VERDICTS);
      const empty = E.VERDICTS.filter((v) => !want[v]);
      for (const v of empty) assert.ok(T.arrangeReadout(arr).includes(v), `empty ${v} named`);
    }
  }
});
check('compute', 'compute:the-timeline-ends-where-the-records-say-and-open-bars-end-at-as-of', () => {
  for (const mode of ['calendar', 'aligned']) {
    const tl = E.timeline(recs, mode);
    assert.equal(tl.rows.length + tl.refused.length, N);
    for (const row of tl.rows) {
      const j = raw.find((r) => r.dir === row.slug).j;
      const open = j.years_to_decision === null;
      assert.equal(row.open, open);
      assert.equal(row.start, j.claim.year);
      const end = open ? fracYear(j.verdict.as_of) : j.claim.year + j.years_to_decision;
      assert.ok(Math.abs(row.end - end) < 1e-9, row.slug);
      if (open) assert.equal(row.openYears, Math.floor(end - j.claim.year));
      assert.ok(row.x0 >= -1e-9 && row.x1 <= 1 + 1e-9 && row.x0 <= row.x1 + 1e-9, `${row.slug} geometry`);
    }
    const nOpen = raw.filter((r) => r.j.years_to_decision === null).length;
    const s = T.timelineReadout(tl);
    assert.ok(s.startsWith(`${N} claims`), s);
    assert.ok(s.includes(`${N - nOpen} decided`) && s.includes(`${nOpen}`), s);
    assert.deepEqual(tl.rows.map((r) => r.slug), timelineOrder(mode), `${mode}: row order`);
    if (mode === 'calendar') assert.equal(tl.lo, Math.floor(Math.min(...raw.map((r) => r.j.claim.year)) / 10) * 10);
  }
});
check('compute', 'compute:every-cross-tabulation-of-every-ordered-pair', () => {
  assert.deepEqual(Object.keys(E.DIMENSIONS).sort(), Object.keys(DIMS).sort());
  let pairs = 0;
  for (const rd of Object.keys(DIMS)) for (const cd of Object.keys(DIMS)) {
    if (rd === cd) { assert.throws(() => E.crossTab(recs, rd, cd)); continue; }
    pairs++;
    const ct = E.crossTab(recs, rd, cd);
    const want = crossOf(raw, rd, cd);
    assert.deepEqual(ct.rows, want.rows, `${rd} x ${cd}: rows`);
    assert.deepEqual(ct.cols, want.cols, `${rd} x ${cd}: columns`);
    assert.deepEqual(ct.counts, want.counts, `${rd} x ${cd}: counts`);
    assert.deepEqual(ct.titles, want.titles, `${rd} x ${cd}: the claims in each cell`);
    assert.deepEqual(ct.rowTotals, want.counts.map((row) => row.reduce((x, y) => x + y, 0)), `${rd} x ${cd}: row totals`);
    assert.deepEqual(ct.colTotals, want.cols.map((_, j) => want.counts.reduce((x, row) => x + row[j], 0)), `${rd} x ${cd}: column totals`);
    assert.equal(ct.total, N);
    assert.equal(ct.identity, identityPair(rd, cd), `${rd} x ${cd}: identity flag`);
    assert.equal(T.crossReadout(ct, null), crossWords(raw, rd, cd, null));
    ct.counts.forEach((row, i) => row.forEach((n, j) => { if (n) assert.equal(T.crossReadout(ct, [i, j]), crossWords(raw, rd, cd, [i, j])); }));
  }
  assert.equal(pairs, 30);
});
// The before-and-after sentence, dated here from the run log rather than from kills.json's own fields.
function sideWords() {
  const tally = (when) => {
    const ds = kills.decisions.filter((d) => timingOf(d) === when);
    const c = (side) => ds.filter((d) => d.side === side).length;
    const u = ds.filter((d) => d.round !== 'first-pass' && d.round !== 'after-grade-b').length;
    return { n: ds.length, claim: c('claim'), control: c('control'), both: c('both'), note: u ? ` (counting ${pl(u, 'kill', 'kills')} the slate lists only among the pages later built, dated by ${u === 1 ? 'its' : 'their'} own file and the run log)` : '' };
  };
  const b = tally('before'), a = tally('after');
  return `Before grade B existed, ${b.control} of ${b.n} kills fell on the control side, ${b.claim} on the claim side and ${b.both} on both${b.note}. After it, ${a.control} of ${a.n} fell on the control side, ${a.claim} on the claim side and ${a.both} on both${a.note}.`;
}
function killsLeadWords() {
  const cands = [...new Set(kills.decisions.map((d) => d.candidate))];
  const twice = cands.filter((c) => kills.decisions.filter((d) => d.candidate === c).length > 1).length;
  const later = kills.decisions.filter((d) => d.later_built_as).length;
  const bits = [];
  if (twice) bits.push(`${twice} ${twice === 1 ? 'was' : 'were'} killed twice`);
  if (later) bits.push(`${later} ${later === 1 ? 'was' : 'were'} later specified again and built`);
  return `The wave killed ${pl(cands.length, 'candidate', 'candidates')} at spec in ${pl(kills.decisions.length, 'decision', 'decisions')}${bits.length ? `: ${words(bits)}` : ''}.`;
}
check('compute', 'compute:the-kill-tallies-and-their-sentences', () => {
  const ks = E.killsSummary(kills);
  const cands = new Set(kills.decisions.map((d) => d.candidate));
  assert.equal(ks.decisions, kills.decisions.length);
  assert.equal(ks.candidates, cands.size);
  const count = (round, side) => kills.decisions.filter((d) => d.round === round && d.side === side).length;
  for (const round of [...new Set(kills.decisions.map((d) => d.round))]) for (const side of ['claim', 'control', 'both']) assert.equal(ks.byRoundSide[round][side], count(round, side));
  assert.deepEqual(Object.keys(ks.byRoundSide), [...new Set(kills.decisions.map((d) => d.round))], 'the tally keeps the order of the rounds');
  for (const when of ['before', 'after']) for (const side of ['claim', 'control', 'both']) assert.equal(ks.byTiming[when][side], kills.decisions.filter((d) => timingOf(d) === when && d.side === side).length, `${when} ${side}`);
  assert.equal(ks.byTiming.undated.n, 0, 'every kill is dated against the rule');
  assert.equal(ks.twice.length, [...cands].filter((c) => kills.decisions.filter((d) => d.candidate === c).length > 1).length);
  assert.equal(ks.laterBuilt.length, kills.decisions.filter((d) => d.later_built_as).length);
  assert.equal(T.killsLead(ks), killsLeadWords());
  assert.equal(T.sideSentence(ks), sideWords());
  for (const side of ['all', 'claim', 'control', 'both']) {
    const k = E.killsShown(kills, side);
    assert.equal(k.shown, side === 'all' ? kills.decisions.length : kills.decisions.filter((d) => d.side === side).length);
  }
});
check('compute', 'compute:counts-move-with-the-records (nothing is a typed count)', () => {
  const fewer = recs.slice(1);
  assert.equal(E.secondLayer(fewer).total, N - 1);
  assert.ok(T.arrangeReadout(E.arrange(fewer, 'verdict')).includes(`${N - 1} claims`));
  const lost = recs[0].verdict;
  assert.equal(E.verdictCounts(fewer).counts[lost], L2.verdicts.counts[lost] - 1);
});

// ================================================================== refuse: doctored records
const base = structuredClone(raw.find((r) => r.j.years_to_decision !== null).j);
function doctored(slug, edit) { const j = structuredClone(base); j.slug = slug; j.title = `Doctored ${slug}`; j.href = `/strata/${slug}/`; edit(j); return E.normalize(j, slug); }
check('refuse', 'refuse:the-timeline-will-not-draw-an-impossible-record', () => {
  const bad = [
    doctored('x-open-with-years', (j) => { j.verdict.category = 'OPEN'; j.decided_by = 'not-yet'; j.years_to_decision = 3; }),
    doctored('x-settled-no-years', (j) => { j.years_to_decision = null; }),
    doctored('x-negative-years', (j) => { j.years_to_decision = -2; }),
    doctored('x-after-as-of', (j) => { j.claim.year = 2025; j.years_to_decision = 5; }),
    doctored('x-no-year', (j) => { delete j.claim.year; }),
    doctored('x-bad-date', (j) => { j.verdict.as_of = '2026-02-30'; }),
    doctored('x-claim-after-as-of', (j) => { j.claim.year = 2031; j.years_to_decision = 0; }),
    doctored('x-fractional-years', (j) => { j.years_to_decision = 2.5; }),
  ];
  // Each doctored record must be refused for the reason it was doctored to carry, in the page's own words.
  const R = E.REFUSALS;
  const because = { 'x-open-with-years': R.openWithYears, 'x-settled-no-years': R.settledNoYears, 'x-negative-years': R.badYears, 'x-after-as-of': R.decisionAfterAsOf, 'x-no-year': R.noClaimYear, 'x-bad-date': R.noAsOf, 'x-claim-after-as-of': R.claimAfterAsOf, 'x-fractional-years': R.badYears };
  const tl = E.timeline([...recs, ...bad], 'calendar');
  for (const b of bad) {
    assert.ok(!tl.rows.some((r) => r.slug === b.slug), `${b.slug} was drawn`);
    const ref = tl.refused.find((r) => r.slug === b.slug);
    assert.ok(ref && ref.reasons.includes(because[b.slug]), `${b.slug} was not refused for ${because[b.slug]}`);
  }
  assert.deepEqual(new Set(Object.values(because)), new Set(Object.values(R)), 'every refusal the engine can give is exercised');
  assert.equal(tl.rows.length, E.timeline(recs, 'calendar').rows.length, 'the good records are still drawn');
  assert.ok(T.refusedText(tl).startsWith('Not drawn: '));
  assert.ok(T.refusedText(tl).includes('an OPEN verdict that also gives a decision year'));
});
check('refuse', 'refuse:the-contract-rules-catch-doctored-records', () => {
  const bad = [
    doctored('x-grade-b-true', (j) => { j.power.grade = 'B-published-sensitivity'; j.ledger.control_can_confirm.value = true; }),
    doctored('x-one-source', (j) => { j.verdict.sources = [j.verdict.sources[0]]; }),
    doctored('x-open-decided', (j) => { j.verdict.category = 'OPEN'; }),
    doctored('x-missing-cell', (j) => { delete j.ledger.verdict_dated; }),
    doctored('x-new-verdict', (j) => { j.verdict.category = 'DEBATED'; }),
  ];
  const more = [
    doctored('x-hunch', (j) => { j.decided_by = 'hunch'; }),
    doctored('x-open-with-years-rule', (j) => { j.verdict.category = 'OPEN'; j.decided_by = 'not-yet'; }),
    doctored('x-undated', (j) => { j.verdict.as_of = 'last spring'; }),
    doctored('x-decided-late', (j) => { j.claim.year = 2020; j.years_to_decision = 9; }),
    doctored('x-elsewhere', (j) => { j.href = '/strata/elsewhere/'; }),
  ];
  // Each doctored record is named by exactly the rule it breaks: the rows are shown to be able to fail.
  const rules = Object.fromEntries(E.contractChecks([...recs, ...bad, ...more]).map((r) => [r.id, r]));
  const t = (slug) => [...bad, ...more].find((r) => r.slug === slug).title;
  const expectFail = {
    'grade-b-cell-false': 'x-grade-b-true', 'two-sources': 'x-one-source', 'open-iff-not-yet': 'x-open-decided', 'nine-cells': 'x-missing-cell',
    'verdict-vocab': 'x-new-verdict', 'decided-vocab': 'x-hunch', 'open-iff-no-years': 'x-open-with-years-rule', dated: 'x-undated',
    'decided-by-as-of': 'x-decided-late', 'href-is-slug': 'x-elsewhere',
  };
  assert.deepEqual(Object.keys(expectFail).sort(), E.RULES.map((r) => r.id).sort(), 'every rule has a doctored record');
  for (const [id, slug] of Object.entries(expectFail)) assert.ok(rules[id].failing.includes(t(slug)), `${id} did not name ${slug}`);
  const tall = E.ledgerTallies([...recs, bad[3]]);
  assert.equal(tall[8].absent, 1, 'a missing cell is shown as missing, never as false');
});
check('refuse', 'refuse:a-verdict-outside-the-five-words-is-kept-and-named', () => {
  const odd = doctored('x-odd', (j) => { j.verdict.category = 'DEBATED'; });
  const arr = E.arrange([...recs, odd], 'verdict');
  assert.ok(arr.groups.some((g) => g.key === 'outside the vocabulary' && g.items.length === 1));
  assert.ok(T.verdictSentence(E.verdictCounts([...recs, odd])).includes('1 record carries a verdict outside the five words'));
});
check('refuse', 'refuse:the-index-refuses-a-record-whose-slug-disagrees-with-its-directory', () => withTree((t, s) => {
  const f = path.join(s, first, 'record.json');
  const j = JSON.parse(fs.readFileSync(f, 'utf8'));
  j.slug = 'somewhere-else';
  fs.writeFileSync(f, JSON.stringify(j));
  const w = cli(t);
  assert.notEqual(w.status, 0, 'the generator wrote an index over a mislabelled record');
  assert.notEqual(cli(t, '--check').status, 0);
}));
check('refuse', 'refuse:the-page-will-not-fetch-a-path-outside-a-record', () => {
  const src = fs.readFileSync(path.join(P.dir, 'page.js'), 'utf8');
  const m = /const RECORD_PATH = (\/.*\/);/.exec(src);
  assert.ok(m);
  const re = eval(m[1]); // eslint-disable-line no-eval
  assert.ok(re.test('/strata/the-sum-nobody-knew/record.json'));
  for (const bad of ['https://example.com/strata/a/record.json', '/strata/../secret/record.json', '//evil.test/strata/a/record.json', '/strata/a/other.json']) assert.ok(!re.test(bad), bad);
  assert.ok(src.includes('m[1] !== e.slug'), 'the path must name the slug the index gives');
});

check('refuse', 'refuse:the-check-panel-lists-every-refusal-the-engine-can-give', () => {
  const p = textOf(/<p id="check-refused">([\s\S]*?)<\/p>/.exec(html)[1]);
  for (const reason of Object.values(E.REFUSALS)) assert.ok(p.includes(reason), `the static list leaves out: ${reason}`);
  assert.equal((p.match(/;/g) || []).length + 1, Object.keys(E.REFUSALS).length, 'the static list names a reason the engine does not give');
});
check('refuse', 'refuse:a-record-link-that-is-not-a-page-here-is-drawn-as-text', () => {
  const src = fs.readFileSync(path.join(P.dir, 'render.js'), 'utf8');
  const m = /export const safeHref = \(h\) => \(typeof h === 'string' && (\/.*\/)\.test\(h\) \? h : null\);/.exec(src);
  assert.ok(m, 'render.js no longer guards hrefs');
  const re = eval(m[1]); // eslint-disable-line no-eval
  for (const r of recs) assert.ok(re.test(r.href), r.slug);
  for (const bad of ['javascript:alert(1)', 'https://example.com/', '//evil.test/strata/a/', '/strata/../x/', '/strata/a', null]) assert.ok(!(typeof bad === 'string' && re.test(bad)), String(bad));
  assert.ok(!/el\('a', \{ href: r\.href \}/.test(src), 'a raw record href reaches a link');
});
check('compute', 'compute:the-verdict-s-own-bounds-reach-the-card-whole', () => {
  let bounded = 0;
  for (const r of raw) {
    const n = recs.find((x) => x.slug === r.dir);
    assert.deepEqual(n.scopes, scopesOf(r.j), r.dir);
    if (n.scopes.length) bounded++;
  }
  assert.ok(bounded === raw.filter((r) => scopesOf(r.j).length).length);
});
check('compute', 'compute:no-score-a-ledger-cell-moves-nothing-but-the-wall', () => {
  // Behaviour, not only a lint: flip one ledger cell and nothing the page reports may move except the wall's own
  // tallies, the false-cells sentence, the rule that reads that cell and the wall's row filter.
  const r0 = raw.find((r) => r.j.ledger.claim_reproduced.value === true);
  const flipped = structuredClone(r0.j); flipped.ledger.claim_reproduced.value = false;
  const recs2 = recs.map((r) => (r.slug === r0.dir ? E.normalize(flipped, r0.dir) : r));
  const a = E.secondLayer(recs), b = E.secondLayer(recs2);
  for (const k of Object.keys(a)) if (!['ledger', 'rules'].includes(k)) assert.deepEqual(b[k], a[k], `${k} moved with a ledger cell`);
  for (const by of E.ARRANGEMENTS) assert.deepEqual(E.arrange(recs2, by).groups.map((g) => g.items.map((x) => x.slug)), E.arrange(recs, by).groups.map((g) => g.items.map((x) => x.slug)), `${by} moved with a ledger cell`);
  for (const mode of ['calendar', 'aligned']) assert.deepEqual(E.timeline(recs2, mode).rows.map((x) => x.slug), E.timeline(recs, mode).rows.map((x) => x.slug));
  const norm0 = E.normalize(r0.j, r0.dir), norm1 = E.normalize(flipped, r0.dir);
  for (const k of Object.keys(norm0)) if (k !== 'ledger') assert.deepEqual(norm1[k], norm0[k], `normalize.${k} moved with a ledger cell`);
  for (const f of ['engine.js', 'render.js', 'text.js', 'page.js']) {
    const src = fs.readFileSync(path.join(P.dir, f), 'utf8');
    assert.ok(!/ledger\s*(?:\)\s*)?\.\s*(?:filter|reduce)\s*\(/.test(src), `${f}: a ledger is filtered or reduced, the first step of a per-page score`);
    assert.ok(!/ledger[\s\S]{0,60}?\.length\s*[-+*/]/.test(src), `${f}: arithmetic on a count of ledger cells`);
  }
});

// ================================================================== surface
const dek = fmStr('dek');
const plain = fmStr('plain');
const seoTitle = fmStr('seoTitle');
const title = fmStr('title');
const OG_DESC = 'Extraordinary claims from the record of science, each rebuilt from its authors’ own numbers and put to the test that decided it, or, for a claim still open, the test that would. Sort them by verdict, by what decided them and by how long deciding took, and read what the wave would not build.';
const CANON = `https://artwaste.land/strata/${SLUG}/`;
const OGIMG = `https://artwaste.land/og/${SLUG}.png`;
check('surface', 'surface:title-description-canonical', () => {
  assert.equal(title, 'Every Claim at Full Strength');
  assert.equal(textOf(/<title>([\s\S]*?)<\/title>/.exec(html)[1]), seoTitle);
  assert.equal(meta('name', 'description'), dek);
  assert.ok(html.includes(`<link rel="canonical" href="${CANON}" />`));
  assert.equal(textOf(/<h1>([\s\S]*?)<\/h1>/.exec(html)[1]), title);
  assert.equal(textOf(/<p class="dek">([\s\S]*?)<\/p>/.exec(html)[1]), dek);
});
check('surface', 'surface:open-graph-and-twitter', () => {
  assert.equal(meta('property', 'og:title'), `${title} · Artificial Wasteland`);
  assert.equal(meta('name', 'twitter:title'), `${title} · Artificial Wasteland`);
  assert.equal(meta('property', 'og:description'), OG_DESC);
  assert.equal(meta('name', 'twitter:description'), OG_DESC);
  assert.equal(meta('property', 'og:url'), CANON);
  assert.equal(meta('property', 'og:image'), OGIMG);
  assert.equal(meta('name', 'twitter:image'), OGIMG);
  assert.equal(meta('property', 'og:type'), 'article');
});
check('surface', 'surface:json-ld', () => {
  const blocks = [...html.matchAll(/<script type="application\/ld\+json">([\s\S]*?)<\/script>/g)];
  assert.equal(blocks.length, 1);
  const j = JSON.parse(blocks[0][1]);
  assert.equal(j['@type'], 'Article');
  assert.equal(j.name, seoTitle);
  assert.equal(j.headline, title);
  assert.equal(j.description, dek);
  assert.equal(j.url, CANON);
  assert.equal(j.image, OGIMG);
});
check('surface', 'surface:dek-and-placard-carry-no-count-and-follow-the-rules', () => {
  for (const s of [dek, OG_DESC, plain, seoTitle]) {
    assert.ok(!/\d/.test(s), `a digit in: ${s.slice(0, 60)}`);
    assert.ok(!s.includes(EM));
  }
  assert.ok(plain.length >= 90 && plain.length <= 420, `plain is ${plain.length} characters`);
  assert.ok((plain.match(/[.!?](\s|$)/g) || []).length <= 3, 'plain has more than three sentences');
  assert.ok(!plain.includes('"'));
  const countWord = NUMWORDS[N];
  if (countWord) for (const s of [dek, OG_DESC, plain]) assert.ok(!new RegExp(`\\b${countWord}\\b`, 'i').test(s), `the count ${countWord} is typed`);
  // What the shareable surface says every page did must be true of every record, and what it says of some pages must
  // be there when some records need it: rebuilt claims, the grade B route, open claims.
  assert.ok(dek.includes('rebuilt the claim from its authors’ own numbers') && OG_DESC.includes('each rebuilt from its authors’ own numbers'));
  assert.equal(raw.filter((r) => r.j.ledger.claim_reproduced.value !== true).length, 0, 'the dek says every claim was rebuilt, and a record says it was not');
  const anyB = raw.some((r) => r.j.power.grade === 'B-published-sensitivity');
  const anyA = raw.some((r) => r.j.power.grade === 'A-injection');
  const anyOpen = raw.some((r) => r.j.verdict.category === 'OPEN');
  assert.equal(dek.includes('by setting it against the control’s printed sensitivity where they were not'), anyB, 'the dek and the grade B records disagree');
  assert.equal(dek.includes('by planting the claim into the control’s own data where those were released'), anyA);
  assert.ok(!/tested that test by planting|for each one .* by planting the claim into its data/.test(dek), 'the dek claims planting for every page');
  for (const s of [dek, OG_DESC]) assert.equal(s.includes('for a claim still open, the test that would'), anyOpen, 'an open claim is on the surface only when one is in the index');
  assert.equal(seoTitle.endsWith('and Which Are Still Open'), anyOpen);
  assert.equal(plain.includes('how each has turned out so far and, for the ones already settled, what settled it'), anyOpen);
  const body = textOf(html.slice(html.indexOf('<body>')));
  assert.equal(body.includes('read from the control’s published summary where they were not'), raw.some((r) => r.j.ledger.control_computed.value === false), 'the body and the control-computed cells disagree');
  assert.ok(body.includes('whose claimants’ numbers, and whose control’s data or printed sensitivity, were public in the same observable'));
  // The dek names two claims; both must be in the index.
  assert.ok(dek.includes('a counting horse') && index.claims.some((c) => c.slug === 'the-sum-nobody-knew'));
  assert.ok(dek.includes('faster-than-light neutrinos') && index.claims.some((c) => c.slug === 'the-clock-that-moved-the-particle'));
});
check('surface', 'surface:the-injected-placard-if-present-is-the-frontmatter-plain', () => {
  const m = /<!--aw-plain:start--><meta name="aw-plain" content="([^"]*)" \/><!--aw-plain:end-->/.exec(rawHtml);
  if (m) assert.equal(decode(m[1]), plain);
});
check('surface', 'surface:frontmatter', () => {
  assert.equal(fmStr('seam'), 'groundtruth');
  assert.equal(fmStr('href'), `/strata/${SLUG}/`);
  assert.match(fm, /^draft: false$/m);
  const tags = /^tags:\s*\[(.*)\]$/m.exec(fm)[1];
  for (const t of ['immersive', 'interactive', 'show-the-check', 'at-full-strength']) assert.ok(tags.includes(`"${t}"`), t);
  const rel = [...fm.matchAll(/- to: ([a-z0-9-]+)\n\s+note: "(.*)"/g)];
  assert.ok(rel.length >= 3 && rel.length <= 5, `${rel.length} relates`);
  for (const [, to, note] of rel) {
    assert.ok(fs.existsSync(path.join(root, 'src/content/strata', `${to}.md`)), to);
    assert.ok(!note.includes(EM) && !note.includes('"'));
  }
});
check('surface', 'surface:every-figure-in-the-relates-notes-against-the-records', () => {
  const rel = Object.fromEntries([...fm.matchAll(/- to: ([a-z0-9-]+)\n\s+note: "(.*)"/g)].map((m) => [m[1], m[2]]));
  const rec = (s) => raw.find((r) => r.dir === s).j;
  const p = rec('the-plates-that-were-set-aside');
  assert.ok(rel['the-plates-that-were-set-aside'].includes(`the ${p.claim.year} report's claim ${p.years_to_decision} years later`));
  assert.equal(p.decided_by, 'independent-replication'); assert.equal(p.verdict.category, 'VINDICATED');
  assert.equal(p.power.grade, 'B-published-sensitivity'); assert.equal(p.ledger.control_can_confirm.value, false);
  assert.ok(/no star positions/.test(p.power.trusts) && /1979/.test(p.control.citation));
  const c = rec('thirty-seven-thousand-curtains');
  const note = rel['thirty-seven-thousand-curtains'];
  assert.ok(c.claim.headline_as_printed.startsWith('53.1%') && note.includes('the claimed 53.1%'));
  assert.ok(note.includes(`${c.years_to_decision} years after the ${c.claim.year} claim`));
  assert.equal(c.verdict.category, 'DISSOLVED'); assert.equal(c.power.grade, 'A-injection'); assert.equal(c.decided_by, 'independent-replication');
  assert.ok(/53\.1/.test(c.ledger.control_can_confirm.assertion));
  const cdek = /^dek: "(.*)"$/m.exec(fs.readFileSync(path.join(root, 'src/content/strata/thirty-seven-thousand-curtains.md'), 'utf8'))[1];
  assert.ok(cdek.includes('49.89%') && note.includes('49.89%'));
  const s = rec('the-sum-nobody-knew');
  const sn = rel['the-sum-nobody-knew'];
  // Corrected 2026-09-28 (second pass): this used to assert "the decision in the same year", which
  // the record's own definition contradicts (decided 9 December 1904, claim anchored 5 January 1905).
  assert.ok(sn.includes(`the claim as ${s.claim.year}`) && sn.includes('27 days earlier') && sn.includes('1904') && s.years_to_decision === 0);
  assert.ok(/not in 1905/.test(s.years_to_decision_definition));
  assert.equal(s.decided_by, 'contamination'); assert.equal(s.power.grade, 'A-injection');
  assert.ok(/31-rows/.test(s.ledger.control_can_confirm.assertion) && sn.includes('31 rows'));
  assert.ok(Math.min(...raw.map((r) => r.j.years_to_decision ?? Infinity)) >= s.years_to_decision, 'nothing decided faster');
});
check('surface', 'surface:the-framing-prose-claims-only-what-the-records-and-files-support', () => {
  const body = textOf(html.slice(html.indexOf('<body>')).replace(/<script[\s\S]*?<\/script>/g, ''));
  // The kill screen: a kill can fail because the numbers are not public or because what is public cannot carry the
  // test (several KILLED files say their objection survives perfect data), so the page names both.
  assert.ok(body.includes('each kill names the half of the evidence on which the test broke down, whether because the numbers are not public or because what is public does not measure the claim at its claimed size'));
  assert.ok(!body.includes('which half of the evidence the public record does not hold'));
  const mdBody = norm(md.slice(md.indexOf('\n---', 4) + 4));
  assert.ok(mdBody.includes("counts which half of the evidence each objection falls on: the claimants' numbers, the control's data or printed sensitivity in the same observable, or both."));
  assert.ok(kills.decisions.some((d) => d.side === 'both'), 'the content file names a both side no kill has');
  // The relates note to smaller-than-we-could-see: no causal history that no wave file records, and its factual half
  // (every grade B page records its control-can-confirm cell false) holds on every record.
  const note = Object.fromEntries([...fm.matchAll(/- to: ([a-z0-9-]+)\n\s+note: "(.*)"/g)].map((m) => [m[1], m[2]]))['smaller-than-we-could-see'];
  assert.ok(!/\b(answered|in response|prompted|because of that)\b/i.test(note), 'the note claims the wave answered the portal');
  assert.ok(note.includes('The At Full Strength wave’s own rule meets that warning'));
  assert.ok(note.includes('where a control was published only as a sensitivity the page says grade B and records its control-can-confirm cell false'));
  for (const r of raw.filter((x) => x.j.power.grade === 'B-published-sensitivity')) assert.equal(r.j.ledger.control_can_confirm.value, false, r.dir);
});
check('surface', 'surface:no-figure-a-reader-sees-outside-the-generated-blocks', () => {
  let body = html.slice(html.indexOf('<body>'));
  for (const b of L.BLOCKS) body = body.replace(new RegExp(`<!--${b}:start-->[\\s\\S]*?<!--${b}:end-->`), '');
  const visible = textOf(body.replace(/<script[\s\S]*?<\/script>/g, '').replace(/<style[\s\S]*?<\/style>/g, '').replace(/<!--[\s\S]*?-->/g, ''));
  const digits = [...visible.matchAll(/[\w-]*\d[\w-]*/g)].map((m) => m[0]);
  assert.deepEqual(digits.filter((d) => d !== 'SHA-256'), [], 'a typed figure in the static prose');
  const countWord = NUMWORDS[N];
  if (countWord) assert.ok(!new RegExp(`\\b${countWord}\\b`, 'i').test(visible), `the count ${countWord} is typed into the prose`);
  // Any count of the index's own things, right or stale, is typed prose; every such count comes from the records.
  const counted = new RegExp(`\\b(${NUMWORDS.filter((w) => w !== 'one').join('|')})\\s+(?:[a-z-]+\\s+)?(claims|pages|records|candidates|kills|decisions|controls|verdicts|layers|strata)\\b`, 'i').exec(visible);
  assert.ok(!counted, `a typed count: ${counted && counted[0]}`);
  assert.ok(!/\b(debunked|refuted|disproved)\b/i.test(visible), 'an open claim is never debunked');
  // A numeric character reference is digits a reader never sees; the page writes every character literally.
  assert.ok(!/&#\d+;|&#x[0-9a-f]+;/i.test(html.slice(html.indexOf('<body>'))), 'a numeric character reference in the body');
});

// ================================================================== page
const own = fs.readdirSync(P.dir).map((f) => path.join(P.dir, f));
check('page', 'page:closing-tags-and-module-last', () => {
  assert.ok(/<\/script>\n<\/body>\n<\/html>\n?$/.test(html), 'closing tags');
  const tail = html.slice(html.lastIndexOf('</main>'));
  assert.ok(/^<\/main>\n<script type="module" src="\/strata\/every-claim-at-full-strength\/page\.js"><\/script>\n<\/body>/.test(tail), 'the module is the last element before </body>');
});
check('page', 'page:only-inline-script-is-json-ld', () => {
  const inline = [...html.matchAll(/<script(?![^>]*\bsrc=)([^>]*)>/g)].map((m) => m[1]);
  assert.deepEqual(inline, [' type="application/ld+json"']);
});
check('page', 'page:every-module-parses', () => {
  for (const f of own.filter((x) => x.endsWith('.js'))) {
    const r = spawnSync(process.execPath, ['--check', f], { encoding: 'utf8' });
    assert.equal(r.status, 0, `${path.basename(f)}: ${r.stderr}`);
  }
  for (const f of own.filter((x) => x.endsWith('.json'))) JSON.parse(fs.readFileSync(f, 'utf8'));
});
check('page', 'page:zero-third-party-requests', () => {
  for (const f of own.filter((x) => x.endsWith('.js'))) {
    const s = fs.readFileSync(f, 'utf8');
    assert.ok(!/https?:\/\//.test(s), `${path.basename(f)} names a URL`);
    assert.ok(!/\bimport\s*\(/.test(s) && !/XMLHttpRequest|WebSocket|EventSource|sendBeacon|new Image|importScripts/.test(s), path.basename(f));
    for (const m of s.matchAll(/fetch\(([^,)]*)/g)) assert.ok(/^new URL\(/.test(m[1].trim()), `fetch of ${m[1]}`);
    for (const m of s.matchAll(/^import .* from '([^']+)'/gm)) assert.ok(m[1].startsWith('./'), m[1]);
  }
  const urls = [...html.matchAll(/(?:src|href)="([^"]+)"/g)].map((m) => m[1]);
  for (const u of urls) assert.ok(u.startsWith('/') || u.startsWith('#') || u.startsWith('https://artwaste.land/'), u);
  const sheets = [...html.matchAll(/<link rel="stylesheet" href="([^"]+)"/g)].map((m) => m[1]);
  assert.deepEqual(sheets, ['/fonts/fonts.css']);
});
check('page', 'page:accessible-wiring', () => {
  for (const id of ['load-status', 'arrange-readout', 'time-readout', 'ledger-readout', 'wall-rows', 'cross-readout', 'kills-lead', 'kills-readout']) {
    assert.ok(new RegExp(`id="${id}" role="status" aria-live="polite"`).test(html), id);
  }
  const arr = [...html.matchAll(/<label><input type="radio" name="arr" value="([a-z]+)"[^>]*\/><span>[^<]+<\/span><\/label>/g)].map((m) => m[1]);
  assert.deepEqual(arr, E.ARRANGEMENTS);
  assert.equal([...html.matchAll(/<fieldset class="seg" id="(arrange|tmode|kside)">\s*<legend>/g)].length, 3);
  assert.ok(html.includes('@media (prefers-reduced-motion: reduce)'));
  assert.ok(html.includes(':focus-visible{outline'));
  assert.ok(/\.scroll\{overflow-x:auto/.test(html), 'wide tables scroll inside their own box');
  assert.ok(/<div class="scroll" role="region" aria-labelledby="h-ledger" tabindex="0"><table class="wall" id="wall">/.test(html), 'the ledger wall sits in a scroller');
  const pageSrc = fs.readFileSync(path.join(P.dir, 'page.js'), 'utf8');
  for (const m of pageSrc.matchAll(/\$\('([a-z0-9-]+)'\)/g)) assert.ok(html.includes(`id="${m[1]}"`), `page.js writes to #${m[1]}, which is not in the page`);
  assert.ok(!/<(span|div)[^>]*onclick/i.test(html), 'a clickable span is a defect');
});
check('page', 'page:no-unmarked-em-dash-in-anything-this-page-ships', () => {
  const files = [...own, path.join(root, 'src/content/strata', `${SLUG}.md`), ...fs.readdirSync(here).map((f) => path.join(here, f))];
  for (const f of files) {
    if (fs.statSync(f).isDirectory()) continue;
    fs.readFileSync(f, 'utf8').split('\n').forEach((l, i) => { if (l.includes(EM) && !l.includes('em-dash-ok')) throw new Error(`${path.relative(root, f)}:${i + 1}`); });
  }
});
check('page', 'page:the-prebuild-runs-the-index-check', () => {
  const pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
  assert.ok(pkg.scripts.prebuild.split('&&').map((s) => s.trim()).includes('node research/every-claim-at-full-strength/build-index.mjs --check'));
});

// ================================================================== browser (on by default; --no-browser skips it)
// Every string below is built here from the raw records and the verifier's own copies of the page's words, never
// from text.js or render.js, so a drawing or wording fault in the page has to be made twice to pass.
const VERDICT_GLOSS = { VINDICATED: 'the claim held', DISSOLVED: 'a fluctuation that more data removed', ARTEFACT: 'instrument, analysis, contamination or perception', OPEN: 'not yet decided', WITHDRAWN: 'retracted, on record' };
const ARR_LABEL = { verdict: 'verdict', decided: 'what decided it', years: 'years to decision', field: 'field', grade: 'power grade', decade: 'decade of the claim' };
const FAMILY = { instrument: 'recheck', analysis: 'recheck', contamination: 'recheck', perception: 'recheck', 'more-data': 'new', 'independent-replication': 'new', theory: 'theory' };
const FAMILY_WORDS = { recheck: 'looking again at the original evidence', new: 'new evidence', theory: 'theory' };
const orWords = (xs) => words(xs).replace(/ and ([^,]*)$/, ' or $1');
const ytdNoteOf = (j) => { for (const k of ['years_to_decision_definition', 'years_to_decision_note', 'years_to_decision_convention']) if (typeof j[k] === 'string' && j[k].trim()) return j[k].trim(); return null; };

function arrangementWords(by) {
  const keyOf = {
    verdict: (j) => j.verdict.category, decided: (j) => j.decided_by, years: (j) => (j.years_to_decision === null ? 'undecided' : j.years_to_decision),
    field: (j) => fieldKey(j.field), grade: (j) => j.power.grade, decade: (j) => Math.floor(j.claim.year / 10) * 10,
  }[by];
  const groups = new Map();
  for (const r of raw) { const k = keyOf(r.j); if (!groups.has(k)) groups.set(k, []); groups.get(k).push(r); }
  let order;
  if (by === 'verdict') order = V_ORDER;
  else if (by === 'decided') order = D_ORDER.filter((k) => groups.has(k));
  else if (by === 'years') order = [...[...groups.keys()].filter((k) => k !== 'undecided').sort((a, b) => a - b), ...(groups.has('undecided') ? ['undecided'] : [])];
  else if (by === 'field') order = [...groups.keys()].sort((a, b) => (groups.get(b).length - groups.get(a).length) || a.localeCompare(b, 'en'));
  else if (by === 'grade') order = G_ORDER.filter((k) => groups.has(k));
  else order = [...groups.keys()].sort((a, b) => a - b);
  const label = (k) => ({ verdict: String(k), decided: D_LABEL[k], years: k === 'undecided' ? 'not yet decided' : pl(k, 'year', 'years'), field: String(k), grade: G_LONG[k], decade: `the ${k}s` }[by]);
  const note = (k) => (by === 'verdict' ? VERDICT_GLOSS[k] : by === 'years' && k === 0 ? 'decided in the year the claim was made' : by === 'years' && k === 'undecided' ? 'OPEN: no decision year exists' : '');
  const out = order.map((k) => ({ label: label(k), n: pl((groups.get(k) || []).length, 'claim', 'claims'), note: note(k), slugs: (groups.get(k) || []).slice().sort(byYT).map((r) => r.dir) }));
  let readout = `Arranged by ${ARR_LABEL[by]}: ${pl(N, 'claim', 'claims')} in ${pl(order.filter((k) => groups.has(k)).length, 'group', 'groups')}.`;
  if (by === 'verdict') { const empty = V_ORDER.filter((k) => !groups.has(k)); if (empty.length) readout += ` Nothing in the index is ${words(empty).replace(/ and /, ' or ')} yet.`; }
  if (by === 'decided') { const empty = D_ORDER.filter((k) => !groups.has(k)); if (empty.length) readout += ` Nothing here was decided by ${orWords(empty.map((k) => D_LABEL[k]))}.`; }
  return { groups: out, readout };
}

function layerWords() {
  const c = Object.fromEntries(V_ORDER.map((k) => [k, raw.filter((r) => r.j.verdict.category === k).length]));
  const decided = raw.filter((r) => r.j.years_to_decision !== null);
  const open = N - decided.length;
  const rows = D_ORDER.filter((d) => d !== 'not-yet').map((d) => {
    const rs = decided.filter((r) => r.j.decided_by === d).sort((a, b) => (a.j.years_to_decision - b.j.years_to_decision) || byYT(a, b));
    const v = rs.map((r) => r.j.years_to_decision);
    return { d, n: v.length, cells: [D_LABEL[d], String(v.length), `${words(v.map(String))} (${words(rs.map((r) => r.j.title))})`, v.length ? fmt1(median(v)) : ''], v };
  });
  const present = rows.filter((r) => r.n);
  const absent = rows.filter((r) => !r.n).map((r) => D_LABEL[r.d]);
  const fam = ['recheck', 'new', 'theory'].map((f) => {
    const rs = decided.filter((r) => FAMILY[r.j.decided_by] === f);
    const v = rs.map((r) => r.j.years_to_decision).sort((a, b) => a - b);
    return { f, v, deciders: D_ORDER.filter((d) => rs.some((r) => r.j.decided_by === d)) };
  }).filter((x) => x.v.length);
  let family = fam.map((x) => `Decided by ${FAMILY_WORDS[x.f]} (${orWords(x.deciders.map((d) => D_LABEL[d]))}): ${pl(x.v.length, 'claim', 'claims')}, ${x.v[0] === x.v[x.v.length - 1] ? pl(x.v[0], 'year', 'years') : `${x.v[0]} to ${x.v[x.v.length - 1]} years`}, median ${fmt1(median(x.v))}.`).join(' ');
  const a = fam.find((x) => x.f === 'recheck'), b = fam.find((x) => x.f === 'new');
  if (a && b) {
    if (a.v[a.v.length - 1] < b.v[0]) family += ' In this selection every claim settled by looking again at the original evidence was settled sooner than every claim settled by new evidence.';
    else if (a.v[0] > b.v[b.v.length - 1]) family += ' In this selection every claim settled by new evidence was settled sooner than every claim settled by looking again at the original evidence.';
    else family += ' In this selection the two ranges overlap.';
    let so = 0, sa = 0, la = 0;
    for (const x of a.v) for (const y of b.v) { if (x < y) so++; else if (x === y) sa++; else la++; }
    family += ` Pairing each claim settled by looking again with each claim settled by new evidence gives ${pl(a.v.length * b.v.length, 'pairing', 'pairings')}: in ${so} the first was settled sooner, in ${sa} in the same number of years, and in ${la} later.`;
  }
  const A = raw.filter((r) => r.j.power.grade === 'A-injection').length, B = raw.filter((r) => r.j.power.grade === 'B-published-sensitivity').length;
  const against = raw.filter((r) => ['DISSOLVED', 'ARTEFACT', 'WITHDRAWN'].includes(r.j.verdict.category));
  const aA = against.filter((r) => r.j.power.grade === 'A-injection').length, aB = against.filter((r) => r.j.power.grade === 'B-published-sensitivity').length;
  return {
    vindicated: `${c.VINDICATED} of ${N} claims were vindicated.`,
    verdicts: `Of ${pl(N, 'claim', 'claims')}, ${c.VINDICATED} vindicated, ${c.DISSOLVED} dissolved, ${pl(c.ARTEFACT, 'artefact', 'artefacts')}, ${c.OPEN} open and ${c.WITHDRAWN} withdrawn, each as of its own record’s date.`,
    open: `${pl(decided.length, 'claim has', 'claims have')} a decision year. ${pl(open, 'open claim is', 'open claims are')} left out of every figure below, because an open claim has no end to measure.`,
    yearsHead: `On one axis, 0 to ${Math.max(1, ...present.map((r) => r.v[r.v.length - 1]))} years`,
    yearsRows: present.map((r) => ({ cells: r.cells, dots: r.n })),
    absent: absent.length ? `No claim in the index was decided by ${orWords(absent)}.` : '',
    family,
    grade: `${A} of ${N} controls were rerun on real data with the claimed effect planted in at its claimed size (grade A). ${B} of ${N} could only be trusted from the control authors’ own printed sensitivity (grade B).${N - A - B ? ` ${pl(N - A - B, 'record gives', 'records give')} no grade.` : ''}`,
    against: against.length ? `Of ${pl(against.length, 'claim', 'claims')} the record settled against the claimants (dissolved, an artefact, or withdrawn), ${aA} ${aA === 1 ? 'rests' : 'rest'} on a control the page reran with the claim planted in (grade A) and ${aB} on a control trusted from its authors’ printed sensitivity (grade B).` : 'No claim in the index was settled against its claimants.',
  };
}

function wallWords() {
  const sorted = raw.slice().sort(byYT);
  const falses = [];
  const rows = sorted.map((r) => ({
    dir: r.dir, title: r.j.title,
    cells: L_KEYS.map((k) => {
      const c = r.j.ledger?.[k];
      const present = !!c && typeof c.value === 'boolean';
      if (present && !c.value) falses.push(`${L_LABEL[k]} on ${r.j.title}`);
      return { cls: !present ? 'a' : c.value ? 't' : 'f', word: !present ? 'missing' : String(c.value), id: present && typeof c.assertion === 'string' ? c.assertion : '' };
    }),
  }));
  const foot = L_KEYS.map((k) => {
    const t = raw.filter((r) => r.j.ledger?.[k]?.value === true).length, f = raw.filter((r) => r.j.ledger?.[k]?.value === false).length, a = N - t - f;
    return !f && !a ? `true on all ${t}` : `${[f ? `false on ${f}` : '', a ? `missing on ${a}` : ''].filter(Boolean).join(', ')} of ${N}`;
  });
  const notAllTrue = rows.filter((r) => r.cells.some((c) => c.cls !== 't')).length;
  return {
    rows, foot, notAllTrue,
    readout: falses.length ? `The false cells, every one: ${words(falses)}.` : 'No page records a false cell.',
    filtered: `Showing ${notAllTrue} of ${pl(N, 'page', 'pages')}: the ${notAllTrue === 1 ? 'one' : 'ones'} with a false or missing cell. Every other page records all nine cells true.`,
  };
}

function cardWords(r) {
  const j = r.j;
  return {
    slug: r.dir, title: j.title, href: `/strata/${r.dir}/`, cls: `v-${j.verdict.category}`,
    meta: `claimed ${j.claim.year} · ${j.field}`,
    headline: j.claim.headline_as_printed,
    chip: j.verdict.category,
    line: verdictLineOf(j),
    scopes: scopesOf(j).map((x) => `${SC_LABEL[x.field]}${x.text}`),
    statement: j.claim.statement,
    by: [j.claim.claimants, j.claim.citation].filter((x) => typeof x === 'string' && x).join('. '),
    pageHeadline: `The page’s own headline: ${j.headline}`,
    sources: j.verdict.sources,
    wouldChange: `What would change it: ${j.verdict.would_change}`,
    power: `Could the control have confirmed it? ${j.power.verdict}`,
    ytdNote: ytdNoteOf(j) ? `How the record counts its years: ${ytdNoteOf(j)}` : null,
  };
}

const { createRequire } = await import('node:module');
const shaOnDisk = (slug) => sha(fs.readFileSync(path.join(P.strata, slug, 'record.json')));
const hashWords = (total, matched) => (total === matched
  ? `All ${total} records match, byte for byte, the SHA-256 digest the index holds for them.`
  : `${matched} of ${total} records match the digest the index holds for them; ${pl(total - matched, 'record has', 'records have')} changed since the index was written, and the page shows ${total - matched === 1 ? 'it' : 'them'} as served.`);
function playwright() {
  try { return createRequire(path.join(root, 'package.json'))('playwright'); } catch { return null; }
}
const RULE_WORDS = {
  'verdict-vocab': 'The verdict is one of the five words.',
  'decided-vocab': 'What decided it is one of the eight words.',
  'open-iff-not-yet': 'A claim is OPEN exactly when nothing has decided it yet.',
  'open-iff-no-years': 'A claim is OPEN exactly when it gives no years to decision.',
  'two-sources': 'The verdict names at least two sources.',
  dated: 'The verdict carries a valid as-of date.',
  'decided-by-as-of': 'The decision year is not after the as-of date.',
  'grade-b-cell-false': 'A grade B page records its control-can-confirm cell as false, as the CONTRACT requires.',
  'nine-cells': 'All nine ledger cells are present, each with a true or false value and an assertion id.',
  'href-is-slug': 'The link points at the page the record sits beside.',
};

async function browserChecks(pw) {
  const http = await import('node:http');
  const TYPES = { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.json': 'application/json', '.woff2': 'font/woff2', '.svg': 'image/svg+xml', '.png': 'image/png', '.ico': 'image/x-icon' };
  const pub = path.join(root, 'public');
  const server = http.createServer((req, res) => {
    let p = decodeURIComponent(req.url.split('?')[0]); if (p.endsWith('/')) p += 'index.html';
    const f = path.join(pub, p);
    if (!f.startsWith(pub) || !fs.existsSync(f) || fs.statSync(f).isDirectory()) { res.writeHead(404); res.end(); return; }
    res.writeHead(200, { 'Content-Type': TYPES[path.extname(f)] || 'application/octet-stream' }); fs.createReadStream(f).pipe(res);
  });
  let port = 0;
  for (let tries = 0; tries < 8 && !port; tries++) {
    const p = 8200 + Math.floor(Math.random() * 690);
    port = await new Promise((resolve) => { server.once('error', () => resolve(0)); server.listen(p, '127.0.0.1', () => resolve(p)); });
  }
  if (!port) throw new Error('no free local port for the browser pass');
  const browser = await pw.chromium.launch();
  const errors = [];
  const external = [];
  const base = `http://127.0.0.1:${port}`;
  const out = [];
  const b = async (name, fn) => { try { await fn(); out.push({ group: 'browser', name, pass: true }); } catch (e) { out.push({ group: 'browser', name, pass: false, error: e.message }); } };
  try {
    const page = await browser.newPage({ viewport: { width: 1280, height: 900 }, reducedMotion: 'reduce' });
    page.on('pageerror', (e) => errors.push(e.message));
    page.on('console', (m) => { if (m.type() === 'error') errors.push(m.text()); });
    page.on('request', (r) => { if (!r.url().startsWith(`${base}/`)) external.push(r.url()); });
    await page.goto(`${base}/strata/${SLUG}/`, { waitUntil: 'networkidle' });
    await page.waitForSelector('#groups .card');
    const txt = (sel) => page.$eval(sel, (n) => n.textContent.trim());

    await b('browser:load-status-and-hashes', async () => {
      assert.equal(await txt('#load-status'), `Read the index and fetched ${N} of the ${pl(N, 'record', 'records')} it lists from this site. Everything below is drawn from those bytes.`);
      assert.equal(await txt('#check-hash'), hashWords(index.claims.length, index.claims.filter((c) => shaOnDisk(c.slug) === c.sha256).length));
      assert.equal(await page.$eval('#fallback-claims', (n) => n.hidden), true);
    });

    await b('browser:every-card-against-its-record', async () => {
      const got = await page.$$eval('#groups .card', (cards) => cards.map((c) => ({
        slug: c.dataset.slug, cls: c.className, title: c.querySelector('h4').textContent, href: c.querySelector('h4 a')?.getAttribute('href') ?? null,
        meta: c.querySelector('.meta').textContent,
        lbl: c.querySelector('.hl .lbl').textContent, headline: [...c.querySelector('.hl').childNodes].slice(1).map((x) => x.textContent).join(''),
        chip: c.querySelector('.vd .chip').textContent, chipCls: c.querySelector('.vd .chip').className,
        line: [...c.querySelector('.vd').childNodes].slice(1).map((x) => x.textContent).join(''),
        scopes: [...c.querySelectorAll(':scope > p.scope')].map((p) => p.textContent),
        statement: c.querySelector('details blockquote')?.textContent ?? null,
        by: c.querySelector('details p.small')?.textContent ?? null,
        paras: [...c.querySelectorAll('details > p')].map((p) => p.textContent),
        sources: [...c.querySelectorAll('details ol li')].map((li) => li.textContent),
      })));
      assert.equal(got.length, N);
      for (const g of got) {
        const r = raw.find((x) => x.dir === g.slug);
        assert.ok(r, `a card for ${g.slug}, which is not a record`);
        const w = cardWords(r);
        assert.equal(g.title, w.title, g.slug); assert.equal(g.href, w.href, g.slug);
        assert.ok(g.cls.split(' ').includes(w.cls) && g.chipCls.split(' ').includes(w.cls), `${g.slug}: verdict colour`);
        assert.equal(g.meta, w.meta, g.slug);
        assert.equal(g.lbl, 'headline, as printed'); assert.equal(g.headline, w.headline, g.slug);
        assert.equal(g.chip, w.chip, g.slug);
        assert.equal(g.line, w.line, g.slug);
        assert.deepEqual(g.scopes, w.scopes, `${g.slug}: the verdict's own bounds`);
        assert.equal(g.statement, w.statement, g.slug);
        assert.equal(g.by, w.by || null, g.slug);
        assert.deepEqual(g.sources, w.sources, g.slug);
        for (const p of [w.pageHeadline, w.wouldChange, w.power, ...(w.ytdNote ? [w.ytdNote] : [])]) assert.ok(g.paras.includes(p), `${g.slug}: ${p.slice(0, 50)}`);
        assert.ok(!/decided by not yet decided/.test(g.line), `${g.slug}: decided by not yet decided`);
      }
    });

    await b('browser:every-arrangement-by-keyboard-group-by-group', async () => {
      await page.focus('#arrange input[value="verdict"]');
      for (const by of E.ARRANGEMENTS) {
        if (by !== 'verdict') await page.keyboard.press('ArrowRight');
        assert.equal(await page.$eval('#arrange input:checked', (n) => n.value), by);
        const w = arrangementWords(by);
        assert.equal(await txt('#arrange-readout'), w.readout, by);
        const got = await page.$$eval('#groups section.group', (secs) => secs.map((s) => ({
          label: s.querySelector('h3').textContent, n: s.querySelector('.n').textContent, note: s.querySelector('.gl')?.textContent ?? '',
          slugs: [...s.querySelectorAll('.card')].map((c) => c.dataset.slug),
        })));
        assert.deepEqual(got, w.groups, by);
      }
    });

    await b('browser:the-timeline-row-by-row-and-bar-by-bar', async () => {
      for (const mode of ['calendar', 'aligned']) {
        await page.check(`#tmode input[value="${mode}"]`);
        const want = timelineExpect(mode);
        const got = await page.$$eval('#time-chart li.tl-row', (lis) => lis.map((li) => {
          const bar = li.querySelector('.tl-bar');
          const st = bar.getAttribute('style');
          return { title: li.querySelector('.tl-name a').textContent, href: li.querySelector('.tl-name a').getAttribute('href'), words: li.querySelector('.tl-name .d').textContent,
            open: bar.classList.contains('open'), zero: bar.classList.contains('zero'), left: parseFloat(/left:([-\d.]+)%/.exec(st)[1]), width: parseFloat(/width:([-\d.]+)%/.exec(st)[1]) };
        }));
        assert.equal(got.length, want.length, mode);
        want.forEach((w, i) => {
          const g = got[i];
          assert.equal(g.title, w.title, `${mode} row ${i}`); assert.equal(g.href, `/strata/${w.dir}/`);
          assert.equal(g.words, w.words, `${mode}: ${w.dir}`);
          assert.equal(g.open, w.open, `${mode}: ${w.dir} open`); assert.equal(g.zero, w.zero, `${mode}: ${w.dir} zero`);
          assert.ok(Math.abs(g.left - w.left * 100) < 0.001, `${mode}: ${w.dir} starts at ${g.left}%, not ${(w.left * 100).toFixed(3)}%`);
          assert.ok(Math.abs(g.width - w.width * 100) < 0.001, `${mode}: ${w.dir} is ${g.width}% wide, not ${(w.width * 100).toFixed(3)}%`);
        });
        const o = want.filter((w) => w.open).length, d = want.length - o;
        assert.equal(await txt('#time-readout'), mode === 'calendar'
          ? `${pl(want.length, 'claim', 'claims')} on the calendar: ${d} decided, ${o} still open and running to ${o === 1 ? 'its' : 'their'} as-of ${o === 1 ? 'date' : 'dates'}.`
          : `${pl(want.length, 'claim', 'claims')}, every bar starting at its claim: ${d} decided, shortest first, then ${o} open.`);
      }
      assert.equal(await txt('#time-refused'), 'Every record in the index could be placed on the timeline; none was refused.');
    });

    await b('browser:the-ledger-wall-cell-by-cell-and-both-filters', async () => {
      const w = wallWords();
      const got = await page.$$eval('#wall tbody tr', (trs) => trs.map((tr) => ({ dir: tr.dataset.slug, title: tr.querySelector('th').textContent,
        cells: [...tr.querySelectorAll('td')].map((td) => ({ cls: td.className, word: td.querySelector('.v').textContent, id: td.querySelector('code')?.textContent ?? '' })) })));
      assert.deepEqual(got, w.rows);
      assert.deepEqual(await page.$$eval('#wall thead th', (ns) => ns.map((n) => n.textContent)), ['Page', ...L_KEYS.map((k) => L_LABEL[k])]);
      assert.deepEqual(await page.$$eval('#wall tfoot td', (ns) => ns.map((n) => n.textContent)), w.foot);
      assert.equal(await txt('#ledger-readout'), w.readout);
      const visible = (sel) => page.$$eval(sel, (ns) => ns.filter((n) => getComputedStyle(n).display !== 'none' && n.getClientRects().length).length);
      const cellsWith = (cls) => w.rows.reduce((s, r) => s + r.cells.filter((c) => c.cls === cls && c.id).length, 0);
      assert.equal(await visible('#wall td.t code'), cellsWith('t'));
      await page.check('#only-false');
      assert.equal(await visible('#wall td.t code'), 0, 'ids on true cells still shown');
      assert.equal(await visible('#wall td.f code'), cellsWith('f'), 'ids on false cells hidden');
      await page.uncheck('#only-false');
      assert.equal(await visible('#wall td.t code'), cellsWith('t'));
      assert.equal(await visible('#wall tbody tr'), N);
      assert.equal(await txt('#wall-rows'), '');
      await page.check('#only-false-rows');
      assert.equal(await visible('#wall tbody tr'), w.notAllTrue, 'the row filter');
      assert.deepEqual(await page.$$eval('#wall tbody tr', (trs) => trs.filter((t) => getComputedStyle(t).display !== 'none').map((t) => t.dataset.slug)), w.rows.filter((r) => r.cells.some((c) => c.cls !== 't')).map((r) => r.dir));
      assert.equal(await txt('#wall-rows'), w.filtered);
      await page.uncheck('#only-false-rows');
      assert.equal(await visible('#wall tbody tr'), N);
    });

    await b('browser:the-second-layer-in-the-verifier-s-own-words', async () => {
      const w = layerWords();
      assert.equal(await txt('#sl-vindicated'), w.vindicated);
      assert.equal(await txt('#sl-verdict-text'), w.verdicts);
      assert.equal(await txt('#sl-years-open'), w.open);
      assert.equal(await txt('#sl-family'), w.family);
      assert.equal(await txt('#sl-grade-text'), w.grade);
      assert.equal(await txt('#sl-against-text'), w.against);
      assert.equal(await txt('#sl-years-absent'), w.absent);
      assert.equal(await page.$eval('#sl-years-table thead th:last-child', (n) => n.textContent), w.yearsHead);
      const rows = await page.$$eval('#sl-years-table tbody tr', (trs) => trs.map((tr) => ({ cells: [tr.querySelector('th').textContent, ...[...tr.querySelectorAll('td')].slice(0, 3).map((td) => td.textContent)], dots: tr.querySelectorAll('.strip i').length })));
      assert.deepEqual(rows, w.yearsRows);
      const rules = await page.$$eval('#rules-table tbody tr', (trs) => trs.map((tr) => [...tr.querySelectorAll('td')].map((td) => td.textContent)));
      const byId = Object.fromEntries(L2.rules.map((r) => [r.id, r]));
      assert.equal(rules.length, 10);
      rules.forEach((cells, i) => {
        const rc = L2.rules[i];
        assert.equal(cells[0], RULE_WORDS[rc.id], rc.id);
        assert.equal(cells[1], byId[rc.id].applicable ? `holds for ${byId[rc.id].holding} of ${byId[rc.id].applicable}` : 'applies to none', rc.id);
        assert.equal(cells[2], rc.failing.length ? words(rc.failing) : 'nowhere', rc.id);
      });
    });

    await b('browser:cross-every-ordered-pair-and-a-named-cell-in-each', async () => {
      let n = 0;
      for (const rd of Object.keys(DIMS)) for (const cd of Object.keys(DIMS)) {
        if (rd === cd) continue;
        await page.selectOption('#cross-rows', rd);
        await page.selectOption('#cross-cols', cd);
        assert.deepEqual([await page.$eval('#cross-rows', (s) => s.value), await page.$eval('#cross-cols', (s) => s.value)], [rd, cd]);
        const ct = crossOf(raw, rd, cd);
        const got = await page.$eval('#cross-table', (t) => ({
          caption: t.querySelector('caption').textContent, corner: t.querySelector('thead th').textContent,
          head: [...t.querySelectorAll('thead th')].slice(1).map((th) => th.textContent),
          rows: [...t.querySelectorAll('tbody tr')].map((tr) => [tr.querySelector('th').textContent, ...[...tr.querySelectorAll('td')].map((td) => td.textContent)]),
          foot: [...t.querySelectorAll('tfoot td')].map((td) => td.textContent),
        }));
        assert.equal(got.caption, `${DIM_LABEL[rd]} (rows) against ${DIM_LABEL[cd]} (columns), ${pl(N, 'claim', 'claims')}`);
        assert.equal(got.corner, `${DIM_LABEL[rd]} down, ${DIM_LABEL[cd]} across`);
        assert.deepEqual(got.head, [...ct.cols.map(DIMS[cd].label), 'all'], `${rd} x ${cd}`);
        assert.deepEqual(got.rows, ct.rows.map((rk, i) => [DIMS[rd].label(rk), ...ct.counts[i].map(String), String(ct.counts[i].reduce((x, y) => x + y, 0))]), `${rd} x ${cd}`);
        assert.deepEqual(got.foot, [...ct.cols.map((_, j) => String(ct.counts.reduce((x, row) => x + row[j], 0))), String(N)], `${rd} x ${cd}`);
        assert.equal(await txt('#cross-readout'), crossWords(raw, rd, cd, null));
        const i = ct.counts.findIndex((row) => row.some((x) => x > 0));
        const j = ct.counts[i].findIndex((x) => x > 0);
        await page.click(`#cross-table tbody tr:nth-child(${i + 1}) td:nth-of-type(${j + 1}) button`);
        assert.equal(await txt('#cross-readout'), crossWords(raw, rd, cd, [i, j]), `${rd} x ${cd}: the named cell`);
        n++;
      }
      assert.equal(n, 30);
    });

    await b('browser:kills-lead-tally-and-filter', async () => {
      assert.equal(await txt('#kills-lead'), `${killsLeadWords()} ${sideWords()}`);
      const rounds = [...new Set(kills.decisions.map((d) => d.round))];
      const tally = await page.$$eval('#kills-tally tbody tr', (trs) => trs.map((tr) => [tr.querySelector('th').textContent, ...[...tr.querySelectorAll('td')].map((td) => td.textContent)]));
      assert.deepEqual(tally, rounds.map((r) => { const ds = kills.decisions.filter((d) => d.round === r); return [ROUND_WORDS[r], ...['claim', 'control', 'both'].map((s) => String(ds.filter((d) => d.side === s).length)), String(ds.length)]; }));
      for (const side of ['claim', 'control', 'both', 'all']) {
        await page.check(`#kside input[value="${side}"]`);
        const shown = side === 'all' ? kills.decisions.length : kills.decisions.filter((d) => d.side === side).length;
        assert.equal(await txt('#kills-readout'), side === 'all' ? `Showing all ${kills.decisions.length} kill decisions.` : `Showing ${shown} of ${kills.decisions.length} kill decisions: those that fell on ${SIDE_WORDS[side]}.`);
        assert.deepEqual(await page.$$eval('#fallback-kills li:not([hidden])', (ns) => ns.map((n) => n.dataset.candidate)), kills.decisions.filter((d) => side === 'all' || d.side === side).map((d) => d.candidate));
      }
    });

    await b('browser:no-errors-no-third-party-no-overflow', async () => {
      assert.deepEqual(errors, []);
      assert.deepEqual(external, []);
      await page.check('#only-false-rows');
      for (const wdt of [390, 768]) {
        await page.setViewportSize({ width: wdt, height: 900 });
        await page.waitForTimeout(150);
        const over = await page.evaluate(() => document.documentElement.scrollWidth - window.innerWidth);
        assert.ok(over <= 1, `${wdt}px overflows by ${over}`);
      }
    });

    // The planted fault for the hash comparison: one record served with a changed byte and one not served at all,
    // through the page's own unmodified fetch and hash code.
    await b('browser:a-changed-record-and-a-missing-record-are-reported-as-such', async () => {
      const p2 = await browser.newPage({ viewport: { width: 1280, height: 900 } });
      const [changed, missing] = [index.claims[0].slug, index.claims[1].slug];
      await p2.route(`**/strata/${changed}/record.json`, async (route) => { const bytes = fs.readFileSync(path.join(P.strata, changed, 'record.json')); await route.fulfill({ status: 200, contentType: 'application/json', body: Buffer.concat([bytes, Buffer.from('\n')]) }); });
      await p2.route(`**/strata/${missing}/record.json`, (route) => route.fulfill({ status: 404, body: '' }));
      await p2.goto(`${base}/strata/${SLUG}/`, { waitUntil: 'networkidle' });
      await p2.waitForSelector('#groups .card');
      const t2 = (sel) => p2.$eval(sel, (n) => n.textContent.trim());
      const served = index.claims.filter((c) => c.slug !== missing);
      const matching = served.filter((c) => c.slug !== changed && shaOnDisk(c.slug) === c.sha256).length;
      assert.equal(await t2('#check-hash'), hashWords(served.length, matching));
      assert.ok(matching < served.length, 'the planted change must leave at least one record unmatched');
      assert.equal(await t2('#load-status'), `Read the index and fetched ${N - 1} of the ${pl(N, 'record', 'records')} it lists from this site. Everything below is drawn from those bytes. 1 record could not be read: ${missing}: answered 404.`);
      assert.equal(await p2.$$eval('#groups .card', (ns) => ns.length), N - 1);
      await p2.close();
    });
  } finally {
    await browser.close();
    server.close();
  }
  return out;
}
const notes = [];
if (BROWSER) {
  const pw = playwright();
  if (!pw) notes.push('browser pass not run: Playwright is not installed here');
  else {
    try { results.push(...await browserChecks(pw)); } catch (e) { results.push({ group: 'browser', name: 'browser:could-run', pass: false, error: e.message }); }
  }
} else notes.push('browser pass skipped (--no-browser)');

// ================================================================== report
const failed = results.filter((r) => !r.pass);
for (const r of results) console.log(`${r.pass ? 'ok  ' : 'FAIL'} ${r.name}${r.pass ? '' : `\n      ${r.error}`}`);
console.log(`\n${results.length - failed.length}/${results.length} assertions pass over ${N} records and ${kills.decisions.length} kill decisions${results.some((r) => r.group === 'browser') ? ', browser included' : ''}.${notes.length ? ` Note: ${notes.join('; ')}.` : ''}`);
process.exit(failed.length ? 1 : 0);
