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    /// The directory holding the `.visdom/` this session keeps its
116    /// session dir (`.stream_offset`, pending queues, `origin`) in, recorded
117    /// once by the `SessionStart` hook from where the session started
118    /// (VIS-1257). Claude Code's hook `cwd` follows the shell's `cd`, so
119    /// resolving it per event split a session that moved from an umbrella
120    /// dir into a child repo across two session dirs, each re-sending the
121    /// transcript from its own offset. Absent for sessions started before
122    /// this was recorded, and for agents without a `SessionStart` hook: those
123    /// keep resolving from each event's `cwd`. Read through [`storage_root`].
124    #[serde(default, skip_serializing_if = "Option::is_none")]
125    pub storage_root: Option<String>,
126    /// What each checkout this session touched resolves to for a project-only
127    /// session's events (VIS-1258), keyed by the checkout's git toplevel, so
128    /// the server is asked once per checkout and not once per event. Read and
129    /// written only through `crate::inferred_repo`.
130    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
131    pub inferred_repos: std::collections::BTreeMap<String, InferredRepo>,
132}
133
134/// One [`SessionState::inferred_repos`] entry: the repo a checkout resolved to
135/// within `project_id`, or none. A `None` repo is remembered only until
136/// `retry_after` (RFC3339), so a checkout registered or added to the project
137/// later is picked up without asking on every event. A found repo has no
138/// expiry: it is a fact about the server that changes only by a re-register.
139#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
140pub struct InferredRepo {
141    pub project_id: String,
142    #[serde(default, skip_serializing_if = "Option::is_none")]
143    pub retry_after: Option<String>,
144    #[serde(default, skip_serializing_if = "Option::is_none")]
145    pub repo: Option<RepoBinding>,
146}
147
148/// The session's recorded [`SessionState::storage_root`], if that directory
149/// still exists. Its `.visdom/` may not exist yet: a git root is recorded
150/// whether or not it has one, and the stream hook creates it on first use,
151/// exactly as it would for an event whose `cwd` resolved there.
152pub fn storage_root(state: &SessionState) -> Option<PathBuf> {
153    let root = PathBuf::from(state.storage_root.as_deref()?);
154    root.is_dir().then_some(root)
155}
156
157/// Inside an anchored session dir: every worktree toplevel the session ran
158/// an event in, one per line. The `origin` marker names only the latest, and
159/// `check` / `verify-start` in a checkout must still find a session that
160/// worked there and then moved on — as they did when the session kept a
161/// second dir in that checkout.
162pub const WORKTREES_FILE: &str = "worktrees";
163
164/// Add `worktree_top` to `session_dir`'s [`WORKTREES_FILE`] unless listed.
165pub fn record_worktree(session_dir: &std::path::Path, worktree_top: &str) -> std::io::Result<()> {
166    use std::io::Write as _;
167    let path = session_dir.join(WORKTREES_FILE);
168    if let Ok(existing) = std::fs::read_to_string(&path) {
169        if existing.lines().any(|l| l == worktree_top) {
170            return Ok(());
171        }
172    }
173    let mut f = std::fs::OpenOptions::new()
174        .create(true)
175        .append(true)
176        .open(&path)?;
177    writeln!(f, "{worktree_top}")
178}
179
180/// Whether the session in `session_dir` ran an event in `worktree_top`: its
181/// `origin` marker names it, or its [`WORKTREES_FILE`] lists it.
182pub fn ran_in(session_dir: &std::path::Path, worktree_top: &str) -> bool {
183    let names = |file: &str, all_lines: bool| {
184        std::fs::read_to_string(session_dir.join(file))
185            .map(|s| {
186                if all_lines {
187                    s.lines().any(|l| l == worktree_top)
188                } else {
189                    s.trim() == worktree_top
190                }
191            })
192            .unwrap_or(false)
193    };
194    names("origin", false) || names(WORKTREES_FILE, true)
195}
196
197/// The dirs of sessions anchored OUTSIDE `local_sessions_dir` (see
198/// [`SessionState::storage_root`]) that ran an event in `worktree_top`, read
199/// from the per-session state files in `state_dir`. A session started in an
200/// umbrella dir keeps its dir there, so the checkout it worked in has to look
201/// it up this way. Sorted; unreadable entries are skipped.
202pub fn anchored_session_dirs_in(
203    state_dir: &std::path::Path,
204    local_sessions_dir: &std::path::Path,
205    worktree_top: &str,
206) -> Vec<PathBuf> {
207    // Sessions an earlier release recorded are still in the legacy state dir.
208    let state_dirs = std::iter::once(state_dir.to_path_buf())
209        .chain(crate::layout::legacy_user_sessions_dir(state_dir));
210    let ids: std::collections::BTreeSet<String> = state_dirs
211        .filter_map(|dir| std::fs::read_dir(dir).ok())
212        .flatten()
213        .filter_map(|e| e.ok())
214        .filter_map(|e| Some(e.file_name().to_str()?.strip_suffix(".toml")?.to_string()))
215        .collect();
216    let mut dirs: Vec<PathBuf> = ids
217        .into_iter()
218        .filter_map(|id| {
219            let root = storage_root(&load_in(state_dir, &id))?;
220            let dir = crate::layout::session_dir(&root, &id);
221            let local = dir
222                .parent()
223                .is_some_and(|parent| is_local_sessions_dir(parent, local_sessions_dir));
224            (!local && dir.is_dir() && ran_in(&dir, worktree_top)).then_some(dir)
225        })
226        .collect();
227    dirs.sort();
228    dirs
229}
230
231/// Whether `dir` is the checkout's own sessions directory `local` — under
232/// either of the names its `.visdom/` directory has had.
233pub(crate) fn is_local_sessions_dir(dir: &std::path::Path, local: &std::path::Path) -> bool {
234    if dir == local {
235        return true;
236    }
237    match (
238        crate::layout::session_dir_root(&dir.join("x")),
239        crate::layout::session_dir_root(&local.join("x")),
240    ) {
241        (Some(a), Some(b)) => a == b,
242        _ => false,
243    }
244}
245
246/// [`anchored_session_dirs_in`] the user's state dir.
247pub fn anchored_session_dirs(
248    local_sessions_dir: &std::path::Path,
249    worktree_top: &str,
250) -> Vec<PathBuf> {
251    sessions_dir()
252        .map(|d| anchored_session_dirs_in(&d, local_sessions_dir, worktree_top))
253        .unwrap_or_default()
254}
255
256/// `<root>/.visdom/sessions/<session_id>` for `session_id` (or the
257/// `.tracevault/` one an earlier release started it in), where `root`
258/// is the session's recorded [`storage_root`], else `fallback_root` (the root
259/// resolved from the caller's working directory). Every reader and writer of
260/// a session dir goes through this, so a session is found where its hook
261/// keeps it.
262pub fn session_dir(fallback_root: &std::path::Path, session_id: &str) -> PathBuf {
263    let root = storage_root(&load(session_id)).unwrap_or_else(|| fallback_root.to_path_buf());
264    crate::layout::session_dir(&root, session_id)
265}
266
267/// Record `root` as the session's [`SessionState::storage_root`] unless one
268/// is already recorded: `SessionStart` fires again on resume, `/clear` and
269/// compaction, from wherever the shell has moved, and the session dir must
270/// not move with it. Returns whether it wrote.
271pub fn record_storage_root(
272    sessions_dir: &std::path::Path,
273    session_id: &str,
274    root: &std::path::Path,
275) -> Result<bool, Box<dyn std::error::Error>> {
276    let mut state = load_in(sessions_dir, session_id);
277    if state.storage_root.is_some() {
278        return Ok(false);
279    }
280    state.storage_root = Some(root.to_string_lossy().into_owned());
281    save_in(sessions_dir, session_id, &state)?;
282    Ok(true)
283}
284
285/// `$XDG_STATE_HOME/visdom/sessions` or `~/.local/state/visdom/sessions`. A
286/// session recorded under the legacy `tracevault/sessions` beside it is still
287/// read from there (see [`load_from`]).
288pub fn sessions_dir() -> Option<PathBuf> {
289    let base = std::env::var_os("XDG_STATE_HOME")
290        .map(PathBuf::from)
291        .or_else(|| dirs::home_dir().map(|h| h.join(".local").join("state")))?;
292    Some(crate::layout::user_dir_in(&base).join("sessions"))
293}
294
295/// The session of the agent that runs this command, from its environment:
296/// `$TRACEVAULT_SESSION_ID` (exported by the Claude Code / Codex SessionStart
297/// hook), else `$AMP_CURRENT_THREAD_ID`.
298///
299/// Amp's plugin cannot export a variable into Amp's shell (it runs in a
300/// separate process), but that shell has the current thread id, and the Amp
301/// plugin uses the thread id as the Visdom session id (VIS-1199). Empty
302/// values count as unset.
303pub fn env_session_id() -> Option<String> {
304    session_id_from_env(
305        std::env::var("TRACEVAULT_SESSION_ID").ok(),
306        std::env::var("AMP_CURRENT_THREAD_ID").ok(),
307    )
308}
309
310/// [`env_session_id`] on given values: `tracevault` wins, then `amp_thread`.
311pub fn session_id_from_env(
312    tracevault: Option<String>,
313    amp_thread: Option<String>,
314) -> Option<String> {
315    tracevault
316        .filter(|s| !s.is_empty())
317        .or_else(|| amp_thread.filter(|s| !s.is_empty()))
318}
319
320/// A session id is used to build the state file path, so it must be a safe
321/// filename token — no path separators or `..` that could escape the sessions
322/// directory. Claude Code session ids are UUIDs, which satisfy this.
323pub(crate) fn is_safe_session_id(session_id: &str) -> bool {
324    !session_id.is_empty()
325        && session_id
326            .chars()
327            .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
328}
329
330fn state_path_in(sessions_dir: &std::path::Path, session_id: &str) -> PathBuf {
331    sessions_dir.join(format!("{session_id}.toml"))
332}
333
334fn load_in(sessions_dir: &std::path::Path, session_id: &str) -> SessionState {
335    if !is_safe_session_id(session_id) {
336        return SessionState::default();
337    }
338    let mut path = state_path_in(sessions_dir, session_id);
339    if !path.exists() {
340        // Recorded by an earlier release, under the legacy state dir.
341        if let Some(legacy) = crate::layout::legacy_user_sessions_dir(sessions_dir) {
342            path = state_path_in(&legacy, session_id);
343        }
344    }
345    match std::fs::read_to_string(path) {
346        Ok(s) => toml::from_str(&s).unwrap_or_default(),
347        Err(_) => SessionState::default(),
348    }
349}
350
351fn save_in(
352    sessions_dir: &std::path::Path,
353    session_id: &str,
354    state: &SessionState,
355) -> Result<(), Box<dyn std::error::Error>> {
356    if !is_safe_session_id(session_id) {
357        return Err(format!("invalid session id: {session_id:?}").into());
358    }
359    std::fs::create_dir_all(sessions_dir)?;
360    let final_path = state_path_in(sessions_dir, session_id);
361    // Write to a temp file in the same dir, then atomically rename over the
362    // target so a crash or a concurrent reader never sees a partial/empty file.
363    // The temp name is unique per write: a session's parallel hooks save
364    // concurrently, and a shared name let one writer rename the other's
365    // half-written file into place.
366    let tmp_path = sessions_dir.join(format!("{session_id}.toml.{}.tmp", uuid::Uuid::now_v7()));
367    std::fs::write(&tmp_path, toml::to_string(state)?)?;
368    std::fs::rename(&tmp_path, &final_path).inspect_err(|_| {
369        let _ = std::fs::remove_file(&tmp_path);
370    })?;
371    Ok(())
372}
373
374/// Load, change and save a session's state while holding an exclusive lock
375/// on `<session_id>.lock` beside it, so the session's parallel hooks — each
376/// recording what it looked up — do not overwrite each other's changes. The
377/// lock is advisory: writers that do not take it (the interactive `switch`
378/// commands) are as before. The OS releases it when the holder exits.
379pub fn update_in(
380    sessions_dir: &std::path::Path,
381    session_id: &str,
382    change: impl FnOnce(&mut SessionState),
383) -> Result<SessionState, Box<dyn std::error::Error>> {
384    if !is_safe_session_id(session_id) {
385        return Err(format!("invalid session id: {session_id:?}").into());
386    }
387    std::fs::create_dir_all(sessions_dir)?;
388    let lock = std::fs::OpenOptions::new()
389        .create(true)
390        .truncate(false)
391        .write(true)
392        .open(sessions_dir.join(format!("{session_id}.lock")))?;
393    lock.lock()?;
394    let mut state = load_in(sessions_dir, session_id);
395    change(&mut state);
396    save_in(sessions_dir, session_id, &state)?;
397    Ok(state)
398}
399
400/// Load a session's state, returning the default (empty) state if the file is
401/// absent or malformed (workspace state is best-effort, never fatal).
402pub fn load(session_id: &str) -> SessionState {
403    match sessions_dir() {
404        Some(dir) => load_in(&dir, session_id),
405        None => SessionState::default(),
406    }
407}
408
409/// Persist a session's state, creating the state dir if needed.
410pub fn save(session_id: &str, state: &SessionState) -> Result<(), Box<dyn std::error::Error>> {
411    let dir = sessions_dir().ok_or("cannot determine state dir")?;
412    save_in(&dir, session_id, state)
413}
414
415/// Load a session's state from an explicit sessions dir (test seam / callers
416/// that resolve the dir themselves). Absent or malformed → default state.
417pub fn load_from(sessions_dir: &std::path::Path, session_id: &str) -> SessionState {
418    load_in(sessions_dir, session_id)
419}
420
421/// [`save`] into an explicit sessions dir — the write half of [`load_from`].
422/// Hooks write through the locking [`update_in`] instead.
423#[cfg(test)]
424pub fn save_to(
425    sessions_dir: &std::path::Path,
426    session_id: &str,
427    state: &SessionState,
428) -> Result<(), Box<dyn std::error::Error>> {
429    save_in(sessions_dir, session_id, state)
430}
431
432#[cfg(test)]
433mod tests {
434    use super::*;
435
436    #[test]
437    fn env_session_id_prefers_tracevault_then_amp_thread() {
438        let id = |tv: Option<&str>, amp: Option<&str>| {
439            session_id_from_env(tv.map(String::from), amp.map(String::from))
440        };
441        assert_eq!(id(Some("sess"), Some("T-1")).as_deref(), Some("sess"));
442        assert_eq!(id(None, Some("T-1")).as_deref(), Some("T-1"));
443        assert_eq!(id(Some(""), Some("T-1")).as_deref(), Some("T-1"));
444        assert_eq!(id(Some(""), Some("")), None);
445        assert_eq!(id(None, None), None);
446    }
447
448    fn binding(id: &str) -> RepoBinding {
449        RepoBinding {
450            repo_id: id.into(),
451            git_url: None,
452            remote_id: None,
453            codebase_name: None,
454            updated_at: "t".into(),
455        }
456    }
457
458    /// The single parse-and-compare both `commands::stream::attribution_mode`
459    /// and `commands::project::format_force_line` now go through. Each arm is
460    /// asserted here once so a change to the shared rule shows up in one
461    /// place, not only through its two callers.
462    #[test]
463    fn force_status_classifies_live_lapsed_and_unreadable() {
464        let future = chrono::Utc::now() + chrono::Duration::hours(4);
465        assert_eq!(
466            force_status(&future.to_rfc3339()),
467            ForceStatus::Live(future)
468        );
469        let past = chrono::Utc::now() - chrono::Duration::hours(1);
470        assert_eq!(force_status(&past.to_rfc3339()), ForceStatus::Lapsed(past));
471        // Fail-safe: unreadable is NOT in force, and never a panic.
472        assert_eq!(force_status("not-a-timestamp"), ForceStatus::Unreadable);
473        assert_eq!(force_status(""), ForceStatus::Unreadable);
474        // A non-UTC offset is normalised, not rejected.
475        assert_eq!(
476            force_status("2020-01-01T00:00:00+02:00"),
477            ForceStatus::Lapsed(
478                chrono::DateTime::parse_from_rfc3339("2020-01-01T00:00:00+02:00")
479                    .unwrap()
480                    .with_timezone(&chrono::Utc)
481            )
482        );
483    }
484
485    #[test]
486    fn save_in_then_load_in_round_trips() {
487        let tmp = tempfile::tempdir().unwrap();
488        let s = SessionState {
489            active: Some(binding("r1")),
490            subagents: HashMap::from([("/wt/a".to_string(), binding("r2"))]),
491            ..Default::default()
492        };
493        save_in(tmp.path(), "sess-1", &s).unwrap();
494        assert_eq!(load_in(tmp.path(), "sess-1"), s);
495    }
496
497    #[test]
498    fn load_in_missing_returns_default() {
499        let tmp = tempfile::tempdir().unwrap();
500        assert_eq!(
501            load_in(tmp.path(), "no-such-session"),
502            SessionState::default()
503        );
504    }
505
506    #[test]
507    fn rejects_unsafe_session_ids() {
508        let tmp = tempfile::tempdir().unwrap();
509        let s = SessionState::default();
510        // Path-traversal / separator ids must be refused, never written to disk.
511        assert!(save_in(tmp.path(), "../evil", &s).is_err());
512        assert!(save_in(tmp.path(), "a/b", &s).is_err());
513        assert!(save_in(tmp.path(), "", &s).is_err());
514        // load of an unsafe id never touches disk; returns the default.
515        assert_eq!(load_in(tmp.path(), "../evil"), SessionState::default());
516        // A UUID-style id is accepted.
517        assert!(save_in(tmp.path(), "0190a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b", &s).is_ok());
518    }
519
520    #[test]
521    fn load_from_reads_active_binding() {
522        let dir = tempfile::tempdir().unwrap();
523        save_in(
524            dir.path(),
525            "sess-1",
526            &SessionState {
527                active: Some(binding("r1")),
528                ..Default::default()
529            },
530        )
531        .unwrap();
532        let st = load_from(dir.path(), "sess-1");
533        assert_eq!(st.active.unwrap().repo_id, "r1");
534    }
535
536    #[test]
537    fn load_from_missing_is_default() {
538        let dir = tempfile::tempdir().unwrap();
539        assert_eq!(load_from(dir.path(), "nope"), SessionState::default());
540    }
541
542    #[test]
543    fn save_in_is_atomic_and_leaves_no_tmp() {
544        let tmp = tempfile::tempdir().unwrap();
545        let s = SessionState {
546            active: Some(binding("r1")),
547            subagents: HashMap::new(),
548            ..Default::default()
549        };
550        save_in(tmp.path(), "sess-atomic", &s).unwrap();
551        assert_eq!(load_in(tmp.path(), "sess-atomic"), s);
552        // no stray temp file
553        let leftover = std::fs::read_dir(tmp.path())
554            .unwrap()
555            .filter_map(|e| e.ok())
556            .any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
557        assert!(
558            !leftover,
559            "temp file should be renamed away, not left behind"
560        );
561    }
562
563    #[test]
564    fn record_storage_root_is_first_write_wins_and_keeps_other_fields() {
565        let tmp = tempfile::tempdir().unwrap();
566        let s = SessionState {
567            active: Some(binding("r1")),
568            ..Default::default()
569        };
570        save_in(tmp.path(), "sess-1", &s).unwrap();
571
572        assert!(
573            record_storage_root(tmp.path(), "sess-1", std::path::Path::new("/umbrella")).unwrap()
574        );
575        assert!(!record_storage_root(
576            tmp.path(),
577            "sess-1",
578            std::path::Path::new("/umbrella/child")
579        )
580        .unwrap());
581
582        let loaded = load_in(tmp.path(), "sess-1");
583        assert_eq!(loaded.storage_root.as_deref(), Some("/umbrella"));
584        assert_eq!(loaded.active, s.active);
585    }
586
587    #[test]
588    fn storage_root_needs_the_dir_but_not_its_tracevault() {
589        let tmp = tempfile::tempdir().unwrap();
590        let mut s = SessionState {
591            storage_root: Some(tmp.path().to_string_lossy().into_owned()),
592            ..Default::default()
593        };
594        assert_eq!(storage_root(&s), Some(tmp.path().to_path_buf()));
595        s.storage_root = Some(tmp.path().join("gone").to_string_lossy().into_owned());
596        assert_eq!(storage_root(&s), None);
597        s.storage_root = None;
598        assert_eq!(storage_root(&s), None);
599    }
600
601    #[test]
602    fn record_worktree_lists_each_worktree_once_and_ran_in_reads_it() {
603        let tmp = tempfile::tempdir().unwrap();
604        let d = tmp.path();
605        assert!(!ran_in(d, "/wt/a"));
606        record_worktree(d, "/wt/a").unwrap();
607        record_worktree(d, "/wt/b").unwrap();
608        record_worktree(d, "/wt/a").unwrap();
609        assert_eq!(
610            std::fs::read_to_string(d.join(WORKTREES_FILE)).unwrap(),
611            "/wt/a\n/wt/b\n"
612        );
613        assert!(ran_in(d, "/wt/a") && ran_in(d, "/wt/b"));
614        assert!(!ran_in(d, "/wt"), "whole lines only");
615        std::fs::write(d.join("origin"), "/wt/c").unwrap();
616        assert!(ran_in(d, "/wt/c"));
617    }
618
619    #[test]
620    fn anchored_session_dirs_finds_sessions_kept_elsewhere_that_ran_here() {
621        let tmp = tempfile::tempdir().unwrap();
622        let state = tmp.path().join("state");
623        let umbrella = tmp.path().join("umbrella");
624        let repo = tmp.path().join("umbrella/repo");
625        let local = repo.join(".visdom/sessions");
626        let anchor = |id: &str, root: &std::path::Path, ran: Option<&str>| {
627            let st = SessionState {
628                storage_root: Some(root.to_string_lossy().into_owned()),
629                ..Default::default()
630            };
631            save_in(&state, id, &st).unwrap();
632            let dir = root.join(".visdom/sessions").join(id);
633            std::fs::create_dir_all(&dir).unwrap();
634            if let Some(wt) = ran {
635                record_worktree(&dir, wt).unwrap();
636            }
637            dir
638        };
639        let worked_here = anchor("here", &umbrella, Some("/repo"));
640        anchor("elsewhere", &umbrella, Some("/other"));
641        anchor("local", &repo, Some("/repo"));
642        save_in(&state, "unanchored", &SessionState::default()).unwrap();
643
644        assert_eq!(
645            anchored_session_dirs_in(&state, &local, "/repo"),
646            vec![worked_here]
647        );
648        assert!(anchored_session_dirs_in(&tmp.path().join("none"), &local, "/repo").is_empty());
649    }
650
651    #[test]
652    fn old_state_files_load_without_a_storage_root() {
653        let st: SessionState =
654            toml::from_str("[active]\nrepo_id = \"r1\"\nupdated_at = \"t\"\n").unwrap();
655        assert_eq!(st.storage_root, None);
656        assert!(!toml::to_string(&st).unwrap().contains("storage_root"));
657    }
658
659    #[test]
660    fn session_state_carries_project_bindings() {
661        let tmp = tempfile::tempdir().unwrap();
662        let pb = ProjectBinding {
663            project_id: "11111111-1111-1111-1111-111111111111".into(),
664            project_name: "payments".into(),
665            updated_at: "t".into(),
666            forced_until: None,
667        };
668        let mut subagent_projects = HashMap::new();
669        subagent_projects.insert("/wt".into(), pb.clone());
670        let st = SessionState {
671            active_project: Some(pb.clone()),
672            subagent_projects,
673            ..Default::default()
674        };
675        save_in(tmp.path(), "sess-1", &st).unwrap();
676        let loaded = load_from(tmp.path(), "sess-1");
677        assert_eq!(loaded.active_project, Some(pb.clone()));
678        assert_eq!(loaded.subagent_projects.get("/wt"), Some(&pb));
679    }
680
681    #[test]
682    fn a_session_recorded_by_an_earlier_release_is_still_found() {
683        let dir = tempfile::tempdir().unwrap();
684        let legacy = dir.path().join("tracevault/sessions");
685        let new = dir.path().join("visdom/sessions");
686        let umbrella = dir.path().join("umbrella");
687        let state = SessionState {
688            storage_root: Some(umbrella.to_string_lossy().into_owned()),
689            ..Default::default()
690        };
691        save_in(&legacy, "old", &state).unwrap();
692
693        // Read through the new state dir, from the legacy one beside it.
694        assert_eq!(load_from(&new, "old").storage_root, state.storage_root);
695
696        // Its directory under the umbrella's `.tracevault/` is still the one.
697        let session = umbrella.join(".tracevault/sessions/old");
698        std::fs::create_dir_all(&session).unwrap();
699        record_worktree(&session, "/work/tree").unwrap();
700        let local = dir.path().join("checkout/.visdom/sessions");
701        assert_eq!(
702            anchored_session_dirs_in(&new, &local, "/work/tree"),
703            vec![session]
704        );
705
706        // Once saved, the state lives in the new dir and shadows the old file.
707        update_in(&new, "old", |s| s.storage_root = Some("/elsewhere".into())).unwrap();
708        assert!(new.join("old.toml").exists());
709        assert_eq!(
710            load_from(&new, "old").storage_root.as_deref(),
711            Some("/elsewhere")
712        );
713    }
714
715    #[test]
716    fn a_checkouts_own_sessions_are_local_under_either_name() {
717        let root = std::path::Path::new("/repo");
718        let local = root.join(".visdom/sessions");
719        assert!(is_local_sessions_dir(&local, &local));
720        assert!(is_local_sessions_dir(
721            &root.join(".tracevault/sessions"),
722            &local
723        ));
724        assert!(!is_local_sessions_dir(
725            std::path::Path::new("/other/.tracevault/sessions"),
726            &local
727        ));
728    }
729}