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 if crate::upgrade::PRE_V1.key(kind, key) {
71 return crate::upgrade::pre_v1_key(key_path(key), key);
72 }
73 unknown_field(key_path(key), "", key)
74}
75
76pub(crate) fn unknown_field(path: Vec<PathSegment>, table: &str, key: &str) -> SchemaDiagnostic {
80 SchemaDiagnostic::new(
81 "field.unknown",
82 Severity::Info,
83 path,
84 unknown_key_message(table, key),
85 )
86}
87
88pub fn unknown_key_message(table: &str, key: &str) -> String {
92 let table = if table.is_empty() {
93 String::new()
94 } else {
95 format!("[{table}] ")
96 };
97 format!(
98 "{table}unknown key `{key}` is not read by Mars v{} (a typo, or a key from a newer Mars); it stays in the file",
99 crate::VERSION
100 )
101}
102
103pub(crate) fn push_invalid(
105 kind: &str,
106 diags: &mut Vec<SchemaDiagnostic>,
107 path: Vec<PathSegment>,
108 value: impl Into<String>,
109 allowed: &'static str,
110) {
111 let value = value.into();
112 let severity = if matches!(path.first(), Some(PathSegment::Key(key)) if key == "harness-overrides")
113 {
114 Severity::Warning
115 } else {
116 Severity::Error
117 };
118 let display_field = if matches!(path.first(), Some(PathSegment::Key(key)) if key == "model-policies")
119 {
120 path.iter()
121 .map(|segment| match segment {
122 PathSegment::Key(key) => key.clone(),
123 PathSegment::Index(index) => format!("[{}]", index),
124 })
125 .fold(String::new(), |mut display, segment| {
126 if !display.is_empty() && !segment.starts_with('[') {
127 display.push('.');
128 }
129 display.push_str(&segment);
130 display
131 })
132 } else {
133 display_path(&path)
134 };
135 diags.push(SchemaDiagnostic::new(
136 "field.value",
137 severity,
138 path,
139 format!("{kind} field `{display_field}` has invalid value `{value}`; allowed: {allowed}"),
140 ));
141}
142
143pub(crate) fn key_path(field: impl Into<String>) -> Vec<PathSegment> {
144 vec![PathSegment::Key(field.into())]
145}
146
147pub(crate) fn child_path(parent: impl Into<String>, child: impl Into<String>) -> Vec<PathSegment> {
148 vec![
149 PathSegment::Key(parent.into()),
150 PathSegment::Key(child.into()),
151 ]
152}
153
154pub fn display_path(path: &[PathSegment]) -> String {
155 let mut display = String::new();
156 for segment in path {
157 match segment {
158 PathSegment::Key(key) => {
159 if !display.is_empty() {
160 display.push('.');
161 }
162 display.push_str(key);
163 }
164 PathSegment::Index(index) => {
165 use std::fmt::Write;
166 let _ = write!(display, "[{index}]");
167 }
168 }
169 }
170 display
171}
172
173pub(crate) fn frontmatter_error(error: &crate::frontmatter::FrontmatterError) -> SchemaDiagnostic {
174 let code = match error {
175 crate::frontmatter::FrontmatterError::TooLarge(_) => "frontmatter.too-large",
176 crate::frontmatter::FrontmatterError::TooDeep => "frontmatter.too-deep",
177 crate::frontmatter::FrontmatterError::Unclosed => "frontmatter.unclosed",
178 crate::frontmatter::FrontmatterError::Anchor => "yaml.anchor",
179 crate::frontmatter::FrontmatterError::DocumentEnd => "yaml.document-end",
180 crate::frontmatter::FrontmatterError::UnsupportedSyntax(_) => "yaml.unsupported-syntax",
181 crate::frontmatter::FrontmatterError::NotAMapping => "frontmatter.not-mapping",
182 crate::frontmatter::FrontmatterError::MalformedYaml(inner) => {
183 let message = inner.to_string();
184 if message.contains("duplicate entry") || message.contains("duplicate key") {
185 "yaml.duplicate-key"
186 } else {
187 "yaml.invalid"
188 }
189 }
190 };
191 SchemaDiagnostic::new(code, Severity::Error, Vec::new(), error.to_string())
192}
193
194pub(crate) fn frontmatter_missing() -> SchemaDiagnostic {
196 SchemaDiagnostic::new(
197 "frontmatter.missing",
198 Severity::Error,
199 Vec::new(),
200 "an Agent's frontmatter must open with a first line that is exactly `---`; without it every field takes its default",
201 )
202}