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