1use anyhow::Result;
2use serde::Serialize;
3use std::collections::{HashMap, HashSet};
4use std::path::{Path, PathBuf};
5
6use super::content_hash;
7use super::skill_metadata;
8use super::skill_store::DiscoveredSkillRecord;
9use super::tool_adapters;
10
11pub struct ScanPlan {
12 pub tools_scanned: usize,
13 pub skills_found: usize,
14 pub discovered: Vec<DiscoveredSkillRecord>,
15}
16
17#[derive(Debug, Clone, Serialize)]
18pub struct DiscoveredGroup {
19 pub name: String,
20 pub fingerprint: Option<String>,
21 pub locations: Vec<DiscoveredLocation>,
22 pub imported: bool,
23 pub found_at: i64,
24}
25
26#[derive(Debug, Clone, Serialize)]
27pub struct DiscoveredLocation {
28 pub id: String,
29 pub tool: String,
30 pub found_path: String,
31 pub is_symlink: bool,
32 pub resolved_path: Option<String>,
33}
34
35const RECURSIVE_SCAN_SKIP_DIRS: &[&str] = &[".hub", ".agent-hub", ".git", "node_modules"];
37
38fn symlink_target(path: &Path) -> Option<String> {
39 if !path.is_symlink() {
40 return None;
41 }
42 std::fs::canonicalize(path)
43 .ok()
44 .map(|target| target.to_string_lossy().into_owned())
45}
46
47pub fn collect_skill_dirs(dir: &Path) -> Vec<PathBuf> {
51 let mut results = Vec::new();
52 let mut visited = HashSet::new();
53 collect_skill_dirs_recursive(dir, &mut visited, &mut results);
54 results
55}
56
57fn collect_skill_dirs_recursive(
58 dir: &Path,
59 visited: &mut HashSet<PathBuf>,
60 results: &mut Vec<PathBuf>,
61) {
62 let canonical = std::fs::canonicalize(dir).unwrap_or_else(|_| dir.to_path_buf());
63 if !visited.insert(canonical) {
64 return;
65 }
66 let entries = match std::fs::read_dir(dir) {
67 Ok(e) => e,
68 Err(_) => return,
69 };
70 for entry in entries.flatten() {
71 let path = entry.path();
72 if !path.is_dir() && !path.is_symlink() {
73 continue;
74 }
75 let dir_name = entry.file_name();
76 let dir_name_str = dir_name.to_string_lossy();
77 if RECURSIVE_SCAN_SKIP_DIRS.iter().any(|s| dir_name_str == *s) {
78 continue;
79 }
80 if skill_metadata::is_valid_skill_dir(&path) {
81 results.push(path);
82 continue;
83 }
84 collect_skill_dirs_recursive(&path, visited, results);
85 }
86}
87
88fn push_discovered(
91 adapter_key: &str,
92 path: PathBuf,
93 managed_paths: &[String],
94 discovered: &mut Vec<DiscoveredSkillRecord>,
95 hash_directory: &mut impl FnMut(&Path) -> Option<String>,
96) {
97 let path_str = path.to_string_lossy().to_string();
98 if managed_paths.contains(&path_str) {
99 return;
100 }
101 let name = skill_metadata::infer_skill_name(&path);
102 let fingerprint = hash_directory(&path);
103 let found_at = std::fs::metadata(&path)
104 .and_then(|m| m.modified())
105 .ok()
106 .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
107 .map(|d| d.as_millis() as i64)
108 .unwrap_or_else(|| chrono::Utc::now().timestamp_millis());
109 discovered.push(DiscoveredSkillRecord {
110 id: uuid::Uuid::new_v4().to_string(),
111 tool: adapter_key.to_string(),
112 found_path: path_str,
113 name_guess: Some(name),
114 fingerprint,
115 found_at,
116 imported_skill_id: None,
117 });
118}
119
120fn scan_flat_dir(
121 adapter_key: &str,
122 scan_dir: &Path,
123 managed_paths: &[String],
124 discovered: &mut Vec<DiscoveredSkillRecord>,
125 hash_directory: &mut impl FnMut(&Path) -> Option<String>,
126) {
127 let entries = match std::fs::read_dir(scan_dir) {
128 Ok(e) => e,
129 Err(_) => return,
130 };
131
132 for entry in entries.flatten() {
133 let path = entry.path();
134 if !path.is_dir() && !path.is_symlink() {
135 continue;
136 }
137 if !skill_metadata::is_valid_skill_dir(&path) {
138 continue;
139 }
140 push_discovered(adapter_key, path, managed_paths, discovered, hash_directory);
141 }
142}
143
144fn scan_recursive_dir(
145 adapter_key: &str,
146 scan_dir: &Path,
147 managed_paths: &[String],
148 discovered: &mut Vec<DiscoveredSkillRecord>,
149 hash_directory: &mut impl FnMut(&Path) -> Option<String>,
150) {
151 let mut skill_dirs = Vec::new();
152 let mut visited = HashSet::new();
153 collect_skill_dirs_recursive(scan_dir, &mut visited, &mut skill_dirs);
154 for path in skill_dirs {
155 push_discovered(adapter_key, path, managed_paths, discovered, hash_directory);
156 }
157}
158
159#[allow(dead_code)]
160pub fn scan_local_skills(managed_paths: &[String]) -> Result<ScanPlan> {
161 scan_local_skills_with_adapters(managed_paths, &tool_adapters::default_tool_adapters())
162}
163
164pub fn scan_local_skills_with_adapters(
165 managed_paths: &[String],
166 adapters: &[tool_adapters::ToolAdapter],
167) -> Result<ScanPlan> {
168 scan_local_skills_with_hasher(managed_paths, adapters, &mut |path| {
169 content_hash::hash_directory(path).ok()
170 })
171}
172
173fn scan_local_skills_with_hasher(
174 managed_paths: &[String],
175 adapters: &[tool_adapters::ToolAdapter],
176 hash_directory: &mut impl FnMut(&Path) -> Option<String>,
177) -> Result<ScanPlan> {
178 let mut discovered = Vec::new();
179 let mut tools_scanned = 0;
180 let mut fingerprints = HashMap::new();
184 let mut cached_hasher = |path: &Path| {
185 let canonical = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
186 fingerprints
187 .entry(canonical)
188 .or_insert_with(|| hash_directory(path))
189 .clone()
190 };
191
192 for adapter in adapters {
193 let primary_scan_dir = adapter.skills_dir();
194 let primary_exists = primary_scan_dir.is_dir();
195 let additional_dirs = adapter.additional_existing_scan_dirs();
196
197 if !primary_exists && additional_dirs.is_empty() {
202 continue;
203 }
204
205 tools_scanned += 1;
206
207 if primary_exists {
210 if adapter.recursive_scan {
211 scan_recursive_dir(
212 &adapter.key,
213 &primary_scan_dir,
214 managed_paths,
215 &mut discovered,
216 &mut cached_hasher,
217 );
218 } else {
219 scan_flat_dir(
220 &adapter.key,
221 &primary_scan_dir,
222 managed_paths,
223 &mut discovered,
224 &mut cached_hasher,
225 );
226 }
227 }
228
229 for scan_dir in additional_dirs {
231 scan_flat_dir(
232 &adapter.key,
233 &scan_dir,
234 managed_paths,
235 &mut discovered,
236 &mut cached_hasher,
237 );
238 }
239 }
240
241 let skills_found = discovered.len();
242 Ok(ScanPlan {
243 tools_scanned,
244 skills_found,
245 discovered,
246 })
247}
248
249pub fn group_discovered(records: &[DiscoveredSkillRecord]) -> Vec<DiscoveredGroup> {
250 group_discovered_with_preferred_root(records, &tool_adapters::shared_skills_dir())
251}
252
253fn group_discovered_with_preferred_root(
254 records: &[DiscoveredSkillRecord],
255 preferred_root: &Path,
256) -> Vec<DiscoveredGroup> {
257 use std::collections::HashMap;
258 let mut groups: HashMap<String, DiscoveredGroup> = HashMap::new();
259
260 for rec in records {
261 let name = rec.name_guess.clone().unwrap_or_else(|| "unknown".into());
262 let group_key = if let Some(fingerprint) = rec.fingerprint.as_deref() {
263 format!("fp:{name}:{fingerprint}")
264 } else {
265 format!("path:{name}:{}", rec.found_path)
266 };
267 let entry = groups.entry(group_key).or_insert_with(|| DiscoveredGroup {
268 name,
269 fingerprint: rec.fingerprint.clone(),
270 locations: Vec::new(),
271 imported: false,
272 found_at: rec.found_at,
273 });
274
275 if rec.imported_skill_id.is_some() {
276 entry.imported = true;
277 }
278
279 if rec.found_at < entry.found_at {
281 entry.found_at = rec.found_at;
282 }
283
284 entry.locations.push(DiscoveredLocation {
285 id: rec.id.clone(),
286 tool: rec.tool.clone(),
287 found_path: rec.found_path.clone(),
288 is_symlink: Path::new(&rec.found_path).is_symlink(),
289 resolved_path: symlink_target(Path::new(&rec.found_path)),
290 });
291 }
292
293 let mut result: Vec<_> = groups.into_values().collect();
294 for group in &mut result {
295 group
298 .locations
299 .sort_by_key(|location| !Path::new(&location.found_path).starts_with(preferred_root));
300 }
301 result.sort_by(|a, b| a.name.cmp(&b.name));
302 result
303}
304
305#[cfg(test)]
306mod tests;