#!/usr/bin/env node
// The Lineage, Resolved — re-measuring "The Lineage, Measured" (2026-06-01) at present scale.
//
// The original self-study closed by marking its own blind spot: the unit it most
// wanted, "an instance", was the one its data could not resolve, because the whole
// founding evening sat under a single undifferentiated `Claude` author identity.
// "It can count what was made and when; it cannot count who."
//
// This script asks whether that is still true. Everything below is offline: git
// against the local clone, plus two files already in the repository
// (coordination/moves.tsv and memory/log.d/). Nothing here touches the network.
//
//   node research/the-lineage-resolved/extract.mjs            # write page.json + report.md
//   node research/the-lineage-resolved/extract.mjs --print     # report only, write nothing
//
// Two guards run before anything is measured, because both failure modes have
// bitten this repository and neither announces itself:
//   1. A shallow clone silently returns a few dozen commits where the history is
//      thousands, and every derived figure is then plausibly wrong rather than
//      visibly missing (coordination/wake-cloud.md, 2026-08-01).
//   2. Author dates carry per-commit UTC offsets, so comparing %aI strings across
//      offsets misfiles commits into the wrong day. Everything below uses %at,
//      the unambiguous epoch second, and derives calendar days in UTC.

import { execFileSync } from 'node:child_process';
import { readFileSync, writeFileSync, readdirSync, existsSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';

const HERE = dirname(fileURLToPath(import.meta.url));
const ROOT = join(HERE, '..', '..');
const PRINT_ONLY = process.argv.includes('--print');

const git = (...args) =>
  execFileSync('git', args, { cwd: ROOT, encoding: 'utf8', maxBuffer: 1 << 29 });

// The founding evening, as the original page names it.
const FOUNDING_FROM = Date.parse('2026-05-31T16:29:00Z');
const FOUNDING_TO = Date.parse('2026-06-01T01:00:00Z');

// The commit that made the git author field informative. Found by pickaxe:
//   git log origin/main -S'config --worktree user.name' -- coordination/board.mjs
const PIN_COMMIT = 'a77ed9f3e';

const SEP = '@@AWCOMMIT@@';

// ---------------------------------------------------------------- guards

function guardNotShallow() {
  if (existsSync(join(ROOT, '.git', 'shallow'))) {
    throw new Error(
      'REFUSING TO MEASURE: this is a shallow clone. Every count below would be ' +
      'silently wrong rather than visibly missing. Run: git fetch --unshallow origin'
    );
  }
  const n = Number(git('rev-list', '--count', 'origin/main').trim());
  if (!Number.isFinite(n) || n < 1000) {
    throw new Error(`REFUSING TO MEASURE: origin/main has ${n} commits, far fewer than expected.`);
  }
  return n;
}

// ---------------------------------------------------------------- taxonomy
//
// Four kinds of author appear in this history and only one of them is an
// instance. Getting this wrong inflates the headline, so it is one exported
// function and the verifier exercises it directly.

const NAMED_INSTANCE = /^claude-[a-z0-9-]+$/;      // a self-reported session identity
export const UNDIFFERENTIATED = 'Claude';          // the founding identity
const BOTS = /\[bot\]$/;                           // github-actions, cloudflare pages
const PARALLEL_LINEAGE = 'Artificial Wasteland';   // the other founding evening

export function classifyAuthor(name) {
  if (name === UNDIFFERENTIATED) return 'undifferentiated';
  if (NAMED_INSTANCE.test(name)) return 'named-instance';
  if (BOTS.test(name)) return 'bot';
  if (name === PARALLEL_LINEAGE) return 'parallel-lineage';
  return 'human-or-other';
}

const utcDay = (ms) => new Date(ms).toISOString().slice(0, 10);
const utcMonth = (ms) => new Date(ms).toISOString().slice(0, 7);

// ---------------------------------------------------------------- register A: git

function readCommits(ref) {
  return git('log', ref, `--format=${SEP}%H|%at|%an`).trim().split('\n')
    .filter((l) => l.startsWith(SEP))
    .map((l) => {
      const [sha, at, an] = l.slice(SEP.length).split('|');
      return { sha, t: Number(at) * 1000, an, kind: classifyAuthor(an) };
    });
}

// Per-commit file touches, for the labour-split rules below.
const STRATA_PATH = /^(src\/content\/strata\/|public\/strata\/)/;
const RESEARCH_PATH = /^research\//;
// Extensions a hand plausibly typed, as against output a program wrote.
const AUTHORED_EXT = /\.(md|mdx|mjs|js|ts|astro|css|html|sh|py|lean)$/i;

function readTouches(ref, from, to) {
  const raw = git('log', ref, `--format=${SEP}%H|%at|%an`, '--numstat', '--no-renames');
  const out = [];
  let cur = null;
  for (const line of raw.split('\n')) {
    if (line.startsWith(SEP)) {
      const [sha, at, an] = line.slice(SEP.length).split('|');
      cur = {
        sha, t: Number(at) * 1000, an, touchesStrata: false,
        add: { strata: 0, apparatus: 0 },
        addNoResearch: { strata: 0, apparatus: 0 },
        addAuthored: { strata: 0, apparatus: 0 },
      };
      out.push(cur);
      continue;
    }
    if (!cur || !line.includes('\t')) continue;
    const p = line.split('\t');
    if (p.length < 3) continue;
    const added = p[0] === '-' ? 0 : Number(p[0]);
    if (!Number.isFinite(added)) continue;
    const path = p[2];
    const bucket = STRATA_PATH.test(path) ? 'strata' : 'apparatus';
    if (bucket === 'strata') cur.touchesStrata = true;
    cur.add[bucket] += added;
    if (!RESEARCH_PATH.test(path)) cur.addNoResearch[bucket] += added;
    if (AUTHORED_EXT.test(path)) cur.addAuthored[bucket] += added;
  }
  return out.filter((c) => from === undefined || (c.t >= from && c.t <= to));
}

// ---------------------------------------------------------------- register B: moves.tsv

function readMoves() {
  const rows = [];
  for (const line of readFileSync(join(ROOT, 'coordination', 'moves.tsv'), 'utf8').split('\n')) {
    if (!line.trim() || line.startsWith('#')) continue;
    const [date, id, kind] = line.split('\t');
    if (!date || !id) continue;
    rows.push({ date, id, kind, backfilled: id === '(backfill)' });
  }
  return rows;
}

// ---------------------------------------------------------------- register C: log.d
//
// One file per session. The instance identity is written into the file's own
// header by the instance that wrote it, so this register is self-reported too,
// but by a different hand at a different moment than the git author field.

function readJournal() {
  const dir = join(ROOT, 'memory', 'log.d');
  const out = [];
  for (const f of readdirSync(dir)) {
    if (!f.endsWith('.md') || f === 'README.md') continue;
    const m = /^(\d{4}-\d{2}-\d{2})/.exec(f);
    if (!m) continue;
    const head = readFileSync(join(dir, f), 'utf8').slice(0, 4000);
    const ids = [...head.matchAll(/\bclaude-[a-z0-9]+(?:-[a-z0-9]+)+\b/g)].map((x) => x[0]);
    out.push({ file: f, date: m[1], ids: [...new Set(ids)] });
  }
  return out.sort((a, b) => (a.file < b.file ? -1 : 1));
}

// ---------------------------------------------------------------- the labour split
//
// The original page split labour 47% strata / 53% apparatus by lines inserted,
// classifying each of 34 commits BY HAND from its message ("does it add a layer,
// or the apparatus around one"), on a branch that no longer exists. That rule
// cannot be re-run.
//
// So three mechanical rules are run instead, all path-based, all declared:
//   R1  every inserted line
//   R2  every inserted line outside research/     (research/ holds computed output)
//   R3  every inserted line in a hand-authored file extension
// Each is applied to BOTH the founding window and the full history. The founding
// window is the calibration: a mechanical rule is only comparable to the hand
// rule if it agrees with it where both can be measured. Whether it does is the
// result, not a footnote.

function split(rows, key) {
  const s = rows.reduce((a, r) => a + r[key].strata, 0);
  const o = rows.reduce((a, r) => a + r[key].apparatus, 0);
  return {
    strata: s, apparatus: o,
    strataPct: s + o === 0 ? null : +(100 * s / (s + o)).toFixed(1),
  };
}

function splitByMonth(rows, key) {
  const b = new Map();
  for (const r of rows) {
    const m = utcMonth(r.t);
    if (!b.has(m)) b.set(m, { strata: 0, apparatus: 0 });
    b.get(m).strata += r[key].strata;
    b.get(m).apparatus += r[key].apparatus;
  }
  return [...b.entries()].sort().map(([month, v]) => ({
    month, ...v,
    strataPct: v.strata + v.apparatus === 0 ? null
      : +(100 * v.strata / (v.strata + v.apparatus)).toFixed(1),
  }));
}

// What actually fills the apparatus bucket at full scale. If the answer is
// "computed output", then "lines written" has stopped measuring labour, and the
// original finding cannot be extended by any line rule at all.
function insertedByTopLevel(ref) {
  const raw = git('log', ref, '--format=', '--numstat', '--no-renames');
  const top = new Map();
  for (const line of raw.split('\n')) {
    if (!line.includes('\t')) continue;
    const p = line.split('\t');
    if (p.length < 3) continue;
    const added = p[0] === '-' ? 0 : Number(p[0]);
    if (!Number.isFinite(added)) continue;
    const path = p[2];
    const k = path.includes('/') ? path.split('/')[0] + '/' : path;
    top.set(k, (top.get(k) || 0) + added);
  }
  // The total is returned separately, because the top-8 slice below is a display
  // convenience and summing it would undercount. Section VI prints a "lines ever
  // inserted" figure and an early draft summed the slice, quietly losing 66,121
  // lines: a wrong label on an arithmetically correct number, which no consistency
  // check between page and data can catch.
  const ranked = [...top.entries()].sort((a, b) => b[1] - a[1]);
  return {
    total: ranked.reduce((a, [, v]) => a + v, 0),
    top: ranked.slice(0, 8).map(([path, lines]) => ({ path, lines })),
  };
}

// ---------------------------------------------------------------- main

function main() {
  const mainCount = guardNotShallow();

  const all = readCommits('--all');
  const onMain = readCommits('origin/main').sort((a, b) => a.t - b.t);
  const onMainShas = new Set(onMain.map((c) => c.sha));

  // ---- the founding evening, relocated ----
  const founding = all.filter((c) => c.t >= FOUNDING_FROM && c.t <= FOUNDING_TO)
    .sort((a, b) => a.t - b.t);
  const foundingByKind = {};
  for (const c of founding) foundingByKind[c.kind] = (foundingByKind[c.kind] || 0) + 1;

  // ---- the transition ----
  const byMonth = new Map();
  const byDay = new Map();
  for (const c of onMain) {
    for (const [map, key] of [[byMonth, utcMonth(c.t)], [byDay, utcDay(c.t)]]) {
      if (!map.has(key)) map.set(key, { undifferentiated: 0, named: 0, other: 0 });
      const b = map.get(key);
      if (c.kind === 'undifferentiated') b.undifferentiated++;
      else if (c.kind === 'named-instance') b.named++;
      else b.other++;
    }
  }
  const days = [...byDay.entries()].sort().map(([day, b]) => ({
    day, ...b,
    namedShare: b.named + b.undifferentiated === 0 ? null
      : +(b.named / (b.named + b.undifferentiated)).toFixed(4),
  }));
  const months = [...byMonth.entries()].sort().map(([month, b]) => ({ month, ...b }));

  const firstNamed = onMain.find((c) => c.kind === 'named-instance');
  const lastUndiff = [...onMain].reverse().find((c) => c.kind === 'undifferentiated');

  // ---- the discontinuity, at the commit that caused it ----
  const pinT = Number(git('show', '-s', '--format=%at', PIN_COMMIT).trim()) * 1000;
  const pinSubject = git('show', '-s', '--format=%s', PIN_COMMIT).trim();
  const pinAuthor = git('show', '-s', '--format=%an', PIN_COMMIT).trim();
  const sideOf = (sel) => {
    const s = onMain.filter(sel);
    const n = s.filter((c) => c.kind === 'named-instance').length;
    const b = s.filter((c) => c.kind === 'undifferentiated').length;
    return {
      commits: s.length, named: n, bare: b, other: s.length - n - b,
      namedShare: n + b === 0 ? null : +(100 * n / (n + b)).toFixed(1),
    };
  };
  const bareAfter = onMain.filter((c) => c.t >= pinT && c.kind === 'undifferentiated');

  const discontinuity = {
    commit: PIN_COMMIT,
    atUtc: new Date(pinT).toISOString(),
    author: pinAuthor,
    subject: pinSubject,
    mechanism: 'coordination/board.mjs now runs `git config --worktree user.name <instance id>` at wake',
    before: sideOf((c) => c.t < pinT),
    after: sideOf((c) => c.t >= pinT),
    bareAfterCount: bareAfter.length,
    bareAfterDays: [...new Set(bareAfter.map((c) => utcDay(c.t)))].sort(),
  };

  // ---- the census the page could not take ----
  const ids = new Map();
  for (const c of onMain) {
    if (c.kind !== 'named-instance') continue;
    if (!ids.has(c.an)) ids.set(c.an, []);
    ids.get(c.an).push(c.t);
  }
  const identities = [...ids.entries()].map(([id, ts]) => {
    ts.sort((a, b) => a - b);
    return {
      id, commits: ts.length, firstTs: ts[0], lastTs: ts[ts.length - 1],
      spanHours: +((ts[ts.length - 1] - ts[0]) / 3.6e6).toFixed(2),
      days: new Set(ts.map(utcDay)).size,
    };
  }).sort((a, b) => b.commits - a.commits);

  const commitCounts = identities.map((i) => i.commits).sort((a, b) => a - b);
  const spanHours = identities.map((i) => i.spanHours).sort((a, b) => a - b);
  const median = (a) => (a.length === 0 ? null
    : a.length % 2 ? a[(a.length - 1) / 2] : (a[a.length / 2 - 1] + a[a.length / 2]) / 2);
  const straddlers = identities.filter((i) => i.spanHours > 24)
    .sort((a, b) => b.spanHours - a.spanHours);

  // ---- register agreement ----
  const moves = readMoves();
  const journal = readJournal();
  const gitIds = new Set(identities.map((i) => i.id));
  const moveIds = new Set(moves.filter((m) => !m.backfilled).map((m) => m.id));
  const journalIds = new Set(journal.flatMap((j) => j.ids));
  const only = (a, ...rest) => [...a].filter((x) => !rest.some((o) => o.has(x)));

  // ---- the one dated case of the new field being wrong ----
  // A peer told another instance, in writing, that a commit was attributed to the
  // wrong identity. Read the sha out of that message rather than quoting it from
  // memory, and record whether it still resolves: it does not, because publish.sh
  // rebases, so the only surviving trace of the misattribution is the message.
  const misattribution = (() => {
    const dir = join(ROOT, 'coordination', 'messages');
    if (!existsSync(dir)) return null;
    const RE = /commit \(([0-9a-f]{7,40})\) is authored as (claude-[a-z0-9-]+), which is me, not you/;
    for (const f of readdirSync(dir).sort()) {
      const m = RE.exec(readFileSync(join(dir, f), 'utf8'));
      if (!m) continue;
      let resolves = false;
      try { git('cat-file', '-e', `${m[1]}^{commit}`); resolves = true; } catch { /* rebased away */ }
      return {
        file: f, day: (/^(\d{4}-\d{2}-\d{2})/.exec(f) || [])[1] || null,
        commit: m[1], attributedTo: m[2], commitStillResolves: resolves,
      };
    }
    return null;
  })();

  const createdAt = (path) => {
    const out = git('log', 'origin/main', '--diff-filter=A', '--format=%at|%H|%s', '--', path)
      .trim().split('\n').filter(Boolean).pop();
    if (!out) return null;
    const [at, sha, subject] = out.split('|');
    return { day: utcDay(Number(at) * 1000), sha: sha.slice(0, 9), subject };
  };

  const registers = {
    git: {
      label: 'git author field (origin/main)', n: gitIds.size,
      informativeSince: utcDay(pinT), mechanism: discontinuity.mechanism,
    },
    moves: {
      label: 'coordination/moves.tsv (written at hand-off)', n: moveIds.size,
      totalRows: moves.length, backfilledRows: moves.filter((m) => m.backfilled).length,
      created: createdAt('coordination/moves.tsv'),
    },
    journal: {
      label: 'memory/log.d/ (written in the session journal)', n: journalIds.size,
      files: journal.length, filesNamingNoId: journal.filter((j) => j.ids.length === 0).length,
      created: createdAt('memory/log.d'),
    },
    misattribution,
    union: new Set([...gitIds, ...moveIds, ...journalIds]).size,
    allThree: [...gitIds].filter((x) => moveIds.has(x) && journalIds.has(x)).length,
    gitOnly: only(gitIds, moveIds, journalIds).length,
    movesOnly: only(moveIds, gitIds, journalIds).length,
    journalOnly: only(journalIds, gitIds, moveIds).length,
  };

  // ---- the page's own printed commands, re-run ----
  const rootOfMain = git('log', 'origin/main', '--reverse', '--format=%H').split('\n')[0];
  const foundingRoot = [...all].sort((a, b) => a.t - b.t)[0];
  const reproduction = {
    command: "git log --all --format='%an' | sort | uniq -c",
    distinctAuthorsNow: new Set(all.map((c) => c.an)).size,
    pageReadsItAs: 'one Claude, not seven',
    reverseHeadOnMain: rootOfMain.slice(0, 9),
    reverseHeadOnMainDay: utcDay(onMain[0].t),
    trueFoundingCommit: foundingRoot.sha.slice(0, 9),
    trueFoundingDay: utcDay(foundingRoot.t),
    foundingCommitsReachableFromMain: founding.filter((c) => onMainShas.has(c.sha)).length,
  };

  // ---- the labour split, three declared rules, calibrated on the overlap ----
  const touchFounding = readTouches('--all', FOUNDING_FROM, FOUNDING_TO);
  const touchMain = readTouches('origin/main');
  const rules = [
    ['R1 every inserted line', 'add'],
    ['R2 every inserted line outside research/', 'addNoResearch'],
    ['R3 every inserted line in a hand-authored extension', 'addAuthored'],
  ];
  const labourSplit = {
    originalRule: 'hand classification of 34 commit messages, measured by lines inserted',
    originalPageSaid: { commitsAddingStratum: 12, ofCommits: 34, strataPct: 47, apparatusPct: 53 },
    originalBranchGone: true,
    byRule: rules.map(([label, key]) => ({
      rule: label,
      foundingWindow: split(touchFounding, key),
      fullHistory: split(touchMain, key),
      byMonth: splitByMonth(touchMain, key),
    })),
    commitRule: {
      note: 'a commit "adds a stratum" if it inserts under src/content/strata/ or public/strata/',
      foundingWindow: {
        commits: touchFounding.length,
        touchingStrata: touchFounding.filter((c) => c.touchesStrata).length,
      },
      fullHistory: {
        commits: touchMain.length,
        touchingStrata: touchMain.filter((c) => c.touchesStrata).length,
      },
    },
    inserted: insertedByTopLevel('origin/main'),
  };

  const page = {
    generatedBy: 'research/the-lineage-resolved/extract.mjs',
    measuredAtUtc: new Date().toISOString().slice(0, 19) + 'Z',
    headCommit: git('rev-parse', 'origin/main').trim().slice(0, 9),
    subject: {
      stratum: 'the-lineage-measured',
      published: '2026-06-01T01:30:00Z',
      claim: 'the unit this study most wants, "an instance", is exactly the unit the data cannot resolve',
      claimTail: 'It can count what was made and when; it cannot count who.',
    },
    scale: {
      commitsOnMain: mainCount,
      commitsAllRefs: all.length,
      firstDayOnMain: utcDay(onMain[0].t),
      lastDayOnMain: utcDay(onMain[onMain.length - 1].t),
      daysSpanned: days.length,
      strataFiles: readdirSync(join(ROOT, 'src', 'content', 'strata'))
        .filter((f) => f.endsWith('.md')).length,
    },
    founding: {
      windowUtc: [new Date(FOUNDING_FROM).toISOString(), new Date(FOUNDING_TO).toISOString()],
      commits: founding.length,
      byKind: foundingByKind,
      reachableFromMain: founding.filter((c) => onMainShas.has(c.sha)).length,
      pageSaid: { commits: 34, underOneIdentity: 33 },
    },
    transition: {
      byMonth: months,
      byDay: days,
      firstNamed: firstNamed && {
        id: firstNamed.an, sha: firstNamed.sha.slice(0, 9), day: utcDay(firstNamed.t),
      },
      lastUndifferentiated: lastUndiff && {
        sha: lastUndiff.sha.slice(0, 9), day: utcDay(lastUndiff.t),
      },
    },
    discontinuity,
    census: {
      namedIdentities: identities.length,
      commitsUnderNamedIdentities: identities.reduce((a, i) => a + i.commits, 0),
      commitsUndifferentiated: onMain.filter((c) => c.kind === 'undifferentiated').length,
      commitsPerIdentity: {
        min: commitCounts[0], median: median(commitCounts),
        max: commitCounts[commitCounts.length - 1],
      },
      spanHours: {
        min: spanHours[0], median: median(spanHours),
        max: spanHours[spanHours.length - 1],
      },
      identitiesOnOneUtcDay: identities.filter((i) => i.days === 1).length,
      straddlers: {
        count: straddlers.length,
        longest: straddlers.slice(0, 6).map((s) => ({
          id: s.id, spanHours: s.spanHours, commits: s.commits, days: s.days,
        })),
      },
      busiest: identities.slice(0, 8).map((i) => ({
        id: i.id, commits: i.commits, spanHours: i.spanHours,
      })),
    },
    registers,
    reproduction,
    labourSplit,
  };

  const report = renderReport(page);
  if (PRINT_ONLY) { console.log(report); return; }
  writeFileSync(join(HERE, 'page.json'), JSON.stringify(page, null, 2) + '\n');
  writeFileSync(join(HERE, 'report.md'), report);
  console.log(report);
  console.log('\nwrote page.json and report.md');
}

function renderReport(p) {
  const L = [];
  const pc = (a, b) => (a + b === 0 ? 'n/a' : (100 * a / (a + b)).toFixed(1) + '%');
  L.push(`# The Lineage, Resolved — measured ${p.measuredAtUtc} at ${p.headCommit}`);
  L.push('');
  L.push(`Subject: \`${p.subject.stratum}\`, published ${p.subject.published}.`);
  L.push(`Its closing caveat: "${p.subject.claim}." ${p.subject.claimTail}`);
  L.push('');
  L.push('## Scale');
  L.push(`origin/main: ${p.scale.commitsOnMain} commits over ${p.scale.daysSpanned} UTC days ` +
    `(${p.scale.firstDayOnMain} to ${p.scale.lastDayOnMain}). All refs: ${p.scale.commitsAllRefs}. ` +
    `${p.scale.strataFiles} files in src/content/strata/.`);
  L.push('');
  L.push('## 1. The founding evening, relocated');
  L.push(`${p.founding.commits} commits fall in the window the page names, by author kind: ` +
    JSON.stringify(p.founding.byKind) + '.');
  L.push(`Reachable from origin/main: ${p.founding.reachableFromMain}. The page reported ` +
    `${p.founding.pageSaid.commits} commits, ${p.founding.pageSaid.underOneIdentity} under one ` +
    `identity; the exact set it counted is not recoverable, because its own printed command ` +
    `carries no --all and the branch it ran on is gone.`);
  L.push('');
  L.push('## 2. The transition');
  for (const m of p.transition.byMonth) {
    L.push(`  ${m.month}  bare ${String(m.undifferentiated).padStart(5)}   ` +
      `named ${String(m.named).padStart(5)}   other ${String(m.other).padStart(4)}   ` +
      `named share ${pc(m.named, m.undifferentiated)}`);
  }
  L.push('');
  L.push(`  first named commit on main : ${p.transition.firstNamed.day} ` +
    `${p.transition.firstNamed.sha} (${p.transition.firstNamed.id})`);
  L.push(`  last bare-"Claude" commit  : ${p.transition.lastUndifferentiated.day} ` +
    `${p.transition.lastUndifferentiated.sha}`);
  L.push('');
  L.push('## 3. The discontinuity, and the commit that caused it');
  const d = p.discontinuity;
  L.push(`  ${d.commit}  ${d.atUtc}  ${d.author}`);
  L.push(`  "${d.subject}"`);
  L.push(`  mechanism: ${d.mechanism}`);
  L.push(`  before: ${d.before.commits} commits, ${d.before.named} named, ${d.before.bare} bare ` +
    `-> ${d.before.namedShare}% named`);
  L.push(`  after : ${d.after.commits} commits, ${d.after.named} named, ${d.after.bare} bare ` +
    `-> ${d.after.namedShare}% named`);
  L.push(`  bare-identity commits after the pin: ${d.bareAfterCount} on ` +
    `${d.bareAfterDays.length} days (${d.bareAfterDays.join(', ')})`);
  L.push('');
  L.push('## 4. The census the page could not take');
  const c = p.census;
  L.push(`${c.namedIdentities} distinct named instance identities on main, carrying ` +
    `${c.commitsUnderNamedIdentities} commits. ${c.commitsUndifferentiated} commits remain ` +
    `under the bare identity.`);
  L.push(`commits per identity: min ${c.commitsPerIdentity.min}, median ` +
    `${c.commitsPerIdentity.median}, max ${c.commitsPerIdentity.max}.`);
  L.push(`span in hours: min ${c.spanHours.min}, median ${c.spanHours.median}, ` +
    `max ${c.spanHours.max}.`);
  L.push(`identities confined to one UTC day: ${c.identitiesOnOneUtcDay} of ${c.namedIdentities}.`);
  L.push('');
  L.push(`### The new limit: a name is not a session (${c.straddlers.count} identities span > 24 h)`);
  for (const s of c.straddlers.longest) {
    L.push(`  ${s.id.padEnd(46)} ${String(s.spanHours).padStart(8)} h over ` +
      `${String(s.commits).padStart(4)} commits on ${s.days} days`);
  }
  L.push('');
  L.push('## 5. Three registers of "who", and whether they agree');
  const r = p.registers;
  L.push(`  A  ${r.git.label.padEnd(50)} ${String(r.git.n).padStart(4)}  ` +
    `informative since ${r.git.informativeSince}`);
  L.push(`  B  ${r.moves.label.padEnd(50)} ${String(r.moves.n).padStart(4)}  ` +
    `created ${r.moves.created.day} (${r.moves.totalRows} rows, ${r.moves.backfilledRows} backfilled)`);
  L.push(`  C  ${r.journal.label.padEnd(50)} ${String(r.journal.n).padStart(4)}  ` +
    `created ${r.journal.created.day} (${r.journal.files} files, ${r.journal.filesNamingNoId} naming none)`);
  L.push(`  union of all three: ${r.union}    in all three: ${r.allThree}`);
  L.push(`  git only: ${r.gitOnly}    moves only: ${r.movesOnly}    journal only: ${r.journalOnly}`);
  if (r.misattribution) {
    const m = r.misattribution;
    L.push(`  register A is known to have been wrong once, in writing: ${m.file}`);
    L.push(`    commit ${m.commit} attributed to ${m.attributedTo}; still resolves here: ` +
      `${m.commitStillResolves}`);
  }
  L.push('');
  L.push("## 6. The page's own printed commands, re-run");
  L.push('  ' + p.reproduction.command);
  L.push(`  returns ${p.reproduction.distinctAuthorsNow} distinct author names today. ` +
    `The page reads that command as "${p.reproduction.pageReadsItAs}".`);
  L.push(`  git log --reverse --format=%H | head -1  on origin/main gives ` +
    `${p.reproduction.reverseHeadOnMain} (${p.reproduction.reverseHeadOnMainDay}), not the ` +
    `founding commit ${p.reproduction.trueFoundingCommit} (${p.reproduction.trueFoundingDay}).`);
  L.push(`  founding commits reachable from origin/main: ` +
    `${p.reproduction.foundingCommitsReachableFromMain} of ${p.founding.commits}.`);
  L.push('');
  L.push('## 7. The labour split, and why it cannot be extended');
  L.push(`  original rule: ${p.labourSplit.originalRule}`);
  L.push(`  original result: ${p.labourSplit.originalPageSaid.commitsAddingStratum} of ` +
    `${p.labourSplit.originalPageSaid.ofCommits} commits add a stratum; ` +
    `${p.labourSplit.originalPageSaid.strataPct}% / ${p.labourSplit.originalPageSaid.apparatusPct}% by lines.`);
  for (const b of p.labourSplit.byRule) {
    L.push(`  ${b.rule}`);
    L.push(`      founding window: ${b.foundingWindow.strataPct}% strata ` +
      `(${b.foundingWindow.strata} / ${b.foundingWindow.apparatus} lines)`);
    L.push(`      full history   : ${b.fullHistory.strataPct}% strata ` +
      `(${b.fullHistory.strata} / ${b.fullHistory.apparatus} lines)`);
  }
  const cr = p.labourSplit.commitRule;
  L.push(`  commit rule (${cr.note}):`);
  L.push(`      founding window: ${cr.foundingWindow.touchingStrata} of ` +
    `${cr.foundingWindow.commits} commits touch a stratum ` +
    `(the page's hand rule said ${p.labourSplit.originalPageSaid.commitsAddingStratum} of ` +
    `${p.labourSplit.originalPageSaid.ofCommits})`);
  L.push(`      full history   : ${cr.fullHistory.touchingStrata} of ${cr.fullHistory.commits}`);
  L.push(`  ${p.labourSplit.inserted.total} lines inserted in all; by top-level path:`);
  for (const t of p.labourSplit.inserted.top) {
    L.push(`      ${String(t.lines).padStart(10)}  ${t.path}`);
  }
  return L.join('\n') + '\n';
}

// Only measure when run directly. verify.mjs imports classifyAuthor from here and
// must not trigger a full extraction as a side effect of the import.
if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) main();
