geneseed 5.3.1 → 5.5.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 (248) hide show
  1. package/CHANGELOG.md +102 -0
  2. package/README.md +51 -18
  3. package/SHIPPED.md +7 -7
  4. package/adapters/bob/README.md +12 -1
  5. package/adapters/opencode/README.md +5 -3
  6. package/adapters/opencode/plugins/geneseed-context.js +77 -10
  7. package/adapters/opencode/plugins/geneseed-guard.js +106 -22
  8. package/adapters/opencode/plugins/geneseed-learn.js +641 -6
  9. package/bin/geneseed-cli.mjs +10 -0
  10. package/bin/geneseed-hook.mjs +5 -4
  11. package/docs/PRD.md +1 -1
  12. package/docs/README.md +1 -0
  13. package/docs/concepts/agents.md +14 -2
  14. package/docs/concepts/collaboration.md +2 -2
  15. package/docs/concepts/enforcement-table.md +5 -2
  16. package/docs/concepts/exclusions.md +16 -2
  17. package/docs/concepts/footprint.md +1 -1
  18. package/docs/concepts/foreman-mode.md +23 -4
  19. package/docs/concepts/hook-gates.md +4 -4
  20. package/docs/concepts/hooks.md +25 -7
  21. package/docs/concepts/host-matrix.md +4 -4
  22. package/docs/concepts/hosts.md +1 -1
  23. package/docs/concepts/kits.md +12 -2
  24. package/docs/concepts/loop-bricks.md +3 -3
  25. package/docs/concepts/loops.md +6 -4
  26. package/docs/concepts/ownership.md +1 -1
  27. package/docs/concepts/rules.md +2 -2
  28. package/docs/concepts/shared-tier.md +1 -1
  29. package/docs/concepts/skills.md +21 -1
  30. package/docs/concepts/themes.md +1 -1
  31. package/docs/extending.md +73 -29
  32. package/docs/guides/auto-merge.md +100 -0
  33. package/docs/guides/choose-your-setup.md +1 -1
  34. package/docs/guides/headless.md +1 -1
  35. package/docs/guides/install-clone.md +19 -1
  36. package/docs/guides/install-scripted.md +8 -2
  37. package/docs/guides/install.md +20 -2
  38. package/docs/guides/loop-finish.md +3 -3
  39. package/docs/guides/loop-running.md +4 -4
  40. package/docs/guides/project-context.md +1 -1
  41. package/docs/guides/run-a-factory.md +2 -2
  42. package/docs/guides/setup-doctrines.md +2 -2
  43. package/docs/guides/setup-footprint.md +1 -1
  44. package/docs/guides/uninstall.md +3 -3
  45. package/docs/guides/upgrade.md +2 -2
  46. package/docs/guides/worktree.md +1 -1
  47. package/docs/reference/env-context.md +1 -1
  48. package/docs/reference/environment.md +4 -2
  49. package/docs/reference/plugin-activity.md +1 -1
  50. package/docs/reference/plugin-guard.md +1 -1
  51. package/docs/reference/plugin-learn.md +5 -1
  52. package/docs/reference/plugin-workflow.md +1 -1
  53. package/docs/reference/profiles.md +142 -0
  54. package/docs/reference/troubleshoot-doctor.md +1 -1
  55. package/docs/reference/troubleshoot-hooks.md +2 -2
  56. package/docs/reference/troubleshoot-install.md +3 -3
  57. package/docs/reference/troubleshoot-tools.md +1 -1
  58. package/docs/token-footprint.md +11 -6
  59. package/docs/understand/design-choices-engineering.md +1 -1
  60. package/docs/understand/enforced-vs-asked.md +1 -1
  61. package/docs/understand/machine-claude.md +2 -2
  62. package/docs/understand/on-your-machine.md +1 -1
  63. package/docs/web-ui.md +8 -6
  64. package/harness.config.json +1 -1
  65. package/js/README.md +11 -3
  66. package/js/build/args.mjs +16 -4
  67. package/js/build/catalog.mjs +11 -1
  68. package/js/build/driver.mjs +74 -16
  69. package/js/build/emit-claude.mjs +32 -5
  70. package/js/build/emit-opencode.mjs +16 -9
  71. package/js/build/export.mjs +1 -1
  72. package/js/build/generate.mjs +12 -157
  73. package/js/build/notes-migrate.mjs +99 -0
  74. package/js/build/profile.mjs +326 -0
  75. package/js/build/render.mjs +110 -8
  76. package/js/build/retired-skills.mjs +60 -13
  77. package/js/build/source.mjs +100 -3
  78. package/js/build/stubs.mjs +4 -1
  79. package/js/cli-table.json +212 -7
  80. package/js/hosts/agent-runs.mjs +205 -0
  81. package/js/hosts/done-checks.mjs +3 -1
  82. package/js/hosts/hooks-done.mjs +428 -63
  83. package/js/hosts/hooks-learn.mjs +89 -3
  84. package/js/hosts/hooks-prims.mjs +44 -4
  85. package/js/hosts/hooks.mjs +159 -9
  86. package/js/hosts/hosts.mjs +10 -0
  87. package/js/hosts/installs.mjs +44 -2
  88. package/js/hosts/link.mjs +45 -10
  89. package/js/hosts/native.mjs +61 -7
  90. package/js/hosts/opencode.mjs +1 -1
  91. package/js/hosts/settings.mjs +101 -3
  92. package/js/hosts/spec-feedback.mjs +538 -0
  93. package/js/hosts/usage.mjs +67 -8
  94. package/js/inspect/agent-scores.mjs +118 -0
  95. package/js/inspect/checks-authoring.mjs +2 -1
  96. package/js/inspect/checks-build.mjs +20 -4
  97. package/js/inspect/checks-constitution.mjs +32 -0
  98. package/js/inspect/checks-repo.mjs +27 -2
  99. package/js/inspect/cost.mjs +6 -5
  100. package/js/inspect/diff.mjs +46 -8
  101. package/js/inspect/doctor.mjs +4 -0
  102. package/js/inspect/inventory.mjs +1 -1
  103. package/js/inspect/status.mjs +3 -1
  104. package/js/inspect/validate.mjs +1 -0
  105. package/js/lib/machine-dir.mjs +8 -0
  106. package/js/lib/paths.mjs +4 -1
  107. package/js/maintain/profile-scope.mjs +145 -0
  108. package/js/maintain/profiles.mjs +486 -0
  109. package/js/maintain/setup.mjs +413 -15
  110. package/js/maintain/uninstall.mjs +4 -1
  111. package/js/maintain/update.mjs +4 -2
  112. package/js/web/actions.mjs +44 -41
  113. package/js/web/api.mjs +13 -3
  114. package/js/web/handler.mjs +8 -0
  115. package/js/web/jobs.mjs +5 -4
  116. package/js/web/profiles-api.mjs +201 -0
  117. package/js/web/routes.mjs +5 -0
  118. package/package.json +2 -1
  119. package/profiles/guillaume-claude-global.json +16 -0
  120. package/profiles/starter.json +14 -0
  121. package/registry.json +14 -0
  122. package/src/AGENT.md.tmpl +16 -18
  123. package/src/agents/_self-improvement.md +15 -7
  124. package/src/agents/_template.md +4 -2
  125. package/src/agents/advocate.md +1 -1
  126. package/src/agents/architect.md +1 -1
  127. package/src/agents/developer.md +10 -3
  128. package/src/agents/devops-engineer.md +1 -1
  129. package/src/agents/docker-expert.md +1 -1
  130. package/src/agents/docs.md +1 -1
  131. package/src/agents/empiricist.md +1 -1
  132. package/src/agents/explorer.md +4 -2
  133. package/src/agents/framer.md +1 -1
  134. package/src/agents/historian.md +1 -1
  135. package/src/agents/kubernetes-specialist.md +1 -1
  136. package/src/agents/memory-curator.md +1 -1
  137. package/src/agents/operator.md +1 -1
  138. package/src/agents/performance.md +1 -1
  139. package/src/agents/pragmatist.md +1 -1
  140. package/src/agents/react-engineer.md +1 -1
  141. package/src/agents/react-reviewer.md +1 -1
  142. package/src/agents/researcher.md +1 -1
  143. package/src/agents/reviewer.md +10 -3
  144. package/src/agents/security.md +1 -1
  145. package/src/agents/skeptic.md +1 -1
  146. package/src/agents/spring-boot-engineer.md +1 -1
  147. package/src/agents/spring-reviewer.md +1 -1
  148. package/src/agents/spring-security.md +1 -1
  149. package/src/agents/steward.md +1 -1
  150. package/src/agents/tester.md +4 -2
  151. package/src/agents/user-advocate.md +1 -1
  152. package/src/agents/visionary.md +1 -1
  153. package/src/bricks/pr-open.md +3 -2
  154. package/src/doctrines/ops.md +2 -2
  155. package/src/doctrines/process.md +40 -36
  156. package/src/factories/analysis-to-build.json +1 -1
  157. package/src/factories/bug-report-to-fix.json +1 -1
  158. package/src/factories/issue-to-pr.json +1 -1
  159. package/src/kits/terminal-tools/rules.md +10 -0
  160. package/src/kits/terminal-tools.json +13 -0
  161. package/src/licenses/herdr.txt +201 -0
  162. package/src/memory/README.md +12 -2
  163. package/src/modes/foreman.md +25 -9
  164. package/src/skill-descriptions.json +63 -0
  165. package/src/skills/_self-improvement.md +42 -24
  166. package/src/skills/_template.md +3 -1
  167. package/src/skills/brainstorm.md +35 -22
  168. package/src/skills/commit.md +17 -17
  169. package/src/skills/daydream/VENDOR.md +6 -0
  170. package/src/skills/debug/ci.md +1 -1
  171. package/src/skills/dependencies.md +3 -3
  172. package/src/skills/diagram-design/VENDOR.md +4 -0
  173. package/src/skills/document-project.md +3 -2
  174. package/src/skills/explain-changes/VENDOR.md +5 -1
  175. package/src/skills/factory.md +13 -4
  176. package/src/skills/geneseed.md +4 -2
  177. package/src/skills/git-history.md +5 -7
  178. package/src/skills/herdr.md +135 -0
  179. package/src/skills/loop.md +3 -2
  180. package/src/skills/opencode-cli.md +84 -0
  181. package/src/skills/parallel-agents.md +11 -0
  182. package/src/skills/pipeline.md +3 -3
  183. package/src/skills/plan.md +5 -4
  184. package/src/skills/react-view-transitions/VENDOR.md +7 -1
  185. package/src/skills/release.md +11 -9
  186. package/src/skills/review-response.md +4 -2
  187. package/src/skills/rule/approve.md +2 -1
  188. package/src/skills/rule.md +27 -1
  189. package/src/skills/ship.md +54 -7
  190. package/src/skills/skill-forge.md +5 -3
  191. package/src/skills/token-report/VENDOR.md +5 -1
  192. package/src/skills/worktree.md +2 -2
  193. package/src/upstreams.json +9 -2
  194. package/themes/README.md +3 -1
  195. package/themes/_TEMPLATE.json +2 -0
  196. package/themes/biker.json +2 -0
  197. package/themes/commentator.json +2 -0
  198. package/themes/cyberpunk.json +2 -0
  199. package/themes/gamer.json +2 -0
  200. package/themes/imperial.json +2 -0
  201. package/themes/joker.json +2 -0
  202. package/themes/marvin.json +2 -0
  203. package/themes/mean.json +2 -0
  204. package/themes/military.json +2 -0
  205. package/themes/neutral.json +2 -0
  206. package/themes/pirate.json +2 -0
  207. package/themes/sports.json +2 -0
  208. package/themes/verstappen.json +2 -0
  209. package/themes/wizard.json +2 -0
  210. package/web/dist/assets/{ActiveLoops-BJJN3P-V.js → ActiveLoops-DOJCPPPc.js} +1 -1
  211. package/web/dist/assets/Activity-LKsDzsnK.js +1 -0
  212. package/web/dist/assets/ActivityDetail-DhwTfPm6.js +1 -0
  213. package/web/dist/assets/{Bonsai-BBl4XXqs.js → Bonsai-CePMLrpr.js} +1 -1
  214. package/web/dist/assets/{CopyButton-Beven8yn.js → CopyButton-CuoaJ6k7.js} +1 -1
  215. package/web/dist/assets/Dashboard-D1VKuvLe.js +2 -0
  216. package/web/dist/assets/Docs-CUrHJKaU.js +5 -0
  217. package/web/dist/assets/Factories-Ci1XfmSy.js +1 -0
  218. package/web/dist/assets/{GreenhouseView-Bce212qd.js → GreenhouseView-CNfH2lPK.js} +1 -1
  219. package/web/dist/assets/Installs-ZHQZM1iS.js +3 -0
  220. package/web/dist/assets/{JournalView-CV4omyww.js → JournalView-CMsWahkS.js} +1 -1
  221. package/web/dist/assets/Kits-CkliyK0n.js +1 -0
  222. package/web/dist/assets/Laws-hh4O3HZ4.js +4 -0
  223. package/web/dist/assets/{LibRows-Dag1s0ZX.js → LibRows-Brv0Hmkr.js} +1 -1
  224. package/web/dist/assets/Library-BYmiLjJr.js +3 -0
  225. package/web/dist/assets/Loops-ytm-xJ68.js +2 -0
  226. package/web/dist/assets/{OperatorHudView-JmYY1pBR.js → OperatorHudView-KaqCx_HP.js} +1 -1
  227. package/web/dist/assets/Personal-CmcnRKYE.js +2 -0
  228. package/web/dist/assets/Settings-tUrpdOfq.js +1 -0
  229. package/web/dist/assets/{Tabs-8zsyEPSK.js → Tabs-CD7etcGD.js} +1 -1
  230. package/web/dist/assets/api-CZ-x0iWG.js +1 -0
  231. package/web/dist/assets/{controls-D4wmg_pl.js → controls-CK7qHA8H.js} +1 -1
  232. package/web/dist/assets/{index-CRWqKxfY.css → index-Ba_Kg3Af.css} +1 -1
  233. package/web/dist/assets/index-COKbhFNo.js +6 -0
  234. package/web/dist/index.html +3 -3
  235. package/web/dist/assets/Activity-WQ3ykgxU.js +0 -1
  236. package/web/dist/assets/ActivityDetail-7rt04SkS.js +0 -1
  237. package/web/dist/assets/Dashboard-BgLArtgu.js +0 -2
  238. package/web/dist/assets/Docs-B5aHp86J.js +0 -5
  239. package/web/dist/assets/Factories-BjqzXAw8.js +0 -1
  240. package/web/dist/assets/Installs-B1OsrHXF.js +0 -3
  241. package/web/dist/assets/Kits-CW1e7xNa.js +0 -1
  242. package/web/dist/assets/Laws-1Ckf1lbs.js +0 -4
  243. package/web/dist/assets/Library-B3FuFLel.js +0 -3
  244. package/web/dist/assets/Loops-CwqgnLNw.js +0 -2
  245. package/web/dist/assets/Personal-DKLgLa7Z.js +0 -2
  246. package/web/dist/assets/Settings-BwErnh-R.js +0 -1
  247. package/web/dist/assets/api-DLDVY3K-.js +0 -1
  248. package/web/dist/assets/index-Ce6qF2nG.js +0 -6
@@ -48,18 +48,41 @@
48
48
  * whose result is not an error (a denied write changed nothing);
49
49
  * - a pass is a Bash/PowerShell call whose command contains one of the check's forms UNPIPED (a pipe
50
50
  * takes the exit code of its last stage: `npm test | tail` exits 0 on a red suite), not MASKED
51
- * after it (`|| true`, `; exit 0` — see `runsUnpiped`), and whose
51
+ * after it (`|| true`, `; exit 0` — see `runsUnpiped`), compared after `normalizeRun` takes
52
+ * `npm --prefix <project>`, `git -C <project>` and `--test-concurrency N` off both sides, and whose
52
53
  * 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).
54
+ * 14 000+ real Claude Code results, 2026-10-17);
55
+ * - a BACKGROUND run (`run_in_background: true`, or moved there after its foreground timeout)
56
+ * is pending, not passed: its result is `is_error` false, with
57
+ * `toolUseResult.backgroundTaskId` set (or, in a sub-agent's transcript, only the host's
58
+ * `BACKGROUNDED` text) — it says the command STARTED. It passes only when a later task notification names its tool-use id with
59
+ * `<status>completed</status>` and `completed (exit code 0)` (`notificationText`); any other
60
+ * status or code leaves it owed. Before this, 76 of 112 accepted passes in 30 days of real
61
+ * transcripts here were launches. The pass is still placed by the CALL: a launch before the
62
+ * last edit proves nothing, even when it completes after it.
54
63
  *
55
- * READ FROM THE END (constant-cost Stop). Only the current turn matters, so the transcript is read
64
+ * READ FROM THE END. Only the current turn matters, so the transcript is read
56
65
  * backward in growing windows (`tailReader`) until the turn's opening prompt is inside one; a
57
66
  * 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".
67
+ * a window without a prompt answers "read more", not "no edit". A task notification is no prompt:
68
+ * Claude Code writes it as a `type: "user"` line whose text opens `<task-notification>` (4 258
69
+ * such lines in this machine's transcripts, 2026-11), and as a prompt it would open a new turn
70
+ * and hide the edit before it. So a turn now spans every continuation a notification drives, up
71
+ * to the last HUMAN prompt, and so does the cap's count. The cost follows: in a long session that
72
+ * a stream of notifications kept going, `tailReader` may read back that far, up to the whole
73
+ * file, so a Stop's read is no longer constant. It is bounded by the file, never by the session's
74
+ * age alone.
59
75
  *
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.
76
+ * THE CAP (`nextBlock`). Counted per CONTINUATION: a task notification since the last block starts
77
+ * a new one. Inside one, a Stop is blocked again only when an edit landed since the last block or
78
+ * an owed check's background verdict changed (pending -> failed), and at most 3 times; a Stop past
79
+ * that ends the turn and leaves a `done-gate-cap` ledger line, so a gate that cries wolf gets
80
+ * found. Over the whole human turn, across continuations, at most 10 blocks (`TURN_BLOCKS`):
81
+ * past it no notification, verdict or edit blocks again until the next human prompt, and the
82
+ * stderr line says the total ceiling was reached. The count lives in a per-session file under the install; without one,
83
+ * `stop_hook_active` (true when this Stop follows a block) ends the turn at once.
62
84
  */
85
+ import { mkdirSync, readdirSync, readFileSync, realpathSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
63
86
  import path from 'node:path';
64
87
  import { printOut as out, printErr as err } from '../lib/fs.mjs';
65
88
  import { within } from '../lib/paths.mjs';
@@ -87,7 +110,9 @@ const SHELL_TOOLS = new Set(['Bash', 'PowerShell']);
87
110
  * Whitespace is collapsed on both sides. shortcut: the shell is not parsed — a prefix such as
88
111
  * `sudo`/`time`/`env X=1`, a subshell, or a `|` inside a quoted argument after the check all read
89
112
  * 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:
113
+ * of the command line above refuses a pass, so the gate errs toward a reminder. That says nothing
114
+ * of the call's mode: a `run_in_background` launch is judged by its completion, not here
115
+ * (`missingChecks`). One known opening the other way remains:
91
116
  * `npm test; npm run lint` passes both, though `;` lets a green lint hide a red test (the line's
92
117
  * exit code is the last command's). Kept so a chained proof line still counts; upgrade by
93
118
  * requiring `&&` between checks if that opening is ever seen in a real transcript.
@@ -125,25 +150,158 @@ export function runsUnpiped(command, line) {
125
150
  return false;
126
151
  }
127
152
 
153
+ /**
154
+ * `command` with the flags that name WHERE a check runs, or how many workers run it, taken out,
155
+ * so a check line and the command that proves it compare on what is tested (user decision
156
+ * 2026-11-14: workers in worktrees ran `npm --prefix <worktree> run lint` and the suite at the
157
+ * default concurrency, all green, and the gate blocked them). Applied to both sides before the
158
+ * prefix match (`groupPasses`). Removed, and nothing else:
159
+ * - `--prefix <dir>` / `--prefix=<dir>` in a segment opened by `npm`, before any `--`;
160
+ * - `-C <dir>` right after `git` (its global options only, so `make -C` and `tar -C` stay);
161
+ * - `--test-concurrency=N` / `--test-concurrency N` (N digits) in a `node` segment holding `--test`.
162
+ * A `<dir>` is removed only when `sameProject(dir)` says it names the judged project (`projectDir`):
163
+ * a check run in another project still counts as not run. Separators (`&&`, `||`, `|`, `;`,
164
+ * newlines) are kept as they stand, so the piping and masking rules of `runsUnpiped` read the
165
+ * same line. shortcut: a segment is tokenized on spaces with quoted runs kept whole; a segment
166
+ * left unchanged keeps its text byte for byte. Pure: the plugin twin is a copy.
167
+ */
168
+ export function normalizeRun(command, sameProject) {
169
+ const cmd = String(command).replace(/[ \t]+/g, ' ');
170
+ return cmd.split(/(&&|\|\||[|;\n])/).map((seg, k) => {
171
+ if (k % 2) return seg;
172
+ const toks = seg.trim().match(/(?:"[^"]*"|'[^']*'|[^ "']|["'])+/g);
173
+ if (!toks) return seg;
174
+ const [tool] = toks;
175
+ const test = tool === 'node' && toks.includes('--test');
176
+ const out = [tool];
177
+ let opts = true;
178
+ for (let i = 1; i < toks.length; i += 1) {
179
+ const t = toks[i];
180
+ if (t === '--') opts = false;
181
+ if (opts && tool === 'npm') {
182
+ if (t === '--prefix' && i + 1 < toks.length && sameProject(toks[i + 1])) { i += 1; continue; }
183
+ if (t.startsWith('--prefix=') && sameProject(t.slice(9))) continue;
184
+ }
185
+ if (tool === 'git' && out.length === 1 && t === '-C' && i + 1 < toks.length && sameProject(toks[i + 1])) { i += 1; continue; }
186
+ if (opts && test) {
187
+ if (/^--test-concurrency=\d+$/.test(t)) continue;
188
+ if (t === '--test-concurrency' && /^\d+$/.test(toks[i + 1] ?? '')) { i += 1; continue; }
189
+ }
190
+ out.push(t);
191
+ }
192
+ if (out.length === toks.length) return seg;
193
+ return `${seg.startsWith(' ') ? ' ' : ''}${out.join(' ')}${seg.endsWith(' ') ? ' ' : ''}`;
194
+ }).join('');
195
+ }
196
+
197
+ /**
198
+ * The `sameProject` of `normalizeRun` for the project at `root`, a dir resolved against `cwd`:
199
+ * true only when it is the judged root ITSELF (real paths, so a junction or symlink to it counts;
200
+ * case-blind on Windows). The root may be a linked worktree. A sibling worktree or the main checkout
201
+ * of the same repository is false (user ruling 2026-11-14): a run there never saw this tree's
202
+ * edits. So are a subfolder, another repository, and a dir that does not exist. shortcut: a Git
203
+ * Bash path (`/c/Users/...`) does not resolve to a drive path here, so it reads as another
204
+ * project — the closed direction.
205
+ */
206
+ export function projectDir(root, cwd) {
207
+ const key = (p) => (process.platform === 'win32' ? p.toLowerCase() : p);
208
+ let me;
209
+ try { me = key(realpathSync(root)); } catch { return () => false; }
210
+ return (dir) => {
211
+ const bare = /^(["'])(.*)\1$/.exec(dir)?.[2] ?? dir;
212
+ if (!bare) return false;
213
+ try { return key(realpathSync(path.resolve(cwd, bare))) === me; } catch { return false; }
214
+ };
215
+ }
216
+
128
217
  /**
129
218
  * True when `command` proves the check group `g`: one of its forms runs unpiped and unmasked
130
219
  * (`runsUnpiped`), and — when the group names `refuse`, the flags that skip the tests
131
220
  * (`mvn install -DskipTests`, `gradle build -x test`, `cargo test --no-run`) — some unpiped
132
- * segment opening with a form carries none of them. shortcut: segments split on `&&`, `||`, `;`
133
- * and newlines without reading quotes; a quoted separator only makes a refusal more likely.
221
+ * segment opening with a form carries none of them. Both sides go through `normalizeRun` first;
222
+ * without `sameProject` no `--prefix`/`-C` dir counts, so only the concurrency flag goes.
223
+ * shortcut: segments split on `&&`, `||`, `;` and newlines without reading quotes; a quoted
224
+ * separator only makes a refusal more likely.
134
225
  */
135
- export function groupPasses(command, g) {
136
- if (!g.forms.some((f) => runsUnpiped(command, f))) return false;
226
+ export function groupPasses(command, g, sameProject = () => false) {
227
+ const run = normalizeRun(command, sameProject);
228
+ const forms = g.forms.map((f) => normalizeRun(f, sameProject));
229
+ if (!forms.some((f) => runsUnpiped(run, f))) return false;
137
230
  if (!g.refuse) return true;
138
- return String(command).replace(/[ \t]+/g, ' ').split(/&&|\|\||;|\n/).map((s) => s.trim())
231
+ return run.split(/&&|\|\||;|\n/).map((s) => s.trim())
139
232
  .some((s) => !s.includes('|') && !g.refuse.test(s)
140
- && g.forms.some((f) => s === f || s.startsWith(`${f} `)));
233
+ && forms.some((f) => s === f || s.startsWith(`${f} `)));
234
+ }
235
+
236
+ const NOTE_OPEN = '<task-notification>';
237
+
238
+ /**
239
+ * The openings of a block's feedback, should the host write it back as a user line. As a prompt
240
+ * it would open a new turn: the cap's `opening` would change, the record would count as none, and
241
+ * the turn's edit would fall before the judged turn. UNVERIFIED: no blocked Stop or SubagentStop
242
+ * exists in any transcript on this machine (2026-11), so the host's real feedback line is unseen.
243
+ * Both guesses are kept: Claude Code's `Stop hook feedback` label, and the gate's own reason.
244
+ */
245
+ const REASON_OPEN = 'Geneseed (Verify Before Asserting)';
246
+ const FEEDBACK_OPENS = ['Stop hook feedback', 'SubagentStop hook feedback', REASON_OPEN];
247
+
248
+ /**
249
+ * The text of a background task's notification, or null. Claude Code writes it twice: as a
250
+ * `queued_command` attachment (`attachment.prompt`, a string; 174 of them here are objects, not
251
+ * notifications) and as a `type: "user"` line holding the same text. `queue-operation` lines carry
252
+ * it a third time and are not read.
253
+ */
254
+ function notificationText(obj) {
255
+ let t = null;
256
+ if (obj.type === 'attachment') {
257
+ const a = obj.attachment;
258
+ if (a && a.type === 'queued_command') t = a.prompt;
259
+ } else if (obj.type === 'user') {
260
+ const c = obj.message && obj.message.content;
261
+ t = typeof c === 'string' ? c
262
+ : Array.isArray(c) && c.length === 1 && c[0] && c[0].type === 'text' ? c[0].text : null;
263
+ }
264
+ return typeof t === 'string' && t.trimStart().startsWith(NOTE_OPEN) ? t : null;
141
265
  }
142
266
 
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;
267
+ /**
268
+ * `[tool-use id, proven]` for one notification: proven only when its FIRST `<status>` is
269
+ * `completed` and the notification ENDS `completed (exit code 0)</summary></task-notification>`.
270
+ * The summary quotes the call's `description` (or, without one, its command: both seen here,
271
+ * 2026-11), which the agent writes freely, so a match anywhere else — a description holding
272
+ * `completed (exit code 0)</summary>` on a call that exited 1 — would be the agent's own text.
273
+ * The host's status tag precedes the summary, so the first one is the host's.
274
+ */
275
+ function notified(text) {
276
+ const id = /<tool-use-id>([^<]+)<\/tool-use-id>/.exec(text);
277
+ if (!id) return null;
278
+ const status = /<status>([^<]*)<\/status>/.exec(text);
279
+ return [id[1].trim(), Boolean(status) && status[1] === 'completed'
280
+ && /completed \(exit code 0\)<\/summary>\s*<\/task-notification>\s*$/.test(text)];
281
+ }
282
+
283
+ /**
284
+ * The text Claude Code gives a call that runs on in the background: started so
285
+ * (`run_in_background`), or moved there after its foreground timeout. A sub-agent's transcript
286
+ * records no `toolUseResult` at all (none on any line of one read here, 2026-11), so a call MOVED
287
+ * to the background — `run_in_background` absent from its input — shows only in this text. A
288
+ * command that prints such a line itself reads as pending: an owed check, never a false pass.
289
+ */
290
+ 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)/;
291
+ const resultText = (b) => (typeof b.content === 'string' ? b.content
292
+ : Array.isArray(b.content) && b.content[0] && typeof b.content[0].text === 'string' ? b.content[0].text : '');
293
+
294
+ /**
295
+ * A user line that opens a turn: the user typed it, it is not a tool result, a meta note or a task notification.
296
+ * Exported for ./agent-runs.mjs, which counts the same turn the gate judges.
297
+ */
298
+ export function isPrompt(obj, sidechain = false) {
299
+ if (obj.type !== 'user' || obj.isMeta || (obj.isSidechain && !sidechain)) return false;
300
+ if (notificationText(obj)) return false;
146
301
  const c = obj.message && obj.message.content;
302
+ const t = typeof c === 'string' ? c
303
+ : Array.isArray(c) && c.length === 1 && c[0] && c[0].type === 'text' ? c[0].text : null;
304
+ if (typeof t === 'string' && FEEDBACK_OPENS.some((p) => t.trimStart().startsWith(p))) return false;
147
305
  if (typeof c === 'string') return true;
148
306
  return Array.isArray(c) && c.length > 0 && !c.some((b) => b && b.type === 'tool_result');
149
307
  }
@@ -153,8 +311,16 @@ function isPrompt(obj) {
153
311
  * old text the host recorded for a write. `whole` false means the text is only the file's tail:
154
312
  * with no prompt in it the turn may start earlier, so the answer is null ("read more") — a turn
155
313
  * judged from its middle could miss its edit and wrongly pass.
314
+ *
315
+ * `sidechain` true reads a SUB-AGENT's own transcript (`agent_transcript_path` on SubagentStop).
316
+ * Every message line there carries `isSidechain: true` — seen in 300 of 300 transcripts under
317
+ * `~/.claude/projects/<p>/<session>/subagents/` here (2026-11) — and the turn opens on ONE user
318
+ * line, the Agent call's prompt as a string; the `isMeta` system reminder after it opens nothing.
319
+ * Read as a main transcript, it would hold no prompt and no call, and every sub-agent would pass.
320
+ * `cwd` is the last `cwd` the turn's lines name: a sub-agent's is its own (its worktree), where
321
+ * the payload's `cwd` is its parent's.
156
322
  */
157
- function turnOf(transcript, whole) {
323
+ function turnOf(transcript, whole, sidechain = false) {
158
324
  const entries = [];
159
325
  for (const line of splitLines(transcript)) {
160
326
  if (!line.trim()) continue;
@@ -162,30 +328,71 @@ function turnOf(transcript, whole) {
162
328
  }
163
329
  let start = -1;
164
330
  for (let i = entries.length - 1; i >= 0; i -= 1) {
165
- if (isPrompt(entries[i])) { start = i + 1; break; }
331
+ if (isPrompt(entries[i], sidechain)) { start = i + 1; break; }
166
332
  }
167
333
  if (start === -1) {
168
334
  if (!whole) return null;
169
335
  start = 0;
170
336
  }
337
+ // Which turn this is, for the block cap's state: the prompt line's `uuid`, else its text.
338
+ const first = entries[start - 1];
339
+ const opening = !first ? '' : typeof first.uuid === 'string' ? first.uuid
340
+ : JSON.stringify(first.message && first.message.content).slice(0, 300);
171
341
  const calls = []; // tool_use blocks, in order
172
342
  const results = new Map(); // tool_use_id -> is_error
173
343
  const originals = new Map(); // tool_use_id -> the file before a Write
344
+ const background = new Set(); // tool_use_id of a run_in_background launch
345
+ const finished = new Map(); // tool_use_id -> its notification proved it
346
+ let cwd = null;
347
+ // Distinct notifications in the turn, by text: the host writes each twice (an attachment and a
348
+ // user line holding the same text), and a set counts it once. The cap reads its size.
349
+ const notes = new Set();
174
350
  for (const obj of entries.slice(start)) {
175
- if (obj.isSidechain) continue;
351
+ if (obj.isSidechain && !sidechain) continue;
352
+ if (typeof obj.cwd === 'string' && obj.cwd) cwd = obj.cwd;
353
+ const note = notificationText(obj);
354
+ const said = note && notified(note);
355
+ if (note) notes.add(note.trim());
356
+ // The last notification wins: an agent's task may notify more than once.
357
+ if (said) finished.set(said[0], said[1]);
176
358
  const content = obj.message && obj.message.content;
177
359
  if (!Array.isArray(content)) continue;
178
360
  for (const b of content) {
179
361
  if (!b || typeof b !== 'object') continue;
180
- if (b.type === 'tool_use') calls.push(b);
181
- else if (b.type === 'tool_result') {
362
+ if (b.type === 'tool_use') {
363
+ calls.push(b);
364
+ if (b.input && b.input.run_in_background === true) background.add(b.id);
365
+ } else if (b.type === 'tool_result') {
182
366
  results.set(b.tool_use_id, b.is_error === true);
183
367
  const before = obj.toolUseResult && obj.toolUseResult.originalFile;
184
368
  if (typeof before === 'string') originals.set(b.tool_use_id, before);
369
+ if ((obj.toolUseResult && obj.toolUseResult.backgroundTaskId) || BACKGROUNDED.test(resultText(b))) {
370
+ background.add(b.tool_use_id);
371
+ }
185
372
  }
186
373
  }
187
374
  }
188
- return { calls, results, originals };
375
+ return { calls, results, originals, background, finished, cwd, opening, notes: notes.size };
376
+ }
377
+
378
+ /**
379
+ * The git roots a sub-agent's landed writes fall under, in first-write order: each target's own
380
+ * root (`gitRootOf` of its folder), so a worker in `.claude/worktrees/x` is judged as its own
381
+ * project, against its own list. A target outside every repository is no project's.
382
+ */
383
+ function editRoots({ calls, results }, cwd) {
384
+ const roots = [];
385
+ const byDir = new Map();
386
+ for (const c of calls) {
387
+ if (!EDIT_TOOLS.has(c.name) || results.get(c.id) === true) continue;
388
+ const p = c.input && (c.input.file_path || c.input.notebook_path || c.input.path);
389
+ if (typeof p !== 'string' || !p) continue;
390
+ const dir = path.dirname(path.resolve(cwd, p));
391
+ if (!byDir.has(dir)) byDir.set(dir, gitRootOf(dir));
392
+ const root = byDir.get(dir);
393
+ if (root && !roots.includes(root)) roots.push(root);
394
+ }
395
+ return roots;
189
396
  }
190
397
 
191
398
  /** The target of a landed write under `root`, absolute, or null. A denied write changed nothing. */
@@ -216,101 +423,259 @@ function weakenedTests({ calls, results, originals }, root, cwd) {
216
423
  * edit, or [] when the turn may end (no edit, or every check passed after it); null when `whole`
217
424
  * is false and the tail holds no prompt (`turnOf`). Exported for the unit tier — a transcript is
218
425
  * text no CLI cell can vary cheaply. A check is a line (one form) or a `{ label, forms }` group;
219
- * the answer lists labels.
426
+ * the answer lists labels. `sidechain` reads a sub-agent's transcript (`turnOf`).
220
427
  */
221
- export function doneDecide(transcript, checks, root, cwd = root, whole = true) {
222
- const turn = turnOf(transcript, whole);
428
+ export function doneDecide(transcript, checks, root, cwd = root, whole = true, sidechain = false) {
429
+ const turn = turnOf(transcript, whole, sidechain);
223
430
  return turn && missingChecks(turn, checks, root, cwd);
224
431
  }
225
432
 
226
433
  /** `weakenedTests` over transcript TEXT, for the unit tier: `doneDecide`'s other question. */
227
434
  export const weakenedIn = (transcript, root, cwd = root) => weakenedTests(turnOf(transcript, true), root, cwd);
228
435
 
229
- function missingChecks({ calls, results }, checks, root, cwd) {
436
+ function missingChecks({ calls, results, background, finished }, checks, root, cwd) {
230
437
  const groups = checks.map((c) => (typeof c === 'string' ? { label: c, forms: [c] } : c));
231
438
  let lastEdit = -1;
232
439
  calls.forEach((c, i) => { if (editTarget(c, results, root, cwd)) lastEdit = i; });
233
440
  if (lastEdit === -1) return [];
234
441
  const passed = new Set();
442
+ const same = projectDir(root, cwd);
235
443
  calls.slice(lastEdit + 1).forEach((c) => {
236
444
  const command = SHELL_TOOLS.has(c.name) && c.input && c.input.command;
237
445
  // A call with no result yet (the host has not flushed it) is not a pass.
238
446
  if (typeof command !== 'string' || results.get(c.id) !== false) return;
239
- for (const g of groups) if (groupPasses(command, g)) passed.add(g.label);
447
+ // A background launch's result only says it started: its notification is the verdict.
448
+ if (background.has(c.id) && finished.get(c.id) !== true) return;
449
+ for (const g of groups) if (groupPasses(command, g, same)) passed.add(g.label);
240
450
  });
241
451
  return groups.map((g) => g.label).filter((l) => !passed.has(l));
242
452
  }
243
453
 
454
+ /** The id of the turn's last landed write under any of `roots`, or null. */
455
+ function lastEditId({ calls, results }, roots, cwd) {
456
+ let id = null;
457
+ for (const c of calls) if (roots.some((r) => editTarget(c, results, r, cwd))) id = c.id;
458
+ return id;
459
+ }
460
+
461
+ // ---- the block cap -------------------------------------------------------------------------
462
+ // A block may repeat within a continuation, but only when it can change something: an edit landed
463
+ // since the last block (the agent is working, and its new edit owes the proof again) or a
464
+ // background verdict changed, and fewer than CAP_BLOCKS blocks were given in this continuation. A
465
+ // repeat with neither is the agent saying it will
466
+ // not run the checks, and blocking it again only spins (Claude Code itself ends a run of 8 Stop
467
+ // continuations, reset by a tool call — too late to be the gate's bound).
468
+ const CAP_BLOCKS = 3;
469
+ // The ceiling over a whole human turn, across its continuations. Each notification restarts the
470
+ // per-continuation count, so without it a red suite relaunched in the background loops for ever:
471
+ // it fails (a notification: new count, block), the relaunch turns the verdict back to pending
472
+ // (block), and again — a full suite run per cycle. Reset only by a new human prompt.
473
+ const TURN_BLOCKS = 10;
474
+ const CAP_DIR = path.join('notebook', 'done-gate');
475
+ const CAP_STALE_MS = 7 * 24 * 60 * 60 * 1000;
476
+
477
+ /**
478
+ * The cap's decision, pure: the state to save with a block, or null when the turn ends. `state` is
479
+ * what the last block of this session (and sub-agent) saved, `{ opening, lastEdit, notes, verdict,
480
+ * blocks }`, or null; a different `opening` is another turn, so it counts as none. With no state
481
+ * for this turn, `active` (`stop_hook_active`) alone decides, as before the cap: a Stop that follows
482
+ * a block we have no record of ends the turn. Once a block is on record, the record decides
483
+ * whatever `active` says, so a host that clears the flag mid-turn cannot loop the gate.
484
+ *
485
+ * PER CONTINUATION. A notification opens no turn, so one turn may span many continuations an
486
+ * unattended session's notifications drive. The count is per continuation: a notification since
487
+ * the last block (`notes`, the turn's count of distinct notifications, grew) starts a new one at
488
+ * count 1, so three early blocks cannot spend the cap for the rest of the turn. Inside one
489
+ * continuation the bound is CAP_BLOCKS, and a repeat needs a reason: a new edit, or a changed
490
+ * background `verdict` for an owed check (`pending` -> `failed`), since a failed proof with no new
491
+ * edit must still block.
492
+ */
493
+ export function nextBlock(state, { active, opening, lastEdit, notes = 0, verdict = '' }) {
494
+ const mine = state && state.opening === opening ? state : null;
495
+ if (!mine) return active ? null : { opening, lastEdit, notes, verdict, blocks: 1, total: 1 };
496
+ // The ceiling first: no notification and no verdict reopens a turn that has spent it.
497
+ const total = mine.total ?? 0;
498
+ if (total >= TURN_BLOCKS) return null;
499
+ if (notes > (mine.notes ?? 0)) return { opening, lastEdit, notes, verdict, blocks: 1, total: total + 1 };
500
+ if (mine.blocks >= CAP_BLOCKS) return null;
501
+ if (mine.lastEdit === lastEdit && (mine.verdict ?? '') === verdict) return null;
502
+ return { opening, lastEdit, notes, verdict, blocks: mine.blocks + 1, total: total + 1 };
503
+ }
504
+
505
+ /** True when `state` is this turn's record and has spent the per-turn ceiling: `nextBlock`'s first refusal, named. */
506
+ export const turnCeilingReached = (state, opening) =>
507
+ Boolean(state && state.opening === opening && (state.total ?? 0) >= TURN_BLOCKS);
508
+
509
+ /**
510
+ * Each owed check's background state since the turn's last edit, `label -> 'pending' | 'failed'`:
511
+ * the last background run of one of its forms, launched with no completion seen, or completed with
512
+ * anything but exit 0. A check never run in the background has no entry.
513
+ */
514
+ function backgroundOwed({ calls, results, background, finished }, checks, owedLabels, lastEdit, root, cwd) {
515
+ const states = new Map();
516
+ const same = projectDir(root, cwd);
517
+ let after = lastEdit === null;
518
+ for (const c of calls) {
519
+ if (!after) { after = c.id === lastEdit; continue; }
520
+ const command = SHELL_TOOLS.has(c.name) && c.input && c.input.command;
521
+ if (typeof command !== 'string' || results.get(c.id) !== false || !background.has(c.id)) continue;
522
+ for (const g of checks) {
523
+ if (!owedLabels.has(g.label) || !groupPasses(command, g, same)) continue;
524
+ states.set(g.label, finished.has(c.id) ? (finished.get(c.id) ? 'passed' : 'failed') : 'pending');
525
+ }
526
+ }
527
+ for (const [l, s] of states) if (s === 'passed') states.delete(l);
528
+ return states;
529
+ }
530
+
244
531
  /**
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
532
+ * The cap's state file, one per session (and sub-agent), under the install's notebook — the
533
+ * store-watch baseline pattern (`./store-watch.mjs`). Read and written only on a Stop with owed
534
+ * checks, so an allowed Stop costs nothing here. Unreadable reads as none. Exported for
535
+ * ./agent-runs.mjs, which reads a finished sub-agent's block count back from it.
536
+ */
537
+ export function capFile(install, meta) {
538
+ const key = [meta.session_id, meta.hook_event_name === 'SubagentStop' ? meta.agent_id : null]
539
+ .filter((k) => typeof k === 'string' && k).join('~');
540
+ return key ? path.join(install, CAP_DIR, `${key.replace(/[^\w.~-]/g, '_').slice(0, 160)}.json`) : null;
541
+ }
542
+ function readCap(file) {
543
+ try { return JSON.parse(readFileSync(file, 'utf8')); } catch { return null; }
544
+ }
545
+ function saveCap(file, state) {
546
+ try {
547
+ mkdirSync(path.dirname(file), { recursive: true });
548
+ writeFileSync(file, JSON.stringify(state));
549
+ } catch { return; /* unwritable: the next Stop finds no record, and ends the turn as before the cap */ }
550
+ if (state.blocks !== 1) return;
551
+ // A turn's first block: drop other sessions' stale files, as the baselines do. After the write,
552
+ // and one entry at a time: a file another Stop removed (ENOENT) or holds (EPERM) costs only itself.
553
+ let names = [];
554
+ try { names = readdirSync(path.dirname(file)); } catch { /* nothing to sweep */ }
555
+ for (const n of names) {
556
+ try {
557
+ const old = path.join(path.dirname(file), n);
558
+ if (Date.now() - statSync(old).mtimeMs > CAP_STALE_MS) unlinkSync(old);
559
+ } catch { /* gone or held: the next sweep tries it again */ }
560
+ }
561
+ }
562
+
563
+ /**
564
+ * The Stop-side wrapper `cmdLearn` calls first, on Stop and on SubagentStop. Returns 'block' when
565
+ * it printed a block (the turn goes on, so `learn` must not distil yet); 'advisory' when it
566
+ * printed the advisory `systemMessage` (the turn ends and learning runs, but `learn` must print
567
+ * nothing more on stdout, or the JSON stops parsing); null in every other case, with nothing on
568
+ * stdout. `install` is the root `cmdLearn` already derived from `--memory` (null without one), so
569
+ * the ledger lands in the same root its sovereignty check read. `read` is `cmdLearn`'s per-Stop
251
570
  * transcript reader, so the distillation after an allow reuses the windows read here.
571
+ *
572
+ * SUBAGENTSTOP. The turn judged is the sub-agent's own, from `agent_transcript_path` (no path: not
573
+ * judged, and a stderr line when the cwd's project lists checks, as on Bob). The payload's `cwd`
574
+ * is the PARENT's, so the projects are the git roots of the files the sub-agent wrote
575
+ * (`editRoots`), each judged against its own `doneChecksOf`. A block keeps the sub-agent running
576
+ * with the reason as its next instruction (Claude Code hooks doc, SubagentStop). An advisory is
577
+ * a stderr line and a ledger entry only: nobody sees a sub-agent's `systemMessage`, so it returns
578
+ * null and prints nothing on stdout.
252
579
  */
253
580
  export function doneGate(meta, args, install, read = tailReader()) {
254
581
  try {
582
+ const sub = meta.hook_event_name === 'SubagentStop';
255
583
  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);
584
+ const cwdRoot = gitRootOf(cwd);
585
+ if (!sub && !cwdRoot) return null;
586
+ const here = cwdRoot ? doneChecksOf(cwdRoot) : null;
587
+ const listed = Boolean(here && here.blocking && here.checks.length);
588
+ const file = sub ? meta.agent_transcript_path : meta.transcript_path;
259
589
  // Bob's Stop payload carries no transcript (learn's I2): nothing to judge, and a listed gate
260
590
  // 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`);
591
+ if (args.host === 'bob' || typeof file !== 'string' || (sub && !file)) {
592
+ if (listed) {
593
+ err(sub ? '[done-gate] no agent transcript — sub-agent turn not judged.\n'
594
+ : `[done-gate] no transcript${args.host === 'bob' ? ' (bob)' : ''} — turn not judged.\n`);
595
+ }
263
596
  return null;
264
597
  }
265
- let verdict;
598
+ let turn;
266
599
  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
- });
600
+ turn = read(file, (text, whole) => turnOf(text, whole, sub));
273
601
  } catch {
274
602
  // 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');
603
+ if (sub ? listed : here.checks.length) err('[done-gate] transcript unreadable — turn not judged.\n');
276
604
  return null;
277
605
  }
278
- const { missing } = verdict;
606
+ const at = sub ? turn.cwd || cwd : cwd;
607
+ const judged = (sub ? editRoots(turn, at) : [cwdRoot]).map((root) => {
608
+ const d = root === cwdRoot ? here : doneChecksOf(root);
609
+ return { root, ...d, missing: missingChecks(turn, d.checks, root, at), weakened: weakenedTests(turn, root, at) };
610
+ });
611
+ // One project names nothing; several say whose each entry is.
612
+ const tag = (r) => (judged.length > 1 ? `${r.root}: ` : '');
613
+ const list = (rs) => rs.flatMap((r) => r.missing.map((m) => `${tag(r)}${m}`)).join('; ');
279
614
  // `--no-test-note`: the line goes, the done checks do not.
280
- const weakened = args.noTestNote ? [] : verdict.weakened;
615
+ const weakened = args.noTestNote ? [] : judged.flatMap((r) => r.weakened.map((w) => `${tag(r)}${w}`));
616
+ const owed = judged.filter((r) => r.blocking && r.missing.length);
617
+ const inferred = judged.filter((r) => !r.blocking && r.missing.length);
618
+ const who = sub ? 'this sub-agent' : 'this turn';
281
619
  // One JSON document on stdout, whatever the advisories: Stop reads no second one.
282
620
  const advise = (...said) => {
283
621
  if (weakened.length) {
284
622
  // A stable id, not a law number: an advisory is no hook-pinned rule (`HOOK_PINNED`).
285
623
  recordGate(install, ADVISORY_VERB, 'cure-the-cause');
286
- const line = `[done-gate] advisory — test weakened this turn: ${weakened.join('; ')}`;
624
+ const line = `[done-gate] advisory — test weakened ${sub ? 'by a sub-agent' : 'this turn'}: ${weakened.join('; ')}`;
287
625
  err(`${line}\n`);
288
626
  said.push(`${line}. Cure the Cause: fix the code, not the test.`);
289
627
  }
628
+ if (sub) return null;
290
629
  out(`${JSON.stringify({ systemMessage: said.join(' ') })}\n`);
291
630
  return 'advisory';
292
631
  };
293
- if (!missing.length && weakened.length) return advise();
294
- if (!missing.length) return null;
295
- if (!blocking) {
632
+ const inferredSaid = () => {
633
+ if (!inferred.length) return [];
296
634
  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) {
635
+ err(`[done-gate] advisory${sub ? ' (sub-agent)' : ''} — unproven since the last edit: ${list(inferred)}\n`);
636
+ const sources = [...new Set(inferred.map((r) => r.source))].join(', ');
637
+ return [`Geneseed done gate (advisory) — ${who} edited files, and these checks `
638
+ + `inferred from ${sources} have not passed since the last edit: ${list(inferred)}. `
639
+ + `List your own in ${DONE_LIST} to make the gate block.`];
640
+ };
641
+ const settle = () => {
642
+ const said = inferredSaid();
643
+ return said.length || weakened.length ? advise(...said) : null;
644
+ };
645
+ if (!owed.length) return settle();
646
+ const active = meta.stop_hook_active === true;
647
+ const capPath = install ? capFile(install, meta) : null;
648
+ // The owed checks whose proof is a background run still pending, or one that reported a failure.
649
+ const bg = owed.flatMap((r) => [...backgroundOwed(turn, r.checks, new Set(r.missing), lastEditId(turn, [r.root], at), r.root, at)]
650
+ .map(([l, st]) => [`${tag(r)}${l}`, st]));
651
+ const verdict = bg.map(([l, st]) => `${l}=${st}`).sort().join('\n');
652
+ // Without an install or a session id there is nowhere to count: one block per turn, as before.
653
+ const record = capPath ? readCap(capPath) : null;
654
+ const next = capPath
655
+ ? nextBlock(record, { active, opening: turn.opening, notes: turn.notes, verdict,
656
+ lastEdit: lastEditId(turn, owed.map((r) => r.root), at) })
657
+ : (active ? null : true);
658
+ if (!next) {
303
659
  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;
660
+ const why = turnCeilingReached(record, turn.opening)
661
+ ? `total ceiling reached (${TURN_BLOCKS} blocks this turn)` : 'cap reached';
662
+ err(`[done-gate] ${why} — turn ends with unproven checks: ${list(owed)}\n`);
663
+ return settle();
306
664
  }
665
+ if (capPath) saveCap(capPath, next);
307
666
  // The turn goes on, so a weakened test is said at the Stop that really ends it.
308
667
  recordGate(install, 'done-gate', 'law-3');
668
+ const named = (st) => bg.filter(([, s]) => s === st).map(([l]) => l).join('; ');
669
+ const pending = named('pending');
670
+ const failed = named('failed');
309
671
  out(`${JSON.stringify({
310
672
  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.',
673
+ reason: `${REASON_OPEN} — ${who} edited files, and these `
674
+ + `checks from ${DONE_LIST} have not passed since the last edit: ${list(owed)}. `
675
+ + (pending ? `Still running in the background, with no completion seen: ${pending}; a launch is no pass. ` : '')
676
+ + (failed ? `Run in the background and reported a failure: ${failed}. ` : '')
677
+ + 'Run them unpiped, or wait for the background run to complete with exit 0, '
678
+ + 'or say plainly that they were not run and why.',
314
679
  })}\n`);
315
680
  return 'block';
316
681
  } catch (e) {