Skip to main content

vtcode_core/skills/loader/
enhanced.rs

1use std::path::{Path, PathBuf};
2
3use anyhow::Result;
4
5use super::SkillLoaderConfig;
6use super::discovery::{find_git_root, skill_roots_with_home_dir};
7use crate::skills::cli_bridge::CliToolBridge;
8use crate::skills::command_skills::{
9    BuiltInCommandSkill, CommandSkillBackend, built_in_command_skill, find_command_skill_by_skill_name,
10    merge_built_in_command_skill_contexts,
11};
12use crate::skills::container_validation::{
13    ContainerSkillsValidator, ContainerValidationReport, ContainerValidationResult,
14};
15use crate::skills::discovery::{DiscoveryConfig, DiscoveryResult, SkillDiscovery};
16use crate::skills::model::SkillScope;
17use crate::skills::system::{install_system_skills, system_cache_root_dir};
18use crate::skills::types::{Skill, SkillContext};
19use crate::tools::error_messages::skill_ops;
20
21/// Enhanced skill variant for unified handling
22pub enum EnhancedSkill {
23    /// Traditional instruction-based skill
24    Traditional(Box<Skill>),
25    /// CLI-based tool skill
26    CliTool(Box<CliToolBridge>),
27    /// Built-in VT Code command skill
28    BuiltInCommand(Box<BuiltInCommandSkill>),
29    /// Native code plugin skill reserved for explicitly gated integrations
30    NativePlugin(Box<dyn crate::skills::native_plugin::NativePluginTrait>),
31}
32
33impl std::fmt::Debug for EnhancedSkill {
34    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
35        match self {
36            Self::Traditional(skill) => f.debug_tuple("Traditional").field(skill).finish(),
37            Self::CliTool(tool) => f.debug_tuple("CliTool").field(tool).finish(),
38            Self::BuiltInCommand(skill) => f.debug_tuple("BuiltInCommand").field(skill).finish(),
39            Self::NativePlugin(plugin) => f.debug_tuple("NativePlugin").field(plugin).finish(),
40        }
41    }
42}
43
44/// High-level loader that provides discovery and validation features
45pub struct EnhancedSkillLoader {
46    workspace_root: PathBuf,
47    codex_home: PathBuf,
48    discovery: SkillDiscovery,
49    include_bundled_system_skills: bool,
50}
51
52fn default_codex_home() -> PathBuf {
53    // Unified VT Code home, never another tool's directory. An unresolvable
54    // home yields an empty path that install/uninstall refuse and discovery
55    // skips (callers force `include_bundled_system_skills` off with it).
56    crate::skills::system::bundled_skills_home().unwrap_or_default()
57}
58
59/// Whether `home` came from a successful unified-home resolution.
60fn home_is_usable(home: &Path) -> bool {
61    !home.as_os_str().is_empty() && home.is_absolute()
62}
63
64pub(crate) fn discovery_config_for_codex_home(
65    workspace_root: &Path,
66    codex_home: &Path,
67    include_bundled_system_skills: bool,
68) -> DiscoveryConfig {
69    let home_dir = dirs::home_dir();
70    let loader_config = SkillLoaderConfig {
71        codex_home: codex_home.to_path_buf(),
72        cwd: workspace_root.to_path_buf(),
73        project_root: find_git_root(workspace_root),
74        include_bundled_system_skills,
75    };
76    let roots = skill_roots_with_home_dir(&loader_config, home_dir.as_deref());
77
78    DiscoveryConfig {
79        skill_paths: roots
80            .iter()
81            .filter(|root| !root.is_tool_root && !root.is_plugin_root)
82            .map(|root| root.path.clone())
83            .collect(),
84        tool_paths: roots
85            .iter()
86            .filter(|root| root.is_tool_root)
87            .map(|root| root.path.clone())
88            .collect(),
89        ..Default::default()
90    }
91}
92
93impl EnhancedSkillLoader {
94    /// Create a new enhanced loader for workspace.
95    ///
96    /// Bundled system skills resolve to the unified VT Code home and are
97    /// installed/discovered only when ask-first consent permits.
98    pub fn new(workspace_root: PathBuf) -> Self {
99        let permitted = crate::skills::bundled_skills_install_permitted_for_workspace(&workspace_root);
100        let codex_home = default_codex_home();
101        let include_bundled_system_skills = permitted && home_is_usable(&codex_home);
102        let discovery = SkillDiscovery::with_config(discovery_config_for_codex_home(
103            &workspace_root,
104            &codex_home,
105            include_bundled_system_skills,
106        ));
107        Self {
108            workspace_root,
109            codex_home,
110            discovery,
111            include_bundled_system_skills,
112        }
113    }
114
115    /// Create a loader pinned to a specific home directory.
116    ///
117    /// The override changes the install/discovery location (hermetic tests,
118    /// benchmarks) but never the permission: consent is still consulted.
119    pub fn with_codex_home(workspace_root: PathBuf, codex_home: PathBuf) -> Self {
120        let permitted = crate::skills::bundled_skills_install_permitted_for_workspace(&workspace_root);
121        let include_bundled_system_skills = permitted && home_is_usable(&codex_home);
122        let discovery = SkillDiscovery::with_config(discovery_config_for_codex_home(
123            &workspace_root,
124            &codex_home,
125            include_bundled_system_skills,
126        ));
127        Self {
128            workspace_root,
129            codex_home,
130            discovery,
131            include_bundled_system_skills,
132        }
133    }
134
135    fn ensure_system_skills_installed(&self) {
136        if !self.include_bundled_system_skills {
137            return;
138        }
139        if let Err(err) = install_system_skills(&self.codex_home) {
140            tracing::warn!("enhanced skill loader failed to install bundled system skills: {err}");
141        }
142    }
143
144    /// Discover all available skills and tools
145    pub async fn discover_all_skills(&mut self) -> Result<DiscoveryResult> {
146        self.ensure_system_skills_installed();
147        let mut result = self.discovery.discover_all(&self.workspace_root).await?;
148        merge_built_in_command_skill_contexts(&mut result.skills);
149        Ok(result)
150    }
151
152    /// Get a specific skill by name
153    pub async fn get_skill(&mut self, name: &str) -> Result<EnhancedSkill> {
154        self.ensure_system_skills_installed();
155        let result = self.discovery.discover_all(&self.workspace_root).await?;
156
157        // Try traditional skills first. Command skills (`cmd-*` with a bundled
158        // `.system` contract) prefer the System copy so a stale workspace
159        // shadow cannot break `/review` free-form + fix-mode behavior.
160        if let Some(skill_ctx) = select_traditional_skill_ctx(&result.skills, name, &self.workspace_root) {
161            let path = skill_ctx.path();
162            let (manifest, instructions) = crate::skills::manifest::parse_skill_file(path)?;
163            let skill = Skill::with_scope(
164                manifest,
165                path.clone(),
166                infer_scope_from_skill_path(path, &self.workspace_root),
167                instructions,
168            )?;
169            return Ok(EnhancedSkill::Traditional(Box::new(skill)));
170        }
171
172        // Try CLI tools
173        for tool_config in &result.tools {
174            if tool_config.name == name {
175                let bridge = CliToolBridge::new(tool_config.clone())?;
176                return Ok(EnhancedSkill::CliTool(Box::new(bridge)));
177            }
178        }
179
180        if let Some(skill) = built_in_command_skill(name) {
181            return Ok(EnhancedSkill::BuiltInCommand(Box::new(skill)));
182        }
183
184        // Native plugins are intentionally not loaded by the generic skill
185        // lookup. Opening a dynamic library executes arbitrary native code
186        // before this loader can inspect its metadata, so native loading must
187        // remain an explicit, separately-gated operation.
188        if crate::skills::system::bundled_skill_names().contains(&name) {
189            return Err(anyhow::anyhow!(crate::config::consent::bundled_skill_missing_hint(name)));
190        }
191        Err(skill_ops::skill_not_found_error(name))
192    }
193
194    /// Generate a comprehensive container validation report
195    pub async fn generate_validation_report(&mut self) -> Result<ContainerValidationReport> {
196        let result = self.discovery.discover_all(&self.workspace_root).await?;
197        let mut report = ContainerValidationReport::new();
198        let validator = ContainerSkillsValidator::new();
199
200        for skill_ctx in &result.skills {
201            match self.load_full_skill_from_ctx(skill_ctx) {
202                Ok(skill) => {
203                    let analysis = validator.analyze_skill(&skill);
204                    report.add_skill_analysis(skill.name().to_string(), analysis);
205                }
206                Err(e) => {
207                    report.add_incompatible_skill(
208                        skill_ctx.manifest().name.clone(),
209                        skill_ctx.manifest().description.clone(),
210                        format!("Load error: {e}"),
211                    );
212                }
213            }
214        }
215
216        report.finalize();
217        Ok(report)
218    }
219
220    /// Check container requirements for a skill
221    pub fn check_container_requirements(&self, skill: &Skill) -> ContainerValidationResult {
222        let validator = ContainerSkillsValidator::new();
223        validator.analyze_skill(skill)
224    }
225
226    fn load_full_skill_from_ctx(&self, ctx: &SkillContext) -> Result<Skill> {
227        let path = ctx.path();
228        let (manifest, instructions) = crate::skills::manifest::parse_skill_file(path)?;
229        Skill::with_scope(manifest, path.clone(), infer_scope_from_skill_path(path, &self.workspace_root), instructions)
230    }
231}
232
233fn infer_scope_from_skill_path(path: &Path, workspace_root: &Path) -> SkillScope {
234    if path.starts_with(Path::new("/etc/codex/skills")) {
235        return SkillScope::Admin;
236    }
237    if crate::skills::system::bundled_skills_home().is_ok_and(|home| path.starts_with(system_cache_root_dir(&home))) {
238        return SkillScope::System;
239    }
240    if let Some(home) = dirs::home_dir()
241        && path.starts_with(home.join(".agents/skills"))
242    {
243        return SkillScope::User;
244    }
245    if path.starts_with(workspace_root) {
246        return SkillScope::Repo;
247    }
248
249    // Fallback for non-canonicalized paths: walk the components looking for a
250    // `.agents/skills` ancestor. Uses proper component matching rather than
251    // string-contains so a directory named `skills-backup` cannot trigger a
252    // false positive.
253    if has_agents_skills_ancestor(path) {
254        return SkillScope::Repo;
255    }
256
257    SkillScope::User
258}
259
260fn has_agents_skills_ancestor(path: &Path) -> bool {
261    let mut ancestors = path.parent().map(Path::new).into_iter().peekable();
262    while let Some(current) = ancestors.next() {
263        let is_skills = current.file_name().and_then(|f| f.to_str()) == Some("skills");
264        let parent_is_agents = ancestors.peek().and_then(|p| p.file_name().and_then(|f| f.to_str())) == Some(".agents");
265        if is_skills && parent_is_agents {
266            return true;
267        }
268    }
269    false
270}
271
272fn is_bundled_command_skill(name: &str) -> bool {
273    find_command_skill_by_skill_name(name)
274        .is_some_and(|spec| matches!(spec.backend, CommandSkillBackend::TraditionalSkill { .. }))
275}
276
277fn is_system_skill_path(path: &Path) -> bool {
278    let mut components = path.components().peekable();
279    while let Some(component) = components.next() {
280        let is_skills = component.as_os_str() == "skills";
281        let next_is_system = components.peek().is_some_and(|next| next.as_os_str() == ".system");
282        if is_skills && next_is_system {
283            return true;
284        }
285    }
286    false
287}
288
289pub(crate) fn select_traditional_skill_ctx<'a>(
290    skills: &'a [SkillContext],
291    name: &str,
292    workspace_root: &Path,
293) -> Option<&'a SkillContext> {
294    let mut first_match: Option<&'a SkillContext> = None;
295    let mut system_match: Option<&'a SkillContext> = None;
296    for skill_ctx in skills {
297        if skill_ctx.manifest().name != name {
298            continue;
299        }
300        if first_match.is_none() {
301            first_match = Some(skill_ctx);
302        }
303        // Shape-based system detection covers custom `CODEX_HOME` values where
304        // `infer_scope_from_skill_path` falls back to `User`. Exclude `Repo`
305        // scope so a workspace-nested `skills/.system` path cannot spoof it.
306        let scope = infer_scope_from_skill_path(skill_ctx.path(), workspace_root);
307        if system_match.is_none()
308            && (scope == SkillScope::System || (scope != SkillScope::Repo && is_system_skill_path(skill_ctx.path())))
309        {
310            system_match = Some(skill_ctx);
311        }
312        if first_match.is_some() && system_match.is_some() {
313            break;
314        }
315    }
316    if is_bundled_command_skill(name) {
317        system_match.or(first_match)
318    } else {
319        first_match
320    }
321}