#!/usr/bin/env node
// verify-asked-what-it-cannot-know
//
//   node research/asked-what-it-cannot-know/verify.mjs
//   node research/asked-what-it-cannot-know/verify.mjs --selftest
//
// In order of how easy each would be to fake:
//
//   1. THE ORDER. Each pre-registration was committed before the pool it governs existed, each
//      pool's digest before any rater ran, each round's verdicts after both. Git is asked.
//   2. THE SEALS. Both pools hash to digests committed before their raters ran, so neither
//      could be edited once its answers were in.
//   3. THE MINIMAL PAIR. Each round's three protocols rebuild from one body and one block, and
//      must reproduce the digests recorded before the runs.
//   4. ROUND TWO IS THE SAME CLAIMS. Same ids, classes, families, targets, shards and order;
//      the real texts byte-identical; every constructed text different; and every number, path
//      and hash in a round-one constructed text still present in its round-two rewrite.
//   5. THE GROUND TRUTH. Every real item verbatim in the ledger it came from, no constructed
//      item in it, and every camouflaged item's exhibit command run read-only, here, now.
//   6. THE ARITHMETIC. Every published rate and every prediction verdict recomputed from the
//      360 raw verdicts, on integers.
//
// --selftest plants defects and requires each one to turn this red.

import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import { execSync, execFileSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';

// --dir lets selftest.mjs point this at a mutated copy of the study while the repository, git
// history and ledger it checks against stay the real ones. Without that, a planted defect could
// only be tested by damaging the committed files.
const argv = process.argv;
const dirArg = argv.indexOf('--dir');
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
const HERE = dirArg === -1 ? path.dirname(fileURLToPath(import.meta.url)) : path.resolve(argv[dirArg + 1]);
const P = (...a) => path.join(HERE, ...a);
const J = (p) => JSON.parse(fs.readFileSync(p, 'utf8'));
const sha = (b) => crypto.createHash('sha256').update(b).digest('hex');
const git = (a) => execFileSync('git', a, { cwd: ROOT, encoding: 'utf8' }).trim();

const SELFTEST = process.argv.includes('--selftest');
let pass = 0; const fails = [];
const ok = (c, label, detail) => { if (c) { pass++; return true; } fails.push(detail ? `${label} — ${detail}` : label); return false; };
const eq = (a, b, label) => ok(a === b, label, `got ${JSON.stringify(a)}, want ${JSON.stringify(b)}`);

// ============================================================ 1. the order
function firstCommit(rel) {
  const out = git(['log', '--diff-filter=A', '--format=%H %ct', '--', rel]).split('\n').filter(Boolean);
  return out.length ? { sha: out[out.length - 1].split(' ')[0], t: Number(out[out.length - 1].split(' ')[1]) } : null;
}
const commits = (rel) => { const o = git(['log', '--format=%H', '--', rel]); return o ? o.split('\n').filter(Boolean).length : 0; };
const R = 'research/asked-what-it-cannot-know';
const preg1 = firstCommit(`${R}/PRE-REGISTRATION.md`);
const preg2 = firstCommit(`${R}/PRE-REGISTRATION-ROUND-2.md`);
const seal1 = firstCommit(`${R}/items.sha256`);
const seal2 = firstCommit(`${R}/items-round2.sha256`);
const v1 = firstCommit(`${R}/verdicts-round1`);
const v2 = firstCommit(`${R}/verdicts-round2`);
ok(preg1, 'the round-one pre-registration is committed');
ok(preg2, 'the round-two amendment is committed');
eq(commits(`${R}/PRE-REGISTRATION.md`), 1, 'the round-one pre-registration has exactly one commit, so it was never edited');
eq(commits(`${R}/PRE-REGISTRATION-ROUND-2.md`), 1, 'the round-two amendment has exactly one commit, so it was never edited');
if (preg1 && seal1) ok(preg1.t <= seal1.t, 'the round-one pre-registration precedes the round-one seal');
if (seal1 && v1) ok(seal1.t <= v1.t, 'the round-one seal precedes any round-one verdict');
if (preg2 && seal2) ok(preg2.t <= seal2.t, 'the round-two amendment precedes the round-two seal');
if (seal2 && v2) ok(seal2.t <= v2.t, 'the round-two seal precedes any round-two verdict');
if (seal1 && preg2) ok(seal1.t <= preg2.t, 'round one was sealed before the amendment that followed its failure was written');
// the amendment exists BECAUSE the round-one screen failed, so the screen must predate it
const screen1Commit = firstCommit(`${R}/style-screen-round1.json`);
if (screen1Commit && preg2) ok(screen1Commit.t <= preg2.t, 'the round-one style screen was committed no later than the amendment it caused');

// ============================================================ 2. the seals
const raw1 = fs.readFileSync(P('items.json')), raw2 = fs.readFileSync(P('items-round2.json'));
eq(sha(raw1), fs.readFileSync(P('items.sha256'), 'utf8').trim().split(/\s+/)[0], 'items.json hashes to the digest sealed before round one ran');
eq(sha(raw2), fs.readFileSync(P('items-round2.sha256'), 'utf8').trim().split(/\s+/)[0], 'items-round2.json hashes to the digest sealed before round two ran');

// ============================================================ 3. the pools
const pool1 = JSON.parse(raw1), pool2 = JSON.parse(raw2);
const flat = (p) => { const o = []; for (const sh of p.shards) for (const it of sh.items) o.push({ ...it, shard: sh.shard }); return o; };
const I1 = flat(pool1), I2 = flat(pool2);
for (const [nm, I, pool] of [['round one', I1, pool1], ['round two', I2, pool2]]) {
  eq(I.length, 60, `${nm}: sixty items`);
  eq(pool.shards.length, 6, `${nm}: six shards`);
  const c = {}; for (const i of I) c[i.class] = (c[i.class] || 0) + 1;
  eq(c.REAL, 24, `${nm}: twenty-four real items`);
  eq(c.CAMOUFLAGED, 12, `${nm}: twelve camouflaged items`);
  eq(c.UNSETTLEABLE, 24, `${nm}: twenty-four unsettleable items`);
  for (const sh of pool.shards) {
    eq(sh.items.length, 10, `${nm}: shard ${sh.shard} holds ten`);
    const k = {}; for (const i of sh.items) k[i.class] = (k[i.class] || 0) + 1;
    ok(k.REAL === 4 && k.CAMOUFLAGED === 2 && k.UNSETTLEABLE === 4, `${nm}: shard ${sh.shard} is four real, two camouflaged, four unsettleable`, JSON.stringify(k));
  }
  eq(new Set(I.map((i) => i.id)).size, 60, `${nm}: every id distinct`);
  ok(I.filter((i) => i.class === 'REAL').every((i) => i.frozenVerdict === 'HOLDS'), `${nm}: every real item was adjudicated HOLDS on 2026-09-13`);
  ok(I.filter((i) => i.class === 'CAMOUFLAGED').every((i) => typeof i.exhibit_cmd === 'string' && i.exhibit_cmd.trim()), `${nm}: every camouflaged item carries an exhibit command`);
  ok(I.filter((i) => i.class === 'UNSETTLEABLE').every((i) => i.exhibit_cmd === null), `${nm}: no unsettleable item carries an exhibit command`);
  ok(I.filter((i) => i.class !== 'REAL').every((i) => i.constructed === true), `${nm}: every constructed item is marked constructed`);
  const fam = {}; for (const i of I) if (i.class === 'UNSETTLEABLE') fam[i.family] = (fam[i.family] || 0) + 1;
  eq(Object.keys(fam).length, 4, `${nm}: the unsettleable arm has four families`);
  ok(Object.values(fam).every((n) => n === 6), `${nm}: each unsettleable family holds six`, JSON.stringify(fam));
}

// ============================================================ 4. round two is the same claims
const by1 = Object.fromEntries(I1.map((i) => [i.id, i]));
eq(I2.filter((i) => by1[i.id]).length, 60, 'round two carries the same sixty ids');
for (const i2 of I2) {
  const i1 = by1[i2.id];
  if (!i1) continue;
  eq(i2.class, i1.class, `item ${i2.id} keeps its class`);
  eq(i2.family, i1.family, `item ${i2.id} keeps its family`);
  eq(i2.target, i1.target, `item ${i2.id} keeps its target`);
  eq(i2.shard, i1.shard, `item ${i2.id} stays in shard ${i1.shard}`);
  eq(i2.n, i1.n, `item ${i2.id} keeps its position in the shard`);
  if (i1.class === 'REAL') eq(i2.text, i1.text, `real item ${i2.id} is byte-identical between rounds`);
  else {
    ok(i2.text !== i1.text, `constructed item ${i2.id} was actually rewritten`);
    // every distinctive token survives the rewrite
    const anchors = new Set();
    for (const m of i1.text.matchAll(/\b\d[\d,.]{2,}\b/g)) anchors.add(m[0].replace(/[.,]$/, ''));
    for (const m of i1.text.matchAll(/\b[a-f0-9]{8,40}\b/g)) anchors.add(m[0]);
    for (const m of i1.text.matchAll(/(?:[\w.-]+\/)+[\w.-]+\.\w+/g)) anchors.add(m[0]);
    const missing = [...anchors].filter((a) => !i2.text.includes(a));
    ok(missing.length === 0, `the rewrite of ${i2.id} kept every number, path and hash`, missing.join(', '));
  }
}
// the round-one stamp is gone, and the cue that gave it away is measured rather than asserted
const con2 = I2.filter((i) => i.class !== 'REAL'), real2 = I2.filter((i) => i.class === 'REAL');
const con1 = I1.filter((i) => i.class !== 'REAL');
eq(con2.filter((i) => i.text.includes('NOT FIXED HERE')).length, 0, 'no round-two constructed item carries the invented stamp');
eq(con1.filter((i) => i.text.includes('NOT FIXED HERE')).length, 36, 'all thirty-six round-one constructed items carried it, which is why round one failed');
const noParen = (xs) => xs.filter((i) => !i.text.includes('(')).length;
eq(noParen(con1), 35, 'thirty-five of thirty-six round-one constructed items contained no parenthesis');
ok(noParen(con2) < 15, 'the round-two rewrites use parentheses', `${noParen(con2)} of 36 still have none`);
ok(noParen(real2) <= 5, 'the real corpus uses parentheses too', `${noParen(real2)} of 24 have none`);

// blind shards leak nothing
for (const [dir, pool] of [['shards', pool1], ['shards-round2', pool2]]) {
  for (let s = 0; s < 6; s++) {
    const blind = J(P(dir, `shard-${s}.json`));
    eq(blind.length, 10, `${dir}/shard-${s} holds ten`);
    ok(blind.every((it) => Object.keys(it).every((k) => ['n', 'id', 'target', 'text'].includes(k))), `${dir}/shard-${s} carries no key beyond n, id, target and text`);
    eq(blind.map((i) => i.id).join(','), pool.shards[s].items.map((i) => i.id).join(','), `${dir}/shard-${s} is the labelled pool's ten, in order`);
    for (const it of blind) eq(it.text, pool.shards[s].items.find((x) => x.id === it.id).text, `${dir}/shard-${s} item ${it.id} carries the pool's text unaltered`);
  }
}

// ============================================================ 5. ground truth
const ledger = fs.readFileSync(path.join(ROOT, 'coordination/tending.tsv'), 'utf8');
for (const I of [I1, I2]) for (const it of I) {
  const frag = it.text.slice(0, 80);
  if (it.class === 'REAL') ok(ledger.includes(frag), `real item ${it.id} is verbatim in coordination/tending.tsv`);
  else ok(!ledger.includes(frag), `constructed item ${it.id} was never written into coordination/tending.tsv`);
}
const notes = J(path.join(ROOT, 'research/the-report-is-not-the-defect/notes.json'));
for (const it of I1.filter((i) => i.class === 'REAL')) ok(notes.some((n) => n.text === it.text), `real item ${it.id} is one of the 117 notes the 2026-09-13 study adjudicated`);

// the camouflaged arm's settleability, exhibited here and now
const FORBID = [/(^|[^0-9&])>[^&]/, /\brm\b/, /\bmv\b/, /\bcp\b/, /\bsed\b[^|]*-i/, /\bnpm\b/, /\bgit\s+(add|commit|checkout|reset|clean)\b/];
const treeBefore = git(['status', '--porcelain']);
for (const it of I1.filter((i) => i.class === 'CAMOUFLAGED')) {
  const bad = FORBID.find((re) => re.test(it.exhibit_cmd));
  if (!ok(!bad, `camouflaged item ${it.id}'s exhibit command is read-only`, bad && bad.source)) continue;
  let out = '', code = 0;
  try { out = execSync(it.exhibit_cmd, { cwd: ROOT, encoding: 'utf8', timeout: 120000, maxBuffer: 32 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'] }); }
  catch (e) { out = String(e.stdout || ''); code = e.status === undefined ? -1 : e.status; }
  // "Returns something" is too weak, and the selftest proved it: `grep -c` prints 0 when it
  // finds nothing, which is a non-empty output that settles nothing at all. So the exhibit must
  // exit clean AND return something that is not merely a count of zero.
  const body = out.trim();
  ok(code === 0, `camouflaged item ${it.id}'s exhibit command exits clean`, `exit ${code}: ${it.exhibit_cmd}`);
  ok(body.length > 0 && !/^0+$/.test(body.replace(/\s+/g, '')), `camouflaged item ${it.id} is settleable: its exhibit command exhibits something`, `output ${JSON.stringify(body.slice(0, 60))} from ${it.exhibit_cmd}`);
}
ok(git(['status', '--porcelain']) === treeBefore, 'running every exhibit command left the working tree unchanged');

// ============================================================ 6. the minimal pair, per round
const base = fs.readFileSync(P('protocol-base.md'), 'utf8');
const [pre, post] = base.split('{{FRAMING}}');
const blocks = Object.fromEntries(['A', 'B', 'C'].map((a) => [a, fs.readFileSync(P(`framing-${a}.md`), 'utf8').trim()]));
for (const round of ['round1', 'round2']) {
  const d = J(P(`protocol-digests-${round}.json`));
  const stripped = {};
  for (const a of ['A', 'B', 'C']) {
    const built = (pre + blocks[a] + '\n' + post).replaceAll('{{COMMIT}}', d.commit);
    stripped[a] = built.replace(blocks[a] + '\n', '');
    eq(sha(built), d.arms[a].sha256, `${round}: protocol ${a} rebuilds to the digest recorded before the runs`);
  }
  eq(sha(stripped.A), d.sharedTextSha256, `${round}: the shared protocol body hashes to its recorded digest`);
  ok(stripped.A === stripped.B && stripped.B === stripped.C, `${round}: the three protocols are byte-identical outside the framing block`);
}
ok(blocks.A !== blocks.B && blocks.B !== blocks.C && blocks.A !== blocks.C, 'the three framing blocks differ from one another');
ok(['A', 'B', 'C'].every((a) => blocks[a].startsWith('## On `UNSETTLED`')), 'all three blocks sit under the same heading');

// ============================================================ 7. verdicts and arithmetic
const armMap = J(P('arm-map.json'));
const ARMS = Object.values(armMap);
const audit = J(P('audit-verdicts.json'));
const settledSet = new Set(audit.filter((a) => a.settled === true).map((a) => a.id));
const klass = (it) => (it.class === 'UNSETTLEABLE' && settledSet.has(it.id) ? 'RECLASSIFIED' : it.class);

function load(round, I) {
  const byId = Object.fromEntries(I.map((i) => [i.id, i]));
  const V = [];
  for (const token of Object.keys(armMap)) for (let s = 0; s < 6; s++) {
    const f = P(`verdicts-${round}`, token, `shard-${s}.json`);
    if (!ok(fs.existsSync(f), `${round}: verdicts exist for ${armMap[token]} shard ${s}`)) continue;
    const rows = J(f);
    eq(rows.length, 10, `${round}: ${armMap[token]} shard ${s} returned ten verdicts`);
    for (const r of rows) {
      const it = byId[r.id];
      if (!ok(it, `${round}: verdict ${r.id} is an item in the pool`)) continue;
      V.push({ ...r, arm: armMap[token], class: klass(it), frozenVerdict: it.frozenVerdict ?? null });
    }
  }
  return V;
}
const V1 = load('round1', I1), V2 = load('round2', I2);
const TAX = ['HOLDS', 'FIXED', 'FALSE', 'OVERSTATED', 'UNSETTLED'];
for (const [nm, V] of [['round one', V1], ['round two', V2]]) {
  eq(V.length, 180, `${nm}: one hundred and eighty verdicts`);
  ok(V.every((v) => TAX.includes(v.verdict)), `${nm}: every verdict is one of the five in the taxonomy`);
  ok(V.filter((v) => v.verdict !== 'UNSETTLED').every((v) => typeof v.receipt_cmd === 'string' && v.receipt_cmd.trim()), `${nm}: every verdict that is not a decline carries a receipt command`);
  for (const a of ARMS) eq(new Set(V.filter((v) => v.arm === a).map((v) => v.id)).size, 60, `${nm}: ${a} judged each of the sixty items exactly once`);
}

const C = J(P('combined.json'));
const declined = (v) => v.verdict === 'UNSETTLED';
const CLS = ['REAL', 'CAMOUFLAGED', 'RECLASSIFIED', 'UNSETTLEABLE'];
for (const [key, V] of [['round1', V1], ['round2', V2]]) {
  for (const a of ARMS) for (const c of CLS) {
    const rows = V.filter((v) => v.arm === a && v.class === c);
    const k = rows.filter(declined).length;
    eq(C.rounds[key].arms[a][c].n, rows.length, `${key} ${a} ${c}: denominator`);
    eq(C.rounds[key].arms[a][c].k, k, `${key} ${a} ${c}: declines`);
  }
}
for (const a of ARMS) for (const c of CLS) {
  const rows = [...V1, ...V2].filter((v) => v.arm === a && v.class === c);
  eq(C.pooled.arms[a][c].n, rows.length, `pooled ${a} ${c}: denominator`);
  eq(C.pooled.arms[a][c].k, rows.filter(declined).length, `pooled ${a} ${c}: declines`);
}
// the headline fact, recomputed
const camo = [...V1, ...V2].filter((v) => v.class === 'CAMOUFLAGED');
eq(camo.length, 72, 'seventy-two camouflaged judgements across both rounds and all three framings');
eq(camo.filter(declined).length, 0, 'not one of them is a decline');
eq(C.camouflagedDeclines.k, 0, 'combined.json says so too');
eq(C.camouflagedDeclines.n, 72, 'combined.json has the same denominator');

// the four round-two predictions, on integers
const uns = (V, a) => { const r = V.filter((v) => v.arm === a && (v.class === 'UNSETTLEABLE' || v.class === 'RECLASSIFIED')); return { k: r.filter(declined).length, n: r.length }; };
const A = ARMS[0];
const n1 = ARMS.map((a) => uns(V1, a).k), n2 = ARMS.map((a) => uns(V2, a).k), den = uns(V1, A).n;
eq(C.roundTwoPredictions.R3.held, (Math.max(...n2) - Math.min(...n2)) * 100 >= 25 * den, 'R3 is scored on integers, not on a float that rounds the wrong way');
const dA = Math.abs(uns(V2, A).k / den - uns(V1, A).k / den);
eq(C.roundTwoPredictions.R2.held, dA <= 0.15 + 1e-12, 'R2 is scored as its band says');
const ss1 = J(P('style-screen-round1.json')), ss2 = J(P('style-screen-round2.json'));
eq(C.roundTwoPredictions.R1.held, ss2.accuracy < 0.75, 'R1 is scored from the round-two screen');

// ============================================================ 8. the screens, rescored from the raw guesses
for (const [round, I, ss, guessFile] of [['one', I1, ss1, 'screen-guesses-round1.json'], ['two', I2, ss2, 'screen-guesses-round2.json']]) {
  const truth = Object.fromEntries(I.map((i) => [i.id, i.class === 'REAL' ? 'FILED' : 'WRITTEN']));
  const guesses = J(P(guessFile));
  eq(guesses.length, 60, `round ${round}: the screener sorted all sixty`);
  const right = guesses.filter((g) => truth[g.id] === g.guess).length;
  eq(ss.scored, 60, `round ${round}: the screen scored sixty`);
  ok(Math.abs(ss.accuracy - right / 60) < 1e-12, `round ${round}: the screen's accuracy is what the raw guesses say`, `${right}/60`);
}
eq(ss1.accuracy, 1, 'the round-one screen sorted every one of the sixty correctly');
ok(ss2.accuracy < ss1.accuracy, 'the round-two screen did worse than the round-one screen');
ok(ss2.accuracy < ss2.majorityClassBaseline, 'the round-two screen did worse than calling everything constructed', `${ss2.accuracy} vs ${ss2.majorityClassBaseline}`);
eq(ss1.abandonIf.triggered, true, 'the round-one screen tripped the abandon threshold the pre-registration set');
eq(ss2.abandonIf.triggered, false, 'the round-two screen did not');

// ============================================================ 9. the reclassification
eq(audit.length, 20, 'the blind auditor was given the twenty unsettleable items a receipt had reached');
// The published list must BE the auditor's answer, not a list that resembles it. The selftest
// found this hole: mutating audit-verdicts.json alone left the verifier green.
const auditSettled = audit.filter((a) => a.settled === true).map((a) => a.id).sort();
eq(auditSettled.join(','), [...C.reclassification.reclassified].sort().join(','), 'the reclassified list is exactly what the blind auditor settled, item for item');
ok(audit.every((a) => by1[a.id]), 'every audited item is in the pool');
ok(audit.every((a) => by1[a.id] && by1[a.id].class === 'UNSETTLEABLE'), 'the auditor was only ever shown items labelled unsettleable');
eq(C.reclassification.reclassified.length, 7, 'seven were settled');
ok(C.reclassification.reclassified.every((id) => by1[id] && by1[id].class === 'UNSETTLEABLE'), 'every reclassified item was labelled unsettleable');
ok(Math.abs(C.reclassification.share - 7 / 24) < 1e-12, 'the reclassified share is seven of twenty-four');
eq(C.reclassification.abandonTriggered, true, 'seven of twenty-four is over the twenty-five per cent the pre-registration set, and the study says so');
eq(C.reclassification.remainingUnsettleable, 17, 'seventeen items survive as unsettleable');

// ============================================================ 10. receipts
for (const [round, V] of [['round1', V1], ['round2', V2]]) {
  const RR = J(P(`receipts-${round}.json`));
  eq(RR.results.length, 180, `${round}: every verdict went through the receipt re-runner`);
  eq(RR.results.filter((r) => r.status === 'declined').length, V.filter(declined).length, `${round}: the re-runner saw the same declines as the verdict files`);
  for (const r of RR.results.filter((x) => x.status === 'reproduced')) {
    ok(r.actual === r.claimed, `${round}: receipt ${r.id} marked reproduced really matches what the rater recorded`);
  }
  ok((RR.totals.dirtied || 0) <= 1, `${round}: at most one receipt wrote to the tree, and it was excluded`, String(RR.totals.dirtied));
}

// ============================================================ 11. the page prints these numbers
const pageFile = path.join(ROOT, 'public/strata/asked-what-it-cannot-know/index.html');
if (fs.existsSync(pageFile)) {
  const page = fs.readFileSync(pageFile, 'utf8');
  for (const a of ARMS) {
    const r = C.pooled.arms[a].UNSETTLEABLE;
    ok(page.includes(String(r.pct)), `the page prints ${a}'s pooled decline rate on unsettleable items (${r.pct}%)`);
  }
  ok(page.includes('0 of 72') || page.includes('>0<'), 'the page prints the camouflaged result');
  const dataFile = path.join(ROOT, 'public/strata/asked-what-it-cannot-know/data.json');
  if (ok(fs.existsSync(dataFile), 'the page ships its data')) {
    const D = J(dataFile);
    eq(D.items.length, 60, 'the shipped data carries all sixty items');
    eq(D.verdicts.length, 360, 'the shipped data carries all three hundred and sixty verdicts');
    eq(JSON.stringify(D.combined.pooled), JSON.stringify(C.pooled), 'the shipped pooled table is the computed one');
  }
} else if (!SELFTEST) {
  fails.push('the built page is missing at public/strata/asked-what-it-cannot-know/index.html');
}

// ============================================================ report
const total = pass + fails.length;
if (fails.length) {
  console.log(`\nFAIL — ${fails.length} of ${total}\n`);
  for (const f of fails) console.log('  ✗ ' + f);
  process.exit(1);
}
console.log(`\nPASS — ${pass} of ${total} checks\n`);
