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#[cfg(test)]
103mod tests {
104    use super::*;
105
106    fn binding(id: &str) -> RepoBinding {
107        RepoBinding {
108            org_slug: "org".into(),
109            repo_id: id.into(),
110            git_url: None,
111            updated_at: "t".into(),
112        }
113    }
114
115    #[test]
116    fn save_in_then_load_in_round_trips() {
117        let tmp = tempfile::tempdir().unwrap();
118        let s = SessionState {
119            active: Some(binding("r1")),
120            subagents: HashMap::from([("/wt/a".to_string(), binding("r2"))]),
121            ..Default::default()
122        };
123        save_in(tmp.path(), "sess-1", &s).unwrap();
124        assert_eq!(load_in(tmp.path(), "sess-1"), s);
125    }
126
127    #[test]
128    fn load_in_missing_returns_default() {
129        let tmp = tempfile::tempdir().unwrap();
130        assert_eq!(
131            load_in(tmp.path(), "no-such-session"),
132            SessionState::default()
133        );
134    }
135
136    #[test]
137    fn rejects_unsafe_session_ids() {
138        let tmp = tempfile::tempdir().unwrap();
139        let s = SessionState::default();
140        // Path-traversal / separator ids must be refused, never written to disk.
141        assert!(save_in(tmp.path(), "../evil", &s).is_err());
142        assert!(save_in(tmp.path(), "a/b", &s).is_err());
143        assert!(save_in(tmp.path(), "", &s).is_err());
144        // load of an unsafe id never touches disk; returns the default.
145        assert_eq!(load_in(tmp.path(), "../evil"), SessionState::default());
146        // A UUID-style id is accepted.
147        assert!(save_in(tmp.path(), "0190a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b", &s).is_ok());
148    }
149
150    #[test]
151    fn save_in_is_atomic_and_leaves_no_tmp() {
152        let tmp = tempfile::tempdir().unwrap();
153        let s = SessionState {
154            active: Some(binding("r1")),
155            subagents: HashMap::new(),
156            ..Default::default()
157        };
158        save_in(tmp.path(), "sess-atomic", &s).unwrap();
159        assert_eq!(load_in(tmp.path(), "sess-atomic"), s);
160        // no stray temp file
161        let leftover = std::fs::read_dir(tmp.path())
162            .unwrap()
163            .filter_map(|e| e.ok())
164            .any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
165        assert!(
166            !leftover,
167            "temp file should be renamed away, not left behind"
168        );
169    }
170}