Skip to main content

vtcode_skills/
manifest.rs

1//! SKILL.md manifest parsing
2//!
3//! Parses YAML frontmatter from SKILL.md files to extract skill metadata and instructions.
4
5use crate::file_references::FileReferenceValidator;
6use crate::types::{SkillManifest, SkillManifestMetadata};
7use anyhow::Context;
8use serde::{Deserialize, Deserializer, Serialize};
9use serde_json::Value as JsonValue;
10use std::fs;
11use std::path::Path;
12
13/// Supported YAML frontmatter keys for SKILL.md validation.
14pub(crate) const SUPPORTED_FRONTMATTER_KEYS: &[&str] = &[
15    "name",
16    "description",
17    "license",
18    "allowed-tools",
19    "argument-hint",
20    "disable-model-invocation",
21    "compatibility",
22    "hooks",
23    "metadata",
24];
25
26/// Coerce `argument-hint` to a string.
27///
28/// Claude Code coerces non-string values (e.g. YAML sequences such as
29/// `[topic: foo | bar]`) to a string instead of failing; match that so
30/// third-party skills do not fail to parse here.
31fn deserialize_argument_hint_opt<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
32where
33    D: Deserializer<'de>,
34{
35    let value = Option::<JsonValue>::deserialize(deserializer)?;
36    Ok(value.and_then(|value| match value {
37        JsonValue::Null => None,
38        JsonValue::String(s) => Some(s),
39        JsonValue::Bool(b) => Some(b.to_string()),
40        JsonValue::Number(n) => Some(n.to_string()),
41        JsonValue::Array(items) => {
42            let parts: Vec<String> = items
43                .into_iter()
44                .filter_map(|item| match item {
45                    JsonValue::Null => None,
46                    JsonValue::String(s) => Some(s),
47                    JsonValue::Bool(b) => Some(b.to_string()),
48                    JsonValue::Number(n) => Some(n.to_string()),
49                    other => Some(other.to_string()),
50                })
51                .collect();
52            if parts.is_empty() { None } else { Some(parts.join(" ")) }
53        }
54        // Objects have no scalar form; keep compact JSON rather than failing.
55        other => Some(other.to_string()),
56    }))
57}
58
59/// YAML frontmatter structure for SKILL.md
60#[derive(Debug, Serialize, Deserialize)]
61pub struct SkillYaml {
62    pub(crate) name: String,
63    pub(crate) description: String,
64    #[serde(skip_serializing_if = "Option::is_none")]
65    license: Option<String>,
66    #[serde(skip_serializing_if = "Option::is_none")]
67    #[serde(rename = "allowed-tools")]
68    allowed_tools: Option<AllowedToolsField>,
69    #[serde(
70        skip_serializing_if = "Option::is_none",
71        default,
72        deserialize_with = "deserialize_argument_hint_opt"
73    )]
74    #[serde(rename = "argument-hint")]
75    #[serde(alias = "argument_hint")]
76    argument_hint: Option<String>,
77    #[serde(skip_serializing_if = "Option::is_none")]
78    #[serde(rename = "disable-model-invocation")]
79    #[serde(alias = "disable_model_invocation")]
80    disable_model_invocation: Option<bool>,
81    #[serde(skip_serializing_if = "Option::is_none")]
82    compatibility: Option<String>,
83    #[serde(skip_serializing_if = "Option::is_none")]
84    hooks: Option<JsonValue>,
85    #[serde(skip_serializing_if = "Option::is_none")]
86    metadata: Option<SkillManifestMetadata>,
87}
88
89#[derive(Debug, Serialize, Deserialize)]
90#[serde(untagged)]
91pub enum AllowedToolsField {
92    List(Vec<String>),
93    String(String),
94}
95
96/// Parse SKILL.md file and extract manifest + instructions
97pub fn parse_skill_file(skill_path: &Path) -> anyhow::Result<(SkillManifest, String)> {
98    let skill_md = skill_path.join("SKILL.md");
99    // `read_to_string` already reports a missing file, so an `exists()` probe
100    // would only add a second open/stat for the same answer. Keep the specific
101    // "not found" wording that callers and operator logs relied on.
102    let content = fs::read_to_string(&skill_md).map_err(|error| {
103        if error.kind() == std::io::ErrorKind::NotFound {
104            anyhow::anyhow!("SKILL.md not found at {}", skill_md.display())
105        } else {
106            anyhow::Error::new(error).context(format!("Failed to read SKILL.md at {}", skill_md.display()))
107        }
108    })?;
109
110    let (manifest, instructions) = parse_skill_content(&content)?;
111
112    // Directory-name match is a spec SHOULD, not a load gate: warn and load
113    // anyway so skills authored for other clients (whose directory was renamed
114    // on install) still work. `vtcode skills validate` still surfaces the
115    // mismatch via the comprehensive validator. Safe to load: `Skill::new`
116    // does not depend on the directory name, and discovery keys collisions by
117    // manifest name.
118    if let Err(err) = manifest.validate_directory_name_match(&skill_md) {
119        tracing::warn!("{}; loading skill anyway", err);
120    }
121
122    // Validate file references in instructions
123    // For traditional skills (SKILL.md files), validate references
124    let skill_root = skill_md.parent().unwrap_or_else(|| Path::new("."));
125    let reference_validator = FileReferenceValidator::new(skill_root.to_path_buf());
126    let reference_errors = reference_validator.validate_references(&instructions);
127
128    if !reference_errors.is_empty() {
129        let sample_count = reference_errors.len().min(3);
130        let sample = &reference_errors[..sample_count];
131        tracing::warn!(
132            warning_count = reference_errors.len(),
133            sample = ?sample,
134            "File reference validation warnings detected (showing first {})",
135            sample_count
136        );
137        tracing::debug!(
138            warnings = ?reference_errors,
139            "File reference validation warnings (full list)"
140        );
141    }
142
143    Ok((manifest, instructions))
144}
145
146/// Collect unknown top-level frontmatter keys from a YAML string.
147///
148/// Only keys at column 0 are examined; nested keys indented under a supported
149/// parent (e.g. `metadata:`) are not flagged. Returns keys in first-seen
150/// order, deduplicated. This is a pure helper extracted so the filtering logic
151/// is independently testable without capturing `tracing` output.
152fn collect_unknown_frontmatter_keys(yaml_str: &str) -> Vec<&str> {
153    let mut unknown_keys: Vec<&str> = Vec::new();
154    let mut seen: std::collections::HashSet<&str> = std::collections::HashSet::new();
155    for line in yaml_str.lines() {
156        // Only top-level keys begin at column 0; indented lines are nested
157        // under a parent (e.g. `metadata:`) and must not be flagged.
158        match line.as_bytes().first() {
159            None => continue,
160            Some(&b) if b == b' ' || b == b'\t' => continue,
161            _ => {}
162        }
163        let trimmed = line.trim();
164        if trimmed.is_empty() || trimmed.starts_with('#') {
165            continue;
166        }
167        if let Some(colon_pos) = trimmed.find(':') {
168            let key = trimmed[..colon_pos].trim();
169            if !key.is_empty()
170                && !key.starts_with('#')
171                && !SUPPORTED_FRONTMATTER_KEYS.contains(&key)
172                && seen.insert(key)
173            {
174                unknown_keys.push(key);
175            }
176        }
177    }
178    unknown_keys
179}
180
181/// Validate that all YAML frontmatter keys are in the supported set.
182///
183/// Unknown **top-level** keys are logged as a single consolidated warning but
184/// do not fail parsing, preserving forward compatibility when newer vtcode
185/// versions add new fields. Nested keys under a supported parent (e.g.
186/// `metadata:`) are not flagged. Consolidating to one warning per skill (with
187/// all unknown keys listed once) avoids the per-key log spam that previously
188/// produced ~180 warning lines per startup, each repeating the full
189/// supported-keys list.
190fn validate_frontmatter_keys(yaml_str: &str) {
191    let unknown_keys = collect_unknown_frontmatter_keys(yaml_str);
192    if !unknown_keys.is_empty() {
193        tracing::warn!(
194            unknown_keys = ?unknown_keys,
195            supported = ?SUPPORTED_FRONTMATTER_KEYS,
196            "SKILL.md frontmatter has {} unknown top-level key(s); they are ignored but may indicate a typo or a field this vtcode version does not recognize yet",
197            unknown_keys.len()
198        );
199    }
200}
201
202/// Parse SKILL.md content string
203pub fn parse_skill_content(content: &str) -> anyhow::Result<(SkillManifest, String)> {
204    // Split YAML frontmatter (between --- markers)
205    let parts: Vec<&str> = content.splitn(3, "---").collect();
206
207    anyhow::ensure!(parts.len() >= 3, "SKILL.md must start with YAML frontmatter: --- ... ---");
208
209    let yaml_str = parts[1].trim();
210    let instructions = parts[2].trim_start().to_string();
211
212    // Validate frontmatter keys before parsing. This replaces the stricter
213    // #[serde(deny_unknown_fields)] with a forward-compatible approach:
214    // unknown keys are warned about but do not fail parsing.
215    validate_frontmatter_keys(yaml_str);
216
217    // Parse YAML frontmatter
218    let yaml: SkillYaml = match serde_saphyr::from_str(yaml_str) {
219        Ok(yaml) => yaml,
220        Err(first_err) => match fold_bare_description_to_block_scalar(yaml_str) {
221            Some(fixed) => {
222                tracing::debug!("SKILL.md frontmatter needed description block-scalar fallback to parse");
223                serde_saphyr::from_str(&fixed)
224                    .with_context(|| format!("Failed to parse SKILL.md YAML frontmatter ({first_err:#})"))?
225            }
226            None => return Err(first_err).context("Failed to parse SKILL.md YAML frontmatter"),
227        },
228    };
229
230    let name = yaml.name.trim().to_string();
231    anyhow::ensure!(!name.is_empty(), "name is required and must not be empty");
232
233    let description = yaml.description.trim().to_string();
234    anyhow::ensure!(!description.is_empty(), "description is required and must not be empty");
235
236    // Convert allowed-tools into space-delimited string for compatibility.
237    // Both the space-delimited string and the YAML list forms are accepted
238    // (Claude Code supports YAML lists); normalization is silent.
239    let allowed_tools_string = yaml.allowed_tools.map(normalize_allowed_tools).transpose()?;
240
241    let argument_hint = yaml
242        .argument_hint
243        .map(|hint| hint.trim().to_string())
244        .filter(|hint| !hint.is_empty());
245
246    let manifest = SkillManifest {
247        name,
248        description,
249        version: None,
250        default_version: None,
251        latest_version: None,
252        author: None,
253        license: yaml.license,
254        model: None,
255        mode: None,
256        vtcode_native: None,
257        allowed_tools: allowed_tools_string,
258        disable_model_invocation: yaml.disable_model_invocation,
259        when_to_use: None,
260        when_not_to_use: None,
261        argument_hint,
262        user_invocable: None,
263        context: None,
264        agent: None,
265        hooks: yaml.hooks,
266        requires_container: None,
267        disallow_container: None,
268        compatibility: yaml.compatibility,
269        variety: crate::types::SkillVariety::AgentSkill,
270        metadata: yaml.metadata,
271        tools: None,
272        network_policy: None,
273        permissions: None,
274    };
275
276    manifest.validate()?;
277
278    Ok((manifest, instructions))
279}
280/// Whether `line` looks like a new top-level `key:` mapping entry.
281///
282/// Column-0 lines starting a mapping key terminate description folding; `- `
283/// sequence entries, comments, blank lines, and `scheme://...` runs (colon not
284/// followed by space/end) stay inside the folded value, matching YAML plain
285/// scalar rules closely enough for a last-resort retry.
286fn looks_like_top_level_key(line: &str) -> bool {
287    match line.as_bytes().first() {
288        None | Some(b' ') | Some(b'\t') | Some(b'#') | Some(b'-') => return false,
289        _ => {}
290    }
291    let trimmed = line.trim_start();
292    let Some(colon_pos) = trimmed.find(':') else {
293        return false;
294    };
295    if colon_pos == 0 {
296        return false;
297    }
298    matches!(trimmed.as_bytes().get(colon_pos + 1), None | Some(b' ') | Some(b'\t'))
299}
300
301/// Retry helper for cross-client SKILL.md files whose unquoted `description:`
302/// value contains a colon (invalid YAML that lenient parsers accept, e.g.
303/// `description: Use this skill when: the user asks about PDFs`).
304///
305/// Rewrites the description value as a `|` block scalar and returns the
306/// rewritten frontmatter, or `None` when there is no bare top-level
307/// `description:` key to repair. Only runs after a hard parse failure, so it
308/// can never break a file that already parses.
309fn fold_bare_description_to_block_scalar(yaml_str: &str) -> Option<String> {
310    const KEY: &str = "description:";
311    let lines: Vec<&str> = yaml_str.lines().collect();
312    let desc_idx = lines.iter().position(|line| {
313        if matches!(line.as_bytes().first(), None | Some(b' ') | Some(b'\t') | Some(b'#')) {
314            return false;
315        }
316        let trimmed = line.trim_start();
317        if !trimmed.starts_with(KEY) {
318            return false;
319        }
320        matches!(trimmed.as_bytes().get(KEY.len()), None | Some(b' ') | Some(b'\t'))
321    })?;
322    let first_value = lines[desc_idx].trim_start()[KEY.len()..].trim_start();
323    // Only engage for the classic failure: an unquoted scalar containing a
324    // colon. Explicit `|`/`>`/quoted scalars and empty values fail elsewhere.
325    if first_value.is_empty() || first_value.starts_with(['|', '>', '"', '\'']) || !first_value.contains(':') {
326        return None;
327    }
328
329    let mut rebuilt: Vec<String> = lines[..desc_idx].iter().map(|line| line.to_string()).collect();
330    rebuilt.push("description: |".to_string());
331    rebuilt.push(format!("  {first_value}"));
332    let mut folding = true;
333    for line in &lines[desc_idx + 1..] {
334        if folding && looks_like_top_level_key(line) {
335            folding = false;
336        }
337        if folding && !line.is_empty() {
338            rebuilt.push(format!("  {}", line.trim_start()));
339        } else {
340            rebuilt.push(line.to_string());
341        }
342    }
343    Some(rebuilt.join("\n"))
344}
345
346fn normalize_allowed_tools(field: AllowedToolsField) -> anyhow::Result<String> {
347    match field {
348        AllowedToolsField::List(tools) => {
349            let normalized = tools.join(" ");
350            if normalized.trim().is_empty() {
351                return Err(anyhow::anyhow!("allowed-tools must not be empty if specified"));
352            }
353            tracing::debug!("normalized allowed-tools from YAML list to space-delimited string");
354            Ok(normalized)
355        }
356        AllowedToolsField::String(value) => {
357            let trimmed = value.trim();
358            if trimmed.is_empty() {
359                return Err(anyhow::anyhow!("allowed-tools must not be empty if specified"));
360            }
361            let has_commas = trimmed.contains(',');
362            if has_commas {
363                tracing::debug!("normalized allowed-tools from comma-separated to space-delimited");
364            }
365            let parts = if has_commas {
366                trimmed
367                    .split(',')
368                    .map(|part| part.trim())
369                    .filter(|part| !part.is_empty())
370                    .collect::<Vec<_>>()
371            } else {
372                trimmed.split_whitespace().collect::<Vec<_>>()
373            };
374            Ok(parts.join(" "))
375        }
376    }
377}
378
379/// Generate a skill template with YAML frontmatter
380pub fn generate_skill_template(name: &str, description: &str) -> String {
381    let skill_title = name
382        .split('-')
383        .filter(|word| !word.is_empty())
384        .map(|word| {
385            let mut chars = word.chars();
386            match chars.next() {
387                Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
388                None => String::new(),
389            }
390        })
391        .collect::<Vec<_>>()
392        .join(" ");
393
394    format!(
395        r#"---
396name: {name}
397description: {description}
398license: Apache-2.0
399# Optional fields (uncomment to use):
400# compatibility: "Requires git and network access"
401# allowed-tools: "Read Write Bash"
402# argument-hint: "[expected argument]"
403# disable-model-invocation: true
404# metadata:
405#   author: your-team
406#   version: "1.0"
407---
408
409# {skill_title}
410
411## Purpose
412
413Summarize the workflow, expected inputs, and the artifact or outcome this skill should produce.
414
415## Workflow
416
4171. Confirm the request matches the routing guidance above.
4182. Keep core instructions here; move detailed reference material into bundled files.
4193. Prefer reusable scripts, templates, or assets over re-describing large procedures in prose.
4204. Produce the expected artifact or outcome and note any important constraints.
421
422## Resources
423
424- `scripts/`: deterministic helpers for repeatable or fragile steps
425- `references/`: detailed docs loaded only when needed
426- `assets/`: reusable output skeletons, examples, or supporting files
427
428## Example
429
430**Input:** [Describe the request or files]
431**Output/Artifact:** [Describe the result this skill should produce]
432
433## Gotchas
434
435- List non-obvious facts the agent will get wrong without being told.
436- Example: soft-delete filters, ID aliases across systems, health-check quirks.
437
438## Output Format
439
440Use this shape for the final artifact; adapt sections as needed:
441
442```markdown
443# [Title]
444
445## Summary
446[One-paragraph overview]
447
448## Findings
449- Finding with supporting data
450
451## Next Steps
4521. Specific actionable step
453```
454
455For longer templates, store them under `assets/` and reference them here.
456
457## Checklist
458
459- [ ] Confirm trigger matches `description` routing
460- [ ] Load only needed `references/` files
461- [ ] Run bundled `scripts/` instead of retyping logic
462- [ ] Validate output before finishing
463
464## Validation
465
4661. Make the change or produce the artifact.
4672. Run validation: `python3 scripts/validate.py --help` (or skill-specific validator).
4683. If validation fails, fix and re-run. Only finish when validation passes.
469
470## Notes
471
472- Keep SKILL.md concise; move deep detail into `references/` files.
473- If output needs a fixed shape, store a starter template or asset alongside the skill.
474- Prefer one default tool path with a brief escape hatch over a menu of options.
475- Describe reusable procedures, not single-instance answers.
476""#
477    )
478}
479
480#[cfg(test)]
481mod tests {
482    use super::*;
483    use serde_json::json;
484
485    #[test]
486    fn test_parse_valid_skill() {
487        let content = r#"---
488name: test-skill
489description: A test skill for parsing
490---
491
492# Test Skill
493
494## Instructions
495This is the instruction section.
496
497## Examples
498- Example 1
499- Example 2
500"#;
501
502        let (manifest, instructions) = parse_skill_content(content).unwrap();
503
504        assert_eq!(manifest.name, "test-skill");
505        assert_eq!(manifest.description, "A test skill for parsing");
506        assert!(instructions.contains("# Test Skill"));
507        assert!(instructions.contains("## Instructions"));
508    }
509
510    #[test]
511    fn test_parse_missing_frontmatter() {
512        let content = "This is not valid";
513        let result = parse_skill_content(content);
514        result.unwrap_err();
515    }
516
517    #[test]
518    fn test_parse_skill_accepts_non_spec_fields_with_warning() {
519        // Unknown frontmatter keys are now warned about but do not fail parsing,
520        // preserving forward compatibility when newer vtcode versions add fields.
521        let content = r#"---
522name: sandboxed-skill
523description: A skill with unsupported fields
524permissions:
525  file_system:
526    write:
527      - outputs
528---
529
530# Instructions
531"#;
532
533        let (manifest, _) = parse_skill_content(content)
534            .expect("unknown frontmatter keys should be accepted for forward compatibility");
535        assert_eq!(manifest.name, "sandboxed-skill");
536    }
537
538    #[test]
539    fn test_parse_invalid_yaml() {
540        let content = r#"---
541invalid: yaml: content: here
542missing_required_fields: true
543---
544
545# Instructions
546"#;
547
548        let result = parse_skill_content(content);
549        result.unwrap_err();
550    }
551
552    #[test]
553    fn test_parse_skill_metadata_accepts_arrays_and_maps() {
554        let content = r#"---
555name: rust-skills
556description: Rust guidance
557license: MIT
558metadata:
559  author: leonardomso
560  version: "1.0.0"
561  sources:
562    - Rust API Guidelines
563    - Rust Performance Book
564---
565
566# Rust Best Practices
567"#;
568
569        let (manifest, _) = parse_skill_content(content).expect("metadata arrays should parse");
570        let metadata = manifest.metadata.expect("metadata should be present");
571
572        assert_eq!(metadata.get("author"), Some(&json!("leonardomso")));
573        assert_eq!(metadata.get("version"), Some(&json!("1.0.0")));
574        assert_eq!(metadata.get("sources"), Some(&json!(["Rust API Guidelines", "Rust Performance Book"])));
575    }
576
577    #[test]
578    fn test_parse_skill_disable_model_invocation_flag() {
579        let content = r#"---
580name: command-skill
581description: A skill hidden from model-driven activation
582disable-model-invocation: true
583---
584
585# Command Skill
586"#;
587
588        let (manifest, _) = parse_skill_content(content).expect("flag should parse");
589        assert_eq!(manifest.disable_model_invocation, Some(true));
590    }
591
592    #[test]
593    fn test_parse_skill_description_with_bare_colon() {
594        let content = r#"---
595name: colon-skill
596description: Use this skill when: the user asks about PDFs
597---
598
599# Body
600"#;
601
602        let (manifest, _) = parse_skill_content(content).expect("bare colon should fold to block scalar");
603        assert_eq!(manifest.name, "colon-skill");
604        assert_eq!(manifest.description, "Use this skill when: the user asks about PDFs");
605    }
606
607    #[test]
608    fn test_parse_skill_multiline_description_with_colon() {
609        let content = "---\nname: multi-skill\ndescription: First line: overview\ncontinued second line\nlicense: MIT\n---\n\n# Body\n";
610
611        let (manifest, _) = parse_skill_content(content).expect("multiline description should fold");
612        assert_eq!(manifest.name, "multi-skill");
613        assert!(manifest.description.contains("First line: overview"), "got: {}", manifest.description);
614        assert!(manifest.description.contains("continued second line"), "got: {}", manifest.description);
615        assert_eq!(manifest.license.as_deref(), Some("MIT"));
616    }
617
618    #[test]
619    fn test_parse_skill_garbage_frontmatter_still_fails() {
620        let content = "---\nname: [unclosed\ndescription: Broken\n---\n\n# Body\n";
621
622        let err = parse_skill_content(content).expect_err("unrelated YAML failure must still error");
623        assert!(err.to_string().contains("frontmatter"), "got: {err:#}");
624    }
625
626    #[test]
627    fn test_generate_template() {
628        let template = generate_skill_template("my-skill", "Does cool things");
629        assert!(template.contains("name: my-skill"));
630        assert!(template.contains("description: Does cool things"));
631        assert!(template.contains("license: Apache-2.0"));
632        assert!(template.contains("## Workflow"));
633        assert!(template.contains("assets/`: reusable output skeletons"));
634        assert!(template.contains("## Gotchas"));
635        assert!(template.contains("## Output Format"));
636        assert!(template.contains("## Checklist"));
637        assert!(template.contains("## Validation"));
638    }
639
640    #[test]
641    fn collect_unknown_frontmatter_keys_ignores_nested_keys() {
642        // Nested keys under `metadata:` (a supported key) must NOT be flagged.
643        // This is the regression that produced ~180 false-positive warning
644        // lines per startup: author/version/sources/category are nested under
645        // metadata in well-formed third-party skills, not top-level.
646        let yaml = "name: test\ndescription: test\nmetadata:\n  author: leo\n  version: \"1.0\"\n  sources:\n    - a\n    - b\n  category: foo\n  backend: bar\n";
647        let unknown = collect_unknown_frontmatter_keys(yaml);
648        assert!(unknown.is_empty(), "nested keys under a supported parent must not be flagged, got {unknown:?}");
649    }
650
651    #[test]
652    fn collect_unknown_frontmatter_keys_flags_top_level_only() {
653        // `permissions` and `backend` are top-level unknown keys; `file_system`
654        // and `write` are nested under `permissions` and must be skipped.
655        let yaml =
656            "name: test\ndescription: test\npermissions:\n  file_system:\n    write:\n      - outputs\nbackend: foo\n";
657        let unknown = collect_unknown_frontmatter_keys(yaml);
658        assert_eq!(unknown, vec!["permissions", "backend"]);
659    }
660
661    #[test]
662    fn collect_unknown_frontmatter_keys_deduplicates() {
663        let yaml = "name: test\ndescription: test\nbackend: foo\nbackend: bar\n";
664        let unknown = collect_unknown_frontmatter_keys(yaml);
665        assert_eq!(unknown, vec!["backend"]);
666    }
667
668    #[test]
669    fn collect_unknown_frontmatter_keys_skips_comments_and_blank_lines() {
670        let yaml = "# a comment\nname: test\n\ndescription: test\n# another\n";
671        let unknown = collect_unknown_frontmatter_keys(yaml);
672        assert!(unknown.is_empty());
673    }
674
675    #[test]
676    fn collect_unknown_frontmatter_keys_preserves_first_seen_order() {
677        let yaml = "name: test\ndescription: test\nzee: 1\nalpha: 2\nmid: 3\n";
678        let unknown = collect_unknown_frontmatter_keys(yaml);
679        assert_eq!(unknown, vec!["zee", "alpha", "mid"]);
680    }
681
682    #[test]
683    fn collect_unknown_frontmatter_keys_accepts_argument_hint() {
684        let yaml = "name: test\ndescription: test\nargument-hint: \"<input>\"\n";
685        let unknown = collect_unknown_frontmatter_keys(yaml);
686        assert!(unknown.is_empty(), "argument-hint is supported, got {unknown:?}");
687    }
688
689    #[test]
690    fn parse_skill_content_accepts_codemod_style_frontmatter() {
691        let content = r#"---
692name: codemod
693description: Use Codemod CLI whenever the user wants to migrate something.
694allowed-tools:
695  - Bash(codemod *)
696argument-hint: "<migration-intent>"
697---
698
699# Codemod
700"#;
701        let (manifest, _) = parse_skill_content(content).expect("codemod-style frontmatter should parse");
702        assert_eq!(manifest.allowed_tools.as_deref(), Some("Bash(codemod *)"));
703        assert_eq!(manifest.argument_hint.as_deref(), Some("<migration-intent>"));
704    }
705
706    #[test]
707    fn parse_skill_content_coerces_sequence_argument_hint() {
708        let content =
709            "---\nname: seq-skill\ndescription: Test skill\nargument-hint:\n  - topic\n  - foo\n---\n\n# Body\n";
710        let (manifest, _) = parse_skill_content(content).expect("sequence argument-hint should coerce");
711        assert_eq!(manifest.argument_hint.as_deref(), Some("topic foo"));
712    }
713
714    #[test]
715    fn parse_skill_content_rejects_empty_allowed_tools_list() {
716        let content = "---\nname: empty-tools\ndescription: Test skill\nallowed-tools: []\n---\n\n# Body\n";
717        let err = parse_skill_content(content).expect_err("empty allowed-tools list must fail");
718        assert!(err.to_string().contains("allowed-tools"), "got: {err:#}");
719    }
720
721    #[test]
722    fn parse_skill_file_reports_a_missing_manifest_without_a_preflight_stat() {
723        let tmp = tempfile::TempDir::new().expect("temp dir");
724        // No SKILL.md: the read itself supplies the diagnostic, so the error
725        // must still say "not found" rather than a generic read failure.
726        let error = parse_skill_file(tmp.path()).expect_err("missing SKILL.md must fail");
727        let message = error.to_string();
728        assert!(message.contains("SKILL.md not found"), "{message}");
729    }
730
731    #[test]
732    fn parse_skill_file_loads_despite_directory_name_mismatch() {
733        // Agent Skills client guide: directory-name mismatch warns but loads,
734        // so skills renamed on install (cross-client) still work.
735        let tmp = tempfile::TempDir::new().expect("temp dir");
736        let skill_dir = tmp.path().join("renamed-dir");
737        fs::create_dir(&skill_dir).expect("create skill dir");
738        fs::write(skill_dir.join("SKILL.md"), "---\nname: original-name\ndescription: Test skill\n---\n\n# Body\n")
739            .expect("write SKILL.md");
740
741        let (manifest, _) = parse_skill_file(&skill_dir).expect("mismatched directory must still load");
742        assert_eq!(manifest.name, "original-name");
743    }
744}