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 `.tracevault/` 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 `.tracevault/` 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    let Ok(entries) = std::fs::read_dir(state_dir) else {
208        return vec![];
209    };
210    let mut dirs: Vec<PathBuf> = entries
211        .filter_map(|e| e.ok())
212        .filter_map(|e| {
213            let name = e.file_name();
214            let id = name.to_str()?.strip_suffix(".toml")?.to_string();
215            let root = storage_root(&load_in(state_dir, &id))?;
216            let dir = root.join(".tracevault").join("sessions").join(&id);
217            (dir.parent() != Some(local_sessions_dir) && dir.is_dir() && ran_in(&dir, worktree_top))
218                .then_some(dir)
219        })
220        .collect();
221    dirs.sort();
222    dirs
223}
224
225/// [`anchored_session_dirs_in`] the user's state dir.
226pub fn anchored_session_dirs(
227    local_sessions_dir: &std::path::Path,
228    worktree_top: &str,
229) -> Vec<PathBuf> {
230    sessions_dir()
231        .map(|d| anchored_session_dirs_in(&d, local_sessions_dir, worktree_top))
232        .unwrap_or_default()
233}
234
235/// `<root>/.tracevault/sessions/<session_id>` for `session_id`, where `root`
236/// is the session's recorded [`storage_root`], else `fallback_root` (the root
237/// resolved from the caller's working directory). Every reader and writer of
238/// a session dir goes through this, so a session is found where its hook
239/// keeps it.
240pub fn session_dir(fallback_root: &std::path::Path, session_id: &str) -> PathBuf {
241    let root = storage_root(&load(session_id)).unwrap_or_else(|| fallback_root.to_path_buf());
242    root.join(".tracevault").join("sessions").join(session_id)
243}
244
245/// Record `root` as the session's [`SessionState::storage_root`] unless one
246/// is already recorded: `SessionStart` fires again on resume, `/clear` and
247/// compaction, from wherever the shell has moved, and the session dir must
248/// not move with it. Returns whether it wrote.
249pub fn record_storage_root(
250    sessions_dir: &std::path::Path,
251    session_id: &str,
252    root: &std::path::Path,
253) -> Result<bool, Box<dyn std::error::Error>> {
254    let mut state = load_in(sessions_dir, session_id);
255    if state.storage_root.is_some() {
256        return Ok(false);
257    }
258    state.storage_root = Some(root.to_string_lossy().into_owned());
259    save_in(sessions_dir, session_id, &state)?;
260    Ok(true)
261}
262
263/// `$XDG_STATE_HOME/tracevault/sessions` or `~/.local/state/tracevault/sessions`.
264pub fn sessions_dir() -> Option<PathBuf> {
265    let base = std::env::var_os("XDG_STATE_HOME")
266        .map(PathBuf::from)
267        .or_else(|| dirs::home_dir().map(|h| h.join(".local").join("state")))?;
268    Some(base.join("tracevault").join("sessions"))
269}
270
271/// The session of the agent that runs this command, from its environment:
272/// `$TRACEVAULT_SESSION_ID` (exported by the Claude Code / Codex SessionStart
273/// hook), else `$AMP_CURRENT_THREAD_ID`.
274///
275/// Amp's plugin cannot export a variable into Amp's shell (it runs in a
276/// separate process), but that shell has the current thread id, and the Amp
277/// plugin uses the thread id as the TraceVault session id (VIS-1199). Empty
278/// values count as unset.
279pub fn env_session_id() -> Option<String> {
280    session_id_from_env(
281        std::env::var("TRACEVAULT_SESSION_ID").ok(),
282        std::env::var("AMP_CURRENT_THREAD_ID").ok(),
283    )
284}
285
286/// [`env_session_id`] on given values: `tracevault` wins, then `amp_thread`.
287pub fn session_id_from_env(
288    tracevault: Option<String>,
289    amp_thread: Option<String>,
290) -> Option<String> {
291    tracevault
292        .filter(|s| !s.is_empty())
293        .or_else(|| amp_thread.filter(|s| !s.is_empty()))
294}
295
296/// A session id is used to build the state file path, so it must be a safe
297/// filename token — no path separators or `..` that could escape the sessions
298/// directory. Claude Code session ids are UUIDs, which satisfy this.
299pub(crate) fn is_safe_session_id(session_id: &str) -> bool {
300    !session_id.is_empty()
301        && session_id
302            .chars()
303            .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
304}
305
306fn state_path_in(sessions_dir: &std::path::Path, session_id: &str) -> PathBuf {
307    sessions_dir.join(format!("{session_id}.toml"))
308}
309
310fn load_in(sessions_dir: &std::path::Path, session_id: &str) -> SessionState {
311    if !is_safe_session_id(session_id) {
312        return SessionState::default();
313    }
314    match std::fs::read_to_string(state_path_in(sessions_dir, session_id)) {
315        Ok(s) => toml::from_str(&s).unwrap_or_default(),
316        Err(_) => SessionState::default(),
317    }
318}
319
320fn save_in(
321    sessions_dir: &std::path::Path,
322    session_id: &str,
323    state: &SessionState,
324) -> Result<(), Box<dyn std::error::Error>> {
325    if !is_safe_session_id(session_id) {
326        return Err(format!("invalid session id: {session_id:?}").into());
327    }
328    std::fs::create_dir_all(sessions_dir)?;
329    let final_path = state_path_in(sessions_dir, session_id);
330    // Write to a temp file in the same dir, then atomically rename over the
331    // target so a crash or a concurrent reader never sees a partial/empty file.
332    // The temp name is unique per write: a session's parallel hooks save
333    // concurrently, and a shared name let one writer rename the other's
334    // half-written file into place.
335    let tmp_path = sessions_dir.join(format!("{session_id}.toml.{}.tmp", uuid::Uuid::now_v7()));
336    std::fs::write(&tmp_path, toml::to_string(state)?)?;
337    std::fs::rename(&tmp_path, &final_path).inspect_err(|_| {
338        let _ = std::fs::remove_file(&tmp_path);
339    })?;
340    Ok(())
341}
342
343/// Load, change and save a session's state while holding an exclusive lock
344/// on `<session_id>.lock` beside it, so the session's parallel hooks — each
345/// recording what it looked up — do not overwrite each other's changes. The
346/// lock is advisory: writers that do not take it (the interactive `switch`
347/// commands) are as before. The OS releases it when the holder exits.
348pub fn update_in(
349    sessions_dir: &std::path::Path,
350    session_id: &str,
351    change: impl FnOnce(&mut SessionState),
352) -> Result<SessionState, Box<dyn std::error::Error>> {
353    if !is_safe_session_id(session_id) {
354        return Err(format!("invalid session id: {session_id:?}").into());
355    }
356    std::fs::create_dir_all(sessions_dir)?;
357    let lock = std::fs::OpenOptions::new()
358        .create(true)
359        .truncate(false)
360        .write(true)
361        .open(sessions_dir.join(format!("{session_id}.lock")))?;
362    lock.lock()?;
363    let mut state = load_in(sessions_dir, session_id);
364    change(&mut state);
365    save_in(sessions_dir, session_id, &state)?;
366    Ok(state)
367}
368
369/// Load a session's state, returning the default (empty) state if the file is
370/// absent or malformed (workspace state is best-effort, never fatal).
371pub fn load(session_id: &str) -> SessionState {
372    match sessions_dir() {
373        Some(dir) => load_in(&dir, session_id),
374        None => SessionState::default(),
375    }
376}
377
378/// Persist a session's state, creating the state dir if needed.
379pub fn save(session_id: &str, state: &SessionState) -> Result<(), Box<dyn std::error::Error>> {
380    let dir = sessions_dir().ok_or("cannot determine state dir")?;
381    save_in(&dir, session_id, state)
382}
383
384/// Load a session's state from an explicit sessions dir (test seam / callers
385/// that resolve the dir themselves). Absent or malformed → default state.
386pub fn load_from(sessions_dir: &std::path::Path, session_id: &str) -> SessionState {
387    load_in(sessions_dir, session_id)
388}
389
390/// [`save`] into an explicit sessions dir — the write half of [`load_from`].
391/// Hooks write through the locking [`update_in`] instead.
392#[cfg(test)]
393pub fn save_to(
394    sessions_dir: &std::path::Path,
395    session_id: &str,
396    state: &SessionState,
397) -> Result<(), Box<dyn std::error::Error>> {
398    save_in(sessions_dir, session_id, state)
399}
400
401#[cfg(test)]
402mod tests {
403    use super::*;
404
405    #[test]
406    fn env_session_id_prefers_tracevault_then_amp_thread() {
407        let id = |tv: Option<&str>, amp: Option<&str>| {
408            session_id_from_env(tv.map(String::from), amp.map(String::from))
409        };
410        assert_eq!(id(Some("sess"), Some("T-1")).as_deref(), Some("sess"));
411        assert_eq!(id(None, Some("T-1")).as_deref(), Some("T-1"));
412        assert_eq!(id(Some(""), Some("T-1")).as_deref(), Some("T-1"));
413        assert_eq!(id(Some(""), Some("")), None);
414        assert_eq!(id(None, None), None);
415    }
416
417    fn binding(id: &str) -> RepoBinding {
418        RepoBinding {
419            repo_id: id.into(),
420            git_url: None,
421            remote_id: None,
422            codebase_name: None,
423            updated_at: "t".into(),
424        }
425    }
426
427    /// The single parse-and-compare both `commands::stream::attribution_mode`
428    /// and `commands::project::format_force_line` now go through. Each arm is
429    /// asserted here once so a change to the shared rule shows up in one
430    /// place, not only through its two callers.
431    #[test]
432    fn force_status_classifies_live_lapsed_and_unreadable() {
433        let future = chrono::Utc::now() + chrono::Duration::hours(4);
434        assert_eq!(
435            force_status(&future.to_rfc3339()),
436            ForceStatus::Live(future)
437        );
438        let past = chrono::Utc::now() - chrono::Duration::hours(1);
439        assert_eq!(force_status(&past.to_rfc3339()), ForceStatus::Lapsed(past));
440        // Fail-safe: unreadable is NOT in force, and never a panic.
441        assert_eq!(force_status("not-a-timestamp"), ForceStatus::Unreadable);
442        assert_eq!(force_status(""), ForceStatus::Unreadable);
443        // A non-UTC offset is normalised, not rejected.
444        assert_eq!(
445            force_status("2020-01-01T00:00:00+02:00"),
446            ForceStatus::Lapsed(
447                chrono::DateTime::parse_from_rfc3339("2020-01-01T00:00:00+02:00")
448                    .unwrap()
449                    .with_timezone(&chrono::Utc)
450            )
451        );
452    }
453
454    #[test]
455    fn save_in_then_load_in_round_trips() {
456        let tmp = tempfile::tempdir().unwrap();
457        let s = SessionState {
458            active: Some(binding("r1")),
459            subagents: HashMap::from([("/wt/a".to_string(), binding("r2"))]),
460            ..Default::default()
461        };
462        save_in(tmp.path(), "sess-1", &s).unwrap();
463        assert_eq!(load_in(tmp.path(), "sess-1"), s);
464    }
465
466    #[test]
467    fn load_in_missing_returns_default() {
468        let tmp = tempfile::tempdir().unwrap();
469        assert_eq!(
470            load_in(tmp.path(), "no-such-session"),
471            SessionState::default()
472        );
473    }
474
475    #[test]
476    fn rejects_unsafe_session_ids() {
477        let tmp = tempfile::tempdir().unwrap();
478        let s = SessionState::default();
479        // Path-traversal / separator ids must be refused, never written to disk.
480        assert!(save_in(tmp.path(), "../evil", &s).is_err());
481        assert!(save_in(tmp.path(), "a/b", &s).is_err());
482        assert!(save_in(tmp.path(), "", &s).is_err());
483        // load of an unsafe id never touches disk; returns the default.
484        assert_eq!(load_in(tmp.path(), "../evil"), SessionState::default());
485        // A UUID-style id is accepted.
486        assert!(save_in(tmp.path(), "0190a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b", &s).is_ok());
487    }
488
489    #[test]
490    fn load_from_reads_active_binding() {
491        let dir = tempfile::tempdir().unwrap();
492        save_in(
493            dir.path(),
494            "sess-1",
495            &SessionState {
496                active: Some(binding("r1")),
497                ..Default::default()
498            },
499        )
500        .unwrap();
501        let st = load_from(dir.path(), "sess-1");
502        assert_eq!(st.active.unwrap().repo_id, "r1");
503    }
504
505    #[test]
506    fn load_from_missing_is_default() {
507        let dir = tempfile::tempdir().unwrap();
508        assert_eq!(load_from(dir.path(), "nope"), SessionState::default());
509    }
510
511    #[test]
512    fn save_in_is_atomic_and_leaves_no_tmp() {
513        let tmp = tempfile::tempdir().unwrap();
514        let s = SessionState {
515            active: Some(binding("r1")),
516            subagents: HashMap::new(),
517            ..Default::default()
518        };
519        save_in(tmp.path(), "sess-atomic", &s).unwrap();
520        assert_eq!(load_in(tmp.path(), "sess-atomic"), s);
521        // no stray temp file
522        let leftover = std::fs::read_dir(tmp.path())
523            .unwrap()
524            .filter_map(|e| e.ok())
525            .any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
526        assert!(
527            !leftover,
528            "temp file should be renamed away, not left behind"
529        );
530    }
531
532    #[test]
533    fn record_storage_root_is_first_write_wins_and_keeps_other_fields() {
534        let tmp = tempfile::tempdir().unwrap();
535        let s = SessionState {
536            active: Some(binding("r1")),
537            ..Default::default()
538        };
539        save_in(tmp.path(), "sess-1", &s).unwrap();
540
541        assert!(
542            record_storage_root(tmp.path(), "sess-1", std::path::Path::new("/umbrella")).unwrap()
543        );
544        assert!(!record_storage_root(
545            tmp.path(),
546            "sess-1",
547            std::path::Path::new("/umbrella/child")
548        )
549        .unwrap());
550
551        let loaded = load_in(tmp.path(), "sess-1");
552        assert_eq!(loaded.storage_root.as_deref(), Some("/umbrella"));
553        assert_eq!(loaded.active, s.active);
554    }
555
556    #[test]
557    fn storage_root_needs_the_dir_but_not_its_tracevault() {
558        let tmp = tempfile::tempdir().unwrap();
559        let mut s = SessionState {
560            storage_root: Some(tmp.path().to_string_lossy().into_owned()),
561            ..Default::default()
562        };
563        assert_eq!(storage_root(&s), Some(tmp.path().to_path_buf()));
564        s.storage_root = Some(tmp.path().join("gone").to_string_lossy().into_owned());
565        assert_eq!(storage_root(&s), None);
566        s.storage_root = None;
567        assert_eq!(storage_root(&s), None);
568    }
569
570    #[test]
571    fn record_worktree_lists_each_worktree_once_and_ran_in_reads_it() {
572        let tmp = tempfile::tempdir().unwrap();
573        let d = tmp.path();
574        assert!(!ran_in(d, "/wt/a"));
575        record_worktree(d, "/wt/a").unwrap();
576        record_worktree(d, "/wt/b").unwrap();
577        record_worktree(d, "/wt/a").unwrap();
578        assert_eq!(
579            std::fs::read_to_string(d.join(WORKTREES_FILE)).unwrap(),
580            "/wt/a\n/wt/b\n"
581        );
582        assert!(ran_in(d, "/wt/a") && ran_in(d, "/wt/b"));
583        assert!(!ran_in(d, "/wt"), "whole lines only");
584        std::fs::write(d.join("origin"), "/wt/c").unwrap();
585        assert!(ran_in(d, "/wt/c"));
586    }
587
588    #[test]
589    fn anchored_session_dirs_finds_sessions_kept_elsewhere_that_ran_here() {
590        let tmp = tempfile::tempdir().unwrap();
591        let state = tmp.path().join("state");
592        let umbrella = tmp.path().join("umbrella");
593        let repo = tmp.path().join("umbrella/repo");
594        let local = repo.join(".tracevault/sessions");
595        let anchor = |id: &str, root: &std::path::Path, ran: Option<&str>| {
596            let st = SessionState {
597                storage_root: Some(root.to_string_lossy().into_owned()),
598                ..Default::default()
599            };
600            save_in(&state, id, &st).unwrap();
601            let dir = root.join(".tracevault/sessions").join(id);
602            std::fs::create_dir_all(&dir).unwrap();
603            if let Some(wt) = ran {
604                record_worktree(&dir, wt).unwrap();
605            }
606            dir
607        };
608        let worked_here = anchor("here", &umbrella, Some("/repo"));
609        anchor("elsewhere", &umbrella, Some("/other"));
610        anchor("local", &repo, Some("/repo"));
611        save_in(&state, "unanchored", &SessionState::default()).unwrap();
612
613        assert_eq!(
614            anchored_session_dirs_in(&state, &local, "/repo"),
615            vec![worked_here]
616        );
617        assert!(anchored_session_dirs_in(&tmp.path().join("none"), &local, "/repo").is_empty());
618    }
619
620    #[test]
621    fn old_state_files_load_without_a_storage_root() {
622        let st: SessionState =
623            toml::from_str("[active]\nrepo_id = \"r1\"\nupdated_at = \"t\"\n").unwrap();
624        assert_eq!(st.storage_root, None);
625        assert!(!toml::to_string(&st).unwrap().contains("storage_root"));
626    }
627
628    #[test]
629    fn session_state_carries_project_bindings() {
630        let tmp = tempfile::tempdir().unwrap();
631        let pb = ProjectBinding {
632            project_id: "11111111-1111-1111-1111-111111111111".into(),
633            project_name: "payments".into(),
634            updated_at: "t".into(),
635            forced_until: None,
636        };
637        let mut subagent_projects = HashMap::new();
638        subagent_projects.insert("/wt".into(), pb.clone());
639        let st = SessionState {
640            active_project: Some(pb.clone()),
641            subagent_projects,
642            ..Default::default()
643        };
644        save_in(tmp.path(), "sess-1", &st).unwrap();
645        let loaded = load_from(tmp.path(), "sess-1");
646        assert_eq!(loaded.active_project, Some(pb.clone()));
647        assert_eq!(loaded.subagent_projects.get("/wt"), Some(&pb));
648    }
649}