geneseed 5.3.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 (96) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/README.md +2 -2
  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 +169 -62
  10. package/adapters/opencode/plugins/geneseed-guard.js +414 -202
  11. package/adapters/opencode/plugins/geneseed-workflow.js +3 -2
  12. package/adapters/opencode/workflows/_runtime.js +3 -2
  13. package/bin/geneseed-hook.mjs +57 -9
  14. package/docs/concepts/enforcement-table.md +1 -1
  15. package/docs/concepts/exclusions.md +2 -2
  16. package/docs/concepts/footprint.md +10 -0
  17. package/docs/concepts/hook-gates.md +3 -3
  18. package/docs/concepts/host-matrix.md +22 -4
  19. package/docs/design-history.md +8 -0
  20. package/docs/extending.md +49 -7
  21. package/docs/guides/install-bob.md +2 -2
  22. package/docs/guides/install-openclaude.md +1 -1
  23. package/docs/guides/verify.md +12 -0
  24. package/docs/reference/environment.md +1 -0
  25. package/docs/reference/troubleshoot-doctor.md +1 -1
  26. package/docs/token-footprint.md +66 -2
  27. package/docs/understand/design-choices-hosts.md +1 -1
  28. package/docs/understand/design-choices-shape.md +1 -0
  29. package/docs/understand/enforced-vs-asked.md +1 -1
  30. package/docs/understand/machine-bob.md +1 -1
  31. package/docs/web-ui.md +5 -0
  32. package/harness.config.json +1 -1
  33. package/js/README.md +3 -2
  34. package/js/build/args.mjs +1 -1
  35. package/js/build/driver.mjs +1 -1
  36. package/js/build/emit-claude.mjs +1 -1
  37. package/js/build/generate.mjs +5 -14
  38. package/js/hosts/done-checks.mjs +6 -0
  39. package/js/hosts/geneseed-dir.mjs +3 -2
  40. package/js/hosts/gitref.mjs +5 -3
  41. package/js/hosts/hook-tap.mjs +104 -0
  42. package/js/hosts/hooks-context.mjs +4 -2
  43. package/js/hosts/hooks-learn.mjs +47 -16
  44. package/js/hosts/hooks.mjs +19 -13
  45. package/js/hosts/hosts.mjs +80 -12
  46. package/js/hosts/installs.mjs +7 -0
  47. package/js/hosts/native.mjs +14 -5
  48. package/js/hosts/owned.mjs +7 -6
  49. package/js/hosts/ownership-gate.mjs +14 -1
  50. package/js/hosts/settings.mjs +245 -103
  51. package/js/hosts/shim.mjs +4 -4
  52. package/js/hosts/usage.mjs +9 -3
  53. package/js/inspect/checks-probe.mjs +66 -5
  54. package/js/inspect/checks-repo.mjs +196 -2
  55. package/js/inspect/cost.mjs +34 -2
  56. package/js/inspect/doctor.mjs +6 -1
  57. package/js/lib/machine-dir.mjs +1 -1
  58. package/js/lib/node-floor.mjs +46 -6
  59. package/js/maintain/uninstall.mjs +42 -16
  60. package/js/web/actions.mjs +1 -9
  61. package/package.json +1 -1
  62. package/web/dist/assets/Activity-WQ3ykgxU.js +1 -0
  63. package/web/dist/assets/{ActivityDetail-BSzevynX.js → ActivityDetail-7rt04SkS.js} +1 -1
  64. package/web/dist/assets/{Bonsai-Bfpb6W-1.js → Bonsai-BBl4XXqs.js} +1 -1
  65. package/web/dist/assets/{CopyButton-ByIntFtB.js → CopyButton-Beven8yn.js} +1 -1
  66. package/web/dist/assets/Dashboard-BgLArtgu.js +2 -0
  67. package/web/dist/assets/{Docs-DvlMJhpu.js → Docs-B5aHp86J.js} +3 -3
  68. package/web/dist/assets/Factories-BjqzXAw8.js +1 -0
  69. package/web/dist/assets/GreenhouseView-Bce212qd.js +1 -0
  70. package/web/dist/assets/{Installs-BlGmVrFK.js → Installs-B1OsrHXF.js} +3 -3
  71. package/web/dist/assets/JournalView-CV4omyww.js +1 -0
  72. package/web/dist/assets/{Kits-DRwpxC-J.js → Kits-CW1e7xNa.js} +1 -1
  73. package/web/dist/assets/{Laws-CZkiNOWQ.js → Laws-1Ckf1lbs.js} +2 -2
  74. package/web/dist/assets/{LibRows-DEHjIoD-.js → LibRows-Dag1s0ZX.js} +1 -1
  75. package/web/dist/assets/Library-B3FuFLel.js +3 -0
  76. package/web/dist/assets/Loops-CwqgnLNw.js +2 -0
  77. package/web/dist/assets/Markdown-CxkA7940.js +71 -0
  78. package/web/dist/assets/OperatorHudView-JmYY1pBR.js +1 -0
  79. package/web/dist/assets/{Personal-Bp9nV4GR.js → Personal-DKLgLa7Z.js} +2 -2
  80. package/web/dist/assets/Settings-BwErnh-R.js +1 -0
  81. package/web/dist/assets/{Tabs-CWeQTADL.js → Tabs-8zsyEPSK.js} +1 -1
  82. package/web/dist/assets/{index-CsAZq0BQ.css → index-CRWqKxfY.css} +1 -1
  83. package/web/dist/assets/index-Ce6qF2nG.js +6 -0
  84. package/web/dist/index.html +2 -2
  85. package/adapters/claude-code/settings.json +0 -52
  86. package/web/dist/assets/Activity-CqJiquEq.js +0 -1
  87. package/web/dist/assets/Dashboard-DBOEi9lQ.js +0 -2
  88. package/web/dist/assets/Factories-Bpvv7L2H.js +0 -1
  89. package/web/dist/assets/GreenhouseView-GpBsYn50.js +0 -1
  90. package/web/dist/assets/JournalView-iLuLrOxE.js +0 -1
  91. package/web/dist/assets/Library-B4K-1iNF.js +0 -3
  92. package/web/dist/assets/Loops-BWSzaW8E.js +0 -2
  93. package/web/dist/assets/Markdown-0ORz7tAc.js +0 -69
  94. package/web/dist/assets/OperatorHudView-BAXwCEvY.js +0 -1
  95. package/web/dist/assets/Settings-CWWuaIp-.js +0 -1
  96. 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
@@ -1436,13 +1453,19 @@ function plainPaths(args) {
1436
1453
  // as the segment separator) match `C:\Users\me\.ssh\id_rsa` the same as a POSIX path.
1437
1454
  return PATH_KEYS.map((k) => args?.[k]).filter((v) => typeof v === "string" && v).map((v) => v.replace(/\\/g, "/"))
1438
1455
  }
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.
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.
1442
1465
  function pickPath(args, cwd) {
1443
1466
  const marked = args && typeof args.patchText === "string" ? parsePatchPaths(args.patchText)
1444
1467
  .map((p) => path.resolve(cwd || process.cwd(), p).replace(/\\/g, "/")) : []
1445
- return [...new Set([...marked, ...plainPaths(args)])]
1468
+ return [...new Set([...marked, ...plainPaths(args), ...editsOf(args).flatMap(plainPaths)])]
1446
1469
  }
1447
1470
  // Per-FILE added content for an `apply_patch` call: `parsePatchPaths` flattens every marker
1448
1471
  // path into one list (right for the path-only gates, which must catch a secret/protected name
@@ -1488,7 +1511,9 @@ function patchSections(patchText) {
1488
1511
  // (OpenCode tool Parameters, packages/opencode/src/tool/{write,edit}.ts) — both single-path, so
1489
1512
  // one pair. For `apply_patch`, one pair per marker section; only the `+`-prefixed hunk lines are
1490
1513
  // 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.
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).
1492
1517
  function pickAddedContentByPath(args, cwd) {
1493
1518
  const found = args && typeof args.patchText === "string" ? parsePatchSections(args.patchText)
1494
1519
  .filter((s) => s.added.length)
@@ -1498,10 +1523,40 @@ function pickAddedContentByPath(args, cwd) {
1498
1523
  })) : []
1499
1524
  // Beside a patch too: a decoy `patchText` must not hide the content a call also carries.
1500
1525
  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 })
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
+ }
1503
1532
  return found
1504
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
+ }
1505
1560
  function pickCommand(args) {
1506
1561
  for (const k of ["command", "cmd", "script"]) {
1507
1562
  if (args && typeof args[k] === "string") return args[k]
@@ -1577,8 +1632,8 @@ function machineDir() {
1577
1632
  return path.join(process.env.XDG_CONFIG_HOME || path.join(homedir(), ".config"), "geneseed")
1578
1633
  }
1579
1634
 
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"]
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'];
1582
1637
 
1583
1638
  // The host's own config dir counts as global too, whatever its marker says (the hook's
1584
1639
  // isHostGlobalDir accepts both): OPENCODE_CONFIG_DIR, else <XDG config>/opencode.
@@ -2290,36 +2345,69 @@ const noProgramWord = (command) => scanSegments(command).some((seg) => seg.inclu
2290
2345
  .some((t) => !/^\w+=/.test(t)))
2291
2346
 
2292
2347
  // ---- 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
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
2295
2352
  // holding a build manifest) whose root AGENTS.md has no `## Ownership` section outside the
2296
2353
  // Geneseed block, the first write of a session is refused once, so the agent proposes the setup
2297
2354
  // 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.
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.
2299
2359
  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")
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
2303
2386
  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}`
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
2320
2408
  // The developer's durable, personal decline (`DECLINED_RE` in the hook twin; geneseed-context.js
2321
2409
  // 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
2410
+ const DECLINED_RE = /^Setup:[ \t]*declined[ \t]+(\d{4}-\d{2}-\d{2})[ \t]*\r?$/m;
2323
2411
  // The reason to refuse this write, or null. `p` is absolute. Never throws.
2324
2412
  function ownershipBlock(p, sessionID) {
2325
2413
  try {
@@ -2337,7 +2425,7 @@ function ownershipBlock(p, sessionID) {
2337
2425
  let text = null
2338
2426
  try { text = readFileSync(path.join(root, "AGENTS.md"), "utf8") } catch { /* none: gate */ }
2339
2427
  const own = text === null ? "" : text.replace(MANAGED_BLOCK_RE, "")
2340
- if (OWNERSHIP_SECTION_RE.test(own)) return null
2428
+ if (SECTION_RE.test(own)) return null
2341
2429
  let personal = ""
2342
2430
  // In the MAIN worktree (the hook twin's `mainWorktreeOf(root) ?? root`): the shared `.git`'s
2343
2431
  // parent, else this root (a main worktree, a submodule, a bare common dir, a bad link).
@@ -2346,11 +2434,21 @@ function ownershipBlock(p, sessionID) {
2346
2434
  let home = root
2347
2435
  try { const c = gitCommonDirOf(root); if (path.basename(c) === ".git") home = path.dirname(c) } catch { /* this root */ }
2348
2436
  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
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
2354
2452
  } catch { return null }
2355
2453
  }
2356
2454
 
@@ -2390,8 +2488,9 @@ function argPaths(v, key = "", out = [], depth = 0) {
2390
2488
  // from the repo (V2 loads every .js in plugins/ as a plugin). One line per skill or subagent
2391
2489
  // call, the day and the name only, under <cfg>/notebook/usage.jsonl. Silent and never throws:
2392
2490
  // 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}$/
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}$/;
2395
2494
  function usageOf(tool, args) {
2396
2495
  const t = String(tool || "").toLowerCase()
2397
2496
  const a = args || {}
@@ -2401,7 +2500,7 @@ function usageOf(tool, args) {
2401
2500
  else if (t === "agent" || t === "task" || t === "subagent") { kind = "agent"; name = a.subagent_type ?? a.agent }
2402
2501
  if (!kind || typeof name !== "string") return null
2403
2502
  name = name.trim().replace(/^\/+/, "")
2404
- return USAGE_NAME_RE.test(name) ? { kind, name } : null
2503
+ return NAME_RE.test(name) ? { kind, name } : null
2405
2504
  }
2406
2505
  async function recordUse(tool, args) {
2407
2506
  try {
@@ -2416,19 +2515,45 @@ async function recordUse(tool, args) {
2416
2515
  } catch { /* a counter never fails a tool call */ }
2417
2516
  }
2418
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
+
2419
2540
  export const GeneseedGuard = async (ctx) => {
2420
2541
  if (ctx?.client) LOG_CLIENT = ctx.client
2421
2542
  // The session's working directory, the same resolution the context plugin uses.
2422
2543
  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) => {
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) => {
2427
2552
  try {
2428
2553
  const info = ctx?.sessionMeta ? await ctx.sessionMeta(sid)
2429
2554
  : await ctx?.client?.session?.get?.({ path: { id: sid } })
2430
2555
  const meta = info?.data ?? info
2431
- return Boolean(meta?.parentID ?? meta?.parentId)
2556
+ return Boolean(meta?.parentID ?? meta?.parentId) || String(meta?.title ?? "").startsWith("geneseed-")
2432
2557
  } catch { return false }
2433
2558
  }
2434
2559
  // Whether the host itself will ask the user about this write once this hook lets it run. V2
@@ -2464,7 +2589,7 @@ export const GeneseedGuard = async (ctx) => {
2464
2589
  const unwatched = new Set()
2465
2590
  const watch = async (sid) => {
2466
2591
  if (OFF || !sid || watched.has(sid) || unwatched.has(sid)) return
2467
- if (await sovereignBypass(root()) || await isChildSession(sid)) { unwatched.add(sid); return }
2592
+ if (await sovereignBypass(root()) || await cannotAsk(sid)) { unwatched.add(sid); return }
2468
2593
  watched.set(sid, scanAllStores(root()))
2469
2594
  }
2470
2595
  const compare = async (sid) => {
@@ -2525,144 +2650,205 @@ export const GeneseedGuard = async (ctx) => {
2525
2650
  if (OFF) return
2526
2651
  // A session that predates this plugin never sent `session.created`. Once per session.
2527
2652
  try { await watch(input?.sessionID) } catch { /* the report never decides a tool call */ }
2528
- const tool = (input?.tool || input?.name || "").toLowerCase()
2653
+ const tool = String(input?.tool || input?.name || "").toLowerCase()
2529
2654
  const args = output?.args || input?.args || {}
2530
2655
  // `rule` is the ledger key, spelled as js/hosts/hooks.mjs spells it (`law-1`,
2531
2656
  // `law-4`, `process-1`) plus `wiki`, so status counts one vocabulary across hosts.
2532
2657
  // The model reads this text. It never names the GENESEED_GUARD switch: a weak model read
2533
2658
  // "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.
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.
2536
2662
  const refused = (id, facts) => gateSafe(id, "refused", facts)
2537
2663
  // V1's explanations, held to the end of this hook: a later gate may still refuse the call, and a
2538
2664
  // note about a dialog that never comes is a false one. V2 posts from `evaluate` instead.
2539
2665
  const notes = []
2666
+ // GENESEED_GUARD=warn: the first would-be block is logged and ends the inspection.
2667
+ let warned = false
2540
2668
  const deny = async (why, rule) => {
2541
- if (WARN_ONLY) { log(`WARN (would block): ${why}`); return false }
2669
+ if (WARN_ONLY) { log(`WARN (would block): ${why}`); warned = true; return false }
2542
2670
  log(`BLOCKED: ${why}`)
2543
2671
  await ledger(rule)
2544
2672
  throw new Error(`[geneseed-guard] blocked: ${why}`)
2545
2673
  }
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
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
+ }
2578
2742
  }
2579
- }
2743
+ }],
2580
2744
  // Content scan (Sealed Secrets, the twin of js/hosts/hooks.mjs's ruleDecide): per
2581
2745
  // FILE, not pooled — a patch touching `.env` AND an ordinary file must still catch a
2582
2746
  // secret in the ordinary file; only the hunk whose OWN path is `.env`-shaped is
2583
2747
  // 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
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
+ }
2589
2756
  }
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) {
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)) {
2595
2765
  const why = ownershipBlock(path.resolve(cwd, p), input?.sessionID)
2596
- if (why && !(await isChildSession(input.sessionID))) { await deny(why, "ownership"); return }
2766
+ if (why && !(await cannotAsk(input.sessionID))) { await deny(why, "ownership"); return }
2597
2767
  }
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
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
+ }
2610
2781
  }
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")
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")
2652
2806
  return
2653
2807
  }
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}`) }
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
2661
2842
  }
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}`)
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}`) }
2666
2852
  }
2667
2853
  },
2668
2854
  }
@@ -2690,10 +2876,16 @@ export const GeneseedGuard = async (ctx) => {
2690
2876
  // and an unattended session turns the ask into a deny. A V2 without the domain has no `hostAsks`,
2691
2877
  // so the guard refuses those writes.
2692
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
+ //
2693
2885
  // The dialog shows no plugin text, so each ask posts a note first. The TUI renders a synthetic item's
2694
2886
  // `description` and the model gets its `text`, so the block goes in the first and the second must read
2695
2887
  // true whether the user allows or denies (spec 2026-11-07-gate-prompts-5.0.3, S0 result).
2696
- async function askOnRuleStore(ctx, shellAsks) {
2888
+ async function askOnRuleStore(ctx, shellAsks, gateErrors) {
2697
2889
  const dir = ctx?.location?.directory || process.cwd()
2698
2890
  const note = async (event) => {
2699
2891
  try {
@@ -2705,6 +2897,22 @@ async function askOnRuleStore(ctx, shellAsks) {
2705
2897
  await ctx.permission.hook("evaluate", async (event) => {
2706
2898
  try {
2707
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
+ }
2708
2916
  if (event.action === "shell") {
2709
2917
  // The shell tool's assert: action `shell`, one resource per parsed command, `source.id` the
2710
2918
  // call the tool hook marked. A command the host's parser finds no command in asserts nothing.
@@ -2736,14 +2944,15 @@ async function askOnRuleStore(ctx, shellAsks) {
2736
2944
  }
2737
2945
 
2738
2946
  async function setupV2(ctx) {
2739
- // 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.
2740
2948
  const shellAsks = new Map()
2741
- const hostAsks = await askOnRuleStore(ctx, shellAsks)
2949
+ const gateErrors = new Map()
2950
+ const hostAsks = await askOnRuleStore(ctx, shellAsks, gateErrors)
2742
2951
  const hooks = await GeneseedGuard({
2743
2952
  worktree: ctx?.location?.project?.directory, directory: ctx?.location?.directory,
2744
2953
  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 }),
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 }),
2747
2956
  })
2748
2957
  const report = (type, properties) => hooks.event({ event: { type, properties } })
2749
2958
  // V2's turn edges, as geneseed-notify reads them. `say` above is the only way out to the user.
@@ -2767,11 +2976,14 @@ async function setupV2(ctx) {
2767
2976
  // `sessionID` rides on every V2 execute.before event (@opencode/plugin 2.1.4 `ToolHooks`).
2768
2977
  await hooks["tool.execute.before"]({ tool: event.tool, sessionID: event.sessionID, callID: event.id }, { args: event.input })
2769
2978
  } catch (err) {
2770
- const why = String(err?.message || "")
2771
- if (!why.startsWith("[geneseed-guard]")) return
2979
+ if (!isDeny(err)) return
2772
2980
  // 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 = {}
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)}`) }
2775
2987
  }
2776
2988
  })
2777
2989
  return () => controller.abort()