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