1use 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#[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 #[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 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 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
65const HOOK_BUDGET: std::time::Duration = std::time::Duration::from_secs(8);
68
69const MAX_CONTEXT: usize = 10_000;
71
72const HEAD_LEN: usize = 9_500;
76
77pub 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
91pub 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
107pub(crate) fn print_allow() -> Result<(), Box<dyn std::error::Error>> {
111 print_allow_with(None)
112}
113
114fn 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
124pub(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
143async 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
152pub async fn resolve_and_inject(hook_event: &HookEvent) -> Result<(), Box<dyn std::error::Error>> {
162 let deadline = std::time::Instant::now() + HOOK_BUDGET;
163 let event = hook_event.hook_event_name.as_str();
164 let hook_cwd = Path::new(&hook_event.cwd);
165 let project_root = crate::paths::resolve_project_root(hook_cwd).root;
166 let session = crate::session_state::load(&hook_event.session_id);
167 let worktree = crate::paths::worktree_toplevel(hook_cwd);
168 let bound =
169 crate::config::TracevaultConfig::load(&project_root).and_then(|c| binding_from_config(&c));
170 let user_default = crate::user_default::load();
171 let mut binding = effective_binding(ResolveInputs {
172 repo_flag: None,
173 session: &session,
174 worktree_path: Some(&worktree),
175 bound,
176 user_default,
177 })
178 .map(|(b, _)| b);
179
180 let mut notice = None;
183 if binding.is_none() {
184 if let Ok((Some(server_url), credential)) =
185 crate::credentials::resolve_credentials_quiet(&project_root)
186 {
187 let client = ApiClient::with_credential(&server_url, credential);
188 let auto =
189 crate::auto_bind::bind_session(&hook_event.session_id, hook_cwd, &client, deadline)
190 .await;
191 binding = auto.binding;
192 notice = auto.notice;
193 }
194 }
195
196 if !should_inject(
197 event,
198 binding.as_ref().map(|b| b.repo_id.as_str()),
199 session.last_injected_repo.as_deref(),
200 ) {
201 return print_allow_with(notice);
202 }
203 let Some(binding) = binding else {
206 return print_allow();
207 };
208
209 let Ok(repo_uuid) = binding.repo_id.parse::<uuid::Uuid>() else {
210 return print_allow();
213 };
214
215 let (server_url, credential) = match resolve_credentials(&project_root) {
220 Ok(resolved) => resolved,
221 Err(e) => {
222 eprintln!("Skipping context injection: {e}");
223 return print_allow();
224 }
225 };
226 let Some(server_url) = server_url else {
227 return print_allow();
228 };
229 let client = ApiClient::with_credential(&server_url, credential);
230
231 let remaining = deadline.saturating_duration_since(std::time::Instant::now());
232 let fetched = tokio::time::timeout(remaining, fetch_context(&client, event, repo_uuid))
233 .await
234 .ok()
235 .flatten();
236 match fetched {
237 Some(output) => {
238 println!("{}", serde_json::to_string(&output)?);
239 let mut fresh = crate::session_state::load(&hook_event.session_id);
247 fresh.last_injected_repo = Some(binding.repo_id.clone());
248 let _ = crate::session_state::save(&hook_event.session_id, &fresh);
249 Ok(())
250 }
251 None => print_allow(),
252 }
253}
254
255#[cfg(test)]
256mod tests {
257 use super::*;
258
259 #[test]
262 fn session_start_injects_when_bound() {
263 assert!(should_inject("SessionStart", Some("repo-1"), None));
264 }
265
266 #[test]
267 fn session_start_skips_when_unbound() {
268 assert!(!should_inject("SessionStart", None, None));
269 }
270
271 #[test]
272 fn session_start_injects_even_if_same_as_last_injected() {
273 assert!(should_inject(
275 "SessionStart",
276 Some("repo-1"),
277 Some("repo-1")
278 ));
279 }
280
281 #[test]
282 fn user_prompt_submit_injects_when_repo_changed() {
283 assert!(should_inject(
284 "UserPromptSubmit",
285 Some("repo-2"),
286 Some("repo-1")
287 ));
288 }
289
290 #[test]
291 fn user_prompt_submit_injects_when_no_prior_injection() {
292 assert!(should_inject("UserPromptSubmit", Some("repo-1"), None));
293 }
294
295 #[test]
296 fn user_prompt_submit_skips_when_repo_unchanged() {
297 assert!(!should_inject(
298 "UserPromptSubmit",
299 Some("repo-1"),
300 Some("repo-1")
301 ));
302 }
303
304 #[test]
305 fn user_prompt_submit_skips_when_unbound() {
306 assert!(!should_inject("UserPromptSubmit", None, None));
307 assert!(!should_inject("UserPromptSubmit", None, Some("repo-1")));
308 }
309
310 #[test]
311 fn unknown_event_never_injects() {
312 assert!(!should_inject("SomeOtherEvent", Some("repo-1"), None));
313 assert!(!should_inject("SomeOtherEvent", None, None));
314 }
315
316 #[test]
319 fn cap_context_leaves_short_string_unchanged() {
320 let s = "short policy text".to_string();
321 assert_eq!(cap_context(s.clone()), s);
322 }
323
324 #[test]
325 fn cap_context_truncates_oversize_string_and_points_at_repo_status() {
326 let s = "a".repeat(MAX_CONTEXT + 1);
327 let capped = cap_context(s.clone());
328 assert!(capped.starts_with(&"a".repeat(HEAD_LEN)));
330 assert!(capped.contains("tracevault repo status"));
334 assert!(!capped.contains("agent-policies"));
335 assert!(capped.chars().count() <= MAX_CONTEXT);
336 }
337
338 #[test]
339 fn cap_context_allows_exactly_max_context() {
340 let s = "a".repeat(MAX_CONTEXT);
341 assert_eq!(cap_context(s.clone()), s);
342 }
343
344 #[test]
347 fn with_context_serializes_expected_shape() {
348 let out = HookOutput::with_context("SessionStart", "x".to_string());
349 let json = serde_json::to_string(&out).unwrap();
350 assert!(json.contains("\"hookSpecificOutput\""));
351 assert!(json.contains("\"hookEventName\":\"SessionStart\""));
352 assert!(json.contains("\"additionalContext\":\"x\""));
353 }
354
355 #[test]
356 fn a_notice_serializes_as_system_message() {
357 let out = HookOutput {
358 system_message: Some("not recorded".into()),
359 ..HookOutput::allow()
360 };
361 let json = serde_json::to_string(&out).unwrap();
362 assert!(json.contains("\"systemMessage\":\"not recorded\""));
363 assert!(!serde_json::to_string(&HookOutput::allow())
364 .unwrap()
365 .contains("systemMessage"));
366 }
367
368 #[test]
369 fn allow_serializes_without_hook_specific_output() {
370 let out = HookOutput::allow();
371 let json = serde_json::to_string(&out).unwrap();
372 assert!(!json.contains("hookSpecificOutput"));
373 assert!(json.contains("\"suppressOutput\":true"));
374 }
375
376 #[tokio::test]
386 async fn resolve_and_inject_allows_when_no_binding() {
387 let tmp = tempfile::tempdir().unwrap();
388 let hook_event = HookEvent {
389 session_id: "resolve-and-inject-no-binding-test".to_string(),
390 transcript_path: "t".to_string(),
391 cwd: tmp.path().to_string_lossy().into_owned(),
392 permission_mode: None,
393 hook_event_name: "UserPromptSubmit".to_string(),
394 tool_name: None,
395 tool_input: None,
396 tool_response: None,
397 tool_use_id: None,
398 source: None,
399 transcript_records: None,
400 };
401
402 let result = resolve_and_inject(&hook_event).await;
403 assert!(result.is_ok());
404 }
405
406 #[tokio::test]
417 async fn fetch_context_returns_none_on_network_failure() {
418 let client = ApiClient::new("http://127.0.0.1:1", None);
419 let repo_id = uuid::Uuid::new_v4();
420 let result = fetch_context(&client, "SessionStart", repo_id).await;
421 assert!(result.is_none());
422 }
423}