1use 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
15pub const MAX_DISCOVERY_DEPTH: usize = 10;
21
22pub const MAX_DISCOVERY_DIRS: usize = 2000;
27
28pub const SKIPPED_DISCOVERY_DIRS: &[&str] = &[".git", ".hg", ".svn", "node_modules", "target"];
33
34pub fn discovery_dir_skipped(file_name: &str) -> bool {
36 SKIPPED_DISCOVERY_DIRS.contains(&file_name)
37}
38
39#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
41pub enum SkillLocationType {
42 VtcodeUser = 7,
44 AgentsProject = 6,
46 VtcodeProject = 5,
48 PiUser = 4,
50 PiProject = 3,
52 ClaudeUser = 2,
54 ClaudeProject = 1,
56 CodexUser = 0,
58}
59
60impl SkillLocationType {}
61
62#[derive(Debug, Clone)]
64pub struct SkillLocation {
65 location_type: SkillLocationType,
67
68 base_path: PathBuf,
70
71 recursive: bool,
73
74 name_separator: char,
76}
77
78impl SkillLocation {
79 fn new(location_type: SkillLocationType, base_path: PathBuf, recursive: bool) -> Self {
81 let name_separator = match location_type {
82 SkillLocationType::PiUser | SkillLocationType::PiProject => ':',
83 _ => '/', };
85
86 Self {
87 location_type,
88 base_path,
89 recursive,
90 name_separator,
91 }
92 }
93
94 fn exists(&self) -> bool {
99 self.base_path.is_dir()
100 }
101
102 fn get_skill_name(&self, skill_path: &Path) -> Option<String> {
108 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 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 skill_path.file_name().and_then(|name| name.to_str()).map(|s| s.to_string())
135 }
136 }
137}
138
139pub struct SkillLocations {
141 locations: Vec<SkillLocation>,
142}
143
144impl SkillLocations {
145 fn new() -> Self {
147 Self::with_locations(Self::default_locations())
148 }
149
150 fn with_locations(locations: Vec<SkillLocation>) -> Self {
152 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 fn default_locations() -> Vec<SkillLocation> {
161 let mut locations = Vec::new();
162 if let Ok(paths) = VtCodePaths::resolve() {
163 locations.push(SkillLocation::new(
167 SkillLocationType::VtcodeUser,
168 paths.skills_dir(),
169 true, ));
171 }
172 locations.extend([
173 SkillLocation::new(
174 SkillLocationType::AgentsProject,
175 PathBuf::from(".agents/skills"),
176 true, ),
178 SkillLocation::new(
179 SkillLocationType::VtcodeProject,
180 PathBuf::from(".vtcode/skills"),
181 true, ),
183 SkillLocation::new(
185 SkillLocationType::PiUser,
186 PathBuf::from("~/.pi/agent/skills"),
187 true, ),
189 SkillLocation::new(
190 SkillLocationType::PiProject,
191 PathBuf::from(".pi/skills"),
192 true, ),
194 SkillLocation::new(
196 SkillLocationType::ClaudeUser,
197 PathBuf::from("~/.claude/skills"),
198 true, ),
200 SkillLocation::new(
201 SkillLocationType::ClaudeProject,
202 PathBuf::from(".claude/skills"),
203 true, ),
205 SkillLocation::new(
207 SkillLocationType::CodexUser,
208 PathBuf::from("~/.codex/skills"),
209 true, ),
211 ]);
212 locations
213 }
214
215 fn discover_skills(&self) -> Result<Vec<DiscoveredSkill>> {
217 let mut discovered_skills = HashMap::new(); 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 let mut final_skills: Vec<DiscoveredSkill> = discovered_skills.into_values().collect();
251
252 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 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
272fn 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 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 if let Some(skill_name) = location.get_skill_name(dir) {
297 match parse_skill_file(dir) {
298 Ok((manifest, _)) => {
299 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 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 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 if let Ok(entries) = std::fs::read_dir(dir) {
339 for entry in entries.flatten() {
340 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 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 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 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 pub fn get_location_types(&self) -> Vec<SkillLocationType> {
417 self.locations.iter().map(|loc| loc.location_type).collect()
418 }
419
420 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#[derive(Debug, Clone)]
428pub struct DiscoveredSkill {
429 location_type: SkillLocationType,
431
432 skill_context: SkillContext,
434
435 skill_path: PathBuf,
437
438 skill_name: String,
440}
441
442#[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
459impl 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 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 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, );
547
548 let skill_name = location.get_skill_name(&skill_path);
549 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 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 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 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}