返回 CodeWhale
frontmatter.rs
根目录 / crates / skill-install / src / frontmatter.rs
1 //! Shared frontmatter reader for Skills, agent profiles, and installation.
2 //! This leaf is also included by the installation acceptance harness.
3
4 use std::collections::HashMap;
5 use std::path::{Component, Path};
6
7 /// Parsed frontmatter: lowercased metadata keys and the body after the fence.
8 pub type Frontmatter<'a> = (HashMap<String, String>, &'a str);
9
10 #[derive(Debug, Clone, Default, PartialEq, Eq)]
11 pub struct SkillDependencies {
12 pub mcp_servers: Vec<String>,
13 pub tools: Vec<String>,
14 }
15
16 pub struct CodexSkillMetadata {
17 pub allows_implicit_invocation: bool,
18 pub dependencies: SkillDependencies,
19 }
20
21 impl Default for CodexSkillMetadata {
22 fn default() -> Self {
23 Self {
24 allows_implicit_invocation: true,
25 dependencies: SkillDependencies::default(),
26 }
27 }
28 }
29
30 pub fn codex_skill_metadata(yaml: &str) -> Result<CodexSkillMetadata, String> {
31 use yaml_rust2::{Yaml, YamlLoader};
32 let documents = YamlLoader::load_from_str(yaml).map_err(|error| error.to_string())?;
33 let [document] = documents.as_slice() else {
34 return Err("Expected one skill policy document".into());
35 };
36 if !matches!(document, Yaml::Hash(_)) {
37 return Err("Expected a mapping for the skill policy document".into());
38 }
39 let allows_implicit_invocation = match &document["policy"] {
40 Yaml::BadValue => true,
41 policy @ Yaml::Hash(_) => match &policy["allow_implicit_invocation"] {
42 Yaml::BadValue => true,
43 Yaml::Boolean(allowed) => *allowed,
44 _ => return Err("Expected a boolean allow_implicit_invocation policy".into()),
45 },
46 _ => return Err("Expected a mapping for the skill policy".into()),
47 };
48 let mut dependencies = SkillDependencies::default();
49 if let Some(tools) = document["dependencies"]["tools"].as_vec() {
50 for tool in tools.iter().take(16) {
51 let Some(name) = tool["value"].as_str().filter(|name| {
52 !name.is_empty()
53 && name.len() <= 64
54 && name
55 .bytes()
56 .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
57 }) else {
58 continue;
59 };
60 let destination = match tool["type"].as_str() {
61 Some("mcp") => &mut dependencies.mcp_servers,
62 Some("tool") => &mut dependencies.tools,
63 _ => continue,
64 };
65 if !destination.iter().any(|existing| existing == name) {
66 destination.push(name.to_owned());
67 }
68 }
69 }
70 Ok(CodexSkillMetadata {
71 allows_implicit_invocation,
72 dependencies,
73 })
74 }
75
76 #[derive(Clone, Copy, PartialEq, Eq)]
77 pub enum SkillValidationMode {
78 Lenient,
79 Strict,
80 }
81
82 /// Runtime accepts incomplete authoring metadata with visible warnings;
83 /// installation requires frontmatter, a path-safe name, and a description.
84 /// Neither mode grants tools, model selection, execution, or fork authority.
85 pub fn validate_skill_frontmatter(
86 metadata: Option<&HashMap<String, String>>,
87 path: Option<&Path>,
88 mode: SkillValidationMode,
89 ) -> Result<Vec<String>, String> {
90 let Some(metadata) = metadata else {
91 return match mode {
92 SkillValidationMode::Strict => {
93 Err("SKILL.md is missing the leading '---' frontmatter fence".into())
94 }
95 SkillValidationMode::Lenient => Ok(vec![
96 "missing frontmatter; using the Markdown heading as the skill name".into(),
97 "missing description".into(),
98 ]),
99 };
100 };
101 let name = metadata
102 .get("name")
103 .filter(|name| !name.trim().is_empty())
104 .ok_or_else(|| "missing required frontmatter field: name".to_string())?;
105 if mode == SkillValidationMode::Strict && !is_path_safe_skill_name(name) {
106 return Err(format!(
107 "SKILL.md `name` must be a single path-safe segment (got '{name}')"
108 ));
109 }
110 let mut warnings = Vec::new();
111 if !metadata
112 .get("description")
113 .is_some_and(|value| !value.trim().is_empty())
114 {
115 if mode == SkillValidationMode::Strict {
116 return Err("missing required frontmatter field: description".into());
117 }
118 warnings.push("missing description".into());
119 }
120 if let Some(directory) = path
121 .and_then(Path::parent)
122 .and_then(Path::file_name)
123 .and_then(|name| name.to_str())
124 && directory != name
125 {
126 warnings.push(format!(
127 "frontmatter name `{name}` differs from directory `{directory}`"
128 ));
129 }
130 let mut keys: Vec<_> = metadata.keys().collect();
131 keys.sort();
132 for key in keys {
133 if key.starts_with("metadata.") || key.starts_with("x-") || key.starts_with("description_")
134 {
135 continue;
136 }
137 let warning = match key.as_str() {
138 "name" | "description" | "invocation" | "aliases-for" | "license" | "compatibility"
139 | "metadata" | "when_to_use" | "argument-hint" => None,
140 "disable-model-invocation"
141 | "user-invocable"
142 | "allow_implicit_invocation"
143 | "explicit_only" => {
144 if parse_frontmatter_bool(&metadata[key]).is_none() {
145 let warning = format!("invalid boolean `{key}`; invocation fails closed");
146 if mode == SkillValidationMode::Strict {
147 return Err(warning);
148 }
149 Some(warning)
150 } else {
151 None
152 }
153 }
154 "allowed-tools" | "disallowed-tools" => Some(format!(
155 "`{key}` ignored: skills grant no tool or approval authority"
156 )),
157 "model" => Some("`model` ignored: skills do not select providers or models".into()),
158 "context" | "agent" => Some(format!(
159 "`{key}` unsupported: skills do not create a separate execution context"
160 )),
161 _ => Some(format!("unknown frontmatter key `{key}` ignored")),
162 };
163 if let Some(warning) = warning {
164 warnings.push(warning);
165 }
166 }
167 Ok(warnings)
168 }
169
170 pub fn parse_frontmatter_bool(value: &str) -> Option<bool> {
171 match value.trim().to_ascii_lowercase().as_str() {
172 "true" | "yes" | "on" | "1" => Some(true),
173 "false" | "no" | "off" | "0" => Some(false),
174 _ => None,
175 }
176 }
177
178 pub fn is_path_safe_skill_name(name: &str) -> bool {
179 if name.is_empty()
180 || name.trim() != name
181 || name.chars().any(char::is_whitespace)
182 || name.contains(['/', '\\'])
183 {
184 return false;
185 }
186 let mut components = Path::new(name).components();
187 matches!(components.next(), Some(Component::Normal(_))) && components.next().is_none()
188 }
189
190 /// Split a Markdown file into its `---` frontmatter metadata and body.
191 ///
192 /// Returns `Ok(None)` when the file does not open with a `---` fence. Keys are
193 /// lowercased; values are unquoted, and YAML block scalars (`>`, `|`, with
194 /// chomping) are folded the way `SKILL.md` has always read them. This is the
195 /// one frontmatter reader: skills and Claude Code agent files both use it.
196 pub fn parse_frontmatter(content: &str) -> std::result::Result<Option<Frontmatter<'_>>, String> {
197 let content = content
198 .strip_prefix('\u{feff}')
199 .unwrap_or(content)
200 .trim_start();
201 let opening = content.split_inclusive('\n').next().unwrap_or_default();
202 if opening.trim_end() != "---" {
203 return Ok(None);
204 }
205 let rest = &content[opening.len()..];
206 let mut offset = 0;
207 let end = rest
208 .split_inclusive('\n')
209 .find_map(|line| {
210 let start = offset;
211 offset += line.len();
212 (line.trim_end() == "---").then_some(start)
213 })
214 .ok_or_else(|| "missing frontmatter closing delimiter".to_string())?;
215 let frontmatter = &rest[..end];
216 let body = &rest[end + 3..];
217
218 let mut metadata = HashMap::new();
219 let indentation = |line: &str| line.chars().take_while(|ch| ch.is_whitespace()).count();
220 let lines: Vec<&str> = frontmatter.lines().collect();
221 let mut i = 0;
222 let mut maps: Vec<(usize, String)> = Vec::new();
223 while i < lines.len() {
224 let raw = lines[i];
225 let line = raw.trim();
226 if line.is_empty() || line.starts_with('#') {
227 i += 1;
228 continue;
229 }
230 if let Some((key, value)) = line.split_once(':') {
231 let indent = indentation(raw);
232 while maps
233 .last()
234 .is_some_and(|(parent_indent, _)| *parent_indent >= indent)
235 {
236 maps.pop();
237 }
238 let key = key.trim().to_ascii_lowercase();
239 let key = maps
240 .last()
241 .map_or_else(|| key.clone(), |(_, parent)| format!("{parent}.{key}"));
242 let value = value.trim();
243 // Check for YAML block scalar indicators: > (folded), | (literal),
244 // optionally with chomping: >-, >+, |-, |+
245 let is_block_scalar = matches!(value, ">" | "|" | ">-" | ">+" | "|-" | "|+");
246 if is_block_scalar {
247 let is_folded = value.starts_with('>');
248 let chomp = if value.ends_with('-') {
249 "strip"
250 } else if value.ends_with('+') {
251 "keep"
252 } else {
253 "clip"
254 };
255 // Determine the base indentation from the key line
256 let base_indent = indentation(raw);
257 let mut block_lines: Vec<&str> = Vec::new();
258 let mut content_indent: Option<usize> = None;
259 i += 1;
260 while i < lines.len() {
261 let raw_line = lines[i];
262 if raw_line.trim().is_empty() {
263 // Empty lines are part of the block
264 block_lines.push("");
265 i += 1;
266 continue;
267 }
268 let line_indent = indentation(raw_line);
269 if line_indent > base_indent {
270 // Track content indent from the first non-empty
271 // line so we strip only that one level of
272 // leading whitespace, preserving any deeper
273 // relative indentation (YAML §8.1.2).
274 if content_indent.is_none() {
275 content_indent = Some(line_indent);
276 }
277 block_lines.push(raw_line);
278 i += 1;
279 } else {
280 break;
281 }
282 }
283 let content_indent = content_indent.unwrap_or(base_indent);
284 // Strip only the content indent from each non-empty
285 // line so nested indentation survives.
286 let block_lines: Vec<&str> = block_lines
287 .iter()
288 .map(|raw| {
289 if raw.is_empty() {
290 ""
291 } else {
292 let indent = indentation(raw);
293 let strip = std::cmp::min(indent, content_indent);
294 let byte = raw.char_indices().nth(strip).map_or(raw.len(), |(i, _)| i);
295 &raw[byte..]
296 }
297 })
298 .collect();
299 // Apply chomping to trailing empty lines before folding.
300 // Chomping operates on the raw block_lines (before join), so
301 // strip / keep / clip behave per the YAML spec.
302 let block_lines = if matches!(chomp, "strip") {
303 // strip: remove all trailing empty lines
304 let mut lines = block_lines;
305 while lines.last().is_some_and(|s| s.is_empty()) {
306 lines.pop();
307 }
308 lines
309 } else if matches!(chomp, "keep") {
310 // keep: no modification
311 block_lines
312 } else {
313 // clip: keep at most one trailing empty line
314 let mut lines = block_lines;
315 while lines.len() >= 2
316 && lines[lines.len() - 1].is_empty()
317 && lines[lines.len() - 2].is_empty()
318 {
319 lines.pop();
320 }
321 lines
322 };
323 let description = if is_folded {
324 // Folded: join non-empty lines with spaces; empty
325 // lines become paragraph breaks.
326 let mut result = String::new();
327 let mut pending_space = false;
328 for line in &block_lines {
329 if line.is_empty() {
330 result.push('\n');
331 pending_space = false;
332 } else {
333 if pending_space {
334 result.push(' ');
335 }
336 result.push_str(line);
337 pending_space = true;
338 }
339 }
340 result
341 } else {
342 // Literal: join with newlines.
343 block_lines.join("\n")
344 };
345 metadata.insert(key, description);
346 } else if value.is_empty()
347 && lines
348 .get(i + 1)
349 .is_some_and(|next| is_block_sequence_item(next))
350 {
351 // A block sequence (`tools:` then ` - Read` lines) becomes
352 // one comma-separated value, the same as the flow form
353 // `tools: Read, Grep`. Dropping it would read as "no list".
354 let mut items = Vec::new();
355 i += 1;
356 while let Some(next) = lines.get(i).filter(|next| is_block_sequence_item(next)) {
357 let item = next.trim()[1..].trim();
358 let item = item
359 .strip_prefix('"')
360 .and_then(|v| v.strip_suffix('"'))
361 .or_else(|| item.strip_prefix('\'').and_then(|v| v.strip_suffix('\'')))
362 .unwrap_or(item);
363 if !item.is_empty() {
364 items.push(item);
365 }
366 i += 1;
367 }
368 metadata.insert(key, items.join(", "));
369 } else if value.is_empty() {
370 // Child fields retain their map path. In particular,
371 // metadata.name must never replace the skill's own name.
372 metadata.insert(key.clone(), String::new());
373 maps.push((indent, key));
374 i += 1;
375 } else if value.starts_with('[') {
376 // Reuse the installed YAML reader for quoted flow items rather
377 // than splitting commas inside quoted tool names or aliases.
378 let documents = yaml_rust2::YamlLoader::load_from_str(value)
379 .map_err(|err| format!("invalid frontmatter sequence `{key}`: {err}"))?;
380 let items = documents
381 .first()
382 .and_then(yaml_rust2::Yaml::as_vec)
383 .ok_or_else(|| format!("frontmatter `{key}` must be a flow sequence"))?;
384 let values: Result<Vec<_>, _> = items
385 .iter()
386 .map(|item| {
387 item.as_str().ok_or_else(|| {
388 format!("frontmatter `{key}` sequence items must be strings")
389 })
390 })
391 .collect();
392 metadata.insert(key, values?.join(", "));
393 i += 1;
394 } else {
395 let unquoted = match value {
396 v if (v.starts_with('"') && v.ends_with('"') && v.len() >= 2)
397 || (v.starts_with('\'') && v.ends_with('\'') && v.len() >= 2) =>
398 {
399 &v[1..v.len() - 1]
400 }
401 _ => value,
402 };
403 i += 1;
404 let mut text = unquoted.to_string();
405 // Wrapped plain scalars continue at a deeper indentation.
406 // A colon in that continuation belongs to the value, not a
407 // new metadata key. Quoted/flow values retain their grammar.
408 if !value.is_empty() && !value.starts_with(['"', '\'', '[', '{']) {
409 while let Some(next) = lines.get(i) {
410 if next.trim().is_empty() || indentation(next) <= indentation(raw) {
411 break;
412 }
413 if !next.trim_start().starts_with('#') {
414 text.push(' ');
415 text.push_str(next.trim());
416 }
417 i += 1;
418 }
419 }
420 metadata.insert(key, text);
421 }
422 } else {
423 i += 1;
424 }
425 }
426
427 Ok(Some((metadata, body)))
428 }
429
430 /// A YAML block-sequence entry: `- item` (or a bare `-`) on its own line.
431 fn is_block_sequence_item(line: &str) -> bool {
432 let line = line.trim();
433 line == "-" || line.starts_with("- ")
434 }
435
436 #[cfg(test)]
437 mod tests {
438 use super::*;
439
440 #[test]
441 fn codex_metadata_keeps_policy_and_bounded_exact_dependency_names() {
442 let metadata = codex_skill_metadata(
443 r#"
444 policy:
445 allow_implicit_invocation: false
446 dependencies:
447 tools:
448 - {type: mcp, value: local-docs}
449 - {type: mcp, value: local-docs}
450 - {type: mcp, value: 'https://invalid.test/remote'}
451 - {type: tool, value: read}
452 "#,
453 )
454 .unwrap();
455 assert!(!metadata.allows_implicit_invocation);
456 assert_eq!(metadata.dependencies.mcp_servers, ["local-docs"]);
457 assert_eq!(metadata.dependencies.tools, ["read"]);
458 }
459
460 #[test]
461 fn nested_metadata_does_not_override_name_or_description() {
462 let (metadata, _) = parse_frontmatter("---\nname: outer\ndescription: real routing\nmetadata:\n name: impostor\n description: hidden\n nested:\n name: deeper\nlicense: MIT\n---\nbody").unwrap().unwrap();
463 assert_eq!(metadata["name"], "outer");
464 assert_eq!(metadata["description"], "real routing");
465 assert_eq!(metadata["metadata.name"], "impostor");
466 assert_eq!(metadata["metadata.nested.name"], "deeper");
467 assert_eq!(metadata["license"], "MIT");
468 }
469
470 #[test]
471 fn flow_list_parsed() {
472 let (metadata, _) = parse_frontmatter("---\nname: demo\nallowed-tools: [Read, 'Bash(ls *)', \"Grep, Glob\"]\naliases-for: [other, another]\n---\nbody").unwrap().unwrap();
473 assert_eq!(metadata["allowed-tools"], "Read, Bash(ls *), Grep, Glob");
474 assert_eq!(metadata["aliases-for"], "other, another");
475 assert!(parse_frontmatter("---\nname: demo\nallowed-tools: [Read\n---\nbody").is_err());
476 }
477
478 #[test]
479 fn metadata_short_description_captured() {
480 // Actual Codex sample frontmatter, retaining its nested metadata map.
481 let (metadata, _) = parse_frontmatter(include_str!(
482 "../tests/fixtures/skills/codex-skill-creator.md"
483 ))
484 .unwrap()
485 .unwrap();
486 assert_eq!(
487 metadata["metadata.short-description"],
488 "Create or update a skill"
489 );
490 assert!(!metadata.contains_key("short-description"));
491 assert!(
492 validate_skill_frontmatter(Some(&metadata), None, SkillValidationMode::Strict)
493 .unwrap()
494 .is_empty()
495 );
496 }
497
498 #[test]
499 fn real_claude_fixture_preserves_block_sequence_and_authority_warning() {
500 let (metadata, _) =
501 parse_frontmatter(include_str!("../tests/fixtures/skills/claude-access.md"))
502 .unwrap()
503 .unwrap();
504 assert_eq!(metadata["name"], "access");
505 assert_eq!(
506 metadata["allowed-tools"],
507 "Read, Write, Bash(ls *), Bash(mkdir *)"
508 );
509 let warnings =
510 validate_skill_frontmatter(Some(&metadata), None, SkillValidationMode::Strict).unwrap();
511 assert_eq!(warnings.len(), 1);
512 assert!(warnings[0].contains("grant no tool or approval authority"));
513 }
514
515 #[test]
516 fn runtime_and_install_validation_agree() {
517 let (metadata, _) = parse_frontmatter("---\nname: valid\ndescription: routing\n---\nbody")
518 .unwrap()
519 .unwrap();
520 assert_eq!(
521 validate_skill_frontmatter(Some(&metadata), None, SkillValidationMode::Lenient),
522 validate_skill_frontmatter(Some(&metadata), None, SkillValidationMode::Strict)
523 );
524 let mut missing = metadata.clone();
525 missing.remove("description");
526 assert_eq!(
527 validate_skill_frontmatter(Some(&missing), None, SkillValidationMode::Lenient).unwrap(),
528 vec!["missing description"]
529 );
530 assert!(
531 validate_skill_frontmatter(Some(&missing), None, SkillValidationMode::Strict)
532 .unwrap_err()
533 .contains("description")
534 );
535 missing.remove("name");
536 assert!(
537 validate_skill_frontmatter(Some(&missing), None, SkillValidationMode::Lenient).is_err()
538 );
539 let mut unsafe_name = metadata;
540 unsafe_name.insert("name".into(), "../escape".into());
541 assert!(
542 validate_skill_frontmatter(Some(&unsafe_name), None, SkillValidationMode::Strict)
543 .is_err()
544 );
545 }
546
547 #[test]
548 fn unknown_keys_warn_once_spec_keys_silent() {
549 let (metadata, _) = parse_frontmatter("---\nname: demo\ndescription: routing\nlicense: MIT\ncompatibility: Codewhale\nmetadata:\n vendor-field: fine\nx-custom: fine\nallowed-tools: [Read]\nmodel: example\ncontext: fork\nmystery: ignored\n---\nbody").unwrap().unwrap();
550 let warnings =
551 validate_skill_frontmatter(Some(&metadata), None, SkillValidationMode::Lenient)
552 .unwrap();
553 assert_eq!(warnings.len(), 4, "{warnings:?}");
554 for key in ["allowed-tools", "model", "context", "mystery"] {
555 assert_eq!(
556 warnings
557 .iter()
558 .filter(|warning| warning.contains(key))
559 .count(),
560 1
561 );
562 }
563 }
564
565 #[test]
566 fn invalid_invocation_booleans_fail_closed() {
567 let (metadata, _) = parse_frontmatter(
568 "---\nname: demo\ndescription: routing\nuser-invocable: maybe\n---\nbody",
569 )
570 .unwrap()
571 .unwrap();
572 assert!(
573 validate_skill_frontmatter(Some(&metadata), None, SkillValidationMode::Lenient)
574 .unwrap()[0]
575 .contains("fails closed")
576 );
577 assert!(
578 validate_skill_frontmatter(Some(&metadata), None, SkillValidationMode::Strict).is_err()
579 );
580 for value in ["yes", "on", "1", "true"] {
581 assert_eq!(parse_frontmatter_bool(value), Some(true));
582 }
583 for value in ["no", "off", "0", "false"] {
584 assert_eq!(parse_frontmatter_bool(value), Some(false));
585 }
586 }
587 }
588
588 lines RUST