// verify.mjs — the check behind the combine portal
// "The Date That Can Only Say No" (/strata/the-date-that-can-only-say-no/).
//
// PORTAL LAW. A combine adds no new fact. Every year, count and quotation the
// portal displays is already published inside a member layer and covered by that
// layer's own committed verifier. This script does four jobs:
//
//   (A) holds an INDEPENDENT copy of every member figure, typed here from the
//       member pages, and re-derives every signed gap from it, so the page and
//       this file cannot silently drift apart;
//   (B) runs the verdict rule exhaustively over every integer year 1400..2026
//       against all six cases and asserts no confirmation occurs.
//       Cobalt flags are separate from refutations.
//       6 x 627 = 3,762 settings, 0 confirmations;
//   (C) re-reads the shipped HTML and asserts the page's own CASES array matches
//       (A) field for field, and that the load-bearing sentences are present;
//   (D) re-runs all eight members' verifiers (nine scripts) and confirms each
//       exits clean, so the borrowed numbers still stand under their own checks.
//
// THE SPINE. A terminus post quem is a one-sided instrument. A dated attestation
// can refute a claim and can never confirm one. Six members collide, sorted by
// the signed gap (attested year minus claimed year):
//   -23  boredom-word ................ the word is already in print in 1829
//   -16  who-discovered-... .......... Slipher publishes velocities in 1913
//    -3  let-them-eat-cake ........... Rousseau finishes the sentence by 1767
//  +112  pigment-that-wasnt-born ..... cobalt aluminate documented in 1777; flag only
//  +361  a-minor-leonardo ............ supremacy is attested only from 1911
//  +500  the-dancing-plague .......... Pennant-Rea's conditional published in 2018
// Plus the limit case (what-the-first-sleep-was-first-of: an absence claim has no
// year, so no gap) and the foil (every-tree-wrote-the-same-bad-year: the one
// member that returns an exact year, and the only one with a measured
// false-positive rate).
//
// run:  node research/the-date-that-can-only-say-no/verify.mjs
//       node research/the-date-that-can-only-say-no/verify.mjs --fast   (skip part D)
// No package dependencies or network. Git reads the pinned historical quotes.
// Part D runs the member scripts (a few minutes); --fast skips those scripts.

import { execFileSync } from "node:child_process";
import { existsSync, readFileSync, readdirSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";

const HERE = dirname(fileURLToPath(import.meta.url));
const RESEARCH = dirname(HERE);
const ROOT = dirname(RESEARCH);
const FAST = process.argv.includes("--fast");

let pass = 0, fail = 0;
const ok = (name, cond, extra = "") => {
  if (cond) pass++; else fail++;
  console.log(`${cond ? "  ok  " : "FAIL  "}${name}${extra ? "   " + extra : ""}`);
};

// ============================================================================
console.log("\n── A. the member figures, typed independently, and every gap re-derived ──\n");
// ============================================================================
//
// Each entry is transcribed from the member layer named in `slug`. `att` is the
// year by which the thing is proved to have existed; `claim` is the year the
// popular claim requires. `dir` is which side the collision is on. For plague,
// `att` dates the selected passage's publication, not a first-attestation bound.

const MEMBERS = [
  {
    key: "boredom", slug: "boredom-word", dir: "antedating",
    claim: 1852,   // Dickens, Bleak House: the OED's earliest evidence in 2024; its revised entry now gives 1829
    att:   1829,   // The Albion, New York, 8 August 1829
    // 1829 is soft (reported, not inspected at the original) and its own page says so.
    // It is kept because it is the figure that layer machine-checks, and A6 below
    // asserts the verdict survives at the solid Poe 1844 floor as well.
    selfStates: true, checked: "yes", soft: 1844,
    verifier: "research/boredom-word/build.mjs",
    memberAssertion: "OED first citation (1852) above its lowest antedating (1829)",
  },
  {
    key: "redshift", slug: "who-discovered-the-expanding-universe", dir: "antedating",
    claim: 1929,   // Hubble, PNAS 15:168-173
    // NOT Slipher 1913. That layer's own heading is "One measurement is not the
    // discovery": its headline object is blueshifted and Slipher read his shifts as
    // ordinary Doppler motion. A velocity catalogue attests a technique. The datum
    // that collides with "discovered in 1929" is Lemaitre's 1927 derivation, which
    // that page prints as "two years before Hubble".
    att:   1927,
    selfStates: false, checked: "no", soft: null,
    verifier: "research/who-discovered-the-expanding-universe/verify-who-discovered-the-expanding-universe.mjs",
    memberAssertion: null,   // its verifier compares quantities, never two years
  },
  {
    key: "cake", slug: "let-them-eat-cake", dir: "antedating",
    claim: 1770,   // Marie Antoinette arrives in France
    att:   1767,   // latest end of the Confessions I-VI composition range
    selfStates: true, checked: "yes", soft: null,
    verifier: "research/let-them-eat-cake/verify.mjs",
    memberAssertion: "latest plausible writing year",
  },
  {
    key: "pigment", slug: "pigment-that-wasnt-born", dir: "milestone",
    claim: 1665,   // illustrative setting, not a documented claimed date
    att:   1777,   // documented cobalt-aluminate experiment; not first existence
    selfStates: true, checked: "yes", soft: null,
    verifier: "research/pigment-that-wasnt-born/verify-pigment-that-wasnt-born.mjs",
    memberAssertion: "cobalt milestone 1777 > 1665",
  },
  {
    key: "monalisa", slug: "a-minor-leonardo", dir: "anachronism",
    claim: 1550,   // Vasari's praise: the earliest year the always-famous story could start
    att:   1911,   // the coverage peak, the year of the theft
    // it does NOT state the portal's asymmetry: its OCR sentence (counts can understate
    // or overstate coverage) is a caution about an instrument, not about a date
    selfStates: false, checked: "yes", soft: null,
    verifier: "research/a-minor-leonardo/verify-a-minor-leonardo.mjs",
    memberAssertion: "Vasari praised the painting 361 years before the theft",
  },
  {
    key: "plague", slug: "the-dancing-plague", dir: "publication",
    claim: 1518,   // this specific conditional is offered as contemporary testimony
    att:   2018,   // Pennant-Rea's publication; Waller reports a chronicle's rate in 2009
    // "partial": the member pins the event and both modern accounts, without
    // claiming first attestation. This portal calculates the publication gap.
    selfStates: true, checked: "partial", soft: null,
    verifier: "research/the-dancing-plague/verify.mjs",
    memberAssertion: "provenance anchors: 1518 · 1526 visit · 2009 report · 2018 conditional",
  },
];

// the verdict rule, written once and used by the page, part B and part C alike
const verdict = (m, claimYear) =>
  m.dir === "milestone" ? (m.att > claimYear ? "FLAGGED" : "SILENT") :
  (m.dir === "publication" || m.dir === "anachronism")
    ? (m.att > claimYear ? "REFUTED" : "SILENT")
    : (m.att < claimYear ? "REFUTED" : "SILENT");

ok("six collision members on the spine", MEMBERS.length === 6, `${MEMBERS.length}`);

// A1. every gap re-derived, and its sign agrees with its declared direction
const EXPECTED_GAPS = { boredom: -23, redshift: -2, cake: -3, pigment: 112, monalisa: 361, plague: 500 };
for (const m of MEMBERS) {
  const gap = m.att - m.claim;
  ok(`A1. ${m.key}: gap = ${m.att} - ${m.claim}`, gap === EXPECTED_GAPS[m.key], `${gap > 0 ? "+" : ""}${gap} years`);
  ok(`A1. ${m.key}: sign matches its declared direction (${m.dir})`,
     m.dir !== "antedating" ? gap > 0 : gap < 0);
  // Cobalt reports a milestone flag, not a historical refutation.
  const expected = m.dir === "milestone" ? "FLAGGED" : "REFUTED";
  ok(`A1. ${m.key}: ${expected} at its own setting`, verdict(m, m.claim) === expected);
}

// A2. THE MACHINE-CHECK COLUMN, CHECKED AGAINST THE MEMBER VERIFIERS THEMSELVES.
// An earlier version of this block compared two numbers typed side by side in the
// same object literal, which is not a check and let a wrong claim survive. It now
// opens each member's verifier file and looks for the assertion string.
for (const m of MEMBERS) {
  const vp = join(ROOT, m.verifier);
  ok(`A2. ${m.key}: its verifier file exists`, existsSync(vp), m.verifier);
  const src = existsSync(vp) ? readFileSync(vp, "utf8") : "";
  if (m.memberAssertion === null) {
    ok(`A2. ${m.key}: declared as NOT machine-checking its dates, and it does not`,
       m.checked === "no" &&
       !/1913\s*[<>]\s*1929|1929\s*-\s*1913|1927\s*[<>]\s*1929|1929\s*-\s*1927/.test(src),
       "no year-to-year comparison in its verifier");
  } else {
    ok(`A2. ${m.key}: its verifier really contains the assertion the table cites`,
       src.includes(m.memberAssertion), JSON.stringify(m.memberAssertion.slice(0, 44)));
  }
}
{
  const yes = MEMBERS.filter(m => m.checked === "yes").length;
  const part = MEMBERS.filter(m => m.checked === "partial").length;
  const no = MEMBERS.filter(m => m.checked === "no").length;
  ok("A2. the column is four yes, one partly, one no", yes === 4 && part === 1 && no === 1,
     `${yes} / ${part} / ${no}`);
  const states = MEMBERS.filter(m => m.selfStates).length;
  ok("A2. four of the six state the asymmetry in their own prose, two do not",
     states === 4 && MEMBERS.filter(m => !m.selfStates).length === 2, `${states} of 6`);
}

// A3. the sorted order the page prints
const sorted = [...MEMBERS].sort((a, b) => (a.att - a.claim) - (b.att - b.claim)).map(m => m.key);
ok("A3. sorted by signed gap: the order the page shows",
   sorted.join(" ") === "boredom cake redshift pigment monalisa plague", sorted.join(" "));

// A4. the point the sort is making: the magnitude carries no verdict
{
  const smallest = MEMBERS.find(m => m.key === "redshift");
  const largest  = MEMBERS.find(m => m.key === "plague");
  const ratio = Math.abs(largest.att - largest.claim) / Math.abs(smallest.att - smallest.claim);
  ok("A4. the largest gap is 250x the smallest", ratio === 250,
     `${Math.abs(largest.att - largest.claim)} / ${Math.abs(smallest.att - smallest.claim)} = ${ratio.toFixed(2)}x`);
  ok("A4. and both return the identical verdict at their own claimed year",
     verdict(smallest, smallest.claim) === verdict(largest, largest.claim) &&
     verdict(smallest, smallest.claim) === "REFUTED",
     "REFUTED = REFUTED");
}

// A5. monotonicity: the property two members already prove inside their own
// instruments, here shown to hold across the whole spine. Moving the claim AWAY
// from the attestation can only ever extinguish the verdict, never create one.
for (const m of MEMBERS) {
  let seenSilent = false, bad = 0;
  // walk in the direction that should silence this member
  const range = m.dir !== "antedating"
    ? Array.from({ length: 627 }, (_, i) => 1400 + i)          // claim rising -> eventually silent
    : Array.from({ length: 627 }, (_, i) => 2026 - i);         // claim falling -> eventually silent
  for (const y of range) {
    const v = verdict(m, y);
    if (v === "SILENT") seenSilent = true;
    else if (seenSilent) bad++;                                 // a refutation AFTER silence began
  }
  ok(`A5. ${m.key}: once silent, no later refutation or flag (monotone)`, bad === 0, `${bad} regressions`);
}

// A6. THE SOFT FLOOR. boredom's 1829 antedating is reported rather than inspected,
// and it is the row that sets the left end of the axis. So the verdict is checked
// at the solid Poe 1844 floor too: nothing on this page may rest on the soft year.
{
  const b = MEMBERS.find(m => m.key === "boredom");
  ok("A6. boredom is refuted at its soft 1829 floor", verdict(b, b.claim) === "REFUTED");
  const solid = { ...b, att: b.soft };
  ok("A6. and still refuted at the solid 1844 floor", verdict(solid, solid.claim) === "REFUTED",
     `gap ${solid.att - solid.claim} years`);
  ok("A6. the solid floor is the one its own layer calls verbatim-checked", b.soft === 1844);
}

// ============================================================================
console.log("\n── B. the exhaustive sweep: every year, every case, no confirmations ──\n");
// ============================================================================

const SWEEP_LO = 1400, SWEEP_HI = 2026;
const YEARS = SWEEP_HI - SWEEP_LO + 1;
{
  let n = 0, refuted = 0, flagged = 0, silent = 0, confirmed = 0;
  const per = {};
  for (const m of MEMBERS) {
    let r = 0, f = 0, s = 0;
    for (let y = SWEEP_LO; y <= SWEEP_HI; y++) {
      const v = verdict(m, y);
      n++;
      if (v === "REFUTED") { r++; refuted++; }
      else if (v === "FLAGGED") { f++; flagged++; }
      else if (v === "SILENT") { s++; silent++; }
      else confirmed++;
    }
    per[m.key] = { r, f, s };
    ok(`B. ${m.key}: ${r} refuted, ${f} flagged, ${s} silent, 0 confirmed over ${YEARS} years`,
       r + f + s === YEARS);
  }
  ok("B. the sweep covers 627 years", YEARS === 627, `${SWEEP_LO}-${SWEEP_HI} inclusive`);
  ok("B. 3,762 settings swept", n === 3762, `6 cases x ${YEARS} years = ${n}`);
  ok("B. the third lamp never lit", confirmed === 0, `confirmed = ${confirmed}`);
  ok("B. every setting is accounted for without treating flags as refutations",
     refuted + flagged + silent === n, `${refuted} + ${flagged} + ${silent} = ${n}`);
  ok("B. cobalt: 377 flags, 250 silent settings, zero refutations",
     per.pigment.f === 377 && per.pigment.s === 250 && per.pigment.r === 0);

  // the per-case counts are forced by the geometry, so state them and check them
  const geo = {};
  for (const m of MEMBERS) {
    // anachronism: refuted while claim < att, i.e. years SWEEP_LO..att-1
    // antedating : refuted while claim > att, i.e. years att+1..SWEEP_HI
    geo[m.key] = m.dir !== "antedating" ? (m.att - SWEEP_LO) : (SWEEP_HI - m.att);
  }
  for (const m of MEMBERS) {
    ok(`B. ${m.key}: refutation or flag count matches its inequality`,
       per[m.key].r + per[m.key].f === geo[m.key], `${per[m.key].r} refuted, ${per[m.key].f} flagged`);
  }
}

// ============================================================================
console.log("\n── C. the shipped page says exactly what part A derived ──\n");
// ============================================================================

const PAGE = join(ROOT, "public/strata/the-date-that-can-only-say-no/index.html");
ok("C. the immersive page exists", existsSync(PAGE));
const html = readFileSync(PAGE, "utf8");

for (const m of MEMBERS) {
  // the page's CASES array carries key, dir, claim, att for each member
  const block = new RegExp(
    `key:'${m.key}',\\s*dir:'${m.dir}',\\s*claim:${m.claim},\\s*att:${m.att}`
  );
  ok(`C. page CASES carries ${m.key} as ${m.dir} ${m.claim}/${m.att}`, block.test(html));
  ok(`C. page links the ${m.key} member layer`, html.includes(`slug:'${m.slug}'`));
}

// the page must declare the same sweep bounds this file swept
ok("C. page sweeps the same range", /const SWEEP_LO = 1400, SWEEP_HI = 2026;/.test(html));

// The page must distinguish flags without acquiring an authentication result.
{
  const rule = html.match(/function verdict\(c, claimYear\)\{[\s\S]*?\n\}/);
  ok("C. the page's verdict rule is present", !!rule);
  const body = rule ? rule[0] : "";
  ok("C. the page distinguishes milestone flags and never returns CONFIRMED",
     body.includes("c.dir === 'milestone'") && body.includes("'FLAGGED'") &&
     (body.match(/return[^;]*'(REFUTED|SILENT)'/g) || []).length >= 2 &&
     !body.includes("CONFIRMED"),
     "no CONFIRMED branch exists");
}

// C1b. THE PAGE'S OWN INLINE SCRIPT MUST PARSE.
// `astro build` ships a page whose inline JS is broken without a word, and the
// regex checks above happily match text inside a script that never runs. So the
// script is extracted and handed to the same parser the browser would use.
{
  const scripts = [...html.matchAll(/<script>([\s\S]*?)<\/script>/g)].map(m => m[1]);
  ok("C1b. the page carries exactly one inline script", scripts.length === 1, `${scripts.length}`);
  let parsed = false, why = "";
  try { new Function(scripts[0] ?? ""); parsed = true; }
  catch (e) { why = String(e && e.message ? e.message : e); }
  ok("C1b. and it parses", parsed, why);
}

// C1c. Exercise the actual shipped script and its rendered text, without a browser
// or external dependencies. Every requested ID must exist in the shipped HTML.
{
  const scripts = [...html.matchAll(/<script>([\s\S]*?)<\/script>/g)].map(m => m[1]);
  const ids = new Set([...html.matchAll(/\bid="([^"]+)"/g)].map(m => m[1]));
  const nodes = new Map();
  const element = () => ({
    children: [], listeners: {}, attrs: {}, value: "", textContent: "", innerHTML: "", className: "",
    appendChild(child) { this.children.push(child); },
    setAttribute(name, value) { this.attrs[name] = value; },
    addEventListener(name, fn) { this.listeners[name] = fn; },
  });
  const document = {
    getElementById(id) {
      if (!ids.has(id)) throw new Error(`Missing page element: ${id}`);
      if (!nodes.has(id)) nodes.set(id, element());
      return nodes.get(id);
    },
    createElement: element,
  };
  try {
    const page = new Function("document", scripts[0] + "\nreturn {CASES, verdict, getTally: () => ({...tally})};")(document);
    let mismatches = 0, cobaltRefutations = 0;
    for (const m of MEMBERS) {
      const i = page.CASES.findIndex(c => c.key === m.key);
      nodes.get("cases").children[i].listeners.click();
      for (let y = SWEEP_LO; y <= SWEEP_HI; y++) {
        nodes.get("claimYear").value = String(y);
        nodes.get("claimYear").listeners.input();
        const expected = verdict(m, y);
        const displayed = nodes.get("verdict").innerHTML;
        if (page.verdict(page.CASES[i], y) !== expected || !displayed.includes(`>${expected}.</span>`)) mismatches++;
        if (m.key === "pigment" && /REFUTED|not there to be there/.test(displayed)) cobaltRefutations++;
      }
    }
    ok("C1c. shipped verdicts and displayed labels agree over all 3,762 settings", mismatches === 0, `${mismatches} mismatches`);
    ok("C1c. cobalt never displays a refutation", cobaltRefutations === 0);
    const pigmentIndex = page.CASES.findIndex(c => c.key === "pigment");
    nodes.get("cases").children[pigmentIndex].listeners.click();
    for (const [year, expected] of [[1665, "FLAGGED"], [1776, "FLAGGED"], [1777, "SILENT"], [1780, "SILENT"], [1801, "SILENT"], [1802, "SILENT"]]) {
      nodes.get("claimYear").value = String(year);
      const before = page.getTally();
      nodes.get("claimYear").listeners.input();
      const after = page.getTally();
      ok(`C1c. cobalt ${year}: ${expected}, with a Flagged lamp and separate tally`,
         nodes.get("verdict").innerHTML.includes(`>${expected}.</span>`) &&
         nodes.get("redName").textContent === "Flagged" &&
         after.refuted === before.refuted && after.confirmed === before.confirmed &&
         after.flagged - before.flagged === (expected === "FLAGGED" ? 1 : 0));
    }
    nodes.get("claimYear").value = "1665";
    nodes.get("claimYear").listeners.input();
    ok("C1c. cobalt flag requires original paint, excluding restoration and contamination",
       nodes.get("verdict").innerHTML.includes("exclude later restoration and contamination"));
    ok("C1c. generated cobalt row prints +112, illustrative 1665, 1943, and a milestone limit",
       nodes.get("spine").innerHTML.includes("+112<span>years</span>") &&
       nodes.get("spine").innerHTML.includes("with illustrative setting 1665") &&
       nodes.get("spine").innerHTML.includes("sold to G&ouml;ring in 1943") &&
       nodes.get("spine").innerHTML.includes("milestone flag, not proof of impossibility"));
    const plagueIndex = page.CASES.findIndex(c => c.key === "plague");
    nodes.get("cases").children[plagueIndex].listeners.click();
    ok("C1c. plague dates a particular publication and separates the two accounts",
       nodes.get("claimline").innerHTML.includes("this specific passage") &&
       nodes.get("claimline").innerHTML.includes("Ned Pennant-Rea") &&
       nodes.get("claimline").innerHTML.includes("2018") &&
       nodes.get("claimline").innerHTML.includes("2009") &&
       nodes.get("claimline").innerHTML.includes("Neither source establishes first attestation"));
    for (const [year, expected] of [[1518, "REFUTED"], [2017, "REFUTED"], [2018, "SILENT"], [2026, "SILENT"]]) {
      nodes.get("claimYear").value = String(year);
      nodes.get("claimYear").listeners.input();
      const displayed = nodes.get("verdict").innerHTML;
      ok(`C1c. plague ${year}: ${expected} concerns publication, not whether deaths occurred`,
         displayed.includes(`>${expected}.</span>`) &&
         (expected === "REFUTED"
           ? displayed.includes("not testimony published in that earlier year") &&
             displayed.includes("does not date the first death-toll report or show that nobody died")
           : displayed.includes("does not confirm the death toll or establish its first attestation")) &&
         !displayed.includes("The thing was not there to be there") &&
         nodes.get("strip").innerHTML.includes("published 2018"));
    }
    ok("C1c. generated plague row prints a 500-year publication gap with the current quotation",
       nodes.get("spine").innerHTML.includes("+500<span>years</span>") &&
       nodes.get("spine").innerHTML.includes("publication gap for this passage, not first attestation") &&
       nodes.get("spine").innerHTML.includes("No contemporary toll is documented; a later report and a conditional total are not a contemporary count."));
    nodes.get("sweep").listeners.click();
    ok("C1c. rendered cobalt sweep: 0 refuted, 377 flagged, 250 silent, 0 confirmed",
       /pigment\s+refuted\s+0\s+flagged\s+377\s+silent\s+250\s+confirmed\s+0/.test(nodes.get("sweepout").textContent));
    ok("C1c. rendered plague sweep: 618 publication refutations, 9 silent, 0 confirmed",
       /plague\s+refuted\s+618\s+flagged\s+0\s+silent\s+9\s+confirmed\s+0/.test(nodes.get("sweepout").textContent));
    ok("C1c. rendered total includes all 3,762 settings and no confirmations",
       /TOTAL\s+refuted\s+1684\s+flagged\s+377\s+silent\s+1701\s+confirmed\s+0/.test(nodes.get("sweepout").textContent) &&
       nodes.get("sweepout").textContent.includes("3762 settings. The third lamp did not light."));
  } catch (e) {
    ok("C1c. shipped script executes with the page's actual element IDs", false, String(e.stack || e));
  }
}

// A6, page side: the soft row must be marked, not quietly relied on
ok("C. the page marks boredom's soft floor and gives the solid one",
   html.includes("at the solid 1844 its gap is not -23 but -8") &&
   html.includes("REFUTED under <em>both</em> years"));

// the load-bearing sentences, verbatim on the page
const SENTENCES = [
  ["the join's headline",
   "A refutation needs correct dates, identification and a justified inference. A match can be wrong when every measurement is right."],
  ["the concession that a one-sided date can still be mistaken",
   "an attestation can be misdated, a pigment misidentified, a document forged, a transcription misread, and then the red lamp lights on nothing"],
  ["the foil's named cause of its own false positives",
   "what happens when you take the best of several hundred tries and then apply a cutoff designed for one try"],
  ["the floor-is-under-the-searching line",
   "The floor you have found is a floor under your searching, not under the world."],
  ["the size-does-not-matter line",
   "Nothing in the verdict depends on the size of the number."],
  ["the dead socket's label", "no wire runs to this lamp"],
  ["the foil's false-positive count", "23 of those 48 certainly-wrong Alaskan matches"],
  ["the foil's separation figures", "t = 7.21"],
  ["the foil's control", "zero of 48"],
  ["the foil's flattening quote", "reads the same on the page whether it means a felled year or a floor"],
  ["the heartwood floor quote", "There is no upper bound at all."],
  ["the limit case's corpus size", "61,287"],
  ["the limit case's word count", "1,547,130,448"],
  ["the limit case's found attestation", "Gouernayle of Helthe"],
  ["the boredom floor's lowering", "1852 to 1844 to 1829"],
  ["the declared gap in the redshift member",
   "asserts quantities (velocities, rate constants, 24 of 46 nebulae with individual distances) and never compares two years"],
  ["the portal law", "It builds no new fact"],
];
for (const [what, s] of SENTENCES) ok(`C. page carries ${what}`, html.includes(s));

// C2. EVERY BORROWED QUOTATION, VERBATIM IN THE MEMBER IT IS ATTRIBUTED TO.
// The one unforgivable move here is a paraphrase presented as a quotation, so it
// gets its own gate: each string below is normalised (tags stripped, entities
// unescaped, curly punctuation folded, whitespace collapsed) on BOTH sides and
// must appear in the member page it is credited to on the portal.
{
  const norm = (s) => s
    // NB: <script> is deliberately NOT stripped. Two members build the sentence
    // this portal quotes at runtime from an inline string, so the only place the
    // words exist is the script block, and a check that skipped it would pass
    // vacuously on the very quotes most likely to drift.
    .replace(/<style[\s\S]*?<\/style>/g, " ")
    .replace(/<[^>]+>/g, " ")
    .replace(/&ldquo;|&rdquo;|&quot;/g, '"')
    .replace(/&lsquo;|&rsquo;|&#39;/g, "'")
    .replace(/&hellip;/g, "...")
    .replace(/&amp;/g, "&").replace(/&nbsp;/g, " ")
    .replace(/&mdash;/g, "\u2014")
    .replace(/[\u2018\u2019]/g, "'")
    .replace(/[\u201c\u201d]/g, '"')
    .replace(/\s+/g, " ")
    // markup inserts spaces where tags were, so normalise spacing AROUND
    // punctuation while preserving WHICH mark is there. An em dash silently
    // demoted to a comma inside a quotation still fails, which is the point.
    .replace(/\s*([,.;:!?"'\u2014])\s*/g, "$1")
    .trim();

  const QUOTES = [
    ["boredom-word", "The dates mix attestations, approximate eras, and the date of an engraving; none establishes a word’s birthday."],
    ["pigment-that-wasnt-born", "This comparison does not establish public availability or authenticate the painter."],
    ["a-minor-leonardo", "OCR errors and unrelated uses of a phrase can make counts understate or overstate artwork coverage."],
    ["the-dancing-plague", "No contemporary toll is documented; a later report and a conditional total are not a contemporary count."],
    ["let-them-eat-cake", "The chronology puts Rousseau's text before her arrival in France; it cannot prove that she could never have repeated an older sentence."],
    ["every-tree-wrote-the-same-bad-year", "a stretch of prehistory acquired exact years. Not a range. Years."],
    ["every-tree-wrote-the-same-bad-year", "There is no upper bound at all"],
    ["every-tree-wrote-the-same-bad-year",
     'reads the same on the page whether it means a felled year or a floor'],
    ["every-tree-wrote-the-same-bad-year",
     "what happens when you take the best of several hundred tries and then apply a cutoff designed for one try"],
    ["what-the-first-sleep-was-first-of",
     "That is a real counterexample to the sentence quoted above, found by a search rather than by memory"],
    ["what-the-first-sleep-was-first-of", "not discussed in manuals of health"],
    ["what-the-first-sleep-was-first-of", "And after thi fyrst slepe turne on thy lifte syde"],
    // Replaced 2026-10-18: the portal quoted "every second-sleep count on this page is a
    // floor", which that layer withdrew on 2026-10-14. These are its current words.
    ["what-the-first-sleep-was-first-of", "phrase counts do not count the practice"],
  ];
  const portal = norm(html);
  const cache = {};
  for (const [slug, q] of QUOTES) {
    const mp = join(ROOT, `public/strata/${slug}/index.html`);
    if (!cache[slug]) cache[slug] = existsSync(mp) ? norm(readFileSync(mp, "utf8")) : "";
    const inMember = cache[slug].includes(norm(q));
    const inPortal = portal.includes(norm(q));
    ok(`C2. verbatim in ${slug}: "${q.slice(0, 46)}..."`, inMember);
    ok(`C2. and the portal actually carries it`, inPortal);
  }
  // The old sentence remains intact, explicitly labelled as superseded.
  // Read its two original literals at the pinned revision, never from the current member.
  const historical = norm(execFileSync("git", ["show",
    "67088387e0:public/strata/pigment-that-wasnt-born/index.html"],
    { cwd: ROOT, encoding: "utf8", maxBuffer: 1024 * 1024 }));
  for (const fragment of ["It also does not prove the painter \u2014",
                          "material possibility is necessary, not sufficient."]) {
    ok("C2. retained pigment quotation is verbatim at its historical revision",
       historical.includes(norm(fragment)) && portal.includes(norm(fragment)));
  }
  ok("C2. the old pigment sentence is visibly labelled as superseded",
     html.includes("member wording before 2026-10-14, superseded; preserved verbatim") &&
     html.includes("c.quoteContext ||"));
  ok("C2. the retained earliest-availability quotation is historical",
     historical.includes(norm("if even the earliest date is after the claim, the anachronism is certain")) &&
     html.includes("That quotation is preserved verbatim as wording superseded on 2026-10-14."));
  // The sentence assembled from two literals is checked whole on this portal.
  // Superseded member claims corrected on 2026-10-14 must not survive outside the
  // dated Corrections lines that name them.
  const live = norm(html.replace(/<section class="app" aria-label="Corrections">[\s\S]*?<\/section>/, " "));
  ok("C2. no lower-bound guarantee for the Mona Lisa counts outside Corrections",
     !/lower bound/i.test(live) && live.includes(norm("understate or overstate")));
  ok("C2. the cake case claims an origin in France, not an impossible utterance",
     !live.includes(norm("could not have, and you don't have to take a historian's word")) && !live.includes(norm("Marie Antoinette said")) &&
     live.includes(norm("began with Marie Antoinette in France")) &&
     live.includes(norm("cannot rule out her repeating an older sentence later")));
  ok("C2. the portal preserves the historical pigment sentence joined",
     portal.includes(norm("It also does not prove the painter \u2014 material possibility is necessary, not sufficient.")));
  {
  }
}

// the first-sleep corpus figures the portal prints come from that layer's own
// numbers.json (its page slot-fills them at runtime, so they are not static HTML)
{
  const nj = join(ROOT, "public/strata/what-the-first-sleep-was-first-of/numbers.json");
  ok("C2. the first-sleep numbers file exists", existsSync(nj));
  if (existsSync(nj)) {
    const n = JSON.parse(readFileSync(nj, "utf8")).corpus;
    ok("C2. corpus texts 61,287 as the portal prints", n.texts === 61287, `${n.texts}`);
    ok("C2. corpus words 1,547,130,448 as the portal prints", n.words === 1547130448, `${n.words}`);
    ok("C2. corpus range 1473 to 1810 as the portal prints",
       n.yearMin === 1473 && n.yearMax === 1810, `${n.yearMin}-${n.yearMax}`);
  }
}

// C3. THE COUNTS THE PAGE ASSERTS ABOUT ITSELF.
// The portal walks EIGHT layers: six comparisons on the sorted axis, one limit
// case (an absence claim has no year, so no gap) and one foil. An earlier draft
// said "seven" in nine places, which quietly wrote the foil out of the set whose
// numbers it borrows, so the count is pinned here.
{
  const LIMIT = "what-the-first-sleep-was-first-of";
  const FOIL  = "every-tree-wrote-the-same-bad-year";
  const walked = MEMBERS.length + 2;
  ok("C3. the portal walks eight layers", walked === 8, `${MEMBERS.length} + limit + foil`);
  ok("C3. the page says eight, not seven", html.includes("a combine across eight layers"));
  ok("C3. no stray 'seven layers' or 'seven member' survives",
     !/seven layers|seven member|these seven|the seven /.test(html));
  ok("C3. the page links the limit case", html.includes(`/strata/${LIMIT}/`));
  ok("C3. the page links the foil", html.includes(`/strata/${FOIL}/`));
  ok("C3. the page reports the column in three values",
     html.includes("<b>Four say yes</b>") && html.includes("<b>One says partly:</b>") &&
     html.includes("<b>One says no:</b>"));
  ok("C3. and no longer claims seven of eight",
     !html.includes("Seven of the eight do.") && !html.includes("Five of seven assert it."));
}

// C4. WHICH MEMBERS ARE DOUBLED, AND WHEN THAT WAS TRUE. The page does not claim
// its eight layers are walked by nobody else; it states the overlap, and the
// overlap is a checkable fact about the repository, so it is checked rather than
// asserted. Every portal-tagged stratum's frontmatter, its immersive page AND its
// sibling data files are searched for each member.
//
// WHY THIS CHECK IS A TRIPWIRE, NOT A CONSTANT (2026-08-21). A portal's count over
// the corpus expires without anyone touching the page: the archive keeps growing,
// and an older portal can fold in a member years after this one counted it. That is
// exactly what happened. The Anatomy of Error (frontmatter date 2026-06-29, so older
// than this page) added the-dancing-plague to its data.json on 2026-08-02, five days
// AFTER this page shipped on 2026-07-28 (git: 6f368e8e2, "89 record-corrections,
// relabelled blind"). The note written here on 2026-08-21 said it had added
// boredom-word that day; that was wrong (corrected 2026-10-18, assay line): its
// data.json had carried boredom-word, let-them-eat-cake, a-minor-leonardo and
// who-discovered-the-expanding-universe as cards since before this page shipped,
// and what changed on 2026-08-02 was the dancing-plague card plus a prose link to
// /strata/boredom-word/. This check could not see the cards, because a JSON card
// is written "slug": "x" and none of the patterns below matched that form, so it
// counted five pairings at ship and six on 2026-08-21 while the cards gave nine and
// ten. The JSON form is matched now. The distinct-member count was five throughout.
//
// THE FIX ON THE PAGE. The bullet no longer states a bare present-tense count, which
// is a claim with an unwritten expiry date. It states two dated facts that can never
// rot (what was true on 2026-07-28, and what The Anatomy of Error did on 2026-08-02)
// plus one live tally explicitly scoped by date ("as of 2026-10-18" since the 2026-10-18
// correction; it said "as of 2026-08-21" before). The live tally is not
// typed twice: it is REBUILT below from the set this check just computed, so the page
// and the checker cannot drift apart. If the corpus moves again, the expected list
// below fails first and a human has to look, which is the point.
{
  const stratDir = join(ROOT, "src/content/strata");
  const files = readdirSync(stratDir).filter(f => f.endsWith(".md"));
  const portals = files.filter(f => readFileSync(join(stratDir, f), "utf8").includes('"portal"'));
  ok("C4. the archive has more than fifty portals to diverge from", portals.length > 50, `${portals.length}`);
  const all = [...MEMBERS.map(m => m.slug),
               "what-the-first-sleep-was-first-of", "every-tree-wrote-the-same-bad-year"];
  const doubled = [];
  for (const f of portals) {
    const slug = f.slice(0, -3);
    if (slug === "the-date-that-can-only-say-no") continue;
    let blob = readFileSync(join(stratDir, f), "utf8");
    const dir = join(ROOT, `public/strata/${slug}`);
    // THE SECOND PLACE THE WALKING HIDES (added 2026-08-21): a portal can keep its
    // card list in a sibling data.json that index.html fetches at runtime, so the
    // shipped HTML names nobody. The Anatomy of Error is built that way, and this
    // check caught its boredom-word card only by accident, through one prose link in
    // the body text. Read the whole directory, not just index.html.
    if (existsSync(dir)) for (const g of readdirSync(dir)) {
      if (/\.(html|json|js|mjs)$/.test(g)) blob += readFileSync(join(dir, g), "utf8");
    }
    for (const m of all) {
      // THE BUG THIS REPLACES: portals build their links at runtime from a slug
      // list, so `/strata/<slug>/` never appears in their source and a search for
      // it comes back clean. The slug list is where the walking actually is.
      if (blob.includes(`to: ${m}\n`) || blob.includes(`/strata/${m}/`) ||
          blob.includes(`slug:"${m}"`) || blob.includes(`slug: "${m}"`) ||
          blob.includes(`slug:'${m}'`) ||
          // added 2026-10-18 (assay line): a JSON card, as in a sibling data.json
          blob.includes(`"slug": "${m}"`) || blob.includes(`"slug":"${m}"`)) doubled.push(`${slug} -> ${m}`);
    }
  }
  const expected = [
    "repeated-until-true -> boredom-word",
    "repeated-until-true -> let-them-eat-cake",
    "repeated-until-true -> who-discovered-the-expanding-universe",
    "repeated-until-true -> a-minor-leonardo",
    "what-the-ground-cant-say -> the-dancing-plague",
    // The Anatomy of Error's data.json cards: the first four before this page shipped,
    // the dancing plague from 2026-08-02. Counted from 2026-10-18; see the note above.
    "the-anatomy-of-error -> boredom-word",
    "the-anatomy-of-error -> let-them-eat-cake",
    "the-anatomy-of-error -> a-minor-leonardo",
    "the-anatomy-of-error -> who-discovered-the-expanding-universe",
    "the-anatomy-of-error -> the-dancing-plague",
  ].sort();
  const got = [...new Set(doubled)].sort();
  ok("C4. ten portal-member pairings over five distinct members, and these are they",
     got.length === expected.length && got.every((d, i) => d === expected[i]),
     got.join(" | ") || "none");

  // Every portal in that set really is older than this page, so "appeared before"
  // is a statement about the record and not about which file was edited last.
  const dateOf = s => (readFileSync(join(stratDir, `${s}.md`), "utf8")
                        .match(/^date:\s*"?(\d{4}-\d{2}-\d{2})/m) || [])[1];
  const SHIPPED = dateOf("the-date-that-can-only-say-no");
  const walkers = [...new Set(got.map(d => d.split(" -> ")[0]))].sort();
  ok("C4. every portal in the overlap set is older than this page",
     SHIPPED === "2026-07-28" && walkers.every(p => dateOf(p) < SHIPPED),
     walkers.map(p => `${p} ${dateOf(p)}`).join(" | ") + ` < ${SHIPPED}`);

  // The page's live tally, rebuilt from the set above rather than typed twice.
  const WORD = ["zero", "one", "two", "three", "four", "five", "six", "seven",
                "eight", "nine", "ten", "eleven", "twelve"];
  const members = new Set(got.map(d => d.split(" -> ")[1]));
  const tally = `as of 2026-10-18 the overlap is ${WORD[got.length]} portal-member pairings `
              + `across ${WORD[walkers.length]} portals, over ${WORD[members.size]} `
              + `distinct members of the eight.`;
  ok("C4. the page states the overlap rather than claiming no layer is doubled",
     html.includes("Five of the eight had already appeared as single cards when this page shipped on 2026-07-28") &&
     !html.includes("None of the eight members has been walked"));
  ok("C4. and its live tally is scoped to a date and matches the set just computed",
     html.includes(tally), tally);
  ok("C4. and it names all three portals that walked them",
     html.includes("/strata/repeated-until-true/") && html.includes("/strata/what-the-ground-cant-say/") &&
     html.includes("/strata/the-anatomy-of-error/"));
}

// the divergences the portal law requires it to declare
for (const slug of ["the-number-that-ends-the-argument", "the-auditor-that-wants-nothing",
                    "repeated-until-true", "the-anatomy-of-error", "what-the-ground-cant-say"]) {
  ok(`C. divergence declared against ${slug}`, html.includes(`/strata/${slug}/`));
}

// house rules
// House rule (2026-07-14): no em dash in OUR prose. It survives exactly where it
// is a source's own choice, and editing a source's dash would turn "verbatim"
// into a lie, so the rule and the never-lie rule point the same way here. Every
// em dash on this page must therefore sit on a line marked em-dash-ok, and each
// such line must be one of the verbatim quotations checked in C2 above.
{
  const lines = html.split("\n");
  const dashed = lines.filter(l => l.includes("\u2014") || l.includes("&mdash;"));
  const unmarked = dashed.filter(l => !/em-dash-ok/.test(l));
  ok("C. every em dash on the page is a source's own, marked em-dash-ok",
     unmarked.length === 0, `${dashed.length} marked, ${unmarked.length} unmarked`);
  ok("C. and each marked line is one of the verbatim-checked quotations",
     dashed.every(l => /quote:'/.test(l)), `${dashed.length} lines`);
}
ok("C. canonical way-out footer present", html.includes('class="aw-wayout"'));
ok("C. canonical top bar present", html.includes("/media/home-banner.js"));
ok("C. canonical URL declared", html.includes('href="https://artwaste.land/strata/the-date-that-can-only-say-no/"'));

// the frontmatter that puts it on the ground
const MD = join(ROOT, "src/content/strata/the-date-that-can-only-say-no.md");
ok("C. the frontmatter file exists", existsSync(MD));
{
  const md = readFileSync(MD, "utf8");
  ok("C. frontmatter declares the href", md.includes('href: "/strata/the-date-that-can-only-say-no/"'));
  ok("C. frontmatter is tagged portal", md.includes('"portal"'));
  const rel = (md.match(/^\s+- to: (\S+)/gm) || []).map(s => s.trim().slice(6));
  for (const m of MEMBERS) ok(`C. frontmatter relates to ${m.slug}`, rel.includes(m.slug));
  for (const s of ["what-the-first-sleep-was-first-of", "every-tree-wrote-the-same-bad-year"])
    ok(`C. frontmatter relates to ${s}`, rel.includes(s));
  ok("C. frontmatter declares the two inversions it diverges from",
     rel.includes("the-number-that-ends-the-argument") && rel.includes("the-auditor-that-wants-nothing"));
}

// ============================================================================
console.log("\n── D. every member's own verifier, re-run end to end ──\n");
// ============================================================================

// Pass totals can change as members add checks; zero failures must not.
const MEMBER_CHECKS = [
  ["pigment-that-wasnt-born",
   "research/pigment-that-wasnt-born/verify-pigment-that-wasnt-born.mjs", [], "ALL CHECKS PASSED"],
  ["boredom-word",
   "research/boredom-word/build.mjs", [], "OK  OED first citation (1852) above its lowest antedating (1829) = 23"],
  ["let-them-eat-cake",
   "research/let-them-eat-cake/verify.mjs", [], "ALL CHECKS PASS"],
  ["who-discovered-the-expanding-universe",
   "research/who-discovered-the-expanding-universe/verify-who-discovered-the-expanding-universe.mjs", [], "ALL CHECKS PASSED"],
  ["the-dancing-plague",
   "research/the-dancing-plague/verify.mjs", [], "ALL CHECKS PASSED"],
  ["a-minor-leonardo",
   "research/a-minor-leonardo/verify-a-minor-leonardo.mjs", [], /^✓ ALL (\d+)\/\1 checks passed\.$/m],
  ["a-minor-leonardo (immersive)",
   "research/a-minor-leonardo/verify-immersive.mjs", [], /^\d+ passed, 0 failed$/m],
  ["what-the-first-sleep-was-first-of",
   "verify-what-the-first-sleep-was-first-of.mjs", ["--no-net"], /^\d+ passed, 0 failed$/m],
  ["every-tree-wrote-the-same-bad-year (foil)",
   "research/every-tree-wrote-the-same-bad-year/verify-every-tree-wrote-the-same-bad-year.mjs",
   ["--no-net"], "0 failures"],
];

if (FAST) {
  console.log("  (skipped: --fast)\n");
} else {
  for (const [name, rel, args, passLine] of MEMBER_CHECKS) {
    const p = join(ROOT, rel);
    if (!existsSync(p)) { ok(`D. ${name}: verifier present`, false, rel); continue; }
    let out = "", code = 0;
    try {
      out = execFileSync(process.execPath, [p, ...args], {
        cwd: ROOT, encoding: "utf8", timeout: 900_000, maxBuffer: 64 * 1024 * 1024,
      });
    } catch (e) {
      code = e.status ?? 1;
      out = (e.stdout || "") + (e.stderr || "");
    }
    ok(`D. ${name}: exits clean`, code === 0, `exit ${code}`);
    ok(`D. ${name}: reports its own pass line`,
       passLine instanceof RegExp ? passLine.test(out) : out.includes(passLine), String(passLine));
  }
}

// ============================================================================
console.log("\n" + "=".repeat(66));
console.log(`${pass} passed, ${fail} failed`);
console.log(fail === 0 ? "ALL CHECKS PASSED" : "FAILURES ABOVE");
process.exit(fail === 0 ? 0 : 1);
