#!/usr/bin/env node
// Offline verifier for /strata/halflife-disagreement/.
//
// Three obligations, in order:
//   1. Independently recompute everything the page shows, from the committed
//      primary records, with code that does not import the page's engine.
//   2. Execute the shipped page's own inline engine and assert it agrees.
//   3. Mutate inputs and conventions and assert the checks turn red.
//
// Run: node research/halflife-disagreement/verify-halflife-disagreement.mjs

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

const here = path.dirname(fileURLToPath(import.meta.url));
const root = path.resolve(here, '../..');
const pagePath = path.join(root, 'public/strata/halflife-disagreement/index.html');
const entryPath = path.join(root, 'src/content/strata/halflife-disagreement.md');
const commentsPath = path.join(here, 'data/nubase2020-birge-comments.txt');
const censusPath = path.join(here, 'data/birge-halflife-census.json');
const tablePath = path.join(here, 'data/nubase_4.mas20.txt');

const html = fs.readFileSync(pagePath, 'utf8');
const markdown = fs.readFileSync(entryPath, 'utf8');
const commentsFile = fs.readFileSync(commentsPath, 'utf8');
const census = JSON.parse(fs.readFileSync(censusPath, 'utf8'));
const asciiTable = fs.readFileSync(tablePath, 'utf8');

let checks = 0;
let failures = 0;

function report(ok, label, detail = '') {
  checks += 1;
  console.log(`${ok ? 'PASS' : 'FAIL'} ${String(checks).padStart(3, '0')}  ${label}${detail ? `  ${detail}` : ''}`);
  if (!ok) failures += 1;
  return ok;
}
function equal(actual, expected, label) {
  return report(Object.is(actual, expected), label, `actual=${actual} expected=${expected}`);
}
function close(actual, expected, tolerance, label) {
  const ok = Number.isFinite(actual) && Number.isFinite(expected) && Math.abs(actual - expected) <= tolerance;
  return report(ok, label, `actual=${actual} expected=${expected} tol=${tolerance}`);
}
function truth(value, label, detail = '') {
  return report(Boolean(value), label, detail);
}

// ---------------------------------------------------------------------------
// 0. Constants that this verifier owns. Nothing is read from the page.
// ---------------------------------------------------------------------------

const I = Object.freeze({
  thresholdInternal: 2.5,
  thresholdUnweighted: 4,
  symmetryShift: 0.64,
  publishedGoldValue: 6.165,
  publishedGoldUncertainty: 0.011,
  publishedGoldBirge: 10.86,
  goldInputs: [
    { key: '11Hi19', value: 6.1451, sigma: 0.0013 },
    { key: '01Li17', value: 6.1669, sigma: 0.0006 },
    { key: '63Ik01', value: 6.1830, sigma: 0.0100 }
  ],
  nearRelative: 0.01,
  publicationDate: null
});

// ---------------------------------------------------------------------------
// 1. Independent implementation.
// ---------------------------------------------------------------------------

function ownWeighted(points) {
  let totalWeight = 0;
  let weightedSum = 0;
  for (const point of points) {
    const weight = 1 / (point.sigma ** 2);
    totalWeight += weight;
    weightedSum += weight * point.value;
  }
  const mean = weightedSum / totalWeight;
  let chiSquared = 0;
  for (const point of points) chiSquared += ((point.value - mean) / point.sigma) ** 2;
  return {
    n: points.length,
    mean,
    internal: 1 / Math.sqrt(totalWeight),
    chiSquared,
    birge: points.length > 1 ? Math.sqrt(chiSquared / (points.length - 1)) : null
  };
}

function ownUnweighted(points) {
  const n = points.length;
  let sum = 0;
  for (const point of points) sum += point.value;
  const mean = sum / n;
  let spread = 0;
  for (const point of points) spread += (point.value - mean) ** 2;
  return { n, mean, sigma: n > 1 ? Math.sqrt(spread / (n * (n - 1))) : null };
}

function ownRecommend(points, t1 = I.thresholdInternal, t2 = I.thresholdUnweighted) {
  const w = ownWeighted(points);
  const u = ownUnweighted(points);
  if (w.birge === null) return { rule: 'single', value: w.mean, sigma: w.internal };
  if (w.birge <= t1) return { rule: 'internal', value: w.mean, sigma: w.internal };
  if (w.birge <= t2) return { rule: 'external', value: w.mean, sigma: w.birge * w.internal };
  return { rule: 'unweighted', value: u.mean, sigma: u.sigma };
}

function ownSymmetrise(centre, up, down) {
  return {
    value: centre + I.symmetryShift * (up - down),
    sigma: Math.sqrt((1 - 2 / Math.PI) * (up - down) ** 2 + up * down)
  };
}

// An independent parser for the printed measurement substrings. It knows only
// the conventions the page states, not the page's code.
function ownParse(printed) {
  const match = /^(?:([A-Za-z0-9.,]+)\s*=\s*)?([0-9]+(?:\.[0-9]+)?)\s*\((.*)\)\s*$/.exec(printed.trim());
  if (!match) throw new Error(`unparsable measurement: ${printed}`);
  const [, key, valueText, uncertaintyText] = match;
  const value = Number(valueText);
  const body = uncertaintyText.trim();
  const asymmetric = /^\+([0-9.]+)-([0-9.]+)$/.exec(body);
  if (asymmetric) {
    const s = ownSymmetrise(value, Number(asymmetric[1]), Number(asymmetric[2]));
    return { key, value: s.value, sigma: s.sigma };
  }
  if (/stat|syst/.test(body)) {
    const parts = body.match(/[0-9]+(?:\.[0-9]+)?/g).map(Number);
    return { key, value, sigma: Math.sqrt(parts.reduce((a, b) => a + b * b, 0)) };
  }
  if (/^[0-9]+\.[0-9]+$/.test(body)) return { key, value, sigma: Number(body) };
  if (/^[0-9]+$/.test(body)) {
    const decimals = valueText.includes('.') ? valueText.split('.')[1].length : 0;
    return { key, value, sigma: Number(body) * 10 ** -decimals };
  }
  throw new Error(`unparsable uncertainty: ${printed}`);
}

function ownDecimals(x) {
  const text = String(x);
  const dot = text.indexOf('.');
  return dot < 0 ? 0 : text.length - dot - 1;
}

function ownVerdict(entry, birge) {
  if (birge === null) return 'not-recomputable';
  const gap = Math.abs(birge - entry.printedBirge);
  if (gap <= 0.5 * 10 ** -ownDecimals(entry.printedBirge)) return 'exact';
  return gap / entry.printedBirge <= I.nearRelative ? 'near' : 'miss';
}

console.log('SECTION 1: THE ANCHOR, RECOMPUTED WITHOUT THE PAGE');

const goldWeighted = ownWeighted(I.goldInputs);
const goldUnweighted = ownUnweighted(I.goldInputs);
const goldRecommendation = ownRecommend(I.goldInputs);

close(goldWeighted.mean, 6.16313067559, 5e-11, 'gold-196 inverse-variance weighted mean');
close(goldWeighted.internal, 0.000543969032, 5e-12, 'gold-196 internal uncertainty');
close(goldWeighted.chiSquared, 235.784007365, 5e-9, 'gold-196 chi-squared about the weighted mean');
close(goldWeighted.birge, 10.8578084199, 5e-10, 'gold-196 Birge ratio, equation 4');
equal(Number(goldWeighted.birge.toFixed(2)), I.publishedGoldBirge, 'gold-196 Birge ratio rounds to the printed 10.86');
truth(goldWeighted.birge > I.thresholdUnweighted, 'gold-196 exceeds the threshold where NUBASE abandons weighting',
  `B=${goldWeighted.birge.toFixed(4)} > ${I.thresholdUnweighted}`);
equal(goldRecommendation.rule, 'unweighted', 'the rule selected for gold-196 is the arithmetic mean');
close(goldUnweighted.mean, 6.165, 1e-12, 'gold-196 arithmetic mean, equation 6');
close(goldUnweighted.sigma, 0.0109819548958, 5e-12, 'gold-196 external spread, equation 6');
equal(Number(goldRecommendation.value.toFixed(3)), I.publishedGoldValue, 'recommended value reproduces the published 6.165 d');
equal(Number(goldRecommendation.sigma.toFixed(3)), I.publishedGoldUncertainty, 'recommended uncertainty reproduces the published 0.011 d');

// The published fixed-width row is the second, independent witness.
const goldRow = asciiTable.split('\n').find(line => line.startsWith('196 0790'));
truth(Boolean(goldRow), 'gold-196 row located in the fixed-width NUBASE2020 table');
equal(goldRow.slice(69, 78).trim(), '6.165', 'fixed-width table half-life field');
equal(goldRow.slice(78, 80).trim(), 'd', 'fixed-width table half-life unit');
equal(goldRow.slice(81, 88).trim(), '0.011', 'fixed-width table half-life uncertainty');

// The counterfactual the evaluators did NOT take.
close(goldWeighted.birge * goldWeighted.internal, 0.00590631153299, 5e-12,
  'mechanically inflating the weighted result would have given a different uncertainty');
truth(Math.abs(goldWeighted.birge * goldWeighted.internal - goldUnweighted.sigma) > 0.004,
  'the inflated and the adopted uncertainties are materially different');

console.log('\nSECTION 2: THE COMMITTED RECORD MATCHES THE VERBATIM SOURCE LINES');

const commentLines = new Map();
for (const line of commentsFile.split('\n')) {
  if (!line.trim() || line.startsWith('#')) continue;
  const match = /^\s*(\d+)\s\s(.*)$/.exec(line);
  if (!match) continue;
  commentLines.set(Number(match[1]), match[2]);
}
truth(commentLines.size >= 57, 'verbatim comment file carries the flagged comment lines', `lines=${commentLines.size}`);

let transcriptionChecks = 0;
for (const entry of census.entries) {
  const joined = entry.lines.map(n => commentLines.get(n)).join(' ');
  truth(entry.lines.every(n => commentLines.has(n)), `${entry.slug}: every cited source line is present`);
  for (const item of entry.inputs.concat(entry.excluded)) {
    if (!joined.includes(item.printed)) {
      report(false, `${entry.slug}: printed substring ${item.printed} not found in its source lines`);
    }
    transcriptionChecks += 1;
    const own = ownParse(item.printed);
    if (Math.abs(own.value - item.value) > 1e-9 || Math.abs(own.sigma - item.sigma) > 1e-9) {
      report(false, `${entry.slug}: independent parse of ${item.printed} disagrees`,
        `own=${own.value}±${own.sigma} record=${item.value}±${item.sigma}`);
    }
  }
  truth(joined.includes('Birge'), `${entry.slug}: source lines contain the Birge flag`);
  truth(joined.includes(entry.printedPhrase), `${entry.slug}: printed Birge phrase appears verbatim`);
}
report(true, 'independent parser reproduced every transcribed value and uncertainty',
  `${transcriptionChecks} measurement substrings`);

// Counts, recomputed from the verbatim file rather than trusted.
const halfLifeFlagged = [...commentLines.values()].filter(l => /\sT\s*:/.test(l) && l.includes('Birge'));
const decayFlagged = [...commentLines.values()].filter(l => /\sD\s*:/.test(l) && l.includes('Birge'));
const literalFlagged = halfLifeFlagged.filter(l => l.includes('Birge ratio'));
equal(halfLifeFlagged.length, census.counts.halfLifeCommentLinesWithBirge, 'half-life comment lines carrying Birge');
equal(decayFlagged.length, census.counts.decayCommentLinesWithBirge, 'decay comment lines carrying Birge');
equal(literalFlagged.length, census.counts.halfLifeCommentsWithLiteralBirgeRatio, 'literal "Birge ratio" count');
equal(census.entries.length, census.counts.halfLifeCommentsWithBirge, 'record carries one entry per flagged half-life comment');
equal(census.counts.halfLifeCommentsWithBirge - census.counts.halfLifeCommentsWithLiteralBirgeRatio, 1,
  'exactly one flagged comment omits the literal words "Birge ratio"');
const nonLiteral = census.entries.filter(e => !e.literalBirgeRatio);
equal(nonLiteral.length, 1, 'the non-literal entry is unique');
equal(nonLiteral[0].slug, '76Ga', 'the non-literal entry is gallium-76');
truth(nonLiteral[0].comment.includes('Birge B=2.7'), 'gallium-76 prints Birge B rather than Birge ratio');
equal(census.counts.everyLineWithBirge,
  census.counts.halfLifeCommentLinesWithBirge + census.counts.decayCommentLinesWithBirge + 1,
  'every article line mentioning Birge is accounted for, definition included');

console.log('\nSECTION 3: THE AUDIT, RECOMPUTED INDEPENDENTLY');

const ownAudit = new Map();
const tally = { exact: 0, near: 0, miss: 0, 'not-recomputable': 0 };
for (const entry of census.entries) {
  const points = entry.inputs.map(item => ownParse(item.printed));
  const w = points.length ? ownWeighted(points) : null;
  const birge = w ? w.birge : null;
  const verdict = ownVerdict(entry, birge);
  tally[verdict] += 1;
  ownAudit.set(entry.slug, { birge, verdict, weighted: w });
}
equal(tally.exact, 41, 'entries reproducing the printed ratio at the precision printed');
equal(tally.near, 2, 'entries within one percent but not at the printed precision');
equal(tally.miss, 2, 'entries that do not reproduce');
equal(tally['not-recomputable'], 1, 'entries whose inputs the comment does not print');
equal(tally.exact + tally.near + tally.miss + tally['not-recomputable'], 46, 'verdicts partition the flagged set');

const misses = census.entries.filter(e => ownAudit.get(e.slug).verdict === 'miss').map(e => e.slug).sort();
equal(misses.join(','), '101Rh-m,134Sn', 'the two non-reproducing entries are named');

// Tin-137 (corrected 2026-10-18): read like 146Tm-m, keeping 02Sh08, the printed
// inputs reproduce both the printed ratio and the adopted uncertainty.
const tinSevenEntry = census.entries.find(e => e.slug === '137Sn');
const tinSevenWeighted = ownAudit.get('137Sn').weighted;
equal(ownAudit.get('137Sn').verdict, 'exact', 'tin-137 reproduces its printed 3.09 with 02Sh08 kept');
equal(Math.round(tinSevenWeighted.birge * tinSevenWeighted.internal), Number(tinSevenEntry.adoptedUncertainty),
  'tin-137 inflated internal uncertainty rounds to the adopted 15 ms');
equal(Math.round(tinSevenWeighted.mean), Number(tinSevenEntry.adopted), 'tin-137 weighted mean rounds to the adopted 249 ms');
const tinSevenThree = tinSevenEntry.inputs.filter(item => item.key !== '02Sh08').map(item => ownParse(item.printed));
truth(ownVerdict(tinSevenEntry, ownWeighted(tinSevenThree).birge) === 'miss',
  'dropping 02Sh08 as well (the pre-2026-10-18 reading) does not reproduce');
const nears = census.entries.filter(e => ownAudit.get(e.slug).verdict === 'near').map(e => e.slug).sort();
equal(nears.join(','), '148La,94Y-m', 'the two near-miss entries are named');

const maxPrinted = Math.max(...census.entries.map(e => e.printedBirge));
equal(maxPrinted, I.publishedGoldBirge, 'the largest printed half-life Birge ratio is gold-196');
close(ownAudit.get('196Au').birge, goldWeighted.birge, 1e-12, 'the record path and the anchor path agree for gold-196');

// The tin-134 reconstruction the page offers, recomputed here.
const tin = census.entries.find(e => e.slug === '134Sn');
const tinCandidate = tin.inputs.map(item => {
  const parsed = ownParse(item.printed);
  return item.key === '15Lo04' ? { ...parsed, sigma: 0.02 } : parsed;
});
close(ownWeighted(tinCandidate).birge, 4.148222210255683, 1e-9,
  'reading tin-134 15Lo04 as 0.02 rather than 0.2 reproduces the printed 4.15');
equal(Number(ownWeighted(tinCandidate).birge.toFixed(2)), tin.printedBirge,
  'the reconstructed tin-134 ratio rounds to the printed value');
truth(ownAudit.get('134Sn').birge < 2, 'tin-134 as printed is far from its printed ratio',
  `recomputed=${ownAudit.get('134Sn').birge.toFixed(4)}`);

// Rhodium-101m's internal tension: the adopted uncertainty equals the internal one.
const rhodium = census.entries.find(e => e.slug === '101Rh-m');
const rhodiumWeighted = ownAudit.get('101Rh-m').weighted;
close(Number(rhodium.adoptedUncertainty), Number(rhodiumWeighted.internal.toFixed(3)), 1e-9,
  'rhodium-101m publishes the uninflated internal uncertainty of its printed inputs');
truth(rhodium.printedBirge > I.thresholdInternal,
  'yet its printed ratio is above the threshold at which the internal uncertainty is kept');

// Leave-one-out, recomputed independently.
function ownLeaveOneOut(points) {
  if (points.length < 3) return null;
  const full = ownWeighted(points);
  let worst = null;
  points.forEach((p, i) => {
    const contribution = ((p.value - full.mean) / p.sigma) ** 2;
    const without = ownWeighted(points.filter((_, j) => j !== i));
    if (!worst || contribution > worst.contribution) {
      worst = { key: p.key, contribution, birge: without.birge };
    }
  });
  return { full: full.birge, worst };
}
const goldLeave = ownLeaveOneOut(I.goldInputs);
equal(goldLeave.worst.key, '11Hi19', 'gold-196 leave-one-out selects the 2011 measurement');
close(goldLeave.worst.birge, 1.607109801199882, 1e-9, 'gold-196 ratio without the 2011 measurement');
truth(goldLeave.worst.birge <= I.thresholdUnweighted, 'gold-196 falls out of the unweighted band once one input is dropped');
const iridiumPoints = census.entries.find(e => e.slug === '194Ir').inputs.map(item => ownParse(item.printed));
const iridiumLeave = ownLeaveOneOut(iridiumPoints);
truth(iridiumLeave.worst.birge > I.thresholdUnweighted,
  'iridium-194 stays in the unweighted band even after its worst input is dropped',
  `${iridiumLeave.full.toFixed(3)} -> ${iridiumLeave.worst.birge.toFixed(3)}`);
// Corrected 2026-10-18: not because all three disagree. 16Kr06 and 72Ge10 agree;
// the outlier is 72Em01, and the worst-contributor rule drops 16Kr06 instead.
equal(iridiumLeave.worst.key, '16Kr06', 'iridium-194 leave-one-out selects 16Kr06');
const irKr = iridiumPoints.find(p => p.key === '16Kr06');
const irGe = iridiumPoints.find(p => p.key === '72Ge10');
truth(Math.abs(irKr.value - irGe.value) / Math.hypot(irKr.sigma, irGe.sigma) < 1.5,
  'iridium-194: 16Kr06 and 72Ge10 agree within 1.5 combined standard deviations');
const irNoEm = ownWeighted(iridiumPoints.filter(p => p.key !== '72Em01'));
truth(irNoEm.birge < 1.5, 'iridium-194 without 72Em01 falls below 1.5', irNoEm.birge.toFixed(3));

console.log('\nSECTION 4: EXECUTE THE SHIPPED PAGE ENGINE AND COMPARE');

const engineMatch = /<script id="hd-engine">([\s\S]*?)<\/script>/.exec(html);
truth(Boolean(engineMatch), 'the page carries an extractable engine script');
const context = vm.createContext({ console });
vm.runInContext(engineMatch[1], context, { filename: 'halflife-disagreement-page-engine.js' });
const P = context.HDEngine;
truth(P && typeof P.auditAll === 'function', 'shipped engine executed and exported its API');

const islandMatch = /<script type="application\/json" id="census-data">([\s\S]*?)<\/script>/.exec(html);
truth(Boolean(islandMatch), 'the page carries an embedded data island');
const island = JSON.parse(islandMatch[1]);
equal(island.entries.length, census.entries.length, 'embedded island and committed record have the same entry count');
equal(JSON.stringify(island.counts), JSON.stringify(census.counts), 'embedded island counts match the committed record');
let islandDrift = 0;
for (let i = 0; i < island.entries.length; i += 1) {
  if (JSON.stringify(island.entries[i]) !== JSON.stringify(census.entries[i])) islandDrift += 1;
}
equal(islandDrift, 0, 'every embedded entry is byte-identical to the committed record');

equal(P.C.T1, I.thresholdInternal, 'page threshold 1 matches the paper');
equal(P.C.T2, I.thresholdUnweighted, 'page threshold 2 matches the paper');
equal(P.C.SYM_SHIFT, I.symmetryShift, 'page symmetrisation coefficient matches equation 12');
equal(P.C.ANCHOR_VALUE, I.publishedGoldValue, 'page anchor value matches the published table');
equal(P.C.ANCHOR_UNCERTAINTY, I.publishedGoldUncertainty, 'page anchor uncertainty matches the published table');
equal(P.C.ANCHOR_BIRGE, I.publishedGoldBirge, 'page anchor Birge ratio matches the printed comment');

const pageGold = P.weighted(island.entries.find(e => e.slug === '196Au').inputs);
close(pageGold.mean, goldWeighted.mean, 1e-13, 'page weighted mean matches independent');
close(pageGold.internal, goldWeighted.internal, 1e-15, 'page internal uncertainty matches independent');
close(pageGold.chi2, goldWeighted.chiSquared, 1e-10, 'page chi-squared matches independent');
close(pageGold.birge, goldWeighted.birge, 1e-12, 'page Birge ratio matches independent');
const pageRecommendation = P.recommend(island.entries.find(e => e.slug === '196Au').inputs, P.C.T1, P.C.T2);
equal(pageRecommendation.rule, goldRecommendation.rule, 'page rule selection matches independent');
close(pageRecommendation.value, goldRecommendation.value, 1e-13, 'page recommended value matches independent');
close(pageRecommendation.sigma, goldRecommendation.sigma, 1e-14, 'page recommended uncertainty matches independent');

const pageSymmetric = P.symmetrise(261, 22, 18);
const ownSymmetric = ownSymmetrise(261, 22, 18);
close(pageSymmetric.value, ownSymmetric.value, 1e-12, 'page symmetrisation centre matches equation 12');
close(pageSymmetric.sigma, ownSymmetric.sigma, 1e-12, 'page symmetrisation width matches equation 9');

const pageAudit = P.auditAll(island.entries);
equal(pageAudit.counts.exact, tally.exact, 'page exact count matches independent');
equal(pageAudit.counts.near, tally.near, 'page near count matches independent');
equal(pageAudit.counts.miss, tally.miss, 'page miss count matches independent');
equal(pageAudit.counts['not-recomputable'], tally['not-recomputable'], 'page not-recomputable count matches independent');
let verdictDrift = 0;
let birgeDrift = 0;
for (const row of pageAudit.rows) {
  const mine = ownAudit.get(row.entry.slug);
  if (mine.verdict !== row.verdict) verdictDrift += 1;
  if (mine.birge !== null && Math.abs(mine.birge - row.birge) > 1e-11) birgeDrift += 1;
}
equal(verdictDrift, 0, 'every page verdict matches the independent verdict');
equal(birgeDrift, 0, 'every page ratio matches the independent ratio');

const pageSweep = P.sweep(island.entries, 1, P.C.T1, P.C.T2);
equal(pageSweep.considered, 45, 'page sweep considers every entry with printed inputs');
equal(pageSweep.moved, 0, 'at NUBASE settings the sweep reports no moved recommendation, as the page discloses');
equal(pageSweep.bands.internal + pageSweep.bands.external + pageSweep.bands.unweighted, 45, 'sweep bands partition the set');
let ownAbove = 0;
let ownTestable = 0;
let ownRescued = 0;
for (const entry of census.entries) {
  const record = ownAudit.get(entry.slug);
  if (!record.weighted || record.weighted.birge === null) continue;
  if (record.weighted.birge > I.thresholdUnweighted) {
    ownAbove += 1;
    const leave = ownLeaveOneOut(entry.inputs.map(item => ownParse(item.printed)));
    if (leave) {
      ownTestable += 1;
      if (leave.worst.birge <= I.thresholdUnweighted) ownRescued += 1;
    }
  }
}
equal(pageSweep.above, ownAbove, 'page count above the threshold matches independent');
equal(pageSweep.testable, ownTestable, 'page testable count matches independent');
equal(pageSweep.rescued, ownRescued, 'page leave-one-out rescue count matches independent');
equal(ownRescued, 6, 'six of the testable entries above the threshold are carried by a single measurement');
equal(ownTestable, 7, 'seven entries above the threshold have enough inputs to test');

const pageVariants = P.conventionVariants(I.goldInputs);
close(pageVariants.nubase, 10.8578084199, 1e-9, 'page convention table: NUBASE equation 4');
close(pageVariants.overN, 8.8653634512, 1e-9, 'page convention table: dividing by N');
close(pageVariants.reducedChiSquared, 117.8920037, 1e-6, 'page convention table: reduced chi-squared itself');
close(pageVariants.aboutUnweightedMean, 11.1263925323, 1e-9, 'page convention table: residuals about the unweighted mean');

// Every number the page asserts in prose must be reachable from the engine.
const bodyText = html.replace(/<script[\s\S]*?<\/script>/g, '');
truth(!/we discovered|the first census|unknown until now|for the first time/i.test(bodyText),
  'the page makes no discovery or priority claim');
truth(bodyText.includes('we could not find this published as of 2026-08-01')
  || bodyText.includes('we could not find this published as of 2026-08-01.')
  || /could not find this published as of 2026-08-01/.test(bodyText),
  'the page uses the required hedged absence claim');
truth(!bodyText.includes(String.fromCharCode(0x2014)), 'the page body contains no em dash');
truth(html.includes('role="status"') && html.includes('aria-live'), 'live regions are announced');
truth(html.includes('prefers-reduced-motion'), 'a reduced-motion guard is present');
truth(html.includes(':focus-visible'), 'focus rings are styled');
truth(!/https?:\/\/(?!artwaste\.land|doi\.org|creativecommons\.org|schema\.org)/.test(
  html.replace(/<script type="application\/ld\+json">[\s\S]*?<\/script>/g, '')
    .replace(/<script type="application\/json"[\s\S]*?<\/script>/g, '')),
  'the page requests nothing from a third-party host');
truth(html.trimEnd().endsWith('</body>\n</html>'), 'the closing tags that keep inline script alive are present');

const frontmatterDate = /^date:\s*(\S+)\s*$/m.exec(markdown);
truth(Boolean(frontmatterDate), 'the markdown entry declares a publication date');
truth(html.includes(`"datePublished":"${frontmatterDate[1]}"`), 'JSON-LD datePublished matches the frontmatter date');
const dateModified = /"dateModified":"(\d{4}-\d{2}-\d{2})"/.exec(html);
truth(Boolean(dateModified) && dateModified[1] >= frontmatterDate[1], 'JSON-LD dateModified is on or after the frontmatter date');
truth(bodyText.includes(frontmatterDate[1]), 'the absence claim is dated with the frontmatter date');
truth(/^seam:\s*"groundtruth"\s*$/m.test(markdown), 'the entry is filed under the groundtruth seam');
truth(/^draft:\s*false\s*$/m.test(markdown), 'the entry is not a draft');
for (const slug of [...markdown.matchAll(/^\s+- to:\s*(\S+)\s*$/gm)].map(m => m[1])) {
  truth(fs.existsSync(path.join(root, 'src/content/strata', `${slug}.md`)), `relates edge ${slug} exists`);
}

console.log('\nSECTION 5: MUTATION SWEEP, PROVE THE CHECKS CAN FAIL');

let attempted = 0;
let caught = 0;
function mutation(label, detected) {
  attempted += 1;
  if (detected) caught += 1;
  report(Boolean(detected), `mutation caught: ${label}`);
}

mutation('treat the Birge ratio as reduced chi-squared itself',
  Math.abs(goldWeighted.chiSquared / 2 - goldWeighted.birge) > 1);
mutation('divide chi-squared by N instead of N minus 1',
  Number(Math.sqrt(goldWeighted.chiSquared / 3).toFixed(2)) !== I.publishedGoldBirge);
mutation('omit the square root entirely',
  Number(goldWeighted.chiSquared.toFixed(2)) !== I.publishedGoldBirge);
mutation('take residuals about the unweighted mean',
  (() => {
    let chi = 0;
    for (const p of I.goldInputs) chi += ((p.value - goldUnweighted.mean) / p.sigma) ** 2;
    return Number(Math.sqrt(chi / 2).toFixed(2)) !== I.publishedGoldBirge;
  })());
mutation('publish the weighted mean as the recommendation',
  Number(goldWeighted.mean.toFixed(3)) !== I.publishedGoldValue);
mutation('inflate the weighted uncertainty by B instead of dropping the weights',
  Number((goldWeighted.birge * goldWeighted.internal).toFixed(3)) !== I.publishedGoldUncertainty);
mutation('use equal weights when computing the ratio',
  (() => {
    const equalSigma = I.goldInputs.map(p => ({ ...p, sigma: 0.001 }));
    return Math.abs(ownWeighted(equalSigma).birge - goldWeighted.birge) > 1;
  })());
mutation('drop the 1963 input from the anchor',
  Math.abs(ownWeighted(I.goldInputs.slice(0, 2)).birge - goldWeighted.birge) > 1);
mutation('read every uncertainty as two sigma',
  Math.abs(ownWeighted(I.goldInputs.map(p => ({ ...p, sigma: p.sigma / 2 }))).birge - 2 * goldWeighted.birge) < 1e-9
    && Number(ownWeighted(I.goldInputs.map(p => ({ ...p, sigma: p.sigma / 2 }))).birge.toFixed(2)) !== I.publishedGoldBirge);
mutation('use an isomer instead of the ground state',
  (() => {
    const isomerRow = asciiTable.split('\n').find(line => line.startsWith('196 0791'));
    return Boolean(isomerRow) && isomerRow.slice(69, 78).trim() !== '6.165';
  })());
mutation('read a trailing-digit uncertainty as an absolute one',
  Math.abs(ownParse('61Ki05=32.643(260)').sigma - 260) > 1);
mutation('read an absolute uncertainty as trailing digits',
  Math.abs(ownParse('63Ik01=6.183(0.010)').sigma - 10) > 1);
mutation('add statistical and systematic uncertainties linearly',
  Math.abs(ownParse('09Ak03=670 (12, stat) (30, syst)').sigma - 42) > 1);
mutation('symmetrise an asymmetric uncertainty at its midpoint',
  Math.abs(ownSymmetrise(261, 22, 18).value - 261) > 1e-9);
mutation('symmetrise without NUBASE equation 9',
  Math.abs(ownSymmetrise(261, 22, 18).sigma - 20) > 1e-6);
mutation('drop the naive symmetrisation and lose thorium-217 agreement',
  (() => {
    const thorium = census.entries.find(e => e.slug === '217Th');
    const naive = thorium.inputs.map(item => {
      const asym = /\(\+([0-9.]+)-([0-9.]+)\)/.exec(item.printed);
      if (!asym) return ownParse(item.printed);
      return { key: item.key, value: Number(/=([0-9.]+)/.exec(item.printed)[1]),
        sigma: (Number(asym[1]) + Number(asym[2])) / 2 };
    });
    return ownVerdict(thorium, ownWeighted(naive).birge) !== 'exact';
  })());
mutation('include the values a comment marks as superseded',
  (() => {
    const tinSeven = census.entries.find(e => e.slug === '137Sn');
    const all = tinSeven.inputs.concat(tinSeven.excluded).map(item => ownParse(item.printed));
    return ownVerdict(tinSeven, ownWeighted(all).birge) !== 'exact';
  })());
mutation('include the value gadolinium-153 calls discrepant',
  (() => {
    const gadolinium = census.entries.find(e => e.slug === '153Gd');
    const all = gadolinium.inputs.concat(gadolinium.excluded).map(item => ownParse(item.printed));
    return ownVerdict(gadolinium, ownWeighted(all).birge) !== 'exact';
  })());
mutation('corrupt one transcribed input value by one part in a thousand',
  (() => {
    const bent = I.goldInputs.map((p, i) => (i === 1 ? { ...p, value: p.value * 1.001 } : p));
    return Number(ownWeighted(bent).birge.toFixed(2)) !== I.publishedGoldBirge;
  })());
mutation('count decay comments as half-life comments',
  census.counts.halfLifeCommentLinesWithBirge + census.counts.decayCommentLinesWithBirge
    !== census.counts.halfLifeCommentsWithBirge);
mutation('count every line mentioning Birge, definition included',
  census.counts.everyLineWithBirge !== census.counts.halfLifeCommentsWithBirge);
mutation('use the literal-string count as if it were the semantic count',
  census.counts.halfLifeCommentsWithLiteralBirgeRatio !== census.counts.halfLifeCommentsWithBirge);
mutation('treat the mercury-197 hypothetical as an adopted evaluation',
  (() => {
    const mercury = census.entries.find(e => e.slug === '197Hg');
    const adopted = mercury.inputs.filter(item => item.key !== '66El09').map(item => ownParse(item.printed));
    return Math.abs(ownWeighted(adopted).birge - mercury.printedBirge) > 1;
  })());
mutation('claim every printed ratio reproduces',
  tally.miss > 0);
mutation('claim no printed ratio reproduces',
  tally.exact > 0);
mutation('let the page engine and the independent code drift',
  (() => {
    const bent = P.weighted(I.goldInputs.map(p => ({ ...p, sigma: p.sigma * 1.01 })));
    return Math.abs(bent.birge - goldWeighted.birge) > 1e-6;
  })());
mutation('scale every uncertainty and expect the weighted mean to move',
  (() => {
    const scaled = ownWeighted(I.goldInputs.map(p => ({ ...p, sigma: p.sigma * 3 })));
    return Math.abs(scaled.mean - goldWeighted.mean) < 1e-12 && Math.abs(scaled.birge * 3 - goldWeighted.birge) < 1e-9;
  })());

console.log(`\nMUTATIONS CAUGHT ${caught}/${attempted}`);
console.log(`ASSERTIONS ${checks}, FAILURES ${failures}`);
if (failures > 0 || caught !== attempted) process.exitCode = 1;
