Skip to main content

mars_schema/
read.rs

1//! The serialized v1 reading shared by native and WASM callers.
2
3use serde::Serialize;
4
5use crate::diagnostic::SchemaDiagnostic;
6use crate::frontmatter::Frontmatter;
7use crate::item::DefinitionKind;
8use crate::ordered::OrderedValue;
9
10/// The serialized v1 reading of one schema-owned file.
11///
12/// Serializes as the bare [`DefinitionRead`]; the caller knows the kind from the path (or, in
13/// a prepared package, from the definition's `kind`).
14#[derive(Debug, Clone, Serialize)]
15#[serde(untagged)]
16pub enum Reading {
17    Manifest(Box<crate::manifest::ManifestRead>),
18    Agent(DefinitionRead<crate::agent::AgentProfile>),
19    Skill(DefinitionRead<crate::skill::SkillProfile>),
20}
21
22impl Reading {
23    pub fn diagnostics(&self) -> &[SchemaDiagnostic] {
24        match self {
25            Self::Manifest(reading) => &reading.package.diagnostics,
26            Self::Agent(reading) => &reading.diagnostics,
27            Self::Skill(reading) => &reading.diagnostics,
28        }
29    }
30}
31
32/// `read` was given a path that is not a schema-owned file.
33#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
34#[error(
35    "`{0}` is not a schema file: expected `mars.toml`, `agents/<slug>.md` or `skills/<slug>/SKILL.md`"
36)]
37pub struct UnrecognizedPath(pub String);
38
39impl UnrecognizedPath {
40    /// A stable identifier for callers that map failures to their own codes.
41    pub fn code(&self) -> &'static str {
42        "read.unrecognized-path"
43    }
44}
45
46/// Read one schema-owned file, choosing the reader from its package-relative path. A file read
47/// here is schema 1, so an Agent with no frontmatter is an error (see [`require_agent_frontmatter`]).
48pub fn read(path: &str, text: &str) -> Result<Reading, UnrecognizedPath> {
49    let parts: Vec<&str> = path.split('/').collect();
50    match parts.as_slice() {
51        ["mars.toml"] => Ok(Reading::Manifest(Box::new(crate::manifest::read_all(text)))),
52        ["agents", file]
53            if file
54                .strip_suffix(".md")
55                .is_some_and(|slug| !slug.is_empty()) =>
56        {
57            Ok(read_authored(DefinitionKind::Agent, text))
58        }
59        ["skills", slug, "SKILL.md"] if !slug.is_empty() => {
60            Ok(read_definition(DefinitionKind::Skill, text))
61        }
62        _ => Err(UnrecognizedPath(path.to_owned())),
63    }
64}
65
66/// Read one Agent or skill file, the one way: the structure-preserving parse (an anchor, a
67/// document-end marker and the like are diagnostics beside the fields, never a refusal to read
68/// them), then the kind's field reader. `agent::read`, `skill::read`, `read` and `prepare`
69/// are this function.
70pub(crate) fn read_definition(kind: DefinitionKind, text: &str) -> Reading {
71    match kind {
72        DefinitionKind::Agent => Reading::Agent(crate::agent::read(text)),
73        DefinitionKind::Skill => Reading::Skill(crate::skill::read(text)),
74    }
75}
76
77/// [`read_definition`] for a file written as schema 1: an Agent with no frontmatter is an error.
78/// Installed trees and foreign layouts are read with [`read_definition`] alone, because their
79/// body-only Agents were valid in the format that wrote them.
80pub(crate) fn read_authored(kind: DefinitionKind, text: &str) -> Reading {
81    let mut reading = read_definition(kind, text);
82    if let Reading::Agent(agent) = &mut reading {
83        require_agent_frontmatter(text, &mut agent.diagnostics);
84    }
85    reading
86}
87
88/// A file whose first line is not `---` has no frontmatter, so every field takes its default,
89/// and the defaults are the widest permissions: one stray line above `---` would turn a narrow
90/// Agent into an unrestricted one that reads clean.
91fn require_agent_frontmatter(text: &str, diagnostics: &mut Vec<SchemaDiagnostic>) {
92    if matches!(crate::frontmatter::yaml_text(text), Ok(None)) {
93        diagnostics.insert(0, crate::diagnostic::frontmatter_missing());
94    }
95}
96
97/// What the strict field reader says about `fm`, without the structure parse.
98pub(crate) fn field_diagnostics(kind: DefinitionKind, fm: &Frontmatter) -> Vec<SchemaDiagnostic> {
99    let mut diagnostics = Vec::new();
100    match kind {
101        DefinitionKind::Agent => {
102            crate::agent::read_fields(fm, &mut diagnostics);
103        }
104        DefinitionKind::Skill => {
105            crate::skill::read_fields(fm, &mut diagnostics);
106        }
107    }
108    diagnostics
109}
110
111/// The structure-preserving parse and ordered frontmatter shared by the Agent and skill
112/// readers; `fields` is the kind's field reader. Diagnostics come in the order structure,
113/// fields, then values with no JSON form.
114pub(crate) fn read_with<T>(
115    text: &str,
116    fields: impl FnOnce(&Frontmatter, &mut Vec<SchemaDiagnostic>) -> T,
117) -> DefinitionRead<T> {
118    match Frontmatter::parse_preserving_structure(text) {
119        Ok((frontmatter, structural_errors)) => {
120            let mut diagnostics = structural_errors
121                .iter()
122                .map(crate::diagnostic::frontmatter_error)
123                .collect::<Vec<_>>();
124            let fields = fields(&frontmatter, &mut diagnostics);
125            DefinitionRead {
126                frontmatter: frontmatter_json(frontmatter.mapping(), &mut diagnostics),
127                fields: Some(fields),
128                body: Some(frontmatter.body().to_string()),
129                diagnostics,
130            }
131        }
132        Err(error) => DefinitionRead::unread(vec![crate::diagnostic::frontmatter_error(&error)]),
133    }
134}
135
136#[derive(Debug, Clone, Serialize)]
137pub struct DefinitionRead<T> {
138    /// Ordered top-level mapping, retaining unknown authored keys.
139    pub frontmatter: Vec<(String, OrderedValue)>,
140    pub fields: Option<T>,
141    pub body: Option<String>,
142    pub diagnostics: Vec<SchemaDiagnostic>,
143}
144
145/// A definition with no errors: see [`DefinitionRead::into_valid`].
146#[derive(Debug, Clone)]
147pub struct Valid<T> {
148    pub fields: T,
149    pub body: String,
150    pub warnings: Vec<SchemaDiagnostic>,
151}
152
153impl<T> DefinitionRead<T> {
154    /// A file that could not be read: no fields, only why.
155    pub(crate) fn unread(diagnostics: Vec<SchemaDiagnostic>) -> Self {
156        Self {
157            frontmatter: Vec::new(),
158            fields: None,
159            body: None,
160            diagnostics,
161        }
162    }
163
164    /// The typed fields, or why there are none: the frontmatter cannot be parsed at all.
165    pub fn into_fields(self) -> Result<T, String> {
166        self.fields.ok_or_else(|| {
167            self.diagnostics
168                .first()
169                .map_or("unreadable".to_owned(), |diagnostic| {
170                    diagnostic.message.clone()
171                })
172        })
173    }
174
175    /// What a caller that acts on the file needs: the fields, the body and the warnings that
176    /// came with them, or the first error. A file with any error is refused whole.
177    pub fn into_valid(self) -> Result<Valid<T>, SchemaDiagnostic> {
178        if let Some(error) = self
179            .diagnostics
180            .iter()
181            .find(|diagnostic| diagnostic.is_error())
182        {
183            return Err(error.clone());
184        }
185        match (self.fields, self.body) {
186            (Some(fields), Some(body)) => Ok(Valid {
187                fields,
188                body,
189                warnings: self.diagnostics,
190            }),
191            _ => unreachable!("a reading with no error has its fields and body"),
192        }
193    }
194}
195
196pub(crate) fn frontmatter_json(
197    mapping: &serde_yaml::Mapping,
198    diagnostics: &mut Vec<SchemaDiagnostic>,
199) -> Vec<(String, OrderedValue)> {
200    mapping
201        .iter()
202        .filter_map(|(key, value)| {
203            let Some(key) = key.as_str() else {
204                diagnostics.push(SchemaDiagnostic::new(
205                    "yaml.non-string-key",
206                    crate::diagnostic::Severity::Error,
207                    Vec::new(),
208                    "frontmatter keys must be strings",
209                ));
210                return None;
211            };
212            match OrderedValue::from_yaml(value) {
213                Ok(value) => Some((key.to_owned(), value)),
214                Err(message) => {
215                    diagnostics.push(SchemaDiagnostic::new(
216                        "yaml.non-json-value",
217                        crate::diagnostic::Severity::Error,
218                        vec![crate::diagnostic::PathSegment::Key(key.to_owned())],
219                        message,
220                    ));
221                    None
222                }
223            }
224        })
225        .collect()
226}