Skip to main content

mars_schema/
frontmatter.rs

1use indexmap::{IndexMap, IndexSet};
2use serde_yaml::{Mapping, Value};
3
4/// Parsed markdown frontmatter and body.
5#[derive(Debug, Clone)]
6pub struct Frontmatter {
7    yaml: Mapping,
8    body: String,
9    has_frontmatter: bool,
10    has_bom: bool,
11}
12
13/// Structured agent skill references.
14///
15/// A flat `skills: [a, b]` list is represented as all `load` entries for
16/// backward compatibility. A structured `skills: { load: [...], available: [...] }`
17/// keeps the two launch-bundle channels separate.
18#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
19pub struct SkillsSpec {
20    pub load: Vec<String>,
21    pub available: Vec<String>,
22}
23
24impl SkillsSpec {
25    pub fn all(&self) -> Vec<String> {
26        self.load
27            .iter()
28            .chain(self.available.iter())
29            .cloned()
30            .collect()
31    }
32}
33
34/// The most frontmatter bytes a file may carry. Parsing time grows with the square of the
35/// nesting depth the text can hold, so an unbounded block is a way to stall a server that reads
36/// untrusted files; real frontmatter is a few hundred bytes.
37pub const MAX_FRONTMATTER_BYTES: usize = 64 * 1024;
38
39/// The deepest run of `[` and `{` the frontmatter may open, counted over the raw text. The
40/// YAML scanners take time quadratic in that depth, so a size cap alone still lets 64 KiB of `[`
41/// stall a parse for seconds; real frontmatter nests a few levels.
42pub const MAX_FLOW_DEPTH: usize = 64;
43
44/// Errors from frontmatter parsing.
45#[derive(Debug, thiserror::Error)]
46pub enum FrontmatterError {
47    #[error("frontmatter is {0} bytes; the limit is {MAX_FRONTMATTER_BYTES}")]
48    TooLarge(usize),
49
50    #[error("frontmatter nests `[` or `{{` more than {MAX_FLOW_DEPTH} deep")]
51    TooDeep,
52
53    #[error("malformed YAML frontmatter: {0}")]
54    MalformedYaml(#[from] serde_yaml::Error),
55
56    #[error("frontmatter is not closed with an exact `---` line")]
57    Unclosed,
58
59    #[error("YAML anchors and aliases are not supported")]
60    Anchor,
61
62    #[error("YAML document-end markers are not supported")]
63    DocumentEnd,
64
65    #[error(
66        "YAML syntax accepted by the semantic parser is unsupported by the structural scanner: {0}"
67    )]
68    UnsupportedSyntax(String),
69
70    #[error("frontmatter is not a YAML mapping")]
71    NotAMapping,
72}
73
74/// Parse markdown content into frontmatter and body.
75pub fn parse(content: &str) -> Result<Frontmatter, FrontmatterError> {
76    Frontmatter::parse(content)
77}
78
79impl Frontmatter {
80    /// Parse a markdown document into frontmatter + body.
81    pub fn parse(content: &str) -> Result<Self, FrontmatterError> {
82        let (frontmatter, mut structural_errors) = Self::parse_preserving_structure(content)?;
83        if structural_errors.is_empty() {
84            Ok(frontmatter)
85        } else {
86            Err(structural_errors.remove(0))
87        }
88    }
89
90    /// Parse semantic content while returning every structural refusal found.
91    ///
92    /// Schema readers use this to avoid losing an anchor diagnostic when the
93    /// structural parser later encounters syntax it cannot scan.
94    pub(crate) fn parse_preserving_structure(
95        content: &str,
96    ) -> Result<(Self, Vec<FrontmatterError>), FrontmatterError> {
97        let Some(regions) = split_regions(content)? else {
98            return Ok((
99                Self {
100                    yaml: Mapping::new(),
101                    body: content.to_string(),
102                    has_frontmatter: false,
103                    has_bom: false,
104                },
105                Vec::new(),
106            ));
107        };
108
109        let yaml_text = regions.yaml;
110        if yaml_text.trim().is_empty() {
111            return Ok((
112                Self {
113                    yaml: Mapping::new(),
114                    body: regions.body.to_string(),
115                    has_frontmatter: true,
116                    has_bom: regions.has_bom,
117                },
118                Vec::new(),
119            ));
120        }
121
122        let value: Value = serde_yaml::from_str(yaml_text)?;
123        let structural_errors = validate_yaml_structure(yaml_text);
124        let yaml = match value {
125            Value::Mapping(mapping) => mapping,
126            Value::Null => Mapping::new(),
127            _ => return Err(FrontmatterError::NotAMapping),
128        };
129
130        Ok((
131            Self {
132                yaml,
133                body: regions.body.to_string(),
134                has_frontmatter: true,
135                has_bom: regions.has_bom,
136            },
137            structural_errors,
138        ))
139    }
140
141    /// Read all referenced skills as a flat list (`load` followed by `available`).
142    pub fn skills(&self) -> Vec<String> {
143        self.skills_structured().all()
144    }
145
146    /// Read `skills` in structured load/available form.
147    pub fn skills_structured(&self) -> SkillsSpec {
148        match self.get("skills") {
149            Some(Value::Mapping(mapping)) => SkillsSpec {
150                load: mapping
151                    .get(yaml_key("load"))
152                    .map(yaml_str_list)
153                    .unwrap_or_default(),
154                available: mapping
155                    .get(yaml_key("available"))
156                    .map(yaml_str_list)
157                    .unwrap_or_default(),
158            },
159            Some(value) => SkillsSpec {
160                load: yaml_str_list(value),
161                available: Vec::new(),
162            },
163            None => SkillsSpec::default(),
164        }
165    }
166
167    pub fn name(&self) -> Option<&str> {
168        self.get("name").and_then(Value::as_str)
169    }
170
171    pub fn get(&self, key: &str) -> Option<&Value> {
172        self.yaml.get(yaml_key(key))
173    }
174
175    pub fn get_mut(&mut self, key: &str) -> Option<&mut Value> {
176        self.yaml.get_mut(yaml_key(key))
177    }
178
179    /// Markdown body after frontmatter.
180    pub fn body(&self) -> &str {
181        &self.body
182    }
183
184    /// Replace the Markdown body while preserving the parsed frontmatter.
185    pub fn set_body(&mut self, body: String) {
186        self.body = body;
187    }
188
189    pub fn has_frontmatter(&self) -> bool {
190        self.has_frontmatter
191    }
192
193    /// All frontmatter keys as strings.
194    pub fn keys(&self) -> Vec<String> {
195        self.yaml
196            .keys()
197            .filter_map(|k| k.as_str().map(str::to_owned))
198            .collect()
199    }
200
201    /// Parsed top-level YAML, for schema transforms that must verify an edited source.
202    pub(crate) fn mapping(&self) -> &Mapping {
203        &self.yaml
204    }
205
206    /// Insert or replace a top-level frontmatter field.
207    pub fn insert(&mut self, key: &str, value: Value) {
208        self.has_frontmatter = true;
209        self.yaml.insert(yaml_key(key), value);
210    }
211
212    pub fn remove(&mut self, key: &str) -> Option<Value> {
213        self.yaml.shift_remove(yaml_key(key))
214    }
215
216    /// Serialize back to full markdown.
217    pub fn render(&self) -> String {
218        if !self.has_frontmatter && self.yaml.is_empty() {
219            return self.body.clone();
220        }
221        let mut out = if self.has_bom {
222            String::from("\u{feff}---\n")
223        } else {
224            String::from("---\n")
225        };
226        if !self.yaml.is_empty() {
227            let mut yaml = serde_yaml::to_string(&self.yaml)
228                .expect("serializing frontmatter mapping should succeed");
229            if let Some(stripped) = yaml.strip_prefix("---\n") {
230                yaml = stripped.to_string();
231            }
232            out.push_str(&yaml);
233            if !yaml.ends_with('\n') {
234                out.push('\n');
235            }
236        }
237        out.push_str("---\n");
238        out.push_str(&self.body);
239        out
240    }
241}
242
243/// Rename skills in frontmatter using exact-match replacement.
244fn rewrite_skills(fm: &mut Frontmatter, renames: &IndexMap<String, String>) -> IndexSet<String> {
245    let mut renamed = IndexSet::new();
246    let key = yaml_key("skills");
247    if let Some(value) = fm.yaml.get_mut(&key) {
248        rewrite_skill_value(value, renames, &mut renamed);
249    }
250
251    renamed
252}
253
254/// Rename subagents in frontmatter using exact-match replacement.
255fn rewrite_subagents(fm: &mut Frontmatter, renames: &IndexMap<String, String>) -> IndexSet<String> {
256    rewrite_string_list_field(fm, "subagents", renames)
257}
258
259/// Parse content, rewrite skills, and render updated content if changed.
260pub fn rewrite_content_skills(
261    content: &str,
262    renames: &IndexMap<String, String>,
263) -> Result<Option<String>, FrontmatterError> {
264    let mut fm = Frontmatter::parse(content)?;
265    let renamed = rewrite_skills(&mut fm, renames);
266    if renamed.is_empty() {
267        Ok(None)
268    } else {
269        Ok(Some(fm.render()))
270    }
271}
272
273/// Parse content, rewrite subagents, and render updated content if changed.
274pub fn rewrite_content_subagents(
275    content: &str,
276    renames: &IndexMap<String, String>,
277) -> Result<Option<String>, FrontmatterError> {
278    let mut fm = Frontmatter::parse(content)?;
279    let renamed = rewrite_subagents(&mut fm, renames);
280    if renamed.is_empty() {
281        Ok(None)
282    } else {
283        Ok(Some(fm.render()))
284    }
285}
286
287fn rewrite_string_list_field(
288    fm: &mut Frontmatter,
289    field_name: &str,
290    renames: &IndexMap<String, String>,
291) -> IndexSet<String> {
292    let mut renamed = IndexSet::new();
293    let key = yaml_key(field_name);
294    if let Some(value) = fm.yaml.get_mut(&key) {
295        rewrite_string_list_value(value, renames, &mut renamed);
296    }
297
298    renamed
299}
300
301fn yaml_str_list(val: &Value) -> Vec<String> {
302    match val {
303        Value::Sequence(seq) => seq
304            .iter()
305            .filter_map(Value::as_str)
306            .map(str::to_owned)
307            .collect(),
308        Value::String(s) => vec![s.clone()],
309        _ => vec![],
310    }
311}
312
313fn rewrite_skill_value(
314    value: &mut Value,
315    renames: &IndexMap<String, String>,
316    renamed: &mut IndexSet<String>,
317) {
318    match value {
319        Value::Sequence(_) | Value::String(_) => rewrite_string_list_value(value, renames, renamed),
320        Value::Mapping(mapping) => {
321            for field in ["load", "available"] {
322                if let Some(child) = mapping.get_mut(yaml_key(field)) {
323                    rewrite_skill_value(child, renames, renamed);
324                }
325            }
326        }
327        _ => {}
328    }
329}
330
331fn rewrite_string_list_value(
332    value: &mut Value,
333    renames: &IndexMap<String, String>,
334    renamed: &mut IndexSet<String>,
335) {
336    match value {
337        Value::Sequence(seq) => {
338            for item in seq {
339                let Some(name) = item.as_str() else {
340                    continue;
341                };
342                if let Some(new_name) = renames.get(name) {
343                    renamed.insert(name.to_string());
344                    *item = Value::String(new_name.clone());
345                }
346            }
347        }
348        Value::String(name) => {
349            if let Some(new_name) = renames.get(name.as_str()) {
350                renamed.insert(name.clone());
351                *name = new_name.clone();
352            }
353        }
354        _ => {}
355    }
356}
357
358fn exceeds_flow_depth(yaml: &str) -> bool {
359    let mut depth = 0usize;
360    for byte in yaml.bytes() {
361        match byte {
362            b'[' | b'{' => {
363                depth += 1;
364                if depth > MAX_FLOW_DEPTH {
365                    return true;
366                }
367            }
368            b']' | b'}' => depth = depth.saturating_sub(1),
369            _ => {}
370        }
371    }
372    false
373}
374
375/// A document's frontmatter region: the YAML between the fences, where it starts in the
376/// document, and the Markdown after the closing fence.
377struct Regions<'a> {
378    has_bom: bool,
379    /// Byte offset of `yaml`: past a byte-order mark and the opening fence line.
380    yaml_start: usize,
381    yaml: &'a str,
382    body: &'a str,
383}
384
385/// The frontmatter region of `content`, and `None` when it has no frontmatter.
386fn split_regions(content: &str) -> Result<Option<Regions<'_>>, FrontmatterError> {
387    let (has_bom, document) = content
388        .strip_prefix('\u{feff}')
389        .map_or((false, content), |document| (true, document));
390    let (first_line, after_first_line) = split_first_line(document);
391    if !is_delimiter_line(first_line) {
392        return Ok(None);
393    }
394
395    let mut yaml_end = None;
396    let mut offset = 0usize;
397    for line in after_first_line.split_inclusive('\n') {
398        if is_delimiter_line(line) {
399            yaml_end = Some((offset, line.len()));
400            break;
401        }
402        offset += line.len();
403    }
404
405    let Some((yaml_len, closing_len)) = yaml_end else {
406        return Err(FrontmatterError::Unclosed);
407    };
408
409    if yaml_len > MAX_FRONTMATTER_BYTES {
410        return Err(FrontmatterError::TooLarge(yaml_len));
411    }
412    let yaml = &after_first_line[..yaml_len];
413    if exceeds_flow_depth(yaml) {
414        return Err(FrontmatterError::TooDeep);
415    }
416    Ok(Some(Regions {
417        has_bom,
418        yaml_start: content.len() - after_first_line.len(),
419        yaml,
420        body: &after_first_line[yaml_len + closing_len..],
421    }))
422}
423
424/// The YAML text between a document's frontmatter fences, and where it starts in the document.
425pub(crate) fn yaml_text(content: &str) -> Result<Option<(&str, usize)>, FrontmatterError> {
426    Ok(split_regions(content)?.map(|regions| (regions.yaml, regions.yaml_start)))
427}
428
429fn split_first_line(content: &str) -> (&str, &str) {
430    match content.split_once('\n') {
431        Some((first, rest)) => (first, rest),
432        None => (content, ""),
433    }
434}
435
436fn is_delimiter_line(line: &str) -> bool {
437    line.strip_suffix('\n')
438        .unwrap_or(line)
439        .strip_suffix('\r')
440        .unwrap_or(line.strip_suffix('\n').unwrap_or(line))
441        == "---"
442}
443
444fn validate_yaml_structure(text: &str) -> Vec<FrontmatterError> {
445    use yaml_rust2::parser::{Event, MarkedEventReceiver, Parser};
446    use yaml_rust2::scanner::Marker;
447
448    #[derive(Default)]
449    struct StructuralEvents {
450        anchor_or_alias: bool,
451        document_end: bool,
452        source: String,
453        char_to_byte: Vec<usize>,
454    }
455    impl MarkedEventReceiver for StructuralEvents {
456        fn on_event(&mut self, event: Event, marker: Marker) {
457            match event {
458                Event::Alias(_) | Event::Scalar(_, _, 1.., _) => self.anchor_or_alias = true,
459                Event::SequenceStart(1.., _) | Event::MappingStart(1.., _) => {
460                    self.anchor_or_alias = true;
461                }
462                Event::DocumentEnd => {
463                    let byte = self.char_to_byte.get(marker.index()).copied();
464                    if byte.is_some_and(|byte| self.source[byte..].starts_with("...")) {
465                        self.document_end = true;
466                    }
467                }
468                _ => {}
469            }
470        }
471    }
472
473    let mut char_to_byte: Vec<usize> = text.char_indices().map(|(byte, _)| byte).collect();
474    char_to_byte.push(text.len());
475    let mut events = StructuralEvents {
476        source: text.to_owned(),
477        char_to_byte,
478        ..StructuralEvents::default()
479    };
480    // serde_yaml already accepted the document. The event parser is used only
481    // to distinguish YAML structure from identical text inside scalar values.
482    let parse_error = Parser::new_from_str(text).load(&mut events, true).err();
483    let mut errors = Vec::new();
484    if events.anchor_or_alias {
485        errors.push(FrontmatterError::Anchor);
486    }
487    if events.document_end {
488        errors.push(FrontmatterError::DocumentEnd);
489    }
490    if let Some(error) = parse_error {
491        errors.push(FrontmatterError::UnsupportedSyntax(error.to_string()));
492    }
493    errors
494}
495
496fn yaml_key(key: &str) -> Value {
497    Value::String(key.to_string())
498}
499
500#[cfg(test)]
501mod tests {
502    use super::*;
503
504    #[test]
505    fn parse_and_render_roundtrip() {
506        let input = "---\nname: coder\nskills:\n- plan\n- review\n---\n# Body\ntext";
507        let fm = Frontmatter::parse(input).unwrap();
508        assert_eq!(fm.name(), Some("coder"));
509        assert_eq!(fm.skills(), vec!["plan", "review"]);
510        assert_eq!(fm.body(), "# Body\ntext");
511        assert!(fm.has_frontmatter());
512
513        let rendered = fm.render();
514        let reparsed = Frontmatter::parse(&rendered).unwrap();
515        assert_eq!(reparsed.name(), Some("coder"));
516        assert_eq!(reparsed.skills(), vec!["plan", "review"]);
517        assert_eq!(reparsed.body(), "# Body\ntext");
518    }
519
520    #[test]
521    fn parse_without_frontmatter_keeps_body() {
522        let input = "# Markdown only\ntext";
523        let fm = parse(input).unwrap();
524        assert!(!fm.has_frontmatter());
525        assert!(fm.skills().is_empty());
526        assert_eq!(fm.body(), input);
527        assert_eq!(fm.render(), input);
528    }
529
530    #[test]
531    fn parse_empty_frontmatter_roundtrips_delimiters() {
532        let input = "---\n---\nbody";
533        let fm = Frontmatter::parse(input).unwrap();
534        assert!(fm.has_frontmatter());
535        assert!(fm.skills().is_empty());
536        assert_eq!(fm.body(), "body");
537        assert_eq!(fm.render(), input);
538    }
539
540    #[test]
541    fn parse_malformed_yaml_errors() {
542        let input = "---\ninvalid: [:\n---\nbody";
543        assert!(matches!(
544            Frontmatter::parse(input),
545            Err(FrontmatterError::MalformedYaml(_))
546        ));
547    }
548
549    #[test]
550    fn parse_flow_style_skills() {
551        let input = "---\nskills: [plan, review]\n---\nbody";
552        let fm = Frontmatter::parse(input).unwrap();
553        assert_eq!(fm.skills(), vec!["plan", "review"]);
554        assert_eq!(fm.skills_structured().load, vec!["plan", "review"]);
555        assert!(fm.skills_structured().available.is_empty());
556    }
557
558    #[test]
559    fn parse_structured_skills() {
560        let input = "---\nskills:\n  load: [principles]\n  available:\n    - planning\n    - spawn\n---\nbody";
561        let fm = Frontmatter::parse(input).unwrap();
562        assert_eq!(fm.skills(), vec!["principles", "planning", "spawn"]);
563        assert_eq!(fm.skills_structured().load, vec!["principles"]);
564        assert_eq!(fm.skills_structured().available, vec!["planning", "spawn"]);
565    }
566
567    #[test]
568    fn rewrite_structured_skills_preserves_split() {
569        let input = "---\nskills:\n  load: [plan]\n  available: [review]\n---\nbody\n";
570        let renames = IndexMap::from([
571            ("plan".to_string(), "plan__org".to_string()),
572            ("review".to_string(), "review__org".to_string()),
573        ]);
574
575        let rewritten = rewrite_content_skills(input, &renames).unwrap().unwrap();
576        let fm = Frontmatter::parse(&rewritten).unwrap();
577        assert_eq!(fm.skills_structured().load, vec!["plan__org"]);
578        assert_eq!(fm.skills_structured().available, vec!["review__org"]);
579    }
580
581    #[test]
582    fn rewrite_does_not_corrupt_substrings() {
583        let input = "---\nskills:\n- plan\n- planner\n- planning-extended\n---\nbody\n";
584        let renames = IndexMap::from([(
585            "plan".to_string(),
586            "plan__meridian-flow_meridian-base".to_string(),
587        )]);
588
589        let rewritten = rewrite_content_skills(input, &renames).unwrap().unwrap();
590        let fm = Frontmatter::parse(&rewritten).unwrap();
591        assert_eq!(
592            fm.skills(),
593            vec![
594                "plan__meridian-flow_meridian-base",
595                "planner",
596                "planning-extended"
597            ]
598        );
599    }
600
601    #[test]
602    fn rewrite_subagents_uses_exact_matches() {
603        let input = "---\nsubagents:\n- web-researcher\n- web\n---\nbody\n";
604        let renames = IndexMap::from([(
605            "web-researcher".to_string(),
606            "web-researcher__source-a".to_string(),
607        )]);
608
609        let rewritten = rewrite_content_subagents(input, &renames).unwrap().unwrap();
610        let fm = Frontmatter::parse(&rewritten).unwrap();
611        assert_eq!(
612            fm.get("subagents").map(yaml_str_list).unwrap(),
613            vec!["web-researcher__source-a", "web"]
614        );
615    }
616}