#!/usr/bin/env node
/**
 * verify-the-check-that-cannot-fail.mjs
 *
 *   node research/verifier-independence/verify-the-check-that-cannot-fail.mjs
 *
 * The check for a page whose subject is checks that cannot fail. It would be a
 * joke to write this one page-blind, so it is not: it lifts the page's own
 * `auditMatrix` out of the shipped HTML, evaluates it, and compares the whole
 * six-by-three outcome matrix against an implementation written here, from the
 * calendar rather than from the page. If the instrument and this file ever
 * disagree, this file goes red. That is coupling C3, mechanism `lift`, which is
 * the same mechanism the rebuilt copyright verifier uses.
 *
 * It also ties the tagged census figures and results block to their records,
 * and re-derives that measurement over its own recorded file list, so a change to
 * any classified check turns this red while the corpus simply growing does not.
 *
 * Exits 0 on success, 1 on any failure.
 */

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

const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, '..', '..');
const SLUG = 'the-check-that-cannot-fail';
const PAGE = path.join(ROOT, 'public', 'strata', SLUG, 'index.html');

let checks = 0, failures = 0;
const ok = (label, v) => { checks++; console.log('  ok   ' + label + (v === undefined ? '' : '  ->  ' + v)); };
const fail = (label, detail) => { checks++; failures++; console.error('  FAIL ' + label + '\n       ' + detail); };
const eq = (label, got, want) => (got === want ? ok(label, String(got))
  : fail(label, 'got ' + JSON.stringify(got) + ', want ' + JSON.stringify(want)));
const truthy = (label, cond, detail) => (cond ? ok(label) : fail(label, detail || 'condition false'));
const section = n => console.log('\n== ' + n + ' ==');

/* ------------------------------------------------------------------ 0. page */

section('the shipped page');
if (!fs.existsSync(PAGE)) { console.error('  FAIL page missing at ' + PAGE); process.exit(1); }
const html = fs.readFileSync(PAGE, 'utf8');

truthy('page ends with the load-bearing closing tags',
  /<\/script>\s*<\/body>\s*<\/html>\s*$/.test(html.trim()),
  'tail is ' + JSON.stringify(html.slice(-90)));
truthy('canonical link present',
  html.includes('<link rel="canonical" href="https://artwaste.land/strata/' + SLUG + '/" />'));
truthy('JSON-LD preserves the landing date and dates this revision',
  html.includes('"datePublished":"2026-07-26"') && html.includes('"dateModified":"2026-10-01"'));
truthy('the shared site bar is included',
  html.includes('<script src="/media/home-banner.js" defer></script>'));
truthy('the way-out footer is present',
  html.includes('class="aw-wayout"') && html.includes('href="/archive/"'));
truthy('no off-site script or stylesheet',
  !/(?:src|href)="https?:\/\/(?!artwaste\.land)/.test(
    html.replace(/<a\b[^>]*>/g, '')
      .replace(/<meta[^>]*>/g, '')
      .replace(/<script type="application\/ld\+json">[\s\S]*?<\/script>/, '')),
  'a script or stylesheet points off-site');

/* --------------------------------------- 1. the page's own code, lifted out */

section("the instrument, lifted out of the HTML and run");

/** Brace-match a declaration out of the page and return its full source. */
function lift(marker) {
  const at = html.indexOf(marker);
  if (at < 0) throw new Error('marker not found in page: ' + marker);
  const open = html.indexOf('{', at + marker.length - 1);
  if (open < 0) throw new Error('no body brace after ' + marker);
  let depth = 0, i = open, state = 'code', quote = '';
  while (i < html.length) {
    const c = html[i], d = html[i + 1];
    if (state === 'code') {
      if (c === '/' && d === '*') { state = 'block'; i += 2; continue; }
      if (c === '/' && d === '/') { state = 'line'; i += 2; continue; }
      if (c === '"' || c === "'" || c === '`') { state = 'str'; quote = c; i++; continue; }
      if (c === '{') depth++;
      else if (c === '}') { depth--; if (depth === 0) return html.slice(at, i + 1); }
      i++; continue;
    }
    if (state === 'block') { if (c === '*' && d === '/') { state = 'code'; i += 2; continue; } i++; continue; }
    if (state === 'line') { if (c === '\n') state = 'code'; i++; continue; }
    if (c === '\\') { i += 2; continue; }
    if (c === quote) { state = 'code'; i++; continue; }
    i++;
  }
  throw new Error('unbalanced braces after ' + marker);
}

let pageMatrix;
try {
  const src = lift('function auditMatrix() {');
  truthy('auditMatrix lifted from the page', src.length > 800, 'lifted only ' + src.length + ' chars');
  truthy('the lifted block is self-contained (no outside identifiers)',
    !/\bdocument\b|\bwindow\b|\bstate\b|\bM\b\s*\./.test(src),
    'the block reaches outside itself, so it cannot be evaluated in isolation');
  // eslint-disable-next-line no-new-func
  pageMatrix = new Function(src + '; return auditMatrix();')();
  ok('auditMatrix evaluated');
} catch (e) {
  fail('auditMatrix lifted and evaluated', String(e && e.message));
}

/* ------------- 2. an implementation written here, not taken from the page */

/* Written from the calendar. 400 Gregorian years hold 97 leap days and 146097
   days, which is 7 x 20871, so the weekday pattern repeats every 400 years. */
const greg = y => y % 4 === 0 && (y % 100 !== 0 || y % 400 === 0);
const MINE = {
  none: y => greg(y),
  no400: y => y % 4 === 0 && y % 100 !== 0,
  off4: y => y % 4 === 1 && (y % 100 !== 0 || y % 400 === 0),
  century: y => y % 4 === 0 && (y % 100 === 0 || y % 400 === 0),
  shift: y => greg(y - 4),
  julian: y => (y < 1583 ? y % 4 === 0 : greg(y)),
};
const YEARS = [1600, 1700, 1800, 1900, 1996, 1999, 2000, 2020, 2021, 2024, 2100, 2400];
const PUBLISHED = [true, false, false, false, true, false, true, true, false, true, false, true];

const myTable = f => YEARS.every((y, i) => f(y) === PUBLISHED[i]);
const myInvariant = f => {
  let n = 0;
  for (let y = 1600; y < 2000; y++) if (f(y)) n++;
  return { pass: n === 97 && 400 * 365 + n === 146097, leaps: n, days: 400 * 365 + n };
};

section('the arithmetic this file derives independently');
eq('leap years in 1600..1999 under the Gregorian rule', myInvariant(MINE.none).leaps, 97);
eq('days in 400 Gregorian years', myInvariant(MINE.none).days, 146097);
eq('146097 divided by 7 is a whole number of weeks', 146097 % 7, 0);
eq('146097 / 7', 146097 / 7, 20871);
eq('mean Gregorian year in days', 146097 / 400, 365.2425);
truthy('1900 was a common year and 2000 a leap year', !greg(1900) && greg(2000));

/* ---------------------------- 3. the page's matrix against this one */

section('the page agrees with this file, defect by defect');
if (pageMatrix) {
  eq('the page uses the same twelve reference years', pageMatrix.years.join(','), YEARS.join(','));
  eq('the page uses the same published answers', pageMatrix.published.join(','), PUBLISHED.join(','));
  eq('the page carries six variants', pageMatrix.rows.length, 6);

  for (const r of pageMatrix.rows) {
    const mine = MINE[r.id];
    if (!mine) { fail('variant ' + r.id + ' is one this file knows', 'unknown variant id'); continue; }

    // The page's answers for the twelve years must match this file's function.
    const want = YEARS.map(y => mine(y));
    eq(`variant ${r.id}: twelve answers match`, r.answers.join(','), want.join(','));

    // Check A never sees the page, so it passes for every variant, which is the
    // whole demonstration and therefore the thing most worth asserting.
    truthy(`variant ${r.id}: the restatement passes even so`, r.coupled.restatement.pass === true,
      'the restatement went red, which would break the page\'s central claim');

    // Checks B and C, coupled, must agree with this file's verdicts.
    eq(`variant ${r.id}: table check verdict`, r.coupled.table.pass, myTable(mine));
    const inv = myInvariant(mine);
    eq(`variant ${r.id}: invariant verdict`, r.coupled.invariant.pass, inv.pass);
    eq(`variant ${r.id}: invariant leap count`, r.coupled.invariant.leaps, inv.leaps);
    eq(`variant ${r.id}: invariant day count`, r.coupled.invariant.days, inv.days);

    // Uncoupled, every check passes whatever the page says. If this ever fails,
    // the page's first lesson is false.
    truthy(`variant ${r.id}: own-copy mode is green on all three`,
      r.ownCopy.restatement.pass && r.ownCopy.table.pass && r.ownCopy.invariant.pass,
      'a check with its own copy went red, which cannot happen if it never reads the page');
  }

  section('the three lessons the prose claims, asserted');
  const by = id => pageMatrix.rows.find(r => r.id === id);
  truthy('lesson 1: with its own copy, nothing catches the worst defect',
    ['no400', 'off4', 'century', 'shift', 'julian'].every(id => {
      const r = by(id);
      return r.ownCopy.restatement.pass && r.ownCopy.table.pass && r.ownCopy.invariant.pass;
    }));
  truthy('lesson 2: the shift defect fails the table and passes the invariant',
    by('shift').coupled.table.pass === false && by('shift').coupled.invariant.pass === true,
    'the density-preserving defect no longer splits the two coupled checks');
  truthy('lesson 3: the pre-1583 defect passes all three even when coupled',
    by('julian').coupled.table.pass && by('julian').coupled.invariant.pass
      && by('julian').coupled.restatement.pass,
    'the out-of-scope defect is no longer out of scope');
  truthy('and the correct variant passes all three',
    by('none').coupled.table.pass && by('none').coupled.invariant.pass);
}

/* ------------------------------- 4. the corpus figures the page prints */

section('the corpus figures, against the committed measurement');
const censusPath = path.join(HERE, 'census.json');
if (!fs.existsSync(censusPath)) {
  fail('census.json committed beside this file', 'missing ' + censusPath);
} else {
  const C = JSON.parse(fs.readFileSync(censusPath, 'utf8'));

  const pairsAll = fs.readFileSync(path.join(HERE, 'census-pairs.tsv'), 'utf8')
    .trim().split('\n').slice(1).map(l => l.split('\t'));
  const modFilesEarly = () => new Set(pairsAll.filter(r => r[3] === 'mod').map(r => r[1])).size;

  /* The tagged census figures must match the measured values. Each lives in a
     <span data-fig="..."> that `fill-page-results.mjs` sets from the census, and
     this asserts that what the page currently shows equals what the census
     currently says. The previous arrangement pinned the counts as literals HERE,
     in words THERE ("Seventeen checks ... covering fifteen layers"), and the two
     were kept in step by a person. They were not in step: the page said 595
     layers at 673, 253 printed commands at 298, and twelve lift-checks at 49.
     A layer about checks that cannot fail was shipping a check that had gone red
     and a paragraph that had gone false, which is the subject of the page
     happening to the page. */
  const { proseFigures } = await import('./fill-page-results.mjs');
  const figs = proseFigures();
  const shown = {};
  for (const m of html.matchAll(/<span data-fig="([a-zA-Z]+)">([^<]*)<\/span>/g)) {
    (shown[m[1]] ||= new Set()).add(m[2]);
  }
  for (const [key, want] of Object.entries(figs)) {
    if (want === null || want === undefined) continue;
    const got = shown[key];
    if (!got) { fail(`the page carries a data-fig span for ${key}`, `no span named ${key}`); continue; }
    const wrong = [...got].filter(v => v !== String(want));
    truthy(`the page states the measured ${key} (${want})`, wrong.length === 0,
      `span(s) show ${JSON.stringify(wrong)}; run fill-page-results.mjs`);
  }

  // The embedded per-layer table must match the committed TSV row for row.
  const tsv = fs.readFileSync(path.join(HERE, 'census-slugs.tsv'), 'utf8').trim().split('\n').slice(1);
  const want = tsv.map(l => { const c = l.split('\t'); return c[0] + ' ' + c[1] + ' ' + (c[5] || ''); });
  const m = /<script type="text\/plain" id="census-table">([\s\S]*?)<\/script>/.exec(html);
  if (!m) fail('the page embeds its per-layer table', 'no census-table block found');
  else {
    const got = m[1].trim().split('\n');
    eq('embedded table row count', got.length, want.length);
    const firstBad = got.findIndex((l, i) => l !== want[i]);
    truthy('embedded table matches census-slugs.tsv row for row', firstBad === -1,
      firstBad === -1 ? '' : `row ${firstBad + 1}: page has ${JSON.stringify(got[firstBad])}, tsv has ${JSON.stringify(want[firstBad])}`);
    // And the bar chart the page draws is derived from that block, so its
    // totals must be the census's totals.
    const tally = { C3: 0, C2: 0, C0: 0, NONE: 0 };
    for (const l of got) { const t = l.split(' ')[1]; if (tally[t] !== undefined) tally[t]++; }
    for (const k of Object.keys(tally)) {
      eq(`embedded table tallies ${k} as the census does`, tally[k], C.slug_counts[k]);
    }
  }

  // Re-derive the measurement over its own recorded file list. Corpus growth
  // adds rows that are not in the record and so cannot break this; editing a
  // classified check can, and should.
  const { fileFacts, couplingTo } = await import('./lib/classify.mjs');
  let rechecked = 0, drifted = [];
  for (const s of C.strata) {
    for (const c of s.code) {
      const abs = path.join(ROOT, c.rel);
      if (!fs.existsSync(abs)) { drifted.push(c.rel + ' (gone)'); continue; }
      const now = couplingTo(fileFacts(c.rel, ROOT), s.slug);
      rechecked++;
      if (now.tier !== c.tier) drifted.push(`${c.rel} for ${s.slug}: recorded ${c.tier}, now ${now.tier}`);
    }
  }
  truthy(`all ${rechecked} recorded (check, layer) pairs reclassify to their recorded coupling`,
    drifted.length === 0,
    drifted.slice(0, 6).join('; ') + (drifted.length > 6 ? ` ... and ${drifted.length - 6} more` : ''));

  /* The claim that every printed command resolves is a gate; assert the gate holds.
     The counting moved to lib/commands.mjs on 2026-08-01 so that this assertion and
     the figures the page prints come from the same function rather than from a
     verifier and a human who each counted once. */
  const { commandCensus } = await import('./lib/commands.mjs');
  const { pagesWithCommand: pagesWith, commands: cmds, broken } = commandCensus();
  truthy('every printed reproduce-it-yourself command resolves', broken.length === 0, broken.join('; '));
  /* The page's stated command figures are checked by the data-fig block above,
     against the same commandCensus() this assertion calls, so restating them here
     as a regex over prose would be a second copy of the same claim, kept in step
     by hand, which is the failure this whole edit is undoing. */
  void pagesWith; void cmds;
}

/* ------------------------------------ 5. the trace and mutation figures */

/* The sweep this page reports is the one recorded by 2026-08-10 (66 layers). It was written to the
   shared mutation-results.json, which later sweeps rewrote (a heartbeat checkpoint of 2026-08-25,
   merges from 2026-09-06), so this page's figures had come to be compared with other experiments.
   The record the figures came from is kept under its date; mutate.mjs still writes the shared file.
   (2026-09-28, research/observation-or-error/.) */
const MUTATION_RECORD = 'dated/mutation-results-2026-08-10.json'; // outside verdicts.mjs's glob, so placards do not read it
section('the graded and tested figures, against their committed records');
for (const [file, label] of [['trace-results.json', 'kernel trace'], [MUTATION_RECORD, 'mutation run']]) {
  const p = path.join(HERE, file);
  truthy(`${label} record committed`, fs.existsSync(p), 'missing ' + p);
}
/* The grading is read from grading.json rather than recomputed here, because
   regrade.mjs is the one place that knows which rows are held out and why (a
   crashed run, an ambiguous browser launch, a direct eval the tracer cannot
   see). Two implementations of the holdout rule would eventually disagree, and
   the one that disagreed silently would be this file. */
if (fs.existsSync(path.join(HERE, 'grading.json'))) {
  const G = JSON.parse(fs.readFileSync(path.join(HERE, 'grading.json'), 'utf8'));
  ok('checks traced under strace', G.traced);
  ok('gradable (exited 0, unambiguous)', G.graded);
  ok('static agreed with the kernel', G.agree + ' (' + (100 * G.agree / G.graded).toFixed(1) + '%)');
  truthy('no gradable run had its coupling OVERSTATED, so the census is a lower bound',
    G.overstated === 0, G.overstated + ' overstatements recorded in grading.json');
  truthy('the page states the lower-bound property',
    /lower bound/i.test(html), 'the caveat about the census being a lower bound is missing');
  truthy('grading.json was written from the trace record on disk',
    fs.existsSync(path.join(HERE, 'trace-results.json')) &&
    G.traced === JSON.parse(fs.readFileSync(path.join(HERE, 'trace-results.json'), 'utf8')).rows.length,
    'grading.json and trace-results.json disagree on how many checks were traced; re-run regrade.mjs');
}
if (fs.existsSync(path.join(HERE, MUTATION_RECORD))) {
  const Mu = JSON.parse(fs.readFileSync(path.join(HERE, MUTATION_RECORD), 'utf8'));
  const flat = Mu.records.flatMap(r => (r.rows || []).map(x => ({ ...x, aimed: r.aimed })));
  const c0 = flat.filter(r => r.tier === 'C0');
  /* Reds traced to nondeterminism (a network fetch, a generator write) are not
     evidence about coupling, and the page discloses them by name. The control
     turns on the UNEXPLAINED ones. */
  const NONDET = /\bfetch\s*\(|https?:\/\/(?!artwaste\.land)[a-z]|writeFileSync\s*\([^)]*(?:public|dist)\//;
  const nondet = rel => {
    try { return NONDET.test(fs.readFileSync(path.join(ROOT, rel), 'utf8')); } catch { return false; }
  };
  const c0red = c0.filter(r => r.detected && !nondet(r.rel));
  const c0redExplained = c0.filter(r => r.detected && nondet(r.rel));
  if (c0redExplained.length) {
    truthy('every disclosed control red is named on the page',
      c0redExplained.every(r => html.includes(r.rel)),
      'a control failure is in the record but not named on the page: '
        + c0redExplained.map(r => r.rel).join(', '));
  }
  /* A control with no runs in it passes for free, and a check that passes for
     free is the exact fault this page is about. So the control has to be
     populated before it is allowed to hold. */
  const FLOOR = 20;
  truthy(`the negative control is populated (at least ${FLOOR} C0 check-runs)`,
    c0.length >= FLOOR,
    `only ${c0.length} C0 check-runs in the record, which would make the next assertion vacuous`);
  truthy(`the negative control held: ${c0.length} C0 check-runs against mutated pages, none red`,
    c0.length >= FLOOR && c0red.length === 0,
    c0red.length
      ? c0red.slice(0, 5).map(r => r.slug + ' ' + r.rel).join('; ')
      : 'the control was not populated, so it cannot be said to have held');

  /* A run cut short is a legitimate thing to publish and an illegitimate thing to
     publish silently, so an incomplete record has to be declared as one. Records
     written before checkpointing existed carry no flag at all, which is not the
     same as claiming completeness. */
  /* A partial sweep is a legitimate thing to publish. A partial sweep that reads
     as a complete one is not. So the rule is not "must be complete", it is "if it
     is partial, the page must say so, in the row and in the sentence". */
  if (Mu.complete === false) {
    const planned = Mu.slugs_planned ?? '?';
    truthy('the page declares the sweep partial in Instrument III',
      new RegExp('of ' + planned + ' planned').test(html),
      'the record is partial and the layers-mutated row does not say so');
    truthy('the page declares the sweep partial in the sentence beneath it',
      /injection sweep is <b>partial<\/b>/.test(html),
      'the record is partial and the note beneath Instrument III does not say so');
  } else {
    ok('the mutation record is a complete sweep');
  }
  ok('mutations applied', Mu.mutations);
}

/* -------------------- 6. the page's results block, re-derived not trusted */

section("Instrument III's figures, re-derived from the records");
if (fs.existsSync(path.join(HERE, 'grading.json')) && fs.existsSync(path.join(HERE, MUTATION_RECORD))) {
  const { figures, blockText } = await import('./fill-page-results.mjs');
  const want = blockText(figures());
  const m = /<script type="text\/plain" id="results-data">([\s\S]*?)<\/script>/.exec(html);
  if (!m) fail('the page carries a results-data block', 'block missing');
  else {
    const got = m[1].trim();
    if (got === want.trim()) ok('every figure in Instrument III matches the committed records');
    else {
      const gl = got.split('\n'), wl = want.trim().split('\n');
      const bad = wl.filter((l, i) => gl[i] !== l).slice(0, 4);
      fail('every figure in Instrument III matches the committed records',
        'first differences: ' + JSON.stringify(bad) + ' (regenerate with fill-page-results.mjs)');
    }
  }
}

/* ------------------ 6b. the hermetic arm, and the words it borrowed from
                          people who are not us */

/**
 * The page quotes two strangers. Everything else on it can be re-derived from
 * this repository; those two sentences cannot, because they belong to somebody
 * else and the only honest source for them is the record they were published in.
 * So they are pinned in `prompts-from-outside.json`, fetched from the public AT
 * Protocol API, and this section requires the page to reproduce them exactly.
 *
 * The direction of the assertion is the point. A drifted figure is an error; a
 * drifted quotation is an invention with a real person's name on it, which is
 * the one failure this ground has no way to apologise its way out of.
 */
section('the hermetic arm, and the quotations it rests on');
{
  const pf = path.join(HERE, 'prompts-from-outside.json');
  if (!fs.existsSync(pf)) {
    fail('prompts-from-outside.json exists', 'missing: the page quotes posts with no pinned record behind them');
  } else {
    const P = JSON.parse(fs.readFileSync(pf, 'utf8'));
    const byHandle = new Map(P.posts.map(p => [p.handle, p]));
    /* The page renders curly quotes and HTML entities; compare on a normalised
       form so the assertion is about the words, not about the typography. */
    const norm = s => s.replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>')
      .replace(/&quot;/g, '"').replace(/&#39;/g, "'")
      .replace(/[“”]/g, '"').replace(/[‘’]/g, "'")
      .replace(/\s+/g, ' ').trim();
    const flat = norm(html.replace(/<[^>]+>/g, ' '));

    for (const handle of ['@void.comind.network', '@wisp.mk.gg']) {
      const post = byHandle.get(handle);
      if (!post) { fail(`a pinned record exists for ${handle}`, 'not in prompts-from-outside.json'); continue; }
      truthy(`the page names ${handle}`, html.includes(handle));
      /* The page quotes a SPAN of each post, not always the whole of it, so the
         test is that what the page shows is a contiguous piece of what was
         actually written. A paraphrase fails this; so does a tidied-up dash. */
      const src = norm(post.text);
      const quoted = [...flat.matchAll(/"([^"]{40,400})"/g)].map(m => norm(m[1]));
      const found = quoted.filter(q => src.includes(q));
      truthy(`the page quotes ${handle} verbatim from the pinned record`, found.length > 0,
        `nothing the page shows in quotation marks is a contiguous span of ${post.uri}`);
    }
    truthy('the pinned records carry their at:// URIs', P.posts.every(p => /^at:\/\//.test(p.uri)));
  }

  const hg = path.join(HERE, 'hermetic-grading.json');
  if (!fs.existsSync(hg)) {
    fail('hermetic-grading.json exists', 'the page reports an arm with no record behind it');
  } else {
    const H = JSON.parse(fs.readFileSync(hg, 'utf8'));
    /* The arm's whole worth rests on the two passes really having been taken
       under the two conditions they claim. A closed pass that could still reach
       the world would report every network-dependent check as independent. */
    const O = JSON.parse(fs.readFileSync(path.join(HERE, H.openFile), 'utf8'));
    const C = JSON.parse(fs.readFileSync(path.join(HERE, H.closedFile), 'utf8'));
    truthy('the open pass really reached the world', O.isolation.reachesWorld === true,
      'the open baseline was taken offline, which would make every check look network-independent');
    truthy('the closed pass really could not', C.isolation.reachesWorld === false,
      'the isolated pass could still reach the network, so it measured nothing');
    truthy('the closed pass was isolated by namespace, not by patching a library',
      C.isolation.dns.ok === false && C.isolation.raw.ok === false,
      'DNS and a raw connection to a literal address must BOTH be denied, or a check dialling an IP escapes');
    truthy('the population excludes checks that were already red',
      H.population.greenWithNetworkOpen <= H.population.runsBoth);
    /* Reds under isolation with no network error in their own stderr are not
       evidence and must not be inside the dependent count. */
    truthy('unexplained reds are held out of the dependent count',
      H.measured.networkDependent + H.measured.networkIndependent + H.measured.redUnderIsolationUnexplained
        === H.population.greenWithNetworkOpen,
      'the three outcomes do not partition the population');
    eq('the confusion matrix covers the same population',
      H.confusion.regexYes_measuredDependent + H.confusion.regexYes_measuredIndependent
      + H.confusion.regexNo_measuredDependent + H.confusion.regexNo_measuredIndependent,
      H.measured.networkDependent + H.measured.networkIndependent);
    truthy('every check the regex missed is named, not just counted',
      H.missedByRegex.length === H.confusion.regexNo_measuredDependent);
    truthy('the page carries the hermetic section', html.includes('id="take-the-network-away"'));
  }
}

/* --------------------------------- 7. the score the page pins for this file */

/* The page prints a pinned result for this very check, so this file has to be
   the thing that decides whether that number is true. The assertion counts
   itself, which is fine and stable: it exists whether or not the page is right,
   so the total does not move when the page is corrected. */
section('the score this page pins for this check');
{
  /* The pinned string used to be built as 'PASS n/n' unconditionally, so it only
     ever asserted that the page knew how many assertions this file contains. The
     page could therefore print PASS while this run exited red, and on 2026-08-10
     it was doing exactly that: the page pinned "PASS 109/109" against a run that
     produced FAIL 106/109. On a page about checks that cannot fail, that is the
     page's own species of bug. The verdict is now part of what the page must
     state. Failures are read BEFORE this assertion adds itself, so a corrected
     page is a fixed point: pin what it asks for, re-run, and it agrees. */
  const m = /Pinned result: <b id="pin">([^<]*)<\/b>/.exec(html);
  const total = checks + 1;
  const want = (failures ? 'FAIL ' : 'PASS ') + (total - failures) + '/' + total;
  if (!m) fail('the page pins a result for this check', 'no <b id="pin"> found');
  else if (m[1].trim() === want) ok('the pinned score is the score this run produces', want);
  else fail('the pinned score is the score this run produces',
    `the page pins ${JSON.stringify(m[1].trim())}, this run produces ${JSON.stringify(want)}`);
}

/* ---------------------------------------------------------------- verdict */

console.log('\n' + (failures ? 'FAIL ' : 'PASS ') + (checks - failures) + '/' + checks);
process.exit(failures ? 1 : 0);
