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