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}
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 pub fn allow() -> Self {
41 Self {
42 hook_specific_output: None,
43 cont: None,
44 suppress_output: Some(true),
45 }
46 }
47 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
60const MAX_CONTEXT: usize = 10_000;
62
63const HEAD_LEN: usize = 9_500;
67
68pub 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
82pub 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
98pub(crate) fn print_allow() -> Result<(), Box<dyn std::error::Error>> {
102 println!("{}", serde_json::to_string(&HookOutput::allow())?);
103 Ok(())
104}
105
106pub(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
125async 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
134pub 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 let Some(binding) = binding else {
170 return print_allow();
171 };
172
173 let Ok(repo_uuid) = binding.repo_id.parse::<uuid::Uuid>() else {
174 return print_allow();
177 };
178
179 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 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 #[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 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 #[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 assert!(capped.starts_with(&"a".repeat(HEAD_LEN)));
289 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 #[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 #[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 #[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}