Skip to main content

tracevault_cli/commands/
session_hooks.rs

1//! Shared helpers for the SessionStart / UserPromptSubmit hook commands
2//! (sub-plan C): the Claude Code hook-output JSON shape for injecting context,
3//! the pure decision logic for when to inject, and the shared
4//! resolve-binding-then-inject flow used by both hook commands.
5
6use std::io::Read as _;
7use std::path::Path;
8
9use serde::Serialize;
10
11use tracevault_protocol::hooks::{parse_hook_event, HookEvent};
12
13use crate::api_client::ApiClient;
14use crate::credentials::resolve_credentials;
15use crate::resolution::{binding_from_config, effective_binding, ResolveInputs};
16
17/// Claude Code hook output. Field names are camelCase to match CC's contract
18/// (the shared protocol `HookResponse` is snake_case and server-facing; this is
19/// the CLI-local shape used only for hook stdout).
20#[derive(Debug, Serialize)]
21pub struct HookOutput {
22    #[serde(rename = "hookSpecificOutput", skip_serializing_if = "Option::is_none")]
23    pub hook_specific_output: Option<HookSpecificOutput>,
24    #[serde(rename = "continue", skip_serializing_if = "Option::is_none")]
25    pub cont: Option<bool>,
26    #[serde(rename = "suppressOutput", skip_serializing_if = "Option::is_none")]
27    pub suppress_output: Option<bool>,
28    /// A message Claude Code shows the user (not the model).
29    #[serde(rename = "systemMessage", skip_serializing_if = "Option::is_none")]
30    pub system_message: Option<String>,
31}
32
33#[derive(Debug, Serialize)]
34pub struct HookSpecificOutput {
35    #[serde(rename = "hookEventName")]
36    pub hook_event_name: String,
37    #[serde(rename = "additionalContext")]
38    pub additional_context: String,
39}
40
41impl HookOutput {
42    /// Minimal allow/quiet response with no injected context.
43    pub fn allow() -> Self {
44        Self {
45            hook_specific_output: None,
46            cont: None,
47            suppress_output: Some(true),
48            system_message: None,
49        }
50    }
51    /// Allow + inject `context` under the given hook event name.
52    pub fn with_context(event: &str, context: String) -> Self {
53        Self {
54            hook_specific_output: Some(HookSpecificOutput {
55                hook_event_name: event.to_string(),
56                additional_context: context,
57            }),
58            cont: None,
59            suppress_output: Some(true),
60            system_message: None,
61        }
62    }
63}
64
65/// How long `resolve_and_inject` may spend on the network, kept under the
66/// hooks' 10 s timeout: a hook killed at its timeout prints no allow response.
67const HOOK_BUDGET: std::time::Duration = std::time::Duration::from_secs(8);
68
69/// Maximum additionalContext size (CC guidance). Larger → truncated.
70const MAX_CONTEXT: usize = 10_000;
71
72/// How much of an oversize policy text to keep before appending the
73/// truncation suffix. Chosen so `HEAD_LEN` + the suffix stays under
74/// `MAX_CONTEXT`.
75const HEAD_LEN: usize = 9_500;
76
77/// Cap injected context. Oversize policy text is truncated to its first
78/// `HEAD_LEN` chars with a suffix pointing at `tracevault repo status` —
79/// unlike `tracevault agent-policies`, `repo status` works in workspace mode
80/// (no `.tracevault/config.toml` required), so the fallback is reachable in
81/// every install mode.
82pub fn cap_context(s: String) -> String {
83    if s.chars().count() > MAX_CONTEXT {
84        let head: String = s.chars().take(HEAD_LEN).collect();
85        format!("{head}\n\n…(truncated; run `tracevault repo status` to see full policies)")
86    } else {
87        s
88    }
89}
90
91/// Whether to inject policies for this hook event.
92/// - SessionStart: inject whenever a repo is bound (refresh context at start/resume).
93/// - UserPromptSubmit: inject only when the effective repo changed since last injection.
94/// - other events: never.
95pub fn should_inject(
96    event: &str,
97    effective_repo_id: Option<&str>,
98    last_injected: Option<&str>,
99) -> bool {
100    match event {
101        "SessionStart" => effective_repo_id.is_some(),
102        "UserPromptSubmit" => effective_repo_id.is_some() && effective_repo_id != last_injected,
103        _ => false,
104    }
105}
106
107/// Print the minimal allow/quiet `HookOutput` and return `Ok(())`. Shared by
108/// every hook command's error paths — a hook must always emit valid JSON,
109/// even (especially) when something upstream failed.
110pub(crate) fn print_allow() -> Result<(), Box<dyn std::error::Error>> {
111    print_allow_with(None)
112}
113
114/// [`print_allow`], showing the user `notice` if there is one.
115fn print_allow_with(notice: Option<String>) -> Result<(), Box<dyn std::error::Error>> {
116    let output = HookOutput {
117        system_message: notice,
118        ..HookOutput::allow()
119    };
120    println!("{}", serde_json::to_string(&output)?);
121    Ok(())
122}
123
124/// Read stdin, parse it as a `HookEvent`, and return it. On any read or parse
125/// error, print the allow response (never fail the hook) and return `None`.
126/// Shared by `session-start` and `user-prompt`, whose `run()` bodies both
127/// start with "read the hook event or bail out allowing".
128pub(crate) fn read_hook_event_or_allow() -> Option<HookEvent> {
129    let mut input = String::new();
130    if std::io::stdin().read_to_string(&mut input).is_err() {
131        let _ = print_allow();
132        return None;
133    }
134    match parse_hook_event(&input) {
135        Ok(e) => Some(e),
136        Err(_) => {
137            let _ = print_allow();
138            None
139        }
140    }
141}
142
143/// Fetch rendered policies and build the injection output; `None` on ANY
144/// error (best-effort — a fetch failure degrades to allow, never blocks the
145/// hook). Factored out of `resolve_and_inject` so the network step can be
146/// exercised in a unit test without touching creds/env/git.
147async fn fetch_context(client: &ApiClient, event: &str, repo_id: uuid::Uuid) -> Option<HookOutput> {
148    let resp = client.get_agent_instructions(&repo_id).await.ok()?;
149    Some(HookOutput::with_context(event, cap_context(resp.content)))
150}
151
152/// Resolve the session's effective binding (auto-binding an unbound session
153/// from its checkout's remote, whose "not registered" notice goes to the user
154/// as `systemMessage`) and, if `should_inject(event, ...)`, best-effort fetch + print policies as `additionalContext` and persist
155/// `last_injected_repo`. Always prints a valid `HookOutput`; never hard-fails.
156///
157/// Shared by `session-start` and `user-prompt`: both need the same
158/// resolve-binding → decide → fetch-and-inject flow, differing only in which
159/// hook-specific steps happen around it (SessionStart also writes the session
160/// env file, which stays in `session_start.rs`). `notice` is a message for the
161/// user from that hook-specific part (the upgrade step's, VIS-1109); it is
162/// shown whatever this flow decides.
163pub async fn resolve_and_inject(
164    hook_event: &HookEvent,
165    notice: Option<String>,
166) -> Result<(), Box<dyn std::error::Error>> {
167    let deadline = std::time::Instant::now() + HOOK_BUDGET;
168    let event = hook_event.hook_event_name.as_str();
169    let hook_cwd = Path::new(&hook_event.cwd);
170    let project_root = crate::paths::resolve_project_root(hook_cwd).root;
171    let session = crate::session_state::load(&hook_event.session_id);
172    let worktree = crate::paths::worktree_toplevel(hook_cwd);
173    let config = crate::config::TracevaultConfig::load(&project_root);
174    let bound = config.as_ref().and_then(binding_from_config);
175    let config_project = config
176        .as_ref()
177        .and_then(crate::resolution::project_from_config);
178    let user_default = crate::user_default::load();
179    let mut binding = effective_binding(ResolveInputs {
180        repo_flag: None,
181        session: &session,
182        worktree_path: Some(&worktree),
183        bound,
184        user_default,
185    })
186    .map(|(b, _)| b);
187
188    // Nothing binds the session: bind it to the repo of the checkout it runs
189    // in, if the server knows that checkout's remote (VIS-1048). A session
190    // bound to a project is not bound to a repo at all: the repo of the
191    // checkout it is in now is inferred, within the project, for its policies
192    // here as for its events (VIS-1258) — a binding stored now would pin the
193    // rest of the session to this checkout's repo wherever it goes next.
194    let mut notice = notice;
195    if binding.is_none() {
196        if let Ok((Some(server_url), credential)) =
197            crate::credentials::resolve_credentials_quiet(&project_root)
198        {
199            let client = ApiClient::with_credential(&server_url, credential);
200            let project =
201                crate::commands::stream::capture_project(&session, Some(&worktree), config_project);
202            match crate::commands::stream::inference_project(None, project) {
203                Some(pid) => {
204                    binding = crate::inferred_repo::infer(
205                        &hook_event.session_id,
206                        &worktree,
207                        pid,
208                        &client,
209                        deadline,
210                    )
211                    .await;
212                }
213                None => {
214                    let auto = crate::auto_bind::bind_session(
215                        &hook_event.session_id,
216                        hook_cwd,
217                        &client,
218                        deadline,
219                    )
220                    .await;
221                    binding = auto.binding;
222                    notice = match (notice, auto.notice) {
223                        (Some(a), Some(b)) => Some(format!("{a}\n{b}")),
224                        (a, b) => a.or(b),
225                    };
226                }
227            }
228        }
229    }
230
231    if !should_inject(
232        event,
233        binding.as_ref().map(|b| b.repo_id.as_str()),
234        session.last_injected_repo.as_deref(),
235    ) {
236        return print_allow_with(notice);
237    }
238    // `should_inject` returning true requires `effective_repo_id.is_some()`, so
239    // `binding` is always `Some` here.
240    let Some(binding) = binding else {
241        return print_allow_with(notice);
242    };
243
244    let Ok(repo_uuid) = binding.repo_id.parse::<uuid::Uuid>() else {
245        // A corrupted/hand-edited session-state or config file could contain a
246        // non-UUID repo_id — skip injection rather than fail the hook.
247        return print_allow_with(notice);
248    };
249
250    // A credential/URL mismatch is a misconfiguration the user has to fix, but
251    // this hook must ALWAYS emit an allow response — failing it would block the
252    // prompt. Report it on stderr (where hook output is surfaced) and skip
253    // injection, exactly as a missing server URL already does.
254    let (server_url, credential) = match resolve_credentials(&project_root) {
255        Ok(resolved) => resolved,
256        Err(e) => {
257            eprintln!("Skipping context injection: {e}");
258            return print_allow_with(notice);
259        }
260    };
261    let Some(server_url) = server_url else {
262        return print_allow_with(notice);
263    };
264    let client = ApiClient::with_credential(&server_url, credential);
265
266    let remaining = deadline.saturating_duration_since(std::time::Instant::now());
267    let fetched = tokio::time::timeout(remaining, fetch_context(&client, event, repo_uuid))
268        .await
269        .ok()
270        .flatten();
271    match fetched {
272        Some(mut output) => {
273            output.system_message = notice;
274            println!("{}", serde_json::to_string(&output)?);
275            // Best-effort: persist the last-injected repo so a later
276            // UserPromptSubmit can avoid redundant re-injection. A save
277            // failure must not turn this into a hook failure. Reload the
278            // session state right before saving (rather than reusing the
279            // snapshot loaded before the network `await` above) so a
280            // concurrent `repo switch`/`reset` that happened during the
281            // fetch isn't silently reverted by this save.
282            let mut fresh = crate::session_state::load(&hook_event.session_id);
283            fresh.last_injected_repo = Some(binding.repo_id.clone());
284            let _ = crate::session_state::save(&hook_event.session_id, &fresh);
285            Ok(())
286        }
287        None => print_allow_with(notice),
288    }
289}
290
291#[cfg(test)]
292mod tests {
293    use super::*;
294
295    // ── should_inject ────────────────────────────────────────────────────
296
297    #[test]
298    fn session_start_injects_when_bound() {
299        assert!(should_inject("SessionStart", Some("repo-1"), None));
300    }
301
302    #[test]
303    fn session_start_skips_when_unbound() {
304        assert!(!should_inject("SessionStart", None, None));
305    }
306
307    #[test]
308    fn session_start_injects_even_if_same_as_last_injected() {
309        // SessionStart always refreshes, regardless of last_injected.
310        assert!(should_inject(
311            "SessionStart",
312            Some("repo-1"),
313            Some("repo-1")
314        ));
315    }
316
317    #[test]
318    fn user_prompt_submit_injects_when_repo_changed() {
319        assert!(should_inject(
320            "UserPromptSubmit",
321            Some("repo-2"),
322            Some("repo-1")
323        ));
324    }
325
326    #[test]
327    fn user_prompt_submit_injects_when_no_prior_injection() {
328        assert!(should_inject("UserPromptSubmit", Some("repo-1"), None));
329    }
330
331    #[test]
332    fn user_prompt_submit_skips_when_repo_unchanged() {
333        assert!(!should_inject(
334            "UserPromptSubmit",
335            Some("repo-1"),
336            Some("repo-1")
337        ));
338    }
339
340    #[test]
341    fn user_prompt_submit_skips_when_unbound() {
342        assert!(!should_inject("UserPromptSubmit", None, None));
343        assert!(!should_inject("UserPromptSubmit", None, Some("repo-1")));
344    }
345
346    #[test]
347    fn unknown_event_never_injects() {
348        assert!(!should_inject("SomeOtherEvent", Some("repo-1"), None));
349        assert!(!should_inject("SomeOtherEvent", None, None));
350    }
351
352    // ── cap_context ──────────────────────────────────────────────────────
353
354    #[test]
355    fn cap_context_leaves_short_string_unchanged() {
356        let s = "short policy text".to_string();
357        assert_eq!(cap_context(s.clone()), s);
358    }
359
360    #[test]
361    fn cap_context_truncates_oversize_string_and_points_at_repo_status() {
362        let s = "a".repeat(MAX_CONTEXT + 1);
363        let capped = cap_context(s.clone());
364        // Head is preserved (truncated policy text is still useful context)…
365        assert!(capped.starts_with(&"a".repeat(HEAD_LEN)));
366        // …and the fallback points at a command that works without
367        // `.tracevault/config.toml` (workspace mode), unlike
368        // `tracevault agent-policies`.
369        assert!(capped.contains("tracevault repo status"));
370        assert!(!capped.contains("agent-policies"));
371        assert!(capped.chars().count() <= MAX_CONTEXT);
372    }
373
374    #[test]
375    fn cap_context_allows_exactly_max_context() {
376        let s = "a".repeat(MAX_CONTEXT);
377        assert_eq!(cap_context(s.clone()), s);
378    }
379
380    // ── HookOutput serialization ─────────────────────────────────────────
381
382    #[test]
383    fn with_context_serializes_expected_shape() {
384        let out = HookOutput::with_context("SessionStart", "x".to_string());
385        let json = serde_json::to_string(&out).unwrap();
386        assert!(json.contains("\"hookSpecificOutput\""));
387        assert!(json.contains("\"hookEventName\":\"SessionStart\""));
388        assert!(json.contains("\"additionalContext\":\"x\""));
389    }
390
391    #[test]
392    fn a_notice_serializes_as_system_message() {
393        let out = HookOutput {
394            system_message: Some("not recorded".into()),
395            ..HookOutput::allow()
396        };
397        let json = serde_json::to_string(&out).unwrap();
398        assert!(json.contains("\"systemMessage\":\"not recorded\""));
399        assert!(!serde_json::to_string(&HookOutput::allow())
400            .unwrap()
401            .contains("systemMessage"));
402    }
403
404    #[test]
405    fn allow_serializes_without_hook_specific_output() {
406        let out = HookOutput::allow();
407        let json = serde_json::to_string(&out).unwrap();
408        assert!(!json.contains("hookSpecificOutput"));
409        assert!(json.contains("\"suppressOutput\":true"));
410    }
411
412    // ── resolve_and_inject ───────────────────────────────────────────────
413    //
414    // `resolve_and_inject` is network/IO-bound, so coverage here stays thin:
415    // this exercises the no-binding path (empty session state, no
416    // `.tracevault/config.toml`, non-git cwd), which `should_inject` already
417    // proves resolves to "don't inject" — so this must return `Ok(())`
418    // without ever reaching the network. No env mutation: `cwd` is an
419    // isolated tempdir and the session id is unique to this test.
420
421    #[tokio::test]
422    async fn resolve_and_inject_allows_when_no_binding() {
423        let tmp = tempfile::tempdir().unwrap();
424        let hook_event = HookEvent {
425            session_id: "resolve-and-inject-no-binding-test".to_string(),
426            transcript_path: "t".to_string(),
427            cwd: tmp.path().to_string_lossy().into_owned(),
428            permission_mode: None,
429            hook_event_name: "UserPromptSubmit".to_string(),
430            tool_name: None,
431            tool_input: None,
432            tool_response: None,
433            tool_use_id: None,
434            source: None,
435            transcript_records: None,
436        };
437
438        let result = resolve_and_inject(&hook_event, None).await;
439        assert!(result.is_ok());
440    }
441
442    // ── fetch_context ────────────────────────────────────────────────────
443    //
444    // `resolve_and_inject` can't be unit-tested end-to-end without real
445    // creds/env/git, but the network step it delegates to (`fetch_context`)
446    // can be: point an `ApiClient` at a port nothing listens on so the
447    // request fails fast with connection-refused, and assert the failure
448    // degrades to `None` (→ `print_allow()` in the caller) rather than
449    // propagating an error. This proves the hook never blocks on a fetch
450    // failure.
451
452    #[tokio::test]
453    async fn fetch_context_returns_none_on_network_failure() {
454        let client = ApiClient::new("http://127.0.0.1:1", None);
455        let repo_id = uuid::Uuid::new_v4();
456        let result = fetch_context(&client, "SessionStart", repo_id).await;
457        assert!(result.is_none());
458    }
459}