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(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 an Agent from an installed `.mars` tree.
47///
48/// The bytes are what the Mars that installed them wrote, not an authored schema v1 file: a tree
49/// an older Mars wrote carries the pre-v1 spellings (`type`, `when_to_use`, a `tools` list,
50/// `permission`, ...) that the strict reader refuses. When the strict reading reports one, the
51/// file is upgraded in memory with the same conversion `prepare` applies to a pre-v1 package and
52/// read again. A file that reports any other error is simply invalid, and keeps that error: only
53/// a spelling the upgrade can cure says the bytes predate schema v1. The upgrade's notes are
54/// about the authored file, which `mars sync` and `mars migrate` report, so only the reading is
55/// returned. An authored package's own Agent is read strictly with [`crate::agent::read`].
56pub fn installed_agent(text: &str) -> DefinitionRead<crate::agent::AgentProfile> {
57    installed(text, DefinitionKind::Agent, crate::agent::read)
58}
59
60/// Read a skill from an installed `.mars` tree; the skill counterpart of [`installed_agent`].
61pub fn installed_skill(text: &str) -> DefinitionRead<crate::skill::SkillProfile> {
62    installed(text, DefinitionKind::Skill, crate::skill::read)
63}
64
65fn installed<T>(
66    text: &str,
67    kind: DefinitionKind,
68    strict: impl Fn(&str) -> DefinitionRead<T>,
69) -> DefinitionRead<T> {
70    let reading = strict(text);
71    // `field.removed` is a key or value the reader names, and `tools.list-form` is the one pre-v1
72    // shape Mars rewrote without removing a key. Both are what `upgrade_definition` converts.
73    let pre_v1 = reading.diagnostics.iter().any(|diagnostic| {
74        matches!(
75            diagnostic.code.as_str(),
76            "field.removed" | "tools.list-form"
77        )
78    });
79    if !pre_v1 {
80        return reading;
81    }
82    match crate::upgrade::upgrade_definition(kind, text) {
83        Ok(upgraded) => strict(&upgraded.text),
84        // A file the upgrade cannot parse is one the strict reader reports on as well.
85        Err(_) => reading,
86    }
87}
88
89/// Read one schema-owned file, choosing the reader from its package-relative path. A file read
90/// here is schema 1, so an Agent with no frontmatter is an error (see [`require_agent_frontmatter`]).
91pub fn read(path: &str, text: &str) -> Result<Reading, UnrecognizedPath> {
92    let parts: Vec<&str> = path.split('/').collect();
93    match parts.as_slice() {
94        ["mars.toml"] => Ok(Reading::Manifest(crate::manifest::read(text))),
95        ["agents", file]
96            if file
97                .strip_suffix(".md")
98                .is_some_and(|slug| !slug.is_empty()) =>
99        {
100            Ok(read_authored(DefinitionKind::Agent, text))
101        }
102        ["skills", slug, "SKILL.md"] if !slug.is_empty() => {
103            Ok(read_definition(DefinitionKind::Skill, text))
104        }
105        _ => Err(UnrecognizedPath(path.to_owned())),
106    }
107}
108
109/// Read one Agent or skill file, the one way: the structure-preserving parse (an anchor, a
110/// document-end marker and the like are diagnostics beside the fields, never a refusal to read
111/// them), then the kind's field reader. `agent::read`, `skill::read`, `read` and `prepare`
112/// are this function.
113pub(crate) fn read_definition(kind: DefinitionKind, text: &str) -> Reading {
114    match kind {
115        DefinitionKind::Agent => Reading::Agent(crate::agent::read(text)),
116        DefinitionKind::Skill => Reading::Skill(crate::skill::read(text)),
117    }
118}
119
120/// [`read_definition`] for a file written as schema 1: an Agent with no frontmatter is an error.
121/// Installed trees, pre-v1 packages and foreign layouts are read with [`read_definition`]
122/// alone, because their body-only Agents were valid in the format that wrote them.
123pub(crate) fn read_authored(kind: DefinitionKind, text: &str) -> Reading {
124    let mut reading = read_definition(kind, text);
125    if let Reading::Agent(agent) = &mut reading {
126        require_agent_frontmatter(text, &mut agent.diagnostics);
127    }
128    reading
129}
130
131/// A file whose first line is not `---` has no frontmatter, so every field takes its default,
132/// and the defaults are the widest permissions: one stray line above `---` would turn a narrow
133/// Agent into an unrestricted one that reads clean.
134fn require_agent_frontmatter(text: &str, diagnostics: &mut Vec<SchemaDiagnostic>) {
135    if matches!(crate::frontmatter::yaml_text(text), Ok(None)) {
136        diagnostics.insert(0, crate::diagnostic::frontmatter_missing());
137    }
138}
139
140/// What the strict field reader says about `fm`, without the structure parse.
141pub(crate) fn field_diagnostics(kind: DefinitionKind, fm: &Frontmatter) -> Vec<SchemaDiagnostic> {
142    let mut diagnostics = Vec::new();
143    match kind {
144        DefinitionKind::Agent => {
145            crate::agent::read_fields(fm, &mut diagnostics);
146        }
147        DefinitionKind::Skill => {
148            crate::skill::read_fields(fm, &mut diagnostics);
149        }
150    }
151    diagnostics
152}
153
154/// The structure-preserving parse and ordered frontmatter shared by the Agent and skill
155/// readers; `fields` is the kind's field reader. Diagnostics come in the order structure,
156/// fields, then values with no JSON form.
157pub(crate) fn read_with<T>(
158    text: &str,
159    fields: impl FnOnce(&Frontmatter, &mut Vec<SchemaDiagnostic>) -> T,
160) -> DefinitionRead<T> {
161    match Frontmatter::parse_preserving_structure(text) {
162        Ok((frontmatter, structural_errors)) => {
163            let mut diagnostics = structural_errors
164                .iter()
165                .map(crate::diagnostic::frontmatter_error)
166                .collect::<Vec<_>>();
167            let fields = fields(&frontmatter, &mut diagnostics);
168            DefinitionRead {
169                frontmatter: frontmatter_json(frontmatter.mapping(), &mut diagnostics),
170                fields: Some(fields),
171                body: Some(frontmatter.body().to_string()),
172                diagnostics,
173            }
174        }
175        Err(error) => DefinitionRead::unread(vec![crate::diagnostic::frontmatter_error(&error)]),
176    }
177}
178
179#[derive(Debug, Clone, Serialize)]
180pub struct DefinitionRead<T> {
181    /// Ordered top-level mapping, retaining unknown authored keys.
182    pub frontmatter: Vec<(String, OrderedValue)>,
183    pub fields: Option<T>,
184    pub body: Option<String>,
185    pub diagnostics: Vec<SchemaDiagnostic>,
186}
187
188/// A definition with no errors: see [`DefinitionRead::into_valid`].
189#[derive(Debug, Clone)]
190pub struct Valid<T> {
191    pub fields: T,
192    pub body: String,
193    pub warnings: Vec<SchemaDiagnostic>,
194}
195
196impl<T> DefinitionRead<T> {
197    /// A file that could not be read: no fields, only why.
198    pub(crate) fn unread(diagnostics: Vec<SchemaDiagnostic>) -> Self {
199        Self {
200            frontmatter: Vec::new(),
201            fields: None,
202            body: None,
203            diagnostics,
204        }
205    }
206
207    /// The typed fields, or why there are none: the frontmatter cannot be parsed at all.
208    pub fn into_fields(self) -> Result<T, String> {
209        self.fields.ok_or_else(|| {
210            self.diagnostics
211                .first()
212                .map_or("unreadable".to_owned(), |diagnostic| {
213                    diagnostic.message.clone()
214                })
215        })
216    }
217
218    /// What a caller that acts on the file needs: the fields, the body and the warnings that
219    /// came with them, or the first error. A file with any error is refused whole.
220    pub fn into_valid(self) -> Result<Valid<T>, SchemaDiagnostic> {
221        if let Some(error) = self
222            .diagnostics
223            .iter()
224            .find(|diagnostic| diagnostic.is_error())
225        {
226            return Err(error.clone());
227        }
228        match (self.fields, self.body) {
229            (Some(fields), Some(body)) => Ok(Valid {
230                fields,
231                body,
232                warnings: self.diagnostics,
233            }),
234            _ => unreachable!("a reading with no error has its fields and body"),
235        }
236    }
237}
238
239pub(crate) fn frontmatter_json(
240    mapping: &serde_yaml::Mapping,
241    diagnostics: &mut Vec<SchemaDiagnostic>,
242) -> Vec<(String, OrderedValue)> {
243    mapping
244        .iter()
245        .filter_map(|(key, value)| {
246            let Some(key) = key.as_str() else {
247                diagnostics.push(SchemaDiagnostic::new(
248                    "yaml.non-string-key",
249                    crate::diagnostic::Severity::Error,
250                    Vec::new(),
251                    "frontmatter keys must be strings",
252                ));
253                return None;
254            };
255            match OrderedValue::from_yaml(value) {
256                Ok(value) => Some((key.to_owned(), value)),
257                Err(message) => {
258                    diagnostics.push(SchemaDiagnostic::new(
259                        "yaml.non-json-value",
260                        crate::diagnostic::Severity::Error,
261                        vec![crate::diagnostic::PathSegment::Key(key.to_owned())],
262                        message,
263                    ));
264                    None
265                }
266            }
267        })
268        .collect()
269}