Skip to main content

tracevault_cli/commands/
session_start.rs

1//! `tracevault session-start` — the Claude Code `SessionStart` hook.
2//!
3//! Installed (sub-plan C) as the `SessionStart` hook for `init --global`. Runs
4//! on every session start/resume and does these things, all best-effort:
5//!
6//! 1. Exports `TRACEVAULT_SESSION_ID` into Claude Code's session env file (when
7//!    present) so agent-invoked `tracevault repo …` commands can find the
8//!    session without an explicit `--session-id` flag.
9//! 2. Resolves the effective repo binding (workspace-mode precedence chain;
10//!    with none, binds the session from its checkout's origin remote — see
11//!    `auto_bind`) and, if one exists, injects that repo's policies as
12//!    `SessionStart` `additionalContext` — the reliable way to hand an agent
13//!    up-to-date policy text at the start of a session.
14//! 3. Once per CLI upgrade, refreshes the installed hooks and turns telemetry
15//!    on (`upgrade`, VIS-1109).
16//! 4. After its response is printed, sends the `cost-state` reports earlier
17//!    sessions of the repo left unsent (`catch_up`, VIS-1108).
18//!
19//! This hook must NEVER hard-fail: a failing `SessionStart` hook blocks
20//! Claude Code from starting the session. Every fallible step below is
21//! handled internally, and the function always prints a valid `HookOutput`
22//! JSON payload before returning `Ok(())`.
23
24use std::path::Path;
25
26use crate::commands::session_hooks::{read_hook_event_or_allow, resolve_and_inject};
27
28/// Append `export TRACEVAULT_SESSION_ID='<session_id>'` to the Claude Code
29/// session env file, unless that exact line is already present. Pure I/O
30/// helper factored out so it can be unit-tested without touching the real
31/// `CLAUDE_ENV_FILE` env var. Creates the file if it doesn't exist.
32///
33/// `SessionStart` fires on startup *and* on resume/clear/compact — all with
34/// the same session id — so an unconditional append would grow the env file
35/// with duplicate export lines every time. Reading the file first and
36/// skipping an already-present line makes the write idempotent.
37///
38/// `session_id` is untrusted input from the hook event JSON, and this file is
39/// later `source`d by the shell — a naive unquoted interpolation would be a
40/// shell-injection sink. Defend in depth: reject anything outside the
41/// existing session-id allowlist (`[A-Za-z0-9_-]`, non-empty) by silently
42/// skipping the write (best-effort: a malformed id is simply never
43/// exported), and single-quote the value we do write. After the allowlist
44/// check there are no quote or metacharacters left, so single-quoting closes
45/// the sink.
46pub fn write_session_env(env_file: &Path, session_id: &str) -> std::io::Result<()> {
47    use std::io::Write as _;
48    if !crate::session_state::is_safe_session_id(session_id) {
49        return Ok(());
50    }
51    let line = format!("export TRACEVAULT_SESSION_ID='{session_id}'");
52
53    if let Ok(existing) = std::fs::read_to_string(env_file) {
54        if existing.lines().any(|l| l == line) {
55            return Ok(());
56        }
57    }
58
59    let mut file = std::fs::OpenOptions::new()
60        .create(true)
61        .append(true)
62        .open(env_file)?;
63    writeln!(file, "{line}")
64}
65
66pub async fn run() -> Result<(), Box<dyn std::error::Error>> {
67    let started = std::time::Instant::now();
68    // 1. Read the hook event from stdin. A parse error must never fail the
69    // hook — print the minimal allow response and return Ok.
70    let Some(hook_event) = read_hook_event_or_allow() else {
71        return Ok(());
72    };
73
74    // 2. Export the session id, best-effort. Older Claude Code versions don't
75    // set CLAUDE_ENV_FILE — silently skip in that case.
76    if let Ok(env_file) = std::env::var("CLAUDE_ENV_FILE") {
77        let _ = write_session_env(Path::new(&env_file), &hook_event.session_id);
78    }
79
80    // 3. Once per CLI upgrade: refresh this repo's hooks and turn telemetry
81    // on (VIS-1109). Its notice is shown with whatever step 4 prints.
82    let notice = run_upgrade_step(Path::new(&hook_event.cwd));
83
84    // 4. Resolve the effective repo binding and, if warranted, inject its
85    // policies. Shared with `user-prompt` (sub-plan C's UserPromptSubmit hook).
86    let injected = resolve_and_inject(&hook_event, notice).await;
87
88    // 5. Send the cost reports earlier sessions of this repo left unsent
89    // (VIS-1108). After the response is printed, so it never delays it, and
90    // within what is left of the hook's timeout.
91    run_catch_up(Path::new(&hook_event.cwd), &hook_event.session_id, started).await;
92    injected
93}
94
95/// [`catch_up::sweep`](crate::commands::catch_up::sweep) for the repo of a
96/// session in `cwd`, in a hook that started at `started`. It must never fail
97/// the hook, so a panic in it is caught too (a spawned task's panic is
98/// returned, not propagated).
99async fn run_catch_up(cwd: &Path, session_id: &str, started: std::time::Instant) {
100    use crate::commands::catch_up;
101    let project_root = crate::paths::resolve_project_root(cwd).root;
102    let deadline = catch_up::deadline(started, std::time::Instant::now());
103    let sweep = catch_up::sweep(project_root, session_id.to_string(), deadline);
104    if tokio::spawn(sweep).await.is_err() {
105        eprintln!("tracevault: the catch-up sweep failed unexpectedly");
106    }
107}
108
109/// [`upgrade::run`](crate::commands::upgrade::run) for a session in `cwd`.
110/// It must never fail the hook, so a panic in it is caught too.
111fn run_upgrade_step(cwd: &Path) -> Option<String> {
112    use crate::commands::{claude_telemetry, upgrade};
113    std::panic::catch_unwind(|| {
114        let paths = upgrade::Paths::current(cwd)?;
115        let env = claude_telemetry::Environment::current(&paths.claude_dir);
116        let credentials_root = paths
117            .project_root
118            .clone()
119            .unwrap_or_else(|| cwd.to_path_buf());
120        upgrade::run(&paths, crate::install_state::CURRENT_VERSION, &env, || {
121            claude_telemetry::telemetry_server_url(&credentials_root, None)
122        })
123    })
124    .unwrap_or_else(|_| {
125        eprintln!("tracevault: the upgrade step failed unexpectedly");
126        None
127    })
128}
129
130#[cfg(test)]
131mod tests {
132    use super::*;
133
134    #[test]
135    fn write_session_env_appends_export_line() {
136        let dir = tempfile::tempdir().unwrap();
137        let env_file = dir.path().join("env.sh");
138
139        write_session_env(&env_file, "sess-123").unwrap();
140
141        let content = std::fs::read_to_string(&env_file).unwrap();
142        assert_eq!(content, "export TRACEVAULT_SESSION_ID='sess-123'\n");
143    }
144
145    #[test]
146    fn write_session_env_appends_on_repeated_calls_with_different_ids() {
147        let dir = tempfile::tempdir().unwrap();
148        let env_file = dir.path().join("env.sh");
149
150        write_session_env(&env_file, "sess-a").unwrap();
151        write_session_env(&env_file, "sess-b").unwrap();
152
153        let content = std::fs::read_to_string(&env_file).unwrap();
154        let lines: Vec<&str> = content.lines().collect();
155        assert_eq!(
156            lines,
157            vec![
158                "export TRACEVAULT_SESSION_ID='sess-a'",
159                "export TRACEVAULT_SESSION_ID='sess-b'",
160            ]
161        );
162    }
163
164    #[test]
165    fn write_session_env_is_idempotent_for_repeated_calls_with_same_id() {
166        // SessionStart fires on startup, resume, clear, AND compact — all
167        // with the SAME session id — so repeated calls for the same id must
168        // not grow the file with duplicate export lines.
169        let dir = tempfile::tempdir().unwrap();
170        let env_file = dir.path().join("env.sh");
171
172        write_session_env(&env_file, "sess-a").unwrap();
173        write_session_env(&env_file, "sess-a").unwrap();
174        write_session_env(&env_file, "sess-a").unwrap();
175
176        let content = std::fs::read_to_string(&env_file).unwrap();
177        let lines: Vec<&str> = content.lines().collect();
178        assert_eq!(lines, vec!["export TRACEVAULT_SESSION_ID='sess-a'"]);
179    }
180
181    #[test]
182    fn write_session_env_creates_missing_file() {
183        let dir = tempfile::tempdir().unwrap();
184        let env_file = dir.path().join("nested").join("env.sh");
185        // Parent dir does not exist — OpenOptions::create only creates the
186        // file itself, not parent dirs, so this must error rather than panic.
187        assert!(write_session_env(&env_file, "sess-x").is_err());
188    }
189
190    #[test]
191    fn write_session_env_quotes_valid_uuid() {
192        let dir = tempfile::tempdir().unwrap();
193        let env_file = dir.path().join("env.sh");
194        let uuid = "0190a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b";
195
196        write_session_env(&env_file, uuid).unwrap();
197
198        let content = std::fs::read_to_string(&env_file).unwrap();
199        assert_eq!(content, format!("export TRACEVAULT_SESSION_ID='{uuid}'\n"));
200    }
201
202    #[test]
203    fn write_session_env_skips_unsafe_session_id() {
204        let dir = tempfile::tempdir().unwrap();
205        let env_file = dir.path().join("env.sh");
206
207        // Shell-metacharacter / path-traversal ids must never be written.
208        write_session_env(&env_file, "x; rm -rf /").unwrap();
209        write_session_env(&env_file, "../evil").unwrap();
210
211        // Nothing was written — the file wasn't even created for the first
212        // call, and the second call didn't add anything either.
213        match std::fs::read_to_string(&env_file) {
214            Ok(content) => assert!(content.is_empty()),
215            Err(e) => assert_eq!(e.kind(), std::io::ErrorKind::NotFound),
216        }
217    }
218}