#!/usr/bin/env node
// verify-every-prediction-we-wrote-down-first.mjs
//
//   node research/every-prediction-we-wrote-down-first/verify-every-prediction-we-wrote-down-first.mjs
//
// Exit 0 on pass. Runs entirely offline, reads the shipped page under `public/` and never a
// build output, and takes no dependency beyond the repository and the shared kit the page
// itself loads.
//
// WHAT IT IS FOR. The page it checks is a scoreboard whose subject is this project, which is
// the arrangement with the worst incentives in the whole corpus: the archive holds the
// predictions, the archive picks which ones count, and the archive writes the rate. So the
// checks below are built so that the flattering direction is the one that fails first.
//
//   1. THE PARSE IS RE-RUN against the nine live source pages, and the blob inlined in the
//      shipped page must equal it byte for byte. Edit any source ledger and this goes red.
//   2. EVERY QUOTATION is re-matched against the file it is attributed to.
//   3. THE TWO PUBLISHED ANCHORS are re-derived: the 90 OEIS absence rows from their raw hit
//      lists, and the 32 self-correction episodes from two committed files that have to agree.
//   4. THE CHANCE CONTROL is run for 40,000 rounds against node's CSPRNG through the same
//      shared kit the page uses, which is enough rounds for a 2-point edge to show.
//   5. FIVE NEGATIVE CONTROLS deliberately break something and require the check to notice.
//   6. THE POOLED RATE IS FORBIDDEN: the hand-written rate and the machine-scored rate must
//      never appear combined, and the number that would result is searched for and must be
//      absent.
//   7. THE STUDY THAT IS STILL OPEN is not read. Nothing this page ships may reference the
//      placard arm's outcome data, and that is asserted over every shipped file.

import { readFileSync, readdirSync, existsSync, statSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { createHash, webcrypto } from 'node:crypto';
import vm from 'node:vm';
import {
  ROOT, HERE, SELF, build, sweepStrata, extractLedger, classify, RULES, SCORED,
  plainText, mdText, normalisedFile, QUOTES, asciiJSON, sealedPrediction,
} from './extract.mjs';

let pass = 0;
const failures = [];
function ok(cond, what, detail) {
  if (cond) { pass++; return true; }
  failures.push(what + (detail ? '  [' + detail + ']' : ''));
  return false;
}
function eq(a, b, what) { return ok(a === b, what, `got ${JSON.stringify(a)}, expected ${JSON.stringify(b)}`); }

const PAGE = join(ROOT, 'public', 'strata', SELF, 'index.html');
const html = readFileSync(PAGE, 'utf8');
const md = readFileSync(join(ROOT, 'src', 'content', 'strata', SELF + '.md'), 'utf8');

// ---------------------------------------------------------------- load the shared kit
// The kit has no Node fallback on purpose: it uses the same WebCrypto a browser gives it.
// Loading it into a vm sandbox with node's webcrypto injected is how its own tests run it,
// so the code exercised here is the code a reader runs.
const kitSrc = readFileSync(join(ROOT, 'public', '_kit', 'precommit.js'), 'utf8');
const sandbox = { crypto: webcrypto, TextEncoder, TextDecoder, Uint8Array, Math, JSON, Error, RangeError, String, Object, Array, Number, Promise, console };
sandbox.globalThis = sandbox;
vm.createContext(sandbox);
vm.runInContext(kitSrc, sandbox);
const K = sandbox.AW.precommit;
ok(typeof K.ci === 'function' && typeof K.chanceControl === 'function', 'the shared kit loads and exposes ci/chanceControl');

// ================================================================ 1 · the parse
const fresh = build(ROOT);
const inlined = (() => {
  const open = '<script id="ledger-data" type="application/json">';
  const i = html.indexOf(open);
  ok(i > 0, 'the page carries its inlined dataset');
  const j = html.indexOf('</scr' + 'ipt>', i);
  return JSON.parse(html.slice(i + open.length, j));
})();

eq(asciiJSON(inlined), asciiJSON(fresh),
   'the blob inlined in the shipped page equals a fresh parse of the nine source pages');

const items = fresh.pages.flatMap((p) => p.items);
const scored = items.filter((i) => SCORED.includes(i.verdict));
const died = scored.filter((i) => i.verdict === 'DIED');
const heldStrict = scored.filter((i) => i.verdict === 'HELD');
const survived = scored.filter((i) => i.verdict !== 'DIED');
const unscored = items.filter((i) => !SCORED.includes(i.verdict));

eq(fresh.pages.length, 9, 'nine pages carry an itemised prediction ledger');
eq(items.length, 51, 'fifty-one ledger entries are parsed');
eq(scored.length, 48, 'forty-eight of them are scorable predictions');
eq(died.length, 22, 'twenty-two died outright');
eq(heldStrict.length, 19, 'nineteen held without qualification');
eq(survived.length, 26, 'twenty-six survived in some form');
eq(unscored.length, 3, 'three entries are not scorable');
eq(scored.length + unscored.length, items.length, 'nothing is dropped between the ledger and the rates');
eq(died.length + survived.length, scored.length, 'the two scorings partition the scored set');
ok(items.every((i) => i.slug !== SELF), 'the survey does not count itself among the surveyed');

// Every page's item count, individually, so a change to one ledger names itself.
const PER_PAGE = {
  'how-far-away-the-internet-is': 5, 'how-many-cores-do-you-have': 7,
  'ten-millionths-of-a-second': 6, 'the-battery-that-cant-tell': 5,
  'the-clock-in-the-glass': 5, 'the-exponent-between-number-and-light': 6,
  'the-rounding-you-were-allowed': 5, 'the-shape-of-the-silicon': 7,
  'where-a-word-breaks': 5,
};
for (const [slug, n] of Object.entries(PER_PAGE)) {
  const p = fresh.pages.find((x) => x.slug === slug);
  ok(p && p.items.length === n, `${slug} still carries ${n} ledger items`, p ? String(p.items.length) : 'missing');
}
eq(Object.values(PER_PAGE).reduce((a, b) => a + b, 0), items.length, 'the per-page counts add up to the total');

// The one page that states its predictions in prose rather than a list.
const prose = fresh.pages.find((p) => p.slug === 'where-a-word-breaks');
ok(prose.items.every((i) => i.form === 'prose'), 'where-a-word-breaks is parsed in prose form');
ok(fresh.pages.filter((p) => p.items.every((i) => i.form === 'list')).length === 8,
   'the other eight are parsed in list form');

// The single unclassified item, named rather than hidden.
const unclassified = items.filter((i) => i.verdict === 'UNCLASSIFIED');
eq(unclassified.length, 1, 'exactly one entry has no verdict word the rules can read');
eq(unclassified[0].slug + '/' + unclassified[0].label, 'where-a-word-breaks/P2',
   'the unclassified entry is the one that reports a number instead of a verdict');

// The one re-scored item.
const rescored = items.find((i) => i.slug === 'the-shape-of-the-silicon' && i.label === 'P1');
ok(rescored && rescored.rule === 'R2' && rescored.verdict === 'SPLIT',
   'the re-scored prediction is read by the rule written for it');

// ================================================================ 2 · the rates
const ciDeath = K.ci(died.length, scored.length);
const pDeath = K.test(died.length, scored.length, 0.5);
ok(Math.abs(died.length / scored.length - 0.4583) < 0.001, 'the death rate is 45.8 per cent');
ok(ciDeath.lo > 0.313 && ciDeath.lo < 0.315 && ciDeath.hi > 0.607 && ciDeath.hi < 0.609,
   'the exact interval on the death rate is 31.4 to 60.8 per cent',
   `${(100 * ciDeath.lo).toFixed(1)}-${(100 * ciDeath.hi).toFixed(1)}`);
ok(pDeath > 0.05, 'the death rate is not distinguishable from a coin at the 5 per cent level', String(pDeath));
ok(ciDeath.lo < 0.5 && ciDeath.hi > 0.5, 'the interval on the death rate contains a coin');

// The denominator, fixed against a corpus that grows nightly.
eq(fresh.corpus.total, 765, 'the denominator is 765 strata dated before 2026-08-13');
eq(fresh.corpus.drafts, 1, 'one of those 765 is a draft');
eq(fresh.habit.union.length, 12, 'twelve strata of 765 ever wrote a prediction down first');
eq(fresh.habit.ledgerPages.length, 9, 'nine of the twelve carry an itemised on-page ledger');
eq(fresh.habit.union.filter((s) => !fresh.habit.ledgerPages.includes(s)).length, 3,
   'three more froze a dated pre-registration file instead');
eq(fresh.prereg.length, 6, 'six pre-registration files exist in the repository');
eq(fresh.habit.openStudies.length, 1, 'exactly one pre-registration has no page yet');
eq(fresh.habit.openStudies[0], 'research/plain-placard-arm/PREREGISTRATION.md',
   'the one with no page is the placard arm');

// The three properties the page counts in section 09, each read off the files rather than
// asserted about them.
eq(fresh.prereg.filter((p) => p.falsifiedClause).length, 2,
   'two of the six frozen files write an explicit falsification clause');
eq(fresh.prereg.filter((p) => p.readoutDate).length, 1,
   'one of the six fixes a date in advance for its readout');
eq(fresh.prereg.find((p) => p.readoutDate).readoutDate, '2026-09-12',
   'and that date is the placard arm\'s');
eq(fresh.pages.filter((p) => p.revisitDate).length, 0,
   'none of the nine on-page ledgers carries a revisit date');
ok(html.includes("id=\"p-falsif\"") && html.includes("id=\"p-readout\"") && html.includes("id=\"p-revisit\""),
   'the page renders those three counts rather than stating them in prose');

// ================================================================ 3 · the anchors
// Anchor A: the OEIS block, re-derived from the raw hit lists rather than the stored verdict.
{
  const q = fresh.oeis.queries;
  let absent = 0, hits = 0, mismatch = 0, tailOnly = 0;
  for (const r of q) {
    const derived = r.head === 0 && r.tail === 0;
    derived ? absent++ : hits++;
    if (derived !== r.published) mismatch++;
    if (r.head === 0 && r.tail > 0) tailOnly++;
  }
  eq(q.length, 90, 'the OEIS block carries all 90 queries');
  eq(absent, 70, 're-deriving absence from the raw hit lists gives 70 absent');
  eq(hits, 20, 're-deriving gives 20 hits');
  eq(mismatch, 0, 'every re-derived verdict matches the one stored beside it');
  eq(tailOnly, 5, 'five rows are the flagged kind where only the large terms hit');
  eq(fresh.oeis.publishedSummary.absent, 70, 'the published summary says 70 absent');
  eq(fresh.oeis.publishedSummary.hits, 20, 'the published summary says 20 hits');
  eq(fresh.oeis.publishedSummary.total, 90, 'the published summary says 90 total');
  eq(fresh.oeis.controls.bothHeld, true, 'the OEIS sweep\'s positive and negative controls both held');
  ok(fresh.oeis.controls.positiveHits > 0, 'the positive control returned matches');
  eq(fresh.oeis.controls.negativeHits, 0, 'the negative control returned nothing');
}

// Anchor B: the self-corrections, recounted from two committed files that must agree.
{
  const c = fresh.corrections;
  const cat = {}, catch_ = {};
  let maxLat = 0;
  for (const e of c.events) {
    cat[e.category] = (cat[e.category] || 0) + 1;
    catch_[e.catch_type] = (catch_[e.catch_type] || 0) + 1;
    if (typeof e.latency_days === 'number' && e.latency_days > maxLat) maxLat = e.latency_days;
  }
  eq(c.events.length, c.published.total_episodes, 'the 32 episodes recount to the published total');
  eq(c.idsMatch, true, 'the curated file and the derived file carry the same episode ids');
  eq(JSON.stringify(cat), JSON.stringify(c.published.by_category),
     'the category split recounts from the curated inclusion file');
  eq(JSON.stringify(catch_), JSON.stringify(c.published.by_catch_type),
     'the cross-versus-self split recounts from the derived rows');
  eq(maxLat, c.published.max_days, 'the worst latency recounts to the published 34 days');
  eq(c.published.total_commits, 2017, 'the published corpus is 2,017 commits');
  eq(c.published.distinct_sessions, 352, 'over 352 sessions');
  eq(c.published.span_days, 37, 'in 37 days');
}

// ================================================================ 4 · the chance control
// The very object the page plays the reader with, warmed exactly as the page warms it, then
// handed a CSPRNG instead of the ledger. 40,000 rounds: at that n the interval is about a
// point wide, so a house with the ledger's 4-point edge leaking into it would be caught.
function makeHouse() {
  let s = 0, d = 0;
  return {
    predict() { return d > s ? 'DIED' : 'SURVIVED'; },
    observe(a) { if (a === 'DIED') d++; else s++; },
    state() { return { survived: s, died: d }; },
  };
}
{
  const warm = makeHouse();
  for (const it of scored) warm.observe(it.verdict === 'DIED' ? 'DIED' : 'SURVIVED');
  eq(warm.state().survived, 26, 'the house warms to 26 survived');
  eq(warm.state().died, 22, 'the house warms to 22 died');

  const res = K.chanceControl(warm, 40000, ['SURVIVED', 'DIED']);
  eq(res.n, 40000, 'the chance control ran 40,000 rounds');
  ok(res.atChance === true, 'the same unmodified house falls to chance against a CSPRNG',
     `${res.hits}/${res.n}, CI ${(100 * res.ci.lo).toFixed(2)}-${(100 * res.ci.hi).toFixed(2)}`);
  ok(res.ci.hi - res.ci.lo < 0.012,
     'the control has enough rounds for its interval to be narrower than the edge it is testing for',
     String(res.ci.hi - res.ci.lo));

  // And the same house against the real thing, where the edge is real and small.
  const real = K.ledger({ baseline: 0.5 });
  const replay = makeHouse();
  for (const it of scored) {
    const truth = it.verdict === 'DIED' ? 'DIED' : 'SURVIVED';
    real.record(replay.predict(), truth);
    replay.observe(truth);
  }
  ok(real.hits >= 24 && real.hits <= 28, 'against the real ledger the house lands near the base rate', String(real.hits));
  ok(real.p() > 0.05, 'and even that edge is not distinguishable from chance at n = 48', String(real.p()));
}

// ================================================================ 5 · negative controls
// A check nobody has watched fail is a check nobody has tested.
{
  // (a) inject a fabricated item and require the parser to see it
  const src = readFileSync(join(ROOT, 'public', 'strata', 'the-clock-in-the-glass', 'index.html'), 'utf8');
  const before = extractLedger(src).items.length;
  // Inject into the LEDGER's own list. Replacing the first </ul> in the file would land in an
  // unrelated list further up the page, and the control would then pass while proving nothing
  // (the parser would return the same count, which is exactly what a broken parser does).
  const at = src.indexOf('Predictions, and how they did');
  const closeUl = src.indexOf('</ul>', at);
  const inject = (li) => src.slice(0, closeUl) + li + src.slice(closeUl);
  const withDied = extractLedger(inject('<li><strong>P9 died, and it is fabricated.</strong> Injected by the verifier.</li>'));
  eq(withDied.items.length, before + 1, 'NEGATIVE CONTROL: an injected item changes the count');
  eq(withDied.items[withDied.items.length - 1].phrase, 'P9 died, and it is fabricated.',
     'NEGATIVE CONTROL: the injected item is the one that was read');
  eq(classify(withDied.items[withDied.items.length - 1].phrase).verdict, 'DIED',
     'NEGATIVE CONTROL: the injected death is classified as one');

  // (b) an unknown verdict word must NOT be given a verdict
  const withWeird = extractLedger(inject('<li><strong>P9 evaporated, mysteriously.</strong> Injected by the verifier.</li>'));
  eq(classify(withWeird.items[withWeird.items.length - 1].phrase).verdict, 'UNCLASSIFIED',
     'NEGATIVE CONTROL: an unreadable verdict lands in UNCLASSIFIED rather than defaulting to a verdict');
  ok(RULES.every((r) => classify('P9 evaporated, mysteriously.').rule !== r.id),
     'NEGATIVE CONTROL: no rule claims the unreadable phrase');

  // (c) removing the ledger heading must make the page invisible to the sweep
  eq(extractLedger(src.replace('Predictions, and how they did', 'Some notes')), null,
     'NEGATIVE CONTROL: a page without the heading is not counted as carrying a ledger');

  // (d) a quotation corrupted by one character must fail
  const q = QUOTES[0];
  const body = normalisedFile(ROOT, q.file);
  ok(body.includes(q.text), 'the first quotation matches its source');
  ok(!body.includes(q.text.replace('wrong', 'wromg')),
     'NEGATIVE CONTROL: a one-character corruption of that quotation does not match');

  // (e) flipping one OEIS row must move the re-derived total
  const flipped = fresh.oeis.queries.map((r, i) => (i === 0 ? { ...r, head: 1 } : r));
  eq(flipped.filter((r) => r.head === 0 && r.tail === 0).length, 69,
     'NEGATIVE CONTROL: flipping one OEIS row moves the re-derived absence count');

  // (f) the page's own figure assertions must be able to fail
  const mutated = html.replace('<span class="mono" id="hero-died">22</span>', '<span class="mono" id="hero-died">7</span>');
  ok(!mutated.includes('id="hero-died">' + died.length + '<'),
     'NEGATIVE CONTROL: the rendered-figure assertion fails on a page with the wrong figure');
}

// ================================================================ 6 · the quotations
{
  const checked = fresh.quotes;
  eq(checked.length, 17, 'seventeen quotations are checked');
  const bad = checked.filter((q) => !q.found);
  ok(bad.length === 0, 'every quotation appears in the file it is attributed to', bad.map((q) => q.id).join(', '));
  // and every one of them is actually printed on the page
  const pageText = plainText(html.replace(/<script id="ledger-data"[\s\S]*?<\/script>/, ' '));
  const printed = checked.filter((q) => pageText.includes(q.text));
  ok(printed.length >= 8, 'at least eight of the checked quotations are printed on the page', String(printed.length));
  for (const q of ['Q1', 'Q2', 'Q3', 'Q4', 'Q9', 'Q12', 'Q13', 'Q16']) {
    const item = checked.find((x) => x.id === q);
    ok(pageText.includes(item.text), `${q} is printed on the page verbatim`);
  }
}

// ================================================================ 7 · rendered figures
// String matches against the shipped HTML, not only against computed values.
{
  const must = [
    ['id="hero-died">' + died.length + '<', 'the hero prints the death count'],
    ['id="inline-corpus">' + fresh.corpus.total + '<', 'the corpus size is in the page source'],
    ['Between them, 48 scorable predictions: 22 died', 'the meta description states the counts'],
    ['Twelve pages out of 765', 'the meta description states the denominator'],
    ['22 of the 48 predictions', 'the OG description states the counts'],
    ['48 predictions written before the answer existed. 22 died.', 'the Twitter description states the counts'],
    ['22 of 48 died', 'the JSON-LD description states the counts'],
    [fresh.sealed.hash, 'the sealed digest is printed in the page'],
    [fresh.placard.statedDigest, 'the placard assignment digest is printed in the page'],
    ['2026-09-12', 'the readout date is printed in the page'],
    ['id="the-way-out"', 'the page tells the reader how to beat it'],
    ['chanceControl(', 'the page runs the shared chance control'],
    ['revealText(', 'the page reveals through revealText'],
    ['shellCommand(', 'the page offers the shell escape hatch'],
    ['/_kit/precommit.js', 'the page loads the shared kit'],
  ];
  // The slate-level gate's own structural requirements, asserted here too, so this layer does
  // not depend on being remembered in somebody else's registry.
  const SLATE = [
    [/(^|[^\w.])seal\s*\(/m, 'seals a prediction through the kit'],
    [/(^|[^\w.])(ci|ledger)\s*\(/m, 'reaches for the exact interval rather than a bare rate'],
    [/chanceControl\s*\(/, 'runs the unmodified predictor against a CSPRNG'],
    [/revealText\b/, 'reveals through revealText'],
    [/shellCommand\s*\(/, 'offers the shell escape hatch'],
    [/id="the-way-out"/, 'tells the reader how to beat it'],
  ];
  for (const [re, what] of SLATE) ok(re.test(html), `slate requirement: ${what}`);
  for (const [needle, what] of must) ok(html.includes(needle), what, needle.slice(0, 48));

  // the numbers in the meta description have to be the computed ones
  ok(html.includes(`Between them, ${scored.length} scorable predictions: ${died.length} died`),
     'the meta description numbers are the computed ones');
  ok(html.includes(`${died.length} of the ${scored.length} predictions`),
     'the OG description numbers are the computed ones');
  ok(md.includes(`${died.length} of ${scored.length}`), 'the stratum dek carries the computed counts');
}

// ================================================================ 8 · the pooled rate is forbidden
// The hand-written and machine-scored columns must never be combined. The number that would
// result from combining them is computed here and required to be absent from the page.
{
  const pooledHits = heldStrict.length + fresh.oeis.publishedSummary.absent;   // 19 + 70
  const pooledN = scored.length + fresh.oeis.publishedSummary.total;           // 48 + 90
  const pooled = pooledHits / pooledN;
  // Only forms distinctive enough to be evidence. A bare "64" or "138" occurs in quoted item
  // text about cache lines and sample sizes, so banning those substrings would be a check that
  // fails on innocent pages and tells you nothing about this one.
  const forms = [
    (100 * pooled).toFixed(1), (100 * pooled).toFixed(2),
    `${pooledHits} of ${pooledN}`, `${pooledHits}/${pooledN}`, `${pooledHits} of the ${pooledN}`,
  ];
  const text = plainText(html.replace(/<script id="ledger-data"[\s\S]*?<\/script>/, ' '));
  for (const f of forms) {
    ok(!text.includes(f), `the pooled hand-and-machine figure "${f}" appears nowhere on the page`);
  }
  ok(html.includes('Kept in its own column on purpose') || html.includes('never be averaged') ||
     html.includes('never will be on this page'),
     'the page says in words that the two columns are not combined');
}

// ================================================================ 9 · the sealed prediction
{
  const s = sealedPrediction();
  eq(s.hash, fresh.sealed.hash, 'the sealed digest is stable across runs');
  eq(createHash('sha256').update(s.text, 'utf8').digest('hex'), s.hash,
     'the digest is the SHA-256 of the published preimage');
  ok(s.text.includes(s.nonce), 'the published preimage contains the published nonce');
  ok(await K.verify(s.hash, s.text), 'the shared kit verifies the digest against the preimage');
  const reSealed = await K.seal(s.prediction, { nonce: s.nonce });
  eq(reSealed.hash, s.hash, 'the kit re-seals the published prediction to the same digest');
  eq(reSealed.text, s.text, 'the kit canonicalises the prediction the same way this build did');
  ok(html.includes('EP-P1'), 'the sealed prediction has an id in the ledger');
  ok(html.includes('OPEN'), 'the sealed prediction is entered as OPEN');
  ok(html.includes("verdict: 'OPEN'"), 'the OPEN row is added to the table the page publishes');
  ok(s.prediction.scoring.includes('HELD only if both clauses'), 'the scoring rule is fixed in the sealed text');
  ok(!scored.some((i) => i.label === 'EP-P1'), 'the open prediction does not enter any rate');
  // NEGATIVE CONTROL: a single character change to the prediction must change the digest
  const tampered = { ...s.prediction, clause2: s.prediction.clause2.replace('greater', 'less') };
  const t = await K.seal(tampered, { nonce: s.nonce });
  ok(t.hash !== s.hash, 'NEGATIVE CONTROL: rewording the prediction changes the digest');
}

// ================================================================ 10 · the study left alone
// Nothing this page ships may reach the placard arm's outcome data. The assertion is over the
// shipped bytes rather than over intent, because intent is not checkable.
{
  const shipped = [PAGE, join(ROOT, 'src', 'content', 'strata', SELF + '.md')];
  const dir = join(HERE);
  const walk = (d) => {
    for (const f of readdirSync(d)) {
      const p = join(d, f);
      statSync(p).isDirectory() ? walk(p) : shipped.push(p);
    }
  };
  walk(dir);
  // A substring ban is the wrong check here: the page NAMES the outcome directory in prose, in
  // order to say it was left alone, and a ban on the name would forbid the disclosure while
  // permitting the read. So the check is on CODE, in two nets.
  //
  // Net 1, the path literals. Every `research/plain-placard-arm/<x>` that appears anywhere in
  // this directory's executable files, however it is later used, must name a file the
  // pre-registration allows: itself, or the frozen assignment. This catches a path assigned to
  // a variable first, which is how a corpus audit once found four leaks that a check scanning
  // only call sites could not see.
  const code = shipped.filter((f) => f.endsWith('.mjs'));
  ok(code.length >= 2, 'there is executable code to police', String(code.length));
  const PATHS = /research\/plain-placard-arm\/([A-Za-z0-9_.\/-]*)/g;
  const ALLOWED = ['', 'PREREGISTRATION.md', 'assignment.json'];
  let literals = 0;
  for (const f of code) {
    for (const m of readFileSync(f, 'utf8').matchAll(PATHS)) {
      literals++;
      ok(ALLOWED.includes(m[1]),
         'every placard-study path in executable code names the pre-registration or the frozen assignment',
         f.replace(ROOT, '') + ': ' + m[1]);
    }
  }
  ok(literals >= 2, 'net 1 actually found the paths it is policing', String(literals));

  // Net 2, the read positions, for a path built out of pieces that net 1 cannot see whole.
  const READ_CALL = /(?:readFileSync|readdirSync|createReadStream|execSync|execFileSync|import)\s*\(([^)]*placard[^)]*)\)/gi;
  for (const f of code) {
    for (const m of readFileSync(f, 'utf8').matchAll(READ_CALL)) {
      ok(['PREREGISTRATION.md', 'assignment.json'].some((a) => m[1].includes(a)),
         'every read call mentioning the placard study targets an allowed file',
         f.replace(ROOT, '') + ': ' + m[1].slice(0, 70));
    }
  }

  // NEGATIVE CONTROLS for both nets, assembled at runtime so this file's own bytes do not trip
  // the very checks it is testing.
  const smuggledPath = 'research/plain-placard' + '-arm/snap' + 'shots/2026-09-01.json';
  const smuggledCall = 'read' + 'FileSync(join(root, "' + smuggledPath + '"))';
  const n1 = [...smuggledPath.matchAll(PATHS)];
  ok(n1.length === 1 && !ALLOWED.includes(n1[0][1]),
     'NEGATIVE CONTROL: net 1 rejects a path into the outcome data');
  const n2 = [...smuggledCall.matchAll(READ_CALL)];
  ok(n2.length === 1 && !['PREREGISTRATION.md', 'assignment.json'].some((a) => n2[0][1].includes(a)),
     'NEGATIVE CONTROL: net 2 rejects a read call into the outcome data');

  // And the block built from that study may not grow an outcome-shaped field.
  eq(Object.keys(fresh.placard).sort().join(','),
     'control,digestHolds,file,frame,frozen,readout,recomputedDigest,statedDigest,treated',
     'the placard block carries only design facts, never an outcome');
  ok(!existsSync(join(HERE, 'snap' + 'shots')), 'no copy of the outcome data was taken');
  eq(fresh.placard.digestHolds, true, 'the frozen assignment re-derives to the digest its pre-registration published');
  eq(fresh.placard.treated, 261, 'the treated arm holds 261 pages');
  eq(fresh.placard.control, 262, 'the control arm holds 262 pages');
  eq(fresh.placard.readout, '2026-09-12', 'the readout date is the one the pre-registration fixed');
}

// ================================================================ 11 · house mechanics
{
  ok(/<\/body>/i.test(html) && /<\/html>/i.test(html), 'the page closes </body> and </html>');
  const opens = (html.match(/<script\b/gi) || []).length;
  const closes = (html.match(/<\/script>/gi) || []).length;
  eq(opens, closes, 'every script tag in the page is closed');
  // NOT an exact inventory: site-wide chrome generators inject scripts into every shipped page
  // at publish time, and asserting the count would go red on a byte this layer never wrote.
  // Assert the page's OWN four are present instead.
  for (const own of ['application/ld+json', 'src="/_kit/precommit.js"',
                     'id="ledger-data"', "const DATA = JSON.parse"]) {
    ok(html.includes(own), `the page still carries its own script: ${own}`);
  }
  ok(opens >= 4, 'the page carries at least its own four script tags', String(opens));

  // no third-party request in any syntactic form
  const scripts = [...html.matchAll(/<script\b[^>]*>([\s\S]*?)<\/script>/gi)].map((m) => m[1]);
  const offenders = [];
  for (const body of scripts) {
    for (const m of body.matchAll(/https?:\/\/[^\s"'`)\\]+/g)) {
      if (!/^https?:\/\/(schema\.org|artwaste\.land)/.test(m[0])) offenders.push(m[0]);
    }
  }
  ok(offenders.length === 0, 'no third-party URL appears inside any script', offenders.slice(0, 3).join(' '));
  const srcs = [...html.matchAll(/<(?:script|link|img|iframe)\b[^>]*(?:src|href)="([^"]+)"/gi)].map((m) => m[1]);
  const external = srcs.filter((u) => /^https?:/i.test(u) && !/^https:\/\/artwaste\.land/.test(u));
  ok(external.length === 0, 'no element loads from a third-party host', external.join(' '));

  // the em-dash rule, over this page's own prose (the dataset quotes other pages and is
  // escaped to ASCII, so a source's dash cannot be mistaken for ours)
  ok(!html.includes('—'), 'no literal em dash in the shipped page');
  ok(!md.includes('—'), 'no literal em dash in the stratum file');
  ok(!readFileSync(join(HERE, 'README.md'), 'utf8').includes('—'), 'no literal em dash in the README');

  // accessibility and responsiveness affordances that are checkable from source
  for (const needle of ['prefers-reduced-motion', ':focus-visible', 'aria-live="polite"',
                        'role="status"', '/fonts/fonts.css', 'lang="en"']) {
    ok(html.includes(needle), `the page carries ${needle}`);
  }
  ok((html.match(/role="status"/g) || []).length >= 8, 'every live readout is announced');

  // frontmatter claims
  for (const needle of ['seam: "lineage"', 'draft: false', 'href: "/strata/' + SELF + '/"',
                        'plain:', 'dek:', 'seoTitle:', 'relates:']) {
    ok(md.includes(needle), `the stratum file declares ${needle}`);
  }
  const plainVal = (md.match(/^plain:\s*"([\s\S]*?)"\s*$/m) || [null, ''])[1];
  ok(plainVal.length >= 90 && plainVal.length <= 420, 'the placard is within the house length bounds', String(plainVal.length));
  ok(plainVal.split(/(?<=[.!?])\s+/).filter(Boolean).length <= 3, 'the placard is at most three sentences');
  ok(html.includes('name="aw-plain"'), 'the placard is carried into the page');
}

// ---------------------------------------------------------------- report
console.log(`\n${pass} assertions passed, ${failures.length} failed.`);
if (failures.length) {
  for (const f of failures) console.error('  FAIL  ' + f);
  process.exit(1);
}
console.log('every-prediction-we-wrote-down-first: green.');
