@namzu/sdk 63.1.0 → 64.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (200) hide show
  1. package/CHANGELOG.md +96 -0
  2. package/dist/agents/QueryAgent.d.ts.map +1 -1
  3. package/dist/agents/QueryAgent.js +2 -1
  4. package/dist/agents/QueryAgent.js.map +1 -1
  5. package/dist/agents/file-definitions.d.ts +10 -0
  6. package/dist/agents/file-definitions.d.ts.map +1 -1
  7. package/dist/agents/file-definitions.js +10 -2
  8. package/dist/agents/file-definitions.js.map +1 -1
  9. package/dist/compaction/hooks.d.ts +57 -0
  10. package/dist/compaction/hooks.d.ts.map +1 -0
  11. package/dist/compaction/hooks.js +44 -0
  12. package/dist/compaction/hooks.js.map +1 -0
  13. package/dist/compaction/manual.d.ts +9 -0
  14. package/dist/compaction/manual.d.ts.map +1 -1
  15. package/dist/compaction/manual.js +74 -5
  16. package/dist/compaction/manual.js.map +1 -1
  17. package/dist/compaction/model-summary.d.ts +6 -0
  18. package/dist/compaction/model-summary.d.ts.map +1 -1
  19. package/dist/compaction/model-summary.js +13 -3
  20. package/dist/compaction/model-summary.js.map +1 -1
  21. package/dist/compaction/verifier.d.ts +8 -2
  22. package/dist/compaction/verifier.d.ts.map +1 -1
  23. package/dist/compaction/verifier.js +23 -7
  24. package/dist/compaction/verifier.js.map +1 -1
  25. package/dist/plugin/file-change-hooks.d.ts +53 -0
  26. package/dist/plugin/file-change-hooks.d.ts.map +1 -0
  27. package/dist/plugin/file-change-hooks.js +111 -0
  28. package/dist/plugin/file-change-hooks.js.map +1 -0
  29. package/dist/plugin/file-change-watch.d.ts +111 -0
  30. package/dist/plugin/file-change-watch.d.ts.map +1 -0
  31. package/dist/plugin/file-change-watch.js +324 -0
  32. package/dist/plugin/file-change-watch.js.map +1 -0
  33. package/dist/plugin/hook-context.d.ts +16 -0
  34. package/dist/plugin/hook-context.d.ts.map +1 -1
  35. package/dist/plugin/hook-context.js +40 -0
  36. package/dist/plugin/hook-context.js.map +1 -1
  37. package/dist/plugin/index.d.ts +14 -4
  38. package/dist/plugin/index.d.ts.map +1 -1
  39. package/dist/plugin/index.js +10 -3
  40. package/dist/plugin/index.js.map +1 -1
  41. package/dist/plugin/lifecycle.d.ts +60 -1
  42. package/dist/plugin/lifecycle.d.ts.map +1 -1
  43. package/dist/plugin/lifecycle.js +118 -7
  44. package/dist/plugin/lifecycle.js.map +1 -1
  45. package/dist/plugin/loader.d.ts.map +1 -1
  46. package/dist/plugin/loader.js +24 -1
  47. package/dist/plugin/loader.js.map +1 -1
  48. package/dist/plugin/session-hook-env.d.ts +140 -0
  49. package/dist/plugin/session-hook-env.d.ts.map +1 -0
  50. package/dist/plugin/session-hook-env.js +458 -0
  51. package/dist/plugin/session-hook-env.js.map +1 -0
  52. package/dist/plugin/shell-hook-command.d.ts +25 -0
  53. package/dist/plugin/shell-hook-command.d.ts.map +1 -0
  54. package/dist/plugin/shell-hook-command.js +218 -0
  55. package/dist/plugin/shell-hook-command.js.map +1 -0
  56. package/dist/plugin/shell-hook-env.d.ts +107 -0
  57. package/dist/plugin/shell-hook-env.d.ts.map +1 -0
  58. package/dist/plugin/shell-hook-env.js +272 -0
  59. package/dist/plugin/shell-hook-env.js.map +1 -0
  60. package/dist/plugin/shell-hook-tool-names.d.ts +20 -0
  61. package/dist/plugin/shell-hook-tool-names.d.ts.map +1 -0
  62. package/dist/plugin/shell-hook-tool-names.js +43 -0
  63. package/dist/plugin/shell-hook-tool-names.js.map +1 -0
  64. package/dist/plugin/shell-hook.d.ts +167 -22
  65. package/dist/plugin/shell-hook.d.ts.map +1 -1
  66. package/dist/plugin/shell-hook.js +651 -106
  67. package/dist/plugin/shell-hook.js.map +1 -1
  68. package/dist/plugin/worktree-hook-answer.d.ts +26 -0
  69. package/dist/plugin/worktree-hook-answer.d.ts.map +1 -0
  70. package/dist/plugin/worktree-hook-answer.js +132 -0
  71. package/dist/plugin/worktree-hook-answer.js.map +1 -0
  72. package/dist/public-runtime.d.ts +5 -3
  73. package/dist/public-runtime.d.ts.map +1 -1
  74. package/dist/public-runtime.js +4 -3
  75. package/dist/public-runtime.js.map +1 -1
  76. package/dist/public-types.d.ts +9 -2
  77. package/dist/public-types.d.ts.map +1 -1
  78. package/dist/runtime/query/compact-session.d.ts +7 -1
  79. package/dist/runtime/query/compact-session.d.ts.map +1 -1
  80. package/dist/runtime/query/compact-session.js +8 -3
  81. package/dist/runtime/query/compact-session.js.map +1 -1
  82. package/dist/runtime/query/executor/tool-call-admission.d.ts +1 -1
  83. package/dist/runtime/query/executor/tool-call-admission.d.ts.map +1 -1
  84. package/dist/runtime/query/executor/tool-call-admission.js +4 -3
  85. package/dist/runtime/query/executor/tool-call-admission.js.map +1 -1
  86. package/dist/runtime/query/executor.d.ts +5 -0
  87. package/dist/runtime/query/executor.d.ts.map +1 -1
  88. package/dist/runtime/query/executor.js +8 -3
  89. package/dist/runtime/query/executor.js.map +1 -1
  90. package/dist/runtime/query/finalize-turn.d.ts.map +1 -1
  91. package/dist/runtime/query/finalize-turn.js +9 -2
  92. package/dist/runtime/query/finalize-turn.js.map +1 -1
  93. package/dist/runtime/query/index.d.ts +9 -0
  94. package/dist/runtime/query/index.d.ts.map +1 -1
  95. package/dist/runtime/query/index.js +3 -0
  96. package/dist/runtime/query/index.js.map +1 -1
  97. package/dist/runtime/query/iteration/index.d.ts.map +1 -1
  98. package/dist/runtime/query/iteration/index.js +2 -1
  99. package/dist/runtime/query/iteration/index.js.map +1 -1
  100. package/dist/runtime/query/iteration/phases/compaction.d.ts.map +1 -1
  101. package/dist/runtime/query/iteration/phases/compaction.js +24 -12
  102. package/dist/runtime/query/iteration/phases/compaction.js.map +1 -1
  103. package/dist/runtime/query/iteration/phases/tool-review.d.ts.map +1 -1
  104. package/dist/runtime/query/iteration/phases/tool-review.js +2 -0
  105. package/dist/runtime/query/iteration/phases/tool-review.js.map +1 -1
  106. package/dist/runtime/query/plugin-hooks.d.ts +13 -0
  107. package/dist/runtime/query/plugin-hooks.d.ts.map +1 -1
  108. package/dist/runtime/query/plugin-hooks.js +29 -2
  109. package/dist/runtime/query/plugin-hooks.js.map +1 -1
  110. package/dist/runtime/query/tooling.d.ts +5 -0
  111. package/dist/runtime/query/tooling.d.ts.map +1 -1
  112. package/dist/runtime/query/tooling.js +3 -0
  113. package/dist/runtime/query/tooling.js.map +1 -1
  114. package/dist/session/workspace/hooked-driver.d.ts +72 -0
  115. package/dist/session/workspace/hooked-driver.d.ts.map +1 -0
  116. package/dist/session/workspace/hooked-driver.js +204 -0
  117. package/dist/session/workspace/hooked-driver.js.map +1 -0
  118. package/dist/session/workspace/index.d.ts +2 -0
  119. package/dist/session/workspace/index.d.ts.map +1 -1
  120. package/dist/session/workspace/index.js +1 -0
  121. package/dist/session/workspace/index.js.map +1 -1
  122. package/dist/skills/index.d.ts +1 -1
  123. package/dist/skills/index.d.ts.map +1 -1
  124. package/dist/skills/index.js +1 -1
  125. package/dist/skills/index.js.map +1 -1
  126. package/dist/skills/loader.d.ts +22 -0
  127. package/dist/skills/loader.d.ts.map +1 -1
  128. package/dist/skills/loader.js +41 -0
  129. package/dist/skills/loader.js.map +1 -1
  130. package/dist/tools/builtins/bash-cwd.d.ts +6 -1
  131. package/dist/tools/builtins/bash-cwd.d.ts.map +1 -1
  132. package/dist/tools/builtins/bash-cwd.js +27 -2
  133. package/dist/tools/builtins/bash-cwd.js.map +1 -1
  134. package/dist/tools/builtins/bash.js +1 -1
  135. package/dist/tools/builtins/bash.js.map +1 -1
  136. package/dist/tools/builtins/skill.d.ts.map +1 -1
  137. package/dist/tools/builtins/skill.js +93 -16
  138. package/dist/tools/builtins/skill.js.map +1 -1
  139. package/dist/types/agent/query.d.ts +8 -0
  140. package/dist/types/agent/query.d.ts.map +1 -1
  141. package/dist/types/plugin/index.d.ts +130 -13
  142. package/dist/types/plugin/index.d.ts.map +1 -1
  143. package/dist/types/plugin/index.js +5 -0
  144. package/dist/types/plugin/index.js.map +1 -1
  145. package/dist/types/skills/index.d.ts +8 -0
  146. package/dist/types/skills/index.d.ts.map +1 -1
  147. package/dist/types/skills/index.js.map +1 -1
  148. package/dist/types/tool/index.d.ts +68 -0
  149. package/dist/types/tool/index.d.ts.map +1 -1
  150. package/dist/types/tool/index.js.map +1 -1
  151. package/dist/types/workspace/ref.d.ts +6 -0
  152. package/dist/types/workspace/ref.d.ts.map +1 -1
  153. package/dist/utils/frontmatter.d.ts +16 -0
  154. package/dist/utils/frontmatter.d.ts.map +1 -1
  155. package/dist/utils/frontmatter.js +31 -1
  156. package/dist/utils/frontmatter.js.map +1 -1
  157. package/package.json +1 -1
  158. package/src/agents/QueryAgent.ts +2 -1
  159. package/src/agents/file-definitions.ts +17 -2
  160. package/src/compaction/hooks.ts +104 -0
  161. package/src/compaction/manual.ts +117 -4
  162. package/src/compaction/model-summary.ts +19 -3
  163. package/src/compaction/verifier.ts +33 -3
  164. package/src/plugin/file-change-hooks.ts +131 -0
  165. package/src/plugin/file-change-watch.ts +367 -0
  166. package/src/plugin/hook-context.ts +46 -0
  167. package/src/plugin/index.ts +53 -1
  168. package/src/plugin/lifecycle.ts +162 -8
  169. package/src/plugin/loader.ts +22 -1
  170. package/src/plugin/session-hook-env.ts +475 -0
  171. package/src/plugin/shell-hook-command.ts +215 -0
  172. package/src/plugin/shell-hook-env.ts +335 -0
  173. package/src/plugin/shell-hook-tool-names.ts +46 -0
  174. package/src/plugin/shell-hook.ts +818 -100
  175. package/src/plugin/worktree-hook-answer.ts +142 -0
  176. package/src/public-runtime.ts +44 -0
  177. package/src/public-types.ts +22 -1
  178. package/src/runtime/query/compact-session.ts +16 -4
  179. package/src/runtime/query/executor/tool-call-admission.ts +10 -2
  180. package/src/runtime/query/executor.ts +13 -2
  181. package/src/runtime/query/finalize-turn.ts +9 -2
  182. package/src/runtime/query/index.ts +12 -0
  183. package/src/runtime/query/iteration/index.ts +2 -1
  184. package/src/runtime/query/iteration/phases/compaction.ts +31 -12
  185. package/src/runtime/query/iteration/phases/tool-review.ts +2 -0
  186. package/src/runtime/query/plugin-hooks.ts +32 -2
  187. package/src/runtime/query/tooling.ts +8 -0
  188. package/src/session/workspace/hooked-driver.ts +272 -0
  189. package/src/session/workspace/index.ts +7 -0
  190. package/src/skills/index.ts +3 -0
  191. package/src/skills/loader.ts +47 -0
  192. package/src/tools/builtins/bash-cwd.ts +25 -1
  193. package/src/tools/builtins/bash.ts +1 -1
  194. package/src/tools/builtins/skill.ts +115 -26
  195. package/src/types/agent/query.ts +9 -0
  196. package/src/types/plugin/index.ts +150 -23
  197. package/src/types/skills/index.ts +9 -0
  198. package/src/types/tool/index.ts +74 -0
  199. package/src/types/workspace/ref.ts +6 -0
  200. package/src/utils/frontmatter.ts +52 -1
@@ -24,8 +24,8 @@
24
24
  * same facts as `NAMZU_HOOK_EVENT`, `NAMZU_SESSION_ID`, `NAMZU_TURN_ID`,
25
25
  * `NAMZU_TOOL_NAME` and, when the input names a file, `NAMZU_TOOL_PATH`;
26
26
  * `NAMZU_PROJECT_DIR` is the folder the session was started for.
27
- * `session_start` also sends `source` (`startup` or `resume`) and `session_end`
28
- * `reason` (`exit` or `replaced`).
27
+ * `session_start` also sends `source` (`startup`, `resume` or `clear`) and
28
+ * `session_end` `reason` (`exit`, `replaced` or `clear`).
29
29
  *
30
30
  * `session_start` and `session_end` run outside any turn, so they carry no
31
31
  * `turn_id` on stdin and no `NAMZU_TURN_ID` in the environment — not even
@@ -36,7 +36,8 @@
36
36
  * stdout. The exit codes:
37
37
  *
38
38
  * - `0` — carry on. On `user_prompt_submit`, `subagent_start` and
39
- * `session_start`, plain (non-JSON) stdout becomes context for the model.
39
+ * `session_start`, plain (non-JSON) stdout becomes context for the model;
40
+ * on `pre_compact` it is instructions for the summariser.
40
41
  * - `2` — **block**, read per event: before a tool (`pre_tool_use`) the call is
41
42
  * skipped and the model is told why, with the hook's stderr as the reason;
42
43
  * on `user_prompt_submit` the turn ends; on `turn_end` and `subagent_stop`
@@ -104,6 +105,8 @@
104
105
  * and does not block: one that could not answer in time has not answered no.
105
106
  */
106
107
  import { spawn } from 'node:child_process';
108
+ import { constants, accessSync, mkdirSync, statSync } from 'node:fs';
109
+ import { basename, delimiter } from 'node:path';
107
110
  import { decodedCommands, decomposeCommandLine } from '../authorization/command-line.js';
108
111
  import { SKILL_TOOL_NAME_ALIASES, permissionPatternToRegExpSource, } from '../authorization/skill-grant.js';
109
112
  import { withSessionChildMarker } from '../process/session-child.js';
@@ -112,7 +115,11 @@ import { RENAMED_PLUGIN_HOOK_EVENTS } from '../types/plugin/index.js';
112
115
  import { asPluginId } from '../utils/id.js';
113
116
  import { NOOP_LOGGER } from '../utils/log/create-logger.js';
114
117
  import { boundHookReplacement } from './hook-context.js';
118
+ import { readHookCommand } from './shell-hook-command.js';
119
+ import { hookUnsetVariableHint, movedEnvironment, shellPathOutsideEnv, substituteMovedFolders, } from './shell-hook-env.js';
115
120
  import { postHookJson } from './shell-hook-http.js';
121
+ import { shellHookToolName } from './shell-hook-tool-names.js';
122
+ import { worktreeHookVerdict } from './worktree-hook-answer.js';
116
123
  export const SHELL_HOOK_EVENTS = [
117
124
  'user_prompt_submit',
118
125
  'session_start',
@@ -131,6 +138,10 @@ export const SHELL_HOOK_EVENTS = [
131
138
  'turn_failure',
132
139
  'turn_start',
133
140
  'turn_end',
141
+ 'file_changed',
142
+ 'cwd_changed',
143
+ 'worktree_create',
144
+ 'worktree_remove',
134
145
  ];
135
146
  /** The plugin id host shell hooks register under when the host names none. */
136
147
  export const SHELL_HOOKS_PLUGIN_ID = asPluginId('6d6f6bec-9d54-485b-90ca-52edbac1009d');
@@ -169,12 +180,28 @@ const WRITTEN_TOOL_NAMES = Object.freeze({
169
180
  taskupdate: 'TaskUpdate',
170
181
  tasklist: 'TaskList',
171
182
  });
183
+ /**
184
+ * The tools a written name stands for. The skill alias table sends `Task` and
185
+ * `Agent` to `create_task`, but the command line's sub-agent tool is named
186
+ * `Agent`, and a hook written for either spelling means it: both name it.
187
+ */
188
+ function toolsNamedBy(written) {
189
+ const alias = SKILL_TOOL_NAME_ALIASES[written];
190
+ const names = alias !== undefined ? [alias] : [];
191
+ if (written === 'task' || written === 'agent')
192
+ names.push('agent');
193
+ return names;
194
+ }
195
+ /** A name with the separators dropped: `ViewImage` and `view_image` are one tool. */
196
+ function squashed(name) {
197
+ return name.toLowerCase().replace(/[_-]/g, '');
198
+ }
172
199
  /** The names a skill writes for the tool called `toolName` here. */
173
200
  function writtenNamesFor(toolName) {
174
201
  const lower = toolName.toLowerCase();
175
202
  const names = [];
176
- for (const [written, tool] of Object.entries(SKILL_TOOL_NAME_ALIASES)) {
177
- if (tool !== lower)
203
+ for (const written of new Set([...Object.keys(SKILL_TOOL_NAME_ALIASES), 'agent', 'task'])) {
204
+ if (!toolsNamedBy(written).includes(lower))
178
205
  continue;
179
206
  names.push(written);
180
207
  const spelled = WRITTEN_TOOL_NAMES[written];
@@ -183,27 +210,74 @@ function writtenNamesFor(toolName) {
183
210
  }
184
211
  return names;
185
212
  }
213
+ /** A glob over names: `*` matches any run of characters, the rest is literal. */
214
+ function globMatches(pattern, subject) {
215
+ const source = pattern
216
+ .split('*')
217
+ .map((piece) => piece.replace(/[.+?^${}()|[\]\\]/g, '\\$&'))
218
+ .join('.*');
219
+ return new RegExp(`^${source}$`, 'i').test(subject);
220
+ }
221
+ /**
222
+ * Whether a list part (`Edit`, `Web*`, `mcp__*__search`) names `subject`, as a
223
+ * tool name or not. A `*` at the end is a prefix; a `*` anywhere else is a
224
+ * glob. For a tool, a bare tool-server name (`mcp__github`) names every tool
225
+ * of that server.
226
+ */
227
+ function listPartNames(part, subject, tool) {
228
+ const prefix = part.endsWith('*');
229
+ const core = prefix ? part.slice(0, -1) : part;
230
+ const written = core.toLowerCase();
231
+ const lower = subject.toLowerCase();
232
+ if (core.includes('*')) {
233
+ if (globMatches(part, subject))
234
+ return true;
235
+ return tool && writtenNamesFor(subject).some((name) => globMatches(part, name));
236
+ }
237
+ const spellings = [written];
238
+ if (tool)
239
+ spellings.push(...toolsNamedBy(written));
240
+ return spellings.some((name) => {
241
+ if (prefix ? lower.startsWith(name) : lower === name)
242
+ return true;
243
+ if (!tool)
244
+ return false;
245
+ // A tool's name also compares without its `_` and `-`.
246
+ if (prefix ? squashed(lower).startsWith(squashed(name)) : squashed(lower) === squashed(name)) {
247
+ return true;
248
+ }
249
+ return !prefix && name.startsWith('mcp__') && !name.slice(5).includes('__')
250
+ ? lower.startsWith(`${name}__`)
251
+ : false;
252
+ });
253
+ }
254
+ const MATCHER_LIST_PART = /^[A-Za-z0-9_.:*-]+$/;
186
255
  /**
187
256
  * `matcher` against a name (a tool's, or a notification's type).
188
257
  *
189
258
  * Empty or `*` matches everything. A list of names separated by `|` or `,`
190
259
  * matches exactly, each part optionally ending in `*` as a prefix (the
191
260
  * spelling this adapter has always taken). Anything else is a regular
192
- * expression, tested unanchored against the name; one that does not compile
193
- * matches nothing. A matcher on an event that has no name (`turn_start`)
194
- * matches nothing unless it is `*`.
261
+ * expression, tested unanchored against the name. This function called with no
262
+ * name matches only `*`; a hook on an event that has no name (`turn_end`)
263
+ * ignores its matcher and fires (see `createShellHook`).
264
+ *
265
+ * A text that reads both ways (it is a list, and it holds a `.*`
266
+ * that a regular expression reads differently: `Bash.*`,
267
+ * `mcp__.*__search`) fires when either reading matches. A pattern that does
268
+ * not compile cannot be read, and a guard that silently matches nothing is
269
+ * the failure to avoid, so it matches every name; `/hooks` and
270
+ * `namzu doctor` say that it cannot be read (`shellHookMatcherProblem`).
195
271
  *
196
272
  * Names in a list compare without regard to case. With `tool: true` (the
197
273
  * event's name is a tool: the tool events and `permission_request`) they also
198
- * take the names skills write, the way an entry's `if` does: `Bash` matches
199
- * the tool `bash`, `MultiEdit` matches `edit`, and a prefix such as `Web*`
200
- * matches `web_fetch` by its written name too. Where the name is not a tool
201
- * (a notification's type, an agent's name, a session's `source` or `reason`)
202
- * no tool alias applies, since those words are not tool names; case is still
203
- * ignored there, because a guard that silently never runs over a capital
204
- * letter is worse than one that also runs for a name differing only in case.
205
- *
206
- * A list part ending in `.*` is also tried as a regular expression.
274
+ * take the names skills write, the way an entry's `if` does, and a tool name
275
+ * compares without its `_` and `-`: `Bash` matches the tool `bash`,
276
+ * `MultiEdit` matches `edit`, `ViewImage` matches `view_image`, `Task` and
277
+ * `Agent` match the sub-agent tool `Agent`, and a prefix such as `Web*`
278
+ * matches `web_fetch`. Where the name is not a tool (a notification's type,
279
+ * an agent's name, a session's `source` or `reason`) no tool alias applies,
280
+ * since those words are not tool names; case is still ignored there.
207
281
  *
208
282
  * A regular expression is tested, case-sensitively as written, against the
209
283
  * real name and, with `tool: true`, against each name skills write for that
@@ -217,23 +291,13 @@ export function shellHookMatches(matcher, toolName, options = {}) {
217
291
  return false;
218
292
  const tool = options.tool === true;
219
293
  const parts = matcher.split(/[|,]/).map((part) => part.trim());
220
- if (parts.every((part) => /^[A-Za-z0-9_.:-]+\*?$/.test(part))) {
221
- const subject = toolName.toLowerCase();
222
- const listed = parts.some((candidate) => {
223
- const prefix = candidate.endsWith('*');
224
- const written = (prefix ? candidate.slice(0, -1) : candidate).toLowerCase();
225
- const spellings = [written];
226
- if (tool) {
227
- const alias = SKILL_TOOL_NAME_ALIASES[written];
228
- if (alias !== undefined)
229
- spellings.push(alias);
230
- }
231
- return spellings.some((name) => (prefix ? subject.startsWith(name) : subject === name));
232
- });
233
- // `Bash.*` reads as the prefix `bash.` above, which no tool has. A part
234
- // ending in `.*` is also a regular expression, so it is tried as one.
235
- if (listed || !matcher.includes('.*'))
236
- return listed;
294
+ if (parts.every((part) => MATCHER_LIST_PART.test(part))) {
295
+ if (parts.some((part) => listPartNames(part, toolName, tool)))
296
+ return true;
297
+ // A list of names is exact (a `*` in it is a prefix or a glob). Only `.*` reads differently
298
+ // as a regular expression, so only then is the second reading tried.
299
+ if (!matcher.includes('.*'))
300
+ return false;
237
301
  }
238
302
  try {
239
303
  const expression = new RegExp(matcher);
@@ -242,41 +306,138 @@ export function shellHookMatches(matcher, toolName, options = {}) {
242
306
  return tool && writtenNamesFor(toolName).some((name) => expression.test(name));
243
307
  }
244
308
  catch {
245
- return false;
309
+ return true;
310
+ }
311
+ }
312
+ /**
313
+ * Why a `matcher` cannot be read, or `undefined` when it can. A matcher that
314
+ * is not a list of names and does not compile as a regular expression fires
315
+ * for every name (see {@link shellHookMatches}).
316
+ */
317
+ export function shellHookMatcherProblem(matcher) {
318
+ if (matcher === undefined || matcher.trim() === '' || matcher.trim() === '*')
319
+ return undefined;
320
+ const parts = matcher.split(/[|,]/).map((part) => part.trim());
321
+ if (parts.every((part) => MATCHER_LIST_PART.test(part)))
322
+ return undefined;
323
+ // `Bash(git push *)` is a tool and a pattern, which is what an `if` reads. As a
324
+ // matcher it is a regular expression that no tool name satisfies, so the hook
325
+ // would never fire; say so, and name the `if`.
326
+ if (/^[A-Za-z0-9_.:*-]+\([\s\S]*\)$/.test(matcher.trim())) {
327
+ return `the matcher "${matcher}" is written as Tool(pattern), which is an if, not a matcher: as a matcher it matches no tool name and the hook never fires; put the tool in matcher and the pattern in if`;
328
+ }
329
+ try {
330
+ new RegExp(matcher);
331
+ return undefined;
332
+ }
333
+ catch (error) {
334
+ return `the matcher "${matcher}" is not a list of names and is not a regular expression (${error.message}), so it cannot be read and the hook fires for every call`;
246
335
  }
247
336
  }
337
+ const IF_SHAPE = /^([A-Za-z0-9_.:*|, -]+)(?:\(([\s\S]*)\))?$/;
338
+ /** A part of a `file_changed` matcher that names a path: letters, digits and the characters of a path. */
339
+ const FILE_LIST_PART = /^[A-Za-z0-9_.:*\\/-]+$/;
340
+ /** The parts of a `file_changed` matcher when every part is written as a path, else `undefined`. */
341
+ function fileMatcherParts(matcher) {
342
+ if (matcher === undefined || matcher.trim() === '' || matcher.trim() === '*')
343
+ return undefined;
344
+ const parts = matcher.split(/[|,]/).map((part) => part.trim());
345
+ return parts.every((part) => FILE_LIST_PART.test(part)) ? parts : undefined;
346
+ }
347
+ /**
348
+ * The files a `file_changed` matcher names: each part of a `|` list that is a
349
+ * path with no `*` in it (`.envrc`, `config/app.json`, `/etc/hosts`). A part
350
+ * with a `*`, a pattern, or no matcher names no file; the hook then runs only
351
+ * for the files hooks hand back with `watchPaths`. A relative path is under
352
+ * the working folder, which the host knows.
353
+ */
354
+ export function fileChangedMatcherPaths(matcher) {
355
+ return (fileMatcherParts(matcher) ?? []).filter((part) => !part.includes('*'));
356
+ }
357
+ /**
358
+ * Whether a `file_changed` hook with this matcher runs for `filePath`. The
359
+ * matcher is read as every matcher is, but against the file's base name: a
360
+ * part written as a path (`config/app.json`) stands for its base name
361
+ * (`app.json`). An unreadable pattern runs the hook.
362
+ */
363
+ export function fileChangedMatches(matcher, filePath) {
364
+ if (filePath === undefined)
365
+ return true;
366
+ const name = basename(filePath.replace(/[\\/]+$/, ''));
367
+ const parts = fileMatcherParts(matcher);
368
+ if (parts === undefined)
369
+ return shellHookMatches(matcher, name);
370
+ return shellHookMatches(parts.map((part) => basename(part.replace(/[\\/]+$/, '')) || part).join('|'), name);
371
+ }
372
+ /**
373
+ * What a `file_changed` entry's matcher does not do, or `undefined`: a matcher
374
+ * that names no file watches nothing by itself.
375
+ */
376
+ export function fileChangedMatcherNote(matcher) {
377
+ if (fileChangedMatcherPaths(matcher).length > 0)
378
+ return undefined;
379
+ return 'its matcher names no file, so it watches nothing itself and runs only for files other hooks hand back with watchPaths';
380
+ }
381
+ /**
382
+ * Why an `if` cannot be read, or `undefined` when it can. A filter that
383
+ * cannot be read runs the hook.
384
+ */
385
+ export function shellHookIfProblem(filter) {
386
+ if (filter === undefined || filter.trim() === '')
387
+ return undefined;
388
+ return IF_SHAPE.test(filter.trim())
389
+ ? undefined
390
+ : `the if "${filter}" is not Tool or Tool(pattern), so it cannot be read and the hook runs for every call`;
391
+ }
248
392
  /**
249
393
  * A hook's `if` against one tool call: `Tool` or `Tool(pattern)`. The tool
250
- * part is case-insensitive and takes the names skills write (`Bash`,
251
- * `Read`). A pattern is matched against a shell tool's command line and only
252
- * there; for a tool with no command line the filter cannot be read, which
253
- * runs the hook.
394
+ * part takes every spelling a `matcher` takes as a list: names skills write
395
+ * (`Bash`, `Read`, `Agent`), separated by `|` or `,`, a prefix ending in `*`,
396
+ * case ignored; a regular expression is not read here (use `matcher`). A
397
+ * pattern is matched against a shell tool's command line (one command at a
398
+ * time) or, for a file tool, a path the host reads; for a tool with neither
399
+ * the filter cannot be read, which runs the hook.
254
400
  */
255
401
  export function shellHookIfMatches(filter, toolName, toolInput, pathFilter) {
256
402
  if (filter === undefined || filter.trim() === '')
257
403
  return true;
258
404
  if (toolName === undefined)
259
405
  return true;
260
- const shape = /^([A-Za-z0-9_.-]+)(?:\(([\s\S]*)\))?$/.exec(filter.trim());
406
+ const shape = IF_SHAPE.exec(filter.trim());
261
407
  if (!shape)
262
408
  return true;
263
- const written = (shape[1] ?? '').toLowerCase();
264
- const tool = SKILL_TOOL_NAME_ALIASES[written] ?? written;
265
409
  const specifier = shape[2]?.trim();
266
410
  const hasPattern = specifier !== undefined && specifier !== '' && specifier.replaceAll('*', '') !== '';
267
- // A path pattern is the permission rules' own: the host that has them says
268
- // whether this call's path is named. It decides for the tools it knows.
269
- if (hasPattern && pathFilter !== undefined) {
270
- const answer = pathFilter(tool, specifier, toolName, toolInput);
271
- if (answer !== undefined)
272
- return answer;
273
- }
274
- if (tool !== toolName.toLowerCase())
275
- return false;
276
- if (!hasPattern)
411
+ const parts = (shape[1] ?? '')
412
+ .split(/[|,]/)
413
+ .map((part) => part.trim())
414
+ .filter((part) => part !== '');
415
+ if (parts.length === 0)
277
416
  return true;
278
- if (tool !== 'bash')
417
+ if (parts.some((part) => part === '*'))
279
418
  return true;
419
+ const callTool = toolName.toLowerCase();
420
+ return parts.some((part) => {
421
+ const written = part.replace(/\*$/, '').toLowerCase();
422
+ const tool = SKILL_TOOL_NAME_ALIASES[written] ?? written;
423
+ // A path pattern is the permission rules' own: the host that has them says
424
+ // whether this call's path is named. It decides for the tools it knows.
425
+ if (hasPattern && pathFilter !== undefined && !part.endsWith('*')) {
426
+ const answer = pathFilter(tool, specifier, toolName, toolInput);
427
+ if (answer !== undefined)
428
+ return answer;
429
+ }
430
+ if (!listPartNames(part, toolName, true))
431
+ return false;
432
+ if (!hasPattern)
433
+ return true;
434
+ if (callTool !== 'bash')
435
+ return true;
436
+ return commandMatches(specifier, toolInput);
437
+ });
438
+ }
439
+ /** A shell tool's command line against a permission-rule pattern, per command. */
440
+ function commandMatches(specifier, toolInput) {
280
441
  const line = toolInput !== null && typeof toolInput === 'object'
281
442
  ? toolInput.command
282
443
  : undefined;
@@ -291,7 +452,17 @@ export function shellHookIfMatches(filter, toolName, toolInput, pathFilter) {
291
452
  // whole line is visible and none of its commands matches.
292
453
  if (decomposed.opaque)
293
454
  return true;
294
- const candidates = [...decomposed.segments, ...decodedCommands(line, 'sh')].map((each) => each.trim());
455
+ // Wrappers, a program's full path and git's global options do not change
456
+ // which command runs; a command whose name is only known at run time
457
+ // cannot be compared, so the hook runs.
458
+ const reading = readHookCommand(line);
459
+ if (reading.unknowable)
460
+ return true;
461
+ const candidates = [
462
+ ...decomposed.segments,
463
+ ...decodedCommands(line, 'sh'),
464
+ ...reading.candidates,
465
+ ].map((each) => each.trim());
295
466
  return candidates.some((each) => matcher.test(each));
296
467
  }
297
468
  catch {
@@ -302,7 +473,7 @@ export function shellHookIfMatches(filter, toolName, toolInput, pathFilter) {
302
473
  export function shellHookPayload(input) {
303
474
  return JSON.stringify({
304
475
  event: input.event,
305
- hook_event_name: PASCAL_EVENT_NAMES[input.event] ?? input.event,
476
+ hook_event_name: SHELL_HOOK_PASCAL_EVENT_NAMES[input.event] ?? input.event,
306
477
  cwd: input.cwd,
307
478
  session_id: input.sessionId,
308
479
  ...(input.transcriptPath !== undefined ? { transcript_path: input.transcriptPath } : {}),
@@ -315,9 +486,22 @@ export function shellHookPayload(input) {
315
486
  ? { agent_id: input.sessionId, agent_type: input.agentType }
316
487
  : {}),
317
488
  ...(input.prompt !== undefined ? { prompt: input.prompt } : {}),
318
- ...(input.compaction !== undefined ? { compaction: input.compaction } : {}),
319
- ...(input.toolName !== undefined ? { tool_name: input.toolName } : {}),
320
- ...(input.toolInput !== undefined ? { tool_input: input.toolInput } : {}),
489
+ ...(input.filePath !== undefined ? { file_path: input.filePath } : {}),
490
+ ...(input.change !== undefined ? { change: input.change } : {}),
491
+ ...(input.oldCwd !== undefined ? { old_cwd: input.oldCwd } : {}),
492
+ ...(input.newCwd !== undefined ? { new_cwd: input.newCwd } : {}),
493
+ ...(input.worktreeName !== undefined ? { name: input.worktreeName } : {}),
494
+ ...(input.worktreeRoot !== undefined ? { worktree_root: input.worktreeRoot } : {}),
495
+ ...(input.worktreeBaseRef !== undefined ? { base_ref: input.worktreeBaseRef } : {}),
496
+ ...(input.worktreePath !== undefined ? { worktree_path: input.worktreePath } : {}),
497
+ ...(input.compaction !== undefined ? compactionFields(input.event, input.compaction) : {}),
498
+ ...(input.toolName !== undefined
499
+ ? { tool_name: shellHookToolName(input.toolName, input.toolNames) }
500
+ : {}),
501
+ ...(input.toolCallId !== undefined ? { tool_use_id: input.toolCallId } : {}),
502
+ ...(input.toolInput !== undefined
503
+ ? { tool_input: withFilePathKey(input.toolName, input.toolInput) }
504
+ : {}),
321
505
  ...(input.toolResult !== undefined
322
506
  ? { tool_result: input.toolResult, tool_response: input.toolResult }
323
507
  : {}),
@@ -327,8 +511,8 @@ export function shellHookPayload(input) {
327
511
  ...(input.toolCalls !== undefined
328
512
  ? {
329
513
  tool_calls: input.toolCalls.map((call) => ({
330
- tool_name: call.toolName,
331
- tool_input: call.toolInput,
514
+ tool_name: shellHookToolName(call.toolName, input.toolNames),
515
+ tool_input: withFilePathKey(call.toolName, call.toolInput),
332
516
  tool_use_id: call.toolCallId,
333
517
  tool_response: call.output,
334
518
  is_error: call.isError,
@@ -348,8 +532,37 @@ export function shellHookPayload(input) {
348
532
  }
349
533
  : {}),
350
534
  ...(input.stopHookActive === true ? { stop_hook_active: true } : {}),
535
+ ...(input.lastAssistantMessage !== undefined
536
+ ? { last_assistant_message: input.lastAssistantMessage }
537
+ : {}),
351
538
  });
352
539
  }
540
+ /**
541
+ * A compaction hook's fields. `compaction` keeps what it always had and gains
542
+ * `trigger`; the person's instructions and the summary are top-level
543
+ * (`custom_instructions`, null when there are none, and `compact_summary`),
544
+ * where a script reads them without opening the object.
545
+ */
546
+ function compactionFields(event, compaction) {
547
+ const { instructions, summary, ...rest } = compaction;
548
+ return {
549
+ compaction: rest,
550
+ ...(compaction.trigger !== undefined ? { trigger: compaction.trigger } : {}),
551
+ ...(event === 'pre_compact' ? { custom_instructions: instructions ?? null } : {}),
552
+ ...(event === 'post_compact' && summary !== undefined ? { compact_summary: summary } : {}),
553
+ };
554
+ }
555
+ function isExecutableFile(path) {
556
+ try {
557
+ if (!statSync(path).isFile())
558
+ return false;
559
+ accessSync(path, constants.X_OK);
560
+ return true;
561
+ }
562
+ catch {
563
+ return false;
564
+ }
565
+ }
353
566
  /** Run one hook command to completion, bounded by its deadline and capture. */
354
567
  export function runShellHook(entry, input, signal) {
355
568
  const timeoutMs = Math.min(MAX_SHELL_HOOK_TIMEOUT_MS, Math.max(1, entry.timeoutMs ?? DEFAULT_SHELL_HOOK_TIMEOUT_MS));
@@ -357,19 +570,63 @@ export function runShellHook(entry, input, signal) {
357
570
  const toolPath = pathOf(input.toolInput);
358
571
  // A hook outside a turn must not see a turn id, including one the host
359
572
  // inherited from an enclosing hook's environment.
360
- const { NAMZU_TURN_ID: _inheritedTurnId, ...inherited } = process.env;
573
+ // Nor the variables file of an enclosing hook: only the three events that own one get it.
574
+ const { NAMZU_TURN_ID: _inheritedTurnId, NAMZU_ENV_FILE: _inheritedEnvFile, ...inherited } = process.env;
575
+ const projectDir = input.projectDir ?? input.cwd;
576
+ const kernel = {
577
+ NAMZU_HOOK_EVENT: input.event,
578
+ NAMZU_SESSION_ID: input.sessionId,
579
+ NAMZU_PROJECT_DIR: projectDir,
580
+ ...(input.plugin !== undefined
581
+ ? { NAMZU_PLUGIN_ROOT: input.plugin.root, NAMZU_PLUGIN_DATA: input.plugin.dataDir }
582
+ : {}),
583
+ ...(input.turnId !== undefined ? { NAMZU_TURN_ID: input.turnId } : {}),
584
+ ...(input.envFile !== undefined ? { NAMZU_ENV_FILE: input.envFile } : {}),
585
+ ...(input.toolName !== undefined
586
+ ? { NAMZU_TOOL_NAME: shellHookToolName(input.toolName, input.toolNames) }
587
+ : {}),
588
+ ...(toolPath !== undefined ? { NAMZU_TOOL_PATH: toolPath } : {}),
589
+ };
590
+ // The entry's `env`, and any `..._PROJECT_DIR`, `..._PLUGIN_ROOT` or
591
+ // `..._PLUGIN_DATA` its command refers to without it being set, over the
592
+ // inherited environment; the kernel's own names last. A shell expands the
593
+ // variables itself, so a folder name is never read as shell text.
594
+ const pluginFolders = input.plugin;
595
+ const { env, unset } = movedEnvironment(entry, { ...inherited, ...input.extraEnv, ...kernel }, kernel, {
596
+ project: projectDir,
597
+ ...(input.skillRoot !== undefined ? { skill: input.skillRoot } : {}),
598
+ ...(input.envFile !== undefined ? { envFile: input.envFile } : {}),
599
+ ...(pluginFolders !== undefined
600
+ ? { plugin: pluginFolders.root, pluginData: pluginFolders.dataDir }
601
+ : {}),
602
+ });
603
+ // The exec form has no shell to expand them, so the values are put in.
604
+ const placed = entry.args === undefined
605
+ ? entry
606
+ : {
607
+ ...entry,
608
+ command: substituteMovedFolders(entry.command, env),
609
+ args: entry.args.map((arg) => substituteMovedFolders(arg, env)),
610
+ };
611
+ const unsetVariables = unset.length > 0 ? { unsetVariables: unset } : {};
612
+ if (pluginFolders !== undefined) {
613
+ try {
614
+ // Created when first needed; never inside the plugin's own folder.
615
+ mkdirSync(pluginFolders.dataDir, { recursive: true, mode: 0o700 });
616
+ }
617
+ catch (error) {
618
+ return Promise.resolve({
619
+ exitCode: null,
620
+ timedOut: false,
621
+ stdout: '',
622
+ stderr: '',
623
+ spawnError: `the plugin's data folder could not be created (${error instanceof Error ? error.message : String(error)})`,
624
+ });
625
+ }
626
+ }
361
627
  return new Promise((resolve) => {
362
628
  let child;
363
629
  try {
364
- const env = {
365
- ...inherited,
366
- NAMZU_HOOK_EVENT: input.event,
367
- NAMZU_SESSION_ID: input.sessionId,
368
- NAMZU_PROJECT_DIR: input.projectDir ?? input.cwd,
369
- ...(input.turnId !== undefined ? { NAMZU_TURN_ID: input.turnId } : {}),
370
- ...(input.toolName !== undefined ? { NAMZU_TOOL_NAME: input.toolName } : {}),
371
- ...(toolPath !== undefined ? { NAMZU_TOOL_PATH: toolPath } : {}),
372
- };
373
630
  // Its own process group, so the deadline can kill everything the
374
631
  // command started. `sh -c 'sleep 5'` is one process under a shell
375
632
  // that execs its last command and two under one that forks it;
@@ -378,15 +635,15 @@ export function runShellHook(entry, input, signal) {
378
635
  // its own — the hook's deadline becomes the grandchild's.
379
636
  const detached = process.platform !== 'win32';
380
637
  child =
381
- entry.args !== undefined
638
+ placed.args !== undefined
382
639
  ? // The exec form: no shell reads `command` or any argument.
383
- spawn(entry.command, [...entry.args], {
640
+ spawn(placed.command, [...placed.args], {
384
641
  cwd: input.cwd,
385
642
  env: withSessionChildMarker(env),
386
643
  stdio: ['pipe', 'pipe', 'pipe'],
387
644
  detached,
388
645
  })
389
- : spawnHostShell(entry.command, {
646
+ : spawnHostShell(placed.command, {
390
647
  cwd: input.cwd,
391
648
  env,
392
649
  stdio: ['pipe', 'pipe', 'pipe'],
@@ -396,7 +653,13 @@ export function runShellHook(entry, input, signal) {
396
653
  // when installed, cmd.exe when not.
397
654
  ...(process.platform === 'win32'
398
655
  ? {}
399
- : { shell: { path: 'sh', dialect: 'sh', source: 'sh' } }),
656
+ : {
657
+ shell: {
658
+ path: shellPathOutsideEnv('sh', inherited.PATH, env.PATH, isExecutableFile, delimiter) ?? 'sh',
659
+ dialect: 'sh',
660
+ source: 'sh',
661
+ },
662
+ }),
400
663
  });
401
664
  }
402
665
  catch (error) {
@@ -406,6 +669,7 @@ export function runShellHook(entry, input, signal) {
406
669
  stdout: '',
407
670
  stderr: '',
408
671
  spawnError: error instanceof Error ? error.message : String(error),
672
+ ...unsetVariables,
409
673
  });
410
674
  return;
411
675
  }
@@ -467,6 +731,7 @@ export function runShellHook(entry, input, signal) {
467
731
  stderr,
468
732
  ...(stdoutTruncated ? { stdoutTruncated } : {}),
469
733
  spawnError: error.message,
734
+ ...unsetVariables,
470
735
  });
471
736
  });
472
737
  child.on('close', (code) => {
@@ -476,6 +741,7 @@ export function runShellHook(entry, input, signal) {
476
741
  stdout,
477
742
  stderr,
478
743
  ...(stdoutTruncated ? { stdoutTruncated } : {}),
744
+ ...unsetVariables,
479
745
  });
480
746
  });
481
747
  child.on('exit', () => {
@@ -492,6 +758,56 @@ export function runShellHook(entry, input, signal) {
492
758
  child.stdin?.end(payload);
493
759
  });
494
760
  }
761
+ /**
762
+ * The tools whose input names a file or folder `path`. A moved script reads
763
+ * that file under the key `file_path`, so the input a hook receives carries
764
+ * both, with the same value.
765
+ */
766
+ const FILE_PATH_TOOLS = new Set([
767
+ 'read',
768
+ 'write',
769
+ 'edit',
770
+ 'grep',
771
+ 'glob',
772
+ 'ls',
773
+ 'view_image',
774
+ 'lsp',
775
+ ]);
776
+ /** `toolInput` as a hook receives it: a file tool's `path` is also `file_path`. */
777
+ function withFilePathKey(toolName, toolInput) {
778
+ if (toolName === undefined || !FILE_PATH_TOOLS.has(toolName.toLowerCase()))
779
+ return toolInput;
780
+ if (!isRecord(toolInput))
781
+ return toolInput;
782
+ const path = toolInput.path;
783
+ if (typeof path !== 'string' || 'file_path' in toolInput)
784
+ return toolInput;
785
+ return { ...toolInput, file_path: path };
786
+ }
787
+ /**
788
+ * A rewritten input read back. An echoed `file_path` is never a reason to
789
+ * refuse the rewrite: when only one of the two keys was changed that change is
790
+ * the new path; when both were changed to different values the answer cannot be
791
+ * read (`undefined`). The tool never sees `file_path`.
792
+ */
793
+ function readRewrittenInput(toolName, original, rewritten) {
794
+ if (toolName === undefined || !FILE_PATH_TOOLS.has(toolName.toLowerCase()))
795
+ return rewritten;
796
+ if (!('file_path' in rewritten))
797
+ return rewritten;
798
+ const { file_path: echoed, ...rest } = rewritten;
799
+ const before = isRecord(original) ? original.path : undefined;
800
+ const pathChanged = 'path' in rest && rest.path !== before;
801
+ const echoChanged = echoed !== before;
802
+ if (pathChanged && echoChanged && echoed !== rest.path)
803
+ return undefined;
804
+ if (!pathChanged && echoChanged) {
805
+ if (typeof echoed !== 'string')
806
+ return undefined;
807
+ return { ...rest, path: echoed };
808
+ }
809
+ return rest;
810
+ }
495
811
  function pathOf(toolInput) {
496
812
  if (toolInput === null || typeof toolInput !== 'object')
497
813
  return undefined;
@@ -504,7 +820,7 @@ function pathOf(toolInput) {
504
820
  return undefined;
505
821
  }
506
822
  /** The PascalCase spelling of each event name, which a hook's JSON may use. */
507
- const PASCAL_EVENT_NAMES = {
823
+ export const SHELL_HOOK_PASCAL_EVENT_NAMES = {
508
824
  user_prompt_submit: 'UserPromptSubmit',
509
825
  session_start: 'SessionStart',
510
826
  session_end: 'SessionEnd',
@@ -521,7 +837,36 @@ const PASCAL_EVENT_NAMES = {
521
837
  permission_denied: 'PermissionDenied',
522
838
  turn_failure: 'StopFailure',
523
839
  turn_end: 'Stop',
840
+ file_changed: 'FileChanged',
841
+ cwd_changed: 'CwdChanged',
842
+ worktree_create: 'WorktreeCreate',
843
+ worktree_remove: 'WorktreeRemove',
524
844
  };
845
+ /** The keys that carry a replacement for a tool's result. */
846
+ const REPLACEMENT_KEYS = ['updatedToolOutput', 'updatedMCPToolOutput'];
847
+ /**
848
+ * A replacement for a tool's result, whatever its JSON type. A string is the
849
+ * text; an object that has the shape of the result object a hook is sent
850
+ * (`output` a string, `success` a boolean and `error` a string when present)
851
+ * is read as that; anything else (another object, an array, a number, a
852
+ * boolean) is shown as its JSON text. The call's own success is not changed.
853
+ */
854
+ function replacementText(value) {
855
+ if (typeof value === 'string')
856
+ return value;
857
+ if (isRecord(value) &&
858
+ typeof value.output === 'string' &&
859
+ (value.success === undefined || typeof value.success === 'boolean') &&
860
+ (value.error === undefined || typeof value.error === 'string')) {
861
+ if (value.success === false && typeof value.error === 'string' && value.error !== '') {
862
+ return value.output === ''
863
+ ? `Error: ${value.error}`
864
+ : `${value.output}\n\nError: ${value.error}`;
865
+ }
866
+ return value.output;
867
+ }
868
+ return JSON.stringify(value);
869
+ }
525
870
  function isRecord(value) {
526
871
  return value !== null && typeof value === 'object' && !Array.isArray(value);
527
872
  }
@@ -531,7 +876,7 @@ function isRecord(value) {
531
876
  * sets the whole object aside rather than half-obeying it, so a typo in a
532
877
  * guard's `decision` is reported instead of silently becoming "continue".
533
878
  */
534
- function readShellHookJson(event, stdout) {
879
+ function readShellHookJson(event, stdout, call = {}) {
535
880
  const text = stdout.trim();
536
881
  if (!text.startsWith('{'))
537
882
  return undefined;
@@ -570,6 +915,28 @@ function readShellHookJson(event, stdout) {
570
915
  parsed.decision !== 'block') {
571
916
  return { invalid: '`decision` must be "approve" or "block"' };
572
917
  }
918
+ // A replacement written where it is not read (at the top level of the answer
919
+ // instead of under `hookSpecificOutput`) is a hook that clearly tried to say
920
+ // something we cannot read: set the answer aside as unreadable, so
921
+ // `onFailure: block` withholds the result rather than showing the original.
922
+ if (event === 'post_tool_use' || event === 'post_tool_use_failure') {
923
+ const misplaced = REPLACEMENT_KEYS.find((key) => parsed[key] !== undefined);
924
+ const inSpecific = isRecord(parsed.hookSpecificOutput) &&
925
+ REPLACEMENT_KEYS.some((key) => parsed.hookSpecificOutput[key] !== undefined);
926
+ if (misplaced !== undefined && !inSpecific) {
927
+ return {
928
+ invalid: `\`${misplaced}\` is read under \`hookSpecificOutput\`, not at the top level of the answer`,
929
+ };
930
+ }
931
+ }
932
+ // The same for a list of files to watch written at the top level.
933
+ if ((event === 'session_start' || event === 'file_changed' || event === 'cwd_changed') &&
934
+ parsed.watchPaths !== undefined &&
935
+ !(isRecord(parsed.hookSpecificOutput) && parsed.hookSpecificOutput.watchPaths !== undefined)) {
936
+ return {
937
+ invalid: '`watchPaths` is read under `hookSpecificOutput`, not at the top level of the answer',
938
+ };
939
+ }
573
940
  const reading = {};
574
941
  if (parsed.suppressOutput === true)
575
942
  reading.suppressOutput = true;
@@ -595,7 +962,7 @@ function readShellHookJson(event, stdout) {
595
962
  if (typeof named !== 'string') {
596
963
  return { invalid: '`hookSpecificOutput` is missing its `hookEventName`' };
597
964
  }
598
- if (named !== event && named !== PASCAL_EVENT_NAMES[event]) {
965
+ if (named !== event && named !== SHELL_HOOK_PASCAL_EVENT_NAMES[event]) {
599
966
  return {
600
967
  invalid: `\`hookSpecificOutput.hookEventName\` is "${named}" but this hook ran for ${event}`,
601
968
  };
@@ -608,6 +975,14 @@ function readShellHookJson(event, stdout) {
608
975
  if (problem)
609
976
  return { invalid: `hookSpecificOutput: ${problem}` };
610
977
  }
978
+ if ((event === 'session_start' || event === 'file_changed' || event === 'cwd_changed') &&
979
+ specific.watchPaths !== undefined) {
980
+ const list = specific.watchPaths;
981
+ if (!Array.isArray(list) || list.some((item) => typeof item !== 'string')) {
982
+ return { invalid: 'hookSpecificOutput: `watchPaths` must be a list of paths (strings)' };
983
+ }
984
+ reading.watchPaths = list.filter((item) => item.trim() !== '');
985
+ }
611
986
  const additional = optionalString('additionalContext', specific);
612
987
  if (additional && additional.trim().length > 0)
613
988
  reading.context = additional.trim();
@@ -632,14 +1007,25 @@ function readShellHookJson(event, stdout) {
632
1007
  if (specific.updatedInput !== undefined) {
633
1008
  if (!isRecord(specific.updatedInput))
634
1009
  return { invalid: '`updatedInput` must be an object' };
635
- reading.updatedInput = specific.updatedInput;
1010
+ const rewritten = readRewrittenInput(call.toolName, call.toolInput, specific.updatedInput);
1011
+ if (rewritten === undefined) {
1012
+ return {
1013
+ invalid: '`updatedInput` changes both `path` and `file_path`, to different values: say which file is meant',
1014
+ };
1015
+ }
1016
+ reading.updatedInput = rewritten;
636
1017
  }
637
1018
  }
638
- if (event === 'post_tool_use' && specific.updatedToolOutput !== undefined) {
639
- if (typeof specific.updatedToolOutput !== 'string') {
640
- return { invalid: 'hookSpecificOutput: `updatedToolOutput` must be a string' };
1019
+ if (event === 'post_tool_use' || event === 'post_tool_use_failure') {
1020
+ // For a tool-server tool the common contract has a second field, read
1021
+ // when `updatedToolOutput` is absent or null. `updatedToolOutput` wins when
1022
+ // both carry a value: it is the field for every tool, so a script that
1023
+ // sets both has said the general thing last.
1024
+ const toolServer = call.toolName?.startsWith('mcp__') === true;
1025
+ const chosen = specific.updatedToolOutput ?? (toolServer ? specific.updatedMCPToolOutput : undefined);
1026
+ if (chosen !== undefined && chosen !== null) {
1027
+ reading.replacement = boundHookReplacement(replacementText(chosen));
641
1028
  }
642
- reading.replacement = boundHookReplacement(specific.updatedToolOutput);
643
1029
  }
644
1030
  if (event === 'permission_request') {
645
1031
  const decision = specific.decision;
@@ -667,17 +1053,22 @@ function readShellHookJson(event, stdout) {
667
1053
  * so the mapping — the part that decides what the model is told — is
668
1054
  * testable without a process.
669
1055
  */
670
- export function shellHookVerdict(event, entry, outcome, log = NOOP_LOGGER) {
1056
+ export function shellHookVerdict(event, entry, outcome, log = NOOP_LOGGER, call = {}) {
671
1057
  const label = describeShellHook(entry);
672
1058
  const attrs = {
673
1059
  'namzu.hook.event': event,
674
1060
  'namzu.hook.command': label,
675
1061
  };
1062
+ // A program or file that was not found, with a variable in the command that
1063
+ // is set nowhere: the line says which, and what to do about it.
1064
+ const hint = hookUnsetVariableHint(outcome);
676
1065
  // A failure of the hook itself is "carry on" unless the entry asked for
677
1066
  // it to count as a refusal, which is exit 2 with the failure as the reason.
678
1067
  const failed = (reason, shown = reason) => {
679
1068
  if (entry.onFailure !== 'block' || entry.type === 'prompt' || isAsyncShellHook(entry)) {
680
- return { action: 'continue' };
1069
+ return hint !== undefined
1070
+ ? { action: 'continue', notice: `${label}: ${hint}` }
1071
+ : { action: 'continue' };
681
1072
  }
682
1073
  // The call has run and a refusal cannot undo it, but the hook may have
683
1074
  // been the one thing keeping something out of the result (a redaction),
@@ -692,14 +1083,15 @@ export function shellHookVerdict(event, entry, outcome, log = NOOP_LOGGER) {
692
1083
  disclose: true,
693
1084
  };
694
1085
  }
695
- return shellHookVerdict(event, { ...entry, onFailure: 'continue' }, { exitCode: 2, timedOut: false, stdout: '', stderr: `hook failed: ${reason}` }, log);
1086
+ return shellHookVerdict(event, { ...entry, onFailure: 'continue' }, { exitCode: 2, timedOut: false, stdout: '', stderr: `hook failed: ${reason}` }, log, call);
696
1087
  };
697
1088
  if (outcome.spawnError !== undefined) {
698
1089
  log.warn('hook could not start', {
699
1090
  ...attrs,
700
1091
  'namzu.hook.error': outcome.spawnError,
1092
+ ...(hint !== undefined ? { 'namzu.hook.hint': hint } : {}),
701
1093
  });
702
- return failed(`could not start (${outcome.spawnError})`);
1094
+ return failed(`could not start (${outcome.spawnError})${hint !== undefined ? `; ${hint}` : ''}`);
703
1095
  }
704
1096
  if (outcome.timedOut) {
705
1097
  log.warn('hook timed out', attrs);
@@ -736,8 +1128,9 @@ export function shellHookVerdict(event, entry, outcome, log = NOOP_LOGGER) {
736
1128
  ...attrs,
737
1129
  'namzu.hook.exit': outcome.exitCode ?? -1,
738
1130
  'namzu.hook.stderr': outcome.stderr.trim().slice(0, 500),
1131
+ ...(hint !== undefined ? { 'namzu.hook.hint': hint } : {}),
739
1132
  });
740
- return failed(`exited with ${outcome.exitCode ?? 'no code'}`);
1133
+ return failed(`exited with ${outcome.exitCode ?? 'no code'}${hint !== undefined ? `; ${hint}` : ''}`);
741
1134
  }
742
1135
  // Exit 0.
743
1136
  const text = outcome.stdout.trim();
@@ -745,12 +1138,27 @@ export function shellHookVerdict(event, entry, outcome, log = NOOP_LOGGER) {
745
1138
  ? {
746
1139
  invalid: `answer is too large: the hook printed more than the ${MAX_CAPTURE_BYTES} characters of stdout that are read`,
747
1140
  }
748
- : readShellHookJson(event, outcome.stdout);
1141
+ : readShellHookJson(event, outcome.stdout, call);
749
1142
  if (reading === undefined) {
1143
+ // A post-tool hook whose plain output (or whose stderr) names a replacement
1144
+ // key tried to replace the result and put the answer where it is not read
1145
+ // (a log line before the JSON, the JSON on stderr). That is an answer that
1146
+ // does not read, so it follows `onFailure` like one.
1147
+ if ((event === 'post_tool_use' || event === 'post_tool_use_failure') &&
1148
+ REPLACEMENT_KEYS.some((key) => outcome.stdout.includes(key) || outcome.stderr.includes(key))) {
1149
+ log.warn('hook output ignored', {
1150
+ ...attrs,
1151
+ 'namzu.hook.problem': 'a replacement is named but the answer is not a JSON object on stdout',
1152
+ });
1153
+ return failed('its answer names a replacement but is not a JSON object that starts stdout');
1154
+ }
750
1155
  // On the prompt event, what the hook printed is context for the
751
1156
  // model — the branch, the time, a ticket. Everywhere else stdout is
752
1157
  // the operator's to read and the model's business not at all.
753
- if ((event === 'user_prompt_submit' || event === 'subagent_start' || event === 'session_start') &&
1158
+ if ((event === 'user_prompt_submit' ||
1159
+ event === 'subagent_start' ||
1160
+ event === 'session_start' ||
1161
+ event === 'pre_compact') &&
754
1162
  text.length > 0)
755
1163
  return { action: 'annotate', text };
756
1164
  return { action: 'continue' };
@@ -817,13 +1225,33 @@ export function shellHookVerdict(event, entry, outcome, log = NOOP_LOGGER) {
817
1225
  // Nothing here can be refused. What the hook said for the model becomes
818
1226
  // the session's context; a stop request and a warning still count.
819
1227
  return reading.context !== undefined
820
- ? { action: 'annotate', text: reading.context }
1228
+ ? {
1229
+ action: 'annotate',
1230
+ text: reading.context,
1231
+ ...(reading.watchPaths !== undefined ? { watchPaths: reading.watchPaths } : {}),
1232
+ ...(reading.notice ? { notice: reading.notice } : {}),
1233
+ }
821
1234
  : {
822
1235
  action: 'continue',
823
1236
  ...(reading.halt ? { halt: reading.halt } : {}),
824
1237
  ...(reading.notice ? { notice: reading.notice } : {}),
1238
+ ...(reading.watchPaths !== undefined ? { watchPaths: reading.watchPaths } : {}),
825
1239
  };
826
1240
  }
1241
+ case 'worktree_create':
1242
+ case 'worktree_remove':
1243
+ // Read by `worktreeHookVerdict`, which the handler calls for these two
1244
+ // events; a caller that gets here has no run to read.
1245
+ return { action: 'continue' };
1246
+ case 'file_changed':
1247
+ case 'cwd_changed':
1248
+ // Nothing here can be refused and nothing reaches the model: what the hook
1249
+ // can say is a line for the person and the files to watch from now on.
1250
+ return {
1251
+ action: 'continue',
1252
+ ...(reading.notice ? { notice: reading.notice } : {}),
1253
+ ...(reading.watchPaths !== undefined ? { watchPaths: reading.watchPaths } : {}),
1254
+ };
827
1255
  case 'post_tool_use':
828
1256
  case 'post_tool_use_failure': {
829
1257
  // The call has run, so a "block" cannot undo it: its reason is what the
@@ -871,6 +1299,8 @@ export function shellHookVerdict(event, entry, outcome, log = NOOP_LOGGER) {
871
1299
  };
872
1300
  }
873
1301
  case 'pre_compact':
1302
+ // What the hook said is for the summariser: it rides as `context` on
1303
+ // either answer (a refusal a forced pass overrides is still heard).
874
1304
  return reading.block !== undefined
875
1305
  ? { action: 'skip', reason: reading.block, ...notes }
876
1306
  : { action: 'continue', ...notes };
@@ -985,9 +1415,52 @@ function readJudgement(reply) {
985
1415
  return undefined;
986
1416
  }
987
1417
  }
1418
+ /**
1419
+ * One run of a `worktree_create` or `worktree_remove` hook, to its answer. It
1420
+ * is always awaited (an `async` flag cannot make a hook that does the work run
1421
+ * out of sight), and a `prompt` hook cannot do it at all, which is said as a
1422
+ * failure rather than skipped.
1423
+ */
1424
+ async function runWorktreeHook(event, entry, input, signal, reportTimeout) {
1425
+ const label = describeShellHook(entry);
1426
+ if (entry.type === 'prompt') {
1427
+ return {
1428
+ action: 'error',
1429
+ message: `The ${event} hook \`${label}\` is a prompt, and a prompt cannot make or remove a worktree. Use a command or an http hook.`,
1430
+ };
1431
+ }
1432
+ if (entry.type === 'http') {
1433
+ const response = await postHookJson({
1434
+ url: entry.url,
1435
+ body: shellHookPayload(input),
1436
+ ...(entry.headers !== undefined ? { headers: entry.headers } : {}),
1437
+ ...(entry.allowedEnvVars !== undefined ? { allowedEnvVars: entry.allowedEnvVars } : {}),
1438
+ timeoutMs: hookTimeout(entry),
1439
+ ...(signal !== undefined ? { signal } : {}),
1440
+ });
1441
+ reportTimeout(response.timedOut);
1442
+ const ok = response.status !== null && response.status >= 200 && response.status < 300;
1443
+ return worktreeHookVerdict(event, label, {
1444
+ exitCode: ok ? 0 : (response.status ?? null),
1445
+ timedOut: response.timedOut,
1446
+ stdout: ok ? response.body : '',
1447
+ stderr: ok ? '' : response.body.slice(0, 500),
1448
+ ...(response.error !== undefined ? { spawnError: response.error } : {}),
1449
+ });
1450
+ }
1451
+ const outcome = await runShellHook(entry, input, signal);
1452
+ reportTimeout(outcome.timedOut);
1453
+ return worktreeHookVerdict(event, label, outcome);
1454
+ }
1455
+ /**
1456
+ * The place a hook has among the ones that set variables: entries are made in
1457
+ * configuration order, so a later number is a later line in the file.
1458
+ */
1459
+ let nextHookEnvSlot = 0;
988
1460
  /** One entry as a hook definition the lifecycle manager accepts. */
989
1461
  export function createShellHook(event, configured, options) {
990
1462
  const log = options.log ?? NOOP_LOGGER;
1463
+ const envSlot = nextHookEnvSlot++;
991
1464
  const eventDefault = options.defaultTimeoutMs?.[event];
992
1465
  const entry = configured.timeoutMs === undefined && eventDefault !== undefined
993
1466
  ? { ...configured, timeoutMs: eventDefault }
@@ -1005,37 +1478,82 @@ export function createShellHook(event, configured, options) {
1005
1478
  return {
1006
1479
  event,
1007
1480
  ...(entry.statusMessage !== undefined ? { statusMessage: entry.statusMessage } : {}),
1481
+ // A file named by the matcher is watched for as long as the hook is attached.
1482
+ ...(event === 'file_changed' && fileChangedMatcherPaths(entry.matcher).length > 0
1483
+ ? { watches: fileChangedMatcherPaths(entry.matcher) }
1484
+ : {}),
1008
1485
  handler: async (context) => {
1009
- if (spent)
1486
+ if (spent && event !== 'worktree_create' && event !== 'worktree_remove') {
1010
1487
  return { action: 'continue' };
1488
+ }
1011
1489
  // A notification is matched on its type; every other event on the tool.
1012
- const namesATool = !(event === 'notification' ||
1490
+ const namesATool = !(event === 'pre_compact' ||
1491
+ event === 'post_compact' ||
1492
+ event === 'notification' ||
1013
1493
  event === 'subagent_start' ||
1014
1494
  event === 'subagent_stop' ||
1015
1495
  event === 'session_start' ||
1016
1496
  event === 'session_end');
1017
1497
  const subject = event === 'notification'
1018
1498
  ? context.notification?.type
1019
- : event === 'subagent_start' || event === 'subagent_stop'
1020
- ? context.agentType
1021
- : event === 'session_start'
1022
- ? context.source
1023
- : event === 'session_end'
1024
- ? context.endReason
1025
- : context.toolName;
1026
- if (!shellHookMatches(entry.matcher, subject, { tool: namesATool }))
1499
+ : event === 'pre_compact' || event === 'post_compact'
1500
+ ? context.compaction?.trigger
1501
+ : event === 'subagent_start' || event === 'subagent_stop'
1502
+ ? context.agentType
1503
+ : event === 'session_start'
1504
+ ? context.source
1505
+ : event === 'session_end'
1506
+ ? context.endReason
1507
+ : context.toolName;
1508
+ // An event that has no name to match (`turn_end`, `user_prompt_submit`,
1509
+ // `turn_start`, `post_tool_batch`) ignores the matcher and the hook
1510
+ // fires: a matcher cannot be read against a name that is not there, and
1511
+ // a guard that never fires is the failure to avoid. The compaction
1512
+ // events are matched on `trigger`.
1513
+ if (subject !== undefined && !shellHookMatches(entry.matcher, subject, { tool: namesATool }))
1027
1514
  return { action: 'continue' };
1028
- if (!shellHookIfMatches(entry.if, context.toolName, context.toolInput, options.pathFilter)) {
1515
+ // A changed file is matched on its base name, and a matcher written as a
1516
+ // path stands for the file's name: `config/app.json` is `app.json`.
1517
+ if (event === 'file_changed' && !fileChangedMatches(entry.matcher, context.filePath)) {
1029
1518
  return { action: 'continue' };
1030
1519
  }
1031
- if (entry.once === true)
1520
+ // A worktree hook does the work itself, so a filter or a one-shot flag on
1521
+ // it could only make the kernel act where the person wanted the hook to:
1522
+ // both are ignored there, and the hook always runs.
1523
+ const doesTheWork = event === 'worktree_create' || event === 'worktree_remove';
1524
+ if (!doesTheWork &&
1525
+ !shellHookIfMatches(entry.if, context.toolName, context.toolInput, options.pathFilter)) {
1526
+ return { action: 'continue' };
1527
+ }
1528
+ if (entry.once === true && !doesTheWork)
1032
1529
  spent = true;
1530
+ options.onRun?.({ event });
1033
1531
  const transcriptPath = options.transcriptPath?.(String(context.sessionId));
1034
1532
  const permissionMode = options.permissionMode?.();
1533
+ const envEvent = event === 'session_start' || event === 'cwd_changed' || event === 'file_changed'
1534
+ ? event
1535
+ : undefined;
1536
+ const runsACommand = entry.type === undefined || entry.type === 'command';
1537
+ const envFile = envEvent !== undefined && runsACommand
1538
+ ? options.hookEnv?.fileFor(envEvent, envSlot)
1539
+ : undefined;
1035
1540
  const hookInput = {
1036
1541
  event,
1037
- cwd: options.cwd,
1542
+ // A hook told the folder changed runs in the folder entered.
1543
+ cwd: event === 'cwd_changed' && context.newCwd !== undefined ? context.newCwd : options.cwd,
1544
+ ...(envFile !== undefined ? { envFile } : {}),
1545
+ ...(context.filePath !== undefined ? { filePath: context.filePath } : {}),
1546
+ ...(context.change !== undefined ? { change: context.change } : {}),
1547
+ ...(context.oldCwd !== undefined ? { oldCwd: context.oldCwd } : {}),
1548
+ ...(context.newCwd !== undefined ? { newCwd: context.newCwd } : {}),
1549
+ ...(context.worktreeName !== undefined ? { worktreeName: context.worktreeName } : {}),
1550
+ ...(context.worktreeRoot !== undefined ? { worktreeRoot: context.worktreeRoot } : {}),
1551
+ ...(context.worktreeBaseRef !== undefined
1552
+ ? { worktreeBaseRef: context.worktreeBaseRef }
1553
+ : {}),
1554
+ ...(context.worktreePath !== undefined ? { worktreePath: context.worktreePath } : {}),
1038
1555
  ...(options.projectDir !== undefined ? { projectDir: options.projectDir } : {}),
1556
+ ...(options.plugin !== undefined ? { plugin: options.plugin } : {}),
1039
1557
  sessionId: String(context.sessionId),
1040
1558
  ...(context.source !== undefined ? { sessionSource: context.source } : {}),
1041
1559
  ...(context.endReason !== undefined ? { endReason: context.endReason } : {}),
@@ -1050,6 +1568,8 @@ export function createShellHook(event, configured, options) {
1050
1568
  ...(context.prompt !== undefined ? { prompt: context.prompt } : {}),
1051
1569
  ...(context.compaction !== undefined ? { compaction: context.compaction } : {}),
1052
1570
  ...(context.toolName !== undefined ? { toolName: context.toolName } : {}),
1571
+ ...(entry.toolNames !== undefined ? { toolNames: entry.toolNames } : {}),
1572
+ ...(context.toolCallId !== undefined ? { toolCallId: context.toolCallId } : {}),
1053
1573
  ...(context.toolInput !== undefined ? { toolInput: context.toolInput } : {}),
1054
1574
  ...(context.toolResult !== undefined
1055
1575
  ? {
@@ -1067,9 +1587,21 @@ export function createShellHook(event, configured, options) {
1067
1587
  ...(context.error !== undefined ? { error: context.error } : {}),
1068
1588
  ...(context.notification !== undefined ? { notification: context.notification } : {}),
1069
1589
  ...(context.stopHookActive === true ? { stopHookActive: true } : {}),
1590
+ ...(context.lastAssistantMessage !== undefined
1591
+ ? { lastAssistantMessage: context.lastAssistantMessage }
1592
+ : {}),
1070
1593
  ...(transcriptPath !== undefined ? { transcriptPath } : {}),
1071
1594
  ...(permissionMode !== undefined ? { permissionMode } : {}),
1595
+ ...(options.extraEnv !== undefined ? { extraEnv: options.extraEnv } : {}),
1596
+ ...(options.skillRoot !== undefined ? { skillRoot: options.skillRoot } : {}),
1072
1597
  };
1598
+ const verdictCall = {
1599
+ ...(context.toolName !== undefined ? { toolName: context.toolName } : {}),
1600
+ ...(context.toolInput !== undefined ? { toolInput: context.toolInput } : {}),
1601
+ };
1602
+ if (event === 'worktree_create' || event === 'worktree_remove') {
1603
+ return runWorktreeHook(event, entry, hookInput, context.signal, reportTimeout);
1604
+ }
1073
1605
  if (entry.type === 'http') {
1074
1606
  const response = await postHookJson({
1075
1607
  url: entry.url,
@@ -1087,7 +1619,7 @@ export function createShellHook(event, configured, options) {
1087
1619
  stdout: ok ? response.body : '',
1088
1620
  stderr: ok ? '' : response.body.slice(0, 500),
1089
1621
  ...(response.error !== undefined ? { spawnError: response.error } : {}),
1090
- }, log);
1622
+ }, log, verdictCall);
1091
1623
  }
1092
1624
  if (entry.type === 'prompt') {
1093
1625
  return judgePromptHook(event, entry, hookInput, options.judge, context.signal, log);
@@ -1097,14 +1629,27 @@ export function createShellHook(event, configured, options) {
1097
1629
  // for it and its own failure is only written down.
1098
1630
  void runShellHook(entry, hookInput)
1099
1631
  .then((outcome) => {
1100
- shellHookVerdict(event, entry, outcome, log);
1632
+ if (envEvent !== undefined)
1633
+ options.hookEnv?.absorb(envEvent, envSlot);
1634
+ const verdict = shellHookVerdict(event, entry, outcome, log, verdictCall);
1635
+ if (verdict.action !== 'continue') {
1636
+ log.warn('an async hook answered, and its answer is not applied', {
1637
+ 'namzu.hook.event': event,
1638
+ 'namzu.hook.command': describeShellHook(entry),
1639
+ 'namzu.hook.action': verdict.action,
1640
+ });
1641
+ }
1101
1642
  })
1102
1643
  .catch(() => undefined);
1103
1644
  return { action: 'continue' };
1104
1645
  }
1105
1646
  const outcome = await runShellHook(entry, hookInput, context.signal);
1647
+ // What the hook appended counts even when it was ended or failed after
1648
+ // writing it: the lines are data it already gave.
1649
+ if (envEvent !== undefined)
1650
+ options.hookEnv?.absorb(envEvent, envSlot);
1106
1651
  reportTimeout(outcome.timedOut);
1107
- return shellHookVerdict(event, entry, outcome, log);
1652
+ return shellHookVerdict(event, entry, outcome, log, verdictCall);
1108
1653
  },
1109
1654
  };
1110
1655
  }