tracevault-cli 0.29.6

CLI tool for Visdom Trace - AI code tracing and attribution
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
//! Shared helpers for the SessionStart / UserPromptSubmit hook commands
//! (sub-plan C): the Claude Code hook-output JSON shape for injecting context,
//! the pure decision logic for when to inject, and the shared
//! resolve-binding-then-inject flow used by both hook commands.

use std::io::Read as _;
use std::path::Path;

use serde::Serialize;

use tracevault_protocol::hooks::{parse_hook_event, HookEvent};

use crate::api_client::ApiClient;
use crate::credentials::resolve_credentials;
use crate::resolution::{binding_from_config, effective_binding, ResolveInputs};

/// Claude Code hook output. Field names are camelCase to match CC's contract
/// (the shared protocol `HookResponse` is snake_case and server-facing; this is
/// the CLI-local shape used only for hook stdout).
#[derive(Debug, Serialize)]
pub struct HookOutput {
    #[serde(rename = "hookSpecificOutput", skip_serializing_if = "Option::is_none")]
    pub hook_specific_output: Option<HookSpecificOutput>,
    #[serde(rename = "continue", skip_serializing_if = "Option::is_none")]
    pub cont: Option<bool>,
    #[serde(rename = "suppressOutput", skip_serializing_if = "Option::is_none")]
    pub suppress_output: Option<bool>,
    /// A message Claude Code shows the user (not the model).
    #[serde(rename = "systemMessage", skip_serializing_if = "Option::is_none")]
    pub system_message: Option<String>,
}

#[derive(Debug, Serialize)]
pub struct HookSpecificOutput {
    #[serde(rename = "hookEventName")]
    pub hook_event_name: String,
    #[serde(rename = "additionalContext")]
    pub additional_context: String,
}

impl HookOutput {
    /// Minimal allow/quiet response with no injected context.
    pub fn allow() -> Self {
        Self {
            hook_specific_output: None,
            cont: None,
            suppress_output: Some(true),
            system_message: None,
        }
    }
    /// Allow + inject `context` under the given hook event name.
    pub fn with_context(event: &str, context: String) -> Self {
        Self {
            hook_specific_output: Some(HookSpecificOutput {
                hook_event_name: event.to_string(),
                additional_context: context,
            }),
            cont: None,
            suppress_output: Some(true),
            system_message: None,
        }
    }
}

/// How long `resolve_and_inject` may spend on the network, kept under the
/// hooks' 10 s timeout: a hook killed at its timeout prints no allow response.
const HOOK_BUDGET: std::time::Duration = std::time::Duration::from_secs(8);

/// Maximum additionalContext size (CC guidance). Larger → truncated.
const MAX_CONTEXT: usize = 10_000;

/// How much of an oversize policy text to keep before appending the
/// truncation suffix. Chosen so `HEAD_LEN` + the suffix stays under
/// `MAX_CONTEXT`.
const HEAD_LEN: usize = 9_500;

/// Cap injected context. Oversize policy text is truncated to its first
/// `HEAD_LEN` chars with a suffix pointing at `tracevault repo status` —
/// unlike `tracevault agent-policies`, `repo status` works in workspace mode
/// (no `.tracevault/config.toml` required), so the fallback is reachable in
/// every install mode.
pub fn cap_context(s: String) -> String {
    if s.chars().count() > MAX_CONTEXT {
        let head: String = s.chars().take(HEAD_LEN).collect();
        format!("{head}\n\n…(truncated; run `tracevault repo status` to see full policies)")
    } else {
        s
    }
}

/// Whether to inject policies for this hook event.
/// - SessionStart: inject whenever a repo is bound (refresh context at start/resume).
/// - UserPromptSubmit: inject only when the effective repo changed since last injection.
/// - other events: never.
pub fn should_inject(
    event: &str,
    effective_repo_id: Option<&str>,
    last_injected: Option<&str>,
) -> bool {
    match event {
        "SessionStart" => effective_repo_id.is_some(),
        "UserPromptSubmit" => effective_repo_id.is_some() && effective_repo_id != last_injected,
        _ => false,
    }
}

/// Print the minimal allow/quiet `HookOutput` and return `Ok(())`. Shared by
/// every hook command's error paths — a hook must always emit valid JSON,
/// even (especially) when something upstream failed.
pub(crate) fn print_allow() -> Result<(), Box<dyn std::error::Error>> {
    print_allow_with(None)
}

/// [`print_allow`], showing the user `notice` if there is one.
fn print_allow_with(notice: Option<String>) -> Result<(), Box<dyn std::error::Error>> {
    let output = HookOutput {
        system_message: notice,
        ..HookOutput::allow()
    };
    println!("{}", serde_json::to_string(&output)?);
    Ok(())
}

/// Read stdin, parse it as a `HookEvent`, and return it. On any read or parse
/// error, print the allow response (never fail the hook) and return `None`.
/// Shared by `session-start` and `user-prompt`, whose `run()` bodies both
/// start with "read the hook event or bail out allowing".
pub(crate) fn read_hook_event_or_allow() -> Option<HookEvent> {
    let mut input = String::new();
    if std::io::stdin().read_to_string(&mut input).is_err() {
        let _ = print_allow();
        return None;
    }
    match parse_hook_event(&input) {
        Ok(e) => Some(e),
        Err(_) => {
            let _ = print_allow();
            None
        }
    }
}

/// Fetch rendered policies and build the injection output; `None` on ANY
/// error (best-effort — a fetch failure degrades to allow, never blocks the
/// hook). Factored out of `resolve_and_inject` so the network step can be
/// exercised in a unit test without touching creds/env/git.
async fn fetch_context(client: &ApiClient, event: &str, repo_id: uuid::Uuid) -> Option<HookOutput> {
    let resp = client.get_agent_instructions(&repo_id).await.ok()?;
    Some(HookOutput::with_context(event, cap_context(resp.content)))
}

/// Resolve the session's effective binding (auto-binding an unbound session
/// from its checkout's remote, whose "not registered" notice goes to the user
/// as `systemMessage`) and, if `should_inject(event, ...)`, best-effort fetch + print policies as `additionalContext` and persist
/// `last_injected_repo`. Always prints a valid `HookOutput`; never hard-fails.
///
/// Shared by `session-start` and `user-prompt`: both need the same
/// resolve-binding → decide → fetch-and-inject flow, differing only in which
/// hook-specific steps happen around it (SessionStart also writes the session
/// env file, which stays in `session_start.rs`). `notice` is a message for the
/// user from that hook-specific part (the upgrade step's, VIS-1109); it is
/// shown whatever this flow decides.
pub async fn resolve_and_inject(
    hook_event: &HookEvent,
    notice: Option<String>,
) -> Result<(), Box<dyn std::error::Error>> {
    let deadline = std::time::Instant::now() + HOOK_BUDGET;
    let event = hook_event.hook_event_name.as_str();
    let hook_cwd = Path::new(&hook_event.cwd);
    let project_root = crate::paths::resolve_project_root(hook_cwd).root;
    let session = crate::session_state::load(&hook_event.session_id);
    let worktree = crate::paths::worktree_toplevel(hook_cwd);
    let config = crate::config::TracevaultConfig::load(&project_root);
    let bound = config.as_ref().and_then(binding_from_config);
    let config_project = config
        .as_ref()
        .and_then(crate::resolution::project_from_config);
    let user_default = crate::user_default::load();
    let mut binding = effective_binding(ResolveInputs {
        repo_flag: None,
        session: &session,
        worktree_path: Some(&worktree),
        bound,
        user_default,
    })
    .map(|(b, _)| b);

    // Nothing binds the session: bind it to the repo of the checkout it runs
    // in, if the server knows that checkout's remote (VIS-1048). A session
    // bound to a project is not bound to a repo at all: the repo of the
    // checkout it is in now is inferred, within the project, for its policies
    // here as for its events (VIS-1258) — a binding stored now would pin the
    // rest of the session to this checkout's repo wherever it goes next.
    let mut notice = notice;
    if binding.is_none() {
        if let Ok((Some(server_url), credential)) =
            crate::credentials::resolve_credentials_quiet(&project_root)
        {
            let client = ApiClient::with_credential(&server_url, credential);
            let project =
                crate::commands::stream::capture_project(&session, Some(&worktree), config_project);
            match crate::commands::stream::inference_project(None, project) {
                Some(pid) => {
                    binding = crate::inferred_repo::infer(
                        &hook_event.session_id,
                        &worktree,
                        pid,
                        &client,
                        deadline,
                    )
                    .await;
                }
                None => {
                    let auto = crate::auto_bind::bind_session(
                        &hook_event.session_id,
                        hook_cwd,
                        &client,
                        deadline,
                    )
                    .await;
                    binding = auto.binding;
                    notice = match (notice, auto.notice) {
                        (Some(a), Some(b)) => Some(format!("{a}\n{b}")),
                        (a, b) => a.or(b),
                    };
                }
            }
        }
    }

    if !should_inject(
        event,
        binding.as_ref().map(|b| b.repo_id.as_str()),
        session.last_injected_repo.as_deref(),
    ) {
        return print_allow_with(notice);
    }
    // `should_inject` returning true requires `effective_repo_id.is_some()`, so
    // `binding` is always `Some` here.
    let Some(binding) = binding else {
        return print_allow_with(notice);
    };

    let Ok(repo_uuid) = binding.repo_id.parse::<uuid::Uuid>() else {
        // A corrupted/hand-edited session-state or config file could contain a
        // non-UUID repo_id — skip injection rather than fail the hook.
        return print_allow_with(notice);
    };

    // A credential/URL mismatch is a misconfiguration the user has to fix, but
    // this hook must ALWAYS emit an allow response — failing it would block the
    // prompt. Report it on stderr (where hook output is surfaced) and skip
    // injection, exactly as a missing server URL already does.
    let (server_url, credential) = match resolve_credentials(&project_root) {
        Ok(resolved) => resolved,
        Err(e) => {
            eprintln!("Skipping context injection: {e}");
            return print_allow_with(notice);
        }
    };
    let Some(server_url) = server_url else {
        return print_allow_with(notice);
    };
    let client = ApiClient::with_credential(&server_url, credential);

    let remaining = deadline.saturating_duration_since(std::time::Instant::now());
    let fetched = tokio::time::timeout(remaining, fetch_context(&client, event, repo_uuid))
        .await
        .ok()
        .flatten();
    match fetched {
        Some(mut output) => {
            output.system_message = notice;
            println!("{}", serde_json::to_string(&output)?);
            // Best-effort: persist the last-injected repo so a later
            // UserPromptSubmit can avoid redundant re-injection. A save
            // failure must not turn this into a hook failure. Reload the
            // session state right before saving (rather than reusing the
            // snapshot loaded before the network `await` above) so a
            // concurrent `repo switch`/`reset` that happened during the
            // fetch isn't silently reverted by this save.
            let mut fresh = crate::session_state::load(&hook_event.session_id);
            fresh.last_injected_repo = Some(binding.repo_id.clone());
            let _ = crate::session_state::save(&hook_event.session_id, &fresh);
            Ok(())
        }
        None => print_allow_with(notice),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // ── should_inject ────────────────────────────────────────────────────

    #[test]
    fn session_start_injects_when_bound() {
        assert!(should_inject("SessionStart", Some("repo-1"), None));
    }

    #[test]
    fn session_start_skips_when_unbound() {
        assert!(!should_inject("SessionStart", None, None));
    }

    #[test]
    fn session_start_injects_even_if_same_as_last_injected() {
        // SessionStart always refreshes, regardless of last_injected.
        assert!(should_inject(
            "SessionStart",
            Some("repo-1"),
            Some("repo-1")
        ));
    }

    #[test]
    fn user_prompt_submit_injects_when_repo_changed() {
        assert!(should_inject(
            "UserPromptSubmit",
            Some("repo-2"),
            Some("repo-1")
        ));
    }

    #[test]
    fn user_prompt_submit_injects_when_no_prior_injection() {
        assert!(should_inject("UserPromptSubmit", Some("repo-1"), None));
    }

    #[test]
    fn user_prompt_submit_skips_when_repo_unchanged() {
        assert!(!should_inject(
            "UserPromptSubmit",
            Some("repo-1"),
            Some("repo-1")
        ));
    }

    #[test]
    fn user_prompt_submit_skips_when_unbound() {
        assert!(!should_inject("UserPromptSubmit", None, None));
        assert!(!should_inject("UserPromptSubmit", None, Some("repo-1")));
    }

    #[test]
    fn unknown_event_never_injects() {
        assert!(!should_inject("SomeOtherEvent", Some("repo-1"), None));
        assert!(!should_inject("SomeOtherEvent", None, None));
    }

    // ── cap_context ──────────────────────────────────────────────────────

    #[test]
    fn cap_context_leaves_short_string_unchanged() {
        let s = "short policy text".to_string();
        assert_eq!(cap_context(s.clone()), s);
    }

    #[test]
    fn cap_context_truncates_oversize_string_and_points_at_repo_status() {
        let s = "a".repeat(MAX_CONTEXT + 1);
        let capped = cap_context(s.clone());
        // Head is preserved (truncated policy text is still useful context)…
        assert!(capped.starts_with(&"a".repeat(HEAD_LEN)));
        // …and the fallback points at a command that works without
        // `.tracevault/config.toml` (workspace mode), unlike
        // `tracevault agent-policies`.
        assert!(capped.contains("tracevault repo status"));
        assert!(!capped.contains("agent-policies"));
        assert!(capped.chars().count() <= MAX_CONTEXT);
    }

    #[test]
    fn cap_context_allows_exactly_max_context() {
        let s = "a".repeat(MAX_CONTEXT);
        assert_eq!(cap_context(s.clone()), s);
    }

    // ── HookOutput serialization ─────────────────────────────────────────

    #[test]
    fn with_context_serializes_expected_shape() {
        let out = HookOutput::with_context("SessionStart", "x".to_string());
        let json = serde_json::to_string(&out).unwrap();
        assert!(json.contains("\"hookSpecificOutput\""));
        assert!(json.contains("\"hookEventName\":\"SessionStart\""));
        assert!(json.contains("\"additionalContext\":\"x\""));
    }

    #[test]
    fn a_notice_serializes_as_system_message() {
        let out = HookOutput {
            system_message: Some("not recorded".into()),
            ..HookOutput::allow()
        };
        let json = serde_json::to_string(&out).unwrap();
        assert!(json.contains("\"systemMessage\":\"not recorded\""));
        assert!(!serde_json::to_string(&HookOutput::allow())
            .unwrap()
            .contains("systemMessage"));
    }

    #[test]
    fn allow_serializes_without_hook_specific_output() {
        let out = HookOutput::allow();
        let json = serde_json::to_string(&out).unwrap();
        assert!(!json.contains("hookSpecificOutput"));
        assert!(json.contains("\"suppressOutput\":true"));
    }

    // ── resolve_and_inject ───────────────────────────────────────────────
    //
    // `resolve_and_inject` is network/IO-bound, so coverage here stays thin:
    // this exercises the no-binding path (empty session state, no
    // `.tracevault/config.toml`, non-git cwd), which `should_inject` already
    // proves resolves to "don't inject" — so this must return `Ok(())`
    // without ever reaching the network. No env mutation: `cwd` is an
    // isolated tempdir and the session id is unique to this test.

    #[tokio::test]
    async fn resolve_and_inject_allows_when_no_binding() {
        let tmp = tempfile::tempdir().unwrap();
        let hook_event = HookEvent {
            session_id: "resolve-and-inject-no-binding-test".to_string(),
            transcript_path: "t".to_string(),
            cwd: tmp.path().to_string_lossy().into_owned(),
            permission_mode: None,
            hook_event_name: "UserPromptSubmit".to_string(),
            tool_name: None,
            tool_input: None,
            tool_response: None,
            tool_use_id: None,
            source: None,
            transcript_records: None,
        };

        let result = resolve_and_inject(&hook_event, None).await;
        assert!(result.is_ok());
    }

    // ── fetch_context ────────────────────────────────────────────────────
    //
    // `resolve_and_inject` can't be unit-tested end-to-end without real
    // creds/env/git, but the network step it delegates to (`fetch_context`)
    // can be: point an `ApiClient` at a port nothing listens on so the
    // request fails fast with connection-refused, and assert the failure
    // degrades to `None` (→ `print_allow()` in the caller) rather than
    // propagating an error. This proves the hook never blocks on a fetch
    // failure.

    #[tokio::test]
    async fn fetch_context_returns_none_on_network_failure() {
        let client = ApiClient::new("http://127.0.0.1:1", None);
        let repo_id = uuid::Uuid::new_v4();
        let result = fetch_context(&client, "SessionStart", repo_id).await;
        assert!(result.is_none());
    }
}