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    // 2b. Anchor the session dir to where the session started (VIS-1257),
81    // before anything below can bind the session and save its state.
82    if let Some(dir) = crate::session_state::sessions_dir() {
83        let _ = record_storage_root(&dir, Path::new(&hook_event.cwd), &hook_event.session_id);
84    }
85
86    // 3. Once per CLI upgrade: refresh this repo's hooks and turn telemetry
87    // on (VIS-1109). Its notice is shown with whatever step 4 prints.
88    let notice = run_upgrade_step(Path::new(&hook_event.cwd));
89
90    // 4. Resolve the effective repo binding and, if warranted, inject its
91    // policies. Shared with `user-prompt` (sub-plan C's UserPromptSubmit hook).
92    let injected = resolve_and_inject(&hook_event, notice).await;
93
94    // 5. Send the cost reports earlier sessions of this repo left unsent
95    // (VIS-1108). After the response is printed, so it never delays it, and
96    // within what is left of the hook's timeout.
97    run_catch_up(Path::new(&hook_event.cwd), &hook_event.session_id, started).await;
98    injected
99}
100
101/// Record the `.tracevault/` root `cwd` resolves to as the session's storage
102/// root (see [`crate::session_state::SessionState::storage_root`]) — unless
103/// nothing resolves there: a [`Fallback`](crate::paths::ProjectRootSource::Fallback)
104/// root would put a stray `.tracevault/` in, say, the home directory and keep
105/// the session out of the repo it then works in, so that session keeps
106/// resolving per event. Best-effort; returns whether it wrote.
107fn record_storage_root(
108    sessions_dir: &Path,
109    cwd: &Path,
110    session_id: &str,
111) -> Result<bool, Box<dyn std::error::Error>> {
112    let resolved = crate::paths::resolve_project_root(cwd);
113    if resolved.source == crate::paths::ProjectRootSource::Fallback {
114        return Ok(false);
115    }
116    crate::session_state::record_storage_root(sessions_dir, session_id, &resolved.root)
117}
118
119/// [`catch_up::sweep`](crate::commands::catch_up::sweep) for the repo of a
120/// session in `cwd`, in a hook that started at `started`. It must never fail
121/// the hook, so a panic in it is caught too (a spawned task's panic is
122/// returned, not propagated).
123async fn run_catch_up(cwd: &Path, session_id: &str, started: std::time::Instant) {
124    use crate::commands::catch_up;
125    let project_root = crate::paths::resolve_project_root(cwd).root;
126    let deadline = catch_up::deadline(started, std::time::Instant::now());
127    let worktree = crate::paths::worktree_toplevel(cwd);
128    let sweep = catch_up::sweep(project_root, worktree, session_id.to_string(), deadline);
129    if tokio::spawn(sweep).await.is_err() {
130        eprintln!("tracevault: the catch-up sweep failed unexpectedly");
131    }
132}
133
134/// [`upgrade::run`](crate::commands::upgrade::run) for a session in `cwd`.
135/// It must never fail the hook, so a panic in it is caught too.
136fn run_upgrade_step(cwd: &Path) -> Option<String> {
137    use crate::commands::{claude_telemetry, upgrade};
138    std::panic::catch_unwind(|| {
139        let paths = upgrade::Paths::current(cwd)?;
140        let env = claude_telemetry::Environment::current(&paths.claude_dir);
141        let credentials_root = paths
142            .project_root
143            .clone()
144            .unwrap_or_else(|| cwd.to_path_buf());
145        upgrade::run(&paths, crate::install_state::CURRENT_VERSION, &env, || {
146            claude_telemetry::telemetry_server_url(&credentials_root, None)
147        })
148    })
149    .unwrap_or_else(|_| {
150        eprintln!("tracevault: the upgrade step failed unexpectedly");
151        None
152    })
153}
154
155#[cfg(test)]
156mod tests {
157    use super::*;
158
159    #[test]
160    fn record_storage_root_skips_a_fallback_root() {
161        let state = tempfile::tempdir().unwrap();
162        let nowhere = tempfile::tempdir().unwrap();
163        assert!(!record_storage_root(state.path(), nowhere.path(), "sess-1").unwrap());
164        assert_eq!(
165            crate::session_state::load_from(state.path(), "sess-1").storage_root,
166            None
167        );
168    }
169
170    #[test]
171    fn record_storage_root_records_an_ancestor_tracevault_dir() {
172        let state = tempfile::tempdir().unwrap();
173        let umbrella = tempfile::tempdir().unwrap();
174        std::fs::create_dir(umbrella.path().join(".tracevault")).unwrap();
175        let sub = umbrella.path().join("notes");
176        std::fs::create_dir(&sub).unwrap();
177        assert!(record_storage_root(state.path(), &sub, "sess-1").unwrap());
178        assert_eq!(
179            crate::session_state::load_from(state.path(), "sess-1").storage_root,
180            Some(umbrella.path().to_string_lossy().into_owned())
181        );
182    }
183
184    #[test]
185    fn write_session_env_appends_export_line() {
186        let dir = tempfile::tempdir().unwrap();
187        let env_file = dir.path().join("env.sh");
188
189        write_session_env(&env_file, "sess-123").unwrap();
190
191        let content = std::fs::read_to_string(&env_file).unwrap();
192        assert_eq!(content, "export TRACEVAULT_SESSION_ID='sess-123'\n");
193    }
194
195    #[test]
196    fn write_session_env_appends_on_repeated_calls_with_different_ids() {
197        let dir = tempfile::tempdir().unwrap();
198        let env_file = dir.path().join("env.sh");
199
200        write_session_env(&env_file, "sess-a").unwrap();
201        write_session_env(&env_file, "sess-b").unwrap();
202
203        let content = std::fs::read_to_string(&env_file).unwrap();
204        let lines: Vec<&str> = content.lines().collect();
205        assert_eq!(
206            lines,
207            vec![
208                "export TRACEVAULT_SESSION_ID='sess-a'",
209                "export TRACEVAULT_SESSION_ID='sess-b'",
210            ]
211        );
212    }
213
214    #[test]
215    fn write_session_env_is_idempotent_for_repeated_calls_with_same_id() {
216        // SessionStart fires on startup, resume, clear, AND compact — all
217        // with the SAME session id — so repeated calls for the same id must
218        // not grow the file with duplicate export lines.
219        let dir = tempfile::tempdir().unwrap();
220        let env_file = dir.path().join("env.sh");
221
222        write_session_env(&env_file, "sess-a").unwrap();
223        write_session_env(&env_file, "sess-a").unwrap();
224        write_session_env(&env_file, "sess-a").unwrap();
225
226        let content = std::fs::read_to_string(&env_file).unwrap();
227        let lines: Vec<&str> = content.lines().collect();
228        assert_eq!(lines, vec!["export TRACEVAULT_SESSION_ID='sess-a'"]);
229    }
230
231    #[test]
232    fn write_session_env_creates_missing_file() {
233        let dir = tempfile::tempdir().unwrap();
234        let env_file = dir.path().join("nested").join("env.sh");
235        // Parent dir does not exist — OpenOptions::create only creates the
236        // file itself, not parent dirs, so this must error rather than panic.
237        assert!(write_session_env(&env_file, "sess-x").is_err());
238    }
239
240    #[test]
241    fn write_session_env_quotes_valid_uuid() {
242        let dir = tempfile::tempdir().unwrap();
243        let env_file = dir.path().join("env.sh");
244        let uuid = "0190a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b";
245
246        write_session_env(&env_file, uuid).unwrap();
247
248        let content = std::fs::read_to_string(&env_file).unwrap();
249        assert_eq!(content, format!("export TRACEVAULT_SESSION_ID='{uuid}'\n"));
250    }
251
252    #[test]
253    fn write_session_env_skips_unsafe_session_id() {
254        let dir = tempfile::tempdir().unwrap();
255        let env_file = dir.path().join("env.sh");
256
257        // Shell-metacharacter / path-traversal ids must never be written.
258        write_session_env(&env_file, "x; rm -rf /").unwrap();
259        write_session_env(&env_file, "../evil").unwrap();
260
261        // Nothing was written — the file wasn't even created for the first
262        // call, and the second call didn't add anything either.
263        match std::fs::read_to_string(&env_file) {
264            Ok(content) => assert!(content.is_empty()),
265            Err(e) => assert_eq!(e.kind(), std::io::ErrorKind::NotFound),
266        }
267    }
268}