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(client: &ApiClient, event: &str, repo_id: uuid::Uuid) -> Option<HookOutput> {
129 let resp = client.get_agent_instructions(&repo_id).await.ok()?;
130 Some(HookOutput::with_context(event, cap_context(resp.content)))
131}
132
133pub async fn resolve_and_inject(hook_event: &HookEvent) -> Result<(), Box<dyn std::error::Error>> {
142 let event = hook_event.hook_event_name.as_str();
143 let hook_cwd = Path::new(&hook_event.cwd);
144 let project_root = crate::paths::resolve_project_root(hook_cwd).root;
145 let session = crate::session_state::load(&hook_event.session_id);
146 let worktree = crate::paths::worktree_toplevel(hook_cwd);
147 let bound =
148 crate::config::TracevaultConfig::load(&project_root).and_then(|c| binding_from_config(&c));
149 let user_default = crate::user_default::load();
150 let binding = effective_binding(ResolveInputs {
151 repo_flag: None,
152 session: &session,
153 worktree_path: Some(&worktree),
154 bound,
155 user_default,
156 })
157 .map(|(b, _)| b);
158
159 if !should_inject(
160 event,
161 binding.as_ref().map(|b| b.repo_id.as_str()),
162 session.last_injected_repo.as_deref(),
163 ) {
164 return print_allow();
165 }
166 let Some(binding) = binding else {
169 return print_allow();
170 };
171
172 let Ok(repo_uuid) = binding.repo_id.parse::<uuid::Uuid>() else {
173 return print_allow();
176 };
177
178 let (server_url, token) = resolve_credentials(&project_root);
179 let Some(server_url) = server_url else {
180 return print_allow();
181 };
182 let client = ApiClient::new(&server_url, token.as_deref());
183
184 match fetch_context(&client, event, repo_uuid).await {
185 Some(output) => {
186 println!("{}", serde_json::to_string(&output)?);
187 let mut fresh = crate::session_state::load(&hook_event.session_id);
195 fresh.last_injected_repo = Some(binding.repo_id.clone());
196 let _ = crate::session_state::save(&hook_event.session_id, &fresh);
197 Ok(())
198 }
199 None => print_allow(),
200 }
201}
202
203#[cfg(test)]
204mod tests {
205 use super::*;
206
207 #[test]
210 fn session_start_injects_when_bound() {
211 assert!(should_inject("SessionStart", Some("repo-1"), None));
212 }
213
214 #[test]
215 fn session_start_skips_when_unbound() {
216 assert!(!should_inject("SessionStart", None, None));
217 }
218
219 #[test]
220 fn session_start_injects_even_if_same_as_last_injected() {
221 assert!(should_inject(
223 "SessionStart",
224 Some("repo-1"),
225 Some("repo-1")
226 ));
227 }
228
229 #[test]
230 fn user_prompt_submit_injects_when_repo_changed() {
231 assert!(should_inject(
232 "UserPromptSubmit",
233 Some("repo-2"),
234 Some("repo-1")
235 ));
236 }
237
238 #[test]
239 fn user_prompt_submit_injects_when_no_prior_injection() {
240 assert!(should_inject("UserPromptSubmit", Some("repo-1"), None));
241 }
242
243 #[test]
244 fn user_prompt_submit_skips_when_repo_unchanged() {
245 assert!(!should_inject(
246 "UserPromptSubmit",
247 Some("repo-1"),
248 Some("repo-1")
249 ));
250 }
251
252 #[test]
253 fn user_prompt_submit_skips_when_unbound() {
254 assert!(!should_inject("UserPromptSubmit", None, None));
255 assert!(!should_inject("UserPromptSubmit", None, Some("repo-1")));
256 }
257
258 #[test]
259 fn unknown_event_never_injects() {
260 assert!(!should_inject("SomeOtherEvent", Some("repo-1"), None));
261 assert!(!should_inject("SomeOtherEvent", None, None));
262 }
263
264 #[test]
267 fn cap_context_leaves_short_string_unchanged() {
268 let s = "short policy text".to_string();
269 assert_eq!(cap_context(s.clone()), s);
270 }
271
272 #[test]
273 fn cap_context_truncates_oversize_string_and_points_at_repo_status() {
274 let s = "a".repeat(MAX_CONTEXT + 1);
275 let capped = cap_context(s.clone());
276 assert!(capped.starts_with(&"a".repeat(HEAD_LEN)));
278 assert!(capped.contains("tracevault repo status"));
282 assert!(!capped.contains("agent-policies"));
283 assert!(capped.chars().count() <= MAX_CONTEXT);
284 }
285
286 #[test]
287 fn cap_context_allows_exactly_max_context() {
288 let s = "a".repeat(MAX_CONTEXT);
289 assert_eq!(cap_context(s.clone()), s);
290 }
291
292 #[test]
295 fn with_context_serializes_expected_shape() {
296 let out = HookOutput::with_context("SessionStart", "x".to_string());
297 let json = serde_json::to_string(&out).unwrap();
298 assert!(json.contains("\"hookSpecificOutput\""));
299 assert!(json.contains("\"hookEventName\":\"SessionStart\""));
300 assert!(json.contains("\"additionalContext\":\"x\""));
301 }
302
303 #[test]
304 fn allow_serializes_without_hook_specific_output() {
305 let out = HookOutput::allow();
306 let json = serde_json::to_string(&out).unwrap();
307 assert!(!json.contains("hookSpecificOutput"));
308 assert!(json.contains("\"suppressOutput\":true"));
309 }
310
311 #[tokio::test]
321 async fn resolve_and_inject_allows_when_no_binding() {
322 let tmp = tempfile::tempdir().unwrap();
323 let hook_event = HookEvent {
324 session_id: "resolve-and-inject-no-binding-test".to_string(),
325 transcript_path: "t".to_string(),
326 cwd: tmp.path().to_string_lossy().into_owned(),
327 permission_mode: None,
328 hook_event_name: "UserPromptSubmit".to_string(),
329 tool_name: None,
330 tool_input: None,
331 tool_response: None,
332 tool_use_id: None,
333 source: None,
334 transcript_records: None,
335 };
336
337 let result = resolve_and_inject(&hook_event).await;
338 assert!(result.is_ok());
339 }
340
341 #[tokio::test]
352 async fn fetch_context_returns_none_on_network_failure() {
353 let client = ApiClient::new("http://127.0.0.1:1", None);
354 let repo_id = uuid::Uuid::new_v4();
355 let result = fetch_context(&client, "SessionStart", repo_id).await;
356 assert!(result.is_none());
357 }
358}