Skip to main content

vtcode_core/skills/
discovery.rs

1//! Dynamic Skill Discovery System
2//!
3//! Implements filesystem-based skill discovery with support for:
4//! - Traditional VT Code skills (SKILL.md files)
5//! - CLI tool skills (executable + README.md)
6//! - Auto-discovery of tools in standard locations
7//! - Progressive metadata loading
8
9use crate::skills::cli_bridge::{CliToolBridge, CliToolConfig, discover_cli_tools};
10use crate::skills::manifest::parse_skill_file;
11use crate::skills::types::{SkillContext, SkillManifest, SkillVariety};
12use crate::tools::error_messages::skill_ops;
13use anyhow::{Context, Result};
14use hashbrown::HashMap;
15use serde::{Deserialize, Serialize};
16use std::path::{Path, PathBuf};
17use tracing::{debug, info, warn};
18use vtcode_commons::VtCodePaths;
19use vtcode_commons::walk::{entry_is_dir, entry_is_file};
20
21/// Enhanced skill discovery configuration
22#[derive(Debug, Clone, Serialize, Deserialize)]
23pub struct DiscoveryConfig {
24    /// Search paths for traditional skills
25    pub skill_paths: Vec<PathBuf>,
26
27    /// Search paths for CLI tools
28    pub tool_paths: Vec<PathBuf>,
29
30    /// Auto-discover system tools
31    pub auto_discover_system_tools: bool,
32
33    /// Maximum depth for recursive directory scanning
34    pub max_depth: usize,
35
36    /// File patterns to consider as skills
37    pub skill_patterns: Vec<String>,
38
39    /// Tool file patterns
40    pub tool_patterns: Vec<String>,
41}
42
43impl Default for DiscoveryConfig {
44    fn default() -> Self {
45        let mut tool_paths = vec![PathBuf::from("./tools"), PathBuf::from("./vendor/tools")];
46        if let Ok(paths) = VtCodePaths::resolve() {
47            if let Ok(user_tool_path) = paths.data_path("tools") {
48                tool_paths.push(user_tool_path);
49            }
50            tool_paths.push(paths.legacy_dir().join("tools"));
51        }
52        Self {
53            skill_paths: Vec::new(),
54            tool_paths,
55            auto_discover_system_tools: false,
56            max_depth: 3,
57            skill_patterns: vec!["SKILL.md".to_string()],
58            tool_patterns: vec!["*.exe".to_string(), "*.sh".to_string(), "*.py".to_string()],
59        }
60    }
61}
62
63/// Discovery result containing both traditional skills and CLI tools
64#[derive(Debug, Clone)]
65pub struct DiscoveryResult {
66    /// Traditional VT Code skills
67    pub skills: Vec<SkillContext>,
68
69    /// CLI tool configurations
70    pub tools: Vec<CliToolConfig>,
71
72    /// Discovery statistics
73    pub stats: DiscoveryStats,
74}
75
76/// Discovery statistics
77#[derive(Debug, Clone, Default, Serialize, Deserialize)]
78pub struct DiscoveryStats {
79    pub directories_scanned: usize,
80    pub files_checked: usize,
81    pub skills_found: usize,
82    pub tools_found: usize,
83    pub errors_encountered: usize,
84    pub discovery_time_ms: u64,
85}
86
87/// Dynamic skill discovery engine
88pub struct SkillDiscovery {
89    config: DiscoveryConfig,
90    cache: HashMap<PathBuf, DiscoveryCacheEntry>,
91}
92
93#[derive(Debug, Clone)]
94struct DiscoveryCacheEntry {
95    skills: Vec<SkillContext>,
96    tools: Vec<CliToolConfig>,
97}
98
99impl SkillDiscovery {
100    /// Create new discovery engine with default configuration
101    pub fn new() -> Self {
102        Self::with_config(DiscoveryConfig::default())
103    }
104
105    /// Create new discovery engine with custom configuration
106    pub fn with_config(config: DiscoveryConfig) -> Self {
107        Self { config, cache: HashMap::new() }
108    }
109}
110
111impl Default for SkillDiscovery {
112    fn default() -> Self {
113        Self::new()
114    }
115}
116
117impl SkillDiscovery {
118    /// Discover all available skills and tools
119    pub async fn discover_all(&mut self, workspace_root: &Path) -> Result<DiscoveryResult> {
120        let start_time = std::time::Instant::now();
121        info!("Starting skill discovery in: {}", workspace_root.display());
122
123        let config = self.config.clone();
124        let workspace_root = workspace_root.to_path_buf();
125        let (skills, tools, mut stats) = tokio::task::spawn_blocking(move || {
126            let mut worker = Self::with_config(config);
127            let mut stats = DiscoveryStats::default();
128            let skills = worker.discover_traditional_skills(&workspace_root, &mut stats)?;
129            let mut tools = worker.discover_cli_tools(&workspace_root, &mut stats)?;
130            if worker.config.auto_discover_system_tools {
131                tools.extend(worker.discover_system_tools(&mut stats)?);
132            }
133            Ok::<_, anyhow::Error>((skills, tools, stats))
134        })
135        .await
136        .context("skill discovery task panicked")??;
137
138        stats.discovery_time_ms = start_time.elapsed().as_millis() as u64;
139        Ok(DiscoveryResult { skills, tools, stats })
140    }
141
142    /// Discover traditional VT Code skills
143    fn discover_traditional_skills(
144        &mut self,
145        workspace_root: &Path,
146        stats: &mut DiscoveryStats,
147    ) -> Result<Vec<SkillContext>> {
148        let mut skills = vec![];
149        let skill_paths = if self.config.skill_paths.is_empty() {
150            default_skill_paths(workspace_root)
151        } else {
152            self.config.skill_paths.clone()
153        };
154
155        for skill_path in &skill_paths {
156            let full_path = self.expand_path(skill_path, workspace_root);
157
158            if !full_path.exists() {
159                debug!("Skill path does not exist: {}", full_path.display());
160                continue;
161            }
162
163            stats.directories_scanned += 1;
164
165            // Scan for skill directories
166            match self.scan_for_skills(&full_path, stats) {
167                Ok(found_skills) => {
168                    info!("Found {} skills in {}", found_skills.len(), full_path.display());
169                    skills.extend(found_skills);
170                }
171                Err(e) => {
172                    warn!("Failed to scan {}: {}", full_path.display(), e);
173                    stats.errors_encountered += 1;
174                }
175            }
176        }
177
178        Ok(skills)
179    }
180
181    /// Scan directory for traditional skills
182    fn scan_for_skills(&self, dir: &Path, stats: &mut DiscoveryStats) -> Result<Vec<SkillContext>> {
183        self.scan_for_skills_recursive(dir, stats, 0)
184    }
185
186    fn scan_for_skills_recursive(
187        &self,
188        dir: &Path,
189        stats: &mut DiscoveryStats,
190        depth: usize,
191    ) -> Result<Vec<SkillContext>> {
192        let mut skills = vec![];
193
194        if depth > self.config.max_depth {
195            return Ok(skills);
196        }
197
198        for entry in std::fs::read_dir(dir)? {
199            let entry = entry?;
200            let path = entry.path();
201
202            if entry_is_dir(&entry) {
203                stats.directories_scanned += 1;
204
205                // Check for SKILL.md file
206                let skill_file = path.join("SKILL.md");
207                if skill_file.exists() {
208                    stats.files_checked += 1;
209
210                    match parse_skill_file(&path) {
211                        Ok((manifest, _instructions)) => {
212                            skills.push(SkillContext::MetadataOnly(manifest, path.to_path_buf()));
213                            stats.skills_found += 1;
214                            let skill_name = skills
215                                .last()
216                                .map(|ctx| ctx.manifest().name.clone())
217                                .unwrap_or_else(|| "<unknown>".to_string());
218                            info!("Discovered skill: {} from {}", skill_name, path.display());
219                        }
220                        Err(e) => {
221                            warn!("Failed to parse skill from {}: {}", path.display(), e);
222                            stats.errors_encountered += 1;
223                        }
224                    }
225                }
226
227                if depth < self.config.max_depth {
228                    skills.extend(self.scan_for_skills_recursive(&path, stats, depth + 1)?);
229                }
230            }
231        }
232
233        Ok(skills)
234    }
235
236    /// Discover CLI tools in workspace
237    fn discover_cli_tools(&mut self, workspace_root: &Path, stats: &mut DiscoveryStats) -> Result<Vec<CliToolConfig>> {
238        let mut tools = vec![];
239
240        for tool_path in &self.config.tool_paths {
241            let full_path = self.expand_path(tool_path, workspace_root);
242
243            if !full_path.exists() {
244                debug!("Tool path does not exist: {}", full_path.display());
245                continue;
246            }
247
248            stats.directories_scanned += 1;
249
250            match self.scan_for_tools(&full_path, stats) {
251                Ok(found_tools) => {
252                    info!("Found {} tools in {}", found_tools.len(), full_path.display());
253                    tools.extend(found_tools);
254                }
255                Err(e) => {
256                    warn!("Failed to scan {}: {}", full_path.display(), e);
257                    stats.errors_encountered += 1;
258                }
259            }
260        }
261
262        Ok(tools)
263    }
264
265    /// Scan directory for CLI tools
266    fn scan_for_tools(&self, dir: &Path, stats: &mut DiscoveryStats) -> Result<Vec<CliToolConfig>> {
267        let mut tools = vec![];
268
269        for entry in std::fs::read_dir(dir)? {
270            let entry = entry?;
271            let path = entry.path();
272
273            if entry_is_file(&entry) {
274                stats.files_checked += 1;
275
276                // Single shared predicate lives in `cli_bridge` so the
277                // "executable + explicit docs" rule cannot drift between
278                // scanners.
279                if let Some(config) = crate::skills::cli_bridge::cli_tool_config_from_executable(dir, &path) {
280                    debug!("Discovered CLI tool: {} from {}", config.name, path.display());
281                    tools.push(config);
282                    stats.tools_found += 1;
283                }
284            }
285        }
286
287        Ok(tools)
288    }
289
290    /// Discover system-wide CLI tools
291    fn discover_system_tools(&self, stats: &mut DiscoveryStats) -> Result<Vec<CliToolConfig>> {
292        info!("Auto-discovering system CLI tools");
293
294        match discover_cli_tools() {
295            Ok(tools) => {
296                stats.tools_found += tools.len();
297                Ok(tools)
298            }
299            Err(e) => {
300                warn!("Failed to auto-discover system tools: {}", e);
301                stats.errors_encountered += 1;
302                Ok(vec![])
303            }
304        }
305    }
306
307    /// Expand path with workspace root and home directory
308    fn expand_path(&self, path: &Path, workspace_root: &Path) -> PathBuf {
309        if path.starts_with("~") {
310            // Expand home directory
311            if let Ok(home) = std::env::var("HOME") {
312                let stripped = path.strip_prefix("~").unwrap_or(path);
313                return PathBuf::from(home).join(stripped);
314            }
315        }
316
317        if path.is_relative() {
318            // Make relative to workspace root
319            workspace_root.join(path)
320        } else {
321            path.to_path_buf()
322        }
323    }
324
325    /// Clear discovery cache
326    pub fn clear_cache(&mut self) {
327        self.cache.clear();
328        info!("Discovery cache cleared");
329    }
330
331    /// Get discovery statistics
332    pub fn get_stats(&self) -> DiscoveryStats {
333        DiscoveryStats {
334            directories_scanned: 0,
335            files_checked: 0,
336            skills_found: self.cache.values().map(|entry| entry.skills.len()).sum(),
337            tools_found: self.cache.values().map(|entry| entry.tools.len()).sum(),
338            errors_encountered: 0,
339            discovery_time_ms: 0,
340        }
341    }
342}
343
344fn default_codex_home() -> PathBuf {
345    std::env::var_os("CODEX_HOME")
346        .filter(|value| !value.is_empty())
347        .map(PathBuf::from)
348        .or_else(|| dirs::home_dir().map(|home| home.join(".codex")))
349        .unwrap_or_else(|| PathBuf::from(".codex"))
350}
351
352fn default_skill_paths(workspace_root: &Path) -> Vec<PathBuf> {
353    let mut paths = Vec::new();
354    let stop = find_git_root(workspace_root).unwrap_or_else(|| workspace_root.to_path_buf());
355    let mut current = workspace_root.to_path_buf();
356
357    loop {
358        paths.push(current.join(".agents/skills"));
359        if current == stop {
360            break;
361        }
362        let Some(parent) = current.parent() else {
363            break;
364        };
365        current = parent.to_path_buf();
366    }
367
368    if let Some(home) = dirs::home_dir() {
369        paths.push(home.join(".agents/skills"));
370    }
371    if let Ok(vtcode_paths) = VtCodePaths::resolve() {
372        paths.push(vtcode_paths.data_dir().join("skills"));
373        paths.push(vtcode_paths.legacy_dir().join("skills"));
374        paths.extend(vtcode_paths.system_data_paths("skills").unwrap_or_default());
375    }
376    #[cfg(unix)]
377    paths.push(PathBuf::from("/etc/codex/skills"));
378    paths.push(crate::skills::system::system_cache_root_dir(&default_codex_home()));
379    paths
380}
381
382fn find_git_root(path: &Path) -> Option<PathBuf> {
383    let mut current = Some(path);
384    while let Some(dir) = current {
385        if dir.join(".git").exists() {
386            return Some(dir.to_path_buf());
387        }
388        current = dir.parent();
389    }
390    None
391}
392
393/// Convert CLI tool configuration to SkillContext
394pub fn tool_config_to_skill_context(config: &CliToolConfig) -> Result<SkillContext> {
395    let manifest = SkillManifest {
396        name: config.name.clone(),
397        description: config.description.clone(),
398        version: Some("1.0.0".to_string()),
399        author: Some("VT Code CLI Discovery".to_string()),
400        variety: SkillVariety::SystemUtility,
401        ..Default::default()
402    };
403
404    Ok(SkillContext::MetadataOnly(manifest, config.executable_path.clone()))
405}
406
407/// Progressive skill loader that can load full skill details on demand
408pub struct ProgressiveSkillLoader {
409    discovery: SkillDiscovery,
410    skill_cache: HashMap<String, crate::skills::types::Skill>,
411}
412
413impl ProgressiveSkillLoader {
414    pub fn new(config: DiscoveryConfig) -> Self {
415        Self {
416            discovery: SkillDiscovery::with_config(config),
417            skill_cache: HashMap::new(),
418        }
419    }
420
421    /// Get skill metadata (lightweight)
422    pub async fn get_skill_metadata(&mut self, workspace_root: &Path, name: &str) -> Result<SkillContext> {
423        let result = self.discovery.discover_all(workspace_root).await?;
424
425        // Check traditional skills
426        for skill in &result.skills {
427            if skill.manifest().name == name {
428                return Ok(skill.clone());
429            }
430        }
431
432        // Check CLI tools
433        for tool in &result.tools {
434            if tool.name == name {
435                return tool_config_to_skill_context(tool);
436            }
437        }
438
439        Err(skill_ops::skill_not_found_error(name))
440    }
441
442    /// Load full skill with instructions and resources
443    pub async fn load_full_skill(&mut self, workspace_root: &Path, name: &str) -> Result<crate::skills::types::Skill> {
444        // Check cache first
445        if let Some(skill) = self.skill_cache.get(name) {
446            return Ok(skill.clone());
447        }
448
449        let result = self.discovery.discover_all(workspace_root).await?;
450
451        // Try traditional skills first
452        for skill_ctx in &result.skills {
453            if skill_ctx.manifest().name == name {
454                // Load full skill details
455                // This would require path information - simplified for now
456                let manifest = skill_ctx.manifest().clone();
457                let skill = crate::skills::types::Skill::new(
458                    manifest,
459                    workspace_root.to_path_buf(),
460                    "# Full instructions would be loaded here".to_string(),
461                )?;
462
463                self.skill_cache.insert(name.to_string(), skill.clone());
464                return Ok(skill);
465            }
466        }
467
468        // Try CLI tools
469        for tool_config in &result.tools {
470            if tool_config.name == name {
471                let bridge = CliToolBridge::new(tool_config.clone())?;
472                let skill = bridge.to_skill()?;
473
474                self.skill_cache.insert(name.to_string(), skill.clone());
475                return Ok(skill);
476            }
477        }
478
479        Err(skill_ops::skill_not_found_error(name))
480    }
481}
482
483#[cfg(test)]
484mod tests {
485    use super::*;
486    use tempfile::TempDir;
487
488    #[tokio::test]
489    async fn test_discovery_config_default() {
490        let config = DiscoveryConfig::default();
491        assert!(config.skill_paths.is_empty());
492        assert!(!config.tool_paths.is_empty());
493        assert!(!config.auto_discover_system_tools); // Disabled by default for security
494    }
495
496    #[tokio::test]
497    async fn test_discovery_engine_creation() {
498        let discovery = SkillDiscovery::new();
499        assert_eq!(discovery.cache.len(), 0);
500    }
501
502    #[tokio::test]
503    async fn test_progressive_loader() {
504        let temp_dir = TempDir::new().unwrap();
505        let config = DiscoveryConfig::default();
506        let mut loader = ProgressiveSkillLoader::new(config);
507
508        // Should handle empty directory gracefully
509        let result = loader.discovery.discover_all(temp_dir.path()).await;
510        result.unwrap();
511    }
512
513    #[cfg(unix)]
514    #[test]
515    fn scan_for_tools_shares_the_documented_executable_rule() {
516        use std::os::unix::fs::PermissionsExt;
517
518        let temp_dir = TempDir::new().unwrap();
519        let write_executable = |name: &str| {
520            let path = temp_dir.path().join(name);
521            std::fs::write(&path, "#!/bin/sh\necho hi\n").unwrap();
522            let mut perms = std::fs::metadata(&path).unwrap().permissions();
523            perms.set_mode(0o755);
524            std::fs::set_permissions(&path, perms).unwrap();
525        };
526        // Asymmetric pair: same executable bit, docs present vs absent.
527        write_executable("kept-tool");
528        std::fs::write(temp_dir.path().join("kept-tool.md"), "# kept\n").unwrap();
529        write_executable("dropped-tool");
530
531        let worker = SkillDiscovery::new();
532        let mut stats = DiscoveryStats::default();
533        let tools = worker.scan_for_tools(temp_dir.path(), &mut stats).unwrap();
534        let names: Vec<&str> = tools.iter().map(|tool| tool.name.as_str()).collect();
535        assert_eq!(names, vec!["kept-tool"], "only the documented executable is a skill");
536        assert_eq!(stats.tools_found, 1);
537    }
538}