#!/usr/bin/env node
/**
 * scan.mjs — which checks on this ground can be satisfied by their own printed output?
 *
 * Many layers print their verifier's transcript on the page ("A. 52 passed ..."),
 * and many verifiers then read the page and assert that it states a figure. If the
 * assertion searches the whole page, the transcript satisfies it: the prose can say
 * anything and the check stays green, because the check is reading its own answer.
 * On 2026-09-27 an outside claims pass found this in one layer by hand
 * (every-edge-but-one: four prose numbers changed, 52 passed, 0 failed). This asks
 * whether it is a case or a class, by experiment rather than by reading source.
 *
 * THE EXPERIMENT, per figure t that appears both in a page's prose and in the lines
 * of that page which are a verbatim copy of the verifier's own stdout:
 *
 *   P  change t in the prose only (the transcript keeps the true value)
 *   T  change t in the transcript only (the prose keeps the true value)
 *   A  change t in both
 *
 *               P       T       A      reading
 *             green   green   RED      SELF-READING: a check wants t somewhere on the
 *                                        page and either copy will do. The prose is
 *                                        unguarded for t while the transcript stands.
 *             RED       .      RED      the prose is checked for t (fine)
 *             green    RED     RED      the transcript is checked, the prose is not
 *             green   green   green     nothing reads t (the page's prose is not
 *                                        checked for it at all; C0 for this figure)
 *
 * Only the first row is the defect this looks for, and it is the only row that needs
 * all three runs to tell apart: a check that compares the printed transcript to a
 * fresh run (a legitimate staleness check) goes red on A as well, and T separates it.
 *
 * A change is +1 on the last digit (9 -> 0), whole-number boundaries only, and only
 * in text a reader sees: never inside a tag, a <script> or a <style>.
 *
 *   node research/self-reading-verifiers/scan.mjs --baseline          # run + trace every read/lift check
 *   node research/self-reading-verifiers/scan.mjs --probe             # the P/T/A experiment
 *   node research/self-reading-verifiers/scan.mjs --only <slug>       # one layer (either stage)
 *   node research/self-reading-verifiers/scan.mjs --probe --rev <commit> # the checks as they were then (a control)
 *   node research/self-reading-verifiers/scan.mjs --jobs 4 --timeout 180
 *
 * Every run happens in a scratch git worktree (--work, default a temp dir), never in
 * the checkout you are standing in, so a crash mid-mutation cannot leave a page
 * altered. Results: baseline.json, probe.json beside this file.
 */

import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { spawn, execFileSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';

const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, '../..');
const argv = process.argv.slice(2);
const arg = (f, d) => { const i = argv.indexOf(f); return i >= 0 ? argv[i + 1] : d; };
const JOBS = +arg('--jobs', 4);
const TIMEOUT_S = +arg('--timeout', 180);
const ONLY = arg('--only', null);
const SLOW_MS = +arg('--slow', 40) * 1000; // shadow: skip checks slower than this per run
const WORK = arg('--work', path.join(os.tmpdir(), 'self-reading-work'));
const HOOK = path.join(ROOT, 'research/verifier-independence/lib/hook.mjs');
const BASE_OUT = path.join(HERE, 'baseline.json');
const REV = arg('--rev', null); // control: probe the checks as they stood at an older commit
const REV_HASH = REV ? execFileSync('git', ['-C', ROOT, 'rev-parse', REV], { encoding: 'utf8' }).trim() : null;
const PROBE_OUT = path.join(HERE, REV ? `probe-at-${REV_HASH.slice(0, 8)}.json` : 'probe.json');

/* ---------------------------------------------------------------- worktree */

function ensureWorktree() {
  const head = execFileSync('git', ['-C', ROOT, 'rev-parse', 'HEAD'], { encoding: 'utf8' }).trim();
  if (!fs.existsSync(path.join(WORK, '.git'))) {
    execFileSync('git', ['-C', ROOT, 'worktree', 'add', '--detach', WORK, head], { stdio: 'ignore' });
  } else {
    execFileSync('git', ['-C', WORK, 'checkout', '-q', '--detach', '-f', head]);
    execFileSync('git', ['-C', WORK, 'clean', '-qfd', '-e', 'node_modules']);
  }
  const nm = path.join(WORK, 'node_modules');
  if (!fs.existsSync(nm) && fs.existsSync(path.join(ROOT, 'node_modules'))) fs.symlinkSync(path.join(ROOT, 'node_modules'), nm);
  return head;
}

/* -------------------------------------------------------------- population */

// Every file the corpus's two naming conventions call a verifier: research/<dir>/verify*.mjs
// (one level of nesting allowed) and root verify-*.mjs. Which of them read a page is not
// guessed from source: stage 1 runs each under the tracer and keeps the ones that did.
// (The verifier-independence census would have been the natural list, but it covered 693
// of 1,082 layers when this was written, so it is not used.)
function population() {
  const out = [];
  const add = rel => { if (/\.m?js$/.test(rel)) out.push({ code: rel }); };
  for (const f of fs.readdirSync(ROOT)) if (/^verify-.*\.mjs$/.test(f)) add(f);
  const walk = (dir, depth) => {
    for (const e of fs.readdirSync(path.join(ROOT, dir), { withFileTypes: true })) {
      const rel = path.join(dir, e.name);
      if (e.isDirectory() && depth < 2 && !/^(node_modules|\.)/.test(e.name)) walk(rel, depth + 1);
      else if (e.isFile() && /^verify.*\.mjs$/.test(e.name)) add(rel);
    }
  };
  walk('research', 0);
  return { checks: out.sort((a, b) => a.code.localeCompare(b.code)), domPairs: null };
}

/* ------------------------------------------------------------------- runs */

function run(code, { traceTo = null } = {}) {
  return new Promise(resolve => {
    const t0 = Date.now();
    const args = traceTo ? ['--import', HOOK, code] : [code];
    const env = { ...process.env, WI_QUIET: '1', NO_COLOR: '1', FORCE_COLOR: '0' };
    if (traceTo) env.WI_TRACE = traceTo;
    const child = spawn(process.execPath, args, { cwd: WORK, env, stdio: ['ignore', 'pipe', 'pipe'], detached: true });
    let out = '', err = '', timedOut = false;
    child.stdout.on('data', d => { if (out.length < 4e6) out += d; });
    child.stderr.on('data', d => { if (err.length < 2e5) err += d; });
    const timer = setTimeout(() => { timedOut = true; try { process.kill(-child.pid, 'SIGKILL'); } catch {} }, TIMEOUT_S * 1000);
    child.on('close', exitCode => { clearTimeout(timer); resolve({ exitCode, timedOut, ms: Date.now() - t0, out, err }); });
    child.on('error', e => { clearTimeout(timer); resolve({ exitCode: null, timedOut, ms: 0, out, err: String(e) }); });
  });
}

async function pool(items, fn) {
  const res = new Array(items.length); let i = 0;
  await Promise.all(Array.from({ length: Math.min(JOBS, items.length) }, async () => {
    while (i < items.length) { const k = i++; res[k] = await fn(items[k], k); }
  }));
  return res;
}

/* -------------------------------------------------- the page and its copy */

const ENT = { '&amp;': '&', '&lt;': '<', '&gt;': '>', '&quot;': '"', '&#39;': "'", '&#x27;': "'", '&nbsp;': ' ', '&minus;': '−', '&times;': '×' };
const decode = s => s.replace(/&(?:amp|lt|gt|quot|#39|#x27|nbsp|minus|times);/g, m => ENT[m]);
const stripAnsi = s => s.replace(/\x1b\[[0-9;]*[A-Za-z]/g, '');
const normLine = s => decode(stripAnsi(s)).replace(/<[^>]*>/g, '').replace(/\s+/g, ' ').trim();

/** Lines of stdout long enough, and specific enough, to be recognised when copied. */
function stdoutLines(out) {
  const set = new Set();
  for (const l of stripAnsi(out).split('\n')) {
    const n = normLine(l);
    if (n.length >= 12 && /\d/.test(n)) set.add(n);
  }
  return set;
}

/**
 * Split a page source into its physical lines, each tagged: `code` (inside a <script>
 * or <style>, never touched), `transcript` (its visible text, normalised, is a verbatim
 * line of the verifier's own stdout) or `prose` (everything else a reader sees).
 * Mutation only ever touches text between tags, so markup and attributes survive.
 */
function segments(src, outSet) {
  const lines = src.split('\n');
  let inCode = false;
  return lines.map(text => {
    const wasIn = inCode;
    const opens = (text.match(/<(script|style)\b/gi) || []).length, closes = (text.match(/<\/(script|style)>/gi) || []).length;
    if (opens > closes) inCode = true; else if (closes > opens) inCode = false;
    if (wasIn || opens) return { text, kind: 'code' };
    const vis = normLine(text);
    return { text, kind: vis && outSet.has(vis) ? 'transcript' : 'prose' };
  });
}

// A figure: at least two digits, or a digit with a separator, bounded as a whole number.
const FIG = /(?<![\d.,])\d{1,3}(?:,\d{3})+(?:\.\d+)?(?![\d])|(?<![\d.,])\d+\.\d+(?![\d])|(?<![\d.,])\d{2,}(?![\d])/g;
const figs = s => new Set((s.match(FIG) || []));
const bump = t => t.replace(/(\d)(?!.*\d)/, d => String((+d + 1) % 10));
function mutateIn(text, t) {
  const esc = t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  return text.replace(new RegExp(`(?<![\\d.,])${esc}(?![\\d]|[.,]\\d)`, 'g'), bump(t));
}
// Tags and character references are opaque: '&frac12;' is not the figure 12.
const textOnly = (line, f) => line.replace(/(<[^>]*>|&#?\w+;)|([^<&]+|&)/g, (m, tag, txt) => (tag ? tag : f(txt)));
function render(parts, ts, where) {
  return parts.map(p => (where.includes(p.kind) ? textOnly(p.text, x => ts.reduce((acc, t) => mutateIn(acc, t), x)) : p.text)).join('\n');
}

/**
 * Every place figure t is stated in visible text, in document order, with its kind
 * (prose or transcript) and a little context. The order is the index `renderOcc` uses.
 */
function occurrences(parts, t) {
  const esc = t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  const re = new RegExp(`(?<![\\d.,])${esc}(?![\\d]|[.,]\\d)`, 'g');
  const occ = [];
  parts.forEach((p, line) => {
    if (p.kind === 'code') return;
    const ctx = normLine(p.text).slice(0, 200);
    textOnly(p.text, txt => { txt.replace(re, () => { occ.push({ line: line + 1, kind: p.kind, ctx }); return ''; }); return txt; });
  });
  return occ;
}
/** Change only the occurrences of t whose index is in `which`. */
function renderOcc(parts, t, which) {
  const esc = t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  const re = new RegExp(`(?<![\\d.,])${esc}(?![\\d]|[.,]\\d)`, 'g');
  let k = 0;
  return parts.map(p => (p.kind === 'code' ? p.text : textOnly(p.text, txt => txt.replace(re, m => (which.has(k++) ? bump(m) : m))))).join('\n');
}

/* --------------------------------------------------------------- stage 1 */

async function baseline() {
  const head = ensureWorktree();
  const { checks, domPairs } = population();
  const todo = ONLY ? checks.filter(c => c.code.includes(ONLY)) : checks;
  const tdir = fs.mkdtempSync(path.join(os.tmpdir(), 'srv-trace-'));
  console.log(`baseline: ${todo.length} verifier files at ${head.slice(0, 8)}`);
  // checkpoint: a long sweep that dies at file 600 should not have to start again
  const CKPT = path.join(HERE, '.baseline-partial.jsonl');
  const done = new Map();
  if (argv.includes('--resume') && fs.existsSync(CKPT)) for (const l of fs.readFileSync(CKPT, 'utf8').split('\n')) if (l) { const r = JSON.parse(l); done.set(r.code, r); }
  if (!argv.includes('--resume')) fs.rmSync(CKPT, { force: true });
  if (done.size) console.log(`resuming: ${done.size} already run`);
  const rows = await pool(todo, async (c, k) => {
    if (done.has(c.code)) return done.get(c.code);
    const tp = path.join(tdir, k + '.json');
    const r = await run(c.code, { traceTo: tp });
    let reads = [];
    try { reads = JSON.parse(fs.readFileSync(tp, 'utf8')).reads.map(x => (typeof x === 'string' ? x : x.path)).filter(Boolean); } catch {}
    const pages = [...new Set(reads.map(p => path.relative(WORK, p)))]
      .filter(p => /^(public\/strata\/[^/]+\/[^/]+\.html|src\/content\/strata\/[^/]+\.mdx?)$/.test(p) && fs.existsSync(path.join(WORK, p)));
    const outSet = stdoutLines(r.out);
    const withCopy = [];
    for (const p of pages) {
      const src = fs.readFileSync(path.join(WORK, p), 'utf8');
      const parts = segments(src, outSet);
      const tr = parts.filter(x => x.kind === 'transcript');
      if (!tr.length) continue;
      const vis = xs => xs.map(x => textOnly(x.text, y => y).replace(/<[^>]*>/g, ' ')).join('\n');
      const inTr = figs(vis(tr));
      const inPr = figs(vis(parts.filter(x => x.kind === 'prose')));
      const both = [...inTr].filter(t => inPr.has(t));
      withCopy.push({ page: p, transcriptLines: tr.length, figuresBoth: both });
    }
    process.stdout.write(`  ${r.exitCode === 0 ? '·' : 'x'} ${c.code} ${r.ms}ms pages=${pages.length} copies=${withCopy.length}\n`);
    const row = { ...c, exitCode: r.exitCode, timedOut: r.timedOut, ms: r.ms, pages, withCopy, tail: r.exitCode === 0 ? '' : (r.out + r.err).slice(-600) };
    fs.appendFileSync(CKPT, JSON.stringify(row) + '\n');
    return row;
  });
  execFileSync('git', ['-C', WORK, 'checkout', '-q', '-f', 'HEAD']);
  const prev = !ONLY || !fs.existsSync(BASE_OUT) ? { rows: [] } : JSON.parse(fs.readFileSync(BASE_OUT, 'utf8'));
  const merged = ONLY ? [...prev.rows.filter(r => !rows.some(x => x.code === r.code)), ...rows] : rows;
  fs.rmSync(CKPT, { force: true });
  fs.writeFileSync(BASE_OUT, JSON.stringify({ head, at: new Date().toISOString(), domPairs, rows: merged.sort((a, b) => a.code.localeCompare(b.code)) }, null, 1) + '\n');
  const green = rows.filter(r => r.exitCode === 0), copies = green.filter(r => r.withCopy.length);
  console.log(`\n${green.length}/${rows.length} green at baseline; ${copies.length} read a page that prints a verbatim copy of their own output`);
}

/* --------------------------------------------------------------- stage 2 */

async function probe() {
  const base = JSON.parse(fs.readFileSync(BASE_OUT, 'utf8'));
  const head = ensureWorktree();
  if (head !== base.head) console.log(`note: baseline was taken at ${base.head.slice(0, 8)}, probing at ${head.slice(0, 8)}`);
  let targets = base.rows.filter(r => r.exitCode === 0 && r.withCopy.some(w => w.figuresBoth.length));
  if (ONLY) targets = targets.filter(r => r.code.includes(ONLY) || r.pages.some(p => p.includes(ONLY)));
  // Pages are mutated in the shared worktree, so two checks reading one page must not
  // run at once. Group by page; groups run in parallel, a group's runs in series.
  const jobs = [];
  for (const r of targets) for (const w of r.withCopy) if (w.figuresBoth.length) jobs.push({ code: r.code, ...w });
  const groups = new Map();
  for (const j of jobs) { if (!groups.has(j.page)) groups.set(j.page, []); groups.get(j.page).push(j); }
  const pagesReadBy = new Map();
  for (const r of base.rows) for (const p of r.pages) { if (!pagesReadBy.has(p)) pagesReadBy.set(p, new Set()); pagesReadBy.get(p).add(r.code); }
  if (REV) for (const c of new Set(jobs.map(j => j.code))) execFileSync('git', ['-C', WORK, 'checkout', REV_HASH, '--', c]);
  console.log(`probe: ${jobs.length} (check, page) pairs, ${jobs.reduce((s, j) => s + j.figuresBoth.length, 0)} figures, in ${groups.size} page groups`);

  const results = [];
  await pool([...groups.values()], async group => {
    for (const j of group) {
      const abs = path.join(WORK, j.page);
      const orig = fs.readFileSync(abs, 'utf8');
      const again = await run(j.code); // fresh stdout, so the transcript is recognised against this run
      const parts = segments(orig, stdoutLines(again.out));
      // the figures in both places, found again against this run (the page may have changed since the baseline)
      const visOf = kind => parts.filter(x => x.kind === kind).map(x => textOnly(x.text, y => y).replace(/<[^>]*>/g, ' ')).join('\n');
      const inPr = figs(visOf('prose'));
      j.figuresBoth = [...figs(visOf('transcript'))].filter(t => inPr.has(t));
      const figures = [];
      try {
        // a cheap screen first: all figures at once, everywhere. If that stays green nothing
        // reads any of them and the per-figure runs would all be green-green-green.
        fs.writeFileSync(abs, render(parts, j.figuresBoth, ['prose', 'transcript']));
        const screen = await run(j.code);
        if (screen.exitCode === 0) {
          for (const t of j.figuresBoth) figures.push({ t, P: 0, T: 0, A: 0, reading: 'unread' });
        } else {
          for (const t of j.figuresBoth) {
            const res = {};
            for (const [key, where] of [['A', ['prose', 'transcript']], ['P', ['prose']], ['T', ['transcript']]]) {
              fs.writeFileSync(abs, render(parts, [t], where));
              const x = await run(j.code);
              res[key] = x.exitCode === 0 ? 0 : 1;
              if (key === 'A' && !res.A) { res.P = 0; res.T = 0; break; }
            }
            const reading = !res.A ? 'unread' : res.P ? 'prose-checked' : res.T ? 'transcript-only' : 'SELF-READING';
            figures.push({ t, ...res, reading });
          }
        }
      } finally { fs.writeFileSync(abs, orig); }
      const self = figures.filter(f => f.reading === 'SELF-READING').map(f => f.t);
      process.stdout.write(`  ${self.length ? '!' : '·'} ${j.code} × ${j.page}: ${figures.length} figures, ${self.length} self-read${self.length ? ' [' + self.join(' ') + ']' : ''}\n`);
      results.push({ code: j.code, page: j.page, transcriptLines: j.transcriptLines, figures });
    }
  });
  execFileSync('git', ['-C', WORK, 'checkout', '-q', '-f', 'HEAD']);
  const prev = !ONLY || !fs.existsSync(PROBE_OUT) ? { results: [] } : JSON.parse(fs.readFileSync(PROBE_OUT, 'utf8'));
  const merged = ONLY ? [...prev.results.filter(r => !results.some(x => x.code === r.code && x.page === r.page)), ...results] : results;
  merged.sort((a, b) => (a.code + a.page).localeCompare(b.code + b.page));
  fs.writeFileSync(PROBE_OUT, JSON.stringify({ head, checksAt: REV_HASH || head, at: new Date().toISOString(), results: merged }, null, 1) + '\n');
  const bad = merged.filter(r => r.figures.some(f => f.reading === 'SELF-READING'));
  console.log(`\n${bad.length} of ${merged.length} (check, page) pairs have at least one figure a check accepts from its own transcript`);
}

/* --------------------------------------------------------------- stage 3 */

/**
 * The general form. A transcript is one kind of second copy; a figure stated in the dek,
 * again in the body and again in a table is three copies, and a check that asks only
 * whether the page contains it is satisfied by any one. So, for every page a verifier
 * reads, and every figure the page states more than once:
 *
 *   A   change every copy                  -> red means some check reads this figure
 *   Oi  change copy i only (for each i)    -> green, when A was red, means copy i is
 *                                             UNGUARDED: it could say anything
 *   Ni  change every copy but i            -> for an unguarded copy, splits the two reasons:
 *                                             green: the check accepts copy i too, any one
 *                                               copy will do (SHADOWED, the every-edge shape)
 *                                             red: the check reads a particular other copy
 *                                               and never looks at i (OUT OF ITS SIGHT)
 *
 * Figures stated once cannot be shadowed and are not tested here. Figures no check reads
 * (A green) are counted as unread, which is a different fact and not a defect of the check.
 */
async function shadow() {
  // --code <file> --page <page> [--out <name>] sweeps one named pair without touching the baseline
  // (used to sweep the page's own check, which is not in the corpus the baseline ran)
  const CODE = arg('--code', null), PAGE1 = arg('--page', null);
  const base = CODE ? { rows: [{ code: CODE, exitCode: 0, ms: 0, pages: [PAGE1] }] } : JSON.parse(fs.readFileSync(BASE_OUT, 'utf8'));
  const head = ensureWorktree();
  const OUT = path.join(HERE, arg('--out', 'shadow.json'));
  // A verifier that reads more than WIDE pages is a census or a portal reading the corpus,
  // not a layer's check reading its own page; those are named and left out.
  const WIDE = 7;
  let targets = base.rows.filter(r => r.exitCode === 0 && r.pages.length && r.pages.length <= WIDE);
  const wide = base.rows.filter(r => r.exitCode === 0 && r.pages.length > WIDE).map(r => `${r.code} (${r.pages.length} pages)`);
  if (!ONLY && wide.length) console.log(`left out, reading more than ${WIDE} pages: ${wide.join(', ')}`);
  if (ONLY) targets = targets.filter(r => r.code.includes(ONLY) || r.pages.some(p => p.includes(ONLY)));
  const jobs = [];
  const slow = targets.filter(r => r.ms > SLOW_MS);
  if (slow.length) console.log(`left out, slower than ${SLOW_MS / 1000} s a run at baseline: ${slow.length} checks (${slow.map(r => r.code.split('/').pop()).join(', ')})`);
  targets = targets.filter(r => r.ms <= SLOW_MS);
  for (const r of targets) for (const page of r.pages) jobs.push({ code: r.code, page });
  const groups = new Map();
  for (const j of jobs) { if (!groups.has(j.page)) groups.set(j.page, []); groups.get(j.page).push(j); }
  console.log(`shadow: ${jobs.length} (check, page) pairs in ${groups.size} page groups`);
  const CK = path.join(HERE, CODE ? '.shadow-self-partial.jsonl' : '.shadow-partial.jsonl');
  const doneS = new Map();
  if (argv.includes('--resume') && fs.existsSync(CK)) for (const l of fs.readFileSync(CK, 'utf8').split('\n')) if (l) { const r = JSON.parse(l); doneS.set(r.code + ' ' + r.page, r); }
  if (!argv.includes('--resume')) fs.rmSync(CK, { force: true });
  const results = [...doneS.values()];
  await pool([...groups.values()], async group => {
    for (const j of group) {
      if (doneS.has(j.code + ' ' + j.page)) continue;
      const abs = path.join(WORK, j.page);
      const orig = fs.readFileSync(abs, 'utf8');
      const fresh = await run(j.code);
      if (fresh.exitCode !== 0) { results.push({ ...j, skipped: 'not green on a fresh run' }); continue; }
      if (fresh.ms > SLOW_MS) { results.push({ ...j, skipped: `slow: ${Math.round(fresh.ms / 1000)} s a run` }); process.stdout.write(`  - ${j.code}: skipped, ${Math.round(fresh.ms / 1000)} s a run\n`); continue; }
      const parts = segments(orig, stdoutLines(fresh.out));
      const vis = parts.filter(p => p.kind !== 'code').map(p => textOnly(p.text, y => y).replace(/<[^>]*>/g, ' ')).join('\n');
      const counts = new Map();
      for (const m of vis.match(FIG) || []) counts.set(m, (counts.get(m) || 0) + 1);
      const multi = [...counts].filter(([, n]) => n >= 2).map(([t]) => t);
      const figures = [];
      let screenRed = false, runs = 1;
      try {
        if (multi.length) {
          fs.writeFileSync(abs, render(parts, multi, ['prose', 'transcript']));
          screenRed = (await run(j.code)).exitCode !== 0; runs++;
        }
        // Which repeated figures does any check read? Group testing: change a whole group,
        // and split only the groups that turn the check red.
        const readSet = [];
        const split = async ts => {
          if (!ts.length) return;
          fs.writeFileSync(abs, render(parts, ts, ['prose', 'transcript']));
          const red = (await run(j.code)).exitCode !== 0; runs++;
          if (!red) { for (const t of ts) figures.push({ t, n: occurrences(parts, t).length, read: false }); return; }
          if (ts.length === 1) { readSet.push(ts[0]); return; }
          const h = ts.length >> 1; await split(ts.slice(0, h)); await split(ts.slice(h));
        };
        if (screenRed) {
          const h = multi.length >> 1;
          if (multi.length === 1) readSet.push(multi[0]); else { await split(multi.slice(0, h)); await split(multi.slice(h)); }
        }
        for (const t of readSet) {
          const occ = occurrences(parts, t);
          const shadowed = [];
          for (let i = 0; i < occ.length; i++) {
            fs.writeFileSync(abs, renderOcc(parts, t, new Set([i])));
            const red = (await run(j.code)).exitCode !== 0; runs++;
            occ[i].guarded = red;
            if (red) continue;
            // Copy i changed and nothing noticed. Is that because the check would accept copy i
            // (any copy will do: change all the OTHERS and it stays green), or because it only
            // ever reads somewhere else (change the others and it goes red)?
            fs.writeFileSync(abs, renderOcc(parts, t, new Set(occ.map((_, k) => k).filter(k => k !== i))));
            occ[i].acceptsThisCopy = (await run(j.code)).exitCode === 0; runs++;
            shadowed.push(i);
          }
          figures.push({ t, n: occ.length, read: true, occ, shadowed: shadowed.length });
        }
      } finally { fs.writeFileSync(abs, orig); }
      const read = figures.filter(f => f.read), sh = read.filter(f => f.shadowed);
      process.stdout.write(`  ${sh.length ? '!' : '·'} ${j.code} × ${j.page}: ${multi.length} repeated figures, ${read.length} read, ${sh.length} with a shadowed copy (${runs} runs)\n`);
      const row = { ...j, repeated: multi.length, screenRed, runs, figures };
      fs.appendFileSync(CK, JSON.stringify(row) + '\n');
      results.push(row);
    }
  });
  execFileSync('git', ['-C', WORK, 'checkout', '-q', '-f', 'HEAD']);
  const prev = !ONLY || !fs.existsSync(OUT) ? { results: [] } : JSON.parse(fs.readFileSync(OUT, 'utf8'));
  const merged = ONLY ? [...prev.results.filter(r => !results.some(x => x.code === r.code && x.page === r.page)), ...results] : results;
  merged.sort((a, b) => (a.code + a.page).localeCompare(b.code + b.page));
  fs.writeFileSync(OUT, JSON.stringify({ head, at: new Date().toISOString(), slowMs: SLOW_MS, results: merged }, null, 1) + '\n');
  fs.rmSync(CK, { force: true });
}

if (argv.includes('--baseline')) await baseline();
else if (argv.includes('--shadow')) await shadow();
else if (argv.includes('--probe')) await probe();
else { console.log('usage: --baseline | --probe  [--only <slug>] [--jobs n] [--timeout s]'); process.exit(2); }
