#!/usr/bin/env node
// verify-told-or-counted.mjs — the check behind /strata/told-or-counted/.
//
//   node verify-told-or-counted.mjs              # from inside the repository
//   node verify-told-or-counted.mjs --from-site  # from an empty directory, over HTTPS
//   node verify-told-or-counted.mjs --arms       # read the live store, print the readout
//                                                # research/told-or-counted/PREREGISTRATION.md asks for
//
// WHAT THIS PAGE IS AND WHY IT NEEDS A CHECK OF THIS PARTICULAR SHAPE.
//
// /strata/told-or-counted/ is a guide to eleven OTHER pages. It rules, per experiment, on
// which facts may be shown to a reader before that reader takes part, and it derives every
// ruling from what the experiment's own page already does. That is a claim about somebody
// else's file, which is the most perishable kind of claim this corpus can make: the eleven
// pages have their own authors and their own nights, and a sentence here goes quietly false
// the moment one of them is edited.
//
// So the ruling is not prose. It is research/told-or-counted -> public/strata/told-or-counted/
// policy.mjs, where every entry carries a VERBATIM quotation and the file it came from, and
// this program re-reads all of them. Thirty-three quotations across eleven pages. If any one
// of them stops occurring, this goes red, which is the only way a claim about another page
// survives being written down.
//
// The other half is the mathematics the page operates in front of the reader: that a betting
// confidence sequence keeps its coverage while somebody watches it, and that the ordinary
// interval does not. That is checked by running the same computation the browser runs, in
// Node, against the same shared module, and it is checked DIFFERENTIALLY: if the classical
// interval also passes, the harness is not measuring peeking and the run fails loudly rather
// than reporting a comfortable success.

import { readFileSync, existsSync, writeFileSync, mkdirSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import path from 'node:path';
import os from 'node:os';
import vm from 'node:vm';
import { webcrypto } from 'node:crypto';

const ORIGIN = 'https://artwaste.land';
const ARGS = new Set(process.argv.slice(2));
const FROM_SITE = ARGS.has('--from-site');
const ARMS_ONLY = ARGS.has('--arms');
const ROOT = path.dirname(fileURLToPath(import.meta.url));

let pass = 0;
const failures = [];
const skipped = [];
function ok(name, cond, detail) {
  if (cond) { pass += 1; return true; }
  failures.push(detail ? `${name} — ${detail}` : name);
  return false;
}

// ── reading a file, from the repository or from the deployed site ──────────
// The reader running this in an empty directory possesses nothing. Every path below is a
// repository path; --from-site maps it to the URL that serves the same bytes, so the check a
// stranger runs is the check that ran here, over the wire, against what is actually deployed.
const SITE_PATH = new Map([
  ['public/strata/told-or-counted/policy.mjs', '/strata/told-or-counted/policy.mjs'],
  ['public/strata/told-or-counted/index.html', '/strata/told-or-counted/'],
  ['public/strata/told-or-counted/app.js', '/strata/told-or-counted/app.js'],
  ['public/_kit/collective.js', '/_kit/collective.js'],
  ['worker.js', null],   // not served; checked only from inside the repository
]);

function siteUrlFor(repoPath) {
  if (SITE_PATH.has(repoPath)) {
    const mapped = SITE_PATH.get(repoPath);
    return mapped === null ? null : ORIGIN + mapped;
  }
  if (repoPath.startsWith('public/')) return ORIGIN + '/' + repoPath.slice('public/'.length);
  return null;
}

const cache = new Map();
async function readSource(repoPath) {
  if (cache.has(repoPath)) return cache.get(repoPath);
  let text = null;
  if (!FROM_SITE) {
    const local = path.join(ROOT, repoPath);
    if (existsSync(local)) text = readFileSync(local, 'utf8');
  }
  if (text === null) {
    const url = siteUrlFor(repoPath);
    if (url) {
      const r = await fetch(url, { redirect: 'follow' });
      if (r.ok) text = await r.text();
    }
  }
  cache.set(repoPath, text);
  return text;
}

// ── the policy module, however we can reach it ─────────────────────────────
async function loadPolicy() {
  const repoPath = 'public/strata/told-or-counted/policy.mjs';
  const local = path.join(ROOT, repoPath);
  if (!FROM_SITE && existsSync(local)) return import(path.toNamespaceURL ? path.toNamespaceURL(local) : 'file://' + local);
  const src = await readSource(repoPath);
  if (!src) throw new Error('could not obtain policy.mjs from disk or from ' + ORIGIN);
  const dir = path.join(os.tmpdir(), 'aw-told-or-counted');
  mkdirSync(dir, { recursive: true });
  const tmp = path.join(dir, 'policy.mjs');
  writeFileSync(tmp, src);
  return import('file://' + tmp);
}

// ── the shared kit, loaded the way its own tests load it ───────────────────
async function loadKit() {
  const src = await readSource('public/_kit/collective.js');
  if (!src) throw new Error('could not obtain the shared kit');
  const sandbox = { crypto: webcrypto, TextEncoder, console, fetch: async () => { throw new Error('no network in the sandbox'); } };
  vm.createContext(sandbox);
  vm.runInContext(src, sandbox);
  return sandbox.AW.collective;
}

// ── the mathematics the page shows, recomputed here ────────────────────────
const Z = 1.959963984540054;
function wilson(successes, n) {
  if (n <= 0) return [0, 1];
  const p = successes / n;
  const d = 1 + (Z * Z) / n;
  const centre = p + (Z * Z) / (2 * n);
  const half = Z * Math.sqrt((p * (1 - p)) / n + (Z * Z) / (4 * n * n));
  return [Math.max(0, (centre - half) / d), Math.min(1, (centre + half) / d)];
}
function xorshift32(seed) {
  let x = seed >>> 0 || 1;
  return () => { x ^= x << 13; x >>>= 0; x ^= x >>> 17; x ^= x << 5; x >>>= 0; return x / 4294967296; };
}
function comparison(kit, pTrue, nMax, runs, seed) {
  const rand = xorshift32(seed);
  let cls = 0;
  let cs = 0;
  for (let r = 0; r < runs; r++) {
    const seq = kit.makeBettingCS({ alpha: 0.05, gridSize: 201 });
    let successes = 0;
    let clsBad = false;
    let csBad = false;
    for (let n = 1; n <= nMax; n++) {
      const x = rand() < pTrue ? 1 : 0;
      successes += x;
      seq.update(x);
      if (!clsBad) {
        const [lo, hi] = wilson(successes, n);
        if (pTrue < lo || pTrue > hi) clsBad = true;
      }
      if (!csBad) {
        const iv = seq.interval();
        if (iv.empty || pTrue < iv.lo || pTrue > iv.hi) csBad = true;
      }
    }
    if (clsBad) cls += 1;
    if (csBad) cs += 1;
  }
  return { runs, cls, cs, clsRate: cls / runs, csRate: cs / runs };
}

// ── the live store ─────────────────────────────────────────────────────────
async function readArm(id) {
  const r = await fetch(`${ORIGIN}/api/collective/${encodeURIComponent(id)}`, { cache: 'no-store' });
  const j = await r.json();
  if (!j || j.ok !== true) throw new Error(j && j.error ? j.error : 'unavailable');
  return j;
}

async function armsReadout(policy) {
  console.log('\nTHE LIVING ARMS, read from ' + ORIGIN + ' at ' + new Date().toISOString());
  console.log('(the readout research/told-or-counted/PREREGISTRATION.md asks for)\n');
  let total = 0;
  let safeTotal = 0;
  let gatedTotal = 0;
  const rows = [];
  for (const e of policy.EXPERIMENTS) {
    let cell;
    try {
      const arm = await readArm(e.arm);
      total += arm.n;
      if (e.countSafe) safeTotal += arm.n; else gatedTotal += arm.n;
      cell = { n: arm.n, since: arm.since, cap: arm.maxRows };
    } catch (err) {
      cell = { n: null, since: null, cap: null, error: String(err.message || err) };
    }
    rows.push([e.arm, e.countSafe ? 'open' : 'gated', cell]);
  }
  const w = Math.max(...rows.map((r) => r[0].length));
  for (const [arm, kind, cell] of rows) {
    const n = cell.error ? 'ERR ' + cell.error : String(cell.n).padStart(6);
    console.log(`  ${arm.padEnd(w)}  ${kind.padEnd(5)}  ${n}   since ${cell.since === null ? 'never' : cell.since}`);
  }
  console.log(`\n  total across the eleven: ${total}`);
  console.log(`  count-open arms: ${safeTotal}   count-gated arms: ${gatedTotal}`);
  console.log(`  what the total says about any single arm: ${policy.leakDescription(total)}`);
  console.log('\n  PREDICTION 1 (at least one row somewhere by 2026-10-14): ' + (total >= 1 ? 'SATISFIED' : 'not yet'));
  console.log('  PREDICTION 2 (open arms hold at least as many as gated): ' + (safeTotal >= gatedTotal ? 'holds' : 'FAILS'));
  if (total >= 1) {
    console.log('\n  Before recording P1 as satisfied, the pre-registration asks two things of you:');
    console.log('   1. check research/told-or-counted/ for any record of a row posted by this project;');
    console.log('   2. check whether the day stamp on the first row falls on a night an instance was awake.');
  }
  return total;
}

// ── the run ────────────────────────────────────────────────────────────────
async function main() {
  const policy = await loadPolicy();

  if (ARMS_ONLY) {
    await armsReadout(policy);
    return 0;
  }

  console.log('verify-told-or-counted.mjs' + (FROM_SITE ? '  (reading ' + ORIGIN + ')' : '  (reading this checkout)'));

  // 1. Every quotation the ruling rests on still occurs, verbatim, where it says it does.
  let quotes = 0;
  for (const e of policy.EXPERIMENTS) {
    for (const ev of e.evidence) {
      const src = await readSource(ev.file);
      quotes += 1;
      ok(`evidence: ${e.arm} <- ${ev.file}`, src !== null && src.includes(ev.quote),
        src === null ? 'file unreadable' : 'quotation no longer present: ' + JSON.stringify(ev.quote.slice(0, 70)));
    }
  }
  ok('every experiment carries at least two quotations', policy.EXPERIMENTS.every((e) => e.evidence.length >= 2));

  // 2. The published column is sourced the same way. No figure typed from memory.
  for (const [arm, pub] of Object.entries(policy.PUBLISHED)) {
    const src = await readSource(pub.file);
    quotes += 1;
    ok(`published figure: ${arm} <- ${pub.file}`, src !== null && src.includes(pub.quote),
      src === null ? 'file unreadable' : 'figure no longer present in its own source: ' + JSON.stringify(pub.quote));
  }
  ok('the published column covers all eleven',
    Object.keys(policy.PUBLISHED).sort().join(',') === policy.EXPERIMENTS.map((e) => e.arm).sort().join(','));

  // 3. The eleven are the registry's living arms, parsed rather than typed.
  const worker = await readSource('worker.js');
  if (worker) {
    const block = worker.slice(worker.indexOf('const COLLECTIVE_EXPERIMENTS'), worker.indexOf('const COLLECTIVE_NOTE'));
    const declared = [...block.matchAll(/^\s{2}"([a-z0-9][a-z0-9-]*)":\s*\{/gm)].map((m) => m[1]);
    const living = declared.filter((id) => id !== 'kit-selftest');
    ok('the registry declares a kit-selftest arm', declared.includes('kit-selftest'));
    ok('the eleven are exactly the registry\'s living arms',
      living.sort().join(',') === policy.EXPERIMENTS.map((e) => e.arm).sort().join(','),
      `registry has [${living.sort().join(', ')}]`);
    for (const e of policy.EXPERIMENTS) {
      const spec = block.slice(block.indexOf(`"${e.arm}"`));
      const m = spec.match(/perIpDay:\s*(\d+)/);
      ok(`per-address daily limit printed for ${e.arm} matches the registry`, m && Number(m[1]) === e.perIpDay,
        m ? `page says ${e.perIpDay}, registry says ${m[1]}` : 'registry limit not found');
      const fieldsBlock = spec.slice(spec.indexOf('fields:'), spec.indexOf('perIpDay'));
      const fieldCount = (fieldsBlock.match(/\{\s*name:/g) || []).length;
      ok(`integer count printed for ${e.arm} matches the registry`, fieldCount === e.integers,
        `page says ${e.integers}, registry declares ${fieldCount}`);
    }
  } else {
    // Not a failure and not waved through. The Worker's registry is not a served file, so a
    // reader running --from-site cannot see it, and saying so is the honest report. Claiming
    // a check we were not in a position to run is the exact fault this corpus keeps catching.
    skipped.push('the registry comparison (worker.js is not a served file, so it runs only inside the repository): '
      + (1 + policy.EXPERIMENTS.length * 2) + ' checks');
  }

  // 4. Each of the eleven really is at the address the page sends a reader to, and really
  //    does name the arm the ruling attributes to it.
  for (const e of policy.EXPERIMENTS) {
    const pagePath = `public/strata/${e.slug}/index.html`;
    const page = await readSource(pagePath);
    ok(`${e.slug} is a real page`, page !== null && page.length > 500);
    const files = [page || ''];
    for (const extra of [`public/strata/${e.slug}/app.js`, `public/strata/${e.slug}/analysis.mjs`]) {
      const t = await readSource(extra);
      if (t) files.push(t);
    }
    ok(`${e.slug} names the arm ${e.arm}`, files.some((t) => t.includes(`'${e.arm}'`) || t.includes(`"${e.arm}"`)));
  }

  // 5. This page posts nothing. The one thing the project may not do to its own experiments.
  const portalHtml = await readSource('public/strata/told-or-counted/index.html');
  const portalJs = await readSource('public/strata/told-or-counted/app.js');
  const bytes = (portalHtml || '') + '\n' + (portalJs || '');
  ok('the portal ships both of its own files', Boolean(portalHtml && portalJs));
  ok('the portal never calls contribute', !/\bcontribute\s*\(/.test(bytes),
    'a call to AW.collective.contribute appears in the portal\'s own bytes');
  // Every write the shipped bytes make, named rather than assumed absent. This check was
  // WRONG until the reader-side run caught it: it asserted the page issues no POST at all,
  // which is false and was false from the moment it deployed, because the site's own pulse
  // beacon is injected into every built page and posts the path to /api/pulse. Inside the
  // repository the source file carries no beacon, so the check passed on a page that does
  // not exist, and only a run against the served bytes could tell. The claim that matters is
  // narrower and is now the one being made: nothing here writes to a collective arm.
  const posts = [...bytes.matchAll(/method\s*:\s*['"]POST['"]/gi)]
    .map((m) => bytes.slice(Math.max(0, m.index - 200), m.index + 120));
  ok('every write the shipped bytes make is the site-wide pulse beacon',
    posts.every((ctx) => ctx.includes('/api/pulse')),
    `${posts.filter((c) => !c.includes('/api/pulse')).length} POST(s) go somewhere else`);
  ok('nothing here writes to a collective arm',
    !posts.some((ctx) => ctx.includes('/api/collective')));
  ok('the collective endpoint is only ever read',
    [...bytes.matchAll(/\/api\/collective/g)].every((m) => {
      const ctx = bytes.slice(Math.max(0, m.index - 260), m.index + 260);
      return !/method\s*:\s*['"]POST['"]/i.test(ctx);
    }));

  // 5b. The machine column the page cites. Six of the eleven ship a committed file of model
  //     draws; the page prints their total, so the total is counted here rather than typed.
  let modelFiles = 0;
  let modelDraws = 0;
  for (const e of policy.EXPERIMENTS) {
    const raw = await readSource(`public/strata/${e.slug}/model-arm.json`);
    if (!raw) continue;
    let parsed = null;
    try { parsed = JSON.parse(raw); } catch (err) { parsed = null; }
    if (!parsed || !Array.isArray(parsed.runs)) continue;
    modelFiles += 1;
    modelDraws += parsed.runs.length;
  }
  const pagePrintsDraws = (portalHtml || '').includes(modelDraws.toLocaleString('en'));
  ok('the model-draw total the page prints is the one on disk',
    pagePrintsDraws, `counted ${modelDraws.toLocaleString('en')} draws across ${modelFiles} committed files`);
  ok('the page is right about how many of the eleven ship one',
    (portalHtml || '').includes('Six of the eleven') === (modelFiles === 6),
    `${modelFiles} of the eleven ship a model-arm file`);

  // 5c. The pre-registration the page links. It lives in the lab notebook at
  //     research/told-or-counted/ and is served from public/research/told-or-counted/ by the
  //     convention thirty-two other layers already use. Two copies can drift, so they are
  //     compared rather than trusted, and the served one is the one a reader can actually get.
  const preregServed = await readSource('public/research/told-or-counted/PREREGISTRATION.md');
  ok('the pre-registration the page links is served', Boolean(preregServed && preregServed.length > 2000));
  ok('the page links the served copy, not a repository path',
    (portalHtml || '').includes('/research/told-or-counted/PREREGISTRATION.md') &&
    !(portalHtml || '').includes('/checks/research/told-or-counted/PREREGISTRATION.md'));
  if (!FROM_SITE) {
    const preregLab = await readSource('research/told-or-counted/PREREGISTRATION.md');
    ok('the served pre-registration is byte-identical to the one in the lab notebook',
      preregLab !== null && preregServed !== null && preregLab === preregServed,
      'the two copies have drifted; the served one is what a reader gets');
  }
  for (const needle of ['2026-10-14', 'Prediction P1', 'Falsification of H1']) {
    ok(`the pre-registration still carries "${needle}"`, Boolean(preregServed && preregServed.includes(needle)));
  }

  // 6. The differential pair. The claim the page operates in front of the reader.
  const kit = await loadKit();
  const nulled = comparison(kit, 0.5, 200, 400, 20260914);
  ok('the confidence sequence keeps its coverage under continuous peeking',
    nulled.csRate <= 0.05, `it excluded the truth in ${nulled.cs} of ${nulled.runs} streams`);
  ok('the ordinary interval does NOT, in the same harness',
    nulled.clsRate > 0.05, `it excluded the truth in ${nulled.cls} of ${nulled.runs}; if this passes the harness is not measuring peeking`);
  ok('and the gap is large enough to be the point rather than noise',
    nulled.clsRate >= nulled.csRate * 3 && nulled.clsRate - nulled.csRate > 0.1,
    `classical ${(nulled.clsRate * 100).toFixed(1)}% against sequence ${(nulled.csRate * 100).toFixed(1)}%`);
  const off = comparison(kit, 0.25, 200, 200, 4242);
  ok('the sequence holds at a rate away from one half too', off.csRate <= 0.05,
    `excluded in ${off.cs} of ${off.runs} at p = 0.25`);

  // 7. Exclusion is permanent, which is what makes "ever" the right word above.
  // Once a candidate mean has been bankrupted it must stay out, however the stream turns
  // afterwards. Watch one candidate across a stream built to tempt a re-admission: sixty
  // ones, which shoves the interval far from 0.05, then sixty zeros, which drags it back.
  const seq = kit.makeBettingCS({ alpha: 0.05, gridSize: 201 });
  const watch = 0.05;
  const inside = [];
  for (let i = 0; i < 120; i++) {
    seq.update(i < 60 ? 1 : 0);
    const iv = seq.interval();
    inside.push(!iv.empty && watch >= iv.lo && watch <= iv.hi);
  }
  let readmitted = false;
  for (let i = 1; i < inside.length; i++) if (!inside[i - 1] && inside[i]) readmitted = true;
  ok('a bankrupted value is never re-admitted', inside.includes(false) && !readmitted,
    inside.includes(false) ? 'the interval let an excluded value back in' : 'the harness never excluded anything, so it tested nothing');
  ok('an interval with nothing in it is the whole line and says so',
    (() => { const z = kit.makeBettingCS({}); const iv = z.interval(); return iv.n === 0 && iv.lo === 0 && iv.hi === 1; })());

  // 8. The leak arithmetic, exercised at its boundary.
  ok('a total of zero is stated as pinning every arm exactly', policy.totalLeaksExactCount(0));
  ok('a total above zero is not', !policy.totalLeaksExactCount(1));
  ok('the leak description changes at the declared threshold',
    policy.leakDescription(policy.LEAK_CLOSES_AT - 1) !== policy.leakDescription(policy.LEAK_CLOSES_AT));

  // 9. The ruling is a ruling: every gate carries a stated reason, not a shrug.
  for (const e of policy.EXPERIMENTS) {
    ok(`${e.arm} states why its count is or is not safe to show`, e.countReason.length > 40);
    ok(`${e.arm} states why its published result is or is not safe to show`, e.priorReason.length > 40);
    ok(`${e.arm} is named by an act, not by its subject`, e.ask.length > 20 && !e.ask.includes(e.title));
  }
  ok('some of the eleven are gated and some are not',
    policy.COUNT_GATED.length > 0 && policy.COUNT_GATED.length < policy.EXPERIMENTS.length &&
    policy.PRIOR_GATED.length > 0 && policy.PRIOR_GATED.length < policy.EXPERIMENTS.length);

  console.log(`\n  ${quotes} quotations re-read across ${policy.EXPERIMENTS.length} pages`);
  console.log(`  machine column: ${modelDraws.toLocaleString('en')} attempted draws across ${modelFiles} committed files`);
  console.log(`  peeking harness: ordinary interval failed ${(nulled.clsRate * 100).toFixed(1)}% of ${nulled.runs} streams, sequence ${(nulled.csRate * 100).toFixed(1)}%`);
  console.log(`\n  ${pass} checks passed, ${failures.length} failed${skipped.length ? ', ' + skipped.length + ' not runnable here' : ''}`);
  for (const s2 of skipped) console.log('   \u2014 skipped: ' + s2);
  for (const f of failures) console.log('   ✗ ' + f);
  return failures.length === 0 ? 0 : 1;
}

main().then((code) => process.exit(code)).catch((err) => {
  console.error('verify-told-or-counted.mjs could not run: ' + (err && err.stack || err));
  process.exit(2);
});
