Skip to main content

merry_runtime/skill/
frontmatter.rs

1//! `SKILL.md` frontmatter extraction and YAML parsing.
2//!
3//! Skill frontmatter is the YAML document between the leading `---`
4//! delimiters. Merry reads only `name` and `description` and intentionally
5//! ignores every other top-level key, so third-party skill files that carry
6//! structured `metadata`, tool policy, or license sections still load.
7//!
8//! Parsing the block as YAML instead of scanning it line by line is what makes
9//! block scalars (`|`, `>`), quoted values, trailing comments, plain
10//! multi-line scalars, CRLF line endings, and a leading byte-order mark behave
11//! the way their authors expect.
12
13use serde::Deserialize;
14use thiserror::Error;
15
16/// Frontmatter values Merry requires from one `SKILL.md` file.
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct SkillFrontmatter {
19    name: String,
20    description: String,
21}
22
23impl SkillFrontmatter {
24    /// Skill name as written in the frontmatter.
25    #[must_use]
26    pub fn name(&self) -> &str {
27        &self.name
28    }
29
30    /// Skill description as written in the frontmatter.
31    #[must_use]
32    pub fn description(&self) -> &str {
33        &self.description
34    }
35}
36
37/// Errors raised while extracting and parsing `SKILL.md` frontmatter.
38#[derive(Debug, Clone, PartialEq, Eq, Error)]
39pub enum FrontmatterError {
40    /// The document does not open with a `---` line.
41    #[error("missing frontmatter delimited by ---")]
42    MissingDelimiter,
43    /// The opening `---` line has no closing `---` line.
44    #[error("missing closing frontmatter delimiter")]
45    MissingClosingDelimiter,
46    /// A required field is absent or null.
47    #[error("missing frontmatter field `{field}`")]
48    MissingField {
49        /// Missing field name.
50        field: &'static str,
51    },
52    /// The frontmatter is not valid YAML for the fields Merry reads.
53    #[error("invalid frontmatter: {message}")]
54    Invalid {
55        /// Deserialization detail.
56        message: String,
57    },
58}
59
60/// Frontmatter as deserialized from YAML.
61///
62/// Unknown keys are ignored on purpose: real skill files carry `metadata`,
63/// `license`, or tool policy sections that Merry does not model, and an
64/// unsupported key must not hide the whole skill from the catalog.
65#[derive(Debug, Deserialize)]
66struct FrontmatterDocument {
67    #[serde(default)]
68    name: Option<String>,
69    #[serde(default)]
70    description: Option<String>,
71}
72
73/// Extracts `name` and `description` from one `SKILL.md` document.
74///
75/// The complete file is accepted and only its frontmatter block is parsed.
76/// Failures are reported as [`FrontmatterError`] so the caller can skip this
77/// skill with a typed warning instead of rejecting the configured root.
78pub fn parse(text: &str) -> Result<SkillFrontmatter, FrontmatterError> {
79    let block = frontmatter_block(text)?;
80    let document =
81        serde_norway::from_str::<Option<FrontmatterDocument>>(block).map_err(|error| {
82            FrontmatterError::Invalid {
83                message: error.to_string(),
84            }
85        })?;
86    let Some(document) = document else {
87        return Err(FrontmatterError::MissingField { field: "name" });
88    };
89    Ok(SkillFrontmatter {
90        name: document
91            .name
92            .ok_or(FrontmatterError::MissingField { field: "name" })?,
93        description: document.description.ok_or(FrontmatterError::MissingField {
94            field: "description",
95        })?,
96    })
97}
98
99/// Returns the YAML text between the opening and closing `---` lines.
100///
101/// Delimiter lines are matched textually, which stays consistent with YAML
102/// document boundaries because block scalar content is always indented.
103fn frontmatter_block(text: &str) -> Result<&str, FrontmatterError> {
104    // Editors on Windows may save a byte-order mark before the delimiter.
105    let text = text.strip_prefix('\u{feff}').unwrap_or(text);
106    let mut offset = 0usize;
107    let mut block_start = None;
108    for line in text.split_inclusive('\n') {
109        if line.trim_end() == "---" {
110            match block_start {
111                None => block_start = Some(offset + line.len()),
112                Some(start) => return Ok(&text[start..offset]),
113            }
114        } else if block_start.is_none() {
115            return Err(FrontmatterError::MissingDelimiter);
116        }
117        offset += line.len();
118    }
119    match block_start {
120        None => Err(FrontmatterError::MissingDelimiter),
121        Some(_) => Err(FrontmatterError::MissingClosingDelimiter),
122    }
123}
124
125#[cfg(test)]
126mod tests {
127    use super::*;
128
129    fn parse_document(text: &str) -> SkillFrontmatter {
130        parse(text).expect("frontmatter should parse")
131    }
132
133    #[test]
134    fn reads_name_and_description_and_ignores_structured_metadata() {
135        let skill = parse_document(
136            "---\nname: sample-tool\ndescription: Use when the task needs the sample tool.\nmetadata:\n  cli_version: \">=1.2.3\"\n  category: product\n  requires:\n    bins:\n      - sample-cli\n---\n\n# Sample Tool Skill\n",
137        );
138
139        assert_eq!(skill.name(), "sample-tool");
140        assert_eq!(
141            skill.description(),
142            "Use when the task needs the sample tool."
143        );
144    }
145
146    #[test]
147    fn folds_plain_multi_line_scalars() {
148        let skill = parse_document(
149            "---\nname: sample-tool\ndescription: Use when the task needs\n  the sample tool.\n---\n# Body\n",
150        );
151
152        assert_eq!(
153            skill.description(),
154            "Use when the task needs the sample tool."
155        );
156    }
157
158    #[test]
159    fn parses_block_scalars_and_comments() {
160        let folded = parse_document(
161            "---\nname: folded\ndescription: >-\n  Use when the task\n  needs the sample tool.\n---\n",
162        );
163        assert_eq!(
164            folded.description(),
165            "Use when the task needs the sample tool."
166        );
167
168        let literal = parse_document(
169            "---\nname: literal\ndescription: |\n  First line.\n  Second line.\n---\n",
170        );
171        assert_eq!(literal.description(), "First line.\nSecond line.\n");
172
173        let commented = parse_document(
174            "---\n# generated skill\nname: commented\ndescription: Use when parsing comments. # trailing note\nlicense: MIT\n---\n",
175        );
176        assert_eq!(commented.name(), "commented");
177        assert_eq!(commented.description(), "Use when parsing comments.");
178    }
179
180    #[test]
181    fn parses_quoted_values_and_crlf_and_byte_order_mark() {
182        let quoted = parse_document(
183            "---\nname: \"quoted\"\ndescription: 'Use when quoted: values matter.'\n---\n",
184        );
185        assert_eq!(quoted.name(), "quoted");
186        assert_eq!(quoted.description(), "Use when quoted: values matter.");
187
188        let crlf = parse_document(
189            "---\r\nname: windows\r\ndescription: Windows-authored skill.\r\n---\r\n# Body\r\n",
190        );
191        assert_eq!(crlf.description(), "Windows-authored skill.");
192
193        let bom = parse_document(
194            "\u{feff}---\nname: bom\ndescription: BOM-authored skill.\n---\n# Body\n",
195        );
196        assert_eq!(bom.name(), "bom");
197        assert_eq!(bom.description(), "BOM-authored skill.");
198    }
199
200    #[test]
201    fn reports_missing_delimiters() {
202        assert_eq!(
203            parse("# Body only\n"),
204            Err(FrontmatterError::MissingDelimiter)
205        );
206        assert_eq!(
207            parse("---\nname: sample-tool\n"),
208            Err(FrontmatterError::MissingClosingDelimiter)
209        );
210    }
211
212    #[test]
213    fn reports_missing_and_null_fields() {
214        assert_eq!(
215            parse("---\nname: sample-tool\n---\n"),
216            Err(FrontmatterError::MissingField {
217                field: "description"
218            })
219        );
220        assert_eq!(
221            parse("---\ndescription: Use when needed.\n---\n"),
222            Err(FrontmatterError::MissingField { field: "name" })
223        );
224        assert_eq!(
225            parse("---\nname:\ndescription: Use when needed.\n---\n"),
226            Err(FrontmatterError::MissingField { field: "name" })
227        );
228        assert_eq!(
229            parse("---\n---\n"),
230            Err(FrontmatterError::MissingField { field: "name" })
231        );
232    }
233
234    #[test]
235    fn reports_non_scalar_and_invalid_frontmatter() {
236        let non_scalar = parse("---\nname: sample-tool\ndescription:\n  nested: value\n---\n")
237            .expect_err("nested description should be rejected");
238        assert!(
239            matches!(non_scalar, FrontmatterError::Invalid { .. }),
240            "{non_scalar:?}"
241        );
242
243        let invalid = parse("---\nname: sample-tool\ndescription: [unclosed\n---\n")
244            .expect_err("invalid YAML should be rejected");
245        assert!(
246            matches!(invalid, FrontmatterError::Invalid { .. }),
247            "{invalid:?}"
248        );
249    }
250
251    #[test]
252    fn stringifies_plain_scalar_field_values() {
253        // YAML resolves an unquoted number to a scalar; reading it as text keeps
254        // frontmatter written with `name: 123` loadable instead of rejected.
255        let skill = parse_document("---\nname: 123\ndescription: Use when needed.\n---\n");
256
257        assert_eq!(skill.name(), "123");
258    }
259}