geneseed 5.2.0 → 5.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (142) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/README.md +2 -2
  3. package/SHIPPED.md +1 -1
  4. package/adapters/opencode/plugins/geneseed-context.js +56 -10
  5. package/adapters/opencode/plugins/geneseed-guard.js +6 -1
  6. package/bin/geneseed-cli.mjs +61 -16
  7. package/bin/geneseed-hook.mjs +37 -3
  8. package/docs/concepts/factories.md +40 -6
  9. package/docs/concepts/footprint.md +1 -1
  10. package/docs/concepts/foreman-mode.md +2 -2
  11. package/docs/concepts/loop-gates.md +1 -1
  12. package/docs/concepts/loops.md +2 -2
  13. package/docs/concepts/shared-tier.md +1 -1
  14. package/docs/design-history.md +140 -0
  15. package/docs/extending.md +54 -162
  16. package/docs/guides/run-a-factory.md +15 -2
  17. package/docs/guides/upgrade.md +2 -2
  18. package/docs/reference/factory-actions.md +6 -5
  19. package/docs/reference/troubleshoot-update.md +1 -1
  20. package/docs/web-ui.md +16 -3
  21. package/harness.config.json +1 -1
  22. package/js/README.md +4 -3
  23. package/js/build/args.mjs +3 -3
  24. package/js/build/render.mjs +44 -24
  25. package/js/cli-table.json +135 -59
  26. package/js/factory/cli.mjs +24 -5
  27. package/js/factory/graph.mjs +13 -9
  28. package/js/factory/metrics.mjs +93 -0
  29. package/js/factory/registry.mjs +37 -12
  30. package/js/factory/state.mjs +25 -6
  31. package/js/hosts/hooks-context.mjs +26 -1
  32. package/js/hosts/hooks-prims.mjs +52 -3
  33. package/js/hosts/hooks.mjs +50 -29
  34. package/js/hosts/loss.mjs +6 -1
  35. package/js/inspect/diff.mjs +16 -1
  36. package/js/inspect/doctor.mjs +7 -3
  37. package/js/inspect/excludes.mjs +18 -6
  38. package/js/inspect/status.mjs +35 -7
  39. package/js/inspect/validate.mjs +44 -21
  40. package/js/maintain/uninstall.mjs +28 -1
  41. package/js/maintain/update.mjs +31 -7
  42. package/js/ui/cli.mjs +34 -4
  43. package/js/ui/menu.mjs +1 -1
  44. package/js/ui/tui.mjs +11 -14
  45. package/js/web/actions.mjs +2 -0
  46. package/js/web/api.mjs +28 -10
  47. package/js/web/daemon.mjs +0 -1
  48. package/js/web/server.mjs +1 -0
  49. package/js/web/state.mjs +37 -16
  50. package/package.json +1 -1
  51. package/src/AGENT.md.tmpl +23 -17
  52. package/src/agents/_template.md +1 -1
  53. package/src/agents/advocate.md +1 -1
  54. package/src/agents/developer.md +12 -3
  55. package/src/agents/empiricist.md +1 -1
  56. package/src/agents/framer.md +1 -1
  57. package/src/agents/historian.md +1 -1
  58. package/src/agents/operator.md +1 -1
  59. package/src/agents/pragmatist.md +1 -1
  60. package/src/agents/researcher.md +1 -1
  61. package/src/agents/skeptic.md +1 -1
  62. package/src/agents/steward.md +1 -1
  63. package/src/agents/user-advocate.md +1 -1
  64. package/src/agents/visionary.md +1 -1
  65. package/src/bricks/intake.md +10 -3
  66. package/src/bricks/retro.md +13 -3
  67. package/src/doctrines/comms.md +1 -1
  68. package/src/doctrines/ops.md +1 -1
  69. package/src/doctrines/process.md +7 -5
  70. package/src/factories/analysis-to-build.json +1 -0
  71. package/src/factories/bug-report-to-fix.json +1 -0
  72. package/src/factories/issue-to-pr.json +1 -0
  73. package/src/laws/universal.md +2 -2
  74. package/src/modes/foreman.md +8 -14
  75. package/src/skills/commit.md +7 -2
  76. package/src/skills/debug.md +1 -1
  77. package/src/skills/diagram-design/SKILL.md +1 -1
  78. package/src/skills/diagram-design/VENDOR.md +3 -1
  79. package/src/skills/factory-forge.md +5 -3
  80. package/src/skills/factory.md +22 -1
  81. package/src/skills/geneseed.md +1 -1
  82. package/src/skills/handoff.md +1 -1
  83. package/src/skills/parallel-agents.md +1 -1
  84. package/src/skills/pipeline.md +6 -6
  85. package/src/skills/plan.md +7 -3
  86. package/src/skills/spring-testing.md +1 -1
  87. package/themes/biker.json +78 -78
  88. package/themes/commentator.json +81 -81
  89. package/themes/cyberpunk.json +79 -79
  90. package/themes/gamer.json +77 -77
  91. package/themes/imperial.json +82 -82
  92. package/themes/joker.json +79 -79
  93. package/themes/marvin.json +82 -82
  94. package/themes/mean.json +82 -82
  95. package/themes/military.json +78 -78
  96. package/themes/neutral.json +78 -78
  97. package/themes/pirate.json +79 -79
  98. package/themes/sports.json +79 -79
  99. package/themes/verstappen.json +78 -78
  100. package/themes/wizard.json +79 -79
  101. package/web/dist/assets/ActiveLoops-BJJN3P-V.js +1 -0
  102. package/web/dist/assets/Activity-CqJiquEq.js +1 -0
  103. package/web/dist/assets/ActivityDetail-BSzevynX.js +1 -0
  104. package/web/dist/assets/{Bonsai-DSwUbavu.js → Bonsai-Bfpb6W-1.js} +1 -1
  105. package/web/dist/assets/{CopyButton-BzRQz7k2.js → CopyButton-ByIntFtB.js} +1 -1
  106. package/web/dist/assets/Dashboard-DBOEi9lQ.js +2 -0
  107. package/web/dist/assets/Docs-DvlMJhpu.js +5 -0
  108. package/web/dist/assets/Factories-Bpvv7L2H.js +1 -0
  109. package/web/dist/assets/{GreenhouseView-y9WAfcc_.js → GreenhouseView-GpBsYn50.js} +1 -1
  110. package/web/dist/assets/Installs-BlGmVrFK.js +3 -0
  111. package/web/dist/assets/{JournalView-DeBLRNGc.js → JournalView-iLuLrOxE.js} +1 -1
  112. package/web/dist/assets/Kits-DRwpxC-J.js +1 -0
  113. package/web/dist/assets/Laws-CZkiNOWQ.js +4 -0
  114. package/web/dist/assets/LibRows-DEHjIoD-.js +1 -0
  115. package/web/dist/assets/Library-B4K-1iNF.js +3 -0
  116. package/web/dist/assets/Loops-BWSzaW8E.js +2 -0
  117. package/web/dist/assets/{OperatorHudView-2ujVMjq1.js → OperatorHudView-BAXwCEvY.js} +1 -1
  118. package/web/dist/assets/Personal-Bp9nV4GR.js +2 -0
  119. package/web/dist/assets/Settings-CWWuaIp-.js +1 -0
  120. package/web/dist/assets/Tabs-CWeQTADL.js +1 -0
  121. package/web/dist/assets/index-CsAZq0BQ.css +1 -0
  122. package/web/dist/assets/index-How7SzDZ.js +6 -0
  123. package/web/dist/assets/usePoll-D5c_qIFZ.js +1 -0
  124. package/web/dist/index.html +2 -2
  125. package/web/dist/assets/ActiveLoops-BTHIaRhn.js +0 -1
  126. package/web/dist/assets/Activity-DlQ30znB.js +0 -1
  127. package/web/dist/assets/ActivityDetail-CG0mn5fW.js +0 -1
  128. package/web/dist/assets/Dashboard-Ce3UOsxJ.js +0 -2
  129. package/web/dist/assets/Docs-CisVnYqv.js +0 -5
  130. package/web/dist/assets/Factories-Dq5oW4CU.js +0 -1
  131. package/web/dist/assets/Installs-m4GElwFW.js +0 -3
  132. package/web/dist/assets/Kits-DJYVAnyE.js +0 -1
  133. package/web/dist/assets/Laws-CNpc_8ZV.js +0 -4
  134. package/web/dist/assets/LibRows-RO5bvXth.js +0 -1
  135. package/web/dist/assets/Library-Dg0ScciC.js +0 -3
  136. package/web/dist/assets/Loops-CjEdo-NG.js +0 -2
  137. package/web/dist/assets/Personal-D0yS7ahT.js +0 -2
  138. package/web/dist/assets/Settings-DEN0U8QI.js +0 -1
  139. package/web/dist/assets/Tabs-But5R6_r.js +0 -1
  140. package/web/dist/assets/index-Ck42AbRX.js +0 -6
  141. package/web/dist/assets/index-PG_ukkh6.css +0 -1
  142. package/web/dist/assets/usePoll-o8ul-Sog.js +0 -1
@@ -0,0 +1,93 @@
1
+ /**
2
+ * The numbers of a factory run, computed from `FACTORY.md`'s state and nothing else: no clock, no
3
+ * file, no catalogue. `geneseed factory report` prints them, and the console's board reads them
4
+ * through `js/factory/registry.mjs`, so the `retro` brick, the Rite and the console show the same
5
+ * figures and no model does date arithmetic (D4, D5).
6
+ *
7
+ * WORK TIME AND WAITING TIME. A history entry's duration is its `at` minus the `at` of the entry
8
+ * before it (the run's `started` for the first). On a `record` entry that is the stage's work
9
+ * time. On a `decide` entry it is the time the run waited at a human gate: the entry before it is
10
+ * always the gated record, so the gap is the user's, never the stage's.
11
+ *
12
+ * UNKNOWN IS `null`, NEVER ZERO. An entry with no `at`, or whose predecessor has none (a
13
+ * FACTORY.md written before the engine stamped times), has a duration of `null`, and so has every
14
+ * sum that holds it: a total that silently left a stage out would read as a fast run. A time that
15
+ * does not parse, or one earlier than its predecessor, is unknown too.
16
+ *
17
+ * TOKENS ARE THE SUM OF WHAT WAS REPORTED. `record --tokens` is passed only where the host gave a
18
+ * count, so a stage's `tokens` adds the counts its entries carry and is `null` when none does.
19
+ * A loop stage carries none: nothing sums a loop's agents by hand (D3).
20
+ *
21
+ * A REWORK IS AN OUTCOME THAT SPENT A CYCLE: the stage reported an outcome whose edge routes back
22
+ * into a declared cycle (`spentCycle`, the rule the engine counts laps with). A held outcome
23
+ * spends its cycle only when the user answers `ok`; `amend` re-runs the stage and `no` stops, and
24
+ * neither is a rework. The fork test needs each stage's outcomes, which live in the catalogue;
25
+ * here they are read off the factory's own edges, one edge per outcome (rule 3 of `checkFactory`),
26
+ * so this module needs no catalogue and the daemon can call it on any registered run.
27
+ *
28
+ * THE OPEN WAIT. A wait is counted on the `decide` that ends it, so a run still held at a gate has
29
+ * waited nothing yet by that count. `now` (an ISO time, optional) gives `openWaitMs`: `now` minus
30
+ * the `at` of the gated record, while the run is `awaiting`. It is null without `now`, on a run
31
+ * that is not awaiting, and when that record has no `at`. The caller reads the clock (`factory
32
+ * report` its own, the console the time of its poll); this module stays pure.
33
+ *
34
+ * NEVER THROWS on a state that parsed: the console calls it on a FACTORY.md nobody validated.
35
+ */
36
+ import { edgeFor, laneTargets, spentCycle } from './graph.mjs';
37
+
38
+ const list = (v) => (Array.isArray(v) ? v : []);
39
+ const elapsed = (from, to) => {
40
+ const a = Date.parse(from ?? ''); const b = Date.parse(to ?? '');
41
+ return Number.isFinite(a) && Number.isFinite(b) && b >= a ? b - a : null;
42
+ };
43
+ const sum = (xs) => (xs.includes(null) ? null : xs.reduce((a, b) => a + b, 0));
44
+ const tokensOf = (hs) => {
45
+ const known = hs.map((h) => h.tokens).filter((t) => Number.isSafeInteger(t) && t >= 1);
46
+ return known.length ? known.reduce((a, b) => a + b, 0) : null;
47
+ };
48
+
49
+ /**
50
+ * `{ started, stages, workMs, waitMs, openWaitMs, tokens, transitions, entries }`. `stages` lists each stage
51
+ * the run recorded, in the order it first ran: `{ stage, runs, reworks, workMs, tokens }`.
52
+ * `entries` is parallel to `state.history`: `{ ms, wait, rework }`, `wait` true on a `decide`
53
+ * entry. `transitions` is the run-wide count the engine keeps.
54
+ */
55
+ export function runMetrics(state, { now = null } = {}) {
56
+ const factory = state?.factory;
57
+ const history = list(state?.history).map((h) => (h !== null && typeof h === 'object' ? h : {}));
58
+ const edges = list(factory?.edges);
59
+ const outcomes = new Map(list(factory?.stages).map((s) => [s, { outcomes: edges.filter((e) => e?.from === s).map((e) => e.on) }]));
60
+ const lanes = laneTargets(factory, outcomes);
61
+ const spends = (h) => {
62
+ const edge = edgeFor(factory, h.stage, h.outcome);
63
+ return !!edge && spentCycle(list(factory?.cycles), h.stage, edge.to, lanes) !== null;
64
+ };
65
+
66
+ let prev = state?.started ?? null;
67
+ const entries = history.map((h, i) => {
68
+ const ms = elapsed(prev, h.at);
69
+ prev = h.at ?? null;
70
+ if (h.verdict !== undefined) return { ms, wait: true, rework: false };
71
+ const answer = history[i + 1]?.verdict; // set when this record held a gate that was answered
72
+ const held = answer !== undefined || (i === history.length - 1 && state?.awaiting != null);
73
+ return { ms, wait: false, rework: (held ? answer === 'ok' : true) && spends(h) };
74
+ });
75
+
76
+ const byStage = new Map();
77
+ history.forEach((h, i) => {
78
+ if (entries[i].wait) return;
79
+ const row = byStage.get(h.stage) ?? { stage: h.stage, runs: 0, reworks: 0, ms: [], hs: [] };
80
+ row.runs += 1; row.reworks += entries[i].rework ? 1 : 0; row.ms.push(entries[i].ms); row.hs.push(h);
81
+ byStage.set(h.stage, row);
82
+ });
83
+ return {
84
+ started: typeof state?.started === 'string' ? state.started : null,
85
+ stages: [...byStage.values()].map(({ stage, runs, reworks, ms, hs }) => ({ stage, runs, reworks, workMs: sum(ms), tokens: tokensOf(hs) })),
86
+ workMs: sum(entries.filter((e) => !e.wait).map((e) => e.ms)),
87
+ waitMs: sum(entries.filter((e) => e.wait).map((e) => e.ms)),
88
+ openWaitMs: state?.status === 'awaiting' && now ? elapsed(history.at(-1)?.at, now) : null,
89
+ tokens: tokensOf(history),
90
+ transitions: Number.isInteger(state?.runTransitions) ? state.runTransitions : null,
91
+ entries,
92
+ };
93
+ }
@@ -6,8 +6,16 @@
6
6
  *
7
7
  * EVERY CONVENTION IS THE LOOP REGISTRY'S, and so is the code (`js/loop/registry.mjs`: `loadRows`,
8
8
  * `saveRows`, `sweepRows`): atomic tmp + rename, every function swallows its own errors, rows keyed
9
- * by their normalised root, no `lastSeen`, a save only when the kept set changed, and a finished
10
- * run dropped 7 days after it was first seen without its FACTORY.md.
9
+ * by their normalised root, no `lastSeen`, and a finished run dropped 7 days after it was first
10
+ * seen without its FACTORY.md.
11
+ *
12
+ * THE CONSOLE'S POLL NEVER WRITES (spec 2026-11-11 D7). The board polls every 5 s; a sweep there
13
+ * would stamp `finishedAt`, drop rows, and race `recordFactory` on the one `factories.json.tmp`
14
+ * during a `factory init`. So `listFactories` is read-only, as `runningLoops` is beside
15
+ * `activeLoops` (but with no sweeping twin: nothing else needs one), and the sweep (stamp,
16
+ * 7-day prune, drop of a vanished root) runs in
17
+ * `recordFactory`, which writes the file anyway. A finished run is first stamped by the next
18
+ * `factory init` on the machine, so it is pruned 7 days after that, not after it closed.
11
19
  *
12
20
  * THE ROOT IS THE JOIN KEY. A child loop runs in the factory's own worktree, so its `loops.json`
13
21
  * row has the same root, and carries `factory: <slug>` (`loop init --factory`). A reader groups a
@@ -15,9 +23,12 @@
15
23
  */
16
24
  import path from 'node:path';
17
25
 
26
+ import { readText, isDir, isFile } from '../lib/fs.mjs';
27
+
18
28
  import { userLoopsDir } from '../loop/catalog.mjs';
19
29
  import { loadRows, saveRows, sweepRows, normalize, sameRoot } from '../loop/registry.mjs';
20
30
  import { FACTORY_FILE, parseFactoryFile } from './state.mjs';
31
+ import { runMetrics } from './metrics.mjs';
21
32
 
22
33
  export function factoryRegistryPath() {
23
34
  return path.join(userLoopsDir(), 'factories.json');
@@ -34,7 +45,7 @@ const save = (rows) => saveRows(factoryRegistryPath(), 'factories', rows);
34
45
  export function recordFactory({ root, branch, factory, title, now = new Date() }) {
35
46
  try {
36
47
  const key = normalize(root);
37
- const rows = load();
48
+ const rows = sweep(load(), now).kept; // the registry's one sweep: see the docblock
38
49
  const idx = rows.findIndex((r) => sameRoot(r.root, key));
39
50
  if (idx >= 0) rows[idx] = { ...rows[idx], root: key, branch, factory, title };
40
51
  else rows.push({ root: key, branch, factory, title, started: now.toISOString() });
@@ -46,7 +57,7 @@ export function recordFactory({ root, branch, factory, title, now = new Date() }
46
57
 
47
58
  const identity = (e) => ({ root: e.root, branch: e.branch, factory: e.factory, title: e.title, started: e.started });
48
59
 
49
- function runningRow(entry, state) {
60
+ function runningRow(entry, state, now = null) {
50
61
  return {
51
62
  ...identity(entry), status: state.status, stage: state.stage, awaiting: state.awaiting,
52
63
  reason: state.reason, transitions: state.transitions, counters: state.counters,
@@ -54,18 +65,32 @@ function runningRow(entry, state) {
54
65
  // The graph the run was started from, as the loop row carries its `graph`: the console draws
55
66
  // it, and a run started in another project names a factory this install may not have.
56
67
  graph: state.factory,
68
+ // D7: the board's numbers, from the one function `factory report` prints (it never throws on
69
+ // a state that parsed, and nothing here validated this one).
70
+ metrics: runMetrics(state, { now }),
57
71
  };
58
72
  }
59
73
 
74
+ const sweep = (rows, now) => sweepRows(rows, {
75
+ stateFile: FACTORY_FILE, parse: parseFactoryFile, project: runningRow, identity, now,
76
+ });
77
+
60
78
  /**
61
- * The rows the console renders, read fresh off each registered worktree's FACTORY.md: a running
62
- * row, `unreadable` (kept, R4), or `finished` (FACTORY.md gone; pruned 7 days later). A root that
63
- * no longer exists is dropped. Saves only when the kept set changed.
79
+ * The rows the console renders, READ-ONLY: never a save, a stamp or a prune. A running row read
80
+ * fresh off each registered worktree's FACTORY.md (its metrics' open wait measured to `now`, the
81
+ * time of the poll), `unreadable` when it does not parse, and
82
+ * `finished` when it is gone. A row whose root no longer exists is skipped: the sweep in
83
+ * `recordFactory` drops it, and a card for a deleted worktree would open on nothing.
64
84
  */
65
- export function activeFactories({ now = new Date() } = {}) {
66
- const { kept, rows, changed } = sweepRows(load(), {
67
- stateFile: FACTORY_FILE, parse: parseFactoryFile, project: runningRow, identity, now,
68
- });
69
- if (changed) save(kept);
85
+ export function listFactories({ now = new Date().toISOString() } = {}) {
86
+ const rows = [];
87
+ for (const entry of load()) {
88
+ if (!isDir(entry.root)) continue;
89
+ const file = path.join(entry.root, FACTORY_FILE);
90
+ if (!isFile(file)) { rows.push({ ...identity(entry), status: 'finished' }); continue; }
91
+ let state;
92
+ try { state = parseFactoryFile(readText(file)); } catch { rows.push({ ...identity(entry), status: 'unreadable' }); continue; }
93
+ rows.push(runningRow(entry, state, now));
94
+ }
70
95
  return rows;
71
96
  }
@@ -80,6 +80,13 @@
80
80
  * budget or a higher ceiling. And it is capped at `FACTORY_MAX_TASKS` (20), so the
81
81
  * ceiling is at most 1200 transitions: past twenty tasks a requirement is a project, to be split
82
82
  * into several factory runs a human can review, not one run nobody reads to the end.
83
+ *
84
+ * TIME AND TOKENS ARE RECORDED, NEVER READ BACK (D2, D3). `init` stamps `started`, and `record`
85
+ * and `decide` stamp `at` on the history entry they push: the ISO time the CLI passes as `now`,
86
+ * as `next` does for a launch. `record` also stores `tokens`, the count the host reported for the
87
+ * agent that ran the stage. No transition reads either one, so both are optional in a state: a
88
+ * FACTORY.md written before them still validates and still runs. `runMetrics`
89
+ * (`js/factory/metrics.mjs`) is their one reader.
83
90
  */
84
91
  import { writeText } from '../lib/fs.mjs';
85
92
  import { renameWithRetry, filterPorcelain } from '../loop/state.mjs';
@@ -117,6 +124,7 @@ export function parseFactoryFile(text) {
117
124
  }
118
125
 
119
126
  const count = (v) => Number.isInteger(v) && v >= 0;
127
+ const tokenCount = (v) => Number.isSafeInteger(v) && v >= 1;
120
128
  const plainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
121
129
 
122
130
  /**
@@ -150,6 +158,12 @@ export function validateFactoryState(state, catalog) {
150
158
  }
151
159
  if (!STATUSES.includes(state.status)) bad(`status must be one of ${STATUSES.join(', ')}`);
152
160
  if (!Array.isArray(state.history)) bad('history must be a list');
161
+ // D2, D3: optional, so a state written before them validates; a wrong shape would feed `runMetrics` nonsense
162
+ if (state.started != null && typeof state.started !== 'string') bad('started must be a time');
163
+ for (const h of state.history) {
164
+ if (h?.at != null && typeof h.at !== 'string') bad('a history entry\'s at must be a time');
165
+ if (h?.tokens !== undefined && !tokenCount(h.tokens)) bad('a history entry\'s tokens must be a positive integer');
166
+ }
153
167
  if (!plainObject(state.gateAmends) || !Object.values(state.gateAmends).every((n) => count(n) && n <= GATE_MAX_AMENDS)) {
154
168
  bad(`gateAmends must map each gate to an integer from 0 to ${GATE_MAX_AMENDS}`);
155
169
  }
@@ -236,13 +250,14 @@ export function countSpecTasks(text) {
236
250
  return count;
237
251
  }
238
252
 
239
- export function initFactory({ title, requirement, factory, input = null }) {
253
+ export function initFactory({ title, requirement, factory, input = null, now = null }) {
240
254
  return {
241
255
  v: 1, title, requirement, input, factory, stage: factory.start,
242
256
  status: 'running', awaiting: null, reason: null,
243
257
  counters: {}, transitions: 0, runTransitions: 0, runCeiling: FACTORY_MAX_TRANSITIONS, taskHigh: 0, taskCount: null,
244
258
  lane: null, tasks: null, carry: null, launched: null,
245
259
  history: [], gateAmends: {},
260
+ ...(now ? { started: now } : {}),
246
261
  };
247
262
  }
248
263
 
@@ -361,13 +376,16 @@ export function unquotePath(p) {
361
376
  * with `taskCount` (a stage that wrote a spec), `carry` (the reason the next stage — above all a
362
377
  * re-entered loop — must hear). `loopTemplate` is the graph name in the LOOP.md the CLI read,
363
378
  * `head` the HEAD commit now, `loopInitAt` the registry row's last `loop init` time for this
364
- * worktree, or null (R2). Every refusal throws before the state changes.
379
+ * worktree, or null (R2). `now` is the ISO time stamped on the history entry as `at`, and `tokens`
380
+ * the count the host reported for the stage's agent (D2, D3); both are left out when null.
381
+ * Every refusal throws before the state changes.
365
382
  */
366
383
  export function recordStage(state, { bricks }, outcome, {
367
384
  porcelain = null, specPath = null, taskCount = null, carry = null, loopStatus = null,
368
- loopTemplate = null, head = null, loopInitAt = null,
385
+ loopTemplate = null, head = null, loopInitAt = null, now = null, tokens = null,
369
386
  } = {}) {
370
387
  assertRunning(state);
388
+ if (tokens !== null && !tokenCount(tokens)) throw new Error('--tokens must be a positive integer: the count the host reported, never an estimate');
371
389
  assertNoLoop(loopStatus);
372
390
  const from = state.stage;
373
391
  const outcomes = stageOutcomes(from, bricks);
@@ -440,6 +458,7 @@ export function recordStage(state, { bricks }, outcome, {
440
458
  state.carry = carry || null;
441
459
  state.history.push({
442
460
  stage: from, outcome, task: taskNo(state), ...(carry ? { carry } : {}),
461
+ ...(tokens !== null ? { tokens } : {}), ...(now ? { at: now } : {}),
443
462
  });
444
463
  const brick = isLoop ? null : bricks.get(from);
445
464
  if (brick?.gate === 'human' && (!brick.gateOn || brick.gateOn.includes(outcome))) {
@@ -487,16 +506,16 @@ function transition(state, from, edge, bricks) {
487
506
  /**
488
507
  * The answer to a held `gate: human` stage (D14: the loop engine's gate and verdicts, reused).
489
508
  * `ok` follows the held edge; `no` stops; `amend` re-runs the stage with the note as its `carry`,
490
- * `GATE_MAX_AMENDS` times per stage per task.
509
+ * `GATE_MAX_AMENDS` times per stage per task. `now` is stamped on the history entry as `at` (D2).
491
510
  */
492
- export function decideFactory(state, { bricks }, verdict, note = '') {
511
+ export function decideFactory(state, { bricks }, verdict, note = '', { now = null } = {}) {
493
512
  if (state.status !== 'awaiting') throw new Error('nothing is awaiting a decision');
494
513
  if (!['ok', 'no', 'amend'].includes(verdict)) throw new Error(`verdict must be ok, no or amend, not ${JSON.stringify(verdict)}`);
495
514
  const { stage, outcome } = state.awaiting;
496
515
  const edge = edgeFor(state.factory, stage, outcome) ?? { from: stage, on: outcome, to: '$stop' };
497
516
  if (verdict === 'ok') assertLane(state, edge);
498
517
  state.awaiting = null; state.status = 'running';
499
- state.history.push({ stage, verdict, task: taskNo(state), ...(note ? { note } : {}) });
518
+ state.history.push({ stage, verdict, task: taskNo(state), ...(note ? { note } : {}), ...(now ? { at: now } : {}) });
500
519
  if (verdict === 'no') return stop(state, `gate rejected at ${stage}${note ? `: ${note}` : ''}`);
501
520
  if (verdict === 'amend') {
502
521
  const key = `${stage}@${taskNo(state)}`;
@@ -219,13 +219,38 @@ function runtimeFloorLine(root) {
219
219
  return pkg && typeof pkg === 'object' && !Array.isArray(pkg) && pkg.engines === undefined ? FLOOR_LINE : null;
220
220
  }
221
221
 
222
+ // ---- rules preamble twin: BEGIN — adapters/opencode/plugins/geneseed-context.js carries everything
223
+ // down to the END marker verbatim, with `export ` dropped (node tests/twins.mjs --write keeps it).
224
+
225
+ /**
226
+ * SHA-256 of the `user-rules.md` seed with its trailing newlines trimmed: the explanation every
227
+ * rules file starts with, until its owner edits it. Hashed, not imported, for `SEED_SHA256`'s
228
+ * reason; tests/unit/claude.test.mjs derives it from `SESSION_SEEDS`.
229
+ */
230
+ export const RULES_PREAMBLE_SHA256 = 'd6973e837c9bf25b50ce068832ceef0a5e5ed2b5931c2c488428ad68aad758c3';
231
+ // A rule's heading, at column 0: the seed's own example (` ## R1 — …`) is indented.
232
+ const RULE_HEADING_RE = /^## R\d+\b/m;
233
+
234
+ /**
235
+ * `text` from its first rule on, when the text above that rule is still the seed's, byte for byte
236
+ * once CRLF is folded: the seed explains the file to its owner, and it cost 1 331 of 4 474
237
+ * characters at every session and sub-agent start. Any prose the owner wrote above the rules stays.
238
+ */
239
+ export function withoutRulesPreamble(text) {
240
+ const rule = RULE_HEADING_RE.exec(text);
241
+ const head = rule ? text.slice(0, rule.index).replace(/\n+$/, '') : null;
242
+ return head !== null && createHash('sha256').update(head).digest('hex') === RULES_PREAMBLE_SHA256
243
+ ? text.slice(rule.index) : text;
244
+ }
245
+ // ---- rules preamble twin: END
246
+
222
247
  /** A session file's text, CRLF-folded and trimmed; null when missing, unreadable or still its seed. */
223
248
  function sessionText(abs) {
224
249
  if (!isFile(abs)) return null;
225
250
  let text;
226
251
  try { text = readFileSync(abs, 'utf8').replace(/\r\n/g, '\n'); } catch { return null; }
227
252
  if (SEED_SHA256.has(createHash('sha256').update(text).digest('hex'))) return null;
228
- return text.replace(/\n+$/, '');
253
+ return withoutRulesPreamble(text).replace(/\n+$/, '');
229
254
  }
230
255
 
231
256
  /** The machine tier's copy of a session file; null for what stays per host (the notebook). */
@@ -182,8 +182,37 @@ export function weakenedBy(pairs) {
182
182
  }
183
183
  // ---- test-weakening twin: END
184
184
 
185
- // One Roo-style `apply_diff` block: its SEARCH half, then its REPLACE half.
186
- export const DIFF_BLOCK_RE = /<<<<<<< SEARCH\r?\n(?::start_line:\s*\d+\r?\n)?(?:-------\r?\n)?([\s\S]*?)\r?\n?=======\r?\n([\s\S]*?)\r?\n?>>>>>>> REPLACE/g;
185
+ /**
186
+ * The Roo-style `apply_diff` blocks of `diff` as `[search, replace]` pairs: what
187
+ * `/<<<<<<< SEARCH\r?\n(?::start_line:\s*\d+\r?\n)?(?:-------\r?\n)?([\s\S]*?)\r?\n?=======\r?\n([\s\S]*?)\r?\n?>>>>>>> REPLACE/g`
188
+ * matched, read in one pass. That regex, on blocks opened and never closed, retried every later
189
+ * separator from every opening: 32 KB took 4.7 s and 256 KB ran past 120 s, past Bob's hook
190
+ * timeout, so the secrets gate never judged the call. Each half ends at the FIRST separator after
191
+ * it, as the lazy groups did; a block with no closing after its first separator has none after any
192
+ * later one either, so the scan stops there, where the regex would have found nothing more.
193
+ */
194
+ export function diffBlocks(diff) {
195
+ const at = (re, from) => { re.lastIndex = from; return re.exec(diff); };
196
+ const OPEN = /<<<<<<< SEARCH\r?\n/g;
197
+ const LINE = /:start_line:\s*\d+\r?\n/y;
198
+ const DASH = /-------\r?\n/y;
199
+ const SEP = /\r?\n?=======\r?\n/g;
200
+ const CLOSE = /\r?\n?>>>>>>> REPLACE/g;
201
+ const pairs = [];
202
+ for (let pos = 0, open; (open = at(OPEN, pos));) {
203
+ let start = open.index + open[0].length;
204
+ const line = at(LINE, start);
205
+ if (line) start += line[0].length;
206
+ const dash = at(DASH, start);
207
+ if (dash) start += dash[0].length;
208
+ const sep = at(SEP, start);
209
+ const close = sep && at(CLOSE, sep.index + sep[0].length);
210
+ if (!close) break;
211
+ pairs.push([diff.slice(start, sep.index), diff.slice(sep.index + sep[0].length, close.index)]);
212
+ pos = close.index + close[0].length;
213
+ }
214
+ return pairs;
215
+ }
187
216
 
188
217
  /**
189
218
  * A write tool's input as `[old, new]` pairs for `weakenedBy`. `whole` is the file before a
@@ -200,7 +229,7 @@ export function editPairs(ti, whole = '') {
200
229
  for (const e of Array.isArray(ti.edits) ? ti.edits : []) {
201
230
  if (e && typeof e.new_string === 'string') pairs.push([text(e.old_string), e.new_string]);
202
231
  }
203
- if (typeof ti.diff === 'string') for (const m of ti.diff.matchAll(DIFF_BLOCK_RE)) pairs.push([m[1], m[2]]);
232
+ if (typeof ti.diff === 'string') pairs.push(...diffBlocks(ti.diff));
204
233
  return pairs;
205
234
  }
206
235
 
@@ -474,6 +503,26 @@ export function gateLoss(reason) {
474
503
  }
475
504
  // ---- gate text twin: END
476
505
 
506
+ /**
507
+ * The `permissionDecision: "ask"` document, in Python's compact `json.dumps` spelling: `, ` and
508
+ * `: ` separators, and `ensure_ascii` — every code unit past `~` as a lowercase `\uXXXX`, which is
509
+ * why a reason's em dash reaches stdout as `—`.
510
+ *
511
+ * A TEMPLATE, NOT `js/lib/json.mjs`'s `jsonDumpsCompact`. The keys are fixed and the one value
512
+ * is a string, so the general serializer bought nothing here — and it cost every tool call a
513
+ * 378-line module parse, being the only thing on the gate path that needed it.
514
+ * `tests/unit/hook_gates.test.mjs` holds the two byte-identical over non-ASCII reasons.
515
+ */
516
+ export function askDecision(reason) { return decisionDoc('ask', reason); }
517
+
518
+ export function decisionDoc(decision, reason) {
519
+ return `{"hookSpecificOutput": {"hookEventName": "PreToolUse", "permissionDecision": "${decision}", `
520
+ + `"permissionDecisionReason": ${asciiJson(reason)}}}\n`;
521
+ }
522
+
523
+ export const asciiJson = (s) => JSON.stringify(s)
524
+ .replace(/[\u007f-￿]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, '0')}`);
525
+
477
526
  const OFF = ['off', '0', 'false', 'no'];
478
527
 
479
528
  /**
@@ -67,8 +67,8 @@ import {
67
67
  } from './gitref.mjs';
68
68
  import { LOSS_CANDIDATE_RE, catastrophic, lossReason, stripStructure } from './loss.mjs';
69
69
  import {
70
- readStdin, SECRET_RE, DONE_LIST, DIFF_BLOCK_RE, isTestPath, weakenedBy, editPairs,
71
- gateLoss, gateSafe,
70
+ readStdin, SECRET_RE, DONE_LIST, diffBlocks, isTestPath, weakenedBy, editPairs,
71
+ gateLoss, gateSafe, askDecision, decisionDoc, asciiJson,
72
72
  } from './hooks-prims.mjs';
73
73
  import { recordUse } from './usage.mjs';
74
74
  import { WRITE_NAME_RE, ownershipBlock } from './ownership-gate.mjs';
@@ -81,7 +81,20 @@ import { WRITE_NAME_RE, ownershipBlock } from './ownership-gate.mjs';
81
81
  // (`git add . && git commit … && git push`) and `-C <path>` forms, so a compound
82
82
  // one-liner can never slip a commit past the prompt. `[^\n]*` is the boundary: a `git` on
83
83
  // one line and a `commit` on the next are two commands, not one.
84
- const GIT_GATE_RE = /\bgit\b[^\n]*\b(?:commit|push)\b/;
84
+ //
85
+ // LINEAR, ON PURPOSE. The plain `\bgit\b[^\n]*\b(?:commit|push)\b` rescanned to the end of the
86
+ // line from EVERY `git`, so `git -C x ` repeated to 270 KB took 7.8 s here alone, and past the
87
+ // host's hook timeout the call ran unguarded. A match can start only at the input's start or at
88
+ // a `\n` (never `^` with `m`, whose `\r`/`U+2028` line starts would bring the rescan back), and
89
+ // it tries only the line's FIRST `git`: if any `git` on a line precedes a verb, the first one
90
+ // does too, so the truth set is unchanged and each line is read once.
91
+ const GIT_GATE_RE = /(?:^|\n)(?:(?!\bgit\b)[^\n])*\bgit\b[^\n]*\b(?:commit|push)\b/;
92
+
93
+ // Past this many characters a command is not read at all: it asks. Every reader on the path
94
+ // (`shellReading`, the splitters, `catastrophic`) is at least linear, some worse, and a gate
95
+ // that has not finished when the host's hook timeout fires lets the call through unjudged. No
96
+ // real command line comes near it; a generated one that does is worth a human look.
97
+ const MAX_COMMAND_CHARS = 64 * 1024;
85
98
 
86
99
  // Law IV's boundary half lives in `./loss.mjs`: it asks only when a command would really lose
87
100
  // data — a protected branch deleted or force-pushed, an unpushed unmerged branch deleted,
@@ -241,17 +254,8 @@ export function worktreeExempt(command, cwd, agentId) {
241
254
  }
242
255
  }
243
256
 
244
- /**
245
- * The `permissionDecision: "ask"` document, in Python's compact `json.dumps` spelling: `, ` and
246
- * `: ` separators, and `ensure_ascii` — every code unit past `~` as a lowercase `\uXXXX`, which is
247
- * why a reason's em dash reaches stdout as `—`.
248
- *
249
- * A TEMPLATE, NOT `js/lib/json.mjs`'s `jsonDumpsCompact`. The keys are fixed and the one value
250
- * is a string, so the general serializer bought nothing here — and it cost every tool call a
251
- * 378-line module parse, being the only thing on the gate path that needed it.
252
- * `tests/unit/hook_gates.test.mjs` holds the two byte-identical over non-ASCII reasons.
253
- */
254
- export function askDecision(reason) { return decisionDoc('ask', reason); }
257
+ // `askDecision` lives in `./hooks-prims.mjs`, so the entry can ask when THIS module fails to load.
258
+ export { askDecision };
255
259
 
256
260
  /**
257
261
  * The `permissionDecision: "deny"` twin of `askDecision`, same spelling. Claude Code shows an
@@ -261,14 +265,6 @@ export function askDecision(reason) { return decisionDoc('ask', reason); }
261
265
  */
262
266
  export function denyDecision(reason) { return decisionDoc('deny', reason); }
263
267
 
264
- function decisionDoc(decision, reason) {
265
- return `{"hookSpecificOutput": {"hookEventName": "PreToolUse", "permissionDecision": "${decision}", `
266
- + `"permissionDecisionReason": ${asciiJson(reason)}}}\n`;
267
- }
268
-
269
- const asciiJson = (s) => JSON.stringify(s)
270
- .replace(/[\u007f-￿]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, '0')}`);
271
-
272
268
  /**
273
269
  * A note to the MODEL that decides nothing: PreToolUse `additionalContext` with no
274
270
  * `permissionDecision` defers, and the host puts the text next to the tool result (hooks.md,
@@ -901,9 +897,16 @@ function consentBenign(command) {
901
897
  return true;
902
898
  }
903
899
 
904
- function gitDecide(args, payload) {
900
+ // Exported for the in-process timing rows (tests/unit/hook_gates.test.mjs): a spawn's own start-up
901
+ // on a loaded Windows host is noise next to a 200 ms bound.
902
+ export function gitDecide(args, payload) {
905
903
  const ti = (payload && payload.tool_input) || {};
906
904
  if (typeof ti.command !== 'string') return 0;
905
+ // Before any switch: the catastrophic class below runs whatever the install turned off, so
906
+ // every gate verb reads the command. `unverified` under law-4, so Bob refuses it as well.
907
+ if (ti.command.length > MAX_COMMAND_CHARS) {
908
+ return ask(args, 'git-gate', 'law-4', 'unverified', {});
909
+ }
907
910
  const tool = payload && payload.tool_name;
908
911
  const command = shellReading(ti.command, tool === 'Bash' ? 'bash' : tool === 'PowerShell' ? 'powershell' : null);
909
912
  // The agent's own words, for the asks where they are no conflict of interest (`gateText`'s `quote`).
@@ -1173,9 +1176,9 @@ function settingsAfter(before, payload) {
1173
1176
  return ranged ? null : replaceOnce(before, ti.search, ti.replace);
1174
1177
  }
1175
1178
  if (tool === 'apply_diff' && typeof ti.diff === 'string') {
1176
- const blocks = [...ti.diff.matchAll(DIFF_BLOCK_RE)];
1179
+ const blocks = diffBlocks(ti.diff);
1177
1180
  let text = before;
1178
- for (const [, search, replace] of blocks) if ((text = replaceOnce(text, search, replace)) === null) return null;
1181
+ for (const [search, replace] of blocks) if ((text = replaceOnce(text, search, replace)) === null) return null;
1179
1182
  // One block only: with several, Bob may apply some and refuse others (its start-line window).
1180
1183
  return blocks.length === 1 ? text : null;
1181
1184
  }
@@ -1230,8 +1233,8 @@ const ASK_COUNT_MAX = 1024 * 1024;
1230
1233
  * The `editPairs` of a write the gate will ask about, for the line count, or undefined for none. Run
1231
1234
  * only then, because `Write`'s old text is a file read. A pair says nothing of how often it applies,
1232
1235
  * so a `replace_all` and a `search_and_replace` count nothing, and a notebook cell names no old text.
1233
- * A `diff` counts nothing either: the agent writes it, and `DIFF_BLOCK_RE` took 20 s on 80 KB of
1234
- * opened blocks. A count must cost no verdict, so whatever is not a small regular file, or cannot be
1236
+ * A `diff` counts nothing either: the agent writes it, and the regex `diffBlocks` replaced took 20 s
1237
+ * on 80 KB of opened blocks. A count must cost no verdict, so whatever is not a small regular file, or cannot be
1235
1238
  * read, counts nothing. Only a file that is truly absent is a new file.
1236
1239
  */
1237
1240
  function askPairs(payload, p) {
@@ -1336,21 +1339,39 @@ function ruleGate(args) {
1336
1339
 
1337
1340
  // The REPLACE halves of a Roo-style `apply_diff` (`<<<<<<< SEARCH … ======= <new> >>>>>>> REPLACE`).
1338
1341
  // A diff without those markers is a shape we do not know, so it is returned whole: fail closed.
1342
+ // One pass: each half runs from a separator line to the FIRST closing line after it, as the lazy
1343
+ // `/^=======\r?\n([\s\S]*?)^>>>>>>> REPLACE/gm` did, and a separator with no closing after it ends
1344
+ // the scan, where that regex rescanned the rest of the diff once per separator.
1339
1345
  function diffReplaced(diff) {
1340
1346
  if (typeof diff !== 'string') return diff;
1341
- const halves = [...diff.matchAll(/^=======\r?\n([\s\S]*?)^>>>>>>> REPLACE/gm)].map((m) => m[1]);
1347
+ const SEP = /^=======\r?\n/gm;
1348
+ const CLOSE = /^>>>>>>> REPLACE/gm;
1349
+ const halves = [];
1350
+ for (let sep; (sep = SEP.exec(diff));) {
1351
+ CLOSE.lastIndex = sep.index + sep[0].length;
1352
+ const close = CLOSE.exec(diff);
1353
+ if (!close) break;
1354
+ halves.push(diff.slice(sep.index + sep[0].length, close.index));
1355
+ SEP.lastIndex = CLOSE.lastIndex;
1356
+ }
1342
1357
  return halves.length ? halves.join('\n') : diff;
1343
1358
  }
1344
1359
 
1345
1360
  const RULE_PATH_KEYS = ['file_path', 'path', 'notebook_path', 'target_file', 'target', 'file', 'filename', 'destination', 'dest',
1346
1361
  'new_path', 'new_name', 'old_path', 'source', 'from', 'to'];
1347
- function ruleDecide(args, payload) {
1362
+ // Exported for the in-process timing rows, as `gitDecide` is.
1363
+ export function ruleDecide(args, payload) {
1348
1364
  const ti = (payload && payload.tool_input) || {};
1349
1365
  // NotebookEdit names its target `notebook_path`; the settings matcher routes it here too. Every
1350
1366
  // key is read, never the first found: Bob's move and rename tools carry two, and a harmless
1351
1367
  // `path` beside the real target must not hide it from any gate below.
1352
1368
  const paths = [...new Set(RULE_PATH_KEYS.map((k) => ti[k]).filter((v) => typeof v === 'string' && v))];
1353
1369
  if (!paths.length) return 0;
1370
+ // A diff past the command bound is not read, for `MAX_COMMAND_CHARS`' reason: on Bob a scan past
1371
+ // the hook timeout lets the write through with no secrets check. Same `unverified` ask, law-4.
1372
+ if (typeof ti.diff === 'string' && ti.diff.length > MAX_COMMAND_CHARS) {
1373
+ return ask(args, 'rule-gate', 'law-4', 'unverified', {});
1374
+ }
1354
1375
  // Write carries `content`, Edit `new_string`, NotebookEdit `new_source`, MultiEdit an
1355
1376
  // `edits[]` of `new_string`s — every one can plant a credential, so every one is scanned.
1356
1377
  // MultiEdit is no longer in Claude Code's own tool table (tools-reference.md) or the
package/js/hosts/loss.mjs CHANGED
@@ -64,9 +64,14 @@ import { currentBranch, gitRootOf, protectedBranches, stashExists } from './gitr
64
64
  * a spawn. A git destructive VERB anywhere after `git` on the same line, or a removal program
65
65
  * as a word at a command boundary. Deliberately loose — the parse decides; this only has to be
66
66
  * a superset of what the parse acts on.
67
+ *
68
+ * The git half is LINEAR: it starts only at the input's start or a `\n` and tries the line's
69
+ * first `git` alone, which matches whenever any later `git` would. `\bgit\b[^\n]*\b(?:…)` from
70
+ * every `git` was quadratic: a 270 KB `git -C x …` took seconds, and a hook past its timeout
71
+ * lets the call through. `(?<![\s\S])`, not `^`: under `m`, `^` also starts after `\r`.
67
72
  */
68
73
  export const LOSS_CANDIDATE_RE =
69
- /\bgit\b[^\n]*\b(?:reset|clean|branch|checkout|switch|restore|stash|reflog|gc|push)\b|(?:^|[\s;&|("'`])(?:rm|rmdir|unlink|del|erase|remove-item|ri|rd)(?:\.exe)?(?=[\s;&|)"'`]|$)|(?:^|\s)-delete(?=\s|$)/im;
74
+ /(?:(?<![\s\S])|\n)(?:(?!\bgit\b)[^\n])*\bgit\b[^\n]*\b(?:reset|clean|branch|checkout|switch|restore|stash|reflog|gc|push)\b|(?:^|[\s;&|("'`])(?:rm|rmdir|unlink|del|erase|remove-item|ri|rd)(?:\.exe)?(?=[\s;&|)"'`]|$)|(?:^|\s)-delete(?=\s|$)/im;
70
75
 
71
76
  class Unverified extends Error {}
72
77
  const unverified = (why) => { throw new Unverified(why); };
@@ -46,6 +46,7 @@ import {
46
46
  readJsonMaybe, readMaybe, renderedTier, themeOfDir,
47
47
  } from '../hosts/installs.mjs';
48
48
  import { hashesOf, ownedState, safeLeaf } from '../hosts/owned.mjs';
49
+ import { hostGlobalInstalls as globalInstalls } from './excludes.mjs';
49
50
  import { unifiedDiff, splitLines } from '../lib/udiff.mjs';
50
51
  import { printOut, printErr, readText, writeText, isFile } from '../lib/fs.mjs';
51
52
  import { NOTES_DIRS, sharedPaths } from '../lib/machine-dir.mjs';
@@ -527,7 +528,21 @@ export function flushExportNotes() {
527
528
  }
528
529
 
529
530
  export function cmdDiff(args) {
530
- const { target, theme, files } = diffCollect({ target: args.target, theme: args.theme });
531
+ // No `--target`: the global install there is, whatever its host — the OpenCode dir used to be
532
+ // the answer on a Claude-only machine too. Several: the first, named on stderr. None: the
533
+ // OpenCode dir, whose refusal below says what to do. Here and not in `diffCollect`, whose
534
+ // other caller (`upgrade`'s export) keeps its own default.
535
+ let chosen = args.target;
536
+ if (!chosen) {
537
+ const globals = globalInstalls((_h, d) => existsSync(path.join(d, GLOBAL_MANIFEST))
538
+ && manifestScope(d) !== 'project');
539
+ if (globals.length) chosen = globals[0][1];
540
+ if (globals.length > 1) {
541
+ printErr(`[diff] ${globals.length} global installs found; diffing ${globals[0][1]} `
542
+ + `(${globals[0][0]}:global). Pass --target for another.\n`);
543
+ }
544
+ }
545
+ const { target, theme, files } = diffCollect({ target: chosen, theme: args.theme });
531
546
  if (files === null) {
532
547
  if (existsSync(path.join(target, GLOBAL_MANIFEST)) && manifestScope(target) === 'project') {
533
548
  printErr(`[diff] ${target} is a PROJECT install — diff only compares GLOBAL `
@@ -38,7 +38,7 @@ import {
38
38
  hookShellProblems, installedDefaults, openclaudeDualHarnessRoots, themeFiles,
39
39
  } from '../hosts/installs.mjs';
40
40
  import { validateIsVendored } from '../hosts/native.mjs';
41
- import { printOut } from '../lib/fs.mjs';
41
+ import { printErr, printOut } from '../lib/fs.mjs';
42
42
  import { authoringProblems, factoryProblems, loopProblems } from './checks-authoring.mjs';
43
43
  import { gateProbe, guardProbe } from './checks-probe.mjs';
44
44
  import {
@@ -189,7 +189,7 @@ export function claudeBobEmitProblems(themeName) {
189
189
  */
190
190
  export function doctorCollect({
191
191
  theme = null, allThemes = false, bundle = null, noBundle = false, groups = null,
192
- probe = false, probed = null, extraProbeProblems = [],
192
+ probe = false, probed = null, extraProbeProblems = [], onTheme = null,
193
193
  } = {}) {
194
194
  const available = themeFiles().map(stemOf);
195
195
  if (!available.length) return [[], ['[doctor] no themes found']];
@@ -217,7 +217,9 @@ export function doctorCollect({
217
217
  if (probeRun && probed) probed.push(...probeRun.probed);
218
218
  let problems = [];
219
219
  withTempDir((tmp) => {
220
- for (const themeName of themes) {
220
+ for (const [i, themeName] of themes.entries()) {
221
+ // A sweep of several themes runs for minutes; the caller may say where it is.
222
+ if (onTheme && themes.length > 1) onTheme(i + 1, themes.length, themeName);
221
223
  const out = path.join(tmp, themeName);
222
224
  // capture_output=True: BOTH streams, unlike the emits below, which redirect stdout
223
225
  // only. A failing build's stderr is not doctor's output either — the return code is.
@@ -302,6 +304,8 @@ function doctorReport(args, guard) {
302
304
  theme: args.theme, allThemes: Boolean(args.all), bundle: args.bundle,
303
305
  noBundle: Boolean(args.noBundle), probe: Boolean(args.probe), probed,
304
306
  extraProbeProblems: guard ? guard.problems : [],
307
+ // stderr, so the verdict on stdout is the bytes it was; `--all` took ~2 min 40 s in silence.
308
+ onTheme: (n, total, name) => printErr(`[doctor] theme ${n}/${total}: ${name}\n`),
305
309
  });
306
310
  if (!themes.length) {
307
311
  printOut(`${collected.length ? collected[0] : '[doctor] no themes found'}\n`);