Skip to main content

vtcode_core/hooks/lifecycle/
engine.rs

1use std::path::PathBuf;
2use std::process::Stdio;
3use std::sync::Arc;
4use std::time::Duration;
5
6use anyhow::{Context, Result};
7use serde_json::Value;
8use tokio::io::{AsyncReadExt, AsyncWriteExt};
9use tokio::process::Command;
10use tokio::sync::Mutex;
11use tokio::time;
12
13use crate::config::{HookCommandConfig, HooksConfig};
14use crate::exec::events::{CompactionMode, CompactionTrigger};
15use crate::permissions::PermissionRequest;
16use crate::utils::dot_config::load_lifecycle_hook_approval;
17
18use crate::hooks::lifecycle::compiled::CompiledLifecycleHooks;
19use crate::hooks::lifecycle::interpret::{
20    HookCommandResult, interpret_permission_request, interpret_post_tool, interpret_pre_tool, interpret_session_end,
21    interpret_session_start, interpret_stop, interpret_user_prompt,
22};
23use crate::hooks::lifecycle::types::{
24    HookMessage, NotificationHookType, PermissionRequestHookOutcome, PostToolHookOutcome, PreCompactHookOutcome,
25    PreToolHookDecision, PreToolHookOutcome, SessionEndReason, SessionStartHookOutcome, SessionStartTrigger,
26    StopHookOutcome, UserPromptHookOutcome,
27};
28#[cfg(test)]
29use crate::hooks::lifecycle::utils::generate_session_id;
30use crate::hooks::lifecycle::utils::path_to_string;
31
32const DEFAULT_TIMEOUT_SECS: u64 = 60;
33
34/// Upper bound on the post-kill stdout/stderr drain for a timed-out hook.
35/// Mirrors `crate::exec::async_command`: a descendant that escaped the process
36/// group via `setsid()` can keep a pipe write end open forever, so the drain
37/// must be bounded or `run_session_end` can hang (and leak the hook task).
38const HOOK_POST_KILL_DRAIN_TIMEOUT: Duration = Duration::from_secs(2);
39
40/// Best-effort cleanup for a hook's process group on abort.
41///
42/// `kill_on_drop(true)` only kills the direct `sh` child, which leaves shell
43/// grandchildren alive and holding the captured pipes open. When the owning
44/// future is cancelled, this guard kills the whole group; it is disarmed once
45/// the hook finishes normally so a deliberately detached descendant is not
46/// retroactively killed. Mirrors `crate::exec::async_command`.
47#[cfg(unix)]
48struct HookProcessGroupGuard {
49    pid: Option<u32>,
50    armed: bool,
51}
52
53#[cfg(unix)]
54impl HookProcessGroupGuard {
55    fn new(pid: Option<u32>) -> Self {
56        Self { pid, armed: true }
57    }
58
59    /// Kill at most once: once the child has been reaped its PID can be
60    /// recycled, so a second best-effort kill could hit an unrelated group.
61    fn kill(&mut self) {
62        if !self.armed {
63            return;
64        }
65        self.armed = false;
66        if let Some(pid) = self.pid {
67            let _ = vtcode_bash_runner::process_group::kill_process_group_by_pid(pid);
68        }
69    }
70
71    fn disarm(&mut self) {
72        self.armed = false;
73    }
74}
75
76#[cfg(unix)]
77impl Drop for HookProcessGroupGuard {
78    fn drop(&mut self) {
79        self.kill();
80    }
81}
82
83mod payloads;
84
85#[derive(Clone)]
86pub struct LifecycleHookEngine {
87    inner: Arc<LifecycleHookInner>,
88}
89
90impl LifecycleHookEngine {
91    /// Test-only convenience constructor. Production session paths must use
92    /// [`Self::new_with_session_gated`] so workspace-controlled hook content
93    /// stays fail-closed; this un-gated entry point exists only so test
94    /// configurations can construct engines directly.
95    #[cfg(test)]
96    pub fn new(workspace: PathBuf, config: &HooksConfig, trigger: SessionStartTrigger) -> Result<Option<Self>> {
97        Self::new_with_session(workspace, config, trigger, generate_session_id())
98    }
99
100    /// Test-only convenience constructor; see [`Self::new`].
101    #[cfg(test)]
102    pub fn new_with_session(
103        workspace: PathBuf,
104        config: &HooksConfig,
105        trigger: SessionStartTrigger,
106        session_id: impl Into<String>,
107    ) -> Result<Option<Self>> {
108        Self::new_with_session_gated(workspace, config, trigger, session_id, false)
109    }
110
111    /// Construct the engine with the workspace approval gate.
112    ///
113    /// When `workspace_gated` is true, the workspace configuration (a
114    /// workspace-root `vtcode.toml`, the workspace `.vtcode/` fallback, a
115    /// project profile, or a workspace-sourced agent spec with hooks) contains
116    /// lifecycle hook commands. No lifecycle command then executes until the
117    /// user explicitly approves the exact command set this engine will run,
118    /// bound to its digest. Callers must pass `true` whenever
119    /// `VTCodeConfig.workspace_lifecycle_hooks` is non-empty or the active
120    /// primary agent contributes workspace-controlled hooks.
121    pub fn new_with_session_gated(
122        workspace: PathBuf,
123        config: &HooksConfig,
124        trigger: SessionStartTrigger,
125        session_id: impl Into<String>,
126        workspace_gated: bool,
127    ) -> Result<Option<Self>> {
128        if config.lifecycle.is_empty() {
129            return Ok(None);
130        }
131
132        let compiled = CompiledLifecycleHooks::from_config(&config.lifecycle)?;
133        if compiled.is_empty() {
134            return Ok(None);
135        }
136
137        let command_digest = commands_digest(&compiled);
138
139        Ok(Some(Self {
140            inner: Arc::new(LifecycleHookInner {
141                workspace,
142                session_id: session_id.into(),
143                trigger,
144                hooks: compiled,
145                workspace_gated,
146                command_digest,
147                state: Mutex::new(LifecycleHookState {
148                    transcript_path: None,
149                    approved_workspace_digest: None,
150                }),
151            }),
152        }))
153    }
154
155    pub async fn run_session_start(&self) -> Result<SessionStartHookOutcome> {
156        let mut messages = Vec::new();
157        let mut additional_context = Vec::new();
158
159        if self.inner.hooks.session_start.is_empty() {
160            return Ok(SessionStartHookOutcome { messages, additional_context });
161        }
162
163        let trigger_value = self.inner.trigger.as_str().to_owned();
164        let payload = self.build_session_start_payload().await?;
165
166        for group in &self.inner.hooks.session_start {
167            if !group.matcher.matches(&trigger_value) {
168                continue;
169            }
170
171            for command in &group.commands {
172                match self.execute_command("SessionStart", command, &payload).await {
173                    Ok(result) => interpret_session_start(
174                        command,
175                        &result,
176                        &mut messages,
177                        &mut additional_context,
178                        self.inner.hooks.quiet_success_output,
179                    ),
180                    Err(err) => messages
181                        .push(HookMessage::error(format!("SessionStart hook `{}` failed: {err}", command.command))),
182                }
183            }
184        }
185
186        Ok(SessionStartHookOutcome { messages, additional_context })
187    }
188
189    pub async fn run_session_end(&self, turn_id: &str, reason: SessionEndReason) -> Result<Vec<HookMessage>> {
190        let mut messages = Vec::new();
191
192        if self.inner.hooks.session_end.is_empty() {
193            return Ok(messages);
194        }
195
196        let payload = self.build_session_end_payload(turn_id, reason).await?;
197        let reason_value = reason.as_str().to_owned();
198
199        for group in &self.inner.hooks.session_end {
200            if !group.matcher.matches(&reason_value) {
201                continue;
202            }
203
204            for command in &group.commands {
205                match self.execute_command("SessionEnd", command, &payload).await {
206                    Ok(result) => {
207                        interpret_session_end(command, &result, &mut messages, self.inner.hooks.quiet_success_output)
208                    }
209                    Err(err) => messages
210                        .push(HookMessage::error(format!("SessionEnd hook `{}` failed: {err}", command.command))),
211                }
212            }
213        }
214
215        Ok(messages)
216    }
217
218    pub async fn run_subagent_start(
219        &self,
220        parent_session_id: &str,
221        child_thread_id: &str,
222        agent_name: &str,
223        display_label: &str,
224        background: bool,
225        status: &str,
226        transcript_path: Option<&std::path::Path>,
227    ) -> Result<Vec<HookMessage>> {
228        let mut messages = Vec::new();
229
230        if self.inner.hooks.subagent_start.is_empty() {
231            return Ok(messages);
232        }
233
234        let payload = self
235            .build_subagent_start_payload(
236                parent_session_id,
237                child_thread_id,
238                agent_name,
239                display_label,
240                background,
241                status,
242                transcript_path,
243            )
244            .await?;
245        let matcher_value = agent_name.to_owned();
246
247        for group in &self.inner.hooks.subagent_start {
248            if !group.matcher.matches(&matcher_value) {
249                continue;
250            }
251
252            for command in &group.commands {
253                match self.execute_command("SubagentStart", command, &payload).await {
254                    Ok(result) => {
255                        interpret_session_end(command, &result, &mut messages, self.inner.hooks.quiet_success_output)
256                    }
257                    Err(err) => messages
258                        .push(HookMessage::error(format!("SubagentStart hook `{}` failed: {err}", command.command))),
259                }
260            }
261        }
262
263        Ok(messages)
264    }
265
266    pub async fn run_subagent_stop(
267        &self,
268        parent_session_id: &str,
269        child_thread_id: &str,
270        agent_name: &str,
271        display_label: &str,
272        background: bool,
273        status: &str,
274        transcript_path: Option<&std::path::Path>,
275    ) -> Result<Vec<HookMessage>> {
276        let mut messages = Vec::new();
277
278        if self.inner.hooks.subagent_stop.is_empty() {
279            return Ok(messages);
280        }
281
282        let payload = self
283            .build_subagent_stop_payload(
284                parent_session_id,
285                child_thread_id,
286                agent_name,
287                display_label,
288                background,
289                status,
290                transcript_path,
291            )
292            .await?;
293        let matcher_value = agent_name.to_owned();
294
295        for group in &self.inner.hooks.subagent_stop {
296            if !group.matcher.matches(&matcher_value) {
297                continue;
298            }
299
300            for command in &group.commands {
301                match self.execute_command("SubagentStop", command, &payload).await {
302                    Ok(result) => {
303                        interpret_session_end(command, &result, &mut messages, self.inner.hooks.quiet_success_output)
304                    }
305                    Err(err) => messages
306                        .push(HookMessage::error(format!("SubagentStop hook `{}` failed: {err}", command.command))),
307                }
308            }
309        }
310
311        Ok(messages)
312    }
313
314    /// Execute all `UserPromptSubmit` hooks that match the prompt content.
315    pub async fn run_user_prompt_submit(&self, turn_id: &str, prompt: &str) -> Result<UserPromptHookOutcome> {
316        let mut outcome = UserPromptHookOutcome::default();
317
318        if self.inner.hooks.user_prompt_submit.is_empty() {
319            return Ok(outcome);
320        }
321
322        let payload = self.build_user_prompt_payload(turn_id, prompt).await?;
323
324        for group in &self.inner.hooks.user_prompt_submit {
325            if !group.matcher.matches(prompt) {
326                continue;
327            }
328
329            for command in &group.commands {
330                match self.execute_command("UserPromptSubmit", command, &payload).await {
331                    Ok(result) => {
332                        interpret_user_prompt(command, &result, &mut outcome, self.inner.hooks.quiet_success_output);
333                        if !outcome.allow_prompt {
334                            return Ok(outcome);
335                        }
336                    }
337                    Err(err) => outcome
338                        .messages
339                        .push(HookMessage::error(format!("UserPromptSubmit hook `{}` failed: {err}", command.command))),
340                }
341            }
342        }
343
344        Ok(outcome)
345    }
346
347    /// Execute all `PermissionRequest` hooks that match the tool name.
348    pub async fn run_permission_request(
349        &self,
350        tool_name: &str,
351        tool_input: Option<&Value>,
352        permission_request: &PermissionRequest,
353        permission_suggestions: &[Value],
354    ) -> Result<PermissionRequestHookOutcome> {
355        let mut outcome = PermissionRequestHookOutcome::default();
356
357        if self.inner.hooks.permission_request.is_empty() {
358            return Ok(outcome);
359        }
360
361        let payload = self
362            .build_permission_request_payload(tool_name, tool_input, permission_request, permission_suggestions)
363            .await?;
364
365        for group in &self.inner.hooks.permission_request {
366            if !group.matcher.matches(tool_name) {
367                continue;
368            }
369
370            for command in &group.commands {
371                match self.execute_command("PermissionRequest", command, &payload).await {
372                    Ok(result) => {
373                        interpret_permission_request(
374                            command,
375                            &result,
376                            &mut outcome,
377                            self.inner.hooks.quiet_success_output,
378                        );
379                        if outcome.decision.is_some() {
380                            return Ok(outcome);
381                        }
382                    }
383                    Err(err) => outcome.messages.push(HookMessage::error(format!(
384                        "PermissionRequest hook `{}` failed: {err}",
385                        command.command
386                    ))),
387                }
388            }
389        }
390
391        Ok(outcome)
392    }
393
394    /// Execute all `PreToolUse` hooks that match the tool name.
395    ///
396    /// Hooks run in configuration order. When a hook returns
397    /// `hookSpecificOutput.updatedInput`, later hooks receive the rewritten
398    /// tool input in their payload, so policy hooks placed after rewrite
399    /// hooks observe the final command. The first Allow/Deny decision still
400    /// short-circuits the remaining hooks.
401    pub async fn run_pre_tool_use(
402        &self,
403        tool_name: &str,
404        tool_input: Option<&Value>,
405        tool_call_id: Option<&str>,
406    ) -> Result<PreToolHookOutcome> {
407        let mut outcome = PreToolHookOutcome::default();
408
409        if self.inner.hooks.pre_tool_use.is_empty() {
410            return Ok(outcome);
411        }
412
413        let mut payload = self.build_pre_tool_payload(tool_name, tool_input, tool_call_id).await?;
414
415        for group in &self.inner.hooks.pre_tool_use {
416            if !group.matcher.matches(tool_name) {
417                continue;
418            }
419
420            for command in &group.commands {
421                match self.execute_command("PreToolUse", command, &payload).await {
422                    Ok(result) => {
423                        interpret_pre_tool(command, &result, &mut outcome, self.inner.hooks.quiet_success_output);
424                        if let Some(updated) = outcome.updated_input.take() {
425                            outcome.updated_input = Some(updated.clone());
426                            if let Some(payload_obj) = payload.as_object_mut() {
427                                payload_obj.insert("tool_input".to_string(), updated);
428                            }
429                        }
430                        match outcome.decision {
431                            PreToolHookDecision::Allow | PreToolHookDecision::Deny => {
432                                return Ok(outcome);
433                            }
434                            _ => {}
435                        }
436                    }
437                    Err(err) => outcome
438                        .messages
439                        .push(HookMessage::error(format!("PreToolUse hook `{}` failed: {err}", command.command))),
440                }
441            }
442        }
443
444        Ok(outcome)
445    }
446
447    /// Execute all `PostToolUse` hooks that match the tool name.
448    pub async fn run_post_tool_use(
449        &self,
450        tool_name: &str,
451        tool_input: Option<&Value>,
452        tool_output: &Value,
453        tool_call_id: Option<&str>,
454    ) -> Result<PostToolHookOutcome> {
455        let mut outcome = PostToolHookOutcome::default();
456
457        if self.inner.hooks.post_tool_use.is_empty() {
458            return Ok(outcome);
459        }
460
461        let payload = self
462            .build_post_tool_payload(tool_name, tool_input, tool_output, tool_call_id)
463            .await?;
464
465        for group in &self.inner.hooks.post_tool_use {
466            if !group.matcher.matches(tool_name) {
467                continue;
468            }
469
470            for command in &group.commands {
471                match self.execute_command("PostToolUse", command, &payload).await {
472                    Ok(result) => {
473                        interpret_post_tool(command, &result, &mut outcome, self.inner.hooks.quiet_success_output)
474                    }
475                    Err(err) => outcome
476                        .messages
477                        .push(HookMessage::error(format!("PostToolUse hook `{}` failed: {err}", command.command))),
478                }
479            }
480        }
481
482        Ok(outcome)
483    }
484
485    /// Execute all `PreCompact` hooks that match the compaction trigger.
486    pub async fn run_pre_compact(
487        &self,
488        trigger: CompactionTrigger,
489        mode: CompactionMode,
490        original_message_count: usize,
491        compacted_message_count: usize,
492        history_artifact_path: Option<&str>,
493    ) -> Result<PreCompactHookOutcome> {
494        let mut outcome = PreCompactHookOutcome::default();
495
496        if self.inner.hooks.pre_compact.is_empty() {
497            return Ok(outcome);
498        }
499
500        let payload = self
501            .build_pre_compact_payload(
502                trigger,
503                mode,
504                original_message_count,
505                compacted_message_count,
506                history_artifact_path,
507            )
508            .await?;
509        let trigger_value = trigger.as_str().to_owned();
510
511        for group in &self.inner.hooks.pre_compact {
512            if !group.matcher.matches(&trigger_value) {
513                continue;
514            }
515
516            for command in &group.commands {
517                match self.execute_command("PreCompact", command, &payload).await {
518                    Ok(result) => {
519                        interpret_session_end(
520                            command,
521                            &result,
522                            &mut outcome.messages,
523                            self.inner.hooks.quiet_success_output,
524                        );
525                    }
526                    Err(err) => outcome
527                        .messages
528                        .push(HookMessage::error(format!("PreCompact hook `{}` failed: {err}", command.command))),
529                }
530            }
531        }
532
533        Ok(outcome)
534    }
535
536    /// Execute all `Notification` hooks that match the notification type.
537    pub async fn run_notification(
538        &self,
539        notification_type: NotificationHookType,
540        title: &str,
541        message: &str,
542    ) -> Result<Vec<HookMessage>> {
543        let mut messages = Vec::new();
544
545        if self.inner.hooks.notification.is_empty() {
546            return Ok(messages);
547        }
548
549        let payload = self.build_notification_payload(notification_type, title, message).await?;
550        let matcher_value = notification_type.as_str().to_owned();
551
552        for group in &self.inner.hooks.notification {
553            if !group.matcher.matches(&matcher_value) {
554                continue;
555            }
556
557            for command in &group.commands {
558                match self.execute_command("Notification", command, &payload).await {
559                    Ok(result) => {
560                        interpret_session_end(command, &result, &mut messages, self.inner.hooks.quiet_success_output)
561                    }
562                    Err(err) => messages
563                        .push(HookMessage::error(format!("Notification hook `{}` failed: {err}", command.command))),
564                }
565            }
566        }
567
568        Ok(messages)
569    }
570
571    /// Execute all `Stop` hooks.
572    pub async fn run_stop(&self, last_assistant_message: &str, stop_hook_active: bool) -> Result<StopHookOutcome> {
573        let mut outcome = StopHookOutcome::default();
574
575        if self.inner.hooks.stop.is_empty() {
576            return Ok(outcome);
577        }
578
579        let payload = self.build_stop_payload(last_assistant_message, stop_hook_active).await?;
580
581        for group in &self.inner.hooks.stop {
582            if !group.matcher.matches("stop") {
583                continue;
584            }
585
586            for command in &group.commands {
587                match self.execute_command("Stop", command, &payload).await {
588                    Ok(result) => {
589                        interpret_stop(command, &result, &mut outcome, self.inner.hooks.quiet_success_output);
590                        if outcome.block_reason.is_some() {
591                            return Ok(outcome);
592                        }
593                    }
594                    Err(err) => outcome
595                        .messages
596                        .push(HookMessage::error(format!("Stop hook `{}` failed: {err}", command.command))),
597                }
598            }
599        }
600
601        Ok(outcome)
602    }
603
604    /// Update the transcript path that hooks can access via the `VT_TRANSCRIPT_PATH` env var.
605    pub async fn update_transcript_path(&self, path: Option<PathBuf>) {
606        let mut state = self.inner.state.lock().await;
607        state.transcript_path = path;
608    }
609
610    /// Return the current transcript path, if set.
611    pub async fn transcript_path(&self) -> Option<PathBuf> {
612        let state = self.inner.state.lock().await;
613        state.transcript_path.clone()
614    }
615
616    /// Whether the workspace approval gate is active for this engine.
617    pub fn workspace_gated(&self) -> bool {
618        self.inner.workspace_gated
619    }
620
621    /// Digest of the exact lifecycle command set this engine will execute.
622    /// Approvals are bound to this digest and revalidated before every spawn.
623    pub fn command_digest(&self) -> &str {
624        &self.inner.command_digest
625    }
626
627    /// Every lifecycle command this engine will execute, with its canonical
628    /// event key — the exact set an approval covers.
629    pub fn command_previews(&self) -> Vec<LifecycleHookCommandPreview> {
630        let mut previews = Vec::new();
631        self.inner.hooks.for_each_command(|event, matcher, command| {
632            previews.push(LifecycleHookCommandPreview {
633                event,
634                matcher: matcher.map(str::to_string),
635                command: command.command.clone(),
636                timeout_seconds: command.timeout_seconds,
637            });
638        });
639        previews
640    }
641
642    /// Mark this engine's exact command set as approved for the session.
643    /// Only a digest equal to `command_digest()` satisfies the gate.
644    pub async fn approve_workspace_hooks(&self) {
645        let mut state = self.inner.state.lock().await;
646        state.approved_workspace_digest = Some(self.inner.command_digest.clone());
647    }
648
649    /// Whether the gate is active and the current command set is not yet
650    /// approved. The binary prompts the user before the first lifecycle run
651    /// when this is true.
652    pub async fn workspace_hooks_need_approval(&self) -> bool {
653        if !self.inner.workspace_gated {
654            return false;
655        }
656        let state = self.inner.state.lock().await;
657        state.approved_workspace_digest.as_deref() != Some(self.inner.command_digest.as_str())
658    }
659
660    /// Fail-closed gate: when workspace-controlled hook content is present,
661    /// the engine refuses to spawn any lifecycle command until its exact
662    /// command set has been approved.
663    async fn workspace_approval_granted(&self) -> bool {
664        if !self.inner.workspace_gated {
665            return true;
666        }
667        let state = self.inner.state.lock().await;
668        state.approved_workspace_digest.as_deref() == Some(self.inner.command_digest.as_str())
669    }
670
671    async fn execute_command(
672        &self,
673        event_name: &str,
674        command: &HookCommandConfig,
675        payload: &Value,
676    ) -> Result<HookCommandResult> {
677        if !self.workspace_approval_granted().await {
678            return Err(anyhow::anyhow!(
679                "skipped: the workspace configuration defines lifecycle hooks that are not approved for this workspace. \
680                 Approve workspace lifecycle hooks at session start to enable `{}` (event: {event_name}).",
681                command.command
682            ));
683        }
684
685        let mut process = Command::new("sh");
686        process.arg("-c").arg(&command.command);
687        process.current_dir(&self.inner.workspace);
688        process.stdin(Stdio::piped());
689        process.stdout(Stdio::piped());
690        process.stderr(Stdio::piped());
691        process.kill_on_drop(true);
692        // Own process group (PGID == PID) on Unix so timeout/abort kills reach
693        // shell grandchildren via killpg, not just the direct `sh` child.
694        #[cfg(unix)]
695        process.process_group(0);
696
697        let workspace_str = self.inner.workspace.to_string_lossy().into_owned();
698        process.env("VT_PROJECT_DIR", &workspace_str);
699        process.env("CLAUDE_PROJECT_DIR", &workspace_str);
700        process.env("VT_SESSION_ID", &self.inner.session_id);
701        process.env("CLAUDE_SESSION_ID", &self.inner.session_id);
702        process.env("VT_HOOK_EVENT", event_name);
703
704        if let Some(transcript_path) = self.current_transcript_path().await {
705            process.env("VT_TRANSCRIPT_PATH", &transcript_path);
706            process.env("CLAUDE_TRANSCRIPT_PATH", &transcript_path);
707        }
708
709        let mut child = process
710            .spawn()
711            .with_context(|| format!("failed to spawn lifecycle hook `{}`", command.command))?;
712        #[cfg(unix)]
713        let mut group_guard = HookProcessGroupGuard::new(child.id());
714
715        if let Some(mut stdin) = child.stdin.take() {
716            let mut payload_bytes =
717                serde_json::to_vec(payload).context("failed to serialize lifecycle hook payload")?;
718            payload_bytes.push(b'\n');
719            stdin
720                .write_all(&payload_bytes)
721                .await
722                .context("failed to write lifecycle hook payload")?;
723            stdin.shutdown().await.context("failed to close lifecycle hook stdin")?;
724        }
725
726        let mut stdout_pipe = child.stdout.take().context("lifecycle hook missing stdout pipe")?;
727        let mut stderr_pipe = child.stderr.take().context("lifecycle hook missing stderr pipe")?;
728
729        let stdout_task = tokio::spawn(async move {
730            let mut buffer = Vec::new();
731            stdout_pipe.read_to_end(&mut buffer).await.map(|_| buffer)
732        });
733        let stderr_task = tokio::spawn(async move {
734            let mut buffer = Vec::new();
735            stderr_pipe.read_to_end(&mut buffer).await.map(|_| buffer)
736        });
737
738        let timeout_secs = command.timeout_seconds.unwrap_or(DEFAULT_TIMEOUT_SECS).max(1);
739        let wait_result = time::timeout(Duration::from_secs(timeout_secs), child.wait()).await;
740
741        let (exit_code, timed_out) = match wait_result {
742            Ok(status_res) => {
743                let status = status_res.context("failed to wait for lifecycle hook")?;
744                #[cfg(unix)]
745                group_guard.disarm();
746                (status.code(), false)
747            }
748            Err(_) => {
749                #[cfg(unix)]
750                group_guard.kill();
751                #[cfg(not(unix))]
752                let _ = child.start_kill();
753                let _ = child.wait().await;
754                (None, true)
755            }
756        };
757
758        // After a timeout the group kill should close every writer, but a
759        // setsid-escaped descendant can still hold a pipe open — bound the
760        // drain so a hook can never stall the lifecycle engine.
761        let stdout_bytes = if timed_out {
762            match time::timeout(HOOK_POST_KILL_DRAIN_TIMEOUT, stdout_task).await {
763                Ok(result) => result.unwrap_or_else(|_| Ok(Vec::new())).unwrap_or_default(),
764                Err(_) => Vec::new(),
765            }
766        } else {
767            stdout_task.await.unwrap_or_else(|_| Ok(Vec::new())).unwrap_or_default()
768        };
769        let stderr_bytes = if timed_out {
770            match time::timeout(HOOK_POST_KILL_DRAIN_TIMEOUT, stderr_task).await {
771                Ok(result) => result.unwrap_or_else(|_| Ok(Vec::new())).unwrap_or_default(),
772                Err(_) => Vec::new(),
773            }
774        } else {
775            stderr_task.await.unwrap_or_else(|_| Ok(Vec::new())).unwrap_or_default()
776        };
777
778        Ok(HookCommandResult {
779            exit_code,
780            stdout: String::from_utf8_lossy(&stdout_bytes).into_owned(),
781            stderr: String::from_utf8_lossy(&stderr_bytes).into_owned(),
782            timed_out,
783            timeout_seconds: timeout_secs,
784        })
785    }
786
787    async fn current_transcript_path(&self) -> Option<String> {
788        let state = self.inner.state.lock().await;
789        state.transcript_path.as_ref().and_then(|path| path_to_string(path))
790    }
791}
792
793struct LifecycleHookInner {
794    workspace: PathBuf,
795    session_id: String,
796    trigger: SessionStartTrigger,
797    hooks: CompiledLifecycleHooks,
798    workspace_gated: bool,
799    command_digest: String,
800    state: Mutex<LifecycleHookState>,
801}
802
803struct LifecycleHookState {
804    transcript_path: Option<PathBuf>,
805    approved_workspace_digest: Option<String>,
806}
807
808/// A lifecycle hook command exactly as the engine will execute it, with its
809/// canonical snake_case event key. Displayed to the user so an approval covers
810/// the precise command set.
811#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
812pub struct LifecycleHookCommandPreview {
813    /// Canonical event key, e.g. `session_start`.
814    pub event: &'static str,
815    /// Optional regex matcher of the containing group.
816    pub matcher: Option<String>,
817    /// The shell command string executed via `sh -c`.
818    pub command: String,
819    /// Optional execution timeout in seconds.
820    pub timeout_seconds: Option<u64>,
821}
822
823/// Stable digest over the engine's exact compiled command set. Deterministic
824/// across processes so approvals can be persisted and revalidated. Commands
825/// are serialized as JSON lines (length-safe, no delimiter ambiguity) and
826/// hashed with SHA-256, matching the codebase's config-fingerprint approach
827/// (collision-resistant; a crafted command set cannot collide with an
828/// approved one).
829fn commands_digest(hooks: &CompiledLifecycleHooks) -> String {
830    let mut lines: Vec<String> = Vec::new();
831    hooks.for_each_command(|event, matcher, command| {
832        let entry = LifecycleHookCommandPreview {
833            event,
834            matcher: matcher.map(str::to_string),
835            command: command.command.clone(),
836            timeout_seconds: command.timeout_seconds,
837        };
838        if let Ok(line) = serde_json::to_string(&entry) {
839            lines.push(line);
840        }
841    });
842    lines.sort();
843    vtcode_commons::utils::calculate_sha256(lines.join("\n").as_bytes())
844}
845
846/// Restore a persisted workspace lifecycle-hook approval onto a freshly built
847/// engine. The persisted record only applies when its digest still matches the
848/// engine's exact command set; any configuration change since approval leaves
849/// the engine fail-closed.
850pub async fn restore_workspace_hook_approval(engine: &LifecycleHookEngine, workspace: &std::path::Path) {
851    if !engine.workspace_gated() {
852        return;
853    }
854    let digest = engine.command_digest().to_string();
855    let Ok(Some(record)) = load_lifecycle_hook_approval(workspace).await else {
856        return;
857    };
858    if record.config_digest == digest {
859        engine.approve_workspace_hooks().await;
860    }
861}
862
863/// Carry an in-memory approval from a previous engine onto a rebuilt engine
864/// (primary-agent switch or config reload), falling back to the persisted
865/// record. A session-only approval that could not be persisted (e.g. dot-config
866/// write failure) survives the rebuild while the command set is unchanged,
867/// instead of being silently dropped mid-session. Fails closed in every other
868/// case: a changed command set, a previously unapproved engine, or a gated
869/// engine with no matching persisted record leaves the rebuilt engine gated.
870pub async fn carry_or_restore_workspace_hook_approval(
871    previous: Option<&LifecycleHookEngine>,
872    next: &LifecycleHookEngine,
873    workspace: &std::path::Path,
874) {
875    let previous_approved_same_set = match previous {
876        Some(prev) => {
877            prev.workspace_gated()
878                && prev.command_digest() == next.command_digest()
879                && !prev.workspace_hooks_need_approval().await
880        }
881        None => false,
882    };
883    if previous_approved_same_set {
884        next.approve_workspace_hooks().await;
885    } else {
886        restore_workspace_hook_approval(next, workspace).await;
887    }
888}