1use 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#[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 #[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 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 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
66const HOOK_BUDGET: std::time::Duration = std::time::Duration::from_secs(8);
69
70const MAX_CONTEXT: usize = 10_000;
72
73const HEAD_LEN: usize = 9_500;
77
78pub 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
92pub 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
108pub(crate) fn print_allow() -> Result<(), Box<dyn std::error::Error>> {
112 print_allow_with(None)
113}
114
115fn 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
125pub(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
144async 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
153pub 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 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 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 return print_allow_with(notice);
249 };
250
251 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 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 #[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 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 #[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 assert!(capped.starts_with(&"a".repeat(HEAD_LEN)));
367 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 #[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 #[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 #[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}