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