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