Skip to main content

tracevault_cli/commands/
upgrade.rs

1//! The one-time step a newer CLI runs on an existing install (VIS-1109).
2//!
3//! Nothing runs when the CLI binary is replaced, so `session-start` calls
4//! [`run`] once per Claude Code session. It compares this binary's version
5//! with what [`install_state`](crate::install_state) recorded, and when the
6//! binary is newer:
7//!
8//! - **per hook location** (the session's repo, and the global
9//!   `~/.claude/settings.json`): re-merges Visdom's hooks into each Claude
10//!   Code settings file that already holds them, so hooks a newer `init` adds
11//!   (e.g. `SessionEnd`, VIS-1108) reach existing installs. Repos the user
12//!   never opens again keep their old hook set.
13//! - **once per machine**: turns Claude Code telemetry on, unless the user
14//!   opted out, another exporter is set up, or Claude Code is set to export
15//!   content (prompt text etc.), and returns the one-line notice for the user.
16//!
17//! Everything here is best-effort: it never fails the hook. Errors go to
18//! stderr, and a step that could not finish is retried by the next session.
19//!
20//! Per-repo work a later version needs to do once goes into
21//! [`upgrade_hook_location`], after the hooks are re-merged. (VIS-1108's
22//! catch-up sweep is not once per version: `session-start` runs it on every
23//! session, see [`catch_up`](crate::commands::catch_up).)
24
25use crate::commands::claude_telemetry::{self, Environment, InstallOutcome, TelemetryState};
26use crate::install_state::{self, InstallState, RepoState};
27use crate::program::{CLI, TOP};
28use serde_json::Value;
29use std::path::{Path, PathBuf};
30
31/// The notice shown when the upgrade step turned telemetry on.
32pub const TELEMETRY_NOTICE: &str = "AI Tracing: Claude Code cost telemetry is now on for new \
33     sessions (`tracevault telemetry off` to disable)";
34
35/// Where the step reads and writes; [`Paths::current`] for real use, temp
36/// dirs in tests.
37pub struct Paths {
38    /// `~/.config/tracevault`: the install state lives here.
39    pub config_root: PathBuf,
40    /// `~/.claude`: global hooks and the telemetry settings.
41    pub claude_dir: PathBuf,
42    /// The session's repository (primary checkout), if it runs in one.
43    pub project_root: Option<PathBuf>,
44    /// The linked worktree the session runs in, when it is not the primary
45    /// checkout: Claude Code reads that worktree's `.claude/` settings.
46    pub worktree_root: Option<PathBuf>,
47}
48
49impl Paths {
50    /// This user's, for a session whose working directory is `cwd`. `None`
51    /// without a home directory.
52    pub fn current(cwd: &Path) -> Option<Self> {
53        let project = crate::paths::resolve_project_root(cwd);
54        let in_git = project.source == crate::paths::ProjectRootSource::Git;
55        let canonical = |p: &Path| p.canonicalize().unwrap_or_else(|_| p.to_path_buf());
56        let worktree = PathBuf::from(crate::paths::worktree_toplevel(cwd));
57        let worktree_root =
58            (in_git && canonical(&worktree) != canonical(&project.root)).then_some(worktree);
59        Some(Self {
60            config_root: crate::config::tv_config_root(),
61            claude_dir: dirs::home_dir()?.join(".claude"),
62            project_root: Some(project.root),
63            worktree_root,
64        })
65    }
66}
67
68/// Run the upgrade step for `version` (this binary's, in production). The
69/// server telemetry is exported to comes from `server_url`, called only when
70/// telemetry is about to be turned on. Returns the notice for the user, if
71/// there is one. Never panics on I/O; never fails.
72pub fn run(
73    paths: &Paths,
74    version: &str,
75    env: &Environment,
76    server_url: impl FnOnce() -> Result<String, String>,
77) -> Option<String> {
78    let Some(_lock) = install_state::Lock::try_take(&paths.config_root) else {
79        // Another session is upgrading right now; this one leaves it be.
80        return None;
81    };
82    let mut state = install_state::load_in(&paths.config_root);
83    let before = state.clone();
84
85    let mut claude_hooks_found = false;
86    for location in hook_locations(paths) {
87        claude_hooks_found |= upgrade_hook_location(&mut state, &location, version);
88    }
89
90    let notice = if claude_hooks_found
91        && install_state::is_newer(version, state.configured_version.as_deref())
92    {
93        upgrade_machine(&mut state, paths, version, env, server_url)
94    } else {
95        None
96    };
97
98    if state != before {
99        if let Err(e) = install_state::save_in(&paths.config_root, &state) {
100            eprintln!("{TOP}: cannot record the upgrade step: {e}");
101        }
102    }
103    notice
104}
105
106/// A place Visdom's Claude Code hooks may be installed: a repo
107/// (`.claude/settings.json` / `settings.local.json`) or the user's global
108/// settings. `key` names it in the install state.
109struct HookLocation {
110    key: String,
111    candidates: Vec<PathBuf>,
112}
113
114fn hook_locations(paths: &Paths) -> Vec<HookLocation> {
115    let mut out = vec![HookLocation {
116        key: paths.claude_dir.display().to_string(),
117        candidates: vec![paths.claude_dir.join("settings.json")],
118    }];
119    // The primary checkout, where `init` installs, and a linked worktree the
120    // session runs in, whose own `.claude/` Claude Code reads there.
121    for root in paths.project_root.iter().chain(&paths.worktree_root) {
122        // A session in the home directory itself would name ~/.claude twice.
123        let key = root.display().to_string();
124        if root.join(".claude") != paths.claude_dir && out.iter().all(|l| l.key != key) {
125            out.push(HookLocation {
126                key,
127                candidates: ["settings.json", "settings.local.json"]
128                    .iter()
129                    .map(|f| root.join(".claude").join(f))
130                    .collect(),
131            });
132        }
133    }
134    out
135}
136
137/// The `files` that hold Visdom hooks; `Err` when one of them cannot be
138/// read or parsed, so the location is not recorded as having none.
139fn files_with_hooks<'a>(files: impl IntoIterator<Item = &'a PathBuf>) -> Result<Vec<PathBuf>, ()> {
140    let mut found = Vec::new();
141    let mut failed = false;
142    for file in files {
143        match crate::commands::init::has_tracevault_hooks(file) {
144            Ok(true) => found.push(file.clone()),
145            Ok(false) => {}
146            Err(e) => {
147                eprintln!("{TOP}: cannot check the hooks in {}: {e}", file.display());
148                failed = true;
149            }
150        }
151    }
152    if failed {
153        Err(())
154    } else {
155        Ok(found)
156    }
157}
158
159/// Re-merge the hooks at `location` once per version, in every candidate
160/// file that holds our commands (both can, e.g. after a checkout brought in a
161/// shared `settings.json`). The files found are recorded, for the next
162/// sessions of this version (whether the location is installed) and for
163/// `status`. Returns whether `location` holds Visdom's Claude Code hooks.
164fn upgrade_hook_location(state: &mut InstallState, location: &HookLocation, version: &str) -> bool {
165    let recorded = state.repos.get(&location.key);
166    let due = install_state::is_newer(version, recorded.map(|r| r.version.as_str()));
167    let was_installed = recorded.is_some_and(|r| !r.hook_files.is_empty());
168    if !due {
169        return was_installed;
170    }
171    // A file that cannot be read may hold our hooks: retry next session, and
172    // count the location as installed if it was before.
173    let Ok(files) = files_with_hooks(&location.candidates) else {
174        return was_installed;
175    };
176    let mut done = true;
177    for file in &files {
178        if let Err(e) = crate::commands::init::refresh_claude_hooks(file) {
179            eprintln!("{TOP}: cannot update the hooks in {}: {e}", file.display());
180            done = false;
181        }
182    }
183    // VIS-1108's catch-up sweep, which backfills the `cost-state` of sessions
184    // that ended before this upgrade installed `SessionEnd`, is not here:
185    // `session-start` runs it on every session, right after this step (it
186    // needs the network and its own time budget).
187    if done {
188        state.repos.insert(
189            location.key.clone(),
190            RepoState {
191                version: version.to_string(),
192                hook_files: files.clone(),
193            },
194        );
195    }
196    !files.is_empty()
197}
198
199/// Turn Claude Code telemetry on for this machine, unless the user opted out,
200/// it is already exported elsewhere, or content logging is on. Records the
201/// version once settled; leaves it unrecorded (so the next session retries)
202/// when the server is unknown or the settings could not be written.
203fn upgrade_machine(
204    state: &mut InstallState,
205    paths: &Paths,
206    version: &str,
207    env: &Environment,
208    server_url: impl FnOnce() -> Result<String, String>,
209) -> Option<String> {
210    let settled = |state: &mut InstallState| state.configured_version = Some(version.to_string());
211    if state.claude_telemetry_opt_out {
212        settled(state);
213        return None;
214    }
215    let settings = match read_settings(&paths.claude_dir.join("settings.json")) {
216        Ok(s) => s,
217        Err(e) => {
218            eprintln!("{TOP}: Claude Code telemetry not turned on: {e}");
219            return None;
220        }
221    };
222    let was_off = match claude_telemetry::inspect(&settings, env, None) {
223        TelemetryState::Foreign { .. } => {
224            settled(state);
225            return None;
226        }
227        TelemetryState::Off => true,
228        TelemetryState::Ours { .. } => false,
229    };
230    if was_off {
231        let content = claude_telemetry::content_logging_settings(&settings, env);
232        if !content.is_empty() {
233            eprintln!(
234                "{TOP}: Claude Code telemetry left off: it is set to export content ({}); \
235                 run `{CLI} telemetry on` to send it to Visdom anyway",
236                content.join("; ")
237            );
238            settled(state);
239            return None;
240        }
241    }
242    let url = match server_url() {
243        Ok(url) => url,
244        Err(e) => {
245            eprintln!("{TOP}: Claude Code telemetry not turned on: {e}");
246            return None;
247        }
248    };
249    let interval_ours = claude_telemetry::interval_added_by_install(&paths.claude_dir);
250    match claude_telemetry::install(&paths.claude_dir, &url, env) {
251        Ok(InstallOutcome::Configured) => {
252            settled(state);
253            if interval_ours.is_some() {
254                state.telemetry_added_interval = interval_ours;
255            }
256            if was_off {
257                state.telemetry_auto_enabled = Some(version.to_string());
258                Some(crate::program::say(TELEMETRY_NOTICE))
259            } else {
260                None
261            }
262        }
263        Ok(InstallOutcome::Foreign(_)) => {
264            settled(state);
265            None
266        }
267        Err(e) => {
268            eprintln!("{TOP}: Claude Code telemetry not turned on: {e}");
269            None
270        }
271    }
272}
273
274/// `~/.claude/settings.json` parsed; a missing file is `{}`.
275fn read_settings(path: &Path) -> Result<Value, String> {
276    match std::fs::read_to_string(path) {
277        Ok(s) => {
278            serde_json::from_str(&s).map_err(|e| format!("cannot parse {}: {e}", path.display()))
279        }
280        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(serde_json::json!({})),
281        Err(e) => Err(format!("cannot read {}: {e}", path.display())),
282    }
283}
284
285#[cfg(test)]
286mod tests {
287    use super::*;
288    use serde_json::json;
289    use std::fs;
290
291    const SERVER: &str = "https://tv.example.com";
292
293    struct Fixture {
294        _home: tempfile::TempDir,
295        paths: Paths,
296    }
297
298    /// A home with a repo whose `.claude/<hooks_file>` holds an old hook set
299    /// (no SubagentStop, an extra retired event).
300    fn fixture(hooks_file: &str) -> Fixture {
301        let home = tempfile::tempdir().unwrap();
302        let repo = home.path().join("repo");
303        fs::create_dir_all(repo.join(".claude")).unwrap();
304        fs::write(
305            repo.join(".claude").join(hooks_file),
306            json!({"hooks": {
307                "Stop": [{"matcher": "", "hooks": [
308                    {"type": "command", "command": "tracevault stream --event stop"}]}],
309                "PreCompact": [{"matcher": "", "hooks": [
310                    {"type": "command", "command": "tracevault stream --event pre-compact"}]}],
311                "PostToolUse": [{"matcher": "", "hooks": [
312                    {"type": "command", "command": "./my-own-hook.sh"}]}]
313            }})
314            .to_string(),
315        )
316        .unwrap();
317        let paths = Paths {
318            config_root: home.path().join(".config/visdom"),
319            claude_dir: home.path().join(".claude"),
320            project_root: Some(repo),
321            worktree_root: None,
322        };
323        Fixture { _home: home, paths }
324    }
325
326    fn run_with(paths: &Paths, version: &str, env: &Environment) -> Option<String> {
327        run(paths, version, env, || Ok(SERVER.to_string()))
328    }
329
330    fn json_at(path: &Path) -> Value {
331        serde_json::from_str(&fs::read_to_string(path).unwrap()).unwrap()
332    }
333
334    fn user_settings(paths: &Paths) -> Value {
335        json_at(&paths.claude_dir.join("settings.json"))
336    }
337
338    fn repo_settings(paths: &Paths, file: &str) -> Value {
339        json_at(
340            &paths
341                .project_root
342                .as_ref()
343                .unwrap()
344                .join(".claude")
345                .join(file),
346        )
347    }
348
349    #[test]
350    fn existing_install_gets_current_hooks_and_telemetry_with_the_notice_once() {
351        let f = fixture("settings.local.json");
352        let notice = run_with(&f.paths, "0.30.0", &Environment::default());
353        assert_eq!(notice.as_deref(), Some(TELEMETRY_NOTICE));
354
355        let hooks = &repo_settings(&f.paths, "settings.local.json")["hooks"];
356        for event in crate::commands::init::tracevault_hooks()
357            .as_object()
358            .unwrap()
359            .keys()
360        {
361            assert!(hooks[event].is_array(), "{event} installed");
362        }
363        assert_eq!(
364            hooks["SessionEnd"][0]["hooks"][0]["command"], "tracevault stream --event session-end",
365            "an existing install gets the SessionEnd hook (VIS-1108)"
366        );
367        assert!(hooks.get("PreCompact").is_none(), "retired event removed");
368        assert!(
369            hooks.to_string().contains("./my-own-hook.sh"),
370            "foreign hook kept"
371        );
372        assert!(
373            !f.paths
374                .project_root
375                .as_ref()
376                .unwrap()
377                .join(".claude/settings.json")
378                .exists(),
379            "the other settings file is not created"
380        );
381
382        let s = user_settings(&f.paths);
383        assert_eq!(
384            s["otelHeadersHelper"],
385            "tracevault otel-headers --server-url https://tv.example.com"
386        );
387        assert!(s.get("hooks").is_none(), "global hooks are not installed");
388
389        let state = install_state::load_in(&f.paths.config_root);
390        assert_eq!(state.configured_version.as_deref(), Some("0.30.0"));
391        assert_eq!(state.telemetry_auto_enabled.as_deref(), Some("0.30.0"));
392        let repo_key = f.paths.project_root.as_ref().unwrap().display().to_string();
393        assert_eq!(
394            state.repos[&repo_key].hook_files,
395            vec![f
396                .paths
397                .project_root
398                .as_ref()
399                .unwrap()
400                .join(".claude/settings.local.json")]
401        );
402
403        // The next session: nothing to do, no notice.
404        assert_eq!(run_with(&f.paths, "0.30.0", &Environment::default()), None);
405        assert!(!f.paths.config_root.join("install-state.lock").exists());
406    }
407
408    #[test]
409    fn opted_out_machine_stays_off_but_hooks_are_updated() {
410        let f = fixture("settings.json");
411        install_state::update_in(&f.paths.config_root, |s| {
412            s.claude_telemetry_opt_out = true;
413            s.configured_version = Some("0.29.0".into());
414        })
415        .unwrap();
416        assert_eq!(run_with(&f.paths, "0.30.0", &Environment::default()), None);
417        assert!(!f.paths.claude_dir.join("settings.json").exists());
418        assert!(repo_settings(&f.paths, "settings.json")["hooks"]["SessionStart"].is_array());
419        assert_eq!(
420            install_state::load_in(&f.paths.config_root)
421                .configured_version
422                .as_deref(),
423            Some("0.30.0")
424        );
425    }
426
427    #[test]
428    fn foreign_exporter_is_untouched() {
429        let f = fixture("settings.json");
430        fs::create_dir_all(&f.paths.claude_dir).unwrap();
431        let foreign = json!({"env": {"OTEL_LOGS_EXPORTER": "otlp",
432            "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT": "https://collector.corp/v1/logs"}});
433        fs::write(
434            f.paths.claude_dir.join("settings.json"),
435            foreign.to_string(),
436        )
437        .unwrap();
438        assert_eq!(run_with(&f.paths, "0.30.0", &Environment::default()), None);
439        assert_eq!(user_settings(&f.paths), foreign);
440        let state = install_state::load_in(&f.paths.config_root);
441        assert_eq!(state.configured_version.as_deref(), Some("0.30.0"));
442        assert_eq!(state.telemetry_auto_enabled, None);
443    }
444
445    #[test]
446    fn content_logging_keeps_telemetry_off() {
447        let f = fixture("settings.json");
448        let env = claude_telemetry::tests::shell("OTEL_LOG_USER_PROMPTS", "1");
449        assert_eq!(run_with(&f.paths, "0.30.0", &env), None);
450        assert!(!f.paths.claude_dir.join("settings.json").exists());
451    }
452
453    #[test]
454    fn already_ours_is_refreshed_without_a_notice() {
455        let f = fixture("settings.json");
456        claude_telemetry::install(&f.paths.claude_dir, SERVER, &Environment::default()).unwrap();
457        assert_eq!(run_with(&f.paths, "0.30.0", &Environment::default()), None);
458        assert_eq!(
459            install_state::load_in(&f.paths.config_root).telemetry_auto_enabled,
460            None
461        );
462    }
463
464    #[test]
465    fn not_logged_in_is_retried_by_the_next_session() {
466        let f = fixture("settings.json");
467        let notice = run(&f.paths, "0.30.0", &Environment::default(), || {
468            Err("Not logged in".into())
469        });
470        assert_eq!(notice, None);
471        assert_eq!(
472            install_state::load_in(&f.paths.config_root).configured_version,
473            None
474        );
475        assert_eq!(
476            run_with(&f.paths, "0.30.0", &Environment::default()).as_deref(),
477            Some(TELEMETRY_NOTICE)
478        );
479    }
480
481    #[test]
482    fn without_claude_hooks_nothing_is_done() {
483        // E.g. a Codex-only install, whose hooks also run `session-start`.
484        let home = tempfile::tempdir().unwrap();
485        let paths = Paths {
486            config_root: home.path().join(".config/visdom"),
487            claude_dir: home.path().join(".claude"),
488            project_root: Some(home.path().join("repo")),
489            worktree_root: None,
490        };
491        assert_eq!(run_with(&paths, "0.30.0", &Environment::default()), None);
492        assert!(!paths.claude_dir.join("settings.json").exists());
493        assert_eq!(
494            install_state::load_in(&paths.config_root).configured_version,
495            None
496        );
497    }
498
499    #[test]
500    fn global_hooks_are_refreshed_and_count_as_an_install() {
501        let home = tempfile::tempdir().unwrap();
502        let claude_dir = home.path().join(".claude");
503        fs::create_dir_all(&claude_dir).unwrap();
504        fs::write(
505            claude_dir.join("settings.json"),
506            json!({"hooks": {"Stop": [{"matcher": "", "hooks": [
507                {"type": "command", "command": "tracevault stream --event stop"}]}]}})
508            .to_string(),
509        )
510        .unwrap();
511        let paths = Paths {
512            config_root: home.path().join(".config/visdom"),
513            claude_dir,
514            project_root: None,
515            worktree_root: None,
516        };
517        assert_eq!(
518            run_with(&paths, "0.30.0", &Environment::default()).as_deref(),
519            Some(TELEMETRY_NOTICE)
520        );
521        let s = user_settings(&paths);
522        assert!(s["hooks"]["SessionStart"].is_array());
523        assert!(s["otelHeadersHelper"].is_string());
524    }
525
526    #[test]
527    fn a_downgrade_or_the_same_version_does_nothing() {
528        let f = fixture("settings.json");
529        install_state::update_in(&f.paths.config_root, |s| {
530            s.configured_version = Some("0.31.0".into());
531            let key = f.paths.project_root.as_ref().unwrap().display().to_string();
532            s.repos.insert(
533                key,
534                RepoState {
535                    version: "0.31.0".into(),
536                    hook_files: vec![],
537                },
538            );
539        })
540        .unwrap();
541        let before = fs::read_to_string(
542            f.paths
543                .project_root
544                .as_ref()
545                .unwrap()
546                .join(".claude/settings.json"),
547        )
548        .unwrap();
549        assert_eq!(run_with(&f.paths, "0.30.0", &Environment::default()), None);
550        let after = fs::read_to_string(
551            f.paths
552                .project_root
553                .as_ref()
554                .unwrap()
555                .join(".claude/settings.json"),
556        )
557        .unwrap();
558        assert_eq!(before, after);
559    }
560
561    #[test]
562    fn a_held_lock_skips_the_step_and_a_stale_one_is_taken_over() {
563        let f = fixture("settings.json");
564        fs::create_dir_all(&f.paths.config_root).unwrap();
565        let lock = f.paths.config_root.join("install-state.lock");
566        fs::write(&lock, "").unwrap();
567        assert_eq!(run_with(&f.paths, "0.30.0", &Environment::default()), None);
568        assert!(!f.paths.claude_dir.join("settings.json").exists());
569
570        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(120);
571        fs::File::options()
572            .write(true)
573            .open(&lock)
574            .unwrap()
575            .set_modified(old)
576            .unwrap();
577        assert!(run_with(&f.paths, "0.30.0", &Environment::default()).is_some());
578        assert!(!lock.exists());
579    }
580
581    #[test]
582    fn malformed_repo_settings_do_not_fail_and_are_retried() {
583        let f = fixture("settings.json");
584        let file = f
585            .paths
586            .project_root
587            .as_ref()
588            .unwrap()
589            .join(".claude/settings.json");
590        // Holds our hook, but `hooks.Stop` is not an array: the merge refuses.
591        fs::write(
592            &file,
593            r#"{"hooks": {"Stop": {"x": 1}, "SessionStart": [{"hooks": [{"command": "tracevault session-start"}]}]}}"#,
594        )
595        .unwrap();
596        run_with(&f.paths, "0.30.0", &Environment::default());
597        let key = f.paths.project_root.as_ref().unwrap().display().to_string();
598        assert!(!install_state::load_in(&f.paths.config_root)
599            .repos
600            .contains_key(&key));
601    }
602
603    #[test]
604    fn unparseable_settings_are_not_recorded_as_hook_free() {
605        let f = fixture("settings.json");
606        let file = f
607            .paths
608            .project_root
609            .as_ref()
610            .unwrap()
611            .join(".claude/settings.json");
612        let good = fs::read_to_string(&file).unwrap();
613        fs::write(&file, "{ half-written").unwrap();
614        assert_eq!(run_with(&f.paths, "0.30.0", &Environment::default()), None);
615        let key = f.paths.project_root.as_ref().unwrap().display().to_string();
616        assert!(!install_state::load_in(&f.paths.config_root)
617            .repos
618            .contains_key(&key));
619
620        // Repaired: the next session at the same version does the work.
621        fs::write(&file, good).unwrap();
622        assert_eq!(
623            run_with(&f.paths, "0.30.0", &Environment::default()).as_deref(),
624            Some(TELEMETRY_NOTICE)
625        );
626        assert!(repo_settings(&f.paths, "settings.json")["hooks"]["SessionStart"].is_array());
627    }
628
629    #[test]
630    fn every_settings_file_with_our_hooks_is_refreshed_not_only_the_recorded_one() {
631        let f = fixture("settings.local.json");
632        run_with(&f.paths, "0.30.0", &Environment::default());
633        // A checkout later brings in a shared settings.json with old hooks.
634        let shared = f
635            .paths
636            .project_root
637            .as_ref()
638            .unwrap()
639            .join(".claude/settings.json");
640        fs::write(
641            &shared,
642            json!({"hooks": {"Stop": [{"matcher": "", "hooks": [
643                {"type": "command", "command": "tracevault stream --event stop"}]}]}})
644            .to_string(),
645        )
646        .unwrap();
647        run_with(&f.paths, "0.31.0", &Environment::default());
648        assert!(json_at(&shared)["hooks"]["SessionStart"].is_array());
649        let key = f.paths.project_root.as_ref().unwrap().display().to_string();
650        assert_eq!(
651            install_state::load_in(&f.paths.config_root).repos[&key]
652                .hook_files
653                .len(),
654            2
655        );
656    }
657
658    #[test]
659    fn an_opt_out_holding_the_lock_wins_over_a_concurrent_upgrade() {
660        // `telemetry off` holds the lock while it removes our settings and
661        // records the opt-out; an upgrade starting meanwhile does nothing,
662        // and every later one sees the opt-out.
663        let f = fixture("settings.json");
664        claude_telemetry::install(&f.paths.claude_dir, SERVER, &Environment::default()).unwrap();
665        let lock = install_state::Lock::try_take(&f.paths.config_root).unwrap();
666        assert_eq!(run_with(&f.paths, "0.30.0", &Environment::default()), None);
667        assert!(
668            claude_telemetry::uninstall(&f.paths.claude_dir, &Environment::default(), None)
669                .unwrap()
670        );
671        install_state::update_in(&f.paths.config_root, |s| s.claude_telemetry_opt_out = true)
672            .unwrap();
673        drop(lock);
674
675        for version in ["0.30.0", "0.31.0"] {
676            assert_eq!(run_with(&f.paths, version, &Environment::default()), None);
677        }
678        assert_eq!(user_settings(&f.paths), json!({}));
679        let state = install_state::load_in(&f.paths.config_root);
680        assert!(state.claude_telemetry_opt_out);
681        assert_eq!(state.configured_version.as_deref(), Some("0.31.0"));
682    }
683
684    #[test]
685    fn the_interval_the_upgrade_added_is_recorded_as_ours() {
686        let f = fixture("settings.json");
687        run_with(&f.paths, "0.30.0", &Environment::default());
688        assert_eq!(
689            install_state::load_in(&f.paths.config_root).telemetry_added_interval,
690            Some(true)
691        );
692    }
693
694    #[test]
695    fn a_linked_worktrees_own_settings_are_refreshed_too() {
696        let f = fixture("settings.local.json");
697        let worktree = f._home.path().join("wt");
698        fs::create_dir_all(worktree.join(".claude")).unwrap();
699        fs::write(
700            worktree.join(".claude/settings.json"),
701            json!({"hooks": {"Stop": [{"matcher": "", "hooks": [
702                {"type": "command", "command": "tracevault stream --event stop"}]}]}})
703            .to_string(),
704        )
705        .unwrap();
706        let paths = Paths {
707            worktree_root: Some(worktree.clone()),
708            config_root: f.paths.config_root.clone(),
709            claude_dir: f.paths.claude_dir.clone(),
710            project_root: f.paths.project_root.clone(),
711        };
712        run_with(&paths, "0.30.0", &Environment::default());
713        let wt = json_at(&worktree.join(".claude/settings.json"));
714        assert!(wt["hooks"]["SessionStart"].is_array());
715        assert!(repo_settings(&paths, "settings.local.json")["hooks"]["SessionStart"].is_array());
716    }
717}