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 crate::program::TOP;
25use std::path::Path;
26
27use crate::commands::session_hooks::{read_hook_event_or_allow, resolve_and_inject};
28
29/// Append `export TRACEVAULT_SESSION_ID='<session_id>'` to the Claude Code
30/// session env file, unless that exact line is already present. Pure I/O
31/// helper factored out so it can be unit-tested without touching the real
32/// `CLAUDE_ENV_FILE` env var. Creates the file if it doesn't exist.
33///
34/// `SessionStart` fires on startup *and* on resume/clear/compact — all with
35/// the same session id — so an unconditional append would grow the env file
36/// with duplicate export lines every time. Reading the file first and
37/// skipping an already-present line makes the write idempotent.
38///
39/// `session_id` is untrusted input from the hook event JSON, and this file is
40/// later `source`d by the shell — a naive unquoted interpolation would be a
41/// shell-injection sink. Defend in depth: reject anything outside the
42/// existing session-id allowlist (`[A-Za-z0-9_-]`, non-empty) by silently
43/// skipping the write (best-effort: a malformed id is simply never
44/// exported), and single-quote the value we do write. After the allowlist
45/// check there are no quote or metacharacters left, so single-quoting closes
46/// the sink.
47pub fn write_session_env(env_file: &Path, session_id: &str) -> std::io::Result<()> {
48    write_session_env_as(env_file, session_id, crate::program::is_visdom())
49}
50
51/// [`write_session_env`] for the binary chosen by `visdom`.
52fn write_session_env_as(env_file: &Path, session_id: &str, visdom: bool) -> std::io::Result<()> {
53    use std::io::Write as _;
54    if !crate::session_state::is_safe_session_id(session_id) {
55        return Ok(());
56    }
57    // `TRACEVAULT_SESSION_ID` is what every command reads. Run as `visdom`,
58    // the variable is exported under that name as well: it is the one the
59    // messages name, and `visdom` takes it for the other.
60    let mut names = vec!["TRACEVAULT_SESSION_ID"];
61    if visdom {
62        names.push("VISDOM_SESSION_ID");
63    }
64    let existing = std::fs::read_to_string(env_file).unwrap_or_default();
65    let missing: Vec<String> = names
66        .iter()
67        .map(|name| format!("export {name}='{session_id}'"))
68        .filter(|line| !existing.lines().any(|l| l == line))
69        .collect();
70    if missing.is_empty() {
71        return Ok(());
72    }
73    let mut file = std::fs::OpenOptions::new()
74        .create(true)
75        .append(true)
76        .open(env_file)?;
77    for line in missing {
78        writeln!(file, "{line}")?;
79    }
80    Ok(())
81}
82
83pub async fn run() -> Result<(), Box<dyn std::error::Error>> {
84    let started = std::time::Instant::now();
85    // 1. Read the hook event from stdin. A parse error must never fail the
86    // hook — print the minimal allow response and return Ok.
87    let Some(hook_event) = read_hook_event_or_allow() else {
88        return Ok(());
89    };
90
91    // 2. Export the session id, best-effort. Older Claude Code versions don't
92    // set CLAUDE_ENV_FILE — silently skip in that case.
93    if let Ok(env_file) = std::env::var("CLAUDE_ENV_FILE") {
94        let _ = write_session_env(Path::new(&env_file), &hook_event.session_id);
95    }
96
97    // 2b. Anchor the session dir to where the session started (VIS-1257),
98    // before anything below can bind the session and save its state.
99    if let Some(dir) = crate::session_state::sessions_dir() {
100        let _ = record_storage_root(&dir, Path::new(&hook_event.cwd), &hook_event.session_id);
101    }
102
103    // 3. Once per CLI upgrade: refresh this repo's hooks and turn telemetry
104    // on (VIS-1109). Its notice is shown with whatever step 4 prints.
105    let notice = run_upgrade_step(Path::new(&hook_event.cwd));
106
107    // 4. Resolve the effective repo binding and, if warranted, inject its
108    // policies. Shared with `user-prompt` (sub-plan C's UserPromptSubmit hook).
109    let injected = resolve_and_inject(&hook_event, notice).await;
110
111    // 5. Send the cost reports earlier sessions of this repo left unsent
112    // (VIS-1108). After the response is printed, so it never delays it, and
113    // within what is left of the hook's timeout.
114    run_catch_up(Path::new(&hook_event.cwd), &hook_event.session_id, started).await;
115    injected
116}
117
118/// Record the `.visdom/` root `cwd` resolves to as the session's storage
119/// root (see [`crate::session_state::SessionState::storage_root`]) — unless
120/// nothing resolves there: a [`Fallback`](crate::paths::ProjectRootSource::Fallback)
121/// root would put a stray `.visdom/` in, say, the home directory and keep
122/// the session out of the repo it then works in, so that session keeps
123/// resolving per event. Best-effort; returns whether it wrote.
124fn record_storage_root(
125    sessions_dir: &Path,
126    cwd: &Path,
127    session_id: &str,
128) -> Result<bool, Box<dyn std::error::Error>> {
129    let resolved = crate::paths::resolve_project_root(cwd);
130    if resolved.source == crate::paths::ProjectRootSource::Fallback {
131        return Ok(false);
132    }
133    crate::session_state::record_storage_root(sessions_dir, session_id, &resolved.root)
134}
135
136/// [`catch_up::sweep`](crate::commands::catch_up::sweep) for the repo of a
137/// session in `cwd`, in a hook that started at `started`. It must never fail
138/// the hook, so a panic in it is caught too (a spawned task's panic is
139/// returned, not propagated).
140async fn run_catch_up(cwd: &Path, session_id: &str, started: std::time::Instant) {
141    use crate::commands::catch_up;
142    let project_root = crate::paths::resolve_project_root(cwd).root;
143    let deadline = catch_up::deadline(started, std::time::Instant::now());
144    let worktree = crate::paths::worktree_toplevel(cwd);
145    let sweep = catch_up::sweep(project_root, worktree, session_id.to_string(), deadline);
146    if tokio::spawn(sweep).await.is_err() {
147        eprintln!("{TOP}: the catch-up sweep failed unexpectedly");
148    }
149}
150
151/// [`upgrade::run`](crate::commands::upgrade::run) for a session in `cwd`.
152/// It must never fail the hook, so a panic in it is caught too.
153fn run_upgrade_step(cwd: &Path) -> Option<String> {
154    use crate::commands::{claude_telemetry, upgrade};
155    std::panic::catch_unwind(|| {
156        let paths = upgrade::Paths::current(cwd)?;
157        let env = claude_telemetry::Environment::current(&paths.claude_dir);
158        let credentials_root = paths
159            .project_root
160            .clone()
161            .unwrap_or_else(|| cwd.to_path_buf());
162        upgrade::run(&paths, crate::install_state::CURRENT_VERSION, &env, || {
163            claude_telemetry::telemetry_server_url(&credentials_root, None)
164        })
165    })
166    .unwrap_or_else(|_| {
167        eprintln!("{TOP}: the upgrade step failed unexpectedly");
168        None
169    })
170}
171
172#[cfg(test)]
173mod tests {
174    use super::*;
175
176    #[test]
177    fn record_storage_root_skips_a_fallback_root() {
178        let state = tempfile::tempdir().unwrap();
179        let nowhere = tempfile::tempdir().unwrap();
180        assert!(!record_storage_root(state.path(), nowhere.path(), "sess-1").unwrap());
181        assert_eq!(
182            crate::session_state::load_from(state.path(), "sess-1").storage_root,
183            None
184        );
185    }
186
187    #[test]
188    fn record_storage_root_records_an_ancestor_tracevault_dir() {
189        let state = tempfile::tempdir().unwrap();
190        let umbrella = tempfile::tempdir().unwrap();
191        std::fs::create_dir(umbrella.path().join(".visdom")).unwrap();
192        let sub = umbrella.path().join("notes");
193        std::fs::create_dir(&sub).unwrap();
194        assert!(record_storage_root(state.path(), &sub, "sess-1").unwrap());
195        assert_eq!(
196            crate::session_state::load_from(state.path(), "sess-1").storage_root,
197            Some(umbrella.path().to_string_lossy().into_owned())
198        );
199    }
200
201    #[test]
202    fn write_session_env_appends_export_line() {
203        let dir = tempfile::tempdir().unwrap();
204        let env_file = dir.path().join("env.sh");
205
206        write_session_env(&env_file, "sess-123").unwrap();
207
208        let content = std::fs::read_to_string(&env_file).unwrap();
209        assert_eq!(content, "export TRACEVAULT_SESSION_ID='sess-123'\n");
210    }
211
212    #[test]
213    fn write_session_env_appends_on_repeated_calls_with_different_ids() {
214        let dir = tempfile::tempdir().unwrap();
215        let env_file = dir.path().join("env.sh");
216
217        write_session_env(&env_file, "sess-a").unwrap();
218        write_session_env(&env_file, "sess-b").unwrap();
219
220        let content = std::fs::read_to_string(&env_file).unwrap();
221        let lines: Vec<&str> = content.lines().collect();
222        assert_eq!(
223            lines,
224            vec![
225                "export TRACEVAULT_SESSION_ID='sess-a'",
226                "export TRACEVAULT_SESSION_ID='sess-b'",
227            ]
228        );
229    }
230
231    #[test]
232    fn write_session_env_is_idempotent_for_repeated_calls_with_same_id() {
233        // SessionStart fires on startup, resume, clear, AND compact — all
234        // with the SAME session id — so repeated calls for the same id must
235        // not grow the file with duplicate export lines.
236        let dir = tempfile::tempdir().unwrap();
237        let env_file = dir.path().join("env.sh");
238
239        write_session_env(&env_file, "sess-a").unwrap();
240        write_session_env(&env_file, "sess-a").unwrap();
241        write_session_env(&env_file, "sess-a").unwrap();
242
243        let content = std::fs::read_to_string(&env_file).unwrap();
244        let lines: Vec<&str> = content.lines().collect();
245        assert_eq!(lines, vec!["export TRACEVAULT_SESSION_ID='sess-a'"]);
246    }
247
248    #[test]
249    fn write_session_env_creates_missing_file() {
250        let dir = tempfile::tempdir().unwrap();
251        let env_file = dir.path().join("nested").join("env.sh");
252        // Parent dir does not exist — OpenOptions::create only creates the
253        // file itself, not parent dirs, so this must error rather than panic.
254        assert!(write_session_env(&env_file, "sess-x").is_err());
255    }
256
257    #[test]
258    fn write_session_env_quotes_valid_uuid() {
259        let dir = tempfile::tempdir().unwrap();
260        let env_file = dir.path().join("env.sh");
261        let uuid = "0190a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b";
262
263        write_session_env(&env_file, uuid).unwrap();
264
265        let content = std::fs::read_to_string(&env_file).unwrap();
266        assert_eq!(content, format!("export TRACEVAULT_SESSION_ID='{uuid}'\n"));
267    }
268
269    #[test]
270    fn write_session_env_skips_unsafe_session_id() {
271        let dir = tempfile::tempdir().unwrap();
272        let env_file = dir.path().join("env.sh");
273
274        // Shell-metacharacter / path-traversal ids must never be written.
275        write_session_env(&env_file, "x; rm -rf /").unwrap();
276        write_session_env(&env_file, "../evil").unwrap();
277
278        // Nothing was written — the file wasn't even created for the first
279        // call, and the second call didn't add anything either.
280        match std::fs::read_to_string(&env_file) {
281            Ok(content) => assert!(content.is_empty()),
282            Err(e) => assert_eq!(e.kind(), std::io::ErrorKind::NotFound),
283        }
284    }
285
286    #[test]
287    fn run_as_visdom_the_session_id_is_exported_under_both_names_once() {
288        let dir = tempfile::tempdir().unwrap();
289        let env_file = dir.path().join("env");
290        // A line an earlier `tracevault` hook of this session already wrote.
291        write_session_env_as(&env_file, "sess-1", false).unwrap();
292        write_session_env_as(&env_file, "sess-1", true).unwrap();
293        write_session_env_as(&env_file, "sess-1", true).unwrap();
294        assert_eq!(
295            std::fs::read_to_string(&env_file).unwrap(),
296            "export TRACEVAULT_SESSION_ID='sess-1'\nexport VISDOM_SESSION_ID='sess-1'\n"
297        );
298        // A new id is appended under both names, after the old ones: the
299        // shell sources the file in order, so the last wins for each.
300        write_session_env_as(&env_file, "sess-2", true).unwrap();
301        assert!(std::fs::read_to_string(&env_file).unwrap().ends_with(
302            "export TRACEVAULT_SESSION_ID='sess-2'\nexport VISDOM_SESSION_ID='sess-2'\n"
303        ));
304    }
305}