import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import {fileURLToPath} from 'node:url';
import {
  CHOICES,
  DEFAULT_OPTIONS,
  WITNESS_IDS,
  allWitnessesReading,
  analyze,
  comparisonSentence,
  computeAnchor,
  headlineFor,
  inspectCell,
  modelFingerprint,
  outsideRecordRefusal
} from '../../public/strata/the-proprietors-have-consented/engine.js';
import {gridDiameters} from '../../public/strata/the-proprietors-have-consented/render.js';

const slug = 'the-proprietors-have-consented';
const here = path.dirname(fileURLToPath(import.meta.url));
const root = path.resolve(here, '../..');
const pageDir = path.join(root, 'public', 'strata', slug);
const pagePath = path.join(pageDir, 'index.html');
const recordPath = path.join(pageDir, 'record.json');
const researchDataDir = path.join(here, 'data');
const publicDataDir = pageDir;
const readText = file => fs.readFileSync(file, 'utf8');
const readJson = file => JSON.parse(readText(file));
const sha256 = file => crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex');
const deepEqual = (left, right) => JSON.stringify(left) === JSON.stringify(right);
const formatNumber = value => Number(value).toLocaleString('en-US', {maximumFractionDigits: 4});
const formatList = values => values.map(formatNumber).join(', ');
const numberWords = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'];
const numberWord = value => numberWords[value] || String(value);
const capitalizedNumberWord = value => {
  const word = numberWord(value);
  return word.charAt(0).toUpperCase() + word.slice(1);
};
const EXPECTED_FREESE_DOYLE_ROW = [4, 16, 36, 64, 100, 144, 196, 256, 324, 400, 484, 576, 676, 784, 900, 1024];
const independentDoyleValue = (lengthFt, diameterIn) => lengthFt * (diameterIn - 4) ** 2 / 16;

const ledgerKeys = [
  'anchor_reproduced_by_engine',
  'rendered_figures_asserted',
  'choices_are_live',
  'planted_fault_caught',
  'refusal_asserted',
  'provenance_pinned'
];

function decodeEntities(value) {
  return value
    .replace(/&amp;/g, '&')
    .replace(/&lt;/g, '<')
    .replace(/&gt;/g, '>')
    .replace(/&quot;/g, '"')
    .replace(/&#39;/g, "'")
    .replace(/&nbsp;/g, ' ');
}

function visibleText(value) {
  return decodeEntities(value
    .replace(/<!--[\s\S]*?-->/g, '')
    .replace(/<\/?(?:em|strong|span|a)\b[^>]*>/gi, '')
    .replace(/<[^>]+>/g, ' '))
    .replace(/\s+/g, ' ')
    .trim();
}

function escapeRegExp(value) {
  return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

function tagContent(html, tag) {
  const match = html.match(new RegExp('<' + tag + '\\b[^>]*>([\\s\\S]*?)</' + tag + '>', 'i'));
  return match ? visibleText(match[1]) : null;
}

function elementTextById(html, id) {
  const safeId = escapeRegExp(id);
  const match = html.match(new RegExp("<([a-z][a-z0-9]*)\\b[^>]*\\bid=[\"']" + safeId + "[\"'][^>]*>([\\s\\S]*?)</\\1>", 'i'));
  return match ? visibleText(match[2]) : null;
}

function elementTextByClass(html, tag, className) {
  const safeClass = escapeRegExp(className);
  const match = html.match(new RegExp("<" + tag + "\\b[^>]*\\bclass=[\"'][^\"']*\\b" + safeClass + "\\b[^\"']*[\"'][^>]*>([\\s\\S]*?)</" + tag + ">", 'i'));
  return match ? visibleText(match[1]) : null;
}

function metaContent(html, attribute, value) {
  const safeValue = escapeRegExp(value);
  for (const match of html.matchAll(/<meta\b[^>]*>/gi)) {
    const tag = match[0];
    if (!new RegExp("\\b" + attribute + "\\s*=\\s*[\"']" + safeValue + "[\"']", 'i').test(tag)) continue;
    const content = tag.match(/\bcontent\s*=\s*"([^"]*)"/i);
    if (content) return decodeEntities(content[1]);
  }
  return null;
}

function linkHref(html, rel) {
  const safeRel = escapeRegExp(rel);
  for (const match of html.matchAll(/<link\b[^>]*>/gi)) {
    const tag = match[0];
    if (!new RegExp("\\brel\\s*=\\s*[\"'][^\"']*\\b" + safeRel + "\\b[^\"']*[\"']", 'i').test(tag)) continue;
    const href = tag.match(/\bhref\s*=\s*["']([^"']*)["']/i);
    if (href) return decodeEntities(href[1]);
  }
  return null;
}

function classBlock(html, tag, className) {
  const safeClass = escapeRegExp(className);
  const match = html.match(new RegExp("<" + tag + "\\b[^>]*\\bclass=[\"'][^\"']*\\b" + safeClass + "\\b[^\"']*[\"'][^>]*>([\\s\\S]*?)</" + tag + ">", 'i'));
  return match ? match[1] : null;
}

function frontmatterValue(markdown, key) {
  const match = markdown.match(new RegExp('^' + escapeRegExp(key) + ':\\s*"([^"\\n]*)"\\s*$', 'm'));
  return match ? match[1] : null;
}

function main() {
  const groups = Object.fromEntries(ledgerKeys.map(key => [key, []]));
  const failures = [];
  const externalFailures = [];
  const check = (group, label, condition) => {
    const pass = Boolean(condition);
    groups[group].push({label, pass});
    if (!pass) failures.push(group + ': ' + label);
    return pass;
  };

  const data = readJson(path.join(researchDataDir, 'doyle-diagnostic.json'));
  const anchor = readJson(path.join(researchDataDir, 'freese-anchor.json'));
  const resolution = readJson(path.join(researchDataDir, 'joint-resolution.json'));
  const record = readJson(recordPath);
  const html = readText(pagePath);
  const markdown = readText(path.join(root, 'src', 'content', 'strata', slug + '.md'));
  const model = analyze(data, DEFAULT_OPTIONS);
  const computedHeadline = headlineFor(data);
  const anchorResult = computeAnchor(anchor);
  const independentlyComputedAnchor = anchor.diameters_in.map(diameter => independentDoyleValue(anchor.length_ft, diameter));
  const defaultCell = data.cells.find(cell => cell.length_ft === 20 && cell.diameter_in === 10);
  const defaultInspection = inspectCell(data, defaultCell.length_ft, defaultCell.diameter_in, DEFAULT_OPTIONS);
  const doubtfulCell = data.cells.find(cell => cell.length_ft === 25 && cell.diameter_in === 16);
  const doubtfulReading = doubtfulCell.readings.W1;
  const publicDomainMarkCount = data.witnesses.filter(witness => witness.licence.includes('Public Domain Mark')).length;
  const noRightsFieldCount = data.witnesses.filter(witness => witness.licence.startsWith('No rights field')).length;

  check('anchor_reproduced_by_engine', 'anchor:independent-fixed-freese-row-oracle', deepEqual(anchor.as_printed, EXPECTED_FREESE_DOYLE_ROW) && deepEqual(independentlyComputedAnchor, EXPECTED_FREESE_DOYLE_ROW));
  check('anchor_reproduced_by_engine', 'anchor:engine-agrees-with-independent-oracle', anchorResult.agrees && deepEqual(anchorResult.computed, independentlyComputedAnchor));
  check('anchor_reproduced_by_engine', 'anchor:record-expected-is-the-published-row', record.anchor.expected === formatList(EXPECTED_FREESE_DOYLE_ROW));
  check('anchor_reproduced_by_engine', 'anchor:record-computed-is-engine-output', record.anchor.computed === formatList(anchorResult.computed));
  const badAnchor = structuredClone(anchor);
  badAnchor.as_printed[0] += 1;
  check('anchor_reproduced_by_engine', 'anchor:bad-frozen-value-fails', computeAnchor(badAnchor).agrees === false);

  const expectedTitle = 'Doyle Log Tables: Which Printing Reached the Government?';
  const expectedName = 'The Proprietors Have Consented';
  const expectedDek = "The 1903 Woodsman's Handbook prints a Doyle log table beside a notice that its copyrighted matter was used by consent. Read the same cells in seven printings, run Doyle's rule on each one, and follow only the readings that the rule cannot produce. The record cannot recover a proprietor's name or turn board feet into lumber yield.";
  const expectedPlain = "A printed log table can be a chain of copies rather than a fresh calculation. This page recomputes Doyle's rule against cells from seven lumber books, lets you test which readings travel together, and refuses untranscribed cells, the proprietor's individual name, and any promise that board feet predict sawmill yield.";
  const expectedUrl = 'https://artwaste.land/strata/the-proprietors-have-consented/';
  const expectedImage = 'https://artwaste.land/og/the-proprietors-have-consented.png';
  const expectedNovelty = "we searched the listed books, the two Belyea records, Internet Archive full text, Crossref and Semantic Scholar records, and the Artificial Wasteland corpus on 2026-09-15 and did not find a cell-level collation of these Doyle printings that states the Handbook carries the Lumber and Log Book's misreadings.";
  const expectedSources = "Frank Freese, A Collection of Log Rules, USDA Forest Service General Technical Report FPL 1, anchor page and catalogue record. Henry Solon Graves, The Woodsman's Handbook, USDA Bureau of Forestry Bulletin 36, 1903, and Graves and Ziegler, 1910. George W. Fisher, Scribner's Lumber and Log Book, revised edition of 1882, and the related printings listed above. Harold C. Belyea, “A Postscript on the Lost Identity of Doyle and Scribner”, Journal of Forestry 51(5), 326 to 329, 1953, DOI 10.1093/jof/51.5.326. C. Harold Belyea and Robert T. Sheldon, “Some Anomalies in the Board Foot Measurement of Logs”, Journal of Forestry 36(10), 963 to 969, 1938, DOI 10.1093/jof/36.10.963. The accessible routes did not expose a cell-level collation of the Handbook printings.";

  check('rendered_figures_asserted', 'surface:title-is-seo-title', tagContent(html, 'title') === expectedTitle);
  check('rendered_figures_asserted', 'surface:dek-meta-description', metaContent(html, 'name', 'description') === expectedDek);
  check('rendered_figures_asserted', 'surface:canonical', linkHref(html, 'canonical') === expectedUrl);
  check('rendered_figures_asserted', 'surface:og-title', metaContent(html, 'property', 'og:title') === expectedName + ' · Artificial Wasteland');
  check('rendered_figures_asserted', 'surface:og-description', metaContent(html, 'property', 'og:description') === expectedDek);
  check('rendered_figures_asserted', 'surface:og-url', metaContent(html, 'property', 'og:url') === expectedUrl);
  check('rendered_figures_asserted', 'surface:og-image', metaContent(html, 'property', 'og:image') === expectedImage);
  check('rendered_figures_asserted', 'surface:twitter-title', metaContent(html, 'name', 'twitter:title') === expectedName + ' · Artificial Wasteland');
  check('rendered_figures_asserted', 'surface:twitter-description', metaContent(html, 'name', 'twitter:description') === expectedDek);
  check('rendered_figures_asserted', 'surface:twitter-image', metaContent(html, 'name', 'twitter:image') === expectedImage);
  check('rendered_figures_asserted', 'surface:plain-placard', metaContent(html, 'name', 'aw-plain') === expectedPlain);
  check('rendered_figures_asserted', 'surface:frontmatter-dek', frontmatterValue(markdown, 'dek') === expectedDek);
  check('rendered_figures_asserted', 'surface:frontmatter-plain', frontmatterValue(markdown, 'plain') === expectedPlain);
  check('rendered_figures_asserted', 'surface:frontmatter-seo-title', frontmatterValue(markdown, 'seoTitle') === expectedTitle);
  check('rendered_figures_asserted', 'surface:headline-is-engine-output', elementTextById(html, 'static-headline') === computedHeadline && record.headline === computedHeadline);
  check('rendered_figures_asserted', 'surface:default-selected-cell-is-record-coordinate', elementTextById(html, 'selected-cell') === String(defaultCell.length_ft) + ' feet by ' + String(defaultCell.diameter_in) + ' inches');
  check('rendered_figures_asserted', 'surface:default-rule-value-is-engine-output', elementTextById(html, 'rule-value') === formatNumber(defaultInspection.rule.value) + ' board feet');
  check('rendered_figures_asserted', 'surface:doubtful-control-is-record-coordinate', html.includes('W1 doubtful ' + String(doubtfulCell.length_ft) + ' ft by ' + String(doubtfulCell.diameter_in) + ' in'));
  check('rendered_figures_asserted', 'surface:doubtful-option-is-alternate-record-reading', html.includes('Use the possible ' + String(doubtfulReading.alternate_as_printed) + ' reading'));
  check('rendered_figures_asserted', 'surface:default-cells', elementTextById(html, 'metric-cells') === String(model.counts.cellCount));
  check('rendered_figures_asserted', 'surface:default-readings', elementTextById(html, 'metric-observations') === String(model.counts.observationCount));
  check('rendered_figures_asserted', 'surface:default-evidence', elementTextById(html, 'metric-evidence') === String(model.counts.evidenceCount));
  check('rendered_figures_asserted', 'surface:default-diagnostic-cells', elementTextById(html, 'metric-diagnostics') === String(model.counts.diagnosticCellCount));
  check('rendered_figures_asserted', 'surface:default-pass-disagreements', elementTextById(html, 'metric-disagreements') === String(model.counts.transcriptionDisagreements));
  check('rendered_figures_asserted', 'surface:check-panel-readings', elementTextById(html, 'metric-check-readings') === String(model.counts.observationCount));
  check('rendered_figures_asserted', 'surface:check-panel-evidence', elementTextById(html, 'metric-check-evidence') === String(model.counts.evidenceCount));
  check('rendered_figures_asserted', 'surface:headline-is-labelled-default-run', html.includes('<p class="section-label">default run</p>'));
  check('rendered_figures_asserted', 'surface:check-panel-says-current-run', html.includes('the current run has') && !html.includes('the default run has'));
  check('rendered_figures_asserted', 'surface:published-anchor-wording', html.includes('published arithmetic anchor') && !html.includes('independent implementation anchor'));
  check('rendered_figures_asserted', 'surface:grid-includes-doubtful-cell', data.cells.some(cell => cell.length_ft === 25 && cell.diameter_in === 16) && gridDiameters(data).includes(16));
  check('rendered_figures_asserted', 'surface:government-printings-stay-distinct', (() => {
    const inspection = inspectCell(data, 13, 33, DEFAULT_OPTIONS);
    const entries = inspection.groupedObservations;
    return entries.some(item => item.groupId === 'government-1903' && item.printed === 633 && item.groupLabel === 'W6, Handbook 1903')
      && entries.some(item => item.groupId === 'government-1910' && item.printed === 683 && item.groupLabel === 'W7, Handbook 1910');
  })());
  check('rendered_figures_asserted', 'surface:resolution-keeps-source-punctuation', resolution.proprietor_clause_as_written.endsWith(',') && resolution.context_clause_as_written.endsWith(', under the restriction that') && resolution.restriction_clause_as_written.endsWith('; and') && resolution.authority_clause_as_written.endsWith(':') && resolution.resolved_clause_as_written.endsWith('.') && resolution.section_two_as_written.endsWith('.') && readText(path.join(pageDir, 'render.js')).includes("resolution.proprietor_clause_as_written + ' '"));
  check('rendered_figures_asserted', 'surface:dynamic-readouts-have-status', html.includes('id="selected-status" class="status" role="status" aria-live="polite"') && html.includes('id="anchor-status" role="status" aria-live="polite"') && html.includes('id="refusal-result" role="status" aria-live="polite"') && html.includes('id="descent-status" class="status" role="status" aria-live="polite"') && html.includes('id="shares-status" class="status" role="status" aria-live="polite"') && html.includes('id="hypothesis-status" class="status" role="status" aria-live="polite"') && !/<div class="selected-card"[^>]*aria-live=/.test(html) && readText(path.join(pageDir, 'page.js')).includes("inspection.rule.value"));
  check('rendered_figures_asserted', 'surface:apparatus-cell-count-is-record-count', html.includes(capitalizedNumberWord(data.cells.length) + ' cell coordinates are frozen here.'));
  check('rendered_figures_asserted', 'surface:witness-count-is-record-count', html.includes('in ' + numberWord(data.witnesses.length) + ' printings') && html.includes('from ' + numberWord(data.witnesses.length) + ' lumber books') && html.includes('The ' + numberWord(data.witnesses.length) + ' witnesses'));
  check('rendered_figures_asserted', 'surface:anchor-length-is-record-coordinate', html.includes("Freese's printed " + String(anchor.length_ft) + '-foot Doyle row'));
  check('rendered_figures_asserted', 'surface:rights-counts-are-record-counts', html.includes('The first ' + numberWord(publicDomainMarkCount) + ' Internet Archive records name the Public Domain Mark.') && html.includes('The ' + numberWord(noRightsFieldCount) + ' Canadian records supplied no rights field'));
  check('rendered_figures_asserted', 'surface:apparatus-scope', html.includes(capitalizedNumberWord(data.cells.length) + ' cell coordinates are frozen here.') && html.includes('The 1903 and 1910 tables are represented at the cells needed for the provenance result'));
  check('rendered_figures_asserted', 'surface:rights-uncertainty', html.includes('The ' + numberWord(noRightsFieldCount) + ' Canadian records supplied no rights field, so no scans are shipped.') && html.includes('the 1903 table prints a copyright notice'));
  check('rendered_figures_asserted', 'surface:novelty-sentence', html.includes(expectedNovelty));
  check('rendered_figures_asserted', 'surface:source-list', visibleText(classBlock(html, 'ol', 'source-list') || '') === expectedSources);
  check('rendered_figures_asserted', 'surface:refusal-wording', html.includes('A refusal never fills the blank from the formula.') && html.includes('A witness without a transcribed cell is not silently filled from the rule.'));
  check('rendered_figures_asserted', 'surface:article-jsonld', (() => {
    const match = html.match(/<script\b[^>]*type=["']application\/ld\+json["'][^>]*>([\s\S]*?)<\/script>/i);
    if (!match) return false;
    const json = JSON.parse(match[1]);
    return json['@type'] === 'Article' && json.name === expectedTitle && json.headline === expectedName && json.description === expectedDek && json.url === expectedUrl && json.image === expectedImage && json.datePublished === '2026-09-15';
  })());
  const inlineScripts = [...html.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)].filter(match => !/\bsrc\s*=/.test(match[1]));
  check('rendered_figures_asserted', 'surface:only-jsonld-inline-script', inlineScripts.length === 1 && /application\/ld\+json/i.test(inlineScripts[0][1]));
  check('rendered_figures_asserted', 'surface:closing-tags', html.trim().endsWith('</body>\n</html>') && html.includes('</script>'));
  check('rendered_figures_asserted', 'surface:accessibility-hooks', html.includes(':focus-visible') && html.includes('prefers-reduced-motion') && html.includes('aria-live="polite"'));
  check('rendered_figures_asserted', 'surface:no-third-party-module-url', ['data.js', 'engine.js', 'render.js', 'page.js'].every(file => !/https?:\/\//.test(readText(path.join(pageDir, file)))));

  check('choices_are_live', 'choices:manifest-matches-engine', record.choices.length === CHOICES.length && record.choices.every((choice, index) => deepEqual(choice, CHOICES[index])));
  for (const choice of CHOICES) {
    const fingerprints = choice.options.map(option => {
      let value = option;
      if (choice.id === 'witnesses') value = option === 'all' ? [...WITNESS_IDS] : WITNESS_IDS.filter(id => id !== option.replace('without-', ''));
      return modelFingerprint(analyze(data, {...DEFAULT_OPTIONS, [choice.id]: value}));
    });
    check('choices_are_live', 'choice:' + choice.id + ':each-option-changes-output', new Set(fingerprints).size === choice.options.length);
    const optionsInControl = choice.id === 'witnesses'
      ? WITNESS_IDS.every(id => html.includes('value="' + id + '"'))
      : choice.options.every(option => html.includes('value="' + option + '"'));
    check('choices_are_live', 'choice:' + choice.id + ':each-option-is-in-the-control', optionsInControl);
  }

  const cleanPairCount = model.pairShares['W2|W7'].count;
  const badW7 = structuredClone(data);
  const badW7Cell = badW7.cells.find(cell => cell.length_ft === 28 && cell.diameter_in === 30);
  badW7Cell.readings.W7.as_printed = 1183;
  const badW7Model = analyze(badW7, DEFAULT_OPTIONS);
  check('planted_fault_caught', 'fault:clean-w2-w7-share-count-is-11', cleanPairCount === 11);
  check('planted_fault_caught', 'fault:doctored-w7-value-falls-by-one', badW7Model.pairShares['W2|W7'].count === cleanPairCount - 1);
  const badW2 = structuredClone(data);
  const badW2Cell = badW2.cells.find(cell => cell.length_ft === 20 && cell.diameter_in === 10);
  badW2Cell.readings.W2.as_printed = 45;
  check('planted_fault_caught', 'fault:clean-all-witnesses-still-share-46', allWitnessesReading(data, 20, 10, 46) === true);
  check('planted_fault_caught', 'fault:doctored-w2-stops-all-witness-46', allWitnessesReading(badW2, 20, 10, 46) === false);
  check('planted_fault_caught', 'fault:doctored-w2-changes-headline-path', headlineFor(badW2) !== computedHeadline && headlineFor(badW2).includes('matches plate B at 13'));

  const outside = outsideRecordRefusal(data, 20, 8, 'W1');
  const untranscribed = outsideRecordRefusal(data, 20, 16, 'W1');
  const inspectedOutside = inspectCell(data, 20, 8, DEFAULT_OPTIONS);
  const emptyWitnessModel = analyze(data, {...DEFAULT_OPTIONS, witnesses: []});
  const withoutW6Model = analyze(data, {...DEFAULT_OPTIONS, witnesses: WITNESS_IDS.filter(id => id !== 'W6')});
  const withoutW2Model = analyze(data, {...DEFAULT_OPTIONS, witnesses: WITNESS_IDS.filter(id => id !== 'W2')});
  const withoutW6PlateB = withoutW6Model.hypotheses.find(hypothesis => hypothesis.id === 'plate-B');
  const withoutW2PlateB = withoutW2Model.hypotheses.find(hypothesis => hypothesis.id === 'plate-B');
  check('refusal_asserted', 'refuse:outside-declared-range', outside.refused === true && outside.reason.includes('not printed in W1'));
  check('refusal_asserted', 'refuse:inside-range-but-untranscribed', untranscribed.refused === true && untranscribed.reason.includes('not read in the frozen transcription block'));
  check('refusal_asserted', 'refuse:inspect-does-not-invent-observations', inspectedOutside.refused === true && inspectedOutside.observations.length === 0 && inspectedOutside.groupedObservations.length === 0);
  check('refusal_asserted', 'refuse:page-explains-no-formula-fill', html.includes('A refusal never fills the blank from the formula.') && html.includes('A witness without a transcribed cell is not silently filled from the rule.'));
  check('refusal_asserted', 'refuse:empty-witness-selection-is-not-restored', emptyWitnessModel.refusal && emptyWitnessModel.options.witnesses.length === 0 && emptyWitnessModel.counts.observationCount === 0 && comparisonSentence(emptyWitnessModel).includes('Select at least one witness'));
  check('refusal_asserted', 'refuse:zero-target-denominator-is-unavailable', withoutW6PlateB && withoutW6PlateB.unavailable && withoutW6PlateB.compared === 0 && comparisonSentence(withoutW6Model).includes('comparison is unavailable'));
  check('refusal_asserted', 'refuse:partial-target-uses-actual-denominator', withoutW2PlateB && withoutW2PlateB.compared === 3 && comparisonSentence(withoutW2Model).includes('of 3 compared cells'));

  const expectedHashes = Object.fromEntries(record.data_files.map(file => [file.path, file.sha256]));
  const dataFiles = ['doyle-diagnostic.json', 'freese-anchor.json', 'joint-resolution.json'];
  for (const file of dataFiles) {
    const researchFile = path.join(researchDataDir, file);
    const publicFile = path.join(publicDataDir, file);
    const researchHash = sha256(researchFile);
    const publicHash = sha256(publicFile);
    check('provenance_pinned', 'provenance:' + file + ':research-hash', researchHash === expectedHashes[file]);
    check('provenance_pinned', 'provenance:' + file + ':public-hash', publicHash === expectedHashes[file]);
    check('provenance_pinned', 'provenance:' + file + ':research-public-json-equal', deepEqual(readJson(researchFile), readJson(publicFile)));
    check('provenance_pinned', 'provenance:' + file + ':readme-hash', readText(path.join(here, 'README.md')).includes(expectedHashes[file]));
  }
  check('provenance_pinned', 'provenance:primary-record-hash', record.record.sha256 === expectedHashes['doyle-diagnostic.json']);
  check('provenance_pinned', 'provenance:record-unit-count', record.record.units === model.counts.observationCount);
  check('provenance_pinned', 'provenance:all-readings-have-locators-and-two-passes', data.cells.every(cell => Object.values(cell.readings).every(reading => reading.as_written && reading.as_printed !== undefined && reading.pass_a !== undefined && reading.pass_b !== undefined && Number.isInteger(reading.page) && Number.isInteger(reading.leaf))));
  check('provenance_pinned', 'provenance:resolution-preserves-furnised', resolution.restriction_clause_as_written.includes('furnised'));
  check('provenance_pinned', 'provenance:record-rights-scope-is-explicit', record.record.licence_scope === 'W1 and W2 only; W3 through W7 have the witness-specific rights statuses below' && record.record.witness_rights && Object.keys(record.record.witness_rights).length === 7 && record.record.witness_rights.W3.status.includes('No rights') && record.record.witness_rights.W3.url === data.witnesses.find(witness => witness.id === 'W3').metadata_url);

  const actualLedger = Object.fromEntries(ledgerKeys.map(key => [key, groups[key].length > 0 && groups[key].every(assertion => assertion.pass)]));
  for (const key of ledgerKeys) {
    if (!record.ledger || record.ledger[key]?.value !== actualLedger[key]) externalFailures.push('record ledger disagrees for ' + key);
  }
  const overallPass = Object.values(actualLedger).every(Boolean) && failures.length === 0 && externalFailures.length === 0;
  const ledgerOutput = ledgerKeys.map(key => key + '=' + String(actualLedger[key])).join('\n') + '\n';
  if (process.argv.includes('--ledger')) {
    process.stdout.write(ledgerOutput);
    if (!overallPass) process.stderr.write([...failures, ...externalFailures].map(item => 'FAIL ' + item).join('\n') + '\n');
  } else {
    for (const failure of [...failures, ...externalFailures]) console.error('FAIL ' + failure);
    console.log(ledgerOutput.trim());
    console.log('assertions=' + (groups[ledgerKeys[0]].length + groups[ledgerKeys[1]].length + groups[ledgerKeys[2]].length + groups[ledgerKeys[3]].length + groups[ledgerKeys[4]].length + groups[ledgerKeys[5]].length));
  }
  process.exitCode = overallPass ? 0 : 1;
}

try {
  main();
} catch (error) {
  if (process.argv.includes('--ledger')) {
    process.stdout.write(ledgerKeys.map(key => key + '=false').join('\n') + '\n');
  } else {
    console.error(error.stack || error.message);
  }
  process.exitCode = 1;
}
