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
@@ -52,15 +52,20 @@
52
52
  // upgrade path there is still a session-level `permission` ruleset set by the loop launcher
53
53
  // when it creates the loop session (`session.create` accepts one).
54
54
 
55
- import { promises as fs, realpathSync, existsSync, readFileSync, readdirSync, readlinkSync, statSync, lstatSync, writeFileSync, mkdirSync, unlinkSync } from "node:fs"
55
+ import { promises as fs, realpathSync, existsSync, readFileSync, readdirSync, readlinkSync, statSync, lstatSync, writeFileSync, appendFileSync, mkdirSync, unlinkSync } from "node:fs"
56
56
  import { spawnSync } from "node:child_process"
57
57
  import * as path from "node:path"
58
58
  import { fileURLToPath } from "node:url"
59
- import { homedir, tmpdir } from "node:os"
59
+ import { homedir, tmpdir, userInfo } from "node:os"
60
60
  import { createHash } from "node:crypto"
61
61
 
62
62
  const PLUGIN_DIR = path.dirname(fileURLToPath(import.meta.url))
63
63
 
64
+ // The helpers this plugin shares with its siblings (`norm`, `resolvePath`, `sovereignBypass`,
65
+ // `mainWorktreeOf`, `stripJsonc`, `isFile`, `isDir`, `patchSections`, `machineDir`, `readsTier`,
66
+ // `storeScan`) have their HOME in this file: edit one here, then `node tests/twins.mjs --write`
67
+ // copies it into the others (the list of who carries what is that file's `PLUGIN_HELPERS`).
68
+ //
64
69
  // Sovereign-repo bypass — twin of the harness's own `sovereignBypass()`.
65
70
  // <cfg>/excludes.json (user-owned, managed by `harness exclude`) lists folders where
66
71
  // this GLOBAL install goes dormant. Any error degrades to "not excluded".
@@ -293,59 +298,71 @@ const SHELL_BLOCK_RE = [
293
298
  // on state is decided here. `tool.execute.before` has no ask tier, so a real loss is BLOCKED —
294
299
  // the Bob behaviour — and `GENESEED_GUARD=warn` downgrades it to a log line.
295
300
  //
296
- // The fs-only readers below are the twins of js/hosts/gitref.mjs (gitRootOf, gitDirOf,
297
- // gitCommonDirOf, currentBranch, protectedBranches, stashExists) — tests/plugins/guard.test.mjs
298
- // compares each with its gitref.mjs original, quotes, semicolons and layout aside; the block
299
- // between the twin markers is js/hosts/loss.mjs verbatim, and the same file diffs it.
301
+ // The fs-only readers below are js/hosts/gitref.mjs's (gitRootOf, gitDirOf, gitCommonDirOf,
302
+ // currentBranch, protectedBranches, stashExists) and the block between the twin markers is
303
+ // js/hosts/loss.mjs, all verbatim: `node tests/twins.mjs --write` copies them, so edit the
304
+ // original. Their house style (semicolons, single quotes) is the original's.
300
305
  function gitRootOf(cwd) {
301
306
  try {
302
- let dir = path.resolve(cwd)
307
+ let dir = path.resolve(cwd);
303
308
  for (;;) {
304
- if (existsSync(path.join(dir, ".git"))) return dir
305
- const up = path.dirname(dir)
306
- if (up === dir) return null
307
- dir = up
309
+ if (existsSync(path.join(dir, '.git'))) return dir;
310
+ const up = path.dirname(dir);
311
+ if (up === dir) return null;
312
+ dir = up;
308
313
  }
309
- } catch { return null }
314
+ } catch {
315
+ return null;
316
+ }
310
317
  }
311
318
  function gitDirOf(root) {
312
- const dotgit = path.join(root, ".git")
319
+ const dotgit = path.join(root, '.git');
313
320
  if (statSync(dotgit).isFile()) {
314
- const m = /^gitdir:\s*(.+?)\s*$/m.exec(readFileSync(dotgit, "utf8"))
315
- if (!m) throw new Error(`${dotgit} does not name a gitdir`)
316
- return path.resolve(root, m[1])
321
+ const m = /^gitdir:\s*(.+?)\s*$/m.exec(readFileSync(dotgit, 'utf8'));
322
+ if (!m) throw new Error(`${dotgit} does not name a gitdir`);
323
+ return path.resolve(root, m[1]);
317
324
  }
318
- return dotgit
325
+ return dotgit;
319
326
  }
320
327
  function gitCommonDirOf(root) {
321
- const gitdir = gitDirOf(root)
322
- try { return path.resolve(gitdir, readFileSync(path.join(gitdir, "commondir"), "utf8").trim()) } catch { return gitdir }
328
+ const gitdir = gitDirOf(root);
329
+ try {
330
+ return path.resolve(gitdir, readFileSync(path.join(gitdir, 'commondir'), 'utf8').trim());
331
+ } catch {
332
+ return gitdir;
333
+ }
323
334
  }
324
335
  function currentBranch(cwd) {
325
336
  try {
326
- const root = gitRootOf(cwd)
327
- if (!root) return null
328
- const ref = /^ref:\s*refs\/heads\/(.+?)\s*$/m.exec(readFileSync(path.join(gitDirOf(root), "HEAD"), "utf8"))
329
- return ref ? ref[1] : null
330
- } catch { return null }
337
+ const root = gitRootOf(cwd);
338
+ if (!root) return null;
339
+ const ref = /^ref:\s*refs\/heads\/(.+?)\s*$/m.exec(readFileSync(path.join(gitDirOf(root), 'HEAD'), 'utf8'));
340
+ return ref ? ref[1] : null;
341
+ } catch {
342
+ return null;
343
+ }
331
344
  }
332
345
  function protectedBranches(root) {
333
- const names = new Set(["main", "master"])
334
- const remotes = path.join(gitCommonDirOf(root), "refs", "remotes")
335
- let dirs = []
336
- try { dirs = readdirSync(remotes) } catch { /* no remotes */ }
346
+ const names = new Set(['main', 'master']);
347
+ const remotes = path.join(gitCommonDirOf(root), 'refs', 'remotes');
348
+ let dirs = [];
349
+ try { dirs = readdirSync(remotes); } catch { /* no remotes */ }
337
350
  for (const r of dirs) {
338
351
  try {
339
- const m = /^ref:\s*refs\/remotes\/[^/]+\/(.+?)\s*$/m.exec(readFileSync(path.join(remotes, r, "HEAD"), "utf8"))
340
- if (m) names.add(m[1])
352
+ const m = /^ref:\s*refs\/remotes\/[^/]+\/(.+?)\s*$/m.exec(readFileSync(path.join(remotes, r, 'HEAD'), 'utf8'));
353
+ if (m) names.add(m[1]);
341
354
  } catch { /* this remote has no HEAD symref */ }
342
355
  }
343
- return names
356
+ return names;
344
357
  }
345
358
  function stashExists(root) {
346
- const common = gitCommonDirOf(root)
347
- if (existsSync(path.join(common, "refs", "stash"))) return true
348
- try { return /^[0-9a-f]+ refs\/stash$/m.test(readFileSync(path.join(common, "packed-refs"), "utf8")) } catch { return false }
359
+ const common = gitCommonDirOf(root);
360
+ if (existsSync(path.join(common, 'refs', 'stash'))) return true;
361
+ try {
362
+ return /^[0-9a-f]+ refs\/stash$/m.test(readFileSync(path.join(common, 'packed-refs'), 'utf8'));
363
+ } catch {
364
+ return false;
365
+ }
349
366
  }
350
367
 
351
368
  // ---- loss twin: BEGIN — adapters/opencode/plugins/geneseed-guard.js carries everything down to
@@ -1237,9 +1254,11 @@ const GATE_ASKS = {
1237
1254
  impact: 'the scan can run for hours', tail: 'search one named directory',
1238
1255
  can: 'You can name the directory to search.' }),
1239
1256
  // Routine and frequent, so one line: three more would train the user to stop reading all of them.
1240
- commit: () => ({ rule: 'Consent Before Push', quote: true, short: true,
1241
- line: 'This command commits or pushes with git, which needs your approval each time.',
1242
- why: 'every commit and push is your decision', can: GATE_RUN_IT }),
1257
+ // `strict`: the install asks for every commit and push (`--strict-consent`), not only main's.
1258
+ commit: (f) => ({ rule: 'Consent Before Push', quote: true, short: true,
1259
+ line: f.strict ? 'This command commits or pushes with git, which needs your approval each time.'
1260
+ : '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.',
1261
+ why: f.strict ? 'every commit and push is your decision' : 'the main branch changes only through a pull request', can: GATE_RUN_IT }),
1243
1262
  // The next four are the OpenCode guard's alone: no hook reads a key path, a stream, a wiki manifest
1244
1263
  // or an unknown tool's arguments, and the guard only refuses them. `wiki` has no rule to name.
1245
1264
  'secret-file': (f) => ({ rule: 'Sealed Secrets', line: `This edit writes to ${gateName(gatePath(f.name))}, a file that holds a secret or key.`,
@@ -1436,13 +1455,19 @@ function plainPaths(args) {
1436
1455
  // as the segment separator) match `C:\Users\me\.ssh\id_rsa` the same as a POSIX path.
1437
1456
  return PATH_KEYS.map((k) => args?.[k]).filter((v) => typeof v === "string" && v).map((v) => v.replace(/\\/g, "/"))
1438
1457
  }
1439
- // Returns every candidate path for this call, normalized (backslashes -> `/`): every path key, and
1440
- // every patch marker resolved against `cwd` (the session's `ctx.directory` — the same root
1441
- // `apply_patch.ts:72` resolves against upstream) since a patch marker is worktree-relative.
1458
+ // A multi-edit call's entries: `edits[]`, each carrying its new text and, on some tools, a file of
1459
+ // its own. UNVERIFIED against a live OpenCode: the shape is its V1 `multiedit` tool's as its
1460
+ // source reads (`filePath` beside `edits: [{ filePath, oldString, newString }]`), and no host was
1461
+ // run here to see whether that tool still ships under that name on either major.
1462
+ const editsOf = (args) => (Array.isArray(args?.edits) ? args.edits.filter((e) => e && typeof e === "object") : [])
1463
+ // Returns every candidate path for this call, normalized (backslashes -> `/`): every path key, the
1464
+ // path keys of each `edits[]` entry, and every patch marker resolved against `cwd` (the session's
1465
+ // `ctx.directory` — the same root `apply_patch.ts:72` resolves against upstream) since a patch
1466
+ // marker is worktree-relative.
1442
1467
  function pickPath(args, cwd) {
1443
1468
  const marked = args && typeof args.patchText === "string" ? parsePatchPaths(args.patchText)
1444
1469
  .map((p) => path.resolve(cwd || process.cwd(), p).replace(/\\/g, "/")) : []
1445
- return [...new Set([...marked, ...plainPaths(args)])]
1470
+ return [...new Set([...marked, ...plainPaths(args), ...editsOf(args).flatMap(plainPaths)])]
1446
1471
  }
1447
1472
  // Per-FILE added content for an `apply_patch` call: `parsePatchPaths` flattens every marker
1448
1473
  // path into one list (right for the path-only gates, which must catch a secret/protected name
@@ -1488,7 +1513,9 @@ function patchSections(patchText) {
1488
1513
  // (OpenCode tool Parameters, packages/opencode/src/tool/{write,edit}.ts) — both single-path, so
1489
1514
  // one pair. For `apply_patch`, one pair per marker section; only the `+`-prefixed hunk lines are
1490
1515
  // NEW content — a `-` line is text being REMOVED, so a secret there is leaving the file, not
1491
- // landing in it, and must not block the call.
1516
+ // landing in it, and must not block the call. A multi-edit carries one `newString` (or
1517
+ // `new_string`) per `edits[]` entry, each attributed to the entry's own file, else the call's
1518
+ // (the twin read: `ruleDecide` in js/hosts/hooks.mjs joins `edits[].new_string` the same way).
1492
1519
  function pickAddedContentByPath(args, cwd) {
1493
1520
  const found = args && typeof args.patchText === "string" ? parsePatchSections(args.patchText)
1494
1521
  .filter((s) => s.added.length)
@@ -1498,10 +1525,40 @@ function pickAddedContentByPath(args, cwd) {
1498
1525
  })) : []
1499
1526
  // Beside a patch too: a decoy `patchText` must not hide the content a call also carries.
1500
1527
  const [p] = plainPaths(args)
1501
- if (!p) return found
1502
- for (const text of [args.content, args.newString]) if (typeof text === "string") found.push({ path: p, content: text })
1528
+ if (p) for (const text of [args.content, args.newString]) if (typeof text === "string") found.push({ path: p, content: text })
1529
+ for (const edit of editsOf(args)) {
1530
+ const own = plainPaths(edit)[0] ?? p
1531
+ if (!own) continue
1532
+ for (const text of [edit.newString, edit.new_string]) if (typeof text === "string") found.push({ path: own, content: text })
1533
+ }
1503
1534
  return found
1504
1535
  }
1536
+ // The calls a tool carries inside its own arguments: `tool_calls[]` or `calls[]`, each entry
1537
+ // `{ tool | name, parameters | args | input }`. A tool outside the write and shell classes was
1538
+ // read for rule-store paths only, so a `batch` holding a nested `bash rm -rf /` or a nested write
1539
+ // of a key passed every other gate. Each entry now runs the whole gate pipeline as its own call.
1540
+ // An entry with no tool name is no call, and its strings still reach the rule-store walk.
1541
+ //
1542
+ // UNVERIFIED against a live OpenCode, all of it: whether a `batch` tool ships under that name on
1543
+ // either major, whether its entries have this shape (V1's source reads `tool_calls: [{ tool,
1544
+ // parameters }]`), and whether the host fires `tool.execute.before` again for each nested call. If
1545
+ // it does, nothing is refused twice (the outer call is refused first, and then no entry runs),
1546
+ // but a gate ERROR is ledgered once for the outer call and once more for the nested one.
1547
+ const NESTED_KEYS = ["tool_calls", "calls"]
1548
+ // A batch inside a batch is already unusual; past this, what cannot be read is refused.
1549
+ const NESTED_DEPTH = 8
1550
+ function nestedCalls(args) {
1551
+ const out = []
1552
+ for (const key of NESTED_KEYS) {
1553
+ for (const call of Array.isArray(args?.[key]) ? args[key] : []) {
1554
+ if (!call || typeof call !== "object") continue
1555
+ const tool = [call.tool, call.name].find((v) => typeof v === "string" && v)
1556
+ const inner = [call.parameters, call.args, call.input].find((v) => v && typeof v === "object")
1557
+ if (tool) out.push({ tool: tool.toLowerCase(), args: inner ?? {} })
1558
+ }
1559
+ }
1560
+ return out
1561
+ }
1505
1562
  function pickCommand(args) {
1506
1563
  for (const k of ["command", "cmd", "script"]) {
1507
1564
  if (args && typeof args[k] === "string") return args[k]
@@ -1577,8 +1634,8 @@ function machineDir() {
1577
1634
  return path.join(process.env.XDG_CONFIG_HOME || path.join(homedir(), ".config"), "geneseed")
1578
1635
  }
1579
1636
 
1580
- // The wiki manifest's names, newest first: WIKI_NAMES in js/lib/machine-dir.mjs.
1581
- const WIKI_NAMES = ["geneseed-wiki.jsonc", "wiki.jsonc", "wiki.json"]
1637
+ // The wiki manifest's names, newest first: js/lib/machine-dir.mjs's line (node tests/twins.mjs).
1638
+ const WIKI_NAMES = ['geneseed-wiki.jsonc', 'wiki.jsonc', 'wiki.json'];
1582
1639
 
1583
1640
  // The host's own config dir counts as global too, whatever its marker says (the hook's
1584
1641
  // isHostGlobalDir accepts both): OPENCODE_CONFIG_DIR, else <XDG config>/opencode.
@@ -2290,36 +2347,69 @@ const noProgramWord = (command) => scanSegments(command).some((seg) => seg.inclu
2290
2347
  .some((t) => !/^\w+=/.test(t)))
2291
2348
 
2292
2349
  // ---- the ownership first-write gate --------------------------------------------
2293
- // Twin of js/hosts/ownership-gate.mjs's `ownershipBlock` — keep in step (same manifests, same
2294
- // managed-block strip, same section match, same reason). In an application repo (a git root
2350
+ // Twin of js/hosts/ownership-gate.mjs's `ownershipBlock`, by hand: this one reads OpenCode's
2351
+ // call, not a hook payload, so the function cannot be a copy. Its constants are (the two twin
2352
+ // blocks and the one-line `WRITE_NAME_RE`, `safeStem`, `DECLINED_RE`, kept by
2353
+ // `node tests/twins.mjs --write`), so the reason cannot drift again. In an application repo (a git root
2295
2354
  // holding a build manifest) whose root AGENTS.md has no `## Ownership` section outside the
2296
2355
  // Geneseed block, the first write of a session is refused once, so the agent proposes the setup
2297
2356
  // to the developer; the session and root are recorded BEFORE the refusal, so the next write
2298
- // passes. The marker is this module Set: the plugin lives as long as the OpenCode process.
2357
+ // passes. The record is the hook's marker file, in the hook's own scheme (`ownershipBlock` in the
2358
+ // twin): `<tmpdir>/geneseed-ownership-<user>/<session id>`, one root per line. This module Set was
2359
+ // once the only record, so a session resumed after OpenCode restarted was refused again on every
2360
+ // restart; it stays as a cache in front of the file.
2299
2361
  const OWNERSHIP_SEEN = new Set()
2300
- const OWNERSHIP_MANIFESTS = new Set(["package.json", "pom.xml", "pyproject.toml", "go.mod", "Cargo.toml",
2301
- "composer.json", "Gemfile"])
2302
- const isManifest = (n) => OWNERSHIP_MANIFESTS.has(n) || n.startsWith("build.gradle") || n.endsWith(".csproj")
2362
+ // The twin's `WRITE_NAME_RE`: the tool names the gate reads as a write, wider than WRITE_TOOLS
2363
+ // by the verbs that move, copy or remove a file (an MCP server's `move_file`, `delete_file`).
2364
+ const WRITE_NAME_RE = /write|edit|diff|replace|insert|move|rename|delete|remove|trash|copy/i;
2365
+ // The twin's `safeStem`, `userTag` and `normcase`, so both hosts name one marker the same way: a
2366
+ // hostile session id cannot steer the join, and the folder is per user on a shared /tmp.
2367
+ const safeStem = (sid) => String(sid).replace(/[^A-Za-z0-9_.-]/gu, '_').slice(0, 128);
2368
+ function ownershipUser() {
2369
+ if (typeof process.getuid === "function") return String(process.getuid())
2370
+ try { return safeStem(userInfo().username) } catch { return "user" }
2371
+ }
2372
+ const ownershipKey = (root) => (process.platform === "win32" ? root.replaceAll("/", "\\").toLowerCase() : root)
2373
+ // ---- ownership shape twin: BEGIN — adapters/opencode/plugins/geneseed-guard.js and
2374
+ // geneseed-context.js carry everything down to the END marker verbatim (node tests/twins.mjs
2375
+ // --write keeps it), and the one-line `WRITE_NAME_RE`, `safeStem` and `DECLINED_RE` below too.
2376
+
2377
+ // D5: the build manifests that make a git root an "application". Exact names, plus two families.
2378
+ const MANIFESTS = new Set(['package.json', 'pom.xml', 'pyproject.toml', 'go.mod', 'Cargo.toml',
2379
+ 'composer.json', 'Gemfile']);
2380
+ const isManifest = (n) => MANIFESTS.has(n) || n.startsWith('build.gradle') || n.endsWith('.csproj');
2381
+
2382
+ // On a Bob project install the managed block holds the whole carrier, `#### Ownership` included —
2383
+ // hence the strip (`withoutBlocks`) and the exact `##` heading match. `\r?`: a CRLF file's `$`
2384
+ // sits after the `\r`.
2385
+ const SECTION_RE = /^## Ownership[ \t]*\r?$/m;
2386
+
2387
+ // ---- ownership shape twin: END
2303
2388
  const MANAGED_BLOCK_RE = /^<!-- BEGIN GENESEED -->[ \t]*\r?\n[\s\S]*?^<!-- END GENESEED -->[ \t]*\r?$/gm
2304
- const OWNERSHIP_SECTION_RE = /^## Ownership[ \t]*\r?$/m
2305
- const OWNERSHIP_TAIL = "Opt out per repo: `## Ownership` with `mode: off` in the root `AGENTS.md`; per " +
2306
- "install: rebuild with `--no-ownership-gate`. Offer the full documentation " +
2307
- "(`/document-project`) as yes / later. Stop and ask the developer now; re-issue the write only " +
2308
- "after they answer. This gate fires once per session and repo."
2309
- const OWNERSHIP_SKIP = "skip this session; or skip in this repo until they ask — only on that third answer, " +
2310
- "write the line `Setup: declined <YYYY-MM-DD>` (today) into `.geneseed/ownership.md` at the " +
2311
- "MAIN worktree's root (in a linked git worktree, the main checkout's, so it outlives this " +
2312
- "worktree), which is personal and never committed (if `.geneseed/.gitignore` is absent there, " +
2313
- "create it first, as the ownership skill's checkpoint rules say)"
2314
- const OWNERSHIP_REASON_NONE = "Geneseed (Ownership) — this application has no `AGENTS.md` with " +
2315
- "`## Ownership`. Before writing, propose three answers to the developer: set it up now " +
2316
- `(ownership skill); ${OWNERSHIP_SKIP}. ${OWNERSHIP_TAIL}`
2317
- const OWNERSHIP_REASON_NO_SECTION = "Geneseed (Ownership) — this application's `AGENTS.md` has no " +
2318
- "`## Ownership` section. Before writing, ask the developer: add the Ownership section now " +
2319
- `(ownership skill); ${OWNERSHIP_SKIP}? ${OWNERSHIP_TAIL}`
2389
+ // ---- ownership text twin: BEGIN — adapters/opencode/plugins/geneseed-guard.js carries everything
2390
+ // down to the END marker verbatim (node tests/twins.mjs --write keeps it).
2391
+
2392
+ const TAIL = 'Opt out per repo: `## Ownership` with `mode: off` in the root `AGENTS.md`; per '
2393
+ + 'install: rebuild with `--no-ownership-gate`. Offer the full documentation '
2394
+ + '(`/document-project`) as yes / later. Stop and ask the developer now; re-issue the write only '
2395
+ + 'after they answer. This gate fires once per session and repo.';
2396
+ // D5: three answers. Only the third writes anything — the durable, personal decline below.
2397
+ const SKIP = 'skip this session; or skip in this repo until they ask — only on that third answer, '
2398
+ + 'write the line `Setup: declined <YYYY-MM-DD>` (today) into `.geneseed/ownership.md` at the '
2399
+ + 'MAIN worktree\'s root (in a linked git worktree, the main checkout\'s, so it outlives this '
2400
+ + 'worktree), which is personal and never committed (if `.geneseed/.gitignore` is absent there, '
2401
+ + 'create it first, as the ownership skill\'s checkpoint rules say)';
2402
+ const REASON_NONE = 'Geneseed (Ownership) — this application has no `AGENTS.md` with '
2403
+ + '`## Ownership`. Before writing, propose three answers to the developer: set it up now '
2404
+ + `(ownership skill); ${SKIP}. ${TAIL}`;
2405
+ const REASON_NO_SECTION = 'Geneseed (Ownership) — this application\'s `AGENTS.md` has no '
2406
+ + '`## Ownership` section. Before writing, ask the developer: add the Ownership section now '
2407
+ + `(ownership skill); ${SKIP}? ${TAIL}`;
2408
+
2409
+ // ---- ownership text twin: END
2320
2410
  // The developer's durable, personal decline (`DECLINED_RE` in the hook twin; geneseed-context.js
2321
2411
  // carries it too): with no section, this line in `.geneseed/ownership.md` defers the gate.
2322
- const OWNERSHIP_DECLINED_RE = /^Setup:[ \t]*declined[ \t]+(\d{4}-\d{2}-\d{2})[ \t]*\r?$/m
2412
+ const DECLINED_RE = /^Setup:[ \t]*declined[ \t]+(\d{4}-\d{2}-\d{2})[ \t]*\r?$/m;
2323
2413
  // The reason to refuse this write, or null. `p` is absolute. Never throws.
2324
2414
  function ownershipBlock(p, sessionID) {
2325
2415
  try {
@@ -2337,7 +2427,7 @@ function ownershipBlock(p, sessionID) {
2337
2427
  let text = null
2338
2428
  try { text = readFileSync(path.join(root, "AGENTS.md"), "utf8") } catch { /* none: gate */ }
2339
2429
  const own = text === null ? "" : text.replace(MANAGED_BLOCK_RE, "")
2340
- if (OWNERSHIP_SECTION_RE.test(own)) return null
2430
+ if (SECTION_RE.test(own)) return null
2341
2431
  let personal = ""
2342
2432
  // In the MAIN worktree (the hook twin's `mainWorktreeOf(root) ?? root`): the shared `.git`'s
2343
2433
  // parent, else this root (a main worktree, a submodule, a bare common dir, a bad link).
@@ -2346,11 +2436,21 @@ function ownershipBlock(p, sessionID) {
2346
2436
  let home = root
2347
2437
  try { const c = gitCommonDirOf(root); if (path.basename(c) === ".git") home = path.dirname(c) } catch { /* this root */ }
2348
2438
  try { personal = readFileSync(path.join(home, ".geneseed", "ownership.md"), "utf8") } catch { /* none: gate */ }
2349
- if (OWNERSHIP_DECLINED_RE.test(personal.replace(/^\uFEFF/, ""))) return null
2350
- const key = `${sessionID}|${nocase(root)}`
2351
- if (OWNERSHIP_SEEN.has(key)) return null
2352
- OWNERSHIP_SEEN.add(key)
2353
- return own.trim() ? OWNERSHIP_REASON_NO_SECTION : OWNERSHIP_REASON_NONE
2439
+ if (DECLINED_RE.test(personal.replace(/^\uFEFF/, ""))) return null
2440
+ const key = ownershipKey(root)
2441
+ const memo = `${sessionID}|${key}`
2442
+ if (OWNERSHIP_SEEN.has(memo)) return null
2443
+ const dir = path.join(tmpdir(), `geneseed-ownership-${ownershipUser()}`)
2444
+ const marker = path.join(dir, safeStem(sessionID))
2445
+ let seen = ""
2446
+ try { seen = readFileSync(marker, "utf8") } catch { /* first gated write of the session */ }
2447
+ if (seen.split("\n").includes(key)) { OWNERSHIP_SEEN.add(memo); return null }
2448
+ // Recorded BEFORE refusing, as in the twin: a marker that cannot be written throws to the
2449
+ // catch below and defers, or every write of the session would be refused.
2450
+ mkdirSync(dir, { recursive: true })
2451
+ appendFileSync(marker, `${key}\n`)
2452
+ OWNERSHIP_SEEN.add(memo)
2453
+ return own.trim() ? REASON_NO_SECTION : REASON_NONE
2354
2454
  } catch { return null }
2355
2455
  }
2356
2456
 
@@ -2390,8 +2490,9 @@ function argPaths(v, key = "", out = [], depth = 0) {
2390
2490
  // from the repo (V2 loads every .js in plugins/ as a plugin). One line per skill or subagent
2391
2491
  // call, the day and the name only, under <cfg>/notebook/usage.jsonl. Silent and never throws:
2392
2492
  // a counter must not change, slow or fail a tool call. tests/unit/usage.test.mjs holds this
2393
- // copy and the hook's to one table.
2394
- const USAGE_NAME_RE = /^[A-Za-z0-9][\w.:@/-]{0,99}$/
2493
+ // copy and the hook's to one table. `usageOf` is by hand (no Bob shapes here); `NAME_RE` is the
2494
+ // hook's line, kept by `node tests/twins.mjs --write`.
2495
+ const NAME_RE = /^[A-Za-z0-9][\w.:@/-]{0,99}$/;
2395
2496
  function usageOf(tool, args) {
2396
2497
  const t = String(tool || "").toLowerCase()
2397
2498
  const a = args || {}
@@ -2401,7 +2502,7 @@ function usageOf(tool, args) {
2401
2502
  else if (t === "agent" || t === "task" || t === "subagent") { kind = "agent"; name = a.subagent_type ?? a.agent }
2402
2503
  if (!kind || typeof name !== "string") return null
2403
2504
  name = name.trim().replace(/^\/+/, "")
2404
- return USAGE_NAME_RE.test(name) ? { kind, name } : null
2505
+ return NAME_RE.test(name) ? { kind, name } : null
2405
2506
  }
2406
2507
  async function recordUse(tool, args) {
2407
2508
  try {
@@ -2416,19 +2517,45 @@ async function recordUse(tool, args) {
2416
2517
  } catch { /* a counter never fails a tool call */ }
2417
2518
  }
2418
2519
 
2520
+ // ---- a gate that fails -----------------------------------------------------------
2521
+ // An error's text, from anything a gate can throw: reading it must not throw in turn.
2522
+ const errorText = (err) => { try { return String(err?.message ?? err) } catch { return "an error that cannot be read" } }
2523
+ // Our own refusal, the one error that must leave the hook.
2524
+ const isDeny = (err) => errorText(err).startsWith("[geneseed-guard]")
2525
+ // How many unanswered marks `setupV2`'s `gateErrors` keeps before the oldest goes.
2526
+ const GATE_ERRORS_HELD = 256
2527
+ // Where the host cannot ask (V1, and a V2 with no permission domain) a gate error lets the call
2528
+ // run (ADR 0007), so the user is told: once per gate for the life of the process, because a
2529
+ // fault in a gate repeats on every call and a notice per call would bury the session. `tell` is
2530
+ // the instance's `say`: a V1 toast (nothing without a TUI client, and the log line stands
2531
+ // alone), a V2 synthetic message.
2532
+ const GATE_ERRORS_TOLD = new Set()
2533
+ async function tellGateError(tell, sid, name, what) {
2534
+ if (GATE_ERRORS_TOLD.has(name)) return
2535
+ GATE_ERRORS_TOLD.add(name)
2536
+ try {
2537
+ await tell(sid, `Geneseed gate error: the ${name} check failed with "${what}", so it did not judge a tool call, and the call ran. `
2538
+ + "The other checks still ran. Run geneseed doctor to find the fault.", "Geneseed gate error")
2539
+ } catch (err) { log(`gate error not shown: ${errorText(err)}`) }
2540
+ }
2541
+
2419
2542
  export const GeneseedGuard = async (ctx) => {
2420
2543
  if (ctx?.client) LOG_CLIENT = ctx.client
2421
2544
  // The session's working directory, the same resolution the context plugin uses.
2422
2545
  const root = () => ctx?.worktree || ctx?.directory || process.cwd()
2423
- // Whether a session has a parent (a subagent's child session). V2 hands in `sessionMeta`
2424
- // (`ctx.session.get`); V1 asks its client. Read only on the rare would-block path; a failed
2425
- // lookup reads as a top-level session.
2426
- const isChildSession = async (sid) => {
2546
+ // Whether a session has no user to ask: a subagent's child session (it has a parent), or a
2547
+ // headless one Geneseed started itself. A workflow's agents run in sessions titled
2548
+ // `geneseed-wf:…` with NO parent (adapters/opencode/workflows/_runtime.js), so the parent test
2549
+ // alone had the ownership gate refuse each one's first write with "ask the developer". The rule
2550
+ // is `isSkippedSession`'s in geneseed-context.js. V2 hands in `sessionMeta` (`ctx.session.get`);
2551
+ // V1 asks its client. Read only on the rare would-block path; a failed lookup reads as a
2552
+ // session with a user.
2553
+ const cannotAsk = async (sid) => {
2427
2554
  try {
2428
2555
  const info = ctx?.sessionMeta ? await ctx.sessionMeta(sid)
2429
2556
  : await ctx?.client?.session?.get?.({ path: { id: sid } })
2430
2557
  const meta = info?.data ?? info
2431
- return Boolean(meta?.parentID ?? meta?.parentId)
2558
+ return Boolean(meta?.parentID ?? meta?.parentId) || String(meta?.title ?? "").startsWith("geneseed-")
2432
2559
  } catch { return false }
2433
2560
  }
2434
2561
  // Whether the host itself will ask the user about this write once this hook lets it run. V2
@@ -2464,7 +2591,7 @@ export const GeneseedGuard = async (ctx) => {
2464
2591
  const unwatched = new Set()
2465
2592
  const watch = async (sid) => {
2466
2593
  if (OFF || !sid || watched.has(sid) || unwatched.has(sid)) return
2467
- if (await sovereignBypass(root()) || await isChildSession(sid)) { unwatched.add(sid); return }
2594
+ if (await sovereignBypass(root()) || await cannotAsk(sid)) { unwatched.add(sid); return }
2468
2595
  watched.set(sid, scanAllStores(root()))
2469
2596
  }
2470
2597
  const compare = async (sid) => {
@@ -2525,144 +2652,205 @@ export const GeneseedGuard = async (ctx) => {
2525
2652
  if (OFF) return
2526
2653
  // A session that predates this plugin never sent `session.created`. Once per session.
2527
2654
  try { await watch(input?.sessionID) } catch { /* the report never decides a tool call */ }
2528
- const tool = (input?.tool || input?.name || "").toLowerCase()
2655
+ const tool = String(input?.tool || input?.name || "").toLowerCase()
2529
2656
  const args = output?.args || input?.args || {}
2530
2657
  // `rule` is the ledger key, spelled as js/hosts/hooks.mjs spells it (`law-1`,
2531
2658
  // `law-4`, `process-1`) plus `wiki`, so status counts one vocabulary across hosts.
2532
2659
  // The model reads this text. It never names the GENESEED_GUARD switch: a weak model read
2533
2660
  // "set GENESEED_GUARD=off to allow" as leave to route the write through a shell (4.27.1).
2534
- // A refusal's words, through `gateSafe` (the ownership reason is the agent's, so it keeps its own): the catch below lets a call through on any error
2535
- // but a deny. No count: no `editPairs` here, and the line reads whole without one.
2661
+ // A refusal's words, through `gateSafe` (the ownership reason is the agent's, so it keeps its
2662
+ // own): `runGate` below lets a call past any error but a deny, so the words must not throw.
2663
+ // No count: no `editPairs` here, and the line reads whole without one.
2536
2664
  const refused = (id, facts) => gateSafe(id, "refused", facts)
2537
2665
  // V1's explanations, held to the end of this hook: a later gate may still refuse the call, and a
2538
2666
  // note about a dialog that never comes is a false one. V2 posts from `evaluate` instead.
2539
2667
  const notes = []
2668
+ // GENESEED_GUARD=warn: the first would-be block is logged and ends the inspection.
2669
+ let warned = false
2540
2670
  const deny = async (why, rule) => {
2541
- if (WARN_ONLY) { log(`WARN (would block): ${why}`); return false }
2671
+ if (WARN_ONLY) { log(`WARN (would block): ${why}`); warned = true; return false }
2542
2672
  log(`BLOCKED: ${why}`)
2543
2673
  await ledger(rule)
2544
2674
  throw new Error(`[geneseed-guard] blocked: ${why}`)
2545
2675
  }
2546
- try {
2547
- // `apply_patch`'s own tool resolves every marker path against `instance.directory`
2548
- // (`apply_patch.ts:72` in the verdict's evidence), NOT the worktree root `root()`
2549
- // uses for the sovereign-repo bypass above — a worktree session started in a
2550
- // subdirectory of its git root must see the same (narrower) root the write
2551
- // actually lands under, or a protected-check/wiki/secret hit one directory up
2552
- // would be missed.
2553
- const cwd = ctx?.directory || process.cwd()
2554
- if (hasAny(tool, WRITE_TOOLS)) {
2555
- // `apply_patch` (gpt-5*) can carry several marker paths in one call — every
2556
- // one of them is a write target, so every one runs every gate; the first hit
2557
- // blocks the whole call (see `pickPath` for why this is not a single path).
2558
- const paths = pickPath(args, cwd)
2559
- for (const raw of paths) {
2560
- if (namesStream(raw)) { await deny(refused("stream", { name: repoRel(path.resolve(cwd, raw)) }), "rigor-5"); return }
2561
- // Once, here: under `opencode serve` this process's cwd is not the session's directory, and
2562
- // every gate below resolves a relative path against it.
2563
- const p = landsOn(raw, cwd)[0].replace(/\\/g, "/")
2564
- if (!SECRETS_GATE_OFF && SECRET_RE.some((re) => re.test(p))) { await deny(refused("secret-file", { name: repoRel(p) }), "law-1"); return }
2565
- if (SECRET_WARN_RE.some((re) => re.test(p))) log(`WARN: writing ${p} — keep secrets out of tracked files (Sealed Secrets)`)
2566
- const sensor = protectedCheck(p)
2567
- if (sensor) { await deny(refused("check", { name: sensor }), "rigor-5"); return }
2568
- if (gateConfig(p)) { await deny(refused("config", { name: repoRel(p) }), "rigor-5"); return }
2569
- if (carrierBlockChange(path.resolve(cwd, raw), tool, args)) { await deny(refused("config", { name: repoRel(p) }), "rigor-5"); return }
2570
- // V1 after an "always": the `permission.edit` ask on these files is gone too.
2571
- if (everyEditApproved && !ctx?.hostAsks && nativeAskFile(p)) { await deny(refused("config", { name: repoRel(p) }), "rigor-5"); return }
2572
- const store = ruleTarget(raw, cwd)
2573
- const prompted = (store || nativeAskFile(p)) && await hostPrompts(tool, raw, cwd)
2574
- if (prompted && !ctx?.hostAsks) notes.push(gateSafe(store ? "store" : "config", "ask", { name: store || repoRel(p) }))
2575
- if (store && !prompted) {
2576
- await deny(`${refused("store", { name: store })}\n${NATIVE_EDIT_TOOLS.has(tool) ? PERSIST_NO_PROMPT : PERSIST_EDIT_TOOL}`, "process-1")
2577
- return
2676
+ // Each gate runs alone. Our own deny propagates. Any other error is that gate's alone: it is
2677
+ // logged, the call is ledgered once as `gate-error`, and the NEXT gate still runs, so a fault
2678
+ // in an early gate no longer switches off the secret scan, the loss gate and the wiki gate
2679
+ // behind it. `failure` is the first gate that failed on this call; what it would have said
2680
+ // is lost, and `unjudged` below answers that once every gate has run.
2681
+ let failure = null
2682
+ const runGate = async (name, gate) => {
2683
+ try { await gate() } catch (err) {
2684
+ if (isDeny(err)) throw err
2685
+ const what = errorText(err).slice(0, 200)
2686
+ log(`gate error in ${name} (the other gates still run): ${what}`)
2687
+ if (failure) return
2688
+ failure = { name, what }
2689
+ await ledger("gate-error")
2690
+ }
2691
+ }
2692
+ // A call no gate refused and one gate could not judge: each host answers to its own ceiling
2693
+ // (ADR 0007). A V2 that can ask marks the call by its id, and `evaluate` raises it to a
2694
+ // prompt. V1 and a V2 with no prompt let it run, and tell the user once per gate.
2695
+ const unjudged = async () => {
2696
+ if (!failure) return
2697
+ if (!ctx?.gateErrors || !input?.callID) { await tellGateError(say, input?.sessionID, failure.name, failure.what); return }
2698
+ ctx.gateErrors.set(input.callID, `${failure.name}: ${failure.what}`)
2699
+ // A call that asserts nothing is never asked about, so its mark would stay for good.
2700
+ if (ctx.gateErrors.size > GATE_ERRORS_HELD) ctx.gateErrors.delete(ctx.gateErrors.keys().next().value)
2701
+ }
2702
+ // `apply_patch`'s own tool resolves every marker path against `instance.directory`
2703
+ // (`apply_patch.ts:72` in the verdict's evidence), NOT the worktree root `root()`
2704
+ // uses for the sovereign-repo bypass above — a worktree session started in a
2705
+ // subdirectory of its git root must see the same (narrower) root the write
2706
+ // actually lands under, or a protected-check/wiki/secret hit one directory up
2707
+ // would be missed.
2708
+ const cwd = ctx?.directory || process.cwd()
2709
+ // The gates of one call, in order. Each reads the arguments for itself: a gate that shared
2710
+ // another's reading would fail with it. A gate's `return` after `deny` is the warn mode's.
2711
+ // `depth` is 0 for the call the host handed in, and counts up through `nestedCalls`. A nested
2712
+ // call has no prompt of its own that this hook can count on (the mark for `evaluate` is the
2713
+ // OUTER call's id, and whether the host asks about a nested edit is unverified), so a nested
2714
+ // rule-store write is refused where a direct one would be handed to the host's prompt.
2715
+ const gatesFor = (tool, args, depth) => {
2716
+ const nested = depth > 0
2717
+ const writes = hasAny(tool, WRITE_TOOLS)
2718
+ return [
2719
+ ["paths", async () => {
2720
+ if (!writes) return
2721
+ // `apply_patch` (gpt-5*) can carry several marker paths in one call — every
2722
+ // one of them is a write target, so every one runs every gate; the first hit
2723
+ // blocks the whole call (see `pickPath` for why this is not a single path).
2724
+ for (const raw of pickPath(args, cwd)) {
2725
+ if (namesStream(raw)) { await deny(refused("stream", { name: repoRel(path.resolve(cwd, raw)) }), "rigor-5"); return }
2726
+ // Once, here: under `opencode serve` this process's cwd is not the session's directory, and
2727
+ // every gate below resolves a relative path against it.
2728
+ const p = landsOn(raw, cwd)[0].replace(/\\/g, "/")
2729
+ if (!SECRETS_GATE_OFF && SECRET_RE.some((re) => re.test(p))) { await deny(refused("secret-file", { name: repoRel(p) }), "law-1"); return }
2730
+ if (SECRET_WARN_RE.some((re) => re.test(p))) log(`WARN: writing ${p} — keep secrets out of tracked files (Sealed Secrets)`)
2731
+ const sensor = protectedCheck(p)
2732
+ if (sensor) { await deny(refused("check", { name: sensor }), "rigor-5"); return }
2733
+ if (gateConfig(p)) { await deny(refused("config", { name: repoRel(p) }), "rigor-5"); return }
2734
+ if (carrierBlockChange(path.resolve(cwd, raw), tool, args)) { await deny(refused("config", { name: repoRel(p) }), "rigor-5"); return }
2735
+ // V1 after an "always": the `permission.edit` ask on these files is gone too.
2736
+ if (everyEditApproved && !ctx?.hostAsks && nativeAskFile(p)) { await deny(refused("config", { name: repoRel(p) }), "rigor-5"); return }
2737
+ const store = ruleTarget(raw, cwd)
2738
+ const prompted = !nested && (store || nativeAskFile(p)) && await hostPrompts(tool, raw, cwd)
2739
+ if (prompted && !ctx?.hostAsks) notes.push(gateSafe(store ? "store" : "config", "ask", { name: store || repoRel(p) }))
2740
+ if (store && !prompted) {
2741
+ await deny(`${refused("store", { name: store })}\n${NATIVE_EDIT_TOOLS.has(tool) && !nested ? PERSIST_NO_PROMPT : PERSIST_EDIT_TOOL}`, "process-1")
2742
+ return
2743
+ }
2578
2744
  }
2579
- }
2745
+ }],
2580
2746
  // Content scan (Sealed Secrets, the twin of js/hosts/hooks.mjs's ruleDecide): per
2581
2747
  // FILE, not pooled — a patch touching `.env` AND an ordinary file must still catch a
2582
2748
  // secret in the ordinary file; only the hunk whose OWN path is `.env`-shaped is
2583
2749
  // exempt, same as the path WARN tier above.
2584
- for (const { path: cp, content } of SECRETS_GATE_OFF ? [] : pickAddedContentByPath(args, cwd)) {
2585
- if (SECRET_WARN_RE.some((re) => re.test(cp))) continue
2586
- if (SECRET_CONTENT_RE.test(content)) {
2587
- await deny(refused("secret", { name: repoRel(path.resolve(cwd, cp)) }), "law-1")
2588
- return
2750
+ ["content", async () => {
2751
+ if (!writes || SECRETS_GATE_OFF) return
2752
+ for (const { path: cp, content } of pickAddedContentByPath(args, cwd)) {
2753
+ if (SECRET_WARN_RE.some((re) => re.test(cp))) continue
2754
+ if (SECRET_CONTENT_RE.test(content)) {
2755
+ await deny(refused("secret", { name: repoRel(path.resolve(cwd, cp)) }), "law-1")
2756
+ return
2757
+ }
2589
2758
  }
2590
- }
2591
- // The ownership first-write gate, last, as in js/hosts/hooks.mjs's ruleDecide. A child
2592
- // session is a subagent (ruling D29): it cannot ask the user, so it never spends a block.
2593
- if (!OWNERSHIP_GATE_OFF) {
2594
- for (const p of paths) {
2759
+ }],
2760
+ // The ownership first-write gate, after the write gates, as in js/hosts/hooks.mjs's
2761
+ // ruleDecide, and over the twin's own tool class (`WRITE_NAME_RE`): a move, a copy
2762
+ // or a delete is a first write too. A session that cannot ask the user (`cannotAsk`: a
2763
+ // subagent, ruling D29, or a headless workflow agent) is never refused.
2764
+ ["ownership", async () => {
2765
+ if (OWNERSHIP_GATE_OFF || !(writes || WRITE_NAME_RE.test(tool))) return
2766
+ for (const p of pickPath(args, cwd)) {
2595
2767
  const why = ownershipBlock(path.resolve(cwd, p), input?.sessionID)
2596
- if (why && !(await isChildSession(input.sessionID))) { await deny(why, "ownership"); return }
2768
+ if (why && !(await cannotAsk(input.sessionID))) { await deny(why, "ownership"); return }
2597
2769
  }
2598
- }
2599
- }
2600
- // Any tool the host's prompt does not cover, whatever it calls its arguments. `pickCommand`,
2601
- // because SHELL_TOOLS is a substring class: `mcp_prune_write` holds "run".
2602
- if (!RULE_STORE_OFF && !NATIVE_EDIT_TOOLS.has(tool) && !readsOnly(tool) && !(hasAny(tool, SHELL_TOOLS) && pickCommand(args))) {
2603
- const named = argPaths(args)
2604
- if (named.overflow) { await deny(refused("deep-args", { name: tool }), "process-1"); return }
2605
- for (const v of named) {
2606
- const store = ruleTarget(v, cwd)
2607
- if (store) {
2608
- await deny(`${refused("store", { name: store })}\n${PERSIST_EDIT_TOOL}`, "process-1")
2609
- return
2770
+ }],
2771
+ // Any tool the host's prompt does not cover, whatever it calls its arguments. `pickCommand`,
2772
+ // because SHELL_TOOLS is a substring class: `mcp_prune_write` holds "run".
2773
+ ["store-args", async () => {
2774
+ if (RULE_STORE_OFF || NATIVE_EDIT_TOOLS.has(tool) || readsOnly(tool) || (hasAny(tool, SHELL_TOOLS) && pickCommand(args))) return
2775
+ const named = argPaths(args)
2776
+ if (named.overflow) { await deny(refused("deep-args", { name: tool }), "process-1"); return }
2777
+ for (const v of named) {
2778
+ const store = ruleTarget(v, cwd)
2779
+ if (store) {
2780
+ await deny(`${refused("store", { name: store })}\n${PERSIST_EDIT_TOOL}`, "process-1")
2781
+ return
2782
+ }
2610
2783
  }
2611
- }
2612
- }
2613
- if (hasAny(tool, WIKI_MUTATE_TOOLS)) {
2614
- for (const p of pickPath(args, cwd)) {
2615
- const abs = landsOn(p, cwd)[0].replace(/\\/g, "/").toLowerCase()
2616
- const hit = (await protectedPrefixes()).find(
2617
- (x) => abs.startsWith(x.prefix) || abs === x.prefix.slice(0, -1))
2618
- if (hit) { await deny(refused("wiki", { name: hit.label }), "wiki"); return }
2619
- }
2620
- }
2621
- // NOT else-if: a compound tool name (e.g. exec_and_save) can match both
2622
- // classes, and the shell check must still run after the write check.
2623
- if (hasAny(tool, SHELL_TOOLS)) {
2624
- // OpenCode's bash tool may run in `workdir`, resolved against the session directory.
2625
- const wd = typeof args.workdir === "string" && args.workdir ? path.resolve(cwd, args.workdir) : cwd
2626
- // One reading for every check below: continuations joined, escaped quotes inert (`shellReading`).
2627
- const picked = pickCommand(args)
2628
- const c = typeof picked === "string" && picked ? shellReading(picked, /powershell|pwsh/i.test(tool) ? "powershell" : null) : picked
2629
- const cut = (t) => scanSegments(t).map((seg) => seg.match(SCAN_TOKEN_RE) || [])
2630
- if (c && (SHELL_BLOCK_RE.some((re) => re.test(c)) || catastrophic(c, cut))) { await deny(refused("catastrophic", { name: c }), "law-4"); return }
2631
- const scan = c && !ROOT_SCAN_OFF && rootScan(c)
2632
- if (scan) {
2633
- await deny(refused("root-scan", { name: scan }), "ops-2")
2634
- return
2635
- }
2636
- if (c && !DELETION_GATE_OFF && LOSS_CANDIDATE_RE.test(c)) {
2637
- const loss = lossReason(cut(c), wd, { always: false, split: cut })
2638
- if (loss) { const facts = gateLoss(loss); await deny(refused(facts.id, facts), "law-4"); return }
2639
- }
2640
- // External Gate over a shell write: the same paths as a write tool, no content scan. A
2641
- // throw fails open through the catch below, as the twin's `shellWriteReason` does.
2642
- for (const p of c ? shellWriteTargets(c, wd, /powershell|pwsh/i.test(tool)) : []) {
2643
- const sensor = protectedCheck(p)
2644
- if (sensor) { await deny(refused("check", { name: sensor, shell: true }), "rigor-5"); return }
2645
- if (gateConfig(p) || nativeAskFile(p)) { await deny(refused("config", { name: repoRel(p), shell: true }), "rigor-5"); return }
2646
- // A parsed form that lands in a store. V2 can ask: `evaluate` runs for the shell tool's own
2647
- // `permission.assert`, so the call is marked by its id and the host prompts. V1 cannot.
2648
- const store = ruleTarget(p, wd)
2649
- if (store && ctx?.shellAsks && input?.callID && !noProgramWord(c)) { ctx.shellAsks.set(input.callID, store); continue }
2650
- if (store) {
2651
- await deny(`${refused("store", { name: store, shell: true })}\n${PERSIST_EDIT_TOOL}`, "process-1")
2784
+ }],
2785
+ ["wiki", async () => {
2786
+ if (!hasAny(tool, WIKI_MUTATE_TOOLS)) return
2787
+ for (const p of pickPath(args, cwd)) {
2788
+ const abs = landsOn(p, cwd)[0].replace(/\\/g, "/").toLowerCase()
2789
+ const hit = (await protectedPrefixes()).find(
2790
+ (x) => abs.startsWith(x.prefix) || abs === x.prefix.slice(0, -1))
2791
+ if (hit) { await deny(refused("wiki", { name: hit.label }), "wiki"); return }
2792
+ }
2793
+ }],
2794
+ // Its own gate, never an else of the write gates: a compound tool name (e.g.
2795
+ // exec_and_save) can match both classes, and the shell check must still run.
2796
+ ["shell", async () => {
2797
+ if (!hasAny(tool, SHELL_TOOLS)) return
2798
+ // OpenCode's bash tool may run in `workdir`, resolved against the session directory.
2799
+ const wd = typeof args.workdir === "string" && args.workdir ? path.resolve(cwd, args.workdir) : cwd
2800
+ // One reading for every check below: continuations joined, escaped quotes inert (`shellReading`).
2801
+ const picked = pickCommand(args)
2802
+ const c = typeof picked === "string" && picked ? shellReading(picked, /powershell|pwsh/i.test(tool) ? "powershell" : null) : picked
2803
+ const cut = (t) => scanSegments(t).map((seg) => seg.match(SCAN_TOKEN_RE) || [])
2804
+ if (c && (SHELL_BLOCK_RE.some((re) => re.test(c)) || catastrophic(c, cut))) { await deny(refused("catastrophic", { name: c }), "law-4"); return }
2805
+ const scan = c && !ROOT_SCAN_OFF && rootScan(c)
2806
+ if (scan) {
2807
+ await deny(refused("root-scan", { name: scan }), "ops-2")
2652
2808
  return
2653
2809
  }
2654
- }
2655
- }
2656
- for (const note of notes) {
2657
- // No count here, as in a refusal. 120 s, because the dialog stays until it is answered.
2658
- try {
2659
- await ctx?.client?.tui?.showToast?.({ body: { title: "Geneseed", message: gateNote(note), variant: "warning", duration: 120000 }, query: { directory: cwd } })
2660
- } catch (err) { log(`note not shown: ${err?.message ?? err}`) }
2810
+ if (c && !DELETION_GATE_OFF && LOSS_CANDIDATE_RE.test(c)) {
2811
+ const loss = lossReason(cut(c), wd, { always: false, split: cut })
2812
+ if (loss) { const facts = gateLoss(loss); await deny(refused(facts.id, facts), "law-4"); return }
2813
+ }
2814
+ // External Gate over a shell write: the same paths as a write tool, no content scan. A
2815
+ // throw here is this gate's error (`runGate`), where the twin's `shellWriteReason` fails open.
2816
+ for (const p of c ? shellWriteTargets(c, wd, /powershell|pwsh/i.test(tool)) : []) {
2817
+ const sensor = protectedCheck(p)
2818
+ if (sensor) { await deny(refused("check", { name: sensor, shell: true }), "rigor-5"); return }
2819
+ if (gateConfig(p) || nativeAskFile(p)) { await deny(refused("config", { name: repoRel(p), shell: true }), "rigor-5"); return }
2820
+ // A parsed form that lands in a store. V2 can ask: `evaluate` runs for the shell tool's own
2821
+ // `permission.assert`, so the call is marked by its id and the host prompts. V1 cannot.
2822
+ const store = ruleTarget(p, wd)
2823
+ if (store && !nested && ctx?.shellAsks && input?.callID && !noProgramWord(c)) { ctx.shellAsks.set(input.callID, store); continue }
2824
+ if (store) {
2825
+ await deny(`${refused("store", { name: store, shell: true })}\n${PERSIST_EDIT_TOOL}`, "process-1")
2826
+ return
2827
+ }
2828
+ }
2829
+ }],
2830
+ // Last, so the call's own gates have spoken: every call it carries, as a call of its own.
2831
+ ["nested", async () => {
2832
+ for (const call of nestedCalls(args)) {
2833
+ if (depth >= NESTED_DEPTH) { await deny(refused("deep-args", { name: tool }), "process-1"); return }
2834
+ await judge(call.tool, call.args, depth + 1)
2835
+ if (warned) return
2836
+ }
2837
+ }],
2838
+ ]
2839
+ }
2840
+ const judge = async (tool, args, depth) => {
2841
+ for (const [name, gate] of gatesFor(tool, args, depth)) {
2842
+ await runGate(name, gate)
2843
+ if (warned) return
2661
2844
  }
2662
- } catch (err) {
2663
- // Our own deny must propagate; any inspection error must never break a tool call.
2664
- if (err && String(err.message || "").startsWith("[geneseed-guard]")) throw err
2665
- log(`inspect error (ignored): ${err?.message ?? err}`)
2845
+ }
2846
+ await judge(tool, args, 0)
2847
+ await unjudged()
2848
+ if (warned) return
2849
+ for (const note of notes) {
2850
+ // No count here, as in a refusal. 120 s, because the dialog stays until it is answered.
2851
+ try {
2852
+ await ctx?.client?.tui?.showToast?.({ body: { title: "Geneseed", message: gateNote(note), variant: "warning", duration: 120000 }, query: { directory: cwd } })
2853
+ } catch (err) { log(`note not shown: ${err?.message ?? err}`) }
2666
2854
  }
2667
2855
  },
2668
2856
  }
@@ -2690,10 +2878,16 @@ export const GeneseedGuard = async (ctx) => {
2690
2878
  // and an unattended session turns the ask into a deny. A V2 without the domain has no `hostAsks`,
2691
2879
  // so the guard refuses those writes.
2692
2880
  //
2881
+ // The same hook asks about a call a gate FAILED on (`runGate`, ADR 0007 as amended 2026-11): the
2882
+ // tool hook marks the call's id in `gateErrors`, and the first `evaluate` whose `source.id` is that
2883
+ // call becomes an ask with the `gate-error` text. Unverified against a live host: `source.id` is
2884
+ // seen on the shell tool's assert (2.2.5), and is assumed, not observed, on `edit` and on an MCP
2885
+ // tool's. A call that asserts nothing, or whose assert names no call, runs unasked, as on V1.
2886
+ //
2693
2887
  // The dialog shows no plugin text, so each ask posts a note first. The TUI renders a synthetic item's
2694
2888
  // `description` and the model gets its `text`, so the block goes in the first and the second must read
2695
2889
  // true whether the user allows or denies (spec 2026-11-07-gate-prompts-5.0.3, S0 result).
2696
- async function askOnRuleStore(ctx, shellAsks) {
2890
+ async function askOnRuleStore(ctx, shellAsks, gateErrors) {
2697
2891
  const dir = ctx?.location?.directory || process.cwd()
2698
2892
  const note = async (event) => {
2699
2893
  try {
@@ -2705,6 +2899,22 @@ async function askOnRuleStore(ctx, shellAsks) {
2705
2899
  await ctx.permission.hook("evaluate", async (event) => {
2706
2900
  try {
2707
2901
  if (OFF || event.effect === "deny") return
2902
+ // A call one of the tool hook's gates could not judge (`runGate`), by its id, whatever the
2903
+ // action: the user decides in the gate's place. The first assert of the call carries it.
2904
+ const failed = gateErrors.get(event.source?.id)
2905
+ if (gateErrors.delete(event.source?.id)) {
2906
+ if (WARN_ONLY) log(`WARN (would ask): a gate failed (${failed})`)
2907
+ else {
2908
+ // A store write the same call was marked for is said first: it is what the call does.
2909
+ const shellStore = shellAsks.get(event.source?.id)
2910
+ shellAsks.delete(event.source?.id)
2911
+ event.effect = "ask"
2912
+ event.message = [...(shellStore ? [gateSafe("store", "ask", { name: shellStore, shell: true })] : []),
2913
+ gateSafe("gate-error", "ask", { name: failed })].join("\n")
2914
+ await note(event)
2915
+ return
2916
+ }
2917
+ }
2708
2918
  if (event.action === "shell") {
2709
2919
  // The shell tool's assert: action `shell`, one resource per parsed command, `source.id` the
2710
2920
  // call the tool hook marked. A command the host's parser finds no command in asserts nothing.
@@ -2736,14 +2946,15 @@ async function askOnRuleStore(ctx, shellAsks) {
2736
2946
  }
2737
2947
 
2738
2948
  async function setupV2(ctx) {
2739
- // Call id to the store it writes, for the prompt's text.
2949
+ // Call id to the store it writes, for the prompt's text; call id to the gate that failed on it.
2740
2950
  const shellAsks = new Map()
2741
- const hostAsks = await askOnRuleStore(ctx, shellAsks)
2951
+ const gateErrors = new Map()
2952
+ const hostAsks = await askOnRuleStore(ctx, shellAsks, gateErrors)
2742
2953
  const hooks = await GeneseedGuard({
2743
2954
  worktree: ctx?.location?.project?.directory, directory: ctx?.location?.directory,
2744
2955
  sessionMeta: (sessionID) => ctx.session.get({ sessionID }),
2745
- hostAsks, shellAsks: hostAsks ? shellAsks : null,
2746
- say: (sessionID, text) => ctx.session.synthetic({ sessionID, text, description: "Geneseed change report", resume: false }),
2956
+ hostAsks, shellAsks: hostAsks ? shellAsks : null, gateErrors: hostAsks ? gateErrors : null,
2957
+ say: (sessionID, text, description = "Geneseed change report") => ctx.session.synthetic({ sessionID, text, description, resume: false }),
2747
2958
  })
2748
2959
  const report = (type, properties) => hooks.event({ event: { type, properties } })
2749
2960
  // V2's turn edges, as geneseed-notify reads them. `say` above is the only way out to the user.
@@ -2767,11 +2978,14 @@ async function setupV2(ctx) {
2767
2978
  // `sessionID` rides on every V2 execute.before event (@opencode/plugin 2.1.4 `ToolHooks`).
2768
2979
  await hooks["tool.execute.before"]({ tool: event.tool, sessionID: event.sessionID, callID: event.id }, { args: event.input })
2769
2980
  } catch (err) {
2770
- const why = String(err?.message || "")
2771
- if (!why.startsWith("[geneseed-guard]")) return
2981
+ if (!isDeny(err)) return
2772
2982
  // Core prints `No tool named "<this>"`, so the name must say first that nothing is missing.
2773
- event.tool = `BLOCKED, not a missing tool: ${why}`
2774
- event.input = {}
2983
+ // In their own try: an event that cannot be written (frozen, a setter that throws) must not
2984
+ // fail the step. The refusal is then only logged, and the call runs.
2985
+ try {
2986
+ event.tool = `BLOCKED, not a missing tool: ${errorText(err)}`
2987
+ event.input = {}
2988
+ } catch (failed) { log(`refusal not applied, the call runs: ${errorText(failed)}`) }
2775
2989
  }
2776
2990
  })
2777
2991
  return () => controller.abort()