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}
40
41impl SchemaDiagnostic {
42 pub fn new(
43 code: impl Into<String>,
44 severity: Severity,
45 path: Vec<PathSegment>,
46 message: impl Into<String>,
47 ) -> Self {
48 Self {
49 code: code.into(),
50 severity,
51 path,
52 message: message.into(),
53 range: None,
54 }
55 }
56
57 pub fn is_error(&self) -> bool {
58 self.severity == Severity::Error
59 }
60
61 pub fn message(&self) -> &str {
62 &self.message
63 }
64}
65
66pub(crate) fn unrecognized_field(kind: DefinitionKind, key: &str) -> SchemaDiagnostic {
70 let scope = match kind {
71 DefinitionKind::Agent => crate::retired::Scope::Agent,
72 DefinitionKind::Skill => crate::retired::Scope::Skill,
73 };
74 crate::retired::diagnostic(scope, key, key_path(key))
75 .unwrap_or_else(|| unknown_field(key_path(key), "", key))
76}
77
78pub(crate) const DOCS: &str = "https://github.com/haowjy/mars-agents/blob/main/docs/config";
81
82pub fn unknown_field(path: Vec<PathSegment>, table: &str, key: &str) -> SchemaDiagnostic {
86 SchemaDiagnostic::new(
87 "field.unknown",
88 Severity::Info,
89 path,
90 unknown_key_message(table, key),
91 )
92}
93
94pub fn unknown_key_message(table: &str, key: &str) -> String {
98 let table = if table.is_empty() {
99 String::new()
100 } else {
101 format!("[{table}] ")
102 };
103 format!(
104 "{table}unknown key `{key}` is not read by Mars v{} (a typo, or a key from a newer Mars); it stays in the file",
105 crate::VERSION
106 )
107}
108
109pub(crate) fn push_invalid(
111 kind: &str,
112 diags: &mut Vec<SchemaDiagnostic>,
113 path: Vec<PathSegment>,
114 value: impl Into<String>,
115 allowed: &'static str,
116) {
117 let value = value.into();
118 let severity = if matches!(path.first(), Some(PathSegment::Key(key)) if key == "harness-overrides")
119 {
120 Severity::Warning
121 } else {
122 Severity::Error
123 };
124 let display_field = if matches!(path.first(), Some(PathSegment::Key(key)) if key == "model-policies")
125 {
126 path.iter()
127 .map(|segment| match segment {
128 PathSegment::Key(key) => key.clone(),
129 PathSegment::Index(index) => format!("[{}]", index),
130 })
131 .fold(String::new(), |mut display, segment| {
132 if !display.is_empty() && !segment.starts_with('[') {
133 display.push('.');
134 }
135 display.push_str(&segment);
136 display
137 })
138 } else {
139 display_path(&path)
140 };
141 diags.push(SchemaDiagnostic::new(
142 "field.value",
143 severity,
144 path,
145 format!("{kind} field `{display_field}` has invalid value `{value}`; allowed: {allowed}"),
146 ));
147}
148
149pub(crate) fn key_path(field: impl Into<String>) -> Vec<PathSegment> {
150 vec![PathSegment::Key(field.into())]
151}
152
153pub(crate) fn child_path(parent: impl Into<String>, child: impl Into<String>) -> Vec<PathSegment> {
154 vec![
155 PathSegment::Key(parent.into()),
156 PathSegment::Key(child.into()),
157 ]
158}
159
160pub fn display_path(path: &[PathSegment]) -> String {
161 let mut display = String::new();
162 for segment in path {
163 match segment {
164 PathSegment::Key(key) => {
165 if !display.is_empty() {
166 display.push('.');
167 }
168 display.push_str(key);
169 }
170 PathSegment::Index(index) => {
171 use std::fmt::Write;
172 let _ = write!(display, "[{index}]");
173 }
174 }
175 }
176 display
177}
178
179pub(crate) fn frontmatter_error(error: &crate::frontmatter::FrontmatterError) -> SchemaDiagnostic {
180 let code = match error {
181 crate::frontmatter::FrontmatterError::TooLarge(_) => "frontmatter.too-large",
182 crate::frontmatter::FrontmatterError::TooDeep => "frontmatter.too-deep",
183 crate::frontmatter::FrontmatterError::Unclosed => "frontmatter.unclosed",
184 crate::frontmatter::FrontmatterError::Anchor => "yaml.anchor",
185 crate::frontmatter::FrontmatterError::DocumentEnd => "yaml.document-end",
186 crate::frontmatter::FrontmatterError::UnsupportedSyntax(_) => "yaml.unsupported-syntax",
187 crate::frontmatter::FrontmatterError::NotAMapping => "frontmatter.not-mapping",
188 crate::frontmatter::FrontmatterError::MalformedYaml(inner) => {
189 let message = inner.to_string();
190 if message.contains("duplicate entry") || message.contains("duplicate key") {
191 "yaml.duplicate-key"
192 } else {
193 "yaml.invalid"
194 }
195 }
196 };
197 SchemaDiagnostic::new(code, Severity::Error, Vec::new(), error.to_string())
198}
199
200pub(crate) fn frontmatter_missing() -> SchemaDiagnostic {
202 SchemaDiagnostic::new(
203 "frontmatter.missing",
204 Severity::Error,
205 Vec::new(),
206 "an Agent's frontmatter must open with a first line that is exactly `---`; without it every field takes its default",
207 )
208}