#!/usr/bin/env node
// verify.mjs — the machine check behind The Anatomy of Error (P3 combine portal).
//
// This portal asserts NO new fact about the world: every belief/record/headline is
// lifted from the named member stratum's own verifier. Its claims are structural, and
// every one of them is recomputed here from primary artefacts in this repository:
//
//   1. MEMBERSHIP is exactly the corpus's self-declared `record-correcting` strata
//      (excluding the portals themselves) — no hand-picking, a grep-defined boundary.
//      131 layers as of 2026-10-07.
//   2. Every member file exists, carries the tag, and has non-thin card text.
//   3. Every origin/cure key is one of the declared categories.
//   4. NO LABEL IS HAND-SET. Each member's published origin and cure are re-derived
//      from the blind double-rating in blind-rating/raw/{A,B}/ (agreed axis -> that
//      value) and blind-rating/adjudication/ (split axis -> the blind tie-breaker's
//      verdict), and must equal what data.json publishes. This is the check that makes
//      the finding a measurement instead of an assertion: the labels were assigned by
//      readers who were shown the six origins and four cures with the `domain` field
//      stripped out and were never told any pairing was expected, so they could not
//      have tuned toward the result. Protocol: blind-rating/PROMPT.md.
//   5. The TWO-DOMAIN FINDING: world-origin->compute-cure and record-origin->consult-cure
//      align in 113 of 131 cases (86.3%), and the 18 exceptions are exactly the flagged set.
//   6. The ASYMMETRY: 6 origins are used but the cures collapse to 2 domains.
//   7. The REPRODUCIBILITY figures the page prints (inter-rater agreement and Cohen's
//      kappa on both axes) are recomputed from the raw ratings.
//   8. The RELABELLING the page reports (31 of the 62 previously hand-labelled layers
//      moved) is recomputed against a frozen snapshot of those hand labels.
//   9. THE PRE-REGISTRATION HELD ITS ORDER. The 2026-08-16 cohort's predictions were
//      committed before any of its ratings existed. That is the whole load-bearing claim
//      of a pre-registration, so it is checked against git rather than asserted in prose:
//      the commit that ADDED prereg-2026-08-16.json must predate the commit that added
//      every rating file in the cohort that document names.
//
// Run:  node research/the-anatomy-of-error/verify.mjs
import { readFileSync, readdirSync, existsSync } from 'node:fs';
import { execFileSync } from 'node:child_process';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';

const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..', '..');
const STR = join(ROOT, 'src', 'content', 'strata');
const BR = join(ROOT, 'research', 'the-anatomy-of-error', 'blind-rating');
const DATA = JSON.parse(readFileSync(join(ROOT, 'public', 'strata', 'the-anatomy-of-error', 'data.json'), 'utf8'));

let pass = 0, fail = 0;
const ok = (cond, msg) => { if (cond) { pass++; } else { fail++; console.error('  ✗ ' + msg); } };

// ---- 1. the grep-defined boundary: which strata does the corpus tag record-correcting? ----
const fm = (txt) => (txt.split(/^---$/m)[1] || '');
const tagsOf = (h) => {
  const m = h.match(/^tags:\s*\[(.*)\]/m);
  return m ? m[1].split(',').map(s => s.trim().replace(/^["']|["']$/g, '')) : [];
};
const corpusRC = new Set();    // record-correcting, excluding portals
for (const f of readdirSync(STR)) {
  if (!f.endsWith('.md')) continue;
  const h = fm(readFileSync(join(STR, f), 'utf8'));
  const tags = tagsOf(h);
  const isRC = tags.some(t => /record[- ]correct/i.test(t));
  const isPortal = tags.includes('portal');
  if (isRC && !isPortal) corpusRC.add(f.replace(/\.md$/, ''));
}

const members = DATA.members;
const memberSlugs = new Set(members.map(m => m.slug));

console.log(`\nThe Anatomy of Error — verification`);
console.log(`  corpus record-correcting strata (non-portal): ${corpusRC.size}`);
console.log(`  portal members listed:                        ${members.length}`);

// 2. membership matches the corpus boundary exactly
ok(members.length === 131, `expected 131 members, got ${members.length}`);
for (const slug of corpusRC) ok(memberSlugs.has(slug), `corpus tags '${slug}' record-correcting but it is missing from the portal`);
for (const slug of memberSlugs) ok(corpusRC.has(slug), `portal lists '${slug}' but the corpus does not tag it record-correcting (non-portal)`);

// 3. every member file exists and carries the tag; card text is present and not thin
for (const m of members) {
  let h = '';
  try { h = fm(readFileSync(join(STR, m.slug + '.md'), 'utf8')); } catch { ok(false, `member file missing: ${m.slug}.md`); continue; }
  ok(/record[- ]correct/i.test(h), `${m.slug}: missing record-correcting tag`);
  ok(!!DATA.origins[m.origin], `${m.slug}: unknown origin '${m.origin}'`);
  ok(!!DATA.cures[m.cure], `${m.slug}: unknown cure '${m.cure}'`);
  for (const k of ['belief', 'record', 'headline']) ok(m[k] && m[k].length > 10, `${m.slug}: thin or missing '${k}'`);
}

// ---- 4. no label is hand-set: re-derive every one from the blind ratings ----
const rawOf = (r, s) => JSON.parse(readFileSync(join(BR, 'raw', r, s + '.json'), 'utf8'));
const adjudication = {};
for (const f of readdirSync(join(BR, 'adjudication')).filter(f => f.endsWith('.json'))) {
  const j = JSON.parse(readFileSync(join(BR, 'adjudication', f), 'utf8'));
  adjudication[j.slug] = j;
}
let contestedCount = 0;
for (const m of members) {
  let a, b;
  try { a = rawOf('A', m.slug); b = rawOf('B', m.slug); }
  catch { ok(false, `${m.slug}: published in the portal but not blind-rated by both raters`); continue; }

  const derive = (axis) => (a[axis] === b[axis]) ? a[axis] : adjudication[m.slug]?.[axis]?.verdict;
  ok(derive('origin') === m.origin, `${m.slug}: published origin '${m.origin}' is not what the blind ratings derive ('${derive('origin')}')`);
  ok(derive('cure') === m.cure, `${m.slug}: published cure '${m.cure}' is not what the blind ratings derive ('${derive('cure')}')`);

  const contested = !(a.origin === b.origin && a.cure === b.cure);
  ok(m.contested === contested, `${m.slug}: contested flag says ${m.contested} but the raters ${contested ? 'did' : 'did not'} split`);
  if (contested) {
    contestedCount++;
    ok(!!adjudication[m.slug], `${m.slug}: the raters split but no adjudication is on file`);
  }
  ok(m.rating?.a?.origin === a.origin && m.rating?.b?.origin === b.origin &&
     m.rating?.a?.cure === a.cure && m.rating?.b?.cure === b.cure,
     `${m.slug}: the per-rater record in data.json does not match raw/`);
}
ok(contestedCount === 20, `expected the two raters to split on 20 layers, got ${contestedCount}`);

// ---- 4b. nor is the card text hand-set: it is the frozen prior text, or rater A's draft,
//          or a fact-check correction that names its own source. Nothing else. ----
const FROZEN = JSON.parse(readFileSync(join(BR, 'prior-labels.json'), 'utf8'));
const OVERRIDES = JSON.parse(readFileSync(join(BR, 'card-overrides.json'), 'utf8')).overrides;
for (const m of members) {
  const frozen = FROZEN.members[m.slug] || null;
  const ov = OVERRIDES[m.slug] || {};
  let a; try { a = rawOf('A', m.slug); } catch { continue; }
  for (const k of ['belief', 'record', 'headline']) {
    const expected = ov[k] ?? frozen?.[k] ?? a[k];
    ok(m[k] === expected, `${m.slug}: published ${k} is not the frozen text, rater A's draft, or a recorded override`);
  }
}
for (const slug of Object.keys(OVERRIDES)) {
  ok(memberSlugs.has(slug), `card-overrides names '${slug}', which is not a member`);
  ok(!!OVERRIDES[slug].why && !!OVERRIDES[slug].found_by, `card-overrides for '${slug}' must say why and who found it`);
}

// ---- 5. the cross-tabulation (the portal's one structural claim) ----
const originKeys = Object.keys(DATA.origins);   // 6
const cureKeys = Object.keys(DATA.cures);       // 4
const grid = {};                                // origin -> cure -> count
for (const o of originKeys) { grid[o] = {}; for (const c of cureKeys) grid[o][c] = 0; }
const domDom = { 'world|compute': 0, 'world|consult': 0, 'record|compute': 0, 'record|consult': 0 };
const offDiag = [];
for (const m of members) {
  grid[m.origin][m.cure]++;
  const od = DATA.origins[m.origin].domain;     // world | record
  const cd = DATA.cures[m.cure].domain;         // compute | consult
  domDom[`${od}|${cd}`]++;
  const aligned = (od === 'world' && cd === 'compute') || (od === 'record' && cd === 'consult');
  if (!aligned) offDiag.push(m.slug);
}

const onDiag = domDom['world|compute'] + domDom['record|consult'];
const off = domDom['world|consult'] + domDom['record|compute'];
ok(onDiag === 113, `expected 113 on the world<->compute / record<->consult diagonal, got ${onDiag}`);
ok(off === 18, `expected 18 off-diagonal, got ${off}`);

const flagged = new Set(members.filter(m => m.off_diagonal).map(m => m.slug));
ok(flagged.size === 18, `expected 18 flagged off_diagonal members, got ${flagged.size}`);
for (const s of offDiag) ok(flagged.has(s), `${s} is off-diagonal by the cross-tab but not flagged off_diagonal in the data`);
for (const s of flagged) ok(offDiag.includes(s), `${s} is flagged off_diagonal but lands ON the diagonal by the cross-tab`);

// ---- 6. the asymmetry: many births, few deaths ----
const originsUsed = originKeys.filter(o => members.some(m => m.origin === o)).length;
const cureDomainsUsed = new Set(members.map(m => DATA.cures[m.cure].domain)).size;
ok(originsUsed === 6, `expected all 6 origins used, got ${originsUsed}`);
ok(cureDomainsUsed === 2, `expected cures to span 2 domains, got ${cureDomainsUsed}`);

// ---- 7. reproducibility: recompute what the page prints about the raters ----
const kappa = (pairs, categories) => {
  const n = pairs.length;
  const po = pairs.filter(([x, y]) => x === y).length / n;
  let pe = 0;
  for (const c of categories) {
    pe += (pairs.filter(([x]) => x === c).length / n) * (pairs.filter(([, y]) => y === c).length / n);
  }
  return (po - pe) / (1 - pe);
};
const pairsO = members.map(m => [m.rating.a.origin, m.rating.b.origin]);
const pairsC = members.map(m => [m.rating.a.cure, m.rating.b.cure]);
const agreeO = pairsO.filter(([x, y]) => x === y).length;
const agreeC = pairsC.filter(([x, y]) => x === y).length;
const kO = kappa(pairsO, originKeys), kC = kappa(pairsC, cureKeys);
ok(agreeO === 117, `expected the raters to agree on 117 origins, got ${agreeO}`);
ok(agreeC === 123, `expected the raters to agree on 123 cures, got ${agreeC}`);
ok(Math.abs(kO - 0.863) < 0.005, `expected origin kappa 0.863, got ${kO.toFixed(3)}`);
ok(Math.abs(kC - 0.90) < 0.005, `expected cure kappa 0.90, got ${kC.toFixed(3)}`);

// the sharper cut: alignment is higher where the raters agreed than where they split
const dom = (m) => [DATA.origins[m.origin].domain, DATA.cures[m.cure].domain];
const isAligned = (m) => { const [od, cd] = dom(m); return (od === 'world') === (cd === 'compute'); };
const agreedRows = members.filter(m => !m.contested), splitRows = members.filter(m => m.contested);
const agreedAligned = agreedRows.filter(isAligned).length, splitAligned = splitRows.filter(isAligned).length;
ok(agreedAligned === 99 && agreedRows.length === 111, `expected 99/111 aligned where the raters agreed, got ${agreedAligned}/${agreedRows.length}`);
ok(splitAligned === 14 && splitRows.length === 20, `expected 14/20 aligned where the raters split, got ${splitAligned}/${splitRows.length}`);

// ---- 8. the relabelling, against a frozen snapshot of the old hand labels ----
const PRIOR = JSON.parse(readFileSync(join(BR, 'prior-labels.json'), 'utf8')).labels;
ok(Object.keys(PRIOR).length === 62, `expected 62 frozen prior labels, got ${Object.keys(PRIOR).length}`);
let moved = 0, withPrior = 0;
for (const m of members) {
  const p = PRIOR[m.slug];
  if (!p) { ok(m.prior === null, `${m.slug}: has no frozen prior label but data.json records one`); continue; }
  withPrior++;
  ok(m.prior && m.prior.origin === p.origin && m.prior.cure === p.cure,
     `${m.slug}: the prior label in data.json does not match the frozen snapshot`);
  const didMove = (p.origin !== m.origin || p.cure !== m.cure);
  ok(m.moved === didMove, `${m.slug}: moved flag says ${m.moved} but the label ${didMove ? 'did' : 'did not'} change`);
  if (didMove) moved++;
}
ok(withPrior === 62, `expected 62 members to carry a prior label, got ${withPrior}`);
ok(moved === 31, `expected 31 of the 62 hand labels to have moved under blind rating, got ${moved}`);
// and the headline that survived it
const priorAligned = Object.values(PRIOR).filter(p =>
  (DATA.origins[p.origin].domain === 'world') === (DATA.cures[p.cure].domain === 'compute')).length;
ok(priorAligned === 54, `expected the 62 hand labels to have been 54 aligned, got ${priorAligned}`);

// ---- 9. every pre-registration held its order (checked against git, not asserted) ----
// A pre-registration is worth exactly one thing: the predictions existed before the data.
// Prose cannot establish that; the commit graph can. So for every prereg-YYYY-MM-DD.json
// in this directory, the commit that first added it must be older than the commit that
// first added every rating file for the cohort that document names. New fold-ins add new
// preregs; this loop finds them itself so a later cohort cannot silently escape the check.
//
// AUTHOR date (%at), not committer date (%ct). This is the whole correctness of the check.
// publish.sh rebases onto main before pushing, and a rebase rewrites every committer
// timestamp to the moment of the rebase: measured on the first run of this check, the two
// commits that were genuinely 7 minutes apart came back 0 seconds apart, both stamped
// 15:43:57. Committer time would therefore have let a rebase quietly flatten the one
// ordering this file exists to establish. Author time is set when the commit is written
// and a rebase preserves it.
const addedAt = (rel) => {
  try {
    const out = execFileSync('git', ['log', '--diff-filter=A', '--format=%at', '--follow', '--', rel],
      { cwd: ROOT, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim().split('\n').filter(Boolean);
    return out.length ? Number(out[out.length - 1]) : null;   // the OLDEST add, if a path was re-added
  } catch { return null; }
};
// The optional trailing letter was added 2026-08-21, when a second cohort arrived on the
// same day as the first: a peer shipped a record-correcting layer hours after the n=4
// pass was folded in, so targets.mjs returned a slug again and the portal went red again
// within one session. Without the letter, prereg-2026-08-21b.json would not have matched
// this pattern and its cohort would have escaped the git-order check entirely, which is
// the one check standing between this protocol and a pre-registration written afterwards.
// A dated filename that assumes one cohort per day is a small assumption with a large
// hole under it.
const preregFiles = readdirSync(BR).filter(f => /^prereg-\d{4}-\d{2}-\d{2}[a-z]?\.json$/.test(f)).sort();
for (const pf of preregFiles) {
  const prereg = JSON.parse(readFileSync(join(BR, pf), 'utf8'));
  const pregAt = addedAt(`research/the-anatomy-of-error/blind-rating/${pf}`);
  if (pregAt === null) {
    console.log(`\n  [prereg order · ${pf}] SKIPPED — no git history for the pre-registration here` +
                ` (shallow clone?). Run 'git fetch --unshallow origin' to check it.`);
    continue;
  }
  let checked = 0, latest = 0, offender = null;
  for (const slug of prereg.cohort) {
    for (const rater of ['A', 'B']) {
      const rel = `research/the-anatomy-of-error/blind-rating/raw/${rater}/${slug}.json`;
      const t = addedAt(rel);
      if (t === null) continue;
      checked++;
      ok(t > pregAt, `${pf} is not strictly older than the rating ${rater}/${slug}.json — the ordering claim fails`);
      if (t > latest) { latest = t; offender = rel; }
    }
  }
  ok(checked === prereg.cohort.length * 2,
     `${pf}: expected git-add times for all ${prereg.cohort.length * 2} cohort ratings, found ${checked}`);
  const gap = latest ? Math.round((latest - pregAt) / 60) : 0;
  console.log(`\n  [prereg order · ${pf}] committed ${gap} minutes before the last of` +
              ` its ${checked} cohort ratings (${offender ? offender.split('/').slice(-2).join('/') : 'n/a'}).`);
}

// ---- 10. the 2026-10-07 cohort section: every figure it prints, recomputed here ----
// The page's later sections print figures about one cohort that nothing else asserted.
// Each is derived below from data.json and raw/, and the page must carry the derived text.
{
  const PAGE = readFileSync(join(ROOT, 'public', 'strata', 'the-anatomy-of-error', 'index.html'), 'utf8');
  const has = (t, why) => ok(PAGE.includes(t), `page should say "${t}" (${why})`);
  const pre = JSON.parse(readFileSync(join(BR, 'prereg-2026-10-07.json'), 'utf8'));
  const co = new Set(pre.cohort);
  const inC = members.filter(m => co.has(m.slug)), outC = members.filter(m => !co.has(m.slug));
  ok(inC.length === 20, `expected the 2026-10-07 cohort to be 20 published members, got ${inC.length}`);
  const al = inC.filter(isAligned).length;
  has(`${al} of 20 on the diagonal`, 'cohort alignment');
  has(`<span class="n">${onDiag}/${members.length} = ${(100 * onDiag / members.length).toFixed(1)}%</span>`, 'pooled after the fold-in');
  const agreed = inC.filter(m => !m.contested);
  has(`agreed on both axes for <strong>${agreed.length} of 20</strong>`, 'cohort inter-rater');
  has(`${agreed.filter(isAligned).length} of ${agreed.length} aligned where they agreed, ` +
      `${inC.filter(m => m.contested).filter(isAligned).length} of ${inC.filter(m => m.contested).length} where they split`, 'the missed concentration prediction');
  const world = inC.filter(m => DATA.origins[m.origin].domain === 'world');
  ok(world.length === 16 && world.every(m => m.cure !== 'SOURCE'), `page says 16 world-errors and none with a SOURCE cure; data has ${world.length}, ${world.filter(m => m.cure === 'SOURCE').length} SOURCE`);
  has('Sixteen of the twenty are errors about the world', 'world count');
  const ill = inC.filter(m => m.origin === 'illposed').length, illOut = outC.filter(m => m.origin === 'illposed').length;
  ok(ill === 12 && illOut === 18 && outC.length === 111, `illposed ${ill}/20 vs ${illOut}/${outC.length}; page says 12 of 20 vs 18 of 111`);
  has('<strong>Twelve of the twenty</strong> came back <em>illposed</em>', 'illposed share');
  has(`against 18 of the earlier 111 (${(100 * 18 / 111).toFixed(1)}%)`, 'earlier illposed share');
  // the binomial tail the page quotes as "about once in 87,000 cohorts"
  const Cn = (n, k) => { let r = 1; for (let i = 0; i < k; i++) r = r * (n - i) / (i + 1); return r; };
  const p0 = illOut / outC.length;
  let tail = 0; for (let k = ill; k <= 20; k++) tail += Cn(20, k) * p0 ** k * (1 - p0) ** (20 - k);
  ok(Math.round(1 / tail / 1000) === 87, `1/P(X>=12) should round to 87 thousand, got ${(1 / tail).toFixed(0)}`);
  has('about once in 87,000 cohorts', 'binomial tail');
  ok(inC.filter(m => m.cure === 'COUNT').length === 10 && outC.filter(m => m.cure === 'COUNT').length === 11, 'COUNT cures: page says 10 of 20 against 11 of 111');
  has('against 11 of the earlier 111', 'earlier COUNT share');
  let low = 0, lowLayers = new Set(), lowOut = 0, nOut = 0;
  for (const m of members) for (const r of ['A', 'B']) {
    const j = rawOf(r, m.slug);
    if (co.has(m.slug)) { if (j.origin_confidence === 'low') { low++; lowLayers.add(m.slug); } }
    else { nOut++; if (j.origin_confidence === 'low') lowOut++; }
  }
  ok(low === 11 && lowLayers.size === 7 && lowOut === 0 && nOut === 222,
     `low-confidence origins: ${low} of 40 over ${lowLayers.size} layers, ${lowOut} of ${nOut} earlier; page says 11, 7, 0 of 222`);
  has('<strong>11 of the 40</strong> origin ratings', 'low-confidence count');
  const crossers = inC.filter(m => !isAligned(m)).map(m => m.slug).sort();
  ok(JSON.stringify(crossers) === JSON.stringify(['the-ceiling-the-record-kept', 'the-number-that-was-retyped', 'when-the-wall-went-up']),
     `the three named crossings should be the cohort's off-diagonal set, got ${crossers.join(', ')}`);
  const tx = members.filter(m => m.origin === 'transmission'), txCross = tx.filter(m => !isAligned(m)).map(m => m.slug);
  ok(txCross.length === 1 && txCross[0] === 'the-number-that-was-retyped', `page calls the-number-that-was-retyped the first transmission crossing; crossing transmission layers: ${txCross.join(', ')}`);
}

// ---- report the table ----
const pct = (100 * onDiag / members.length).toFixed(1);
console.log(`\n  origin \\ cure        RECOMPUTE  COUNT  SOURCE   DATE   | domain`);
for (const o of originKeys) {
  const row = cureKeys.map(c => String(grid[o][c]).padStart(6)).join(' ');
  console.log(`  ${o.padEnd(18)} ${row}   | ${DATA.origins[o].domain}`);
}
console.log(`\n  two-domain alignment: ${onDiag}/${members.length} = ${pct}%  (world<->compute, record<->consult)`);
console.log(`  the ${off} that cross: ${offDiag.join(', ')}`);
console.log(`  births (origins): ${originsUsed}   deaths (cure-domains): ${cureDomainsUsed}`);
console.log(`\n  labels: blind double-rated, ${contestedCount} split and sent to a blind tie-breaker`);
console.log(`  inter-rater agreement: origin ${agreeO}/${members.length} (k=${kO.toFixed(2)}) · cure ${agreeC}/${members.length} (k=${kC.toFixed(2)})`);
console.log(`  aligned where the raters agreed: ${agreedAligned}/${agreedRows.length} · where they split: ${splitAligned}/${splitRows.length}`);
console.log(`  hand labels that moved under blind rating: ${moved}/62 (the old pooled alignment was ${priorAligned}/62)`);

console.log(`\n  ${pass} checks passed, ${fail} failed.`);
process.exit(fail ? 1 : 0);
