geneseed 5.3.1 → 5.4.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 (161) hide show
  1. package/CHANGELOG.md +68 -0
  2. package/README.md +21 -18
  3. package/SHIPPED.md +7 -7
  4. package/adapters/opencode/README.md +3 -2
  5. package/adapters/opencode/plugins/geneseed-context.js +6 -0
  6. package/adapters/opencode/plugins/geneseed-guard.js +5 -3
  7. package/bin/geneseed-cli.mjs +7 -0
  8. package/bin/geneseed-hook.mjs +3 -3
  9. package/docs/PRD.md +1 -1
  10. package/docs/README.md +1 -0
  11. package/docs/concepts/agents.md +1 -1
  12. package/docs/concepts/collaboration.md +2 -2
  13. package/docs/concepts/enforcement-table.md +5 -2
  14. package/docs/concepts/exclusions.md +16 -2
  15. package/docs/concepts/footprint.md +1 -1
  16. package/docs/concepts/foreman-mode.md +1 -1
  17. package/docs/concepts/hook-gates.md +3 -3
  18. package/docs/concepts/hooks.md +4 -3
  19. package/docs/concepts/host-matrix.md +2 -2
  20. package/docs/concepts/kits.md +12 -2
  21. package/docs/concepts/loop-bricks.md +3 -3
  22. package/docs/concepts/loops.md +6 -4
  23. package/docs/concepts/ownership.md +1 -1
  24. package/docs/concepts/rules.md +2 -2
  25. package/docs/concepts/skills.md +1 -1
  26. package/docs/extending.md +63 -28
  27. package/docs/guides/auto-merge.md +100 -0
  28. package/docs/guides/choose-your-setup.md +1 -1
  29. package/docs/guides/headless.md +1 -1
  30. package/docs/guides/install-clone.md +1 -1
  31. package/docs/guides/install.md +1 -1
  32. package/docs/guides/loop-finish.md +3 -3
  33. package/docs/guides/loop-running.md +4 -4
  34. package/docs/guides/project-context.md +1 -1
  35. package/docs/guides/run-a-factory.md +2 -2
  36. package/docs/guides/setup-doctrines.md +2 -2
  37. package/docs/guides/setup-footprint.md +1 -1
  38. package/docs/guides/uninstall.md +3 -3
  39. package/docs/guides/upgrade.md +1 -1
  40. package/docs/guides/worktree.md +1 -1
  41. package/docs/reference/environment.md +4 -2
  42. package/docs/reference/plugin-activity.md +1 -1
  43. package/docs/reference/plugin-guard.md +1 -1
  44. package/docs/reference/plugin-learn.md +1 -1
  45. package/docs/reference/plugin-workflow.md +1 -1
  46. package/docs/reference/troubleshoot-doctor.md +1 -1
  47. package/docs/reference/troubleshoot-hooks.md +2 -2
  48. package/docs/reference/troubleshoot-install.md +3 -3
  49. package/docs/reference/troubleshoot-tools.md +1 -1
  50. package/docs/token-footprint.md +2 -2
  51. package/docs/understand/enforced-vs-asked.md +1 -1
  52. package/docs/understand/machine-claude.md +2 -2
  53. package/docs/understand/on-your-machine.md +1 -1
  54. package/docs/web-ui.md +5 -5
  55. package/harness.config.json +1 -1
  56. package/js/README.md +2 -1
  57. package/js/build/args.mjs +12 -1
  58. package/js/build/driver.mjs +33 -6
  59. package/js/build/emit-claude.mjs +8 -4
  60. package/js/build/emit-opencode.mjs +13 -9
  61. package/js/build/generate.mjs +10 -156
  62. package/js/build/profile.mjs +318 -0
  63. package/js/build/render.mjs +81 -3
  64. package/js/build/retired-skills.mjs +60 -13
  65. package/js/build/source.mjs +15 -1
  66. package/js/build/stubs.mjs +4 -1
  67. package/js/cli-table.json +48 -3
  68. package/js/hosts/hooks-done.mjs +345 -55
  69. package/js/hosts/hooks-learn.mjs +4 -3
  70. package/js/hosts/hooks-prims.mjs +5 -3
  71. package/js/hosts/hooks.mjs +153 -6
  72. package/js/hosts/installs.mjs +19 -1
  73. package/js/hosts/native.mjs +19 -2
  74. package/js/hosts/settings.mjs +29 -3
  75. package/js/inspect/checks-constitution.mjs +32 -0
  76. package/js/inspect/diff.mjs +21 -3
  77. package/js/inspect/inventory.mjs +1 -1
  78. package/js/maintain/setup.mjs +5 -1
  79. package/js/maintain/update.mjs +4 -2
  80. package/js/web/actions.mjs +16 -3
  81. package/js/web/api.mjs +7 -2
  82. package/package.json +1 -1
  83. package/registry.json +14 -0
  84. package/src/AGENT.md.tmpl +15 -17
  85. package/src/bricks/pr-open.md +3 -2
  86. package/src/doctrines/ops.md +2 -2
  87. package/src/doctrines/process.md +40 -36
  88. package/src/factories/analysis-to-build.json +1 -1
  89. package/src/factories/bug-report-to-fix.json +1 -1
  90. package/src/factories/issue-to-pr.json +1 -1
  91. package/src/kits/terminal-tools/rules.md +10 -0
  92. package/src/kits/terminal-tools.json +13 -0
  93. package/src/licenses/herdr.txt +201 -0
  94. package/src/modes/foreman.md +6 -3
  95. package/src/skills/_self-improvement.md +9 -7
  96. package/src/skills/commit.md +17 -17
  97. package/src/skills/debug/ci.md +1 -1
  98. package/src/skills/dependencies.md +3 -3
  99. package/src/skills/document-project.md +3 -2
  100. package/src/skills/factory.md +13 -4
  101. package/src/skills/geneseed.md +4 -2
  102. package/src/skills/git-history.md +5 -7
  103. package/src/skills/herdr.md +135 -0
  104. package/src/skills/loop.md +3 -2
  105. package/src/skills/opencode-cli.md +84 -0
  106. package/src/skills/pipeline.md +1 -1
  107. package/src/skills/release.md +5 -8
  108. package/src/skills/review-response.md +4 -2
  109. package/src/skills/rule.md +27 -1
  110. package/src/skills/ship.md +54 -7
  111. package/src/skills/worktree.md +2 -2
  112. package/src/upstreams.json +7 -0
  113. package/themes/_TEMPLATE.json +2 -0
  114. package/themes/biker.json +2 -0
  115. package/themes/commentator.json +2 -0
  116. package/themes/cyberpunk.json +2 -0
  117. package/themes/gamer.json +2 -0
  118. package/themes/imperial.json +2 -0
  119. package/themes/joker.json +2 -0
  120. package/themes/marvin.json +2 -0
  121. package/themes/mean.json +2 -0
  122. package/themes/military.json +2 -0
  123. package/themes/neutral.json +2 -0
  124. package/themes/pirate.json +2 -0
  125. package/themes/sports.json +2 -0
  126. package/themes/verstappen.json +2 -0
  127. package/themes/wizard.json +2 -0
  128. package/web/dist/assets/Activity-D2kOc3yi.js +1 -0
  129. package/web/dist/assets/ActivityDetail-By3xOr21.js +1 -0
  130. package/web/dist/assets/{Bonsai-BBl4XXqs.js → Bonsai-CBWDTBA4.js} +1 -1
  131. package/web/dist/assets/{CopyButton-Beven8yn.js → CopyButton-BVbpriMB.js} +1 -1
  132. package/web/dist/assets/Dashboard-CIJLPHM9.js +2 -0
  133. package/web/dist/assets/Docs-CiRRIELs.js +5 -0
  134. package/web/dist/assets/Factories-DhyK0O8d.js +1 -0
  135. package/web/dist/assets/{GreenhouseView-Bce212qd.js → GreenhouseView-DW3PgTPy.js} +1 -1
  136. package/web/dist/assets/Installs-B6nlo-Ly.js +3 -0
  137. package/web/dist/assets/{JournalView-CV4omyww.js → JournalView-O65qEWfp.js} +1 -1
  138. package/web/dist/assets/Kits-C5U-yT6Z.js +1 -0
  139. package/web/dist/assets/Laws-CuTw_XNf.js +4 -0
  140. package/web/dist/assets/{LibRows-Dag1s0ZX.js → LibRows-D6-CVa3K.js} +1 -1
  141. package/web/dist/assets/Library-CzPlerd6.js +3 -0
  142. package/web/dist/assets/Loops-CqNF_-nS.js +2 -0
  143. package/web/dist/assets/{OperatorHudView-JmYY1pBR.js → OperatorHudView-BNr8K5qj.js} +1 -1
  144. package/web/dist/assets/Personal-DeDb9e8O.js +2 -0
  145. package/web/dist/assets/Settings-B8MPN_AD.js +1 -0
  146. package/web/dist/assets/{Tabs-8zsyEPSK.js → Tabs-DJzAez4h.js} +1 -1
  147. package/web/dist/assets/index-BL3P-9Rg.js +6 -0
  148. package/web/dist/index.html +1 -1
  149. package/web/dist/assets/Activity-WQ3ykgxU.js +0 -1
  150. package/web/dist/assets/ActivityDetail-7rt04SkS.js +0 -1
  151. package/web/dist/assets/Dashboard-BgLArtgu.js +0 -2
  152. package/web/dist/assets/Docs-B5aHp86J.js +0 -5
  153. package/web/dist/assets/Factories-BjqzXAw8.js +0 -1
  154. package/web/dist/assets/Installs-B1OsrHXF.js +0 -3
  155. package/web/dist/assets/Kits-CW1e7xNa.js +0 -1
  156. package/web/dist/assets/Laws-1Ckf1lbs.js +0 -4
  157. package/web/dist/assets/Library-B3FuFLel.js +0 -3
  158. package/web/dist/assets/Loops-CwqgnLNw.js +0 -2
  159. package/web/dist/assets/Personal-DKLgLa7Z.js +0 -2
  160. package/web/dist/assets/Settings-BwErnh-R.js +0 -1
  161. package/web/dist/assets/index-Ce6qF2nG.js +0 -6
package/js/cli-table.json CHANGED
@@ -67,7 +67,7 @@
67
67
  {
68
68
  "name": "build",
69
69
  "help": "render the harness with the generator's flags (dry run: geneseed validate)",
70
- "description": "render the harness (same flags as geneseed-build; an omitted flag takes the generator default, not the install's — see geneseed status --json for an install's own; dry run: geneseed validate)",
70
+ "description": "render the harness (same flags as geneseed-build; an omitted flag takes the generator default, not the install's, so a build over an existing install that would change a setting it was not given refuses and prints the install's own rebuild command, as geneseed status --json shows it — --reset accepts the defaults; dry run: geneseed validate)",
71
71
  "positionals": [],
72
72
  "options": [
73
73
  {
@@ -370,6 +370,21 @@
370
370
  "type": null,
371
371
  "hidden": false
372
372
  },
373
+ {
374
+ "names": [
375
+ "--strict-consent"
376
+ ],
377
+ "dest": "strict_consent",
378
+ "metavar": null,
379
+ "help": "Consent Before Push asks for every git commit and push, own branch included (records `Own-branch pass: off`); default: only the main branch asks",
380
+ "choices": null,
381
+ "default": false,
382
+ "required": false,
383
+ "nargs": "0",
384
+ "is_flag": true,
385
+ "type": null,
386
+ "hidden": false
387
+ },
373
388
  {
374
389
  "names": [
375
390
  "--prune-gates"
@@ -399,6 +414,21 @@
399
414
  "is_flag": true,
400
415
  "type": null,
401
416
  "hidden": false
417
+ },
418
+ {
419
+ "names": [
420
+ "--reset"
421
+ ],
422
+ "dest": "reset",
423
+ "metavar": null,
424
+ "help": "for this one build, return every setting this build does not pass to its default on the install it targets. Without it, a build over an existing install that would change a setting it was not given refuses, lists each change and prints the command that keeps them (the install's own rebuild, as geneseed status --json shows it). Not recorded",
425
+ "choices": null,
426
+ "default": false,
427
+ "required": false,
428
+ "nargs": "0",
429
+ "is_flag": true,
430
+ "type": null,
431
+ "hidden": false
402
432
  }
403
433
  ],
404
434
  "mutex": []
@@ -955,7 +985,7 @@
955
985
  },
956
986
  {
957
987
  "name": "git-gate",
958
- "help": "PreToolUse hook: ASK before a history-discarding git act (Deletion Is Deliberate), a recursive scan of a whole filesystem (Commands Must Return) and every git commit/push (Consent Before Push backstop)",
988
+ "help": "PreToolUse hook: ASK before a history-discarding git act (Deletion Is Deliberate), a recursive scan of a whole filesystem (Commands Must Return) and a git commit or push onto the main branch (Consent Before Push backstop)",
959
989
  "description": "",
960
990
  "positionals": [],
961
991
  "options": [
@@ -995,7 +1025,22 @@
995
1025
  ],
996
1026
  "dest": "no_consent",
997
1027
  "metavar": null,
998
- "help": "skip the Consent Before Push commit/push ask (set by the emit when the process pack or that rule is off); Deletion Is Deliberate still asks",
1028
+ "help": "skip the Consent Before Push main-branch commit/push ask (set by the emit when the process pack or that rule is off); Deletion Is Deliberate still asks",
1029
+ "choices": null,
1030
+ "default": false,
1031
+ "required": false,
1032
+ "nargs": "0",
1033
+ "is_flag": true,
1034
+ "type": null,
1035
+ "hidden": false
1036
+ },
1037
+ {
1038
+ "names": [
1039
+ "--strict-consent"
1040
+ ],
1041
+ "dest": "strict_consent",
1042
+ "metavar": null,
1043
+ "help": "ask on every git commit and push, own branch included (set by the emit for a strict-consent install); the main-branch ask is the same either way",
999
1044
  "choices": null,
1000
1045
  "default": false,
1001
1046
  "required": false,
@@ -50,16 +50,38 @@
50
50
  * takes the exit code of its last stage: `npm test | tail` exits 0 on a red suite), not MASKED
51
51
  * after it (`|| true`, `; exit 0` — see `runsUnpiped`), and whose
52
52
  * result is not `is_error` — every non-zero exit, denial and timeout carries it (checked on
53
- * 14 000+ real Claude Code results, 2026-10-17).
53
+ * 14 000+ real Claude Code results, 2026-10-17);
54
+ * - a BACKGROUND run (`run_in_background: true`, or moved there after its foreground timeout)
55
+ * is pending, not passed: its result is `is_error` false, with
56
+ * `toolUseResult.backgroundTaskId` set (or, in a sub-agent's transcript, only the host's
57
+ * `BACKGROUNDED` text) — it says the command STARTED. It passes only when a later task notification names its tool-use id with
58
+ * `<status>completed</status>` and `completed (exit code 0)` (`notificationText`); any other
59
+ * status or code leaves it owed. Before this, 76 of 112 accepted passes in 30 days of real
60
+ * transcripts here were launches. The pass is still placed by the CALL: a launch before the
61
+ * last edit proves nothing, even when it completes after it.
54
62
  *
55
- * READ FROM THE END (constant-cost Stop). Only the current turn matters, so the transcript is read
63
+ * READ FROM THE END. Only the current turn matters, so the transcript is read
56
64
  * backward in growing windows (`tailReader`) until the turn's opening prompt is inside one; a
57
65
  * turn longer than every window falls back to the whole file. Never judged on a truncated turn:
58
- * a window without a prompt answers "read more", not "no edit".
66
+ * a window without a prompt answers "read more", not "no edit". A task notification is no prompt:
67
+ * Claude Code writes it as a `type: "user"` line whose text opens `<task-notification>` (4 258
68
+ * such lines in this machine's transcripts, 2026-11), and as a prompt it would open a new turn
69
+ * and hide the edit before it. So a turn now spans every continuation a notification drives, up
70
+ * to the last HUMAN prompt, and so does the cap's count. The cost follows: in a long session that
71
+ * a stream of notifications kept going, `tailReader` may read back that far, up to the whole
72
+ * file, so a Stop's read is no longer constant. It is bounded by the file, never by the session's
73
+ * age alone.
59
74
  *
60
- * At most one block per turn: `stop_hook_active` is true when this Stop follows a block, and the
61
- * gate then lets the turn end and leaves a ledger line, so a gate that cries wolf gets found.
75
+ * THE CAP (`nextBlock`). Counted per CONTINUATION: a task notification since the last block starts
76
+ * a new one. Inside one, a Stop is blocked again only when an edit landed since the last block or
77
+ * an owed check's background verdict changed (pending -> failed), and at most 3 times; a Stop past
78
+ * that ends the turn and leaves a `done-gate-cap` ledger line, so a gate that cries wolf gets
79
+ * found. Over the whole human turn, across continuations, at most 10 blocks (`TURN_BLOCKS`):
80
+ * past it no notification, verdict or edit blocks again until the next human prompt, and the
81
+ * stderr line says the total ceiling was reached. The count lives in a per-session file under the install; without one,
82
+ * `stop_hook_active` (true when this Stop follows a block) ends the turn at once.
62
83
  */
84
+ import { mkdirSync, readdirSync, readFileSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
63
85
  import path from 'node:path';
64
86
  import { printOut as out, printErr as err } from '../lib/fs.mjs';
65
87
  import { within } from '../lib/paths.mjs';
@@ -87,7 +109,9 @@ const SHELL_TOOLS = new Set(['Bash', 'PowerShell']);
87
109
  * Whitespace is collapsed on both sides. shortcut: the shell is not parsed — a prefix such as
88
110
  * `sudo`/`time`/`env X=1`, a subshell, or a `|` inside a quoted argument after the check all read
89
111
  * as "not run", and so does a `||` inside a quoted argument after the check. Every approximation
90
- * above refuses a pass, so the gate errs toward a reminder — with ONE known opening the other way:
112
+ * of the command line above refuses a pass, so the gate errs toward a reminder. That says nothing
113
+ * of the call's mode: a `run_in_background` launch is judged by its completion, not here
114
+ * (`missingChecks`). One known opening the other way remains:
91
115
  * `npm test; npm run lint` passes both, though `;` lets a green lint hide a red test (the line's
92
116
  * exit code is the last command's). Kept so a chained proof line still counts; upgrade by
93
117
  * requiring `&&` between checks if that opening is ever seen in a real transcript.
@@ -140,10 +164,72 @@ export function groupPasses(command, g) {
140
164
  && g.forms.some((f) => s === f || s.startsWith(`${f} `)));
141
165
  }
142
166
 
143
- /** A user line that opens a turn: the user typed it, it is not a tool result or a meta note. */
144
- function isPrompt(obj) {
145
- if (obj.type !== 'user' || obj.isMeta || obj.isSidechain) return false;
167
+ const NOTE_OPEN = '<task-notification>';
168
+
169
+ /**
170
+ * The openings of a block's feedback, should the host write it back as a user line. As a prompt
171
+ * it would open a new turn: the cap's `opening` would change, the record would count as none, and
172
+ * the turn's edit would fall before the judged turn. UNVERIFIED: no blocked Stop or SubagentStop
173
+ * exists in any transcript on this machine (2026-11), so the host's real feedback line is unseen.
174
+ * Both guesses are kept: Claude Code's `Stop hook feedback` label, and the gate's own reason.
175
+ */
176
+ const REASON_OPEN = 'Geneseed (Verify Before Asserting)';
177
+ const FEEDBACK_OPENS = ['Stop hook feedback', 'SubagentStop hook feedback', REASON_OPEN];
178
+
179
+ /**
180
+ * The text of a background task's notification, or null. Claude Code writes it twice: as a
181
+ * `queued_command` attachment (`attachment.prompt`, a string; 174 of them here are objects, not
182
+ * notifications) and as a `type: "user"` line holding the same text. `queue-operation` lines carry
183
+ * it a third time and are not read.
184
+ */
185
+ function notificationText(obj) {
186
+ let t = null;
187
+ if (obj.type === 'attachment') {
188
+ const a = obj.attachment;
189
+ if (a && a.type === 'queued_command') t = a.prompt;
190
+ } else if (obj.type === 'user') {
191
+ const c = obj.message && obj.message.content;
192
+ t = typeof c === 'string' ? c
193
+ : Array.isArray(c) && c.length === 1 && c[0] && c[0].type === 'text' ? c[0].text : null;
194
+ }
195
+ return typeof t === 'string' && t.trimStart().startsWith(NOTE_OPEN) ? t : null;
196
+ }
197
+
198
+ /**
199
+ * `[tool-use id, proven]` for one notification: proven only when its FIRST `<status>` is
200
+ * `completed` and the notification ENDS `completed (exit code 0)</summary></task-notification>`.
201
+ * The summary quotes the call's `description` (or, without one, its command: both seen here,
202
+ * 2026-11), which the agent writes freely, so a match anywhere else — a description holding
203
+ * `completed (exit code 0)</summary>` on a call that exited 1 — would be the agent's own text.
204
+ * The host's status tag precedes the summary, so the first one is the host's.
205
+ */
206
+ function notified(text) {
207
+ const id = /<tool-use-id>([^<]+)<\/tool-use-id>/.exec(text);
208
+ if (!id) return null;
209
+ const status = /<status>([^<]*)<\/status>/.exec(text);
210
+ return [id[1].trim(), Boolean(status) && status[1] === 'completed'
211
+ && /completed \(exit code 0\)<\/summary>\s*<\/task-notification>\s*$/.test(text)];
212
+ }
213
+
214
+ /**
215
+ * The text Claude Code gives a call that runs on in the background: started so
216
+ * (`run_in_background`), or moved there after its foreground timeout. A sub-agent's transcript
217
+ * records no `toolUseResult` at all (none on any line of one read here, 2026-11), so a call MOVED
218
+ * to the background — `run_in_background` absent from its input — shows only in this text. A
219
+ * command that prints such a line itself reads as pending: an owed check, never a false pass.
220
+ */
221
+ const BACKGROUNDED = /^(?:Command running in background with ID: |Command was moved to the background |Command did not complete within [^.\n]{0,40}? and was moved to the background)/;
222
+ const resultText = (b) => (typeof b.content === 'string' ? b.content
223
+ : Array.isArray(b.content) && b.content[0] && typeof b.content[0].text === 'string' ? b.content[0].text : '');
224
+
225
+ /** A user line that opens a turn: the user typed it, it is not a tool result, a meta note or a task notification. */
226
+ function isPrompt(obj, sidechain = false) {
227
+ if (obj.type !== 'user' || obj.isMeta || (obj.isSidechain && !sidechain)) return false;
228
+ if (notificationText(obj)) return false;
146
229
  const c = obj.message && obj.message.content;
230
+ const t = typeof c === 'string' ? c
231
+ : Array.isArray(c) && c.length === 1 && c[0] && c[0].type === 'text' ? c[0].text : null;
232
+ if (typeof t === 'string' && FEEDBACK_OPENS.some((p) => t.trimStart().startsWith(p))) return false;
147
233
  if (typeof c === 'string') return true;
148
234
  return Array.isArray(c) && c.length > 0 && !c.some((b) => b && b.type === 'tool_result');
149
235
  }
@@ -153,8 +239,16 @@ function isPrompt(obj) {
153
239
  * old text the host recorded for a write. `whole` false means the text is only the file's tail:
154
240
  * with no prompt in it the turn may start earlier, so the answer is null ("read more") — a turn
155
241
  * judged from its middle could miss its edit and wrongly pass.
242
+ *
243
+ * `sidechain` true reads a SUB-AGENT's own transcript (`agent_transcript_path` on SubagentStop).
244
+ * Every message line there carries `isSidechain: true` — seen in 300 of 300 transcripts under
245
+ * `~/.claude/projects/<p>/<session>/subagents/` here (2026-11) — and the turn opens on ONE user
246
+ * line, the Agent call's prompt as a string; the `isMeta` system reminder after it opens nothing.
247
+ * Read as a main transcript, it would hold no prompt and no call, and every sub-agent would pass.
248
+ * `cwd` is the last `cwd` the turn's lines name: a sub-agent's is its own (its worktree), where
249
+ * the payload's `cwd` is its parent's.
156
250
  */
157
- function turnOf(transcript, whole) {
251
+ function turnOf(transcript, whole, sidechain = false) {
158
252
  const entries = [];
159
253
  for (const line of splitLines(transcript)) {
160
254
  if (!line.trim()) continue;
@@ -162,30 +256,71 @@ function turnOf(transcript, whole) {
162
256
  }
163
257
  let start = -1;
164
258
  for (let i = entries.length - 1; i >= 0; i -= 1) {
165
- if (isPrompt(entries[i])) { start = i + 1; break; }
259
+ if (isPrompt(entries[i], sidechain)) { start = i + 1; break; }
166
260
  }
167
261
  if (start === -1) {
168
262
  if (!whole) return null;
169
263
  start = 0;
170
264
  }
265
+ // Which turn this is, for the block cap's state: the prompt line's `uuid`, else its text.
266
+ const first = entries[start - 1];
267
+ const opening = !first ? '' : typeof first.uuid === 'string' ? first.uuid
268
+ : JSON.stringify(first.message && first.message.content).slice(0, 300);
171
269
  const calls = []; // tool_use blocks, in order
172
270
  const results = new Map(); // tool_use_id -> is_error
173
271
  const originals = new Map(); // tool_use_id -> the file before a Write
272
+ const background = new Set(); // tool_use_id of a run_in_background launch
273
+ const finished = new Map(); // tool_use_id -> its notification proved it
274
+ let cwd = null;
275
+ // Distinct notifications in the turn, by text: the host writes each twice (an attachment and a
276
+ // user line holding the same text), and a set counts it once. The cap reads its size.
277
+ const notes = new Set();
174
278
  for (const obj of entries.slice(start)) {
175
- if (obj.isSidechain) continue;
279
+ if (obj.isSidechain && !sidechain) continue;
280
+ if (typeof obj.cwd === 'string' && obj.cwd) cwd = obj.cwd;
281
+ const note = notificationText(obj);
282
+ const said = note && notified(note);
283
+ if (note) notes.add(note.trim());
284
+ // The last notification wins: an agent's task may notify more than once.
285
+ if (said) finished.set(said[0], said[1]);
176
286
  const content = obj.message && obj.message.content;
177
287
  if (!Array.isArray(content)) continue;
178
288
  for (const b of content) {
179
289
  if (!b || typeof b !== 'object') continue;
180
- if (b.type === 'tool_use') calls.push(b);
181
- else if (b.type === 'tool_result') {
290
+ if (b.type === 'tool_use') {
291
+ calls.push(b);
292
+ if (b.input && b.input.run_in_background === true) background.add(b.id);
293
+ } else if (b.type === 'tool_result') {
182
294
  results.set(b.tool_use_id, b.is_error === true);
183
295
  const before = obj.toolUseResult && obj.toolUseResult.originalFile;
184
296
  if (typeof before === 'string') originals.set(b.tool_use_id, before);
297
+ if ((obj.toolUseResult && obj.toolUseResult.backgroundTaskId) || BACKGROUNDED.test(resultText(b))) {
298
+ background.add(b.tool_use_id);
299
+ }
185
300
  }
186
301
  }
187
302
  }
188
- return { calls, results, originals };
303
+ return { calls, results, originals, background, finished, cwd, opening, notes: notes.size };
304
+ }
305
+
306
+ /**
307
+ * The git roots a sub-agent's landed writes fall under, in first-write order: each target's own
308
+ * root (`gitRootOf` of its folder), so a worker in `.claude/worktrees/x` is judged as its own
309
+ * project, against its own list. A target outside every repository is no project's.
310
+ */
311
+ function editRoots({ calls, results }, cwd) {
312
+ const roots = [];
313
+ const byDir = new Map();
314
+ for (const c of calls) {
315
+ if (!EDIT_TOOLS.has(c.name) || results.get(c.id) === true) continue;
316
+ const p = c.input && (c.input.file_path || c.input.notebook_path || c.input.path);
317
+ if (typeof p !== 'string' || !p) continue;
318
+ const dir = path.dirname(path.resolve(cwd, p));
319
+ if (!byDir.has(dir)) byDir.set(dir, gitRootOf(dir));
320
+ const root = byDir.get(dir);
321
+ if (root && !roots.includes(root)) roots.push(root);
322
+ }
323
+ return roots;
189
324
  }
190
325
 
191
326
  /** The target of a landed write under `root`, absolute, or null. A denied write changed nothing. */
@@ -216,17 +351,17 @@ function weakenedTests({ calls, results, originals }, root, cwd) {
216
351
  * edit, or [] when the turn may end (no edit, or every check passed after it); null when `whole`
217
352
  * is false and the tail holds no prompt (`turnOf`). Exported for the unit tier — a transcript is
218
353
  * text no CLI cell can vary cheaply. A check is a line (one form) or a `{ label, forms }` group;
219
- * the answer lists labels.
354
+ * the answer lists labels. `sidechain` reads a sub-agent's transcript (`turnOf`).
220
355
  */
221
- export function doneDecide(transcript, checks, root, cwd = root, whole = true) {
222
- const turn = turnOf(transcript, whole);
356
+ export function doneDecide(transcript, checks, root, cwd = root, whole = true, sidechain = false) {
357
+ const turn = turnOf(transcript, whole, sidechain);
223
358
  return turn && missingChecks(turn, checks, root, cwd);
224
359
  }
225
360
 
226
361
  /** `weakenedTests` over transcript TEXT, for the unit tier: `doneDecide`'s other question. */
227
362
  export const weakenedIn = (transcript, root, cwd = root) => weakenedTests(turnOf(transcript, true), root, cwd);
228
363
 
229
- function missingChecks({ calls, results }, checks, root, cwd) {
364
+ function missingChecks({ calls, results, background, finished }, checks, root, cwd) {
230
365
  const groups = checks.map((c) => (typeof c === 'string' ? { label: c, forms: [c] } : c));
231
366
  let lastEdit = -1;
232
367
  calls.forEach((c, i) => { if (editTarget(c, results, root, cwd)) lastEdit = i; });
@@ -236,81 +371,236 @@ function missingChecks({ calls, results }, checks, root, cwd) {
236
371
  const command = SHELL_TOOLS.has(c.name) && c.input && c.input.command;
237
372
  // A call with no result yet (the host has not flushed it) is not a pass.
238
373
  if (typeof command !== 'string' || results.get(c.id) !== false) return;
374
+ // A background launch's result only says it started: its notification is the verdict.
375
+ if (background.has(c.id) && finished.get(c.id) !== true) return;
239
376
  for (const g of groups) if (groupPasses(command, g)) passed.add(g.label);
240
377
  });
241
378
  return groups.map((g) => g.label).filter((l) => !passed.has(l));
242
379
  }
243
380
 
381
+ /** The id of the turn's last landed write under any of `roots`, or null. */
382
+ function lastEditId({ calls, results }, roots, cwd) {
383
+ let id = null;
384
+ for (const c of calls) if (roots.some((r) => editTarget(c, results, r, cwd))) id = c.id;
385
+ return id;
386
+ }
387
+
388
+ // ---- the block cap -------------------------------------------------------------------------
389
+ // A block may repeat within a continuation, but only when it can change something: an edit landed
390
+ // since the last block (the agent is working, and its new edit owes the proof again) or a
391
+ // background verdict changed, and fewer than CAP_BLOCKS blocks were given in this continuation. A
392
+ // repeat with neither is the agent saying it will
393
+ // not run the checks, and blocking it again only spins (Claude Code itself ends a run of 8 Stop
394
+ // continuations, reset by a tool call — too late to be the gate's bound).
395
+ const CAP_BLOCKS = 3;
396
+ // The ceiling over a whole human turn, across its continuations. Each notification restarts the
397
+ // per-continuation count, so without it a red suite relaunched in the background loops for ever:
398
+ // it fails (a notification: new count, block), the relaunch turns the verdict back to pending
399
+ // (block), and again — a full suite run per cycle. Reset only by a new human prompt.
400
+ const TURN_BLOCKS = 10;
401
+ const CAP_DIR = path.join('notebook', 'done-gate');
402
+ const CAP_STALE_MS = 7 * 24 * 60 * 60 * 1000;
403
+
404
+ /**
405
+ * The cap's decision, pure: the state to save with a block, or null when the turn ends. `state` is
406
+ * what the last block of this session (and sub-agent) saved, `{ opening, lastEdit, notes, verdict,
407
+ * blocks }`, or null; a different `opening` is another turn, so it counts as none. With no state
408
+ * for this turn, `active` (`stop_hook_active`) alone decides, as before the cap: a Stop that follows
409
+ * a block we have no record of ends the turn. Once a block is on record, the record decides
410
+ * whatever `active` says, so a host that clears the flag mid-turn cannot loop the gate.
411
+ *
412
+ * PER CONTINUATION. A notification opens no turn, so one turn may span many continuations an
413
+ * unattended session's notifications drive. The count is per continuation: a notification since
414
+ * the last block (`notes`, the turn's count of distinct notifications, grew) starts a new one at
415
+ * count 1, so three early blocks cannot spend the cap for the rest of the turn. Inside one
416
+ * continuation the bound is CAP_BLOCKS, and a repeat needs a reason: a new edit, or a changed
417
+ * background `verdict` for an owed check (`pending` -> `failed`), since a failed proof with no new
418
+ * edit must still block.
419
+ */
420
+ export function nextBlock(state, { active, opening, lastEdit, notes = 0, verdict = '' }) {
421
+ const mine = state && state.opening === opening ? state : null;
422
+ if (!mine) return active ? null : { opening, lastEdit, notes, verdict, blocks: 1, total: 1 };
423
+ // The ceiling first: no notification and no verdict reopens a turn that has spent it.
424
+ const total = mine.total ?? 0;
425
+ if (total >= TURN_BLOCKS) return null;
426
+ if (notes > (mine.notes ?? 0)) return { opening, lastEdit, notes, verdict, blocks: 1, total: total + 1 };
427
+ if (mine.blocks >= CAP_BLOCKS) return null;
428
+ if (mine.lastEdit === lastEdit && (mine.verdict ?? '') === verdict) return null;
429
+ return { opening, lastEdit, notes, verdict, blocks: mine.blocks + 1, total: total + 1 };
430
+ }
431
+
432
+ /** True when `state` is this turn's record and has spent the per-turn ceiling: `nextBlock`'s first refusal, named. */
433
+ export const turnCeilingReached = (state, opening) =>
434
+ Boolean(state && state.opening === opening && (state.total ?? 0) >= TURN_BLOCKS);
435
+
436
+ /**
437
+ * Each owed check's background state since the turn's last edit, `label -> 'pending' | 'failed'`:
438
+ * the last background run of one of its forms, launched with no completion seen, or completed with
439
+ * anything but exit 0. A check never run in the background has no entry.
440
+ */
441
+ function backgroundOwed({ calls, results, background, finished }, checks, owedLabels, lastEdit) {
442
+ const states = new Map();
443
+ let after = lastEdit === null;
444
+ for (const c of calls) {
445
+ if (!after) { after = c.id === lastEdit; continue; }
446
+ const command = SHELL_TOOLS.has(c.name) && c.input && c.input.command;
447
+ if (typeof command !== 'string' || results.get(c.id) !== false || !background.has(c.id)) continue;
448
+ for (const g of checks) {
449
+ if (!owedLabels.has(g.label) || !groupPasses(command, g)) continue;
450
+ states.set(g.label, finished.has(c.id) ? (finished.get(c.id) ? 'passed' : 'failed') : 'pending');
451
+ }
452
+ }
453
+ for (const [l, s] of states) if (s === 'passed') states.delete(l);
454
+ return states;
455
+ }
456
+
244
457
  /**
245
- * The Stop-side wrapper `cmdLearn` calls first. Returns 'block' when it printed a block (the
246
- * turn goes on, so `learn` must not distil yet); 'advisory' when it printed the advisory
247
- * `systemMessage` (the turn ends and learning runs, but `learn` must print nothing more on
248
- * stdout, or the JSON stops parsing); null in every other case, with nothing on stdout.
249
- * `install` is the root `cmdLearn` already derived from `--memory` (null without one), so the
250
- * ledger lands in the same root its sovereignty check read. `read` is `cmdLearn`'s per-Stop
458
+ * The cap's state file, one per session (and sub-agent), under the install's notebook — the
459
+ * store-watch baseline pattern (`./store-watch.mjs`). Read and written only on a Stop with owed
460
+ * checks, so an allowed Stop costs nothing here. Unreadable reads as none.
461
+ */
462
+ function capFile(install, meta) {
463
+ const key = [meta.session_id, meta.hook_event_name === 'SubagentStop' ? meta.agent_id : null]
464
+ .filter((k) => typeof k === 'string' && k).join('~');
465
+ return key ? path.join(install, CAP_DIR, `${key.replace(/[^\w.~-]/g, '_').slice(0, 160)}.json`) : null;
466
+ }
467
+ function readCap(file) {
468
+ try { return JSON.parse(readFileSync(file, 'utf8')); } catch { return null; }
469
+ }
470
+ function saveCap(file, state) {
471
+ try {
472
+ mkdirSync(path.dirname(file), { recursive: true });
473
+ writeFileSync(file, JSON.stringify(state));
474
+ } catch { return; /* unwritable: the next Stop finds no record, and ends the turn as before the cap */ }
475
+ if (state.blocks !== 1) return;
476
+ // A turn's first block: drop other sessions' stale files, as the baselines do. After the write,
477
+ // and one entry at a time: a file another Stop removed (ENOENT) or holds (EPERM) costs only itself.
478
+ let names = [];
479
+ try { names = readdirSync(path.dirname(file)); } catch { /* nothing to sweep */ }
480
+ for (const n of names) {
481
+ try {
482
+ const old = path.join(path.dirname(file), n);
483
+ if (Date.now() - statSync(old).mtimeMs > CAP_STALE_MS) unlinkSync(old);
484
+ } catch { /* gone or held: the next sweep tries it again */ }
485
+ }
486
+ }
487
+
488
+ /**
489
+ * The Stop-side wrapper `cmdLearn` calls first, on Stop and on SubagentStop. Returns 'block' when
490
+ * it printed a block (the turn goes on, so `learn` must not distil yet); 'advisory' when it
491
+ * printed the advisory `systemMessage` (the turn ends and learning runs, but `learn` must print
492
+ * nothing more on stdout, or the JSON stops parsing); null in every other case, with nothing on
493
+ * stdout. `install` is the root `cmdLearn` already derived from `--memory` (null without one), so
494
+ * the ledger lands in the same root its sovereignty check read. `read` is `cmdLearn`'s per-Stop
251
495
  * transcript reader, so the distillation after an allow reuses the windows read here.
496
+ *
497
+ * SUBAGENTSTOP. The turn judged is the sub-agent's own, from `agent_transcript_path` (no path: not
498
+ * judged, and a stderr line when the cwd's project lists checks, as on Bob). The payload's `cwd`
499
+ * is the PARENT's, so the projects are the git roots of the files the sub-agent wrote
500
+ * (`editRoots`), each judged against its own `doneChecksOf`. A block keeps the sub-agent running
501
+ * with the reason as its next instruction (Claude Code hooks doc, SubagentStop). An advisory is
502
+ * a stderr line and a ledger entry only: nobody sees a sub-agent's `systemMessage`, so it returns
503
+ * null and prints nothing on stdout.
252
504
  */
253
505
  export function doneGate(meta, args, install, read = tailReader()) {
254
506
  try {
507
+ const sub = meta.hook_event_name === 'SubagentStop';
255
508
  const cwd = typeof meta.cwd === 'string' && meta.cwd ? meta.cwd : process.cwd();
256
- const root = gitRootOf(cwd);
257
- if (!root) return null;
258
- const { source, blocking, checks } = doneChecksOf(root);
509
+ const cwdRoot = gitRootOf(cwd);
510
+ if (!sub && !cwdRoot) return null;
511
+ const here = cwdRoot ? doneChecksOf(cwdRoot) : null;
512
+ const listed = Boolean(here && here.blocking && here.checks.length);
513
+ const file = sub ? meta.agent_transcript_path : meta.transcript_path;
259
514
  // Bob's Stop payload carries no transcript (learn's I2): nothing to judge, and a listed gate
260
515
  // says so. Inferred checks stay quiet there: every repo with a manifest would log it.
261
- if (args.host === 'bob' || typeof meta.transcript_path !== 'string') {
262
- if (blocking && checks.length) err(`[done-gate] no transcript${args.host === 'bob' ? ' (bob)' : ''} — turn not judged.\n`);
516
+ if (args.host === 'bob' || typeof file !== 'string' || (sub && !file)) {
517
+ if (listed) {
518
+ err(sub ? '[done-gate] no agent transcript — sub-agent turn not judged.\n'
519
+ : `[done-gate] no transcript${args.host === 'bob' ? ' (bob)' : ''} — turn not judged.\n`);
520
+ }
263
521
  return null;
264
522
  }
265
- let verdict;
523
+ let turn;
266
524
  try {
267
- verdict = read(meta.transcript_path, (text, whole) => {
268
- const turn = turnOf(text, whole);
269
- return turn && {
270
- missing: missingChecks(turn, checks, root, cwd), weakened: weakenedTests(turn, root, cwd),
271
- };
272
- });
525
+ turn = read(file, (text, whole) => turnOf(text, whole, sub));
273
526
  } catch {
274
527
  // No ask tier on Stop: blocking on an unreadable transcript would trap the user.
275
- if (checks.length) err('[done-gate] transcript unreadable — turn not judged.\n');
528
+ if (sub ? listed : here.checks.length) err('[done-gate] transcript unreadable — turn not judged.\n');
276
529
  return null;
277
530
  }
278
- const { missing } = verdict;
531
+ const at = sub ? turn.cwd || cwd : cwd;
532
+ const judged = (sub ? editRoots(turn, at) : [cwdRoot]).map((root) => {
533
+ const d = root === cwdRoot ? here : doneChecksOf(root);
534
+ return { root, ...d, missing: missingChecks(turn, d.checks, root, at), weakened: weakenedTests(turn, root, at) };
535
+ });
536
+ // One project names nothing; several say whose each entry is.
537
+ const tag = (r) => (judged.length > 1 ? `${r.root}: ` : '');
538
+ const list = (rs) => rs.flatMap((r) => r.missing.map((m) => `${tag(r)}${m}`)).join('; ');
279
539
  // `--no-test-note`: the line goes, the done checks do not.
280
- const weakened = args.noTestNote ? [] : verdict.weakened;
540
+ const weakened = args.noTestNote ? [] : judged.flatMap((r) => r.weakened.map((w) => `${tag(r)}${w}`));
541
+ const owed = judged.filter((r) => r.blocking && r.missing.length);
542
+ const inferred = judged.filter((r) => !r.blocking && r.missing.length);
543
+ const who = sub ? 'this sub-agent' : 'this turn';
281
544
  // One JSON document on stdout, whatever the advisories: Stop reads no second one.
282
545
  const advise = (...said) => {
283
546
  if (weakened.length) {
284
547
  // A stable id, not a law number: an advisory is no hook-pinned rule (`HOOK_PINNED`).
285
548
  recordGate(install, ADVISORY_VERB, 'cure-the-cause');
286
- const line = `[done-gate] advisory — test weakened this turn: ${weakened.join('; ')}`;
549
+ const line = `[done-gate] advisory — test weakened ${sub ? 'by a sub-agent' : 'this turn'}: ${weakened.join('; ')}`;
287
550
  err(`${line}\n`);
288
551
  said.push(`${line}. Cure the Cause: fix the code, not the test.`);
289
552
  }
553
+ if (sub) return null;
290
554
  out(`${JSON.stringify({ systemMessage: said.join(' ') })}\n`);
291
555
  return 'advisory';
292
556
  };
293
- if (!missing.length && weakened.length) return advise();
294
- if (!missing.length) return null;
295
- if (!blocking) {
557
+ const inferredSaid = () => {
558
+ if (!inferred.length) return [];
296
559
  recordGate(install, ADVISORY_VERB, 'law-3');
297
- err(`[done-gate] advisory — unproven since the last edit: ${missing.join('; ')}\n`);
298
- return advise('Geneseed done gate (advisory) — this turn edited files, and these checks '
299
- + `inferred from ${source} have not passed since the last edit: ${missing.join('; ')}. `
300
- + `List your own in ${DONE_LIST} to make the gate block.`);
301
- }
302
- if (meta.stop_hook_active === true) {
560
+ err(`[done-gate] advisory${sub ? ' (sub-agent)' : ''} — unproven since the last edit: ${list(inferred)}\n`);
561
+ const sources = [...new Set(inferred.map((r) => r.source))].join(', ');
562
+ return [`Geneseed done gate (advisory) — ${who} edited files, and these checks `
563
+ + `inferred from ${sources} have not passed since the last edit: ${list(inferred)}. `
564
+ + `List your own in ${DONE_LIST} to make the gate block.`];
565
+ };
566
+ const settle = () => {
567
+ const said = inferredSaid();
568
+ return said.length || weakened.length ? advise(...said) : null;
569
+ };
570
+ if (!owed.length) return settle();
571
+ const active = meta.stop_hook_active === true;
572
+ const capPath = install ? capFile(install, meta) : null;
573
+ // The owed checks whose proof is a background run still pending, or one that reported a failure.
574
+ const bg = owed.flatMap((r) => [...backgroundOwed(turn, r.checks, new Set(r.missing), lastEditId(turn, [r.root], at))]
575
+ .map(([l, st]) => [`${tag(r)}${l}`, st]));
576
+ const verdict = bg.map(([l, st]) => `${l}=${st}`).sort().join('\n');
577
+ // Without an install or a session id there is nowhere to count: one block per turn, as before.
578
+ const record = capPath ? readCap(capPath) : null;
579
+ const next = capPath
580
+ ? nextBlock(record, { active, opening: turn.opening, notes: turn.notes, verdict,
581
+ lastEdit: lastEditId(turn, owed.map((r) => r.root), at) })
582
+ : (active ? null : true);
583
+ if (!next) {
303
584
  recordGate(install, 'done-gate-cap', 'law-3');
304
- err(`[done-gate] cap reached — turn ends with unproven checks: ${missing.join('; ')}\n`);
305
- return weakened.length ? advise() : null;
585
+ const why = turnCeilingReached(record, turn.opening)
586
+ ? `total ceiling reached (${TURN_BLOCKS} blocks this turn)` : 'cap reached';
587
+ err(`[done-gate] ${why} — turn ends with unproven checks: ${list(owed)}\n`);
588
+ return settle();
306
589
  }
590
+ if (capPath) saveCap(capPath, next);
307
591
  // The turn goes on, so a weakened test is said at the Stop that really ends it.
308
592
  recordGate(install, 'done-gate', 'law-3');
593
+ const named = (st) => bg.filter(([, s]) => s === st).map(([l]) => l).join('; ');
594
+ const pending = named('pending');
595
+ const failed = named('failed');
309
596
  out(`${JSON.stringify({
310
597
  decision: 'block',
311
- reason: 'Geneseed (Verify Before Asserting) — this turn edited files, and these '
312
- + `checks from ${DONE_LIST} have not passed since the last edit: ${missing.join('; ')}. `
313
- + 'Run them unpiped, or say plainly that they were not run and why.',
598
+ reason: `${REASON_OPEN} — ${who} edited files, and these `
599
+ + `checks from ${DONE_LIST} have not passed since the last edit: ${list(owed)}. `
600
+ + (pending ? `Still running in the background, with no completion seen: ${pending}; a launch is no pass. ` : '')
601
+ + (failed ? `Run in the background and reported a failure: ${failed}. ` : '')
602
+ + 'Run them unpiped, or wait for the background run to complete with exit 0, '
603
+ + 'or say plainly that they were not run and why.',
314
604
  })}\n`);
315
605
  return 'block';
316
606
  } catch (e) {
@@ -367,14 +367,15 @@ export function cmdLearn(args) {
367
367
  args = { ...args, memory: sharedStoreFor(install, args) };
368
368
  }
369
369
 
370
- // The done gate (#289) judges the turn BEFORE anything here spawns, and only on Stop. A block
371
- // means the turn goes on, so there is nothing to distil yet: the next Stop will.
370
+ // The done gate (#289) judges the turn BEFORE anything here spawns, on Stop and on SubagentStop
371
+ // (the sub-agent's own turn). A block means the turn goes on, so there is nothing to distil
372
+ // yet, and no agent lesson either: the next Stop will.
372
373
  // `--no-done-gate` (the install switched Law III's gate off) skips the check, never the
373
374
  // distillation below.
374
375
  // One reader for this Stop: an allowed turn's distillation reuses the windows the gate read.
375
376
  const read = tailReader();
376
377
  // An advisory verdict already holds stdout: nothing below may print there after it.
377
- const verdict = hookEvent === 'Stop' && !args.file && !args.noDoneGate
378
+ const verdict = (hookEvent === 'Stop' || hookEvent === 'SubagentStop') && !args.file && !args.noDoneGate
378
379
  ? doneGate(meta, args, install, read) : null;
379
380
  if (verdict === 'block') return 0;
380
381