Skip to main content

vtcode_skills/
locations.rs

1//! Skill Location Management
2//!
3//! Implements skill discovery across multiple locations with proper precedence,
4//! following the pi-mono pattern for compatibility with Claude Code and Codex CLI.
5
6use crate::manifest::parse_skill_file;
7use crate::types::SkillContext;
8use anyhow::Result;
9use hashbrown::HashMap;
10use std::path::{Path, PathBuf};
11use tracing::{debug, info, warn};
12use vtcode_commons::VtCodePaths;
13use vtcode_commons::walk::entry_is_dir;
14
15/// Maximum recursion depth when walking a skill location.
16///
17/// The Agent Skills client guide recommends 4-6 levels; kept at 10 for backward
18/// compatibility with deeply nested plugin layouts. Dependency and build-output
19/// trees are excluded separately via [`SKIPPED_DISCOVERY_DIRS`].
20pub const MAX_DISCOVERY_DEPTH: usize = 10;
21
22/// Maximum directories visited per discovery walk.
23///
24/// Bounds runaway scans of huge trees (monorepos, home directories) per the
25/// Agent Skills client guide's directory budget.
26pub const MAX_DISCOVERY_DIRS: usize = 2000;
27
28/// Directory names never descended into during skill discovery.
29///
30/// Build output, VCS metadata, and dependency trees cannot contain skills and
31/// dominate scan time in large repos (notably `node_modules`).
32pub const SKIPPED_DISCOVERY_DIRS: &[&str] = &[".git", ".hg", ".svn", "node_modules", "target"];
33
34/// Whether a directory name is skipped during skill discovery.
35pub fn discovery_dir_skipped(file_name: &str) -> bool {
36    SKIPPED_DISCOVERY_DIRS.contains(&file_name)
37}
38
39/// Skill location types with precedence ordering
40#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
41pub enum SkillLocationType {
42    /// VT Code user skills (highest precedence)
43    VtcodeUser = 7,
44    /// Project-level agent skills
45    AgentsProject = 6,
46    /// VT Code project skills
47    VtcodeProject = 5,
48    /// Pi user skills
49    PiUser = 4,
50    /// Pi project skills
51    PiProject = 3,
52    /// Claude Code user skills
53    ClaudeUser = 2,
54    /// Claude Code project skills
55    ClaudeProject = 1,
56    /// Codex CLI user skills (lowest precedence)
57    CodexUser = 0,
58}
59
60impl SkillLocationType {}
61
62/// Skill location configuration
63#[derive(Debug, Clone)]
64pub struct SkillLocation {
65    /// Location type for precedence
66    location_type: SkillLocationType,
67
68    /// Base directory path
69    base_path: PathBuf,
70
71    /// Scanning mode (recursive vs one-level)
72    recursive: bool,
73
74    /// Skill name separator for recursive mode
75    name_separator: char,
76}
77
78impl SkillLocation {
79    /// Create new skill location
80    fn new(location_type: SkillLocationType, base_path: PathBuf, recursive: bool) -> Self {
81        let name_separator = match location_type {
82            SkillLocationType::PiUser | SkillLocationType::PiProject => ':',
83            _ => '/', // Default to path separator
84        };
85
86        Self {
87            location_type,
88            base_path,
89            recursive,
90            name_separator,
91        }
92    }
93
94    /// Check if this location exists as a directory.
95    ///
96    /// `is_dir()` already resolves the path, so pairing it with `exists()`
97    /// only added a second stat for the same answer.
98    fn exists(&self) -> bool {
99        self.base_path.is_dir()
100    }
101
102    /// Get the skill name for a directory that the caller already proved is one.
103    ///
104    /// Callers obtain that fact from `readdir` or a single `is_dir()`, so this
105    /// deliberately does not re-resolve the path; only the `SKILL.md` probe is
106    /// a real filesystem question.
107    fn get_skill_name(&self, skill_path: &Path) -> Option<String> {
108        // Check if this path contains a SKILL.md file
109        let skill_md = skill_path.join("SKILL.md");
110        if !skill_md.is_file() {
111            return None;
112        }
113
114        if self.recursive {
115            if matches!(self.location_type, SkillLocationType::ClaudeUser | SkillLocationType::ClaudeProject) {
116                return skill_path.file_name().and_then(|name| name.to_str()).map(|s| s.to_string());
117            }
118            // For recursive locations, build name with separators
119            match skill_path.strip_prefix(&self.base_path) {
120                Ok(relative_path) => {
121                    let name_components: Vec<&str> =
122                        relative_path.components().filter_map(|c| c.as_os_str().to_str()).collect();
123
124                    if name_components.is_empty() {
125                        None
126                    } else {
127                        Some(name_components.join(&self.name_separator.to_string()))
128                    }
129                }
130                Err(_) => None,
131            }
132        } else {
133            // For one-level locations, just use the immediate directory name
134            skill_path.file_name().and_then(|name| name.to_str()).map(|s| s.to_string())
135        }
136    }
137}
138
139/// Skill locations manager
140pub struct SkillLocations {
141    locations: Vec<SkillLocation>,
142}
143
144impl SkillLocations {
145    /// Create new skill locations manager with default locations
146    fn new() -> Self {
147        Self::with_locations(Self::default_locations())
148    }
149
150    /// Create with custom locations
151    fn with_locations(locations: Vec<SkillLocation>) -> Self {
152        // Sort by precedence (highest first)
153        let mut sorted_locations = locations;
154        sorted_locations.sort_by_key(|loc| std::cmp::Reverse(loc.location_type));
155
156        Self { locations: sorted_locations }
157    }
158
159    /// Get default skill locations following pi-mono pattern
160    fn default_locations() -> Vec<SkillLocation> {
161        let mut locations = Vec::new();
162        if let Ok(paths) = VtCodePaths::resolve() {
163            // VT Code locations (highest precedence). If the global path
164            // policy is unavailable, omit this optional user location rather
165            // than creating or scanning state relative to the cwd.
166            locations.push(SkillLocation::new(
167                SkillLocationType::VtcodeUser,
168                paths.skills_dir(),
169                true, // recursive
170            ));
171        }
172        locations.extend([
173            SkillLocation::new(
174                SkillLocationType::AgentsProject,
175                PathBuf::from(".agents/skills"),
176                true, // recursive
177            ),
178            SkillLocation::new(
179                SkillLocationType::VtcodeProject,
180                PathBuf::from(".vtcode/skills"),
181                true, // recursive
182            ),
183            // Pi locations (recursive with colon separator)
184            SkillLocation::new(
185                SkillLocationType::PiUser,
186                PathBuf::from("~/.pi/agent/skills"),
187                true, // recursive
188            ),
189            SkillLocation::new(
190                SkillLocationType::PiProject,
191                PathBuf::from(".pi/skills"),
192                true, // recursive
193            ),
194            // Claude Code locations (one-level only)
195            SkillLocation::new(
196                SkillLocationType::ClaudeUser,
197                PathBuf::from("~/.claude/skills"),
198                true, // recursive
199            ),
200            SkillLocation::new(
201                SkillLocationType::ClaudeProject,
202                PathBuf::from(".claude/skills"),
203                true, // recursive
204            ),
205            // Codex CLI locations (recursive)
206            SkillLocation::new(
207                SkillLocationType::CodexUser,
208                PathBuf::from("~/.codex/skills"),
209                true, // recursive
210            ),
211        ]);
212        locations
213    }
214
215    /// Discover all skills across all locations
216    fn discover_skills(&self) -> Result<Vec<DiscoveredSkill>> {
217        let mut discovered_skills = HashMap::new(); // skill_name -> (location_type, skill_context)
218        let mut discovery_stats = DiscoveryStats::default();
219
220        info!("Discovering skills across {} locations", self.locations.len());
221
222        for location in &self.locations {
223            if !location.exists() {
224                debug!("Location does not exist: {}", location.base_path.display());
225                continue;
226            }
227
228            info!(
229                "Scanning location: {} ({})",
230                location.base_path.display(),
231                if location.recursive { "recursive" } else { "one-level" }
232            );
233
234            discovery_stats.locations_scanned += 1;
235
236            if location.recursive {
237                self.scan_recursive_location(location, &mut discovered_skills, &mut discovery_stats)?;
238            } else {
239                self.scan_one_level_location(location, &mut discovered_skills, &mut discovery_stats)?;
240            }
241        }
242
243        info!(
244            "Discovery complete: {} skills found ({} from higher precedence locations)",
245            discovered_skills.len(),
246            discovery_stats.skills_with_higher_precedence
247        );
248
249        // Convert to final result
250        let mut final_skills: Vec<DiscoveredSkill> = discovered_skills.into_values().collect();
251
252        // Sort by location precedence (highest first) and then by name
253        final_skills.sort_by(|a, b| match a.location_type.cmp(&b.location_type) {
254            std::cmp::Ordering::Equal => a.skill_context.manifest().name.cmp(&b.skill_context.manifest().name),
255            other => other.reverse(),
256        });
257
258        Ok(final_skills)
259    }
260
261    /// Scan recursive location (Pi/Codex style)
262    fn scan_recursive_location(
263        &self,
264        location: &SkillLocation,
265        discovered: &mut HashMap<String, DiscoveredSkill>,
266        stats: &mut DiscoveryStats,
267    ) -> Result<()> {
268        walk_directory(&location.base_path, location, discovered, stats, 0)
269    }
270}
271
272/// Walk directory recursively
273fn walk_directory(
274    dir: &Path,
275    location: &SkillLocation,
276    discovered: &mut HashMap<String, DiscoveredSkill>,
277    stats: &mut DiscoveryStats,
278    depth: usize,
279) -> Result<()> {
280    if depth > MAX_DISCOVERY_DEPTH {
281        // Prevent infinite recursion
282        return Ok(());
283    }
284
285    if !dir.is_dir() {
286        return Ok(());
287    }
288
289    stats.dirs_visited += 1;
290    if stats.dirs_visited > MAX_DISCOVERY_DIRS {
291        debug!("skill discovery dir budget ({MAX_DISCOVERY_DIRS}) exhausted under {}", location.base_path.display());
292        return Ok(());
293    }
294
295    // Check if this directory is a skill
296    if let Some(skill_name) = location.get_skill_name(dir) {
297        match parse_skill_file(dir) {
298            Ok((manifest, _)) => {
299                // Check if we already have this skill from a higher precedence location
300                let existing_entry = discovered.get(&manifest.name);
301                let had_existing = existing_entry.is_some();
302
303                if let Some(existing) = existing_entry.filter(|e| e.location_type > location.location_type) {
304                    // Existing skill has higher precedence, skip this one
305                    stats.skips_due_to_precedence += 1;
306                    debug!(
307                        "Skipping skill '{}' from {} (already exists from higher precedence {})",
308                        manifest.name, location.location_type, existing.location_type
309                    );
310                    return Ok(());
311                }
312
313                // Add or update the skill
314                let discovered_skill = DiscoveredSkill {
315                    location_type: location.location_type,
316                    skill_context: SkillContext::MetadataOnly(manifest.clone(), dir.to_path_buf()),
317                    skill_path: dir.to_path_buf(),
318                    skill_name: skill_name.clone(),
319                };
320
321                discovered.insert(manifest.name.clone(), discovered_skill);
322                stats.skills_found += 1;
323                info!("Discovered skill: '{}' from {} at {}", manifest.name, location.location_type, dir.display());
324
325                if had_existing {
326                    stats.skills_with_higher_precedence += 1;
327                }
328            }
329            Err(e) => {
330                warn!("Failed to parse skill from {}: {}", dir.display(), e);
331                stats.parse_errors += 1;
332            }
333        }
334    }
335
336    // Continue walking subdirectories, skipping dependency, build-output,
337    // and VCS trees that cannot contain skills.
338    if let Ok(entries) = std::fs::read_dir(dir) {
339        for entry in entries.flatten() {
340            // Skip the name filter before touching the filesystem: a skipped
341            // tree (`node_modules`, `target`) never needs its type resolved.
342            if entry.file_name().to_str().is_some_and(discovery_dir_skipped) {
343                continue;
344            }
345            if !entry_is_dir(&entry) {
346                continue;
347            }
348            walk_directory(&entry.path(), location, discovered, stats, depth + 1)?;
349        }
350    }
351
352    Ok(())
353}
354
355impl SkillLocations {
356    /// Scan one-level location (Claude style)
357    fn scan_one_level_location(
358        &self,
359        location: &SkillLocation,
360        discovered: &mut HashMap<String, DiscoveredSkill>,
361        stats: &mut DiscoveryStats,
362    ) -> Result<()> {
363        if !location.base_path.is_dir() {
364            return Ok(());
365        }
366
367        for entry in std::fs::read_dir(&location.base_path)? {
368            let entry = entry?;
369            // The dirent type settles directory-ness without a second stat;
370            // `get_skill_name` relies on this proof instead of re-resolving.
371            if !entry_is_dir(&entry) {
372                continue;
373            }
374            let path = entry.path();
375
376            if let Some(skill_name) = location.get_skill_name(&path) {
377                match parse_skill_file(&path) {
378                    Ok((manifest, _)) => {
379                        // Check precedence
380                        if let Some(_existing) = discovered
381                            .get(&manifest.name)
382                            .filter(|e| e.location_type > location.location_type)
383                        {
384                            stats.skips_due_to_precedence += 1;
385                            continue;
386                        }
387
388                        let discovered_skill = DiscoveredSkill {
389                            location_type: location.location_type,
390                            skill_context: SkillContext::MetadataOnly(manifest.clone(), path.clone()),
391                            skill_path: path.clone(),
392                            skill_name: skill_name.clone(),
393                        };
394
395                        discovered.insert(manifest.name.clone(), discovered_skill);
396                        stats.skills_found += 1;
397                        info!(
398                            "Discovered skill: '{}' from {} at {}",
399                            manifest.name,
400                            location.location_type,
401                            path.display()
402                        );
403                    }
404                    Err(e) => {
405                        warn!("Failed to parse skill from {}: {}", path.display(), e);
406                        stats.parse_errors += 1;
407                    }
408                }
409            }
410        }
411
412        Ok(())
413    }
414
415    /// Get all location types in precedence order
416    pub fn get_location_types(&self) -> Vec<SkillLocationType> {
417        self.locations.iter().map(|loc| loc.location_type).collect()
418    }
419
420    /// Get location by type
421    pub fn get_location(&self, location_type: SkillLocationType) -> Option<&SkillLocation> {
422        self.locations.iter().find(|loc| loc.location_type == location_type)
423    }
424}
425
426/// Discovered skill with location information
427#[derive(Debug, Clone)]
428pub struct DiscoveredSkill {
429    /// Location type where skill was found
430    location_type: SkillLocationType,
431
432    /// Skill context (metadata only)
433    skill_context: SkillContext,
434
435    /// Path to skill directory
436    skill_path: PathBuf,
437
438    /// Generated skill name (with separators for recursive)
439    skill_name: String,
440}
441
442/// Discovery statistics
443#[derive(Debug, Default)]
444pub struct DiscoveryStats {
445    locations_scanned: usize,
446    skills_found: usize,
447    skips_due_to_precedence: usize,
448    skills_with_higher_precedence: usize,
449    parse_errors: usize,
450    dirs_visited: usize,
451}
452
453impl Default for SkillLocations {
454    fn default() -> Self {
455        Self::new()
456    }
457}
458
459/// Convert location type to string for display
460impl std::fmt::Display for SkillLocationType {
461    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
462        match self {
463            SkillLocationType::VtcodeUser => write!(f, "VT Code User"),
464            SkillLocationType::AgentsProject => write!(f, "Agents Project"),
465            SkillLocationType::VtcodeProject => write!(f, "VT Code Project"),
466            SkillLocationType::PiUser => write!(f, "Pi User"),
467            SkillLocationType::PiProject => write!(f, "Pi Project"),
468            SkillLocationType::ClaudeUser => write!(f, "Claude User"),
469            SkillLocationType::ClaudeProject => write!(f, "Claude Project"),
470            SkillLocationType::CodexUser => write!(f, "Codex User"),
471        }
472    }
473}
474
475#[cfg(test)]
476mod tests {
477    use super::*;
478    use std::path::Path;
479    use tempfile::TempDir;
480
481    fn create_test_skill(root: &Path, relative_dir: &str, name: &str) {
482        let skill_dir = root.join(relative_dir);
483        std::fs::create_dir_all(&skill_dir).unwrap();
484        let skill_md =
485            format!("---\nname: {name}\ndescription: Test skill {name}\n---\n# {name}\n\nTest instructions.\n");
486        std::fs::write(skill_dir.join("SKILL.md"), skill_md).unwrap();
487    }
488
489    #[test]
490    fn test_discovery_dir_skip_list() {
491        for skipped in [".git", ".hg", ".svn", "node_modules", "target"] {
492            assert!(discovery_dir_skipped(skipped), "{skipped} must be skipped");
493        }
494        for scanned in ["my-skill", "skills", ".agents", "docs"] {
495            assert!(!discovery_dir_skipped(scanned), "{scanned} must be scanned");
496        }
497    }
498
499    #[test]
500    fn test_walk_skips_dependency_and_vcs_trees() {
501        let temp_dir = TempDir::new().unwrap();
502        let base_path = temp_dir.path();
503
504        create_test_skill(base_path, "real-skill", "real-skill");
505        // Skills nested under dependency/VCS/build trees must not be found.
506        create_test_skill(base_path, "node_modules/hidden-skill", "hidden-skill");
507        create_test_skill(base_path, ".git/hidden-git-skill", "hidden-git-skill");
508        create_test_skill(base_path, "target/hidden-target-skill", "hidden-target-skill");
509
510        let locations = SkillLocations::with_locations(vec![SkillLocation::new(
511            SkillLocationType::VtcodeProject,
512            base_path.to_path_buf(),
513            true,
514        )]);
515
516        let discovered = locations.discover_skills().unwrap();
517        let names: Vec<String> = discovered.iter().map(|d| d.skill_context.manifest().name.clone()).collect();
518        assert_eq!(names, vec!["real-skill".to_string()]);
519    }
520
521    #[test]
522    fn test_skill_location_type_precedence() {
523        assert!(SkillLocationType::VtcodeUser > SkillLocationType::AgentsProject);
524        assert!(SkillLocationType::AgentsProject > SkillLocationType::VtcodeProject);
525        assert!(SkillLocationType::VtcodeProject > SkillLocationType::PiUser);
526        assert!(SkillLocationType::PiUser > SkillLocationType::PiProject);
527        assert!(SkillLocationType::PiProject > SkillLocationType::ClaudeUser);
528        assert!(SkillLocationType::ClaudeUser > SkillLocationType::ClaudeProject);
529        assert!(SkillLocationType::ClaudeProject > SkillLocationType::CodexUser);
530    }
531
532    #[test]
533    fn test_skill_name_generation() {
534        let temp_dir = TempDir::new().unwrap();
535        let base_path = temp_dir.path();
536
537        // Create nested skill structure
538        let skill_path = base_path.join("web/tools/search-engine");
539        std::fs::create_dir_all(&skill_path).unwrap();
540        std::fs::write(skill_path.join("SKILL.md"), "---\nname: web-search\n---\n").unwrap();
541
542        let location = SkillLocation::new(
543            SkillLocationType::VtcodeProject,
544            base_path.to_path_buf(),
545            true, // recursive
546        );
547
548        let skill_name = location.get_skill_name(&skill_path);
549        // VT Code uses '/' as separator for recursive locations
550        assert_eq!(skill_name, Some("web/tools/search-engine".to_string()));
551    }
552
553    #[test]
554    fn test_recursive_location() {
555        let temp_dir = TempDir::new().unwrap();
556        let base_path = temp_dir.path();
557
558        // Create one-level skill structure
559        let skill_path = base_path.join("file-analyzer");
560        std::fs::create_dir_all(&skill_path).unwrap();
561        std::fs::write(skill_path.join("SKILL.md"), "---\nname: file-analyzer\n---\n").unwrap();
562
563        let location = SkillLocation::new(SkillLocationType::ClaudeProject, base_path.to_path_buf(), true);
564
565        let skill_name = location.get_skill_name(&skill_path);
566        assert_eq!(skill_name, Some("file-analyzer".to_string()));
567    }
568
569    #[tokio::test]
570    async fn test_location_discovery() {
571        let temp_dir = TempDir::new().unwrap();
572        let project_skills = temp_dir.path().join(".agents/skills");
573        let claude_skills = temp_dir.path().join(".claude/skills");
574
575        create_test_skill(&project_skills, "docs/doc-generator", "doc-generator");
576        create_test_skill(&project_skills, "spreadsheet-generator", "spreadsheet-generator");
577        create_test_skill(&project_skills, "reports/pdf-report-generator", "pdf-report-generator");
578        // Same manifest name in lower-precedence location should be ignored.
579        create_test_skill(&claude_skills, "doc-generator", "doc-generator");
580
581        let locations = SkillLocations::with_locations(vec![
582            SkillLocation::new(SkillLocationType::AgentsProject, project_skills, true),
583            SkillLocation::new(SkillLocationType::ClaudeProject, claude_skills, true),
584        ]);
585
586        let discovered = locations.discover_skills().unwrap();
587        let skill_names: Vec<String> = discovered.iter().map(|d| d.skill_context.manifest().name.clone()).collect();
588        assert!(skill_names.contains(&"doc-generator".to_string()));
589        assert!(skill_names.contains(&"spreadsheet-generator".to_string()));
590        assert!(skill_names.contains(&"pdf-report-generator".to_string()));
591
592        let doc_generator = discovered
593            .iter()
594            .find(|d| d.skill_context.manifest().name == "doc-generator")
595            .expect("doc-generator should be discovered");
596        assert_eq!(doc_generator.location_type, SkillLocationType::AgentsProject);
597    }
598
599    #[test]
600    fn test_full_integration() {
601        let temp_dir = TempDir::new().unwrap();
602        let agents_skills = temp_dir.path().join(".agents/skills");
603        let vtcode_skills = temp_dir.path().join(".vtcode/skills");
604
605        create_test_skill(&agents_skills, "doc-generator", "doc-generator");
606        create_test_skill(&agents_skills, "spreadsheet-generator", "spreadsheet-generator");
607        create_test_skill(&agents_skills, "pdf-report-generator", "pdf-report-generator");
608        // Lower-precedence duplicate should be overwritten by AgentsProject entry.
609        create_test_skill(&vtcode_skills, "doc-generator", "doc-generator");
610
611        let locations = SkillLocations::with_locations(vec![
612            SkillLocation::new(SkillLocationType::VtcodeProject, vtcode_skills, true),
613            SkillLocation::new(SkillLocationType::AgentsProject, agents_skills, true),
614        ]);
615
616        let discovered = locations.discover_skills().unwrap();
617        let skill_names: Vec<String> = discovered.iter().map(|d| d.skill_context.manifest().name.clone()).collect();
618
619        assert!(skill_names.contains(&"doc-generator".to_string()), "Should find doc-generator");
620        assert!(skill_names.contains(&"spreadsheet-generator".to_string()), "Should find spreadsheet-generator");
621        assert!(skill_names.contains(&"pdf-report-generator".to_string()), "Should find pdf-report-generator");
622        let doc_generator = discovered
623            .iter()
624            .find(|d| d.skill_context.manifest().name == "doc-generator")
625            .expect("doc-generator should be discovered");
626        assert_eq!(doc_generator.location_type, SkillLocationType::AgentsProject);
627    }
628}