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()/tracevault/user_project.toml` — beside `credentials.json`.
18pub fn default_project_path() -> Option<PathBuf> {
19    dirs::config_dir().map(|d| d.join("tracevault").join("user_project.toml"))
20}
21
22fn load_from(dir: &Path) -> Option<ProjectBinding> {
23    let path = dir.join("user_project.toml");
24    let s = std::fs::read_to_string(path).ok()?;
25    toml::from_str(&s).ok()
26}
27
28fn save_in(dir: &Path, binding: &ProjectBinding) -> Result<(), Box<dyn std::error::Error>> {
29    std::fs::create_dir_all(dir)?;
30    // Atomic write: temp file in the same dir, then rename over the target so a
31    // crash or concurrent reader never sees a partial file (mirrors session_state).
32    let path = dir.join("user_project.toml");
33    let tmp = dir.join(format!("user_project.toml.{}.tmp", std::process::id()));
34    std::fs::write(&tmp, toml::to_string(binding)?)?;
35    std::fs::rename(&tmp, path)?;
36    Ok(())
37}
38
39fn clear_at(path: &Path) -> std::io::Result<()> {
40    match std::fs::remove_file(path) {
41        Ok(()) => Ok(()),
42        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
43        Err(e) => Err(e),
44    }
45}
46
47/// Load the user-level default binding; `None` if unset or malformed.
48pub fn load() -> Option<ProjectBinding> {
49    let path = default_project_path()?;
50    let dir = path.parent()?;
51    load_from(dir)
52}
53
54/// Persist the user-level default binding, creating the config dir if needed.
55pub fn save(binding: &ProjectBinding) -> Result<(), Box<dyn std::error::Error>> {
56    let path = default_project_path().ok_or("cannot determine user config dir")?;
57    let dir = path.parent().ok_or("cannot determine parent directory")?;
58    save_in(dir, binding)
59}
60
61/// Remove the user-level default binding (ok if already absent).
62#[allow(dead_code)]
63pub fn clear() -> Result<(), Box<dyn std::error::Error>> {
64    let path = default_project_path().ok_or("cannot determine user config dir")?;
65    clear_at(&path)?;
66    Ok(())
67}
68
69/// Default force lifetime: roughly one working day. A persisted force is
70/// strictly worse than a stale project binding, because it also disables the
71/// check that would have caught the binding going stale.
72pub const DEFAULT_FORCE_LIFETIME_HOURS: i64 = 12;
73
74#[cfg(test)]
75mod tests {
76    use super::*;
77
78    #[test]
79    fn user_project_default_roundtrips() {
80        let tmp = tempfile::tempdir().unwrap();
81        let pb = ProjectBinding {
82            project_id: "id".into(),
83            project_name: "p".into(),
84            updated_at: "t".into(),
85            forced_until: None,
86        };
87        save_in(tmp.path(), &pb).unwrap();
88        assert_eq!(load_from(tmp.path()), Some(pb));
89    }
90
91    #[test]
92    fn user_project_default_absent_is_none() {
93        let tmp = tempfile::tempdir().unwrap();
94        assert_eq!(load_from(tmp.path()), None);
95    }
96
97    #[test]
98    fn save_then_load_roundtrips_via_real_paths() {
99        // Exercises the REAL `save()`/`load()` entry points (not `save_in`/
100        // `load_from` directly) so a regression like `load()` looking for
101        // `.../user_project.toml/user_project.toml` (passing the file path
102        // instead of its parent dir into `load_from`) would be caught.
103
104        // `commands::project`'s `switch_without_session_or_user_flag_skips_
105        // codebase_check` test also redirects XDG_CONFIG_HOME (to keep its
106        // credential resolution off the developer's real config); both hold
107        // this process-wide lock for their duration so they can't interleave.
108        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
109        let tmp = tempfile::tempdir().unwrap();
110
111        // SAFETY: test-scoped env mutation, restored in a guard so a panic
112        // in `save`/`load` still cleans up the process env.
113        let mut _guard = crate::test_helpers::EnvVarGuard::new();
114        _guard.set("XDG_CONFIG_HOME", tmp.path());
115
116        let pb = ProjectBinding {
117            project_id: "id".into(),
118            project_name: "p".into(),
119            updated_at: "t".into(),
120            forced_until: None,
121        };
122        save(&pb).unwrap();
123        assert_eq!(load(), Some(pb));
124    }
125
126    /// `forced_until` round-trips through the real `save`/`load` on-disk
127    /// format. The LIVENESS check itself (is a given `forced_until` still in
128    /// the future?) lives entirely in
129    /// `commands::stream::attribution_mode` now — this store only persists
130    /// the binding, it doesn't interpret it (see that function's doc comment
131    /// for why: a force is scoped to the binding that carries it, and this
132    /// module has no notion of "the binding that won").
133    #[test]
134    fn forced_until_round_trips() {
135        let dir = tempfile::tempdir().unwrap();
136        let until = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
137        let binding = ProjectBinding {
138            project_id: "3f2504e0-4f89-11d3-9a0c-0305e82c3301".into(),
139            project_name: "p".into(),
140            updated_at: chrono::Utc::now().to_rfc3339(),
141            forced_until: Some(until),
142        };
143        save_in(dir.path(), &binding).unwrap();
144        assert_eq!(load_from(dir.path()), Some(binding));
145    }
146}