Skip to main content

agent_hub_runtime/commands/
local_cleanup.rs

1//! Reviewable cleanup of scanned Skills belonging to configured Agents.
2use super::discovered_skills::{delete_location, symlink_resolves_into_library, validate_location};
3use crate::core::{
4    central_repo,
5    error::AppError,
6    skill_store::SkillStore,
7    sync_metadata,
8    tool_adapters::{self, ToolAdapter},
9};
10use serde::Serialize;
11use std::{
12    collections::{HashMap, HashSet},
13    path::{Path, PathBuf},
14    sync::Arc,
15};
16use tauri::State;
17
18#[derive(Clone, Serialize)]
19pub struct CleanupLocation {
20    pub id: String,
21    pub tool: String,
22    pub path: String,
23    pub empty_root: bool,
24}
25#[derive(Serialize)]
26pub struct CleanupFailure {
27    pub path: String,
28    pub reason: String,
29}
30#[derive(Default, Serialize)]
31pub struct CleanupResult {
32    pub removed: usize,
33    pub failures: Vec<CleanupFailure>,
34}
35
36fn overlaps(a: &Path, b: &Path) -> bool {
37    a.starts_with(b)
38        || b.starts_with(a)
39        || std::fs::canonicalize(a)
40            .ok()
41            .zip(std::fs::canonicalize(b).ok())
42            .is_some_and(|(a, b)| a.starts_with(&b) || b.starts_with(&a))
43}
44
45fn roots(
46    adapters: &[ToolAdapter],
47    installed: &HashSet<String>,
48    library: &Path,
49    include_installed: bool,
50) -> HashMap<String, PathBuf> {
51    let mut protected = vec![library.to_path_buf()];
52    for adapter in adapters {
53        if adapter.is_custom
54            || adapter.has_path_override()
55            || (!include_installed && installed.contains(&adapter.key))
56        {
57            protected.extend(adapter.all_scan_dirs());
58        }
59    }
60    adapters
61        .iter()
62        .filter(|adapter| {
63            (include_installed || !installed.contains(&adapter.key))
64                && !adapter.is_custom
65                && !adapter.has_path_override()
66        })
67        .filter_map(|adapter| {
68            let root = adapter.skills_dir();
69            // Additional discovery roots are shared collections, not leftovers
70            // owned by this Agent. Never clean those through this operation.
71            (root.is_dir()
72                && !root.is_symlink()
73                && !root.parent().is_some_and(|parent| parent.is_symlink())
74                && !protected.iter().any(|path| overlaps(&root, path)))
75            .then(|| (adapter.key.clone(), root))
76        })
77        .collect()
78}
79
80pub fn preview_for_cli(
81    store: &SkillStore,
82    include_installed: bool,
83) -> Result<Vec<CleanupLocation>, AppError> {
84    let adapters = tool_adapters::all_tool_adapters(store);
85    plan(store, &adapters, &installed(&adapters), include_installed)
86}
87
88pub fn cleanup_for_cli(
89    store: &SkillStore,
90    selected: &[String],
91    include_installed: bool,
92) -> Result<CleanupResult, AppError> {
93    sync_metadata::with_repo_lock("clean local Agent Skills", || {
94        let adapters = tool_adapters::all_tool_adapters(store);
95        Ok(execute(
96            store,
97            selected,
98            &adapters,
99            &installed(&adapters),
100            include_installed,
101        )?)
102    })
103    .map_err(AppError::io)
104}
105
106fn empty_tree(path: &Path) -> bool {
107    !path.is_symlink()
108        && std::fs::read_dir(path).is_ok_and(|mut entries| {
109            entries.all(|entry| {
110                entry.is_ok_and(|entry| {
111                    entry.file_type().is_ok_and(|kind| kind.is_dir()) && empty_tree(&entry.path())
112                })
113            })
114        })
115}
116
117fn prune_empty(path: &Path) {
118    if path.is_symlink() {
119        return;
120    }
121    if let Ok(entries) = std::fs::read_dir(path) {
122        for entry in entries.flatten() {
123            if entry.file_type().is_ok_and(|kind| kind.is_dir()) {
124                prune_empty(&entry.path());
125            }
126        }
127        let _ = std::fs::remove_dir(path); // Only empty directories can be removed.
128    }
129}
130
131fn plan(
132    store: &SkillStore,
133    adapters: &[ToolAdapter],
134    installed: &HashSet<String>,
135    include_installed: bool,
136) -> Result<Vec<CleanupLocation>, AppError> {
137    let roots = roots(
138        adapters,
139        installed,
140        &central_repo::skills_dir(),
141        include_installed,
142    );
143    let targets = store.get_all_targets().map_err(AppError::db)?;
144    let mut result = Vec::new();
145    let mut seen = HashSet::new();
146    for record in store.get_all_discovered().map_err(AppError::db)? {
147        let Some(root) = roots.get(&record.tool) else {
148            continue;
149        };
150        let path = Path::new(&record.found_path);
151        if !path.exists()
152            || record.fingerprint.is_none()
153            || validate_location(path, std::slice::from_ref(root)).is_err()
154            || targets.iter().any(|target| {
155                let target_path = Path::new(&target.target_path);
156                let matched = if path.is_symlink() {
157                    path == target_path
158                } else {
159                    overlaps(path, target_path)
160                };
161                matched && !symlink_resolves_into_library(path)
162            })
163        {
164            continue;
165        }
166        // Lexical dedup: distinct symlinks to one target must each be unlinked.
167        if seen.insert((path.to_path_buf(), record.tool.clone())) {
168            result.push(CleanupLocation {
169                id: record.id,
170                tool: record.tool,
171                path: record.found_path,
172                empty_root: false,
173            });
174        }
175    }
176    for (tool, root) in roots {
177        if empty_tree(&root) && seen.insert((root.clone(), tool.clone())) {
178            let path = root.to_string_lossy().into_owned();
179            result.push(CleanupLocation {
180                id: format!("empty:{tool}:{path}"),
181                tool,
182                path,
183                empty_root: true,
184            });
185        }
186    }
187    result.sort_by(|a, b| a.path.cmp(&b.path));
188    Ok(result)
189}
190
191fn installed(adapters: &[ToolAdapter]) -> HashSet<String> {
192    adapters
193        .iter()
194        .filter(|adapter| adapter.is_installed())
195        .map(|adapter| adapter.key.clone())
196        .collect()
197}
198
199#[tauri::command]
200pub async fn get_local_cleanup_plan(
201    store: State<'_, Arc<SkillStore>>,
202    include_installed: Option<bool>,
203) -> Result<Vec<CleanupLocation>, AppError> {
204    let store = store.inner().clone();
205    // The desktop one-click action cleans all detected Agent roots by default.
206    // Keep the argument optional for older callers, while making installed
207    // Agents eligible instead of silently reporting an empty result.
208    let include_installed = include_installed.unwrap_or(true);
209    tauri::async_runtime::spawn_blocking(move || {
210        let adapters = tool_adapters::all_tool_adapters(&store);
211        plan(&store, &adapters, &installed(&adapters), include_installed)
212    })
213    .await?
214}
215
216fn execute(
217    store: &SkillStore,
218    selected: &[String],
219    adapters: &[ToolAdapter],
220    installed: &HashSet<String>,
221    include_installed: bool,
222) -> Result<CleanupResult, AppError> {
223    // Reuse the scanned records instead of re-reading the whole scan table for
224    // every selected item. The plan already checked the primary root boundary.
225    let records: HashMap<_, _> = store
226        .get_all_discovered()
227        .map_err(AppError::db)?
228        .into_iter()
229        .map(|record| (record.id.clone(), record))
230        .collect();
231    let current: HashMap<_, _> = plan(store, adapters, installed, include_installed)?
232        .into_iter()
233        .map(|entry| (entry.id.clone(), entry))
234        .collect();
235    let roots = roots(
236        adapters,
237        installed,
238        &central_repo::skills_dir(),
239        include_installed,
240    );
241    let mut result = CleanupResult::default();
242    let mut seen = HashSet::new();
243    let mut removed_paths = HashSet::new();
244    for id in selected {
245        if !seen.insert(id) {
246            continue;
247        }
248        let Some(entry) = current.get(id) else {
249            result.failures.push(CleanupFailure {
250                path: id.clone(),
251                reason: "Installation or path changed; preview cleanup again".into(),
252            });
253            continue;
254        };
255        if removed_paths.contains(&entry.path) {
256            continue;
257        }
258        let outcome = if entry.empty_root {
259            if empty_tree(Path::new(&entry.path)) {
260                prune_empty(Path::new(&entry.path));
261            }
262            if Path::new(&entry.path).exists() {
263                Err(AppError::invalid_input("Directory is no longer empty"))
264            } else {
265                Ok(())
266            }
267        } else {
268            records
269                .get(id)
270                .ok_or_else(|| AppError::not_found("Scan changed; preview again"))
271                .and_then(|record| delete_location(store, record))
272        };
273        match outcome {
274            Ok(()) => {
275                removed_paths.insert(entry.path.clone());
276                result.removed += 1;
277                if let Some(root) = roots.get(&entry.tool) {
278                    prune_empty(root);
279                }
280            }
281            Err(error) => result.failures.push(CleanupFailure {
282                path: entry.path.clone(),
283                reason: error.to_string(),
284            }),
285        }
286    }
287    if result.removed > 0 {
288        if let Err(error) = sync_metadata::write_all_from_db_unlocked(store) {
289            result.failures.push(CleanupFailure {
290                path: "library metadata".into(),
291                reason: error.to_string(),
292            });
293        }
294    }
295    Ok(result)
296}
297
298#[tauri::command]
299pub async fn cleanup_uninstalled_agent_skills(
300    store: State<'_, Arc<SkillStore>>,
301    location_ids: Vec<String>,
302    include_installed: Option<bool>,
303) -> Result<CleanupResult, AppError> {
304    let store = store.inner().clone();
305    let include_installed = include_installed.unwrap_or(true);
306    tauri::async_runtime::spawn_blocking(move || {
307        sync_metadata::with_repo_lock("clean local Agent Skills", || {
308            // Fresh installation snapshot after the user confirmed the preview.
309            let adapters = tool_adapters::all_tool_adapters(&store);
310            Ok(execute(
311                &store,
312                &location_ids,
313                &adapters,
314                &installed(&adapters),
315                include_installed,
316            )?)
317        })
318        .map_err(AppError::io)
319    })
320    .await?
321}
322
323#[cfg(test)]
324mod tests;