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 org_slug: String,
15    pub repo_id: String,
16    #[serde(default, skip_serializing_if = "Option::is_none")]
17    pub git_url: Option<String>,
18    pub updated_at: String,
19}
20
21/// Session-level active binding plus per-worktree subagent overrides
22/// (keyed by the subagent's git worktree toplevel path โ€” design ยง7).
23#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
24pub struct SessionState {
25    #[serde(default, skip_serializing_if = "Option::is_none")]
26    pub active: Option<RepoBinding>,
27    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
28    pub subagents: HashMap<String, RepoBinding>,
29    /// The repo id whose policies were last injected into a hook response for
30    /// this session (sub-plan C). Used by `UserPromptSubmit` to avoid
31    /// re-injecting unchanged context on every prompt. `#[serde(default)]`
32    /// keeps old on-disk session files (without this field) loadable.
33    #[serde(default, skip_serializing_if = "Option::is_none")]
34    pub last_injected_repo: Option<String>,
35}
36
37/// `$XDG_STATE_HOME/tracevault/sessions` or `~/.local/state/tracevault/sessions`.
38pub fn sessions_dir() -> Option<PathBuf> {
39    let base = std::env::var_os("XDG_STATE_HOME")
40        .map(PathBuf::from)
41        .or_else(|| dirs::home_dir().map(|h| h.join(".local").join("state")))?;
42    Some(base.join("tracevault").join("sessions"))
43}
44
45/// A session id is used to build the state file path, so it must be a safe
46/// filename token โ€” no path separators or `..` that could escape the sessions
47/// directory. Claude Code session ids are UUIDs, which satisfy this.
48pub(crate) fn is_safe_session_id(session_id: &str) -> bool {
49    !session_id.is_empty()
50        && session_id
51            .chars()
52            .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
53}
54
55fn state_path_in(sessions_dir: &std::path::Path, session_id: &str) -> PathBuf {
56    sessions_dir.join(format!("{session_id}.toml"))
57}
58
59fn load_in(sessions_dir: &std::path::Path, session_id: &str) -> SessionState {
60    if !is_safe_session_id(session_id) {
61        return SessionState::default();
62    }
63    match std::fs::read_to_string(state_path_in(sessions_dir, session_id)) {
64        Ok(s) => toml::from_str(&s).unwrap_or_default(),
65        Err(_) => SessionState::default(),
66    }
67}
68
69fn save_in(
70    sessions_dir: &std::path::Path,
71    session_id: &str,
72    state: &SessionState,
73) -> Result<(), Box<dyn std::error::Error>> {
74    if !is_safe_session_id(session_id) {
75        return Err(format!("invalid session id: {session_id:?}").into());
76    }
77    std::fs::create_dir_all(sessions_dir)?;
78    let final_path = state_path_in(sessions_dir, session_id);
79    // Write to a temp file in the same dir, then atomically rename over the
80    // target so a crash or a concurrent reader never sees a partial/empty file.
81    let tmp_path = sessions_dir.join(format!("{session_id}.toml.tmp"));
82    std::fs::write(&tmp_path, toml::to_string(state)?)?;
83    std::fs::rename(&tmp_path, &final_path)?;
84    Ok(())
85}
86
87/// Load a session's state, returning the default (empty) state if the file is
88/// absent or malformed (workspace state is best-effort, never fatal).
89pub fn load(session_id: &str) -> SessionState {
90    match sessions_dir() {
91        Some(dir) => load_in(&dir, session_id),
92        None => SessionState::default(),
93    }
94}
95
96/// Persist a session's state, creating the state dir if needed.
97pub fn save(session_id: &str, state: &SessionState) -> Result<(), Box<dyn std::error::Error>> {
98    let dir = sessions_dir().ok_or("cannot determine state dir")?;
99    save_in(&dir, session_id, state)
100}
101
102/// Load a session's state from an explicit sessions dir (test seam / callers
103/// that resolve the dir themselves). Absent or malformed โ†’ default state.
104pub fn load_from(sessions_dir: &std::path::Path, session_id: &str) -> SessionState {
105    load_in(sessions_dir, session_id)
106}
107
108#[cfg(test)]
109mod tests {
110    use super::*;
111
112    fn binding(id: &str) -> RepoBinding {
113        RepoBinding {
114            org_slug: "org".into(),
115            repo_id: id.into(),
116            git_url: None,
117            updated_at: "t".into(),
118        }
119    }
120
121    #[test]
122    fn save_in_then_load_in_round_trips() {
123        let tmp = tempfile::tempdir().unwrap();
124        let s = SessionState {
125            active: Some(binding("r1")),
126            subagents: HashMap::from([("/wt/a".to_string(), binding("r2"))]),
127            ..Default::default()
128        };
129        save_in(tmp.path(), "sess-1", &s).unwrap();
130        assert_eq!(load_in(tmp.path(), "sess-1"), s);
131    }
132
133    #[test]
134    fn load_in_missing_returns_default() {
135        let tmp = tempfile::tempdir().unwrap();
136        assert_eq!(
137            load_in(tmp.path(), "no-such-session"),
138            SessionState::default()
139        );
140    }
141
142    #[test]
143    fn rejects_unsafe_session_ids() {
144        let tmp = tempfile::tempdir().unwrap();
145        let s = SessionState::default();
146        // Path-traversal / separator ids must be refused, never written to disk.
147        assert!(save_in(tmp.path(), "../evil", &s).is_err());
148        assert!(save_in(tmp.path(), "a/b", &s).is_err());
149        assert!(save_in(tmp.path(), "", &s).is_err());
150        // load of an unsafe id never touches disk; returns the default.
151        assert_eq!(load_in(tmp.path(), "../evil"), SessionState::default());
152        // A UUID-style id is accepted.
153        assert!(save_in(tmp.path(), "0190a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b", &s).is_ok());
154    }
155
156    #[test]
157    fn load_from_reads_active_binding() {
158        let dir = tempfile::tempdir().unwrap();
159        save_in(
160            dir.path(),
161            "sess-1",
162            &SessionState {
163                active: Some(binding("r1")),
164                ..Default::default()
165            },
166        )
167        .unwrap();
168        let st = load_from(dir.path(), "sess-1");
169        assert_eq!(st.active.unwrap().repo_id, "r1");
170    }
171
172    #[test]
173    fn load_from_missing_is_default() {
174        let dir = tempfile::tempdir().unwrap();
175        assert_eq!(load_from(dir.path(), "nope"), SessionState::default());
176    }
177
178    #[test]
179    fn save_in_is_atomic_and_leaves_no_tmp() {
180        let tmp = tempfile::tempdir().unwrap();
181        let s = SessionState {
182            active: Some(binding("r1")),
183            subagents: HashMap::new(),
184            ..Default::default()
185        };
186        save_in(tmp.path(), "sess-atomic", &s).unwrap();
187        assert_eq!(load_in(tmp.path(), "sess-atomic"), s);
188        // no stray temp file
189        let leftover = std::fs::read_dir(tmp.path())
190            .unwrap()
191            .filter_map(|e| e.ok())
192            .any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
193        assert!(
194            !leftover,
195            "temp file should be renamed away, not left behind"
196        );
197    }
198}