返回 CodeWhale
executor.rs
根目录 / crates / engine / src / hooks / executor.rs
1 use chrono::{DateTime, Utc};
2 use codewhale_config::hooks::{Hook, HookCondition, HookEvent, HooksConfig};
3 use serde_json::json;
4 use std::collections::HashMap;
5 use std::fmt;
6 use std::io::{Read, Write};
7 use std::path::PathBuf;
8 use std::process::{Child, Command, Stdio};
9 use std::sync::mpsc::{self, Receiver, RecvTimeoutError, SyncSender, TrySendError};
10 use std::sync::{Arc, Mutex};
11 use std::thread::JoinHandle;
12 use std::time::{Duration, Instant};
13 use wait_timeout::ChildExt;
14
15 use codewhale_runtime::process_tree::ProcessTree;
16
17 /// Core-only caller receipt. Not exported as an environment value or accepted from JS.
18 #[derive(Debug, Clone)]
19 pub struct HookCaller {
20 pub workspace: PathBuf,
21 pub plugins: Option<Arc<codewhale_plugins::PluginRegistry>>,
22 pub session_id: Option<String>,
23 pub agent_id: Option<String>,
24 pub origin_turn_id: Option<String>,
25 pub origin_call_id: Option<String>,
26 }
27 impl HookCaller {
28 pub fn from_tool(context: &crate::tools::spec::ToolContext) -> Self {
29 Self {
30 workspace: context.workspace.clone(),
31 plugins: context.plugin_registry.clone(),
32 session_id: context
33 .session_objects
34 .as_ref()
35 .map(|s| s.session_id.clone()),
36 agent_id: context.owner_agent_id.clone(),
37 origin_turn_id: context.origin_turn_id.clone(),
38 origin_call_id: context.origin_tool_call_id.clone(),
39 }
40 }
41 }
42
43 /// Context passed to hooks via environment variables
44 #[derive(Debug, Clone, Default)]
45 pub struct HookContext {
46 pub canonical_input: Option<serde_json::Value>,
47 pub caller: Option<HookCaller>,
48 /// Tool name (for ToolCallBefore/After)
49 pub tool_name: Option<String>,
50 /// Engine-assigned tool call id, so a `tool_call_before` record and the
51 /// matching `tool_call_after` / `on_error` record can be correlated.
52 pub tool_call_id: Option<String>,
53 /// Tool arguments as JSON string
54 pub tool_args: Option<String>,
55 /// Tool result output (truncated)
56 pub tool_result: Option<String>,
57 /// Tool exit code if applicable.
58 ///
59 /// `i64` end-to-end: a Windows crash code such as `3221225477`
60 /// (`0xC0000005`) is a real value `exec_shell` reports, and narrowing it
61 /// to `i32` used to discard exactly the failures a hook most wants to see.
62 pub tool_exit_code: Option<i64>,
63 /// How a process-backed tool ended (`completed`, `failed`, `timed_out`,
64 /// `killed`, `running`), when it reported one. A timed-out or killed
65 /// command usually has no exit code, so this is how a hook tells it apart
66 /// from a tool that reported nothing.
67 pub tool_status: Option<String>,
68 /// Serialized post-admission shell execution receipt (#6689), exported as
69 /// `DEEPSEEK_TOOL_EXECUTION_RECEIPT`. Complete JSON or absent — never a
70 /// truncated document — and at most [`HOOK_EXECUTION_RECEIPT_MAX_BYTES`].
71 pub tool_execution_receipt: Option<String>,
72 /// Whether tool succeeded
73 pub tool_success: Option<bool>,
74 /// Current mode
75 pub mode: Option<String>,
76 /// Previous mode (for `ModeChange`)
77 pub previous_mode: Option<String>,
78 /// Session ID
79 pub session_id: Option<String>,
80 /// User message content
81 pub message: Option<String>,
82 /// Error message (for `OnError`)
83 pub error_message: Option<String>,
84 /// Workspace path
85 pub workspace: Option<PathBuf>,
86 /// Current model name
87 pub model: Option<String>,
88 /// Total tokens used
89 pub total_tokens: Option<u32>,
90 /// Session cost in USD
91 pub session_cost: Option<f64>,
92 }
93
94 impl HookContext {
95 fn native_payload(
96 &self,
97 point: &str,
98 existing: Option<&serde_json::Value>,
99 ) -> Result<serde_json::Value, String> {
100 let caller = self
101 .caller
102 .as_ref()
103 .ok_or("Native hook has no caller identity")?;
104 let mut payload = json!({"session_id":caller.session_id,"cwd":caller.workspace,"transcript_path":"","hook_event_name":point});
105 let object = payload.as_object_mut().expect("payload");
106 match point {
107 "PreToolUse" | "PostToolUse" => {
108 object.insert("tool_name".into(), json!(self.tool_name));
109 object.insert("tool_use_id".into(), json!(self.tool_call_id));
110 object.insert(
111 "tool_input".into(),
112 self.canonical_input
113 .clone()
114 .ok_or("Native hook tool input exceeds 32 KiB or is missing")?,
115 );
116 if point == "PostToolUse" {
117 object.insert("tool_response".into(), json!(self.tool_result));
118 }
119 }
120 "UserPromptSubmit" => {
121 object.insert("prompt".into(), json!(self.message));
122 }
123 "SessionStart" => {
124 object.insert("source".into(), json!("startup"));
125 }
126 "Stop" => {
127 object.insert("stop_hook_active".into(), json!(false));
128 }
129 "SubagentStart" | "SubagentStop" => {
130 let id = existing
131 .and_then(|v| v.get("agent_id"))
132 .and_then(serde_json::Value::as_str)
133 .ok_or("subagent hook has no actual child identity")?;
134 object.insert("agent_id".into(), json!(id));
135 object.insert("agent_type".into(), json!("general-purpose"));
136 if point == "SubagentStop" {
137 object.insert("stop_hook_active".into(), json!(false));
138 }
139 }
140 _ => return Err("unknown Native dialect firepoint".into()),
141 }
142 if serde_json::to_vec(&payload)
143 .map_err(|_| "Native hook payload is not JSON")?
144 .len()
145 > 32 * 1024
146 {
147 return Err("Native hook payload exceeds 32 KiB".into());
148 }
149 Ok(payload)
150 }
151
152 pub fn with_caller(mut self, caller: HookCaller) -> Self {
153 self.caller = Some(caller);
154 self
155 }
156 pub fn with_tool_context(self, context: &crate::tools::spec::ToolContext) -> Self {
157 self.with_caller(HookCaller::from_tool(context))
158 }
159 pub fn new() -> Self {
160 Self::default()
161 }
162
163 pub fn with_tool_name(mut self, name: &str) -> Self {
164 self.tool_name = Some(name.to_string());
165 self
166 }
167
168 pub fn with_tool_call_id(mut self, id: &str) -> Self {
169 self.tool_call_id = Some(id.to_string());
170 self
171 }
172
173 pub fn with_tool_args(mut self, args: &serde_json::Value) -> Self {
174 self.canonical_input = (args.to_string().len() <= 32 * 1024).then(|| args.clone());
175 self.tool_args = Some(truncate_env_value(
176 &args.to_string(),
177 HOOK_TOOL_ARGS_ENV_MAX_BYTES,
178 ));
179 self
180 }
181
182 pub fn with_tool_result(mut self, result: &str, success: bool, exit_code: Option<i64>) -> Self {
183 self.tool_result = Some(truncate_env_value(
184 result,
185 HOOK_TOOL_RESULT_CONTEXT_MAX_BYTES,
186 ));
187 self.tool_success = Some(success);
188 self.tool_exit_code = exit_code;
189 self
190 }
191
192 /// Record a settled tool call: its text, success flag, and — when the
193 /// tool reported them, on success or failure — its exit code and status.
194 /// The TUI and Runtime API completion hooks both build their context here.
195 pub fn with_tool_outcome(
196 self,
197 result: &Result<crate::tools::spec::ToolResult, crate::tools::spec::ToolError>,
198 ) -> Self {
199 let (text, success) = match result {
200 Ok(output) => (output.content.clone(), output.success),
201 Err(error) => (error.to_string(), false),
202 };
203 let mut context = self.with_tool_result(&text, success, reported_tool_exit_code(result));
204 context.tool_status = reported_tool_status(result).map(str::to_string);
205 context.tool_execution_receipt = reported_tool_execution_receipt(result);
206 context
207 }
208
209 pub fn with_mode(mut self, mode: &str) -> Self {
210 self.mode = Some(mode.to_string());
211 self
212 }
213
214 pub fn with_previous_mode(mut self, mode: &str) -> Self {
215 self.previous_mode = Some(mode.to_string());
216 self
217 }
218
219 pub fn with_workspace(mut self, path: PathBuf) -> Self {
220 self.workspace = Some(path);
221 self
222 }
223
224 pub fn with_model(mut self, model: &str) -> Self {
225 self.model = Some(model.to_string());
226 self
227 }
228
229 pub fn with_session_id(mut self, session_id: &str) -> Self {
230 self.session_id = Some(session_id.to_string());
231 self
232 }
233
234 pub fn with_message(mut self, message: &str) -> Self {
235 self.message = Some(message.to_string());
236 self
237 }
238
239 pub fn with_error(mut self, error: &str) -> Self {
240 self.error_message = Some(truncate_env_value(error, HOOK_ERROR_CONTEXT_MAX_BYTES));
241 self
242 }
243
244 pub fn with_tokens(mut self, tokens: u32) -> Self {
245 self.total_tokens = Some(tokens);
246 self
247 }
248
249 /// Clamp all observer-owned strings before the context is cloned into a
250 /// bounded queue. Builders already apply these limits, but fields remain
251 /// public for compatibility, so the submission boundary must defend
252 /// itself against a directly-constructed context too.
253 fn bounded_for_observer(mut self) -> Self {
254 fn bound(value: &mut Option<String>, max_bytes: usize) {
255 if let Some(raw) = value.take() {
256 *value = Some(truncate_env_value(&raw, max_bytes));
257 }
258 }
259
260 bound(&mut self.tool_name, HOOK_OBSERVER_METADATA_MAX_BYTES);
261 bound(&mut self.tool_call_id, HOOK_OBSERVER_METADATA_MAX_BYTES);
262 bound(&mut self.tool_args, HOOK_TOOL_ARGS_ENV_MAX_BYTES);
263 bound(&mut self.tool_result, HOOK_TOOL_RESULT_CONTEXT_MAX_BYTES);
264 bound(&mut self.mode, HOOK_OBSERVER_METADATA_MAX_BYTES);
265 bound(&mut self.previous_mode, HOOK_OBSERVER_METADATA_MAX_BYTES);
266 bound(&mut self.session_id, HOOK_OBSERVER_METADATA_MAX_BYTES);
267 bound(&mut self.message, HOOK_MESSAGE_CONTEXT_MAX_BYTES);
268 bound(&mut self.error_message, HOOK_ERROR_CONTEXT_MAX_BYTES);
269 bound(&mut self.model, HOOK_OBSERVER_METADATA_MAX_BYTES);
270 // A receipt is complete JSON or nothing: truncating it would export a
271 // broken document, so an oversized one is dropped instead.
272 if self
273 .tool_execution_receipt
274 .as_ref()
275 .is_some_and(|receipt| receipt.len() > HOOK_EXECUTION_RECEIPT_MAX_BYTES)
276 {
277 self.tool_execution_receipt = None;
278 }
279 if let Some(workspace) = self.workspace.take() {
280 self.workspace = Some(PathBuf::from(truncate_env_value(
281 &workspace.to_string_lossy(),
282 HOOK_OBSERVER_METADATA_MAX_BYTES,
283 )));
284 }
285 self
286 }
287
288 /// Project the shell's post-admission receipt into the versioned observer
289 /// contract. Never reconstruct execution identity from requested arguments.
290 fn tool_after_payload(&self) -> Option<serde_json::Value> {
291 let tool_name = self.tool_name.as_deref()?;
292 if !is_shell_tool_name(tool_name) {
293 return None;
294 }
295 let encoded = self.tool_execution_receipt.as_deref()?;
296 if encoded.len() > HOOK_EXECUTION_RECEIPT_MAX_BYTES {
297 return None;
298 }
299 let receipt: serde_json::Value = serde_json::from_str(encoded).ok()?;
300 if receipt.get("schema_version")?.as_u64()? != 1
301 || receipt.get("scope")?.as_str()? != "local"
302 || !matches!(receipt.get("state")?.as_str()?, "completed" | "interrupted")
303 {
304 return None;
305 }
306 let completion = self.tool_status.as_deref()?;
307 if !matches!(completion, "completed" | "failed" | "killed" | "timed_out") {
308 return None;
309 }
310 let command = receipt.get("command")?.as_str()?;
311 let cwd = receipt.get("cwd")?.as_str()?;
312 if command.is_empty()
313 || command.contains('\0')
314 || cwd.contains('\0')
315 || !std::path::Path::new(cwd).is_absolute()
316 {
317 return None;
318 }
319 let exit_code = receipt.get("exit_code")?;
320 if !exit_code.is_null() && exit_code.as_i64().is_none() {
321 return None;
322 }
323 let output_mode = receipt.get("output_kind")?.as_str()?;
324 let stdout = receipt.get("stdout")?.as_str()?;
325 let stderr = receipt.get("stderr")?.as_str()?;
326 if !matches!(output_mode, "separate" | "combined")
327 || (output_mode == "combined" && !stderr.is_empty())
328 {
329 return None;
330 }
331 // Bound correlation fields before the observer queue clamps its legacy
332 // environment context, so every stdin truncation flag remains truthful.
333 const ID_MAX_BYTES: usize = 1_024;
334 let bounded_id =
335 |id: &Option<String>| id.as_deref().map(|s| truncate_env_value(s, ID_MAX_BYTES));
336 let clipped_id = |id: &Option<String>| id.as_ref().is_some_and(|s| s.len() > ID_MAX_BYTES);
337 let payload = json!({
338 "schema_version": 1,
339 "event": "tool_call_after",
340 "tool_name": tool_name,
341 "session_id": bounded_id(&self.session_id),
342 "tool_call_id": bounded_id(&self.tool_call_id),
343 "session_id_truncated": clipped_id(&self.session_id),
344 "tool_call_id_truncated": clipped_id(&self.tool_call_id),
345 "tool_name_truncated": false,
346 "execution_receipt": {
347 "schema_version": 1,
348 "command": command,
349 "cwd": cwd,
350 "command_truncated": false,
351 "cwd_truncated": false,
352 "execution": "started",
353 "completion": completion,
354 "exit_code": exit_code,
355 "stdout": stdout,
356 "stderr": stderr,
357 "stdout_truncated": receipt.get("stdout_truncated")?.as_bool()?,
358 "stderr_truncated": receipt.get("stderr_truncated")?.as_bool()?,
359 "output_mode": output_mode,
360 },
361 });
362 (serde_json::to_vec(&payload).ok()?.len() <= 64 * 1024).then_some(payload)
363 }
364
365 /// Convert to environment variables
366 pub fn to_env_vars(&self) -> HashMap<String, String> {
367 let mut env = HashMap::new();
368
369 if let Some(ref name) = self.tool_name {
370 env.insert("DEEPSEEK_TOOL_NAME".to_string(), name.clone());
371 }
372 if let Some(ref id) = self.tool_call_id {
373 env.insert("CODEWHALE_TOOL_CALL_ID".to_string(), id.clone());
374 env.insert("DEEPSEEK_TOOL_CALL_ID".to_string(), id.clone());
375 }
376 if let Some(ref args) = self.tool_args {
377 // Tool arguments can include whole patches or encoded payloads.
378 // Keep the diagnostic environment surface bounded just like tool
379 // results; hooks that need the canonical arguments already receive
380 // the structured tool request at the engine boundary.
381 env.insert(
382 "DEEPSEEK_TOOL_ARGS".to_string(),
383 truncate_env_value(args, HOOK_TOOL_ARGS_ENV_MAX_BYTES),
384 );
385 }
386 if let Some(ref result) = self.tool_result {
387 // Truncate result to 10KB to avoid environment variable size limits
388 env.insert(
389 "DEEPSEEK_TOOL_RESULT".to_string(),
390 truncate_env_value(result, 10000),
391 );
392 }
393 if let Some(code) = self.tool_exit_code {
394 env.insert("DEEPSEEK_TOOL_EXIT_CODE".to_string(), code.to_string());
395 }
396 if let Some(success) = self.tool_success {
397 env.insert("DEEPSEEK_TOOL_SUCCESS".to_string(), success.to_string());
398 }
399 if let Some(ref status) = self.tool_status {
400 env.insert("DEEPSEEK_TOOL_STATUS".to_string(), status.clone());
401 }
402 if let Some(ref receipt) = self.tool_execution_receipt
403 && receipt.len() <= HOOK_EXECUTION_RECEIPT_MAX_BYTES
404 {
405 env.insert(
406 "DEEPSEEK_TOOL_EXECUTION_RECEIPT".to_string(),
407 receipt.clone(),
408 );
409 }
410 if let Some(ref mode) = self.mode {
411 env.insert("DEEPSEEK_MODE".to_string(), mode.clone());
412 }
413 if let Some(ref prev) = self.previous_mode {
414 env.insert("DEEPSEEK_PREVIOUS_MODE".to_string(), prev.clone());
415 }
416 if let Some(ref session_id) = self.session_id {
417 env.insert("CODEWHALE_SESSION_ID".to_string(), session_id.clone());
418 env.insert("DEEPSEEK_SESSION_ID".to_string(), session_id.clone());
419 }
420 if let Some(ref message) = self.message {
421 // Truncate message to prevent env var issues
422 env.insert(
423 "DEEPSEEK_MESSAGE".to_string(),
424 truncate_env_value(message, 5000),
425 );
426 }
427 if let Some(ref error) = self.error_message {
428 // Bounded like every other payload field: a tool failure message
429 // can be the whole of a failed command's output, and an unbounded
430 // env var is both an exec limit risk and an accidental transcript
431 // copy in whatever the hook writes it to.
432 env.insert(
433 "DEEPSEEK_ERROR".to_string(),
434 truncate_env_value(error, 5000),
435 );
436 }
437 if let Some(ref ws) = self.workspace {
438 env.insert("DEEPSEEK_WORKSPACE".to_string(), ws.display().to_string());
439 }
440 if let Some(ref model) = self.model {
441 env.insert("DEEPSEEK_MODEL".to_string(), model.clone());
442 }
443 if let Some(tokens) = self.total_tokens {
444 env.insert("DEEPSEEK_TOTAL_TOKENS".to_string(), tokens.to_string());
445 }
446 if let Some(cost) = self.session_cost {
447 env.insert("DEEPSEEK_SESSION_COST".to_string(), format!("{cost:.6}"));
448 }
449
450 env
451 }
452 }
453
454 /// Clamp a hook environment value to `max_bytes`, on a UTF-8 boundary, with a
455 /// visible marker so a hook can tell truncation from a short value.
456 fn truncate_env_value(value: &str, max_bytes: usize) -> String {
457 if value.len() <= max_bytes {
458 return value.to_string();
459 }
460 let safe_end = value
461 .char_indices()
462 .take_while(|(i, c)| *i + c.len_utf8() <= max_bytes)
463 .last()
464 .map_or(0, |(i, c)| i + c.len_utf8());
465 format!("{}...[truncated]", &value[..safe_end])
466 }
467
468 /// Result of a hook execution
469 #[derive(Debug, Clone, Default)]
470 pub struct HookResult {
471 /// Hook name (if specified)
472 pub name: Option<String>,
473 /// Whether the hook succeeded.
474 ///
475 /// For a background hook this is `true` as soon as the bounded supervisor
476 /// accepts the job: no child outcome has been observed yet. Check
477 /// [`Self::background`] before reading this as "the command succeeded".
478 pub success: bool,
479 /// `true` when this result describes a background submission rather than
480 /// a completed run. Background results always carry `exit_code: None`,
481 /// empty `stdout`/`stderr`, and a duration that measures the spawn, not
482 /// the command.
483 pub background: bool,
484 /// `true` when the hook behind this result declared
485 /// `continue_on_error = false` and ran in the foreground.
486 ///
487 /// This travels with the *result*, not with the event, because it is the
488 /// only way a steering call site can tell "the gate that actually matched
489 /// this call could not answer" from "some other, unrelated strict hook for
490 /// the same event exists in config". Background submissions are never
491 /// strict: nothing is awaited, so there is no answer to withhold.
492 pub strict: bool,
493 /// Exit code from the hook command
494 pub exit_code: Option<i32>,
495 /// Standard output
496 pub stdout: String,
497 /// Standard error
498 pub stderr: String,
499 /// Time taken to execute
500 pub duration: Duration,
501 /// Error message if execution failed
502 pub error: Option<String>,
503 }
504
505 impl HookResult {
506 /// A result that carries an observed exit code, as opposed to a
507 /// background submission or a spawn failure.
508 ///
509 /// Steering paths must gate on this: a background hook's `exit_code` is
510 /// `None` because nothing was waited for, not because the command exited
511 /// without a code.
512 #[must_use]
513 pub fn observed_exit_code(&self) -> Option<i32> {
514 if self.background {
515 return None;
516 }
517 self.exit_code
518 }
519 }
520
521 /// Result of running mutable `message_submit` hooks.
522 #[derive(Debug, Clone, PartialEq, Eq)]
523 pub enum MessageSubmitOutcome {
524 /// No hook changed the submitted text.
525 Unchanged { warning: Option<String> },
526 /// One or more hooks replaced the submitted text.
527 Replaced {
528 text: String,
529 warning: Option<String>,
530 },
531 /// A hook intentionally blocked the submission.
532 Blocked { reason: String },
533 }
534
535 impl MessageSubmitOutcome {
536 pub fn unchanged() -> Self {
537 Self::Unchanged { warning: None }
538 }
539
540 pub fn replaced(text: String) -> Self {
541 Self::Replaced {
542 text,
543 warning: None,
544 }
545 }
546
547 fn with_warning(self, warning: Option<String>) -> Self {
548 match self {
549 Self::Unchanged { .. } => Self::Unchanged { warning },
550 Self::Replaced { text, .. } => Self::Replaced { text, warning },
551 Self::Blocked { reason } => Self::Blocked { reason },
552 }
553 }
554
555 pub fn warning(&self) -> Option<&str> {
556 match self {
557 Self::Unchanged { warning } | Self::Replaced { warning, .. } => warning.as_deref(),
558 Self::Blocked { .. } => None,
559 }
560 }
561 }
562
563 #[derive(Debug, Clone, PartialEq, Eq)]
564 enum MessageSubmitStdout {
565 Blocked(String),
566 Unchanged,
567 Replaced(String),
568 Invalid(String),
569 }
570
571 /// Maximum characters kept from one text field a `tool_call_before` hook
572 /// prints (`reason`, `additionalContext`).
573 ///
574 /// Both fields end up somewhere unbounded output would be a real problem:
575 /// `reason` in a TUI denial line, `additionalContext` inside the tool result
576 /// that is sent to the model and counted against the context budget. A hook
577 /// that prints a megabyte gets a bounded, marked prefix instead.
578 pub const HOOK_TEXT_FIELD_MAX_CHARS: usize = 2_000;
579
580 /// Maximum characters of concatenated `additionalContext` appended to a single
581 /// tool result, across every hook that contributed to that one call.
582 pub const HOOK_CONTEXT_AGGREGATE_MAX_CHARS: usize = 8_000;
583
584 /// Largest tool-argument snapshot exported through `DEEPSEEK_TOOL_ARGS`.
585 const HOOK_TOOL_ARGS_ENV_MAX_BYTES: usize = 10_000;
586
587 /// Largest raw tool result retained in an observer job before enqueue.
588 const HOOK_TOOL_RESULT_CONTEXT_MAX_BYTES: usize = 10_000;
589
590 /// Largest serialized shell execution receipt exported through
591 /// `DEEPSEEK_TOOL_EXECUTION_RECEIPT`. The shell tool fits its output previews
592 /// beneath this bound; the hook boundary drops anything larger rather than
593 /// truncate a JSON document.
594 pub const HOOK_EXECUTION_RECEIPT_MAX_BYTES: usize = 32 * 1024;
595
596 /// Largest error retained in an observer job before enqueue.
597 const HOOK_ERROR_CONTEXT_MAX_BYTES: usize = 5_000;
598
599 /// Largest user/message preview retained in an observer job before enqueue.
600 const HOOK_MESSAGE_CONTEXT_MAX_BYTES: usize = 5_000;
601
602 /// Largest identifier or other diagnostic retained in an observer job.
603 const HOOK_OBSERVER_METADATA_MAX_BYTES: usize = 4_096;
604
605 /// Largest stdout or stderr prefix retained from one foreground hook. Reader
606 /// threads continue draining after this cap so a verbose child cannot fill its
607 /// pipe and deadlock before exit; only the in-memory receipt is clipped.
608 const HOOK_PIPE_CAPTURE_MAX_BYTES: usize = 64 * 1024;
609
610 /// Largest serialized `updatedInput` object accepted from a decision hook.
611 /// This is intentionally smaller than the pipe cap so the surrounding JSON
612 /// and other fields still have headroom.
613 pub const HOOK_UPDATED_INPUT_MAX_BYTES: usize = 32 * 1024;
614
615 /// Largest replacement message accepted from `message_submit`.
616 const HOOK_MESSAGE_REPLACEMENT_MAX_CHARS: usize = 32_000;
617
618 /// Hard ceiling for the complete serialized `message_submit` stdin document.
619 /// The text prefix is fitted beneath this boundary after bounded metadata has
620 /// been added, so JSON escaping cannot push a producer past the limit.
621 pub const HOOK_MESSAGE_SUBMIT_PAYLOAD_MAX_BYTES: usize = 32 * 1024;
622
623 /// Individual metadata fields in `message_submit` stdin are diagnostic only.
624 /// Bound them before fitting text so an unusual workspace/model value cannot
625 /// consume the entire payload budget.
626 const HOOK_MESSAGE_SUBMIT_METADATA_MAX_BYTES: usize = 4 * 1024;
627
628 /// Largest turn error copied into a `turn_end` observer payload.
629 const HOOK_TURN_ERROR_MAX_CHARS: usize = 2_000;
630
631 /// Largest denial reason persisted into UI/model receipts.
632 const HOOK_DENIAL_RECEIPT_MAX_CHARS: usize = 240;
633
634 /// Bound and de-fang text a hook printed before it is shown or sent onward.
635 ///
636 /// Control characters are removed (`\r`) or flattened to a space so hook
637 /// stdout cannot repaint the TUI with escape sequences or forge structure in
638 /// the model-facing transcript; `\n` and `\t` survive because a hook's context
639 /// is legitimately multi-line. Truncation carries a visible marker so a
640 /// consumer can tell a clipped value from a short one.
641 pub fn sanitize_hook_text(text: &str, max_chars: usize) -> String {
642 let mut out = String::new();
643 let mut kept = 0usize;
644 let mut truncated = false;
645 for ch in text.chars() {
646 let mapped = match ch {
647 '\n' | '\t' => ch,
648 '\r' => continue,
649 c if c.is_control() => ' ',
650 c => c,
651 };
652 if kept == max_chars {
653 truncated = true;
654 break;
655 }
656 out.push(mapped);
657 kept += 1;
658 }
659 if truncated {
660 out.push_str("…[truncated]");
661 }
662 out
663 }
664
665 /// Longest hook/config name kept in a log line, a `/hooks` row, or a receipt.
666 ///
667 /// Names are operator-supplied and otherwise unbounded: nothing stops a
668 /// `name` from being a megabyte of ANSI escapes, and it is echoed into the
669 /// TUI, the tracing stream, and the model-facing denial.
670 pub const HOOK_LABEL_MAX_CHARS: usize = 64;
671
672 /// [`sanitize_hook_text`], forced onto one line.
673 ///
674 /// Labels and previews sit inside a formatted row, so an embedded newline or
675 /// tab would forge structure in the very listing that is supposed to describe
676 /// the hook. Everything else [`sanitize_hook_text`] does — control-character
677 /// removal and the marked truncation — still applies.
678 pub fn sanitize_hook_line(text: &str, max_chars: usize) -> String {
679 sanitize_hook_text(text, max_chars)
680 .chars()
681 .map(|c| if c == '\n' || c == '\t' { ' ' } else { c })
682 .collect()
683 }
684
685 /// The display label for a hook, from its optional operator-supplied `name`.
686 ///
687 /// One line, bounded, control-free, and never empty — every surface that
688 /// prints a hook name (logs, `/hooks list`, config problems, no-verdict
689 /// receipts) goes through here so there is one answer to "what can a `name`
690 /// put on my screen".
691 pub fn sanitize_hook_label(name: Option<&str>) -> String {
692 let cleaned = name
693 .map(|name| sanitize_hook_line(name, HOOK_LABEL_MAX_CHARS))
694 .unwrap_or_default();
695 if cleaned.trim().is_empty() {
696 "(unnamed)".to_string()
697 } else {
698 cleaned.trim().to_string()
699 }
700 }
701
702 #[derive(Clone, Copy)]
703 enum PendingDenialRedaction {
704 AuthorizationSchemeOrCredential,
705 SecretValue,
706 Command,
707 Path,
708 }
709
710 /// Split a denial into whitespace-delimited fields while keeping quoted
711 /// values together. This makes `command="rm -rf"` and
712 /// `path='/private folder'` one redaction unit even though the value contains
713 /// spaces. Unterminated quotes are conservatively kept in the final field.
714 fn denial_fields(line: &str) -> Vec<String> {
715 let mut fields = Vec::new();
716 let mut current = String::new();
717 let mut quote = None;
718 for ch in line.chars() {
719 match (quote, ch) {
720 (None, '\'' | '"') => {
721 quote = Some(ch);
722 current.push(ch);
723 }
724 (Some(open), close) if open == close => {
725 quote = None;
726 current.push(ch);
727 }
728 (None, ch) if ch.is_whitespace() => {
729 if !current.is_empty() {
730 fields.push(std::mem::take(&mut current));
731 }
732 }
733 _ => current.push(ch),
734 }
735 }
736 if !current.is_empty() {
737 fields.push(current);
738 }
739 fields
740 }
741
742 fn denial_field_core(field: &str) -> &str {
743 field.trim_matches(|ch: char| {
744 matches!(
745 ch,
746 '\'' | '"' | '`' | '(' | ')' | '[' | ']' | '{' | '}' | ',' | ';'
747 )
748 })
749 }
750
751 fn denial_sensitive_assignment(field: &str) -> Option<(&str, &str)> {
752 let core = denial_field_core(field);
753 let separator = core.find([':', '='])?;
754 let key = denial_field_core(&core[..separator]);
755 let value = denial_field_core(&core[separator + 1..]);
756 Some((key, value))
757 }
758
759 fn normalized_denial_key(key: &str) -> String {
760 denial_field_core(key)
761 .chars()
762 .map(|ch| match ch {
763 '-' | '.' => '_',
764 ch => ch.to_ascii_lowercase(),
765 })
766 .collect()
767 }
768
769 fn denial_key_is_secret(key: &str) -> bool {
770 matches!(
771 key,
772 "token"
773 | "secret"
774 | "password"
775 | "passwd"
776 | "api_key"
777 | "apikey"
778 | "authorization"
779 | "bearer"
780 ) || key.ends_with("_api_key")
781 || key.ends_with("_token")
782 || key.ends_with("_secret")
783 }
784
785 /// Render an explicit hook denial without carrying raw process output into a
786 /// durable transcript. Structured reasons are useful operator copy, but they
787 /// still pass through a conservative redaction boundary: path-like tokens,
788 /// command-line flags, and common secret assignments are replaced rather than
789 /// persisted. Unstructured stdout/stderr never reaches this function.
790 pub fn sanitize_hook_denial_reason(reason: &str) -> String {
791 let line = sanitize_hook_line(reason, HOOK_DENIAL_RECEIPT_MAX_CHARS);
792 let mut redacted = Vec::new();
793 let mut pending = None;
794 for field in denial_fields(&line) {
795 let core = denial_field_core(&field);
796 let lower = core.to_ascii_lowercase();
797
798 if matches!(core, "=" | ":") {
799 continue;
800 }
801
802 if let Some(expected) = pending {
803 match expected {
804 PendingDenialRedaction::AuthorizationSchemeOrCredential => {
805 redacted.push("[secret]".to_string());
806 // Authorization uses `scheme credentials`. Treat the
807 // first field as a scheme even when it is proprietary;
808 // over-redacting one following field is safer than
809 // leaking a credential for a scheme we do not know.
810 pending = Some(PendingDenialRedaction::SecretValue);
811 }
812 PendingDenialRedaction::SecretValue => {
813 redacted.push("[secret]".to_string());
814 pending = None;
815 }
816 PendingDenialRedaction::Command => {
817 redacted.push("[command]".to_string());
818 pending = None;
819 }
820 PendingDenialRedaction::Path => {
821 redacted.push("[path]".to_string());
822 pending = None;
823 }
824 }
825 continue;
826 }
827
828 if let Some((key, value)) = denial_sensitive_assignment(&field) {
829 let key = normalized_denial_key(key);
830 if denial_key_is_secret(&key) {
831 redacted.push("[secret]".to_string());
832 pending = if key == "authorization" && value.is_empty() {
833 Some(PendingDenialRedaction::AuthorizationSchemeOrCredential)
834 } else if key == "authorization"
835 && !value.chars().any(char::is_whitespace)
836 && !value.contains(':')
837 {
838 // A lone assignment value is normally the scheme
839 // (`Authorization=Digest <credential>`). Quoted values
840 // containing whitespace already include both pieces.
841 Some(PendingDenialRedaction::SecretValue)
842 } else if value.is_empty() {
843 Some(PendingDenialRedaction::SecretValue)
844 } else {
845 None
846 };
847 continue;
848 }
849 if matches!(
850 key.as_str(),
851 "path" | "file" | "directory" | "cwd" | "workspace"
852 ) {
853 redacted.push("[path]".to_string());
854 pending = value.is_empty().then_some(PendingDenialRedaction::Path);
855 continue;
856 }
857 if matches!(key.as_str(), "command" | "cmd" | "argv" | "executable") {
858 redacted.push("[command]".to_string());
859 pending = value.is_empty().then_some(PendingDenialRedaction::Command);
860 continue;
861 }
862 }
863
864 let secret_prefix = lower.starts_with("sk-")
865 || lower.starts_with("ghp_")
866 || lower.starts_with("github_pat_");
867 let path_like = core.starts_with('/')
868 || core.starts_with("~/")
869 || core.starts_with("./")
870 || core.starts_with("../")
871 || core.contains('/')
872 || core.contains('\\')
873 || core
874 .as_bytes()
875 .get(1)
876 .is_some_and(|separator| *separator == b':');
877 let command_flag = core.starts_with('-');
878 let label = lower.trim_end_matches([':', '=']);
879 if matches!(label, "command" | "cmd" | "argv" | "executable") {
880 redacted.push("[command]".to_string());
881 pending = Some(PendingDenialRedaction::Command);
882 } else if label == "authorization" {
883 redacted.push("[secret]".to_string());
884 pending = Some(PendingDenialRedaction::AuthorizationSchemeOrCredential);
885 } else if matches!(label, "bearer" | "token" | "secret" | "password" | "passwd") {
886 redacted.push("[secret]".to_string());
887 pending = Some(PendingDenialRedaction::SecretValue);
888 } else if matches!(label, "path" | "file" | "directory" | "cwd" | "workspace") {
889 redacted.push("[path]".to_string());
890 pending = Some(PendingDenialRedaction::Path);
891 } else if secret_prefix {
892 redacted.push("[secret]".to_string());
893 } else if path_like {
894 redacted.push("[path]".to_string());
895 } else if command_flag {
896 redacted.push("[argument]".to_string());
897 } else {
898 redacted.push(field);
899 }
900 }
901 let rendered = sanitize_hook_line(&redacted.join(" "), HOOK_DENIAL_RECEIPT_MAX_CHARS);
902 if rendered.is_empty() {
903 "hook denied the action".to_string()
904 } else {
905 rendered
906 }
907 }
908
909 /// Render a foreground hook's failure as a detail string that is safe to show.
910 ///
911 /// The executor already writes generic errors, but this is the *boundary*, not
912 /// a restatement of that habit: only the shapes recognized here survive, and
913 /// each is re-rendered from parts rather than passed through. A future code
914 /// path that stuffs a command line, a resolved interpreter path, or hook
915 /// output into `HookResult::error` therefore cannot leak it into a receipt
916 /// merely by skipping the genericization at the producer — it degrades to the
917 /// catch-all instead, and the raw text is discarded.
918 pub fn generic_unavailable_detail(error: Option<&str>) -> String {
919 const GENERIC: &str = "hook returned no verdict";
920 let Some(error) = error else {
921 return GENERIC.to_string();
922 };
923 if let Some(rest) = error.strip_prefix("Hook timed out after ") {
924 let secs: String = rest.chars().take_while(char::is_ascii_digit).collect();
925 return if secs.is_empty() {
926 "hook timed out".to_string()
927 } else {
928 format!("hook timed out after {secs}s")
929 };
930 }
931 if let Some(rest) = error.strip_prefix("hook process could not be started (") {
932 // Only the `std::io::ErrorKind` debug name, and only if it really is
933 // one: bare ASCII letters, nothing else.
934 let kind: String = rest.chars().take_while(char::is_ascii_alphabetic).collect();
935 return if kind.is_empty() {
936 "hook process could not be started".to_string()
937 } else {
938 format!("hook process could not be started ({kind})")
939 };
940 }
941 if error.starts_with("failed to contain hook process tree")
942 || error.starts_with("failed to resume contained hook process")
943 {
944 return "hook process could not be contained".to_string();
945 }
946 if error.starts_with("hook executor did not run") {
947 return "hook executor did not run".to_string();
948 }
949 if error.starts_with("Failed to submit background hook")
950 || error.starts_with("background hook supervisor could not be started")
951 || error.starts_with("background hook supervisor queue is full")
952 || error.starts_with("background hook supervisor is unavailable")
953 {
954 return "hook could not be submitted".to_string();
955 }
956 if error.starts_with("Failed to wait for hook")
957 || error.starts_with("hook could not be reaped")
958 || error.starts_with("Failed to encode hook stdin")
959 || error.starts_with("hook stdout reader could not be started")
960 || error.starts_with("hook stderr reader could not be started")
961 || error.starts_with("hook stdin writer could not be started")
962 || error.starts_with("background hook process could not be started")
963 || error.starts_with("background hook stdin writer could not be started")
964 || error.starts_with("background hook setup")
965 {
966 return "hook did not complete cleanly".to_string();
967 }
968 tracing::debug!(target: "hooks", "hook failure had no recognized shape; reporting it generically");
969 GENERIC.to_string()
970 }
971
972 /// [`sanitize_hook_text`], dropping the value entirely when nothing
973 /// meaningful survives.
974 fn sanitized_hook_field(text: &str) -> Option<String> {
975 let cleaned = sanitize_hook_text(text, HOOK_TEXT_FIELD_MAX_CHARS);
976 if cleaned.trim().is_empty() {
977 None
978 } else {
979 Some(cleaned)
980 }
981 }
982
983 /// Parsed stdout from a `tool_call_before` hook (#3026).
984 ///
985 /// Hooks may emit a JSON decision on stdout:
986 /// `{"decision": "allow"|"deny"|"ask", "reason": "...",
987 /// "updatedInput": {...}, "additionalContext": "..."}`
988 /// Non-JSON or empty stdout → legacy passthrough (allow).
989 ///
990 /// `reason` and `additional_context` are sanitized and bounded here, at the
991 /// only door hook stdout comes through, so no downstream consumer has to
992 /// remember to do it.
993 #[derive(Debug, Clone, PartialEq, Eq)]
994 pub struct ToolCallBeforeStdout {
995 pub decision: Option<ToolCallDecision>,
996 pub reason: Option<String>,
997 pub updated_input: Option<serde_json::Value>,
998 pub additional_context: Option<String>,
999 }
1000
1001 /// Decision a hook can return for a tool call.
1002 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1003 pub enum ToolCallDecision {
1004 Allow,
1005 Deny,
1006 Ask,
1007 }
1008
1009 pub fn parse_tool_call_before_stdout(stdout: &str) -> ToolCallBeforeStdout {
1010 let passthrough = ToolCallBeforeStdout {
1011 decision: None,
1012 reason: None,
1013 updated_input: None,
1014 additional_context: None,
1015 };
1016 let trimmed = stdout.trim();
1017 if trimmed.is_empty() {
1018 return passthrough;
1019 }
1020 let value: serde_json::Value = match serde_json::from_str(trimmed) {
1021 Ok(v) => v,
1022 // Non-JSON stdout → legacy passthrough (allow).
1023 Err(_) => return passthrough,
1024 };
1025 let Some(obj) = value.as_object() else {
1026 tracing::warn!(
1027 "tool_call_before hook stdout is JSON but not an object; \
1028 ignoring it (legacy passthrough)"
1029 );
1030 return passthrough;
1031 };
1032 let decision = obj
1033 .get("decision")
1034 .and_then(|v| v.as_str())
1035 .and_then(|s| match s {
1036 "allow" => Some(ToolCallDecision::Allow),
1037 "deny" => Some(ToolCallDecision::Deny),
1038 "ask" => Some(ToolCallDecision::Ask),
1039 _ => {
1040 tracing::warn!(
1041 "tool_call_before hook returned unrecognized decision \
1042 (expected allow|deny|ask); treating as allow"
1043 );
1044 None
1045 }
1046 });
1047 let reason = obj
1048 .get("reason")
1049 .and_then(|v| v.as_str())
1050 .and_then(sanitized_hook_field);
1051 let updated_input = obj.get("updatedInput").cloned().filter(|v| {
1052 if !v.is_object() {
1053 tracing::warn!("tool_call_before hook updatedInput must be a JSON object; ignoring");
1054 return false;
1055 }
1056 let serialized_len = serde_json::to_vec(v).map_or(usize::MAX, |bytes| bytes.len());
1057 if serialized_len > HOOK_UPDATED_INPUT_MAX_BYTES {
1058 tracing::warn!(
1059 serialized_len,
1060 max_bytes = HOOK_UPDATED_INPUT_MAX_BYTES,
1061 "tool_call_before hook updatedInput exceeded the size limit; ignoring"
1062 );
1063 return false;
1064 }
1065 true
1066 });
1067 let additional_context = obj
1068 .get("additionalContext")
1069 .and_then(|v| v.as_str())
1070 .and_then(sanitized_hook_field);
1071 ToolCallBeforeStdout {
1072 decision,
1073 reason,
1074 updated_input,
1075 additional_context,
1076 }
1077 }
1078
1079 /// Post-turn accumulated totals included in the `turn_end` observer payload.
1080 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1081 pub struct TurnEndTotals {
1082 pub session_tokens: u32,
1083 pub conversation_tokens: u32,
1084 pub input_tokens: u32,
1085 pub output_tokens: u32,
1086 }
1087
1088 /// Input used to build the structured `turn_end` observer payload.
1089 pub struct TurnEndPayloadInput<'a> {
1090 pub context: &'a HookContext,
1091 pub created_at: DateTime<Utc>,
1092 pub model_backed: bool,
1093 pub provider: Option<&'a str>,
1094 pub billing_surface: Option<&'a str>,
1095 pub model: Option<&'a str>,
1096 pub turn_id: &'a str,
1097 pub status: &'a str,
1098 pub error: Option<&'a str>,
1099 pub duration: Duration,
1100 pub usage: &'a codewhale_models::Usage,
1101 pub totals: TurnEndTotals,
1102 pub tool_count: usize,
1103 pub queued_message_count: usize,
1104 }
1105
1106 /// Kill a hook's whole process tree (see [`codewhale_runtime::process_tree`]): hooks run
1107 /// through a shell, so killing only the immediate `sh`/`cmd.exe` child can
1108 /// leave the actual hook runtime alive. Falls back to `taskkill /T` on Windows
1109 /// and to the immediate child everywhere.
1110 fn terminate_tree(process_tree: &ProcessTree, child: &mut Child) {
1111 let result = process_tree.kill();
1112 #[cfg(windows)]
1113 let result = result.or_else(|_| kill_windows_process_tree(child.id()));
1114 if let Err(error) = result {
1115 tracing::warn!(
1116 ?error,
1117 "failed to terminate hook process tree; killing immediate child"
1118 );
1119 let _ = child.kill();
1120 }
1121 }
1122
1123 #[cfg(windows)]
1124 fn kill_windows_process_tree(pid: u32) -> std::io::Result<()> {
1125 let mut command = Command::new("taskkill");
1126 codewhale_util::utils::suppress_console_window(&mut command);
1127 let pid = pid.to_string();
1128 let mut child = command
1129 .args(["/F", "/T", "/PID", pid.as_str()])
1130 .stdin(Stdio::null())
1131 .stdout(Stdio::null())
1132 .stderr(Stdio::null())
1133 .spawn()?;
1134 let status = wait_for_helper_status(&mut child, WINDOWS_TASKKILL_TIMEOUT)?;
1135 if status.success() {
1136 Ok(())
1137 } else {
1138 Err(std::io::Error::other(format!(
1139 "taskkill exited with {status}"
1140 )))
1141 }
1142 }
1143
1144 #[cfg(any(windows, test))]
1145 fn wait_for_helper_status(
1146 child: &mut Child,
1147 timeout: Duration,
1148 ) -> std::io::Result<std::process::ExitStatus> {
1149 match child.wait_timeout(timeout)? {
1150 Some(status) => Ok(status),
1151 None => {
1152 let _ = kill_and_reap_immediate_child(child, HOOK_REAP_TIMEOUT);
1153 Err(std::io::Error::new(
1154 std::io::ErrorKind::TimedOut,
1155 "hook helper did not finish within its timeout",
1156 ))
1157 }
1158 }
1159 }
1160
1161 #[cfg(any(windows, test))]
1162 fn kill_and_reap_immediate_child(child: &mut Child, timeout: Duration) -> bool {
1163 let _ = child.kill();
1164 matches!(child.wait_timeout(timeout), Ok(Some(_)))
1165 }
1166
1167 /// Spawn a contained hook child.
1168 ///
1169 /// Errors returned here are deliberately free of the hook command, the
1170 /// resolved interpreter path, and the OS message: the caller turns them into a
1171 /// user-visible "hook could not answer" receipt, and on Windows a raw spawn
1172 /// error echoes the whole command line back. The detail is logged instead.
1173 fn spawn_hook_child(command: &mut Command) -> std::io::Result<(Child, ProcessTree)> {
1174 codewhale_runtime::process_tree::spawn_contained_std(command).map_err(|error| {
1175 tracing::warn!(target: "hooks", %error, "failed to start contained hook process");
1176 std::io::Error::new(error.kind(), "failed to contain hook process tree")
1177 })
1178 }
1179
1180 /// A spawn failure rendered without the command, the path, or the OS message.
1181 ///
1182 /// The error kind is the useful, non-identifying part (`NotFound`,
1183 /// `PermissionDenied`, …); everything else is logged, not surfaced.
1184 fn spawn_failure_message(error: &std::io::Error) -> String {
1185 format!("hook process could not be started ({:?})", error.kind())
1186 }
1187
1188 const OBSERVER_DISPATCH_QUEUE_CAPACITY: usize = 32;
1189 const OBSERVER_DISPATCH_WORKERS: usize = 2;
1190
1191 #[derive(Debug, Clone, Copy)]
1192 enum ObserverDispatchFailure {
1193 Full,
1194 Disconnected,
1195 }
1196
1197 /// Bounded, persistent submission path for observer-only events.
1198 ///
1199 /// The terminal loop never creates a thread per event. Two long-lived workers
1200 /// drain a fixed-capacity channel, and `try_send` makes saturation observable
1201 /// without ever parking the caller.
1202 #[derive(Clone)]
1203 struct ObserverDispatcher {
1204 sender: Option<SyncSender<ObserverJob>>,
1205 #[cfg(any(test, feature = "test-support"))]
1206 held_receiver: Option<Arc<Mutex<Receiver<ObserverJob>>>>,
1207 }
1208
1209 impl fmt::Debug for ObserverDispatcher {
1210 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1211 formatter
1212 .debug_struct("ObserverDispatcher")
1213 .field("available", &self.sender.is_some())
1214 .finish_non_exhaustive()
1215 }
1216 }
1217
1218 impl ObserverDispatcher {
1219 fn new() -> Self {
1220 let (sender, receiver) = mpsc::sync_channel(OBSERVER_DISPATCH_QUEUE_CAPACITY);
1221 let receiver = Arc::new(Mutex::new(receiver));
1222
1223 for worker_index in 0..OBSERVER_DISPATCH_WORKERS {
1224 let worker_receiver = Arc::clone(&receiver);
1225 let spawned = std::thread::Builder::new()
1226 .name(format!("hook-observer-{worker_index}"))
1227 .spawn(move || observer_worker_loop(worker_receiver));
1228 if let Err(error) = spawned {
1229 tracing::warn!(
1230 target: "hooks",
1231 worker_index,
1232 error_kind = ?error.kind(),
1233 "failed to start observer hook dispatcher"
1234 );
1235 // Dropping the only sender disconnects any workers that did
1236 // start. A partially-created pool is not presented as healthy.
1237 drop(sender);
1238 return Self {
1239 sender: None,
1240 #[cfg(any(test, feature = "test-support"))]
1241 held_receiver: None,
1242 };
1243 }
1244 }
1245
1246 Self {
1247 sender: Some(sender),
1248 #[cfg(any(test, feature = "test-support"))]
1249 held_receiver: None,
1250 }
1251 }
1252
1253 fn submit(&self, event: HookEvent, job: ObserverJob) -> Result<(), String> {
1254 let Some(sender) = &self.sender else {
1255 return Err(observer_dispatch_failure_message(
1256 event,
1257 ObserverDispatchFailure::Disconnected,
1258 ));
1259 };
1260 match sender.try_send(job) {
1261 Ok(()) => Ok(()),
1262 Err(TrySendError::Full(_)) => Err(observer_dispatch_failure_message(
1263 event,
1264 ObserverDispatchFailure::Full,
1265 )),
1266 Err(TrySendError::Disconnected(_)) => Err(observer_dispatch_failure_message(
1267 event,
1268 ObserverDispatchFailure::Disconnected,
1269 )),
1270 }
1271 }
1272 }
1273
1274 fn observer_dispatch_failure_message(event: HookEvent, failure: ObserverDispatchFailure) -> String {
1275 match failure {
1276 ObserverDispatchFailure::Full => format!(
1277 "{} observer hook queue is full; event was not submitted",
1278 event.as_str()
1279 ),
1280 ObserverDispatchFailure::Disconnected => format!(
1281 "{} observer hook dispatcher is unavailable; event was not submitted",
1282 event.as_str()
1283 ),
1284 }
1285 }
1286
1287 enum ObserverJob {
1288 Environment {
1289 hooks: HookExecutor,
1290 event: HookEvent,
1291 context: HookContext,
1292 },
1293 Json {
1294 hooks: HookExecutor,
1295 event: HookEvent,
1296 context: HookContext,
1297 payload: serde_json::Value,
1298 },
1299 }
1300
1301 impl ObserverJob {
1302 fn run(self) {
1303 let policy = match &self {
1304 Self::Environment { hooks, .. } | Self::Json { hooks, .. } => hooks.native_policy,
1305 };
1306 let _policy = codewhale_plugins::activation::PolicyScope::propagate(policy);
1307 match self {
1308 Self::Environment {
1309 hooks,
1310 event,
1311 context,
1312 } => {
1313 let _ = hooks.execute(event, &context);
1314 }
1315 Self::Json {
1316 hooks,
1317 event,
1318 context,
1319 payload,
1320 } => {
1321 let _ = hooks.execute_json_observer(event, &context, &payload);
1322 }
1323 }
1324 }
1325 }
1326
1327 fn observer_worker_loop(receiver: Arc<Mutex<Receiver<ObserverJob>>>) {
1328 loop {
1329 let received = match receiver.lock() {
1330 Ok(receiver) => receiver.recv(),
1331 Err(_) => {
1332 tracing::warn!(target: "hooks", "observer hook dispatcher lock was poisoned");
1333 return;
1334 }
1335 };
1336 match received {
1337 Ok(job) => job.run(),
1338 Err(_) => return,
1339 }
1340 }
1341 }
1342
1343 const BACKGROUND_SUPERVISOR_QUEUE_CAPACITY: usize = 32;
1344 const BACKGROUND_SUPERVISOR_WORKERS: usize = 2;
1345
1346 #[derive(Debug, Clone, Copy)]
1347 enum BackgroundSupervisorFailure {
1348 Full,
1349 Disconnected,
1350 }
1351
1352 /// Bounded pool that owns background-child setup, timeout, tree kill, and
1353 /// reap. Observer workers enqueue here instead of creating one detached
1354 /// supervisor thread per invocation.
1355 #[derive(Clone)]
1356 struct BackgroundSupervisor {
1357 sender: Option<SyncSender<BackgroundHookJob>>,
1358 #[cfg(test)]
1359 held_receiver: Option<Arc<Mutex<Receiver<BackgroundHookJob>>>>,
1360 }
1361
1362 impl fmt::Debug for BackgroundSupervisor {
1363 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1364 formatter
1365 .debug_struct("BackgroundSupervisor")
1366 .field("available", &self.sender.is_some())
1367 .finish_non_exhaustive()
1368 }
1369 }
1370
1371 impl BackgroundSupervisor {
1372 fn new() -> Self {
1373 let (sender, receiver) = mpsc::sync_channel(BACKGROUND_SUPERVISOR_QUEUE_CAPACITY);
1374 let receiver = Arc::new(Mutex::new(receiver));
1375
1376 for worker_index in 0..BACKGROUND_SUPERVISOR_WORKERS {
1377 let worker_receiver = Arc::clone(&receiver);
1378 let spawned = std::thread::Builder::new()
1379 .name(format!("hook-supervisor-{worker_index}"))
1380 .spawn(move || background_supervisor_worker_loop(worker_receiver));
1381 if let Err(error) = spawned {
1382 tracing::warn!(
1383 target: "hooks",
1384 worker_index,
1385 error_kind = ?error.kind(),
1386 "failed to start background hook supervisor pool"
1387 );
1388 drop(sender);
1389 return Self {
1390 sender: None,
1391 #[cfg(test)]
1392 held_receiver: None,
1393 };
1394 }
1395 }
1396
1397 Self {
1398 sender: Some(sender),
1399 #[cfg(test)]
1400 held_receiver: None,
1401 }
1402 }
1403
1404 fn submit(&self, job: BackgroundHookJob) -> Result<(), BackgroundSupervisorFailure> {
1405 let Some(sender) = &self.sender else {
1406 return Err(BackgroundSupervisorFailure::Disconnected);
1407 };
1408 match sender.try_send(job) {
1409 Ok(()) => Ok(()),
1410 Err(TrySendError::Full(_)) => Err(BackgroundSupervisorFailure::Full),
1411 Err(TrySendError::Disconnected(_)) => Err(BackgroundSupervisorFailure::Disconnected),
1412 }
1413 }
1414 }
1415
1416 struct AdmittedBackground {
1417 executor: HookExecutor,
1418 hook: Hook,
1419 env: HashMap<String, String>,
1420 input: Option<serde_json::Value>,
1421 }
1422 struct BackgroundHookJob {
1423 admitted: Option<AdmittedBackground>,
1424 command: String,
1425 env: HashMap<String, String>,
1426 working_dir: PathBuf,
1427 stdin_bytes: Option<Vec<u8>>,
1428 label: String,
1429 timeout: Duration,
1430 plugin_authority: Option<codewhale_config::PluginAuthority>,
1431 project_authority: Option<codewhale_config::ProjectHookAuthority>,
1432 }
1433
1434 impl BackgroundHookJob {
1435 fn run(mut self) {
1436 if let Some(job) = self.admitted.take() {
1437 let result = job
1438 .executor
1439 .execute_sync_inner(&job.hook, &job.env, job.input.as_ref());
1440 if !result.success {
1441 tracing::warn!(target:"hooks",hook=%self.label,"admitted background hook failed");
1442 }
1443 return;
1444 }
1445 if codewhale_plugins::activation::extension_host_policy_enabled() {
1446 tracing::warn!(target:"hooks",hook=%self.label,"legacy background hook was withdrawn by enabled host policy");
1447 return;
1448 }
1449 let Self {
1450 admitted: _,
1451 command: command_text,
1452 env,
1453 working_dir,
1454 stdin_bytes,
1455 label,
1456 timeout,
1457 plugin_authority,
1458 project_authority,
1459 } = self;
1460 if let Err(error) = super::authority::verify_hook_authorities(
1461 plugin_authority.as_ref(),
1462 project_authority.as_ref(),
1463 ) {
1464 tracing::warn!(
1465 target: "hooks",
1466 hook = %label,
1467 error = %error,
1468 "denied queued hook after authority changed"
1469 );
1470 return;
1471 }
1472 let timeout_secs = timeout.as_secs();
1473 let mut command = HookExecutor::build_shell_command(&command_text);
1474 command
1475 .current_dir(&working_dir)
1476 .envs(&env)
1477 .stdout(Stdio::null())
1478 .stderr(Stdio::null())
1479 // Always pipe stdin so dropping it delivers EOF through shell
1480 // wrappers even when there is no structured payload.
1481 .stdin(Stdio::piped());
1482
1483 let (mut child, process_tree) = match spawn_hook_child(&mut command) {
1484 Ok(child) => child,
1485 Err(error) => {
1486 tracing::warn!(
1487 target: "hooks",
1488 hook = %label,
1489 error_kind = ?error.kind(),
1490 "failed to start background hook"
1491 );
1492 return;
1493 }
1494 };
1495
1496 let _stdin_writer = match (stdin_bytes, child.stdin.take()) {
1497 (Some(bytes), Some(stdin)) => match spawn_stdin_writer(stdin, bytes) {
1498 Ok(writer) => Some(writer),
1499 Err(error) => {
1500 tracing::warn!(
1501 target: "hooks",
1502 hook = %label,
1503 error_kind = ?error.kind(),
1504 "failed to start background hook stdin writer"
1505 );
1506 terminate_and_reap(Some(label.as_str()), &mut child, process_tree);
1507 return;
1508 }
1509 },
1510 _ => None,
1511 };
1512
1513 match child.wait_timeout(timeout) {
1514 Ok(Some(status)) => {
1515 if !status.success() {
1516 tracing::warn!(
1517 target: "hooks",
1518 hook = %label,
1519 exit_code = ?status.code(),
1520 "background hook exited non-zero"
1521 );
1522 }
1523 }
1524 Ok(None) => {
1525 let reaped = terminate_and_reap(Some(label.as_str()), &mut child, process_tree);
1526 tracing::warn!(
1527 target: "hooks",
1528 hook = %label,
1529 timeout_secs,
1530 reaped,
1531 "background hook timed out; process tree killed"
1532 );
1533 }
1534 Err(error) => {
1535 terminate_and_reap(Some(label.as_str()), &mut child, process_tree);
1536 tracing::warn!(
1537 target: "hooks",
1538 hook = %label,
1539 ?error,
1540 "failed to wait for background hook; process tree killed"
1541 );
1542 }
1543 }
1544 }
1545 }
1546
1547 fn background_supervisor_worker_loop(receiver: Arc<Mutex<Receiver<BackgroundHookJob>>>) {
1548 loop {
1549 let received = match receiver.lock() {
1550 Ok(receiver) => receiver.recv(),
1551 Err(_) => {
1552 tracing::warn!(target: "hooks", "background supervisor lock was poisoned");
1553 return;
1554 }
1555 };
1556 match received {
1557 Ok(job) => job.run(),
1558 Err(_) => return,
1559 }
1560 }
1561 }
1562
1563 /// Executor for running hooks
1564 #[derive(Clone)]
1565 pub struct HookExecutor {
1566 config: HooksConfig,
1567 default_working_dir: PathBuf,
1568 session_id: String,
1569 observer_dispatcher: ObserverDispatcher,
1570 background_supervisor: BackgroundSupervisor,
1571 caller: Option<HookCaller>,
1572 fire_context: Option<Arc<HookContext>>,
1573 cancel: Option<tokio_util::sync::CancellationToken>,
1574 host_manager: Arc<crate::extension_host::ExtensionHostManager>,
1575 engine_handle: Option<tokio::runtime::Handle>,
1576 native_policy: bool,
1577 #[cfg(any(test, feature = "test-support"))]
1578 lose_message_submit_executor: bool,
1579 }
1580
1581 impl fmt::Debug for HookExecutor {
1582 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1583 f.debug_struct("HookExecutor")
1584 .field("config", &self.config)
1585 .field("default_working_dir", &self.default_working_dir)
1586 .field("caller", &self.caller)
1587 .finish_non_exhaustive()
1588 }
1589 }
1590 impl HookExecutor {
1591 /// Foreground hooks run under this executor stop, and are reaped, when
1592 /// `token` is cancelled; hooks not yet started are skipped.
1593 #[must_use]
1594 pub fn with_cancel(mut self, token: tokio_util::sync::CancellationToken) -> Self {
1595 self.cancel = Some(token);
1596 self
1597 }
1598
1599 fn cancelled(&self) -> bool {
1600 self.cancel
1601 .as_ref()
1602 .is_some_and(tokio_util::sync::CancellationToken::is_cancelled)
1603 }
1604
1605 /// One Engine scheduler, propagated through the existing std workers.
1606 pub fn bind_caller(&self, caller: HookCaller) -> Self {
1607 let mut bound = self.clone();
1608 bound.caller = Some(caller);
1609 bound.native_policy = codewhale_plugins::activation::extension_host_policy_enabled();
1610 if let Ok(handle) = tokio::runtime::Handle::try_current() {
1611 bound.engine_handle = Some(handle);
1612 }
1613 bound
1614 }
1615 fn event_hooks(&self, event: HookEvent, context: &HookContext) -> Vec<Hook> {
1616 let mut hooks: Vec<_> = self
1617 .config
1618 .hooks_for_event(event)
1619 .into_iter()
1620 .cloned()
1621 .collect();
1622 if self.native_policy
1623 && let Some(caller) = context.caller.as_ref().or(self.caller.as_ref())
1624 {
1625 hooks.extend(self.host_manager.shell_hooks(caller, event));
1626 }
1627 hooks
1628 }
1629 fn for_context(&self, context: &HookContext) -> Self {
1630 let mut bound = context
1631 .caller
1632 .clone()
1633 .map_or_else(|| self.clone(), |caller| self.bind_caller(caller));
1634 if let Some(caller) = bound.caller.as_mut() {
1635 caller.origin_call_id = context
1636 .tool_call_id
1637 .clone()
1638 .or(caller.origin_call_id.clone());
1639 }
1640 let mut fire = context.clone();
1641 fire.caller = bound.caller.clone();
1642 bound.fire_context = Some(Arc::new(fire));
1643 bound
1644 }
1645
1646 fn build_shell_command(command: &str) -> Command {
1647 #[cfg(windows)]
1648 {
1649 use std::os::windows::process::CommandExt as _;
1650 let mut cmd = Command::new("cmd");
1651 const CREATE_SUSPENDED: u32 = 0x0000_0004;
1652 const CREATE_NO_WINDOW: u32 = 0x0800_0000;
1653 cmd.creation_flags(CREATE_SUSPENDED | CREATE_NO_WINDOW);
1654 // raw_arg: cmd.exe does not parse the CRT-style \" escapes that
1655 // Command::arg would insert, so pass the command line verbatim.
1656 cmd.arg("/C").raw_arg(command);
1657 // Only this call's context may supply a receipt. In particular,
1658 // a Codewhale launched from another hook must not inherit one.
1659 cmd.env_remove("DEEPSEEK_TOOL_EXECUTION_RECEIPT");
1660 cmd
1661 }
1662 #[cfg(not(windows))]
1663 {
1664 let mut cmd = Command::new("sh");
1665 cmd.arg("-c").arg(command);
1666 #[cfg(unix)]
1667 {
1668 use std::os::unix::process::CommandExt as _;
1669 cmd.process_group(0);
1670 }
1671 // Only this call's context may supply a receipt. In particular,
1672 // a Codewhale launched from another hook must not inherit one.
1673 cmd.env_remove("DEEPSEEK_TOOL_EXECUTION_RECEIPT");
1674 cmd
1675 }
1676 }
1677
1678 /// Create a new `HookExecutor` with configuration.
1679 ///
1680 /// This mints the hook session identity for the whole TUI session. Call it
1681 /// **once per launch**; every later reload (workspace switch, trust
1682 /// onboarding) must go through [`Self::rebind`] so the id every hook has
1683 /// already seen stays valid. Regenerating it mid-session would break
1684 /// correlation for anything that grouped records by `CODEWHALE_SESSION_ID`
1685 /// or its `DEEPSEEK_SESSION_ID` compatibility alias.
1686 pub fn new(config: HooksConfig, default_working_dir: PathBuf) -> Self {
1687 // Generate a session ID
1688 let session_id = format!("sess_{}", &uuid::Uuid::new_v4().to_string()[..8]);
1689 Self {
1690 config,
1691 default_working_dir,
1692 session_id,
1693 observer_dispatcher: ObserverDispatcher::new(),
1694 background_supervisor: BackgroundSupervisor::new(),
1695 caller: None,
1696 fire_context: None,
1697 cancel: None,
1698 host_manager: crate::extension_host::manager(),
1699 engine_handle: tokio::runtime::Handle::try_current().ok(),
1700 native_policy: codewhale_plugins::activation::extension_host_policy_enabled(),
1701 #[cfg(any(test, feature = "test-support"))]
1702 lose_message_submit_executor: false,
1703 }
1704 }
1705
1706 /// Rebuild the executor with new configuration and working directory while
1707 /// preserving the session identity minted at launch.
1708 ///
1709 /// Used when the workspace changes or a trust decision makes project hooks
1710 /// eligible: the hook set may change, the session does not.
1711 #[must_use]
1712 pub fn rebind(&self, config: HooksConfig, default_working_dir: PathBuf) -> Self {
1713 Self {
1714 config,
1715 default_working_dir: default_working_dir.clone(),
1716 session_id: self.session_id.clone(),
1717 observer_dispatcher: self.observer_dispatcher.clone(),
1718 background_supervisor: self.background_supervisor.clone(),
1719 caller: self
1720 .caller
1721 .clone()
1722 .filter(|c| c.workspace == default_working_dir),
1723 fire_context: None,
1724 cancel: self.cancel.clone(),
1725 host_manager: Arc::clone(&self.host_manager),
1726 engine_handle: self.engine_handle.clone(),
1727 native_policy: self.native_policy,
1728 #[cfg(any(test, feature = "test-support"))]
1729 lose_message_submit_executor: self.lose_message_submit_executor,
1730 }
1731 }
1732
1733 /// Create a disabled `HookExecutor` (no hooks will run)
1734 #[cfg(any(test, feature = "test-support"))]
1735 pub fn disabled() -> Self {
1736 Self {
1737 config: HooksConfig {
1738 enabled: false,
1739 ..Default::default()
1740 },
1741 default_working_dir: PathBuf::from("."),
1742 session_id: String::new(),
1743 observer_dispatcher: ObserverDispatcher::new(),
1744 background_supervisor: BackgroundSupervisor::new(),
1745 caller: None,
1746 fire_context: None,
1747 cancel: None,
1748 host_manager: crate::extension_host::manager(),
1749 engine_handle: tokio::runtime::Handle::try_current().ok(),
1750 native_policy: codewhale_plugins::activation::extension_host_policy_enabled(),
1751 #[cfg(any(test, feature = "test-support"))]
1752 lose_message_submit_executor: false,
1753 }
1754 }
1755
1756 /// Check if hooks are enabled
1757 #[cfg(any(test, feature = "test-support"))]
1758 pub fn is_enabled(&self) -> bool {
1759 self.config.enabled
1760 }
1761
1762 /// Get the session ID
1763 /// Read-only access to the underlying configuration. Used by
1764 /// `/hooks` (#460 read-only MVP) so the user can list configured
1765 /// hooks without reaching for `cat ~/.deepseek/config.toml`.
1766 pub fn config(&self) -> &HooksConfig {
1767 &self.config
1768 }
1769
1770 /// The workspace hooks run in unless a hook names its own directory.
1771 #[must_use]
1772 pub fn default_working_dir(&self) -> &std::path::Path {
1773 &self.default_working_dir
1774 }
1775
1776 pub fn session_id(&self) -> &str {
1777 &self.session_id
1778 }
1779
1780 /// Cheap pre-check: are there any enabled hooks for this event?
1781 /// Lets call sites avoid building a [`HookContext`] (which allocates
1782 /// for `workspace`, `model`, `session_id`, …) on every tool call
1783 /// when the user hasn't configured any hooks. The cost matters
1784 /// because `ToolCallBefore` / `ToolCallAfter` fire from
1785 /// `tool_routing.rs` on every tool dispatch (#455).
1786 #[must_use]
1787 pub fn has_hooks_for_event(&self, event: HookEvent) -> bool {
1788 self.config.enabled
1789 && (self.config.hooks.iter().any(|h| h.event == event)
1790 || (self.native_policy && self.host_manager.has_shell_hooks(event)))
1791 }
1792
1793 /// Check if there are any background hooks configured for a specific event.
1794 ///
1795 /// Background hooks fire and forget — their `exit_code` is always `None`,
1796 /// so they cannot deny tool calls. This is a known limitation; the check
1797 /// is used to warn operators when a `ToolCallBefore` hook is configured
1798 /// as background but expects to block a tool.
1799 #[must_use]
1800 pub fn has_background_hooks_for_event(&self, event: HookEvent) -> bool {
1801 if !self.config.enabled {
1802 return false;
1803 }
1804 self.config
1805 .hooks
1806 .iter()
1807 .any(|h| h.event == event && h.background)
1808 }
1809
1810 /// Sanitized labels of the strict foreground gates that *would* run for
1811 /// this event and context.
1812 ///
1813 /// "Strict" is `continue_on_error = false` on a foreground hook: an
1814 /// operator instruction that the action must not proceed without this
1815 /// hook's answer. The caller collects these **before** dispatching the
1816 /// executor so it can still honor them if the execution itself is lost —
1817 /// a panicked or cancelled `spawn_blocking` returns no results at all, and
1818 /// an empty result set is indistinguishable from "every hook allowed it".
1819 ///
1820 /// Condition matching is the same predicate [`Self::execute`] uses, so
1821 /// this never names a hook that would not have run: a strict `write_file`
1822 /// gate has no say over an `exec_shell` call it never matched.
1823 #[must_use]
1824 pub fn matched_strict_gate_labels(
1825 &self,
1826 event: HookEvent,
1827 context: &HookContext,
1828 ) -> Vec<String> {
1829 if !self.config.enabled {
1830 return Vec::new();
1831 }
1832 self.event_hooks(event, context)
1833 .into_iter()
1834 .filter(|hook| {
1835 // A background hook is never awaited, so it is not a gate no
1836 // matter what `continue_on_error` says.
1837 let foreground = !hook.background || !hook.event.honors_background();
1838 foreground && !hook.continue_on_error && self.matches_condition(hook, context)
1839 })
1840 .map(|hook| sanitize_hook_label(hook.name.as_deref()))
1841 .collect()
1842 }
1843
1844 /// Run configured `message_submit` hooks as a mutable submit pipeline.
1845 ///
1846 /// This is deliberately separate from [`Self::execute`]: most hook events
1847 /// are observer-only, while `message_submit` has a narrow stdout JSON
1848 /// contract that can replace or block the submitted text.
1849 pub fn execute_message_submit_transform(
1850 &self,
1851 context: &HookContext,
1852 original_text: &str,
1853 ) -> MessageSubmitOutcome {
1854 let bound = self.for_context(context);
1855 let this = &bound;
1856 if !self.config.enabled {
1857 return MessageSubmitOutcome::unchanged();
1858 }
1859
1860 let hooks = this.event_hooks(HookEvent::MessageSubmit, context);
1861 if hooks.is_empty() {
1862 return MessageSubmitOutcome::unchanged();
1863 }
1864
1865 let mut current_text = original_text.to_string();
1866 let mut warning = None;
1867
1868 for hook in &hooks {
1869 let hook_context = context.clone().with_message(&current_text);
1870 if !self.matches_condition(hook, &hook_context) {
1871 continue;
1872 }
1873
1874 let env_vars = hook_context.to_env_vars();
1875 let payload = message_submit_payload(&hook_context, &current_text);
1876 if hook.background {
1877 // A background `message_submit` hook cannot steer, but it must
1878 // still receive the documented stdin payload — the contract is
1879 // the same JSON, only the steering is dropped.
1880 let submitted = this.execute_background_with_stdin(hook, &env_vars, &payload);
1881 // Submission itself can fail (thread spawn refused, payload not
1882 // encodable). Discarding that silently is the one outcome an
1883 // operator cannot debug: the hook is configured, nothing runs,
1884 // and nothing says so. Still non-blocking — the submit proceeds.
1885 if !submitted.success {
1886 tracing::warn!(
1887 target: "hooks",
1888 hook = %sanitize_hook_label(submitted.name.as_deref()),
1889 event = "message_submit",
1890 error = %generic_unavailable_detail(submitted.error.as_deref()),
1891 "background message_submit hook was not submitted; it will not run"
1892 );
1893 }
1894 continue;
1895 }
1896
1897 let result = this.execute_sync_with_stdin(hook, &env_vars, &payload);
1898
1899 if result.exit_code == Some(2) {
1900 return MessageSubmitOutcome::Blocked {
1901 reason: message_submit_block_reason(
1902 &result,
1903 "message_submit hook blocked submission",
1904 ),
1905 };
1906 }
1907
1908 if !result.success {
1909 let label = sanitize_hook_label(result.name.as_deref());
1910 tracing::warn!(
1911 target: "hooks",
1912 hook = %label,
1913 event = "message_submit",
1914 exit_code = ?result.exit_code,
1915 duration_ms = result.duration.as_millis() as u64,
1916 detail = %generic_unavailable_detail(result.error.as_deref()),
1917 "message_submit hook failed"
1918 );
1919
1920 if hook.continue_on_error {
1921 warning = message_submit_continue_warning(&result).or(warning);
1922 continue;
1923 }
1924
1925 return MessageSubmitOutcome::Blocked {
1926 reason: message_submit_block_reason(
1927 &result,
1928 "message_submit hook failed and blocked submission",
1929 ),
1930 };
1931 }
1932
1933 match parse_message_submit_stdout(&result.stdout) {
1934 MessageSubmitStdout::Blocked(reason) => {
1935 return MessageSubmitOutcome::Blocked { reason };
1936 }
1937 MessageSubmitStdout::Unchanged => {}
1938 MessageSubmitStdout::Replaced(text) => {
1939 current_text = text;
1940 }
1941 MessageSubmitStdout::Invalid(reason) => {
1942 tracing::warn!(
1943 target: "hooks",
1944 hook = %sanitize_hook_label(result.name.as_deref()),
1945 event = "message_submit",
1946 reason = %reason,
1947 "ignored invalid message_submit hook stdout"
1948 );
1949 }
1950 }
1951 }
1952
1953 if current_text == original_text {
1954 MessageSubmitOutcome::unchanged().with_warning(warning)
1955 } else {
1956 MessageSubmitOutcome::replaced(current_text).with_warning(warning)
1957 }
1958 }
1959
1960 /// Dispatch-bound entry point for the mutable submit gate.
1961 ///
1962 /// Keeping this wrapper distinct gives the production dispatch path a
1963 /// deterministic test seam for a lost blocking task. Normal hook tests use
1964 /// [`Self::execute_message_submit_transform`] directly.
1965 pub fn execute_message_submit_transform_for_dispatch(
1966 &self,
1967 context: &HookContext,
1968 original_text: &str,
1969 ) -> MessageSubmitOutcome {
1970 #[cfg(any(test, feature = "test-support"))]
1971 if self.lose_message_submit_executor {
1972 panic!("injected message_submit executor loss");
1973 }
1974 self.execute_message_submit_transform(context, original_text)
1975 }
1976
1977 #[cfg(any(test, feature = "test-support"))]
1978 pub fn inject_message_submit_executor_loss_for_test(&mut self) {
1979 self.lose_message_submit_executor = true;
1980 }
1981
1982 #[cfg(any(test, feature = "test-support"))]
1983 pub fn inject_observer_dispatch_full_for_test(&mut self) {
1984 let (sender, receiver) = mpsc::sync_channel(0);
1985 self.observer_dispatcher.sender = Some(sender);
1986 // Keep the receiver connected but deliberately leave no worker waiting
1987 // on it. The production `try_send` path therefore returns `Full`.
1988 self.observer_dispatcher.held_receiver = Some(Arc::new(Mutex::new(receiver)));
1989 }
1990
1991 #[cfg(any(test, feature = "test-support"))]
1992 pub fn inject_observer_dispatch_disconnect_for_test(&mut self) {
1993 let (sender, receiver) = mpsc::sync_channel(1);
1994 drop(receiver);
1995 self.observer_dispatcher.sender = Some(sender);
1996 self.observer_dispatcher.held_receiver = None;
1997 }
1998
1999 #[cfg(test)]
2000 fn inject_background_supervisor_full_for_test(&mut self) {
2001 let (sender, receiver) = mpsc::sync_channel(0);
2002 self.background_supervisor.sender = Some(sender);
2003 self.background_supervisor.held_receiver = Some(Arc::new(Mutex::new(receiver)));
2004 }
2005
2006 /// Run every `ShellEnv` hook for this context and merge their stdout
2007 /// (`KEY=VALUE\n` lines) into a single env-var map. Used by the
2008 /// `exec_shell` tool to inject ephemeral credentials, per-skill PATH
2009 /// adjustments, etc. (#456). Failures don't abort the shell call —
2010 /// the hook simply contributes no vars and a `tracing::warn!` lands.
2011 ///
2012 /// Each successful hook's keys (NOT values) are written to the audit
2013 /// log so a session can be reconciled later without leaking the
2014 /// secret material itself.
2015 pub fn collect_shell_env(&self, context: &HookContext) -> HashMap<String, String> {
2016 let bound = self.for_context(context);
2017 let this = &bound;
2018 let mut merged: HashMap<String, String> = HashMap::new();
2019 if !self.config.enabled {
2020 return merged;
2021 }
2022 let hooks = this.event_hooks(HookEvent::ShellEnv, context);
2023 if hooks.is_empty() {
2024 return merged;
2025 }
2026 let env_vars = context.to_env_vars();
2027 for hook in &hooks {
2028 if !self.matches_condition(hook, context) {
2029 continue;
2030 }
2031 // ShellEnv hooks must be synchronous — their stdout is the contract.
2032 let result = this.execute_sync(hook, &env_vars);
2033 if !result.success {
2034 tracing::warn!(
2035 target: "hooks",
2036 hook = %sanitize_hook_label(result.name.as_deref()),
2037 event = "shell_env",
2038 exit_code = ?result.exit_code,
2039 detail = %generic_unavailable_detail(result.error.as_deref()),
2040 "shell_env hook failed; contributing no env vars"
2041 );
2042 continue;
2043 }
2044 let parsed = parse_env_lines(&result.stdout);
2045 if parsed.is_empty() {
2046 continue;
2047 }
2048 // Audit-log the *keys* — never the values.
2049 codewhale_runtime::audit::log_sensitive_event(
2050 "shell_env_hook",
2051 serde_json::json!({
2052 // Bounded and de-fanged like every other rendering of a
2053 // hook name: an audit record is read by a person, often
2054 // through `tail`, where a raw escape sequence still acts.
2055 "hook": sanitize_hook_label(result.name.as_deref()),
2056 "tool": context.tool_name,
2057 "keys": parsed.keys().cloned().collect::<Vec<_>>(),
2058 }),
2059 );
2060 // Later hooks override earlier ones. Documented behavior.
2061 merged.extend(parsed);
2062 }
2063 merged
2064 }
2065
2066 /// Execute all hooks for an event
2067 pub fn execute(&self, event: HookEvent, context: &HookContext) -> Vec<HookResult> {
2068 let bound = self.for_context(context);
2069 let this = &bound;
2070 if !self.config.enabled {
2071 return Vec::new();
2072 }
2073
2074 let hooks = this.event_hooks(event, context);
2075 if hooks.is_empty() {
2076 // Fast path: no hooks for this event → skip the
2077 // `context.to_env_vars()` HashMap allocation. With
2078 // `tool_call_before` / `tool_call_after` firing per-tool
2079 // (#455) this allocation would otherwise happen on every
2080 // tool dispatch even for users with zero hooks configured.
2081 return Vec::new();
2082 }
2083 if event == HookEvent::ToolCallAfter
2084 && let Some(payload) = context.tool_after_payload()
2085 {
2086 return self.execute_json_observer(event, context, &payload);
2087 }
2088 let env_vars = context.to_env_vars();
2089 let mut results = Vec::new();
2090
2091 for hook in &hooks {
2092 if this.cancelled() {
2093 break;
2094 }
2095 if !self.matches_condition(hook, context) {
2096 continue;
2097 }
2098
2099 let result = if hook.background {
2100 this.execute_background(hook, &env_vars)
2101 } else {
2102 this.execute_sync(hook, &env_vars)
2103 };
2104
2105 // Log failures via tracing so operators tailing
2106 // `deepseek` with `RUST_LOG=warn` can see hook errors
2107 // without instrumenting each call site. Successful runs
2108 // log nothing (would be too noisy on per-tool events).
2109 if !result.success {
2110 let label = sanitize_hook_label(result.name.as_deref());
2111 tracing::warn!(
2112 target: "hooks",
2113 hook = %label,
2114 event = event.as_str(),
2115 exit_code = ?result.exit_code,
2116 duration_ms = result.duration.as_millis() as u64,
2117 detail = %generic_unavailable_detail(result.error.as_deref()),
2118 "hook failed"
2119 );
2120 }
2121
2122 let should_continue = result.success || hook.continue_on_error;
2123 results.push(result);
2124
2125 if !should_continue {
2126 break;
2127 }
2128 }
2129
2130 results
2131 }
2132
2133 /// Execute observer hooks with a structured JSON stdin payload.
2134 ///
2135 /// Unlike `message_submit`, stdout is deliberately ignored by callers:
2136 /// these hooks are lifecycle observers and cannot mutate or block the
2137 /// underlying action.
2138 pub fn execute_json_observer(
2139 &self,
2140 event: HookEvent,
2141 context: &HookContext,
2142 payload: &serde_json::Value,
2143 ) -> Vec<HookResult> {
2144 let bound = self.for_context(context);
2145 let this = &bound;
2146 if !self.config.enabled {
2147 return Vec::new();
2148 }
2149
2150 let hooks = this.event_hooks(event, context);
2151 if hooks.is_empty() {
2152 return Vec::new();
2153 }
2154
2155 let env_vars = context.to_env_vars();
2156 let mut results = Vec::new();
2157 for hook in &hooks {
2158 if !self.matches_condition(hook, context) {
2159 continue;
2160 }
2161
2162 let result = if hook.background {
2163 this.execute_background_with_stdin(hook, &env_vars, payload)
2164 } else {
2165 this.execute_sync_with_stdin(hook, &env_vars, payload)
2166 };
2167
2168 if !result.success {
2169 let label = sanitize_hook_label(result.name.as_deref());
2170 tracing::warn!(
2171 target: "hooks",
2172 hook = %label,
2173 event = event.as_str(),
2174 exit_code = ?result.exit_code,
2175 duration_ms = result.duration.as_millis() as u64,
2176 detail = %generic_unavailable_detail(result.error.as_deref()),
2177 "observer hook failed"
2178 );
2179 }
2180
2181 results.push(result);
2182 }
2183
2184 results
2185 }
2186
2187 /// Submit an observer event without waiting on foreground child processes
2188 /// from the caller's thread. The outer worker is fallible and the failure
2189 /// is returned to the UI; silently dropping a configured observer is not a
2190 /// truthful fire-and-forget contract.
2191 pub fn submit_observer(&self, event: HookEvent, context: HookContext) -> Result<(), String> {
2192 if !self.has_hooks_for_event(event) {
2193 return Ok(());
2194 }
2195 if event == HookEvent::ToolCallAfter
2196 && let Some(payload) = context.tool_after_payload()
2197 {
2198 return self.submit_json_observer(event, context, payload);
2199 }
2200 self.observer_dispatcher.submit(
2201 event,
2202 ObserverJob::Environment {
2203 hooks: self.clone(),
2204 event,
2205 context: context.bounded_for_observer(),
2206 },
2207 )
2208 }
2209
2210 /// Structured-payload counterpart to [`Self::submit_observer`].
2211 pub fn submit_json_observer(
2212 &self,
2213 event: HookEvent,
2214 context: HookContext,
2215 payload: serde_json::Value,
2216 ) -> Result<(), String> {
2217 if !self.has_hooks_for_event(event) {
2218 return Ok(());
2219 }
2220 self.observer_dispatcher.submit(
2221 event,
2222 ObserverJob::Json {
2223 hooks: self.clone(),
2224 event,
2225 context: context.bounded_for_observer(),
2226 payload,
2227 },
2228 )
2229 }
2230
2231 /// Check whether a tool name matches a condition pattern with `*` glob support.
2232 ///
2233 /// DOCS-04: MCP-scoped patterns match on the owning MCP server, not on the
2234 /// `mcp_` name prefix. The model calls a server tool by
2235 /// [`crate::mcp::McpPool::mcp_model_tool_name`] (`mcp_<server>_<tool>`),
2236 /// while the documented spelling is `mcp__<server>__<tool>`; both are
2237 /// accepted. Any glob starting with `mcp_`, and any `mcp__` pattern, only
2238 /// ever selects tools a server owns, so the built-in MCP helpers such as
2239 /// `mcp_read_resource` are reachable by exact name only.
2240 ///
2241 /// Known limit: ownership is read from the model name, not the live pool,
2242 /// so `mcp__<server>__…` splits at the first `__` (a server whose name
2243 /// contains `__` needs the `mcp_<server>_…` spelling), and a server tool
2244 /// whose model name collides with a helper name is treated as the helper.
2245 fn tool_name_matches_condition(tool_name: &str, pattern: &str) -> bool {
2246 if tool_name == pattern {
2247 return true;
2248 }
2249 // The shell tool is spelled `bash` / `Bash` on the model surface, and
2250 // `exec_shell` is still stamped for the `shell_env` event and lives
2251 // on in older hook configs. Treat the three as one tool, matching
2252 // `tool_category_for`, so a condition written with any spelling fires.
2253 if is_shell_tool_name(tool_name) && is_shell_tool_name(pattern) {
2254 return true;
2255 }
2256 if let Some(rest) = pattern.strip_prefix("mcp_") {
2257 let documented = rest.strip_prefix('_');
2258 if documented.is_some() || pattern.contains('*') {
2259 if !is_mcp_server_tool(tool_name) {
2260 return false;
2261 }
2262 let model_pattern = match documented {
2263 Some(rest) => match rest.split_once("__") {
2264 Some((server, tool)) => {
2265 crate::mcp::McpPool::mcp_model_tool_name(server, tool)
2266 }
2267 None => format!("mcp_{rest}"),
2268 },
2269 None => pattern.to_string(),
2270 };
2271 return Self::glob_matches(tool_name, &model_pattern);
2272 }
2273 }
2274 Self::glob_matches(tool_name, pattern)
2275 }
2276
2277 fn glob_matches(tool_name: &str, pattern: &str) -> bool {
2278 if !pattern.contains('*') {
2279 return tool_name == pattern;
2280 }
2281 // #6208: the pattern is fixed by configuration while this runs once per
2282 // hook per tool-call/stop event, so compile it once and reuse it rather
2283 // than building a fresh `Regex` on every event.
2284 codewhale_execpolicy::matcher::compiled_glob(pattern)
2285 .is_some_and(|re| re.is_match(tool_name))
2286 }
2287
2288 /// Check if a hook's condition matches the context
2289 #[allow(clippy::only_used_in_recursion)]
2290 fn matches_condition(&self, hook: &Hook, context: &HookContext) -> bool {
2291 match &hook.condition {
2292 None | Some(HookCondition::Always) => true,
2293 Some(HookCondition::ToolName { name }) => {
2294 // #3026: Support `*` globs in tool_name conditions so
2295 // `mcp__*` matches every tool an MCP server owns (DOCS-04:
2296 // not the built-in `mcp_*` helpers). Exact names keep working.
2297 context
2298 .tool_name
2299 .as_ref()
2300 .is_some_and(|n| Self::tool_name_matches_condition(n, name))
2301 }
2302 Some(HookCondition::ToolCategory { category }) => {
2303 let tool_category = context
2304 .tool_name
2305 .as_deref()
2306 .map(|name| tool_category_for(name, context.tool_args.as_deref()));
2307 tool_category.is_some_and(|c| c == category.as_str())
2308 }
2309 Some(HookCondition::Mode { mode }) => context
2310 .mode
2311 .as_ref()
2312 .is_some_and(|m| m.eq_ignore_ascii_case(mode)),
2313 Some(HookCondition::ExitCode { code }) => context.tool_exit_code == Some(*code),
2314 Some(HookCondition::All { conditions }) => conditions.iter().all(|c| {
2315 self.matches_condition(
2316 &Hook {
2317 condition: Some(c.clone()),
2318 ..hook.clone()
2319 },
2320 context,
2321 )
2322 }),
2323 Some(HookCondition::Any { conditions }) => conditions.iter().any(|c| {
2324 self.matches_condition(
2325 &Hook {
2326 condition: Some(c.clone()),
2327 ..hook.clone()
2328 },
2329 context,
2330 )
2331 }),
2332 }
2333 }
2334
2335 /// Execute a hook synchronously
2336 fn execute_sync(&self, hook: &Hook, env_vars: &HashMap<String, String>) -> HookResult {
2337 self.execute_sync_inner(hook, env_vars, None)
2338 }
2339
2340 /// Execute a hook synchronously with a structured JSON stdin payload.
2341 ///
2342 /// Used by mutable `message_submit` hooks. Existing observer hooks keep the
2343 /// stdin-less [`Self::execute_sync`] path so their behavior is unchanged.
2344 fn execute_sync_with_stdin(
2345 &self,
2346 hook: &Hook,
2347 env_vars: &HashMap<String, String>,
2348 stdin_json: &serde_json::Value,
2349 ) -> HookResult {
2350 self.execute_sync_inner(hook, env_vars, Some(stdin_json))
2351 }
2352
2353 fn execute_sync_inner(
2354 &self,
2355 hook: &Hook,
2356 env_vars: &HashMap<String, String>,
2357 stdin_json: Option<&serde_json::Value>,
2358 ) -> HookResult {
2359 let _policy = codewhale_plugins::activation::PolicyScope::propagate(self.native_policy);
2360 if !self.native_policy {
2361 if hook.native_shell.is_some() {
2362 return unavailable_hook(hook, "Native shell hook is disabled");
2363 }
2364 return self.execute_sync_legacy(hook, env_vars, stdin_json, self.cancel.as_ref());
2365 }
2366 let Some(caller) = self.caller.clone() else {
2367 return unavailable_hook(hook, "hook caller receipt is unavailable");
2368 };
2369 let Some(handle) = self.engine_handle.clone() else {
2370 return unavailable_hook(hook, "hook Engine scheduler is unavailable");
2371 };
2372 let manager = Arc::clone(&self.host_manager);
2373 manager.bind_engine_handle(handle.clone());
2374 let executor = self.clone();
2375 let owned_hook = hook.clone();
2376 let env = env_vars.clone();
2377 let input = if let Some(native) = hook.native_shell.as_ref() {
2378 let Some(context) = self.fire_context.as_ref() else {
2379 return unavailable_hook(hook, "Native hook firepoint context is missing");
2380 };
2381 match context.native_payload(&native.point, stdin_json) {
2382 Ok(input) => Some(input),
2383 Err(reason) => return unavailable_hook(hook, &reason),
2384 }
2385 } else {
2386 stdin_json.cloned()
2387 };
2388 let (sender, receiver) = mpsc::sync_channel(1);
2389 let policy = self.native_policy;
2390 #[cfg(any(test, feature = "test-support"))]
2391 let env_scope = crate::test_support::env_scope_ticket();
2392 let query = if matches!(
2393 hook.event,
2394 HookEvent::SubagentSpawn | HookEvent::SubagentComplete
2395 ) {
2396 "general-purpose".into()
2397 } else if hook.event == HookEvent::SessionStart {
2398 "startup".into()
2399 } else {
2400 env_vars
2401 .get("DEEPSEEK_TOOL_NAME")
2402 .cloned()
2403 .unwrap_or_default()
2404 };
2405 let turn_cancel = self.cancel.clone();
2406 let work = handle.spawn(async move {
2407 let _policy = codewhale_plugins::activation::PolicyScope::propagate(policy);
2408 #[cfg(any(test, feature = "test-support"))]
2409 let _env_scope = crate::test_support::join_env_scope(env_scope);
2410 let timeout = Duration::from_secs(executor.effective_timeout_secs(&owned_hook));
2411 let hook_for_run = owned_hook.clone();
2412 let run = manager.execute_hook(caller, owned_hook, timeout, query, move |cancel| {
2413 let _policy = codewhale_plugins::activation::PolicyScope::propagate(policy);
2414 executor.execute_sync_legacy(&hook_for_run, &env, input.as_ref(), Some(&cancel))
2415 });
2416 let result = match turn_cancel {
2417 Some(turn_cancel) => tokio::select! {
2418 result = run => result,
2419 () = turn_cancel.cancelled() => Err("hook cancelled with its turn".into()),
2420 },
2421 None => run.await,
2422 };
2423 let _ = sender.send(result);
2424 });
2425 // Never block an Engine/UI runtime worker. Its synchronous callsites already use
2426 // existing observer/blocking dispatch; ShellEnv's async caller is migrated below.
2427 let _engine_task = work;
2428 receiver
2429 .recv()
2430 .unwrap_or_else(|_| Err("hook Engine task was lost".into()))
2431 .unwrap_or_else(|reason| unavailable_hook(hook, &reason))
2432 }
2433
2434 fn execute_sync_legacy(
2435 &self,
2436 hook: &Hook,
2437 env_vars: &HashMap<String, String>,
2438 stdin_json: Option<&serde_json::Value>,
2439 cancel: Option<&tokio_util::sync::CancellationToken>,
2440 ) -> HookResult {
2441 let started = Instant::now();
2442 if let Err(reason) = super::authority::verify_hook(hook) {
2443 return HookResult {
2444 name: hook.name.clone(),
2445 background: false,
2446 strict: !hook.continue_on_error,
2447 success: false,
2448 exit_code: None,
2449 stdout: String::new(),
2450 stderr: String::new(),
2451 duration: started.elapsed(),
2452 error: Some(format!("Hook authority was denied: {reason}")),
2453 };
2454 }
2455 let working_dir = self
2456 .config
2457 .working_dir
2458 .clone()
2459 .unwrap_or_else(|| self.default_working_dir.clone());
2460
2461 let timeout_secs = self.effective_timeout_secs(hook);
2462 let timeout = Duration::from_secs(timeout_secs);
2463 // This path always runs the hook in the foreground and awaits it, so
2464 // `continue_on_error = false` is a live "do not proceed without my
2465 // answer" for whichever call this result belongs to.
2466 let strict = !hook.continue_on_error;
2467
2468 let stdin_bytes = match stdin_json.map(serde_json::to_vec).transpose() {
2469 Ok(bytes) => bytes,
2470 Err(e) => {
2471 return HookResult {
2472 name: hook.name.clone(),
2473 background: false,
2474 strict,
2475 success: false,
2476 exit_code: None,
2477 stdout: String::new(),
2478 stderr: String::new(),
2479 duration: started.elapsed(),
2480 error: Some(format!("Failed to encode hook stdin: {e}")),
2481 };
2482 }
2483 };
2484
2485 let mut command = Self::build_shell_command(&hook.command);
2486 if hook
2487 .native_shell
2488 .as_ref()
2489 .is_some_and(|n| n.dialect == "claude-code")
2490 {
2491 command.env("CLAUDE_PROJECT_DIR", &self.default_working_dir);
2492 }
2493 command
2494 .current_dir(&working_dir)
2495 .envs(env_vars)
2496 .stdout(Stdio::piped())
2497 .stderr(Stdio::piped())
2498 // A closed pipe is a portable EOF signal through shell layers.
2499 // Windows cmd/PowerShell can reopen console input when handed
2500 // NUL, so Stdio::null() is not sufficient when the parent test or
2501 // terminal still owns a live stdin handle.
2502 .stdin(Stdio::piped());
2503
2504 if self.native_policy {
2505 codewhale_runtime::child_env::apply_to_command(
2506 &mut command,
2507 codewhale_runtime::child_env::string_map_env(env_vars),
2508 );
2509 if hook
2510 .native_shell
2511 .as_ref()
2512 .is_some_and(|native| native.dialect == "claude-code")
2513 {
2514 command.env("CLAUDE_PROJECT_DIR", &self.default_working_dir);
2515 }
2516 if !env_vars.contains_key("DEEPSEEK_TOOL_EXECUTION_RECEIPT") {
2517 command.env_remove("DEEPSEEK_TOOL_EXECUTION_RECEIPT");
2518 }
2519 }
2520 let (mut child, process_tree) = match spawn_hook_child(&mut command) {
2521 Ok(child) => child,
2522 Err(e) => {
2523 // Generic on purpose: this string reaches the deny receipt and
2524 // the TUI, and a spawn error can otherwise echo the resolved
2525 // command line or interpreter path back to the transcript.
2526 tracing::warn!(
2527 target: "hooks",
2528 hook = %sanitize_hook_label(hook.name.as_deref()),
2529 error = %e,
2530 "failed to start hook process"
2531 );
2532 return HookResult {
2533 name: hook.name.clone(),
2534 background: false,
2535 strict,
2536 success: false,
2537 exit_code: None,
2538 stdout: String::new(),
2539 stderr: String::new(),
2540 duration: started.elapsed(),
2541 error: Some(spawn_failure_message(&e)),
2542 };
2543 }
2544 };
2545
2546 let stdout_reader = match child
2547 .stdout
2548 .take()
2549 .map(|pipe| spawn_pipe_reader(pipe, "hook-stdout-reader"))
2550 .transpose()
2551 {
2552 Ok(reader) => reader,
2553 Err(error) => {
2554 tracing::warn!(
2555 target: "hooks",
2556 hook = %sanitize_hook_label(hook.name.as_deref()),
2557 error_kind = ?error.kind(),
2558 "failed to start hook stdout reader"
2559 );
2560 terminate_and_reap(hook.name.as_deref(), &mut child, process_tree);
2561 return HookResult {
2562 name: hook.name.clone(),
2563 background: false,
2564 strict,
2565 success: false,
2566 exit_code: None,
2567 stdout: String::new(),
2568 stderr: String::new(),
2569 duration: started.elapsed(),
2570 error: Some("hook stdout reader could not be started".to_string()),
2571 };
2572 }
2573 };
2574 let stderr_reader = match child
2575 .stderr
2576 .take()
2577 .map(|pipe| spawn_pipe_reader(pipe, "hook-stderr-reader"))
2578 .transpose()
2579 {
2580 Ok(reader) => reader,
2581 Err(error) => {
2582 tracing::warn!(
2583 target: "hooks",
2584 hook = %sanitize_hook_label(hook.name.as_deref()),
2585 error_kind = ?error.kind(),
2586 "failed to start hook stderr reader"
2587 );
2588 terminate_and_reap(hook.name.as_deref(), &mut child, process_tree);
2589 let _ = collect_reader(stdout_reader, HOOK_PIPE_SHUTDOWN_TIMEOUT);
2590 return HookResult {
2591 name: hook.name.clone(),
2592 background: false,
2593 strict,
2594 success: false,
2595 exit_code: None,
2596 stdout: String::new(),
2597 stderr: String::new(),
2598 duration: started.elapsed(),
2599 error: Some("hook stderr reader could not be started".to_string()),
2600 };
2601 }
2602 };
2603 let _stdin_writer = match (stdin_bytes, child.stdin.take()) {
2604 (Some(bytes), Some(stdin)) => match spawn_stdin_writer(stdin, bytes) {
2605 Ok(writer) => Some(writer),
2606 Err(error) => {
2607 tracing::warn!(
2608 target: "hooks",
2609 hook = %sanitize_hook_label(hook.name.as_deref()),
2610 error_kind = ?error.kind(),
2611 "failed to start hook stdin writer"
2612 );
2613 terminate_and_reap(hook.name.as_deref(), &mut child, process_tree);
2614 let _ = collect_reader(stdout_reader, HOOK_PIPE_SHUTDOWN_TIMEOUT);
2615 let _ = collect_reader(stderr_reader, HOOK_PIPE_SHUTDOWN_TIMEOUT);
2616 return HookResult {
2617 name: hook.name.clone(),
2618 background: false,
2619 strict,
2620 success: false,
2621 exit_code: None,
2622 stdout: String::new(),
2623 stderr: String::new(),
2624 duration: started.elapsed(),
2625 error: Some("hook stdin writer could not be started".to_string()),
2626 };
2627 }
2628 },
2629 _ => None,
2630 };
2631
2632 let deadline = Instant::now().checked_add(timeout);
2633 let waited = loop {
2634 if cancel.is_some_and(|token| token.is_cancelled()) {
2635 break Ok(None);
2636 }
2637 let remaining = deadline
2638 .map(|d| d.saturating_duration_since(Instant::now()))
2639 .unwrap_or(timeout);
2640 if remaining.is_zero() {
2641 break Ok(None);
2642 }
2643 match child.wait_timeout(remaining.min(Duration::from_millis(25))) {
2644 Ok(None) => continue,
2645 result => break result,
2646 }
2647 };
2648 match waited {
2649 Ok(Some(status)) => {
2650 drop(process_tree);
2651 HookResult {
2652 name: hook.name.clone(),
2653 background: false,
2654 strict,
2655 success: status.success(),
2656 exit_code: status.code(),
2657 stdout: collect_reader(stdout_reader, HOOK_PIPE_DRAIN_TIMEOUT),
2658 stderr: collect_reader(stderr_reader, HOOK_PIPE_DRAIN_TIMEOUT),
2659 duration: started.elapsed(),
2660 error: None,
2661 }
2662 }
2663 Ok(None) => {
2664 let reaped = terminate_and_reap(hook.name.as_deref(), &mut child, process_tree);
2665 let _ = collect_reader(stdout_reader, HOOK_PIPE_SHUTDOWN_TIMEOUT);
2666 let _ = collect_reader(stderr_reader, HOOK_PIPE_SHUTDOWN_TIMEOUT);
2667 HookResult {
2668 name: hook.name.clone(),
2669 background: false,
2670 strict,
2671 success: false,
2672 exit_code: None,
2673 stdout: String::new(),
2674 stderr: String::new(),
2675 duration: started.elapsed(),
2676 error: Some(
2677 if reaped && cancel.is_some_and(|token| token.is_cancelled()) {
2678 "Hook cancelled with its turn".to_string()
2679 } else if reaped {
2680 format!("Hook timed out after {timeout_secs}s")
2681 } else {
2682 // The gate still did not answer, and now we also cannot
2683 // prove the process is gone. Say the weaker thing.
2684 "hook could not be reaped after its timeout".to_string()
2685 },
2686 ),
2687 }
2688 }
2689 Err(e) => {
2690 tracing::warn!(
2691 target: "hooks",
2692 hook = %sanitize_hook_label(hook.name.as_deref()),
2693 error = %e,
2694 "failed to wait for hook process"
2695 );
2696 terminate_and_reap(hook.name.as_deref(), &mut child, process_tree);
2697 let _ = collect_reader(stdout_reader, HOOK_PIPE_SHUTDOWN_TIMEOUT);
2698 let _ = collect_reader(stderr_reader, HOOK_PIPE_SHUTDOWN_TIMEOUT);
2699 HookResult {
2700 name: hook.name.clone(),
2701 background: false,
2702 strict,
2703 success: false,
2704 exit_code: None,
2705 stdout: String::new(),
2706 stderr: String::new(),
2707 duration: started.elapsed(),
2708 // Generic on purpose, like the spawn path: an OS wait error
2709 // can name the child and reaches the deny receipt.
2710 error: Some("Failed to wait for hook".to_string()),
2711 }
2712 }
2713 }
2714 }
2715
2716 /// Execute a hook in the background (non-blocking)
2717 fn execute_background(&self, hook: &Hook, env_vars: &HashMap<String, String>) -> HookResult {
2718 self.execute_background_inner(hook, env_vars, None)
2719 }
2720
2721 fn execute_background_with_stdin(
2722 &self,
2723 hook: &Hook,
2724 env_vars: &HashMap<String, String>,
2725 stdin_json: &serde_json::Value,
2726 ) -> HookResult {
2727 self.execute_background_inner(hook, env_vars, Some(stdin_json))
2728 }
2729
2730 fn execute_background_inner(
2731 &self,
2732 hook: &Hook,
2733 env_vars: &HashMap<String, String>,
2734 stdin_json: Option<&serde_json::Value>,
2735 ) -> HookResult {
2736 let started = Instant::now();
2737 if let Err(reason) = super::authority::verify_hook(hook) {
2738 return HookResult {
2739 name: hook.name.clone(),
2740 background: true,
2741 strict: false,
2742 success: false,
2743 exit_code: None,
2744 stdout: String::new(),
2745 stderr: String::new(),
2746 duration: started.elapsed(),
2747 error: Some(format!("Hook authority was denied: {reason}")),
2748 };
2749 }
2750 let working_dir = self
2751 .config
2752 .working_dir
2753 .clone()
2754 .unwrap_or_else(|| self.default_working_dir.clone());
2755
2756 let stdin_bytes = match stdin_json.map(serde_json::to_vec).transpose() {
2757 Ok(bytes) => bytes,
2758 Err(e) => {
2759 return HookResult {
2760 name: hook.name.clone(),
2761 background: true,
2762 strict: false,
2763 success: false,
2764 exit_code: None,
2765 stdout: String::new(),
2766 stderr: String::new(),
2767 duration: started.elapsed(),
2768 error: Some(format!("Failed to encode hook stdin: {e}")),
2769 };
2770 }
2771 };
2772 let submission = self.background_supervisor.submit(BackgroundHookJob {
2773 admitted: self.native_policy.then(|| AdmittedBackground {
2774 executor: self.clone(),
2775 hook: hook.clone(),
2776 env: env_vars.clone(),
2777 input: stdin_json.cloned(),
2778 }),
2779 command: hook.command.clone(),
2780 env: env_vars.clone(),
2781 working_dir,
2782 stdin_bytes,
2783 label: sanitize_hook_label(hook.name.as_deref()),
2784 timeout: Duration::from_secs(self.effective_timeout_secs(hook)),
2785 plugin_authority: hook.plugin_authority.clone(),
2786 project_authority: hook.project_authority.clone(),
2787 });
2788
2789 // The result describes the bounded submission, not the run: no caller
2790 // can mistake "queued" for "exited 0".
2791 HookResult {
2792 name: hook.name.clone(),
2793 background: true,
2794 strict: false,
2795 success: submission.is_ok(),
2796 exit_code: None,
2797 stdout: String::new(),
2798 stderr: String::new(),
2799 duration: started.elapsed(),
2800 error: submission.err().map(|failure| match failure {
2801 BackgroundSupervisorFailure::Full => {
2802 "background hook supervisor queue is full".to_string()
2803 }
2804 BackgroundSupervisorFailure::Disconnected => {
2805 "background hook supervisor is unavailable".to_string()
2806 }
2807 }),
2808 }
2809 }
2810
2811 /// The timeout actually applied to a hook, foreground or background.
2812 ///
2813 /// `[hooks].default_timeout_secs` *replaces* the per-hook value when set;
2814 /// that is the shipped behavior and is documented as such in
2815 /// `docs/HOOKS.md`.
2816 fn effective_timeout_secs(&self, hook: &Hook) -> u64 {
2817 self.config.effective_timeout_secs(hook)
2818 }
2819 }
2820
2821 fn unavailable_hook(hook: &Hook, reason: &str) -> HookResult {
2822 HookResult {
2823 name: hook.name.clone(),
2824 success: false,
2825 background: false,
2826 strict: !hook.continue_on_error,
2827 exit_code: None,
2828 stdout: String::new(),
2829 stderr: String::new(),
2830 duration: Duration::ZERO,
2831 error: Some(reason.into()),
2832 }
2833 }
2834
2835 /// Whether `name` is a tool some MCP server owns, as opposed to one of the
2836 /// built-in MCP helpers the TUI itself registers (`McpPool::is_mcp_tool`
2837 /// counts both). Server tools are named by `McpPool::mcp_model_tool_name`.
2838 fn is_mcp_server_tool(name: &str) -> bool {
2839 name.starts_with("mcp_")
2840 && !matches!(
2841 name,
2842 "mcp_read_resource"
2843 | "mcp_get_prompt"
2844 | "list_mcp_resources"
2845 | "list_mcp_resource_templates"
2846 | "read_mcp_resource"
2847 )
2848 }
2849
2850 /// The spellings of the one shell tool (see `tool_category_for`).
2851 fn is_shell_tool_name(name: &str) -> bool {
2852 matches!(name, "bash" | "Bash" | "exec_shell")
2853 }
2854
2855 /// Classify a tool call for `condition = { type = "tool_category", … }`.
2856 ///
2857 /// Categories are `shell`, `file_write`, `safe`, and `other`, as documented in
2858 /// `docs/HOOKS.md`. This must be kept in step with the names the registry
2859 /// actually registers: before 2026-08-04 the map knew only the retired
2860 /// `exec_shell`/`write_file`/`read_file` spellings, so EVERY live call fell
2861 /// through to `other` and a `tool_category` **deny** hook silently never
2862 /// fired — the exact failure `docs/HOOKS.md` warns about ("a deny gate the
2863 /// operator believes is armed").
2864 ///
2865 /// `File`, `Git`, `tasks` and `rlm` are multi-action, so the action decides
2866 /// the category: a `File` read is `safe` while a `File` write is `file_write`.
2867 /// An unparseable or absent argument blob is treated as the tool's most
2868 /// dangerous action, because a gate that cannot see the action must not
2869 /// assume the harmless one.
2870 fn tool_category_for(tool_name: &str, tool_args: Option<&str>) -> &'static str {
2871 let action = tool_args
2872 .and_then(|raw| serde_json::from_str::<serde_json::Value>(raw).ok())
2873 .and_then(|value| {
2874 value
2875 .get("action")
2876 .and_then(serde_json::Value::as_str)
2877 .map(str::to_ascii_lowercase)
2878 });
2879
2880 match tool_name {
2881 // The shell surface. `exec_shell` is retired but kept here because
2882 // `shell.rs` still stamps it for the `shell_env` hook event.
2883 name if is_shell_tool_name(name) => "shell",
2884 "terminal_run" | "terminal_send" | "terminal_reset" | "task_shell_start"
2885 | "task_gate_run" | "code_execution" | "js_execution" | "rlm_eval" => "shell",
2886 // The lowercase primitives ship without an action envelope.
2887 "read" | "read_file" | "todo_write" => "safe",
2888 "write" | "edit" | "write_file" | "edit_file" | "fim_edit" => "file_write",
2889 "File" | "file" => match action.as_deref() {
2890 Some("read" | "list" | "search_name" | "search_content") => "safe",
2891 // write/edit/patch, and the unknown-action case, are writes.
2892 _ => "file_write",
2893 },
2894 "apply_patch" => "file_write",
2895 "Git" | "git" => match action.as_deref() {
2896 // Every shipped Git action is read-only today; classify by action
2897 // anyway so adding a mutating one cannot silently inherit `safe`.
2898 Some("status" | "diff" | "log" | "show" | "blame" | "commit_plan") => "safe",
2899 _ => "other",
2900 },
2901 "tasks" => match action.as_deref() {
2902 Some("gate_run") => "shell",
2903 _ => "other",
2904 },
2905 "rlm" => match action.as_deref() {
2906 Some("eval") => "shell",
2907 _ => "other",
2908 },
2909 // `Run` executes test/verifier commands — closer to shell than safe.
2910 "Run" | "run" => "shell",
2911 _ => "other",
2912 }
2913 }
2914
2915 const HOOK_PIPE_DRAIN_TIMEOUT: Duration = Duration::from_secs(5);
2916 const HOOK_PIPE_SHUTDOWN_TIMEOUT: Duration = Duration::from_millis(250);
2917 /// How long the timeout path waits for the killed child to be reaped.
2918 ///
2919 /// The wait after a kill is *bounded* rather than unbounded: `child.wait()`
2920 /// blocks forever if the kill did not take (a `SIGKILL`-immune uninterruptible
2921 /// state on Unix, a `TerminateJobObject` that a protected process survived on
2922 /// Windows), and that turned "this hook has a 30s budget" into a hung turn.
2923 #[cfg(not(windows))]
2924 const HOOK_REAP_TIMEOUT: Duration = Duration::from_secs(2);
2925 #[cfg(windows)]
2926 const HOOK_REAP_TIMEOUT: Duration = Duration::from_secs(10);
2927 #[cfg(windows)]
2928 const WINDOWS_TASKKILL_TIMEOUT: Duration = Duration::from_secs(2);
2929
2930 /// Kill the hook's process tree and wait, briefly, for the corpse.
2931 ///
2932 /// Termination is best-effort by nature — the OS owns whether a kill lands.
2933 /// What is guaranteed here is that *this* thread stops waiting: the
2934 /// containment guard is dropped first (which re-signals the Unix process group
2935 /// and closes the kill-on-close Windows Job Object), then the reap gets one
2936 /// bounded window. Returns `false` when the child could not be confirmed dead,
2937 /// so the caller can report the weaker claim instead of asserting cleanup.
2938 fn terminate_and_reap(
2939 hook_name: Option<&str>,
2940 child: &mut Child,
2941 process_tree: ProcessTree,
2942 ) -> bool {
2943 terminate_tree(&process_tree, child);
2944 // Drop before the wait, not after: on Windows this closes the Job Object
2945 // and is itself a kill, and on Unix it re-signals the group. Waiting first
2946 // would delay the very thing meant to make the wait short.
2947 drop(process_tree);
2948 match child.wait_timeout(HOOK_REAP_TIMEOUT) {
2949 Ok(Some(_)) => true,
2950 Ok(None) => {
2951 tracing::warn!(
2952 target: "hooks",
2953 hook = %sanitize_hook_label(hook_name),
2954 reap_timeout_secs = HOOK_REAP_TIMEOUT.as_secs(),
2955 "hook process did not exit after its tree was killed; abandoning the reap"
2956 );
2957 false
2958 }
2959 Err(error) => {
2960 tracing::warn!(
2961 target: "hooks",
2962 hook = %sanitize_hook_label(hook_name),
2963 %error,
2964 "failed to reap killed hook process"
2965 );
2966 false
2967 }
2968 }
2969 }
2970
2971 fn spawn_pipe_reader(
2972 mut pipe: impl Read + Send + 'static,
2973 worker_name: &str,
2974 ) -> std::io::Result<Receiver<String>> {
2975 let (tx, rx) = mpsc::channel();
2976 std::thread::Builder::new()
2977 .name(worker_name.to_string())
2978 .spawn(move || {
2979 let mut retained = Vec::with_capacity(HOOK_PIPE_CAPTURE_MAX_BYTES.min(8 * 1024));
2980 let mut chunk = [0_u8; 8 * 1024];
2981 let mut truncated = false;
2982 loop {
2983 match pipe.read(&mut chunk) {
2984 Ok(0) => break,
2985 Ok(read) => {
2986 let remaining = HOOK_PIPE_CAPTURE_MAX_BYTES.saturating_sub(retained.len());
2987 let keep = remaining.min(read);
2988 retained.extend_from_slice(&chunk[..keep]);
2989 truncated |= keep < read;
2990 }
2991 Err(error) => {
2992 tracing::warn!(target: "hooks", %error, "failed while draining hook pipe");
2993 break;
2994 }
2995 }
2996 }
2997 let mut output = String::from_utf8_lossy(&retained).into_owned();
2998 if truncated {
2999 output.push_str("…[truncated]");
3000 }
3001 let _ = tx.send(output);
3002 })
3003 .map(|_| rx)
3004 }
3005
3006 fn collect_reader(reader: Option<Receiver<String>>, timeout: Duration) -> String {
3007 let Some(reader) = reader else {
3008 return String::new();
3009 };
3010 match reader.recv_timeout(timeout) {
3011 Ok(output) => output,
3012 Err(RecvTimeoutError::Timeout) => {
3013 tracing::warn!(
3014 ?timeout,
3015 "hook pipe reader did not finish after process cleanup"
3016 );
3017 String::new()
3018 }
3019 Err(RecvTimeoutError::Disconnected) => String::new(),
3020 }
3021 }
3022
3023 fn spawn_stdin_writer(
3024 mut stdin: std::process::ChildStdin,
3025 mut bytes: Vec<u8>,
3026 ) -> std::io::Result<JoinHandle<()>> {
3027 std::thread::Builder::new()
3028 .name("hook-stdin-writer".to_string())
3029 .spawn(move || {
3030 bytes.push(b'\n');
3031 let _ = stdin.write_all(&bytes);
3032 let _ = stdin.flush();
3033 })
3034 }
3035
3036 fn bounded_message_submit_metadata(value: Option<&str>, max_bytes: usize) -> Option<String> {
3037 value.map(|value| truncate_env_value(value, max_bytes))
3038 }
3039
3040 fn build_message_submit_payload(
3041 context: &HookContext,
3042 text: &str,
3043 original_bytes: usize,
3044 truncated: bool,
3045 metadata_max_bytes: Option<usize>,
3046 ) -> serde_json::Value {
3047 let mut payload = json!({
3048 "event": HookEvent::MessageSubmit.as_str(),
3049 "text": text,
3050 "text_bytes": text.len(),
3051 "text_original_bytes": original_bytes,
3052 "text_truncated": truncated,
3053 });
3054 if let Some(max_bytes) = metadata_max_bytes {
3055 let object = payload
3056 .as_object_mut()
3057 .expect("message_submit payload is an object");
3058 object.insert(
3059 "session_id".to_string(),
3060 json!(bounded_message_submit_metadata(
3061 context.session_id.as_deref(),
3062 max_bytes
3063 )),
3064 );
3065 object.insert(
3066 "workspace".to_string(),
3067 json!(bounded_message_submit_metadata(
3068 context.workspace.as_ref().and_then(|path| path.to_str()),
3069 max_bytes
3070 )),
3071 );
3072 object.insert(
3073 "mode".to_string(),
3074 json!(bounded_message_submit_metadata(
3075 context.mode.as_deref(),
3076 max_bytes
3077 )),
3078 );
3079 object.insert(
3080 "model".to_string(),
3081 json!(bounded_message_submit_metadata(
3082 context.model.as_deref(),
3083 max_bytes
3084 )),
3085 );
3086 object.insert("total_tokens".to_string(), json!(context.total_tokens));
3087 }
3088 payload
3089 }
3090
3091 fn encoded_message_submit_payload_fits(payload: &serde_json::Value) -> bool {
3092 serde_json::to_vec(payload)
3093 .is_ok_and(|bytes| bytes.len() <= HOOK_MESSAGE_SUBMIT_PAYLOAD_MAX_BYTES)
3094 }
3095
3096 fn finalize_message_submit_payload(
3097 payload: serde_json::Value,
3098 original_bytes: usize,
3099 ) -> serde_json::Value {
3100 if encoded_message_submit_payload_fits(&payload) {
3101 return payload;
3102 }
3103
3104 // Serialization of a `Value` is infallible in practice, but the size
3105 // boundary is security-sensitive. If an invariant above ever regresses,
3106 // discard all user text and diagnostics rather than handing an oversized
3107 // document to a hook process.
3108 tracing::error!(target: "hooks", "message_submit payload fitter exceeded its hard byte cap");
3109 let fail_closed = build_message_submit_payload(
3110 &HookContext::new(),
3111 "",
3112 original_bytes,
3113 original_bytes != 0,
3114 None,
3115 );
3116 assert!(
3117 encoded_message_submit_payload_fits(&fail_closed),
3118 "minimal message_submit payload must fit the hard byte cap"
3119 );
3120 fail_closed
3121 }
3122
3123 /// Build the one canonical `message_submit` stdin document.
3124 ///
3125 /// Every producer — immediate input, restored queue entries, merged steers,
3126 /// and hook-to-hook replacements — crosses this serialization boundary. The
3127 /// largest UTF-8-safe text prefix that keeps the *serialized JSON* within the
3128 /// byte ceiling is retained, and explicit metadata tells the hook exactly
3129 /// what was clipped.
3130 pub fn message_submit_payload(context: &HookContext, text: &str) -> serde_json::Value {
3131 // Diagnostic metadata is useful but never allowed to crowd the actual
3132 // gate input out of the hard byte budget. Control-heavy strings can grow
3133 // sixfold when JSON-escaped, so try progressively smaller snapshots and
3134 // finally omit diagnostics altogether.
3135 let metadata_max_bytes = [
3136 Some(HOOK_MESSAGE_SUBMIT_METADATA_MAX_BYTES),
3137 Some(1_024),
3138 Some(256),
3139 None,
3140 ]
3141 .into_iter()
3142 .find(|metadata_max_bytes| {
3143 encoded_message_submit_payload_fits(&build_message_submit_payload(
3144 context,
3145 "",
3146 text.len(),
3147 !text.is_empty(),
3148 *metadata_max_bytes,
3149 ))
3150 })
3151 .unwrap_or(None);
3152
3153 if text.len() <= HOOK_MESSAGE_SUBMIT_PAYLOAD_MAX_BYTES {
3154 let complete =
3155 build_message_submit_payload(context, text, text.len(), false, metadata_max_bytes);
3156 if encoded_message_submit_payload_fits(&complete) {
3157 return finalize_message_submit_payload(complete, text.len());
3158 }
3159 }
3160
3161 // No candidate can retain more raw bytes than the full JSON budget. Build
3162 // at most that many UTF-8 boundaries even if a restored queue entry is
3163 // unexpectedly enormous.
3164 let raw_prefix_cap = text.len().min(HOOK_MESSAGE_SUBMIT_PAYLOAD_MAX_BYTES);
3165 let mut utf8_ends = Vec::with_capacity(raw_prefix_cap.saturating_add(1));
3166 utf8_ends.push(0);
3167 utf8_ends.extend(
3168 text.char_indices()
3169 .map(|(index, ch)| index + ch.len_utf8())
3170 .take_while(|end| *end <= raw_prefix_cap),
3171 );
3172
3173 let mut lower = 0usize;
3174 let mut upper = utf8_ends.len();
3175 while lower < upper {
3176 let middle = lower + (upper - lower) / 2;
3177 let end = utf8_ends[middle];
3178 let candidate = build_message_submit_payload(
3179 context,
3180 &text[..end],
3181 text.len(),
3182 true,
3183 metadata_max_bytes,
3184 );
3185 let fits = encoded_message_submit_payload_fits(&candidate);
3186 if fits {
3187 lower = middle + 1;
3188 } else {
3189 upper = middle;
3190 }
3191 }
3192
3193 let retained_end = utf8_ends[lower.saturating_sub(1)];
3194 finalize_message_submit_payload(
3195 build_message_submit_payload(
3196 context,
3197 &text[..retained_end],
3198 text.len(),
3199 true,
3200 metadata_max_bytes,
3201 ),
3202 text.len(),
3203 )
3204 }
3205
3206 pub fn turn_end_payload(input: TurnEndPayloadInput<'_>) -> serde_json::Value {
3207 let bounded_error = input
3208 .error
3209 .map(|error| sanitize_hook_text(error, HOOK_TURN_ERROR_MAX_CHARS));
3210 json!({
3211 "event": HookEvent::TurnEnd.as_str(),
3212 "session_id": input.context.session_id.as_deref(),
3213 "workspace": input.context.workspace.as_ref().map(|path| path.display().to_string()),
3214 "mode": input.context.mode.as_deref(),
3215 "created_at": input.created_at.to_rfc3339(),
3216 "model_backed": input.model_backed,
3217 "provider": input.provider,
3218 "billing_surface": input.billing_surface,
3219 "model": input.model.or(input.context.model.as_deref()),
3220 "turn_id": input.turn_id,
3221 "status": input.status,
3222 "error": bounded_error,
3223 "duration_ms": duration_ms_saturating(input.duration),
3224 "usage": {
3225 "input_tokens": input.usage.input_tokens,
3226 "output_tokens": input.usage.output_tokens,
3227 "prompt_cache_hit_tokens": input.usage.prompt_cache_hit_tokens,
3228 "prompt_cache_miss_tokens": input.usage.prompt_cache_miss_tokens,
3229 "prompt_cache_write_tokens": input.usage.prompt_cache_write_tokens,
3230 "reasoning_tokens": input.usage.reasoning_tokens,
3231 "reasoning_replay_tokens": input.usage.reasoning_replay_tokens,
3232 },
3233 "totals": {
3234 "session_tokens": input.totals.session_tokens,
3235 "conversation_tokens": input.totals.conversation_tokens,
3236 "input_tokens": input.totals.input_tokens,
3237 "output_tokens": input.totals.output_tokens,
3238 },
3239 "tool_count": input.tool_count,
3240 "queued_message_count": input.queued_message_count,
3241 "stop_hook_active": false,
3242 })
3243 }
3244
3245 #[cfg(test)]
3246 pub fn pre_compact_payload(
3247 context: &HookContext,
3248 trigger: &str,
3249 message_count: usize,
3250 token_count: u32,
3251 ) -> serde_json::Value {
3252 json!({
3253 "event": HookEvent::PreCompact.as_str(),
3254 "trigger": trigger,
3255 "message_count": message_count,
3256 "token_count": token_count,
3257 "session_id": context.session_id.as_deref(),
3258 "workspace": context.workspace.as_ref().map(|path| path.display().to_string()),
3259 "mode": context.mode.as_deref(),
3260 "model": context.model.as_deref(),
3261 "total_tokens": context.total_tokens,
3262 })
3263 }
3264
3265 fn duration_ms_saturating(duration: Duration) -> u64 {
3266 u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)
3267 }
3268
3269 fn parse_message_submit_stdout(stdout: &str) -> MessageSubmitStdout {
3270 let trimmed = stdout.trim();
3271 if trimmed.is_empty() {
3272 return MessageSubmitStdout::Unchanged;
3273 }
3274
3275 let value: serde_json::Value = match serde_json::from_str(trimmed) {
3276 Ok(value) => value,
3277 Err(e) => return MessageSubmitStdout::Invalid(format!("invalid JSON: {e}")),
3278 };
3279
3280 let Some(object) = value.as_object() else {
3281 return MessageSubmitStdout::Invalid("stdout JSON must be an object".to_string());
3282 };
3283
3284 if object.get("block").and_then(serde_json::Value::as_bool) == Some(true) {
3285 let reason = object
3286 .get("reason")
3287 .and_then(serde_json::Value::as_str)
3288 .unwrap_or("message_submit hook blocked submission");
3289 return MessageSubmitStdout::Blocked(sanitize_hook_denial_reason(reason));
3290 }
3291 match object.get("text") {
3292 Some(serde_json::Value::String(text)) if !text.is_empty() => {
3293 if text.chars().count() > HOOK_MESSAGE_REPLACEMENT_MAX_CHARS {
3294 MessageSubmitStdout::Invalid(format!(
3295 "stdout `text` field exceeds {HOOK_MESSAGE_REPLACEMENT_MAX_CHARS} characters"
3296 ))
3297 } else {
3298 MessageSubmitStdout::Replaced(text.clone())
3299 }
3300 }
3301 Some(serde_json::Value::String(_)) => {
3302 MessageSubmitStdout::Invalid("stdout `text` field must not be empty".to_string())
3303 }
3304 Some(_) => MessageSubmitStdout::Invalid("stdout `text` field must be a string".to_string()),
3305 None => MessageSubmitStdout::Unchanged,
3306 }
3307 }
3308
3309 fn message_submit_continue_warning(result: &HookResult) -> Option<String> {
3310 message_submit_stdout_reason(&result.stdout)
3311 .or_else(|| {
3312 Some(generic_unavailable_detail(result.error.as_deref()))
3313 .filter(|detail| detail != "hook returned no verdict")
3314 })
3315 .or_else(|| {
3316 result
3317 .observed_exit_code()
3318 .map(|code| format!("message_submit hook exited with code {code}"))
3319 })
3320 }
3321
3322 fn message_submit_block_reason(result: &HookResult, fallback: &str) -> String {
3323 if let Some(reason) = message_submit_stdout_reason(&result.stdout) {
3324 return reason;
3325 }
3326 let detail = generic_unavailable_detail(result.error.as_deref());
3327 if detail != "hook returned no verdict" {
3328 return detail;
3329 }
3330 fallback.to_string()
3331 }
3332
3333 fn message_submit_stdout_reason(stdout: &str) -> Option<String> {
3334 let value: serde_json::Value = serde_json::from_str(stdout.trim()).ok()?;
3335 value
3336 .get("reason")
3337 .and_then(serde_json::Value::as_str)
3338 .map(sanitize_hook_denial_reason)
3339 }
3340
3341 /// Largest single `shell_env` value that is accepted, in bytes.
3342 const SHELL_ENV_VALUE_MAX_BYTES: usize = 32 * 1024;
3343 /// Largest total `shell_env` contribution from one hook, in bytes of
3344 /// `KEY` + `VALUE`. Past this, later entries from that hook are dropped.
3345 const SHELL_ENV_TOTAL_MAX_BYTES: usize = 256 * 1024;
3346
3347 /// Whether a parsed name is usable as an environment variable name.
3348 ///
3349 /// `Command::env` **panics** on a key containing a NUL byte or `=`, and an
3350 /// empty key is meaningless, so an entry that fails this check is dropped
3351 /// rather than carried into `exec_shell`'s environment. A `shell_env` hook is
3352 /// a normal process whose stdout can contain anything — including a NUL
3353 /// straight out of a binary — and "the hook printed something odd" must never
3354 /// become "Codewhale aborted the tool call".
3355 fn is_valid_env_key(key: &str) -> bool {
3356 !key.is_empty()
3357 && !key.contains('=')
3358 && !key.chars().any(|c| c == '\0' || c.is_control() || c == ' ')
3359 }
3360
3361 /// Parse `KEY=VALUE\n` lines from a `shell_env` hook's stdout into a map.
3362 ///
3363 /// Tolerated: blank lines, leading whitespace, `#` comment lines (ignored),
3364 /// `export KEY=VALUE` (the `export ` prefix is dropped), surrounding quotes
3365 /// on the value. Lines without `=` are silently dropped — easier than
3366 /// failing the whole hook for one stray line of human-friendly output.
3367 /// Values are otherwise taken verbatim; we don't run them through a shell
3368 /// for variable expansion to avoid surprises.
3369 ///
3370 /// Rejected: entries whose key is unusable ([`is_valid_env_key`]), values
3371 /// containing a NUL byte, values over [`SHELL_ENV_VALUE_MAX_BYTES`], and
3372 /// anything past [`SHELL_ENV_TOTAL_MAX_BYTES`] of accumulated output. Each
3373 /// drop is logged by key name only — never by value.
3374 fn parse_env_lines(stdout: &str) -> HashMap<String, String> {
3375 let mut out: HashMap<String, String> = HashMap::new();
3376 let mut total_bytes = 0usize;
3377 for raw in stdout.lines() {
3378 let line = raw.trim();
3379 if line.is_empty() || line.starts_with('#') {
3380 continue;
3381 }
3382 let line = line.strip_prefix("export ").unwrap_or(line);
3383 let Some((key, value)) = line.split_once('=') else {
3384 continue;
3385 };
3386 let key = key.trim();
3387 if !is_valid_env_key(key) {
3388 tracing::warn!(
3389 target: "hooks",
3390 "shell_env hook produced an unusable variable name; dropping the entry"
3391 );
3392 continue;
3393 }
3394 let value = value.trim();
3395 let stripped = value
3396 .strip_prefix('"')
3397 .and_then(|v| v.strip_suffix('"'))
3398 .or_else(|| value.strip_prefix('\'').and_then(|v| v.strip_suffix('\'')))
3399 .unwrap_or(value);
3400 if stripped.contains('\0') {
3401 tracing::warn!(
3402 target: "hooks",
3403 key,
3404 "shell_env value contains a NUL byte; dropping the entry"
3405 );
3406 continue;
3407 }
3408 if stripped.len() > SHELL_ENV_VALUE_MAX_BYTES {
3409 tracing::warn!(
3410 target: "hooks",
3411 key,
3412 limit = SHELL_ENV_VALUE_MAX_BYTES,
3413 "shell_env value exceeds the per-value limit; dropping the entry"
3414 );
3415 continue;
3416 }
3417 let entry_bytes = key.len() + stripped.len();
3418 if total_bytes.saturating_add(entry_bytes) > SHELL_ENV_TOTAL_MAX_BYTES {
3419 tracing::warn!(
3420 target: "hooks",
3421 key,
3422 limit = SHELL_ENV_TOTAL_MAX_BYTES,
3423 "shell_env output exceeds the total limit; dropping the remaining entries"
3424 );
3425 break;
3426 }
3427 total_bytes += entry_bytes;
3428 out.insert(key.to_string(), stripped.to_string());
3429 }
3430 out
3431 }
3432
3433 /// Metadata a settled tool call reported, whether it succeeded or failed.
3434 ///
3435 /// `bash` reports a nonzero exit, timeout, or kill as an error, so the error
3436 /// carries the metadata then; reading only `Ok` results lost the exit code of
3437 /// every failing command.
3438 fn reported_tool_metadata(
3439 result: &Result<crate::tools::spec::ToolResult, crate::tools::spec::ToolError>,
3440 ) -> Option<&serde_json::Value> {
3441 match result {
3442 Ok(output) => output.metadata.as_ref(),
3443 Err(error) => error.metadata(),
3444 }
3445 }
3446
3447 /// Read how a process-backed tool ended, for `DEEPSEEK_TOOL_STATUS`.
3448 ///
3449 /// Only the shell statuses the tools record count; anything else stays `None`
3450 /// rather than passing an arbitrary metadata string into a hook's environment.
3451 fn reported_tool_status(
3452 result: &Result<crate::tools::spec::ToolResult, crate::tools::spec::ToolError>,
3453 ) -> Option<&'static str> {
3454 match reported_tool_metadata(result)?.get("status")?.as_str()? {
3455 "Completed" => Some("completed"),
3456 "Failed" => Some("failed"),
3457 "TimedOut" => Some("timed_out"),
3458 "Killed" => Some("killed"),
3459 "Running" => Some("running"),
3460 _ => None,
3461 }
3462 }
3463
3464 /// Read the post-admission execution receipt a shell tool recorded (#6689),
3465 /// serialized for `DEEPSEEK_TOOL_EXECUTION_RECEIPT`.
3466 ///
3467 /// Only a schema-1 object within the size bound counts. The receipt is built
3468 /// by the shell tool from what its process manager recorded at spawn; it is
3469 /// never reconstructed here from the before-hook input, which can differ from
3470 /// what actually ran.
3471 fn reported_tool_execution_receipt(
3472 result: &Result<crate::tools::spec::ToolResult, crate::tools::spec::ToolError>,
3473 ) -> Option<String> {
3474 let receipt = reported_tool_metadata(result)?.get("execution_receipt")?;
3475 if receipt.get("schema_version")?.as_u64()? != 1 {
3476 return None;
3477 }
3478 let encoded = serde_json::to_string(receipt).ok()?;
3479 (encoded.len() <= HOOK_EXECUTION_RECEIPT_MAX_BYTES).then_some(encoded)
3480 }
3481
3482 /// Read the process exit code a tool reported, when it reported one.
3483 ///
3484 /// The one source for `DEEPSEEK_TOOL_EXIT_CODE`: the TUI and the Runtime API
3485 /// thread path both reach it through [`HookContext::with_tool_outcome`].
3486 ///
3487 /// Only process-backed tools (`exec_shell`, `bash`, task runners) carry one,
3488 /// on a successful result or a failed one, and only a real, integer-valued
3489 /// `exit_code` counts. Everything else stays `None` so
3490 /// an `exit_code` condition never matches on a fabricated value.
3491 /// Reported as `i64`, not `i32`: a Windows crash code such as `3221225477`
3492 /// (`0xC0000005`) is a real value the shell tool records in its metadata, and
3493 /// narrowing it dropped exactly those codes — the hook saw no exit code at all
3494 /// for the crashes it most wanted to catch.
3495 fn reported_tool_exit_code(
3496 result: &Result<crate::tools::spec::ToolResult, crate::tools::spec::ToolError>,
3497 ) -> Option<i64> {
3498 let code = reported_tool_metadata(result)?.get("exit_code")?;
3499 if code.is_null() {
3500 return None;
3501 }
3502 code.as_i64()
3503 }
3504
3505 // === Unit Tests ===
3506
3507 #[cfg(test)]
3508 mod tests {
3509 use super::*;
3510 use crate::test_support::{EnvVarGuard, lock_test_env};
3511 use std::collections::HashMap;
3512 use std::path::{Path, PathBuf};
3513
3514 fn trust_workspace_for_project_hooks(workspace: &Path, config_path: &Path) -> EnvVarGuard {
3515 let guard = EnvVarGuard::set("CODEWHALE_CONFIG_PATH", config_path);
3516 codewhale_runtime::config::save_workspace_trust(workspace).expect("save workspace trust");
3517 guard
3518 }
3519
3520 /// #455 — `exit_code` conditions must only ever see a real, reported exit
3521 /// code. `tool_call_after` used to hard-code `None`, which made every
3522 /// `{ type = "exit_code" }` condition permanently unmatchable.
3523 #[test]
3524 fn reported_tool_exit_code_reads_only_real_metadata_codes() {
3525 use crate::tools::spec::{ToolError, ToolResult};
3526
3527 let with_code = Ok(ToolResult {
3528 content: "boom".to_string(),
3529 success: false,
3530 metadata: Some(serde_json::json!({ "exit_code": 127 })),
3531 });
3532 assert_eq!(reported_tool_exit_code(&with_code), Some(127));
3533
3534 // Zero is a real code, not a missing one.
3535 let zero = Ok(ToolResult {
3536 content: "ok".to_string(),
3537 success: true,
3538 metadata: Some(serde_json::json!({ "exit_code": 0 })),
3539 });
3540 assert_eq!(reported_tool_exit_code(&zero), Some(0));
3541
3542 // Tools that report no exit code stay `None` — never synthesized from
3543 // the success flag.
3544 let no_metadata = Ok(ToolResult::error("failed"));
3545 assert_eq!(reported_tool_exit_code(&no_metadata), None);
3546
3547 let null_code = Ok(ToolResult {
3548 content: String::new(),
3549 success: true,
3550 metadata: Some(serde_json::json!({ "exit_code": serde_json::Value::Null })),
3551 });
3552 assert_eq!(reported_tool_exit_code(&null_code), None);
3553
3554 let wrong_type = Ok(ToolResult {
3555 content: String::new(),
3556 success: false,
3557 metadata: Some(serde_json::json!({ "exit_code": "127" })),
3558 });
3559 assert_eq!(reported_tool_exit_code(&wrong_type), None);
3560
3561 // A Windows crash code does not fit in an `i32`, but it is a real code
3562 // and a hook scoped to it must be able to see it.
3563 let windows_crash = Ok(ToolResult {
3564 content: String::new(),
3565 success: false,
3566 metadata: Some(serde_json::json!({ "exit_code": 3_221_225_477_i64 })),
3567 });
3568 assert_eq!(reported_tool_exit_code(&windows_crash), Some(3_221_225_477));
3569
3570 // A transport-level tool error has no metadata at all.
3571 let errored: Result<ToolResult, ToolError> =
3572 Err(ToolError::execution_failed("no such tool"));
3573 assert_eq!(reported_tool_exit_code(&errored), None);
3574 assert_eq!(reported_tool_status(&errored), None);
3575
3576 // A failed command reported as an error still carries its code and
3577 // status.
3578 let failed_command: Result<ToolResult, ToolError> =
3579 Err(ToolError::execution_failed_with_metadata(
3580 "Command exited with code 127",
3581 serde_json::json!({ "exit_code": 127, "status": "Failed" }),
3582 ));
3583 assert_eq!(reported_tool_exit_code(&failed_command), Some(127));
3584 assert_eq!(reported_tool_status(&failed_command), Some("failed"));
3585
3586 // A timeout has a status but no exit code; the code is not invented.
3587 let timed_out: Result<ToolResult, ToolError> =
3588 Err(ToolError::execution_failed_with_metadata(
3589 "Command timed out after 1 seconds",
3590 serde_json::json!({ "exit_code": null, "status": "TimedOut" }),
3591 ));
3592 assert_eq!(reported_tool_exit_code(&timed_out), None);
3593 assert_eq!(reported_tool_status(&timed_out), Some("timed_out"));
3594
3595 // An unknown status string is not passed through.
3596 let odd_status = Ok(ToolResult {
3597 content: String::new(),
3598 success: true,
3599 metadata: Some(serde_json::json!({ "status": "$(boom)" })),
3600 });
3601 assert_eq!(reported_tool_status(&odd_status), None);
3602 }
3603
3604 #[test]
3605 fn config_types_are_available_from_config_module() {
3606 let hook = codewhale_config::hooks::Hook::new(
3607 codewhale_config::hooks::HookEvent::SessionStart,
3608 "echo ready",
3609 );
3610 let config = codewhale_config::hooks::HooksConfig {
3611 enabled: true,
3612 hooks: vec![hook],
3613 ..Default::default()
3614 };
3615
3616 let hooks = config.hooks_for_event(codewhale_config::hooks::HookEvent::SessionStart);
3617
3618 assert_eq!(hooks.len(), 1);
3619 }
3620
3621 #[cfg(unix)]
3622 #[test]
3623 fn plugin_hook_runs_after_restart_and_process_spawn_rechecks_revocation() {
3624 let _lock = lock_test_env();
3625 let fixture = codewhale_plugins::test_fixture::DeclarativePluginFixture::new();
3626 let config = crate::hooks::config::load_with_project_and_plugins(
3627 HooksConfig {
3628 enabled: true,
3629 ..HooksConfig::default()
3630 },
3631 &fixture.workspace,
3632 Some(&fixture.registry),
3633 );
3634 assert!(config.problems.is_empty(), "{:?}", config.problems);
3635 assert_eq!(config.hooks.len(), 1);
3636 assert!(config.hooks[0].plugin_authority.is_some());
3637 let executor = HookExecutor::new(config, fixture.workspace.clone());
3638 let context = HookContext::new().with_workspace(fixture.workspace.clone());
3639
3640 let ran = executor.execute(HookEvent::SessionStart, &context);
3641 assert_eq!(ran.len(), 1);
3642 assert!(ran[0].success, "{:?}", ran[0].error);
3643 assert_eq!(
3644 std::fs::read_to_string(&fixture.marker).expect("plugin hook marker"),
3645 "plugin-hook-ran"
3646 );
3647 std::fs::remove_file(&fixture.marker).expect("clear marker");
3648
3649 let inactive = fixture.revoke_from_fresh_registry();
3650 let denied = executor.execute(HookEvent::SessionStart, &context);
3651 assert_eq!(denied.len(), 1);
3652 assert!(!denied[0].success);
3653 assert!(
3654 denied[0]
3655 .error
3656 .as_deref()
3657 .is_some_and(|error| error.contains("authority was denied")),
3658 "{:?}",
3659 denied[0].error
3660 );
3661 assert!(
3662 !fixture.marker.exists(),
3663 "revoked hook must be denied before process spawn"
3664 );
3665
3666 let reloaded = crate::hooks::config::load_with_project_and_plugins(
3667 HooksConfig {
3668 enabled: true,
3669 ..HooksConfig::default()
3670 },
3671 &fixture.workspace,
3672 Some(&inactive),
3673 );
3674 assert!(
3675 reloaded.hooks.is_empty(),
3676 "reload removes the revoked plugin Hook"
3677 );
3678 }
3679
3680 #[cfg(unix)]
3681 #[test]
3682 fn queued_plugin_hook_rechecks_revocation_at_dequeue() {
3683 let _lock = lock_test_env();
3684 let fixture = codewhale_plugins::test_fixture::DeclarativePluginFixture::new();
3685 let blocker_one = Hook::new(HookEvent::SessionStart, "sleep 1").background();
3686 let blocker_two = Hook::new(HookEvent::SessionStart, "sleep 1").background();
3687 let mut config = crate::hooks::config::load_with_project_and_plugins(
3688 HooksConfig {
3689 enabled: true,
3690 hooks: vec![blocker_one, blocker_two],
3691 ..HooksConfig::default()
3692 },
3693 &fixture.workspace,
3694 Some(&fixture.registry),
3695 );
3696 assert_eq!(config.hooks.len(), 3);
3697 config.hooks[2].background = true;
3698 let executor = HookExecutor::new(config, fixture.workspace.clone());
3699
3700 let submitted = executor.execute(
3701 HookEvent::SessionStart,
3702 &HookContext::new().with_workspace(fixture.workspace.clone()),
3703 );
3704 assert_eq!(submitted.len(), 3);
3705 assert!(submitted.iter().all(|result| result.background));
3706 fixture.revoke_from_fresh_registry();
3707
3708 std::thread::sleep(Duration::from_millis(1_500));
3709 assert!(
3710 !fixture.marker.exists(),
3711 "queued hook must recheck authority after the preceding job finishes"
3712 );
3713 }
3714
3715 #[test]
3716 fn executor_type_is_available_from_executor_module() {
3717 let executor = crate::hooks::executor::HookExecutor::disabled();
3718
3719 assert!(!executor.is_enabled());
3720 }
3721
3722 /// #456 — `parse_env_lines` covers the formats users actually emit from
3723 /// shell hooks: bare `KEY=VAL`, `export KEY=VAL`, quoted values, comments,
3724 /// blank lines. Lines without `=` are dropped; values are taken verbatim
3725 /// (no shell expansion).
3726 #[test]
3727 fn parse_env_lines_handles_realistic_hook_output() {
3728 let stdout = r#"
3729 # Aux comment line, ignored
3730 AWS_ACCESS_KEY_ID=AKIAEXAMPLE
3731 export GITHUB_TOKEN=ghp_examplevalue
3732 QUOTED="value with spaces"
3733 SINGLE='also valid'
3734
3735 = empty key dropped
3736 NOEQUAL line dropped
3737 "#;
3738 let parsed = super::parse_env_lines(stdout);
3739 assert_eq!(
3740 parsed.get("AWS_ACCESS_KEY_ID"),
3741 Some(&"AKIAEXAMPLE".to_string())
3742 );
3743 assert_eq!(
3744 parsed.get("GITHUB_TOKEN"),
3745 Some(&"ghp_examplevalue".to_string())
3746 );
3747 assert_eq!(parsed.get("QUOTED"), Some(&"value with spaces".to_string()));
3748 assert_eq!(parsed.get("SINGLE"), Some(&"also valid".to_string()));
3749 assert!(!parsed.contains_key(""));
3750 assert!(!parsed.contains_key("NOEQUAL line dropped"));
3751 // 4 valid entries above; nothing else.
3752 assert_eq!(parsed.len(), 4);
3753 }
3754
3755 /// #456 — empty stdout (or only blank/comments) yields an empty map.
3756 #[test]
3757 fn parse_env_lines_empty_when_no_assignments() {
3758 let parsed = super::parse_env_lines("# nothing\n\n \n");
3759 assert!(parsed.is_empty());
3760 }
3761
3762 #[test]
3763 fn parse_message_submit_stdout_replaces_text() {
3764 assert_eq!(
3765 super::parse_message_submit_stdout(r#"{"text":"changed"}"#),
3766 MessageSubmitStdout::Replaced("changed".to_string())
3767 );
3768 }
3769
3770 #[test]
3771 fn parse_message_submit_stdout_empty_is_unchanged() {
3772 assert_eq!(
3773 super::parse_message_submit_stdout(" \n\t "),
3774 MessageSubmitStdout::Unchanged
3775 );
3776 }
3777
3778 #[test]
3779 fn parse_message_submit_stdout_without_text_is_unchanged() {
3780 assert_eq!(
3781 super::parse_message_submit_stdout(r#"{"reason":"only used for blocks"}"#),
3782 MessageSubmitStdout::Unchanged
3783 );
3784 }
3785
3786 #[test]
3787 fn message_submit_payload_is_byte_bounded_after_json_escaping() {
3788 let original = "用户\"\\\n".repeat(20_000);
3789 let payload = super::message_submit_payload(
3790 &HookContext::new()
3791 .with_session_id("sess_test")
3792 .with_model("model"),
3793 &original,
3794 );
3795 let encoded = serde_json::to_vec(&payload).expect("serialize bounded payload");
3796
3797 assert!(
3798 encoded.len() <= super::HOOK_MESSAGE_SUBMIT_PAYLOAD_MAX_BYTES,
3799 "serialized payload was {} bytes",
3800 encoded.len()
3801 );
3802 assert_eq!(payload["text_truncated"], true);
3803 assert_eq!(payload["text_original_bytes"], original.len());
3804 let retained = payload["text"].as_str().expect("text string");
3805 assert_eq!(payload["text_bytes"], retained.len());
3806 assert!(original.starts_with(retained));
3807 assert!(std::str::from_utf8(retained.as_bytes()).is_ok());
3808 }
3809
3810 #[test]
3811 fn message_submit_payload_omits_hostile_diagnostics_before_exceeding_cap() {
3812 let hostile = "\u{0}\u{1}\u{1f}\"\\".repeat(8_000);
3813 let original = "\u{0}\"\\用户".repeat(20_000);
3814 let context = HookContext::new()
3815 .with_session_id(&hostile)
3816 .with_workspace(PathBuf::from(&hostile))
3817 .with_mode(&hostile)
3818 .with_model(&hostile);
3819 let payload = super::message_submit_payload(&context, &original);
3820 let encoded = serde_json::to_vec(&payload).expect("serialize hostile payload");
3821
3822 assert!(
3823 encoded.len() <= super::HOOK_MESSAGE_SUBMIT_PAYLOAD_MAX_BYTES,
3824 "serialized payload was {} bytes",
3825 encoded.len()
3826 );
3827 assert_eq!(payload["text_truncated"], true);
3828 assert_eq!(payload["text_original_bytes"], original.len());
3829 assert!(original.starts_with(payload["text"].as_str().expect("text")));
3830
3831 for key in ["session_id", "workspace", "mode", "model"] {
3832 if let Some(value) = payload.get(key).and_then(serde_json::Value::as_str) {
3833 assert!(
3834 value.len() <= super::HOOK_MESSAGE_SUBMIT_METADATA_MAX_BYTES + 16,
3835 "{key} was not bounded before serialization"
3836 );
3837 }
3838 }
3839 }
3840
3841 #[test]
3842 fn short_message_submit_payload_carries_explicit_untruncated_metadata() {
3843 let payload = super::message_submit_payload(&HookContext::new(), "hello 用户");
3844 assert_eq!(payload["text"], "hello 用户");
3845 assert_eq!(payload["text_bytes"], "hello 用户".len());
3846 assert_eq!(payload["text_original_bytes"], "hello 用户".len());
3847 assert_eq!(payload["text_truncated"], false);
3848 }
3849
3850 #[test]
3851 fn parse_message_submit_stdout_rejects_malformed_json() {
3852 assert!(matches!(
3853 super::parse_message_submit_stdout("not json"),
3854 MessageSubmitStdout::Invalid(_)
3855 ));
3856 }
3857
3858 #[test]
3859 fn parse_message_submit_stdout_rejects_non_string_text() {
3860 assert!(matches!(
3861 super::parse_message_submit_stdout(r#"{"text":123}"#),
3862 MessageSubmitStdout::Invalid(_)
3863 ));
3864 }
3865
3866 #[test]
3867 fn parse_message_submit_stdout_rejects_empty_text() {
3868 assert_eq!(
3869 super::parse_message_submit_stdout(r#"{"text":""}"#),
3870 MessageSubmitStdout::Invalid("stdout `text` field must not be empty".to_string())
3871 );
3872 }
3873
3874 #[test]
3875 fn parse_message_submit_stdout_rejects_non_object_json() {
3876 assert!(matches!(
3877 super::parse_message_submit_stdout(r#"["not", "an", "object"]"#),
3878 MessageSubmitStdout::Invalid(_)
3879 ));
3880 assert!(matches!(
3881 super::parse_message_submit_stdout(r#""not an object""#),
3882 MessageSubmitStdout::Invalid(_)
3883 ));
3884 }
3885
3886 #[test]
3887 fn test_hook_event_as_str() {
3888 assert_eq!(HookEvent::SessionStart.as_str(), "session_start");
3889 assert_eq!(HookEvent::ToolCallAfter.as_str(), "tool_call_after");
3890 assert_eq!(HookEvent::ModeChange.as_str(), "mode_change");
3891 assert_eq!(HookEvent::TurnEnd.as_str(), "turn_end");
3892 assert_eq!(HookEvent::SubagentSpawn.as_str(), "subagent_spawn");
3893 assert_eq!(HookEvent::SubagentComplete.as_str(), "subagent_complete");
3894 assert_eq!(HookEvent::PreCompact.as_str(), "pre_compact");
3895 }
3896
3897 #[test]
3898 fn pre_compact_payload_carries_observer_fields() {
3899 let context = HookContext::new()
3900 .with_session_id("sess_compact")
3901 .with_workspace(PathBuf::from("/tmp/codewhale"))
3902 .with_mode("ACT")
3903 .with_model("deepseek-chat")
3904 .with_tokens(4096);
3905 let payload = super::pre_compact_payload(&context, "auto", 42, 4096);
3906 assert_eq!(payload["event"], "pre_compact");
3907 assert_eq!(payload["trigger"], "auto");
3908 assert_eq!(payload["message_count"], 42);
3909 assert_eq!(payload["token_count"], 4096);
3910 assert_eq!(payload["session_id"], "sess_compact");
3911 assert_eq!(payload["mode"], "ACT");
3912 assert_eq!(payload["model"], "deepseek-chat");
3913 }
3914
3915 #[test]
3916 fn turn_end_payload_contains_post_turn_observer_fields() {
3917 let context = HookContext::new()
3918 .with_session_id("sess_test")
3919 .with_workspace(PathBuf::from("/tmp/codewhale"))
3920 .with_mode("agent")
3921 .with_model("deepseek-v4")
3922 .with_tokens(125);
3923 let usage = codewhale_models::Usage {
3924 input_tokens: 40,
3925 output_tokens: 9,
3926 prompt_cache_hit_tokens: Some(10),
3927 prompt_cache_miss_tokens: Some(30),
3928 prompt_cache_write_tokens: None,
3929 reasoning_tokens: Some(4),
3930 reasoning_replay_tokens: Some(2),
3931 server_tool_use: None,
3932
3933 input_audio_tokens: None,
3934 output_audio_tokens: None,
3935
3936 request_usages: Vec::new(),
3937 safety_tokens: None,
3938 };
3939
3940 let payload = super::turn_end_payload(TurnEndPayloadInput {
3941 context: &context,
3942 created_at: "2026-07-12T10:30:00Z".parse().expect("timestamp"),
3943 model_backed: true,
3944 provider: Some("deepseek"),
3945 billing_surface: Some("test-payg"),
3946 model: Some("deepseek-v4-pro"),
3947 turn_id: "turn_123",
3948 status: "completed",
3949 error: None,
3950 duration: Duration::from_millis(321),
3951 usage: &usage,
3952 totals: TurnEndTotals {
3953 session_tokens: 125,
3954 conversation_tokens: 100,
3955 input_tokens: 100,
3956 output_tokens: 25,
3957 },
3958 tool_count: 2,
3959 queued_message_count: 1,
3960 });
3961
3962 assert_eq!(payload["event"], "turn_end");
3963 assert_eq!(payload["session_id"], "sess_test");
3964 assert_eq!(payload["workspace"], "/tmp/codewhale");
3965 assert_eq!(payload["mode"], "agent");
3966 assert_eq!(payload["created_at"], "2026-07-12T10:30:00+00:00");
3967 assert_eq!(payload["model_backed"], true);
3968 assert_eq!(payload["provider"], "deepseek");
3969 assert_eq!(payload["billing_surface"], "test-payg");
3970 assert!(payload.get("base_url").is_none());
3971 assert_eq!(payload["model"], "deepseek-v4-pro");
3972 assert_eq!(payload["turn_id"], "turn_123");
3973 assert_eq!(payload["status"], "completed");
3974 assert_eq!(payload["error"], serde_json::Value::Null);
3975 assert_eq!(payload["duration_ms"], 321);
3976 assert_eq!(payload["usage"]["input_tokens"], 40);
3977 assert_eq!(payload["usage"]["output_tokens"], 9);
3978 assert_eq!(payload["usage"]["prompt_cache_hit_tokens"], 10);
3979 assert_eq!(payload["usage"]["prompt_cache_miss_tokens"], 30);
3980 assert_eq!(payload["usage"]["reasoning_tokens"], 4);
3981 assert_eq!(payload["usage"]["reasoning_replay_tokens"], 2);
3982 assert_eq!(payload["totals"]["session_tokens"], 125);
3983 assert_eq!(payload["totals"]["conversation_tokens"], 100);
3984 assert_eq!(payload["totals"]["input_tokens"], 100);
3985 assert_eq!(payload["totals"]["output_tokens"], 25);
3986 assert_eq!(payload["tool_count"], 2);
3987 assert_eq!(payload["queued_message_count"], 1);
3988 assert_eq!(payload["stop_hook_active"], false);
3989 }
3990
3991 #[test]
3992 fn test_hook_context_to_env_vars() {
3993 let ctx = HookContext::new()
3994 .with_tool_name("exec_shell")
3995 .with_mode("agent")
3996 .with_workspace(PathBuf::from("/tmp"));
3997
3998 let env = ctx.to_env_vars();
3999
4000 assert_eq!(
4001 env.get("DEEPSEEK_TOOL_NAME"),
4002 Some(&"exec_shell".to_string())
4003 );
4004 assert_eq!(env.get("DEEPSEEK_MODE"), Some(&"agent".to_string()));
4005 assert_eq!(env.get("DEEPSEEK_WORKSPACE"), Some(&"/tmp".to_string()));
4006 }
4007
4008 #[test]
4009 fn test_hook_condition_always() {
4010 let hook = Hook::new(HookEvent::SessionStart, "echo test");
4011 let executor = HookExecutor::disabled();
4012 let context = HookContext::new();
4013
4014 assert!(executor.matches_condition(&hook, &context));
4015 }
4016
4017 #[test]
4018 fn test_hook_condition_tool_name() {
4019 let hook = Hook::new(HookEvent::ToolCallBefore, "echo test").with_condition(
4020 HookCondition::ToolName {
4021 name: "exec_shell".to_string(),
4022 },
4023 );
4024
4025 let executor = HookExecutor::disabled();
4026
4027 let context_match = HookContext::new().with_tool_name("exec_shell");
4028 let context_no_match = HookContext::new().with_tool_name("write_file");
4029
4030 assert!(executor.matches_condition(&hook, &context_match));
4031 assert!(!executor.matches_condition(&hook, &context_no_match));
4032 }
4033
4034 #[test]
4035 fn test_hook_condition_mode() {
4036 let hook =
4037 Hook::new(HookEvent::ModeChange, "echo test").with_condition(HookCondition::Mode {
4038 mode: "agent".to_string(),
4039 });
4040
4041 let executor = HookExecutor::disabled();
4042
4043 let context_match = HookContext::new().with_mode("AGENT"); // Case insensitive
4044 let context_no_match = HookContext::new().with_mode("normal");
4045
4046 assert!(executor.matches_condition(&hook, &context_match));
4047 assert!(!executor.matches_condition(&hook, &context_no_match));
4048 }
4049
4050 #[test]
4051 fn test_hooks_config_for_event() {
4052 let config = HooksConfig {
4053 enabled: true,
4054 hooks: vec![
4055 Hook::new(HookEvent::SessionStart, "echo start"),
4056 Hook::new(HookEvent::SessionEnd, "echo end"),
4057 Hook::new(HookEvent::SessionStart, "echo start2"),
4058 ],
4059 ..Default::default()
4060 };
4061
4062 let start_hooks = config.hooks_for_event(HookEvent::SessionStart);
4063 assert_eq!(start_hooks.len(), 2);
4064
4065 let end_hooks = config.hooks_for_event(HookEvent::SessionEnd);
4066 assert_eq!(end_hooks.len(), 1);
4067 }
4068
4069 #[test]
4070 fn test_hooks_config_disabled() {
4071 let config = HooksConfig {
4072 enabled: false,
4073 hooks: vec![Hook::new(HookEvent::SessionStart, "echo start")],
4074 ..Default::default()
4075 };
4076
4077 let hooks = config.hooks_for_event(HookEvent::SessionStart);
4078 assert!(hooks.is_empty());
4079 }
4080
4081 #[test]
4082 fn test_hook_builder() {
4083 let hook = Hook::new(HookEvent::ToolCallAfter, "notify.sh")
4084 .with_name("notify_tool")
4085 .with_timeout(60)
4086 .background()
4087 .with_condition(HookCondition::ToolCategory {
4088 category: "shell".to_string(),
4089 });
4090
4091 assert_eq!(hook.name, Some("notify_tool".to_string()));
4092 assert_eq!(hook.timeout_secs, 60);
4093 assert!(hook.background);
4094 assert!(matches!(
4095 hook.condition,
4096 Some(HookCondition::ToolCategory { .. })
4097 ));
4098 }
4099
4100 #[test]
4101 fn test_hook_timeout_enforced() {
4102 let command = if cfg!(windows) {
4103 "ping -n 3 127.0.0.1 > nul"
4104 } else {
4105 "sleep 2"
4106 };
4107 let hook = Hook::new(HookEvent::SessionStart, command).with_timeout(1);
4108 let executor = HookExecutor::new(HooksConfig::default(), PathBuf::from("."));
4109 let env_vars = HashMap::new();
4110
4111 let result = executor.execute_sync(&hook, &env_vars);
4112 assert!(!result.success);
4113 assert!(
4114 result
4115 .error
4116 .as_ref()
4117 .is_some_and(|e| e.contains("timed out"))
4118 );
4119 }
4120
4121 #[test]
4122 fn observer_hook_receives_eof_instead_of_inheriting_terminal_stdin() {
4123 const INNER_ENV: &str = "CODEWHALE_TEST_HOOK_EOF_INNER";
4124 const TEST_NAME: &str =
4125 "hooks::tests::observer_hook_receives_eof_instead_of_inheriting_terminal_stdin";
4126
4127 if std::env::var_os(INNER_ENV).is_some() {
4128 let dir = tempfile::tempdir().expect("tempdir");
4129 #[cfg(not(windows))]
4130 let command = write_hook_script(
4131 &dir,
4132 "read_to_eof.sh",
4133 r#"#!/bin/sh
4134 payload=$(cat)
4135 printf 'stdin-bytes=%s\n' "${#payload}"
4136 "#,
4137 );
4138 #[cfg(windows)]
4139 let command = "powershell -NoProfile -Command \"$value = [Console]::In.ReadToEnd(); [Console]::Out.WriteLine(('stdin-bytes=' + $value.Length))\"".to_string();
4140 // A cold PowerShell process can take several seconds to start on a
4141 // contended Windows CI runner. Keep the hook timeout finite so the
4142 // regression still detects an inherited live stdin pipe, while
4143 // allowing enough startup time for the EOF assertion itself.
4144 let hook_timeout_secs = if cfg!(windows) { 10 } else { 2 };
4145 let hook =
4146 Hook::new(HookEvent::ToolCallBefore, &command).with_timeout(hook_timeout_secs);
4147 let executor = HookExecutor::new(HooksConfig::default(), dir.path().to_path_buf());
4148
4149 let result = executor.execute_sync(&hook, &HashMap::new());
4150 assert!(result.success, "stdin-less hook should finish: {result:?}");
4151 assert_eq!(result.stdout.trim(), "stdin-bytes=0");
4152 return;
4153 }
4154
4155 // Keep this subprocess's stdin pipe deliberately open. Before #4489,
4156 // the hook inherited that live pipe and blocked instead of receiving
4157 // EOF. The inner test can only finish when HookExecutor closes the
4158 // child's stdin write end.
4159 let mut child = Command::new(std::env::current_exe().expect("current test binary"))
4160 .args(["--exact", TEST_NAME, "--nocapture", "--test-threads=1"])
4161 .env(INNER_ENV, "1")
4162 .stdin(Stdio::piped())
4163 .spawn()
4164 .expect("spawn isolated hook EOF test");
4165 let held_open_stdin = child.stdin.take().expect("piped child stdin");
4166 // Leave headroom around the inner hook timeout so a cold Windows test
4167 // process can start, without weakening the held-open-pipe regression.
4168 let isolated_timeout_secs = if cfg!(windows) { 25 } else { 10 };
4169 let status = match child
4170 .wait_timeout(Duration::from_secs(isolated_timeout_secs))
4171 .expect("wait for isolated hook EOF test")
4172 {
4173 Some(status) => status,
4174 None => {
4175 let _ = child.kill();
4176 let _ = child.wait();
4177 panic!("isolated hook EOF test hung with parent stdin open");
4178 }
4179 };
4180 drop(held_open_stdin);
4181 assert!(status.success(), "isolated hook EOF test failed: {status}");
4182 }
4183
4184 #[cfg(not(windows))]
4185 #[test]
4186 fn timed_out_hook_kills_descendant_process_group() {
4187 let dir = tempfile::tempdir().expect("tempdir");
4188 let marker = dir.path().join("descendant-survived");
4189 let command = write_hook_script(
4190 &dir,
4191 "spawn_descendant.sh",
4192 &format!(
4193 "#!/bin/sh\n(sleep 2; printf leaked > '{}') &\nsleep 5\n",
4194 marker.display()
4195 ),
4196 );
4197 let hook = Hook::new(HookEvent::ToolCallBefore, &command).with_timeout(1);
4198 let executor = HookExecutor::new(HooksConfig::default(), dir.path().to_path_buf());
4199
4200 let result = executor.execute_sync(&hook, &HashMap::new());
4201 assert!(
4202 result
4203 .error
4204 .as_ref()
4205 .is_some_and(|error| error.contains("timed out")),
4206 "hook should time out: {result:?}"
4207 );
4208 std::thread::sleep(Duration::from_millis(1_500));
4209 assert!(
4210 !marker.exists(),
4211 "the timed-out hook's descendant escaped its process group"
4212 );
4213 }
4214
4215 #[cfg(windows)]
4216 #[test]
4217 fn timed_out_hook_kills_windows_descendant_job() {
4218 let dir = tempfile::tempdir().expect("tempdir");
4219 let started = dir.path().join("descendant-started.txt");
4220 let survived = dir.path().join("descendant-survived.txt");
4221 let descendant = dir.path().join("descendant.cmd");
4222 std::fs::write(
4223 &descendant,
4224 "@echo off\r\necho started>descendant-started.txt\r\nping -n 5 127.0.0.1 > nul\r\necho survived>descendant-survived.txt\r\n",
4225 )
4226 .expect("write descendant script");
4227 let parent = dir.path().join("parent.cmd");
4228 std::fs::write(
4229 &parent,
4230 "@echo off\r\nstart \"\" /b cmd.exe /d /c descendant.cmd\r\n:wait_for_child\r\nif exist descendant-started.txt goto child_started\r\nping -n 2 127.0.0.1 > nul\r\ngoto wait_for_child\r\n:child_started\r\nping -n 10 127.0.0.1 > nul\r\n",
4231 )
4232 .expect("write parent script");
4233 let hook = Hook::new(HookEvent::ToolCallBefore, "call parent.cmd").with_timeout(3);
4234 let executor = HookExecutor::new(HooksConfig::default(), dir.path().to_path_buf());
4235
4236 let result = executor.execute_sync(&hook, &HashMap::new());
4237 assert!(
4238 result
4239 .error
4240 .as_ref()
4241 .is_some_and(|error| error.contains("timed out")),
4242 "hook should time out: {result:?}"
4243 );
4244 assert!(
4245 started.exists(),
4246 "descendant never reached its start handshake"
4247 );
4248 std::thread::sleep(Duration::from_secs(5));
4249 assert!(
4250 !survived.exists(),
4251 "the timed-out hook's descendant escaped its Job Object"
4252 );
4253 }
4254
4255 #[cfg(not(windows))]
4256 #[test]
4257 fn message_submit_stdin_write_does_not_deadlock_when_hook_writes_first() {
4258 let dir = tempfile::tempdir().expect("tempdir");
4259 let command = write_hook_script(
4260 &dir,
4261 "write_before_read.sh",
4262 r#"#!/bin/sh
4263 dd if=/dev/zero bs=1024 count=256 2>/dev/null | tr '\000' x
4264 dd if=/dev/zero bs=1024 count=256 2>/dev/null | tr '\000' e >&2
4265 payload=$(cat)
4266 printf '\ndone:%s\n' "${#payload}"
4267 "#,
4268 );
4269 let hook = Hook::new(HookEvent::MessageSubmit, &command).with_timeout(5);
4270 let executor = HookExecutor::new(HooksConfig::default(), dir.path().to_path_buf());
4271 let env_vars = HashMap::new();
4272 let payload = json!({
4273 "event": "message_submit",
4274 "text": "x".repeat(256 * 1024),
4275 });
4276
4277 let result = executor.execute_sync_with_stdin(&hook, &env_vars, &payload);
4278
4279 assert!(result.success, "hook should complete: {result:?}");
4280 assert!(result.stdout.ends_with("…[truncated]"));
4281 assert!(result.stderr.ends_with("…[truncated]"));
4282 assert!(result.stdout.len() <= HOOK_PIPE_CAPTURE_MAX_BYTES + 16);
4283 assert!(result.stderr.len() <= HOOK_PIPE_CAPTURE_MAX_BYTES + 16);
4284 }
4285
4286 #[test]
4287 fn test_executor_session_id() {
4288 let executor = HookExecutor::new(HooksConfig::default(), PathBuf::from("."));
4289
4290 assert!(executor.session_id().starts_with("sess_"));
4291 assert_eq!(executor.session_id().len(), 13); // "sess_" + 8 chars
4292 }
4293
4294 #[cfg(not(windows))]
4295 fn write_hook_script(dir: &tempfile::TempDir, name: &str, content: &str) -> String {
4296 let path = dir.path().join(name);
4297 std::fs::write(&path, content).expect("write hook script");
4298 format!("sh {}", path.display())
4299 }
4300
4301 #[cfg(not(windows))]
4302 fn submit_context(dir: &tempfile::TempDir) -> HookContext {
4303 HookContext::new()
4304 .with_session_id("sess_test")
4305 .with_workspace(dir.path().to_path_buf())
4306 .with_mode("agent")
4307 .with_model("deepseek-test")
4308 .with_tokens(42)
4309 }
4310
4311 #[cfg(not(windows))]
4312 #[test]
4313 fn json_observer_hook_receives_structured_stdin() {
4314 let dir = tempfile::tempdir().expect("tempdir");
4315 let out = dir.path().join("payload.json");
4316 let command = write_hook_script(
4317 &dir,
4318 "capture_observer.sh",
4319 &format!(
4320 r#"#!/bin/sh
4321 cat > "{}"
4322 "#,
4323 out.display()
4324 ),
4325 );
4326 let executor = HookExecutor::new(
4327 HooksConfig {
4328 enabled: true,
4329 hooks: vec![Hook::new(HookEvent::SubagentSpawn, &command)],
4330 ..Default::default()
4331 },
4332 dir.path().to_path_buf(),
4333 );
4334 let payload = json!({
4335 "event": "subagent_spawn",
4336 "agent_id": "agent_123",
4337 "prompt_preview": "inspect this",
4338 "prompt_truncated": false,
4339 });
4340
4341 let results = executor.execute_json_observer(
4342 HookEvent::SubagentSpawn,
4343 &submit_context(&dir),
4344 &payload,
4345 );
4346
4347 assert_eq!(results.len(), 1);
4348 assert!(results[0].success);
4349 let captured: serde_json::Value =
4350 serde_json::from_str(&std::fs::read_to_string(out).expect("payload written"))
4351 .expect("valid JSON payload");
4352 assert_eq!(captured["event"], "subagent_spawn");
4353 assert_eq!(captured["agent_id"], "agent_123");
4354 assert_eq!(captured["prompt_preview"], "inspect this");
4355 assert_eq!(captured["prompt_truncated"], false);
4356 }
4357
4358 #[cfg(not(windows))]
4359 #[test]
4360 fn turn_end_observer_hook_receives_stdin_json_and_ignores_stdout_contract() {
4361 let dir = tempfile::tempdir().expect("tempdir");
4362 let out = dir.path().join("turn_end.json");
4363 let command = write_hook_script(
4364 &dir,
4365 "capture_turn_end.sh",
4366 &format!(
4367 r#"#!/bin/sh
4368 cat > "{}"
4369 printf '%s\n' '{{"text":"stdout is not a mutation contract"}}'
4370 "#,
4371 out.display()
4372 ),
4373 );
4374 let executor = HookExecutor::new(
4375 HooksConfig {
4376 enabled: true,
4377 hooks: vec![Hook::new(HookEvent::TurnEnd, &command)],
4378 ..Default::default()
4379 },
4380 dir.path().to_path_buf(),
4381 );
4382 let usage = codewhale_models::Usage {
4383 input_tokens: 12,
4384 output_tokens: 3,
4385 prompt_cache_hit_tokens: None,
4386 prompt_cache_miss_tokens: None,
4387 prompt_cache_write_tokens: None,
4388 reasoning_tokens: None,
4389 reasoning_replay_tokens: None,
4390 server_tool_use: None,
4391
4392 input_audio_tokens: None,
4393 output_audio_tokens: None,
4394
4395 request_usages: Vec::new(),
4396 safety_tokens: None,
4397 };
4398 let context = submit_context(&dir).with_tokens(15);
4399 let payload = super::turn_end_payload(TurnEndPayloadInput {
4400 context: &context,
4401 created_at: "2026-07-12T10:30:00Z".parse().expect("timestamp"),
4402 model_backed: true,
4403 provider: Some("openai"),
4404 billing_surface: None,
4405 model: Some("gpt-5.5"),
4406 turn_id: "turn_observed",
4407 status: "completed",
4408 error: None,
4409 duration: Duration::from_millis(7),
4410 usage: &usage,
4411 totals: TurnEndTotals {
4412 session_tokens: 15,
4413 conversation_tokens: 15,
4414 input_tokens: 12,
4415 output_tokens: 3,
4416 },
4417 tool_count: 0,
4418 queued_message_count: 0,
4419 });
4420
4421 let results = executor.execute_json_observer(HookEvent::TurnEnd, &context, &payload);
4422
4423 assert_eq!(results.len(), 1);
4424 assert!(results[0].success);
4425 assert!(
4426 results[0]
4427 .stdout
4428 .contains("stdout is not a mutation contract"),
4429 "stdout is still captured for diagnostics"
4430 );
4431 let captured: serde_json::Value =
4432 serde_json::from_str(&std::fs::read_to_string(out).expect("payload written"))
4433 .expect("valid JSON payload");
4434 assert_eq!(captured["event"], "turn_end");
4435 assert_eq!(captured["created_at"], "2026-07-12T10:30:00+00:00");
4436 assert_eq!(captured["provider"], "openai");
4437 assert_eq!(captured["model"], "gpt-5.5");
4438 assert_eq!(captured["turn_id"], "turn_observed");
4439 assert_eq!(captured["totals"]["input_tokens"], 12);
4440 assert_eq!(captured["totals"]["output_tokens"], 3);
4441 }
4442
4443 #[cfg(not(windows))]
4444 #[test]
4445 fn json_observer_hook_failure_does_not_stop_later_hooks() {
4446 let dir = tempfile::tempdir().expect("tempdir");
4447 let marker = dir.path().join("later-ran");
4448 let failing = write_hook_script(
4449 &dir,
4450 "failing_observer.sh",
4451 r#"#!/bin/sh
4452 echo boom >&2
4453 exit 1
4454 "#,
4455 );
4456 let later = write_hook_script(
4457 &dir,
4458 "later_observer.sh",
4459 &format!(
4460 r#"#!/bin/sh
4461 cat > "{}"
4462 "#,
4463 marker.display()
4464 ),
4465 );
4466 let mut first = Hook::new(HookEvent::SubagentComplete, &failing);
4467 first.continue_on_error = false;
4468 let executor = HookExecutor::new(
4469 HooksConfig {
4470 enabled: true,
4471 hooks: vec![first, Hook::new(HookEvent::SubagentComplete, &later)],
4472 ..Default::default()
4473 },
4474 dir.path().to_path_buf(),
4475 );
4476 let payload = json!({
4477 "event": "subagent_complete",
4478 "agent_id": "agent_456",
4479 "status": "completed",
4480 });
4481
4482 let results = executor.execute_json_observer(
4483 HookEvent::SubagentComplete,
4484 &submit_context(&dir),
4485 &payload,
4486 );
4487
4488 assert_eq!(results.len(), 2);
4489 assert!(!results[0].success);
4490 assert!(results[1].success);
4491 assert!(
4492 marker.exists(),
4493 "observer failures must be warn-only and non-blocking"
4494 );
4495 }
4496
4497 #[cfg(not(windows))]
4498 #[test]
4499 fn message_submit_transform_applies_hooks_in_order() {
4500 let dir = tempfile::tempdir().expect("tempdir");
4501 let first = write_hook_script(
4502 &dir,
4503 "first.sh",
4504 r#"#!/bin/sh
4505 printf '%s\n' '{"text":"first"}'
4506 "#,
4507 );
4508 let second = write_hook_script(
4509 &dir,
4510 "second.sh",
4511 r#"#!/bin/sh
4512 payload=$(cat)
4513 case "$payload" in
4514 *'"text":"first"'*) printf '%s\n' '{"text":"first second"}' ;;
4515 *) printf '%s\n' '{"text":"wrong"}' ;;
4516 esac
4517 "#,
4518 );
4519 let config = HooksConfig {
4520 enabled: true,
4521 hooks: vec![
4522 Hook::new(HookEvent::MessageSubmit, &first),
4523 Hook::new(HookEvent::MessageSubmit, &second),
4524 ],
4525 working_dir: Some(dir.path().to_path_buf()),
4526 ..HooksConfig::default()
4527 };
4528 let executor = HookExecutor::new(config, dir.path().to_path_buf());
4529
4530 assert_eq!(
4531 executor.execute_message_submit_transform(&submit_context(&dir), "original"),
4532 MessageSubmitOutcome::replaced("first second".to_string())
4533 );
4534 }
4535
4536 #[cfg(not(windows))]
4537 #[test]
4538 fn message_submit_transform_exit_two_blocks_submission() {
4539 let dir = tempfile::tempdir().expect("tempdir");
4540 let command = write_hook_script(
4541 &dir,
4542 "block.sh",
4543 r#"#!/bin/sh
4544 printf '%s\n' '{"reason":"policy blocked this prompt"}'
4545 exit 2
4546 "#,
4547 );
4548 let config = HooksConfig {
4549 enabled: true,
4550 hooks: vec![Hook::new(HookEvent::MessageSubmit, &command)],
4551 working_dir: Some(dir.path().to_path_buf()),
4552 ..HooksConfig::default()
4553 };
4554 let executor = HookExecutor::new(config, dir.path().to_path_buf());
4555
4556 assert_eq!(
4557 executor.execute_message_submit_transform(&submit_context(&dir), "original"),
4558 MessageSubmitOutcome::Blocked {
4559 reason: "policy blocked this prompt".to_string()
4560 }
4561 );
4562 }
4563
4564 #[cfg(not(windows))]
4565 #[test]
4566 fn background_message_submit_hook_is_observer_only() {
4567 let dir = tempfile::tempdir().expect("tempdir");
4568 let command = write_hook_script(
4569 &dir,
4570 "background.sh",
4571 r#"#!/bin/sh
4572 printf '%s\n' '{"text":"ignored"}'
4573 "#,
4574 );
4575 let config = HooksConfig {
4576 enabled: true,
4577 hooks: vec![Hook::new(HookEvent::MessageSubmit, &command).background()],
4578 working_dir: Some(dir.path().to_path_buf()),
4579 ..HooksConfig::default()
4580 };
4581 let executor = HookExecutor::new(config, dir.path().to_path_buf());
4582
4583 assert_eq!(
4584 executor.execute_message_submit_transform(&submit_context(&dir), "original"),
4585 MessageSubmitOutcome::unchanged()
4586 );
4587 }
4588
4589 #[test]
4590 fn message_submit_transform_without_configured_hooks_is_unchanged() {
4591 let executor = HookExecutor::new(HooksConfig::default(), PathBuf::from("."));
4592
4593 assert_eq!(
4594 executor.execute_message_submit_transform(&HookContext::new(), "original"),
4595 MessageSubmitOutcome::unchanged()
4596 );
4597 }
4598
4599 #[cfg(not(windows))]
4600 #[test]
4601 fn message_submit_transform_skips_non_matching_condition() {
4602 let dir = tempfile::tempdir().expect("tempdir");
4603 let command = write_hook_script(
4604 &dir,
4605 "replace.sh",
4606 r#"#!/bin/sh
4607 printf '%s\n' '{"text":"should not apply"}'
4608 "#,
4609 );
4610 let hook =
4611 Hook::new(HookEvent::MessageSubmit, &command).with_condition(HookCondition::Mode {
4612 mode: "plan".into(),
4613 });
4614 let config = HooksConfig {
4615 enabled: true,
4616 hooks: vec![hook],
4617 working_dir: Some(dir.path().to_path_buf()),
4618 ..HooksConfig::default()
4619 };
4620 let executor = HookExecutor::new(config, dir.path().to_path_buf());
4621
4622 assert_eq!(
4623 executor.execute_message_submit_transform(&submit_context(&dir), "original"),
4624 MessageSubmitOutcome::unchanged()
4625 );
4626 }
4627
4628 #[cfg(not(windows))]
4629 #[test]
4630 fn message_submit_continue_on_error_true_keeps_text_and_runs_later_hooks() {
4631 let dir = tempfile::tempdir().expect("tempdir");
4632 let failing = write_hook_script(
4633 &dir,
4634 "fail_continue.sh",
4635 r#"#!/bin/sh
4636 printf '%s\n' 'soft failure' >&2
4637 exit 9
4638 "#,
4639 );
4640 let replacing = write_hook_script(
4641 &dir,
4642 "replace_after_failure.sh",
4643 r#"#!/bin/sh
4644 printf '%s\n' '{"text":"recovered"}'
4645 "#,
4646 );
4647 let config = HooksConfig {
4648 enabled: true,
4649 hooks: vec![
4650 Hook::new(HookEvent::MessageSubmit, &failing),
4651 Hook::new(HookEvent::MessageSubmit, &replacing),
4652 ],
4653 working_dir: Some(dir.path().to_path_buf()),
4654 ..HooksConfig::default()
4655 };
4656 let executor = HookExecutor::new(config, dir.path().to_path_buf());
4657
4658 assert_eq!(
4659 executor.execute_message_submit_transform(&submit_context(&dir), "original"),
4660 MessageSubmitOutcome::replaced("recovered".to_string())
4661 .with_warning(Some("message_submit hook exited with code 9".to_string()))
4662 );
4663 }
4664
4665 #[cfg(not(windows))]
4666 #[test]
4667 fn message_submit_timeout_continue_surfaces_warning_and_runs_later_hooks() {
4668 let dir = tempfile::tempdir().expect("tempdir");
4669 let slow = write_hook_script(
4670 &dir,
4671 "slow_continue.sh",
4672 r#"#!/bin/sh
4673 sleep 2
4674 "#,
4675 );
4676 let replacing = write_hook_script(
4677 &dir,
4678 "replace_after_timeout.sh",
4679 r#"#!/bin/sh
4680 printf '%s\n' '{"text":"after timeout"}'
4681 "#,
4682 );
4683 let mut slow_hook = Hook::new(HookEvent::MessageSubmit, &slow).with_timeout(1);
4684 slow_hook.continue_on_error = true;
4685 let config = HooksConfig {
4686 enabled: true,
4687 hooks: vec![slow_hook, Hook::new(HookEvent::MessageSubmit, &replacing)],
4688 working_dir: Some(dir.path().to_path_buf()),
4689 ..HooksConfig::default()
4690 };
4691 let executor = HookExecutor::new(config, dir.path().to_path_buf());
4692
4693 assert_eq!(
4694 executor.execute_message_submit_transform(&submit_context(&dir), "original"),
4695 MessageSubmitOutcome::replaced("after timeout".to_string())
4696 .with_warning(Some("hook timed out after 1s".to_string()))
4697 );
4698 }
4699
4700 #[cfg(not(windows))]
4701 #[test]
4702 fn message_submit_invalid_stdout_keeps_text_and_runs_later_hooks() {
4703 let dir = tempfile::tempdir().expect("tempdir");
4704 let invalid = write_hook_script(
4705 &dir,
4706 "invalid_stdout.sh",
4707 r#"#!/bin/sh
4708 printf '%s\n' 'not json'
4709 "#,
4710 );
4711 let replacing = write_hook_script(
4712 &dir,
4713 "replace_after_invalid.sh",
4714 r#"#!/bin/sh
4715 printf '%s\n' '{"text":"valid later"}'
4716 "#,
4717 );
4718 let config = HooksConfig {
4719 enabled: true,
4720 hooks: vec![
4721 Hook::new(HookEvent::MessageSubmit, &invalid),
4722 Hook::new(HookEvent::MessageSubmit, &replacing),
4723 ],
4724 working_dir: Some(dir.path().to_path_buf()),
4725 ..HooksConfig::default()
4726 };
4727 let executor = HookExecutor::new(config, dir.path().to_path_buf());
4728
4729 assert_eq!(
4730 executor.execute_message_submit_transform(&submit_context(&dir), "original"),
4731 MessageSubmitOutcome::replaced("valid later".to_string())
4732 );
4733 }
4734
4735 #[cfg(not(windows))]
4736 #[test]
4737 fn message_submit_continue_on_error_false_blocks_on_failure() {
4738 let dir = tempfile::tempdir().expect("tempdir");
4739 let command = write_hook_script(
4740 &dir,
4741 "fail.sh",
4742 r#"#!/bin/sh
4743 printf '%s\n' 'hard failure' >&2
4744 exit 7
4745 "#,
4746 );
4747 let mut hook = Hook::new(HookEvent::MessageSubmit, &command);
4748 hook.continue_on_error = false;
4749 let config = HooksConfig {
4750 enabled: true,
4751 hooks: vec![hook],
4752 working_dir: Some(dir.path().to_path_buf()),
4753 ..HooksConfig::default()
4754 };
4755 let executor = HookExecutor::new(config, dir.path().to_path_buf());
4756
4757 assert_eq!(
4758 executor.execute_message_submit_transform(&submit_context(&dir), "original"),
4759 MessageSubmitOutcome::Blocked {
4760 reason: "message_submit hook failed and blocked submission".to_string()
4761 }
4762 );
4763 }
4764
4765 #[test]
4766 fn has_hooks_for_event_fast_path_returns_false_for_empty_config() {
4767 let executor = HookExecutor::disabled();
4768 // No hooks configured AT ALL — every event is a fast skip.
4769 for event in [
4770 HookEvent::SessionStart,
4771 HookEvent::SessionEnd,
4772 HookEvent::MessageSubmit,
4773 HookEvent::ToolCallBefore,
4774 HookEvent::ToolCallAfter,
4775 HookEvent::ModeChange,
4776 HookEvent::OnError,
4777 HookEvent::TurnEnd,
4778 HookEvent::SubagentSpawn,
4779 HookEvent::SubagentComplete,
4780 ] {
4781 assert!(
4782 !executor.has_hooks_for_event(event),
4783 "empty config must short-circuit for {event:?}"
4784 );
4785 }
4786 }
4787
4788 #[test]
4789 fn has_hooks_for_event_returns_false_when_globally_disabled() {
4790 let config = HooksConfig {
4791 enabled: false,
4792 hooks: vec![Hook::new(HookEvent::ToolCallBefore, "echo blocked")],
4793 ..HooksConfig::default()
4794 };
4795 let executor = HookExecutor::new(config, PathBuf::from("."));
4796 assert!(
4797 !executor.has_hooks_for_event(HookEvent::ToolCallBefore),
4798 "globally-disabled hooks must report no fires even when one is configured"
4799 );
4800 }
4801
4802 #[test]
4803 fn has_hooks_for_event_distinguishes_event_types() {
4804 let config = HooksConfig {
4805 enabled: true,
4806 hooks: vec![
4807 Hook::new(HookEvent::SessionStart, "echo start"),
4808 Hook::new(HookEvent::ToolCallBefore, "echo before"),
4809 ],
4810 ..HooksConfig::default()
4811 };
4812 let executor = HookExecutor::new(config, PathBuf::from("."));
4813 // Configured events return true.
4814 assert!(executor.has_hooks_for_event(HookEvent::SessionStart));
4815 assert!(executor.has_hooks_for_event(HookEvent::ToolCallBefore));
4816 // Unconfigured events return false even when other events are present.
4817 assert!(!executor.has_hooks_for_event(HookEvent::ToolCallAfter));
4818 assert!(!executor.has_hooks_for_event(HookEvent::OnError));
4819 assert!(!executor.has_hooks_for_event(HookEvent::ModeChange));
4820 }
4821
4822 // ── #3026: tool_call_before stdout decision contract ──────────────────
4823
4824 #[test]
4825 fn tool_call_before_stdout_parses_deny_with_reason() {
4826 let parsed =
4827 parse_tool_call_before_stdout(r#"{"decision":"deny","reason":"blocked by policy"}"#);
4828 assert_eq!(parsed.decision, Some(ToolCallDecision::Deny));
4829 assert_eq!(parsed.reason.as_deref(), Some("blocked by policy"));
4830 assert!(parsed.updated_input.is_none());
4831 assert!(parsed.additional_context.is_none());
4832 }
4833
4834 #[test]
4835 fn tool_call_before_stdout_parses_ask_and_allow() {
4836 let ask = parse_tool_call_before_stdout(r#"{"decision":"ask"}"#);
4837 assert_eq!(ask.decision, Some(ToolCallDecision::Ask));
4838
4839 let allow = parse_tool_call_before_stdout(r#"{"decision":"allow"}"#);
4840 assert_eq!(allow.decision, Some(ToolCallDecision::Allow));
4841 }
4842
4843 #[test]
4844 fn tool_call_before_stdout_parses_updated_input_object() {
4845 let parsed =
4846 parse_tool_call_before_stdout(r#"{"updatedInput":{"command":"ls -la","timeout":5}}"#);
4847 assert!(parsed.decision.is_none());
4848 assert_eq!(
4849 parsed.updated_input,
4850 Some(serde_json::json!({"command":"ls -la","timeout":5}))
4851 );
4852 }
4853
4854 #[test]
4855 fn tool_call_before_stdout_rejects_non_object_updated_input() {
4856 let parsed = parse_tool_call_before_stdout(r#"{"updatedInput":"rm -rf /"}"#);
4857 assert!(
4858 parsed.updated_input.is_none(),
4859 "updatedInput must be a JSON object"
4860 );
4861 let parsed = parse_tool_call_before_stdout(r#"{"updatedInput":[1,2]}"#);
4862 assert!(parsed.updated_input.is_none());
4863 }
4864
4865 #[test]
4866 fn tool_call_before_stdout_parses_additional_context() {
4867 let parsed =
4868 parse_tool_call_before_stdout(r#"{"additionalContext":"remember the style guide"}"#);
4869 assert_eq!(
4870 parsed.additional_context.as_deref(),
4871 Some("remember the style guide")
4872 );
4873 }
4874
4875 #[test]
4876 fn tool_call_before_stdout_empty_and_non_json_are_passthrough() {
4877 for stdout in ["", " \n ", "ok, proceeding", "exit code zero"] {
4878 let parsed = parse_tool_call_before_stdout(stdout);
4879 assert!(parsed.decision.is_none(), "stdout {stdout:?}");
4880 assert!(parsed.reason.is_none());
4881 assert!(parsed.updated_input.is_none());
4882 assert!(parsed.additional_context.is_none());
4883 }
4884 }
4885
4886 #[test]
4887 fn tool_call_before_stdout_json_without_decision_is_passthrough() {
4888 let parsed = parse_tool_call_before_stdout(r#"{"status":"fine"}"#);
4889 assert!(parsed.decision.is_none());
4890 }
4891
4892 #[test]
4893 fn tool_call_before_stdout_non_object_json_is_passthrough() {
4894 for stdout in [r#""deny""#, "[1,2,3]", "42", "true"] {
4895 let parsed = parse_tool_call_before_stdout(stdout);
4896 assert!(parsed.decision.is_none(), "stdout {stdout:?}");
4897 }
4898 }
4899
4900 #[test]
4901 fn tool_call_before_stdout_unknown_decision_treated_as_allow() {
4902 let parsed = parse_tool_call_before_stdout(r#"{"decision":"block"}"#);
4903 assert!(parsed.decision.is_none());
4904 }
4905
4906 // ── #3026: glob matchers for tool_name conditions ──────────────────────
4907
4908 /// DOCS-04: the documented `mcp__*` glob must match the name the model
4909 /// actually calls (built by `McpPool::mcp_model_tool_name`, which is
4910 /// `mcp_<server>_<tool>`), and must not catch the built-in MCP helpers.
4911 #[test]
4912 fn mcp_glob_matches_real_model_tool_names_by_owning_server() {
4913 let served = crate::mcp::McpPool::mcp_model_tool_name("github", "create_issue");
4914 let other = crate::mcp::McpPool::mcp_model_tool_name("wiki", "lookup");
4915 let matches = HookExecutor::tool_name_matches_condition;
4916
4917 assert!(matches(&served, "mcp__*"), "{served} must match mcp__*");
4918 assert!(matches(&served, "mcp_*"), "{served} must match mcp_*");
4919 assert!(matches(&served, "mcp__github__*"));
4920 assert!(!matches(&other, "mcp__github__*"));
4921 assert!(matches(&served, "mcp__github__create_issue"));
4922 assert!(matches(&served, "mcp__*__create_issue"));
4923 assert!(!matches(&other, "mcp__*__create_issue"));
4924
4925 for helper in [
4926 "mcp_read_resource",
4927 "mcp_get_prompt",
4928 "list_mcp_resources",
4929 "list_mcp_resource_templates",
4930 "read_mcp_resource",
4931 ] {
4932 assert!(!matches(helper, "mcp__*"), "{helper} is built in");
4933 assert!(!matches(helper, "mcp_*"), "{helper} is built in");
4934 // Exact names still select a helper deliberately.
4935 assert!(matches(helper, helper));
4936 }
4937 assert!(!matches("read_file", "mcp__*"));
4938 }
4939
4940 #[test]
4941 fn tool_name_exact_match_still_works() {
4942 assert!(HookExecutor::tool_name_matches_condition(
4943 "read_file",
4944 "read_file"
4945 ));
4946 assert!(!HookExecutor::tool_name_matches_condition(
4947 "read_files",
4948 "read_file"
4949 ));
4950 }
4951
4952 #[test]
4953 fn tool_name_shell_spellings_match_each_other_in_both_directions() {
4954 let spellings = ["bash", "Bash", "exec_shell"];
4955 for tool in spellings {
4956 for pattern in spellings {
4957 assert!(
4958 HookExecutor::tool_name_matches_condition(tool, pattern),
4959 "tool {tool} should match condition {pattern}"
4960 );
4961 }
4962 }
4963 // The alias is exact: it does not widen to other shell-ish tools.
4964 assert!(!HookExecutor::tool_name_matches_condition(
4965 "task_shell_start",
4966 "bash"
4967 ));
4968 assert!(!HookExecutor::tool_name_matches_condition(
4969 "bash",
4970 "read_file"
4971 ));
4972 assert!(!HookExecutor::tool_name_matches_condition("BASH", "bash"));
4973 }
4974
4975 #[test]
4976 fn tool_name_glob_escapes_regex_metacharacters() {
4977 // Without escaping, `.` would match any character.
4978 assert!(!HookExecutor::tool_name_matches_condition(
4979 "mcpXgithub",
4980 "mcp.git*"
4981 ));
4982 assert!(HookExecutor::tool_name_matches_condition(
4983 "mcp.github",
4984 "mcp.git*"
4985 ));
4986 // `+` and parens must be literal too.
4987 assert!(HookExecutor::tool_name_matches_condition(
4988 "weird+tool(name)",
4989 "weird+tool(*)"
4990 ));
4991 }
4992
4993 #[test]
4994 fn tool_name_glob_supports_infix_and_suffix_positions() {
4995 assert!(HookExecutor::tool_name_matches_condition(
4996 "task_shell_start",
4997 "*_shell_start"
4998 ));
4999 assert!(!HookExecutor::tool_name_matches_condition(
5000 "task_shell_wait",
5001 "*_shell_start"
5002 ));
5003 }
5004
5005 // ── #3026: project-local hooks ─────────────────────────────────────────
5006
5007 #[test]
5008 fn load_with_project_missing_file_keeps_global() {
5009 let dir = tempfile::tempdir().expect("tempdir");
5010 let global = HooksConfig {
5011 enabled: true,
5012 hooks: vec![Hook::new(HookEvent::ToolCallBefore, "echo global")],
5013 ..HooksConfig::default()
5014 };
5015
5016 let merged = crate::hooks::config::load_with_project(global.clone(), dir.path());
5017 assert_eq!(merged.hooks.len(), 1);
5018 assert_eq!(merged.hooks[0].command, "echo global");
5019 }
5020
5021 #[test]
5022 fn load_with_project_appends_project_hooks_after_global() {
5023 let _lock = lock_test_env();
5024 let dir = tempfile::tempdir().expect("tempdir");
5025 let config_path = dir.path().join("user-config.toml");
5026 let _config = trust_workspace_for_project_hooks(dir.path(), &config_path);
5027 let _legacy_config = EnvVarGuard::remove("DEEPSEEK_CONFIG_PATH");
5028 let project_dir = dir.path().join(".codewhale");
5029 std::fs::create_dir_all(&project_dir).expect("mkdir .codewhale");
5030 std::fs::write(
5031 project_dir.join("hooks.toml"),
5032 r#"
5033 [[hooks]]
5034 event = "tool_call_before"
5035 command = "echo project"
5036 "#,
5037 )
5038 .expect("write hooks.toml");
5039
5040 let global = HooksConfig {
5041 enabled: true,
5042 hooks: vec![Hook::new(HookEvent::ToolCallBefore, "echo global")],
5043 ..HooksConfig::default()
5044 };
5045
5046 let (authority, _) = super::super::authority::review_project_hooks(dir.path()).unwrap();
5047 super::super::authority::approve_project_hooks(dir.path(), &authority.digest).unwrap();
5048 let merged = crate::hooks::config::load_with_project(global, dir.path());
5049 assert_eq!(merged.hooks.len(), 2);
5050 assert_eq!(
5051 merged.hooks[0].command, "echo global",
5052 "global hooks run first"
5053 );
5054 assert_eq!(
5055 merged.hooks[1].command, "echo project",
5056 "project hooks are appended after global"
5057 );
5058 }
5059
5060 #[test]
5061 fn load_with_project_ignores_project_hooks_until_workspace_trusted() {
5062 let _lock = lock_test_env();
5063 let dir = tempfile::tempdir().expect("tempdir");
5064 let _config = EnvVarGuard::set("CODEWHALE_CONFIG_PATH", dir.path().join("config.toml"));
5065 let _legacy_config = EnvVarGuard::remove("DEEPSEEK_CONFIG_PATH");
5066 let project_dir = dir.path().join(".codewhale");
5067 std::fs::create_dir_all(&project_dir).expect("mkdir .codewhale");
5068 std::fs::write(
5069 project_dir.join("hooks.toml"),
5070 r#"
5071 [[hooks]]
5072 event = "tool_call_before"
5073 command = "echo project"
5074 "#,
5075 )
5076 .expect("write hooks.toml");
5077
5078 let global = HooksConfig {
5079 enabled: true,
5080 hooks: vec![Hook::new(HookEvent::ToolCallBefore, "echo global")],
5081 ..HooksConfig::default()
5082 };
5083
5084 let merged = crate::hooks::config::load_with_project(global, dir.path());
5085 assert_eq!(merged.hooks.len(), 1);
5086 assert_eq!(merged.hooks[0].command, "echo global");
5087 }
5088
5089 #[test]
5090 fn load_with_project_ignores_project_local_legacy_trust_marker() {
5091 let _lock = lock_test_env();
5092 let dir = tempfile::tempdir().expect("tempdir");
5093 let _config = EnvVarGuard::set("CODEWHALE_CONFIG_PATH", dir.path().join("config.toml"));
5094 let _legacy_config = EnvVarGuard::remove("DEEPSEEK_CONFIG_PATH");
5095 let project_dir = dir.path().join(".codewhale");
5096 let legacy_trust_dir = dir.path().join(".deepseek");
5097 std::fs::create_dir_all(&project_dir).expect("mkdir .codewhale");
5098 std::fs::create_dir_all(&legacy_trust_dir).expect("mkdir .deepseek");
5099 std::fs::write(legacy_trust_dir.join("trusted"), "").expect("write legacy trust marker");
5100 std::fs::write(
5101 project_dir.join("hooks.toml"),
5102 r#"
5103 [[hooks]]
5104 event = "tool_call_before"
5105 command = "echo project"
5106 "#,
5107 )
5108 .expect("write hooks.toml");
5109
5110 let global = HooksConfig {
5111 enabled: true,
5112 hooks: vec![Hook::new(HookEvent::ToolCallBefore, "echo global")],
5113 ..HooksConfig::default()
5114 };
5115
5116 let merged = crate::hooks::config::load_with_project(global, dir.path());
5117 assert_eq!(merged.hooks.len(), 1);
5118 assert_eq!(merged.hooks[0].command, "echo global");
5119 }
5120
5121 #[test]
5122 fn load_with_project_malformed_file_falls_back_to_global() {
5123 let _lock = lock_test_env();
5124 let dir = tempfile::tempdir().expect("tempdir");
5125 let config_path = dir.path().join("user-config.toml");
5126 let _config = trust_workspace_for_project_hooks(dir.path(), &config_path);
5127 let _legacy_config = EnvVarGuard::remove("DEEPSEEK_CONFIG_PATH");
5128 let project_dir = dir.path().join(".codewhale");
5129 std::fs::create_dir_all(&project_dir).expect("mkdir .codewhale");
5130 std::fs::write(project_dir.join("hooks.toml"), "this is [ not toml")
5131 .expect("write hooks.toml");
5132
5133 let global = HooksConfig {
5134 enabled: true,
5135 hooks: vec![Hook::new(HookEvent::ToolCallBefore, "echo global")],
5136 ..HooksConfig::default()
5137 };
5138
5139 let merged = crate::hooks::config::load_with_project(global, dir.path());
5140 assert_eq!(merged.hooks.len(), 1, "malformed project file is ignored");
5141 assert_eq!(merged.hooks[0].command, "echo global");
5142 }
5143
5144 #[cfg(unix)]
5145 #[test]
5146 fn project_hooks_require_exact_review_at_load_and_every_spawn() {
5147 let _lock = lock_test_env();
5148 let dir = tempfile::tempdir().unwrap();
5149 let _config = trust_workspace_for_project_hooks(dir.path(), &dir.path().join("user.toml"));
5150 let _legacy = EnvVarGuard::remove("DEEPSEEK_CONFIG_PATH");
5151 std::fs::create_dir(dir.path().join(".codewhale")).unwrap();
5152 let hook_path = dir.path().join(".codewhale/hooks.toml");
5153 let contents = "[[hooks]]\nevent = \"session_start\"\ncommand = \"touch hook-ran\"\n";
5154 std::fs::write(&hook_path, contents).unwrap();
5155 let load = || {
5156 crate::hooks::config::load_with_project(
5157 HooksConfig {
5158 enabled: true,
5159 ..Default::default()
5160 },
5161 dir.path(),
5162 )
5163 };
5164 assert!(load().hooks.is_empty(), "folder trust is not hook approval");
5165 let (authority, _) = super::super::authority::review_project_hooks(dir.path()).unwrap();
5166 assert!(super::super::authority::approve_project_hooks(dir.path(), "bad-digest").is_err());
5167 super::super::authority::approve_project_hooks(dir.path(), &authority.digest).unwrap();
5168 let config = load();
5169 let hook = config.hooks[0].clone();
5170 let executor = HookExecutor::new(config, dir.path().to_path_buf());
5171 let good = executor.execute_sync(&hook, &HashMap::new());
5172 assert!(good.success, "{good:?}");
5173 std::fs::remove_file(dir.path().join("hook-ran")).unwrap();
5174 std::fs::write(&hook_path, format!("{contents}# changed\n")).unwrap();
5175 assert!(load().hooks.is_empty());
5176 assert!(!executor.execute_sync(&hook, &HashMap::new()).success);
5177 assert!(
5178 !executor
5179 .execute_background_inner(&hook, &HashMap::new(), None)
5180 .success
5181 );
5182 let queued = BackgroundHookJob {
5183 admitted: None,
5184 command: hook.command.clone(),
5185 env: HashMap::new(),
5186 working_dir: dir.path().to_path_buf(),
5187 stdin_bytes: None,
5188 label: "project".into(),
5189 timeout: Duration::from_secs(2),
5190 plugin_authority: None,
5191 project_authority: hook.project_authority.clone(),
5192 };
5193 queued.run();
5194 assert!(
5195 !dir.path().join("hook-ran").exists(),
5196 "queued work must revalidate"
5197 );
5198 std::fs::write(&hook_path, contents).unwrap();
5199 codewhale_runtime::config::save_workspace_hook_receipt(dir.path(), "").unwrap();
5200 assert!(!executor.execute_sync(&hook, &HashMap::new()).success);
5201 assert!(!dir.path().join("hook-ran").exists());
5202 }
5203
5204 #[cfg(unix)]
5205 #[test]
5206 fn project_hook_approval_rejects_symlinks_and_repository_receipts() {
5207 let _lock = lock_test_env();
5208 let dir = tempfile::tempdir().unwrap();
5209 let _config = trust_workspace_for_project_hooks(dir.path(), &dir.path().join("user.toml"));
5210 let _legacy = EnvVarGuard::remove("DEEPSEEK_CONFIG_PATH");
5211 std::fs::create_dir(dir.path().join(".codewhale")).unwrap();
5212 let target = dir.path().join("hook-source.toml");
5213 std::fs::write(
5214 &target,
5215 "[[hooks]]\nevent = \"session_start\"\ncommand = \"true\"\n",
5216 )
5217 .unwrap();
5218 let hook_path = dir.path().join(".codewhale/hooks.toml");
5219 std::os::unix::fs::symlink(&target, &hook_path).unwrap();
5220 assert!(super::super::authority::review_project_hooks(dir.path()).is_err());
5221 std::fs::remove_file(&hook_path).unwrap();
5222 std::fs::copy(&target, &hook_path).unwrap();
5223 let (authority, _) = super::super::authority::review_project_hooks(dir.path()).unwrap();
5224 std::fs::write(
5225 dir.path().join(".codewhale/config.toml"),
5226 format!("hooks_sha256 = \"{}\"", authority.digest),
5227 )
5228 .unwrap();
5229 assert!(
5230 crate::hooks::config::load_with_project(HooksConfig::default(), dir.path())
5231 .hooks
5232 .is_empty()
5233 );
5234 }
5235
5236 // === v0.9.2 hooks contract regression tests ===============================
5237 //
5238 // Each of these pins a claim that `docs/HOOKS.md` makes, so the docs cannot
5239 // drift ahead of the runtime again. All of them are provider-free: they
5240 // spawn `sh`, never a model.
5241
5242 #[test]
5243 fn background_result_is_a_submission_not_an_observed_exit_code() {
5244 // `background` is the flag that keeps "queued" from reading as
5245 // "exited 0". Steering paths gate on `observed_exit_code`.
5246 let submitted = HookResult {
5247 background: true,
5248 success: true,
5249 exit_code: None,
5250 ..HookResult::default()
5251 };
5252 assert!(submitted.background);
5253 assert_eq!(submitted.observed_exit_code(), None);
5254
5255 // A foreground deny still reads through.
5256 let denied = HookResult {
5257 background: false,
5258 success: false,
5259 exit_code: Some(2),
5260 ..HookResult::default()
5261 };
5262 assert_eq!(denied.observed_exit_code(), Some(2));
5263
5264 // A foreground timeout has no exit code either, but it is *not* a
5265 // background submission — callers must be able to tell them apart.
5266 let timed_out = HookResult {
5267 background: false,
5268 success: false,
5269 exit_code: None,
5270 error: Some("Hook timed out after 1s".to_string()),
5271 ..HookResult::default()
5272 };
5273 assert!(!timed_out.background);
5274 assert_eq!(timed_out.observed_exit_code(), None);
5275 }
5276
5277 #[test]
5278 fn default_timeout_secs_replaces_per_hook_timeout() {
5279 // Documented as-implemented: the global value overrides, it does not
5280 // merely fill in for hooks that omit one.
5281 let hook = Hook::new(HookEvent::SessionStart, "true").with_timeout(90);
5282 let overridden = HookExecutor::new(
5283 HooksConfig {
5284 default_timeout_secs: Some(5),
5285 ..HooksConfig::default()
5286 },
5287 PathBuf::from("."),
5288 );
5289 assert_eq!(overridden.effective_timeout_secs(&hook), 5);
5290
5291 let per_hook = HookExecutor::new(HooksConfig::default(), PathBuf::from("."));
5292 assert_eq!(per_hook.effective_timeout_secs(&hook), 90);
5293 }
5294
5295 #[test]
5296 fn foreground_timeout_result_is_bounded_and_carries_no_payload() {
5297 // The timeout result must not leak the stdin payload, the environment,
5298 // or partial output back to the caller.
5299 let command = if cfg!(windows) {
5300 "ping -n 4 127.0.0.1 > nul"
5301 } else {
5302 "echo secret-stdout; sleep 5"
5303 };
5304 let hook = Hook::new(HookEvent::MessageSubmit, command).with_timeout(1);
5305 let executor = HookExecutor::new(HooksConfig::default(), PathBuf::from("."));
5306 let payload = serde_json::json!({ "text": "super secret user text" });
5307
5308 let result = executor.execute_sync_with_stdin(&hook, &HashMap::new(), &payload);
5309
5310 assert!(!result.success);
5311 assert!(!result.background);
5312 assert_eq!(result.exit_code, None);
5313 assert!(result.stdout.is_empty(), "stdout leaked: {}", result.stdout);
5314 assert!(result.stderr.is_empty(), "stderr leaked: {}", result.stderr);
5315 let error = result.error.unwrap_or_default();
5316 assert!(error.contains("timed out"), "{error}");
5317 assert!(!error.contains("super secret"), "{error}");
5318 }
5319
5320 #[cfg(unix)]
5321 #[test]
5322 fn background_hook_timeout_kills_and_reaps_its_process_tree() {
5323 // The claim under test: "There is no path on which a timed-out hook
5324 // keeps running." A background hook used to be waited on with an
5325 // unbounded `child.wait()`, so a runaway command outlived the session.
5326 let dir = tempfile::tempdir().expect("tempdir");
5327 let marker = dir.path().join("survived.txt");
5328 // The inner `sh -c ... &` is a grandchild: killing only the immediate
5329 // shell would leave it alive, so this also covers process-group kill.
5330 let command = format!(
5331 "sh -c 'sleep 4; echo survived > {}' & wait",
5332 marker.display()
5333 );
5334 let hook = Hook::new(HookEvent::SessionStart, &command).with_timeout(1);
5335 let executor = HookExecutor::new(HooksConfig::default(), dir.path().to_path_buf());
5336
5337 let result = executor.execute_background(&hook, &HashMap::new());
5338 assert!(result.background, "background submission must be flagged");
5339 assert_eq!(result.observed_exit_code(), None);
5340
5341 // Well past the hook's 1s budget, and past the 4s the command wanted.
5342 std::thread::sleep(Duration::from_secs(6));
5343 assert!(
5344 !marker.exists(),
5345 "background hook outlived its timeout and kept running"
5346 );
5347 }
5348
5349 #[cfg(unix)]
5350 #[test]
5351 fn background_hook_receives_the_same_stdin_payload_as_foreground() {
5352 // Background changes scheduling, not the payload contract.
5353 let dir = tempfile::tempdir().expect("tempdir");
5354 let out = dir.path().join("bg-stdin.json");
5355 let command = write_hook_script(
5356 &dir,
5357 "capture_bg_stdin.sh",
5358 &format!("#!/bin/sh\ncat > {}\n", out.display()),
5359 );
5360 let hook = Hook::new(HookEvent::MessageSubmit, &command)
5361 .with_name("bg")
5362 .background();
5363 let executor = HookExecutor::new(
5364 HooksConfig {
5365 enabled: true,
5366 hooks: vec![hook],
5367 ..HooksConfig::default()
5368 },
5369 dir.path().to_path_buf(),
5370 );
5371
5372 let context = submit_context(&dir);
5373 let outcome = executor.execute_message_submit_transform(&context, "hello world");
5374 // Background hooks cannot steer.
5375 assert_eq!(outcome, MessageSubmitOutcome::unchanged());
5376
5377 let raw = wait_for_captured_output(&out);
5378 let payload: serde_json::Value = serde_json::from_str(raw.trim()).expect("valid JSON");
5379 assert_eq!(payload["event"], "message_submit");
5380 assert_eq!(payload["text"], "hello world");
5381 assert_eq!(payload["session_id"], "sess_test");
5382 assert_eq!(payload["mode"], "agent");
5383 assert_eq!(payload["model"], "deepseek-test");
5384 assert_eq!(payload["total_tokens"], 42);
5385 }
5386
5387 #[cfg(unix)]
5388 #[test]
5389 fn background_hook_receives_the_documented_environment() {
5390 let dir = tempfile::tempdir().expect("tempdir");
5391 let out = dir.path().join("bg-env.txt");
5392 let command = write_hook_script(
5393 &dir,
5394 "capture_bg_env.sh",
5395 &format!(
5396 "#!/bin/sh\nprintf '%s|%s|%s\\n' \"$DEEPSEEK_SESSION_ID\" \"$DEEPSEEK_MODE\" \
5397 \"$DEEPSEEK_TOOL_NAME\" > {}\n",
5398 out.display()
5399 ),
5400 );
5401 let hook = Hook::new(HookEvent::ToolCallAfter, &command)
5402 .with_name("bg-env")
5403 .background();
5404 let executor = HookExecutor::new(
5405 HooksConfig {
5406 enabled: true,
5407 hooks: vec![hook],
5408 ..HooksConfig::default()
5409 },
5410 dir.path().to_path_buf(),
5411 );
5412
5413 let context = submit_context(&dir).with_tool_name("exec_shell");
5414 let results = executor.execute(HookEvent::ToolCallAfter, &context);
5415 assert_eq!(results.len(), 1);
5416 assert!(results[0].background);
5417
5418 let captured = wait_for_captured_output(&out);
5419 assert_eq!(captured.trim(), "sess_test|agent|exec_shell");
5420 }
5421
5422 /// Wait for a background hook's capture file to hold real bytes.
5423 ///
5424 /// The capture scripts redirect with `> out`, so the shell creates the
5425 /// file — empty — before `cat`/`printf` writes the payload. Polling for
5426 /// existence alone can win that race under load and read an empty capture,
5427 /// which surfaced in CI as `valid JSON: EOF while parsing a value` (#5929).
5428 /// Both captures are single small writes, so waiting for non-empty bytes
5429 /// means the write has landed without weakening what the tests assert.
5430 #[cfg(unix)]
5431 fn wait_for_captured_output(path: &std::path::Path) -> String {
5432 let deadline = std::time::Instant::now() + Duration::from_secs(10);
5433 loop {
5434 if let Ok(raw) = std::fs::read_to_string(path)
5435 && !raw.trim().is_empty()
5436 {
5437 return raw;
5438 }
5439 assert!(
5440 std::time::Instant::now() < deadline,
5441 "background hook wrote no output to {}",
5442 path.display()
5443 );
5444 std::thread::sleep(Duration::from_millis(50));
5445 }
5446 }
5447
5448 #[test]
5449 fn session_id_is_stable_across_every_event_and_survives_a_rebind() {
5450 // One TUI session, one `CODEWHALE_SESSION_ID`. The legacy
5451 // `DEEPSEEK_SESSION_ID` alias carries the same value so existing hook
5452 // records stay correlatable; assert both names over every event.
5453 let executor = HookExecutor::new(HooksConfig::default(), PathBuf::from("."));
5454 let session_id = executor.session_id().to_string();
5455 assert!(
5456 session_id.starts_with("sess_"),
5457 "unexpected session id shape: {session_id}"
5458 );
5459
5460 for event in codewhale_config::hooks::ALL_HOOK_EVENTS {
5461 let context = HookContext::new()
5462 .with_session_id(executor.session_id())
5463 .with_tool_name(event.as_str());
5464 let env = context.to_env_vars();
5465 assert_eq!(
5466 env.get("CODEWHALE_SESSION_ID"),
5467 Some(&session_id),
5468 "event `{}` reported a different Codewhale session id",
5469 event.as_str()
5470 );
5471 assert_eq!(
5472 env.get("DEEPSEEK_SESSION_ID"),
5473 Some(&session_id),
5474 "event `{}` reported a different legacy session id",
5475 event.as_str()
5476 );
5477 }
5478
5479 // A workspace switch or trust decision reloads the hook set. It must
5480 // not mint a new identity.
5481 let rebound = executor.rebind(
5482 HooksConfig {
5483 enabled: true,
5484 hooks: vec![Hook::new(HookEvent::SessionStart, "true")],
5485 ..HooksConfig::default()
5486 },
5487 PathBuf::from("/tmp"),
5488 );
5489 assert_eq!(rebound.session_id(), session_id);
5490 assert_eq!(rebound.config().hooks.len(), 1);
5491
5492 // A genuinely new executor is a genuinely new session.
5493 let fresh = HookExecutor::new(HooksConfig::default(), PathBuf::from("."));
5494 assert_ne!(fresh.session_id(), session_id);
5495 }
5496
5497 #[test]
5498 fn exit_code_condition_matches_only_a_real_exit_code() {
5499 let executor = HookExecutor::new(HooksConfig::default(), PathBuf::from("."));
5500 let hook = Hook::new(HookEvent::ToolCallAfter, "true")
5501 .with_condition(HookCondition::ExitCode { code: 1 });
5502
5503 // No exit code reported at all: must not match. Notably it must not be
5504 // satisfied by the failure flag either.
5505 let no_code = HookContext::new()
5506 .with_tool_name("read_file")
5507 .with_tool_result("boom", false, None);
5508 assert!(!executor.matches_condition(&hook, &no_code));
5509
5510 // A different exit code: no match.
5511 let other_code = HookContext::new()
5512 .with_tool_name("exec_shell")
5513 .with_tool_result("boom", false, Some(127));
5514 assert!(!executor.matches_condition(&hook, &other_code));
5515
5516 // The real thing.
5517 let exact = HookContext::new()
5518 .with_tool_name("exec_shell")
5519 .with_tool_result("boom", false, Some(1));
5520 assert!(executor.matches_condition(&hook, &exact));
5521
5522 // Exit code 0 on a successful call is a real code and matches a
5523 // `code = 0` predicate.
5524 let zero_hook = Hook::new(HookEvent::ToolCallAfter, "true")
5525 .with_condition(HookCondition::ExitCode { code: 0 });
5526 let zero = HookContext::new()
5527 .with_tool_name("exec_shell")
5528 .with_tool_result("ok", true, Some(0));
5529 assert!(executor.matches_condition(&zero_hook, &zero));
5530 assert!(!executor.matches_condition(&zero_hook, &no_code));
5531 }
5532
5533 #[test]
5534 fn tool_call_id_is_exported_for_correlation() {
5535 let env = HookContext::new()
5536 .with_tool_name("exec_shell")
5537 .with_tool_call_id("call_abc123")
5538 .to_env_vars();
5539 assert_eq!(
5540 env.get("CODEWHALE_TOOL_CALL_ID"),
5541 Some(&"call_abc123".to_string())
5542 );
5543 assert_eq!(
5544 env.get("DEEPSEEK_TOOL_CALL_ID"),
5545 Some(&"call_abc123".to_string())
5546 );
5547
5548 // Absent when unknown — never synthesized.
5549 let without = HookContext::new()
5550 .with_tool_name("exec_shell")
5551 .to_env_vars();
5552 assert!(!without.contains_key("CODEWHALE_TOOL_CALL_ID"));
5553 assert!(!without.contains_key("DEEPSEEK_TOOL_CALL_ID"));
5554 }
5555
5556 #[test]
5557 fn tool_exit_code_env_var_is_absent_when_the_tool_reported_none() {
5558 let with_code = HookContext::new()
5559 .with_tool_result("out", false, Some(3))
5560 .to_env_vars();
5561 assert_eq!(
5562 with_code.get("DEEPSEEK_TOOL_EXIT_CODE"),
5563 Some(&"3".to_string())
5564 );
5565 assert_eq!(
5566 with_code.get("DEEPSEEK_TOOL_SUCCESS"),
5567 Some(&"false".to_string())
5568 );
5569
5570 let without_code = HookContext::new()
5571 .with_tool_result("out", false, None)
5572 .to_env_vars();
5573 assert!(!without_code.contains_key("DEEPSEEK_TOOL_EXIT_CODE"));
5574 assert_eq!(
5575 without_code.get("DEEPSEEK_TOOL_SUCCESS"),
5576 Some(&"false".to_string())
5577 );
5578 }
5579
5580 #[test]
5581 fn payload_env_vars_are_bounded() {
5582 // Errors used to be the one unbounded field; a failed `exec_shell`
5583 // could push its whole output into `DEEPSEEK_ERROR`.
5584 let long = "x".repeat(20_000);
5585 let env = HookContext::new()
5586 .with_error(&long)
5587 .with_message(&long)
5588 .with_tool_result(&long, false, None)
5589 .to_env_vars();
5590
5591 for key in ["DEEPSEEK_ERROR", "DEEPSEEK_MESSAGE", "DEEPSEEK_TOOL_RESULT"] {
5592 let value = env.get(key).unwrap_or_else(|| panic!("{key} missing"));
5593 assert!(value.len() < 20_000, "{key} was not truncated");
5594 assert!(value.ends_with("...[truncated]"), "{key} lost its marker");
5595 }
5596 }
5597
5598 #[test]
5599 fn truncate_env_value_respects_utf8_boundaries() {
5600 // 4-byte characters straddling the cap must not panic or split.
5601 let value = "🐋".repeat(100);
5602 let truncated = super::truncate_env_value(&value, 10);
5603 assert!(truncated.ends_with("...[truncated]"));
5604 let head = truncated.trim_end_matches("...[truncated]");
5605 assert!(head.chars().all(|c| c == '🐋'));
5606 assert!(head.len() <= 12);
5607 }
5608
5609 #[cfg(unix)]
5610 #[test]
5611 fn collect_shell_env_merges_later_hooks_over_earlier_ones() {
5612 // The documented merge: parsed verbatim, later hooks win, failures
5613 // contribute nothing and do not abort.
5614 let dir = tempfile::tempdir().expect("tempdir");
5615 let first = write_hook_script(
5616 &dir,
5617 "env_first.sh",
5618 "#!/bin/sh\necho SHARED=first\necho ONLY_FIRST=1\n",
5619 );
5620 let second = write_hook_script(
5621 &dir,
5622 "env_second.sh",
5623 "#!/bin/sh\necho SHARED=second\necho QUOTED=\"has spaces\"\n",
5624 );
5625 let failing = write_hook_script(&dir, "env_fail.sh", "#!/bin/sh\necho NEVER=1\nexit 1\n");
5626
5627 let executor = HookExecutor::new(
5628 HooksConfig {
5629 enabled: true,
5630 hooks: vec![
5631 Hook::new(HookEvent::ShellEnv, &first).with_name("first"),
5632 Hook::new(HookEvent::ShellEnv, &second).with_name("second"),
5633 Hook::new(HookEvent::ShellEnv, &failing).with_name("failing"),
5634 ],
5635 ..HooksConfig::default()
5636 },
5637 dir.path().to_path_buf(),
5638 );
5639
5640 let context = HookContext::new().with_tool_name("exec_shell");
5641 let merged = executor.collect_shell_env(&context);
5642
5643 assert_eq!(merged.get("SHARED"), Some(&"second".to_string()));
5644 assert_eq!(merged.get("ONLY_FIRST"), Some(&"1".to_string()));
5645 assert_eq!(merged.get("QUOTED"), Some(&"has spaces".to_string()));
5646 assert!(
5647 !merged.contains_key("NEVER"),
5648 "a failing shell_env hook must contribute nothing"
5649 );
5650 }
5651
5652 #[cfg(unix)]
5653 #[test]
5654 fn shell_env_ignores_the_background_flag_and_still_collects_stdout() {
5655 // `background` is not honored here: the stdout IS the contract, so the
5656 // hook runs in the foreground regardless of how it is configured.
5657 let dir = tempfile::tempdir().expect("tempdir");
5658 let script = write_hook_script(&dir, "env_bg.sh", "#!/bin/sh\necho FROM_BG=yes\n");
5659 let executor = HookExecutor::new(
5660 HooksConfig {
5661 enabled: true,
5662 hooks: vec![
5663 Hook::new(HookEvent::ShellEnv, &script)
5664 .with_name("bg-shell-env")
5665 .background(),
5666 ],
5667 ..HooksConfig::default()
5668 },
5669 dir.path().to_path_buf(),
5670 );
5671
5672 let merged = executor.collect_shell_env(&HookContext::new().with_tool_name("exec_shell"));
5673 assert_eq!(merged.get("FROM_BG"), Some(&"yes".to_string()));
5674 }
5675
5676 #[cfg(unix)]
5677 #[test]
5678 fn shell_env_hook_receives_only_the_narrow_documented_context() {
5679 let dir = tempfile::tempdir().expect("tempdir");
5680 let out = dir.path().join("shell-env-context.txt");
5681 let script = write_hook_script(
5682 &dir,
5683 "env_context.sh",
5684 &format!(
5685 "#!/bin/sh\nprintf 'name=%s args=%s session=%s mode=%s\\n' \
5686 \"$DEEPSEEK_TOOL_NAME\" \"$DEEPSEEK_TOOL_ARGS\" \"$DEEPSEEK_SESSION_ID\" \
5687 \"$DEEPSEEK_MODE\" > {}\n",
5688 out.display()
5689 ),
5690 );
5691 let executor = HookExecutor::new(
5692 HooksConfig {
5693 enabled: true,
5694 hooks: vec![Hook::new(HookEvent::ShellEnv, &script)],
5695 ..HooksConfig::default()
5696 },
5697 dir.path().to_path_buf(),
5698 );
5699
5700 let context = HookContext::new()
5701 .with_tool_name("exec_shell")
5702 .with_tool_args(&serde_json::json!({ "command": "ls" }));
5703 let _ = executor.collect_shell_env(&context);
5704
5705 let captured = std::fs::read_to_string(&out).expect("shell_env hook wrote nothing");
5706 assert!(captured.contains("name=exec_shell"), "{captured}");
5707 assert!(captured.contains(r#""command":"ls""#), "{captured}");
5708 // No session id or mode is supplied for this event, which is why a
5709 // `mode` condition on `shell_env` is rejected at load.
5710 assert!(captured.contains("session= "), "{captured}");
5711 assert!(captured.trim_end().ends_with("mode="), "{captured}");
5712 }
5713
5714 /// Strictness has to travel on the result, because only the results tell
5715 /// you which hooks actually *matched* this call.
5716 #[cfg(unix)]
5717 #[test]
5718 fn results_carry_the_strictness_of_the_hook_that_produced_them() {
5719 let dir = tempfile::tempdir().expect("tempdir");
5720 let mut strict = Hook::new(HookEvent::ToolCallBefore, "true")
5721 .with_name("strict")
5722 .with_condition(HookCondition::ToolName {
5723 name: "write_file".to_string(),
5724 });
5725 strict.continue_on_error = false;
5726 let lenient = Hook::new(HookEvent::ToolCallBefore, "true")
5727 .with_name("lenient")
5728 .with_condition(HookCondition::ToolName {
5729 name: "exec_shell".to_string(),
5730 });
5731
5732 let executor = HookExecutor::new(
5733 HooksConfig {
5734 enabled: true,
5735 hooks: vec![strict, lenient],
5736 ..HooksConfig::default()
5737 },
5738 dir.path().to_path_buf(),
5739 );
5740
5741 // Only the lenient hook matches an `exec_shell` call, so nothing about
5742 // this call is strict — even though a strict hook exists in config.
5743 let shell = executor.execute(
5744 HookEvent::ToolCallBefore,
5745 &HookContext::new().with_tool_name("exec_shell"),
5746 );
5747 assert_eq!(shell.len(), 1);
5748 assert_eq!(shell[0].name.as_deref(), Some("lenient"));
5749 assert!(!shell[0].strict);
5750
5751 // The `write_file` call is the one the strict gate guards.
5752 let write = executor.execute(
5753 HookEvent::ToolCallBefore,
5754 &HookContext::new().with_tool_name("write_file"),
5755 );
5756 assert_eq!(write.len(), 1);
5757 assert_eq!(write[0].name.as_deref(), Some("strict"));
5758 assert!(write[0].strict);
5759 }
5760
5761 #[cfg(unix)]
5762 #[test]
5763 fn background_results_are_never_strict() {
5764 let dir = tempfile::tempdir().expect("tempdir");
5765 let mut hook = Hook::new(HookEvent::ToolCallBefore, "true")
5766 .with_name("bg-strict")
5767 .background();
5768 hook.continue_on_error = false;
5769 let executor = HookExecutor::new(HooksConfig::default(), dir.path().to_path_buf());
5770
5771 let result = executor.execute_background(&hook, &HashMap::new());
5772 assert!(result.background);
5773 assert!(
5774 !result.strict,
5775 "nothing is awaited, so there is no answer to withhold"
5776 );
5777 }
5778
5779 /// A background hook that never reads stdin used to hang the supervising
5780 /// thread forever: the payload was written synchronously *before*
5781 /// `wait_timeout`, so a payload larger than the pipe buffer blocked, and
5782 /// the timeout / kill / reap below it were never reached.
5783 #[cfg(unix)]
5784 #[test]
5785 fn oversized_background_stdin_still_times_out_and_kills_the_tree() {
5786 let dir = tempfile::tempdir().expect("tempdir");
5787 let marker = dir.path().join("survived.txt");
5788 // Never reads stdin, and spawns a grandchild so this also covers the
5789 // process-group kill that the blocked write used to prevent.
5790 let command = write_hook_script(
5791 &dir,
5792 "ignores_stdin.sh",
5793 &format!(
5794 "#!/bin/sh\nsh -c 'sleep 6; echo survived > {}' &\nsleep 6\n",
5795 marker.display()
5796 ),
5797 );
5798 let hook = Hook::new(HookEvent::TurnEnd, &command)
5799 .with_name("deaf")
5800 .background()
5801 .with_timeout(1);
5802 let executor = HookExecutor::new(
5803 HooksConfig {
5804 enabled: true,
5805 hooks: vec![hook.clone()],
5806 ..HooksConfig::default()
5807 },
5808 dir.path().to_path_buf(),
5809 );
5810
5811 // Far beyond any pipe buffer (64 KiB on Linux, 8–64 KiB on macOS).
5812 let payload = json!({ "event": "turn_end", "blob": "x".repeat(4 * 1024 * 1024) });
5813
5814 let submitted = Instant::now();
5815 let result = executor.execute_background_with_stdin(&hook, &HashMap::new(), &payload);
5816 assert!(
5817 submitted.elapsed() < Duration::from_secs(2),
5818 "submission blocked on the stdin write: {:?}",
5819 submitted.elapsed()
5820 );
5821 assert!(result.background);
5822 assert!(result.success, "submission failed: {result:?}");
5823
5824 // Past the hook's 1s budget and past the 6s the command wanted.
5825 std::thread::sleep(Duration::from_secs(8));
5826 assert!(
5827 !marker.exists(),
5828 "background hook with an unread oversized stdin outlived its timeout"
5829 );
5830 }
5831
5832 #[test]
5833 fn spawn_failure_messages_carry_no_command_or_path() {
5834 let error = std::io::Error::new(
5835 std::io::ErrorKind::NotFound,
5836 "'C:\\Users\\dev\\secret hooks\\gate.cmd' is not recognized",
5837 );
5838 let message = super::spawn_failure_message(&error);
5839 assert!(message.contains("NotFound"), "{message}");
5840 assert!(!message.contains("gate.cmd"), "{message}");
5841 assert!(!message.contains("C:\\"), "{message}");
5842 assert!(!message.contains("secret"), "{message}");
5843 }
5844
5845 #[test]
5846 fn parse_env_lines_drops_nul_bearing_entries() {
5847 // `Command::env` panics on a NUL in a key or value, so a hook that
5848 // prints binary garbage must contribute nothing rather than take the
5849 // tool call down with it.
5850 let parsed = super::parse_env_lines("GOOD=fine\nBAD=tok\0en\nBA\0D2=x\nALSO_GOOD=2\n");
5851 assert_eq!(parsed.get("GOOD"), Some(&"fine".to_string()));
5852 assert_eq!(parsed.get("ALSO_GOOD"), Some(&"2".to_string()));
5853 assert!(!parsed.contains_key("BAD"), "{parsed:?}");
5854 assert_eq!(parsed.len(), 2, "{parsed:?}");
5855 for (key, value) in &parsed {
5856 assert!(!key.contains('\0'));
5857 assert!(!value.contains('\0'));
5858 // The invariants `Command::env` asserts on.
5859 assert!(!key.is_empty() && !key.contains('='));
5860 }
5861 }
5862
5863 #[test]
5864 fn parse_env_lines_bounds_values_and_the_aggregate() {
5865 let huge = "x".repeat(super::SHELL_ENV_VALUE_MAX_BYTES + 1);
5866 let parsed = super::parse_env_lines(&format!("OK=1\nHUGE={huge}\n"));
5867 assert_eq!(parsed.get("OK"), Some(&"1".to_string()));
5868 assert!(!parsed.contains_key("HUGE"), "over-long value was kept");
5869
5870 // Many individually-legal values still cannot add up to an unbounded
5871 // environment.
5872 let chunk = "y".repeat(16 * 1024);
5873 let mut stdout = String::new();
5874 for i in 0..64 {
5875 stdout.push_str(&format!("K{i}={chunk}\n"));
5876 }
5877 let bulk = super::parse_env_lines(&stdout);
5878 let total: usize = bulk.iter().map(|(k, v)| k.len() + v.len()).sum();
5879 assert!(total <= super::SHELL_ENV_TOTAL_MAX_BYTES, "{total} bytes");
5880 assert!(!bulk.is_empty(), "the bound must not drop everything");
5881 }
5882
5883 #[cfg(unix)]
5884 #[test]
5885 fn shell_env_hook_printing_nul_contributes_nothing_and_does_not_panic() {
5886 let dir = tempfile::tempdir().expect("tempdir");
5887 let script = write_hook_script(
5888 &dir,
5889 "env_nul.sh",
5890 "#!/bin/sh\nprintf 'TOKEN=abc\\000def\\n'\nprintf 'SAFE=ok\\n'\n",
5891 );
5892 let executor = HookExecutor::new(
5893 HooksConfig {
5894 enabled: true,
5895 hooks: vec![Hook::new(HookEvent::ShellEnv, &script).with_name("nul")],
5896 ..HooksConfig::default()
5897 },
5898 dir.path().to_path_buf(),
5899 );
5900
5901 let merged = executor.collect_shell_env(&HookContext::new().with_tool_name("exec_shell"));
5902 assert!(!merged.contains_key("TOKEN"), "{merged:?}");
5903 assert_eq!(merged.get("SAFE"), Some(&"ok".to_string()));
5904 // What `Command::env` would be handed must be panic-free.
5905 for (key, value) in &merged {
5906 assert!(!key.is_empty());
5907 assert!(!key.contains('=') && !key.contains('\0'));
5908 assert!(!value.contains('\0'));
5909 }
5910 }
5911
5912 #[test]
5913 fn tool_call_before_text_fields_are_sanitized_and_bounded() {
5914 let long = "z".repeat(super::HOOK_TEXT_FIELD_MAX_CHARS * 3);
5915 let stdout = serde_json::json!({
5916 "decision": "deny",
5917 "reason": format!("blocked\u{1b}[31m {long}"),
5918 "additionalContext": format!("ctx\u{0}\r\nline {long}"),
5919 })
5920 .to_string();
5921
5922 let parsed = super::parse_tool_call_before_stdout(&stdout);
5923
5924 let reason = parsed.reason.expect("reason kept");
5925 assert!(reason.chars().count() <= super::HOOK_TEXT_FIELD_MAX_CHARS + 16);
5926 assert!(reason.ends_with("…[truncated]"), "{reason}");
5927 assert!(!reason.contains('\u{1b}'), "escape sequence survived");
5928
5929 let context = parsed.additional_context.expect("context kept");
5930 assert!(context.chars().count() <= super::HOOK_TEXT_FIELD_MAX_CHARS + 16);
5931 assert!(!context.contains('\u{0}'));
5932 assert!(!context.contains('\r'));
5933 // Legitimate multi-line context still survives.
5934 assert!(
5935 context.contains('\n'),
5936 "{}",
5937 &context[..40.min(context.len())]
5938 );
5939 }
5940
5941 #[test]
5942 fn hook_context_bounds_tool_args_environment_value() {
5943 let env = HookContext::new()
5944 .with_tool_args(&serde_json::json!({
5945 "command": "x".repeat(super::HOOK_TOOL_ARGS_ENV_MAX_BYTES * 3)
5946 }))
5947 .to_env_vars();
5948 let args = env.get("DEEPSEEK_TOOL_ARGS").expect("tool args env");
5949 assert!(
5950 args.len() <= super::HOOK_TOOL_ARGS_ENV_MAX_BYTES + "...[truncated]".len(),
5951 "{} bytes",
5952 args.len()
5953 );
5954 assert!(args.ends_with("...[truncated]"));
5955 }
5956
5957 #[test]
5958 fn steering_objects_and_replacement_messages_have_independent_caps() {
5959 let oversized_input = serde_json::json!({
5960 "updatedInput": { "command": "x".repeat(super::HOOK_UPDATED_INPUT_MAX_BYTES * 2) }
5961 })
5962 .to_string();
5963 assert!(
5964 parse_tool_call_before_stdout(&oversized_input)
5965 .updated_input
5966 .is_none()
5967 );
5968
5969 let oversized_message = serde_json::json!({
5970 "text": "x".repeat(super::HOOK_MESSAGE_REPLACEMENT_MAX_CHARS + 1)
5971 })
5972 .to_string();
5973 assert!(matches!(
5974 super::parse_message_submit_stdout(&oversized_message),
5975 super::MessageSubmitStdout::Invalid(reason)
5976 if reason.contains("exceeds")
5977 ));
5978 }
5979
5980 #[test]
5981 fn turn_end_error_is_sanitized_and_bounded() {
5982 let context = HookContext::new();
5983 let usage = codewhale_models::Usage::default();
5984 let error = format!(
5985 "boom\u{1b}[2J{}",
5986 "x".repeat(super::HOOK_TURN_ERROR_MAX_CHARS * 2)
5987 );
5988 let payload = super::turn_end_payload(TurnEndPayloadInput {
5989 context: &context,
5990 created_at: chrono::Utc::now(),
5991 model_backed: true,
5992 provider: Some("test"),
5993 billing_surface: None,
5994 model: Some("test-model"),
5995 turn_id: "turn_test",
5996 status: "failed",
5997 error: Some(&error),
5998 duration: Duration::from_millis(1),
5999 usage: &usage,
6000 totals: TurnEndTotals {
6001 session_tokens: 0,
6002 conversation_tokens: 0,
6003 input_tokens: 0,
6004 output_tokens: 0,
6005 },
6006 tool_count: 0,
6007 queued_message_count: 0,
6008 });
6009 let rendered = payload["error"].as_str().expect("bounded error");
6010 assert!(!rendered.contains('\u{1b}'));
6011 assert!(rendered.ends_with("…[truncated]"));
6012 assert!(
6013 rendered.chars().count() <= super::HOOK_TURN_ERROR_MAX_CHARS + 16,
6014 "{} chars",
6015 rendered.chars().count()
6016 );
6017 }
6018
6019 #[test]
6020 fn denial_reason_redacts_paths_arguments_and_secret_assignments() {
6021 let rendered = super::sanitize_hook_denial_reason(
6022 "denied /Users/alice/private --command token=SUPERSECRET safe",
6023 );
6024 assert_eq!(rendered, "denied [path] [argument] [secret] safe");
6025 assert!(!rendered.contains("alice"));
6026 assert!(!rendered.contains("SUPERSECRET"));
6027 assert!(!rendered.contains("--command"));
6028
6029 let command = super::sanitize_hook_denial_reason("blocked command rm bearer abc123");
6030 assert_eq!(command, "blocked [command] [command] [secret] [secret]");
6031 assert!(!command.contains("rm"));
6032 assert!(!command.contains("abc123"));
6033 }
6034
6035 #[test]
6036 fn denial_reason_redacts_adversarial_header_path_and_command_forms() {
6037 for reason in [
6038 r#"Denied Authorization: Bearer TOPSECRET path="/Users/alice/private key" command='rm -rf /tmp/private' safe"#,
6039 r#"Denied authorization:"Bearer TOPSECRET" path=../private command="curl --header secret" safe"#,
6040 r#"Denied (Authorization: Bearer TOPSECRET), path = C:\private command = "powershell -enc SECRET" safe"#,
6041 ] {
6042 let rendered = super::sanitize_hook_denial_reason(reason);
6043 for secret in [
6044 "TOPSECRET",
6045 "alice",
6046 "private key",
6047 "../private",
6048 "C:\\private",
6049 "curl",
6050 "powershell",
6051 "SECRET",
6052 ] {
6053 assert!(!rendered.contains(secret), "leaked {secret}: {rendered}");
6054 }
6055 assert!(rendered.contains("[secret]"), "{rendered}");
6056 assert!(rendered.contains("[path]"), "{rendered}");
6057 assert!(rendered.contains("[command]"), "{rendered}");
6058 }
6059 }
6060
6061 #[test]
6062 fn denial_reason_redacts_auth_schemes_normalized_secrets_and_relative_paths() {
6063 for reason in [
6064 "Denied Authorization: Basic dXNlcjpwYXNz src/private/config.toml",
6065 "Denied Authorization=Digest deadbeef service.API-KEY=topsecret",
6066 "Denied authorization Negotiate kerberos AWS_SESSION_TOKEN=abc123",
6067 "Denied authorization NTLM credential internal_secret=hunter2",
6068 "Denied authorization Proprietary-Scheme opaque-credential src/private/key.txt",
6069 ] {
6070 let rendered = super::sanitize_hook_denial_reason(reason);
6071 for sensitive in [
6072 "dXNlcjpwYXNz",
6073 "deadbeef",
6074 "kerberos",
6075 "credential",
6076 "topsecret",
6077 "abc123",
6078 "hunter2",
6079 "src/private/config.toml",
6080 "opaque-credential",
6081 "src/private/key.txt",
6082 ] {
6083 assert!(
6084 !rendered.contains(sensitive),
6085 "leaked {sensitive}: {rendered}"
6086 );
6087 }
6088 assert!(rendered.contains("[secret]"), "{rendered}");
6089 }
6090 }
6091
6092 #[test]
6093 fn observer_dispatch_failures_are_event_specific_and_fixed() {
6094 let config = HooksConfig {
6095 enabled: true,
6096 hooks: vec![Hook::new(HookEvent::TurnEnd, "true")],
6097 ..HooksConfig::default()
6098 };
6099 let mut full = HookExecutor::new(config.clone(), PathBuf::from("."));
6100 full.inject_observer_dispatch_full_for_test();
6101 let error = full
6102 .submit_observer(HookEvent::TurnEnd, HookContext::new())
6103 .expect_err("full queue must be visible");
6104 assert_eq!(
6105 error,
6106 "turn_end observer hook queue is full; event was not submitted"
6107 );
6108
6109 let mut disconnected = HookExecutor::new(config, PathBuf::from("."));
6110 disconnected.inject_observer_dispatch_disconnect_for_test();
6111 let error = disconnected
6112 .submit_observer(HookEvent::TurnEnd, HookContext::new())
6113 .expect_err("disconnected dispatcher must be visible");
6114 assert_eq!(
6115 error,
6116 "turn_end observer hook dispatcher is unavailable; event was not submitted"
6117 );
6118 }
6119
6120 /// #6689: `DEEPSEEK_TOOL_EXECUTION_RECEIPT` is read from the metadata a
6121 /// shell tool recorded — on a failed call as well as a successful one —
6122 /// and is complete JSON or absent. The existing variables do not change.
6123 #[test]
6124 fn execution_receipt_env_is_complete_json_or_absent() {
6125 use crate::tools::spec::{ToolError, ToolResult};
6126
6127 let receipt = json!({"schema_version": 1, "command": "printf effective",
6128 "cwd": "/tmp", "state": "completed", "scope": "local", "exit_code": 7,
6129 "stdout": "\u{1f40b}", "stderr": "", "stdout_truncated": false,
6130 "stderr_truncated": false, "output_kind": "separate"});
6131 let plain = HookContext::new()
6132 .with_tool_name("Bash")
6133 .with_tool_outcome(&Ok(ToolResult::success("out")));
6134 let legacy = plain.to_env_vars();
6135 assert!(!legacy.contains_key("DEEPSEEK_TOOL_EXECUTION_RECEIPT"));
6136
6137 let with_receipt = HookContext::new()
6138 .with_tool_name("Bash")
6139 .with_tool_outcome(&Ok(
6140 ToolResult::success("out").with_metadata(json!({"execution_receipt": receipt}))
6141 ));
6142 let mut env = with_receipt.to_env_vars();
6143 let encoded = env
6144 .remove("DEEPSEEK_TOOL_EXECUTION_RECEIPT")
6145 .expect("receipt exported");
6146 assert_eq!(
6147 serde_json::from_str::<serde_json::Value>(&encoded).unwrap(),
6148 receipt
6149 );
6150 assert_eq!(env, legacy, "existing variables are unchanged");
6151
6152 let failed =
6153 HookContext::new().with_tool_outcome(&Err(ToolError::execution_failed_with_metadata(
6154 "boom",
6155 json!({"exit_code": 7, "execution_receipt": receipt}),
6156 )));
6157 assert!(
6158 failed
6159 .to_env_vars()
6160 .contains_key("DEEPSEEK_TOOL_EXECUTION_RECEIPT")
6161 );
6162
6163 // An unknown schema or an oversized document is dropped, not cut.
6164 for bad in [
6165 json!({"schema_version": 2, "command": "x"}),
6166 json!({"command": "x"}),
6167 json!({"schema_version": 1,
6168 "stdout": "x".repeat(super::HOOK_EXECUTION_RECEIPT_MAX_BYTES)}),
6169 ] {
6170 let context = HookContext::new().with_tool_outcome(&Ok(
6171 ToolResult::success("out").with_metadata(json!({"execution_receipt": bad}))
6172 ));
6173 assert!(context.tool_execution_receipt.is_none());
6174 }
6175 let oversized = HookContext {
6176 tool_execution_receipt: Some("x".repeat(super::HOOK_EXECUTION_RECEIPT_MAX_BYTES + 1)),
6177 ..HookContext::new()
6178 };
6179 assert!(
6180 !oversized
6181 .to_env_vars()
6182 .contains_key("DEEPSEEK_TOOL_EXECUTION_RECEIPT")
6183 );
6184 assert!(
6185 oversized
6186 .bounded_for_observer()
6187 .tool_execution_receipt
6188 .is_none()
6189 );
6190 }
6191
6192 fn shell_receipt_context() -> HookContext {
6193 HookContext::new()
6194 .with_tool_name("Bash")
6195 .with_session_id("session-receipt")
6196 .with_tool_call_id("call-receipt")
6197 .with_tool_args(&json!({"command": "requested, not executed", "cwd": "/wrong"}))
6198 .with_tool_outcome(&Ok(crate::tools::spec::ToolResult::success("preview")
6199 .with_metadata(json!({
6200 "status": "Failed",
6201 "exit_code": 7,
6202 "execution_receipt": {
6203 "schema_version": 1, "command": "printf effective; exit 7",
6204 "cwd": std::env::temp_dir().to_str().unwrap(), "scope": "local",
6205 "state": "completed", "exit_code": 7, "stdout": "effective",
6206 "stderr": "diagnostic", "stdout_truncated": false,
6207 "stderr_truncated": true, "output_kind": "separate"
6208 }
6209 }))))
6210 }
6211
6212 #[test]
6213 fn tool_after_stdin_uses_execution_evidence_and_truthful_bounds() {
6214 let mut context = shell_receipt_context();
6215 let original_env = context.to_env_vars();
6216 for name in ["bash", "Bash", "exec_shell"] {
6217 context.tool_name = Some(name.into());
6218 let payload = context.tool_after_payload().unwrap();
6219 assert_eq!(payload["schema_version"], 1);
6220 assert_eq!(payload["event"], "tool_call_after");
6221 assert_eq!(payload["tool_name"], name);
6222 let receipt = &payload["execution_receipt"];
6223 assert_eq!(receipt["command"], "printf effective; exit 7");
6224 assert_eq!(receipt["cwd"], std::env::temp_dir().to_str().unwrap());
6225 assert_eq!(receipt["completion"], "failed");
6226 assert_eq!(receipt["execution"], "started");
6227 assert_eq!(receipt["exit_code"], 7);
6228 assert_eq!(receipt["stderr_truncated"], true);
6229 assert_eq!(receipt["command_truncated"], false);
6230 assert_eq!(receipt["cwd_truncated"], false);
6231 assert_eq!(payload["session_id_truncated"], false);
6232 assert_eq!(payload["tool_call_id_truncated"], false);
6233 assert_eq!(payload["tool_name_truncated"], false);
6234 }
6235 context.tool_name = Some("Bash".into());
6236 assert_eq!(
6237 context.to_env_vars(),
6238 original_env,
6239 "legacy receipt is unchanged"
6240 );
6241 context.session_id = Some("用户\u{1}".repeat(20_000));
6242 context.tool_call_id = Some("鲸鱼".repeat(20_000));
6243 let payload = context.tool_after_payload().unwrap();
6244 assert_eq!(payload["session_id_truncated"], true);
6245 assert_eq!(payload["tool_call_id_truncated"], true);
6246 assert!(payload["session_id"].as_str().unwrap().len() <= 1_024 + 16);
6247 assert!(serde_json::to_vec(&payload).unwrap().len() <= 64 * 1024);
6248
6249 for (completion, code) in [
6250 ("killed", json!(null)),
6251 ("timed_out", json!(null)),
6252 ("failed", json!(3_221_225_477_i64)),
6253 ("completed", json!(0)),
6254 ] {
6255 context.tool_status = Some(completion.into());
6256 let mut receipt: serde_json::Value =
6257 serde_json::from_str(context.tool_execution_receipt.as_deref().unwrap()).unwrap();
6258 receipt["exit_code"] = code.clone();
6259 context.tool_execution_receipt = Some(receipt.to_string());
6260 let payload = context.tool_after_payload().unwrap();
6261 assert_eq!(payload["execution_receipt"]["exit_code"], code);
6262 assert_eq!(payload["execution_receipt"]["completion"], completion);
6263 }
6264 }
6265
6266 #[test]
6267 fn tool_after_stdin_has_no_receipt_for_unknown_or_unsupported_execution() {
6268 for name in ["mcp_shell", "task", "BASH"] {
6269 assert!(
6270 shell_receipt_context()
6271 .with_tool_name(name)
6272 .tool_after_payload()
6273 .is_none()
6274 );
6275 }
6276 for status in [None, Some("running"), Some("unknown")] {
6277 let mut context = shell_receipt_context();
6278 context.tool_status = status.map(str::to_owned);
6279 assert!(context.tool_after_payload().is_none());
6280 }
6281 for receipt in [
6282 None,
6283 Some("not JSON".into()),
6284 Some("x".repeat(HOOK_EXECUTION_RECEIPT_MAX_BYTES + 1)),
6285 ] {
6286 let mut context = shell_receipt_context();
6287 context.tool_execution_receipt = receipt;
6288 assert!(context.tool_after_payload().is_none());
6289 }
6290 for (field, value) in [
6291 ("schema_version", json!(2)),
6292 ("scope", json!("remote")),
6293 ("state", json!("running")),
6294 ("command", json!("")),
6295 ("cwd", json!("relative")),
6296 ("exit_code", json!("0")),
6297 ("stdout_truncated", json!(null)),
6298 ("output_kind", json!("guessed")),
6299 ("output_kind", json!("combined")),
6300 ] {
6301 let mut context = shell_receipt_context();
6302 let mut receipt: serde_json::Value =
6303 serde_json::from_str(context.tool_execution_receipt.as_deref().unwrap()).unwrap();
6304 receipt[field] = value;
6305 context.tool_execution_receipt = Some(receipt.to_string());
6306 assert!(
6307 context.tool_after_payload().is_none(),
6308 "accepted invalid {field}"
6309 );
6310 }
6311 }
6312
6313 #[cfg(unix)]
6314 #[tokio::test]
6315 async fn tool_after_stdin_delivers_real_shell_receipt_to_direct_and_queued_observers() {
6316 use crate::tools::spec::ToolSpec;
6317 let dir = tempfile::tempdir().unwrap();
6318 let out = dir.path().join("payload.json");
6319 let command = write_hook_script(
6320 &dir,
6321 "capture.sh",
6322 &format!(
6323 "#!/bin/sh\ncat > '{}'\nprintf '%s' '{{\"decision\":\"deny\",\"updatedInput\":{{\"command\":\"false\"}}}}'\n",
6324 out.display()
6325 ),
6326 );
6327 for background in [false, true] {
6328 for queued in [false, true] {
6329 let mut hook = Hook::new(HookEvent::ToolCallAfter, &command);
6330 hook.background = background;
6331 let hooks = HookExecutor::new(
6332 HooksConfig {
6333 enabled: true,
6334 hooks: vec![hook],
6335 ..Default::default()
6336 },
6337 dir.path().to_owned(),
6338 );
6339 let mut tool_context = crate::tools::spec::ToolContext::new(dir.path())
6340 .with_elevated_sandbox_policy(
6341 codewhale_sandbox::SandboxPolicy::DangerFullAccess,
6342 );
6343 tool_context.auto_approve = true;
6344 tool_context.runtime.hook_executor = Some(Arc::new(hooks.clone()));
6345 let result = crate::tools::shell::BashTool::new("Bash")
6346 .execute(
6347 json!({"command": "printf actual; printf diagnostic >&2; exit 7"}),
6348 &tool_context,
6349 )
6350 .await;
6351 let context = HookContext::new()
6352 .with_tool_name("Bash")
6353 .with_session_id("receipt-session")
6354 .with_tool_call_id("receipt-call")
6355 .with_tool_args(&json!({"command": "requested, not executed"}))
6356 .with_tool_outcome(&result);
6357 if out.exists() {
6358 std::fs::remove_file(&out).unwrap();
6359 }
6360 if queued {
6361 hooks
6362 .submit_observer(HookEvent::ToolCallAfter, context)
6363 .unwrap();
6364 } else {
6365 let results = hooks.execute(HookEvent::ToolCallAfter, &context);
6366 assert_eq!(results.len(), 1);
6367 assert!(results[0].success);
6368 }
6369 let payload: serde_json::Value =
6370 serde_json::from_str(&wait_for_captured_output(&out)).unwrap();
6371 assert_eq!(payload["session_id"], "receipt-session");
6372 assert_eq!(payload["tool_call_id"], "receipt-call");
6373 let receipt = &payload["execution_receipt"];
6374 assert_eq!(
6375 receipt["command"],
6376 "printf actual; printf diagnostic >&2; exit 7"
6377 );
6378 assert_eq!(
6379 receipt["cwd"],
6380 dir.path().canonicalize().unwrap().to_str().unwrap()
6381 );
6382 assert_eq!(receipt["exit_code"], 7);
6383 assert_eq!(receipt["completion"], "failed");
6384 assert_eq!(receipt["stdout"], "actual");
6385 assert_eq!(receipt["stderr"], "diagnostic");
6386 assert_eq!(receipt["output_mode"], "separate");
6387 assert!(
6388 !result.as_ref().unwrap().success,
6389 "observer output cannot rewrite the settled call"
6390 );
6391 }
6392 }
6393 }
6394
6395 /// An absent receipt must be absent in the actual child environment,
6396 /// even when a nested Codewhale inherited an outer hook's receipt.
6397 #[cfg(unix)]
6398 #[test]
6399 fn execution_receipt_never_inherits_another_calls_environment() {
6400 let _env = lock_test_env();
6401 let _stale = EnvVarGuard::set("DEEPSEEK_TOOL_EXECUTION_RECEIPT", "stale-outer-receipt");
6402 let current = r#"{"schema_version":1,"command":"current call"}"#;
6403 let dir = tempfile::tempdir().unwrap();
6404 let out = dir.path().join("receipt-env.txt");
6405 let command = write_hook_script(
6406 &dir,
6407 "capture_receipt_env.sh",
6408 &format!(
6409 "#!/bin/sh\nprintf '%s' \"${{DEEPSEEK_TOOL_EXECUTION_RECEIPT-unset}}\" > {}\n",
6410 out.display()
6411 ),
6412 );
6413 for background in [false, true] {
6414 let mut hook = Hook::new(HookEvent::ToolCallAfter, &command);
6415 hook.background = background;
6416 let executor = HookExecutor::new(
6417 HooksConfig {
6418 enabled: true,
6419 hooks: vec![hook],
6420 ..HooksConfig::default()
6421 },
6422 dir.path().to_path_buf(),
6423 );
6424 for (receipt, expected) in [
6425 (None, "unset"),
6426 (
6427 Some("x".repeat(HOOK_EXECUTION_RECEIPT_MAX_BYTES + 1)),
6428 "unset",
6429 ),
6430 (Some(current.to_string()), current),
6431 ] {
6432 if out.exists() {
6433 std::fs::remove_file(&out).unwrap();
6434 }
6435 let context = HookContext {
6436 tool_execution_receipt: receipt,
6437 ..HookContext::new()
6438 };
6439 let results = executor.execute(HookEvent::ToolCallAfter, &context);
6440 assert_eq!(results.len(), 1);
6441 assert!(results[0].success);
6442 assert_eq!(wait_for_captured_output(&out), expected);
6443 }
6444 }
6445 }
6446
6447 #[test]
6448 fn observer_context_is_bounded_before_enqueue() {
6449 let huge = "用户".repeat(20_000);
6450 let bounded = HookContext {
6451 tool_args: Some(huge.clone()),
6452 tool_result: Some(huge.clone()),
6453 error_message: Some(huge.clone()),
6454 message: Some(huge.clone()),
6455 model: Some(huge),
6456 ..HookContext::new()
6457 }
6458 .bounded_for_observer();
6459
6460 assert!(bounded.tool_args.expect("args").len() <= super::HOOK_TOOL_ARGS_ENV_MAX_BYTES + 16);
6461 assert!(
6462 bounded.tool_result.expect("result").len()
6463 <= super::HOOK_TOOL_RESULT_CONTEXT_MAX_BYTES + 16
6464 );
6465 assert!(
6466 bounded.error_message.expect("error").len() <= super::HOOK_ERROR_CONTEXT_MAX_BYTES + 16
6467 );
6468 assert!(
6469 bounded.message.expect("message").len() <= super::HOOK_MESSAGE_CONTEXT_MAX_BYTES + 16
6470 );
6471 assert!(
6472 bounded.model.expect("model").len() <= super::HOOK_OBSERVER_METADATA_MAX_BYTES + 16
6473 );
6474 }
6475
6476 #[test]
6477 fn background_supervisor_saturation_is_a_failed_submission() {
6478 let hook = Hook::new(HookEvent::TurnEnd, "true").background();
6479 let mut executor = HookExecutor::new(
6480 HooksConfig {
6481 enabled: true,
6482 hooks: vec![hook],
6483 ..HooksConfig::default()
6484 },
6485 PathBuf::from("."),
6486 );
6487 executor.inject_background_supervisor_full_for_test();
6488
6489 let results = executor.execute(HookEvent::TurnEnd, &HookContext::new());
6490 assert_eq!(results.len(), 1);
6491 assert!(results[0].background);
6492 assert!(!results[0].success);
6493 assert_eq!(
6494 results[0].error.as_deref(),
6495 Some("background hook supervisor queue is full")
6496 );
6497 }
6498
6499 #[cfg(not(windows))]
6500 #[test]
6501 fn bounded_observer_dispatcher_executes_a_submitted_event() {
6502 let dir = tempfile::tempdir().expect("tempdir");
6503 let receipt = dir.path().join("observer-receipt.json");
6504 let command = write_hook_script(
6505 &dir,
6506 "persistent_observer.sh",
6507 &format!("#!/bin/sh\ncat > '{}'\n", receipt.display()),
6508 );
6509 let executor = HookExecutor::new(
6510 HooksConfig {
6511 enabled: true,
6512 hooks: vec![Hook::new(HookEvent::TurnEnd, &command)],
6513 ..HooksConfig::default()
6514 },
6515 dir.path().to_path_buf(),
6516 );
6517 executor
6518 .submit_json_observer(
6519 HookEvent::TurnEnd,
6520 HookContext::new(),
6521 serde_json::json!({"event": "turn_end", "turn_id": "turn_test"}),
6522 )
6523 .expect("bounded submission");
6524
6525 let deadline = Instant::now() + Duration::from_secs(2);
6526 let payload = loop {
6527 if let Ok(raw) = std::fs::read_to_string(&receipt)
6528 && let Ok(payload) = serde_json::from_str::<serde_json::Value>(&raw)
6529 {
6530 break payload;
6531 }
6532 assert!(
6533 Instant::now() < deadline,
6534 "persistent worker did not finish a valid receipt"
6535 );
6536 std::thread::sleep(Duration::from_millis(10));
6537 };
6538 assert_eq!(payload["turn_id"], "turn_test");
6539 }
6540
6541 #[cfg(unix)]
6542 #[test]
6543 fn explicit_message_denial_never_copies_raw_process_diagnostics() {
6544 let dir = tempfile::tempdir().expect("tempdir");
6545 let command = r#"printf '%s\n' '{"reason":"blocked /Users/alice/private --run token=SUPERSECRET"}'; printf '%s\n' 'stderr-secret /tmp/private' >&2; exit 2"#;
6546 let executor = HookExecutor::new(
6547 HooksConfig {
6548 enabled: true,
6549 hooks: vec![Hook::new(HookEvent::MessageSubmit, command)],
6550 ..HooksConfig::default()
6551 },
6552 dir.path().to_path_buf(),
6553 );
6554 let outcome = executor.execute_message_submit_transform(&HookContext::new(), "hello");
6555 let MessageSubmitOutcome::Blocked { reason } = outcome else {
6556 panic!("expected explicit block");
6557 };
6558 assert_eq!(reason, "blocked [path] [argument] [secret]");
6559 for secret in ["alice", "SUPERSECRET", "stderr-secret", "/tmp/private"] {
6560 assert!(!reason.contains(secret), "leaked {secret}: {reason}");
6561 }
6562 }
6563
6564 #[cfg(unix)]
6565 #[test]
6566 fn foreground_pipe_capture_is_bounded_while_verbose_child_is_drained() {
6567 let hook = Hook::new(
6568 HookEvent::SessionStart,
6569 "head -c 200000 /dev/zero | tr '\\0' o; head -c 200000 /dev/zero | tr '\\0' e >&2",
6570 )
6571 .with_timeout(5);
6572 let executor = HookExecutor::new(HooksConfig::default(), PathBuf::from("."));
6573 let result = executor.execute_sync(&hook, &HashMap::new());
6574 assert!(result.success, "{:?}", result.error);
6575 for output in [&result.stdout, &result.stderr] {
6576 assert!(output.ends_with("…[truncated]"));
6577 assert!(
6578 output.len() <= super::HOOK_PIPE_CAPTURE_MAX_BYTES + "…[truncated]".len(),
6579 "{} bytes",
6580 output.len()
6581 );
6582 }
6583 }
6584
6585 #[cfg(unix)]
6586 #[test]
6587 fn helper_wait_and_uncontained_reap_paths_are_bounded() {
6588 // These helpers reap one immediate child. A shell can fork `sleep`
6589 // and leave that descendant holding the test's output pipes.
6590 let mut helper = Command::new("sleep")
6591 .arg("30")
6592 .spawn()
6593 .expect("spawn helper");
6594 let started = Instant::now();
6595 let error = super::wait_for_helper_status(&mut helper, Duration::from_millis(20))
6596 .expect_err("slow helper must time out");
6597 assert_eq!(error.kind(), std::io::ErrorKind::TimedOut);
6598 assert!(started.elapsed() < super::HOOK_REAP_TIMEOUT + Duration::from_secs(1));
6599 assert!(matches!(helper.try_wait(), Ok(Some(_))));
6600
6601 let mut uncontained = Command::new("sleep")
6602 .arg("30")
6603 .spawn()
6604 .expect("spawn uncontained child");
6605 assert!(super::kill_and_reap_immediate_child(
6606 &mut uncontained,
6607 Duration::from_secs(1)
6608 ));
6609 assert!(matches!(uncontained.try_wait(), Ok(Some(_))));
6610 }
6611
6612 #[test]
6613 fn sanitize_hook_text_keeps_short_text_verbatim() {
6614 assert_eq!(
6615 super::sanitize_hook_text("plain reason", 100),
6616 "plain reason"
6617 );
6618 assert_eq!(super::sanitize_hook_text("a\tb\nc", 100), "a\tb\nc");
6619 assert_eq!(super::sanitize_hook_text("", 100), "");
6620 }
6621
6622 #[test]
6623 fn sanitize_hook_line_flattens_structure_characters() {
6624 assert_eq!(super::sanitize_hook_line("a\tb\nc", 100), "a b c");
6625 assert_eq!(super::sanitize_hook_line("a\u{1b}[2Jb\r", 100), "a [2Jb");
6626 }
6627
6628 #[test]
6629 fn sanitize_hook_label_bounds_and_defangs_operator_names() {
6630 let noisy = format!("\u{1b}[2Jgate\twith\nnoise{}", "x".repeat(1_000));
6631 let label = super::sanitize_hook_label(Some(&noisy));
6632 assert!(!label.contains('\u{1b}'), "{label}");
6633 assert!(!label.contains('\n') && !label.contains('\t'), "{label}");
6634 assert!(label.contains("gate"), "{label}");
6635 assert!(
6636 label.chars().count() <= super::HOOK_LABEL_MAX_CHARS + 16,
6637 "{} chars",
6638 label.chars().count()
6639 );
6640
6641 assert_eq!(super::sanitize_hook_label(None), "(unnamed)");
6642 assert_eq!(super::sanitize_hook_label(Some("")), "(unnamed)");
6643 assert_eq!(super::sanitize_hook_label(Some(" \t ")), "(unnamed)");
6644 assert_eq!(super::sanitize_hook_label(Some(" gate ")), "gate");
6645 }
6646
6647 /// The point of the boundary: recognized failures are re-rendered from
6648 /// parts, and anything else — including a string a future producer forgot
6649 /// to genericize — collapses instead of passing through.
6650 #[test]
6651 fn generic_unavailable_detail_is_an_allowlist_not_a_passthrough() {
6652 use super::generic_unavailable_detail as detail;
6653
6654 assert_eq!(
6655 detail(Some("Hook timed out after 30s")),
6656 "hook timed out after 30s"
6657 );
6658 assert_eq!(
6659 detail(Some("hook process could not be started (NotFound)")),
6660 "hook process could not be started (NotFound)"
6661 );
6662 assert_eq!(
6663 detail(Some("Failed to wait for hook: os error 10")),
6664 "hook did not complete cleanly"
6665 );
6666 assert_eq!(
6667 detail(Some("hook could not be reaped after its timeout")),
6668 "hook did not complete cleanly"
6669 );
6670 assert_eq!(
6671 detail(Some("Failed to submit background hook: os error 11")),
6672 "hook could not be submitted"
6673 );
6674 assert_eq!(
6675 detail(Some("hook executor did not run")),
6676 "hook executor did not run"
6677 );
6678 assert_eq!(detail(None), "hook returned no verdict");
6679
6680 // A hypothetical future producer that leaks.
6681 let leaky = "spawn failed: /Users/someone/.aws/credentials --token=SECRET";
6682 let rendered = detail(Some(leaky));
6683 assert_eq!(rendered, "hook returned no verdict");
6684 assert!(!rendered.contains("SECRET"));
6685 assert!(!rendered.contains('/'));
6686
6687 // And a recognized prefix cannot be used to smuggle a tail along.
6688 let smuggled = detail(Some(
6689 "Hook timed out after 30s while running /usr/bin/leak --token=SECRET",
6690 ));
6691 assert_eq!(smuggled, "hook timed out after 30s");
6692 let smuggled = detail(Some(
6693 "hook process could not be started (NotFound) /usr/bin/leak",
6694 ));
6695 assert_eq!(smuggled, "hook process could not be started (NotFound)");
6696 }
6697
6698 /// The gate set the caller has to fail closed on if the executor is lost.
6699 #[cfg(unix)]
6700 #[test]
6701 fn matched_strict_gate_labels_names_only_gates_that_would_run() {
6702 use codewhale_config::hooks::{Hook, HookCondition, HookEvent, HooksConfig};
6703
6704 let strict_shell = {
6705 let mut hook = Hook::new(HookEvent::ToolCallBefore, "true")
6706 .with_name("shell-gate")
6707 .with_condition(HookCondition::ToolName {
6708 name: "exec_shell".into(),
6709 });
6710 hook.continue_on_error = false;
6711 hook
6712 };
6713 let strict_write = {
6714 let mut hook = Hook::new(HookEvent::ToolCallBefore, "true")
6715 .with_name("write-gate")
6716 .with_condition(HookCondition::ToolName {
6717 name: "write_file".into(),
6718 });
6719 hook.continue_on_error = false;
6720 hook
6721 };
6722 let lenient_shell = Hook::new(HookEvent::ToolCallBefore, "true").with_name("lenient");
6723 let background_strict = {
6724 let mut hook = Hook::new(HookEvent::ToolCallBefore, "true").with_name("bg-gate");
6725 hook.continue_on_error = false;
6726 hook.background = true;
6727 hook
6728 };
6729 let other_event = {
6730 let mut hook = Hook::new(HookEvent::ToolCallAfter, "true").with_name("after-gate");
6731 hook.continue_on_error = false;
6732 hook
6733 };
6734
6735 let executor = HookExecutor::new(
6736 HooksConfig {
6737 enabled: true,
6738 hooks: vec![
6739 strict_shell,
6740 strict_write,
6741 lenient_shell,
6742 background_strict,
6743 other_event,
6744 ],
6745 ..HooksConfig::default()
6746 },
6747 std::env::temp_dir(),
6748 );
6749
6750 let labels = executor.matched_strict_gate_labels(
6751 HookEvent::ToolCallBefore,
6752 &HookContext::new().with_tool_name("exec_shell"),
6753 );
6754 assert_eq!(labels, vec!["shell-gate".to_string()], "{labels:?}");
6755
6756 // Globally disabled hooks are not gates either.
6757 let disabled = HookExecutor::disabled();
6758 assert!(
6759 disabled
6760 .matched_strict_gate_labels(
6761 HookEvent::ToolCallBefore,
6762 &HookContext::new().with_tool_name("exec_shell"),
6763 )
6764 .is_empty()
6765 );
6766 }
6767
6768 /// The reap after a kill is bounded. This asserts the ordinary case is
6769 /// still confirmed dead and, more importantly, that the call returns —
6770 /// the regression it guards is a hang, not a wrong value.
6771 #[cfg(unix)]
6772 #[test]
6773 fn timed_out_hook_is_killed_and_reaped_within_the_bound() {
6774 use codewhale_config::hooks::{Hook, HookEvent, HooksConfig};
6775
6776 let hook = Hook::new(HookEvent::SessionStart, "sleep 30")
6777 .with_name("slow")
6778 .with_timeout(1);
6779 let executor = HookExecutor::new(
6780 HooksConfig {
6781 enabled: true,
6782 hooks: vec![hook],
6783 ..HooksConfig::default()
6784 },
6785 std::env::temp_dir(),
6786 );
6787
6788 let started = Instant::now();
6789 let results = executor.execute(HookEvent::SessionStart, &HookContext::new());
6790 let elapsed = started.elapsed();
6791
6792 assert_eq!(results.len(), 1);
6793 assert_eq!(
6794 results[0].error.as_deref(),
6795 Some("Hook timed out after 1s"),
6796 "the child was reaped, so the stronger claim is the honest one"
6797 );
6798 assert!(
6799 elapsed < Duration::from_secs(1) + super::HOOK_REAP_TIMEOUT + Duration::from_secs(5),
6800 "timeout path took {elapsed:?}"
6801 );
6802 }
6803
6804 #[test]
6805 fn tool_exit_code_env_var_survives_a_windows_crash_code() {
6806 // 0xC0000005 (access violation) does not fit in an `i32`. It used to
6807 // be dropped on the floor before the hook ever saw it.
6808 let env = HookContext::new()
6809 .with_tool_result("crashed", false, Some(3_221_225_477))
6810 .to_env_vars();
6811 assert_eq!(
6812 env.get("DEEPSEEK_TOOL_EXIT_CODE"),
6813 Some(&"3221225477".to_string())
6814 );
6815
6816 let executor = HookExecutor::new(HooksConfig::default(), PathBuf::from("."));
6817 let hook =
6818 Hook::new(HookEvent::ToolCallAfter, "true").with_condition(HookCondition::ExitCode {
6819 code: 3_221_225_477,
6820 });
6821 let context = HookContext::new()
6822 .with_tool_name("exec_shell")
6823 .with_tool_result("crashed", false, Some(3_221_225_477));
6824 assert!(executor.matches_condition(&hook, &context));
6825 }
6826
6827 /// 2026-08-04: the category map knew only retired tool names, so every
6828 /// live call fell through to `other` and a `tool_category` deny hook —
6829 /// the security control `docs/HOOKS.md` documents — silently never fired.
6830 #[test]
6831 fn tool_category_classifies_the_names_the_registry_actually_registers() {
6832 use super::tool_category_for;
6833
6834 // Anchor to the real catalog. Everything below this pins hardcoded
6835 // names, which would stay green through a tool rename while the gate
6836 // quietly reclassified the renamed tool. `DEFAULT_ACTIVE_NATIVE_TOOLS`
6837 // is the list the engine actually puts on the wire, so if a name here
6838 // stops being a name the product ships, this fails first.
6839 //
6840 // Note the fallback is "other", not "safe" — asserting against "safe"
6841 // here would never fire. This table is checked in both directions, so
6842 // a rename fails on the missing entry and a classifier change fails on
6843 // the mismatched category.
6844 const EXPECTED: &[(&str, &str)] = &[
6845 ("read", "safe"),
6846 ("write", "file_write"),
6847 ("edit", "file_write"),
6848 ("list_dir", "other"),
6849 // Searches the workspace without caller-named write targets, so it
6850 // keeps the classification it already had as a deferred tool.
6851 ("file_search", "other"),
6852 ("grep_files", "other"),
6853 ("bash", "shell"),
6854 // The router itself touches nothing a hook needs to gate.
6855 ("agent", "other"),
6856 ("todo_write", "safe"),
6857 // Goal controls retain their existing hook classification when
6858 // promoted from deferred discovery to the eager catalog.
6859 ("create_goal", "other"),
6860 ("present", "other"),
6861 // Reads the skill registry, not caller-named paths, so it keeps
6862 // the classification it already had as a deferred tool. Making it
6863 // eager must not silently re-gate it.
6864 ("load_skill", "other"),
6865 ];
6866 for name in crate::core::engine::tool_catalog::DEFAULT_ACTIVE_NATIVE_TOOLS {
6867 let expected = EXPECTED.iter().find(|(n, _)| n == name).map(|(_, c)| *c);
6868 assert_eq!(
6869 Some(tool_category_for(name, None)),
6870 expected,
6871 "default-active tool {name:?} is not covered by this test's \
6872 table. It was renamed or added without updating the hook \
6873 gate's classifier, so the gate now sees a shipped tool it \
6874 does not recognise."
6875 );
6876 }
6877 for (name, _) in EXPECTED {
6878 assert!(
6879 crate::core::engine::tool_catalog::DEFAULT_ACTIVE_NATIVE_TOOLS.contains(name),
6880 "{name:?} is pinned here but is no longer default-active; drop \
6881 it so this table keeps describing what actually ships."
6882 );
6883 }
6884
6885 // The shell surface.
6886 assert_eq!(tool_category_for("Bash", None), "shell");
6887 // Retained: shell.rs stamps this for the shell_env event.
6888 assert_eq!(tool_category_for("exec_shell", None), "shell");
6889 // Run executes commands, so it gates with shell rather than safe.
6890 assert_eq!(tool_category_for("Run", None), "shell");
6891
6892 // File is multi-action: the action decides.
6893 let read = r#"{"action":"read","path":"a.rs"}"#;
6894 let write = r#"{"action":"write","path":"a.rs","content":"x"}"#;
6895 assert_eq!(tool_category_for("File", Some(read)), "safe");
6896 assert_eq!(tool_category_for("File", Some(write)), "file_write");
6897 assert_eq!(
6898 tool_category_for("File", Some(r#"{"action":"edit"}"#)),
6899 "file_write"
6900 );
6901 assert_eq!(
6902 tool_category_for("File", Some(r#"{"action":"search_content"}"#)),
6903 "safe"
6904 );
6905
6906 // A gate that cannot see the action must assume the dangerous one.
6907 assert_eq!(tool_category_for("File", None), "file_write");
6908 assert_eq!(tool_category_for("File", Some("not json")), "file_write");
6909
6910 assert_eq!(tool_category_for("apply_patch", None), "file_write");
6911 assert_eq!(
6912 tool_category_for("Git", Some(r#"{"action":"log"}"#)),
6913 "safe"
6914 );
6915 assert_eq!(
6916 tool_category_for("Git", Some(r#"{"action":"commit_plan"}"#)),
6917 "safe"
6918 );
6919 assert_eq!(tool_category_for("web.run", None), "other");
6920
6921 assert_eq!(tool_category_for("read_file", None), "safe");
6922 for name in ["write_file", "edit_file", "fim_edit"] {
6923 assert_eq!(tool_category_for(name, None), "file_write", "{name}");
6924 }
6925 for name in [
6926 "terminal_run",
6927 "terminal_send",
6928 "code_execution",
6929 "rlm_eval",
6930 ] {
6931 assert_eq!(tool_category_for(name, None), "shell", "{name}");
6932 }
6933 assert_eq!(
6934 tool_category_for("tasks", Some(r#"{"action":"gate_run"}"#)),
6935 "shell"
6936 );
6937 assert_eq!(
6938 tool_category_for("rlm", Some(r#"{"action":"eval"}"#)),
6939 "shell"
6940 );
6941 assert_eq!(
6942 tool_category_for("rlm", Some(r#"{"action":"session_objects"}"#)),
6943 "other"
6944 );
6945 }
6946 }
6947
6948 pub fn shell_env_keys(stdout: &str) -> Vec<String> {
6949 parse_env_lines(stdout).into_keys().collect()
6950 }
6951
6952 #[cfg(test)]
6953 mod admitted_hook_tests {
6954 use super::*;
6955 #[test]
6956 fn native_payload_uses_actual_caller_and_bounded_canonical_input() {
6957 let caller = HookCaller {
6958 workspace: PathBuf::from("/actual"),
6959 plugins: None,
6960 session_id: Some("actual-session".into()),
6961 agent_id: Some("child".into()),
6962 origin_turn_id: Some("turn".into()),
6963 origin_call_id: Some("call".into()),
6964 };
6965 let context = HookContext::new()
6966 .with_session_id("legacy-alias")
6967 .with_caller(caller)
6968 .with_tool_name("write")
6969 .with_tool_call_id("call")
6970 .with_tool_args(&json!({"text":"你好"}));
6971 let payload = context.native_payload("PreToolUse", None).unwrap();
6972 assert_eq!(payload["session_id"], "actual-session");
6973 assert_eq!(payload["cwd"], "/actual");
6974 assert_eq!(payload["tool_input"], json!({"text":"你好"}));
6975 let oversized = context.with_tool_args(&json!({"text":"x".repeat(32769)}));
6976 assert!(oversized.native_payload("PreToolUse", None).is_err());
6977 }
6978 #[test]
6979 fn native_submit_block_preserves_real_process_exit_semantics() {
6980 assert_eq!(
6981 parse_message_submit_stdout(r#"{"block":true,"reason":"stop"}"#),
6982 MessageSubmitStdout::Blocked("stop".into())
6983 );
6984 assert_eq!(
6985 parse_message_submit_stdout(r#"{"text":"new"}"#),
6986 MessageSubmitStdout::Replaced("new".into())
6987 );
6988 }
6989 #[cfg(unix)]
6990 #[test]
6991 fn admitted_std_driver_cancels_and_reaps_before_late_side_effect() {
6992 let home = tempfile::tempdir().unwrap();
6993 let marker = home.path().join("late");
6994 let executor = HookExecutor::new(HooksConfig::default(), home.path().to_path_buf());
6995 let hook = Hook::new(
6996 HookEvent::SessionStart,
6997 &format!("sleep 2; touch '{}'", marker.display()),
6998 )
6999 .with_timeout(5);
7000 let token = tokio_util::sync::CancellationToken::new();
7001 let to_cancel = token.clone();
7002 let worker = std::thread::spawn(move || {
7003 std::thread::sleep(Duration::from_millis(100));
7004 to_cancel.cancel();
7005 });
7006 let started = Instant::now();
7007 let result = executor.execute_sync_legacy(&hook, &HashMap::new(), None, Some(&token));
7008 worker.join().unwrap();
7009 assert!(!result.success);
7010 assert!(started.elapsed() < Duration::from_secs(2));
7011 assert!(!marker.exists());
7012 }
7013 }
7014
7014 lines RUST