#!/usr/bin/env node

import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import * as E from '../../public/strata/entered-as-day-sixty-two/engine.js';

const ROOT = path.resolve(new URL('../..', import.meta.url).pathname);
const SLUG = 'entered-as-day-sixty-two';
const PUBLIC_DIR = path.join(ROOT, 'public', 'strata', SLUG);
const RESEARCH_DIR = path.join(ROOT, 'research', SLUG);
const DATA_DIR = path.join(PUBLIC_DIR, 'data');
const PAGE_JS = path.join(PUBLIC_DIR, 'page.js');
const KEYS = ['anchor_reproduced_by_engine', 'rendered_figures_asserted', 'choices_are_live', 'planted_fault_caught', 'refusal_asserted', 'provenance_pinned'];
const outcomes = [];

// These are independent fixtures derived from the frozen source bytes and the published
// comparison, not values copied from a runtime result. The page engine must reproduce them.
const DERIVATION_FIXTURES = Object.freeze({
  anchor: Object.freeze({ early: '0.19', late: '4.61', dated: '0.89', datedN: 73 }),
  live: Object.freeze({
    arai1: Object.freeze({ tobit: '4.61', dated: '0.89', n: 92, censored: 19 }),
    'yatsu-first': Object.freeze({ tobit: '5.00', dated: '0.77', n: 92, censored: 26 }),
    'wsta-first': Object.freeze({ tobit: '4.67', dated: '0.95', n: 92, censored: 19 }),
    'arak-first': Object.freeze({ tobit: '4.59', dated: '0.87', n: 92, censored: 19 }),
  }),
  citedFreeze: Object.freeze({
    'drop/date': Object.freeze({ tobit: '0.85', dated: '0.78', n: 90, censored: 7 }),
    'drop/doy': Object.freeze({ tobit: '0.91', dated: '0.85', n: 90, censored: 7 }),
    'censored/date': Object.freeze({ tobit: '1.11', dated: '0.78', n: 92, censored: 9 }),
    'censored/doy': Object.freeze({ tobit: '1.17', dated: '0.85', n: 92, censored: 9 }),
  }),
});

function readJson(file) {
  return JSON.parse(fs.readFileSync(file, 'utf8'));
}

function check(group, name, condition) {
  const ok = condition === true;
  outcomes.push({ group, name, ok });
  return ok;
}

function attr(tag, name) {
  const doubleQuoted = tag.match(new RegExp(`${name}\\s*=\\s*"([^"]*)"`, 'i'));
  const singleQuoted = tag.match(new RegExp(`${name}\\s*=\\s*'([^']*)'`, 'i'));
  const match = doubleQuoted || singleQuoted;
  return match ? match[1] : null;
}

function tagsFor(html, tagName) {
  return [...html.matchAll(new RegExp(`<${tagName}\\b[^>]*>`, 'gi'))].map((match) => match[0]);
}

function metaValue(html, name, value) {
  const tag = tagsFor(html, 'meta').find((item) => attr(item, name) === value);
  return tag ? attr(tag, 'content') : null;
}

function linkValue(html, rel) {
  const tag = tagsFor(html, 'link').find((item) => attr(item, 'rel') === rel);
  return tag ? attr(tag, 'href') : null;
}

function titleText(html) {
  const match = html.match(/<title>(.*?)<\/title>/i);
  return match ? match[1].replace(/\s+/g, ' ').trim() : null;
}

function elementText(html, id) {
  const match = html.match(new RegExp(`<([a-z0-9]+)\\b[^>]*\\bid=["']${id}["'][^>]*>([\\s\\S]*?)</\\1>`, 'i'));
  if (!match) return null;
  return match[2]
    .replace(/<[^>]*>/g, '')
    .replace(/&amp;/g, '&')
    .replace(/&middot;/g, '·')
    .replace(/\s+/g, ' ')
    .trim();
}

function staticClaim(html, id) {
  const match = html.match(new RegExp(`data-static-claim=["']${id}["'][^>]*>([^<]*)<`, 'i'));
  return match ? match[1].trim() : null;
}

function parseFrontmatter(markdown) {
  const match = markdown.match(/^---\n([\s\S]*?)\n---/);
  if (!match) throw new Error('frontmatter missing');
  const body = match[1];
  const value = (key) => {
    const line = body.split(/\r?\n/).find((item) => item.startsWith(`${key}:`));
    if (!line) return null;
    const raw = line.slice(key.length + 1).trim();
    return raw.replace(/^"|"$/g, '');
  };
  return { title: value('title'), date: value('date'), dek: value('dek'), seoTitle: value('seoTitle'), plain: value('plain'), href: value('href') };
}

function bundle() {
  return {
    nsidc: readJson(path.join(DATA_DIR, 'nsidc-suwa.json')),
    cited: readJson(path.join(DATA_DIR, 'ochanomizu-summary.json')),
  };
}

function clone(value) {
  return structuredClone(value);
}

function mutateDatePlusDays(row, days) {
  const year = Number(row.iceon_year);
  const month = Number(row.iceon_month);
  const day = Number(row.iceon_day);
  const date = new Date(Date.UTC(year, month - 1, day) + days * 86400000);
  row.iceon_year = String(date.getUTCFullYear());
  row.iceon_month = String(date.getUTCMonth() + 1);
  row.iceon_day = String(date.getUTCDate());
}

function surfaceChecks(record, data, cited, html, front, pageJs) {
  const checks = [];
  const early = E.trend(data, { ...E.DEFAULT_OPTIONS, window: 'early' });
  const late = E.trend(data, { ...E.DEFAULT_OPTIONS, window: 'late' });
  const dated = E.trend(data, { ...E.DEFAULT_OPTIONS, window: 'late', includeCensored: false });
  const live = ['arai1', 'yatsu-first', 'wsta-first', 'arak-first'].map((source) => E.trend(data, { source, window: 'late', censorDay: 62, includeCensored: true }));
  const minDated = Math.min(...live.map((item) => Number(E.format(item.datedOnlySlope))));
  const maxDated = Math.max(...live.map((item) => Number(E.format(item.datedOnlySlope))));
  const expectedHeadline = `In the 1923 to 2014 window, dated winters move later by ${E.format(minDated)} to ${E.format(maxDated)} days per decade across four NSIDC series, while the published ARAI1 Tobit slope is ${E.format(late.slope)} because ${late.censored} winters are entered as day ${E.MIN_CENSOR_DAY}.`;
  checks.push(check('surface', 'title equals frontmatter seoTitle', titleText(html) === front.seoTitle));
  checks.push(check('surface', 'meta description equals the vetted dek', metaValue(html, 'name', 'description') === front.dek));
  checks.push(check('surface', 'canonical link is the assigned href', linkValue(html, 'canonical') === `https://artwaste.land${front.href}`));
  checks.push(check('surface', 'Open Graph URL is the assigned href', metaValue(html, 'property', 'og:url') === `https://artwaste.land${front.href}`));
  checks.push(check('surface', 'og image is the assigned card', metaValue(html, 'property', 'og:image') === `https://artwaste.land/og/${SLUG}.png`));
  checks.push(check('surface', 'twitter image is the assigned card', metaValue(html, 'name', 'twitter:image') === `https://artwaste.land/og/${SLUG}.png`));
  checks.push(check('surface', 'og title is the assigned title card', metaValue(html, 'property', 'og:title') === 'Entered as Day Sixty-Two · Artificial Wasteland'));
  checks.push(check('surface', 'twitter title is the assigned title card', metaValue(html, 'name', 'twitter:title') === 'Entered as Day Sixty-Two · Artificial Wasteland'));
  checks.push(check('surface', 'og description equals the vetted dek', metaValue(html, 'property', 'og:description') === front.dek));
  checks.push(check('surface', 'twitter description equals the vetted dek', metaValue(html, 'name', 'twitter:description') === front.dek));
  checks.push(check('surface', 'plain placard equals frontmatter plain', metaValue(html, 'name', 'aw-plain') === front.plain));
  checks.push(check('surface', 'published early figure is the engine rounded value', staticClaim(html, 'published-early') === E.format(early.slope)));
  checks.push(check('surface', 'published late figure is the source printed rounding', staticClaim(html, 'published-late') === '4.6' && E.format(late.slope) === '4.61'));
  checks.push(check('surface', 'headline is generated from the engine values', elementText(html, 'headline') === expectedHeadline && record.headline === expectedHeadline));
  const expectedAnchorProse = `Sharma et al.'s published Lake Suwa anchor gives ${E.format(early.slope)} days per decade for the early analysis and 4.6 days per decade for the late analysis. Their reason for using a Tobit model is precise: a winter with no full freeze is not an ordinary missing value.`;
  checks.push(check('surface', 'anchor prose keeps its cited figures', elementText(html, 'anchorProse') === expectedAnchorProse));
  checks.push(check('surface', 'crossing block prose keeps its source years', elementText(html, 'blockProse') === 'The later compilation marks the crossing block for the years 1507 to 1514 with a star. Mikami\'s account says the source wrote one statement about eight years, not eight yearly observations. Let the note stay unknown, or operate the stronger reading and see exactly what it changes.'));
  checks.push(check('surface', 'refusal boundaries are printed in full', elementText(html, 'refusalBoundaries') === 'This page will not invent a freeze or a no-freeze for a row marked U, -, or a freeze flag with no date. It will not fit 1682 to 1922. It will not call a press report for the next winter a row in this record. It will not attribute the trend to temperature, carbon dioxide, or another driver that this record does not contain.'));
  checks.push(check('surface', 'calendar prose keeps the unverified boundary', elementText(html, 'calendarProse') === 'The NSIDC guide documents a correction before its modern release. It does not state whether dates before 1582 should be treated as Julian or proleptic Gregorian for the step test below. Apply the hypothesis as a sensitivity, then compare it with the record\'s own means.'));
  checks.push(check('surface', 'static anchor comparison is intact', elementText(html, 'anchorPublication') === '0.19 and 4.6, cited'));
  checks.push(check('surface', 'censoring formula names both boundary cases', elementText(html, 'formula') === 'observed freeze value = the dated day capped at L, or L when froze = N; a dated value at or beyond L is censored too'));
  checks.push(check('surface', 'visible baseline panel is wired to fail-capable checks', pageJs.includes('E.baselineChecks(bundle)') && pageJs.includes('R.renderCheck(item.id, item.text, item.ok)')));
  const baselineRows = E.baselineChecks(data).find((item) => item.id === 'checkRows');
  checks.push(check('surface', 'record exclusions are scoped to the full ARAI1 record', baselineRows?.text === '577 ARAI1 seasons loaded, with 135 uncertain rows across the full record'
    && baselineRows.ok === true && pageJs.includes('E.baselineChecks(bundle)')));
  checks.push(check('surface', 'timeline labels cited fallback rows', html.includes('id="timelineNote"') && pageJs.includes('ARAI1 dated-only reference')));
  checks.push(check('surface', 'refusal hides a stale timeline', html.includes('canvas[hidden] { display: none; }') && pageJs.includes("$('freezeStrip').hidden = true")));
  checks.push(check('surface', 'extended conclusion is scoped separately', html.includes('published 1923 to 2014 window')
    && html.includes('published 1923 to 2014 comparison shown in the table') && html.includes('extended control is a separate window')));
  checks.push(check('surface', 'cited repository version is named on the page', html.includes('version 20260107ver')
    && html.includes('created 2026-01-07') && html.includes('available 2026-04-13')));
  checks.push(check('surface', 'novelty claim acknowledges JIVX prior art', html.includes('JIVX already lists nine winter disagreements')
    && !html.includes('or a winter-by-winter account of disagreement among these compilations')));
  const liveReadoutIds = ['heroSlope', 'heroSlopeUnit', 'ringCount', 'datedCount', 'sampleCount', 'checkEarly', 'checkLate', 'checkDated', 'checkCensored', 'checkCounts', 'checkRows', 'anchorEngineEarly', 'anchorEngineLate', 'recordVersionNote', 'sourceSlope', 'sourceSample', 'countEarly', 'countMiddle', 'countRecent', 'countLabel', 'citedFreezeSlope', 'citedFreezeN', 'citedFreezeDated', 'citedCrossSlope', 'citedCrossN', 'citedExtension', 'citedShares', 'earlyCalendarSlope', 'stepFirst', 'stepSecond', 'stepDifference', 'stepPrediction'];
  const allTags = [...tagsFor(html, 'b'), ...tagsFor(html, 'span'), ...tagsFor(html, 'p'), ...tagsFor(html, 'strong')];
  checks.push(check('surface', 'changing numeric readouts are live regions', liveReadoutIds.every((id) => {
    const tag = allTags.find((item) => attr(item, 'id') === id);
    return tag && attr(tag, 'aria-live') === 'polite';
  })));
  checks.push(check('surface', 'dek numbers match the dated-only engine', front.dek.includes(`${dated.n} winters`) && dated.n === 73 && front.dek.includes(E.format(dated.slope))));
  // Added by the wave supervisor after a mutation test (0.89 -> 0.88 in the visible dek went unnoticed):
  // the meta and JSON-LD copies were pinned to the frontmatter, but the dek a reader sees was not.
  const decode = (s) => s.replace(/&#39;|&apos;/g, "'").replace(/&quot;/g, '"').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&');
  const visibleDek = (html.match(/<p class="dek">([^<]*)<\/p>/) || [])[1];
  checks.push(check('surface', 'visible dek equals the vetted dek', visibleDek !== undefined && decode(visibleDek) === front.dek));
  checks.push(check('surface', 'static calendar year is the declared sensitivity boundary', staticClaim(html, 'calendar-year') === '1582'));
  checks.push(check('surface', 'novelty date is the retrieval date', staticClaim(html, 'novelty-date') === '2026-09-14'));
  const input = tagsFor(html, 'input').find((tag) => attr(tag, 'id') === 'censorDay');
  checks.push(check('surface', 'censor input starts at the record limit', input && attr(input, 'value') === '62' && attr(input, 'min') === '0' && attr(input, 'max') === '90'));
  const inspector = tagsFor(html, 'input').find((tag) => attr(tag, 'id') === 'inspectSeason');
  checks.push(check('surface', 'inspector starts at the latest NSIDC season', inspector && attr(inspector, 'value') === '2019' && attr(inspector, 'min') === '1400' && attr(inspector, 'max') === '2100'));
  checks.push(check('surface', 'source citation year is not silently changed', html.includes('Sharma et al. 2016') && html.includes('Arakawa 1954')));
  checks.push(check('surface', 'prior-art labels and refused source are intact', html.includes('Ishiguro 2001') && html.includes('Hasegawa, Hirano and Mikami 2024') && html.includes('Nagano Prefecture, page 50')));
  const ldTag = tagsFor(html, 'script').find((tag) => attr(tag, 'type') === 'application/ld+json');
  let ld = null;
  try {
    const body = html.slice(html.indexOf('>', html.indexOf(ldTag)) + 1, html.indexOf('</script>', html.indexOf(ldTag)));
    ld = JSON.parse(body);
  } catch (error) {
    checks.push(check('surface', 'JSON-LD parses', false));
  }
  if (ld) {
    checks.push(check('surface', 'JSON-LD name equals seoTitle', ld.name === front.seoTitle));
    checks.push(check('surface', 'JSON-LD headline equals poetic title', ld.headline === front.title));
    checks.push(check('surface', 'JSON-LD description equals dek', ld.description === front.dek));
    checks.push(check('surface', 'JSON-LD URL and image are assigned', ld.url === `https://artwaste.land${front.href}` && ld.image === `https://artwaste.land/og/${SLUG}.png`));
    checks.push(check('surface', 'JSON-LD publication date equals frontmatter date', ld.datePublished === front.date));
  }
  checks.push(check('surface', 'the load-bearing closing tags exist', /<\/script>\s*<\/body>\s*<\/html>\s*$/i.test(html)));
  return checks;
}

function runAll() {
  const record = readJson(path.join(PUBLIC_DIR, 'record.json'));
  const data = bundle();
  const html = fs.readFileSync(path.join(PUBLIC_DIR, 'index.html'), 'utf8');
  const pageJs = fs.readFileSync(PAGE_JS, 'utf8');
  const front = parseFrontmatter(fs.readFileSync(path.join(ROOT, 'src', 'content', 'strata', `${SLUG}.md`), 'utf8'));

  const early = E.trend(data, { ...E.DEFAULT_OPTIONS, window: 'early' });
  const late = E.trend(data, { ...E.DEFAULT_OPTIONS, window: 'late' });
  const dated = E.trend(data, { ...E.DEFAULT_OPTIONS, window: 'late', includeCensored: false });
  const computedAnchor = `${E.format(early.slope)} days per decade (1443 to 1683) and ${E.format(late.slope)} days per decade (1923 to 2014)`;
  check('anchor', 'engine reproduces the early slope', E.format(early.slope) === '0.19');
  check('anchor', 'engine reproduces the late slope', E.format(late.slope) === '4.61');
  check('anchor', 'independent anchor fixtures close on the real record', E.format(early.slope) === DERIVATION_FIXTURES.anchor.early
    && E.format(late.slope) === DERIVATION_FIXTURES.anchor.late
    && E.format(dated.slope) === DERIVATION_FIXTURES.anchor.dated
    && dated.n === DERIVATION_FIXTURES.anchor.datedN);
  check('anchor', 'current ARAI1 no-freeze count stays visibly unreconciled', E.noFreezeCount(data, 'arai1', 1443, 2014) === 42
    && pageJs.includes("E.noFreezeCount(bundle, 'arai1', 1443, 2014)")
    && pageJs.includes('Sharma et al. print 37 for their historical data version')
    && html.includes('id="recordVersionNote"'));
  check('anchor', 'record anchor computed field comes from engine', record.anchor.computed === computedAnchor);
  check('anchor', 'record anchor agrees with printed values', record.anchor.agrees === true && record.anchor.expected === '0.19 days per decade (1443 to 1683) and 4.6 days per decade (1923 to 2014)');
  const negativeAnchor = clone(data);
  const badAnchorRow = negativeAnchor.nsidc.rows.find((row) => row.lakecode === 'ARAI1' && row.season === '1931-32');
  badAnchorRow.froze = 'Y';
  badAnchorRow.iceon_year = '1932';
  badAnchorRow.iceon_month = '1';
  badAnchorRow.iceon_day = '15';
  check('anchor', 'a changed source row breaks the late anchor', E.format(E.trend(negativeAnchor, { ...E.DEFAULT_OPTIONS, window: 'late' }).slope) !== '4.61');

  const sourceResults = ['arai1', 'yatsu-first', 'wsta-first', 'arak-first'].map((source) => ({ source, result: E.trend(data, { ...E.DEFAULT_OPTIONS, source, window: 'late' }) }));
  const sourceChoiceResults = E.SOURCE_OPTIONS.map((source) => ({ source: source.id, result: E.trend(data, { ...E.DEFAULT_OPTIONS, source: source.id, window: 'late' }) }));
  check('anchor', 'all four live source results are finite', sourceResults.every(({ result }) => result.ok && Number.isFinite(result.slope)));
  check('anchor', 'all six source options return finite results', sourceChoiceResults.every(({ result }) => result.ok && Number.isFinite(result.slope)));
  check('anchor', 'dated-only slopes stay under one day per decade', sourceResults.every(({ result }) => result.datedOnlySlope < 1));
  check('anchor', 'independent live-source fixtures close on the real record', sourceResults.every(({ source, result }) => {
    const expected = DERIVATION_FIXTURES.live[source];
    return E.format(result.slope) === expected.tobit && E.format(result.datedOnlySlope) === expected.dated
      && result.n === expected.n && result.censored === expected.censored;
  }));
  check('anchor', 'cited aggregate source identity is pinned', data.cited.source.version === '20260107ver'
    && data.cited.source.created === '2026-01-07' && data.cited.source.available === '2026-04-13'
    && !data.cited.source.name.includes('Version 2'));
  check('choices', 'record declares the engine choice vocabulary', JSON.stringify(record.choices) === JSON.stringify(E.CHOICES.map((choice) => ({ ...choice, inert: false }))));

  const choices = [
    ['source', () => sourceChoiceResults.map((item) => item.result.slope)],
    ['no-freeze-winters', () => [late.slope, dated.slope]],
    ['censor-day', () => [62, 75, 90].map((censorDay) => E.trend(data, { ...E.DEFAULT_OPTIONS, censorDay, window: 'late' }).slope)],
    ['window', () => ['early', 'late', 'extended'].map((window) => E.trend(data, { ...E.DEFAULT_OPTIONS, window }).slope)],
    ['calendar-before-1582', () => ['as-compiled', 'julian-hypothesis'].map((calendar) => E.trend(data, { ...E.DEFAULT_OPTIONS, window: 'early', calendar }).slope)],
    ['season-label', () => [E.periodCounts(data, 'arai1', 'season-start').middle, E.periodCounts(data, 'arai1', 'jan-mar').middle]],
    ['star-in-freeze-column', () => [E.trend(data, { source: 'ocha-freeze', star: 'drop' }).slope, E.trend(data, { source: 'ocha-freeze', star: 'censored' }).slope]],
    ['date-or-doy', () => [E.trend(data, { source: 'ocha-freeze', dateOrDoy: 'date' }).slope, E.trend(data, { source: 'ocha-freeze', dateOrDoy: 'doy' }).slope]],
    ['1507-1514', () => [E.crossingRunSummary(data, 'unknown').earlySelected, E.crossingRunSummary(data, 'eight-winters').earlySelected]],
  ];
  check('choices', 'every declared choice moves an engine output', choices.every(([, values]) => {
    const output = values();
    return output.length > 1 && output.some((value, index) => index > 0 && JSON.stringify(value) !== JSON.stringify(output[0]));
  }));
  check('choices', 'the calendar choice is tested on its early window', E.format(E.trend(data, { ...E.DEFAULT_OPTIONS, window: 'early', calendar: 'julian-hypothesis' }).slope) === '-0.36');
  check('choices', 'season labels move the published middle count', E.periodCounts(data, 'arai1', 'season-start').middle === 12 && E.periodCounts(data, 'arai1', 'jan-mar').middle === 11);
  check('choices', 'all four cited star and DOY combinations match independent fixtures', Object.entries(DERIVATION_FIXTURES.citedFreeze).every(([key, expected]) => {
    const [star, dateOrDoy] = key.split('/');
    const result = E.trend(data, { source: 'ocha-freeze', star, dateOrDoy });
    return result.ok && E.format(result.slope) === expected.tobit && E.format(result.datedOnlySlope) === expected.dated
      && result.n === expected.n && result.censored === expected.censored;
  }));
  check('choices', 'crossing run preserves both fixed readings and the selected reading', E.crossingRunSummary(data, 'unknown').earlyUnknown === 1
    && E.crossingRunSummary(data, 'unknown').earlyEight === 8
    && E.crossingRunSummary(data, 'unknown').earlySelected === 1
    && E.crossingRunSummary(data, 'eight-winters').earlySelected === 8);

  const doctored = clone(data);
  for (const row of doctored.nsidc.rows) {
    const key = Number(String(row.season).slice(0, 4));
    if (row.lakecode === 'ARAI1' && key < 1582 && row.froze === 'Y' && Number(row.iceon_year) > 0) mutateDatePlusDays(row, 10);
  }
  check('fault', 'planting dates in the data copy changes the early answer', E.format(E.trend(doctored, { ...E.DEFAULT_OPTIONS, window: 'early' }).slope) !== '0.19');
  check('fault', 'the clean data still closes the anchor', E.format(E.trend(data, { ...E.DEFAULT_OPTIONS, window: 'early' }).slope) === '0.19' && E.format(E.trend(data, { ...E.DEFAULT_OPTIONS, window: 'late' }).slope) === '4.61');
  check('fault', 'planting a new mid-January freeze changes the late answer', E.format(E.trend(negativeAnchor, { ...E.DEFAULT_OPTIONS, window: 'late' }).slope) !== '4.61');

  const censorRefusal = E.refusalForCensorDay(61);
  const middleRefusal = E.trend(data, { ...E.DEFAULT_OPTIONS, window: 'middle' });
  check('refusal', 'censor day below 62 is refused', censorRefusal.ok === false && censorRefusal.message.includes('record already uses day 62'));
  check('refusal', 'the unreliable middle trend is refused', middleRefusal.ok === false && middleRefusal.refusal.code === 'unreliable-middle');
  check('refusal', 'a U row is not turned into a freeze or no-freeze', E.selectedSeason(data, 'arai1', 1507).ok === false);
  check('refusal', 'a season after the ARAI1 record is refused', E.selectedSeason(data, 'arai1', 2020).ok === false);
  check('refusal', 'the cited aggregate has no pretend per-winter inspector', E.selectedSeason(data, 'ocha-freeze', 2019).ok === false);
  check('refusal', 'the page states the refusal boundary and no driver attribution', html.includes('It will not fit 1682 to 1922') && html.includes('carbon dioxide'));

  check('surface', 'page wires the baseline check result to visible pass or fail state', pageJs.includes("status('checkStatus'") && pageJs.includes("passed === checks.length ? 'ok' : 'fail'"));

  surfaceChecks(record, data, data.cited, html, front, pageJs);

  const files = [
    path.join(PUBLIC_DIR, 'data', 'nsidc-suwa.json'),
    path.join(PUBLIC_DIR, 'data', 'ochanomizu-summary.json'),
    path.join(RESEARCH_DIR, 'data', 'nsidc-suwa.json'),
    path.join(RESEARCH_DIR, 'data', 'ochanomizu-summary.json'),
  ];
  const hashes = Object.fromEntries(files.map((file) => [path.relative(ROOT, file), crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex')]));
  check('provenance', 'record primary hash pins the public extract', record.record.sha256 === hashes[`public/strata/${SLUG}/data/nsidc-suwa.json`]);
  check('provenance', 'record lists every frozen data file', Array.isArray(record.record.files) && record.record.files.every((item) => hashes[item.path] === item.sha256));
  check('provenance', 'research and public frozen copies are byte-identical', hashes[`public/strata/${SLUG}/data/nsidc-suwa.json`] === hashes[`research/${SLUG}/data/nsidc-suwa.json`] && hashes[`public/strata/${SLUG}/data/ochanomizu-summary.json`] === hashes[`research/${SLUG}/data/ochanomizu-summary.json`]);
  check('provenance', 'the extract pins the upstream NSIDC bytes', data.nsidc.source.upstream_sha256 === '75bfd0fb1ad2f419e3487455c967d243d845cc4c14ef20836888b0869d4dae61');
  check('provenance', 'the cited summary pins its upstream bytes without shipping them', data.cited.source.upstream_sha256 === '2089cec8c9a864650ab4748f851d14df4351961db4e6f7d57149e25bb4f2a0ed' && data.cited.exclusions.some((item) => item.includes('No per-winter')));

  return record;
}

const record = runAll();
const groupForKey = {
  anchor_reproduced_by_engine: 'anchor',
  rendered_figures_asserted: 'surface',
  choices_are_live: 'choices',
  planted_fault_caught: 'fault',
  refusal_asserted: 'refusal',
  provenance_pinned: 'provenance',
};
const ledger = Object.fromEntries(KEYS.map((key) => [key, outcomes.filter((item) => item.group === groupForKey[key]).every((item) => item.ok)]));

if (process.argv.includes('--ledger')) {
  process.stdout.write(KEYS.map((key) => `${key}=${ledger[key]}`).join('\n') + '\n');
} else {
  for (const outcome of outcomes) console.log(`${outcome.ok ? 'PASS' : 'FAIL'} ${outcome.group}: ${outcome.name}`);
  console.log(`summary: ${outcomes.filter((item) => item.ok).length}/${outcomes.length} assertions passed`);
  console.log(`ledger: ${JSON.stringify(ledger)}`);
}

if (!Object.values(ledger).every(Boolean)) process.exitCode = 1;
