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
@@ -9,8 +9,9 @@
9
9
  // - Deletion Is Deliberate: block catastrophic shell commands, and every command that would
10
10
  // really lose data, judged against the repository's state (`lossReason`, below).
11
11
  // - Commands Must Return: block a recursive scan rooted at a whole filesystem (find /).
12
- // - Persist Insight (rule vs memory): a write to user-rules.md or a memory file needs the
12
+ // - Persist Insight (standing rules): a write to user-rules.md or the rule draft needs the
13
13
  // HOST's own prompt (`permission.edit`; on V2 the `evaluate` hook too); with none, it is refused.
14
+ // Memory is written freely (owner decision, 2026-11-08); the change report still sees it.
14
15
  // - Wiki (AGENT.md §8): block mutations under a declared wiki's `protected`
15
16
  // folders — the user's knowledge base sets its own no-go zones in geneseed-wiki.jsonc.
16
17
  // - Ownership: in an application repo whose root AGENTS.md has no `## Ownership` section,
@@ -163,6 +164,28 @@ const DELETION_GATE_OFF = gateOff("Deletion gate")
163
164
  const SECRETS_GATE_OFF = gateOff("Secrets gate")
164
165
  // `--no-ownership-gate` (ruling D25): the ownership first-write gate below stands down.
165
166
  const OWNERSHIP_GATE_OFF = gateOff("Ownership gate")
167
+ // `--no-external-gate`: `protectedCheck`, `gateConfig` and `nativeAskFile` below all answer no, so the
168
+ // refusals and V2's `evaluate` ask stand down. The static `permission.edit` keys are host config: they stay.
169
+ const EXTERNAL_GATE_OFF = gateOff("External gate")
170
+ // A rule whose hook goes with its text (owner decision, 2026-11-08), read off the same carrier's
171
+ // `Active packs:` and `Excluded rules:` lines, the state the hook hosts get as `--no-rule-store` /
172
+ // `--no-root-scan` (`ruleOn`, js/hosts/settings.mjs). Twin of `doctrinesOfDir` / `excludedRulesOfDir`
173
+ // (js/hosts/installs.mjs), fail closed both ways: a missing or unreadable pack line is every pack, a
174
+ // malformed exclusion line excludes nothing. `PACKS` is js/build/source.mjs's PACK_ORDER.
175
+ const PACKS = ["craft", "rigor", "ops", "process", "comms"]
176
+ function ruleOff(pack, n) {
177
+ const packs = /^Active packs:[ \t]*(.+?)[ \t]*$/m.exec(CARRIER_TEXT)?.[1]?.trim()
178
+ const named = packs === "none" ? [] : packs?.split(",").map((s) => s.trim())
179
+ if (named && named.every((p) => PACKS.includes(p)) && !named.includes(pack)) return true
180
+ const ex = /^Excluded rules:[ \t]*(.+?)[ \t]*$/m.exec(CARRIER_TEXT)?.[1]?.split(",").map((s) => s.trim()) ?? []
181
+ return ex.every((e) => /^[a-z]+[ \t]+\d+$/.test(e) && PACKS.includes(e.split(/[ \t]+/)[0]))
182
+ && ex.some((e) => e.split(/[ \t]+/)[0] === pack && Number(e.split(/[ \t]+/)[1]) === n)
183
+ }
184
+ // Persist Insight off: `ruleTarget` answers no, so every rule-store refusal and V2's `evaluate` ask
185
+ // stand down; the change report still reports a rule-file change (`tool.execute.after` excuses none).
186
+ const RULE_STORE_OFF = ruleOff("process", 1)
187
+ // Commands Must Return off: the root-scan refusal stands down.
188
+ const ROOT_SCAN_OFF = ruleOff("ops", 2)
166
189
 
167
190
  // OpenCode 1.x paints a plugin's stderr over its TUI input box (in red); its own log API
168
191
  // writes to the log file instead. The V1 entry sets LOG_CLIENT; V2 and tests have no
@@ -1014,6 +1037,276 @@ function catastrophic(command, split, depth = 0) {
1014
1037
  }
1015
1038
  // ---- loss twin: END
1016
1039
 
1040
+ // ---- gate text twin: BEGIN — adapters/opencode/plugins/geneseed-guard.js carries everything down to
1041
+ // the END marker verbatim, with `export ` dropped (tests/plugins/guard.test.mjs diffs the two).
1042
+
1043
+ /**
1044
+ * What each protected check is, for a person who has not read the diff: the files, what they are,
1045
+ * what an edit can do. Fixed text, so the governed agent cannot write its own case. A file is written
1046
+ * as `CANDIDATES` (`./geneseed-dir.mjs`) writes it, so tests/unit/gate_text.test.mjs compares the
1047
+ * two entry by entry, both ways: a string ending `/` is a folder, any other string a file, a regex
1048
+ * a file name.
1049
+ * @type {[(string | RegExp)[], string, string][]}
1050
+ */
1051
+ const GATE_FILES = [
1052
+ [['.github/workflows/', '.gitlab-ci.yml', 'Jenkinsfile', 'azure-pipelines.yml', '.circleci/'],
1053
+ 'which defines the checks that run on every push',
1054
+ 'those checks can get weaker or stop running, and a failure could go unseen'],
1055
+ [[/^eslint\.config\./, /^\.eslintrc/, 'biome.json', 'biome.jsonc', 'ruff.toml', '.golangci.yml', 'checkstyle.xml'],
1056
+ 'which sets the rules the linter enforces',
1057
+ 'those rules can get weaker, and bad code could pass unseen'],
1058
+ [['tsconfig.json'],
1059
+ 'which sets how strictly types are checked',
1060
+ 'the type checks can get weaker, and a type error could pass unseen'],
1061
+ [[/^jest\.config\./, /^vitest\.config\./, 'pytest.ini'],
1062
+ 'which decides how the tests run',
1063
+ 'tests can be skipped or loosened, and a failure could go unseen'],
1064
+ [['package.json', 'pom.xml', 'build.gradle', 'build.gradle.kts', 'pyproject.toml', 'Cargo.toml', 'go.mod'],
1065
+ 'which names the commands that test this project',
1066
+ 'those commands can change, and a failing test could read as a pass'],
1067
+ ];
1068
+ /**
1069
+ * Protected by being the lists themselves, so they are in no seed and stay outside `GATE_FILES`. Read
1070
+ * at the repo root only: a `packages/a/.geneseed/done-checks.txt` someone listed feeds no gate.
1071
+ * @type {[string, string, string][]}
1072
+ */
1073
+ const GATE_LISTS = [
1074
+ ['.geneseed/protected-checks.txt', 'which lists the files this gate protects',
1075
+ 'a check can lose its protection, and nothing would tell you'],
1076
+ ['.geneseed/done-checks.txt', 'which lists the checks that must pass before work counts as done',
1077
+ 'work could count as done without passing a check'],
1078
+ ];
1079
+ // Matches at any depth: a user may list `packages/a/tsconfig.json`, and it is still a tsconfig.
1080
+ const gateIs = (rel, file) => {
1081
+ if (typeof file !== 'string') return file.test(rel.slice(rel.lastIndexOf('/') + 1));
1082
+ return file.endsWith('/') ? `/${rel}`.includes(`/${file}`) : `/${rel}`.endsWith(`/${file}`);
1083
+ };
1084
+ const GATE_FILE_OTHER = [null, 'which this project lists as a protected check',
1085
+ 'that check can get weaker or stop running, and a failure could go unseen'];
1086
+
1087
+ // `ruleGateTarget`'s answers: name, what it is, what the safe line calls it, whose call it is, impact.
1088
+ // Memory has none: it is written freely (owner decision, 2026-11-08).
1089
+ const GATE_RULE = ['this rule', 'what becomes a rule'];
1090
+ const GATE_STORES = {
1091
+ 'user-rules.md': ['user-rules.md', 'your standing rules, which the agent obeys in every session', ...GATE_RULE,
1092
+ 'the text binds every later session until you remove it'],
1093
+ 'the rule draft': ['the rule draft', 'which can become one of your standing rules', ...GATE_RULE,
1094
+ 'the text can become a rule that binds every later session'],
1095
+ 'a hard link': ['a second name of a rule file', 'which writes to your standing rules or the rule draft', ...GATE_RULE,
1096
+ 'the text can bind every later session until you remove it'],
1097
+ };
1098
+
1099
+ // Bidi and zero-width marks too (`\p{C}`): they make a name read as something it is not. A double
1100
+ // quote of any shape turns to `'`, or a name could seem to close its own quotes.
1101
+ const gateStrip = (v) => String(v ?? '').replace(/[\p{C}\p{Zl}\p{Zp}]/gu, '').replace(/["\u201C-\u201F\uFF02]/g, "'").trim();
1102
+
1103
+ /**
1104
+ * An agent-supplied value in the human part. Clipped in the middle, because the end of a path names
1105
+ * the file. Quotes mark a name; they do not stop one reading like a sentence. `...` is ASCII so that
1106
+ * clipping alone does not force the quotes.
1107
+ */
1108
+ function gateName(value) {
1109
+ const c = [...gateStrip(value)];
1110
+ const text = c.length > 60 ? `${c.slice(0, 20).join('')}...${c.slice(-37).join('')}` : c.join('');
1111
+ return /^[A-Za-z0-9._/-]+$/.test(text) ? text : `"${text}"`;
1112
+ }
1113
+
1114
+ const gatePath = (p) => String(p ?? '').replace(/\\/g, '/');
1115
+ // Every line end a viewer may honour: a line break that this missed would hide a line from the count.
1116
+ const gateLines = (text) => {
1117
+ const lines = text.split(/\r\n|[\r\n\u2028\u2029]/);
1118
+ if (lines[lines.length - 1] === '') lines.pop();
1119
+ return lines;
1120
+ };
1121
+
1122
+ /**
1123
+ * ` (+3 lines, -1 line)` from `editPairs`, or nothing when no line differs. Each pair loses its common
1124
+ * leading and trailing lines. Exact for one changed region; with several it overstates, and it
1125
+ * never hides a change. A pair says nothing of how often it applies, so a caller whose input has
1126
+ * `replace_all`, at the top or in an `edits` entry, passes no pairs and no count shows: the agent sets
1127
+ * that flag, and a 40-place edit must not read as `+1 line, -1 line`.
1128
+ */
1129
+ function gateCount(pairs) {
1130
+ let added = 0;
1131
+ let removed = 0;
1132
+ for (const [before, after] of pairs) {
1133
+ const a = gateLines(before);
1134
+ const b = gateLines(after);
1135
+ const most = Math.min(a.length, b.length);
1136
+ let head = 0;
1137
+ while (head < most && a[head] === b[head]) head += 1;
1138
+ let tail = 0;
1139
+ while (tail < most - head && a[a.length - 1 - tail] === b[b.length - 1 - tail]) tail += 1;
1140
+ removed += a.length - head - tail;
1141
+ added += b.length - head - tail;
1142
+ }
1143
+ const n = (sign, v) => `${sign}${v} line${v === 1 ? '' : 's'}`;
1144
+ const parts = [...(added ? [n('+', added)] : []), ...(removed ? [n('-', removed)] : [])];
1145
+ return parts.length ? ` (${parts.join(', ')})` : '';
1146
+ }
1147
+
1148
+ const gateEdit = (f, shown, what) => `${f.shell ? 'This command writes to' : 'This edit changes'} ${shown}`
1149
+ + `${f.pairs ? gateCount(f.pairs) : ''}, ${what}.`;
1150
+
1151
+ const GATE_ELSEWHERE = 'This command runs on another repository, through --git-dir or --work-tree, which the gate did not read.';
1152
+ const GATE_DO_IT = 'You can make this change yourself, outside the agent.';
1153
+ const GATE_RUN_IT = 'You can run this command yourself, outside the agent.';
1154
+ const GATE_EXTERNAL = { rule: 'External Gate', safe: 'Deny, unless you asked for this change.',
1155
+ tail: 'do not write this file another way', can: GATE_DO_IT };
1156
+ const GATE_LOSS = { rule: 'Deletion Is Deliberate', quote: true, can: GATE_RUN_IT };
1157
+
1158
+ // `quote` marks the only asks that may carry the agent's words. External Gate, Sealed Secrets and
1159
+ // Persist Insight never do: there the agent's opinion is the conflict of interest.
1160
+ const GATE_ASKS = {
1161
+ check: (f) => {
1162
+ const rel = gatePath(f.name);
1163
+ const [, what, impact] = GATE_LISTS.find(([list]) => list === rel)
1164
+ ?? GATE_FILES.find(([files]) => files.some((n) => gateIs(rel, n))) ?? GATE_FILE_OTHER;
1165
+ return { ...GATE_EXTERNAL, line: gateEdit(f, gateName(rel), what), impact,
1166
+ why: 'the agent\'s own work is judged by this file' };
1167
+ },
1168
+ config: (f) => ({ ...GATE_EXTERNAL, line: gateEdit(f, gateName(gatePath(f.name)), 'which controls the gates that watch the agent'),
1169
+ why: 'a gate the agent can edit is a gate it can switch off',
1170
+ impact: 'a gate can stop working, and nothing would tell you' }),
1171
+ store: (f) => {
1172
+ const [name, what, label, owner, impact] = GATE_STORES[f.name] ?? GATE_STORES['user-rules.md'];
1173
+ return { rule: 'Persist Insight', line: gateEdit(f, name, what), safe: `Deny, unless you asked for ${label}.`,
1174
+ why: `${owner} is your decision`, impact, tail: 'ask the user; do not write it another way', can: GATE_DO_IT };
1175
+ },
1176
+ secret: (f) => ({ rule: 'Sealed Secrets', line: `This edit puts a credential-shaped string in ${gateName(gatePath(f.name))}.`,
1177
+ safe: 'Deny, then keep the value in .env or a secret manager.',
1178
+ why: 'a secret in a tracked file reaches everyone who can read the repository',
1179
+ impact: 'the secret can land in a commit, and then it must be rotated',
1180
+ tail: 'keep the value in .env; do not write it another way',
1181
+ can: 'You can put the value in .env or a secret manager yourself.' }),
1182
+ 'force-push': (f) => ({ ...GATE_LOSS, line: `This command force-pushes the protected branch ${gateName(f.name)} on the remote.`,
1183
+ safe: 'Deny, then push without --force.', why: 'a force push replaces the remote history',
1184
+ impact: 'commits that exist only on the remote can be lost for everyone',
1185
+ can: 'You can push without --force, or run this command yourself.' }),
1186
+ 'branch-delete': (f) => ({ ...GATE_LOSS, line: `This command deletes the protected branch ${gateName(f.name)}.`,
1187
+ safe: 'Deny, unless you mean to remove this branch.', why: 'the project depends on a protected branch',
1188
+ impact: 'commits that only this branch holds can be lost for everyone' }),
1189
+ 'remote-branches': () => ({ ...GATE_LOSS, line: 'This command rewrites or deletes many remote branches, protected ones included.',
1190
+ safe: 'Deny, then push one named branch.', why: 'it makes the remote match this repository, branch by branch',
1191
+ impact: 'branches and commits that exist only on the remote can be lost for everyone' }),
1192
+ 'discard-work': () => ({ ...GATE_LOSS, line: 'This command discards uncommitted changes that git cannot bring back.',
1193
+ safe: 'Deny, then commit or stash the work first.', why: 'uncommitted work exists nowhere else',
1194
+ impact: 'those changes are gone for good' }),
1195
+ 'lose-commits': () => ({ ...GATE_LOSS, line: 'This command drops commits that no remote and no other branch holds.',
1196
+ safe: 'Deny, then keep them on a branch first.', why: 'those commits exist only here',
1197
+ impact: 'only the reflog can bring them back, and only for a while' }),
1198
+ // Git's safety net itself, so `lose-commits`' reflog line would be false here.
1199
+ 'drop-recovery': () => ({ ...GATE_LOSS, line: 'This command deletes the history git uses to recover lost commits.',
1200
+ safe: 'Deny, unless you mean to give up that recovery.', why: 'it is the last copy of work lost earlier',
1201
+ impact: 'commits lost earlier can never come back' }),
1202
+ 'delete-files': () => ({ ...GATE_LOSS, line: 'This command deletes files that git cannot restore.',
1203
+ safe: 'Deny, unless you know these files can go.', why: 'git holds no copy of them',
1204
+ impact: 'those files are gone for good' }),
1205
+ unverified: () => ({ ...GATE_LOSS, line: 'This command may lose data, and the gate could not work out what it removes.',
1206
+ safe: 'Deny, unless you have checked the command yourself.', why: 'the gate cannot read what this command touches',
1207
+ impact: 'data that nothing else holds could be lost' }),
1208
+ catastrophic: (f) => ({ ...GATE_LOSS,
1209
+ line: `This command, ${gateName(f.name)}, would destroy a filesystem root, a drive, the home directory or a whole disk.`,
1210
+ safe: 'Deny.', why: 'nothing could restore what it removes', impact: 'everything under that path is gone for good',
1211
+ can: 'You can check what this command was meant to remove.' }),
1212
+ 'root-scan': (f) => ({ rule: 'Commands Must Return', quote: true, line: `This command, ${gateName(f.name)}, scans a whole filesystem root.`,
1213
+ safe: 'Deny, then search a specific directory.', why: 'a whole root spans every drive',
1214
+ impact: 'the scan can run for hours', tail: 'search one named directory',
1215
+ can: 'You can name the directory to search.' }),
1216
+ // Routine and frequent, so one line: three more would train the user to stop reading all of them.
1217
+ commit: () => ({ rule: 'Consent Before Push', quote: true, short: true,
1218
+ line: 'This command commits or pushes with git, which needs your approval each time.',
1219
+ why: 'every commit and push is your decision', can: GATE_RUN_IT }),
1220
+ // The next four are the OpenCode guard's alone: no hook reads a key path, a stream, a wiki manifest
1221
+ // or an unknown tool's arguments, and the guard only refuses them. `wiki` has no rule to name.
1222
+ 'secret-file': (f) => ({ rule: 'Sealed Secrets', line: `This edit writes to ${gateName(gatePath(f.name))}, a file that holds a secret or key.`,
1223
+ safe: 'Deny, then change this file yourself.', why: 'a secret or key file is never for the agent to write',
1224
+ impact: 'the agent can replace a key that grants access', tail: 'leave this file alone', can: GATE_DO_IT }),
1225
+ stream: (f) => ({ ...GATE_EXTERNAL, line: `This edit names ${gateName(gatePath(f.name))}, an NTFS stream that writes through to the file it hangs on.`,
1226
+ safe: 'Deny, then have the agent name the file itself.', why: 'a stream hides which file really changes',
1227
+ impact: 'a file can change with no gate seeing its name', tail: 'name the file itself' }),
1228
+ wiki: (f) => ({ line: `This edit changes the protected wiki folder ${gateName(f.name)}.`,
1229
+ safe: 'Deny, unless you asked for this change.', why: 'you marked this folder as closed to the agent',
1230
+ impact: 'notes you protected can change', tail: 'leave this folder alone', can: GATE_DO_IT }),
1231
+ 'deep-args': (f) => ({ rule: 'Persist Insight', line: `The arguments of ${gateName(f.name)} nest too deep to read, so a write to your rules cannot be ruled out.`,
1232
+ safe: 'Deny, unless you know what this call writes.', why: 'what the gate cannot read, it cannot clear',
1233
+ impact: 'the call can write to your rules unseen', tail: 'ask the user; do not write it another way', can: GATE_DO_IT }),
1234
+ // It reports a crash, not a change, so it has no rule to name.
1235
+ 'gate-error': (f) => ({ line: `Geneseed gate error: the check failed with ${gateName(f.name)}, so nothing judged this call.`,
1236
+ safe: 'Deny, then run geneseed doctor.', why: 'a gate that crashed cannot say this call is safe',
1237
+ impact: 'this call runs with no check at all', can: 'You can run geneseed doctor to find the fault.' }),
1238
+ };
1239
+
1240
+ /**
1241
+ * The text a gate shows, one sentence per line, so it reads the same if a host folds the newlines.
1242
+ * `mode` is `ask` (a person can answer), `refused` (nothing can be allowed and the model is the only
1243
+ * reader, so it must relay the words) or `warned` (the call runs anyway). `facts` is `name` (the path,
1244
+ * branch, command excerpt, error or `ruleGateTarget` answer), `pairs` (`editPairs`, for the count),
1245
+ * `shell` (reached through a command, which has no count), `says` (the call's own `description`) and
1246
+ * `redirected` (`gateLoss`'s: the loss the text names was read from a repository the command leaves).
1247
+ * The safe choice is line 2, so it stays in the part of a dialog that shows without scrolling. The
1248
+ * caller adds the host's wrapping: Bob's `[geneseed]` prefix and `BOB_FINAL` are not here.
1249
+ */
1250
+ function gateText(id, mode, facts = {}) {
1251
+ const a = GATE_ASKS[id](facts);
1252
+ const tag = a.rule ? ` (${a.rule})` : '';
1253
+ // After the safe choice, so that it keeps its place in the part of a dialog that shows.
1254
+ const far = facts.redirected ? [GATE_ELSEWHERE] : [];
1255
+ if (mode === 'warned') return `${a.line}${tag}\nThis ran without a prompt, because Bob has no approval step.`;
1256
+ if (mode === 'refused') {
1257
+ return [`Tell the user this, word for word: ${a.line}`, ...far, `It was refused because ${a.why}.${tag}`, a.can,
1258
+ ...(a.tail ? [`Agent: ${a.tail}.`] : [])].join('\n');
1259
+ }
1260
+ const c = [...(a.quote ? gateStrip(facts.says) : '')];
1261
+ return [...(a.short ? [`${a.line}${tag}`]
1262
+ : [a.line, `Safe choice: ${a.safe}${tag}`, ...far, `It asks because ${a.why}.`, `If you allow it, ${a.impact}.`]),
1263
+ ...(c.length ? [`The agent says (not checked): "${c.length > 100 ? `${c.slice(0, 97).join('')}...` : c.join('')}"`] : []),
1264
+ ...(a.tail ? [`Agent: if refused, ${a.tail}.`] : [])].join('\n');
1265
+ }
1266
+
1267
+ // Said when `gateText` itself fails. It fits every mode, so nothing about it can fail.
1268
+ const GATE_UNSAID = 'Geneseed could not describe this call. Check what it does before you trust it.';
1269
+
1270
+ /**
1271
+ * `gateText` that cannot throw, and the only way a gate reaches it. Every catch around a gate is a
1272
+ * pass or a lesser verdict (`guardGate`, a shell reader, the guard's own), so a bug in the words would
1273
+ * otherwise change what the gate decides.
1274
+ */
1275
+ function gateSafe(id, mode, facts) {
1276
+ try { return gateText(id, mode, facts); } catch { return GATE_UNSAID; }
1277
+ }
1278
+
1279
+ // `lossReason`'s sentences, by their fixed parts only: the rest is the agent's command, so a pattern
1280
+ // anchored there could be steered. Order matters: `git clean` ends in an agent's path.
1281
+ /** @type {[RegExp, string][]} */
1282
+ const GATE_LOSS_REASONS = [
1283
+ [/^the gate could not verify /, 'unverified'],
1284
+ [/^`git push --(?:mirror|prune)` |^a forced `git push --all` /, 'remote-branches'],
1285
+ [/^`git push` would force-push the protected branch (.+)$/, 'force-push'],
1286
+ [/^`git (?:push|branch -D)\b.* (?:would delete|deletes) the protected branch (.+)$/, 'branch-delete'],
1287
+ [/^`git clean` would delete untracked files | which (?:nothing could|git cannot) restore$| deletes git's own data$| deletes a whole repository or worktree$/, 'delete-files'],
1288
+ [/ would discard uncommitted changes \(.*\)$| deletes stashed work$/, 'discard-work'],
1289
+ [/ recovery depends on$/, 'drop-recovery'],
1290
+ [/ holds$/, 'lose-commits'],
1291
+ ];
1292
+
1293
+ /**
1294
+ * The `gateText` id, branch and `redirected` flag for a `lossReason` sentence. One this table does not
1295
+ * know reads as `unverified`, the most cautious text; tests/unit/gate_text.test.mjs holds every
1296
+ * sentence to an id.
1297
+ */
1298
+ function gateLoss(reason) {
1299
+ const direct = reason.replace(/ \(and --git-dir\/--work-tree points it at a repository the gate did not read\)$/, '');
1300
+ const redirected = direct !== reason;
1301
+ const text = direct.replace(/ on the protected branch \S*$/, '');
1302
+ for (const [re, id] of GATE_LOSS_REASONS) {
1303
+ const m = re.exec(text);
1304
+ if (m) return { id, name: m[1], redirected };
1305
+ }
1306
+ return { id: 'unverified', redirected };
1307
+ }
1308
+ // ---- gate text twin: END
1309
+
1017
1310
  // A recursive scan rooted at a whole filesystem (Commands Must Return) → BLOCK. Twin of
1018
1311
  // js/hosts/hooks.mjs's `rootScan` — keep in step; tests/plugins/guard.test.mjs diffs the
1019
1312
  // constants below against it. In Git Bash `/` mounts every drive and share: on 2026-10-10 a
@@ -1329,10 +1622,11 @@ async function protectedPrefixes() {
1329
1622
  return prefixes
1330
1623
  }
1331
1624
 
1332
- // ---- the rule / memory stores (Persist Insight) --------------------------------
1333
- // Whether something the user wants kept is a standing rule or a durable fact is THEIR call, and
1334
- // the HOST asks it, never the agent (External Gate). This was a speed bump: the first write was
1335
- // refused and any re-issue passed, so an agent could release itself by claiming the user's
1625
+ // ---- the rule stores (Persist Insight) -------------------------------------------
1626
+ // A standing rule is the user's call, and the HOST asks it, never the agent (External Gate). A
1627
+ // durable fact is not: memory is written freely and shown afterwards (owner decision, 2026-11-08),
1628
+ // so only `ruleTarget` gates; `ruleStoreTarget` still names memory for the change report.
1629
+ // This was a speed bump: the first write was refused and any re-issue passed, so an agent could release itself by claiming the user's
1336
1630
  // authorization, and one did (2026-11). `tool.execute.before` can only allow or throw, so the
1337
1631
  // prompt comes from what runs AFTER it, inside the host's own edit tools:
1338
1632
  // - V1: `permission.edit` "ask" keys (`opencodeEditAsks`, js/hosts/settings.mjs). V1 calls no
@@ -1346,9 +1640,9 @@ async function protectedPrefixes() {
1346
1640
  // everything else in a command is the host's own command permission's business.
1347
1641
  //
1348
1642
  // Install folder and file names are theme-independent by design, so the match is on
1349
- // literal names. `user-rules.md` / `MEMORY.md` are Geneseed's own coinage and match
1350
- // anywhere; other markdown matches only inside this install's own memory/ dir, so a
1351
- // project's unrelated memory/ folder is never caught.
1643
+ // literal names. `user-rules.md` / `user-rules.draft.md` / `MEMORY.md` are Geneseed's own
1644
+ // coinage and match anywhere; for the change report, other markdown matches only inside this
1645
+ // install's own memory/ dir, so a project's unrelated memory/ folder is never caught.
1352
1646
  const nocase = (s) => (process.platform === "win32" ? s.toLowerCase() : s)
1353
1647
  // The host's own edit tools, the only ones its `edit` permission covers (V1 `edit`, `write`,
1354
1648
  // `apply_patch`; V2 `patch`). The guard's WRITE_TOOLS is a wider substring class, which also
@@ -1362,6 +1656,10 @@ const PERSIST_EDIT_TOOL = "Stop and ask the user now (the rule skill). Only the
1362
1656
  const PERSIST_NO_PROMPT = "Stop and ask the user now (the rule skill). The host has no prompt wired for " +
1363
1657
  "this file, so this write stays refused and re-issuing it changes nothing: leave it for the user " +
1364
1658
  "to write themself, and never write it another way (for example through a shell command)."
1659
+ // What the user reads beside an OpenCode prompt, whose dialog shows no plugin text: the ask's text inside a
1660
+ // delimiter that ties it to the dialog. Without the `Agent:` line, which is no business of the user's.
1661
+ const gateNote = (text) => ["──── Geneseed · about the next permission request ────",
1662
+ ...text.split("\n").filter((l) => !l.startsWith("Agent:")), "──── The dialog below is for this change ────"].join("\n")
1365
1663
  // Whether the merged `permission.edit` makes V1 ask about `rel`, a path from the worktree: its own
1366
1664
  // evaluation, the LAST matching rule, with `Wildcard.match`'s pattern (util/wildcard.ts, 1.19.5).
1367
1665
  function editRuleAsks(edit, rel) {
@@ -1434,7 +1732,7 @@ function storeScan(home, found = {}) {
1434
1732
  const stamp = (f) => {
1435
1733
  try { const s = statSync(f); if (s.isFile()) found[f] = `${s.size}:${Math.trunc(s.mtimeMs)}` } catch { /* absent */ }
1436
1734
  }
1437
- for (const n of ["user-rules.md", "PROFILE.md", "geneseed-wiki.jsonc", "wiki.jsonc", "wiki.json"]) stamp(path.join(home, n))
1735
+ for (const n of ["user-rules.md", "user-rules.draft.md", "PROFILE.md", "geneseed-wiki.jsonc", "wiki.jsonc", "wiki.json"]) stamp(path.join(home, n))
1438
1736
  const walk = (dir) => {
1439
1737
  let items = []
1440
1738
  try { items = readdirSync(dir, { withFileTypes: true }) } catch { return }
@@ -1449,7 +1747,18 @@ function storeScan(home, found = {}) {
1449
1747
 
1450
1748
  // ---- the change report (twin of js/hosts/store-watch.mjs, whose header says why) ---------------
1451
1749
  // It detects; it prevents nothing. Here the baseline lives in memory, for as long as the plugin does.
1452
- const scanAllStores = () => storeHomes().reduce((found, h) => storeScan(h, found), {})
1750
+ // Plus the project layer's two rule files, at the session's git root (else its directory): the twin
1751
+ // of js/hosts/store-watch.mjs's `projectRules`. A repo's own memory/ folder is no store.
1752
+ const scanAllStores = (dir = null) => {
1753
+ const found = storeHomes().reduce((acc, h) => storeScan(h, acc), {})
1754
+ if (!dir) return found
1755
+ const top = gitRootOf(dir) ?? path.resolve(dir)
1756
+ for (const n of ["user-rules.md", "user-rules.draft.md"]) {
1757
+ const p = path.join(top, n)
1758
+ try { const st = statSync(p); if (st.isFile()) found[p] = `${st.size}:${Math.trunc(st.mtimeMs)}` } catch { /* absent */ }
1759
+ }
1760
+ return found
1761
+ }
1453
1762
  const ownWrites = () => storeHomes().reduce((log, h) => {
1454
1763
  try { return { ...log, ...JSON.parse(readFileSync(path.join(h, "memory", ".own-writes.json"), "utf8")) } } catch { return log }
1455
1764
  }, {})
@@ -1457,7 +1766,7 @@ const storeLine = (files) => {
1457
1766
  const shown = files.slice(0, 5).map((f) => f.split(/[\\/]/).slice(-2).join("/")).join(", ")
1458
1767
  const more = files.length > 5 ? ` (+${files.length - 5} more)` : ""
1459
1768
  return `Geneseed change report: ${files.length} rule or memory file${files.length === 1 ? "" : "s"} ` +
1460
- `changed outside this session's approved writes (another session may have made it): ${shown}${more}. This detects a change; it prevented nothing.`
1769
+ `changed outside this session's approved writes (another session, or a decision of yours in the web console, may have made it): ${shown}${more}. This detects a change; it prevented nothing.`
1461
1770
  }
1462
1771
  function noteForStatus(files) {
1463
1772
  try {
@@ -1465,8 +1774,9 @@ function noteForStatus(files) {
1465
1774
  } catch { /* a status line never fails a turn */ }
1466
1775
  }
1467
1776
 
1468
- // The store a write would land in, or null. `base` is the session's directory: a relative path is
1469
- // the tool's, never this process's.
1777
+ // The rule or memory store a write would land in, or null: what the change report excuses after an
1778
+ // approved native edit. `base` is the session's directory: a relative path is the tool's, never
1779
+ // this process's.
1470
1780
  function ruleStoreTarget(p, base) {
1471
1781
  const stores = storeDirs()
1472
1782
  for (const abs of landsOn(p, base)) {
@@ -1477,6 +1787,45 @@ function ruleStoreTarget(p, base) {
1477
1787
  }
1478
1788
  return null
1479
1789
  }
1790
+ // The rule store a write would land in, or null: the gate's question. Every form a write lands on is
1791
+ // read, so a memory file linked to user-rules.md is still a rule write. Twin of js/hosts/hooks.mjs's
1792
+ // `ruleGateTarget`, `sameAsRule` included.
1793
+ const RULE_NAMES = new Set(["user-rules.md", "the rule draft"])
1794
+ /**
1795
+ * Whether `f` is one of `rules` under a second name: an existing file with more than one name whose
1796
+ * device and inode match a known rule file's. A hard link has no target to follow, so this is the only
1797
+ * way to see one. bigint stat, because a 64-bit NTFS file id does not fit a double. Only a file that
1798
+ * has a second name is compared, and only there does a rule file whose stat fails for any reason but
1799
+ * absence count as a match (fail closed). Twin of js/hosts/hooks.mjs's, byte for byte.
1800
+ */
1801
+ function sameAsRule(f, rules) {
1802
+ let s;
1803
+ try { s = statSync(f, { bigint: true }); } catch { return false; }
1804
+ if (!s.isFile() || s.nlink < 2n) return false;
1805
+ return rules.some((r) => {
1806
+ try { const t = statSync(r, { bigint: true }); return t.dev === s.dev && t.ino === s.ino; } catch (e) {
1807
+ return !['ENOENT', 'ENOTDIR'].includes(e?.code);
1808
+ }
1809
+ });
1810
+ }
1811
+ // The rule files a session loads, under each home: the install, the machine tier, the project layer.
1812
+ const ruleFilesUnder = (homes) => homes.filter(Boolean).flatMap((h) => ['user-rules.md', 'user-rules.draft.md'].map((n) => path.join(h, n)));
1813
+ function ruleTarget(p, base) {
1814
+ if (RULE_STORE_OFF) return null
1815
+ const forms = landsOn(p, base)
1816
+ for (const abs of forms) {
1817
+ const hit = coined(path.basename(abs))
1818
+ if (RULE_NAMES.has(hit)) return hit
1819
+ }
1820
+ // This install's homes, the machine tier and `$GENESEED_HARNESS` (`storeHomes`), the home of the store
1821
+ // `$GENESEED_MEMORY` names, and the project layer at the session's git root.
1822
+ // No session directory: this process's, as the hook twin falls back to its own.
1823
+ const at = base || process.cwd()
1824
+ const project = gitRootOf(at) ?? path.resolve(at)
1825
+ const pinned = process.env.GENESEED_MEMORY ? path.dirname(path.resolve(process.env.GENESEED_MEMORY)) : null
1826
+ const rules = ruleFilesUnder([...storeHomes(), project, pinned])
1827
+ return forms.some((f) => sameAsRule(f, rules)) ? "a hard link" : null
1828
+ }
1480
1829
  // Whether the merged `permission.edit`'s pattern `k` matches `rel`: V1's `Wildcard.match` (1.19.5).
1481
1830
  const wildMatch = (k, s) => new RegExp(`^${k.replace(/\\/g, "/").replace(/[.+^${}()|[\]\\]/g, "\\$&")
1482
1831
  .replace(/\*/g, ".*").replace(/\?/g, ".")}$`, process.platform === "win32" ? "si" : "s").test(s)
@@ -1494,6 +1843,7 @@ const SENSOR_LIST = ".geneseed/protected-checks.txt"
1494
1843
  // without a protected-checks list: emptying it would disarm the gate. Twin of js/hosts/hooks.mjs.
1495
1844
  const DONE_LIST = ".geneseed/done-checks.txt"
1496
1845
  function protectedCheck(p) {
1846
+ if (EXTERNAL_GATE_OFF) return null
1497
1847
  return protectedIn(path.resolve(p)) ?? protectedIn(resolvePath(p))
1498
1848
  }
1499
1849
  function protectedIn(target) {
@@ -1501,16 +1851,24 @@ function protectedIn(target) {
1501
1851
  const root = gitRootOf(path.dirname(target))
1502
1852
  if (!root) return null
1503
1853
  const fold = (s) => nocase(s.replace(/\\/g, "/"))
1504
- const rel = fold(path.relative(root, target))
1505
- if (rel === fold(DONE_LIST)) return DONE_LIST
1854
+ const shown = path.relative(root, target)
1855
+ const rel = fold(shown)
1856
+ if (rel === fold(DONE_LIST)) return shown
1506
1857
  const text = readFileSync(path.join(root, SENSOR_LIST), "utf8")
1507
1858
  const entries = [SENSOR_LIST, ...text.split(/\r?\n/).map((l) => l.trim().replace(/[\\/]+$/, ""))
1508
1859
  .filter((l) => l && !l.startsWith("#"))]
1509
- return entries.find((e) => rel === fold(e) || rel.startsWith(fold(e) + "/")) ?? null
1860
+ return entries.some((e) => rel === fold(e) || rel.startsWith(fold(e) + "/")) ? shown : null
1510
1861
  } catch {
1511
1862
  return null // no list (the common case) or an unreadable one: nothing is protected
1512
1863
  }
1513
1864
  }
1865
+ // `p` from its git root, or as given outside any repository. Twin of js/hosts/hooks.mjs's `repoRel`.
1866
+ function repoRel(p) {
1867
+ try {
1868
+ const root = gitRootOf(path.dirname(p))
1869
+ return root ? path.relative(root, p) : p
1870
+ } catch { return p }
1871
+ }
1514
1872
 
1515
1873
  // ---- the gates' own configuration (External Gate) ------------------------------
1516
1874
  // Twin of js/hosts/hooks.mjs's `gateConfig`, MINUS what OpenCode now asks about itself
@@ -1525,8 +1883,8 @@ function protectedIn(target) {
1525
1883
  // under `$GENESEED_HARNESS`, a carrier the emit cannot name.
1526
1884
  const GATE_CONFIG_FILES = ['excludes.json', 'AGENT.md', '.geneseed-manifest.json', '.geneseed-emit'];
1527
1885
  const GATE_CONFIG_MARKERS = ['.claude', '.openclaude', '.bob'];
1528
- 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).';
1529
1886
  function gateConfig(p) {
1887
+ if (EXTERNAL_GATE_OFF) return false
1530
1888
  try {
1531
1889
  const fold = (s) => nocase(path.resolve(s))
1532
1890
  const cfg = path.dirname(PLUGIN_DIR)
@@ -1544,6 +1902,42 @@ function gateConfig(p) {
1544
1902
  return false
1545
1903
  }
1546
1904
 
1905
+ // Twin of js/hosts/hooks.mjs's `carrierBlockChange`, for another host's carrier: a hook host reads a
1906
+ // `CLAUDE.md` or `AGENTS.md` by its managed block, so a write tool that moves that block, or that this
1907
+ // cannot replay, is refused. An edit outside the block passes. A patch is not replayed: it passes only
1908
+ // when neither the file nor the patch holds the opening delimiter, since a line patch cannot form one.
1909
+ const CARRIER_BEGIN = "<!-- BEGIN GENESEED -->"
1910
+ const CARRIER_REPLAY_CAP = 1024 * 1024
1911
+ const carrierBlockOf = (text) => /<!-- BEGIN GENESEED -->[\s\S]*?<!-- END GENESEED -->/.exec(text)?.[0] ?? ""
1912
+ function carrierName(file) {
1913
+ const s = String(file)
1914
+ const at = Math.max(s.lastIndexOf("/"), s.lastIndexOf("\\")) + 1
1915
+ return s.slice(0, at) + s.slice(at).split(":")[0].replace(/[. ]+$/, "")
1916
+ }
1917
+ function carrierBlockChange(file, tool, args) {
1918
+ if (EXTERNAL_GATE_OFF) return false
1919
+ const target = carrierName(file)
1920
+ const shared = (f) => /(?:^|[\\/])(?:CLAUDE|AGENTS)\.md$/i.test(f)
1921
+ if (!shared(target) && !shared(resolvePath(target))) return false
1922
+ let before = ""
1923
+ try {
1924
+ if (statSync(target).size > CARRIER_REPLAY_CAP) return true
1925
+ before = readFileSync(target, "utf8")
1926
+ } catch (err) {
1927
+ if (err?.code !== "ENOENT") return true
1928
+ }
1929
+ if (typeof args?.patchText === "string") {
1930
+ return before.includes(CARRIER_BEGIN) || args.patchText.includes(CARRIER_BEGIN) || /^\*\*\* Move to:/m.test(args.patchText)
1931
+ }
1932
+ let after = null
1933
+ if (tool === "write" && typeof args?.content === "string") after = args.content
1934
+ else if (tool === "edit" && typeof args?.oldString === "string" && args.oldString && typeof args?.newString === "string") {
1935
+ const parts = before.split(args.oldString)
1936
+ if (parts.length === 2 || (args.replaceAll === true && parts.length > 2)) after = parts.join(args.newString)
1937
+ }
1938
+ return after === null || after.length > CARRIER_REPLAY_CAP || carrierBlockOf(after) !== carrierBlockOf(before)
1939
+ }
1940
+
1547
1941
  // The files `gateConfig` leaves to OpenCode's native `permission.edit` ask (`opencodeEditAsks` in
1548
1942
  // js/hosts/settings.mjs). That ask covers edit tools only: a shell command never reaches it, and
1549
1943
  // this tool hook has no ask tier, so for a SHELL write these are refused. The agent can still
@@ -1565,6 +1959,7 @@ function agentAskTails(cfg) {
1565
1959
  return tails
1566
1960
  }
1567
1961
  function nativeAskFile(p) {
1962
+ if (EXTERNAL_GATE_OFF) return false
1568
1963
  try {
1569
1964
  const cfg = path.dirname(PLUGIN_DIR)
1570
1965
  const name = path.basename(cfg)
@@ -1591,13 +1986,56 @@ function nativeAskFile(p) {
1591
1986
  // to the END marker verbatim, with `export ` dropped (tests/plugins/guard.test.mjs diffs the two).
1592
1987
 
1593
1988
  // The cheap prefilter, a superset of what the parse acts on: a `>`, or one of the programs as a word.
1594
- const SHELL_WRITE_RE = />|(?:^|[\s;&|("'`\\/])(?:tee|sed|cp|mv|rm)(?:\.exe)?(?=[\s;&|)"'`]|$)/im;
1989
+ 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;
1595
1990
  // One pass over a segment: a quoted run (kept: its `>` is data), or a redirection with its optional
1596
1991
  // fd, operator, `&` (a dup such as `2>&1`, which writes no file) and target word. `<` forms match
1597
1992
  // too, so that their words never read as operands. A backslash is no escape here, as in
1598
1993
  // `SCAN_SPLIT_RE`: `echo "say \"hi > f\""` closes its quote early, reads a target, and asks (on Bob, blocks).
1599
1994
  const REDIRECT_RE = /"[^"]*"?|'[^']*'?|(?:(?<!\S)\d+|&)?(<<?<?-?|>>?)[ \t]*(&?)((?:[^\s"';|&<>()]|"[^"]*"?|'[^']*'?)*)/g;
1600
1995
  const SHELL_CD = new Set(['cd', 'pushd', 'chdir', 'set-location', 'sl']);
1996
+ // What says the shell is PowerShell when the caller cannot: a `Verb-Noun` word outside any here-string.
1997
+ 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;
1998
+ // The home a shell expands, spelled for `writePath` as `~/…`, the one form that keeps the two readings.
1999
+ const HOME_WORD_RE = /^(?:~|\$\{?(?:env:)?(?:home|userprofile)\}?)(?=[\\/]|$)/i;
2000
+ // PowerShell's writers, each as the POSIX form that writes the same paths. `ren` is `mv` with a sibling.
2001
+ const PS_WRITERS = new Map(Object.entries({
2002
+ 'add-content': 'rm', ac: 'rm', 'set-content': 'rm', sc: 'rm', 'out-file': 'rm', 'clear-content': 'rm', 'remove-item': 'rm',
2003
+ del: 'rm', 'new-item': 'rm', ni: 'rm', 'copy-item': 'cp', copy: 'cp', 'move-item': 'mv', move: 'mv', 'rename-item': 'ren', ren: 'ren',
2004
+ }));
2005
+ // `rm`, `cp` and `mv` are aliases too, but only a parameter spelled out in full tells them from the
2006
+ // POSIX programs: `-lp` and `-pat` are also POSIX flag clusters.
2007
+ const PS_NAMED_RE = /^-(?:path|literalpath|destination)(?::|$)/i;
2008
+ const PS_PATH_RE = /^-(?:path|literalpath|lp|pspath|filepath)$/i;
2009
+ const PS_SWITCH_RE = /^-(?:force|recurse|append|nonewline|noclobber|whatif|confirm|passthru|verbose|debug|container)$/i;
2010
+ const PS_VALUE_RE = /^-(?:value|encoding|itemtype|type|filter|include|exclude|inputobject|stream|width|target|erroraction|ea)$/i;
2011
+ // `(…)`, `$(…)`, `@(…)`, `{…}`, `@{…}`: an argument whose words cannot be counted. `${x}` is a variable.
2012
+ const PS_OPAQUE_RE = /^(?:[$@]?\(|@?\{)/;
2013
+
2014
+ /**
2015
+ * `s` with each here-string body cut. The body is data, as a heredoc's is: without this, an apostrophe
2016
+ * in a PowerShell commit message unpairs the quotes, and a line that opens with `Move` reads as a
2017
+ * command. One pass: a quote kind with no closer is searched for once, so many openers stay linear.
2018
+ */
2019
+ function hereStringsCut(s) {
2020
+ const re = /@(["'])\r?\n/g;
2021
+ const dead = new Set();
2022
+ let out = ''; let at = 0; let m;
2023
+ while ((m = re.exec(s))) {
2024
+ if (dead.has(m[1])) continue;
2025
+ const end = s.indexOf(`\n${m[1]}@`, re.lastIndex - 1);
2026
+ if (end < 0) { dead.add(m[1]); continue; }
2027
+ out += `${s.slice(at, m.index)}''`;
2028
+ at = end + 3;
2029
+ re.lastIndex = at;
2030
+ }
2031
+ return out + s.slice(at);
2032
+ }
2033
+
2034
+ /** `t` without its quotes, a home spelled `~/…`. Single quotes expand nothing, so `$` stays and hides the path. */
2035
+ function shellWord(t) {
2036
+ const w = t.replace(/["']/g, '');
2037
+ return t[0] !== "'" && HOME_WORD_RE.test(w) ? `~${w.replace(HOME_WORD_RE, '').replace(/\\/g, '/')}` : w;
2038
+ }
1601
2039
 
1602
2040
  /** `t` as an absolute path from `dir`, `~/…` as it stands, or null for what the shell rewrites. */
1603
2041
  function writePath(dir, t) {
@@ -1606,9 +2044,49 @@ function writePath(dir, t) {
1606
2044
  // A Git Bash `/c/…` path, as `resolveIn` reads it.
1607
2045
  const q = process.platform === 'win32' ? t.replace(/^\/([a-zA-Z])(?=\/|$)/, '$1:') : t;
1608
2046
  if (path.isAbsolute(q)) return path.resolve(q);
2047
+ if (dir && dir[0] === '~') return `${dir}/${q}`;
1609
2048
  return dir ? path.resolve(dir, q) : null;
1610
2049
  }
1611
2050
 
2051
+ /**
2052
+ * The operands of a PowerShell writer, in the order the POSIX branches read them, `/`-separated (a
2053
+ * cmdlet takes `\` on every platform). Only the first positional is a path, and for `cp`, `mv` and
2054
+ * `ren` the next is the destination: the next one of `Add-Content a b` is its value and of
2055
+ * `Remove-Item a b` its filter. Named paths are read wherever they stand; a parameter this does
2056
+ * not know, or a `(…)` or `{…}` argument, ends the positionals, because its words cannot be counted.
2057
+ */
2058
+ function psOperands(toks, form) {
2059
+ const paths = []; const dest = []; const pos = [];
2060
+ let name = ''; let open = true;
2061
+ const list = (t) => (t.match(/"[^"]*"?|'[^']*'?|[^,"']+/g) || []).map(shellWord).filter(Boolean);
2062
+ for (let i = 0; i < toks.length; i += 1) {
2063
+ // An array argument spans tokens: `a, b`.
2064
+ const value = (t) => { let v = t; while (v.endsWith(',') && i + 1 < toks.length) { i += 1; v += toks[i]; } return v; };
2065
+ const m = /^(-[a-z]+)(?::(.+))?$/is.exec(toks[i]);
2066
+ if (!m) {
2067
+ const t = value(toks[i]);
2068
+ if (PS_OPAQUE_RE.test(t)) open = false;
2069
+ else if (open && !/^\/[a-z]$/i.test(t)) pos.push(t); // `/y`: `copy` and `del` are cmd.exe's too
2070
+ } else if (!PS_SWITCH_RE.test(m[1])) {
2071
+ const into = PS_PATH_RE.test(m[1]) ? paths : /^-destination$/i.test(m[1]) ? dest : null;
2072
+ const naming = /^-(?:new)?name$/i.test(m[1]);
2073
+ if (!into && !naming && !PS_VALUE_RE.test(m[1])) { open = false; continue; }
2074
+ if (m[2] === undefined) i += 1;
2075
+ const t = value(m[2] ?? toks[i] ?? '');
2076
+ if (PS_OPAQUE_RE.test(t)) open = false;
2077
+ else if (into) into.push(...list(t));
2078
+ else if (naming) name = shellWord(t);
2079
+ }
2080
+ }
2081
+ if (!paths.length && pos.length) paths.push(...list(pos.shift()));
2082
+ if (form === 'rm') return name ? (paths.length ? paths : ['.']).map((p) => `${p}/${name}`) : paths;
2083
+ if (form === 'ren') {
2084
+ const to = name || shellWord(pos[0] ?? '');
2085
+ return to && paths.length ? [paths[0], paths[0].replace(/[^\\/]*$/, '') + to] : paths;
2086
+ }
2087
+ return [...paths, ...(dest.length ? dest : list(pos[0] ?? '')).slice(0, 1)];
2088
+ }
2089
+
1612
2090
  /** The files `sed` edits in place: none without `-i`; else its operands, past the script if inline. */
1613
2091
  function sedFiles(args) {
1614
2092
  const ops = [];
@@ -1629,38 +2107,55 @@ function sedFiles(args) {
1629
2107
  /**
1630
2108
  * The files `command` would write, as absolute paths: redirect targets (`>`, `>>`, `&>`), `tee`
1631
2109
  * and `rm` operands, `sed -i` files, the destination of `cp` and `mv`, and the sources of `mv`, which
1632
- * it removes. A destination may be a folder, so `cp a tests/` also names `tests/a`. Read like
1633
- * `rootScan`: quotes, comments and heredoc bodies are data. A `cd` is followed; one it cannot read
1634
- * leaves later relative paths unseen. What it cannot read, it leaves out: this reader fails OPEN.
2110
+ * it removes. A destination may be a folder, so `cp a tests/` also names `tests/a`. PowerShell's
2111
+ * writers read the same way (`PS_WRITERS`, `psOperands`), case-insensitively, and a pipe into one needs
2112
+ * nothing more: `| Out-File x` is a segment of its own. Read like `rootScan`: quotes, comments and
2113
+ * heredoc bodies are data. So is a here-string body, but only in PowerShell, which `ps` says when the
2114
+ * caller knows the tool and `PS_CUE_RE` otherwise: to bash the opener is a plain quote, so a closed
2115
+ * "here-string" can wrap a real `rm` (the row in tests/unit/hook_gates.test.mjs). With no cue, a
2116
+ * 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.
2117
+ * What it cannot read, it leaves out: this reader fails OPEN.
1635
2118
  *
1636
2119
  * shortcut: KNOWN UNSEEN FORMS, all of them still a write. An interpreter (inline code,
1637
- * `bash -c`, `eval`, `xargs`), a script or `npm run`, a `$(…)` or subshell trick, `>|`, a path with a
1638
- * variable, glob or brace in it, a wrapper with flags (`sudo -u x`) or outside `SCAN_WRAPPERS` (`env rm`,
1639
- * `nohup rm`, `timeout 5 rm`, `exec rm`), `echo x >& file` (read as a dup), a `popd` (not followed, so
1640
- * relative paths after a `pushd`/`popd` pair resolve from the wrong folder), `cp -t`, any other writer
1641
- * (`dd`, `ln`, `install`, `git mv`, `git checkout`, `Set-Content`), and a folder removed above a
1642
- * listed file (`rm -r tests` when only `tests/a.test.js` is listed). CI running the checks is the
1643
- * boundary that holds against those.
2120
+ * `bash -c`, `pwsh -c`, `powershell -Command`, `eval`, `xargs`), a script or `npm run`, a `$(…)` or
2121
+ * subshell trick, `>|`, a path with any other variable, a glob or a brace in it, a wrapper with flags
2122
+ * (`sudo -u x`) or outside `SCAN_WRAPPERS` (`env rm`, `nohup rm`, `timeout 5 rm`, `exec rm`), `echo x >&
2123
+ * file` (read as a dup), a `popd` (not followed, so relative paths after a `pushd`/`popd` pair resolve
2124
+ * from the wrong folder), `cp -t`, any other writer (`dd`, `ln`, `install`, `git mv`, `git checkout`,
2125
+ * `Tee-Object`, `[IO.File]::WriteAllText`, an alias outside `PS_WRITERS` such as `ri`), a cmdlet behind
2126
+ * a PowerShell assignment, `if` or script block (`$null = New-Item x`, `% { Remove-Item x }`), one
2127
+ * continued over lines with a backtick, a parameter abbreviated or unknown before a positional path (so
2128
+ * `Set-Content -Enc utf8 x`), a comma list after a POSIX-read `rm`, `cp` or `mv`, and a folder removed
2129
+ * above a listed file (`rm -r tests` when only `tests/a.test.js` is listed). CI running the checks is
2130
+ * the boundary that holds against those.
1644
2131
  */
1645
- function shellWriteTargets(command, cwd) {
2132
+ function shellWriteTargets(command, cwd, ps = false) {
1646
2133
  if (!SHELL_WRITE_RE.test(command)) return [];
1647
2134
  const found = new Set();
1648
2135
  let dir = cwd;
1649
2136
  const add = (t) => { const p = writePath(dir, t); if (p) found.add(p); };
1650
2137
  const bare = (t) => t.replace(/["']/g, '');
1651
- for (const seg of scanSegments(command)) {
2138
+ const cut = hereStringsCut(command);
2139
+ for (const seg of scanSegments(ps || PS_CUE_RE.test(cut) ? cut : command)) {
1652
2140
  const outs = [];
1653
2141
  const body = seg.replace(REDIRECT_RE, (m, op, dup, target) => {
1654
2142
  if (op === undefined) return m;
1655
- if (op[0] === '>' && !dup && target) outs.push(bare(target));
2143
+ if (op[0] === '>' && !dup && target) outs.push(shellWord(target));
1656
2144
  return ' ';
1657
2145
  });
1658
2146
  let toks = stripStructure(body.match(SCAN_TOKEN_RE) || []);
1659
2147
  while (toks.length && (/^\w+=/.test(toks[0]) || SCAN_WRAPPERS.has(bare(toks[0])))) toks = toks.slice(1);
1660
- const prog = toks.length ? bare(toks[0]).split(/[\\/]/).pop().toLowerCase().replace(/\.exe$/, '') : '';
1661
- const args = toks.slice(1).map(bare);
2148
+ const word = toks.length ? bare(toks[0]).split(/[\\/]/).pop().toLowerCase() : '';
2149
+ let prog = word.replace(/\.exe$/, '');
2150
+ const args = toks.slice(1).map(shellWord);
1662
2151
  const dashes = args.indexOf('--');
1663
- const ops = args.filter((a, i) => a && (a === '-' || !a.startsWith('-') || (dashes >= 0 && i > dashes)));
2152
+ let ops = args.filter((a, i) => a && (a === '-' || !a.startsWith('-') || (dashes >= 0 && i > dashes)));
2153
+ // `word`, not `prog`: `sc.exe` is the service tool, never the Set-Content alias.
2154
+ const form = PS_WRITERS.get(word) ?? (/^(?:rm|cp|mv)$/.test(prog) && toks.some((t) => PS_NAMED_RE.test(t)) ? prog : null);
2155
+ if (form) {
2156
+ prog = form === 'ren' ? 'mv' : form;
2157
+ ops = psOperands(toks.slice(1), form).map((t) => t.replace(/\\/g, '/'));
2158
+ }
1664
2159
  if (SHELL_CD.has(prog)) {
1665
2160
  const to = ops.find((a) => !/^\/d$/i.test(a));
1666
2161
  dir = to && to !== '-' ? writePath(dir, to) : null;
@@ -1863,12 +2358,12 @@ export const GeneseedGuard = async (ctx) => {
1863
2358
  const watch = async (sid) => {
1864
2359
  if (OFF || !sid || watched.has(sid) || unwatched.has(sid)) return
1865
2360
  if (await sovereignBypass(root()) || await isChildSession(sid)) { unwatched.add(sid); return }
1866
- watched.set(sid, scanAllStores())
2361
+ watched.set(sid, scanAllStores(root()))
1867
2362
  }
1868
2363
  const compare = async (sid) => {
1869
2364
  const before = watched.get(sid)
1870
2365
  if (!before) return
1871
- const now = scanAllStores()
2366
+ const now = scanAllStores(root())
1872
2367
  watched.set(sid, now)
1873
2368
  const changed = [...new Set([...Object.keys(before), ...Object.keys(now)])].filter((f) => before[f] !== now[f]).sort()
1874
2369
  if (!changed.length) return
@@ -1902,9 +2397,11 @@ export const GeneseedGuard = async (ctx) => {
1902
2397
  if (!watched.size || !NATIVE_EDIT_TOOLS.has(tool)) return
1903
2398
  const cwd = ctx?.directory || process.cwd()
1904
2399
  for (const raw of pickPath(input?.args ?? {}, cwd)) {
1905
- if (!ruleStoreTarget(raw, cwd)) continue
2400
+ // With Persist Insight off no prompt ran, so a rule file is not excused: the report shows it.
2401
+ const hit = ruleStoreTarget(raw, cwd)
2402
+ if (!hit || (RULE_STORE_OFF && hit !== "memory")) continue
1906
2403
  // Only keys the scan itself names: a link's other spellings would read as files gone.
1907
- const now = scanAllStores()
2404
+ const now = scanAllStores(root())
1908
2405
  for (const f of landsOn(raw, cwd)) {
1909
2406
  for (const base of watched.values()) { if (f in now) base[f] = now[f]; else delete base[f] }
1910
2407
  }
@@ -1926,6 +2423,12 @@ export const GeneseedGuard = async (ctx) => {
1926
2423
  // `law-4`, `process-1`) plus `wiki`, so status counts one vocabulary across hosts.
1927
2424
  // The model reads this text. It never names the GENESEED_GUARD switch: a weak model read
1928
2425
  // "set GENESEED_GUARD=off to allow" as leave to route the write through a shell (4.27.1).
2426
+ // 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
2427
+ // but a deny. No count: no `editPairs` here, and the line reads whole without one.
2428
+ const refused = (id, facts) => gateSafe(id, "refused", facts)
2429
+ // V1's explanations, held to the end of this hook: a later gate may still refuse the call, and a
2430
+ // note about a dialog that never comes is a false one. V2 posts from `evaluate` instead.
2431
+ const notes = []
1929
2432
  const deny = async (why, rule) => {
1930
2433
  if (WARN_ONLY) { log(`WARN (would block): ${why}`); return false }
1931
2434
  log(`BLOCKED: ${why}`)
@@ -1946,21 +2449,23 @@ export const GeneseedGuard = async (ctx) => {
1946
2449
  // blocks the whole call (see `pickPath` for why this is not a single path).
1947
2450
  const paths = pickPath(args, cwd)
1948
2451
  for (const raw of paths) {
1949
- if (namesStream(raw)) { await deny(`${raw} names an NTFS stream, which writes through to the file it hangs on — name the file itself (External Gate)`, "rigor-5"); return }
2452
+ if (namesStream(raw)) { await deny(refused("stream", { name: repoRel(path.resolve(cwd, raw)) }), "rigor-5"); return }
1950
2453
  // Once, here: under `opencode serve` this process's cwd is not the session's directory, and
1951
2454
  // every gate below resolves a relative path against it.
1952
2455
  const p = landsOn(raw, cwd)[0].replace(/\\/g, "/")
1953
- if (!SECRETS_GATE_OFF && SECRET_RE.some((re) => re.test(p))) { await deny(`write to secret/key file ${p} (Sealed Secrets)`, "law-1"); return }
2456
+ if (!SECRETS_GATE_OFF && SECRET_RE.some((re) => re.test(p))) { await deny(refused("secret-file", { name: repoRel(p) }), "law-1"); return }
1954
2457
  if (SECRET_WARN_RE.some((re) => re.test(p))) log(`WARN: writing ${p} — keep secrets out of tracked files (Sealed Secrets)`)
1955
2458
  const sensor = protectedCheck(p)
1956
- if (sensor) { await deny(`${p} is a protected check (${sensor === DONE_LIST ? "the done gate list itself" : `${sensor}, listed in ${SENSOR_LIST}`}) — a check the agent can edit is not a check (External Gate)`, "rigor-5"); return }
1957
- if (gateConfig(p)) { await deny(`${p} ${GATE_CONFIG_ASK} (External Gate)`, "rigor-5"); return }
2459
+ if (sensor) { await deny(refused("check", { name: sensor }), "rigor-5"); return }
2460
+ if (gateConfig(p)) { await deny(refused("config", { name: repoRel(p) }), "rigor-5"); return }
2461
+ if (carrierBlockChange(path.resolve(cwd, raw), tool, args)) { await deny(refused("config", { name: repoRel(p) }), "rigor-5"); return }
1958
2462
  // V1 after an "always": the `permission.edit` ask on these files is gone too.
1959
- if (everyEditApproved && !ctx?.hostAsks && nativeAskFile(p)) { await deny(`${p} ${GATE_CONFIG_ASK} (External Gate)`, "rigor-5"); return }
1960
- const store = ruleStoreTarget(raw, cwd)
1961
- if (store && !(await hostPrompts(tool, raw, cwd))) {
1962
- await deny(`writing to ${store} — a standing rule, or a fact to remember? That ` +
1963
- `choice is the user's (Persist Insight). ${NATIVE_EDIT_TOOLS.has(tool) ? PERSIST_NO_PROMPT : PERSIST_EDIT_TOOL}`, "process-1")
2463
+ if (everyEditApproved && !ctx?.hostAsks && nativeAskFile(p)) { await deny(refused("config", { name: repoRel(p) }), "rigor-5"); return }
2464
+ const store = ruleTarget(raw, cwd)
2465
+ const prompted = (store || nativeAskFile(p)) && await hostPrompts(tool, raw, cwd)
2466
+ if (prompted && !ctx?.hostAsks) notes.push(gateSafe(store ? "store" : "config", "ask", { name: store || repoRel(p) }))
2467
+ if (store && !prompted) {
2468
+ await deny(`${refused("store", { name: store })}\n${NATIVE_EDIT_TOOLS.has(tool) ? PERSIST_NO_PROMPT : PERSIST_EDIT_TOOL}`, "process-1")
1964
2469
  return
1965
2470
  }
1966
2471
  }
@@ -1971,8 +2476,7 @@ export const GeneseedGuard = async (ctx) => {
1971
2476
  for (const { path: cp, content } of SECRETS_GATE_OFF ? [] : pickAddedContentByPath(args, cwd)) {
1972
2477
  if (SECRET_WARN_RE.some((re) => re.test(cp))) continue
1973
2478
  if (SECRET_CONTENT_RE.test(content)) {
1974
- await deny(`${cp} would carry a credential-shaped string (Sealed Secrets) — secrets `
1975
- + "live in .env or a secret manager, never in a tracked file", "law-1")
2479
+ await deny(refused("secret", { name: repoRel(path.resolve(cwd, cp)) }), "law-1")
1976
2480
  return
1977
2481
  }
1978
2482
  }
@@ -1987,14 +2491,13 @@ export const GeneseedGuard = async (ctx) => {
1987
2491
  }
1988
2492
  // Any tool the host's prompt does not cover, whatever it calls its arguments. `pickCommand`,
1989
2493
  // because SHELL_TOOLS is a substring class: `mcp_prune_write` holds "run".
1990
- if (!NATIVE_EDIT_TOOLS.has(tool) && !readsOnly(tool) && !(hasAny(tool, SHELL_TOOLS) && pickCommand(args))) {
2494
+ if (!RULE_STORE_OFF && !NATIVE_EDIT_TOOLS.has(tool) && !readsOnly(tool) && !(hasAny(tool, SHELL_TOOLS) && pickCommand(args))) {
1991
2495
  const named = argPaths(args)
1992
- if (named.overflow) { await deny(`${tool}'s arguments nest too deep to read, so a rule or memory write cannot be ruled out (Persist Insight)`, "process-1"); return }
2496
+ if (named.overflow) { await deny(refused("deep-args", { name: tool }), "process-1"); return }
1993
2497
  for (const v of named) {
1994
- const store = ruleStoreTarget(v, cwd)
2498
+ const store = ruleTarget(v, cwd)
1995
2499
  if (store) {
1996
- await deny(`writing to ${store} through ${tool} — a standing rule, or a fact to remember? That ` +
1997
- `choice is the user's (Persist Insight). ${PERSIST_EDIT_TOOL}`, "process-1")
2500
+ await deny(`${refused("store", { name: store })}\n${PERSIST_EDIT_TOOL}`, "process-1")
1998
2501
  return
1999
2502
  }
2000
2503
  }
@@ -2004,7 +2507,7 @@ export const GeneseedGuard = async (ctx) => {
2004
2507
  const abs = landsOn(p, cwd)[0].replace(/\\/g, "/").toLowerCase()
2005
2508
  const hit = (await protectedPrefixes()).find(
2006
2509
  (x) => abs.startsWith(x.prefix) || abs === x.prefix.slice(0, -1))
2007
- if (hit) { await deny(`mutation in protected wiki folder — ${hit.label} (AGENT.md §8)`, "wiki"); return }
2510
+ if (hit) { await deny(refused("wiki", { name: hit.label }), "wiki"); return }
2008
2511
  }
2009
2512
  }
2010
2513
  // NOT else-if: a compound tool name (e.g. exec_and_save) can match both
@@ -2014,34 +2517,38 @@ export const GeneseedGuard = async (ctx) => {
2014
2517
  const wd = typeof args.workdir === "string" && args.workdir ? path.resolve(cwd, args.workdir) : cwd
2015
2518
  const c = pickCommand(args)
2016
2519
  const cut = (t) => scanSegments(t).map((seg) => seg.match(SCAN_TOKEN_RE) || [])
2017
- if (c && (SHELL_BLOCK_RE.some((re) => re.test(c)) || catastrophic(c, cut))) { await deny(`catastrophic command (Deletion Is Deliberate): ${c.slice(0, 80)}`, "law-4"); return }
2018
- const scan = c && rootScan(c)
2520
+ if (c && (SHELL_BLOCK_RE.some((re) => re.test(c)) || catastrophic(c, cut))) { await deny(refused("catastrophic", { name: c }), "law-4"); return }
2521
+ const scan = c && !ROOT_SCAN_OFF && rootScan(c)
2019
2522
  if (scan) {
2020
- await deny(`\`${scan.slice(0, 80)}\` recursively scans a whole filesystem root (Commands Must Return) — ` +
2021
- "search a specific directory instead: the project, node_modules, ~/.npm, %APPDATA%", "ops-2")
2523
+ await deny(refused("root-scan", { name: scan }), "ops-2")
2022
2524
  return
2023
2525
  }
2024
2526
  if (c && !DELETION_GATE_OFF && LOSS_CANDIDATE_RE.test(c)) {
2025
2527
  const loss = lossReason(cut(c), wd, { always: false, split: cut })
2026
- if (loss) { await deny(`${loss} (Deletion Is Deliberate) — confirm with the user first`, "law-4"); return }
2528
+ if (loss) { const facts = gateLoss(loss); await deny(refused(facts.id, facts), "law-4"); return }
2027
2529
  }
2028
2530
  // External Gate over a shell write: the same paths as a write tool, no content scan. A
2029
2531
  // throw fails open through the catch below, as the twin's `shellWriteReason` does.
2030
- for (const p of c ? shellWriteTargets(c, wd) : []) {
2532
+ for (const p of c ? shellWriteTargets(c, wd, /powershell|pwsh/i.test(tool)) : []) {
2031
2533
  const sensor = protectedCheck(p)
2032
- if (sensor) { await deny(`${p} is a protected check (${sensor === DONE_LIST ? "the done gate list itself" : `${sensor}, listed in ${SENSOR_LIST}`}) — a check the agent can edit is not a check (External Gate)`, "rigor-5"); return }
2033
- if (gateConfig(p) || nativeAskFile(p)) { await deny(`${p} ${GATE_CONFIG_ASK} (External Gate)`, "rigor-5"); return }
2534
+ if (sensor) { await deny(refused("check", { name: sensor, shell: true }), "rigor-5"); return }
2535
+ if (gateConfig(p) || nativeAskFile(p)) { await deny(refused("config", { name: repoRel(p), shell: true }), "rigor-5"); return }
2034
2536
  // A parsed form that lands in a store. V2 can ask: `evaluate` runs for the shell tool's own
2035
2537
  // `permission.assert`, so the call is marked by its id and the host prompts. V1 cannot.
2036
- const store = ruleStoreTarget(p, wd)
2037
- if (store && ctx?.shellAsks && input?.callID && !noProgramWord(c)) { ctx.shellAsks.add(input.callID); continue }
2538
+ const store = ruleTarget(p, wd)
2539
+ if (store && ctx?.shellAsks && input?.callID && !noProgramWord(c)) { ctx.shellAsks.set(input.callID, store); continue }
2038
2540
  if (store) {
2039
- await deny(`writing to ${store} through a shell command — a standing rule, or a fact to ` +
2040
- `remember? That choice is the user's (Persist Insight). ${PERSIST_EDIT_TOOL}`, "process-1")
2541
+ await deny(`${refused("store", { name: store, shell: true })}\n${PERSIST_EDIT_TOOL}`, "process-1")
2041
2542
  return
2042
2543
  }
2043
2544
  }
2044
2545
  }
2546
+ for (const note of notes) {
2547
+ // No count here, as in a refusal. 120 s, because the dialog stays until it is answered.
2548
+ try {
2549
+ await ctx?.client?.tui?.showToast?.({ body: { title: "Geneseed", message: gateNote(note), variant: "warning", duration: 120000 }, query: { directory: cwd } })
2550
+ } catch (err) { log(`note not shown: ${err?.message ?? err}`) }
2551
+ }
2045
2552
  } catch (err) {
2046
2553
  // Our own deny must propagate; any inspection error must never break a tool call.
2047
2554
  if (err && String(err.message || "").startsWith("[geneseed-guard]")) throw err
@@ -2072,8 +2579,18 @@ export const GeneseedGuard = async (ctx) => {
2072
2579
  // and any saved "always" say (core/src/permission.ts, 2.2.5). A configured deny never reaches it,
2073
2580
  // and an unattended session turns the ask into a deny. A V2 without the domain has no `hostAsks`,
2074
2581
  // so the guard refuses those writes.
2582
+ //
2583
+ // The dialog shows no plugin text, so each ask posts a note first. The TUI renders a synthetic item's
2584
+ // `description` and the model gets its `text`, so the block goes in the first and the second must read
2585
+ // true whether the user allows or denies (spec 2026-11-07-gate-prompts-5.0.3, S0 result).
2075
2586
  async function askOnRuleStore(ctx, shellAsks) {
2076
2587
  const dir = ctx?.location?.directory || process.cwd()
2588
+ const note = async (event) => {
2589
+ try {
2590
+ await ctx.session.synthetic({ sessionID: event.sessionID, text: "Geneseed showed the user why the next permission request asks.",
2591
+ description: gateNote(event.message), resume: false })
2592
+ } catch (err) { log(`note not posted: ${err?.message ?? err}`) }
2593
+ }
2077
2594
  try {
2078
2595
  await ctx.permission.hook("evaluate", async (event) => {
2079
2596
  try {
@@ -2081,21 +2598,24 @@ async function askOnRuleStore(ctx, shellAsks) {
2081
2598
  if (event.action === "shell") {
2082
2599
  // The shell tool's assert: action `shell`, one resource per parsed command, `source.id` the
2083
2600
  // call the tool hook marked. A command the host's parser finds no command in asserts nothing.
2601
+ const shellStore = shellAsks.get(event.source?.id)
2084
2602
  if (!shellAsks.delete(event.source?.id)) return
2085
- if (WARN_ONLY) { log("WARN (would ask): a shell write to a rule or memory file (Persist Insight)"); return }
2603
+ if (WARN_ONLY) { log("WARN (would ask): a shell write to a rule file (Persist Insight)"); return }
2086
2604
  event.effect = "ask"
2087
- event.message = "Geneseed (Persist Insight): this command writes a rule or memory file. A standing rule, or a fact to remember? That choice is yours."
2605
+ event.message = gateSafe("store", "ask", { name: shellStore, shell: true })
2606
+ await note(event)
2088
2607
  return
2089
2608
  }
2090
2609
  if (event.action !== "edit") return
2091
- const store = event.resources.map((r) => ruleStoreTarget(r, dir)).find(Boolean)
2610
+ const store = event.resources.map((r) => ruleTarget(r, dir)).find(Boolean)
2092
2611
  // The gate's own files have a static ask a saved "always" can outvote, so they are raised too.
2093
- const gate = !store && event.resources.some((r) => nativeAskFile(path.resolve(dir, r)))
2612
+ const gate = !store && event.resources.find((r) => nativeAskFile(path.resolve(dir, r)))
2094
2613
  if ((!store && !gate) || await sovereignBypass(ctx?.location?.project?.directory || dir)) return
2095
2614
  if (WARN_ONLY) { log(`WARN (would ask): writing to ${store || "a gate's configuration"} (Persist Insight)`); return }
2096
2615
  event.effect = "ask"
2097
- event.message = store ? `Geneseed (Persist Insight): writing to ${store}. A standing rule, or a fact to remember? That choice is yours.`
2098
- : "Geneseed (External Gate): this file is a gate's own configuration. Editing it could switch a check off."
2616
+ event.message = store ? gateSafe("store", "ask", { name: store })
2617
+ : gateSafe("config", "ask", { name: repoRel(path.resolve(dir, gate)) })
2618
+ await note(event)
2099
2619
  } catch {
2100
2620
  // An event this hook cannot read is asked about. A V2 callback never throws.
2101
2621
  try { if (event?.action === "edit") event.effect = "ask" } catch { /* a frozen event: the static key still asks */ }
@@ -2106,7 +2626,8 @@ async function askOnRuleStore(ctx, shellAsks) {
2106
2626
  }
2107
2627
 
2108
2628
  async function setupV2(ctx) {
2109
- const shellAsks = new Set()
2629
+ // Call id to the store it writes, for the prompt's text.
2630
+ const shellAsks = new Map()
2110
2631
  const hostAsks = await askOnRuleStore(ctx, shellAsks)
2111
2632
  const hooks = await GeneseedGuard({
2112
2633
  worktree: ctx?.location?.project?.directory, directory: ctx?.location?.directory,