Skip to main content

vtcode_skills/
types.rs

1//! Agent Skills type definitions
2//!
3//! Defines core types for Agent Skills integration, including
4//! skill metadata, manifest parsing, and resource management.
5
6use crate::limits::{
7    MAX_ALLOWED_TOOLS, MAX_COMPATIBILITY_CHARS, MAX_LICENSE_CHARS, MAX_SKILL_DESCRIPTION_CHARS, MAX_SKILL_NAME_CHARS,
8    allowed_tool_count,
9};
10use hashbrown::HashMap;
11use serde::{Deserialize, Deserializer, Serialize};
12use serde_json::Value as JsonValue;
13use std::path::PathBuf;
14
15pub use crate::model::{SkillErrorInfo, SkillMetadata, SkillScope};
16
17pub type SkillManifestMetadata = HashMap<String, JsonValue>;
18
19/// Skill variety indicating the type of skill
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
21#[serde(rename_all = "snake_case")]
22pub enum SkillVariety {
23    /// High-level instruction-based skill (Agent Skills spec)
24    #[default]
25    AgentSkill,
26    /// Low-level CLI tool bridge
27    SystemUtility,
28    /// Native VT Code functionality
29    BuiltIn,
30}
31
32impl SkillVariety {
33    /// Stable snake_case label for listings and metrics.
34    #[must_use]
35    pub fn as_str(self) -> &'static str {
36        match self {
37            SkillVariety::AgentSkill => "agent_skill",
38            SkillVariety::SystemUtility => "system_utility",
39            SkillVariety::BuiltIn => "built_in",
40        }
41    }
42}
43
44/// Network access policy for a skill
45#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
46pub struct SkillNetworkPolicy {
47    #[serde(default)]
48    pub allowed_domains: Vec<String>,
49    #[serde(default)]
50    pub denied_domains: Vec<String>,
51}
52
53/// Additional sandbox permissions requested by a skill.
54#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
55pub struct SkillPermissionProfile {
56    #[serde(
57        default,
58        skip_serializing_if = "Option::is_none",
59        deserialize_with = "deserialize_boxed_file_system_permissions_opt"
60    )]
61    pub file_system: Option<Box<SkillFileSystemPermissions>>,
62}
63
64/// Skill-scoped filesystem permission additions.
65#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
66pub struct SkillFileSystemPermissions {
67    #[serde(default, skip_serializing_if = "Vec::is_empty")]
68    pub read: Vec<PathBuf>,
69    #[serde(default, skip_serializing_if = "Vec::is_empty")]
70    pub write: Vec<PathBuf>,
71}
72
73/// Skill manifest metadata from SKILL.md frontmatter
74#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
75pub struct SkillManifest {
76    /// Unique identifier (lowercase, hyphens, max 64 chars)
77    pub name: String,
78    /// What the skill does and when to use it (max 1024 chars)
79    pub description: String,
80    /// Optional version string
81    pub version: Option<String>,
82    /// Optional default version for pinning
83    #[serde(skip_serializing_if = "Option::is_none")]
84    #[serde(rename = "default-version")]
85    #[serde(alias = "default_version")]
86    pub default_version: Option<String>,
87    /// Optional latest known version
88    #[serde(skip_serializing_if = "Option::is_none")]
89    #[serde(rename = "latest-version")]
90    #[serde(alias = "latest_version")]
91    pub latest_version: Option<String>,
92    /// Optional author name
93    pub author: Option<String>,
94    /// Optional license string for the skill
95    #[serde(skip_serializing_if = "Option::is_none")]
96    pub license: Option<String>,
97    /// Optional model preference (inherits session if unset)
98    #[serde(skip_serializing_if = "Option::is_none")]
99    pub model: Option<String>,
100    /// Marks the skill as a mode command (displayed prominently)
101    #[serde(skip_serializing_if = "Option::is_none")]
102    pub mode: Option<bool>,
103    /// Indicates if skill uses VT Code native features (not container skills)
104    #[serde(skip_serializing_if = "Option::is_none")]
105    #[serde(rename = "vtcode-native")]
106    #[serde(alias = "vtcode_native")]
107    pub vtcode_native: Option<bool>,
108    /// Space-delimited list of pre-approved tools (Agent Skills spec)
109    #[serde(skip_serializing_if = "Option::is_none")]
110    #[serde(rename = "allowed-tools")]
111    #[serde(alias = "allowed_tools")]
112    pub allowed_tools: Option<String>,
113    /// Optional guard to disable direct model invocations when skill is active
114    #[serde(skip_serializing_if = "Option::is_none")]
115    #[serde(rename = "disable-model-invocation")]
116    #[serde(alias = "disable_model_invocation")]
117    pub disable_model_invocation: Option<bool>,
118    /// Optional guidance on when to use the skill (Claude frontmatter best practice)
119    #[serde(skip_serializing_if = "Option::is_none")]
120    #[serde(rename = "when-to-use")]
121    #[serde(alias = "when_to_use")]
122    pub when_to_use: Option<String>,
123    /// Optional guidance on when NOT to use the skill
124    #[serde(skip_serializing_if = "Option::is_none")]
125    #[serde(rename = "when-not-to-use")]
126    #[serde(alias = "when_not_to_use")]
127    pub when_not_to_use: Option<String>,
128    /// Optional argument hint for slash command style usage
129    #[serde(skip_serializing_if = "Option::is_none")]
130    #[serde(rename = "argument-hint")]
131    #[serde(alias = "argument_hint")]
132    pub argument_hint: Option<String>,
133    /// Optional toggle for user menu visibility
134    #[serde(skip_serializing_if = "Option::is_none")]
135    #[serde(rename = "user-invocable")]
136    #[serde(alias = "user_invocable")]
137    pub user_invocable: Option<bool>,
138    /// Optional execution context ("fork" for isolated execution)
139    #[serde(skip_serializing_if = "Option::is_none")]
140    pub context: Option<String>,
141    /// Optional profile identifier when context is forked
142    #[serde(skip_serializing_if = "Option::is_none")]
143    pub agent: Option<String>,
144    /// Optional hooks configuration (raw payload)
145    #[serde(skip_serializing_if = "Option::is_none")]
146    pub hooks: Option<JsonValue>,
147    /// Indicates the skill explicitly requires container skills
148    #[serde(skip_serializing_if = "Option::is_none")]
149    #[serde(rename = "requires-container")]
150    #[serde(alias = "requires_container")]
151    pub requires_container: Option<bool>,
152    /// Indicates the skill should not be run inside a container (force VT Code-native path)
153    #[serde(skip_serializing_if = "Option::is_none")]
154    #[serde(rename = "disallow-container")]
155    #[serde(alias = "disallow_container")]
156    pub disallow_container: Option<bool>,
157    /// Environment/platform requirements (1-500 chars, Agent Skills spec)
158    #[serde(skip_serializing_if = "Option::is_none")]
159    pub compatibility: Option<String>,
160    /// The variety of this skill
161    #[serde(default)]
162    pub variety: SkillVariety,
163    /// Arbitrary JSON-compatible metadata (Agent Skills spec)
164    #[serde(skip_serializing_if = "Option::is_none")]
165    pub metadata: Option<SkillManifestMetadata>,
166    /// Tool dependencies for this skill (Agent Skills spec extension)
167    #[serde(skip_serializing_if = "Option::is_none")]
168    pub tools: Option<Vec<String>>,
169    /// Optional network access policy
170    #[serde(skip_serializing_if = "Option::is_none")]
171    #[serde(rename = "network")]
172    #[serde(alias = "network_policy")]
173    pub network_policy: Option<Box<SkillNetworkPolicy>>,
174    /// Optional additive sandbox permissions for command tools.
175    #[serde(
176        default,
177        skip_serializing_if = "Option::is_none",
178        alias = "permission_profile",
179        deserialize_with = "deserialize_boxed_permission_profile_opt"
180    )]
181    pub permissions: Option<Box<SkillPermissionProfile>>,
182}
183
184impl SkillPermissionProfile {
185    fn is_empty(&self) -> bool {
186        self.file_system.is_none()
187    }
188
189    fn into_boxed_if_non_empty(self) -> Option<Box<Self>> {
190        (!self.is_empty()).then_some(Box::new(self))
191    }
192}
193
194impl SkillFileSystemPermissions {
195    fn is_empty(&self) -> bool {
196        self.read.is_empty() && self.write.is_empty()
197    }
198
199    fn into_boxed_if_non_empty(self) -> Option<Box<Self>> {
200        (!self.is_empty()).then_some(Box::new(self))
201    }
202}
203
204fn deserialize_boxed_permission_profile_opt<'de, D>(
205    deserializer: D,
206) -> Result<Option<Box<SkillPermissionProfile>>, D::Error>
207where
208    D: Deserializer<'de>,
209{
210    Option::<SkillPermissionProfile>::deserialize(deserializer)
211        .map(|value| value.and_then(SkillPermissionProfile::into_boxed_if_non_empty))
212}
213
214fn deserialize_boxed_file_system_permissions_opt<'de, D>(
215    deserializer: D,
216) -> Result<Option<Box<SkillFileSystemPermissions>>, D::Error>
217where
218    D: Deserializer<'de>,
219{
220    Option::<SkillFileSystemPermissions>::deserialize(deserializer)
221        .map(|value| value.and_then(SkillFileSystemPermissions::into_boxed_if_non_empty))
222}
223
224impl Default for SkillManifest {
225    fn default() -> Self {
226        Self {
227            name: String::new(),
228            description: String::new(),
229            version: None,
230            default_version: None,
231            latest_version: None,
232            author: None,
233            license: None,
234            model: None,
235            mode: None,
236            vtcode_native: None,
237            allowed_tools: None,
238            disable_model_invocation: None,
239            when_to_use: None,
240            when_not_to_use: None,
241            argument_hint: None,
242            user_invocable: None,
243            context: None,
244            agent: None,
245            hooks: None,
246            requires_container: None,
247            disallow_container: None,
248            compatibility: None,
249            variety: SkillVariety::AgentSkill,
250            metadata: None,
251            tools: None,
252            network_policy: None,
253            permissions: None,
254        }
255    }
256}
257
258impl SkillManifest {
259    /// Validate manifest against the Agent Skills specification.
260    pub fn validate(&self) -> anyhow::Result<()> {
261        self.validate_name()?;
262        self.validate_description()?;
263        self.validate_optional_fields()?;
264        Ok(())
265    }
266
267    /// Validate name field per Agent Skills spec
268    fn validate_name(&self) -> anyhow::Result<()> {
269        if self.name.is_empty() {
270            anyhow::bail!("name is required and must not be empty");
271        }
272
273        if self.name.len() > MAX_SKILL_NAME_CHARS {
274            anyhow::bail!("name exceeds maximum length: {} characters (max {MAX_SKILL_NAME_CHARS})", self.name.len());
275        }
276
277        // Check for lowercase letters, numbers, and hyphens only
278        if !self.name.chars().all(|c| c.is_lowercase() || c.is_numeric() || c == '-') {
279            anyhow::bail!(
280                "name contains invalid characters: '{}'\nMust contain only lowercase letters, numbers, and hyphens",
281                self.name
282            );
283        }
284
285        // Check for consecutive hyphens
286        if self.name.contains("--") {
287            anyhow::bail!("name contains consecutive hyphens: '{}'\nHyphens must not appear consecutively", self.name);
288        }
289
290        // Check for leading hyphen
291        if self.name.starts_with('-') {
292            anyhow::bail!("name starts with hyphen: '{}'\nMust not start with a hyphen", self.name);
293        }
294
295        // Check for trailing hyphen
296        if self.name.ends_with('-') {
297            anyhow::bail!("name ends with hyphen: '{}'\nMust not end with a hyphen", self.name);
298        }
299
300        // Check for reserved words
301        if self.name.contains("anthropic") || self.name.contains("claude") {
302            anyhow::bail!("name contains reserved word: '{}'\nMust not contain 'anthropic' or 'claude'", self.name);
303        }
304
305        Ok(())
306    }
307
308    /// Validate description field per Agent Skills spec
309    fn validate_description(&self) -> anyhow::Result<()> {
310        if self.description.is_empty() {
311            anyhow::bail!("description is required and must not be empty");
312        }
313
314        if self.description.len() > MAX_SKILL_DESCRIPTION_CHARS {
315            anyhow::bail!(
316                "description exceeds maximum length: {} characters (max {MAX_SKILL_DESCRIPTION_CHARS})",
317                self.description.len()
318            );
319        }
320
321        Ok(())
322    }
323
324    /// Validate optional fields per the strict SKILL.md spec supported by VT Code.
325    fn validate_optional_fields(&self) -> anyhow::Result<()> {
326        if self.hooks.is_some() {
327            anyhow::bail!("hooks are not supported in VT Code skills");
328        }
329
330        // Validate allowed-tools field
331        if let Some(allowed_tools) = &self.allowed_tools {
332            let tool_count = allowed_tool_count(allowed_tools);
333
334            if tool_count > MAX_ALLOWED_TOOLS {
335                anyhow::bail!("allowed-tools exceeds maximum tool count: {tool_count} tools (max {MAX_ALLOWED_TOOLS})");
336            }
337
338            if tool_count == 0 {
339                anyhow::bail!("allowed-tools must not be empty if specified");
340            }
341        }
342
343        // Validate license field
344        if let Some(license) = &self.license
345            && license.len() > MAX_LICENSE_CHARS
346        {
347            anyhow::bail!("license exceeds maximum length: {} characters (max {MAX_LICENSE_CHARS})", license.len());
348        }
349
350        // Validate compatibility field
351        if let Some(compatibility) = &self.compatibility
352            && (compatibility.is_empty() || compatibility.len() > MAX_COMPATIBILITY_CHARS)
353        {
354            anyhow::bail!(
355                "compatibility must be between 1-{MAX_COMPATIBILITY_CHARS} characters if provided, got {} characters",
356                compatibility.len()
357            );
358        }
359
360        Ok(())
361    }
362
363    /// Validate that the skill's own directory name matches the manifest name.
364    ///
365    /// Accepts either the skill directory or its `SKILL.md` path; the path is
366    /// resolved to the skill directory first so the check can never compare
367    /// against the wrong (parent) directory. This is a requirement per the
368    /// Agent Skills specification.
369    pub(crate) fn validate_directory_name_match(&self, skill_path: &std::path::Path) -> anyhow::Result<()> {
370        let skill_dir = resolve_skill_dir(skill_path);
371
372        // For CLI tools, the directory name might not match the skill name.
373        // Check if this is a CLI tool by looking for tool.json.
374        if skill_dir.join("tool.json").exists() {
375            return Ok(());
376        }
377
378        let dir_name = skill_dir
379            .file_name()
380            .and_then(|name| name.to_str())
381            .ok_or_else(|| anyhow::anyhow!("Cannot extract directory name from: {skill_dir:?}"))?;
382
383        if dir_name != self.name {
384            anyhow::bail!(
385                "Skill name '{}' does not match directory name '{}'\nPer Agent Skills spec, the name field must match the skill's directory name",
386                self.name,
387                dir_name
388            );
389        }
390
391        Ok(())
392    }
393}
394
395/// Resolve the skill's own directory from either the skill directory or its
396/// `SKILL.md` path.
397///
398/// The Agent Skills spec requires the manifest `name` to match the skill's
399/// directory, and file references resolve against that directory. A `SKILL.md`
400/// path must therefore be reduced to its parent, while a directory path is
401/// returned unchanged (reducing it would yield the wrong grandparent).
402pub(crate) fn resolve_skill_dir(skill_path: &std::path::Path) -> &std::path::Path {
403    match skill_path.file_name().and_then(|name| name.to_str()) {
404        Some("SKILL.md") => skill_path.parent().unwrap_or(skill_path),
405        _ => skill_path,
406    }
407}
408
409/// Resource types bundled with a skill
410#[derive(Debug, Clone, PartialEq, Eq)]
411pub enum ResourceType {
412    /// Markdown documentation or additional instructions
413    Markdown,
414    /// Executable script (Python, Shell, etc.)
415    Script,
416    /// Reference data (JSON, schemas, templates, etc.)
417    Reference,
418    /// Static assets (images, data files, templates)
419    Asset,
420    /// Other resource types
421    Other(String),
422}
423
424/// A skill resource (Level 3: on-demand loading)
425#[derive(Debug, Clone)]
426pub struct SkillResource {
427    /// Relative path within skill directory
428    pub path: String,
429    /// Content type
430    pub resource_type: ResourceType,
431    /// Cached content (None until loaded)
432    pub content: Option<Vec<u8>>,
433}
434
435/// Complete skill definition with progressive disclosure levels
436#[derive(Debug, Clone)]
437pub struct Skill {
438    /// Level 1: Metadata (~100 tokens, always loaded)
439    pub manifest: SkillManifest,
440
441    /// Absolute path to skill directory
442    pub path: PathBuf,
443
444    /// Skill scope (user-level or repo-level)
445    pub scope: SkillScope,
446
447    /// Level 2: Instructions from SKILL.md body (<5K tokens, loaded when triggered)
448    pub instructions: String,
449
450    /// Skill variety
451    pub variety: SkillVariety,
452
453    /// Level 3: Bundled resources (lazy-loaded on demand)
454    resources: HashMap<String, SkillResource>,
455}
456
457impl Skill {
458    /// Create a new skill
459    pub fn new(manifest: SkillManifest, path: PathBuf, instructions: String) -> anyhow::Result<Self> {
460        manifest.validate()?;
461        let path_str = path.to_string_lossy();
462        let scope = if path.starts_with(PathBuf::from("/etc/codex/skills")) {
463            SkillScope::Admin
464        } else if path_str.contains("/skills/.system/")
465            || path_str.ends_with("/skills/.system")
466            || path_str.contains("\\skills\\.system\\")
467        {
468            SkillScope::System
469        } else if path_str.contains("/.agents/skills/") || path_str.contains("\\.agents\\skills\\") {
470            SkillScope::Repo
471        } else {
472            SkillScope::User
473        };
474        Ok(Skill {
475            variety: manifest.variety,
476            manifest,
477            path,
478            scope,
479            instructions,
480            resources: HashMap::new(),
481        })
482    }
483
484    /// Create a new skill with explicit scope
485    pub fn with_scope(
486        manifest: SkillManifest,
487        path: PathBuf,
488        scope: SkillScope,
489        instructions: String,
490    ) -> anyhow::Result<Self> {
491        manifest.validate()?;
492        Ok(Skill {
493            variety: manifest.variety,
494            manifest,
495            path,
496            scope,
497            instructions,
498            resources: HashMap::new(),
499        })
500    }
501
502    /// Add a resource to the skill
503    pub fn add_resource(&mut self, path: String, resource: SkillResource) {
504        self.resources.insert(path, resource);
505    }
506
507    /// Get skill's display name
508    pub fn name(&self) -> &str {
509        &self.manifest.name
510    }
511
512    /// Get skill's description
513    pub fn description(&self) -> &str {
514        &self.manifest.description
515    }
516
517    /// Estimate token count for instructions (approximate)
518    fn instruction_tokens(&self) -> usize {
519        // Rough estimate: ~1 token per 4 characters
520        self.instructions.len() / 4
521    }
522
523    /// Check if skill has a resource
524    pub fn has_resource(&self, path: &str) -> bool {
525        self.resources.contains_key(path)
526    }
527
528    /// Get resource by path
529    pub fn get_resource(&self, path: &str) -> Option<&SkillResource> {
530        self.resources.get(path)
531    }
532
533    /// List all available resources
534    pub fn list_resources(&self) -> Vec<&str> {
535        self.resources.keys().map(|s| s.as_str()).collect()
536    }
537}
538
539/// Progressive disclosure context for skill loading
540#[derive(Debug, Clone)]
541pub enum SkillContext {
542    /// Level 1: Only metadata (~100 tokens)
543    MetadataOnly(SkillManifest, PathBuf),
544    /// Level 2: Metadata + instructions (<5K tokens)
545    WithInstructions(Skill),
546    /// Level 3: Full skill with resources loaded
547    Full(Skill),
548}
549
550impl SkillContext {
551    /// Get manifest from any context level
552    pub fn manifest(&self) -> &SkillManifest {
553        match self {
554            SkillContext::MetadataOnly(m, _) => m,
555            SkillContext::WithInstructions(s) => &s.manifest,
556            SkillContext::Full(s) => &s.manifest,
557        }
558    }
559
560    /// Get path from any context level
561    pub fn path(&self) -> &PathBuf {
562        match self {
563            SkillContext::MetadataOnly(_, p) => p,
564            SkillContext::WithInstructions(s) => &s.path,
565            SkillContext::Full(s) => &s.path,
566        }
567    }
568
569    /// Get skill (requires Level 2+)
570    pub fn skill(&self) -> Option<&Skill> {
571        match self {
572            SkillContext::MetadataOnly(_, _) => None,
573            SkillContext::WithInstructions(s) => Some(s),
574            SkillContext::Full(s) => Some(s),
575        }
576    }
577
578    /// Estimated tokens consumed in system prompt
579    fn tokens(&self) -> usize {
580        match self {
581            SkillContext::MetadataOnly(_, _) => 100,
582            SkillContext::WithInstructions(s) => 100 + s.instruction_tokens(),
583            SkillContext::Full(s) => 100 + s.instruction_tokens() + (s.resources.len() * 50),
584        }
585    }
586}
587
588/// Skill registry entry (loaded skill + metadata)
589#[derive(Debug, Clone)]
590pub struct SkillRegistryEntry {
591    skill: Skill,
592    enabled: bool,
593    load_time: std::time::SystemTime,
594}
595
596#[cfg(test)]
597mod tests {
598    use super::*;
599
600    #[test]
601    fn test_manifest_validation_valid() {
602        let m = SkillManifest {
603            name: "my-skill".to_string(),
604            description: "A test skill".to_string(),
605            ..Default::default()
606        };
607        m.validate().unwrap();
608    }
609
610    #[test]
611    fn test_manifest_validation_invalid_name_length() {
612        let m = SkillManifest {
613            name: "a".repeat(65),
614            description: "Valid description".to_string(),
615            ..Default::default()
616        };
617        assert!(m.validate().is_err());
618    }
619
620    #[test]
621    fn test_manifest_validation_reserved_word() {
622        let m = SkillManifest {
623            name: "anthropic-skill".to_string(),
624            description: "Valid description".to_string(),
625            ..Default::default()
626        };
627        assert!(m.validate().is_err());
628    }
629
630    #[test]
631    fn test_skill_context_tokens() {
632        let manifest = SkillManifest {
633            name: "test".to_string(),
634            description: "Test".to_string(),
635            ..Default::default()
636        };
637
638        let meta_ctx = SkillContext::MetadataOnly(manifest.clone(), PathBuf::from("/test"));
639        assert_eq!(meta_ctx.tokens(), 100);
640    }
641
642    #[test]
643    fn test_compatibility_validation() {
644        // Valid compatibility
645        let m = SkillManifest {
646            name: "test-skill".to_string(),
647            description: "Test description".to_string(),
648            compatibility: Some("Designed for VT Code".to_string()),
649            ..Default::default()
650        };
651        m.validate().unwrap();
652
653        // Invalid: empty compatibility
654        let m = SkillManifest {
655            name: "test-skill".to_string(),
656            description: "Test description".to_string(),
657            compatibility: Some("".to_string()),
658            ..Default::default()
659        };
660        assert!(m.validate().is_err());
661
662        // Invalid: too long (> 500 chars)
663        let m = SkillManifest {
664            name: "test-skill".to_string(),
665            description: "Test description".to_string(),
666            compatibility: Some("a".repeat(501)),
667            ..Default::default()
668        };
669        assert!(m.validate().is_err());
670    }
671
672    /// The strict validator and the comprehensive validator must reject the
673    /// same inputs at every shared limit. Asserting the boundary on both sides
674    /// is what catches a limit changed in one validator but not the other —
675    /// the regression the shared `limits` constants exist to prevent.
676    #[test]
677    fn strict_and_comprehensive_validators_agree_at_every_limit() {
678        use crate::enhanced_validator::ComprehensiveSkillValidator;
679        use crate::limits::{
680            MAX_COMPATIBILITY_CHARS, MAX_LICENSE_CHARS, MAX_SKILL_DESCRIPTION_CHARS, MAX_SKILL_NAME_CHARS,
681        };
682
683        let validator = ComprehensiveSkillValidator::new();
684        // (case, manifest, expected to be valid)
685        let boundary_cases = [
686            ("name at limit", "a".repeat(MAX_SKILL_NAME_CHARS), true),
687            ("name over limit", "a".repeat(MAX_SKILL_NAME_CHARS + 1), false),
688            ("description at limit", "a".repeat(MAX_SKILL_DESCRIPTION_CHARS), true),
689            ("description over limit", "a".repeat(MAX_SKILL_DESCRIPTION_CHARS + 1), false),
690        ];
691
692        for (label, value, expect_valid) in boundary_cases {
693            let (name, description) = if label.starts_with("name") {
694                (value, "A valid description for the skill.".to_string())
695            } else {
696                ("valid-name".to_string(), value)
697            };
698            let manifest = SkillManifest { name, description, ..Default::default() };
699
700            assert_eq!(manifest.validate().is_ok(), expect_valid, "strict validator disagreed on {label}");
701            let report = validator.validate_manifest(&manifest, std::path::Path::new("/tmp/nonexistent"));
702            assert_eq!(report.is_valid, expect_valid, "comprehensive validator disagreed on {label}");
703        }
704
705        // Optional string fields: same at-limit / over-limit pairing.
706        for (label, build, expect_valid) in [
707            ("license at limit", (Some("a".repeat(MAX_LICENSE_CHARS)), None::<String>), true),
708            ("license over limit", (Some("a".repeat(MAX_LICENSE_CHARS + 1)), None::<String>), false),
709            ("compatibility at limit", (None, Some("a".repeat(MAX_COMPATIBILITY_CHARS))), true),
710            ("compatibility over limit", (None, Some("a".repeat(MAX_COMPATIBILITY_CHARS + 1))), false),
711        ] {
712            let manifest = SkillManifest {
713                name: "valid-name".to_string(),
714                description: "A valid description for the skill.".to_string(),
715                license: build.0,
716                compatibility: build.1,
717                ..Default::default()
718            };
719            assert_eq!(manifest.validate().is_ok(), expect_valid, "strict validator disagreed on {label}");
720            let report = validator.validate_manifest(&manifest, std::path::Path::new("/tmp/nonexistent"));
721            assert_eq!(report.is_valid, expect_valid, "comprehensive validator disagreed on {label}");
722        }
723    }
724
725    #[test]
726    fn test_allowed_tools_string_format() {
727        // Valid space-delimited string
728        let m = SkillManifest {
729            name: "test-skill".to_string(),
730            description: "Test description".to_string(),
731            allowed_tools: Some("Read Write Bash".to_string()),
732            ..Default::default()
733        };
734        m.validate().unwrap();
735
736        // Invalid: empty string
737        let m = SkillManifest {
738            name: "test-skill".to_string(),
739            description: "Test description".to_string(),
740            allowed_tools: Some("".to_string()),
741            ..Default::default()
742        };
743        assert!(m.validate().is_err());
744
745        // Invalid: too many tools (> 16)
746        let tools = (0..17).map(|i| format!("Tool{i}")).collect::<Vec<_>>().join(" ");
747        let m = SkillManifest {
748            name: "test-skill".to_string(),
749            description: "Test description".to_string(),
750            allowed_tools: Some(tools),
751            ..Default::default()
752        };
753        assert!(m.validate().is_err());
754    }
755
756    /// `allowed_tool_count` is the single rule both validators read, so pin the
757    /// exact limit it enforces rather than just "17 fails": 16 must pass, 17
758    /// must fail, and extra whitespace must not change the count.
759    #[test]
760    fn allowed_tool_limit_is_inclusive_of_sixteen() {
761        let manifest_with = |tools: String| SkillManifest {
762            name: "test-skill".to_string(),
763            description: "Test description".to_string(),
764            allowed_tools: Some(tools),
765            ..Default::default()
766        };
767
768        assert_eq!(allowed_tool_count("Read Write Bash"), 3);
769        assert_eq!(allowed_tool_count("  Read   Write  "), 2);
770        assert_eq!(allowed_tool_count(""), 0);
771        assert_eq!(allowed_tool_count("   \t\n "), 0);
772
773        let at_limit = (0..MAX_ALLOWED_TOOLS).map(|i| format!("Tool{i}")).collect::<Vec<_>>().join(" ");
774        assert_eq!(allowed_tool_count(&at_limit), MAX_ALLOWED_TOOLS);
775        manifest_with(at_limit).validate().expect("16 tools is the inclusive limit");
776
777        let over_limit = (0..=MAX_ALLOWED_TOOLS)
778            .map(|i| format!("Tool{i}"))
779            .collect::<Vec<_>>()
780            .join(" ");
781        assert_eq!(allowed_tool_count(&over_limit), MAX_ALLOWED_TOOLS + 1);
782        manifest_with(over_limit).validate().expect_err("17 tools exceeds the limit");
783    }
784
785    #[test]
786    fn test_hooks_rejected() {
787        let m = SkillManifest {
788            name: "test-skill".to_string(),
789            description: "Test description".to_string(),
790            hooks: Some(serde_json::json!({
791                "pre_tool_use": [
792                    { "command": "echo pre" }
793                ]
794            })),
795            ..Default::default()
796        };
797        assert!(m.validate().is_err());
798    }
799
800    #[test]
801    fn test_metadata_field() {
802        let mut metadata = HashMap::new();
803        metadata.insert("author".to_string(), serde_json::json!("Test Author"));
804        metadata.insert("version".to_string(), serde_json::json!("1.0.0"));
805
806        let m = SkillManifest {
807            name: "test-skill".to_string(),
808            description: "Test description".to_string(),
809            version: Some("1.0.0".to_string()),
810            author: Some("Test Author".to_string()),
811            metadata: Some(metadata),
812            tools: None,
813            ..Default::default()
814        };
815        m.validate().unwrap();
816    }
817
818    #[test]
819    fn empty_permissions_deserialize_to_none() {
820        let manifest: SkillManifest = serde_json::from_str(
821            r#"{
822                "name": "test-skill",
823                "description": "Test description",
824                "permissions": {},
825                "network": {}
826            }"#,
827        )
828        .expect("manifest should deserialize");
829
830        assert!(manifest.permissions.is_none());
831        assert!(manifest.network_policy.is_some());
832    }
833
834    #[test]
835    fn empty_file_system_permissions_deserialize_to_none() {
836        let manifest: SkillManifest = serde_json::from_str(
837            r#"{
838                "name": "test-skill",
839                "description": "Test description",
840                "permissions": {
841                    "file_system": {}
842                }
843            }"#,
844        )
845        .expect("manifest should deserialize");
846
847        assert!(manifest.permissions.is_none());
848    }
849
850    #[test]
851    fn boxed_skill_fields_are_smaller_than_inline_options() {
852        use std::mem::size_of;
853
854        assert!(size_of::<Option<Box<SkillNetworkPolicy>>>() < size_of::<Option<SkillNetworkPolicy>>());
855        assert!(size_of::<Option<Box<SkillPermissionProfile>>>() < size_of::<Option<SkillPermissionProfile>>());
856        assert!(size_of::<Option<Box<SkillFileSystemPermissions>>>() < size_of::<Option<SkillFileSystemPermissions>>());
857    }
858
859    #[test]
860    fn skill_variety_labels_match_serde_snake_case() {
861        assert_eq!(SkillVariety::AgentSkill.as_str(), "agent_skill");
862        assert_eq!(SkillVariety::SystemUtility.as_str(), "system_utility");
863        assert_eq!(SkillVariety::BuiltIn.as_str(), "built_in");
864    }
865}