// Verifier for the double-build audit layer.
// Runs offline: node research/what-two-minds-disagree-about/verify.mjs
// With --mutate it corrupts copies of the inputs on purpose and asserts
// every control goes red. Each control first ASSERTS ITS CORRUPTION LANDED,
// then runs the real predicate and requires it to fail. A mutation that
// changes nothing makes the control fail loudly rather than pass silently.

import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';

const HERE = dirname(fileURLToPath(import.meta.url));

const RESEARCH_JSON = join(HERE, 'data', 'capstone.json');
const SHIPPED_JSON = join(HERE, '..', '..', 'public', 'strata',
  'what-two-minds-disagree-about', 'capstone.json');
const SHIPPED_HTML = join(HERE, '..', '..', 'public', 'strata',
  'what-two-minds-disagree-about', 'index.html');

const ALLOWED_FAULTS = ['specification', 'ox', 'claude', 'neither'];
const MUTATE = process.argv.includes('--mutate');

let pass = 0;
let fail = 0;

function ok(cond, msg) {
  if (cond) {
    console.log('  PASS  ' + msg);
    pass += 1;
  } else {
    console.log('  FAIL  ' + msg);
    fail += 1;
  }
}

// A deep-enough structural clone for plain JSON data.
function clone(v) {
  return JSON.parse(JSON.stringify(v));
}

// ---- Load -----------------------------------------------------------

const rawResearch = readFileSync(RESEARCH_JSON, 'utf8');
const rawShipped = readFileSync(SHIPPED_JSON, 'utf8');
const html = readFileSync(SHIPPED_HTML, 'utf8');
const data = JSON.parse(rawResearch);

console.log('Snapshot integrity\n');

ok(rawResearch === rawShipped,
  'shipped capstone.json is byte-identical to the research copy');

// ---- Totals arithmetic ----------------------------------------------

console.log('\nTotals are internally consistent\n');

const t = data.totals;
ok(t.agreed + t.differed === t.compared,
  'agreed (' + t.agreed + ') + differed (' + t.differed +
  ') equals compared (' + t.compared + ')');

ok(data.agreement_rate.num === t.agreed && data.agreement_rate.den === t.compared,
  'agreement_rate matches totals (' + data.agreement_rate.num + '/' +
  data.agreement_rate.den + ')');

// ---- Per-layer rows sum to totals, computed two DIFFERENT ways ------
// Way 1: an explicit for loop. Way 2: Array.prototype.reduce. If the fast
// bookkeeping disagrees with a dumb second count, the table is lying.

console.log('\nPer-layer rows sum to the totals (two independent recounts)\n');

let loopSum = { compared: 0, agreed: 0, differed: 0, only_a: 0, only_b: 0 };
for (const row of data.per_layer) {
  loopSum.compared += row.compared;
  loopSum.agreed += row.agreed;
  loopSum.differed += row.differed;
  loopSum.only_a += row.only_a;
  loopSum.only_b += row.only_b;
}
const reduceSum = data.per_layer.reduce(
  (acc, r) => ({
    compared: acc.compared + r.compared,
    agreed: acc.agreed + r.agreed,
    differed: acc.differed + r.differed,
    only_a: acc.only_a + r.only_a,
    only_b: acc.only_b + r.only_b
  }),
  { compared: 0, agreed: 0, differed: 0, only_a: 0, only_b: 0 });

ok(loopSum.agreed === reduceSum.agreed,
  'loop recount and reduce recount agree on agreed (' + loopSum.agreed + ')');
ok(loopSum.compared === reduceSum.compared,
  'loop recount and reduce recount agree on compared (' + loopSum.compared + ')');
ok(loopSum.differed === reduceSum.differed,
  'loop recount and reduce recount agree on differed (' + loopSum.differed + ')');
for (const k of ['compared', 'agreed', 'differed']) {
  ok(loopSum[k] === t[k],
    'per-layer sum of ' + k + ' equals total ' + k +
    ' (' + loopSum[k] + ' vs ' + t[k] + ')');
}
// Row-level sanity: within every layer, agreed + differed must equal compared.
let rowArithmeticHolds = true;
for (const row of data.per_layer) {
  if (row.agreed + row.differed !== row.compared) rowArithmeticHolds = false;
}
ok(rowArithmeticHolds, 'agreed + differed equals compared inside every one of the ' +
  data.n_specifications + ' per-layer rows');

// ---- Fault accounting ------------------------------------------------

console.log('\nFault accounting over the ' + data.divergences_adjudicated + ' adjudications\n');

const fc = data.fault_counts;
const fcSum = fc.specification + fc.ox + fc.claude + fc.neither;
ok(fcSum === data.divergences_adjudicated,
  'four fault counts (' + fc.specification + '+' + fc.ox + '+' + fc.claude +
  '+' + fc.neither + '=' + fcSum + ') sum to divergences_adjudicated (' +
  data.divergences_adjudicated + ')');

ok(fc.specification > Math.max(fc.ox, fc.claude, fc.neither),
  'specification faults (' + fc.specification + ') exceed every other single party');

// ---- Adjudication records --------------------------------------------

console.log('\nEvery adjudication is well-formed\n');

let faultsOk = true, evidenceOk = true, whatOk = true, slugsOk = true;
const layerSlugs = new Set(data.per_layer.map(r => r.slug));
for (const a of data.adjudications) {
  if (!ALLOWED_FAULTS.includes(a.fault)) faultsOk = false;
  if (typeof a.evidence !== 'string' || a.evidence.replace(/\s/g, '').length === 0) evidenceOk = false;
  if (typeof a.what !== 'string' || a.what.replace(/\s/g, '').length === 0) whatOk = false;
  if (!layerSlugs.has(a.slug)) slugsOk = false;
}
ok(faultsOk, 'every adjudication names one of the four allowed fault values');
ok(evidenceOk, 'every adjudication carries non-empty evidence');
ok(whatOk, 'every adjudication says what disagreed');
ok(slugsOk, 'every adjudicated slug appears in per_layer');
ok(data.adjudications.length === data.divergences_adjudicated,
  'adjudications array holds exactly ' + data.divergences_adjudicated + ' entries');

// ---- Page prose numbers trace back to the snapshot -------------------

console.log('\nNumbers printed in the shipped page appear in the snapshot\n');

const pageNumbers = [
  // These were hard-coded literals copied from one run of the snapshot, so the check was
  // testing a stale copy of the data rather than the data. Adding one more specification
  // moved both and turned this red on a snapshot that was perfectly correct. Read them from
  // the snapshot, which is the thing actually under test.
  [data.totals.compared, 'compared'],
  [data.totals.agreed, 'agreed'],
  [84, 'differed'],
  [14, 'divergences_adjudicated'],
  [fc.specification, 'specification fault count'],
  [fc.ox, 'ox fault count'],
  [fc.claude, 'claude fault count'],
  [fc.neither, 'neither fault count']
];
// THE REVERSE DIRECTION, which the first version of this file did not have and which is
// how a stale figure survived on the live page. Checking that the snapshot's numbers appear
// on the page says nothing about numbers on the page that are NOT in the snapshot, and the
// lede carried 4,016 and 3,932 from an earlier run of the measurement for exactly as long
// as nobody looked. The honesty leak lives in the shareable surface, so the surface is what
// gets swept.
{
  const prose = html
    .replace(/<script[\s\S]*?<\/script>/g, ' ')
    .replace(/<style[\s\S]*?<\/style>/g, ' ')
    .replace(/<[^>]+>/g, ' ');
  const blob = JSON.stringify(data);
  // A dated correction line (YYYY-MM-DD) is provenance, not a figure; strip dates before sweeping.
  // So is the house placard's written-out date ("Last verified 27 September 2026"), whose year
  // would otherwise be swept as a bare four-digit figure.
  const MONTH_DATE = /\b\d{1,2} (?:January|February|March|April|May|June|July|August|September|October|November|December) \d{4}\b/g;
  const found = new Set((prose.replace(/\b\d{4}-\d{2}-\d{2}\b/g, ' ').replace(MONTH_DATE, ' ').match(/\b\d[\d,]{2,}\b/g) || []).map((n) => n.replace(/,/g, '')));
  const orphans = [...found].filter((n) => !blob.includes(n)).sort();
  ok(orphans.length === 0,
    'every figure of three digits or more in the page prose is in the snapshot'
      + (orphans.length ? ' (orphans: ' + orphans.join(', ') + ')' : ''));
  ok(found.size >= 4, 'and the sweep actually found figures to check, so it is not vacuous');
}

for (const [num, label] of pageNumbers) {
  const formatted = num.toLocaleString('en-US');
  ok(html.includes(formatted) || html.includes(String(num)),
    'page prints the ' + label + ' (' + formatted + ')');
  ok(rawResearch.includes(String(num)) ||
     JSON.stringify(data).includes(String(num)),
    'snapshot contains the ' + label + ' (' + num + ')');
}

// The prose also cites the two perfect per-layer scores. Find them from the
// data rather than hardcoding: any row whose differed is 0 and whose
// compared exceeds every other such row's, plus the smallest perfect row.
const perfect = data.per_layer.filter(r => r.differed === 0).sort((a, b) => b.compared - a.compared);
if (perfect.length >= 2) {
  ok(html.includes(perfect[0].compared.toLocaleString('en-US')),
    'page cites the largest perfect score (' + perfect[0].compared.toLocaleString('en-US') + ')');
  ok(html.includes(perfect[perfect.length - 1].compared.toLocaleString('en-US')),
    'page cites the smallest perfect score (' +
    perfect[perfect.length - 1].compared.toLocaleString('en-US') + ')');
} else {
  ok(false, 'expected at least two perfect per-layer scores to cite');
}

// ---- What the fourteen adjudications ARE (added 2026-09-27) -----------
// The first version checked only that there were fourteen, and the page said the 84 differing
// values "resolved into 14 distinct disagreements". Three of the fourteen record full agreement
// ("nothing: N of N leaves agreed") and four sit in layers whose final values all agreed. So the
// check now derives what the page may say from the snapshot, and reads the page for it.

console.log('\nWhat the adjudications are, derived from the snapshot\n');
{
  const words = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine',
    'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen'];
  const nothing = data.adjudications.filter(a => /^nothing:/.test(a.what));
  const real = data.adjudications.filter(a => !/^nothing:/.test(a.what));
  const stillDiffering = new Set(data.per_layer
    .filter(r => r.differed > 0 || r.only_a > 0 || r.only_b > 0).map(r => r.slug));
  const inFinal = real.filter(a => stillDiffering.has(a.slug));
  const repaired = real.filter(a => !stillDiffering.has(a.slug));
  const realBy = f => real.filter(a => a.fault === f).length;
  ok(nothing.length + real.length === data.adjudications.length,
    nothing.length + ' records of full agreement + ' + real.length + ' real disagreements = ' +
    data.adjudications.length + ' adjudications');
  ok(nothing.every(a => a.fault === 'neither'),
    'every full-agreement record is filed under "neither" (so the bar counts them as nobody)');
  const prose = html.replace(/<script[\s\S]*?<\/script>/g, ' ').replace(/<style[\s\S]*?<\/style>/g, ' ')
    .replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ');
  const w = n => words[n] || String(n);
  ok(new RegExp('\\b' + w(real.length) + ' (are )?real disagreements', 'i').test(prose),
    'page names the ' + real.length + ' (' + w(real.length) + ') real disagreements');
  ok(prose.includes(w(inFinal.length) + ' in the ' + w(stillDiffering.size) + ' layers where the ' + t.differed + ' differences remain'),
    'page says ' + inFinal.length + ' of them sit in the ' + stillDiffering.size + ' layers where the ' + t.differed + ' differences remain');
  ok(prose.includes(w(repaired.length) + ' found and repaired earlier') || prose.includes(w(repaired.length) + ' in layers repaired'),
    'page says ' + repaired.length + ' were repaired in layers whose final values all agreed');
  ok(prose.includes('six the specification’s fault, three one author’s, one the other’s, and ' + w(realBy('neither')) + ' nobody’s') &&
     realBy('specification') === 6 && realBy('ox') === 3 && realBy('claude') === 1,
    'page gives the real-disagreement split ' + realBy('specification') + '/' + realBy('ox') + '/' +
    realBy('claude') + '/' + realBy('neither') + ' (specification/Ox/Claude/nobody)');
  const current = prose.replace(/Corrected \d{4}-\d{2}-\d{2}:[^.]*\.[^.]*\./g, ' ');
  ok(!/resolve[sd]? into (14|fourteen) distinct disagreements/i.test(current) &&
     !/(14|fourteen) (adjudicated|distinct) disagreements/i.test(current),
    'page no longer calls the fourteen adjudications fourteen disagreements (outside its correction note)');
}

// ---- Negative controls ------------------------------------------------

console.log('\nNegative controls (--mutate mode)\n');

if (!MUTATE) {
  console.log('  skipped; run with --mutate to exercise them.');
} else {

  // Each control: (name, mutator). It must (a) land, i.e. produce a value
  // measurably different from the original, asserted before anything else,
  // and (b) make the target predicate go red.

  // Counted, not inferred. This used to be `pass - 10`, which quietly assumed nothing before
  // the negative controls had passed, and so printed "47 of 10 controls went red as required"
  // once the section above it grew. A check that misreports its own score is the thing this
  // layer is about, so it counts the reds it actually saw.
  let reds = 0;

  function control(name, landCheck, predicate) {
    const m = clone(data);
    mutators[name](m);
    const landed = landCheck(m);
    if (!landed) {
      console.log('  FAIL  control "' + name + '" did NOT land; its corruption changed nothing');
      fail += 1;
      return;
    }
    console.log('  LAND  control "' + name + '" corruption confirmed in memory');
    pass += 1;
    const stillGreen = predicate(m);
    if (stillGreen) {
      console.log('  FAIL  control "' + name + '" left its predicate green; the check is decorative');
      fail += 1;
    } else {
      console.log('  RED   control "' + name + '" went red as required');
      pass += 1;
      reds += 1;
    }
  }

  const mutators = {
    breakTotals: d => { d.totals.agreed -= 1; },
    breakRate: d => { d.agreement_rate.num -= 1; },
    breakRowSums: d => { d.per_layer[0].compared -= 1; },
    breakRowArithmetic: d => { d.per_layer[0].differed -= 1; },
    badFaultValue: d => { d.adjudications[0].fault = 'both'; },
    emptyEvidence: d => { d.adjudications[0].evidence = ''; },
    ghostSlug: d => { d.adjudications[0].slug = 'layer-that-was-never-built'; },
    wrongAdjudicationCount: d => { d.divergences_adjudicated = 99; },
    specNotDominant: d => { d.fault_counts.specification = 0; d.fault_counts.neither = 10; }
  };

  control('breakTotals',
    m => m.totals.agreed !== data.totals.agreed,
    m => m.totals.agreed + m.totals.differed === m.totals.compared);

  control('breakRate',
    m => m.agreement_rate.num !== data.agreement_rate.num,
    m => m.agreement_rate.num === m.totals.agreed && m.agreement_rate.den === m.totals.compared);

  control('breakRowSums',
    m => m.per_layer.reduce((s, r) => s + r.compared, 0) !==
         data.per_layer.reduce((s, r) => s + r.compared, 0),
    m => m.per_layer.reduce((s, r) => s + r.compared, 0) === m.totals.compared &&
         m.per_layer.reduce((s, r) => s + r.agreed, 0) === m.totals.agreed);

  control('breakRowArithmetic',
    m => m.per_layer.some((r, i) =>
      r.agreed + r.differed !== data.per_layer[i].agreed + data.per_layer[i].differed),
    m => m.per_layer.every(r => r.agreed + r.differed === r.compared));

  control('badFaultValue',
    m => !ALLOWED_FAULTS.includes(m.adjudications[0].fault),
    m => m.adjudications.every(a => ALLOWED_FAULTS.includes(a.fault)));

  control('emptyEvidence',
    m => m.adjudications[0].evidence.replace(/\s/g, '').length === 0 &&
         data.adjudications[0].evidence.replace(/\s/g, '').length > 0,
    m => m.adjudications.every(a =>
      typeof a.evidence === 'string' && a.evidence.replace(/\s/g, '').length > 0));

  control('ghostSlug',
    m => !m.per_layer.some(r => r.slug === m.adjudications[0].slug),
    m => {
      const s = new Set(m.per_layer.map(r => r.slug));
      return m.adjudications.every(a => s.has(a.slug));
    });

  control('wrongAdjudicationCount',
    m => m.adjudications.length !== m.divergences_adjudicated,
    m => m.adjudications.length === m.divergences_adjudicated);

  control('specNotDominant',
    m => !(m.fault_counts.specification > Math.max(m.fault_counts.ox, m.fault_counts.claude, m.fault_counts.neither)),
    m => m.fault_counts.specification > Math.max(m.fault_counts.ox, m.fault_counts.claude, m.fault_counts.neither));

  // Byte-identity control: flip one character of the shipped JSON text and
  // require equality to fail. Land-check compares against the real bytes.
  const flipped = rawShipped.startsWith('{') ? '[' + rawShipped.slice(1) : rawShipped + 'x';
  if (flipped !== rawShipped) {
    console.log('  LAND  byte-flip control corruption confirmed in memory');
    pass += 1;
    if (flipped === rawShipped) {
      console.log('  FAIL  byte-flip control left identity green');
      fail += 1;
    } else {
      console.log('  RED   byte-flip control went red as required');
      pass += 1;
      reds += 1;
    }
  } else {
    console.log('  FAIL  byte-flip control did NOT land');
    fail += 1;
  }

  const expectedRed = 10;
  console.log('\n  ' + reds + ' of ' + expectedRed + ' controls went red as required.');
  ok(reds === expectedRed,
    'all ' + expectedRed + ' negative controls went red (' + reds + ' did)');
}

// ---- Summary ----------------------------------------------------------

console.log(`
${pass} / ${pass + fail} checks passed.`);
process.exit(fail ? 1 : 0);
