Skip to main content

agent_hub_runtime/core/
project_scanner.rs

1use serde::Serialize;
2use std::path::{Path, PathBuf};
3
4use super::{content_hash, skill_metadata};
5
6/// Join a base path with a forward-slash relative string, splitting each `/`
7/// component so `PathBuf::join` emits the platform separator on every segment.
8fn portable_join(base: &Path, relative: &str) -> PathBuf {
9    relative
10        .split('/')
11        .fold(base.to_path_buf(), |acc, part| acc.join(part))
12}
13
14/// Lightweight config describing where an agent keeps project-level skills.
15#[derive(Debug, Clone)]
16pub struct AgentSkillConfig {
17    pub key: String,
18    pub display_name: String,
19    /// Relative path from project root to the skills directory (e.g. ".claude/skills").
20    pub relative_skills_dir: String,
21}
22
23#[derive(Debug, Clone, Serialize)]
24pub struct ProjectSkillInfo {
25    pub name: String,
26    pub dir_name: String,
27    #[serde(default)]
28    pub relative_path: String,
29    pub description: Option<String>,
30    pub path: String,
31    pub files: Vec<String>,
32    pub enabled: bool,
33    /// Agent key that owns this skill (e.g. "claude_code", "cursor").
34    #[serde(default)]
35    pub agent: String,
36    /// Human-readable agent name (e.g. "Claude Code", "Cursor").
37    #[serde(default)]
38    pub agent_display_name: String,
39    #[serde(default)]
40    pub tags: Vec<String>,
41    #[serde(default)]
42    pub in_center: bool,
43    #[serde(default)]
44    pub sync_status: String,
45    #[serde(default)]
46    pub center_skill_id: Option<String>,
47    #[serde(skip_serializing)]
48    pub last_modified_at: Option<i64>,
49    #[serde(skip_serializing)]
50    pub content_hash: Option<String>,
51}
52
53/// Read skills from all configured agents' project-level skill directories.
54pub fn read_project_skills(
55    project_path: &Path,
56    agent_configs: &[AgentSkillConfig],
57) -> Vec<ProjectSkillInfo> {
58    let mut skills = Vec::new();
59
60    for config in agent_configs {
61        let skills_dir = portable_join(project_path, &config.relative_skills_dir);
62        let disabled_dir = portable_join(
63            project_path,
64            &format!("{}-disabled", config.relative_skills_dir),
65        );
66
67        read_skills_from_dir(
68            &skills_dir,
69            true,
70            &config.key,
71            &config.display_name,
72            &mut skills,
73            true,
74        );
75        read_skills_from_dir(
76            &disabled_dir,
77            false,
78            &config.key,
79            &config.display_name,
80            &mut skills,
81            true,
82        );
83    }
84
85    skills.sort_by_key(|a| a.name.to_lowercase());
86    skills
87}
88
89pub fn read_linked_workspace_skills(
90    skills_root: &Path,
91    disabled_root: Option<&Path>,
92    agent_key: &str,
93    agent_display_name: &str,
94    recursive: bool,
95) -> Vec<ProjectSkillInfo> {
96    let mut skills = Vec::new();
97    read_skills_from_dir(
98        skills_root,
99        true,
100        agent_key,
101        agent_display_name,
102        &mut skills,
103        recursive,
104    );
105    if let Some(disabled_root) = disabled_root {
106        read_skills_from_dir(
107            disabled_root,
108            false,
109            agent_key,
110            agent_display_name,
111            &mut skills,
112            recursive,
113        );
114    }
115    skills.sort_by_key(|a| a.name.to_lowercase());
116    skills
117}
118
119fn should_skip_dir(root: &Path, dir: &Path) -> bool {
120    let name = dir.file_name().and_then(|n| n.to_str()).unwrap_or("");
121    if name.starts_with('.') {
122        return true;
123    }
124
125    // Ignore embedded plugin/cache bundle layouts such as:
126    // <bundle>/<version>/skills/<skill>/SKILL.md
127    // The workspace root itself may be named "skills", so only skip nested
128    // container directories that introduce another "skills" subtree.
129    dir != root && dir.join("skills").is_dir()
130}
131
132fn read_skills_from_dir(
133    dir: &Path,
134    enabled: bool,
135    agent: &str,
136    agent_display_name: &str,
137    skills: &mut Vec<ProjectSkillInfo>,
138    recursive: bool,
139) {
140    if !dir.is_dir() {
141        return;
142    }
143    let mut visited = std::collections::HashSet::new();
144    if let Ok(canon) = std::fs::canonicalize(dir) {
145        visited.insert(canon);
146    }
147    read_skills_from_dir_recursive(
148        dir,
149        dir,
150        enabled,
151        agent,
152        agent_display_name,
153        skills,
154        &mut visited,
155        recursive,
156    );
157}
158
159// Recursive scanner passes immutable traversal context alongside its output buffer.
160#[allow(clippy::too_many_arguments)]
161fn read_skills_from_dir_recursive(
162    root: &Path,
163    current: &Path,
164    enabled: bool,
165    agent: &str,
166    agent_display_name: &str,
167    skills: &mut Vec<ProjectSkillInfo>,
168    visited: &mut std::collections::HashSet<PathBuf>,
169    recursive: bool,
170) {
171    let Ok(entries) = std::fs::read_dir(current) else {
172        return;
173    };
174
175    for entry in entries.filter_map(|e| e.ok()) {
176        let path = entry.path();
177        if !path.is_dir() {
178            continue;
179        }
180
181        if skill_metadata::is_valid_skill_dir(&path) {
182            let dir_name = path
183                .file_name()
184                .map(|n| n.to_string_lossy().to_string())
185                .unwrap_or_else(|| "unknown".to_string());
186            let relative_path = path
187                .strip_prefix(root)
188                .unwrap_or(&path)
189                .to_string_lossy()
190                .replace('\\', "/");
191
192            let meta = skill_metadata::parse_skill_md(&path);
193            let name = meta
194                .name
195                .filter(|n| !n.is_empty())
196                .unwrap_or_else(|| dir_name.clone());
197
198            let files = list_files(&path);
199
200            // One recursive walk feeds both the content hash and the
201            // last-modified time (#248). Previously this ran three separate
202            // walks per skill: `hash_directory`, plus `latest_modified_millis`
203            // which called `canonicalize()` on every node, so the workspace
204            // scan cost scaled at ~3× the necessary syscalls per skill.
205            let content_entries = content_hash::list_content_files(&path);
206            let content_hash = Some(content_hash::hash_entries(&content_entries));
207            let last_modified_at = content_hash::latest_modified_ms(&content_entries);
208
209            skills.push(ProjectSkillInfo {
210                name,
211                dir_name: dir_name.clone(),
212                relative_path,
213                description: meta.description,
214                path: path.to_string_lossy().to_string(),
215                files,
216                enabled,
217                agent: agent.to_string(),
218                agent_display_name: agent_display_name.to_string(),
219                tags: Vec::new(),
220                in_center: false,
221                sync_status: "project_only".to_string(),
222                center_skill_id: None,
223                last_modified_at,
224                content_hash,
225            });
226            continue;
227        }
228
229        // Only check visited set before recursing into namespace dirs
230        // to prevent symlink cycles. Skill dirs (above) are leaf nodes and
231        // are allowed to alias the same canonical target.
232
233        if !recursive || should_skip_dir(root, &path) {
234            continue;
235        }
236
237        let canon = match std::fs::canonicalize(&path) {
238            Ok(c) => c,
239            Err(_) => continue,
240        };
241        if !visited.insert(canon) {
242            continue;
243        }
244        read_skills_from_dir_recursive(
245            root,
246            &path,
247            enabled,
248            agent,
249            agent_display_name,
250            skills,
251            visited,
252            recursive,
253        );
254    }
255}
256
257/// Scan a root directory for projects containing any agent's skills directory.
258pub fn scan_projects_in_dir(
259    root: &Path,
260    max_depth: usize,
261    agent_configs: &[AgentSkillConfig],
262) -> Vec<String> {
263    let mut results = Vec::new();
264    scan_recursive(root, 0, max_depth, agent_configs, &mut results);
265    results.sort();
266    results
267}
268
269fn has_any_agent_skills(dir: &Path, agent_configs: &[AgentSkillConfig]) -> bool {
270    agent_configs
271        .iter()
272        .any(|config| dir.join(&config.relative_skills_dir).is_dir())
273}
274
275fn scan_recursive(
276    dir: &Path,
277    depth: usize,
278    max_depth: usize,
279    agent_configs: &[AgentSkillConfig],
280    results: &mut Vec<String>,
281) {
282    if depth > max_depth {
283        return;
284    }
285
286    if has_any_agent_skills(dir, agent_configs) {
287        results.push(dir.to_string_lossy().to_string());
288        return; // don't recurse into subdirectories of a matched project
289    }
290
291    if depth == max_depth {
292        return;
293    }
294
295    if let Ok(entries) = std::fs::read_dir(dir) {
296        for entry in entries.filter_map(|e| e.ok()) {
297            let path = entry.path();
298            if !path.is_dir() {
299                continue;
300            }
301            // Skip hidden directories and common non-project dirs
302            let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
303            if name.starts_with('.')
304                || name == "node_modules"
305                || name == "target"
306                || name == "__pycache__"
307            {
308                continue;
309            }
310            scan_recursive(&path, depth + 1, max_depth, agent_configs, results);
311        }
312    }
313}
314
315fn list_files(dir: &Path) -> Vec<String> {
316    let mut files = Vec::new();
317    if let Ok(entries) = std::fs::read_dir(dir) {
318        for entry in entries.filter_map(|e| e.ok()) {
319            let path = entry.path();
320            if path.is_file() {
321                if let Some(name) = path.file_name() {
322                    files.push(name.to_string_lossy().to_string());
323                }
324            }
325        }
326    }
327    files.sort();
328    files
329}
330
331#[cfg(test)]
332mod tests;