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::{resolve_credentials, ApiClient};
14use crate::resolution::{binding_from_config, effective_binding, ResolveInputs};
15
16#[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 pub fn allow() -> Self {
40 Self {
41 hook_specific_output: None,
42 cont: None,
43 suppress_output: Some(true),
44 }
45 }
46 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
59const MAX_CONTEXT: usize = 10_000;
61
62const HEAD_LEN: usize = 9_500;
66
67pub 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
81pub 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
97pub(crate) fn print_allow() -> Result<(), Box<dyn std::error::Error>> {
101 println!("{}", serde_json::to_string(&HookOutput::allow())?);
102 Ok(())
103}
104
105pub(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
124async 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
141pub 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 user_default = crate::user_default::load();
158 let binding = effective_binding(ResolveInputs {
159 repo_flag: None,
160 session: &session,
161 worktree_path: Some(&worktree),
162 bound,
163 user_default,
164 })
165 .map(|(b, _)| b);
166
167 if !should_inject(
168 event,
169 binding.as_ref().map(|b| b.repo_id.as_str()),
170 session.last_injected_repo.as_deref(),
171 ) {
172 return print_allow();
173 }
174 let Some(binding) = binding else {
177 return print_allow();
178 };
179
180 let Ok(repo_uuid) = binding.repo_id.parse::<uuid::Uuid>() else {
181 return print_allow();
184 };
185
186 let (server_url, token) = resolve_credentials(&project_root);
187 let Some(server_url) = server_url else {
188 return print_allow();
189 };
190 let client = ApiClient::new(&server_url, token.as_deref());
191
192 match fetch_context(&client, event, &binding.org_slug, repo_uuid).await {
193 Some(output) => {
194 println!("{}", serde_json::to_string(&output)?);
195 let mut fresh = crate::session_state::load(&hook_event.session_id);
203 fresh.last_injected_repo = Some(binding.repo_id.clone());
204 let _ = crate::session_state::save(&hook_event.session_id, &fresh);
205 Ok(())
206 }
207 None => print_allow(),
208 }
209}
210
211#[cfg(test)]
212mod tests {
213 use super::*;
214
215 #[test]
218 fn session_start_injects_when_bound() {
219 assert!(should_inject("SessionStart", Some("repo-1"), None));
220 }
221
222 #[test]
223 fn session_start_skips_when_unbound() {
224 assert!(!should_inject("SessionStart", None, None));
225 }
226
227 #[test]
228 fn session_start_injects_even_if_same_as_last_injected() {
229 assert!(should_inject(
231 "SessionStart",
232 Some("repo-1"),
233 Some("repo-1")
234 ));
235 }
236
237 #[test]
238 fn user_prompt_submit_injects_when_repo_changed() {
239 assert!(should_inject(
240 "UserPromptSubmit",
241 Some("repo-2"),
242 Some("repo-1")
243 ));
244 }
245
246 #[test]
247 fn user_prompt_submit_injects_when_no_prior_injection() {
248 assert!(should_inject("UserPromptSubmit", Some("repo-1"), None));
249 }
250
251 #[test]
252 fn user_prompt_submit_skips_when_repo_unchanged() {
253 assert!(!should_inject(
254 "UserPromptSubmit",
255 Some("repo-1"),
256 Some("repo-1")
257 ));
258 }
259
260 #[test]
261 fn user_prompt_submit_skips_when_unbound() {
262 assert!(!should_inject("UserPromptSubmit", None, None));
263 assert!(!should_inject("UserPromptSubmit", None, Some("repo-1")));
264 }
265
266 #[test]
267 fn unknown_event_never_injects() {
268 assert!(!should_inject("SomeOtherEvent", Some("repo-1"), None));
269 assert!(!should_inject("SomeOtherEvent", None, None));
270 }
271
272 #[test]
275 fn cap_context_leaves_short_string_unchanged() {
276 let s = "short policy text".to_string();
277 assert_eq!(cap_context(s.clone()), s);
278 }
279
280 #[test]
281 fn cap_context_truncates_oversize_string_and_points_at_repo_status() {
282 let s = "a".repeat(MAX_CONTEXT + 1);
283 let capped = cap_context(s.clone());
284 assert!(capped.starts_with(&"a".repeat(HEAD_LEN)));
286 assert!(capped.contains("tracevault repo status"));
290 assert!(!capped.contains("agent-policies"));
291 assert!(capped.chars().count() <= MAX_CONTEXT);
292 }
293
294 #[test]
295 fn cap_context_allows_exactly_max_context() {
296 let s = "a".repeat(MAX_CONTEXT);
297 assert_eq!(cap_context(s.clone()), s);
298 }
299
300 #[test]
303 fn with_context_serializes_expected_shape() {
304 let out = HookOutput::with_context("SessionStart", "x".to_string());
305 let json = serde_json::to_string(&out).unwrap();
306 assert!(json.contains("\"hookSpecificOutput\""));
307 assert!(json.contains("\"hookEventName\":\"SessionStart\""));
308 assert!(json.contains("\"additionalContext\":\"x\""));
309 }
310
311 #[test]
312 fn allow_serializes_without_hook_specific_output() {
313 let out = HookOutput::allow();
314 let json = serde_json::to_string(&out).unwrap();
315 assert!(!json.contains("hookSpecificOutput"));
316 assert!(json.contains("\"suppressOutput\":true"));
317 }
318
319 #[tokio::test]
329 async fn resolve_and_inject_allows_when_no_binding() {
330 let tmp = tempfile::tempdir().unwrap();
331 let hook_event = HookEvent {
332 session_id: "resolve-and-inject-no-binding-test".to_string(),
333 transcript_path: "t".to_string(),
334 cwd: tmp.path().to_string_lossy().into_owned(),
335 permission_mode: None,
336 hook_event_name: "UserPromptSubmit".to_string(),
337 tool_name: None,
338 tool_input: None,
339 tool_response: None,
340 tool_use_id: None,
341 source: None,
342 transcript_records: None,
343 };
344
345 let result = resolve_and_inject(&hook_event).await;
346 assert!(result.is_ok());
347 }
348
349 #[tokio::test]
360 async fn fetch_context_returns_none_on_network_failure() {
361 let client = ApiClient::new("http://127.0.0.1:1", None);
362 let repo_id = uuid::Uuid::new_v4();
363 let result = fetch_context(&client, "SessionStart", "org", repo_id).await;
364 assert!(result.is_none());
365 }
366}