geneseed 5.2.0 → 5.3.1

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 (190) hide show
  1. package/CHANGELOG.md +54 -0
  2. package/README.md +4 -4
  3. package/SHIPPED.md +1 -1
  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/plugins/geneseed-activity.js +20 -21
  9. package/adapters/opencode/plugins/geneseed-context.js +224 -71
  10. package/adapters/opencode/plugins/geneseed-guard.js +420 -203
  11. package/adapters/opencode/plugins/geneseed-workflow.js +3 -2
  12. package/adapters/opencode/workflows/_runtime.js +3 -2
  13. package/bin/geneseed-cli.mjs +61 -16
  14. package/bin/geneseed-hook.mjs +94 -12
  15. package/docs/concepts/enforcement-table.md +1 -1
  16. package/docs/concepts/exclusions.md +2 -2
  17. package/docs/concepts/factories.md +40 -6
  18. package/docs/concepts/footprint.md +11 -1
  19. package/docs/concepts/foreman-mode.md +2 -2
  20. package/docs/concepts/hook-gates.md +3 -3
  21. package/docs/concepts/host-matrix.md +22 -4
  22. package/docs/concepts/loop-gates.md +1 -1
  23. package/docs/concepts/loops.md +2 -2
  24. package/docs/concepts/shared-tier.md +1 -1
  25. package/docs/design-history.md +148 -0
  26. package/docs/extending.md +97 -163
  27. package/docs/guides/install-bob.md +2 -2
  28. package/docs/guides/install-openclaude.md +1 -1
  29. package/docs/guides/run-a-factory.md +15 -2
  30. package/docs/guides/upgrade.md +2 -2
  31. package/docs/guides/verify.md +12 -0
  32. package/docs/reference/environment.md +1 -0
  33. package/docs/reference/factory-actions.md +6 -5
  34. package/docs/reference/troubleshoot-doctor.md +1 -1
  35. package/docs/reference/troubleshoot-update.md +1 -1
  36. package/docs/token-footprint.md +66 -2
  37. package/docs/understand/design-choices-hosts.md +1 -1
  38. package/docs/understand/design-choices-shape.md +1 -0
  39. package/docs/understand/enforced-vs-asked.md +1 -1
  40. package/docs/understand/machine-bob.md +1 -1
  41. package/docs/web-ui.md +21 -3
  42. package/harness.config.json +1 -1
  43. package/js/README.md +7 -5
  44. package/js/build/args.mjs +4 -4
  45. package/js/build/driver.mjs +1 -1
  46. package/js/build/emit-claude.mjs +1 -1
  47. package/js/build/generate.mjs +5 -14
  48. package/js/build/render.mjs +44 -24
  49. package/js/cli-table.json +135 -59
  50. package/js/factory/cli.mjs +24 -5
  51. package/js/factory/graph.mjs +13 -9
  52. package/js/factory/metrics.mjs +93 -0
  53. package/js/factory/registry.mjs +37 -12
  54. package/js/factory/state.mjs +25 -6
  55. package/js/hosts/done-checks.mjs +6 -0
  56. package/js/hosts/geneseed-dir.mjs +3 -2
  57. package/js/hosts/gitref.mjs +5 -3
  58. package/js/hosts/hook-tap.mjs +104 -0
  59. package/js/hosts/hooks-context.mjs +30 -3
  60. package/js/hosts/hooks-learn.mjs +47 -16
  61. package/js/hosts/hooks-prims.mjs +52 -3
  62. package/js/hosts/hooks.mjs +69 -42
  63. package/js/hosts/hosts.mjs +80 -12
  64. package/js/hosts/installs.mjs +7 -0
  65. package/js/hosts/loss.mjs +6 -1
  66. package/js/hosts/native.mjs +14 -5
  67. package/js/hosts/owned.mjs +7 -6
  68. package/js/hosts/ownership-gate.mjs +14 -1
  69. package/js/hosts/settings.mjs +245 -103
  70. package/js/hosts/shim.mjs +4 -4
  71. package/js/hosts/usage.mjs +9 -3
  72. package/js/inspect/checks-probe.mjs +66 -5
  73. package/js/inspect/checks-repo.mjs +196 -2
  74. package/js/inspect/cost.mjs +34 -2
  75. package/js/inspect/diff.mjs +16 -1
  76. package/js/inspect/doctor.mjs +13 -4
  77. package/js/inspect/excludes.mjs +18 -6
  78. package/js/inspect/status.mjs +35 -7
  79. package/js/inspect/validate.mjs +44 -21
  80. package/js/lib/machine-dir.mjs +1 -1
  81. package/js/lib/node-floor.mjs +46 -6
  82. package/js/maintain/uninstall.mjs +70 -17
  83. package/js/maintain/update.mjs +31 -7
  84. package/js/ui/cli.mjs +34 -4
  85. package/js/ui/menu.mjs +1 -1
  86. package/js/ui/tui.mjs +11 -14
  87. package/js/web/actions.mjs +3 -9
  88. package/js/web/api.mjs +28 -10
  89. package/js/web/daemon.mjs +0 -1
  90. package/js/web/server.mjs +1 -0
  91. package/js/web/state.mjs +37 -16
  92. package/package.json +1 -1
  93. package/src/AGENT.md.tmpl +23 -17
  94. package/src/agents/_template.md +1 -1
  95. package/src/agents/advocate.md +1 -1
  96. package/src/agents/developer.md +12 -3
  97. package/src/agents/empiricist.md +1 -1
  98. package/src/agents/framer.md +1 -1
  99. package/src/agents/historian.md +1 -1
  100. package/src/agents/operator.md +1 -1
  101. package/src/agents/pragmatist.md +1 -1
  102. package/src/agents/researcher.md +1 -1
  103. package/src/agents/skeptic.md +1 -1
  104. package/src/agents/steward.md +1 -1
  105. package/src/agents/user-advocate.md +1 -1
  106. package/src/agents/visionary.md +1 -1
  107. package/src/bricks/intake.md +10 -3
  108. package/src/bricks/retro.md +13 -3
  109. package/src/doctrines/comms.md +1 -1
  110. package/src/doctrines/ops.md +1 -1
  111. package/src/doctrines/process.md +7 -5
  112. package/src/factories/analysis-to-build.json +1 -0
  113. package/src/factories/bug-report-to-fix.json +1 -0
  114. package/src/factories/issue-to-pr.json +1 -0
  115. package/src/laws/universal.md +2 -2
  116. package/src/modes/foreman.md +8 -14
  117. package/src/skills/commit.md +7 -2
  118. package/src/skills/debug.md +1 -1
  119. package/src/skills/diagram-design/SKILL.md +1 -1
  120. package/src/skills/diagram-design/VENDOR.md +3 -1
  121. package/src/skills/factory-forge.md +5 -3
  122. package/src/skills/factory.md +22 -1
  123. package/src/skills/geneseed.md +1 -1
  124. package/src/skills/handoff.md +1 -1
  125. package/src/skills/parallel-agents.md +1 -1
  126. package/src/skills/pipeline.md +6 -6
  127. package/src/skills/plan.md +7 -3
  128. package/src/skills/spring-testing.md +1 -1
  129. package/themes/biker.json +78 -78
  130. package/themes/commentator.json +81 -81
  131. package/themes/cyberpunk.json +79 -79
  132. package/themes/gamer.json +77 -77
  133. package/themes/imperial.json +82 -82
  134. package/themes/joker.json +79 -79
  135. package/themes/marvin.json +82 -82
  136. package/themes/mean.json +82 -82
  137. package/themes/military.json +78 -78
  138. package/themes/neutral.json +78 -78
  139. package/themes/pirate.json +79 -79
  140. package/themes/sports.json +79 -79
  141. package/themes/verstappen.json +78 -78
  142. package/themes/wizard.json +79 -79
  143. package/web/dist/assets/ActiveLoops-BJJN3P-V.js +1 -0
  144. package/web/dist/assets/Activity-WQ3ykgxU.js +1 -0
  145. package/web/dist/assets/ActivityDetail-7rt04SkS.js +1 -0
  146. package/web/dist/assets/{Bonsai-DSwUbavu.js → Bonsai-BBl4XXqs.js} +1 -1
  147. package/web/dist/assets/{CopyButton-BzRQz7k2.js → CopyButton-Beven8yn.js} +1 -1
  148. package/web/dist/assets/Dashboard-BgLArtgu.js +2 -0
  149. package/web/dist/assets/Docs-B5aHp86J.js +5 -0
  150. package/web/dist/assets/Factories-BjqzXAw8.js +1 -0
  151. package/web/dist/assets/GreenhouseView-Bce212qd.js +1 -0
  152. package/web/dist/assets/Installs-B1OsrHXF.js +3 -0
  153. package/web/dist/assets/JournalView-CV4omyww.js +1 -0
  154. package/web/dist/assets/Kits-CW1e7xNa.js +1 -0
  155. package/web/dist/assets/Laws-1Ckf1lbs.js +4 -0
  156. package/web/dist/assets/LibRows-Dag1s0ZX.js +1 -0
  157. package/web/dist/assets/Library-B3FuFLel.js +3 -0
  158. package/web/dist/assets/Loops-CwqgnLNw.js +2 -0
  159. package/web/dist/assets/Markdown-CxkA7940.js +71 -0
  160. package/web/dist/assets/OperatorHudView-JmYY1pBR.js +1 -0
  161. package/web/dist/assets/Personal-DKLgLa7Z.js +2 -0
  162. package/web/dist/assets/Settings-BwErnh-R.js +1 -0
  163. package/web/dist/assets/Tabs-8zsyEPSK.js +1 -0
  164. package/web/dist/assets/index-CRWqKxfY.css +1 -0
  165. package/web/dist/assets/index-Ce6qF2nG.js +6 -0
  166. package/web/dist/assets/usePoll-D5c_qIFZ.js +1 -0
  167. package/web/dist/index.html +2 -2
  168. package/adapters/claude-code/settings.json +0 -52
  169. package/web/dist/assets/ActiveLoops-BTHIaRhn.js +0 -1
  170. package/web/dist/assets/Activity-DlQ30znB.js +0 -1
  171. package/web/dist/assets/ActivityDetail-CG0mn5fW.js +0 -1
  172. package/web/dist/assets/Dashboard-Ce3UOsxJ.js +0 -2
  173. package/web/dist/assets/Docs-CisVnYqv.js +0 -5
  174. package/web/dist/assets/Factories-Dq5oW4CU.js +0 -1
  175. package/web/dist/assets/GreenhouseView-y9WAfcc_.js +0 -1
  176. package/web/dist/assets/Installs-m4GElwFW.js +0 -3
  177. package/web/dist/assets/JournalView-DeBLRNGc.js +0 -1
  178. package/web/dist/assets/Kits-DJYVAnyE.js +0 -1
  179. package/web/dist/assets/Laws-CNpc_8ZV.js +0 -4
  180. package/web/dist/assets/LibRows-RO5bvXth.js +0 -1
  181. package/web/dist/assets/Library-Dg0ScciC.js +0 -3
  182. package/web/dist/assets/Loops-CjEdo-NG.js +0 -2
  183. package/web/dist/assets/Markdown-0ORz7tAc.js +0 -69
  184. package/web/dist/assets/OperatorHudView-2ujVMjq1.js +0 -1
  185. package/web/dist/assets/Personal-D0yS7ahT.js +0 -2
  186. package/web/dist/assets/Settings-DEN0U8QI.js +0 -1
  187. package/web/dist/assets/Tabs-But5R6_r.js +0 -1
  188. package/web/dist/assets/index-Ck42AbRX.js +0 -6
  189. package/web/dist/assets/index-PG_ukkh6.css +0 -1
  190. package/web/dist/assets/usePoll-o8ul-Sog.js +0 -1
@@ -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
@@ -356,9 +373,14 @@ function stashExists(root) {
356
373
  * a spawn. A git destructive VERB anywhere after `git` on the same line, or a removal program
357
374
  * as a word at a command boundary. Deliberately loose — the parse decides; this only has to be
358
375
  * a superset of what the parse acts on.
376
+ *
377
+ * The git half is LINEAR: it starts only at the input's start or a `\n` and tries the line's
378
+ * first `git` alone, which matches whenever any later `git` would. `\bgit\b[^\n]*\b(?:…)` from
379
+ * every `git` was quadratic: a 270 KB `git -C x …` took seconds, and a hook past its timeout
380
+ * lets the call through. `(?<![\s\S])`, not `^`: under `m`, `^` also starts after `\r`.
359
381
  */
360
382
  const LOSS_CANDIDATE_RE =
361
- /\bgit\b[^\n]*\b(?:reset|clean|branch|checkout|switch|restore|stash|reflog|gc|push)\b|(?:^|[\s;&|("'`])(?:rm|rmdir|unlink|del|erase|remove-item|ri|rd)(?:\.exe)?(?=[\s;&|)"'`]|$)|(?:^|\s)-delete(?=\s|$)/im;
383
+ /(?:(?<![\s\S])|\n)(?:(?!\bgit\b)[^\n])*\bgit\b[^\n]*\b(?:reset|clean|branch|checkout|switch|restore|stash|reflog|gc|push)\b|(?:^|[\s;&|("'`])(?:rm|rmdir|unlink|del|erase|remove-item|ri|rd)(?:\.exe)?(?=[\s;&|)"'`]|$)|(?:^|\s)-delete(?=\s|$)/im;
362
384
 
363
385
  class Unverified extends Error {}
364
386
  const unverified = (why) => { throw new Unverified(why); };
@@ -1431,13 +1453,19 @@ function plainPaths(args) {
1431
1453
  // as the segment separator) match `C:\Users\me\.ssh\id_rsa` the same as a POSIX path.
1432
1454
  return PATH_KEYS.map((k) => args?.[k]).filter((v) => typeof v === "string" && v).map((v) => v.replace(/\\/g, "/"))
1433
1455
  }
1434
- // Returns every candidate path for this call, normalized (backslashes -> `/`): every path key, and
1435
- // every patch marker resolved against `cwd` (the session's `ctx.directory` — the same root
1436
- // `apply_patch.ts:72` resolves against upstream) since a patch marker is worktree-relative.
1456
+ // A multi-edit call's entries: `edits[]`, each carrying its new text and, on some tools, a file of
1457
+ // its own. UNVERIFIED against a live OpenCode: the shape is its V1 `multiedit` tool's as its
1458
+ // source reads (`filePath` beside `edits: [{ filePath, oldString, newString }]`), and no host was
1459
+ // run here to see whether that tool still ships under that name on either major.
1460
+ const editsOf = (args) => (Array.isArray(args?.edits) ? args.edits.filter((e) => e && typeof e === "object") : [])
1461
+ // Returns every candidate path for this call, normalized (backslashes -> `/`): every path key, the
1462
+ // path keys of each `edits[]` entry, and every patch marker resolved against `cwd` (the session's
1463
+ // `ctx.directory` — the same root `apply_patch.ts:72` resolves against upstream) since a patch
1464
+ // marker is worktree-relative.
1437
1465
  function pickPath(args, cwd) {
1438
1466
  const marked = args && typeof args.patchText === "string" ? parsePatchPaths(args.patchText)
1439
1467
  .map((p) => path.resolve(cwd || process.cwd(), p).replace(/\\/g, "/")) : []
1440
- return [...new Set([...marked, ...plainPaths(args)])]
1468
+ return [...new Set([...marked, ...plainPaths(args), ...editsOf(args).flatMap(plainPaths)])]
1441
1469
  }
1442
1470
  // Per-FILE added content for an `apply_patch` call: `parsePatchPaths` flattens every marker
1443
1471
  // path into one list (right for the path-only gates, which must catch a secret/protected name
@@ -1483,7 +1511,9 @@ function patchSections(patchText) {
1483
1511
  // (OpenCode tool Parameters, packages/opencode/src/tool/{write,edit}.ts) — both single-path, so
1484
1512
  // one pair. For `apply_patch`, one pair per marker section; only the `+`-prefixed hunk lines are
1485
1513
  // NEW content — a `-` line is text being REMOVED, so a secret there is leaving the file, not
1486
- // landing in it, and must not block the call.
1514
+ // landing in it, and must not block the call. A multi-edit carries one `newString` (or
1515
+ // `new_string`) per `edits[]` entry, each attributed to the entry's own file, else the call's
1516
+ // (the twin read: `ruleDecide` in js/hosts/hooks.mjs joins `edits[].new_string` the same way).
1487
1517
  function pickAddedContentByPath(args, cwd) {
1488
1518
  const found = args && typeof args.patchText === "string" ? parsePatchSections(args.patchText)
1489
1519
  .filter((s) => s.added.length)
@@ -1493,10 +1523,40 @@ function pickAddedContentByPath(args, cwd) {
1493
1523
  })) : []
1494
1524
  // Beside a patch too: a decoy `patchText` must not hide the content a call also carries.
1495
1525
  const [p] = plainPaths(args)
1496
- if (!p) return found
1497
- for (const text of [args.content, args.newString]) if (typeof text === "string") found.push({ path: p, content: text })
1526
+ if (p) for (const text of [args.content, args.newString]) if (typeof text === "string") found.push({ path: p, content: text })
1527
+ for (const edit of editsOf(args)) {
1528
+ const own = plainPaths(edit)[0] ?? p
1529
+ if (!own) continue
1530
+ for (const text of [edit.newString, edit.new_string]) if (typeof text === "string") found.push({ path: own, content: text })
1531
+ }
1498
1532
  return found
1499
1533
  }
1534
+ // The calls a tool carries inside its own arguments: `tool_calls[]` or `calls[]`, each entry
1535
+ // `{ tool | name, parameters | args | input }`. A tool outside the write and shell classes was
1536
+ // read for rule-store paths only, so a `batch` holding a nested `bash rm -rf /` or a nested write
1537
+ // of a key passed every other gate. Each entry now runs the whole gate pipeline as its own call.
1538
+ // An entry with no tool name is no call, and its strings still reach the rule-store walk.
1539
+ //
1540
+ // UNVERIFIED against a live OpenCode, all of it: whether a `batch` tool ships under that name on
1541
+ // either major, whether its entries have this shape (V1's source reads `tool_calls: [{ tool,
1542
+ // parameters }]`), and whether the host fires `tool.execute.before` again for each nested call. If
1543
+ // it does, nothing is refused twice (the outer call is refused first, and then no entry runs),
1544
+ // but a gate ERROR is ledgered once for the outer call and once more for the nested one.
1545
+ const NESTED_KEYS = ["tool_calls", "calls"]
1546
+ // A batch inside a batch is already unusual; past this, what cannot be read is refused.
1547
+ const NESTED_DEPTH = 8
1548
+ function nestedCalls(args) {
1549
+ const out = []
1550
+ for (const key of NESTED_KEYS) {
1551
+ for (const call of Array.isArray(args?.[key]) ? args[key] : []) {
1552
+ if (!call || typeof call !== "object") continue
1553
+ const tool = [call.tool, call.name].find((v) => typeof v === "string" && v)
1554
+ const inner = [call.parameters, call.args, call.input].find((v) => v && typeof v === "object")
1555
+ if (tool) out.push({ tool: tool.toLowerCase(), args: inner ?? {} })
1556
+ }
1557
+ }
1558
+ return out
1559
+ }
1500
1560
  function pickCommand(args) {
1501
1561
  for (const k of ["command", "cmd", "script"]) {
1502
1562
  if (args && typeof args[k] === "string") return args[k]
@@ -1572,8 +1632,8 @@ function machineDir() {
1572
1632
  return path.join(process.env.XDG_CONFIG_HOME || path.join(homedir(), ".config"), "geneseed")
1573
1633
  }
1574
1634
 
1575
- // The wiki manifest's names, newest first: WIKI_NAMES in js/lib/machine-dir.mjs.
1576
- const WIKI_NAMES = ["geneseed-wiki.jsonc", "wiki.jsonc", "wiki.json"]
1635
+ // The wiki manifest's names, newest first: js/lib/machine-dir.mjs's line (node tests/twins.mjs).
1636
+ const WIKI_NAMES = ['geneseed-wiki.jsonc', 'wiki.jsonc', 'wiki.json'];
1577
1637
 
1578
1638
  // The host's own config dir counts as global too, whatever its marker says (the hook's
1579
1639
  // isHostGlobalDir accepts both): OPENCODE_CONFIG_DIR, else <XDG config>/opencode.
@@ -2285,36 +2345,69 @@ const noProgramWord = (command) => scanSegments(command).some((seg) => seg.inclu
2285
2345
  .some((t) => !/^\w+=/.test(t)))
2286
2346
 
2287
2347
  // ---- the ownership first-write gate --------------------------------------------
2288
- // Twin of js/hosts/ownership-gate.mjs's `ownershipBlock` — keep in step (same manifests, same
2289
- // managed-block strip, same section match, same reason). In an application repo (a git root
2348
+ // Twin of js/hosts/ownership-gate.mjs's `ownershipBlock`, by hand: this one reads OpenCode's
2349
+ // call, not a hook payload, so the function cannot be a copy. Its constants are (the two twin
2350
+ // blocks and the one-line `WRITE_NAME_RE`, `safeStem`, `DECLINED_RE`, kept by
2351
+ // `node tests/twins.mjs --write`), so the reason cannot drift again. In an application repo (a git root
2290
2352
  // holding a build manifest) whose root AGENTS.md has no `## Ownership` section outside the
2291
2353
  // Geneseed block, the first write of a session is refused once, so the agent proposes the setup
2292
2354
  // to the developer; the session and root are recorded BEFORE the refusal, so the next write
2293
- // passes. The marker is this module Set: the plugin lives as long as the OpenCode process.
2355
+ // passes. The record is the hook's marker file, in the hook's own scheme (`ownershipBlock` in the
2356
+ // twin): `<tmpdir>/geneseed-ownership-<user>/<session id>`, one root per line. This module Set was
2357
+ // once the only record, so a session resumed after OpenCode restarted was refused again on every
2358
+ // restart; it stays as a cache in front of the file.
2294
2359
  const OWNERSHIP_SEEN = new Set()
2295
- const OWNERSHIP_MANIFESTS = new Set(["package.json", "pom.xml", "pyproject.toml", "go.mod", "Cargo.toml",
2296
- "composer.json", "Gemfile"])
2297
- const isManifest = (n) => OWNERSHIP_MANIFESTS.has(n) || n.startsWith("build.gradle") || n.endsWith(".csproj")
2360
+ // The twin's `WRITE_NAME_RE`: the tool names the gate reads as a write, wider than WRITE_TOOLS
2361
+ // by the verbs that move, copy or remove a file (an MCP server's `move_file`, `delete_file`).
2362
+ const WRITE_NAME_RE = /write|edit|diff|replace|insert|move|rename|delete|remove|trash|copy/i;
2363
+ // The twin's `safeStem`, `userTag` and `normcase`, so both hosts name one marker the same way: a
2364
+ // hostile session id cannot steer the join, and the folder is per user on a shared /tmp.
2365
+ const safeStem = (sid) => String(sid).replace(/[^A-Za-z0-9_.-]/gu, '_').slice(0, 128);
2366
+ function ownershipUser() {
2367
+ if (typeof process.getuid === "function") return String(process.getuid())
2368
+ try { return safeStem(userInfo().username) } catch { return "user" }
2369
+ }
2370
+ const ownershipKey = (root) => (process.platform === "win32" ? root.replaceAll("/", "\\").toLowerCase() : root)
2371
+ // ---- ownership shape twin: BEGIN — adapters/opencode/plugins/geneseed-guard.js and
2372
+ // geneseed-context.js carry everything down to the END marker verbatim (node tests/twins.mjs
2373
+ // --write keeps it), and the one-line `WRITE_NAME_RE`, `safeStem` and `DECLINED_RE` below too.
2374
+
2375
+ // D5: the build manifests that make a git root an "application". Exact names, plus two families.
2376
+ const MANIFESTS = new Set(['package.json', 'pom.xml', 'pyproject.toml', 'go.mod', 'Cargo.toml',
2377
+ 'composer.json', 'Gemfile']);
2378
+ const isManifest = (n) => MANIFESTS.has(n) || n.startsWith('build.gradle') || n.endsWith('.csproj');
2379
+
2380
+ // On a Bob project install the managed block holds the whole carrier, `#### Ownership` included —
2381
+ // hence the strip (`withoutBlocks`) and the exact `##` heading match. `\r?`: a CRLF file's `$`
2382
+ // sits after the `\r`.
2383
+ const SECTION_RE = /^## Ownership[ \t]*\r?$/m;
2384
+
2385
+ // ---- ownership shape twin: END
2298
2386
  const MANAGED_BLOCK_RE = /^<!-- BEGIN GENESEED -->[ \t]*\r?\n[\s\S]*?^<!-- END GENESEED -->[ \t]*\r?$/gm
2299
- const OWNERSHIP_SECTION_RE = /^## Ownership[ \t]*\r?$/m
2300
- const OWNERSHIP_TAIL = "Opt out per repo: `## Ownership` with `mode: off` in the root `AGENTS.md`; per " +
2301
- "install: rebuild with `--no-ownership-gate`. Offer the full documentation " +
2302
- "(`/document-project`) as yes / later. Stop and ask the developer now; re-issue the write only " +
2303
- "after they answer. This gate fires once per session and repo."
2304
- const OWNERSHIP_SKIP = "skip this session; or skip in this repo until they ask — only on that third answer, " +
2305
- "write the line `Setup: declined <YYYY-MM-DD>` (today) into `.geneseed/ownership.md` at the " +
2306
- "MAIN worktree's root (in a linked git worktree, the main checkout's, so it outlives this " +
2307
- "worktree), which is personal and never committed (if `.geneseed/.gitignore` is absent there, " +
2308
- "create it first, as the ownership skill's checkpoint rules say)"
2309
- const OWNERSHIP_REASON_NONE = "Geneseed (Ownership) — this application has no `AGENTS.md` with " +
2310
- "`## Ownership`. Before writing, propose three answers to the developer: set it up now " +
2311
- `(ownership skill); ${OWNERSHIP_SKIP}. ${OWNERSHIP_TAIL}`
2312
- const OWNERSHIP_REASON_NO_SECTION = "Geneseed (Ownership) — this application's `AGENTS.md` has no " +
2313
- "`## Ownership` section. Before writing, ask the developer: add the Ownership section now " +
2314
- `(ownership skill); ${OWNERSHIP_SKIP}? ${OWNERSHIP_TAIL}`
2387
+ // ---- ownership text twin: BEGIN — adapters/opencode/plugins/geneseed-guard.js carries everything
2388
+ // down to the END marker verbatim (node tests/twins.mjs --write keeps it).
2389
+
2390
+ const TAIL = 'Opt out per repo: `## Ownership` with `mode: off` in the root `AGENTS.md`; per '
2391
+ + 'install: rebuild with `--no-ownership-gate`. Offer the full documentation '
2392
+ + '(`/document-project`) as yes / later. Stop and ask the developer now; re-issue the write only '
2393
+ + 'after they answer. This gate fires once per session and repo.';
2394
+ // D5: three answers. Only the third writes anything — the durable, personal decline below.
2395
+ const SKIP = 'skip this session; or skip in this repo until they ask — only on that third answer, '
2396
+ + 'write the line `Setup: declined <YYYY-MM-DD>` (today) into `.geneseed/ownership.md` at the '
2397
+ + 'MAIN worktree\'s root (in a linked git worktree, the main checkout\'s, so it outlives this '
2398
+ + 'worktree), which is personal and never committed (if `.geneseed/.gitignore` is absent there, '
2399
+ + 'create it first, as the ownership skill\'s checkpoint rules say)';
2400
+ const REASON_NONE = 'Geneseed (Ownership) — this application has no `AGENTS.md` with '
2401
+ + '`## Ownership`. Before writing, propose three answers to the developer: set it up now '
2402
+ + `(ownership skill); ${SKIP}. ${TAIL}`;
2403
+ const REASON_NO_SECTION = 'Geneseed (Ownership) — this application\'s `AGENTS.md` has no '
2404
+ + '`## Ownership` section. Before writing, ask the developer: add the Ownership section now '
2405
+ + `(ownership skill); ${SKIP}? ${TAIL}`;
2406
+
2407
+ // ---- ownership text twin: END
2315
2408
  // The developer's durable, personal decline (`DECLINED_RE` in the hook twin; geneseed-context.js
2316
2409
  // carries it too): with no section, this line in `.geneseed/ownership.md` defers the gate.
2317
- const OWNERSHIP_DECLINED_RE = /^Setup:[ \t]*declined[ \t]+(\d{4}-\d{2}-\d{2})[ \t]*\r?$/m
2410
+ const DECLINED_RE = /^Setup:[ \t]*declined[ \t]+(\d{4}-\d{2}-\d{2})[ \t]*\r?$/m;
2318
2411
  // The reason to refuse this write, or null. `p` is absolute. Never throws.
2319
2412
  function ownershipBlock(p, sessionID) {
2320
2413
  try {
@@ -2332,7 +2425,7 @@ function ownershipBlock(p, sessionID) {
2332
2425
  let text = null
2333
2426
  try { text = readFileSync(path.join(root, "AGENTS.md"), "utf8") } catch { /* none: gate */ }
2334
2427
  const own = text === null ? "" : text.replace(MANAGED_BLOCK_RE, "")
2335
- if (OWNERSHIP_SECTION_RE.test(own)) return null
2428
+ if (SECTION_RE.test(own)) return null
2336
2429
  let personal = ""
2337
2430
  // In the MAIN worktree (the hook twin's `mainWorktreeOf(root) ?? root`): the shared `.git`'s
2338
2431
  // parent, else this root (a main worktree, a submodule, a bare common dir, a bad link).
@@ -2341,11 +2434,21 @@ function ownershipBlock(p, sessionID) {
2341
2434
  let home = root
2342
2435
  try { const c = gitCommonDirOf(root); if (path.basename(c) === ".git") home = path.dirname(c) } catch { /* this root */ }
2343
2436
  try { personal = readFileSync(path.join(home, ".geneseed", "ownership.md"), "utf8") } catch { /* none: gate */ }
2344
- if (OWNERSHIP_DECLINED_RE.test(personal.replace(/^\uFEFF/, ""))) return null
2345
- const key = `${sessionID}|${nocase(root)}`
2346
- if (OWNERSHIP_SEEN.has(key)) return null
2347
- OWNERSHIP_SEEN.add(key)
2348
- return own.trim() ? OWNERSHIP_REASON_NO_SECTION : OWNERSHIP_REASON_NONE
2437
+ if (DECLINED_RE.test(personal.replace(/^\uFEFF/, ""))) return null
2438
+ const key = ownershipKey(root)
2439
+ const memo = `${sessionID}|${key}`
2440
+ if (OWNERSHIP_SEEN.has(memo)) return null
2441
+ const dir = path.join(tmpdir(), `geneseed-ownership-${ownershipUser()}`)
2442
+ const marker = path.join(dir, safeStem(sessionID))
2443
+ let seen = ""
2444
+ try { seen = readFileSync(marker, "utf8") } catch { /* first gated write of the session */ }
2445
+ if (seen.split("\n").includes(key)) { OWNERSHIP_SEEN.add(memo); return null }
2446
+ // Recorded BEFORE refusing, as in the twin: a marker that cannot be written throws to the
2447
+ // catch below and defers, or every write of the session would be refused.
2448
+ mkdirSync(dir, { recursive: true })
2449
+ appendFileSync(marker, `${key}\n`)
2450
+ OWNERSHIP_SEEN.add(memo)
2451
+ return own.trim() ? REASON_NO_SECTION : REASON_NONE
2349
2452
  } catch { return null }
2350
2453
  }
2351
2454
 
@@ -2385,8 +2488,9 @@ function argPaths(v, key = "", out = [], depth = 0) {
2385
2488
  // from the repo (V2 loads every .js in plugins/ as a plugin). One line per skill or subagent
2386
2489
  // call, the day and the name only, under <cfg>/notebook/usage.jsonl. Silent and never throws:
2387
2490
  // a counter must not change, slow or fail a tool call. tests/unit/usage.test.mjs holds this
2388
- // copy and the hook's to one table.
2389
- const USAGE_NAME_RE = /^[A-Za-z0-9][\w.:@/-]{0,99}$/
2491
+ // copy and the hook's to one table. `usageOf` is by hand (no Bob shapes here); `NAME_RE` is the
2492
+ // hook's line, kept by `node tests/twins.mjs --write`.
2493
+ const NAME_RE = /^[A-Za-z0-9][\w.:@/-]{0,99}$/;
2390
2494
  function usageOf(tool, args) {
2391
2495
  const t = String(tool || "").toLowerCase()
2392
2496
  const a = args || {}
@@ -2396,7 +2500,7 @@ function usageOf(tool, args) {
2396
2500
  else if (t === "agent" || t === "task" || t === "subagent") { kind = "agent"; name = a.subagent_type ?? a.agent }
2397
2501
  if (!kind || typeof name !== "string") return null
2398
2502
  name = name.trim().replace(/^\/+/, "")
2399
- return USAGE_NAME_RE.test(name) ? { kind, name } : null
2503
+ return NAME_RE.test(name) ? { kind, name } : null
2400
2504
  }
2401
2505
  async function recordUse(tool, args) {
2402
2506
  try {
@@ -2411,19 +2515,45 @@ async function recordUse(tool, args) {
2411
2515
  } catch { /* a counter never fails a tool call */ }
2412
2516
  }
2413
2517
 
2518
+ // ---- a gate that fails -----------------------------------------------------------
2519
+ // An error's text, from anything a gate can throw: reading it must not throw in turn.
2520
+ const errorText = (err) => { try { return String(err?.message ?? err) } catch { return "an error that cannot be read" } }
2521
+ // Our own refusal, the one error that must leave the hook.
2522
+ const isDeny = (err) => errorText(err).startsWith("[geneseed-guard]")
2523
+ // How many unanswered marks `setupV2`'s `gateErrors` keeps before the oldest goes.
2524
+ const GATE_ERRORS_HELD = 256
2525
+ // Where the host cannot ask (V1, and a V2 with no permission domain) a gate error lets the call
2526
+ // run (ADR 0007), so the user is told: once per gate for the life of the process, because a
2527
+ // fault in a gate repeats on every call and a notice per call would bury the session. `tell` is
2528
+ // the instance's `say`: a V1 toast (nothing without a TUI client, and the log line stands
2529
+ // alone), a V2 synthetic message.
2530
+ const GATE_ERRORS_TOLD = new Set()
2531
+ async function tellGateError(tell, sid, name, what) {
2532
+ if (GATE_ERRORS_TOLD.has(name)) return
2533
+ GATE_ERRORS_TOLD.add(name)
2534
+ try {
2535
+ await tell(sid, `Geneseed gate error: the ${name} check failed with "${what}", so it did not judge a tool call, and the call ran. `
2536
+ + "The other checks still ran. Run geneseed doctor to find the fault.", "Geneseed gate error")
2537
+ } catch (err) { log(`gate error not shown: ${errorText(err)}`) }
2538
+ }
2539
+
2414
2540
  export const GeneseedGuard = async (ctx) => {
2415
2541
  if (ctx?.client) LOG_CLIENT = ctx.client
2416
2542
  // The session's working directory, the same resolution the context plugin uses.
2417
2543
  const root = () => ctx?.worktree || ctx?.directory || process.cwd()
2418
- // Whether a session has a parent (a subagent's child session). V2 hands in `sessionMeta`
2419
- // (`ctx.session.get`); V1 asks its client. Read only on the rare would-block path; a failed
2420
- // lookup reads as a top-level session.
2421
- const isChildSession = async (sid) => {
2544
+ // Whether a session has no user to ask: a subagent's child session (it has a parent), or a
2545
+ // headless one Geneseed started itself. A workflow's agents run in sessions titled
2546
+ // `geneseed-wf:…` with NO parent (adapters/opencode/workflows/_runtime.js), so the parent test
2547
+ // alone had the ownership gate refuse each one's first write with "ask the developer". The rule
2548
+ // is `isSkippedSession`'s in geneseed-context.js. V2 hands in `sessionMeta` (`ctx.session.get`);
2549
+ // V1 asks its client. Read only on the rare would-block path; a failed lookup reads as a
2550
+ // session with a user.
2551
+ const cannotAsk = async (sid) => {
2422
2552
  try {
2423
2553
  const info = ctx?.sessionMeta ? await ctx.sessionMeta(sid)
2424
2554
  : await ctx?.client?.session?.get?.({ path: { id: sid } })
2425
2555
  const meta = info?.data ?? info
2426
- return Boolean(meta?.parentID ?? meta?.parentId)
2556
+ return Boolean(meta?.parentID ?? meta?.parentId) || String(meta?.title ?? "").startsWith("geneseed-")
2427
2557
  } catch { return false }
2428
2558
  }
2429
2559
  // Whether the host itself will ask the user about this write once this hook lets it run. V2
@@ -2459,7 +2589,7 @@ export const GeneseedGuard = async (ctx) => {
2459
2589
  const unwatched = new Set()
2460
2590
  const watch = async (sid) => {
2461
2591
  if (OFF || !sid || watched.has(sid) || unwatched.has(sid)) return
2462
- if (await sovereignBypass(root()) || await isChildSession(sid)) { unwatched.add(sid); return }
2592
+ if (await sovereignBypass(root()) || await cannotAsk(sid)) { unwatched.add(sid); return }
2463
2593
  watched.set(sid, scanAllStores(root()))
2464
2594
  }
2465
2595
  const compare = async (sid) => {
@@ -2520,144 +2650,205 @@ export const GeneseedGuard = async (ctx) => {
2520
2650
  if (OFF) return
2521
2651
  // A session that predates this plugin never sent `session.created`. Once per session.
2522
2652
  try { await watch(input?.sessionID) } catch { /* the report never decides a tool call */ }
2523
- const tool = (input?.tool || input?.name || "").toLowerCase()
2653
+ const tool = String(input?.tool || input?.name || "").toLowerCase()
2524
2654
  const args = output?.args || input?.args || {}
2525
2655
  // `rule` is the ledger key, spelled as js/hosts/hooks.mjs spells it (`law-1`,
2526
2656
  // `law-4`, `process-1`) plus `wiki`, so status counts one vocabulary across hosts.
2527
2657
  // The model reads this text. It never names the GENESEED_GUARD switch: a weak model read
2528
2658
  // "set GENESEED_GUARD=off to allow" as leave to route the write through a shell (4.27.1).
2529
- // 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
2530
- // but a deny. No count: no `editPairs` here, and the line reads whole without one.
2659
+ // A refusal's words, through `gateSafe` (the ownership reason is the agent's, so it keeps its
2660
+ // own): `runGate` below lets a call past any error but a deny, so the words must not throw.
2661
+ // No count: no `editPairs` here, and the line reads whole without one.
2531
2662
  const refused = (id, facts) => gateSafe(id, "refused", facts)
2532
2663
  // V1's explanations, held to the end of this hook: a later gate may still refuse the call, and a
2533
2664
  // note about a dialog that never comes is a false one. V2 posts from `evaluate` instead.
2534
2665
  const notes = []
2666
+ // GENESEED_GUARD=warn: the first would-be block is logged and ends the inspection.
2667
+ let warned = false
2535
2668
  const deny = async (why, rule) => {
2536
- if (WARN_ONLY) { log(`WARN (would block): ${why}`); return false }
2669
+ if (WARN_ONLY) { log(`WARN (would block): ${why}`); warned = true; return false }
2537
2670
  log(`BLOCKED: ${why}`)
2538
2671
  await ledger(rule)
2539
2672
  throw new Error(`[geneseed-guard] blocked: ${why}`)
2540
2673
  }
2541
- try {
2542
- // `apply_patch`'s own tool resolves every marker path against `instance.directory`
2543
- // (`apply_patch.ts:72` in the verdict's evidence), NOT the worktree root `root()`
2544
- // uses for the sovereign-repo bypass above — a worktree session started in a
2545
- // subdirectory of its git root must see the same (narrower) root the write
2546
- // actually lands under, or a protected-check/wiki/secret hit one directory up
2547
- // would be missed.
2548
- const cwd = ctx?.directory || process.cwd()
2549
- if (hasAny(tool, WRITE_TOOLS)) {
2550
- // `apply_patch` (gpt-5*) can carry several marker paths in one call — every
2551
- // one of them is a write target, so every one runs every gate; the first hit
2552
- // blocks the whole call (see `pickPath` for why this is not a single path).
2553
- const paths = pickPath(args, cwd)
2554
- for (const raw of paths) {
2555
- if (namesStream(raw)) { await deny(refused("stream", { name: repoRel(path.resolve(cwd, raw)) }), "rigor-5"); return }
2556
- // Once, here: under `opencode serve` this process's cwd is not the session's directory, and
2557
- // every gate below resolves a relative path against it.
2558
- const p = landsOn(raw, cwd)[0].replace(/\\/g, "/")
2559
- if (!SECRETS_GATE_OFF && SECRET_RE.some((re) => re.test(p))) { await deny(refused("secret-file", { name: repoRel(p) }), "law-1"); return }
2560
- if (SECRET_WARN_RE.some((re) => re.test(p))) log(`WARN: writing ${p} — keep secrets out of tracked files (Sealed Secrets)`)
2561
- const sensor = protectedCheck(p)
2562
- if (sensor) { await deny(refused("check", { name: sensor }), "rigor-5"); return }
2563
- if (gateConfig(p)) { await deny(refused("config", { name: repoRel(p) }), "rigor-5"); return }
2564
- if (carrierBlockChange(path.resolve(cwd, raw), tool, args)) { await deny(refused("config", { name: repoRel(p) }), "rigor-5"); return }
2565
- // V1 after an "always": the `permission.edit` ask on these files is gone too.
2566
- if (everyEditApproved && !ctx?.hostAsks && nativeAskFile(p)) { await deny(refused("config", { name: repoRel(p) }), "rigor-5"); return }
2567
- const store = ruleTarget(raw, cwd)
2568
- const prompted = (store || nativeAskFile(p)) && await hostPrompts(tool, raw, cwd)
2569
- if (prompted && !ctx?.hostAsks) notes.push(gateSafe(store ? "store" : "config", "ask", { name: store || repoRel(p) }))
2570
- if (store && !prompted) {
2571
- await deny(`${refused("store", { name: store })}\n${NATIVE_EDIT_TOOLS.has(tool) ? PERSIST_NO_PROMPT : PERSIST_EDIT_TOOL}`, "process-1")
2572
- return
2674
+ // Each gate runs alone. Our own deny propagates. Any other error is that gate's alone: it is
2675
+ // logged, the call is ledgered once as `gate-error`, and the NEXT gate still runs, so a fault
2676
+ // in an early gate no longer switches off the secret scan, the loss gate and the wiki gate
2677
+ // behind it. `failure` is the first gate that failed on this call; what it would have said
2678
+ // is lost, and `unjudged` below answers that once every gate has run.
2679
+ let failure = null
2680
+ const runGate = async (name, gate) => {
2681
+ try { await gate() } catch (err) {
2682
+ if (isDeny(err)) throw err
2683
+ const what = errorText(err).slice(0, 200)
2684
+ log(`gate error in ${name} (the other gates still run): ${what}`)
2685
+ if (failure) return
2686
+ failure = { name, what }
2687
+ await ledger("gate-error")
2688
+ }
2689
+ }
2690
+ // A call no gate refused and one gate could not judge: each host answers to its own ceiling
2691
+ // (ADR 0007). A V2 that can ask marks the call by its id, and `evaluate` raises it to a
2692
+ // prompt. V1 and a V2 with no prompt let it run, and tell the user once per gate.
2693
+ const unjudged = async () => {
2694
+ if (!failure) return
2695
+ if (!ctx?.gateErrors || !input?.callID) { await tellGateError(say, input?.sessionID, failure.name, failure.what); return }
2696
+ ctx.gateErrors.set(input.callID, `${failure.name}: ${failure.what}`)
2697
+ // A call that asserts nothing is never asked about, so its mark would stay for good.
2698
+ if (ctx.gateErrors.size > GATE_ERRORS_HELD) ctx.gateErrors.delete(ctx.gateErrors.keys().next().value)
2699
+ }
2700
+ // `apply_patch`'s own tool resolves every marker path against `instance.directory`
2701
+ // (`apply_patch.ts:72` in the verdict's evidence), NOT the worktree root `root()`
2702
+ // uses for the sovereign-repo bypass above — a worktree session started in a
2703
+ // subdirectory of its git root must see the same (narrower) root the write
2704
+ // actually lands under, or a protected-check/wiki/secret hit one directory up
2705
+ // would be missed.
2706
+ const cwd = ctx?.directory || process.cwd()
2707
+ // The gates of one call, in order. Each reads the arguments for itself: a gate that shared
2708
+ // another's reading would fail with it. A gate's `return` after `deny` is the warn mode's.
2709
+ // `depth` is 0 for the call the host handed in, and counts up through `nestedCalls`. A nested
2710
+ // call has no prompt of its own that this hook can count on (the mark for `evaluate` is the
2711
+ // OUTER call's id, and whether the host asks about a nested edit is unverified), so a nested
2712
+ // rule-store write is refused where a direct one would be handed to the host's prompt.
2713
+ const gatesFor = (tool, args, depth) => {
2714
+ const nested = depth > 0
2715
+ const writes = hasAny(tool, WRITE_TOOLS)
2716
+ return [
2717
+ ["paths", async () => {
2718
+ if (!writes) return
2719
+ // `apply_patch` (gpt-5*) can carry several marker paths in one call — every
2720
+ // one of them is a write target, so every one runs every gate; the first hit
2721
+ // blocks the whole call (see `pickPath` for why this is not a single path).
2722
+ for (const raw of pickPath(args, cwd)) {
2723
+ if (namesStream(raw)) { await deny(refused("stream", { name: repoRel(path.resolve(cwd, raw)) }), "rigor-5"); return }
2724
+ // Once, here: under `opencode serve` this process's cwd is not the session's directory, and
2725
+ // every gate below resolves a relative path against it.
2726
+ const p = landsOn(raw, cwd)[0].replace(/\\/g, "/")
2727
+ if (!SECRETS_GATE_OFF && SECRET_RE.some((re) => re.test(p))) { await deny(refused("secret-file", { name: repoRel(p) }), "law-1"); return }
2728
+ if (SECRET_WARN_RE.some((re) => re.test(p))) log(`WARN: writing ${p} — keep secrets out of tracked files (Sealed Secrets)`)
2729
+ const sensor = protectedCheck(p)
2730
+ if (sensor) { await deny(refused("check", { name: sensor }), "rigor-5"); return }
2731
+ if (gateConfig(p)) { await deny(refused("config", { name: repoRel(p) }), "rigor-5"); return }
2732
+ if (carrierBlockChange(path.resolve(cwd, raw), tool, args)) { await deny(refused("config", { name: repoRel(p) }), "rigor-5"); return }
2733
+ // V1 after an "always": the `permission.edit` ask on these files is gone too.
2734
+ if (everyEditApproved && !ctx?.hostAsks && nativeAskFile(p)) { await deny(refused("config", { name: repoRel(p) }), "rigor-5"); return }
2735
+ const store = ruleTarget(raw, cwd)
2736
+ const prompted = !nested && (store || nativeAskFile(p)) && await hostPrompts(tool, raw, cwd)
2737
+ if (prompted && !ctx?.hostAsks) notes.push(gateSafe(store ? "store" : "config", "ask", { name: store || repoRel(p) }))
2738
+ if (store && !prompted) {
2739
+ await deny(`${refused("store", { name: store })}\n${NATIVE_EDIT_TOOLS.has(tool) && !nested ? PERSIST_NO_PROMPT : PERSIST_EDIT_TOOL}`, "process-1")
2740
+ return
2741
+ }
2573
2742
  }
2574
- }
2743
+ }],
2575
2744
  // Content scan (Sealed Secrets, the twin of js/hosts/hooks.mjs's ruleDecide): per
2576
2745
  // FILE, not pooled — a patch touching `.env` AND an ordinary file must still catch a
2577
2746
  // secret in the ordinary file; only the hunk whose OWN path is `.env`-shaped is
2578
2747
  // exempt, same as the path WARN tier above.
2579
- for (const { path: cp, content } of SECRETS_GATE_OFF ? [] : pickAddedContentByPath(args, cwd)) {
2580
- if (SECRET_WARN_RE.some((re) => re.test(cp))) continue
2581
- if (SECRET_CONTENT_RE.test(content)) {
2582
- await deny(refused("secret", { name: repoRel(path.resolve(cwd, cp)) }), "law-1")
2583
- return
2748
+ ["content", async () => {
2749
+ if (!writes || SECRETS_GATE_OFF) return
2750
+ for (const { path: cp, content } of pickAddedContentByPath(args, cwd)) {
2751
+ if (SECRET_WARN_RE.some((re) => re.test(cp))) continue
2752
+ if (SECRET_CONTENT_RE.test(content)) {
2753
+ await deny(refused("secret", { name: repoRel(path.resolve(cwd, cp)) }), "law-1")
2754
+ return
2755
+ }
2584
2756
  }
2585
- }
2586
- // The ownership first-write gate, last, as in js/hosts/hooks.mjs's ruleDecide. A child
2587
- // session is a subagent (ruling D29): it cannot ask the user, so it never spends a block.
2588
- if (!OWNERSHIP_GATE_OFF) {
2589
- for (const p of paths) {
2757
+ }],
2758
+ // The ownership first-write gate, after the write gates, as in js/hosts/hooks.mjs's
2759
+ // ruleDecide, and over the twin's own tool class (`WRITE_NAME_RE`): a move, a copy
2760
+ // or a delete is a first write too. A session that cannot ask the user (`cannotAsk`: a
2761
+ // subagent, ruling D29, or a headless workflow agent) is never refused.
2762
+ ["ownership", async () => {
2763
+ if (OWNERSHIP_GATE_OFF || !(writes || WRITE_NAME_RE.test(tool))) return
2764
+ for (const p of pickPath(args, cwd)) {
2590
2765
  const why = ownershipBlock(path.resolve(cwd, p), input?.sessionID)
2591
- if (why && !(await isChildSession(input.sessionID))) { await deny(why, "ownership"); return }
2766
+ if (why && !(await cannotAsk(input.sessionID))) { await deny(why, "ownership"); return }
2592
2767
  }
2593
- }
2594
- }
2595
- // Any tool the host's prompt does not cover, whatever it calls its arguments. `pickCommand`,
2596
- // because SHELL_TOOLS is a substring class: `mcp_prune_write` holds "run".
2597
- if (!RULE_STORE_OFF && !NATIVE_EDIT_TOOLS.has(tool) && !readsOnly(tool) && !(hasAny(tool, SHELL_TOOLS) && pickCommand(args))) {
2598
- const named = argPaths(args)
2599
- if (named.overflow) { await deny(refused("deep-args", { name: tool }), "process-1"); return }
2600
- for (const v of named) {
2601
- const store = ruleTarget(v, cwd)
2602
- if (store) {
2603
- await deny(`${refused("store", { name: store })}\n${PERSIST_EDIT_TOOL}`, "process-1")
2604
- return
2768
+ }],
2769
+ // Any tool the host's prompt does not cover, whatever it calls its arguments. `pickCommand`,
2770
+ // because SHELL_TOOLS is a substring class: `mcp_prune_write` holds "run".
2771
+ ["store-args", async () => {
2772
+ if (RULE_STORE_OFF || NATIVE_EDIT_TOOLS.has(tool) || readsOnly(tool) || (hasAny(tool, SHELL_TOOLS) && pickCommand(args))) return
2773
+ const named = argPaths(args)
2774
+ if (named.overflow) { await deny(refused("deep-args", { name: tool }), "process-1"); return }
2775
+ for (const v of named) {
2776
+ const store = ruleTarget(v, cwd)
2777
+ if (store) {
2778
+ await deny(`${refused("store", { name: store })}\n${PERSIST_EDIT_TOOL}`, "process-1")
2779
+ return
2780
+ }
2605
2781
  }
2606
- }
2607
- }
2608
- if (hasAny(tool, WIKI_MUTATE_TOOLS)) {
2609
- for (const p of pickPath(args, cwd)) {
2610
- const abs = landsOn(p, cwd)[0].replace(/\\/g, "/").toLowerCase()
2611
- const hit = (await protectedPrefixes()).find(
2612
- (x) => abs.startsWith(x.prefix) || abs === x.prefix.slice(0, -1))
2613
- if (hit) { await deny(refused("wiki", { name: hit.label }), "wiki"); return }
2614
- }
2615
- }
2616
- // NOT else-if: a compound tool name (e.g. exec_and_save) can match both
2617
- // classes, and the shell check must still run after the write check.
2618
- if (hasAny(tool, SHELL_TOOLS)) {
2619
- // OpenCode's bash tool may run in `workdir`, resolved against the session directory.
2620
- const wd = typeof args.workdir === "string" && args.workdir ? path.resolve(cwd, args.workdir) : cwd
2621
- // One reading for every check below: continuations joined, escaped quotes inert (`shellReading`).
2622
- const picked = pickCommand(args)
2623
- const c = typeof picked === "string" && picked ? shellReading(picked, /powershell|pwsh/i.test(tool) ? "powershell" : null) : picked
2624
- const cut = (t) => scanSegments(t).map((seg) => seg.match(SCAN_TOKEN_RE) || [])
2625
- if (c && (SHELL_BLOCK_RE.some((re) => re.test(c)) || catastrophic(c, cut))) { await deny(refused("catastrophic", { name: c }), "law-4"); return }
2626
- const scan = c && !ROOT_SCAN_OFF && rootScan(c)
2627
- if (scan) {
2628
- await deny(refused("root-scan", { name: scan }), "ops-2")
2629
- return
2630
- }
2631
- if (c && !DELETION_GATE_OFF && LOSS_CANDIDATE_RE.test(c)) {
2632
- const loss = lossReason(cut(c), wd, { always: false, split: cut })
2633
- if (loss) { const facts = gateLoss(loss); await deny(refused(facts.id, facts), "law-4"); return }
2634
- }
2635
- // External Gate over a shell write: the same paths as a write tool, no content scan. A
2636
- // throw fails open through the catch below, as the twin's `shellWriteReason` does.
2637
- for (const p of c ? shellWriteTargets(c, wd, /powershell|pwsh/i.test(tool)) : []) {
2638
- const sensor = protectedCheck(p)
2639
- if (sensor) { await deny(refused("check", { name: sensor, shell: true }), "rigor-5"); return }
2640
- if (gateConfig(p) || nativeAskFile(p)) { await deny(refused("config", { name: repoRel(p), shell: true }), "rigor-5"); return }
2641
- // A parsed form that lands in a store. V2 can ask: `evaluate` runs for the shell tool's own
2642
- // `permission.assert`, so the call is marked by its id and the host prompts. V1 cannot.
2643
- const store = ruleTarget(p, wd)
2644
- if (store && ctx?.shellAsks && input?.callID && !noProgramWord(c)) { ctx.shellAsks.set(input.callID, store); continue }
2645
- if (store) {
2646
- await deny(`${refused("store", { name: store, shell: true })}\n${PERSIST_EDIT_TOOL}`, "process-1")
2782
+ }],
2783
+ ["wiki", async () => {
2784
+ if (!hasAny(tool, WIKI_MUTATE_TOOLS)) return
2785
+ for (const p of pickPath(args, cwd)) {
2786
+ const abs = landsOn(p, cwd)[0].replace(/\\/g, "/").toLowerCase()
2787
+ const hit = (await protectedPrefixes()).find(
2788
+ (x) => abs.startsWith(x.prefix) || abs === x.prefix.slice(0, -1))
2789
+ if (hit) { await deny(refused("wiki", { name: hit.label }), "wiki"); return }
2790
+ }
2791
+ }],
2792
+ // Its own gate, never an else of the write gates: a compound tool name (e.g.
2793
+ // exec_and_save) can match both classes, and the shell check must still run.
2794
+ ["shell", async () => {
2795
+ if (!hasAny(tool, SHELL_TOOLS)) return
2796
+ // OpenCode's bash tool may run in `workdir`, resolved against the session directory.
2797
+ const wd = typeof args.workdir === "string" && args.workdir ? path.resolve(cwd, args.workdir) : cwd
2798
+ // One reading for every check below: continuations joined, escaped quotes inert (`shellReading`).
2799
+ const picked = pickCommand(args)
2800
+ const c = typeof picked === "string" && picked ? shellReading(picked, /powershell|pwsh/i.test(tool) ? "powershell" : null) : picked
2801
+ const cut = (t) => scanSegments(t).map((seg) => seg.match(SCAN_TOKEN_RE) || [])
2802
+ if (c && (SHELL_BLOCK_RE.some((re) => re.test(c)) || catastrophic(c, cut))) { await deny(refused("catastrophic", { name: c }), "law-4"); return }
2803
+ const scan = c && !ROOT_SCAN_OFF && rootScan(c)
2804
+ if (scan) {
2805
+ await deny(refused("root-scan", { name: scan }), "ops-2")
2647
2806
  return
2648
2807
  }
2649
- }
2650
- }
2651
- for (const note of notes) {
2652
- // No count here, as in a refusal. 120 s, because the dialog stays until it is answered.
2653
- try {
2654
- await ctx?.client?.tui?.showToast?.({ body: { title: "Geneseed", message: gateNote(note), variant: "warning", duration: 120000 }, query: { directory: cwd } })
2655
- } catch (err) { log(`note not shown: ${err?.message ?? err}`) }
2808
+ if (c && !DELETION_GATE_OFF && LOSS_CANDIDATE_RE.test(c)) {
2809
+ const loss = lossReason(cut(c), wd, { always: false, split: cut })
2810
+ if (loss) { const facts = gateLoss(loss); await deny(refused(facts.id, facts), "law-4"); return }
2811
+ }
2812
+ // External Gate over a shell write: the same paths as a write tool, no content scan. A
2813
+ // throw here is this gate's error (`runGate`), where the twin's `shellWriteReason` fails open.
2814
+ for (const p of c ? shellWriteTargets(c, wd, /powershell|pwsh/i.test(tool)) : []) {
2815
+ const sensor = protectedCheck(p)
2816
+ if (sensor) { await deny(refused("check", { name: sensor, shell: true }), "rigor-5"); return }
2817
+ if (gateConfig(p) || nativeAskFile(p)) { await deny(refused("config", { name: repoRel(p), shell: true }), "rigor-5"); return }
2818
+ // A parsed form that lands in a store. V2 can ask: `evaluate` runs for the shell tool's own
2819
+ // `permission.assert`, so the call is marked by its id and the host prompts. V1 cannot.
2820
+ const store = ruleTarget(p, wd)
2821
+ if (store && !nested && ctx?.shellAsks && input?.callID && !noProgramWord(c)) { ctx.shellAsks.set(input.callID, store); continue }
2822
+ if (store) {
2823
+ await deny(`${refused("store", { name: store, shell: true })}\n${PERSIST_EDIT_TOOL}`, "process-1")
2824
+ return
2825
+ }
2826
+ }
2827
+ }],
2828
+ // Last, so the call's own gates have spoken: every call it carries, as a call of its own.
2829
+ ["nested", async () => {
2830
+ for (const call of nestedCalls(args)) {
2831
+ if (depth >= NESTED_DEPTH) { await deny(refused("deep-args", { name: tool }), "process-1"); return }
2832
+ await judge(call.tool, call.args, depth + 1)
2833
+ if (warned) return
2834
+ }
2835
+ }],
2836
+ ]
2837
+ }
2838
+ const judge = async (tool, args, depth) => {
2839
+ for (const [name, gate] of gatesFor(tool, args, depth)) {
2840
+ await runGate(name, gate)
2841
+ if (warned) return
2656
2842
  }
2657
- } catch (err) {
2658
- // Our own deny must propagate; any inspection error must never break a tool call.
2659
- if (err && String(err.message || "").startsWith("[geneseed-guard]")) throw err
2660
- log(`inspect error (ignored): ${err?.message ?? err}`)
2843
+ }
2844
+ await judge(tool, args, 0)
2845
+ await unjudged()
2846
+ if (warned) return
2847
+ for (const note of notes) {
2848
+ // No count here, as in a refusal. 120 s, because the dialog stays until it is answered.
2849
+ try {
2850
+ await ctx?.client?.tui?.showToast?.({ body: { title: "Geneseed", message: gateNote(note), variant: "warning", duration: 120000 }, query: { directory: cwd } })
2851
+ } catch (err) { log(`note not shown: ${err?.message ?? err}`) }
2661
2852
  }
2662
2853
  },
2663
2854
  }
@@ -2685,10 +2876,16 @@ export const GeneseedGuard = async (ctx) => {
2685
2876
  // and an unattended session turns the ask into a deny. A V2 without the domain has no `hostAsks`,
2686
2877
  // so the guard refuses those writes.
2687
2878
  //
2879
+ // The same hook asks about a call a gate FAILED on (`runGate`, ADR 0007 as amended 2026-11): the
2880
+ // tool hook marks the call's id in `gateErrors`, and the first `evaluate` whose `source.id` is that
2881
+ // call becomes an ask with the `gate-error` text. Unverified against a live host: `source.id` is
2882
+ // seen on the shell tool's assert (2.2.5), and is assumed, not observed, on `edit` and on an MCP
2883
+ // tool's. A call that asserts nothing, or whose assert names no call, runs unasked, as on V1.
2884
+ //
2688
2885
  // The dialog shows no plugin text, so each ask posts a note first. The TUI renders a synthetic item's
2689
2886
  // `description` and the model gets its `text`, so the block goes in the first and the second must read
2690
2887
  // true whether the user allows or denies (spec 2026-11-07-gate-prompts-5.0.3, S0 result).
2691
- async function askOnRuleStore(ctx, shellAsks) {
2888
+ async function askOnRuleStore(ctx, shellAsks, gateErrors) {
2692
2889
  const dir = ctx?.location?.directory || process.cwd()
2693
2890
  const note = async (event) => {
2694
2891
  try {
@@ -2700,6 +2897,22 @@ async function askOnRuleStore(ctx, shellAsks) {
2700
2897
  await ctx.permission.hook("evaluate", async (event) => {
2701
2898
  try {
2702
2899
  if (OFF || event.effect === "deny") return
2900
+ // A call one of the tool hook's gates could not judge (`runGate`), by its id, whatever the
2901
+ // action: the user decides in the gate's place. The first assert of the call carries it.
2902
+ const failed = gateErrors.get(event.source?.id)
2903
+ if (gateErrors.delete(event.source?.id)) {
2904
+ if (WARN_ONLY) log(`WARN (would ask): a gate failed (${failed})`)
2905
+ else {
2906
+ // A store write the same call was marked for is said first: it is what the call does.
2907
+ const shellStore = shellAsks.get(event.source?.id)
2908
+ shellAsks.delete(event.source?.id)
2909
+ event.effect = "ask"
2910
+ event.message = [...(shellStore ? [gateSafe("store", "ask", { name: shellStore, shell: true })] : []),
2911
+ gateSafe("gate-error", "ask", { name: failed })].join("\n")
2912
+ await note(event)
2913
+ return
2914
+ }
2915
+ }
2703
2916
  if (event.action === "shell") {
2704
2917
  // The shell tool's assert: action `shell`, one resource per parsed command, `source.id` the
2705
2918
  // call the tool hook marked. A command the host's parser finds no command in asserts nothing.
@@ -2731,14 +2944,15 @@ async function askOnRuleStore(ctx, shellAsks) {
2731
2944
  }
2732
2945
 
2733
2946
  async function setupV2(ctx) {
2734
- // Call id to the store it writes, for the prompt's text.
2947
+ // Call id to the store it writes, for the prompt's text; call id to the gate that failed on it.
2735
2948
  const shellAsks = new Map()
2736
- const hostAsks = await askOnRuleStore(ctx, shellAsks)
2949
+ const gateErrors = new Map()
2950
+ const hostAsks = await askOnRuleStore(ctx, shellAsks, gateErrors)
2737
2951
  const hooks = await GeneseedGuard({
2738
2952
  worktree: ctx?.location?.project?.directory, directory: ctx?.location?.directory,
2739
2953
  sessionMeta: (sessionID) => ctx.session.get({ sessionID }),
2740
- hostAsks, shellAsks: hostAsks ? shellAsks : null,
2741
- say: (sessionID, text) => ctx.session.synthetic({ sessionID, text, description: "Geneseed change report", resume: false }),
2954
+ hostAsks, shellAsks: hostAsks ? shellAsks : null, gateErrors: hostAsks ? gateErrors : null,
2955
+ say: (sessionID, text, description = "Geneseed change report") => ctx.session.synthetic({ sessionID, text, description, resume: false }),
2742
2956
  })
2743
2957
  const report = (type, properties) => hooks.event({ event: { type, properties } })
2744
2958
  // V2's turn edges, as geneseed-notify reads them. `say` above is the only way out to the user.
@@ -2762,11 +2976,14 @@ async function setupV2(ctx) {
2762
2976
  // `sessionID` rides on every V2 execute.before event (@opencode/plugin 2.1.4 `ToolHooks`).
2763
2977
  await hooks["tool.execute.before"]({ tool: event.tool, sessionID: event.sessionID, callID: event.id }, { args: event.input })
2764
2978
  } catch (err) {
2765
- const why = String(err?.message || "")
2766
- if (!why.startsWith("[geneseed-guard]")) return
2979
+ if (!isDeny(err)) return
2767
2980
  // Core prints `No tool named "<this>"`, so the name must say first that nothing is missing.
2768
- event.tool = `BLOCKED, not a missing tool: ${why}`
2769
- event.input = {}
2981
+ // In their own try: an event that cannot be written (frozen, a setter that throws) must not
2982
+ // fail the step. The refusal is then only logged, and the call runs.
2983
+ try {
2984
+ event.tool = `BLOCKED, not a missing tool: ${errorText(err)}`
2985
+ event.input = {}
2986
+ } catch (failed) { log(`refusal not applied, the call runs: ${errorText(failed)}`) }
2770
2987
  }
2771
2988
  })
2772
2989
  return () => controller.abort()