#!/usr/bin/env node
// verify-the-cold-read-blind-rerun.mjs
//
// Binds the shipped page to the committed data, and the committed data to the raw
// draws. What it checks, in the order that matters:
//
//   1. THE STIMULUS DID NOT MOVE. artifact.md and answer-key.md are the published
//      pre-commitment. If they changed, the goalposts moved and nothing else here
//      means anything.
//   2. THE PRE-REGISTRATION PREDATES THE FIRST DRAW. Read from git, not asserted.
//   3. THE CONTROL DIFFERS AT THE SIX SITES AND NOWHERE ELSE, paragraph by paragraph.
//   4. THE PROTOCOL ON THE PAGE IS THE PROTOCOL THAT RAN. Prompt strings, essay
//      hashes, temperature, token budget, draw counts.
//   5. EVERY NUMBER ON THE PAGE IS IN findings.json, and findings.json re-derives
//      from located.json, which re-derives from draws.jsonl.
//
// `--mutate` runs the negative control: it perturbs each guarded quantity in turn
// and asserts that the check that guards it goes red. A check that stays green
// under mutation is a check that could never have failed.
//
// Usage: node verify-the-cold-read-blind-rerun.mjs [--mutate]

import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import { execSync } from 'node:child_process';
import { SITES, UNPLANTED } from './research/salience-experiment/blind-rerun/score/sites.mjs';

const ROOT = path.resolve(import.meta.dirname);
const EXP = path.join(ROOT, 'research', 'salience-experiment');
const RUN = path.join(EXP, 'blind-rerun');
const PAGE = path.join(ROOT, 'public', 'strata', 'the-cold-read', 'index.html');
const PAGEJSON = path.join(ROOT, 'public', 'strata', 'the-cold-read', 'blind-rerun.json');

const MUTATE = process.argv.includes('--mutate');
let pass = 0, fail = 0;
const failures = [];
function ok(cond, name, detail) {
  if (cond) { pass++; return true; }
  fail++; failures.push(`${name}${detail ? ' — ' + detail : ''}`);
  return false;
}
const sha = (s) => crypto.createHash('sha256').update(s, 'utf8').digest('hex').slice(0, 16);
const read = (p) => fs.readFileSync(p, 'utf8');
const paras = (t) => t.replace(/^#[^\n]*\n+/, '').trim().split('\n').map((s) => s.trim()).filter(Boolean);

// ─────────────────────────────────────────────────────────────────────────────
console.log('[1] the published stimulus and its sealed key have not been edited');

// The stimulus files carry the errors on purpose. If a later hand "fixed" one, the
// two committed readings would be scored against a text nobody read.
const STIMULUS_SHA = {
  'artifact.md': '283f260388ee60a1',
  'artifact-2.md': 'bbfab1c121af46c9',
};
for (const [f, expected] of Object.entries(STIMULUS_SHA)) {
  const got = sha(read(path.join(EXP, f)));
  // The literal is a tripwire, not a source of truth: on first run it is recorded
  // rather than asserted, and every run after that it must not move.
  if (expected === 'RECORD') { console.log(`    ${f}: ${got}  (record this literal)`); continue; }
  ok(got === expected, `${f} unchanged`, `sha ${got}, expected ${expected}`);
}

// The keys may only ever GROW, by dated addenda below the original text.
for (const [f, marker] of [['answer-key.md', '# Addendum, 2026-08-23'], ['answer-key-2.md', '# Addendum, 2026-08-23']]) {
  const t = read(path.join(EXP, f));
  const i = t.indexOf(marker);
  ok(i > 0, `${f} carries its dated addendum`);
  ok(/Six deliberately planted errors|The second specimen/.test(t.slice(0, 1200)), `${f} keeps its original opening`);
  ok(!/~~|<del>/.test(t), `${f} deletes nothing`);
}

// ─────────────────────────────────────────────────────────────────────────────
console.log('[2] the pre-registration predates the first draw');
let preregTime = null, firstDraw = null;
try {
  preregTime = new Date(execSync(
    `git log --diff-filter=A --format=%cI -1 -- research/salience-experiment/blind-rerun/PREREGISTRATION.md`,
    { cwd: ROOT, encoding: 'utf8' },
  ).trim());
} catch (e) { /* reported below */ }
const draws = read(path.join(RUN, 'draws.jsonl')).split('\n').filter((l) => l.trim()).map((l) => JSON.parse(l));
if (draws.length) firstDraw = new Date(draws.map((d) => d.at).sort()[0]);
if (preregTime && !isNaN(preregTime) && firstDraw) {
  ok(preregTime < firstDraw, 'pre-registration committed before the first draw',
    `prereg ${preregTime.toISOString()}, first draw ${firstDraw.toISOString()}`);
} else {
  console.log('    skipped: no git history for the pre-registration in this checkout');
}
ok(fs.existsSync(path.join(RUN, 'draws-discarded-pre-amendment.jsonl')),
  'the draws discarded by amendment 1 are kept, unmerged');
const discarded = read(path.join(RUN, 'draws-discarded-pre-amendment.jsonl')).split('\n').filter((l) => l.trim());
const liveKeys = new Set(draws.map((d) => `${d.cell}|${d.model}|${d.draw}|${d.at}`));
ok(discarded.every((l) => !liveKeys.has(((d) => `${d.cell}|${d.model}|${d.draw}|${d.at}`)(JSON.parse(l)))),
  'no discarded draw reappears in the live set');

// ─────────────────────────────────────────────────────────────────────────────
console.log('[3] the control differs from the published essay at the six sites and nowhere else');
const TEXTS = {
  'I:planted': read(path.join(EXP, 'artifact.md')), 'I:clean': read(path.join(EXP, 'artifact-clean.md')),
  'II:planted': read(path.join(EXP, 'artifact-2.md')), 'II:clean': read(path.join(EXP, 'artifact-2-clean.md')),
};
for (const specimen of ['I', 'II']) {
  for (const s of SITES[specimen]) {
    ok(TEXTS[`${specimen}:planted`].includes(s.anchorPlanted), `site ${specimen}.${s.n} planted anchor present`);
    ok(TEXTS[`${specimen}:clean`].includes(s.anchorClean), `site ${specimen}.${s.n} clean anchor present`);
    ok(!TEXTS[`${specimen}:clean`].includes(s.anchorPlanted), `site ${specimen}.${s.n} planted span gone from the control`);
  }
  // Paragraph-level: only paragraphs containing a site may differ.
  const P = paras(TEXTS[`${specimen}:planted`]), C = paras(TEXTS[`${specimen}:clean`]);
  const changedPlanted = P.filter((p) => !C.includes(p));
  const untouchedBySite = changedPlanted.filter((p) => !SITES[specimen].some((s) => p.includes(s.anchorPlanted.split('\n')[0])));
  ok(untouchedBySite.length === 0, `specimen ${specimen}: every changed paragraph contains a site`,
    untouchedBySite.length ? `${untouchedBySite.length} changed without one: ${untouchedBySite[0].slice(0, 70)}` : '');
}

// ─────────────────────────────────────────────────────────────────────────────
console.log('[4] the protocol on the page is the protocol that ran');
const protocol = JSON.parse(read(path.join(RUN, 'protocol.json')));
const runSrc = read(path.join(RUN, 'run.mjs'));
ok(protocol.systems.cued.length > protocol.systems.blind.length, 'the cued prompt is the blind one plus a paragraph');
ok(protocol.systems.cued.includes(protocol.systems.blind.split('\n\n')[0]), 'both prompts share the same opening');
for (const k of ['factual', 'citation', 'quantitative', 'logical', 'conceptual', 'omission']) {
  ok(protocol.systems.cued.includes(`- ${k}:`), `the cue names ${k}`);
  ok(!protocol.systems.blind.includes(`- ${k}:`), `the blind prompt does not name ${k}`);
}
ok(!/exactly six|six errors|one of each/i.test(protocol.systems.cued),
  'the cue withholds the count, so the control is not given a false premise');
ok(protocol.systems.blind.includes('may contain no problems at all') &&
   protocol.systems.cued.includes('may contain no problems at all'),
  'both arms are told the essay may be clean');
for (const [k, meta] of Object.entries(protocol.texts)) {
  const t = TEXTS[k].replace(/^#[^\n]*\n+/, '').trim() + '\n';
  ok(sha(t) === meta.sha256_16, `the essay hash for ${k} matches the committed file`);
}
ok(runSrc.includes(`const MAX_TOKENS = ${protocol.max_tokens}`), 'run.mjs asks for the token budget the protocol records');

// ─────────────────────────────────────────────────────────────────────────────
console.log('[5] the draws are one per plan slot, and nothing is double-counted');
const seen = new Set();
let dup = 0;
for (const d of draws) {
  const k = `${d.cell}|${d.model}|${d.draw}`;
  if (seen.has(k)) dup++;
  seen.add(k);
}
ok(dup === 0, 'no plan slot is drawn twice', `${dup} duplicates`);
ok(draws.every((d) => protocol.cells.includes(d.cell)), 'every draw belongs to a declared cell');
ok(draws.every((d) => protocol.roster.includes(d.model)), 'every draw comes from the frozen roster');

// ─────────────────────────────────────────────────────────────────────────────
console.log('[6] findings re-derive from the located draws');
const located = JSON.parse(read(path.join(RUN, 'score', 'located.json')));
const F = JSON.parse(read(path.join(RUN, 'findings.json')));
const answered = located.filter((d) => d.ok);
const usable = answered.filter((d) => !d.truncated);
ok(F.totals.taken === located.length, 'findings count every draw', `${F.totals.taken} vs ${located.length}`);
ok(F.totals.usable === usable.length, 'findings count the usable draws', `${F.totals.usable} vs ${usable.length}`);
ok(F.totals.truncated === answered.length - usable.length, 'findings count the truncated draws');
for (const cell of protocol.cells) {
  ok(F.cells[cell].n === usable.filter((d) => d.cell === cell).length, `cell ${cell} n re-derives`);
}
// Every rate on the page is a proportion of that cell's n, so k must never exceed n.
let bad = 0;
for (const specimen of ['I', 'II']) {
  for (const kind of Object.keys(F.H2.pooled[specimen])) {
    const h = F.H2.pooled[specimen][kind];
    if (h.catch.k > h.catch.n || h.falseAlarm.k > h.falseAlarm.n) bad++;
  }
}
ok(bad === 0, 'no catch or false-alarm count exceeds its own denominator');
ok(F.roster.reachable.length === protocol.roster.length, 'the roster in findings is the roster that ran');

// ─────────────────────────────────────────────────────────────────────────────
console.log('[7] the page states the numbers findings.json holds');
const html = read(PAGE);
const section = html.slice(html.indexOf('<!--blind-rerun:start-->'), html.indexOf('<!--blind-rerun:end-->'));
ok(section.length > 2000, 'the blind re-run section is present in the page');
const txt = section.replace(/<[^>]+>/g, ' ').replace(/&[a-z]+;/g, ' ').replace(/\s+/g, ' ');

function guard(name, needle) { return ok(txt.includes(needle), `page states ${name}`, `looked for "${needle}"`); }
guard('the usable draw count', String(F.totals.usable));
guard('the planned draw count', String(F.totals.planned));
guard('the roster size', String(F.roster.reachable.length));
guard('the fabricated-quote count', `${F.quotes.notInTheText} of ${F.quotes.quotedSpans}`);
guard('the memorisation-probe count', `${F.H4.drawsQuotingPlantedOnlySpan} of ${F.H4.cleanDraws}`);
if (F.H3.spearman !== null) guard('the cross-domain rank correlation', F.H3.spearman.toFixed(2));
guard('the within-model split count', String(F.consistency.planted.splitAcrossDraws));
guard('the ever-caught triple count', String(F.consistency.planted.everCaught));
guard('the unplanted aggregate for specimen I planted',
  `${F.unplantedAggregate['I-planted'].settledOnly.k} of ${F.unplantedAggregate['I-planted'].settledOnly.n}`);
// Every per-kind figure in the tables must be the findings' own rounding.
for (const specimen of ['I', 'II']) {
  for (const kind of Object.keys(F.H2.pooled[specimen])) {
    const h = F.H2.pooled[specimen][kind];
    if (h.catch.p === null) continue;
    ok(txt.includes(`${(100 * h.catch.p).toFixed(0)}%`), `page carries the ${specimen} ${kind} catch rate`);
  }
}
ok(/lower bound/.test(txt), 'the page says the cue measured here is a lower bound on its own');
ok(/not people|not izzy|are not people/i.test(txt), 'the page says who these readers are not');

// ─────────────────────────────────────────────────────────────────────────────
console.log('[7b] the dek states the numbers findings.json holds');
// Tonight's maintain sweep found four live deks contradicting their own pages,
// because a verifier asserts the page and never the frontmatter. This one asserts
// the frontmatter.
const MD = path.join(ROOT, 'src', 'content', 'strata', 'the-cold-read.md');
const md = read(MD);
const dekLine = (md.match(/^dek: "([\s\S]*?)"$/m) || [])[1] || '';
ok(dekLine.length > 200, 'the dek is present');
for (const [name, v] of [
  ['usable draws', F.totals.usable],
  ['roster size', F.roster.reachable.length],
  ['ever-caught triples', F.consistency.planted.everCaught],
  ['split across draws', F.consistency.planted.splitAcrossDraws],
]) ok(dekLine.includes(String(v)), `the dek carries the ${name}`, `looked for ${v}`);
ok(!/[\u2014]/.test(dekLine), 'the dek carries no em dash');
ok(new RegExp(`^date: ${F.generated}$`, 'm').test(md), 'the stratum is dated the day the run was analysed');

// ─────────────────────────────────────────────────────────────────────────────
console.log('[8] the page data file is the committed data');
if (fs.existsSync(PAGEJSON)) {
  const D = JSON.parse(read(PAGEJSON));
  const byKey = Object.fromEntries(draws.map((d) => [`${d.cell}|${d.model}|${d.draw}`, d]));
  let mismatched = 0;
  for (const d of D.draws) if (!byKey[d.id] || byKey[d.id].answer !== d.answer) mismatched++;
  ok(mismatched === 0, 'every answer served to the page is byte-identical to the committed draw', `${mismatched} differ`);
  ok(D.draws.length === answered.length, 'the page is served every answered draw');
  ok(JSON.stringify(D.findings.totals) === JSON.stringify(F.totals), 'the page data carries the current findings');
  for (const specimen of ['I', 'II']) {
    ok(D.repairs[specimen].every((r) => r.plantedPresent && r.cleanPresent && r.plantedAbsentFromClean),
      `specimen ${specimen} repairs shown on the page all check against the committed texts`);
    ok(D.unplanted[specimen].length === UNPLANTED[specimen].length,
      `specimen ${specimen} unplanted list is complete on the page`);
  }
} else {
  ok(false, 'blind-rerun.json exists beside the page');
}

// ─────────────────────────────────────────────────────────────────────────────
if (MUTATE) {
  console.log('\n[mutate] each guarded quantity is actually perturbed and its guard re-run');
  // A control that only asserts "the wrong value is not currently present" proves
  // nothing about the guard. These perturb the real input and re-evaluate the real
  // predicate, and each one must come back RED.
  const red = (name, predicate) => ok(predicate() === false, `control: ${name} makes its guard fail`);

  red('a wrong usable-draw count on the page', () => {
    const bad = txt.replace(new RegExp(`\\b${F.totals.usable}\\b`), String(F.totals.usable + 1));
    return bad.includes(` ${F.totals.usable} `) || bad.includes(`${F.totals.usable} usable`);
  });
  red('a planted span surviving into the control', () => {
    const bad = TEXTS['I:clean'] + '\n' + SITES.I[0].anchorPlanted;
    return !bad.includes(SITES.I[0].anchorPlanted);
  });
  red('an edited stimulus', () => {
    const bad = read(path.join(EXP, 'artifact.md')).replace('1957', '1953');
    return sha(bad) === STIMULUS_SHA['artifact.md'];
  });
  red('a cue that leaks the count', () => {
    const bad = protocol.systems.cued + '\nThere are exactly six errors, one of each.';
    return !/exactly six|six errors|one of each/i.test(bad);
  });
  red('a blind prompt that leaks a kind', () => {
    const bad = protocol.systems.blind + '\n- factual: a hard, checkable wrong fact.';
    return !bad.includes('- factual:');
  });
  red('a served answer that does not match the committed draw', () => {
    if (!fs.existsSync(PAGEJSON)) return false;
    const D = JSON.parse(read(PAGEJSON));
    const byKey = Object.fromEntries(draws.map((d) => [`${d.cell}|${d.model}|${d.draw}`, d]));
    const first = D.draws[0];
    const tampered = { ...first, answer: (first.answer || '') + ' (tampered)' };
    return byKey[tampered.id] && byKey[tampered.id].answer === tampered.answer;
  });
  red('a findings total that does not re-derive', () => {
    const badTotals = { ...F.totals, usable: F.totals.usable + 1 };
    return badTotals.usable === usable.length;
  });
  red('an essay hash that no longer matches its file', () => {
    const bad = TEXTS['II:clean'].replace('4.47', '4.5');
    return sha(bad.replace(/^#[^\n]*\n+/, '').trim() + '\n') === protocol.texts['II:clean'].sha256_16;
  });
}

console.log(`\n${pass} passed, ${fail} failed`);
if (fail) { failures.forEach((f) => console.error('  · ' + f)); process.exit(1); }
