#!/usr/bin/env node
/* Read-only verifier. --ledger prints computed ledger values. --mutate runs in-memory negative controls. */
import { createHash } from 'node:crypto';
import { readFile } from 'node:fs/promises';
import { existsSync } from 'node:fs';
import path from 'node:path';
import process from 'node:process';
import { isDeepStrictEqual } from 'node:util';
import { fileURLToPath } from 'node:url';
import { HOME, TARGET, TARGET_FIXTURE, ADAPTER, DROPPED, CONVENTIONS, OUTCOME_COPY } from '../../public/strata/darwin-had-no-global-clock/data.js';
import {
  calibrate, homeViewModel, vectorLess, runTarget, verdictFor, cycleFault,
  blindSpotFault, ablateTarget, transferLedger
} from '../../public/strata/darwin-had-no-global-clock/engine.js';

const here = path.dirname(fileURLToPath(import.meta.url));
const repo = path.resolve(here, '../..');
const files = {
  html: path.join(repo, 'public/strata/darwin-had-no-global-clock/index.html'),
  render: path.join(repo, 'public/strata/darwin-had-no-global-clock/render.js'),
  data: path.join(repo, 'public/strata/darwin-had-no-global-clock/data.js'),
  engine: path.join(repo, 'public/strata/darwin-had-no-global-clock/engine.js'),
  share: path.join(repo, 'public/strata/darwin-had-no-global-clock/share.svg'),
  publicAudit: path.join(repo, 'public/strata/darwin-had-no-global-clock/target-audit.json'),
  audit: path.join(here, 'data/audit.json'),
  sample: path.join(here, 'data/sample.csv'),
  collision: path.join(repo, 'public/strata/darwin-had-no-global-clock/collision.json'),
  frontmatter: path.join(repo, 'src/content/strata/darwin-had-no-global-clock.md'),
  readme: path.join(here, 'README.md'),
  extractor: path.join(here, 'extract-audit.mjs')
};

const expected = {
  slug: 'darwin-had-no-global-clock',
  title: 'Darwin Had No Global Clock',
  seoTitle: 'Why This Epsilon Darwin Export Cannot Run a Vector Clock',
  dek: 'The pinned Epsilon darwin-correspondence collection has 15,238 letters, but its bulk metadata does not establish date-independent local order or matched receive events. Date provenance is unaudited, so an independent target is also unavailable. The separate 1,536-letter darwin-family-letters collection is outside this audit.',
  plain: 'Vector clocks require participant-local event order and matched send and receive events. This page audits the pinned Epsilon darwin-correspondence collection, not the separate darwin-family-letters collection, and finds that its 15,238 bulk records cannot construct a vector clock or provide an independently audited accuracy target.',
  headline: 'No target clock can be built from the audited darwin-correspondence export.',
  canonical: 'https://artwaste.land/strata/darwin-had-no-global-clock/',
  image: 'https://artwaste.land/strata/darwin-had-no-global-clock/share.svg',
  auditSha: '76dbf44d82f07e08df27247920a528d614b2000f1732d30d3dbf0e2548a95db6',
  vectors: {
    p1: [1, 0, 0], p2: [2, 1, 0], p3: [3, 1, 0], p4: [4, 5, 0],
    q1: [0, 1, 0], q2: [1, 2, 0], q3: [1, 3, 0], q4: [1, 4, 0],
    q5: [1, 5, 0], q6: [1, 6, 0], q7: [1, 7, 2],
    r1: [0, 0, 1], r2: [0, 0, 2], r3: [1, 4, 3], r4: [1, 4, 4]
  }
};

const raw = {};
for (const [key, filename] of Object.entries(files)) raw[key] = await readFile(filename, 'utf8');
const audit = JSON.parse(raw.audit);
const publicAudit = JSON.parse(raw.publicAudit);
const collision = JSON.parse(raw.collision);

function sha256(text) { return createHash('sha256').update(text).digest('hex'); }
function same(a, b) { return isDeepStrictEqual(a, b); }
function invariant(condition, message) { if (!condition) throw new Error(message); }
function compactHtml(text) { return text.replace(/<[^>]*>/g, ' ').replace(/&middot;/g, '·').replace(/\s+/g, ' ').trim(); }
function attr(text, selector) {
  const escaped = selector.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  const tag = text.match(new RegExp(`<meta[^>]+(?:name|property)="${escaped}"[^>]*>`, 'i'))?.[0];
  return tag?.match(/content="([^"]*)"/i)?.[1] ?? null;
}
function frontmatterScalar(text, key) { return text.match(new RegExp(`^${key}: "([^"]*)"$`, 'm'))?.[1] ?? null; }
function claimMap(text, attribute) {
  const result = new Map();
  const regex = new RegExp(`<[^>]+${attribute}="([^"]+)"[^>]*>([\\s\\S]*?)<\\/[^>]+>`, 'g');
  for (const match of text.matchAll(regex)) result.set(match[1], compactHtml(match[2]));
  return result;
}

function independentGraph(home) {
  const events = Object.values(home.processes).flat();
  const edges = [];
  for (const sequence of Object.values(home.processes)) {
    for (let i = 1; i < sequence.length; i += 1) edges.push([sequence[i - 1], sequence[i]]);
  }
  for (const edge of home.messages) edges.push(edge.slice());
  const matrix = Object.fromEntries(events.map((a) => [a, Object.fromEntries(events.map((b) => [b, false]))]));
  for (const [a, b] of edges) matrix[a][b] = true;
  for (const k of events) for (const i of events) for (const j of events) matrix[i][j] ||= matrix[i][k] && matrix[k][j];
  return { events, edges, matrix };
}

function homeEvidence(home = HOME, computed = calibrate(home)) {
  try {
    const reference = independentGraph(home);
    invariant(reference.events.length === 15 && reference.edges.length === 18, 'home: fixture shape');
    invariant(same(computed.vectors, expected.vectors), 'home: exact vectors');
    invariant(same(home.expectedVectors, expected.vectors), 'home: expected vector fixture');
    let comparisons = 0;
    let mismatches = 0;
    for (const a of reference.events) for (const b of reference.events) {
      if (a === b) continue;
      comparisons += 1;
      if (vectorLess(computed.vectors[a], computed.vectors[b]) !== reference.matrix[a][b]) mismatches += 1;
    }
    const view = homeViewModel(computed);
    invariant(comparisons === 210 && view.orderedPairs === 210 && view.unorderedPairs === 105, 'home: pair denominators');
    invariant(mismatches === 0 && computed.mismatches === 0 && view.passes, 'home: vector and graph identity');
    invariant(computed.comparable === 58 && computed.incomparable === 47, 'home: pair partition');
    invariant(computed.p1BeforeR4 && computed.p3ConcurrentQ3, 'home: named relations');
    return true;
  } catch { return false; }
}

function adapterEvidence(value = audit) {
  try {
    invariant(value.schema === 2 && value.sourceCommit === TARGET.commit, 'adapter: schema and commit');
    invariant(same(value.counts, TARGET.counts), 'adapter: frozen audit counts');
    invariant(same(value.auditWork, TARGET.auditWork), 'adapter: provenance work ledger');
    invariant(value.counts.csvRows === value.counts.xmlFiles && value.counts.csvXmlIdMatches === value.counts.xmlFiles, 'adapter: CSV and TEI bijection');
    invariant(value.scope.includedCollection === TARGET.collection, 'scope: included collection');
    invariant(value.scope.includedCsvRows === 15238 && value.scope.includedXmlFiles === 15238, 'scope: included counts');
    invariant(value.scope.excludedCollection === TARGET.excludedCollection.id, 'scope: excluded collection');
    invariant(value.scope.excludedCsvRows === 1536 && value.scope.excludedXmlFiles === 1536, 'scope: excluded counts');
    invariant(value.archive.bytes === TARGET.archiveBytes && value.archive.sha256 === TARGET.archiveSha256, 'adapter: archive identity');
    invariant(value.archive.httpStatus === 200 && value.archive.entries === 77447 && value.archive.expandedBytes === 204347124, 'adapter: archive transport and expansion');
    return true;
  } catch { return false; }
}

function faultEvidence() {
  const fault = cycleFault(HOME);
  return fault.caught && fault.includesInjectedEdge && fault.cycle === 'p1 -> q2 -> q3 -> q4 -> r3 -> r4 -> p1';
}
function blindEvidence(fault = blindSpotFault(TARGET_FIXTURE)) {
  return fault.invisible && fault.metadataChanged && fault.positiveLeakageControlCaught &&
    fault.before.runnable && fault.after.runnable && same(fault.before.computation.vectors, fault.after.computation.vectors);
}
function ledgerValues() { return transferLedger(HOME, TARGET, TARGET_FIXTURE); }

if (process.argv.includes('--ledger')) {
  for (const [key, value] of Object.entries(ledgerValues())) process.stdout.write(`${key}=${value}\n`);
  process.exit(0);
}

function checkTargetModel(target = TARGET) {
  const strict = runTarget(target);
  invariant(!('requirements' in target), 'target: no hand-set requirement booleans');
  invariant(!strict.engineConstructible && !strict.targetEvaluable && !strict.runnable, 'target: split null result');
  invariant(strict.evidence.localOrder.status === 'unaudited', 'target: local order is unaudited');
  invariant(strict.evidence.matchedReceives.status === 'missing', 'target: matched receives are missing');
  invariant(strict.evidence.independentTarget.status === 'unaudited', 'target: independent target is unaudited');
  invariant(same(strict.unresolved, ['localOrder', 'matchedReceives', 'independentTarget']), 'target: unresolved evidence');
  const conjectural = runTarget(target, { mode: 'conjectural' });
  invariant(conjectural.conjecturalCandidates === 730 && !conjectural.runnable, 'target: conjectural data-layer mode');
  const leaked = runTarget(target, { leakEditorialDates: true });
  invariant(leaked.evidence.localOrder.status === 'leaked' && !leaked.runnable, 'target: editorial leakage stays invalid');
  const fakeReceiveTarget = structuredClone(target);
  fakeReceiveTarget.auditWork.matchedReceiveEventsAccepted = 1;
  invariant(!runTarget(fakeReceiveTarget).engineConstructible, 'target: fake receive cannot resolve local order');
  const withAddress = { ...target, displayAddress: 'Down' };
  const withoutAddress = { ...withAddress };
  delete withoutAddress.displayAddress;
  invariant(same(runTarget(withAddress), runTarget(withoutAddress)), 'target: address metadata is outside the engine');
  const fixture = runTarget(TARGET_FIXTURE);
  invariant(fixture.runnable && fixture.computation?.mismatches === 0, 'target: complete fixture uses real engine path');
  invariant(verdictFor(TARGET_FIXTURE, { baselineDistinct: true, independentAgrees: true }) === 'HELD', 'target: held branch');
  invariant(verdictFor(TARGET_FIXTURE, { baselineDistinct: false, independentAgrees: true }) === 'BROKE', 'target: broke branch');
  invariant(verdictFor(target, { baselineDistinct: true, independentAgrees: true }) === 'UNDERDETERMINED', 'target: null branch');
  for (const key of ['HELD', 'BROKE', 'UNDERDETERMINED']) {
    invariant(same(Object.keys(OUTCOME_COPY[key]), ['label', 'headline', 'dek', 'promise', 'targetIntro', 'targetExplanation', 'ablationIntro', 'footer']), `target: complete ${key} copy`);
  }
}

function checkAblations(value = collision) {
  invariant(value.ablations.length === ADAPTER.length, 'ablation: one result per mapping');
  for (let i = 0; i < ADAPTER.length; i += 1) {
    const id = ADAPTER[i].id;
    const actual = ablateTarget(TARGET, id);
    invariant(actual.before.activeMappings.includes(id) && !actual.after.activeMappings.includes(id), `ablation: active state ${id}`);
    invariant(actual.after.mappingInstances[id] === 0, `ablation: instances removed ${id}`);
    invariant(value.ablations[i].disabled === id, `ablation: manifest identity ${id}`);
    for (const field of ['result', 'exercised', 'removedInstances', 'survives']) invariant(same(value.ablations[i][field], actual[field]), `ablation: manifest ${id} ${field}`);
  }
  const fixtureEffects = Object.fromEntries(['document-id', 'author-process', 'recipient-process', 'exact-reference', 'independent-date'].map((id) => [id, ablateTarget(TARGET_FIXTURE, id)]));
  for (const id of ['document-id', 'author-process', 'recipient-process', 'exact-reference']) invariant(!fixtureEffects[id].after.engineConstructible, `ablation: complete fixture construction changes for ${id}`);
  invariant(fixtureEffects['independent-date'].after.engineConstructible && !fixtureEffects['independent-date'].after.targetEvaluable, 'ablation: construction and evaluation split');
  let rejectedUnknown = false;
  try { ablateTarget(TARGET, 'unknown-mapping'); } catch { rejectedUnknown = true; }
  invariant(rejectedUnknown, 'ablation: unknown mapping rejected');
}

function checkSurface(html = raw.html, render = raw.render) {
  const claims = claimMap(html, 'data-claim');
  const expectedClaims = {
    'ordered-pairs': '210', 'xml-files': '15,238', 'excluded-letters': '1,536',
    'received-actions': '15,237', 'receive-dates': '0', 'unbracketed-point-dates': '7,219',
    'point-dates': '13,934', 'interval-dates': '1,304', 'zero-vector': '[0,0,0]',
    commit: TARGET.commit, 'http-status': '200', 'archive-bytes': '93,705,444',
    'expanded-bytes': '204,347,124', 'archive-entries': '77,447', 'archive-sha': TARGET.archiveSha256,
    licence: 'CC BY-NC 4.0', retrieved: '10 September 2026', 'csv-bytes': '2,348,852',
    'csv-rows': '15,238', 'audit-xml': '15,238', 'excluded-audit-xml': '1,536',
    'sent-dates': '15,238', 'audit-received': '15,237', 'audit-receive-date': '0', contexts: '0',
    'empty-bodies': '15,238', 'nonempty-bodies': '0', abstracts: '15,229', 'reply-like': '730',
    'id-matches': '15,238', 'scout-sha': TARGET.scoutMainArchiveSha256
  };
  invariant(claims.size === Object.keys(expectedClaims).length, 'surface: unexpected or missing frozen claim');
  for (const [key, value] of Object.entries(expectedClaims)) invariant(claims.get(key) === value, `surface: ${key}`);
  invariant(html.includes(`<h1>${expected.title}</h1>`), 'surface: h1');
  invariant(html.includes(`<p class="headline" id="outcomeHeadline">${expected.headline}</p>`), 'surface: outcome headline');
  invariant(html.includes('The result is underdetermined, not zero percent.'), 'surface: null not scored');
  invariant(html.includes('No chronology percentage will appear because no honest eligible-pair denominator exists.'), 'surface: no false denominator');
  invariant(html.includes('secondary theorem and implementation check') && html.includes('documentary-critical interval chronology'), 'surface: baseline framing');
  invariant(html.includes('66.667% to 100%') && html.includes('33.333 percentage-point adapter sensitivity'), 'surface: spot-check sensitivity');
  invariant(html.includes('structurally empty placeholder bodies'), 'surface: body wording');
  invariant(html.includes(`href="${TARGET.url}"`), 'surface: archive URL');
  invariant(!html.includes('10.1017/S0960116313000213'), 'surface: false Darwin DOI removed');
  for (const row of ADAPTER) invariant(html.includes(row.source) && html.includes(row.formal) && html.includes(row.loses), `surface: adapter ${row.id}`);
  for (const item of DROPPED) invariant(html.toLowerCase().includes(item.toLowerCase()), `surface: dropped ${item}`);
  for (const item of CONVENTIONS) invariant(html.includes(item), `surface: convention ${item}`);
  const vectors = claimMap(html, 'data-vector');
  invariant(vectors.size === 15 && [...vectors.values()].every((value) => value === 'pending'), 'surface: vectors are runtime-bound placeholders');
  const dynamicIds = ['comparableLive', 'incomparableLive', 'mismatchesLive', 'eventsLive', 'unorderedLive', 'homeMismatchesLive', 'publishedP1Live', 'publishedP3Live'];
  for (const id of dynamicIds) invariant(html.includes(`id="${id}"`) && render.includes(`$('${id}').textContent`), `surface: live binding ${id}`);
  for (const event of Object.keys(expected.vectors)) invariant(render.includes('document.querySelector(`[data-vector="${event}"]`)'), 'surface: vector binding loop');
  invariant(/async function runHome\(\)[\s\S]*result = calibrate\(HOME\)/.test(render), 'surface: action recomputes home');
  invariant(/function updatePair\(\)[\s\S]*?if \(a === b\) \{[\s\S]*?Same event\. Strict order and concurrency are not scored\./.test(render), 'surface: self-pair equality');
  invariant(render.includes("Graph diagnostic hidden, so no tie verdict is shown."), 'surface: hidden baseline has no tie claim');
  invariant(render.includes("ablateTarget(TARGET, id") && render.includes('UNEXERCISED'), 'surface: real ablation binding');
  invariant(render.includes("runTarget(TARGET, { mode") && render.includes('conjecturalCandidates'), 'surface: sensitivity binding');
  for (const id of ['verdictLabel', 'outcomeHeadline', 'outcomeDek', 'outcomePromise', 'targetIntro', 'targetExplanation', 'ablationIntro', 'footerOutcome']) invariant(render.includes(`${id}: copy.`), `surface: outcome binding ${id}`);
}

function checkHead(html = raw.html, frontmatter = raw.frontmatter) {
  invariant(html.match(/<title>([^<]+)<\/title>/)?.[1] === expected.seoTitle, 'head: title');
  invariant(attr(html, 'description') === expected.dek, 'head: description');
  invariant(html.includes(`<link rel="canonical" href="${expected.canonical}"`), 'head: canonical');
  invariant(attr(html, 'og:title') === expected.seoTitle && attr(html, 'twitter:title') === expected.seoTitle, 'head: social titles');
  invariant(attr(html, 'og:description') === expected.dek && attr(html, 'twitter:description') === expected.dek, 'head: social descriptions');
  invariant(attr(html, 'og:url') === expected.canonical, 'head: OG URL');
  invariant(attr(html, 'og:image') === expected.image && attr(html, 'twitter:image') === expected.image, 'head: social images');
  invariant(html.match(/name="aw-plain" content="([^"]+)"/)?.[1] === expected.plain, 'head: plain placard');
  for (const [key, value] of Object.entries({ title: expected.title, seoTitle: expected.seoTitle, dek: expected.dek, plain: expected.plain })) invariant(frontmatterScalar(frontmatter, key) === value, `frontmatter: ${key}`);
  invariant(expected.plain.length >= 90 && expected.plain.length <= 420, 'frontmatter: plain length');
  const jsonLd = JSON.parse(html.match(/<script type="application\/ld\+json">([\s\S]*?)<\/script>/)?.[1]);
  invariant(jsonLd['@type'] === 'Article' && jsonLd.name === expected.seoTitle && jsonLd.headline === expected.title, 'JSON-LD: identity');
  invariant(jsonLd.description === expected.dek && jsonLd.url === expected.canonical && jsonLd.image === expected.image, 'JSON-LD: surfaces');
  invariant(raw.share.includes('width="1200"') && raw.share.includes('height="630"') && raw.share.includes('<title id="title">Darwin Had No Global Clock</title>'), 'head: share asset exists and is 1200 by 630');
}

function checkCollision(value = collision) {
  invariant(value.slug === expected.slug && value.title === expected.title && value.href === '/strata/darwin-had-no-global-clock/', 'collision: identity');
  invariant(value.home.agrees === homeEvidence(), 'collision: home result');
  invariant(value.target.collection === audit.scope.includedCollection && value.target.rows === audit.scope.includedXmlFiles, 'collision: target scope');
  invariant(value.target.excluded_collection === audit.scope.excludedCollection && value.target.excluded_rows === audit.scope.excludedXmlFiles, 'collision: excluded scope');
  invariant(value.target.auditSha256 === sha256(raw.audit) && value.target.archiveSha256 === audit.archive.sha256, 'collision: labeled checksums');
  invariant(value.target.url === TARGET.url && value.target.licence === TARGET.licence, 'collision: source');
  invariant(same(value.adapter.map((row) => row.source), ADAPTER.map((row) => row.source)), 'collision: adapter sources');
  invariant(same(value.adapter.map((row) => row.formal), ADAPTER.map((row) => row.formal)), 'collision: adapter formals');
  invariant(same(value.adapter.map((row) => row.loses), ADAPTER.map((row) => row.loses)), 'collision: adapter losses');
  invariant(same(value.dropped, DROPPED) && same(value.hand_conventions, CONVENTIONS), 'collision: omissions and conventions');
  invariant(value.baseline.name === 'documentary-critical interval chronology' && value.baseline.score === null, 'collision: native baseline');
  invariant(value.same_edge_diagnostic.score === 0, 'collision: same-edge diagnostic');
  invariant(value.verdict === verdictFor(TARGET) && value.verdict_sentence === expected.headline, 'collision: verdict');
  checkAblations(value);
  for (const [key, computed] of Object.entries(ledgerValues())) invariant(value.ledger[key].value === computed, `collision: ledger ${key}`);
}

function checkLedgerSurface(html = raw.html, render = raw.render) {
  const shown = claimMap(html, 'data-ledger');
  invariant(shown.size === 6 && [...shown.values()].every((value) => value === 'pending'), 'surface: ledger placeholders');
  invariant(render.includes('transferLedger(HOME, TARGET, TARGET_FIXTURE)'), 'surface: ledger engine binding');
  for (const key of Object.keys(ledgerValues())) invariant(html.includes(`data-ledger="${key}"`), `surface: ledger ${key}`);
}

function checkRelations() {
  const related = Array.from(raw.frontmatter.matchAll(/^  - to: ([^\n]+)$/gm)).map((match) => match[1].replaceAll('"', '').trim());
  invariant(related.length === 4, 'frontmatter: four relates edges');
  // A related slug is a layer when its markdown is in the repository (2026-10-18: this read a .wave/ scratch index
  // that existed only in the checkout that built the page, so the check could run nowhere else).
  for (const slug of related) invariant(existsSync(path.join(repo, 'src/content/strata', `${slug}.md`)), `frontmatter: missing related slug ${slug}`);
}

function checkRuntime() {
  // ⚠ The site's chrome generators inject `/media/home-banner.js` into every shipped page at
  // build time, so an exact script inventory measures the chrome and not this page. The claim
  // this assertion was written to make is about the page's OWN scripts: one JSON-LD block and
  // one module from its own directory, and nothing else of its own. Count those.
  const ownScripts = (raw.html.match(/<script\b[^>]*>/g) || [])
    .filter((tag) => !/\bsrc="\/(?:media|_kit)\//.test(tag));
  invariant(ownScripts.length === 2 && raw.html.includes('<script type="module" src="./render.js"></script>'), 'runtime: scripts');
  invariant(!ownScripts.some((tag) => !/^<script(?: type="application\/ld\+json"| type="module" src=)/i.test(tag)), 'runtime: no executable inline script');
  invariant(raw.html.endsWith('</html>\n') && raw.html.includes('prefers-reduced-motion:reduce') && raw.html.includes(':focus-visible'), 'runtime: document and accessibility shape');
  invariant((raw.html.match(/role="status"/g) || []).length >= 5, 'runtime: status regions');
  const executable = `${raw.render}\n${raw.engine}`;
  invariant(!/\b(?:fetch|XMLHttpRequest|WebSocket|EventSource|sendBeacon|Worker|importScripts)\b/.test(executable), 'runtime: no network API');
  invariant(!/(?:\.src|\.href)\s*=|setAttribute\(\s*['"](?:src|href)['"]/.test(executable), 'runtime: no resource assignment sink');
  invariant(!/https?:\/\/[^"']+\.(?:js|css)(?:[?"'])/i.test(raw.html), 'runtime: no third-party JS or CSS');
  invariant(raw.render.includes("from './engine.js'") && raw.render.includes("from './data.js'"), 'runtime: module separation');
}

function checkSourcesAndStyle() {
  const owned = Object.entries(raw).filter(([key]) => key !== 'corpus').map(([, text]) => text);
  invariant(owned.every((text) => !text.includes('\u2014')), 'house: forbidden em dash');
  invariant(owned.every((text) => !text.includes('10.1017/S0960116313000213')), 'sources: false Darwin DOI absent');
  invariant(raw.html.includes('Lamport defines happened-before and scalar logical clocks, not vector time.'), 'history: Lamport attribution');
  invariant(raw.html.includes('edited version of the October 1988 workshop paper'), 'history: Mattern version');
  invariant(raw.html.includes('Colin Fidge independently published vector timestamps in 1988.'), 'history: Fidge attribution');
  invariant(raw.html.includes('--faint:#83857e'), 'accessibility: faint contrast token');
}

function checkFrozenTarget() {
  invariant(raw.audit === raw.publicAudit, 'target: public and research audit copies');
  invariant(sha256(raw.audit) === expected.auditSha, 'target: audit SHA-256');
  invariant(adapterEvidence(), 'target: audit values and scope');
  checkTargetModel();
  invariant(raw.sample.trimEnd().split(/\r?\n/).length === 10, 'target: ten-line sample');
  invariant(raw.extractor.includes("darwin-family-letters") && raw.extractor.includes('replyLikeAbstracts'), 'target: extractor covers scope and sensitivity counts');
}

if (process.argv.includes('--mutate')) {
  const mutations = [
    ['remove home message', 'home: exact vectors', () => homeEvidence({ ...HOME, messages: HOME.messages.filter(([a, b]) => !(a === 'p1' && b === 'q2')) })],
    ['corrupt computed vector', 'home: exact vectors', () => { const result = calibrate(HOME); result.vectors.p1 = [0, 0, 0]; return homeEvidence(HOME, result); }],
    ['invent receive date', 'adapter: frozen audit counts', () => { const value = structuredClone(audit); value.counts.receivedActionsWithDate = 1; return adapterEvidence(value); }],
    ['hide excluded collection', 'scope: excluded collection', () => { const value = structuredClone(audit); value.scope.excludedCollection = ''; return adapterEvidence(value); }],
    ['ablation keeps mapping active', 'ablation: active state document-id', () => { const value = structuredClone(collision); value.ablations[0].disabled = 'author-process'; checkAblations(value); }],
    ['blind positive control disabled', 'blindspot: positive leakage control', () => blindEvidence({ ...blindSpotFault(TARGET_FIXTURE), positiveLeakageControlCaught: false })],
    ['remove home recomputation', 'surface: action recomputes home', () => checkSurface(raw.html, raw.render.replace('result = calibrate(HOME);', 'result = currentHome;'))],
    ['remove self-pair equality', 'surface: self-pair equality', () => checkSurface(raw.html, raw.render.replace("  if (a === b) {\n    $('pairResult')", "  if (false) {\n    $('pairResult')"))],
    ['remove one live binding', 'surface: live binding comparableLive', () => checkSurface(raw.html, raw.render.replace("$('comparableLive').textContent", "$('missingLive').textContent"))],
    ['change frontmatter dek', 'frontmatter: dek', () => checkHead(raw.html, raw.frontmatter.replace(expected.dek, 'The clock worked.'))],
    ['change social image', 'head: social images', () => checkHead(raw.html.replaceAll(expected.image, 'https://artwaste.land/missing.svg'))],
    ['flip collision ledger', 'collision: ledger home_benchmark_passed', () => { const value = structuredClone(collision); value.ledger.home_benchmark_passed.value = false; checkCollision(value); }],
    ['remove ledger binding', 'surface: ledger engine binding', () => checkLedgerSurface(raw.html, raw.render.replace('transferLedger(HOME, TARGET, TARGET_FIXTURE)', '{}'))]
  ];
  let missed = 0;
  for (const [name, catcher, fn] of mutations) {
    let caught = false;
    try { caught = fn() === false; } catch { caught = true; }
    if (!caught) missed += 1;
    process.stdout.write(`${caught ? 'CAUGHT' : 'MISSED'} ${name} -> ${catcher}\n`);
  }
  process.exit(missed ? 1 : 0);
}

const checks = [];
function check(id, fn) {
  try { fn(); checks.push({ id, ok: true }); }
  catch (error) { checks.push({ id, ok: false, error: error.message }); }
}

check('home:all-210-pairs-and-vectors', () => invariant(homeEvidence(), 'home benchmark disagrees'));
check('target:frozen-audit-and-explicit-scope', checkFrozenTarget);
check('target:evidence-ledger-not-booleans', checkTargetModel);
check('depth:real-adapter-ablations', () => checkAblations());
check('surface:frozen-claims-and-live-bindings', () => checkSurface());
check('surface:head-frontmatter-jsonld-share-asset', () => checkHead());
check('surface:computed-ledger-bindings', () => checkLedgerSurface());
check('collision:manifest', () => checkCollision());
check('frontmatter:relates-exist', checkRelations);
check('runtime:local-and-accessible-shape', checkRuntime);
check('house:sources-contrast-and-dashes', checkSourcesAndStyle);
check('mutation:validator-cycle-contains-injected-edge', () => invariant(faultEvidence(), 'cycle fault not caught through validator'));
check('blindspot:real-adapter-with-positive-leak-control', () => invariant(blindEvidence(), 'blind spot path or leakage control failed'));

for (const item of checks) process.stdout.write(`${item.ok ? 'PASS' : 'FAIL'} ${item.id}${item.error ? `: ${item.error}` : ''}\n`);
const failed = checks.filter((item) => !item.ok).length;
process.stdout.write(`${checks.length - failed}/${checks.length} checks passed\n`);
process.exit(failed ? 1 : 0);
