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 two things, both 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//!
15//! This hook must NEVER hard-fail: a failing `SessionStart` hook blocks
16//! Claude Code from starting the session. Every fallible step below is
17//! handled internally, and the function always prints a valid `HookOutput`
18//! JSON payload before returning `Ok(())`.
19
20use std::path::Path;
21
22use crate::commands::session_hooks::{read_hook_event_or_allow, resolve_and_inject};
23
24/// Append `export TRACEVAULT_SESSION_ID='<session_id>'` to the Claude Code
25/// session env file, unless that exact line is already present. Pure I/O
26/// helper factored out so it can be unit-tested without touching the real
27/// `CLAUDE_ENV_FILE` env var. Creates the file if it doesn't exist.
28///
29/// `SessionStart` fires on startup *and* on resume/clear/compact — all with
30/// the same session id — so an unconditional append would grow the env file
31/// with duplicate export lines every time. Reading the file first and
32/// skipping an already-present line makes the write idempotent.
33///
34/// `session_id` is untrusted input from the hook event JSON, and this file is
35/// later `source`d by the shell — a naive unquoted interpolation would be a
36/// shell-injection sink. Defend in depth: reject anything outside the
37/// existing session-id allowlist (`[A-Za-z0-9_-]`, non-empty) by silently
38/// skipping the write (best-effort: a malformed id is simply never
39/// exported), and single-quote the value we do write. After the allowlist
40/// check there are no quote or metacharacters left, so single-quoting closes
41/// the sink.
42pub fn write_session_env(env_file: &Path, session_id: &str) -> std::io::Result<()> {
43 use std::io::Write as _;
44 if !crate::session_state::is_safe_session_id(session_id) {
45 return Ok(());
46 }
47 let line = format!("export TRACEVAULT_SESSION_ID='{session_id}'");
48
49 if let Ok(existing) = std::fs::read_to_string(env_file) {
50 if existing.lines().any(|l| l == line) {
51 return Ok(());
52 }
53 }
54
55 let mut file = std::fs::OpenOptions::new()
56 .create(true)
57 .append(true)
58 .open(env_file)?;
59 writeln!(file, "{line}")
60}
61
62pub async fn run() -> Result<(), Box<dyn std::error::Error>> {
63 // 1. Read the hook event from stdin. A parse error must never fail the
64 // hook — print the minimal allow response and return Ok.
65 let Some(hook_event) = read_hook_event_or_allow() else {
66 return Ok(());
67 };
68
69 // 2. Export the session id, best-effort. Older Claude Code versions don't
70 // set CLAUDE_ENV_FILE — silently skip in that case.
71 if let Ok(env_file) = std::env::var("CLAUDE_ENV_FILE") {
72 let _ = write_session_env(Path::new(&env_file), &hook_event.session_id);
73 }
74
75 // 3. Resolve the effective repo binding and, if warranted, inject its
76 // policies. Shared with `user-prompt` (sub-plan C's UserPromptSubmit hook).
77 resolve_and_inject(&hook_event).await
78}
79
80#[cfg(test)]
81mod tests {
82 use super::*;
83
84 #[test]
85 fn write_session_env_appends_export_line() {
86 let dir = tempfile::tempdir().unwrap();
87 let env_file = dir.path().join("env.sh");
88
89 write_session_env(&env_file, "sess-123").unwrap();
90
91 let content = std::fs::read_to_string(&env_file).unwrap();
92 assert_eq!(content, "export TRACEVAULT_SESSION_ID='sess-123'\n");
93 }
94
95 #[test]
96 fn write_session_env_appends_on_repeated_calls_with_different_ids() {
97 let dir = tempfile::tempdir().unwrap();
98 let env_file = dir.path().join("env.sh");
99
100 write_session_env(&env_file, "sess-a").unwrap();
101 write_session_env(&env_file, "sess-b").unwrap();
102
103 let content = std::fs::read_to_string(&env_file).unwrap();
104 let lines: Vec<&str> = content.lines().collect();
105 assert_eq!(
106 lines,
107 vec![
108 "export TRACEVAULT_SESSION_ID='sess-a'",
109 "export TRACEVAULT_SESSION_ID='sess-b'",
110 ]
111 );
112 }
113
114 #[test]
115 fn write_session_env_is_idempotent_for_repeated_calls_with_same_id() {
116 // SessionStart fires on startup, resume, clear, AND compact — all
117 // with the SAME session id — so repeated calls for the same id must
118 // not grow the file with duplicate export lines.
119 let dir = tempfile::tempdir().unwrap();
120 let env_file = dir.path().join("env.sh");
121
122 write_session_env(&env_file, "sess-a").unwrap();
123 write_session_env(&env_file, "sess-a").unwrap();
124 write_session_env(&env_file, "sess-a").unwrap();
125
126 let content = std::fs::read_to_string(&env_file).unwrap();
127 let lines: Vec<&str> = content.lines().collect();
128 assert_eq!(lines, vec!["export TRACEVAULT_SESSION_ID='sess-a'"]);
129 }
130
131 #[test]
132 fn write_session_env_creates_missing_file() {
133 let dir = tempfile::tempdir().unwrap();
134 let env_file = dir.path().join("nested").join("env.sh");
135 // Parent dir does not exist — OpenOptions::create only creates the
136 // file itself, not parent dirs, so this must error rather than panic.
137 assert!(write_session_env(&env_file, "sess-x").is_err());
138 }
139
140 #[test]
141 fn write_session_env_quotes_valid_uuid() {
142 let dir = tempfile::tempdir().unwrap();
143 let env_file = dir.path().join("env.sh");
144 let uuid = "0190a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b";
145
146 write_session_env(&env_file, uuid).unwrap();
147
148 let content = std::fs::read_to_string(&env_file).unwrap();
149 assert_eq!(content, format!("export TRACEVAULT_SESSION_ID='{uuid}'\n"));
150 }
151
152 #[test]
153 fn write_session_env_skips_unsafe_session_id() {
154 let dir = tempfile::tempdir().unwrap();
155 let env_file = dir.path().join("env.sh");
156
157 // Shell-metacharacter / path-traversal ids must never be written.
158 write_session_env(&env_file, "x; rm -rf /").unwrap();
159 write_session_env(&env_file, "../evil").unwrap();
160
161 // Nothing was written — the file wasn't even created for the first
162 // call, and the second call didn't add anything either.
163 match std::fs::read_to_string(&env_file) {
164 Ok(content) => assert!(content.is_empty()),
165 Err(e) => assert_eq!(e.kind(), std::io::ErrorKind::NotFound),
166 }
167 }
168}