1use 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#[derive(Debug, Clone, Serialize, Deserialize)]
23pub struct DiscoveryConfig {
24 pub skill_paths: Vec<PathBuf>,
26
27 pub tool_paths: Vec<PathBuf>,
29
30 pub auto_discover_system_tools: bool,
32
33 pub max_depth: usize,
35
36 pub skill_patterns: Vec<String>,
38
39 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#[derive(Debug, Clone)]
65pub struct DiscoveryResult {
66 pub skills: Vec<SkillContext>,
68
69 pub tools: Vec<CliToolConfig>,
71
72 pub stats: DiscoveryStats,
74}
75
76#[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
87pub 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 pub fn new() -> Self {
102 Self::with_config(DiscoveryConfig::default())
103 }
104
105 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 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 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 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 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 let file_name = match path.file_name().and_then(|name| name.to_str()) {
206 Some(name) => name,
207 None => continue,
208 };
209 if file_name.starts_with('.') || crate::skills::locations::discovery_dir_skipped(file_name) {
210 continue;
211 }
212
213 if entry_is_dir(&entry) {
214 stats.directories_scanned += 1;
215
216 let skill_file = path.join("SKILL.md");
218 if skill_file.exists() {
219 stats.files_checked += 1;
220
221 match parse_skill_file(&path) {
222 Ok((manifest, _instructions)) => {
223 skills.push(SkillContext::MetadataOnly(manifest, path.to_path_buf()));
224 stats.skills_found += 1;
225 let skill_name = skills
226 .last()
227 .map(|ctx| ctx.manifest().name.clone())
228 .unwrap_or_else(|| "<unknown>".to_string());
229 info!("Discovered skill: {} from {}", skill_name, path.display());
230 }
231 Err(e) => {
232 warn!("Failed to parse skill from {}: {}", path.display(), e);
233 stats.errors_encountered += 1;
234 }
235 }
236 }
237
238 if depth < self.config.max_depth {
239 skills.extend(self.scan_for_skills_recursive(&path, stats, depth + 1)?);
240 }
241 }
242 }
243
244 Ok(skills)
245 }
246
247 fn discover_cli_tools(&mut self, workspace_root: &Path, stats: &mut DiscoveryStats) -> Result<Vec<CliToolConfig>> {
249 let mut tools = vec![];
250
251 for tool_path in &self.config.tool_paths {
252 let full_path = self.expand_path(tool_path, workspace_root);
253
254 if !full_path.exists() {
255 debug!("Tool path does not exist: {}", full_path.display());
256 continue;
257 }
258
259 stats.directories_scanned += 1;
260
261 match self.scan_for_tools(&full_path, stats) {
262 Ok(found_tools) => {
263 info!("Found {} tools in {}", found_tools.len(), full_path.display());
264 tools.extend(found_tools);
265 }
266 Err(e) => {
267 warn!("Failed to scan {}: {}", full_path.display(), e);
268 stats.errors_encountered += 1;
269 }
270 }
271 }
272
273 Ok(tools)
274 }
275
276 fn scan_for_tools(&self, dir: &Path, stats: &mut DiscoveryStats) -> Result<Vec<CliToolConfig>> {
278 let mut tools = vec![];
279
280 for entry in std::fs::read_dir(dir)? {
281 let entry = entry?;
282 let path = entry.path();
283
284 if entry_is_file(&entry) {
285 stats.files_checked += 1;
286
287 if let Some(config) = crate::skills::cli_bridge::cli_tool_config_from_executable(dir, &path) {
291 debug!("Discovered CLI tool: {} from {}", config.name, path.display());
292 tools.push(config);
293 stats.tools_found += 1;
294 }
295 }
296 }
297
298 Ok(tools)
299 }
300
301 fn discover_system_tools(&self, stats: &mut DiscoveryStats) -> Result<Vec<CliToolConfig>> {
303 info!("Auto-discovering system CLI tools");
304
305 match discover_cli_tools() {
306 Ok(tools) => {
307 stats.tools_found += tools.len();
308 Ok(tools)
309 }
310 Err(e) => {
311 warn!("Failed to auto-discover system tools: {}", e);
312 stats.errors_encountered += 1;
313 Ok(vec![])
314 }
315 }
316 }
317
318 fn expand_path(&self, path: &Path, workspace_root: &Path) -> PathBuf {
320 if path.starts_with("~") {
321 if let Ok(home) = std::env::var("HOME") {
323 let stripped = path.trim_prefix("~");
324 return PathBuf::from(home).join(stripped);
325 }
326 }
327
328 if path.is_relative() {
329 workspace_root.join(path)
331 } else {
332 path.to_path_buf()
333 }
334 }
335
336 pub fn clear_cache(&mut self) {
338 self.cache.clear();
339 info!("Discovery cache cleared");
340 }
341
342 pub fn get_stats(&self) -> DiscoveryStats {
344 DiscoveryStats {
345 directories_scanned: 0,
346 files_checked: 0,
347 skills_found: self.cache.values().map(|entry| entry.skills.len()).sum(),
348 tools_found: self.cache.values().map(|entry| entry.tools.len()).sum(),
349 errors_encountered: 0,
350 discovery_time_ms: 0,
351 }
352 }
353}
354
355fn default_codex_home() -> Option<PathBuf> {
356 crate::skills::system::bundled_skills_home().ok()
359}
360
361fn default_skill_paths(workspace_root: &Path) -> Vec<PathBuf> {
362 let mut paths = Vec::new();
363 let stop = find_git_root(workspace_root).unwrap_or_else(|| workspace_root.to_path_buf());
364 let mut current = workspace_root.to_path_buf();
365
366 loop {
367 paths.push(current.join(".agents/skills"));
368 if current == stop {
369 break;
370 }
371 let Some(parent) = current.parent() else {
372 break;
373 };
374 current = parent.to_path_buf();
375 }
376
377 if let Some(home) = dirs::home_dir() {
378 paths.push(home.join(".agents/skills"));
379 }
380 if let Ok(vtcode_paths) = VtCodePaths::resolve() {
381 paths.push(vtcode_paths.data_dir().join("skills"));
382 paths.push(vtcode_paths.legacy_dir().join("skills"));
383 paths.extend(vtcode_paths.system_data_paths("skills").unwrap_or_default());
384 }
385 #[cfg(unix)]
386 paths.push(PathBuf::from("/etc/codex/skills"));
387 if let Some(home) = default_codex_home() {
388 paths.push(crate::skills::system::system_cache_root_dir(&home));
389 }
390 paths
391}
392
393fn find_git_root(path: &Path) -> Option<PathBuf> {
394 let mut current = Some(path);
395 while let Some(dir) = current {
396 if dir.join(".git").exists() {
397 return Some(dir.to_path_buf());
398 }
399 current = dir.parent();
400 }
401 None
402}
403
404pub fn tool_config_to_skill_context(config: &CliToolConfig) -> Result<SkillContext> {
406 let manifest = SkillManifest {
407 name: config.name.clone(),
408 description: config.description.clone(),
409 version: Some("1.0.0".to_string()),
410 author: Some("VT Code CLI Discovery".to_string()),
411 variety: SkillVariety::SystemUtility,
412 ..Default::default()
413 };
414
415 Ok(SkillContext::MetadataOnly(manifest, config.executable_path.clone()))
416}
417
418pub struct ProgressiveSkillLoader {
420 discovery: SkillDiscovery,
421 skill_cache: HashMap<String, crate::skills::types::Skill>,
422}
423
424impl ProgressiveSkillLoader {
425 pub fn new(config: DiscoveryConfig) -> Self {
426 Self {
427 discovery: SkillDiscovery::with_config(config),
428 skill_cache: HashMap::new(),
429 }
430 }
431
432 pub async fn get_skill_metadata(&mut self, workspace_root: &Path, name: &str) -> Result<SkillContext> {
434 let result = self.discovery.discover_all(workspace_root).await?;
435
436 for skill in &result.skills {
438 if skill.manifest().name == name {
439 return Ok(skill.clone());
440 }
441 }
442
443 for tool in &result.tools {
445 if tool.name == name {
446 return tool_config_to_skill_context(tool);
447 }
448 }
449
450 Err(skill_ops::skill_not_found_error(name))
451 }
452
453 pub async fn load_full_skill(&mut self, workspace_root: &Path, name: &str) -> Result<crate::skills::types::Skill> {
455 if let Some(skill) = self.skill_cache.get(name) {
457 return Ok(skill.clone());
458 }
459
460 let result = self.discovery.discover_all(workspace_root).await?;
461
462 for skill_ctx in &result.skills {
464 if skill_ctx.manifest().name == name {
465 let manifest = skill_ctx.manifest().clone();
468 let skill = crate::skills::types::Skill::new(
469 manifest,
470 workspace_root.to_path_buf(),
471 "# Full instructions would be loaded here".to_string(),
472 )?;
473
474 self.skill_cache.insert(name.to_string(), skill.clone());
475 return Ok(skill);
476 }
477 }
478
479 for tool_config in &result.tools {
481 if tool_config.name == name {
482 let bridge = CliToolBridge::new(tool_config.clone())?;
483 let skill = bridge.to_skill()?;
484
485 self.skill_cache.insert(name.to_string(), skill.clone());
486 return Ok(skill);
487 }
488 }
489
490 Err(skill_ops::skill_not_found_error(name))
491 }
492}
493
494#[cfg(test)]
495mod tests {
496 use super::*;
497 use tempfile::TempDir;
498
499 #[tokio::test]
500 async fn test_discovery_config_default() {
501 let config = DiscoveryConfig::default();
502 assert!(config.skill_paths.is_empty());
503 assert!(!config.tool_paths.is_empty());
504 assert!(!config.auto_discover_system_tools); }
506
507 #[tokio::test]
508 async fn test_discovery_engine_creation() {
509 let discovery = SkillDiscovery::new();
510 assert_eq!(discovery.cache.len(), 0);
511 }
512
513 #[tokio::test]
514 async fn test_progressive_loader() {
515 let temp_dir = TempDir::new().unwrap();
516 let config = DiscoveryConfig::default();
517 let mut loader = ProgressiveSkillLoader::new(config);
518
519 let result = loader.discovery.discover_all(temp_dir.path()).await;
521 result.unwrap();
522 }
523
524 #[cfg(unix)]
525 #[test]
526 fn scan_for_tools_shares_the_documented_executable_rule() {
527 use std::os::unix::fs::PermissionsExt;
528
529 let temp_dir = TempDir::new().unwrap();
530 let write_executable = |name: &str| {
531 let path = temp_dir.path().join(name);
532 std::fs::write(&path, "#!/bin/sh\necho hi\n").unwrap();
533 let mut perms = std::fs::metadata(&path).unwrap().permissions();
534 perms.set_mode(0o755);
535 std::fs::set_permissions(&path, perms).unwrap();
536 };
537 write_executable("kept-tool");
539 std::fs::write(temp_dir.path().join("kept-tool.md"), "# kept\n").unwrap();
540 write_executable("dropped-tool");
541
542 let worker = SkillDiscovery::new();
543 let mut stats = DiscoveryStats::default();
544 let tools = worker.scan_for_tools(temp_dir.path(), &mut stats).unwrap();
545 let names: Vec<&str> = tools.iter().map(|tool| tool.name.as_str()).collect();
546 assert_eq!(names, vec!["kept-tool"], "only the documented executable is a skill");
547 assert_eq!(stats.tools_found, 1);
548 }
549}