// verify-the-map-no-one-drew.mjs — drive the immersive constellation page in a real
// headless browser: no JS errors; the specimen + prose numbers render; the graph canvas
// draws; the three live nulls run and reproduce the artifact's findings (in-degree Gini
// above its temporal null; clustering far above the config null; seam modularity above its
// null); community toggle works; no horizontal overflow at phone / tablet / desktop.
//   npm run build && node verify-the-map-no-one-drew.mjs
//
// WHAT THIS FILE ASSERTS, AND WHAT IT ONLY REPORTS (restated 2026-08-14).
// It used to open with `extract.mjs --json && cat page.json`: it REGENERATED the committed
// artifact from the live corpus and then asserted that the shipped page's figures equalled
// the number it had just computed. Two things were wrong with that, and they are the same
// mistake twice.
//
//   1. It could only pass in the instant between regenerating the data and rebuilding the
//      page. The corpus grows every night; the page is a dated snapshot and says so
//      ("last re-inlined on 2026-08-01", 679 nodes). So the check went red at 785 layers
//      while nothing was broken and nothing was lying. A check that fails on weather
//      teaches the reader to ignore it, which is worse than not checking.
//   2. Regenerating overwrote `research/lineage-constellation/page.json` as a SIDE EFFECT
//      of verification. That destroys the very artifact the page is supposed to be checked
//      against, and it leaves the working tree dirty, which coordination/publish.sh refuses
//      to start on. A verifier that edits the repo is a bug in its own right.
//
// So the checks are split into two classes, and only the first can fail:
//
//   HARD (exit 1 if any of these break): the reproducibility claim, which can actually
//   hold: the shipped page inlines EXACTLY the committed artifact; that artifact is
//   internally consistent; and every headline figure on it recomputes, here, from the
//   committed graph it ships alongside. If the page and its artifact disagree, or the
//   artifact's numbers cannot be re-derived from its own data, that is a real defect and
//   this goes red honestly.
//
//   DRIFT (never fails): the artifact is regenerated from today's live corpus, read-only
//   (`extract.mjs --stdout`, which writes nothing), and every headline figure is printed
//   committed-vs-live with the delta. A growing gap is information: it says the page is due
//   a re-inline, and by how much. It is not a failure, because a dated snapshot that is
//   honestly dated is not wrong.
//
// One consequence to state plainly: if the extractor itself broke, the drift report would
// say so in words but this verifier would still exit 0. That is deliberate (the drift
// section must not be able to fail), and it is covered elsewhere: the extractor's own
// `--verify` runs its 33 checks against the live corpus, and the sweep runs it.
//
// Tolerances: the artifact stores its figures rounded (mostly toFixed(4)), so a
// recomputation is compared to it within that rounding, never within "whatever today's
// number happens to be".
//
// Resolve playwright portably, the same way scripts/headless-check.mjs does: the repo's
// own node_modules first, then the globally installed copy. A bare import fails with
// ERR_MODULE_NOT_FOUND on a fresh ephemeral VM, where playwright is installed globally,
// which is how this verifier came to be un-runnable there (found 2026-08-01).
let pw;
try { pw = (await import('playwright')).default; }
catch { pw = (await import('/opt/node22/lib/node_modules/playwright/index.js')).default; }
const { chromium } = pw;
import { createServer } from 'http';
import { readFileSync } from 'fs';
import { extname, join } from 'path';
import { execFileSync } from 'child_process';
import { fileURLToPath as __f2p } from 'url';
import { dirname as __dn } from 'path';
const AW_REPO_ROOT = __dn(__f2p(import.meta.url));

const root = AW_REPO_ROOT + '/dist/';
const types = { '.html':'text/html','.css':'text/css','.js':'text/javascript','.woff2':'font/woff2','.png':'image/png','.svg':'image/svg+xml','.ico':'image/x-icon','.json':'application/json' };
const server = createServer((req,res)=>{ let p=decodeURIComponent(req.url.split('?')[0]); if(p.endsWith('/'))p+='index.html'; const fp=join(root,p);
  try{ const buf=readFileSync(fp); res.writeHead(200,{'content-type':types[extname(fp)]||'application/octet-stream'}); res.end(buf); }
  catch{ res.writeHead(404); res.end('404'); } });
await new Promise(r=>server.listen(8151,r));
const URL_ = 'http://localhost:8151/strata/the-map-no-one-drew/';

// THE COMMITTED ARTIFACT. Read, never written. This is the dated snapshot the shipped
// page renders, so it is the only thing the page can honestly be measured against.
const ART_REL = 'research/lineage-constellation/page.json';
const ART_PATH = join(AW_REPO_ROOT, ART_REL);
const D = JSON.parse(readFileSync(ART_PATH, 'utf8'));

let fails = 0, total = 0;
const ok=(n,c,x='')=>{ total++; if(!c)fails++; console.log(`${c?'  ok':'FAIL'}  ${n}${x?'   '+x:''}`); };

// ─────────────────────────────────────────────────────────────────────────────
// HARD CLASS A: the committed artifact, checked against itself and against the
// page that ships it. No corpus is read here, so none of this moves when the
// corpus grows: it either holds forever or something is genuinely broken.
// ─────────────────────────────────────────────────────────────────────────────
console.log('== A. the shipped page against its COMMITTED artifact (hard) ==');

// Key order is irrelevant to whether two JSON payloads are the same payload.
const canon = (v) => {
  if (Array.isArray(v)) return '[' + v.map(canon).join(',') + ']';
  if (v && typeof v === 'object') return '{' + Object.keys(v).sort().map((k) => JSON.stringify(k) + ':' + canon(v[k])).join(',') + '}';
  return JSON.stringify(v);
};
const near = (a, b, tol) => Number.isFinite(a) && Number.isFinite(b) && Math.abs(a - b) <= tol;

// A1. the page's inlined data IS the committed artifact (the served copy, not the source)
{
  const TAG = '<script id="data" type="application/json">';
  const served = join(root, 'strata/the-map-no-one-drew/index.html');
  let html = '', i = -1, j = -1;
  let same = false, why = 'no #data block in the served page';
  try { html = readFileSync(served, 'utf8'); i = html.indexOf(TAG); j = i < 0 ? -1 : html.indexOf('</script>', i + TAG.length); }
  catch { why = `${served} missing: run npm run build first`; }
  if (j > 0) {
    try { same = canon(JSON.parse(html.slice(i + TAG.length, j))) === canon(D); why = same ? '' : `served page inlines a DIFFERENT payload than ${ART_REL}`; }
    catch (e) { why = 'inlined block is not JSON: ' + e.message; }
  }
  ok(`[artifact] served page inlines ${ART_REL} verbatim`, same, why);
}

const G = D.graph;
const N = G.nodes.length;

// A2. the graph is well formed: ids in order, ranks a permutation, edges in range,
//     undirected edges unique and normalised, no self-loops
{
  const idsOk = G.nodes.every((n, i) => n.id === i);
  const ranks = G.nodes.map((n) => n.rank).sort((a, b) => a - b);
  const rankOk = ranks.every((r, i) => r === i);
  const inRange = ([a, b]) => Number.isInteger(a) && Number.isInteger(b) && a >= 0 && b >= 0 && a < N && b < N;
  const undOk = G.edges.every((e) => inRange(e) && e[0] < e[1]);
  const undUniq = new Set(G.edges.map(([a, b]) => a * N + b)).size === G.edges.length;
  const dirOk = G.dirEdges.every((e) => inRange(e) && e[0] !== e[1]);
  ok('[artifact] graph well formed (ids, ranks, edge endpoints, no self-loops)',
    idsOk && rankOk && undOk && undUniq && dirOk,
    `${N} nodes, ${G.edges.length} undirected, ${G.dirEdges.length} directed`);
}

// A3. the headline counts are the graph's own counts
ok('[artifact] node and edge counts match the graph it ships',
  D.nodes === N && D.edgesUndirected === G.edges.length && D.edgesDirected === G.dirEdges.length,
  `${D.nodes}/${N} nodes, ${D.edgesUndirected}/${G.edges.length} und, ${D.edgesDirected}/${G.dirEdges.length} dir`);
ok('[artifact] mean out-degree and density recompute',
  near(D.meanOutDeg, G.dirEdges.length / N, 5e-4) && near(D.density, (2 * G.edges.length) / (N * (N - 1)), 5e-6),
  `meanOut ${D.meanOutDeg}, density ${D.density}`);

// A4. per-node degrees are the degrees its own edge list implies
const inDeg = new Array(N).fill(0), outDeg = new Array(N).fill(0);
for (const [s, d] of G.dirEdges) { outDeg[s]++; inDeg[d]++; }
ok('[artifact] per-node in/out degrees recompute from the directed edge list',
  G.nodes.every((n, i) => n.inDeg === inDeg[i] && n.outDeg === outDeg[i]) &&
  inDeg.reduce((a, b) => a + b, 0) === G.dirEdges.length &&
  outDeg.reduce((a, b) => a + b, 0) === G.dirEdges.length);
ok('[artifact] degree extrema recompute',
  D.degree.maxIn === Math.max(...inDeg) && D.degree.maxOut === Math.max(...outDeg),
  `maxIn ${D.degree.maxIn}, maxOut ${D.degree.maxOut}`);

// A5. the inequality figures (the page's first finding) recompute
function gini(arr) {
  const a = arr.slice().sort((x, y) => x - y), n = a.length;
  const sum = a.reduce((s, x) => s + x, 0);
  if (sum === 0) return 0;
  let cum = 0;
  for (let i = 0; i < n; i++) cum += (i + 1) * a[i];
  return (2 * cum) / (n * sum) - (n + 1) / n;
}
ok('[artifact] in/out-degree Gini recompute from the degrees',
  near(D.degree.inGini, gini(inDeg), 1e-4) && near(D.degree.outGini, gini(outDeg), 1e-4),
  `inGini ${D.degree.inGini} vs ${gini(inDeg).toFixed(4)}`);
ok('[artifact] prefAttach observed Gini is the same number as degree.inGini',
  D.prefAttach.inGini_obs === D.degree.inGini, `${D.prefAttach.inGini_obs} vs ${D.degree.inGini}`);

// A6. the time split (links point to the past) recomputes from the stored ranks
{
  const rank = new Array(N);
  for (const n of G.nodes) rank[n.id] = n.rank;
  let toPast = 0, toFuture = 0, toSame = 0;
  for (const [s, d] of G.dirEdges) { if (rank[d] < rank[s]) toPast++; else if (rank[d] > rank[s]) toFuture++; else toSame++; }
  ok('[artifact] edge time-direction split recomputes from the ranks',
    D.edgeTime.toPast === toPast && D.edgeTime.toFuture === toFuture && D.edgeTime.toSame === toSame &&
    near(D.edgeTime.toPastFrac, toPast / G.dirEdges.length, 1e-4),
    `${toPast} past / ${toFuture} future / ${toSame} same`);
}

// undirected adjacency, used by everything below
const adj = Array.from({ length: N }, () => new Set());
for (const [a, b] of G.edges) { adj[a].add(b); adj[b].add(a); }

// A7. connectivity
{
  const comp = new Array(N).fill(-1);
  let c = 0;
  for (let i = 0; i < N; i++) {
    if (comp[i] !== -1) continue;
    const st = [i]; comp[i] = c;
    while (st.length) { const x = st.pop(); for (const y of adj[x]) if (comp[y] === -1) { comp[y] = c; st.push(y); } }
    c++;
  }
  const sizes = {};
  for (const v of comp) sizes[v] = (sizes[v] || 0) + 1;
  const giantId = +Object.entries(sizes).sort((a, b) => b[1] - a[1])[0][0];
  const giant = sizes[giantId];
  const isolated = adj.filter((s) => s.size === 0).length;
  ok('[artifact] components, giant component and isolates recompute',
    D.components === c && D.giantSize === giant && D.isolated === isolated && near(D.giantFrac, giant / N, 1e-4),
    `${c} components, giant ${giant}/${N}, isolated ${isolated}`);
  var _comp = comp, _giantId = giantId; // reused by A9
}

// A8. clustering (the small-world numerator)
{
  let tri = 0, trp = 0;
  for (let v = 0; v < N; v++) {
    const nb = [...adj[v]], k = nb.length;
    trp += (k * (k - 1)) / 2;
    for (let i = 0; i < k; i++) for (let j = i + 1; j < k; j++) if (adj[nb[i]].has(nb[j])) tri++;
  }
  const C = trp === 0 ? 0 : tri / trp;
  ok('[artifact] clustering C recomputes from the graph', near(D.smallWorld.C_obs, C, 1e-4),
    `${D.smallWorld.C_obs} vs ${C.toFixed(4)}`);
}

// A9. mean shortest path and diameter over the giant component (the denominator)
{
  const members = [];
  for (let i = 0; i < N; i++) if (_comp[i] === _giantId) members.push(i);
  let sum = 0, pairs = 0, ecc = 0;
  for (const s of members) {
    const dist = new Array(N).fill(-1);
    dist[s] = 0; const q = [s]; let head = 0;
    while (head < q.length) { const x = q[head++]; for (const y of adj[x]) if (dist[y] === -1) { dist[y] = dist[x] + 1; q.push(y); } }
    for (const t of members) if (t !== s && dist[t] > 0) { sum += dist[t]; pairs++; if (dist[t] > ecc) ecc = dist[t]; }
  }
  const L = pairs ? sum / pairs : 0;
  ok('[artifact] mean path L and diameter recompute over the giant component',
    near(D.smallWorld.L_obs, L, 1e-4) && D.smallWorld.diameter === ecc,
    `L ${D.smallWorld.L_obs} vs ${L.toFixed(4)}, diameter ${ecc}`);
}

// A10. sigma is the ratio the page prints it as. Tolerance is set by the artifact's own
//      4-decimal rounding of C_null (~0.02 relative on a null of 0.023), not by taste.
{
  const sw = D.smallWorld;
  const sigma = (sw.C_obs / sw.C_null) / (sw.L_obs / sw.L_null);
  ok('[artifact] small-world sigma is (C/C_null)/(L/L_null)', near(sw.sigma, sigma, 0.02),
    `stored ${sw.sigma} vs recomputed ${sigma.toFixed(3)}`);
}

// A11/A12. the seam finding: modularity of the human seam partition, and the seam census
{
  const seam = G.nodes.map((n) => n.seam);
  const m = G.edges.length;
  const byLabel = new Map();
  for (let i = 0; i < N; i++) if (!byLabel.has(seam[i])) byLabel.set(seam[i], { e: 0, degsum: 0 });
  for (let i = 0; i < N; i++) {
    byLabel.get(seam[i]).degsum += adj[i].size;
    for (const j of adj[i]) { if (j <= i) continue; if (seam[i] === seam[j]) byLabel.get(seam[i]).e += 1; }
  }
  let Q = 0;
  for (const { e, degsum } of byLabel.values()) Q += e / m - (degsum / (2 * m)) ** 2;
  ok('[artifact] seam modularity Q recomputes from the graph and the seam labels',
    near(D.modularity.Q_seam, Q, 1e-4), `${D.modularity.Q_seam} vs ${Q.toFixed(4)}`);

  const counts = {};
  for (const s of seam) counts[s] = (counts[s] || 0) + 1;
  const stored = D.modularity.seamCounts;
  const sameCensus = Object.keys(counts).length === Object.keys(stored).length &&
    Object.entries(counts).every(([k, v]) => stored[k] === v) &&
    D.modularity.seams === Object.keys(counts).length &&
    Object.values(counts).reduce((a, b) => a + b, 0) === N;
  ok('[artifact] seam census matches the nodes it counts', sameCensus,
    `${Object.keys(counts).length} seams over ${N} nodes`);
}

// A13. the hub table is the true top of the in-degree ranking
{
  const ranked = G.nodes.map((n, i) => ({ slug: n.slug, inDeg: inDeg[i] })).sort((a, b) => b.inDeg - a.inDeg);
  const agree = D.hubsTop.every((h, i) => h.inDeg === ranked[i].inDeg) &&
    D.hubsTop[0].slug === ranked[0].slug &&
    D.hubsTop.every((h) => h.inDeg === inDeg[G.nodes.findIndex((n) => n.slug === h.slug)]);
  ok('[artifact] hubsTop is the top of the in-degree ranking, with its own numbers', agree,
    `top ${D.hubsTop[0].slug} (in ${D.hubsTop[0].inDeg})`);
}

// A14/A15. the temporal series is a series of prefixes of THIS graph, and the summary
//          the page quotes is a summary of THAT series
{
  const T = D.temporal, s = T.series, sN = s[s.length - 1];
  ok('[artifact] temporal snapshots are ascending prefixes ending on the whole graph',
    T.snaps.length === s.length && T.snaps.every((r, i) => s[i].r === r && (i === 0 || r > T.snaps[i - 1])) &&
    sN.r === N && sN.m === D.edgesUndirected && sN.giant === D.giantSize &&
    s.every((x, i) => i === 0 || x.m >= s[i - 1].m),
    `${s.length} snapshots, ${s[0].r} → ${sN.r}`);
  ok('[artifact] temporal summary matches its own series',
    near(T.summary.prefAttach_min_z, Math.min(...s.map((x) => x.inGz)), 1e-9) &&
    T.summary.sigma_first === s[0].sigma && T.summary.sigma_last === sN.sigma &&
    T.summary.Qz_first === s[0].Qz && T.summary.Qz_last === sN.Qz &&
    T.summary.seam_first_z2 === ((s.find((x) => x.Qz >= 2) || {}).r ?? null) &&
    T.summary.prefAttach_first_z2 === ((s.find((x) => x.inGz >= 2) || {}).r ?? null),
    `min z_in ${T.summary.prefAttach_min_z}, sigma ${T.summary.sigma_first}→${T.summary.sigma_last}`);
}

// ─────────────────────────────────────────────────────────────────────────────
// HARD CLASS B: the page itself, in a browser, against that same artifact.
// ─────────────────────────────────────────────────────────────────────────────
console.log('\n== B. the page in a browser, against the same artifact (hard) ==');

const browser = await chromium.launch();
for (const [label, w, h] of [['phone',390,844],['tablet',768,1024],['desktop',1280,900]]) {
  const ctx = await browser.newContext({ viewport:{width:w,height:h} });
  const page = await ctx.newPage();
  const errs=[]; page.on('pageerror',e=>errs.push(String(e))); page.on('console',m=>{ if(m.type()==='error') errs.push(m.text()); });
  await page.goto(URL_, { waitUntil:'networkidle' });

  ok(`[${label}] no JS errors`, errs.length===0, errs.slice(0,2).join(' | '));

  // specimen numbers
  const spn = await page.$eval('#sp-n', e=>e.textContent.trim());
  ok(`[${label}] specimen node count = ${D.nodes}`, spn===String(D.nodes), `got ${spn}`);

  // legend = number of distinct seams present
  const seamsUsed = Object.keys(D.modularity.seamCounts).length;
  const legend = await page.$$eval('#legend > span', e=>e.length);
  ok(`[${label}] legend has ${seamsUsed} seams`, legend===seamsUsed, `got ${legend}`);

  // hubs table 10 rows; top hub matches
  const rows = await page.$$eval('#hubs tr', e=>e.length);
  ok(`[${label}] hubs table 10 rows`, rows===10, `got ${rows}`);
  const topHub = await page.$eval('#hubs tr td:nth-child(2)', e=>e.textContent.trim());
  ok(`[${label}] top hub = ${D.hubsTop[0].slug}`, topHub===D.hubsTop[0].slug, `got ${topHub}`);

  // graph canvas drew something (non-empty pixels)
  const drew = await page.evaluate(()=>{ const c=document.getElementById('map'); const x=c.getContext('2d'); const d=x.getImageData(0,0,c.width,c.height).data; let n=0; for(let i=3;i<d.length;i+=4) if(d[i]>0) n++; return n; });
  ok(`[${label}] constellation canvas has drawn pixels`, drew>500, `lit=${drew}`);

  if (label==='desktop') {
    // run the three nulls and read the verdicts
    await page.click('#pa-go');
    await page.waitForFunction(()=>document.getElementById('pa-run').textContent.includes('nulls'), {timeout:8000});
    const paText = await page.$eval('#pa-out', e=>e.textContent);
    ok('[pa] preferential-attachment null ran', /nulls/.test(await page.$eval('#pa-run',e=>e.textContent)));
    // observed Gini should exceed null mean (rich-get-richer over age)
    const paObsAboveNull = D.prefAttach.inGini_obs > D.prefAttach.inGini_null;
    ok('[pa] observed in-Gini > age-only null (artifact)', paObsAboveNull, `${D.prefAttach.inGini_obs} > ${D.prefAttach.inGini_null}`);

    await page.click('#sw-go');
    await page.waitForFunction(()=>document.getElementById('sw-run').textContent.includes('rewirings'), {timeout:15000});
    const swText = await page.$eval('#sw-out', e=>e.textContent);
    ok('[sw] clustering null ran and reports a multiple', /×/.test(swText), swText.slice(0,60));
    ok('[sw] observed C far above config null (artifact)', D.smallWorld.C_obs > 3*D.smallWorld.C_null, `${D.smallWorld.C_obs} vs ${D.smallWorld.C_null}`);
    ok('[sw] small-world sigma > 1 (artifact)', D.smallWorld.sigma > 1, `σ=${D.smallWorld.sigma}`);

    await page.click('#md-go');
    await page.waitForFunction(()=>document.getElementById('md-run').textContent.includes('rewirings'), {timeout:15000});
    ok('[md] seam modularity above null (artifact)', D.modularity.Q_seam > D.modularity.Q_null + 0.1, `Q=${D.modularity.Q_seam} vs ${D.modularity.Q_null}`);

    // community toggle (greedy detection) runs without error
    await page.click('#b-comm');
    await page.waitForTimeout(200);
    ok('[map] detected-cluster toggle works', errs.length===0, errs.slice(0,1).join(''));

    // ---- temporal-emergence section ----
    const T = D.temporal;
    // both new canvases drew pixels
    const emLit = await page.evaluate(()=>{ const c=document.getElementById('emerge'); const x=c.getContext('2d'); const d=x.getImageData(0,0,c.width,c.height).data; let n=0; for(let i=3;i<d.length;i+=4) if(d[i]>0) n++; return n; });
    ok('[temporal] emergence chart drew pixels', emLit>800, `lit=${emLit}`);
    const raceLit = await page.evaluate(()=>{ const c=document.getElementById('race'); const x=c.getContext('2d'); const d=x.getImageData(0,0,c.width,c.height).data; let n=0; for(let i=3;i<d.length;i+=4) if(d[i]>0) n++; return n; });
    ok('[temporal] hub-race chart drew pixels', raceLit>500, `lit=${raceLit}`);
    // the three emergence findings, as the artifact carries them
    const s0=T.series[0], sN=T.series[T.series.length-1];
    ok('[temporal] seam recovery present at first snapshot', s0.Qz>=2 && s0.Q>s0.Qnull, `z_Q(${s0.r})=${s0.Qz}`);
    ok('[temporal] small-world sigma grows with corpus', sN.sigma>s0.sigma && sN.sigma>2, `${s0.sigma}→${sN.sigma}`);
    ok('[temporal] preferential attachment emerges (weak early, strong late)', T.summary.prefAttach_min_z<1 && sN.inGz>=2, `min z=${T.summary.prefAttach_min_z}, end=${sN.inGz}`);
    ok('[temporal] hub race had >1 lead change; final leader is the top hub', T.leaderChanges.length>=2 && T.leaderChanges[T.leaderChanges.length-1].slug===D.hubsTop[0].slug);
    // live recompute lands near the stored point (same seeded null → within Monte-Carlo noise)
    await page.$eval('#em-r', e=>{ e.value=String(Math.min(20, e.max)); e.dispatchEvent(new Event('input')); });
    const chosenR = await page.evaluate(()=>{ const idx=+document.getElementById('em-r').value; return DATA.temporal.snaps[idx]; });
    await page.click('#em-verify');
    await page.waitForFunction(()=>/recomputed live/.test(document.getElementById('em-out').textContent), {timeout:12000});
    const liveTxt = await page.$eval('#em-out', e=>e.textContent);
    // parse "seam z_Q X (stored Y)" and "σ X (stored Y)" and check they agree within tolerance
    const mz = liveTxt.match(/z\s*Q?\s*([\-\d.]+)\s*\(stored\s*([\-\d.]+)\)/);
    const ms = liveTxt.match(/σ\s*([\-\d.]+)\s*\(stored\s*([\-\d.]+)\)/);
    ok('[temporal] live recompute reports both numbers', !!mz && !!ms, liveTxt.slice(0,90));
    if (ms) ok('[temporal] live σ lands on stored', Math.abs(parseFloat(ms[1])-parseFloat(ms[2]))<0.35, `${ms[1]} vs ${ms[2]} @r=${chosenR}`);
    if (mz) ok('[temporal] live seam z_Q same sign & order', parseFloat(mz[1])>0 && parseFloat(mz[2])>0, `${mz[1]} vs ${mz[2]}`);
  }

  // no horizontal overflow
  const overflow = await page.evaluate(()=> document.documentElement.scrollWidth - document.documentElement.clientWidth);
  ok(`[${label}] no horizontal overflow`, overflow<=1, `${overflow}px`);

  await ctx.close();
}
await browser.close();
server.close();

// ─────────────────────────────────────────────────────────────────────────────
// DRIFT (informational, not a failure): the same extractor, run read-only over
// today's corpus. Nothing here can change the exit code.
// ─────────────────────────────────────────────────────────────────────────────
console.log('\n== DRIFT (informational, not a failure) ==');
console.log(`  the page renders a dated snapshot: ${ART_REL}, ${D.nodes} layers, and says so on its face.`);
console.log('  regenerating from the live corpus (read-only, writes nothing) to show the gap...');
let live = null, liveErr = null;
try {
  live = JSON.parse(execFileSync(process.execPath, [join(AW_REPO_ROOT, 'research/lineage-constellation/extract.mjs'), '--stdout'],
    { cwd: AW_REPO_ROOT, encoding: 'utf8', maxBuffer: 512 << 20 }));
} catch (e) { liveErr = (e.message || String(e)).split('\n')[0]; }

if (!live) {
  console.log(`  could not regenerate: ${liveErr}`);
  console.log('  (that is reported, not asserted; see this file\'s header for why the drift section never fails)');
} else {
  const row = (name, a, b, dp) => {
    const f = (x) => (typeof x === 'number' ? (dp === 0 ? String(x) : x.toFixed(dp)) : String(x));
    const delta = (typeof a === 'number' && typeof b === 'number')
      ? `${b - a >= 0 ? '+' : ''}${dp === 0 ? (b - a) : (b - a).toFixed(dp)}` : '';
    console.log(`  ${name.padEnd(30)} ${f(a).padStart(10)}  →${f(b).padStart(10)}   ${delta}`);
  };
  console.log(`  ${'figure'.padEnd(30)} ${'committed'.padStart(10)}   ${'live'.padStart(9)}   delta`);
  row('nodes', D.nodes, live.nodes, 0);
  row('edges (undirected)', D.edgesUndirected, live.edgesUndirected, 0);
  row('edges (directed)', D.edgesDirected, live.edgesDirected, 0);
  row('mean out-degree', D.meanOutDeg, live.meanOutDeg, 3);
  row('density', D.density, live.density, 5);
  row('giant component', D.giantSize, live.giantSize, 0);
  row('links to the past (frac)', D.edgeTime.toPastFrac, live.edgeTime.toPastFrac, 4);
  row('in-degree Gini', D.degree.inGini, live.degree.inGini, 4);
  row('in-Gini temporal null', D.prefAttach.inGini_null, live.prefAttach.inGini_null, 4);
  row('clustering C', D.smallWorld.C_obs, live.smallWorld.C_obs, 4);
  row('clustering C (config null)', D.smallWorld.C_null, live.smallWorld.C_null, 4);
  row('mean path L', D.smallWorld.L_obs, live.smallWorld.L_obs, 4);
  row('small-world sigma', D.smallWorld.sigma, live.smallWorld.sigma, 3);
  row('seam modularity Q', D.modularity.Q_seam, live.modularity.Q_seam, 4);
  row('seam modularity null', D.modularity.Q_null, live.modularity.Q_null, 4);
  row('detected communities', D.modularity.detectedK, live.modularity.detectedK, 0);
  row('NMI(detected, seam)', D.modularity.nmiDetectedVsSeam, live.modularity.nmiDetectedVsSeam, 4);
  row('seams in use', D.modularity.seams, live.modularity.seams, 0);
  row('top hub in-degree', D.hubsTop[0].inDeg, live.hubsTop[0].inDeg, 0);
  console.log(`  top hub                        ${D.hubsTop[0].slug}  →  ${live.hubsTop[0].slug}`);
  const lag = live.nodes - D.nodes;
  console.log(`  the artifact is ${lag} layers behind the corpus. To close it, read what moved, then:`);
  console.log('    node research/lineage-constellation/extract.mjs --json && node scripts/check-inlined-data.mjs --apply --only the-map-no-one-drew');
  console.log('  Until then nothing is wrong: the page is a dated snapshot and dates itself.');
}

console.log(fails ? `\n${fails} FAILED` : '\nALL PASSED');
console.log(`${total - fails}/${total} checks passed`);
process.exit(fails?1:0);
