Skip to main content

agentmux_srv_core/backend/
shellintegration_prune.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Removes the per-instance shell-integration folders (`~/.agentmux/shell/<hash>`)
5//! of instances that no longer exist.
6//!
7//! `integration_base_for` keys a folder by a hash of the instance's data dir, so
8//! every dev build, test home and old version leaves one behind (372 on one
9//! machine after two months). A hash can't be reversed, so each folder records
10//! the data dir it belongs to in `.instance`; a folder is stale when that dir is
11//! gone. Age is never the test.
12//!
13//! A folder from before the marker existed is matched against the instances
14//! still on disk and stamped, so it is cleaned up later once its dir goes away.
15//! One that matches nothing is left alone: its dir may live anywhere.
16
17use std::path::{Path, PathBuf};
18
19use super::shellintegration::instance_key;
20
21const INSTANCE_MARKER: &str = ".instance";
22
23#[derive(Debug, Default, PartialEq, Eq)]
24pub struct PruneReport {
25    pub removed: usize,
26    pub stamped: usize,
27    /// Folders with no marker that match no known instance: left in place.
28    pub unattributed: usize,
29}
30
31/// Records which instance `base` belongs to. Called at deploy.
32pub fn stamp_instance(base: &Path, data_dir: &Path) {
33    let canonical = data_dir.canonicalize().unwrap_or_else(|_| data_dir.to_path_buf());
34    if let Err(e) = std::fs::write(base.join(INSTANCE_MARKER), canonical.to_string_lossy().as_bytes()) {
35        tracing::debug!("shell integration: could not stamp {}: {}", base.display(), e);
36    }
37}
38
39fn is_instance_folder_name(name: &str) -> bool {
40    name.len() == 16 && name.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
41}
42
43/// True only when the path is definitely absent. An unreadable path (a drive
44/// that is offline, a permissions error) is not proof the instance is gone.
45fn definitely_gone(path: &Path) -> bool {
46    matches!(std::fs::metadata(path), Err(e) if e.kind() == std::io::ErrorKind::NotFound)
47}
48
49/// Sweeps `shell_root`, keeping `current_base` and every folder whose instance
50/// still exists. `live_data_dirs` are the instance data dirs found on disk.
51pub fn prune_stale_integration_dirs(
52    shell_root: &Path,
53    current_base: &Path,
54    live_data_dirs: &[PathBuf],
55) -> PruneReport {
56    let mut report = PruneReport::default();
57    let Ok(entries) = std::fs::read_dir(shell_root) else { return report };
58    for entry in entries.flatten() {
59        let path = entry.path();
60        let name = entry.file_name().to_string_lossy().into_owned();
61        if !is_instance_folder_name(&name) || !path.is_dir() || path == current_base {
62            continue;
63        }
64        match std::fs::read_to_string(path.join(INSTANCE_MARKER)) {
65            Ok(recorded) => {
66                // Verbatim: a data dir's name may end in whitespace, and `stamp_instance` writes no newline.
67                if !recorded.is_empty() && definitely_gone(Path::new(&recorded)) {
68                    match std::fs::remove_dir_all(&path) {
69                        Ok(()) => report.removed += 1,
70                        Err(e) => tracing::debug!("shell integration: could not remove {}: {}", path.display(), e),
71                    }
72                }
73            }
74            Err(_) => match live_data_dirs.iter().find(|d| instance_key(d) == name) {
75                Some(dir) => {
76                    stamp_instance(&path, dir);
77                    report.stamped += 1;
78                }
79                None => report.unattributed += 1,
80            },
81        }
82    }
83    report
84}
85
86/// The data dir of every instance `~/.agentmux` knows of: installed versions
87/// and dev builds.
88pub fn live_instance_data_dirs(agentmux_home: &Path) -> Vec<PathBuf> {
89    crate::registry::enumerate_objects_dbs(agentmux_home)
90        .into_iter()
91        .filter_map(|db| db.parent()?.parent().map(Path::to_path_buf))
92        .collect()
93}
94
95#[cfg(test)]
96mod tests {
97    use super::*;
98
99    fn folder(root: &Path, name: &str) -> PathBuf {
100        let p = root.join(name);
101        std::fs::create_dir_all(&p).unwrap();
102        std::fs::write(p.join("muxlog.mjs"), "x").unwrap();
103        p
104    }
105
106    #[test]
107    fn a_folder_whose_instance_dir_is_gone_is_removed_and_a_live_one_stays() {
108        let tmp = tempfile::tempdir().unwrap();
109        let root = tmp.path().join("shell");
110        let live_dir = tmp.path().join("live-data");
111        std::fs::create_dir_all(&live_dir).unwrap();
112        let live = folder(&root, "aaaaaaaaaaaaaaaa");
113        let dead = folder(&root, "bbbbbbbbbbbbbbbb");
114        let current = folder(&root, "cccccccccccccccc");
115        stamp_instance(&live, &live_dir);
116        stamp_instance(&dead, &tmp.path().join("deleted-data"));
117        let report = prune_stale_integration_dirs(&root, &current, &[]);
118        assert_eq!(report, PruneReport { removed: 1, stamped: 0, unattributed: 0 });
119        assert!(live.exists() && current.exists() && !dead.exists());
120    }
121
122    #[test]
123    fn an_unmarked_folder_is_stamped_when_its_instance_exists_and_left_when_unknown() {
124        let tmp = tempfile::tempdir().unwrap();
125        let root = tmp.path().join("shell");
126        let data = tmp.path().join("inst").join("data");
127        std::fs::create_dir_all(&data).unwrap();
128        let matched = folder(&root, &instance_key(&data));
129        let unknown = folder(&root, "dddddddddddddddd");
130        let current = root.join("eeeeeeeeeeeeeeee");
131        let report = prune_stale_integration_dirs(&root, &current, &[data.clone()]);
132        assert_eq!(report, PruneReport { removed: 0, stamped: 1, unattributed: 1 });
133        assert!(unknown.exists());
134        assert!(std::fs::read_to_string(matched.join(INSTANCE_MARKER)).unwrap().contains("data"));
135        // Once the instance is gone, the stamped folder is stale.
136        std::fs::remove_dir_all(&data).unwrap();
137        let report = prune_stale_integration_dirs(&root, &current, &[]);
138        assert_eq!(report.removed, 1);
139        assert!(!matched.exists() && unknown.exists());
140    }
141
142    #[cfg(unix)]
143    #[test]
144    fn a_data_dir_whose_name_ends_in_whitespace_is_still_found_alive() {
145        let tmp = tempfile::tempdir().unwrap();
146        let root = tmp.path().join("shell");
147        let data = tmp.path().join("data ");
148        std::fs::create_dir_all(&data).unwrap();
149        let live = folder(&root, "aaaaaaaaaaaaaaaa");
150        stamp_instance(&live, &data);
151        let report = prune_stale_integration_dirs(&root, &root.join("cccccccccccccccc"), &[]);
152        assert_eq!(report, PruneReport::default());
153        assert!(live.exists());
154    }
155
156    #[test]
157    fn other_entries_under_the_shell_root_are_never_touched() {
158        let tmp = tempfile::tempdir().unwrap();
159        let root = tmp.path().join("shell");
160        let bash = folder(&root, "bash");
161        let lib = folder(&root, "lib");
162        std::fs::write(root.join(".version"), "v").unwrap();
163        let current = root.join("ffffffffffffffff");
164        let report = prune_stale_integration_dirs(&root, &current, &[]);
165        assert_eq!(report, PruneReport::default());
166        assert!(bash.exists() && lib.exists() && root.join(".version").exists());
167    }
168}