Skip to main content

mars_schema/
diagnostic.rs

1//! Stable diagnostics returned by schema operations.
2
3use serde::{Deserialize, Serialize};
4
5use crate::item::DefinitionKind;
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
8#[serde(rename_all = "lowercase")]
9pub enum Severity {
10    Error,
11    Warning,
12    Info,
13}
14
15#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
16#[serde(untagged)]
17pub enum PathSegment {
18    Key(String),
19    Index(usize),
20}
21
22/// Byte offsets into the file text. Only fence and YAML-syntax errors may carry one
23/// (`serde_yaml` has no spans; divergence V3), and no reader sets it yet. Every other
24/// diagnostic is located by `path`, which consumers map to a range with their own parser.
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
26pub struct ByteRange {
27    pub start: usize,
28    pub end: usize,
29}
30
31#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
32pub struct SchemaDiagnostic {
33    pub code: String,
34    pub severity: Severity,
35    pub path: Vec<PathSegment>,
36    pub message: String,
37    #[serde(skip_serializing_if = "Option::is_none")]
38    pub range: Option<ByteRange>,
39    /// What the package declares does not reach the installed files (a dropped restriction, a
40    /// hook Mars cannot convert). Whoever owns the item, the installer's agents behave
41    /// differently from what the package says.
42    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
43    pub lost: bool,
44}
45
46impl SchemaDiagnostic {
47    pub fn new(
48        code: impl Into<String>,
49        severity: Severity,
50        path: Vec<PathSegment>,
51        message: impl Into<String>,
52    ) -> Self {
53        Self {
54            code: code.into(),
55            severity,
56            path,
57            message: message.into(),
58            range: None,
59            lost: false,
60        }
61    }
62
63    /// Mark this as a loss of declared behaviour: see [`Self::lost`].
64    pub fn losing(mut self) -> Self {
65        self.lost = true;
66        self
67    }
68
69    pub fn is_error(&self) -> bool {
70        self.severity == Severity::Error
71    }
72
73    pub fn message(&self) -> &str {
74        &self.message
75    }
76}
77
78/// What an Agent or skill reader reports for a key it has no field for: `field.retired` when
79/// Mars moved off it, else `field.unknown`. Either way the key stays in the authored file and
80/// reaches no native file.
81pub(crate) fn unrecognized_field(kind: DefinitionKind, key: &str) -> SchemaDiagnostic {
82    let scope = match kind {
83        DefinitionKind::Agent => crate::retired::Scope::Agent,
84        DefinitionKind::Skill => crate::retired::Scope::Skill,
85    };
86    crate::retired::diagnostic(scope, key, key_path(key))
87        .unwrap_or_else(|| unknown_field(key_path(key), "", key))
88}
89
90/// The page that says how to fix a key Mars no longer reads, and where the docs for a
91/// `[package]` that predates schema 1 live.
92pub(crate) const DOCS: &str = "https://github.com/haowjy/mars-agents/blob/main/docs/config";
93
94/// A key a reader has no field for. Nothing is lost by ignoring it and it may be intended
95/// (a typo, or a key from a newer Mars), so it is `Info`: `validate`, `check` and `--verbose`
96/// show it. `table` is as in [`unknown_key_message`].
97pub fn unknown_field(path: Vec<PathSegment>, table: &str, key: &str) -> SchemaDiagnostic {
98    SchemaDiagnostic::new(
99        "field.unknown",
100        Severity::Info,
101        path,
102        unknown_key_message(table, key),
103    )
104}
105
106/// The one warning for a key that a project, package or user config file carries and this Mars
107/// does not read. `table` is the dotted table the key sits in, empty at the top of the file.
108/// The key stays in the file: an older Mars cannot tell a typo from a key a newer one reads.
109pub fn unknown_key_message(table: &str, key: &str) -> String {
110    let table = if table.is_empty() {
111        String::new()
112    } else {
113        format!("[{table}] ")
114    };
115    format!(
116        "{table}unknown key `{key}` is not read by Mars v{} (a typo, or a key from a newer Mars); it stays in the file",
117        crate::VERSION
118    )
119}
120
121/// A bad value for a field the item kind defines (`kind` is the noun in the message).
122pub(crate) fn push_invalid(
123    kind: &str,
124    diags: &mut Vec<SchemaDiagnostic>,
125    path: Vec<PathSegment>,
126    value: impl Into<String>,
127    allowed: &'static str,
128) {
129    let value = value.into();
130    let severity = if matches!(path.first(), Some(PathSegment::Key(key)) if key == "harness-overrides")
131    {
132        Severity::Warning
133    } else {
134        Severity::Error
135    };
136    let display_field = if matches!(path.first(), Some(PathSegment::Key(key)) if key == "model-policies")
137    {
138        path.iter()
139            .map(|segment| match segment {
140                PathSegment::Key(key) => key.clone(),
141                PathSegment::Index(index) => format!("[{}]", index),
142            })
143            .fold(String::new(), |mut display, segment| {
144                if !display.is_empty() && !segment.starts_with('[') {
145                    display.push('.');
146                }
147                display.push_str(&segment);
148                display
149            })
150    } else {
151        display_path(&path)
152    };
153    diags.push(SchemaDiagnostic::new(
154        "field.value",
155        severity,
156        path,
157        format!("{kind} field `{display_field}` has invalid value `{value}`; allowed: {allowed}"),
158    ));
159}
160
161pub(crate) fn key_path(field: impl Into<String>) -> Vec<PathSegment> {
162    vec![PathSegment::Key(field.into())]
163}
164
165pub(crate) fn child_path(parent: impl Into<String>, child: impl Into<String>) -> Vec<PathSegment> {
166    vec![
167        PathSegment::Key(parent.into()),
168        PathSegment::Key(child.into()),
169    ]
170}
171
172pub fn display_path(path: &[PathSegment]) -> String {
173    let mut display = String::new();
174    for segment in path {
175        match segment {
176            PathSegment::Key(key) => {
177                if !display.is_empty() {
178                    display.push('.');
179                }
180                display.push_str(key);
181            }
182            PathSegment::Index(index) => {
183                use std::fmt::Write;
184                let _ = write!(display, "[{index}]");
185            }
186        }
187    }
188    display
189}
190
191pub(crate) fn frontmatter_error(error: &crate::frontmatter::FrontmatterError) -> SchemaDiagnostic {
192    let code = match error {
193        crate::frontmatter::FrontmatterError::TooLarge(_) => "frontmatter.too-large",
194        crate::frontmatter::FrontmatterError::TooDeep => "frontmatter.too-deep",
195        crate::frontmatter::FrontmatterError::Unclosed => "frontmatter.unclosed",
196        crate::frontmatter::FrontmatterError::Anchor => "yaml.anchor",
197        crate::frontmatter::FrontmatterError::DocumentEnd => "yaml.document-end",
198        crate::frontmatter::FrontmatterError::UnsupportedSyntax(_) => "yaml.unsupported-syntax",
199        crate::frontmatter::FrontmatterError::NotAMapping => "frontmatter.not-mapping",
200        crate::frontmatter::FrontmatterError::MalformedYaml(inner) => {
201            let message = inner.to_string();
202            if message.contains("duplicate entry") || message.contains("duplicate key") {
203                "yaml.duplicate-key"
204            } else {
205                "yaml.invalid"
206            }
207        }
208    };
209    SchemaDiagnostic::new(code, Severity::Error, Vec::new(), error.to_string())
210}
211
212/// An Agent whose first line is not exactly `---`, read where the file is schema 1.
213pub(crate) fn frontmatter_missing() -> SchemaDiagnostic {
214    SchemaDiagnostic::new(
215        "frontmatter.missing",
216        Severity::Error,
217        Vec::new(),
218        "an Agent's frontmatter must open with a first line that is exactly `---`; without it every field takes its default",
219    )
220}