geneseed 5.0.0 → 5.0.3

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 (138) hide show
  1. package/CHANGELOG.md +70 -0
  2. package/README.md +1 -1
  3. package/SHIPPED.md +1 -1
  4. package/adapters/claude-code/README.md +6 -4
  5. package/adapters/opencode/HOW-OPENCODE-LOADS.md +3 -0
  6. package/adapters/opencode/plugins/geneseed-context.js +13 -2
  7. package/adapters/opencode/plugins/geneseed-guard.js +595 -74
  8. package/adapters/opencode/plugins/geneseed-learn.js +1 -1
  9. package/bin/geneseed-hook.mjs +21 -7
  10. package/docs/PRD.md +1 -1
  11. package/docs/concepts/enforcement-table.md +22 -3
  12. package/docs/concepts/exclusions.md +48 -2
  13. package/docs/concepts/foreman-mode.md +19 -4
  14. package/docs/concepts/hook-gates.md +1 -1
  15. package/docs/concepts/hooks.md +53 -12
  16. package/docs/concepts/host-matrix.md +4 -3
  17. package/docs/concepts/hosts.md +1 -1
  18. package/docs/concepts/kits.md +18 -0
  19. package/docs/concepts/shared-tier.md +5 -5
  20. package/docs/concepts/skills.md +1 -1
  21. package/docs/extending.md +3 -1
  22. package/docs/guides/autostart.md +27 -3
  23. package/docs/guides/choose-your-setup.md +1 -1
  24. package/docs/guides/migrate.md +5 -3
  25. package/docs/guides/uninstall.md +1 -1
  26. package/docs/guides/upgrade-to-5.md +6 -4
  27. package/docs/reference/plugin-context.md +1 -1
  28. package/docs/reference/plugin-guard.md +24 -5
  29. package/docs/reference/troubleshoot-doctor.md +2 -2
  30. package/docs/understand/a-day.md +9 -5
  31. package/docs/web-ui.md +78 -20
  32. package/harness.config.json +1 -1
  33. package/js/README.md +3 -2
  34. package/js/build/emit-claude.mjs +9 -1
  35. package/js/build/emit-opencode.mjs +2 -1
  36. package/js/build/fold.mjs +7 -7
  37. package/js/build/rule-decide.mjs +273 -0
  38. package/js/build/source.mjs +9 -3
  39. package/js/cli-table.json +122 -2
  40. package/js/hosts/geneseed-dir.mjs +1 -1
  41. package/js/hosts/hooks-context.mjs +9 -7
  42. package/js/hosts/hooks-done.mjs +3 -1
  43. package/js/hosts/hooks-learn.mjs +1 -1
  44. package/js/hosts/hooks-prims.mjs +270 -0
  45. package/js/hosts/hooks.mjs +409 -151
  46. package/js/hosts/hosts.mjs +22 -0
  47. package/js/hosts/installs.mjs +13 -9
  48. package/js/hosts/memory-files.mjs +2 -2
  49. package/js/hosts/settings.mjs +123 -23
  50. package/js/hosts/shim.mjs +155 -7
  51. package/js/hosts/store-watch.mjs +41 -14
  52. package/js/inspect/diff.mjs +2 -1
  53. package/js/inspect/inventory.mjs +1 -0
  54. package/js/inspect/registry.mjs +4 -2
  55. package/js/inspect/validate.mjs +1 -1
  56. package/js/lib/paths.mjs +13 -0
  57. package/js/maintain/migrate.mjs +60 -22
  58. package/js/maintain/uninstall.mjs +5 -1
  59. package/js/web/actions.mjs +17 -1
  60. package/js/web/api.mjs +22 -16
  61. package/js/web/handler.mjs +2 -0
  62. package/js/web/routes.mjs +9 -4
  63. package/js/web/update-check.mjs +2 -2
  64. package/js/web/user-files.mjs +38 -11
  65. package/package.json +1 -1
  66. package/registry.json +21 -0
  67. package/src/AGENT.md.tmpl +17 -21
  68. package/src/agents/_self-improvement.md +7 -6
  69. package/src/agents/developer.md +3 -2
  70. package/src/agents/docker-expert.md +1 -0
  71. package/src/agents/memory-curator.md +3 -2
  72. package/src/doctrines/process.md +24 -19
  73. package/src/kits/ci-pipelines/rules.md +10 -0
  74. package/src/kits/ci-pipelines.json +14 -0
  75. package/src/kits/docker/rules.md +11 -0
  76. package/src/kits/docker.json +12 -0
  77. package/src/memory/README.md +5 -4
  78. package/src/modes/foreman.md +23 -10
  79. package/src/notebook/README.md +1 -1
  80. package/src/skills/_self-improvement.md +12 -9
  81. package/src/skills/compose-ops.md +58 -0
  82. package/src/skills/gitlab-ci.md +51 -0
  83. package/src/skills/jenkins-pipeline.md +56 -0
  84. package/src/skills/pipeline.md +2 -2
  85. package/src/skills/rule/approve.md +11 -5
  86. package/src/skills/rule.md +26 -19
  87. package/src/skills/skill-forge.md +24 -6
  88. package/themes/_TEMPLATE.json +5 -2
  89. package/themes/biker.json +5 -2
  90. package/themes/commentator.json +5 -2
  91. package/themes/cyberpunk.json +5 -2
  92. package/themes/gamer.json +5 -2
  93. package/themes/imperial.json +5 -2
  94. package/themes/joker.json +5 -2
  95. package/themes/marvin.json +5 -2
  96. package/themes/mean.json +5 -2
  97. package/themes/military.json +5 -2
  98. package/themes/neutral.json +5 -2
  99. package/themes/pirate.json +5 -2
  100. package/themes/sports.json +5 -2
  101. package/themes/verstappen.json +5 -2
  102. package/themes/wizard.json +5 -2
  103. package/web/dist/assets/Activity-Ck_Xffpo.js +1 -0
  104. package/web/dist/assets/ActivityDetail-CBxVS4mU.js +1 -0
  105. package/web/dist/assets/{Bonsai-B_y20b3i.js → Bonsai-BlOwsvW6.js} +1 -1
  106. package/web/dist/assets/{CopyButton-CHQte7Ap.js → CopyButton-DFMOIGbe.js} +1 -1
  107. package/web/dist/assets/Dashboard-BUdUTjbB.js +2 -0
  108. package/web/dist/assets/{Docs-Dgv_MWfT.js → Docs-D_2Jt6gU.js} +3 -3
  109. package/web/dist/assets/{GreenhouseView-CSzTMSl_.js → GreenhouseView-WalcX5bp.js} +1 -1
  110. package/web/dist/assets/Installs-UGiPDMDt.js +3 -0
  111. package/web/dist/assets/{JournalView-CvRk1-m5.js → JournalView-CZtXQz-v.js} +1 -1
  112. package/web/dist/assets/Kits-XQHsazCN.js +1 -0
  113. package/web/dist/assets/Laws-B6A55S-2.js +4 -0
  114. package/web/dist/assets/Library-D7L0Wdbh.js +3 -0
  115. package/web/dist/assets/Loops-C0loS73u.js +2 -0
  116. package/web/dist/assets/{OperatorHudView-DuGz_sTk.js → OperatorHudView-CeDw5qMB.js} +1 -1
  117. package/web/dist/assets/Personal-PVmGA2-M.js +2 -0
  118. package/web/dist/assets/{RailCats-AW92uhsX.js → RailCats-BGZnJ6fa.js} +1 -1
  119. package/web/dist/assets/Settings-DWuxwh4i.js +1 -0
  120. package/web/dist/assets/Tabs-d2RIRAKT.js +1 -0
  121. package/web/dist/assets/api-BMFDSXoB.js +1 -0
  122. package/web/dist/assets/index-BEI5ugYQ.css +1 -0
  123. package/web/dist/assets/index-BNttaGQb.js +6 -0
  124. package/web/dist/index.html +3 -3
  125. package/web/dist/assets/Activity-D8G4eClY.js +0 -1
  126. package/web/dist/assets/ActivityDetail-BtOBYk3M.js +0 -1
  127. package/web/dist/assets/Dashboard-B8uXeJZ_.js +0 -2
  128. package/web/dist/assets/Installs-BDk9lqBI.js +0 -3
  129. package/web/dist/assets/Kits-CoITzxWM.js +0 -1
  130. package/web/dist/assets/Laws-Ctf5r9rE.js +0 -3
  131. package/web/dist/assets/Library-DNwHYVXt.js +0 -3
  132. package/web/dist/assets/Loops-S85PMQ8m.js +0 -2
  133. package/web/dist/assets/Personal-afJNwvRS.js +0 -2
  134. package/web/dist/assets/Settings-CGDFz-6j.js +0 -1
  135. package/web/dist/assets/Tabs-1qLrnqmn.js +0 -1
  136. package/web/dist/assets/api-C46vAuqp.js +0 -1
  137. package/web/dist/assets/index-COTd4TRZ.js +0 -3
  138. package/web/dist/assets/index-CtorA7uK.css +0 -1
@@ -51,19 +51,23 @@
51
51
  * and every file left behind. Absolute rather than compared is what let it survive the deletion
52
52
  * of the implementation it was once compared against.
53
53
  */
54
- import { readFileSync, readlinkSync, appendFileSync, writeFileSync } from 'node:fs';
54
+ import { readFileSync, readlinkSync, realpathSync, statSync, appendFileSync, writeFileSync } from 'node:fs';
55
55
  import path from 'node:path';
56
56
  import { printOut as out, printErr as err, withDiscardableStderr } from '../lib/fs.mjs';
57
57
  import { normcase } from '../lib/paths.mjs';
58
- import { sharedPaths, machineDir } from '../lib/machine-dir.mjs';
58
+ import { machineDir } from '../lib/machine-dir.mjs';
59
59
  import { isDict, isTruthy, parseJson, readJsonc } from '../lib/json.mjs';
60
60
  import {
61
- GATE_LEDGER, globalHookStandingDown, hookProjectDir, resolvePath, sovereignBypass,
61
+ GATE_LEDGER, carrierBlock, carrierName, globalHookStandingDown, hookProjectDir, isSharedCarrier,
62
+ resolvePath, sovereignBypass,
62
63
  } from './hosts.mjs';
63
- import { currentBranch, gitRootOf, loopLaunched } from './gitref.mjs';
64
+ import {
65
+ currentBranch, gitCommonDirOf, gitRootOf, loopLaunched, mainWorktreeOf, protectedBranches,
66
+ } from './gitref.mjs';
64
67
  import { LOSS_CANDIDATE_RE, catastrophic, lossReason, stripStructure } from './loss.mjs';
65
68
  import {
66
- selfAndParents, readStdin, SECRET_RE, DONE_LIST, DIFF_BLOCK_RE, isTestPath, weakenedBy, editPairs,
69
+ readStdin, SECRET_RE, DONE_LIST, DIFF_BLOCK_RE, isTestPath, weakenedBy, editPairs,
70
+ gateLoss, gateSafe,
67
71
  } from './hooks-prims.mjs';
68
72
  import { recordUse } from './usage.mjs';
69
73
  import { WRITE_NAME_RE, ownershipBlock } from './ownership-gate.mjs';
@@ -169,6 +173,73 @@ export function loopExempt(command, cwd) {
169
173
  || SEG_READONLY_RE.test(seg) || pushSegmentOk(seg, branch));
170
174
  }
171
175
 
176
+ // A Foreman worker's local commit or merge: `git commit`/`git merge` with no global option
177
+ // (`-C`, `-c`, `--git-dir`, `--work-tree` could aim it at another tree), its arguments plain
178
+ // `ARG_RE` tokens plus at most one quoted message (`-m`, `-am`, `--message`). Nothing else is
179
+ // quoted, so a quoted separator only splits the command into a segment that fails.
180
+ const SEG_LOCAL_RE = new RegExp(`^git\\s+(?:commit|merge)(?:\\s+${ARG_RE})*`
181
+ + `(?:\\s+(?:-[a-zA-Z]*m|--message)\\s+(?:"[^"]*"|'[^']*'))?(?:\\s+${ARG_RE})*$`);
182
+ const SEG_CD_RE = new RegExp(`^cd\\s+(${ARG_RE})$`);
183
+ // What a shell can run inside an argument: PowerShell's `(...)`, `@(...)`, `$(...)`, `$var`,
184
+ // `{...}` blocks and backtick escapes; bash's `$(...)`, `${...}` and backticks. Refused anywhere,
185
+ // quoted or not, so a message can never carry a second command.
186
+ const SUBSHELL_CHARS_RE = /[()@${}`]/;
187
+ // The doctrine's shared branches, by name: never a worker's branch, whatever the repo says.
188
+ const SHARED_BRANCH_RE = /^(?:main|master|develop|development|(?:release|hotfix)(?:\/.*)?)$/i;
189
+
190
+ /**
191
+ * Consent Before Push's worktree exemption (user decision 2026-11-08): a commit or merge that a
192
+ * dispatched sub-agent runs inside a LINKED worktree, on a branch that is not shared, is the
193
+ * Foreman worker's own named batch. Every clause must hold, or the ask stands:
194
+ * - `agentId`: the host says the call comes from a sub-agent (Claude Code's `agent_id`, which it
195
+ * sets on tool events inside a subagent or in-process teammate). A session that merely runs in
196
+ * a worktree, as the desktop app's do, has none and asks. A host that sends none asks always.
197
+ * - The command: none of `UNSAFE_CHARS_RE` or `SUBSHELL_CHARS_RE`, no `push` word anywhere (a mixed
198
+ * command asks), every segment an add, a read-only look, or `SEG_LOCAL_RE`, after at most one
199
+ * leading `cd <path>` (an agent's shell starts in the parent's checkout). The `cd` target and
200
+ * `cwd` are resolved with `realpathSync`, git's physical path; `cd -`, `~` or a path that does
201
+ * not resolve asks.
202
+ * - The tree: `cwd` a linked worktree (`mainWorktreeOf`, read off disk, no spawn), its branch
203
+ * known and, compared case-insensitively, neither a `SHARED_BRANCH_RE` name, a remote's HEAD
204
+ * (`protectedBranches`), nor the branch checked out in the main worktree; and the branch is not
205
+ * itself a symref to another one.
206
+ */
207
+ export function worktreeExempt(command, cwd, agentId) {
208
+ if (typeof agentId !== 'string' || !agentId) return false;
209
+ if (typeof command !== 'string' || UNSAFE_CHARS_RE.test(command) || SUBSHELL_CHARS_RE.test(command)
210
+ || /\bpush\b/i.test(command)) return false;
211
+ const segments = command.split(/&&|\|\||[;|]/).map((x) => x.trim()).filter(Boolean);
212
+ try {
213
+ let dir = realpathSync(cwd);
214
+ const cd = segments.length ? SEG_CD_RE.exec(segments[0]) : null;
215
+ if (cd) {
216
+ if (cd[1] === '-' || cd[1].startsWith('~')) return false;
217
+ dir = realpathSync(path.resolve(dir, cd[1]));
218
+ segments.shift();
219
+ }
220
+ if (!segments.length || !segments.every((seg) => SEG_ADD_RE.test(seg) || SEG_READONLY_RE.test(seg)
221
+ || SEG_LOCAL_RE.test(seg))) return false;
222
+ const main = mainWorktreeOf(dir);
223
+ const branch = main && currentBranch(dir);
224
+ if (!branch || branch.includes('..') || SHARED_BRANCH_RE.test(branch)) return false;
225
+ // HEAD names the branch, but the branch may itself be a symref (`git symbolic-ref
226
+ // refs/heads/sym refs/heads/develop`), and a commit then moves its target. Packed refs hold no
227
+ // symrefs, so only the loose file can alias: one that starts with `ref:` asks, however long
228
+ // the chain behind it. An absent file is a packed or unborn branch, which aliases nothing.
229
+ let loose = '';
230
+ try {
231
+ loose = readFileSync(path.join(gitCommonDirOf(gitRootOf(dir)), 'refs', 'heads', ...branch.split('/')), 'utf8');
232
+ } catch (e) {
233
+ if (e.code !== 'ENOENT') return false;
234
+ }
235
+ if (/^\s*ref:/.test(loose)) return false;
236
+ const taken = [...protectedBranches(gitRootOf(dir)), currentBranch(main)].filter(Boolean);
237
+ return !taken.some((b) => b.toLowerCase() === branch.toLowerCase());
238
+ } catch {
239
+ return false;
240
+ }
241
+ }
242
+
172
243
  /**
173
244
  * The `permissionDecision: "ask"` document, in Python's compact `json.dumps` spelling: `, ` and
174
245
  * `: ` separators, and `ensure_ascii` — every code unit past `~` as a lowercase `\uXXXX`, which is
@@ -231,17 +302,14 @@ const BOB_FINAL = ' Bob has no approval step for this gate: neither a confirmati
231
302
  + 'nor a retry in another form lifts it. Leave it, or ask the user to do it themself, outside '
232
303
  + 'Bob. Never suggest disabling the Geneseed hook.';
233
304
 
234
- /** Law IV's real-loss tail, where the host can ask. Bob's is `BOB_FINAL`, appended by `ask`. */
235
- const confirmTail = () => (HOST === 'bob' ? 'Leave the data in place.'
236
- : 'Confirm this specific command, or leave the data in place.');
237
-
238
305
  /**
239
306
  * On Bob, which has no ask tier, which rules are worth a hard block. Laws I and IV: a
240
307
  * credential in a tracked file and a history-discarding git act are wrong in every context,
241
308
  * so refusing them costs nothing. rigor-5 (External Gate) joins them: a protected check the
242
309
  * agent can edit is not a check, so it is as unconditional as the two Laws — NOT "Laws I/IV
243
310
  * only", see bob-code.md B3. process-1 too (owner decision, 2026-11): with no prompt, a warning
244
- * let the agent write the user's rules and memory on its own say. Process 5 is the USER's call
311
+ * let the agent write the user's rules on its own say. Memory is written freely (owner decision,
312
+ * 2026-11-08), so a memory write reaches no rule here. Process 5 is the USER's call
245
313
  * as well, but a hard block would make Bob unable to commit at all, so it stays a warning the
246
314
  * host logs. ops-2 (Commands Must Return, the root-scan check) is a block too: a warning would let a
247
315
  * scan of every drive run for hours, and the agent loses nothing by re-targeting a directory.
@@ -289,22 +357,26 @@ function ledger(root, verb, rule) {
289
357
  /**
290
358
  * Ask, and record that we asked. Every ask site goes through here so none can skip the
291
359
  * ledger. On `--host bob` the ask becomes a block or a warning (see `BLOCK_RULES`); the
292
- * ledger records the block, never the warning — a warning asked nothing of anyone.
360
+ * ledger records the block, never the warning — a warning asked nothing of anyone. `id` and
361
+ * `facts` are `gateText`'s, and the words are built here, last, through `gateSafe`: this runs
362
+ * from `guardGate`'s catch, where a throw is a bad exit, and Claude lets that call through. The
363
+ * host and the rule pick the mode. `facts.bobWhy` says why Bob refused a settings write.
293
364
  */
294
- function ask(args, verb, rule, reason) {
365
+ function ask(args, verb, rule, id, facts) {
295
366
  if (HOST === 'bob') {
296
367
  if (!BLOCK_RULES.has(rule)) {
297
368
  // No ask tier; a stderr line is the nudge, and the call goes through.
298
- err(`[geneseed] ${reason}\n`);
369
+ err(`[geneseed] ${gateSafe(id, 'warned', facts)}\n`);
299
370
  return 0;
300
371
  }
301
372
  ledger(args && args.root, verb, rule);
373
+ const why = facts && facts.bobWhy ? ` On Bob this write is refused because ${facts.bobWhy}.` : '';
302
374
  // stdout is not read on Bob's PreToolUse; the reason goes where Bob's hook log looks.
303
- err(`[geneseed] BLOCKED: ${reason}${BOB_FINAL}\n`);
375
+ err(`[geneseed] BLOCKED: ${gateSafe(id, 'refused', facts)}${why}${BOB_FINAL}\n`);
304
376
  return BOB_DENY_EXIT;
305
377
  }
306
378
  ledger(args && args.root, verb, rule);
307
- out(askDecision(reason));
379
+ out(askDecision(gateSafe(id, 'ask', facts)));
308
380
  return 0;
309
381
  }
310
382
 
@@ -344,9 +416,10 @@ export function guardGate(fn, verb = 'gate') {
344
416
  try {
345
417
  return fn(args);
346
418
  } catch (e) {
347
- const why = e && e.message ? e.message : String(e);
348
- return ask(args, verb, 'gate-error', `Geneseed gate error — ${why}. The gate could `
349
- + 'not evaluate this call, so it does not defer.');
419
+ // A thrown value can be anything, and this catch has nothing behind it: reading it must not throw.
420
+ let name = e;
421
+ try { name = e.message || e; } catch { /* `gateSafe` meets `e` as it is */ }
422
+ return ask(args, verb, 'gate-error', 'gate-error', { name });
350
423
  }
351
424
  };
352
425
  }
@@ -502,13 +575,56 @@ const rootArg = (t) => !/^["']/.test(t) && FS_ROOT_RE.test(t);
502
575
  // to the END marker verbatim, with `export ` dropped (tests/plugins/guard.test.mjs diffs the two).
503
576
 
504
577
  // The cheap prefilter, a superset of what the parse acts on: a `>`, or one of the programs as a word.
505
- const SHELL_WRITE_RE = />|(?:^|[\s;&|("'`\\/])(?:tee|sed|cp|mv|rm)(?:\.exe)?(?=[\s;&|)"'`]|$)/im;
578
+ const SHELL_WRITE_RE = />|(?:^|[\s;&|("'`\\/])(?:tee|sed|cp|mv|rm|add-content|set-content|out-file|clear-content|remove-item|copy-item|move-item|new-item|rename-item|ac|sc|del|copy|move|ni|ren)(?:\.exe)?(?=[\s;&|)"'`]|$)/im;
506
579
  // One pass over a segment: a quoted run (kept: its `>` is data), or a redirection with its optional
507
580
  // fd, operator, `&` (a dup such as `2>&1`, which writes no file) and target word. `<` forms match
508
581
  // too, so that their words never read as operands. A backslash is no escape here, as in
509
582
  // `SCAN_SPLIT_RE`: `echo "say \"hi > f\""` closes its quote early, reads a target, and asks (on Bob, blocks).
510
583
  const REDIRECT_RE = /"[^"]*"?|'[^']*'?|(?:(?<!\S)\d+|&)?(<<?<?-?|>>?)[ \t]*(&?)((?:[^\s"';|&<>()]|"[^"]*"?|'[^']*'?)*)/g;
511
584
  const SHELL_CD = new Set(['cd', 'pushd', 'chdir', 'set-location', 'sl']);
585
+ // What says the shell is PowerShell when the caller cannot: a `Verb-Noun` word outside any here-string.
586
+ const PS_CUE_RE = /(?:^|[\s;|&(])(?:add|clear|copy|export|foreach|get|import|invoke|move|new|out|remove|rename|select|set|start|stop|test|where|write)-[a-z]+/i;
587
+ // The home a shell expands, spelled for `writePath` as `~/…`, the one form that keeps the two readings.
588
+ const HOME_WORD_RE = /^(?:~|\$\{?(?:env:)?(?:home|userprofile)\}?)(?=[\\/]|$)/i;
589
+ // PowerShell's writers, each as the POSIX form that writes the same paths. `ren` is `mv` with a sibling.
590
+ const PS_WRITERS = new Map(Object.entries({
591
+ 'add-content': 'rm', ac: 'rm', 'set-content': 'rm', sc: 'rm', 'out-file': 'rm', 'clear-content': 'rm', 'remove-item': 'rm',
592
+ del: 'rm', 'new-item': 'rm', ni: 'rm', 'copy-item': 'cp', copy: 'cp', 'move-item': 'mv', move: 'mv', 'rename-item': 'ren', ren: 'ren',
593
+ }));
594
+ // `rm`, `cp` and `mv` are aliases too, but only a parameter spelled out in full tells them from the
595
+ // POSIX programs: `-lp` and `-pat` are also POSIX flag clusters.
596
+ const PS_NAMED_RE = /^-(?:path|literalpath|destination)(?::|$)/i;
597
+ const PS_PATH_RE = /^-(?:path|literalpath|lp|pspath|filepath)$/i;
598
+ const PS_SWITCH_RE = /^-(?:force|recurse|append|nonewline|noclobber|whatif|confirm|passthru|verbose|debug|container)$/i;
599
+ const PS_VALUE_RE = /^-(?:value|encoding|itemtype|type|filter|include|exclude|inputobject|stream|width|target|erroraction|ea)$/i;
600
+ // `(…)`, `$(…)`, `@(…)`, `{…}`, `@{…}`: an argument whose words cannot be counted. `${x}` is a variable.
601
+ const PS_OPAQUE_RE = /^(?:[$@]?\(|@?\{)/;
602
+
603
+ /**
604
+ * `s` with each here-string body cut. The body is data, as a heredoc's is: without this, an apostrophe
605
+ * in a PowerShell commit message unpairs the quotes, and a line that opens with `Move` reads as a
606
+ * command. One pass: a quote kind with no closer is searched for once, so many openers stay linear.
607
+ */
608
+ function hereStringsCut(s) {
609
+ const re = /@(["'])\r?\n/g;
610
+ const dead = new Set();
611
+ let out = ''; let at = 0; let m;
612
+ while ((m = re.exec(s))) {
613
+ if (dead.has(m[1])) continue;
614
+ const end = s.indexOf(`\n${m[1]}@`, re.lastIndex - 1);
615
+ if (end < 0) { dead.add(m[1]); continue; }
616
+ out += `${s.slice(at, m.index)}''`;
617
+ at = end + 3;
618
+ re.lastIndex = at;
619
+ }
620
+ return out + s.slice(at);
621
+ }
622
+
623
+ /** `t` without its quotes, a home spelled `~/…`. Single quotes expand nothing, so `$` stays and hides the path. */
624
+ function shellWord(t) {
625
+ const w = t.replace(/["']/g, '');
626
+ return t[0] !== "'" && HOME_WORD_RE.test(w) ? `~${w.replace(HOME_WORD_RE, '').replace(/\\/g, '/')}` : w;
627
+ }
512
628
 
513
629
  /** `t` as an absolute path from `dir`, `~/…` as it stands, or null for what the shell rewrites. */
514
630
  function writePath(dir, t) {
@@ -517,9 +633,49 @@ function writePath(dir, t) {
517
633
  // A Git Bash `/c/…` path, as `resolveIn` reads it.
518
634
  const q = process.platform === 'win32' ? t.replace(/^\/([a-zA-Z])(?=\/|$)/, '$1:') : t;
519
635
  if (path.isAbsolute(q)) return path.resolve(q);
636
+ if (dir && dir[0] === '~') return `${dir}/${q}`;
520
637
  return dir ? path.resolve(dir, q) : null;
521
638
  }
522
639
 
640
+ /**
641
+ * The operands of a PowerShell writer, in the order the POSIX branches read them, `/`-separated (a
642
+ * cmdlet takes `\` on every platform). Only the first positional is a path, and for `cp`, `mv` and
643
+ * `ren` the next is the destination: the next one of `Add-Content a b` is its value and of
644
+ * `Remove-Item a b` its filter. Named paths are read wherever they stand; a parameter this does
645
+ * not know, or a `(…)` or `{…}` argument, ends the positionals, because its words cannot be counted.
646
+ */
647
+ function psOperands(toks, form) {
648
+ const paths = []; const dest = []; const pos = [];
649
+ let name = ''; let open = true;
650
+ const list = (t) => (t.match(/"[^"]*"?|'[^']*'?|[^,"']+/g) || []).map(shellWord).filter(Boolean);
651
+ for (let i = 0; i < toks.length; i += 1) {
652
+ // An array argument spans tokens: `a, b`.
653
+ const value = (t) => { let v = t; while (v.endsWith(',') && i + 1 < toks.length) { i += 1; v += toks[i]; } return v; };
654
+ const m = /^(-[a-z]+)(?::(.+))?$/is.exec(toks[i]);
655
+ if (!m) {
656
+ const t = value(toks[i]);
657
+ if (PS_OPAQUE_RE.test(t)) open = false;
658
+ else if (open && !/^\/[a-z]$/i.test(t)) pos.push(t); // `/y`: `copy` and `del` are cmd.exe's too
659
+ } else if (!PS_SWITCH_RE.test(m[1])) {
660
+ const into = PS_PATH_RE.test(m[1]) ? paths : /^-destination$/i.test(m[1]) ? dest : null;
661
+ const naming = /^-(?:new)?name$/i.test(m[1]);
662
+ if (!into && !naming && !PS_VALUE_RE.test(m[1])) { open = false; continue; }
663
+ if (m[2] === undefined) i += 1;
664
+ const t = value(m[2] ?? toks[i] ?? '');
665
+ if (PS_OPAQUE_RE.test(t)) open = false;
666
+ else if (into) into.push(...list(t));
667
+ else if (naming) name = shellWord(t);
668
+ }
669
+ }
670
+ if (!paths.length && pos.length) paths.push(...list(pos.shift()));
671
+ if (form === 'rm') return name ? (paths.length ? paths : ['.']).map((p) => `${p}/${name}`) : paths;
672
+ if (form === 'ren') {
673
+ const to = name || shellWord(pos[0] ?? '');
674
+ return to && paths.length ? [paths[0], paths[0].replace(/[^\\/]*$/, '') + to] : paths;
675
+ }
676
+ return [...paths, ...(dest.length ? dest : list(pos[0] ?? '')).slice(0, 1)];
677
+ }
678
+
523
679
  /** The files `sed` edits in place: none without `-i`; else its operands, past the script if inline. */
524
680
  function sedFiles(args) {
525
681
  const ops = [];
@@ -540,38 +696,55 @@ function sedFiles(args) {
540
696
  /**
541
697
  * The files `command` would write, as absolute paths: redirect targets (`>`, `>>`, `&>`), `tee`
542
698
  * and `rm` operands, `sed -i` files, the destination of `cp` and `mv`, and the sources of `mv`, which
543
- * it removes. A destination may be a folder, so `cp a tests/` also names `tests/a`. Read like
544
- * `rootScan`: quotes, comments and heredoc bodies are data. A `cd` is followed; one it cannot read
545
- * leaves later relative paths unseen. What it cannot read, it leaves out: this reader fails OPEN.
699
+ * it removes. A destination may be a folder, so `cp a tests/` also names `tests/a`. PowerShell's
700
+ * writers read the same way (`PS_WRITERS`, `psOperands`), case-insensitively, and a pipe into one needs
701
+ * nothing more: `| Out-File x` is a segment of its own. Read like `rootScan`: quotes, comments and
702
+ * heredoc bodies are data. So is a here-string body, but only in PowerShell, which `ps` says when the
703
+ * caller knows the tool and `PS_CUE_RE` otherwise: to bash the opener is a plain quote, so a closed
704
+ * "here-string" can wrap a real `rm` (the row in tests/unit/hook_gates.test.mjs). With no cue, a
705
+ * PowerShell here-string reads as bash would read it. A home variable is read as `~`. A `cd` is followed; one it cannot read leaves later relative paths unseen.
706
+ * What it cannot read, it leaves out: this reader fails OPEN.
546
707
  *
547
708
  * shortcut: KNOWN UNSEEN FORMS, all of them still a write. An interpreter (inline code,
548
- * `bash -c`, `eval`, `xargs`), a script or `npm run`, a `$(…)` or subshell trick, `>|`, a path with a
549
- * variable, glob or brace in it, a wrapper with flags (`sudo -u x`) or outside `SCAN_WRAPPERS` (`env rm`,
550
- * `nohup rm`, `timeout 5 rm`, `exec rm`), `echo x >& file` (read as a dup), a `popd` (not followed, so
551
- * relative paths after a `pushd`/`popd` pair resolve from the wrong folder), `cp -t`, any other writer
552
- * (`dd`, `ln`, `install`, `git mv`, `git checkout`, `Set-Content`), and a folder removed above a
553
- * listed file (`rm -r tests` when only `tests/a.test.js` is listed). CI running the checks is the
554
- * boundary that holds against those.
709
+ * `bash -c`, `pwsh -c`, `powershell -Command`, `eval`, `xargs`), a script or `npm run`, a `$(…)` or
710
+ * subshell trick, `>|`, a path with any other variable, a glob or a brace in it, a wrapper with flags
711
+ * (`sudo -u x`) or outside `SCAN_WRAPPERS` (`env rm`, `nohup rm`, `timeout 5 rm`, `exec rm`), `echo x >&
712
+ * file` (read as a dup), a `popd` (not followed, so relative paths after a `pushd`/`popd` pair resolve
713
+ * from the wrong folder), `cp -t`, any other writer (`dd`, `ln`, `install`, `git mv`, `git checkout`,
714
+ * `Tee-Object`, `[IO.File]::WriteAllText`, an alias outside `PS_WRITERS` such as `ri`), a cmdlet behind
715
+ * a PowerShell assignment, `if` or script block (`$null = New-Item x`, `% { Remove-Item x }`), one
716
+ * continued over lines with a backtick, a parameter abbreviated or unknown before a positional path (so
717
+ * `Set-Content -Enc utf8 x`), a comma list after a POSIX-read `rm`, `cp` or `mv`, and a folder removed
718
+ * above a listed file (`rm -r tests` when only `tests/a.test.js` is listed). CI running the checks is
719
+ * the boundary that holds against those.
555
720
  */
556
- export function shellWriteTargets(command, cwd) {
721
+ export function shellWriteTargets(command, cwd, ps = false) {
557
722
  if (!SHELL_WRITE_RE.test(command)) return [];
558
723
  const found = new Set();
559
724
  let dir = cwd;
560
725
  const add = (t) => { const p = writePath(dir, t); if (p) found.add(p); };
561
726
  const bare = (t) => t.replace(/["']/g, '');
562
- for (const seg of scanSegments(command)) {
727
+ const cut = hereStringsCut(command);
728
+ for (const seg of scanSegments(ps || PS_CUE_RE.test(cut) ? cut : command)) {
563
729
  const outs = [];
564
730
  const body = seg.replace(REDIRECT_RE, (m, op, dup, target) => {
565
731
  if (op === undefined) return m;
566
- if (op[0] === '>' && !dup && target) outs.push(bare(target));
732
+ if (op[0] === '>' && !dup && target) outs.push(shellWord(target));
567
733
  return ' ';
568
734
  });
569
735
  let toks = stripStructure(body.match(SCAN_TOKEN_RE) || []);
570
736
  while (toks.length && (/^\w+=/.test(toks[0]) || SCAN_WRAPPERS.has(bare(toks[0])))) toks = toks.slice(1);
571
- const prog = toks.length ? bare(toks[0]).split(/[\\/]/).pop().toLowerCase().replace(/\.exe$/, '') : '';
572
- const args = toks.slice(1).map(bare);
737
+ const word = toks.length ? bare(toks[0]).split(/[\\/]/).pop().toLowerCase() : '';
738
+ let prog = word.replace(/\.exe$/, '');
739
+ const args = toks.slice(1).map(shellWord);
573
740
  const dashes = args.indexOf('--');
574
- const ops = args.filter((a, i) => a && (a === '-' || !a.startsWith('-') || (dashes >= 0 && i > dashes)));
741
+ let ops = args.filter((a, i) => a && (a === '-' || !a.startsWith('-') || (dashes >= 0 && i > dashes)));
742
+ // `word`, not `prog`: `sc.exe` is the service tool, never the Set-Content alias.
743
+ const form = PS_WRITERS.get(word) ?? (/^(?:rm|cp|mv)$/.test(prog) && toks.some((t) => PS_NAMED_RE.test(t)) ? prog : null);
744
+ if (form) {
745
+ prog = form === 'ren' ? 'mv' : form;
746
+ ops = psOperands(toks.slice(1), form).map((t) => t.replace(/\\/g, '/'));
747
+ }
575
748
  if (SHELL_CD.has(prog)) {
576
749
  const to = ops.find((a) => !/^\/d$/i.test(a));
577
750
  dir = to && to !== '-' ? writePath(dir, to) : null;
@@ -594,7 +767,7 @@ export function shellWriteTargets(command, cwd) {
594
767
 
595
768
  /**
596
769
  * External Gate over a shell command: the first write target that `externalGate` refuses, as the
597
- * reason to ask, or null. Path check only, no secret scan of the command. Any throw is a pass, not
770
+ * `gateText` facts to ask with, or null. Path check only, no secret scan of the command. Any throw is a pass, not
598
771
  * `guardGate`'s `gate-error` ask: this reader fails open, and a hand-mangled path is not a gate failure.
599
772
  */
600
773
  function shellWriteReason(args, command, payload) {
@@ -603,16 +776,16 @@ function shellWriteReason(args, command, payload) {
603
776
  // A Roo-lineage shell tool may name its own directory, as OpenCode's `workdir` does.
604
777
  const own = payload && payload.tool_input && payload.tool_input.cwd;
605
778
  const cwd = typeof own === 'string' && own ? path.resolve(base, own) : base;
606
- for (const t of shellWriteTargets(command, cwd)) {
607
- const why = externalGate(args, t, payload);
608
- if (why) return why;
779
+ for (const t of shellWriteTargets(command, cwd, payload?.tool_name === 'PowerShell')) {
780
+ const hit = externalGate(args, t, payload);
781
+ if (hit) return { ...hit, shell: true };
609
782
  }
610
783
  } catch { /* see above */ }
611
784
  return null;
612
785
  }
613
786
 
614
787
  /**
615
- * A parsed shell write that lands in a rule or memory store: the reason, or null. Asked on Claude
788
+ * A parsed shell write that lands in a rule store: which one, or null. Asked on Claude
616
789
  * and OpenClaude, and only a warning on Bob, whose one verdict is a hard block: shell is no boundary,
617
790
  * and command text is no ground to refuse on. Fails open, like `shellWriteReason`.
618
791
  */
@@ -621,29 +794,25 @@ function shellStoreReason(args, command, payload) {
621
794
  const base = (payload && typeof payload.cwd === 'string' && payload.cwd) || process.cwd();
622
795
  const own = payload && payload.tool_input && payload.tool_input.cwd;
623
796
  const cwd = typeof own === 'string' && own ? path.resolve(base, own) : base;
624
- for (const t of shellWriteTargets(command, cwd)) {
797
+ for (const t of shellWriteTargets(command, cwd, payload?.tool_name === 'PowerShell')) {
625
798
  const store = ruleGateTarget(t, args.root, cwd);
626
- if (store) {
627
- return `Geneseed (Persist Insight) \u2014 writing to ${store} through a shell command: a standing `
628
- + 'rule, or a fact to remember? That choice is the user\'s.';
629
- }
799
+ if (store) return store;
630
800
  }
631
801
  } catch { /* see above */ }
632
802
  return null;
633
803
  }
634
804
 
635
805
  function gitDecide(args, payload) {
636
- const command = ((payload && payload.tool_input) || {}).command;
806
+ const ti = (payload && payload.tool_input) || {};
807
+ const { command } = ti;
637
808
  if (typeof command !== 'string') return 0;
809
+ // The agent's own words, for the asks where they are no conflict of interest (`gateText`'s `quote`).
810
+ const says = typeof ti.description === 'string' ? ti.description : '';
638
811
  // Law IV's catastrophic class (a root, a drive, the home dir, a disk): no state makes it safe,
639
812
  // so it runs BEFORE the switch below and whatever it says (user decision, 2026-10-18). On
640
813
  // Claude an ask is the strongest verdict the hook has; on Bob, `law-4` exits 2.
641
814
  const doomed = catastrophic(command, lossSegments);
642
- if (doomed) {
643
- return ask(args, 'git-gate', 'law-4', `Geneseed (Deletion Is Deliberate) \u2014 \`${doomed.slice(0, 80)}\` `
644
- + 'would destroy a filesystem root, a drive, the home directory or a whole disk, which nothing '
645
- + 'could restore. This check stands even with the deletion gate off.');
646
- }
815
+ if (doomed) return ask(args, 'git-gate', 'law-4', 'catastrophic', { name: doomed, says });
647
816
  // `--no-deletion-gate`: the install switched Law IV's real-loss boundary off (user decision,
648
817
  // 2026-10-17). Only this check stands down — the catastrophic class above, ops 2 and process 5
649
818
  // below still run.
@@ -653,25 +822,23 @@ function gitDecide(args, payload) {
653
822
  const loss = lossReason(lossSegments(command), (payload && payload.cwd) || process.cwd(),
654
823
  { split: lossSegments });
655
824
  if (loss) {
656
- return ask(args, 'git-gate', 'law-4', `Geneseed (Deletion Is Deliberate) \u2014 ${loss}. `
657
- + confirmTail());
825
+ const facts = gateLoss(loss);
826
+ return ask(args, 'git-gate', 'law-4', facts.id, { ...facts, says });
658
827
  }
659
828
  }
660
- // Before `--no-consent`: that flag drops the process pack's rule, not this one.
661
- const scan = rootScan(command);
662
- if (scan) {
663
- return ask(args, 'git-gate', 'ops-2', `Geneseed (Commands Must Return) \u2014 \`${scan.slice(0, 80)}\` `
664
- + 'recursively scans a whole filesystem root (in Git Bash, / spans every drive and mounted '
665
- + 'share, for hours; | head stops nothing). Search a specific directory instead: the '
666
- + 'project, node_modules, ~/.npm, %APPDATA%.');
667
- }
829
+ // Before `--no-consent`: that flag drops process 5, not this one. `--no-root-scan`: ops 2 is
830
+ // excluded (or its pack off), so its check goes with its text (owner decision, 2026-11-08).
831
+ const scan = args.noRootScan ? null : rootScan(command);
832
+ if (scan) return ask(args, 'git-gate', 'ops-2', 'root-scan', { name: scan, says });
668
833
  // Also before `--no-consent`: rigor-5 is no part of the process pack. On Bob a hook-settings
669
834
  // target cannot be replayed from a command (`bobSettingsChange`), so it blocks.
670
835
  const shellWrite = shellWriteReason(args, command, payload);
671
- if (shellWrite) return ask(args, 'git-gate', 'rigor-5', shellWrite);
672
- const shellStore = shellStoreReason(args, command, payload);
673
- if (shellStore && HOST !== 'bob') return ask(args, 'git-gate', 'process-1', shellStore);
674
- if (shellStore) err(`[geneseed] ${shellStore}\n`);
836
+ if (shellWrite) return ask(args, 'git-gate', 'rigor-5', shellWrite.id, shellWrite);
837
+ // `--no-rule-store`: process 1 is excluded (or its pack off), so neither the ask nor Bob's warning runs.
838
+ const shellStore = args.noRuleStore ? null : shellStoreReason(args, command, payload);
839
+ const storeFacts = { name: shellStore, shell: true };
840
+ if (shellStore && HOST !== 'bob') return ask(args, 'git-gate', 'process-1', 'store', storeFacts);
841
+ if (shellStore) err(`[geneseed] ${gateSafe('store', 'warned', storeFacts)}\n`);
675
842
  // `--no-consent`: the process pack (or process 5 alone) is off, so the commit/push ask has
676
843
  // no rule behind it — but Law IV above is universal and has already run. Checked before
677
844
  // `loopExempt` so a non-git command, or one with consent off, never pays for the whitelist.
@@ -679,8 +846,9 @@ function gitDecide(args, payload) {
679
846
  // Consent Before Push: a loop launched on its own `loop/*` branch is a named batch for a
680
847
  // fixed set of commit/push forms on that branch only — never a merge into anything shared.
681
848
  if (loopExempt(command, (payload && payload.cwd) || process.cwd())) return 0;
682
- return ask(args, 'git-gate', 'process-5', 'Geneseed (Consent Before Push) \u2014 every git '
683
- + 'commit/push needs explicit approval; to see the change first, use the explain-changes skill');
849
+ // A worker's own worktree branch is a named batch for local commits and merges, never a push.
850
+ if (worktreeExempt(command, (payload && payload.cwd) || process.cwd(), payload && payload.agent_id)) return 0;
851
+ return ask(args, 'git-gate', 'process-5', 'commit', { says });
684
852
  }
685
853
  export const cmdGitGate = guardGate(gitGate, 'git-gate');
686
854
 
@@ -689,35 +857,53 @@ export const cmdGitGate = guardGate(gitGate, 'git-gate');
689
857
  // ======================================================================================
690
858
 
691
859
  /**
692
- * `_rule_gate_target` — name the store a write would land in, or null for ordinary work.
860
+ * What `p` lands on, as `ruleGateTarget`'s docblock says: as spelled from `base`, then with links
861
+ * followed, so the last form is the file a write reaches. May throw on a form the home cannot read.
862
+ */
863
+ function landsOn(p, base) {
864
+ const win = process.platform === 'win32';
865
+ const forms = [];
866
+ if (p.startsWith('~')) forms.push(resolvePath(p));
867
+ else {
868
+ const spelled = !win ? p : p.replace(/^\/([a-zA-Z])(?=\/|$)/, '$1:').replace(/^[\\/]{2}[?.][\\/](?=[a-zA-Z]:)/, '')
869
+ .replace(/^[\\/]{2}(?:localhost|127\.0\.0\.1|\[?::1\]?)[\\/]([a-zA-Z])\$(?=[\\/]|$)/i, '$1:');
870
+ let abs = path.resolve(base || process.cwd(), spelled);
871
+ if (win) {
872
+ const drive = /^[a-zA-Z]:|^\\\\[^\\]+\\[^\\]+/.exec(abs)?.[0] ?? '';
873
+ abs = drive + abs.slice(drive.length).split('\\').map((s) => s.replace(/:.*$/, '').replace(/[. ]+$/, '')).join('\\');
874
+ }
875
+ forms.push(abs, resolvePath(abs));
876
+ // A dangling link has no realpath, and a write through it creates its target: follow it by
877
+ // hand, each hop through `resolvePath`, because a hop may pass a folder link. Links can loop.
878
+ for (let cur = forms[1], hop = 0; hop < 8; hop += 1) {
879
+ try { cur = resolvePath(path.resolve(path.dirname(cur), readlinkSync(cur))); forms.push(cur); } catch { break; }
880
+ }
881
+ }
882
+ return forms;
883
+ }
884
+
885
+ /**
886
+ * `_rule_gate_target` — name the rule store a write would land in, or null for ordinary work.
693
887
  *
694
- * A deployed install's folder and file names are theme-INDEPENDENT by design, so this
695
- * matches literal names and needs no install lookup. `user-rules.md`, `user-rules.draft.md` and
696
- * `MEMORY.md` are Geneseed's own coinage and match anywhere; any other markdown matches only
697
- * inside THIS install's `<root>/memory/` or the machine tier's `memory/`, or the store
698
- * `$GENESEED_HARNESS` or `$GENESEED_MEMORY` names. Twin of the OpenCode guard's `ruleStoreTarget`.
888
+ * Only the user's standing rules are gated: `user-rules.md` and the rule draft
889
+ * `user-rules.draft.md`, Geneseed's own coinage, matched anywhere by literal name (a deployed
890
+ * install's file names are theme-INDEPENDENT by design, so this needs no install lookup). Memory
891
+ * is written freely, with no prompt (owner decision, 2026-11-08): the change report
892
+ * (`./store-watch.mjs`) and the web console show it afterwards. Twin of the OpenCode guard's
893
+ * `ruleTarget`.
699
894
  *
700
895
  * The test is on what the write LANDS on: as spelled, `..` and `//` folded, and with links followed,
701
- * since a link from outside into a store and a store that links out are both real. On Windows a
702
- * stream (`user-rules.md::$DATA`), trailing dots and spaces, a device path and this machine's admin
703
- * share name the same file. A coined name matches by exact case outside a store: `docs/concepts/memory.md`
704
- * is another file, on Windows too, and on Bob this is a hard block. A file that EXISTS under a coined
896
+ * since a link from a memory file or any other path to a rule store is a write to that store. On
897
+ * Windows a stream (`user-rules.md::$DATA`), trailing dots and spaces, a device path and this
898
+ * machine's admin share name the same file. A coined name matches by exact case: `User-Rules.md` is
899
+ * another file, on Windows too, and on Bob this is a hard block. A file that EXISTS under a coined
705
900
  * name comes back in its true case through the link-followed form; a differently cased spelling
706
- * of one that does not exist yet is not caught. `base` is the session's directory.
901
+ * of one that does not exist yet is not caught. A hard link has no target to follow, so a file that is
902
+ * a known rule file under a second name answers `a hard link` (`sameAsRule`): this install's, the
903
+ * machine tier's, or the project layer's at the session's git root. `base` is the session's directory.
707
904
  */
708
- // The close of the process-1 text. On Claude this is a real prompt the host shows; the OpenCode
709
- // guard has its own texts, because a re-issue releases nothing there. A weak model once took a
710
- // refusal as leave to write the same file through a shell command, so the text names the one way
711
- // forward and never a switch that turns the gate off.
712
- export const PERSIST_ASK = 'Stop and ask the user now (the rule skill). If this edit was refused, '
713
- + 're-issue the same edit only after they answer; never write it another way (for example '
714
- + 'through a shell command).';
715
- /** Bob's close instead: nothing there lifts the block, so nothing here may speak of re-issuing. */
716
- const PERSIST_BOB = 'Tell the user what you wanted to write (the rule skill).';
717
-
718
- function ruleGateTarget(p, root, base = null) {
905
+ function ruleGateTarget(p, root = null, base = null) {
719
906
  if (typeof p !== 'string') return null;
720
- const win = process.platform === 'win32';
721
907
  // Split on BOTH separators rather than taking a basename: a payload carrying a Windows
722
908
  // path reaches a POSIX host with its backslashes intact, and `path.basename` there
723
909
  // returns the whole string — so the coined names would go unrecognised exactly
@@ -725,48 +911,47 @@ function ruleGateTarget(p, root, base = null) {
725
911
  const coined = (f) => {
726
912
  const name = f.split(/[\\/]/).pop();
727
913
  if (name === 'user-rules.md') return 'user-rules.md';
728
- if (name === 'MEMORY.md') return 'the memory index';
729
914
  if (name === 'user-rules.draft.md') return 'the rule draft';
730
915
  return null;
731
916
  };
732
917
  const named = coined(p);
733
918
  if (named) return named;
734
919
  try {
735
- const forms = [];
736
- if (p.startsWith('~')) forms.push(resolvePath(p));
737
- else {
738
- const spelled = !win ? p : p.replace(/^\/([a-zA-Z])(?=\/|$)/, '$1:').replace(/^[\\/]{2}[?.][\\/](?=[a-zA-Z]:)/, '')
739
- .replace(/^[\\/]{2}(?:localhost|127\.0\.0\.1|\[?::1\]?)[\\/]([a-zA-Z])\$(?=[\\/]|$)/i, '$1:');
740
- let abs = path.resolve(base || process.cwd(), spelled);
741
- if (win) {
742
- const drive = /^[a-zA-Z]:|^\\\\[^\\]+\\[^\\]+/.exec(abs)?.[0] ?? '';
743
- abs = drive + abs.slice(drive.length).split('\\').map((s) => s.replace(/:.*$/, '').replace(/[. ]+$/, '')).join('\\');
744
- }
745
- forms.push(abs, resolvePath(abs));
746
- // A dangling link has no realpath, and a write through it creates its target: follow it by
747
- // hand, each hop through `resolvePath`, because a hop may pass a folder link. Links can loop.
748
- for (let cur = forms[1], hop = 0; hop < 8; hop += 1) {
749
- try { cur = resolvePath(path.resolve(path.dirname(cur), readlinkSync(cur))); forms.push(cur); } catch { break; }
750
- }
751
- }
920
+ const forms = landsOn(p, base);
752
921
  const hit = forms.map(coined).find(Boolean);
753
922
  if (hit) return hit;
754
- // This install's store, the machine tier's (`~/.config/geneseed/memory`) and the two a variable
755
- // points at: a path compare, each store as written and with its links followed.
756
- const stores = [];
757
- if (root) stores.push(path.join(root, 'memory'));
758
- try { stores.push(sharedPaths().memory); } catch { /* no home dir: no shared store to match */ }
759
- if (process.env.GENESEED_HARNESS) stores.push(path.join(process.env.GENESEED_HARNESS, 'memory'));
760
- if (process.env.GENESEED_MEMORY) stores.push(process.env.GENESEED_MEMORY);
761
- const homes = stores.flatMap((s) => [path.resolve(s), resolvePath(s)]).map(normcase);
762
- // `.slice(1)`, so the store dir itself is not one of its own ancestors.
763
- return forms.some((f) => (win ? f.toLowerCase() : f).endsWith('.md')
764
- && selfAndParents(f).slice(1).some((a) => homes.includes(normcase(a)))) ? 'memory' : null;
923
+ // No `cwd` in the payload: the hook runs in the session's directory, so that is the project.
924
+ const at = base || process.cwd();
925
+ const project = gitRootOf(at) ?? path.resolve(at);
926
+ // The install, the machine tier, the project layer, and the homes the two variables name.
927
+ const pinned = process.env.GENESEED_MEMORY ? path.dirname(path.resolve(process.env.GENESEED_MEMORY)) : null;
928
+ const rules = ruleFilesUnder([root, machineDir(), project, process.env.GENESEED_HARNESS, pinned]);
929
+ return forms.some((f) => sameAsRule(f, rules)) ? 'a hard link' : null;
765
930
  } catch {
766
931
  return null;
767
932
  }
768
933
  }
769
934
 
935
+ /**
936
+ * Whether `f` is one of `rules` under a second name: an existing file with more than one name whose
937
+ * device and inode match a known rule file's. A hard link has no target to follow, so this is the only
938
+ * way to see one. bigint stat, because a 64-bit NTFS file id does not fit a double. Only a file that
939
+ * has a second name is compared, and only there does a rule file whose stat fails for any reason but
940
+ * absence count as a match (fail closed). Twin of the guard's, byte for byte.
941
+ */
942
+ function sameAsRule(f, rules) {
943
+ let s;
944
+ try { s = statSync(f, { bigint: true }); } catch { return false; }
945
+ if (!s.isFile() || s.nlink < 2n) return false;
946
+ return rules.some((r) => {
947
+ try { const t = statSync(r, { bigint: true }); return t.dev === s.dev && t.ino === s.ino; } catch (e) {
948
+ return !['ENOENT', 'ENOTDIR'].includes(e?.code);
949
+ }
950
+ });
951
+ }
952
+ // The rule files a session loads, under each home: the install, the machine tier, the project layer.
953
+ const ruleFilesUnder = (homes) => homes.filter(Boolean).flatMap((h) => ['user-rules.md', 'user-rules.draft.md'].map((n) => path.join(h, n)));
954
+
770
955
  // Law I's boundary half is `SECRET_RE` (`./hooks-prims.mjs`, where the activity writer reads it
771
956
  // too). `.env*` is exempt because Law I names it as the place a secret may live.
772
957
  const DOTENV_RE = /(^|[\\/])\.env(\.[^\\/]*)?$/;
@@ -779,8 +964,8 @@ export const SENSOR_LIST = '.geneseed/protected-checks.txt';
779
964
  * edit, or a failing check is one edit away from a passing one. A project opts in by listing
780
965
  * them, one repo-relative path per line (`#` comments), in `.geneseed/protected-checks.txt` at
781
966
  * its git root — found by walking up from the WRITE TARGET, not the cwd, so a session in one repo
782
- * writing into another reads that other repo's list. The list protects itself. Returns the entry
783
- * the path falls under, or null. A write tool's path reaches this through `ruleDecide`, a shell
967
+ * writing into another reads that other repo's list. The list protects itself. Returns the path from
968
+ * its git root, as a person reads it, or null. A write tool's path reaches this through `ruleDecide`, a shell
784
969
  * command's write targets through `shellWriteTargets`, whose docblock names what stays unseen.
785
970
  */
786
971
  function protectedCheck(p) {
@@ -793,14 +978,15 @@ function protectedIn(target) {
793
978
  try {
794
979
  const root = gitRootOf(path.dirname(target));
795
980
  if (!root) return null;
796
- if (normcase(path.relative(root, target)) === normcase(DONE_LIST)) return DONE_LIST;
981
+ const shown = path.relative(root, target);
982
+ if (normcase(shown) === normcase(DONE_LIST)) return shown;
797
983
  const text = readFileSync(path.join(root, SENSOR_LIST), 'utf8');
798
984
  // `normcase` folds case AND slashes on Windows, so both sides go through it, the trailing
799
985
  // separator of the prefix included.
800
- const rel = normcase(path.relative(root, target));
986
+ const rel = normcase(shown);
801
987
  const entries = [SENSOR_LIST, ...text.split(/\r?\n/).map((l) => l.trim().replace(/[\\/]+$/, ''))
802
988
  .filter((l) => l && !l.startsWith('#'))];
803
- return entries.find((e) => rel === normcase(e) || rel.startsWith(normcase(`${e}/`))) ?? null;
989
+ return entries.some((e) => rel === normcase(e) || rel.startsWith(normcase(`${e}/`))) ? shown : null;
804
990
  } catch {
805
991
  return null; // no list (the common case) or an unreadable one: nothing is protected
806
992
  }
@@ -813,7 +999,9 @@ function protectedIn(target) {
813
999
  * * the install root (`--root`): the hook wiring (`settings.json`, `settings.local.json`, Bob
814
1000
  * global's `settings/settings.json` — `claudeWire`), `excludes.json` (`sovereignBypass`), the
815
1001
  * `AGENT.md` gate markers (`Done gate: off`, read by `cmdContext`; every marker is read back
816
- * by a rebuild), and `.geneseed-manifest.json` / `.geneseed-emit` (`globalHookStandingDown`);
1002
+ * by a rebuild; in a `CLAUDE.md` or `AGENTS.md` only the managed block counts, those two are the
1003
+ * user's and are not listed here, and `carrierBlockChange` covers a write tool there), Bob global's
1004
+ * `rules/geneseed.md` (its whole carrier), and `.geneseed-manifest.json` / `.geneseed-emit` (`globalHookStandingDown`);
817
1005
  * * any host project dir the target sits in (`<dir>/.claude/settings.json` and kin, found by
818
1006
  * the parent's — or for `settings/settings.json` the grandparent's — folder name, so a
819
1007
  * monorepo subpackage or a dir with no `.git` is covered): Claude reads project settings
@@ -830,9 +1018,8 @@ function protectedIn(target) {
830
1018
  * (`geneseed exclude`, an emit) writes these with `fs`, never through a write tool, so it is
831
1019
  * not gated. Reached from a shell command too, with the same limit as `protectedCheck`.
832
1020
  */
833
- const GATE_CONFIG_FILES = ['settings.json', 'settings.local.json', 'settings/settings.json', 'excludes.json', 'AGENT.md', '.geneseed-manifest.json', '.geneseed-emit', 'opencode.json', 'opencode.jsonc'];
1021
+ const GATE_CONFIG_FILES = ['settings.json', 'settings.local.json', 'settings/settings.json', 'rules/geneseed.md', 'excludes.json', 'AGENT.md', '.geneseed-manifest.json', '.geneseed-emit', 'opencode.json', 'opencode.jsonc'];
834
1022
  const GATE_CONFIG_MARKERS = ['.claude', '.openclaude', '.bob', '.opencode'];
835
- export const GATE_CONFIG_ASK = 'is a gate\'s own configuration (the hook wiring, the exclusion list, a gate switch or the hook shim). Editing it could switch a check off: fix the code, not the gate, unless the user asks for this edit. Stop and ask the user now; never write it another way (for example through a shell command).';
836
1023
  function gateConfig(p, root) {
837
1024
  let bin = null;
838
1025
  try {
@@ -867,6 +1054,8 @@ function gateConfig(p, root) {
867
1054
  * @returns {string | null} why the write is refused, or null when Geneseed's wiring is untouched
868
1055
  */
869
1056
  const SETTINGS_RE = /(^|[\\/])(settings\.json|settings\.local\.json)$/i;
1057
+ const replaceOnce = (text, search, replace) => (typeof search === 'string' && search && typeof replace === 'string'
1058
+ && text.split(search).length === 2 ? text.replace(search, () => replace) : null);
870
1059
  function settingsAfter(before, payload) {
871
1060
  const ti = payload.tool_input || {};
872
1061
  const tool = payload.tool_name;
@@ -879,16 +1068,14 @@ function settingsAfter(before, payload) {
879
1068
  lines.splice(line === 0 ? lines.length : line - 1, 0, ...ti.content.split('\n'));
880
1069
  return lines.join('\n');
881
1070
  }
882
- const once = (text, search, replace) => (typeof search === 'string' && search && typeof replace === 'string'
883
- && text.split(search).length === 2 ? text.replace(search, () => replace) : null);
884
1071
  if (tool === 'search_and_replace') {
885
1072
  const ranged = ti.use_regex || ti.ignore_case || ti.start_line != null || ti.end_line != null;
886
- return ranged ? null : once(before, ti.search, ti.replace);
1073
+ return ranged ? null : replaceOnce(before, ti.search, ti.replace);
887
1074
  }
888
1075
  if (tool === 'apply_diff' && typeof ti.diff === 'string') {
889
1076
  const blocks = [...ti.diff.matchAll(DIFF_BLOCK_RE)];
890
1077
  let text = before;
891
- for (const [, search, replace] of blocks) if ((text = once(text, search, replace)) === null) return null;
1078
+ for (const [, search, replace] of blocks) if ((text = replaceOnce(text, search, replace)) === null) return null;
892
1079
  // One block only: with several, Bob may apply some and refuse others (its start-line window).
893
1080
  return blocks.length === 1 ? text : null;
894
1081
  }
@@ -927,24 +1114,93 @@ function bobSettingsChange(p, payload) {
927
1114
  return geneseedWiring(a) === geneseedWiring(b) ? null : 'it changes Geneseed\'s own hook entries';
928
1115
  }
929
1116
 
1117
+ /** `p` from its git root, or as written outside any repository. Fails to `p`: it only names the file. */
1118
+ function repoRel(p, payload) {
1119
+ try {
1120
+ const abs = path.resolve(typeof payload?.cwd === 'string' ? payload.cwd : '.', p);
1121
+ const root = gitRootOf(path.dirname(abs));
1122
+ return root ? path.relative(root, abs) : p;
1123
+ } catch { return p; }
1124
+ }
1125
+
1126
+ // The largest text a line count reads. This is a blocking path, and the count is only a courtesy.
1127
+ const ASK_COUNT_MAX = 1024 * 1024;
1128
+
1129
+ /**
1130
+ * The `editPairs` of a write the gate will ask about, for the line count, or undefined for none. Run
1131
+ * only then, because `Write`'s old text is a file read. A pair says nothing of how often it applies,
1132
+ * so a `replace_all` and a `search_and_replace` count nothing, and a notebook cell names no old text.
1133
+ * A `diff` counts nothing either: the agent writes it, and `DIFF_BLOCK_RE` took 20 s on 80 KB of
1134
+ * opened blocks. A count must cost no verdict, so whatever is not a small regular file, or cannot be
1135
+ * read, counts nothing. Only a file that is truly absent is a new file.
1136
+ */
1137
+ function askPairs(payload, p) {
1138
+ const ti = payload.tool_input;
1139
+ const many = Array.isArray(ti.edits) && ti.edits.some((e) => e && e.replace_all);
1140
+ if (many || ti.replace_all || ti.diff !== undefined || typeof ti.search === 'string'
1141
+ || typeof ti.new_source === 'string') return undefined;
1142
+ try {
1143
+ let whole = '';
1144
+ if (/write/i.test(String(payload.tool_name))) {
1145
+ const file = landsOn(p, typeof payload.cwd === 'string' ? payload.cwd : null).at(-1);
1146
+ const stat = statSync(file, { throwIfNoEntry: false });
1147
+ if (stat && (!stat.isFile() || stat.size > ASK_COUNT_MAX)) return undefined;
1148
+ if (stat) whole = readFileSync(file, 'utf8');
1149
+ }
1150
+ const pairs = editPairs(ti, whole);
1151
+ return pairs.flat().some((t) => t.length > ASK_COUNT_MAX) ? undefined : pairs;
1152
+ } catch { return undefined; }
1153
+ }
1154
+
1155
+ /** Past this a carrier is not replayed: it asks. */
1156
+ const CARRIER_REPLAY_CAP = 1024 * 1024;
1157
+ /** The file after a write tool's call, as `settingsAfter` rebuilds it, plus Claude's Edit. */
1158
+ function carrierAfter(before, payload) {
1159
+ const ti = payload.tool_input || {};
1160
+ if (payload.tool_name !== 'Edit') return settingsAfter(before, payload);
1161
+ if (ti.replace_all !== true) return replaceOnce(before, ti.old_string, ti.new_string);
1162
+ const { old_string: old, new_string: now } = ti;
1163
+ return typeof old === 'string' && old && typeof now === 'string' && before.includes(old)
1164
+ ? before.split(old).join(now) : null;
1165
+ }
1166
+
930
1167
  /**
931
- * External Gate on one write target, by tool or by shell: why it must be asked about, or null.
1168
+ * External Gate on a write tool aimed at a shared carrier: true when the call changes the managed
1169
+ * block as `gateCarrierText` reads it, or cannot be shown not to. Structural, not a match on marker
1170
+ * lines, which a two-step edit, a lone CR or a fake block all beat. An edit outside the block
1171
+ * is the user's own and stays silent. shortcut: a shell write has no replay here, so a shell edit
1172
+ * inside or before the block passes; docs/concepts/exclusions.md states the limit.
1173
+ */
1174
+ function carrierBlockChange(p, payload) {
1175
+ const abs = path.resolve(typeof payload.cwd === 'string' ? payload.cwd : '.', carrierName(p));
1176
+ if (!isSharedCarrier(abs) && !isSharedCarrier(resolvePath(abs))) return false;
1177
+ let before = '';
1178
+ try {
1179
+ if (statSync(abs).size > CARRIER_REPLAY_CAP) return true;
1180
+ before = readFileSync(abs, 'utf8');
1181
+ } catch (e) {
1182
+ if (e?.code !== 'ENOENT') return true;
1183
+ }
1184
+ const after = carrierAfter(before, payload);
1185
+ return after === null || after.length > CARRIER_REPLAY_CAP || carrierBlock(after) !== carrierBlock(before);
1186
+ }
1187
+
1188
+ /**
1189
+ * External Gate on one write target, by tool or by shell: the `gateText` id and facts to ask with, or null.
932
1190
  * On Bob a hook-settings file is the user's shared host config, refused only when the write
933
1191
  * touches Geneseed's wiring (`bobSettingsChange`), and it never reads `opencode.json(c)`.
934
1192
  */
935
1193
  function externalGate(args, p, payload) {
1194
+ // `--no-external-gate`: the install switched this hook off. Both callers end here, so the write
1195
+ // tools, the shell path and Bob stand down at once; the store, secret and loss checks do not.
1196
+ if (args.noExternalGate) return null;
936
1197
  const sensor = protectedCheck(p);
937
- if (sensor) {
938
- return `Geneseed (External Gate) — ${p} is a protected check (${sensor === DONE_LIST
939
- ? 'the done gate list itself' : `${sensor}, listed in ${SENSOR_LIST}`}). A check the agent can `
940
- + 'edit is not a check: fix the code, not the check, unless the user asks for this edit.';
941
- }
1198
+ if (sensor) return { id: 'check', name: sensor };
942
1199
  if (HOST === 'bob' && /^opencode\.jsonc?$/i.test(path.basename(p))) return null;
943
1200
  if (!gateConfig(p, args.root)) return null;
944
1201
  const why = HOST === 'bob' && SETTINGS_RE.test(p) ? bobSettingsChange(p, payload) : '';
945
1202
  if (why === null) return null;
946
- return `Geneseed (External Gate) — ${p} ${GATE_CONFIG_ASK}`
947
- + (why ? ` On Bob this write is refused because ${why}.` : '');
1203
+ return { id: 'config', name: repoRel(p, payload), bobWhy: why };
948
1204
  }
949
1205
 
950
1206
  /**
@@ -1011,31 +1267,33 @@ function ruleDecide(args, payload) {
1011
1267
  // this check stands down; the protected checks and process 1 below still run.
1012
1268
  const carrier = paths.find((p) => !DOTENV_RE.test(p));
1013
1269
  if (!args.noSecretsGate && body && carrier && SECRET_RE.test(body)) {
1014
- return ask(args, 'rule-gate', 'law-1', `Geneseed (Sealed Secrets) — ${carrier} would carry a `
1015
- + 'credential-shaped string. Secrets live in .env or a secret manager, never in a '
1016
- + 'tracked file.');
1270
+ return ask(args, 'rule-gate', 'law-1', 'secret', { name: repoRel(carrier, payload) });
1017
1271
  }
1018
1272
  // Bob routes reads here too (`read_file` carries a path): only a write is External Gate's business.
1019
1273
  // shortcut: a write is told by its tool name, so a Bob write tool named outside WRITE_NAME_RE
1020
1274
  // passes both gates; switch to an allowlist of Bob's read tools if Bob adds or renames one.
1021
1275
  const bobRead = HOST === 'bob' && !WRITE_NAME_RE.test(String((payload && payload.tool_name) || ''));
1022
- const external = !bobRead && paths.map((p) => externalGate(args, p, payload)).find(Boolean);
1023
- if (external) return ask(args, 'rule-gate', 'rigor-5', external);
1024
- // A read on Bob names the store too, and that is no write to refuse.
1025
- const target = bobRead ? null : paths.map((p) => ruleGateTarget(p, args.root, payload && payload.cwd)).find(Boolean);
1276
+ for (const q of bobRead ? [] : paths) {
1277
+ // The carrier rule is a write tool's alone: a shell call reaches `externalGate` with nothing to replay.
1278
+ const hit = externalGate(args, q, payload)
1279
+ ?? (!args.noExternalGate && carrierBlockChange(q, payload) ? { id: 'config', name: repoRel(q, payload), bobWhy: '' } : null);
1280
+ if (hit) return ask(args, 'rule-gate', 'rigor-5', hit.id, { ...hit, pairs: askPairs(payload, q) });
1281
+ }
1282
+ // A read on Bob names the store too, and that is no write to refuse. `--no-rule-store`: process 1
1283
+ // is excluded (or its pack off), so a rule write is ordinary work and the gates below still judge it.
1284
+ const stored = bobRead || args.noRuleStore ? null : paths.find((q) => ruleGateTarget(q, args.root, payload && payload.cwd));
1026
1285
  const p = paths[0];
1027
- if (!target) {
1286
+ if (!stored) {
1028
1287
  // The ownership first-write gate (./ownership-gate.mjs), last: every rule above outranks it.
1029
1288
  // `--no-ownership-gate`: the install switched it off (D25).
1030
1289
  const why = args.noOwnershipGate ? null : ownershipBlock(p, payload, body, args.root);
1031
1290
  if (why) return deny(args, 'rule-gate', 'ownership', why);
1032
1291
  // Only here: stdout carries one document, and an ask or a deny above already holds it.
1033
- if (!bobRead) testWeakenedNote(p, payload);
1292
+ if (!bobRead && !args.noTestNote) testWeakenedNote(p, payload);
1034
1293
  return 0;
1035
1294
  }
1036
- return ask(args, 'rule-gate', 'process-1', `Geneseed (Persist Insight) \u2014 writing to `
1037
- + `${target}: a standing rule, or a fact to remember? That choice is the user's. `
1038
- + (HOST === 'bob' ? PERSIST_BOB : PERSIST_ASK));
1295
+ return ask(args, 'rule-gate', 'process-1', 'store',
1296
+ { name: ruleGateTarget(stored, args.root, payload && payload.cwd), pairs: askPairs(payload, stored) });
1039
1297
  }
1040
1298
  export const cmdRuleGate = guardGate(ruleGate, 'rule-gate');
1041
1299