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}
29
30#[derive(Debug, Serialize)]
31pub struct HookSpecificOutput {
32    #[serde(rename = "hookEventName")]
33    pub hook_event_name: String,
34    #[serde(rename = "additionalContext")]
35    pub additional_context: String,
36}
37
38impl HookOutput {
39    /// Minimal allow/quiet response with no injected context.
40    pub fn allow() -> Self {
41        Self {
42            hook_specific_output: None,
43            cont: None,
44            suppress_output: Some(true),
45        }
46    }
47    /// Allow + inject `context` under the given hook event name.
48    pub fn with_context(event: &str, context: String) -> Self {
49        Self {
50            hook_specific_output: Some(HookSpecificOutput {
51                hook_event_name: event.to_string(),
52                additional_context: context,
53            }),
54            cont: None,
55            suppress_output: Some(true),
56        }
57    }
58}
59
60/// Maximum additionalContext size (CC guidance). Larger → truncated.
61const MAX_CONTEXT: usize = 10_000;
62
63/// How much of an oversize policy text to keep before appending the
64/// truncation suffix. Chosen so `HEAD_LEN` + the suffix stays under
65/// `MAX_CONTEXT`.
66const HEAD_LEN: usize = 9_500;
67
68/// Cap injected context. Oversize policy text is truncated to its first
69/// `HEAD_LEN` chars with a suffix pointing at `tracevault repo status` —
70/// unlike `tracevault agent-policies`, `repo status` works in workspace mode
71/// (no `.tracevault/config.toml` required), so the fallback is reachable in
72/// every install mode.
73pub fn cap_context(s: String) -> String {
74    if s.chars().count() > MAX_CONTEXT {
75        let head: String = s.chars().take(HEAD_LEN).collect();
76        format!("{head}\n\n…(truncated; run `tracevault repo status` to see full policies)")
77    } else {
78        s
79    }
80}
81
82/// Whether to inject policies for this hook event.
83/// - SessionStart: inject whenever a repo is bound (refresh context at start/resume).
84/// - UserPromptSubmit: inject only when the effective repo changed since last injection.
85/// - other events: never.
86pub fn should_inject(
87    event: &str,
88    effective_repo_id: Option<&str>,
89    last_injected: Option<&str>,
90) -> bool {
91    match event {
92        "SessionStart" => effective_repo_id.is_some(),
93        "UserPromptSubmit" => effective_repo_id.is_some() && effective_repo_id != last_injected,
94        _ => false,
95    }
96}
97
98/// Print the minimal allow/quiet `HookOutput` and return `Ok(())`. Shared by
99/// every hook command's error paths — a hook must always emit valid JSON,
100/// even (especially) when something upstream failed.
101pub(crate) fn print_allow() -> Result<(), Box<dyn std::error::Error>> {
102    println!("{}", serde_json::to_string(&HookOutput::allow())?);
103    Ok(())
104}
105
106/// Read stdin, parse it as a `HookEvent`, and return it. On any read or parse
107/// error, print the allow response (never fail the hook) and return `None`.
108/// Shared by `session-start` and `user-prompt`, whose `run()` bodies both
109/// start with "read the hook event or bail out allowing".
110pub(crate) fn read_hook_event_or_allow() -> Option<HookEvent> {
111    let mut input = String::new();
112    if std::io::stdin().read_to_string(&mut input).is_err() {
113        let _ = print_allow();
114        return None;
115    }
116    match parse_hook_event(&input) {
117        Ok(e) => Some(e),
118        Err(_) => {
119            let _ = print_allow();
120            None
121        }
122    }
123}
124
125/// Fetch rendered policies and build the injection output; `None` on ANY
126/// error (best-effort — a fetch failure degrades to allow, never blocks the
127/// hook). Factored out of `resolve_and_inject` so the network step can be
128/// exercised in a unit test without touching creds/env/git.
129async fn fetch_context(client: &ApiClient, event: &str, repo_id: uuid::Uuid) -> Option<HookOutput> {
130    let resp = client.get_agent_instructions(&repo_id).await.ok()?;
131    Some(HookOutput::with_context(event, cap_context(resp.content)))
132}
133
134/// Resolve the session's effective binding and, if `should_inject(event, ...)`,
135/// best-effort fetch + print policies as `additionalContext` and persist
136/// `last_injected_repo`. Always prints a valid `HookOutput`; never hard-fails.
137///
138/// Shared by `session-start` and `user-prompt`: both need the same
139/// resolve-binding → decide → fetch-and-inject flow, differing only in which
140/// hook-specific steps happen around it (SessionStart also writes the session
141/// env file, which stays in `session_start.rs`).
142pub async fn resolve_and_inject(hook_event: &HookEvent) -> Result<(), Box<dyn std::error::Error>> {
143    let event = hook_event.hook_event_name.as_str();
144    let hook_cwd = Path::new(&hook_event.cwd);
145    let project_root = crate::paths::resolve_project_root(hook_cwd).root;
146    let session = crate::session_state::load(&hook_event.session_id);
147    let worktree = crate::paths::worktree_toplevel(hook_cwd);
148    let bound =
149        crate::config::TracevaultConfig::load(&project_root).and_then(|c| binding_from_config(&c));
150    let user_default = crate::user_default::load();
151    let binding = effective_binding(ResolveInputs {
152        repo_flag: None,
153        session: &session,
154        worktree_path: Some(&worktree),
155        bound,
156        user_default,
157    })
158    .map(|(b, _)| b);
159
160    if !should_inject(
161        event,
162        binding.as_ref().map(|b| b.repo_id.as_str()),
163        session.last_injected_repo.as_deref(),
164    ) {
165        return print_allow();
166    }
167    // `should_inject` returning true requires `effective_repo_id.is_some()`, so
168    // `binding` is always `Some` here.
169    let Some(binding) = binding else {
170        return print_allow();
171    };
172
173    let Ok(repo_uuid) = binding.repo_id.parse::<uuid::Uuid>() else {
174        // A corrupted/hand-edited session-state or config file could contain a
175        // non-UUID repo_id — skip injection rather than fail the hook.
176        return print_allow();
177    };
178
179    // A credential/URL mismatch is a misconfiguration the user has to fix, but
180    // this hook must ALWAYS emit an allow response — failing it would block the
181    // prompt. Report it on stderr (where hook output is surfaced) and skip
182    // injection, exactly as a missing server URL already does.
183    let (server_url, credential) = match resolve_credentials(&project_root) {
184        Ok(resolved) => resolved,
185        Err(e) => {
186            eprintln!("Skipping context injection: {e}");
187            return print_allow();
188        }
189    };
190    let Some(server_url) = server_url else {
191        return print_allow();
192    };
193    let client = ApiClient::with_credential(&server_url, credential);
194
195    match fetch_context(&client, event, repo_uuid).await {
196        Some(output) => {
197            println!("{}", serde_json::to_string(&output)?);
198            // Best-effort: persist the last-injected repo so a later
199            // UserPromptSubmit can avoid redundant re-injection. A save
200            // failure must not turn this into a hook failure. Reload the
201            // session state right before saving (rather than reusing the
202            // snapshot loaded before the network `await` above) so a
203            // concurrent `repo switch`/`reset` that happened during the
204            // fetch isn't silently reverted by this save.
205            let mut fresh = crate::session_state::load(&hook_event.session_id);
206            fresh.last_injected_repo = Some(binding.repo_id.clone());
207            let _ = crate::session_state::save(&hook_event.session_id, &fresh);
208            Ok(())
209        }
210        None => print_allow(),
211    }
212}
213
214#[cfg(test)]
215mod tests {
216    use super::*;
217
218    // ── should_inject ────────────────────────────────────────────────────
219
220    #[test]
221    fn session_start_injects_when_bound() {
222        assert!(should_inject("SessionStart", Some("repo-1"), None));
223    }
224
225    #[test]
226    fn session_start_skips_when_unbound() {
227        assert!(!should_inject("SessionStart", None, None));
228    }
229
230    #[test]
231    fn session_start_injects_even_if_same_as_last_injected() {
232        // SessionStart always refreshes, regardless of last_injected.
233        assert!(should_inject(
234            "SessionStart",
235            Some("repo-1"),
236            Some("repo-1")
237        ));
238    }
239
240    #[test]
241    fn user_prompt_submit_injects_when_repo_changed() {
242        assert!(should_inject(
243            "UserPromptSubmit",
244            Some("repo-2"),
245            Some("repo-1")
246        ));
247    }
248
249    #[test]
250    fn user_prompt_submit_injects_when_no_prior_injection() {
251        assert!(should_inject("UserPromptSubmit", Some("repo-1"), None));
252    }
253
254    #[test]
255    fn user_prompt_submit_skips_when_repo_unchanged() {
256        assert!(!should_inject(
257            "UserPromptSubmit",
258            Some("repo-1"),
259            Some("repo-1")
260        ));
261    }
262
263    #[test]
264    fn user_prompt_submit_skips_when_unbound() {
265        assert!(!should_inject("UserPromptSubmit", None, None));
266        assert!(!should_inject("UserPromptSubmit", None, Some("repo-1")));
267    }
268
269    #[test]
270    fn unknown_event_never_injects() {
271        assert!(!should_inject("SomeOtherEvent", Some("repo-1"), None));
272        assert!(!should_inject("SomeOtherEvent", None, None));
273    }
274
275    // ── cap_context ──────────────────────────────────────────────────────
276
277    #[test]
278    fn cap_context_leaves_short_string_unchanged() {
279        let s = "short policy text".to_string();
280        assert_eq!(cap_context(s.clone()), s);
281    }
282
283    #[test]
284    fn cap_context_truncates_oversize_string_and_points_at_repo_status() {
285        let s = "a".repeat(MAX_CONTEXT + 1);
286        let capped = cap_context(s.clone());
287        // Head is preserved (truncated policy text is still useful context)…
288        assert!(capped.starts_with(&"a".repeat(HEAD_LEN)));
289        // …and the fallback points at a command that works without
290        // `.tracevault/config.toml` (workspace mode), unlike
291        // `tracevault agent-policies`.
292        assert!(capped.contains("tracevault repo status"));
293        assert!(!capped.contains("agent-policies"));
294        assert!(capped.chars().count() <= MAX_CONTEXT);
295    }
296
297    #[test]
298    fn cap_context_allows_exactly_max_context() {
299        let s = "a".repeat(MAX_CONTEXT);
300        assert_eq!(cap_context(s.clone()), s);
301    }
302
303    // ── HookOutput serialization ─────────────────────────────────────────
304
305    #[test]
306    fn with_context_serializes_expected_shape() {
307        let out = HookOutput::with_context("SessionStart", "x".to_string());
308        let json = serde_json::to_string(&out).unwrap();
309        assert!(json.contains("\"hookSpecificOutput\""));
310        assert!(json.contains("\"hookEventName\":\"SessionStart\""));
311        assert!(json.contains("\"additionalContext\":\"x\""));
312    }
313
314    #[test]
315    fn allow_serializes_without_hook_specific_output() {
316        let out = HookOutput::allow();
317        let json = serde_json::to_string(&out).unwrap();
318        assert!(!json.contains("hookSpecificOutput"));
319        assert!(json.contains("\"suppressOutput\":true"));
320    }
321
322    // ── resolve_and_inject ───────────────────────────────────────────────
323    //
324    // `resolve_and_inject` is network/IO-bound, so coverage here stays thin:
325    // this exercises the no-binding path (empty session state, no
326    // `.tracevault/config.toml`, non-git cwd), which `should_inject` already
327    // proves resolves to "don't inject" — so this must return `Ok(())`
328    // without ever reaching the network. No env mutation: `cwd` is an
329    // isolated tempdir and the session id is unique to this test.
330
331    #[tokio::test]
332    async fn resolve_and_inject_allows_when_no_binding() {
333        let tmp = tempfile::tempdir().unwrap();
334        let hook_event = HookEvent {
335            session_id: "resolve-and-inject-no-binding-test".to_string(),
336            transcript_path: "t".to_string(),
337            cwd: tmp.path().to_string_lossy().into_owned(),
338            permission_mode: None,
339            hook_event_name: "UserPromptSubmit".to_string(),
340            tool_name: None,
341            tool_input: None,
342            tool_response: None,
343            tool_use_id: None,
344            source: None,
345            transcript_records: None,
346        };
347
348        let result = resolve_and_inject(&hook_event).await;
349        assert!(result.is_ok());
350    }
351
352    // ── fetch_context ────────────────────────────────────────────────────
353    //
354    // `resolve_and_inject` can't be unit-tested end-to-end without real
355    // creds/env/git, but the network step it delegates to (`fetch_context`)
356    // can be: point an `ApiClient` at a port nothing listens on so the
357    // request fails fast with connection-refused, and assert the failure
358    // degrades to `None` (→ `print_allow()` in the caller) rather than
359    // propagating an error. This proves the hook never blocks on a fetch
360    // failure.
361
362    #[tokio::test]
363    async fn fetch_context_returns_none_on_network_failure() {
364        let client = ApiClient::new("http://127.0.0.1:1", None);
365        let repo_id = uuid::Uuid::new_v4();
366        let result = fetch_context(&client, "SessionStart", repo_id).await;
367        assert!(result.is_none());
368    }
369}