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}
107
108/// `$XDG_STATE_HOME/tracevault/sessions` or `~/.local/state/tracevault/sessions`.
109pub fn sessions_dir() -> Option<PathBuf> {
110    let base = std::env::var_os("XDG_STATE_HOME")
111        .map(PathBuf::from)
112        .or_else(|| dirs::home_dir().map(|h| h.join(".local").join("state")))?;
113    Some(base.join("tracevault").join("sessions"))
114}
115
116/// A session id is used to build the state file path, so it must be a safe
117/// filename token — no path separators or `..` that could escape the sessions
118/// directory. Claude Code session ids are UUIDs, which satisfy this.
119pub(crate) fn is_safe_session_id(session_id: &str) -> bool {
120    !session_id.is_empty()
121        && session_id
122            .chars()
123            .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
124}
125
126fn state_path_in(sessions_dir: &std::path::Path, session_id: &str) -> PathBuf {
127    sessions_dir.join(format!("{session_id}.toml"))
128}
129
130fn load_in(sessions_dir: &std::path::Path, session_id: &str) -> SessionState {
131    if !is_safe_session_id(session_id) {
132        return SessionState::default();
133    }
134    match std::fs::read_to_string(state_path_in(sessions_dir, session_id)) {
135        Ok(s) => toml::from_str(&s).unwrap_or_default(),
136        Err(_) => SessionState::default(),
137    }
138}
139
140fn save_in(
141    sessions_dir: &std::path::Path,
142    session_id: &str,
143    state: &SessionState,
144) -> Result<(), Box<dyn std::error::Error>> {
145    if !is_safe_session_id(session_id) {
146        return Err(format!("invalid session id: {session_id:?}").into());
147    }
148    std::fs::create_dir_all(sessions_dir)?;
149    let final_path = state_path_in(sessions_dir, session_id);
150    // Write to a temp file in the same dir, then atomically rename over the
151    // target so a crash or a concurrent reader never sees a partial/empty file.
152    let tmp_path = sessions_dir.join(format!("{session_id}.toml.tmp"));
153    std::fs::write(&tmp_path, toml::to_string(state)?)?;
154    std::fs::rename(&tmp_path, &final_path)?;
155    Ok(())
156}
157
158/// Load a session's state, returning the default (empty) state if the file is
159/// absent or malformed (workspace state is best-effort, never fatal).
160pub fn load(session_id: &str) -> SessionState {
161    match sessions_dir() {
162        Some(dir) => load_in(&dir, session_id),
163        None => SessionState::default(),
164    }
165}
166
167/// Persist a session's state, creating the state dir if needed.
168pub fn save(session_id: &str, state: &SessionState) -> Result<(), Box<dyn std::error::Error>> {
169    let dir = sessions_dir().ok_or("cannot determine state dir")?;
170    save_in(&dir, session_id, state)
171}
172
173/// Load a session's state from an explicit sessions dir (test seam / callers
174/// that resolve the dir themselves). Absent or malformed → default state.
175pub fn load_from(sessions_dir: &std::path::Path, session_id: &str) -> SessionState {
176    load_in(sessions_dir, session_id)
177}
178
179#[cfg(test)]
180mod tests {
181    use super::*;
182
183    fn binding(id: &str) -> RepoBinding {
184        RepoBinding {
185            repo_id: id.into(),
186            git_url: None,
187            remote_id: None,
188            codebase_name: None,
189            updated_at: "t".into(),
190        }
191    }
192
193    /// The single parse-and-compare both `commands::stream::attribution_mode`
194    /// and `commands::project::format_force_line` now go through. Each arm is
195    /// asserted here once so a change to the shared rule shows up in one
196    /// place, not only through its two callers.
197    #[test]
198    fn force_status_classifies_live_lapsed_and_unreadable() {
199        let future = chrono::Utc::now() + chrono::Duration::hours(4);
200        assert_eq!(
201            force_status(&future.to_rfc3339()),
202            ForceStatus::Live(future)
203        );
204        let past = chrono::Utc::now() - chrono::Duration::hours(1);
205        assert_eq!(force_status(&past.to_rfc3339()), ForceStatus::Lapsed(past));
206        // Fail-safe: unreadable is NOT in force, and never a panic.
207        assert_eq!(force_status("not-a-timestamp"), ForceStatus::Unreadable);
208        assert_eq!(force_status(""), ForceStatus::Unreadable);
209        // A non-UTC offset is normalised, not rejected.
210        assert_eq!(
211            force_status("2020-01-01T00:00:00+02:00"),
212            ForceStatus::Lapsed(
213                chrono::DateTime::parse_from_rfc3339("2020-01-01T00:00:00+02:00")
214                    .unwrap()
215                    .with_timezone(&chrono::Utc)
216            )
217        );
218    }
219
220    #[test]
221    fn save_in_then_load_in_round_trips() {
222        let tmp = tempfile::tempdir().unwrap();
223        let s = SessionState {
224            active: Some(binding("r1")),
225            subagents: HashMap::from([("/wt/a".to_string(), binding("r2"))]),
226            ..Default::default()
227        };
228        save_in(tmp.path(), "sess-1", &s).unwrap();
229        assert_eq!(load_in(tmp.path(), "sess-1"), s);
230    }
231
232    #[test]
233    fn load_in_missing_returns_default() {
234        let tmp = tempfile::tempdir().unwrap();
235        assert_eq!(
236            load_in(tmp.path(), "no-such-session"),
237            SessionState::default()
238        );
239    }
240
241    #[test]
242    fn rejects_unsafe_session_ids() {
243        let tmp = tempfile::tempdir().unwrap();
244        let s = SessionState::default();
245        // Path-traversal / separator ids must be refused, never written to disk.
246        assert!(save_in(tmp.path(), "../evil", &s).is_err());
247        assert!(save_in(tmp.path(), "a/b", &s).is_err());
248        assert!(save_in(tmp.path(), "", &s).is_err());
249        // load of an unsafe id never touches disk; returns the default.
250        assert_eq!(load_in(tmp.path(), "../evil"), SessionState::default());
251        // A UUID-style id is accepted.
252        assert!(save_in(tmp.path(), "0190a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b", &s).is_ok());
253    }
254
255    #[test]
256    fn load_from_reads_active_binding() {
257        let dir = tempfile::tempdir().unwrap();
258        save_in(
259            dir.path(),
260            "sess-1",
261            &SessionState {
262                active: Some(binding("r1")),
263                ..Default::default()
264            },
265        )
266        .unwrap();
267        let st = load_from(dir.path(), "sess-1");
268        assert_eq!(st.active.unwrap().repo_id, "r1");
269    }
270
271    #[test]
272    fn load_from_missing_is_default() {
273        let dir = tempfile::tempdir().unwrap();
274        assert_eq!(load_from(dir.path(), "nope"), SessionState::default());
275    }
276
277    #[test]
278    fn save_in_is_atomic_and_leaves_no_tmp() {
279        let tmp = tempfile::tempdir().unwrap();
280        let s = SessionState {
281            active: Some(binding("r1")),
282            subagents: HashMap::new(),
283            ..Default::default()
284        };
285        save_in(tmp.path(), "sess-atomic", &s).unwrap();
286        assert_eq!(load_in(tmp.path(), "sess-atomic"), s);
287        // no stray temp file
288        let leftover = std::fs::read_dir(tmp.path())
289            .unwrap()
290            .filter_map(|e| e.ok())
291            .any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
292        assert!(
293            !leftover,
294            "temp file should be renamed away, not left behind"
295        );
296    }
297
298    #[test]
299    fn session_state_carries_project_bindings() {
300        let tmp = tempfile::tempdir().unwrap();
301        let pb = ProjectBinding {
302            project_id: "11111111-1111-1111-1111-111111111111".into(),
303            project_name: "payments".into(),
304            updated_at: "t".into(),
305            forced_until: None,
306        };
307        let mut subagent_projects = HashMap::new();
308        subagent_projects.insert("/wt".into(), pb.clone());
309        let st = SessionState {
310            active_project: Some(pb.clone()),
311            subagent_projects,
312            ..Default::default()
313        };
314        save_in(tmp.path(), "sess-1", &st).unwrap();
315        let loaded = load_from(tmp.path(), "sess-1");
316        assert_eq!(loaded.active_project, Some(pb.clone()));
317        assert_eq!(loaded.subagent_projects.get("/wt"), Some(&pb));
318    }
319}