1use 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#[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 #[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 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
78pub(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
90pub(crate) const DOCS: &str = "https://github.com/haowjy/mars-agents/blob/main/docs/config";
93
94pub 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
106pub 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
121pub(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
212pub(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}