Skip to main content

tracevault_cli/
install_state.rs

1//! User-level install state (VIS-1109): what this machine's TraceVault setup
2//! was last brought to, so a newer CLI knows to run its upgrade step once
3//! (`commands::upgrade`), and the user's Claude Code telemetry opt-out, so
4//! nothing ever turns telemetry back on after `--no-claude-telemetry`.
5//!
6//! Kept in `~/.config/tracevault/install-state.json`, beside `config.toml`:
7//! `config.toml` is rewritten from its struct by `init --global`, and a repo's
8//! `.tracevault/` does not exist in workspace mode.
9
10use serde::{Deserialize, Serialize};
11use std::collections::BTreeMap;
12use std::path::{Path, PathBuf};
13
14#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
15pub struct InstallState {
16    /// The CLI version that last ran the machine-wide step (telemetry, global
17    /// hooks). `None`: an install older than this field, or none at all.
18    #[serde(default, skip_serializing_if = "Option::is_none")]
19    pub configured_version: Option<String>,
20    /// The user turned Claude Code telemetry off (`--no-claude-telemetry`,
21    /// `tracevault telemetry off`, or no at the `init` prompt).
22    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
23    pub claude_telemetry_opt_out: bool,
24    /// The version whose upgrade step turned telemetry on without the user
25    /// asking, for `status` to say so. Cleared by an explicit on/off.
26    #[serde(default, skip_serializing_if = "Option::is_none")]
27    pub telemetry_auto_enabled: Option<String>,
28    /// Whether TraceVault added the helper interval to `~/.claude/settings.json`
29    /// (so turning telemetry off removes it) or found the user's own there.
30    /// `None` for installs made before this was recorded.
31    #[serde(default, skip_serializing_if = "Option::is_none")]
32    pub telemetry_added_interval: Option<bool>,
33    /// Per repository (primary checkout path): the version that last re-merged
34    /// its hooks, and the settings files they were found in.
35    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
36    pub repos: BTreeMap<String, RepoState>,
37}
38
39#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
40pub struct RepoState {
41    pub version: String,
42    /// Settings files (absolute paths) holding TraceVault's Claude Code hooks.
43    #[serde(default)]
44    pub hook_files: Vec<PathBuf>,
45}
46
47pub fn state_path_in(config_root: &Path) -> PathBuf {
48    config_root.join("install-state.json")
49}
50
51/// The state under `config_root`; a missing or unreadable file is an empty
52/// state (every step then runs once, which is safe: each one is idempotent).
53pub fn load_in(config_root: &Path) -> InstallState {
54    std::fs::read_to_string(state_path_in(config_root))
55        .ok()
56        .and_then(|s| serde_json::from_str(&s).ok())
57        .unwrap_or_default()
58}
59
60/// Write `state` atomically (temp file + rename), creating `config_root`.
61pub fn save_in(config_root: &Path, state: &InstallState) -> std::io::Result<()> {
62    std::fs::create_dir_all(config_root)?;
63    let path = state_path_in(config_root);
64    let tmp = path.with_file_name(format!(
65        "install-state.json.{}.{}.tmp",
66        std::process::id(),
67        std::time::SystemTime::now()
68            .duration_since(std::time::UNIX_EPOCH)
69            .map(|d| d.subsec_nanos())
70            .unwrap_or_default()
71    ));
72    let body = serde_json::to_string_pretty(state).map_err(std::io::Error::other)?;
73    std::fs::write(&tmp, body)
74        .and_then(|()| std::fs::rename(&tmp, &path))
75        .inspect_err(|_| {
76            let _ = std::fs::remove_file(&tmp);
77        })
78}
79
80/// Load, apply `change`, save.
81pub fn update_in(
82    config_root: &Path,
83    change: impl FnOnce(&mut InstallState),
84) -> std::io::Result<()> {
85    let mut state = load_in(config_root);
86    change(&mut state);
87    save_in(config_root, &state)
88}
89
90/// Serialises whoever changes the telemetry settings together with this
91/// state: the upgrade step and `telemetry on|off` / `init`. Without it, an
92/// upgrade that read the state before an opt-out could turn telemetry back on
93/// and save its stale copy over the opt-out. Also keeps two sessions starting
94/// at once from both showing the notice. A lock older than [`Lock::STALE`]
95/// was left by a killed process and is taken over. Released on drop.
96pub struct Lock(PathBuf);
97
98impl Lock {
99    const STALE: std::time::Duration = std::time::Duration::from_secs(60);
100
101    fn lock_path(config_root: &Path) -> PathBuf {
102        config_root.join("install-state.lock")
103    }
104
105    /// Take the lock if it is free; `None` when someone else holds it.
106    pub fn try_take(config_root: &Path) -> Option<Self> {
107        std::fs::create_dir_all(config_root).ok()?;
108        let path = Self::lock_path(config_root);
109        for _ in 0..2 {
110            match std::fs::OpenOptions::new()
111                .write(true)
112                .create_new(true)
113                .open(&path)
114            {
115                Ok(_) => return Some(Self(path)),
116                Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
117                    let stale = std::fs::metadata(&path)
118                        .and_then(|m| m.modified())
119                        .ok()
120                        .and_then(|t| t.elapsed().ok())
121                        .is_some_and(|age| age > Self::STALE);
122                    if !stale {
123                        return None;
124                    }
125                    let _ = std::fs::remove_file(&path);
126                }
127                Err(_) => return None,
128            }
129        }
130        None
131    }
132
133    /// Wait up to `timeout` for the lock (an upgrade step holds it for well
134    /// under a second).
135    pub fn take(config_root: &Path, timeout: std::time::Duration) -> std::io::Result<Self> {
136        let deadline = std::time::Instant::now() + timeout;
137        loop {
138            if let Some(lock) = Self::try_take(config_root) {
139                return Ok(lock);
140            }
141            if std::time::Instant::now() >= deadline {
142                return Err(std::io::Error::other(format!(
143                    "{} is held by another TraceVault process; try again",
144                    Self::lock_path(config_root).display()
145                )));
146            }
147            std::thread::sleep(std::time::Duration::from_millis(50));
148        }
149    }
150}
151
152impl Drop for Lock {
153    fn drop(&mut self) {
154        let _ = std::fs::remove_file(&self.0);
155    }
156}
157
158/// This binary's version.
159pub const CURRENT_VERSION: &str = env!("CARGO_PKG_VERSION");
160
161/// `major.minor.patch` of a version string; a pre-release or build suffix is
162/// ignored. `None` when it does not parse.
163fn parse(version: &str) -> Option<(u64, u64, u64)> {
164    let core = version.trim().split(['-', '+']).next()?;
165    let mut parts = core.split('.').map(|p| p.parse::<u64>().ok());
166    let v = (parts.next()??, parts.next()??, parts.next()??);
167    parts.next().is_none().then_some(v)
168}
169
170/// Whether `current` is newer than the `recorded` version. Nothing recorded
171/// (or something unparseable) counts as older, so the step runs; a recorded
172/// version newer than `current` (a downgrade) does not.
173pub fn is_newer(current: &str, recorded: Option<&str>) -> bool {
174    match (parse(current), recorded.and_then(parse)) {
175        (Some(current), Some(recorded)) => current > recorded,
176        _ => true,
177    }
178}
179
180#[cfg(test)]
181mod tests {
182    use super::*;
183
184    #[test]
185    fn version_comparison() {
186        assert!(is_newer("0.30.0", None));
187        assert!(is_newer("0.30.0", Some("0.29.1")));
188        assert!(is_newer("1.0.0", Some("0.99.99")));
189        assert!(is_newer("0.30.0", Some("garbage")));
190        assert!(!is_newer("0.30.0", Some("0.30.0")));
191        assert!(!is_newer("0.29.1", Some("0.30.0")));
192        assert!(!is_newer("0.30.0-rc.1", Some("0.30.0")));
193        assert!(is_newer("0.10.0", Some("0.9.9")), "numeric, not lexical");
194    }
195
196    #[test]
197    fn missing_or_malformed_state_is_empty_and_round_trips() {
198        let dir = tempfile::tempdir().unwrap();
199        assert_eq!(load_in(dir.path()), InstallState::default());
200        std::fs::write(state_path_in(dir.path()), "{not json").unwrap();
201        assert_eq!(load_in(dir.path()), InstallState::default());
202
203        let mut state = InstallState {
204            configured_version: Some("0.30.0".into()),
205            claude_telemetry_opt_out: true,
206            ..Default::default()
207        };
208        state.repos.insert(
209            "/r".into(),
210            RepoState {
211                version: "0.30.0".into(),
212                hook_files: vec!["/r/.claude/settings.local.json".into()],
213            },
214        );
215        save_in(&dir.path().join("nested"), &state).unwrap();
216        assert_eq!(load_in(&dir.path().join("nested")), state);
217    }
218
219    #[test]
220    fn empty_state_serializes_to_an_empty_object() {
221        assert_eq!(
222            serde_json::to_string(&InstallState::default()).unwrap(),
223            "{}"
224        );
225    }
226}