Skip to main content

tracevault_cli/
user_project_default.rs

1//! User-level default project binding: a session-independent binding any Claude
2//! Code session inherits when nothing more specific resolves. Set by
3//! `tracevault project switch --user` (or a no-session `project switch`); read by
4//! `project status` as the lowest-precedence tier, and by the capture path:
5//! `commands::stream::capture_project` reads it as its last tier, so this
6//! store can decide the project an event is attributed to. Since repo-less
7//! ingest landed it can do more than that — for a session with no repo
8//! binding it is the sole reason the event ships at all (see
9//! `commands::stream::attribution_for`). Lets a container bind its project
10//! *before* Claude launches — no session id required, which is exactly why it
11//! is the tier that carries pre-clone runs.
12
13use std::path::{Path, PathBuf};
14
15use crate::session_state::ProjectBinding;
16
17/// `dirs::config_dir()/visdom/user_project.toml` — beside `credentials.json`.
18pub fn default_project_path() -> Option<PathBuf> {
19    dirs::config_dir().map(|d| crate::layout::user_dir_in(&d).join("user_project.toml"))
20}
21
22/// The directory an earlier release kept the binding in.
23fn legacy_dir() -> Option<PathBuf> {
24    crate::layout::legacy_sibling(default_project_path()?.parent()?)
25}
26
27fn load_from(dir: &Path) -> Option<ProjectBinding> {
28    let path = dir.join("user_project.toml");
29    let s = std::fs::read_to_string(path).ok()?;
30    toml::from_str(&s).ok()
31}
32
33fn save_in(dir: &Path, binding: &ProjectBinding) -> Result<(), Box<dyn std::error::Error>> {
34    std::fs::create_dir_all(dir)?;
35    // Atomic write: temp file in the same dir, then rename over the target so a
36    // crash or concurrent reader never sees a partial file (mirrors session_state).
37    let path = dir.join("user_project.toml");
38    let tmp = dir.join(format!("user_project.toml.{}.tmp", std::process::id()));
39    std::fs::write(&tmp, toml::to_string(binding)?)?;
40    std::fs::rename(&tmp, path)?;
41    Ok(())
42}
43
44fn clear_at(path: &Path) -> std::io::Result<()> {
45    match std::fs::remove_file(path) {
46        Ok(()) => Ok(()),
47        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
48        Err(e) => Err(e),
49    }
50}
51
52/// Load the user-level default binding; `None` if unset or malformed.
53pub fn load() -> Option<ProjectBinding> {
54    let path = default_project_path()?;
55    if !path.exists() {
56        if let Some(legacy) = legacy_dir() {
57            return load_from(&legacy);
58        }
59    }
60    load_from(path.parent()?)
61}
62
63/// Persist the user-level default binding, creating the config dir if needed.
64pub fn save(binding: &ProjectBinding) -> Result<(), Box<dyn std::error::Error>> {
65    let path = default_project_path().ok_or("cannot determine user config dir")?;
66    let dir = path.parent().ok_or("cannot determine parent directory")?;
67    save_in(dir, binding)
68}
69
70/// Remove the user-level default binding (ok if already absent).
71#[allow(dead_code)]
72pub fn clear() -> Result<(), Box<dyn std::error::Error>> {
73    let path = default_project_path().ok_or("cannot determine user config dir")?;
74    clear_at(&path)?;
75    // Otherwise the binding an earlier release left would come back.
76    if let Some(legacy) = legacy_dir() {
77        clear_at(&legacy.join("user_project.toml"))?;
78    }
79    Ok(())
80}
81
82/// Default force lifetime: roughly one working day. A persisted force is
83/// strictly worse than a stale project binding, because it also disables the
84/// check that would have caught the binding going stale.
85pub const DEFAULT_FORCE_LIFETIME_HOURS: i64 = 12;
86
87#[cfg(test)]
88mod tests {
89    use super::*;
90
91    #[test]
92    fn user_project_default_roundtrips() {
93        let tmp = tempfile::tempdir().unwrap();
94        let pb = ProjectBinding {
95            project_id: "id".into(),
96            project_name: "p".into(),
97            updated_at: "t".into(),
98            forced_until: None,
99        };
100        save_in(tmp.path(), &pb).unwrap();
101        assert_eq!(load_from(tmp.path()), Some(pb));
102    }
103
104    #[test]
105    fn user_project_default_absent_is_none() {
106        let tmp = tempfile::tempdir().unwrap();
107        assert_eq!(load_from(tmp.path()), None);
108    }
109
110    #[test]
111    fn save_then_load_roundtrips_via_real_paths() {
112        // Exercises the REAL `save()`/`load()` entry points (not `save_in`/
113        // `load_from` directly) so a regression like `load()` looking for
114        // `.../user_project.toml/user_project.toml` (passing the file path
115        // instead of its parent dir into `load_from`) would be caught.
116
117        // `commands::project`'s `switch_without_session_or_user_flag_skips_
118        // codebase_check` test also redirects XDG_CONFIG_HOME (to keep its
119        // credential resolution off the developer's real config); both hold
120        // this process-wide lock for their duration so they can't interleave.
121        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
122        let tmp = tempfile::tempdir().unwrap();
123
124        // SAFETY: test-scoped env mutation, restored in a guard so a panic
125        // in `save`/`load` still cleans up the process env.
126        let mut _guard = crate::test_helpers::EnvVarGuard::new();
127        _guard.set("XDG_CONFIG_HOME", tmp.path());
128
129        let pb = ProjectBinding {
130            project_id: "id".into(),
131            project_name: "p".into(),
132            updated_at: "t".into(),
133            forced_until: None,
134        };
135        save(&pb).unwrap();
136        assert_eq!(load(), Some(pb));
137    }
138
139    /// `forced_until` round-trips through the real `save`/`load` on-disk
140    /// format. The LIVENESS check itself (is a given `forced_until` still in
141    /// the future?) lives entirely in
142    /// `commands::stream::attribution_mode` now — this store only persists
143    /// the binding, it doesn't interpret it (see that function's doc comment
144    /// for why: a force is scoped to the binding that carries it, and this
145    /// module has no notion of "the binding that won").
146    #[test]
147    fn forced_until_round_trips() {
148        let dir = tempfile::tempdir().unwrap();
149        let until = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
150        let binding = ProjectBinding {
151            project_id: "3f2504e0-4f89-11d3-9a0c-0305e82c3301".into(),
152            project_name: "p".into(),
153            updated_at: chrono::Utc::now().to_rfc3339(),
154            forced_until: Some(until),
155        };
156        save_in(dir.path(), &binding).unwrap();
157        assert_eq!(load_from(dir.path()), Some(binding));
158    }
159
160    #[test]
161    fn clearing_removes_the_legacy_default_too() {
162        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
163        let tmp = tempfile::tempdir().unwrap();
164        let mut _guard = crate::test_helpers::EnvVarGuard::new();
165        _guard.set("XDG_CONFIG_HOME", tmp.path());
166        let pb = |name: &str| ProjectBinding {
167            project_id: "id".into(),
168            project_name: name.into(),
169            updated_at: "t".into(),
170            forced_until: None,
171        };
172        let legacy = tmp.path().join("tracevault");
173        save_in(&legacy, &pb("old")).unwrap();
174        assert_eq!(load(), Some(pb("old")));
175        save(&pb("new")).unwrap();
176        assert_eq!(load(), Some(pb("new")));
177
178        clear().unwrap();
179
180        assert!(!legacy.join("user_project.toml").exists());
181        assert!(!tmp.path().join("visdom/user_project.toml").exists());
182        assert_eq!(load(), None);
183    }
184}