#!/usr/bin/env node
// research/the-dead-zone-and-the-clock/verify-the-error-that-is-not-in-the-file.mjs
//
//   node research/the-dead-zone-and-the-clock/verify-the-error-that-is-not-in-the-file.mjs
//
// Reads the bytes this page ships and the records it was built from, and refuses to pass if
// they disagree. It also runs the analyser's own controls, because a checker that cannot fail
// is the failure mode this project keeps rediscovering.
//
// Six kinds of assertion:
//   A. the analyser can fail    — planted defects are caught, planted clean code is not accused
//   B. static against browser   — every CERTAIN shape threw on every load; every safe shape on none
//   C. the page against the record — the inlined JSON is current and its counts are the records'
//   D. the prose against the record — every figure written in sentences is one the record holds
//   E. the page against itself  — this page passes the gate it is about
//   F. the history is coherent  — the walk's end state matches the working tree

import { readFileSync, existsSync } from 'node:fs';
import { dirname, resolve, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { SHAPES } from './shapes.mjs';
import { analyzeHtml } from '../../scripts/check-dead-zone.mjs';

const HERE = dirname(fileURLToPath(import.meta.url));
const ROOT = resolve(HERE, '../..');
// Written as a literal path rather than assembled from a slug, because the placard tooling
// (`research/verifier-independence/lib/checks.mjs`, rule 2) decides which page a check belongs
// to by looking for `/strata/<slug>` in the check's own source. Assembling the path hides that
// answer from it, and a check whose subject a reader cannot grep for is worse documentation
// than one line of duplication.
const PAGE = join(ROOT, 'public/strata/the-error-that-is-not-in-the-file/index.html');

let pass = 0; const fails = [];
const ok = (cond, label, detail = '') => {
  if (cond) { pass++; return true; }
  fails.push(`${label}${detail ? '  ·  ' + detail : ''}`);
  return false;
};
const load = (f) => (existsSync(join(HERE, f)) ? JSON.parse(readFileSync(join(HERE, f), 'utf8')) : null);

const chromium = load('results.json');
const firefox = load('results-firefox.json');
const webkit = load('results-webkit.json');
const history = load('history.json');
const corpus = load('corpus.json');
const html = readFileSync(PAGE, 'utf8');

// ── A. the analyser can fail, and can clear ───────────────────────────────────────────
{
  const planted = '<script type="module">function r(){return X;}\nr();\nlet X=1;</script>';
  const clean = '<script type="module">let X=1;\nfunction r(){return X;}\nr();</script>';
  const varForm = '<script type="module">function r(){return X;}\nr();\nvar X=1;</script>';
  const deferred = '<script type="module">function r(){return X;}\nsetTimeout(r,0);\nlet X=1;</script>';
  const k = (h) => new Set(analyzeHtml(h).findings.map((f) => f.klass));
  ok(k(planted).has('CERTAIN'), 'A1 a planted synchronous dead-zone read is caught');
  ok(k(clean).size === 0, 'A2 the same code in the right order is not accused', [...k(clean)].join(','));
  ok(k(varForm).size === 0, 'A3 a `var` is not accused of a dead zone', [...k(varForm)].join(','));
  ok(k(deferred).has('LATENT') && !k(deferred).has('CERTAIN'),
    'A4 a deferred read with no suspension above the declaration is LATENT, not CERTAIN');

  // A5 exists because the line numbers were WRONG BY ONE for most of this study, and nothing
  // caught it: acorn counts from 1 inside the script source, whose first line shares an HTML
  // line with the opening tag, so the offset is `tagLine - 1` and not `tagLine`. It was found
  // by opening a page the sweep named and not finding the code on the line it named. A
  // reported line is a claim about a file, so it gets an assertion like any other.
  const padded = '<!doctype html>\n<body>\n<script type="module">\nfunction r(){return X;}\nr();\nlet X=1;\n</script>';
  const f = analyzeHtml(padded).findings.filter((x) => x.klass === 'CERTAIN')[0];
  ok(f && f.line === 5 && f.declLine === 6,
    'A5 the reported line numbers are the file\'s own line numbers',
    f ? `read line ${f.line} (want 5), decl line ${f.declLine} (want 6)` : 'nothing flagged');
}

// ── B. the static verdict against what the browser actually did ───────────────────────
const RANK = ['CERTAIN', 'CONDITIONAL', 'RACED', 'LATENT', 'LISTENER'];
const verdictOf = (src) => {
  const kinds = new Set(analyzeHtml(`<script type="module">\n${src}\n</script>`).findings.map((f) => f.klass));
  for (const r of RANK) if (kinds.has(r)) return r;
  return 'CLEAN';
};
if (ok(!!chromium, 'B0 the chromium record exists')) {
  const byId = Object.fromEntries(chromium.shapes.map((s) => [s.id, s]));
  ok(chromium.shapes.length === SHAPES.length, 'B1 every shape was measured',
    `${chromium.shapes.length} of ${SHAPES.length}`);
  let certain = 0, safe = 0, undecided = 0;
  for (const s of SHAPES) {
    const m = byId[s.id];
    if (!m) { fails.push(`B2 ${s.id} has no measurement`); continue; }
    const v = verdictOf(s.src);
    if (v === 'CERTAIN') {
      certain++;
      // CERTAIN has two sub-cases and only their DISJUNCTION is engine-independent.
      //   · the read is on the module's own evaluation path (C3, A1, A2): the body dies, so
      //     `completed` is 0 everywhere. Whether anyone is TOLD is engine-dependent, and
      //     WebKit tells nobody.
      //   · the read is in a callback that fires while the body is suspended (T1): the body
      //     resumes and completes, and the uncaught error is reported by all three engines.
      // So the assertion is "the body died OR an error was reported", every load, every
      // engine. Asserting `threw` alone was wrong and WebKit is what proved it.
      ok(m.completed === 0 || m.threw === m.trials,
        `B3 ${s.id} called CERTAIN either died or reported, on every load`,
        `completed ${m.completed}/${m.trials}, threw ${m.threw}/${m.trials}`);
    } else if (['CLEAN', 'LATENT', 'LISTENER'].includes(v)) {
      safe++;
      ok(m.threw === 0, `B4 ${s.id} called ${v} threw on no load`, `${m.threw}/${m.trials}`);
    } else undecided++;
    ok((m.threw === m.trials ? 'always' : m.threw === 0 ? 'never' : 'split') === s.predict
      || m.threw > 0 && m.threw < m.trials,
      `B5 ${s.id} matched its pre-registered prediction`, `predicted ${s.predict}, threw ${m.threw}/${m.trials}`);
  }
  // 4 CERTAIN, 8 that cannot throw at load, 6 the source refuses to decide. Asserted as exact
  // numbers rather than floors, so adding or reclassifying a shape has to come through here.
  ok(certain === 4 && safe === 8 && undecided === 6,
    'B6 the specimen set spans all three answers', `${certain} certain, ${safe} safe, ${undecided} undecidable`);

  // the sweep must actually contain a split, or the page's central claim is unsupported
  const sweep = chromium.sweep || [];
  const split = sweep.filter((r) => r.threw > 0 && r.threw < r.trials);
  ok(split.length >= 3, 'B7 the latency sweep contains genuinely split stops',
    `${split.length} of ${sweep.length} stops are neither 0 nor ${chromium.trials}`);
  const top = sweep.filter((r) => r.serverDelayMs >= 6);
  ok(top.length > 0 && top.every((r) => r.threw === r.trials),
    'B8 past the knee every stop throws on every load');
}

// cross-engine: a rule of the language should not be a habit of one implementation. The
// agreement is asserted on OUTCOME (did the body finish), not on REPORTING (was anyone told),
// because those turned out to be different questions and only the first is engine-independent.
for (const [name, rec] of [['firefox', firefox], ['webkit', webkit]]) {
  if (!rec) continue;
  const byId = Object.fromEntries(rec.shapes.map((s) => [s.id, s]));
  let agree = 0, total = 0;
  for (const s of SHAPES) {
    const v = verdictOf(s.src), m = byId[s.id];
    if (!m || !['CERTAIN', 'CLEAN', 'LATENT', 'LISTENER'].includes(v)) continue;
    total++;
    if (v === 'CERTAIN' ? (m.completed === 0 || m.threw === m.trials) : m.threw === 0) agree++;
  }
  ok(total > 0 && agree === total, `B9 ${name} agrees with the static verdict on every decidable shape`,
    `${agree}/${total}`);
}

// ── B10. the reporting matrix, which is the finding that changed the wording above ────
{
  const rep = load('reporting.json');
  if (ok(!!rep, 'B10a the reporting-channel experiment is committed')) {
    const engines = [...new Set(rep.rows.map((r) => r.engine))];
    ok(engines.length === 3, 'B10b all three engines were probed', engines.join(','));
    ok(rep.silent.length > 0, 'B10c at least one (engine, failure) pair is reported on no channel',
      `${rep.silent.length}`);
    ok(rep.ruleHolds, 'B10d every silent pair is an already-suspended module whose evaluation rejected');
    // and the ones that are NOT silent must really be reported, or the probe proves nothing
    const loud = rep.rows.filter((r) => !(r.engine === 'webkit' && r.suspended && r.isEvaluation));
    ok(loud.every((r) => r.reported === r.trials),
      'B10e every other (engine, failure) pair is reported on every trial',
      loud.filter((r) => r.reported !== r.trials).map((r) => `${r.engine}/${r.id}`).join(','));
  }
}

// ── C. the page against the record ────────────────────────────────────────────────────
const slot = /<script type="application\/json" id="record">([\s\S]*?)<\/script>/.exec(html);
if (ok(!!slot, 'C0 the page carries an inlined record')) {
  let rec = null;
  try { rec = JSON.parse(slot[1]); } catch (e) { fails.push('C1 the inlined record is not valid JSON'); }
  if (rec) {
    ok(rec.shapes.length === SHAPES.length, 'C2 the inlined record covers every shape');
    const byId = Object.fromEntries(chromium.shapes.map((s) => [s.id, s]));
    const mismatched = rec.shapes.filter((s) => byId[s.id] && s.chromium !== byId[s.id].threw);
    ok(mismatched.length === 0, 'C3 every inlined chromium count is the measured one',
      mismatched.map((s) => s.id).join(','));
    const badStatic = rec.shapes.filter((s) => s.static !== verdictOf(s.src));
    ok(badStatic.length === 0, 'C4 every inlined static verdict is what the analyser says now',
      badStatic.map((s) => s.id).join(','));
    ok(rec.sweep.length === (chromium.sweep || []).length, 'C5 the inlined sweep is the measured sweep');
    if (corpus) {
      const certain = corpus.rows.filter((r) => r.findings.some((x) => x.klass === 'CERTAIN')).length;
      ok(rec.corpus && rec.corpus.files === corpus.files && rec.corpus.certain === certain,
        'C6 the inlined corpus census is the committed one');
    }
    if (history) {
      ok(rec.history && rec.history.versions === history.versionsAnalysed
        && rec.history.certainVersions === history.certainVersions,
        'C7 the inlined history is the committed one');
    }
  }
}

// ── D. the prose against the record ───────────────────────────────────────────────────
//
// Numbers written in sentences are the ones that rot, because nothing renders them. Each of
// these is asserted against the record rather than eyeballed.
{
  const text = html.replace(/<script[\s\S]*?<\/script>/g, ' ').replace(/<[^>]+>/g, ' ');
  const has = (s) => text.includes(s);
  if (chromium) {
    ok(has(`${chromium.trials} times out of ${chromium.trials}`) || has(`${chromium.trials}/${chromium.trials}`),
      'D1 the prose trial count is the measured one', String(chromium.trials));
    const sweep = chromium.sweep || [];
    const band = sweep.filter((r) => r.serverDelayMs <= 5).map((r) => r.threw);
    ok(band.length === 6 && has(band.join(', ').replace(/, (\d+)$/, ' and $1')),
      'D2 the six split counts in the prose are the six measured ones', band.join(', '));
    const knee = sweep.find((r) => r.serverDelayMs >= 6);
    ok(knee && knee.threw === knee.trials, 'D3 the prose knee at six milliseconds is real');
  }
  if (corpus) {
    ok(has(corpus.files.toLocaleString('en-US')), 'D4 the corpus file count in the prose is the census',
      String(corpus.files));
    ok(has(corpus.scripts.toLocaleString('en-US')), 'D5 the inline-script count in the prose is the census',
      String(corpus.scripts));
    const latent = corpus.rows.filter((r) => r.findings.some((x) => x.klass === 'LATENT')).length;
    const listener = corpus.rows.filter((r) => r.findings.some((x) => x.klass === 'LISTENER')).length;
    ok(latent === 11 && listener === 28,
      'D6 the eleven latent and twenty-eight listener pages named in the prose are the census',
      `${latent} latent, ${listener} listener`);
  }
  if (history) {
    ok(has(history.versionsAnalysed.toLocaleString('en-US')), 'D7 the version count in the prose is the walk',
      String(history.versionsAnalysed));
    ok(has(history.pages.toLocaleString('en-US')), 'D8 the page count in the prose is the walk', String(history.pages));
    ok(history.windows.length === 1, 'D9 there is exactly one window, as the prose says',
      String(history.windows.length));
    const w = history.windows[0];
    if (w) {
      // "six days and twenty hours" is a FLOOR of the real span and the prose means it that
      // way, so it is checked against seconds rather than against the rounded `days` field.
      const secs = w.to - w.from;
      const dd = Math.floor(secs / 86400), hh = Math.floor((secs % 86400) / 3600);
      ok(dd === 6 && hh === 20, 'D10 the stated window length is the measured one',
        `${dd}d ${hh}h ${Math.floor((secs % 3600) / 60)}m`);
      const names = [...new Set((w.detail || []).map((d) => d.name))];
      ok(names.length > 0 && has(names[0]),
        'D11 the binding named in the prose is the one the walk found', names.join(','));
    }
  }
}

// ── D2. the safe verdicts, checked against real pages rather than specimens ───────────
//
// The specimens establish that the analyser is right about shapes it wrote itself. The
// control that matters is whether it is right about pages someone else wrote. Every layer it
// calls LATENT or LISTENER was loaded in a browser; none may have thrown.
{
  const ctrl = load('safe-pages-control.json');
  if (ok(!!ctrl, 'D2a the browser control over the safe pages is committed')) {
    const withErrors = ctrl.results.filter((r) => r.errors.length);
    ok(withErrors.length === 0, 'D2b no page the analyser calls LATENT or LISTENER threw at load',
      withErrors.map((r) => r.url).join(','));
    // and the control must have covered every such page the census names, or it proves less
    const named = new Set(corpus.rows
      .filter((r) => r.findings.some((f) => ['LATENT', 'LISTENER'].includes(f.klass)))
      .map((r) => r.file).filter((f) => f.startsWith('public/strata/')).map((f) => f.split('/')[2]));
    const covered = new Set(ctrl.results.map((r) => r.url.replace(/^\/strata\/|\/$/g, '')));
    const missed = [...named].filter((s) => !covered.has(s));
    ok(missed.length === 0, 'D2c the control covered every safe layer the census names', missed.join(','));
    const text = html.replace(/<script[\s\S]*?<\/script>/g, ' ').replace(/<[^>]+>/g, ' ');
    ok(text.includes('twenty-three') && ctrl.results.length === 23,
      'D2d the count in the prose is the count in the control', String(ctrl.results.length));
  }
}

// ── D3. the page may not name an engine it has no numbers for ─────────────────────────
//
// Written because the prose was drafted while a third engine was still installing, and prose
// that names a browser is a claim that the browser was run. If a measurement never lands,
// this fails rather than letting a plausible sentence stand.
{
  const text = html.replace(/<script[\s\S]*?<\/script>/g, ' ').replace(/<[^>]+>/g, ' ');
  for (const [name, rec] of [['Firefox', firefox], ['WebKit', webkit], ['Chromium', chromium]]) {
    if (!new RegExp(name, 'i').test(text)) continue;
    ok(!!rec && rec.shapes && rec.shapes.length === SHAPES.length,
      `D3 the page names ${name}, so ${name} must have a full measurement record`,
      rec ? `${rec.shapes.length} shapes` : 'no record');
  }
}

// ── D4. the worked latent example, checked against the page it names ──────────────────
//
// The page points at another instance's layer by name and quotes two line numbers out of it.
// That is a claim about a file this study does not own, so it is asserted rather than trusted;
// if that layer is edited, this goes red and the sentence gets updated instead of rotting.
{
  const other = join(ROOT, 'public/strata/cast-your-model/index.html');
  if (ok(existsSync(other), 'D4a the layer used as the worked latent example still exists')) {
    const f = analyzeHtml(readFileSync(other, 'utf8')).findings
      .filter((x) => x.klass === 'LATENT' && x.name === 'esc')[0];
    ok(f && f.line === 146 && f.declLine === 149,
      'D4b the two line numbers quoted for cast-your-model are still its own',
      f ? `read ${f.line}, decl ${f.declLine}` : 'no LATENT read of esc found');
    const src = readFileSync(other, 'utf8').split('\n');
    ok(/fetch\(/.test(src[145] || ''), 'D4c line 146 of that layer is still the fetch');
    ok(/const\s+esc\s*=/.test(src[148] || ''), 'D4d line 149 of that layer is still the declaration');
  }
}

// ── D5. the false-negative control: the browser gate over the whole corpus ────────────
//
// The static census says zero. A checker that returns zero on everything also returns zero
// here, so the zero is only worth what its DISAGREEMENTS are worth: the browser gate was run
// over every published layer and must not have seen a script error on any page the analyser
// calls clean.
{
  const sweep = load('browser-sweep.json');
  if (ok(!!sweep, 'D5a the corpus-wide browser sweep is committed')) {
    const withErrors = sweep.results.filter((r) => r.errors.length);
    ok(withErrors.length === 0, 'D5b the browser saw no script error anywhere in the corpus',
      withErrors.map((r) => r.url + ': ' + r.errors[0]).slice(0, 3).join(' | '));
    ok(sweep.results.length >= 900, 'D5c the sweep covered the whole corpus, not a sample',
      `${sweep.results.length} pages`);
    const text = html.replace(/<script[\s\S]*?<\/script>/g, ' ').replace(/<[^>]+>/g, ' ');
    ok(text.includes(String(sweep.results.length)),
      'D5d the page count in the prose is the sweep\'s own', String(sweep.results.length));
  }
}

// ── E. the page passes the gate it is about ───────────────────────────────────────────
{
  const own = analyzeHtml(html).findings;
  const bad = own.filter((f) => ['CERTAIN', 'RACED', 'CONDITIONAL'].includes(f.klass));
  ok(bad.length === 0, 'E1 this page has no load-time dead-zone hazard of its own',
    bad.map((f) => `${f.klass} ${f.name}`).join(','));
}

// ── F. the history walk is coherent with the tree ─────────────────────────────────────
if (history) {
  const w = history.windows[0];
  ok(!!w && w.toCommit, 'F1 the one window is closed, not open at HEAD');
  const now = analyzeHtml(readFileSync(join(ROOT, 'public/strata/the-average-of-a-million-is-one/index.html'), 'utf8'));
  ok(now.findings.filter((f) => f.klass === 'CERTAIN').length === 0,
    'F2 the page that carried the window is clean in the working tree now');
}

// ── report ────────────────────────────────────────────────────────────────────────────
console.log(`\nthe-error-that-is-not-in-the-file — ${pass} passed, ${fails.length} failed`);
for (const f of fails) console.log(`  FAIL  ${f}`);
if (!fails.length) {
  console.log('  every displayed figure is the committed measurement, the analyser can still fail,');
  console.log('  and its verdicts match what the browsers did on every shape it commits to.');
}
process.exit(fails.length ? 1 : 0);
