geneseed 5.3.0 → 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 (198) hide show
  1. package/CHANGELOG.md +95 -0
  2. package/README.md +23 -20
  3. package/SHIPPED.md +7 -7
  4. package/adapters/bob/README.md +31 -18
  5. package/adapters/claude-code/README.md +27 -22
  6. package/adapters/openclaude/README.md +18 -8
  7. package/adapters/opencode/HOW-OPENCODE-LOADS.md +8 -3
  8. package/adapters/opencode/README.md +3 -2
  9. package/adapters/opencode/plugins/geneseed-activity.js +20 -21
  10. package/adapters/opencode/plugins/geneseed-context.js +175 -62
  11. package/adapters/opencode/plugins/geneseed-guard.js +419 -205
  12. package/adapters/opencode/plugins/geneseed-workflow.js +3 -2
  13. package/adapters/opencode/workflows/_runtime.js +3 -2
  14. package/bin/geneseed-cli.mjs +7 -0
  15. package/bin/geneseed-hook.mjs +59 -11
  16. package/docs/PRD.md +1 -1
  17. package/docs/README.md +1 -0
  18. package/docs/concepts/agents.md +1 -1
  19. package/docs/concepts/collaboration.md +2 -2
  20. package/docs/concepts/enforcement-table.md +5 -2
  21. package/docs/concepts/exclusions.md +18 -4
  22. package/docs/concepts/footprint.md +11 -1
  23. package/docs/concepts/foreman-mode.md +1 -1
  24. package/docs/concepts/hook-gates.md +5 -5
  25. package/docs/concepts/hooks.md +4 -3
  26. package/docs/concepts/host-matrix.md +24 -6
  27. package/docs/concepts/kits.md +12 -2
  28. package/docs/concepts/loop-bricks.md +3 -3
  29. package/docs/concepts/loops.md +6 -4
  30. package/docs/concepts/ownership.md +1 -1
  31. package/docs/concepts/rules.md +2 -2
  32. package/docs/concepts/skills.md +1 -1
  33. package/docs/design-history.md +8 -0
  34. package/docs/extending.md +112 -35
  35. package/docs/guides/auto-merge.md +100 -0
  36. package/docs/guides/choose-your-setup.md +1 -1
  37. package/docs/guides/headless.md +1 -1
  38. package/docs/guides/install-bob.md +2 -2
  39. package/docs/guides/install-clone.md +1 -1
  40. package/docs/guides/install-openclaude.md +1 -1
  41. package/docs/guides/install.md +1 -1
  42. package/docs/guides/loop-finish.md +3 -3
  43. package/docs/guides/loop-running.md +4 -4
  44. package/docs/guides/project-context.md +1 -1
  45. package/docs/guides/run-a-factory.md +2 -2
  46. package/docs/guides/setup-doctrines.md +2 -2
  47. package/docs/guides/setup-footprint.md +1 -1
  48. package/docs/guides/uninstall.md +3 -3
  49. package/docs/guides/upgrade.md +1 -1
  50. package/docs/guides/verify.md +12 -0
  51. package/docs/guides/worktree.md +1 -1
  52. package/docs/reference/environment.md +5 -2
  53. package/docs/reference/plugin-activity.md +1 -1
  54. package/docs/reference/plugin-guard.md +1 -1
  55. package/docs/reference/plugin-learn.md +1 -1
  56. package/docs/reference/plugin-workflow.md +1 -1
  57. package/docs/reference/troubleshoot-doctor.md +2 -2
  58. package/docs/reference/troubleshoot-hooks.md +2 -2
  59. package/docs/reference/troubleshoot-install.md +3 -3
  60. package/docs/reference/troubleshoot-tools.md +1 -1
  61. package/docs/token-footprint.md +68 -4
  62. package/docs/understand/design-choices-hosts.md +1 -1
  63. package/docs/understand/design-choices-shape.md +1 -0
  64. package/docs/understand/enforced-vs-asked.md +2 -2
  65. package/docs/understand/machine-bob.md +1 -1
  66. package/docs/understand/machine-claude.md +2 -2
  67. package/docs/understand/on-your-machine.md +1 -1
  68. package/docs/web-ui.md +10 -5
  69. package/harness.config.json +1 -1
  70. package/js/README.md +5 -3
  71. package/js/build/args.mjs +13 -2
  72. package/js/build/driver.mjs +34 -7
  73. package/js/build/emit-claude.mjs +9 -5
  74. package/js/build/emit-opencode.mjs +13 -9
  75. package/js/build/generate.mjs +10 -165
  76. package/js/build/profile.mjs +318 -0
  77. package/js/build/render.mjs +81 -3
  78. package/js/build/retired-skills.mjs +60 -13
  79. package/js/build/source.mjs +15 -1
  80. package/js/build/stubs.mjs +4 -1
  81. package/js/cli-table.json +48 -3
  82. package/js/hosts/done-checks.mjs +6 -0
  83. package/js/hosts/geneseed-dir.mjs +3 -2
  84. package/js/hosts/gitref.mjs +5 -3
  85. package/js/hosts/hook-tap.mjs +104 -0
  86. package/js/hosts/hooks-context.mjs +4 -2
  87. package/js/hosts/hooks-done.mjs +345 -55
  88. package/js/hosts/hooks-learn.mjs +51 -19
  89. package/js/hosts/hooks-prims.mjs +5 -3
  90. package/js/hosts/hooks.mjs +172 -19
  91. package/js/hosts/hosts.mjs +80 -12
  92. package/js/hosts/installs.mjs +26 -1
  93. package/js/hosts/native.mjs +33 -7
  94. package/js/hosts/owned.mjs +7 -6
  95. package/js/hosts/ownership-gate.mjs +14 -1
  96. package/js/hosts/settings.mjs +273 -105
  97. package/js/hosts/shim.mjs +4 -4
  98. package/js/hosts/usage.mjs +9 -3
  99. package/js/inspect/checks-constitution.mjs +32 -0
  100. package/js/inspect/checks-probe.mjs +66 -5
  101. package/js/inspect/checks-repo.mjs +196 -2
  102. package/js/inspect/cost.mjs +34 -2
  103. package/js/inspect/diff.mjs +21 -3
  104. package/js/inspect/doctor.mjs +6 -1
  105. package/js/inspect/inventory.mjs +1 -1
  106. package/js/lib/machine-dir.mjs +1 -1
  107. package/js/lib/node-floor.mjs +46 -6
  108. package/js/maintain/setup.mjs +5 -1
  109. package/js/maintain/uninstall.mjs +42 -16
  110. package/js/maintain/update.mjs +4 -2
  111. package/js/web/actions.mjs +17 -12
  112. package/js/web/api.mjs +7 -2
  113. package/package.json +1 -1
  114. package/registry.json +14 -0
  115. package/src/AGENT.md.tmpl +15 -17
  116. package/src/bricks/pr-open.md +3 -2
  117. package/src/doctrines/ops.md +2 -2
  118. package/src/doctrines/process.md +40 -36
  119. package/src/factories/analysis-to-build.json +1 -1
  120. package/src/factories/bug-report-to-fix.json +1 -1
  121. package/src/factories/issue-to-pr.json +1 -1
  122. package/src/kits/terminal-tools/rules.md +10 -0
  123. package/src/kits/terminal-tools.json +13 -0
  124. package/src/licenses/herdr.txt +201 -0
  125. package/src/modes/foreman.md +6 -3
  126. package/src/skills/_self-improvement.md +9 -7
  127. package/src/skills/commit.md +17 -17
  128. package/src/skills/debug/ci.md +1 -1
  129. package/src/skills/dependencies.md +3 -3
  130. package/src/skills/document-project.md +3 -2
  131. package/src/skills/factory.md +13 -4
  132. package/src/skills/geneseed.md +4 -2
  133. package/src/skills/git-history.md +5 -7
  134. package/src/skills/herdr.md +135 -0
  135. package/src/skills/loop.md +3 -2
  136. package/src/skills/opencode-cli.md +84 -0
  137. package/src/skills/pipeline.md +1 -1
  138. package/src/skills/release.md +5 -8
  139. package/src/skills/review-response.md +4 -2
  140. package/src/skills/rule.md +27 -1
  141. package/src/skills/ship.md +54 -7
  142. package/src/skills/worktree.md +2 -2
  143. package/src/upstreams.json +7 -0
  144. package/themes/_TEMPLATE.json +2 -0
  145. package/themes/biker.json +2 -0
  146. package/themes/commentator.json +2 -0
  147. package/themes/cyberpunk.json +2 -0
  148. package/themes/gamer.json +2 -0
  149. package/themes/imperial.json +2 -0
  150. package/themes/joker.json +2 -0
  151. package/themes/marvin.json +2 -0
  152. package/themes/mean.json +2 -0
  153. package/themes/military.json +2 -0
  154. package/themes/neutral.json +2 -0
  155. package/themes/pirate.json +2 -0
  156. package/themes/sports.json +2 -0
  157. package/themes/verstappen.json +2 -0
  158. package/themes/wizard.json +2 -0
  159. package/web/dist/assets/Activity-D2kOc3yi.js +1 -0
  160. package/web/dist/assets/ActivityDetail-By3xOr21.js +1 -0
  161. package/web/dist/assets/{Bonsai-Bfpb6W-1.js → Bonsai-CBWDTBA4.js} +1 -1
  162. package/web/dist/assets/{CopyButton-ByIntFtB.js → CopyButton-BVbpriMB.js} +1 -1
  163. package/web/dist/assets/Dashboard-CIJLPHM9.js +2 -0
  164. package/web/dist/assets/{Docs-DvlMJhpu.js → Docs-CiRRIELs.js} +3 -3
  165. package/web/dist/assets/Factories-DhyK0O8d.js +1 -0
  166. package/web/dist/assets/GreenhouseView-DW3PgTPy.js +1 -0
  167. package/web/dist/assets/Installs-B6nlo-Ly.js +3 -0
  168. package/web/dist/assets/JournalView-O65qEWfp.js +1 -0
  169. package/web/dist/assets/Kits-C5U-yT6Z.js +1 -0
  170. package/web/dist/assets/Laws-CuTw_XNf.js +4 -0
  171. package/web/dist/assets/{LibRows-DEHjIoD-.js → LibRows-D6-CVa3K.js} +1 -1
  172. package/web/dist/assets/Library-CzPlerd6.js +3 -0
  173. package/web/dist/assets/Loops-CqNF_-nS.js +2 -0
  174. package/web/dist/assets/Markdown-CxkA7940.js +71 -0
  175. package/web/dist/assets/OperatorHudView-BNr8K5qj.js +1 -0
  176. package/web/dist/assets/Personal-DeDb9e8O.js +2 -0
  177. package/web/dist/assets/Settings-B8MPN_AD.js +1 -0
  178. package/web/dist/assets/{Tabs-CWeQTADL.js → Tabs-DJzAez4h.js} +1 -1
  179. package/web/dist/assets/index-BL3P-9Rg.js +6 -0
  180. package/web/dist/assets/{index-CsAZq0BQ.css → index-CRWqKxfY.css} +1 -1
  181. package/web/dist/index.html +2 -2
  182. package/adapters/claude-code/settings.json +0 -52
  183. package/web/dist/assets/Activity-CqJiquEq.js +0 -1
  184. package/web/dist/assets/ActivityDetail-BSzevynX.js +0 -1
  185. package/web/dist/assets/Dashboard-DBOEi9lQ.js +0 -2
  186. package/web/dist/assets/Factories-Bpvv7L2H.js +0 -1
  187. package/web/dist/assets/GreenhouseView-GpBsYn50.js +0 -1
  188. package/web/dist/assets/Installs-BlGmVrFK.js +0 -3
  189. package/web/dist/assets/JournalView-iLuLrOxE.js +0 -1
  190. package/web/dist/assets/Kits-DRwpxC-J.js +0 -1
  191. package/web/dist/assets/Laws-CZkiNOWQ.js +0 -4
  192. package/web/dist/assets/Library-B4K-1iNF.js +0 -3
  193. package/web/dist/assets/Loops-BWSzaW8E.js +0 -2
  194. package/web/dist/assets/Markdown-0ORz7tAc.js +0 -69
  195. package/web/dist/assets/OperatorHudView-BAXwCEvY.js +0 -1
  196. package/web/dist/assets/Personal-Bp9nV4GR.js +0 -2
  197. package/web/dist/assets/Settings-CWWuaIp-.js +0 -1
  198. package/web/dist/assets/index-How7SzDZ.js +0 -6
@@ -24,9 +24,9 @@ const ROOT = path.resolve(import.meta.dirname, '../..');
24
24
 
25
25
  const AGENT_NAME_RE = /^[a-z][a-z0-9-]{1,40}$/;
26
26
  const MAX_NOTES_CHARS = 16000;
27
- // Host payloads name the finished subagent inconsistently; try each.
28
- const SUBAGENT_NAME_FIELDS = ['agent_name', 'agent_type', 'subagent_type', 'agent',
29
- 'agent_id'];
27
+ // Host payloads name the finished subagent inconsistently. Never `agent_id`: it is one dispatch's
28
+ // id, so a lesson keyed on it is a file per dispatch that no later dispatch ever reads.
29
+ const SUBAGENT_NAME_FIELDS = ['agent_name', 'agent_type', 'subagent_type', 'agent'];
30
30
 
31
31
  const PLUGIN_LEARN = path.join(ROOT, 'adapters', 'opencode', 'plugins', 'geneseed-learn.js');
32
32
 
@@ -74,6 +74,17 @@ export function resolveAgentName(raw) {
74
74
  return name && AGENT_NAME_RE.test(name) ? name : null;
75
75
  }
76
76
 
77
+ /**
78
+ * The agent a SubagentStop payload names, as a safe slug, or null. The FIRST field present
79
+ * decides, and a value that is no slug yields no lesson: a plugin's agent arrives namespaced
80
+ * (`plug:rev`), and falling through to a later field would file its lesson under another name.
81
+ * Exported for the unit tier, like `readNotes` below.
82
+ */
83
+ export function subagentNameOf(meta) {
84
+ const field = SUBAGENT_NAME_FIELDS.find((f) => meta[f] !== undefined && meta[f] !== null && meta[f] !== '');
85
+ return field ? resolveAgentName(meta[field]) : null;
86
+ }
87
+
77
88
  /** The lifecycle-hook payload if stdin is one, else `{}`. */
78
89
  function hookMeta(raw) {
79
90
  const s = raw.trim();
@@ -216,9 +227,22 @@ export function buildLearnPrompt(notes, facts) {
216
227
  * distilled memory carrying an accent or an em dash is WRITTEN to the store, so a
217
228
  * mis-decode outlives the process. `maxBuffer` is lifted off Node's 1 MB default, which
218
229
  * would truncate a long reply into a silently-half-parsed set of memory files.
230
+ *
231
+ * BOUNDED: a model CLI that hangs (a login prompt, a dead network) used to hold Stop until the
232
+ * host's own hook timeout killed the hook, and that kill loses whatever the hook had still to
233
+ * say. `$GENESEED_LLM_TIMEOUT` is the limit in seconds, 120 unless it names a positive number.
234
+ * A CLI stopped at the limit has said nothing usable, so its partial reply is dropped, never
235
+ * parsed into half a memory file: one stderr line, and the run ends as if it answered nothing.
219
236
  */
237
+ const LLM_TIMEOUT_S = 120;
238
+ function llmTimeoutSeconds() {
239
+ const n = Number(process.env.GENESEED_LLM_TIMEOUT);
240
+ return Number.isFinite(n) && n > 0 ? n : LLM_TIMEOUT_S;
241
+ }
242
+
220
243
  function runLlm(llm, prompt) {
221
244
  const argv = splitWords(llm);
245
+ const seconds = llmTimeoutSeconds();
222
246
  // `NO_WINDOW` folds in `CREATE_NO_WINDOW`; a model CLI invoked from the windowless daemon
223
247
  // otherwise pops a console for as long as it takes to answer.
224
248
  //
@@ -228,8 +252,12 @@ function runLlm(llm, prompt) {
228
252
  // killing the outermost call. The marker rides in the child's own environment (inherited by
229
253
  // every grandchild too), and `cmdLearn`'s first line stands down the instant it sees it.
230
254
  const proc = spawnSync(argv[0], [...argv.slice(1), prompt],
231
- { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024,
255
+ { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024, timeout: seconds * 1000, killSignal: 'SIGKILL',
232
256
  env: { ...process.env, GENESEED_LEARN_CHILD: '1' }, ...NO_WINDOW });
257
+ if (proc.error && /** @type {NodeJS.ErrnoException} */ (proc.error).code === 'ETIMEDOUT') {
258
+ err(`[learn] ${argv[0]} gave no answer in ${seconds} s and was stopped - nothing learned.\n`);
259
+ return { stdout: '', stderr: '', returncode: 0, error: null };
260
+ }
233
261
  // Universal newlines, because Python reads the pipe in TEXT mode: a model CLI that is
234
262
  // itself a Python script emits CRLF on Windows, `subprocess` folds it to `\n`, and
235
263
  // `write_text` expands it again on the way into the memory file. Node hands back the raw
@@ -253,11 +281,7 @@ function runLlm(llm, prompt) {
253
281
  * parity of mechanism, degrading to a no-op, never a crash.
254
282
  */
255
283
  function learnAgentLesson(meta, notes, args) {
256
- let agent = null;
257
- for (const field of SUBAGENT_NAME_FIELDS) {
258
- agent = resolveAgentName(meta[field]);
259
- if (agent) break;
260
- }
284
+ const agent = subagentNameOf(meta);
261
285
  if (!agent) return 0;
262
286
  const memDir = resolveMemoryDir(args.memory);
263
287
  if (!memDir) return 0;
@@ -283,7 +307,9 @@ function learnAgentLesson(meta, notes, args) {
283
307
  }
284
308
  }
285
309
  if (proc.returncode !== 0 && proc.stderr) err(proc.stderr);
286
- return proc.returncode;
310
+ // Only a SubagentStop hook reaches this, and the model CLI's code is not the hook's: exit 2
311
+ // there sends the subagent back to work. The failure is on stderr above.
312
+ return 0;
287
313
  }
288
314
 
289
315
  /** `--memory` of a global install's hook, swapped for the shared store when that exists. */
@@ -341,14 +367,15 @@ export function cmdLearn(args) {
341
367
  args = { ...args, memory: sharedStoreFor(install, args) };
342
368
  }
343
369
 
344
- // The done gate (#289) judges the turn BEFORE anything here spawns, and only on Stop. A block
345
- // 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.
346
373
  // `--no-done-gate` (the install switched Law III's gate off) skips the check, never the
347
374
  // distillation below.
348
375
  // One reader for this Stop: an allowed turn's distillation reuses the windows the gate read.
349
376
  const read = tailReader();
350
377
  // An advisory verdict already holds stdout: nothing below may print there after it.
351
- const verdict = hookEvent === 'Stop' && !args.file && !args.noDoneGate
378
+ const verdict = (hookEvent === 'Stop' || hookEvent === 'SubagentStop') && !args.file && !args.noDoneGate
352
379
  ? doneGate(meta, args, install, read) : null;
353
380
  if (verdict === 'block') return 0;
354
381
 
@@ -428,13 +455,18 @@ export function cmdLearn(args) {
428
455
  if (!created.length && !updated.length && !archived.length) {
429
456
  err('[learn] nothing new to store (all duplicates).\n');
430
457
  }
431
- } else if (verdict === 'advisory') {
432
- err(output);
433
- } else {
458
+ } else if (!hookEvent) {
459
+ // A person running `learn` by hand with no store: the reply is what they asked to see.
434
460
  out(output);
461
+ } else if (output.trim() && output.trim().toUpperCase() !== 'NOTHING') {
462
+ // On a hook call stdout is the host's: it holds at most ONE JSON document (the change report
463
+ // or an advisory above), and the model's raw words after it made two, which no host parses,
464
+ // so the report was lost. A bare NOTHING says nothing and is dropped.
465
+ err(output);
435
466
  }
436
467
  if (proc.returncode !== 0 && proc.stderr) err(proc.stderr);
437
- // After an advisory, the model CLI's code is not this hook's: exit 2 on Stop would turn the
438
- // advisory into a block, and any non-zero drops the JSON already on stdout.
439
- return verdict === 'advisory' ? 0 : proc.returncode;
468
+ // On a hook call the model CLI's code is not this hook's: exit 2 on Stop or PreCompact blocks
469
+ // the turn's end or the compaction, and any non-zero drops the JSON already on stdout. The
470
+ // failure is on stderr above. A manual run keeps the code, so a script can test it.
471
+ return hookEvent ? 0 : proc.returncode;
440
472
  }
@@ -410,9 +410,11 @@ const GATE_ASKS = {
410
410
  impact: 'the scan can run for hours', tail: 'search one named directory',
411
411
  can: 'You can name the directory to search.' }),
412
412
  // Routine and frequent, so one line: three more would train the user to stop reading all of them.
413
- commit: () => ({ rule: 'Consent Before Push', quote: true, short: true,
414
- line: 'This command commits or pushes with git, which needs your approval each time.',
415
- why: 'every commit and push is your decision', can: GATE_RUN_IT }),
413
+ // `strict`: the install asks for every commit and push (`--strict-consent`), not only main's.
414
+ commit: (f) => ({ rule: 'Consent Before Push', quote: true, short: true,
415
+ line: f.strict ? 'This command commits or pushes with git, which needs your approval each time.'
416
+ : 'This command commits or pushes onto the main branch, forces a push, or takes a form the gate cannot read, so it needs your approval.',
417
+ why: f.strict ? 'every commit and push is your decision' : 'the main branch changes only through a pull request', can: GATE_RUN_IT }),
416
418
  // The next four are the OpenCode guard's alone: no hook reads a key path, a stream, a wiki manifest
417
419
  // or an unknown tool's arguments, and the guard only refuses them. `wiki` has no rule to name.
418
420
  'secret-file': (f) => ({ rule: 'Sealed Secrets', line: `This edit writes to ${gateName(gatePath(f.name))}, a file that holds a secret or key.`,
@@ -12,7 +12,7 @@
12
12
  * (the default) reads `hookSpecificOutput.permissionDecision: "ask"` and shows the user a
13
13
  * prompt; the one `"deny"` (the ownership first-write gate, `./ownership-gate.mjs`) carries
14
14
  * its reason to the MODEL instead. `--host bob` is Bob's own protocol: PreToolUse ignores stdout and refuses only on
15
- * EXIT CODE 2, so `BLOCK_RULES` (Laws I and IV, plus rigor-5 and ops-2) exit 2 with the reason on stderr,
15
+ * EXIT CODE 2, so the rules in `BLOCK_RULES` (below) exit 2 with the reason on stderr,
16
16
  * as does the ownership gate (through `deny`, with a one-time tail in place of `BOB_FINAL`),
17
17
  * and the rest is a stderr line with exit 0; SessionStart context is plain stdout, as on
18
18
  * Claude. `--host openclaude` speaks Claude's dialect verbatim (OpenClaude is a Claude Code
@@ -42,9 +42,9 @@
42
42
  * THE CONTRACT EVERY VERB HOLDS. Exit 0 on every path, and signal through stdout. A hook
43
43
  * that fails is a tool call that fails, so an unreadable payload, a missing file, a
44
44
  * malformed user config and a bypass all end the same way: quietly, with 0. The single
45
- * exception is `learn`, which returns the model CLI's own exit code — an auth or quota
46
- * failure has to be diagnosable, and its hook command carries `|| exit 0` for exactly that
47
- * reason.
45
+ * exception is `learn` run BY HAND, which returns the model CLI's own exit code so a script can
46
+ * test it. On a hook call `learn` returns 0 like every other verb — exit 2 on Stop or PreCompact
47
+ * would block the turn's end — and an auth or quota failure is diagnosable from its stderr.
48
48
  *
49
49
  * The gate is `tests/helpers/cli_golden.mjs` replaying `tests/helpers/matrix/cli.{posix,win32}.json`:
50
50
  * each verb run in a seeded sandbox, with ABSOLUTE assertions on stdout, stderr, the exit code
@@ -59,7 +59,7 @@ import { machineDir } from '../lib/machine-dir.mjs';
59
59
  import { markerLines } from '../lib/managed-block.mjs';
60
60
  import { isDict, isTruthy, parseJson, readJsonc } from '../lib/json.mjs';
61
61
  import {
62
- GATE_LEDGER, carrierBlock, carrierName, globalHookStandingDown, hookProjectDir, isSharedCarrier,
62
+ GATE_LEDGER, HOSTS, carrierBlock, carrierName, globalHookStandingDown, hookProjectDir, isSharedCarrier,
63
63
  resolvePath, sovereignBypass,
64
64
  } from './hosts.mjs';
65
65
  import {
@@ -254,6 +254,148 @@ export function worktreeExempt(command, cwd, agentId) {
254
254
  }
255
255
  }
256
256
 
257
+ // A plain push of one named branch: `[-u|--set-upstream] <remote> <ref>`, nothing else. The
258
+ // remote's first character is alphanumeric so a flag (`-f`, `--all`, `--delete`) is never read
259
+ // as one, and `<ref>` is checked against the current branch by `ownBranchExempt`; a forced push
260
+ // (`-f`, `--force*`, a `+ref`) or a deletion (`:ref`) matches nothing and asks.
261
+ const SEG_PUSH_RE = new RegExp(`^git\\s+push(?:\\s+(?:-u|--set-upstream))?\\s+([A-Za-z0-9][A-Za-z0-9._-]*)\\s+(${ARG_RE})$`);
262
+
263
+ /**
264
+ * Whether the repository's own config can send a push of `<branch>` (no `:<dst>`) somewhere
265
+ * else: a `push =` refspec on a remote, a `[branch "<b>"]` whose `merge` names another branch, or
266
+ * an `[include]`/`[includeIf]` this read does not follow. Each one asks. An explicit
267
+ * `HEAD:<branch>` refspec needs none of this: git ignores the config once a destination is given.
268
+ * The user's global and system config are not read; a remote push refspec there is the one
269
+ * redirect this check cannot see.
270
+ */
271
+ function pushRedirected(common, branch) {
272
+ let text = '';
273
+ try { text = readFileSync(path.join(common, 'config'), 'utf8'); } catch (e) { if (e.code !== 'ENOENT') return true; }
274
+ if (/^\s*\[include/im.test(text) || /^\s*push\s*=/im.test(text)) return true;
275
+ let section = '';
276
+ for (const line of text.split(/\r?\n/)) {
277
+ const head = /^\s*\[\s*([^\]]*?)\s*\]/.exec(line);
278
+ if (head) { section = head[1]; continue; }
279
+ const merge = /^\s*merge\s*=\s*(\S+)/i.exec(line);
280
+ if (merge && section === `branch "${branch}"` && merge[1] !== `refs/heads/${branch}`) return true;
281
+ }
282
+ return false;
283
+ }
284
+
285
+ /**
286
+ * Whether every remote names its default branch: at least one `[remote "<r>"]`, each with a
287
+ * readable `refs/remotes/<r>/HEAD` symref (`git clone` writes it; `git remote add` does not, and
288
+ * `git remote set-head <r> --auto` repairs it). Without it, the default branch may be any name
289
+ * (`trunk`), and the own-branch pass cannot tell it from the session's own branch, so it asks
290
+ * (review F1: "when unsure, treat it as main"). An `[include]` may add a remote: asks too.
291
+ */
292
+ function defaultBranchKnown(common) {
293
+ let text = '';
294
+ try { text = readFileSync(path.join(common, 'config'), 'utf8'); } catch { return false; }
295
+ if (/^\s*\[include/im.test(text)) return false;
296
+ const remotes = [...text.matchAll(/^\s*\[\s*remote\s+"([^"]+)"\s*\]/gim)].map((m) => m[1]);
297
+ if (!remotes.length) return false;
298
+ return remotes.every((r) => {
299
+ try {
300
+ return /^ref:\s*refs\/remotes\//.test(readFileSync(path.join(common, 'refs', 'remotes', ...r.split('/'), 'HEAD'), 'utf8'));
301
+ } catch {
302
+ return false;
303
+ }
304
+ });
305
+ }
306
+
307
+ // One commit message, quoted, after `-m`/`-am`/`--message`, masked before the character checks so
308
+ // a Conventional Commits subject (`fix(hooks): x`) or an `@` does not ask (review F3). Single quotes
309
+ // are literal in bash and PowerShell alike. Inside double quotes both shells still expand `$` (and
310
+ // `$(`), a backtick, and bash a `\`: the class refuses those, so such a message keeps the ask.
311
+ const QUOTED_MSG_RE = /(\s(?:-[a-zA-Z]*m|--message)\s+)(?:'[^'\n]*'|"[^"$`\\\n]*")/g;
312
+ // A bash heredoc message: `git commit -F - <<'EOF'` … `EOF`, last in the command. Only a QUOTED
313
+ // delimiter, which leaves the body literal; and no body line may equal the delimiter, or the shell
314
+ // would end the heredoc there and run the rest as commands.
315
+ const HEREDOC_RE = /\s<<-?[ \t]*(['"])([A-Za-z_][A-Za-z0-9_]*)\1[ \t]*\n([\s\S]*)\n\t*\2[ \t]*\n?$/;
316
+
317
+ /**
318
+ * The command with what cannot run anything masked out — quoted messages always, a quoted-
319
+ * delimiter heredoc feeding `git commit -F -` under bash only — or null when a heredoc is there
320
+ * but not that safe shape. The masked text is what the character checks and the segment
321
+ * whitelist then read.
322
+ */
323
+ function maskMessages(command, shell) {
324
+ let text = command;
325
+ const doc = HEREDOC_RE.exec(text);
326
+ if (doc) {
327
+ const head = text.slice(0, doc.index);
328
+ if (shell !== 'bash' || head.includes('<<') || !/\bgit\s+commit\b[^\n]*\s-F\s+-$/.test(head)) return null;
329
+ if (doc[3].split('\n').some((l) => l.replace(/^\t+/, '').trimEnd() === doc[2])) return null;
330
+ text = head;
331
+ }
332
+ return text.replace(QUOTED_MSG_RE, "$1'M'");
333
+ }
334
+
335
+ /**
336
+ * Consent Before Push's own-branch pass (user decision 2026-11-13): the main branch changes only
337
+ * through a pull request, so every other branch is the session's own, and its commits, local
338
+ * merges and plain pushes go through without a prompt. Every clause must hold, or the ask stands:
339
+ * - No `agentId`: a sub-agent never pushes, and its local commits are `worktreeExempt`'s to judge.
340
+ * - The command, with its messages masked (`maskMessages`): none of `UNSAFE_CHARS_RE` or
341
+ * `SUBSHELL_CHARS_RE`; every segment an add, a
342
+ * read-only look, a plain commit or merge (`SEG_LOCAL_RE`, or the loop's `-F` commit), or a
343
+ * plain push (`SEG_PUSH_RE`) of THIS branch, spelled `<branch>`, `HEAD:<branch>` or
344
+ * `HEAD:refs/heads/<branch>`; after at most one leading `cd <path>`. Bare `git push` asks:
345
+ * `push.default` and the global config decide where it goes, and this read cannot see them.
346
+ * - The repository: every remote names its default branch (`defaultBranchKnown`); no remote, or
347
+ * one with no HEAD symref, asks for everything.
348
+ * - The branch: known, not a symref, and, compared case-insensitively, none of `main`, `master`,
349
+ * a remote's default (`protectedBranches`), or the branch the main worktree holds when `cwd` is
350
+ * a linked worktree. In the main checkout itself the checked-out branch is judged by name, as
351
+ * the doctrine says ("in a linked worktree, the branch the main checkout holds"). A bare
352
+ * `<branch>` refspec also needs `pushRedirected` to be false.
353
+ */
354
+ export function ownBranchExempt(command, cwd, agentId, shell = null) {
355
+ if (typeof agentId === 'string' && agentId) return false;
356
+ if (typeof command !== 'string') return false;
357
+ const masked = maskMessages(command, shell);
358
+ if (masked === null || UNSAFE_CHARS_RE.test(masked) || SUBSHELL_CHARS_RE.test(masked)) return false;
359
+ const segments = masked.split(/&&|\|\||[;|]/).map((x) => x.trim()).filter(Boolean);
360
+ try {
361
+ let dir = realpathSync(cwd);
362
+ const cd = segments.length ? SEG_CD_RE.exec(segments[0]) : null;
363
+ if (cd) {
364
+ if (cd[1] === '-' || cd[1].startsWith('~')) return false;
365
+ dir = realpathSync(path.resolve(dir, cd[1]));
366
+ segments.shift();
367
+ }
368
+ if (!segments.length) return false;
369
+ const root = gitRootOf(dir);
370
+ const branch = root && currentBranch(dir);
371
+ if (!branch || branch.includes('..')) return false;
372
+ const common = gitCommonDirOf(root);
373
+ if (!defaultBranchKnown(common)) return false;
374
+ // The branch may itself be a symref (`git symbolic-ref refs/heads/sym refs/heads/main`), and a
375
+ // commit then moves its target: as in `worktreeExempt`, a loose ref starting `ref:` asks.
376
+ let loose = '';
377
+ try {
378
+ loose = readFileSync(path.join(common, 'refs', 'heads', ...branch.split('/')), 'utf8');
379
+ } catch (e) {
380
+ if (e.code !== 'ENOENT') return false;
381
+ }
382
+ if (/^\s*ref:/.test(loose)) return false;
383
+ const main = mainWorktreeOf(dir);
384
+ const taken = [...protectedBranches(root), main && currentBranch(main)].filter(Boolean);
385
+ if (taken.some((b) => b.toLowerCase() === branch.toLowerCase())) return false;
386
+ return segments.every((seg) => {
387
+ if (SEG_ADD_RE.test(seg) || SEG_READONLY_RE.test(seg) || SEG_LOCAL_RE.test(seg) || SEG_COMMIT_RE.test(seg)) return true;
388
+ const push = SEG_PUSH_RE.exec(seg);
389
+ if (!push) return false;
390
+ const ref = push[2];
391
+ if (ref === `HEAD:${branch}` || ref === `HEAD:refs/heads/${branch}`) return true;
392
+ return ref === branch && !pushRedirected(common, branch);
393
+ });
394
+ } catch {
395
+ return false;
396
+ }
397
+ }
398
+
257
399
  // `askDecision` lives in `./hooks-prims.mjs`, so the entry can ask when THIS module fails to load.
258
400
  export { askDecision };
259
401
 
@@ -304,7 +446,7 @@ const BOB_FINAL = ' Bob has no approval step for this gate: neither a confirmati
304
446
  * credential in a tracked file and a history-discarding git act are wrong in every context,
305
447
  * so refusing them costs nothing. rigor-5 (External Gate) joins them: a protected check the
306
448
  * agent can edit is not a check, so it is as unconditional as the two Laws — NOT "Laws I/IV
307
- * only", see bob-code.md B3. process-1 too (owner decision, 2026-11): with no prompt, a warning
449
+ * only". process-1 too (owner decision, 2026-11): with no prompt, a warning
308
450
  * let the agent write the user's rules on its own say. Memory is written freely (owner decision,
309
451
  * 2026-11-08), so a memory write reaches no rule here. Process 5 is the USER's call
310
452
  * as well, but a hard block would make Bob unable to commit at all, so it stays a warning the
@@ -908,7 +1050,8 @@ export function gitDecide(args, payload) {
908
1050
  return ask(args, 'git-gate', 'law-4', 'unverified', {});
909
1051
  }
910
1052
  const tool = payload && payload.tool_name;
911
- const command = shellReading(ti.command, tool === 'Bash' ? 'bash' : tool === 'PowerShell' ? 'powershell' : null);
1053
+ const shell = tool === 'Bash' ? 'bash' : tool === 'PowerShell' ? 'powershell' : null;
1054
+ const command = shellReading(ti.command, shell);
912
1055
  // The agent's own words, for the asks where they are no conflict of interest (`gateText`'s `quote`).
913
1056
  const says = typeof ti.description === 'string' ? ti.description : '';
914
1057
  // Law IV's catastrophic class (a root, a drive, the home dir, a disk): no state makes it safe,
@@ -946,12 +1089,16 @@ export function gitDecide(args, payload) {
946
1089
  // no rule behind it — but Law IV above is universal and has already run. Checked before
947
1090
  // `loopExempt` so a non-git command, or one with consent off, never pays for the whitelist.
948
1091
  if (args.noConsent || !GIT_GATE_RE.test(command) || consentBenign(command)) return 0;
949
- // Consent Before Push: a loop launched on its own `loop/*` branch is a named batch for a
950
- // fixed set of commit/push forms on that branch only — never a merge into anything shared.
951
- if (loopExempt(command, (payload && payload.cwd) || process.cwd())) return 0;
1092
+ const cwd = (payload && payload.cwd) || process.cwd();
1093
+ // Consent Before Push: off the main branch, commits, local merges and plain pushes are the
1094
+ // session's own. `--strict-consent` turns this pass off, and every commit and push asks again.
1095
+ if (!args.strictConsent && ownBranchExempt(command, cwd, payload && payload.agent_id, shell)) return 0;
1096
+ // Strict consent keeps the narrower passes: a loop launched on its own `loop/*` branch is a
1097
+ // named batch for a fixed set of commit/push forms on that branch only.
1098
+ if (loopExempt(command, cwd)) return 0;
952
1099
  // A worker's own worktree branch is a named batch for local commits and merges, never a push.
953
- if (worktreeExempt(command, (payload && payload.cwd) || process.cwd(), payload && payload.agent_id)) return 0;
954
- return ask(args, 'git-gate', 'process-5', 'commit', { says });
1100
+ if (worktreeExempt(command, cwd, payload && payload.agent_id)) return 0;
1101
+ return ask(args, 'git-gate', 'process-5', 'commit', { says, strict: args.strictConsent === true });
955
1102
  }
956
1103
  export const cmdGitGate = guardGate(gitGate, 'git-gate');
957
1104
 
@@ -1122,7 +1269,9 @@ function protectedIn(target) {
1122
1269
  * not gated. Reached from a shell command too, with the same limit as `protectedCheck`.
1123
1270
  */
1124
1271
  const GATE_CONFIG_FILES = ['settings.json', 'settings.local.json', 'settings/settings.json', 'rules/geneseed.md', 'excludes.json', 'AGENT.md', '.geneseed-manifest.json', '.geneseed-emit', 'opencode.json', 'opencode.jsonc'];
1125
- const GATE_CONFIG_MARKERS = ['.claude', '.openclaude', '.bob', '.opencode'];
1272
+ // Every host's project dir, read from the host table so a new host's settings are gate
1273
+ // configuration the day it gets a row. Exported for the tests that write the list out.
1274
+ export const GATE_CONFIG_MARKERS = HOSTS.map((h) => h.projectMarker);
1126
1275
  function gateConfig(p, root) {
1127
1276
  let bin = null;
1128
1277
  try {
@@ -1378,7 +1527,7 @@ export function ruleDecide(args, payload) {
1378
1527
  // settings matcher that routes here (Claude verdict R2); the `edits[]` read stays as a
1379
1528
  // cheap, harmless guard in case that ever changes.
1380
1529
  // `diff` (Bob's `apply_diff`) and `replace`/`search` (`search_and_replace`) are Roo-lineage
1381
- // field names the Bob docs never confirm (bob-verdict.md I1) — accepted when present, never
1530
+ // field names the Bob docs never confirm — accepted when present, never
1382
1531
  // required, same as every field above. Only WRITTEN text is scanned: `search` and a diff's
1383
1532
  // SEARCH halves are text leaving the file (like Claude's `old_string`), so a secret there is
1384
1533
  // being removed — blocking it would stop the agent cleaning up a leak.
@@ -1392,9 +1541,12 @@ export function ruleDecide(args, payload) {
1392
1541
  return ask(args, 'rule-gate', 'law-1', 'secret', { name: repoRel(carrier, payload) });
1393
1542
  }
1394
1543
  // Bob routes reads here too (`read_file` carries a path): only a write is External Gate's business.
1395
- // shortcut: a write is told by its tool name, so a Bob write tool named outside WRITE_NAME_RE
1396
- // passes both gates; switch to an allowlist of Bob's read tools if Bob adds or renames one.
1397
- const bobRead = HOST === 'bob' && !WRITE_NAME_RE.test(String((payload && payload.tool_name) || ''));
1544
+ // A call that carries text to write is a write whatever its tool is called (`create_file`,
1545
+ // `append_to_file`, `apply_patch`, `save_file`): Bob's tool names are undocumented, so the name
1546
+ // alone let those past the store and gate-config checks. `ownershipBlock` reads a write the same way.
1547
+ // shortcut: a write that carries no text under a name outside WRITE_NAME_RE still reads as a
1548
+ // read; switch to an allowlist of Bob's read tools if Bob adds one.
1549
+ const bobRead = HOST === 'bob' && !body && !WRITE_NAME_RE.test(String((payload && payload.tool_name) || ''));
1398
1550
  for (const q of bobRead ? [] : paths) {
1399
1551
  // The carrier rule is a write tool's alone: a shell call reaches `externalGate` with nothing to replay.
1400
1552
  const hit = externalGate(args, q, payload)
@@ -1424,8 +1576,9 @@ export const cmdRuleGate = guardGate(ruleGate, 'rule-gate');
1424
1576
  // ======================================================================================
1425
1577
 
1426
1578
  /**
1427
- * Bob's documented PreToolUse payload (bob-verdict.md I1) is `{event, session_id, tool,
1428
- * input:{...}}` — none of `tool_input`, `tool_name` or `hook_event_name` exist. Normalised
1579
+ * The LEGACY Bob PreToolUse payload is `{event, session_id, tool, input:{...}}`, with none of
1580
+ * `tool_input`, `tool_name` or `hook_event_name`; Bob 2.2.3 sends Claude's keys (bundle read
1581
+ * 2026-10, docs/concepts/host-matrix.md "What is verified"), and both are read. Normalised
1429
1582
  * HERE, once, at Bob's one entry point (`toolGate` is the only verb its settings.json invokes
1430
1583
  * for PreToolUse), so `gitDecide`/`ruleDecide` keep reading the Claude shape unchanged and
1431
1584
  * never learn Bob exists. A no-op for an already-Claude-shaped payload: every field it sets
@@ -197,6 +197,50 @@ export function globalHookStandingDown(hookRoot, projectDir, host, verb) {
197
197
  }
198
198
  }
199
199
 
200
+ // The marker lives in the shim's FILENAME, not its directory: GENESEED_HOME relocates the dir,
201
+ // and a relocated install's hooks must stay recognisable to `GENESEED_HOOK_SNIFF`. Declared here
202
+ // rather than in ./shim.mjs because `ownHookVerb` below reads it, and shim.mjs imports this module.
203
+ export const SHIM_MARK = 'geneseed-hook';
204
+
205
+ /** The verbs `bin/geneseed-hook.mjs` answers (its `VERBS` table). */
206
+ const HOOK_VERBS = 'context|git-gate|rule-gate|tool-gate|learn|activity';
207
+ /** A command that runs one of them: every emitted form is `<runner> <verb> --root|--memory …`. */
208
+ const RUNS_HOOK_VERB = new RegExp(` (?:${HOOK_VERBS}) --`);
209
+ /** The verb token after the shim's name: the rest of its path, a closing quote, then the verb. */
210
+ const VERB_AFTER_SHIM = new RegExp(`^[^"]*"? (${HOOK_VERBS})(?= |$)`);
211
+
212
+ /**
213
+ * The hook verb `command` runs FOR THE INSTALL AT `cfg`, or null when the handler is not that
214
+ * install's. The one test of "is this handler Geneseed's", shared by the settings merge, the
215
+ * unwire and the integrity check (`js/hosts/settings.mjs`).
216
+ *
217
+ * A SIGNATURE, not deep equality with what this build would emit. Equality broke four ways: a
218
+ * re-emit with other gate flags and no manifest stacked a second group beside the first; a group
219
+ * already on file was never claimed, so uninstall left it running; a user's own `"timeout": 30`
220
+ * on our handler made it a stranger; and the integrity check then reported that handler missing.
221
+ * So a handler is ours when its command names the shim (`SHIM_MARK`), then a hook verb, and
222
+ * carries exactly `--root "<cfg>"` or `--memory "<cfg>/memory"`. Flags, `--host` and every other
223
+ * field are free to differ. The closing quote makes the root exact: `<cfg>-old` is another
224
+ * install, and a global and a project install differ by root, so neither claims the other's.
225
+ *
226
+ * A hand-written hook that runs our binary with our root therefore counts as ours (the maintainer
227
+ * accepted that, 2026-11): a re-emit replaces it and uninstall removes it.
228
+ *
229
+ * The PowerShell form backtick-escapes `$` and a backtick inside the path (`powershellForm`), so
230
+ * the command is read both as written and with those undone; Windows compares paths case-folded.
231
+ */
232
+ export function ownHookVerb(command, cfg) {
233
+ if (typeof command !== 'string' || typeof cfg !== 'string' || !cfg) return null;
234
+ const at = command.indexOf(SHIM_MARK);
235
+ if (at < 0) return null;
236
+ const verb = VERB_AFTER_SHIM.exec(command.slice(at + SHIM_MARK.length))?.[1];
237
+ if (!verb) return null;
238
+ const fold = (s) => (process.platform === 'win32' ? s.toLowerCase() : s);
239
+ const wanted = [` --root "${cfg}"`, ` --memory "${path.join(cfg, 'memory')}"`].map(fold);
240
+ const readings = [command, command.replace(/`([`$])/g, '$1')].map(fold);
241
+ return readings.some((c) => wanted.some((w) => c.includes(w))) ? verb : null;
242
+ }
243
+
200
244
  /**
201
245
  * The hook handlers the install at `cfg` both RECORDS and still RUNS: `[event, handler]` pairs
202
246
  * from its manifest's `managed.settings_hooks` whose command the settings file that manifest
@@ -204,13 +248,20 @@ export function globalHookStandingDown(hookRoot, projectDir, host, verb) {
204
248
  * the host runs. A user who deletes `hooks` by hand keeps the manifest (re-review, Important).
205
249
  * Absent, unparseable or COMMENTED settings fail `JSON.parse` and answer `[]`. Shared by
206
250
  * `projectWiresVerb` and the hook-shell drift check (`hookShellProblems`).
251
+ *
252
+ * Only a recorded handler that runs a hook verb: a claim is the whole group as it sat on file,
253
+ * so it can hold a hook the user added to our group, and that one is not this install's. The
254
+ * shim is NOT required here, unlike `ownHookVerb`: doctor's probe must still be handed a
255
+ * recorded gate that names another binary, to report it. Liveness compares the command alone,
256
+ * so a field the user set on our handler (`timeout`) does not make it read as gone.
207
257
  */
208
258
  export function liveRecordedHooks(cfg) {
209
259
  const readJson = (p) => { try { return JSON.parse(readText(p)); } catch { return null; } };
210
260
  const managed = readJson(path.join(cfg, GLOBAL_MANIFEST))?.managed;
211
261
  const recorded = Array.isArray(managed?.settings_hooks) ? managed.settings_hooks : [];
212
262
  const wanted = recorded.flatMap((r) => (Array.isArray(r?.group?.hooks) ? r.group.hooks : [])
213
- .filter((h) => typeof h?.command === 'string').map((h) => [r.event, h]));
263
+ .filter((h) => typeof h?.command === 'string' && RUNS_HOOK_VERB.test(h.command))
264
+ .map((h) => [r.event, h]));
214
265
  if (!wanted.length) return [];
215
266
  const hooks = readJson(settingsFile(cfg, managed))?.hooks;
216
267
  const live = (event, command) => Array.isArray(hooks?.[event]) && hooks[event]
@@ -304,10 +355,20 @@ export function isCanonical(cfgDir, host) {
304
355
  /**
305
356
  * The project root a hook judges against: `$CLAUDE_PROJECT_DIR` (Claude Code and OpenClaude set
306
357
  * it for every hook — the session's root, where its project hooks were loaded from), else the
307
- * cwd. Bob documents no such variable, so under Bob this is the cwd.
358
+ * payload's `cwd` when the caller has one, else the process cwd.
359
+ *
360
+ * Bob documents no such variable, but its payload carries `cwd`, the root workspace (2.2.3
361
+ * bundle read; docs/concepts/host-matrix.md, "What is verified"). `payloadCwd` is optional and
362
+ * only a caller that ALREADY holds the parsed payload passes it: `context` does, through the
363
+ * hook entry. The gate verbs do not, because their stand-down runs before they read stdin, and
364
+ * a second read on every tool call is not worth a fallback. A value that is not an absolute
365
+ * path is ignored: the payload is the host's text, and a relative one would resolve against
366
+ * the very cwd it was meant to replace.
308
367
  */
309
- export function hookProjectDir() {
310
- return process.env.CLAUDE_PROJECT_DIR || process.cwd();
368
+ export function hookProjectDir(payloadCwd) {
369
+ if (process.env.CLAUDE_PROJECT_DIR) return process.env.CLAUDE_PROJECT_DIR;
370
+ if (typeof payloadCwd === 'string' && path.isAbsolute(payloadCwd)) return payloadCwd;
371
+ return process.cwd();
311
372
  }
312
373
 
313
374
  /**
@@ -449,8 +510,10 @@ export function openclaudeConfigDir() {
449
510
 
450
511
  /**
451
512
  * `_build_global.HOSTS` — one row per host, IN ITS ORDER: opencode, claude, bob, openclaude.
452
- * A new host is one row here; `EMIT_HOST_SCOPE` (`js/hosts/installs.mjs`) and `CLAUDE_STYLE`
453
- * below are derived from it.
513
+ * `EMIT_HOST_SCOPE` and `EMIT_FOR` (`js/hosts/installs.mjs`) and `CLAUDE_STYLE` below are
514
+ * derived from it, but A NEW HOST IS NOT ONE ROW HERE: a dozen hand tables name the hosts
515
+ * too. `docs/extending.md` §4d is the checklist, and `tests/unit/host_tables.test.mjs` fails
516
+ * for each table that falls behind this one.
454
517
  *
455
518
  * An array rather than an object because the order is observable output, not an
456
519
  * implementation detail: `harness exclude add` walks it and prints one message per host, so
@@ -580,12 +643,17 @@ export const CLAUDE_STYLE = HOSTS.filter((h) => h.family === 'claude').map((h) =
580
643
  * user-editable `.geneseed-emit` marker, so an unrecognised one must degrade to the portable
581
644
  * bundle rather than raise.
582
645
  *
583
- * SPLIT PER KIND (2026-09): Bob reads `.bob/skills/<name>/SKILL.md` natively — verified
584
- * against its docs in the Bob injection review — but has no markdown agents directory, so a
585
- * single boolean was wrong both ways: `false` shipped the §4 Skills table on top of a
586
- * catalogue Bob already had (~1.7k tokens twice), `true` would have stripped the §3 Agents
587
- * table that is Bob's ONLY agent catalogue. Each CATALOG block in AGENT.md names its kind and
588
- * resolves against its own flag.
646
+ * SPLIT PER KIND (2026-09): Bob reads `.bob/skills/<name>/SKILL.md` natively (its skills
647
+ * docs), so a single boolean was wrong both ways: `false` shipped the §4 Skills table on top
648
+ * of a catalogue Bob already had (~1.7k tokens twice), `true` would have stripped the §3
649
+ * Agents table. Each CATALOG block in AGENT.md names its kind and resolves against its own flag.
650
+ *
651
+ * BOB'S `agents: false` IS NOT "Bob has no agents directory". The emit writes native
652
+ * `agents/<name>.md` in Bob's dialect (`bobAgentFrontmatter`, `js/hosts/native.mjs`), and Bob
653
+ * 2.2.3 reads them. What is NOT verified is whether Bob lists those agents to the model by
654
+ * itself, so the §3 Agents table stays in Bob's carrier and the flag stays false until someone
655
+ * sees Bob's own listing. Flipping it on a guess would remove the only agent catalogue the
656
+ * model is known to get.
589
657
  *
590
658
  * Returns `{ skills, agents }` for a known host, `false` for an unknown one.
591
659
  */
@@ -45,7 +45,8 @@ import { registryRoots } from '../inspect/registry.mjs';
45
45
  import { printErr, readText, isFile, isDir } from '../lib/fs.mjs';
46
46
  import { formatRepr, isDict } from '../lib/json.mjs';
47
47
  import { comparePaths } from '../lib/paths.mjs';
48
- import { bundleLeftovers, ownedWithin } from './owned.mjs';
48
+ import { bundleLeftovers, ownedWithin, recordedGates } from './owned.mjs';
49
+ import { prunableGates } from './settings.mjs';
49
50
  import { claudeHookShell, hookShimPath } from './shim.mjs';
50
51
 
51
52
  export { carriersFor };
@@ -554,6 +555,13 @@ export const EMIT_HOST_SCOPE = new Map(HOSTS.flatMap(({ host }) => [
554
555
  [host, [host, 'project']], [`${host}-global`, [host, 'global']],
555
556
  ]));
556
557
 
558
+ /**
559
+ * The inverse: `'<host> <scope>'` -> the emit name that installs it. One map for the two
560
+ * readers that had a hand copy each: `rebuild-all`'s default for an install with no marker
561
+ * (`js/build/generate.mjs`) and the console's install command (`js/web/actions.mjs`).
562
+ */
563
+ export const EMIT_FOR = new Map([...EMIT_HOST_SCOPE].map(([emit, [host, scope]]) => [`${host} ${scope}`, emit]));
564
+
557
565
  /** `root`'s own marker, resolved, or null. */
558
566
  export function emitHostScopeOf(root) {
559
567
  const emit = readMaybe(path.join(root, '.geneseed-emit'));
@@ -614,6 +622,23 @@ export function leftoversOf(root, host = 'opencode', scope = 'global') {
614
622
  return { kept: kept.sort(), stale };
615
623
  }
616
624
 
625
+ /**
626
+ * The `permission.bash` gates a `--prune-gates` rebuild of this OpenCode install would remove:
627
+ * owned keys whose rule this install has off, still at Geneseed's verdict, and absent from its
628
+ * `bash_gates` record (an `opencode.json` written before 5.2.0). The console shows them beside
629
+ * the leftovers and offers that rebuild. Read with the install's OWN choices — packs, excluded
630
+ * rules, the deletion gate — so it names what the console's prune would take, not a guess.
631
+ * Every other host has no such block: `{ keys: [] }`.
632
+ */
633
+ export function strandedGatesOf(root, host = 'opencode', scope = 'global') {
634
+ if (host !== 'opencode') return { keys: [], commented: false };
635
+ const manifest = scope === 'project' ? path.join(root, '.opencode', GLOBAL_MANIFEST)
636
+ : path.join(root, GLOBAL_MANIFEST);
637
+ return prunableGates(path.join(root, 'opencode.json'), doctrinesForBuild(root, host),
638
+ excludedRulesOfDir(root, host), gatesOfDir(root, host).deletionGate,
639
+ recordedGates(readJsonMaybe(manifest)));
640
+ }
641
+
617
642
  /** 'active' | 'disabled' | 'absent'. */
618
643
  export function installState(root, host = 'opencode', scope = 'global') {
619
644
  if (CLAUDE_STYLE.includes(host)) return claudeState(root, scope, host);