Skip to main content

vtcode_core/skills/
manager.rs

1use crate::skills::SkillMetadata;
2#[cfg(test)]
3use crate::skills::loader::discover_skill_metadata_lightweight_hermetic;
4use crate::skills::loader::{
5    SkillLoaderConfig, clear_lightweight_skill_metadata_cache, discover_skill_metadata_lightweight, load_skills,
6};
7use crate::skills::model::SkillLoadOutcome;
8use crate::skills::system::install_system_skills;
9use crate::skills::system::uninstall_system_skills;
10use crate::skills::types::Skill;
11use anyhow::Result;
12use hashbrown::HashMap;
13use std::path::{Path, PathBuf};
14use std::sync::OnceLock;
15use std::sync::RwLock;
16use std::time::{Duration, SystemTime};
17
18use crate::utils::file_utils::read_file_with_context_sync;
19
20/// Generic cache entry with TTL tracking.
21#[derive(Clone)]
22struct CachedEntry<T> {
23    value: T,
24    timestamp: SystemTime,
25}
26
27impl<T> CachedEntry<T> {
28    fn new(value: T) -> Self {
29        Self { value, timestamp: SystemTime::now() }
30    }
31
32    fn is_expired(&self, ttl: Duration) -> bool {
33        self.timestamp.elapsed().unwrap_or(ttl) > ttl
34    }
35}
36
37pub struct SkillsManager {
38    codex_home: PathBuf,
39    bundled_skills_enabled: bool,
40    /// Per-cwd skill loading cache with TTL and max capacity
41    cache_by_cwd: RwLock<HashMap<PathBuf, CachedEntry<SkillLoadOutcome>>>,
42    /// Max number of cached workspaces (prevents unbounded growth)
43    max_cache_size: usize,
44    /// TTL for cached metadata (default 5 minutes)
45    cache_ttl: Duration,
46    /// Tracks if system skills installation has been attempted
47    system_skills_initialized: OnceLock<()>,
48    /// Per-skill instruction cache with TTL (Phase 3: deferred SKILL.md parsing)
49    instruction_cache: RwLock<HashMap<String, CachedEntry<Skill>>>,
50    /// Max instructions cached in memory (prevents unbounded growth)
51    max_instruction_cache_size: usize,
52    /// TTL for instruction cache (default 10 minutes - longer than metadata)
53    instruction_cache_ttl: Duration,
54}
55
56/// Generic cache eviction: remove expired entries, then LRU if still over capacity.
57fn evict_cache<K, V>(
58    cache: &mut HashMap<K, V>,
59    max_size: usize,
60    ttl: Duration,
61    get_timestamp: impl Fn(&V) -> SystemTime,
62    is_expired: impl Fn(&V, Duration) -> bool,
63) where
64    K: Eq + std::hash::Hash + Clone,
65{
66    // Remove expired entries
67    let expired: Vec<_> = cache
68        .iter()
69        .filter(|(_, v)| is_expired(v, ttl))
70        .map(|(k, _)| k.clone())
71        .collect();
72    for key in expired {
73        cache.remove(&key);
74    }
75
76    // If still at capacity, remove oldest entry by timestamp (LRU)
77    if cache.len() >= max_size {
78        let oldest_key = cache.iter().min_by_key(|(_, v)| get_timestamp(v)).map(|(k, _)| k.clone());
79        if let Some(key) = oldest_key {
80            cache.remove(&key);
81        }
82    }
83}
84
85impl SkillsManager {
86    /// Create a manager with bundled skills unconditionally enabled.
87    ///
88    /// Prefer [`Self::new_with_bundled_skills_enabled`] with
89    /// [`crate::skills::bundled_skills_install_permitted_for_workspace`]:
90    /// production call sites must gate on ask-first consent, not default on.
91    pub fn new(codex_home: PathBuf) -> Self {
92        Self::new_with_bundled_skills_enabled(codex_home, true)
93    }
94
95    /// Create a manager with an explicit bundled-skills permission.
96    ///
97    /// The flag is the consent-gated permission (see
98    /// [`crate::skills::bundled_skills_install_permitted_for_workspace`]),
99    /// not the raw config value: `false` skips the install, excludes the
100    /// system discovery root, and removes our own cache directory.
101    pub fn new_with_bundled_skills_enabled(codex_home: PathBuf, bundled_skills_enabled: bool) -> Self {
102        let manager = Self {
103            codex_home,
104            bundled_skills_enabled,
105            cache_by_cwd: RwLock::new(HashMap::new()),
106            max_cache_size: 10,
107            cache_ttl: Duration::from_secs(5 * 60), // 5 minutes
108            system_skills_initialized: OnceLock::new(),
109            instruction_cache: RwLock::new(HashMap::new()),
110            max_instruction_cache_size: 50, // Cache up to 50 parsed skills
111            instruction_cache_ttl: Duration::from_secs(10 * 60), // 10 minutes
112        };
113
114        if !manager.bundled_skills_enabled {
115            uninstall_system_skills(&manager.codex_home);
116        }
117
118        manager
119    }
120
121    pub fn bundled_skills_enabled(&self) -> bool {
122        self.bundled_skills_enabled
123    }
124
125    /// Lazy initialize system skills (non-blocking, can be called async)
126    pub fn ensure_system_skills_installed(&self) {
127        self.system_skills_initialized.get_or_init(|| {
128            if !self.bundled_skills_enabled {
129                return;
130            }
131
132            // Try to install system skills, log error if fails but don't panic
133            if let Err(err) = install_system_skills(&self.codex_home) {
134                tracing::warn!("lazy system skills installation failed: {err}");
135            }
136        });
137    }
138
139    pub fn skills_for_cwd(&self, cwd: &Path) -> SkillLoadOutcome {
140        self.skills_for_cwd_with_options(cwd, false)
141    }
142
143    pub fn skills_for_cwd_with_options(&self, cwd: &Path, force_reload: bool) -> SkillLoadOutcome {
144        // Ensure system skills are installed at least once
145        self.ensure_system_skills_installed();
146
147        if !force_reload {
148            if let Ok(cache) = self.cache_by_cwd.read() {
149                if let Some(cached) = cache.get(cwd)
150                    && !cached.is_expired(self.cache_ttl)
151                {
152                    return cached.value.clone();
153                }
154            } else {
155                tracing::warn!("skills metadata cache lock poisoned while reading cache");
156            }
157        }
158
159        let project_root = find_git_root(cwd);
160
161        let config = SkillLoaderConfig {
162            codex_home: self.codex_home.clone(),
163            cwd: cwd.to_path_buf(),
164            project_root,
165            include_bundled_system_skills: self.bundled_skills_enabled,
166        };
167
168        let outcome = load_skills(&config);
169
170        if let Ok(mut cache) = self.cache_by_cwd.write() {
171            // Enforce max cache size: remove expired entries first, then LRU
172            if cache.len() >= self.max_cache_size && !cache.contains_key(cwd) {
173                evict_cache(
174                    &mut cache,
175                    self.max_cache_size,
176                    self.cache_ttl,
177                    |v| v.timestamp,
178                    |v, ttl| v.is_expired(ttl),
179                );
180            }
181
182            cache.insert(cwd.to_path_buf(), CachedEntry::new(outcome.clone()));
183        } else {
184            tracing::warn!("skills metadata cache lock poisoned while writing cache");
185        }
186
187        outcome
188    }
189
190    /// Clear the entire cache
191    pub fn clear_cache(&self) {
192        if let Ok(mut cache) = self.cache_by_cwd.write() {
193            cache.clear();
194        } else {
195            tracing::warn!("skills metadata cache lock poisoned while clearing cache");
196        }
197        clear_lightweight_skill_metadata_cache();
198    }
199
200    /// Get current cache size (for testing/diagnostics)
201    pub fn cache_size(&self) -> usize {
202        if let Ok(cache) = self.cache_by_cwd.read() {
203            cache.len()
204        } else {
205            tracing::warn!("skills metadata cache lock poisoned while reading cache size");
206            0
207        }
208    }
209
210    /// Quick metadata discovery without parsing SKILL.md files (Phase 2)
211    /// Returns skill stubs with name and path only (no manifest parsing).
212    /// ~10x faster than full discovery, suitable for listing available skills.
213    pub fn skills_metadata_lightweight(&self, cwd: &Path) -> SkillLoadOutcome {
214        // Ensure system skills are installed at least once
215        self.ensure_system_skills_installed();
216
217        let project_root = find_git_root(cwd);
218
219        let config = SkillLoaderConfig {
220            codex_home: self.codex_home.clone(),
221            cwd: cwd.to_path_buf(),
222            project_root,
223            include_bundled_system_skills: self.bundled_skills_enabled,
224        };
225
226        // Use lightweight discovery (no manifest parsing)
227        discover_skill_metadata_lightweight(&config)
228    }
229
230    #[cfg(test)]
231    fn skills_metadata_lightweight_hermetic(&self, cwd: &Path) -> SkillLoadOutcome {
232        let project_root = find_git_root(cwd);
233
234        let config = SkillLoaderConfig {
235            codex_home: self.codex_home.clone(),
236            cwd: cwd.to_path_buf(),
237            project_root,
238            include_bundled_system_skills: self.bundled_skills_enabled,
239        };
240
241        discover_skill_metadata_lightweight_hermetic(&config)
242    }
243
244    /// Load full skill instructions on-demand (Phase 3)
245    /// Parses SKILL.md and returns Skill with full manifest and instructions.
246    /// Cached with LRU eviction (max 50 skills, 10-minute TTL).
247    /// Returns cached result if available and not expired.
248    pub fn load_skill_instructions(&self, skill_name: &str, skill_path: &Path) -> Result<Skill> {
249        // Composite cache key: name + resolved path to avoid collisions when
250        // skills in different directories share the same name.
251        let cache_key = format!("{}:{}", skill_name, skill_path.display());
252
253        // Check cache first
254        {
255            if let Ok(cache) = self.instruction_cache.read() {
256                if let Some(cached) = cache.get(&cache_key)
257                    && !cached.is_expired(self.instruction_cache_ttl)
258                {
259                    return Ok(cached.value.clone());
260                }
261            } else {
262                tracing::warn!("skill instruction cache lock poisoned while reading cache");
263            }
264        }
265
266        // Parse SKILL.md on-demand
267        let skill_md = skill_path.join("SKILL.md");
268        let content = read_file_with_context_sync(&skill_md, "skill instructions")
269            .map_err(|e| anyhow::anyhow!("Failed to read SKILL.md for '{skill_name}': {e}"))?;
270
271        let (manifest, instructions) = crate::skills::manifest::parse_skill_content(&content)?;
272        let skill = Skill::new(manifest, skill_path.to_path_buf(), instructions)?;
273
274        // Cache the parsed skill
275        if let Ok(mut cache) = self.instruction_cache.write() {
276            // Enforce max cache size: remove expired entries first, then LRU
277            if cache.len() >= self.max_instruction_cache_size && !cache.contains_key(&cache_key) {
278                evict_cache(
279                    &mut cache,
280                    self.max_instruction_cache_size,
281                    self.instruction_cache_ttl,
282                    |v| v.timestamp,
283                    |v, ttl| v.is_expired(ttl),
284                );
285            }
286
287            cache.insert(cache_key, CachedEntry::new(skill.clone()));
288        } else {
289            tracing::warn!("skill instruction cache lock poisoned while writing cache");
290        }
291
292        Ok(skill)
293    }
294
295    /// Resolve a skill by name from the discovered set for the given cwd.
296    /// Returns `Err` if the skill is not found, enabling callers to fail loud.
297    pub fn resolve_skill_by_name(&self, cwd: &Path, skill_name: &str) -> Result<SkillMetadata> {
298        let outcome = self.skills_for_cwd(cwd);
299        let available: Vec<String> = outcome.skills.iter().map(|s| s.name.clone()).collect();
300        outcome.skills.into_iter().find(|s| s.name == skill_name).ok_or_else(|| {
301            anyhow::anyhow!("Skill '{}' not found. Available skills: [{}]", skill_name, available.join(", "))
302        })
303    }
304
305    /// Load skills by name from a list of skill names (e.g. from
306    /// `LoopEngineConfig.preload_skills`). Returns metadata for each
307    /// found skill and logs warnings for missing ones.
308    pub fn loop_skills(&self, cwd: &Path, skill_names: &[String]) -> Vec<SkillMetadata> {
309        if skill_names.is_empty() {
310            return Vec::new();
311        }
312
313        let outcome = self.skills_for_cwd(cwd);
314        let available: HashMap<String, &SkillMetadata> = outcome.skills.iter().map(|s| (s.name.clone(), s)).collect();
315
316        let mut loaded = Vec::new();
317        for name in skill_names {
318            if let Some(meta) = available.get(name) {
319                loaded.push((*meta).clone());
320            } else {
321                tracing::warn!(
322                    skill = %name,
323                    "Preload skill not found; skipping. Available: {}",
324                    available
325                        .keys()
326                        .cloned()
327                        .collect::<Vec<_>>()
328                        .join(", ")
329                );
330            }
331        }
332        loaded
333    }
334
335    /// Clear instruction cache
336    pub fn clear_instruction_cache(&self) {
337        if let Ok(mut cache) = self.instruction_cache.write() {
338            cache.clear();
339        } else {
340            tracing::warn!("skill instruction cache lock poisoned while clearing cache");
341        }
342    }
343
344    /// Get instruction cache size (for testing/diagnostics)
345    pub fn instruction_cache_size(&self) -> usize {
346        if let Ok(cache) = self.instruction_cache.read() {
347            cache.len()
348        } else {
349            tracing::warn!("skill instruction cache lock poisoned while reading cache size");
350            0
351        }
352    }
353}
354
355fn find_git_root(path: &Path) -> Option<PathBuf> {
356    let mut current = path;
357    loop {
358        if current.join(".git").exists() {
359            return Some(current.to_path_buf());
360        }
361        current = current.parent()?;
362    }
363}
364
365#[cfg(test)]
366mod tests {
367    use super::*;
368    use serial_test::serial;
369    use std::fs;
370    use tempfile::TempDir;
371
372    #[test]
373    fn test_skills_manager_lazy_initialization() {
374        let temp_home = TempDir::new().unwrap();
375        let manager = SkillsManager::new(temp_home.path().to_path_buf());
376
377        // Manager should be created without system skills initialized yet
378        assert_eq!(manager.cache_size(), 0);
379
380        // Ensure system skills are initialized
381        manager.ensure_system_skills_installed();
382
383        // Should still have empty cache (only system installation tracked)
384        assert_eq!(manager.cache_size(), 0);
385    }
386
387    #[test]
388    fn test_skills_manager_cache_with_ttl() {
389        let temp_home = TempDir::new().unwrap();
390        let manager = SkillsManager::new(temp_home.path().to_path_buf());
391
392        let cwd = temp_home.path();
393
394        // First load
395        let outcome1 = manager.skills_for_cwd(cwd);
396        assert_eq!(manager.cache_size(), 1);
397
398        // Second load (should return cached)
399        let outcome2 = manager.skills_for_cwd(cwd);
400        assert_eq!(outcome1.skills.len(), outcome2.skills.len());
401        assert_eq!(manager.cache_size(), 1);
402
403        // Force reload
404        let outcome3 = manager.skills_for_cwd_with_options(cwd, true);
405        assert_eq!(manager.cache_size(), 1);
406        assert_eq!(outcome1.skills.len(), outcome3.skills.len());
407    }
408
409    #[test]
410    fn test_skills_manager_max_cache_size() {
411        let temp_home = TempDir::new().unwrap();
412        let manager = SkillsManager::new(temp_home.path().to_path_buf());
413
414        // Create multiple temp directories and load skills
415        for _ in 0..15 {
416            let dir = TempDir::new().unwrap();
417            let cwd = dir.path();
418            manager.skills_for_cwd(cwd);
419        }
420
421        // Cache should respect max_cache_size (10)
422        assert!(manager.cache_size() <= 10);
423    }
424
425    #[test]
426    fn test_skills_manager_clear_cache() {
427        let temp_home = TempDir::new().unwrap();
428        let manager = SkillsManager::new(temp_home.path().to_path_buf());
429
430        let cwd = temp_home.path();
431        manager.skills_for_cwd(cwd);
432        assert_eq!(manager.cache_size(), 1);
433
434        manager.clear_cache();
435        assert_eq!(manager.cache_size(), 0);
436    }
437
438    #[test]
439    #[serial]
440    fn test_skills_manager_clear_cache_clears_lightweight_discovery_cache() {
441        clear_lightweight_skill_metadata_cache();
442
443        let temp_home = TempDir::new().unwrap();
444        let workspace = TempDir::new().unwrap();
445        let manager = SkillsManager::new(temp_home.path().to_path_buf());
446        let skill_dir = workspace.path().join(".agents/skills/clear-cache-skill");
447
448        fs::create_dir_all(&skill_dir).unwrap();
449        fs::write(
450            skill_dir.join("SKILL.md"),
451            "---\nname: clear-cache-skill\ndescription: clear cache test\n---\n# Body\n",
452        )
453        .unwrap();
454
455        let first = manager.skills_metadata_lightweight_hermetic(workspace.path());
456        assert!(
457            first.skills.iter().any(|skill| skill.name == "clear-cache-skill"),
458            "expected first discovery to find test skill",
459        );
460
461        fs::remove_dir_all(&skill_dir).unwrap();
462
463        let second = manager.skills_metadata_lightweight_hermetic(workspace.path());
464        assert!(
465            second.skills.iter().any(|skill| skill.name == "clear-cache-skill"),
466            "expected cached discovery to preserve removed skill before clear_cache",
467        );
468
469        manager.clear_cache();
470
471        let third = manager.skills_metadata_lightweight_hermetic(workspace.path());
472        assert!(
473            !third.skills.iter().any(|skill| skill.name == "clear-cache-skill"),
474            "expected clear_cache to flush lightweight discovery cache",
475        );
476    }
477
478    #[test]
479    fn test_skills_metadata_lightweight() {
480        let temp_home = TempDir::new().unwrap();
481        let manager = SkillsManager::new(temp_home.path().to_path_buf());
482
483        let cwd = temp_home.path();
484
485        // Lightweight discovery should work without errors
486        let outcome = manager.skills_metadata_lightweight_hermetic(cwd);
487
488        // Should return empty outcome (no skills in temp dir)
489        // but should not crash or error
490        assert_eq!(outcome.errors.len(), 0);
491    }
492
493    #[test]
494    fn test_lightweight_vs_full_discovery() {
495        let temp_home = TempDir::new().unwrap();
496        let manager = SkillsManager::new(temp_home.path().to_path_buf());
497
498        let cwd = temp_home.path();
499
500        // Both should complete without error
501        let lightweight = manager.skills_metadata_lightweight(cwd);
502        let full = manager.skills_for_cwd(cwd);
503
504        // Lightweight discovery should find at least as many skills as full discovery
505        // (or may find more if full discovery filters some due to parse errors)
506        // but they should be in the same ballpark (within 10% difference)
507        let light_count = lightweight.skills.len() as i32;
508        let full_count = full.skills.len() as i32;
509        let diff = (light_count - full_count).abs();
510        let tolerance = (full_count / 10).max(5); // 10% tolerance or 5 items, whichever is larger
511
512        assert!(
513            diff <= tolerance,
514            "Lightweight discovery found {light_count} skills, full discovery found {full_count}. Difference {diff} exceeds tolerance {tolerance}"
515        );
516    }
517
518    #[test]
519    fn test_instruction_cache_initialization() {
520        let temp_home = TempDir::new().unwrap();
521        let manager = SkillsManager::new(temp_home.path().to_path_buf());
522
523        // Instruction cache should be empty at start
524        assert_eq!(manager.instruction_cache_size(), 0);
525
526        // Clear should work without error
527        manager.clear_instruction_cache();
528        assert_eq!(manager.instruction_cache_size(), 0);
529    }
530
531    #[test]
532    fn test_instruction_cache_max_size() {
533        let temp_home = TempDir::new().unwrap();
534        let manager = SkillsManager::new(temp_home.path().to_path_buf());
535
536        // Max size is 50, create more entries than that
537        // Note: This test is limited because we need actual SKILL.md files
538        // For now, just verify the cache respects max size in behavior
539        assert_eq!(manager.instruction_cache_size(), 0);
540
541        // Even after multiple operations, should be bounded
542        manager.clear_instruction_cache();
543        assert_eq!(manager.instruction_cache_size(), 0);
544    }
545
546    #[test]
547    fn test_instruction_cache_clear() {
548        let temp_home = TempDir::new().unwrap();
549        let manager = SkillsManager::new(temp_home.path().to_path_buf());
550
551        // Cache should start empty
552        assert_eq!(manager.instruction_cache_size(), 0);
553
554        // Clear should work
555        manager.clear_instruction_cache();
556        assert_eq!(manager.instruction_cache_size(), 0);
557    }
558
559    #[test]
560    fn test_disabled_bundled_skills_remove_stale_system_cache() {
561        let temp_home = TempDir::new().unwrap();
562        let stale_skill_dir = temp_home.path().join("skills/.system/stale-skill");
563        fs::create_dir_all(&stale_skill_dir).unwrap();
564        fs::write(stale_skill_dir.join("SKILL.md"), "# stale\n").unwrap();
565
566        let _manager = SkillsManager::new_with_bundled_skills_enabled(temp_home.path().to_path_buf(), false);
567
568        assert!(!temp_home.path().join("skills/.system").exists());
569    }
570
571    #[test]
572    fn test_disabled_bundled_skills_exclude_system_root_even_if_recreated() {
573        let temp_home = TempDir::new().unwrap();
574        let workspace = TempDir::new().unwrap();
575        let bundled_skill_dir = temp_home.path().join("skills/.system/bundled-skill");
576        fs::create_dir_all(&bundled_skill_dir).unwrap();
577        fs::write(
578            bundled_skill_dir.join("SKILL.md"),
579            "---\nname: bundled-skill\ndescription: bundled\n---\n\n# Body\n",
580        )
581        .unwrap();
582
583        let manager = SkillsManager::new_with_bundled_skills_enabled(temp_home.path().to_path_buf(), false);
584
585        fs::create_dir_all(&bundled_skill_dir).unwrap();
586        fs::write(
587            bundled_skill_dir.join("SKILL.md"),
588            "---\nname: bundled-skill\ndescription: bundled\n---\n\n# Body\n",
589        )
590        .unwrap();
591
592        let outcome = manager.skills_for_cwd(workspace.path());
593        assert!(outcome.skills.iter().all(|skill| skill.name != "bundled-skill"));
594    }
595}