Skip to main content

tracevault_cli/
session_state.rs

1//! Per-session workspace-mode state: which repo a roaming/detached Claude Code
2//! session is currently bound to. Persisted outside any repo so it survives a
3//! session that changes directories. Set by `tracevault repo switch`
4//! (sub-plan B); read by `stream`/commands as a resolution fallback.
5
6use std::collections::HashMap;
7use std::path::PathBuf;
8
9use serde::{Deserialize, Serialize};
10
11/// A resolved binding to a registered repo.
12#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
13pub struct RepoBinding {
14    pub repo_id: String,
15    #[serde(default, skip_serializing_if = "Option::is_none")]
16    pub git_url: Option<String>,
17    #[serde(default, skip_serializing_if = "Option::is_none")]
18    pub remote_id: Option<uuid::Uuid>,
19    #[serde(default, skip_serializing_if = "Option::is_none")]
20    pub codebase_name: Option<String>,
21    pub updated_at: String,
22}
23
24/// A resolved binding to a registered project.
25#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
26pub struct ProjectBinding {
27    pub project_id: String,
28    pub project_name: String,
29    pub updated_at: String,
30    /// RFC3339 instant after which the FORCE lapses (the binding itself
31    /// survives). Only ever set by `project switch --project-attribution
32    /// explicit`, which persists to disk and can therefore be forgotten.
33    /// Environment-provided force is exempt: it is re-asserted at every launch
34    /// by construction, so it cannot go stale and needs no expiry.
35    /// Interpreted by exactly one function, [`force_status`].
36    #[serde(default, skip_serializing_if = "Option::is_none")]
37    pub forced_until: Option<String>,
38}
39
40/// What a [`ProjectBinding::forced_until`] currently says about its force.
41///
42/// Lives here, beside the field it interprets, because both readers of that
43/// field are in `commands::` and this module depends on neither — so one
44/// place knows the stored format and both can reach it with no cycle.
45///
46/// There used to be two readers and no shared type:
47/// `commands::stream::attribution_mode` folded the question into a bool while
48/// `commands::project::format_force_line` did its own RFC3339 parse and
49/// `Utc::now()` comparison to choose between its active / lapsed / unreadable
50/// wordings — and a test existed purely to pin that the two independently
51/// written predicates agreed on the unparseable case, which is itself the
52/// evidence they could have drifted. That test now pins one implementation
53/// rather than reconciling two.
54#[derive(Debug, Clone, PartialEq, Eq)]
55pub enum ForceStatus {
56    /// Parsed, and still in the future: the force applies.
57    Live(chrono::DateTime<chrono::Utc>),
58    /// Parsed, but already past — the FORCE lapsed; the binding survives.
59    Lapsed(chrono::DateTime<chrono::Utc>),
60    /// Not RFC3339 at all (a hand-edited or corrupted state file).
61    Unreadable,
62}
63
64/// Classify a stored `forced_until` — see [`ForceStatus`].
65///
66/// [`ForceStatus::Unreadable`] is the fail-SAFE direction, and both callers
67/// depend on it: "can't tell" means NOT in force, never `expect()`-worthy.
68/// Not sending an `explicit` header IS the fallback, so ingest never starts
69/// failing because a force was forgotten or a timestamp got mangled.
70///
71/// A parsed instant is normalised to UTC so both arms can carry one type.
72/// `project switch` only ever writes `Utc::now() + …`, so in practice this
73/// changes nothing that is rendered back to the operator.
74pub fn force_status(forced_until: &str) -> ForceStatus {
75    match chrono::DateTime::parse_from_rfc3339(forced_until) {
76        Ok(until) => {
77            let until = until.with_timezone(&chrono::Utc);
78            if until > chrono::Utc::now() {
79                ForceStatus::Live(until)
80            } else {
81                ForceStatus::Lapsed(until)
82            }
83        }
84        Err(_) => ForceStatus::Unreadable,
85    }
86}
87
88/// Session-level active binding plus per-worktree subagent overrides
89/// (keyed by the subagent's git worktree toplevel path — design §7).
90#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
91pub struct SessionState {
92    #[serde(default, skip_serializing_if = "Option::is_none")]
93    pub active: Option<RepoBinding>,
94    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
95    pub subagents: HashMap<String, RepoBinding>,
96    /// The repo id whose policies were last injected into a hook response for
97    /// this session (sub-plan C). Used by `UserPromptSubmit` to avoid
98    /// re-injecting unchanged context on every prompt. `#[serde(default)]`
99    /// keeps old on-disk session files (without this field) loadable.
100    #[serde(default, skip_serializing_if = "Option::is_none")]
101    pub last_injected_repo: Option<String>,
102    #[serde(default, skip_serializing_if = "Option::is_none")]
103    pub active_project: Option<ProjectBinding>,
104    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
105    pub subagent_projects: HashMap<String, ProjectBinding>,
106    /// Origin remote URLs this session already looked up without binding
107    /// (unregistered, or ambiguous), so `auto_bind` asks the server once per
108    /// remote, not once per hook event — and says so once.
109    #[serde(default, skip_serializing_if = "Vec::is_empty")]
110    pub auto_bind_checked: Vec<String>,
111    /// Set by `repo reset`: the session stays unbound instead of being bound
112    /// again from its checkout's remote on the next hook event.
113    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
114    pub auto_bind_off: bool,
115}
116
117/// `$XDG_STATE_HOME/tracevault/sessions` or `~/.local/state/tracevault/sessions`.
118pub fn sessions_dir() -> Option<PathBuf> {
119    let base = std::env::var_os("XDG_STATE_HOME")
120        .map(PathBuf::from)
121        .or_else(|| dirs::home_dir().map(|h| h.join(".local").join("state")))?;
122    Some(base.join("tracevault").join("sessions"))
123}
124
125/// The session of the agent that runs this command, from its environment:
126/// `$TRACEVAULT_SESSION_ID` (exported by the Claude Code / Codex SessionStart
127/// hook), else `$AMP_CURRENT_THREAD_ID`.
128///
129/// Amp's plugin cannot export a variable into Amp's shell (it runs in a
130/// separate process), but that shell has the current thread id, and the Amp
131/// plugin uses the thread id as the TraceVault session id (VIS-1199). Empty
132/// values count as unset.
133pub fn env_session_id() -> Option<String> {
134    session_id_from_env(
135        std::env::var("TRACEVAULT_SESSION_ID").ok(),
136        std::env::var("AMP_CURRENT_THREAD_ID").ok(),
137    )
138}
139
140/// [`env_session_id`] on given values: `tracevault` wins, then `amp_thread`.
141pub fn session_id_from_env(
142    tracevault: Option<String>,
143    amp_thread: Option<String>,
144) -> Option<String> {
145    tracevault
146        .filter(|s| !s.is_empty())
147        .or_else(|| amp_thread.filter(|s| !s.is_empty()))
148}
149
150/// A session id is used to build the state file path, so it must be a safe
151/// filename token — no path separators or `..` that could escape the sessions
152/// directory. Claude Code session ids are UUIDs, which satisfy this.
153pub(crate) fn is_safe_session_id(session_id: &str) -> bool {
154    !session_id.is_empty()
155        && session_id
156            .chars()
157            .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
158}
159
160fn state_path_in(sessions_dir: &std::path::Path, session_id: &str) -> PathBuf {
161    sessions_dir.join(format!("{session_id}.toml"))
162}
163
164fn load_in(sessions_dir: &std::path::Path, session_id: &str) -> SessionState {
165    if !is_safe_session_id(session_id) {
166        return SessionState::default();
167    }
168    match std::fs::read_to_string(state_path_in(sessions_dir, session_id)) {
169        Ok(s) => toml::from_str(&s).unwrap_or_default(),
170        Err(_) => SessionState::default(),
171    }
172}
173
174fn save_in(
175    sessions_dir: &std::path::Path,
176    session_id: &str,
177    state: &SessionState,
178) -> Result<(), Box<dyn std::error::Error>> {
179    if !is_safe_session_id(session_id) {
180        return Err(format!("invalid session id: {session_id:?}").into());
181    }
182    std::fs::create_dir_all(sessions_dir)?;
183    let final_path = state_path_in(sessions_dir, session_id);
184    // Write to a temp file in the same dir, then atomically rename over the
185    // target so a crash or a concurrent reader never sees a partial/empty file.
186    let tmp_path = sessions_dir.join(format!("{session_id}.toml.tmp"));
187    std::fs::write(&tmp_path, toml::to_string(state)?)?;
188    std::fs::rename(&tmp_path, &final_path)?;
189    Ok(())
190}
191
192/// Load a session's state, returning the default (empty) state if the file is
193/// absent or malformed (workspace state is best-effort, never fatal).
194pub fn load(session_id: &str) -> SessionState {
195    match sessions_dir() {
196        Some(dir) => load_in(&dir, session_id),
197        None => SessionState::default(),
198    }
199}
200
201/// Persist a session's state, creating the state dir if needed.
202pub fn save(session_id: &str, state: &SessionState) -> Result<(), Box<dyn std::error::Error>> {
203    let dir = sessions_dir().ok_or("cannot determine state dir")?;
204    save_in(&dir, session_id, state)
205}
206
207/// Load a session's state from an explicit sessions dir (test seam / callers
208/// that resolve the dir themselves). Absent or malformed → default state.
209pub fn load_from(sessions_dir: &std::path::Path, session_id: &str) -> SessionState {
210    load_in(sessions_dir, session_id)
211}
212
213/// [`save`] into an explicit sessions dir — the write half of [`load_from`].
214pub fn save_to(
215    sessions_dir: &std::path::Path,
216    session_id: &str,
217    state: &SessionState,
218) -> Result<(), Box<dyn std::error::Error>> {
219    save_in(sessions_dir, session_id, state)
220}
221
222#[cfg(test)]
223mod tests {
224    use super::*;
225
226    #[test]
227    fn env_session_id_prefers_tracevault_then_amp_thread() {
228        let id = |tv: Option<&str>, amp: Option<&str>| {
229            session_id_from_env(tv.map(String::from), amp.map(String::from))
230        };
231        assert_eq!(id(Some("sess"), Some("T-1")).as_deref(), Some("sess"));
232        assert_eq!(id(None, Some("T-1")).as_deref(), Some("T-1"));
233        assert_eq!(id(Some(""), Some("T-1")).as_deref(), Some("T-1"));
234        assert_eq!(id(Some(""), Some("")), None);
235        assert_eq!(id(None, None), None);
236    }
237
238    fn binding(id: &str) -> RepoBinding {
239        RepoBinding {
240            repo_id: id.into(),
241            git_url: None,
242            remote_id: None,
243            codebase_name: None,
244            updated_at: "t".into(),
245        }
246    }
247
248    /// The single parse-and-compare both `commands::stream::attribution_mode`
249    /// and `commands::project::format_force_line` now go through. Each arm is
250    /// asserted here once so a change to the shared rule shows up in one
251    /// place, not only through its two callers.
252    #[test]
253    fn force_status_classifies_live_lapsed_and_unreadable() {
254        let future = chrono::Utc::now() + chrono::Duration::hours(4);
255        assert_eq!(
256            force_status(&future.to_rfc3339()),
257            ForceStatus::Live(future)
258        );
259        let past = chrono::Utc::now() - chrono::Duration::hours(1);
260        assert_eq!(force_status(&past.to_rfc3339()), ForceStatus::Lapsed(past));
261        // Fail-safe: unreadable is NOT in force, and never a panic.
262        assert_eq!(force_status("not-a-timestamp"), ForceStatus::Unreadable);
263        assert_eq!(force_status(""), ForceStatus::Unreadable);
264        // A non-UTC offset is normalised, not rejected.
265        assert_eq!(
266            force_status("2020-01-01T00:00:00+02:00"),
267            ForceStatus::Lapsed(
268                chrono::DateTime::parse_from_rfc3339("2020-01-01T00:00:00+02:00")
269                    .unwrap()
270                    .with_timezone(&chrono::Utc)
271            )
272        );
273    }
274
275    #[test]
276    fn save_in_then_load_in_round_trips() {
277        let tmp = tempfile::tempdir().unwrap();
278        let s = SessionState {
279            active: Some(binding("r1")),
280            subagents: HashMap::from([("/wt/a".to_string(), binding("r2"))]),
281            ..Default::default()
282        };
283        save_in(tmp.path(), "sess-1", &s).unwrap();
284        assert_eq!(load_in(tmp.path(), "sess-1"), s);
285    }
286
287    #[test]
288    fn load_in_missing_returns_default() {
289        let tmp = tempfile::tempdir().unwrap();
290        assert_eq!(
291            load_in(tmp.path(), "no-such-session"),
292            SessionState::default()
293        );
294    }
295
296    #[test]
297    fn rejects_unsafe_session_ids() {
298        let tmp = tempfile::tempdir().unwrap();
299        let s = SessionState::default();
300        // Path-traversal / separator ids must be refused, never written to disk.
301        assert!(save_in(tmp.path(), "../evil", &s).is_err());
302        assert!(save_in(tmp.path(), "a/b", &s).is_err());
303        assert!(save_in(tmp.path(), "", &s).is_err());
304        // load of an unsafe id never touches disk; returns the default.
305        assert_eq!(load_in(tmp.path(), "../evil"), SessionState::default());
306        // A UUID-style id is accepted.
307        assert!(save_in(tmp.path(), "0190a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b", &s).is_ok());
308    }
309
310    #[test]
311    fn load_from_reads_active_binding() {
312        let dir = tempfile::tempdir().unwrap();
313        save_in(
314            dir.path(),
315            "sess-1",
316            &SessionState {
317                active: Some(binding("r1")),
318                ..Default::default()
319            },
320        )
321        .unwrap();
322        let st = load_from(dir.path(), "sess-1");
323        assert_eq!(st.active.unwrap().repo_id, "r1");
324    }
325
326    #[test]
327    fn load_from_missing_is_default() {
328        let dir = tempfile::tempdir().unwrap();
329        assert_eq!(load_from(dir.path(), "nope"), SessionState::default());
330    }
331
332    #[test]
333    fn save_in_is_atomic_and_leaves_no_tmp() {
334        let tmp = tempfile::tempdir().unwrap();
335        let s = SessionState {
336            active: Some(binding("r1")),
337            subagents: HashMap::new(),
338            ..Default::default()
339        };
340        save_in(tmp.path(), "sess-atomic", &s).unwrap();
341        assert_eq!(load_in(tmp.path(), "sess-atomic"), s);
342        // no stray temp file
343        let leftover = std::fs::read_dir(tmp.path())
344            .unwrap()
345            .filter_map(|e| e.ok())
346            .any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
347        assert!(
348            !leftover,
349            "temp file should be renamed away, not left behind"
350        );
351    }
352
353    #[test]
354    fn session_state_carries_project_bindings() {
355        let tmp = tempfile::tempdir().unwrap();
356        let pb = ProjectBinding {
357            project_id: "11111111-1111-1111-1111-111111111111".into(),
358            project_name: "payments".into(),
359            updated_at: "t".into(),
360            forced_until: None,
361        };
362        let mut subagent_projects = HashMap::new();
363        subagent_projects.insert("/wt".into(), pb.clone());
364        let st = SessionState {
365            active_project: Some(pb.clone()),
366            subagent_projects,
367            ..Default::default()
368        };
369        save_in(tmp.path(), "sess-1", &st).unwrap();
370        let loaded = load_from(tmp.path(), "sess-1");
371        assert_eq!(loaded.active_project, Some(pb.clone()));
372        assert_eq!(loaded.subagent_projects.get("/wt"), Some(&pb));
373    }
374}