Skip to main content

tracevault_cli/
install_state.rs

1//! User-level install state (VIS-1109): what this machine's Visdom 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//! `.visdom/` 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 Visdom 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 Visdom'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    // Still in the legacy directory until something saves it.
55    std::fs::read_to_string(crate::layout::user_path(config_root, "install-state.json"))
56        .ok()
57        .and_then(|s| serde_json::from_str(&s).ok())
58        .unwrap_or_default()
59}
60
61/// Write `state` atomically (temp file + rename), creating `config_root`.
62pub fn save_in(config_root: &Path, state: &InstallState) -> std::io::Result<()> {
63    std::fs::create_dir_all(config_root)?;
64    let path = state_path_in(config_root);
65    let tmp = path.with_file_name(format!(
66        "install-state.json.{}.{}.tmp",
67        std::process::id(),
68        std::time::SystemTime::now()
69            .duration_since(std::time::UNIX_EPOCH)
70            .map(|d| d.subsec_nanos())
71            .unwrap_or_default()
72    ));
73    let body = serde_json::to_string_pretty(state).map_err(std::io::Error::other)?;
74    std::fs::write(&tmp, body)
75        .and_then(|()| std::fs::rename(&tmp, &path))
76        .inspect_err(|_| {
77            let _ = std::fs::remove_file(&tmp);
78        })
79}
80
81/// Load, apply `change`, save.
82pub fn update_in(
83    config_root: &Path,
84    change: impl FnOnce(&mut InstallState),
85) -> std::io::Result<()> {
86    let mut state = load_in(config_root);
87    change(&mut state);
88    save_in(config_root, &state)
89}
90
91/// Serialises whoever changes the telemetry settings together with this
92/// state: the upgrade step and `telemetry on|off` / `init`. Without it, an
93/// upgrade that read the state before an opt-out could turn telemetry back on
94/// and save its stale copy over the opt-out. Also keeps two sessions starting
95/// at once from both showing the notice. A lock older than [`Lock::STALE`]
96/// was left by a killed process and is taken over. Released on drop.
97pub struct Lock(PathBuf);
98
99impl Lock {
100    const STALE: std::time::Duration = std::time::Duration::from_secs(60);
101
102    fn lock_path(config_root: &Path) -> PathBuf {
103        config_root.join("install-state.lock")
104    }
105
106    /// Take the lock if it is free; `None` when someone else holds it.
107    pub fn try_take(config_root: &Path) -> Option<Self> {
108        std::fs::create_dir_all(config_root).ok()?;
109        let path = Self::lock_path(config_root);
110        for _ in 0..2 {
111            match std::fs::OpenOptions::new()
112                .write(true)
113                .create_new(true)
114                .open(&path)
115            {
116                Ok(_) => return Some(Self(path)),
117                Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
118                    let stale = std::fs::metadata(&path)
119                        .and_then(|m| m.modified())
120                        .ok()
121                        .and_then(|t| t.elapsed().ok())
122                        .is_some_and(|age| age > Self::STALE);
123                    if !stale {
124                        return None;
125                    }
126                    let _ = std::fs::remove_file(&path);
127                }
128                Err(_) => return None,
129            }
130        }
131        None
132    }
133
134    /// Wait up to `timeout` for the lock (an upgrade step holds it for well
135    /// under a second).
136    pub fn take(config_root: &Path, timeout: std::time::Duration) -> std::io::Result<Self> {
137        let deadline = std::time::Instant::now() + timeout;
138        loop {
139            if let Some(lock) = Self::try_take(config_root) {
140                return Ok(lock);
141            }
142            if std::time::Instant::now() >= deadline {
143                return Err(std::io::Error::other(format!(
144                    "{} is held by another Visdom process; try again",
145                    Self::lock_path(config_root).display()
146                )));
147            }
148            std::thread::sleep(std::time::Duration::from_millis(50));
149        }
150    }
151}
152
153impl Drop for Lock {
154    fn drop(&mut self) {
155        let _ = std::fs::remove_file(&self.0);
156    }
157}
158
159/// This binary's version.
160pub const CURRENT_VERSION: &str = env!("CARGO_PKG_VERSION");
161
162/// `major.minor.patch` of a version string; a pre-release or build suffix is
163/// ignored. `None` when it does not parse.
164fn parse(version: &str) -> Option<(u64, u64, u64)> {
165    let core = version.trim().split(['-', '+']).next()?;
166    let mut parts = core.split('.').map(|p| p.parse::<u64>().ok());
167    let v = (parts.next()??, parts.next()??, parts.next()??);
168    parts.next().is_none().then_some(v)
169}
170
171/// Whether `current` is newer than the `recorded` version. Nothing recorded
172/// (or something unparseable) counts as older, so the step runs; a recorded
173/// version newer than `current` (a downgrade) does not.
174pub fn is_newer(current: &str, recorded: Option<&str>) -> bool {
175    match (parse(current), recorded.and_then(parse)) {
176        (Some(current), Some(recorded)) => current > recorded,
177        _ => true,
178    }
179}
180
181#[cfg(test)]
182mod tests {
183    use super::*;
184
185    #[test]
186    fn version_comparison() {
187        assert!(is_newer("0.30.0", None));
188        assert!(is_newer("0.30.0", Some("0.29.1")));
189        assert!(is_newer("1.0.0", Some("0.99.99")));
190        assert!(is_newer("0.30.0", Some("garbage")));
191        assert!(!is_newer("0.30.0", Some("0.30.0")));
192        assert!(!is_newer("0.29.1", Some("0.30.0")));
193        assert!(!is_newer("0.30.0-rc.1", Some("0.30.0")));
194        assert!(is_newer("0.10.0", Some("0.9.9")), "numeric, not lexical");
195    }
196
197    #[test]
198    fn missing_or_malformed_state_is_empty_and_round_trips() {
199        let dir = tempfile::tempdir().unwrap();
200        assert_eq!(load_in(dir.path()), InstallState::default());
201        std::fs::write(state_path_in(dir.path()), "{not json").unwrap();
202        assert_eq!(load_in(dir.path()), InstallState::default());
203
204        let mut state = InstallState {
205            configured_version: Some("0.30.0".into()),
206            claude_telemetry_opt_out: true,
207            ..Default::default()
208        };
209        state.repos.insert(
210            "/r".into(),
211            RepoState {
212                version: "0.30.0".into(),
213                hook_files: vec!["/r/.claude/settings.local.json".into()],
214            },
215        );
216        save_in(&dir.path().join("nested"), &state).unwrap();
217        assert_eq!(load_in(&dir.path().join("nested")), state);
218    }
219
220    #[test]
221    fn empty_state_serializes_to_an_empty_object() {
222        assert_eq!(
223            serde_json::to_string(&InstallState::default()).unwrap(),
224            "{}"
225        );
226    }
227}