1use super::{
5 MAX_DECLARED_ITEMS, MutexTag, Profile, ProfileKind, ProfileVariantName,
6 declaration::reject_non_json_values,
7 identifier,
8 location::{self, Location},
9 mutex,
10 profile::AgentProfileOverrides,
11 schemas, settings,
12 validation::{present, text},
13};
14use artifactize_tools::artf::{AliasInvocation, Masked};
15use serde::{Deserialize, Serialize};
16use serde_json::{Map, Value};
17use std::collections::BTreeMap;
18
19const OVERRIDE_WRAPPER_PREFIX: &str = "_ = {";
21
22#[derive(Debug, Clone, Serialize, Deserialize)]
25pub struct EvalPayload {
26 pub instruction: String,
27 #[serde(flatten)]
28 pub extra: Map<String, Value>,
29}
30
31#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
34#[serde(transparent)]
35pub struct LocalEvalId(String);
36
37impl<'de> Deserialize<'de> for LocalEvalId {
38 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
39 String::deserialize(deserializer)?
40 .parse()
41 .map_err(serde::de::Error::custom)
42 }
43}
44
45impl std::str::FromStr for LocalEvalId {
46 type Err = String;
47 fn from_str(value: &str) -> Result<Self, Self::Err> {
48 identifier(value, "Eval id")?;
49 Ok(Self(value.to_owned()))
50 }
51}
52
53impl LocalEvalId {
54 pub fn as_str(&self) -> &str {
55 &self.0
56 }
57}
58
59impl PartialEq<&str> for LocalEvalId {
60 fn eq(&self, other: &&str) -> bool {
61 self.0 == *other
62 }
63}
64
65impl std::ops::Deref for LocalEvalId {
66 type Target = str;
67 fn deref(&self) -> &str {
68 &self.0
69 }
70}
71
72impl std::fmt::Display for LocalEvalId {
73 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
74 self.0.fmt(f)
75 }
76}
77
78#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
81pub enum Priority {
82 P0,
83 P1,
84 P2,
85 P3,
86}
87
88impl Priority {
89 pub const ALL: [Self; 4] = [Self::P0, Self::P1, Self::P2, Self::P3];
90
91 pub fn as_str(self) -> &'static str {
92 match self {
93 Self::P0 => "P0",
94 Self::P1 => "P1",
95 Self::P2 => "P2",
96 Self::P3 => "P3",
97 }
98 }
99}
100
101impl std::fmt::Display for Priority {
102 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
103 f.write_str(self.as_str())
104 }
105}
106
107#[derive(Debug, Clone, Serialize)]
108#[serde(rename_all = "camelCase")]
109pub struct EvalDeclaration {
110 pub id: LocalEvalId,
111 pub title: String,
112 #[serde(skip_serializing_if = "Vec::is_empty")]
113 pub mutex: Vec<MutexTag>,
114 #[serde(flatten)]
115 body: EvalBody,
116}
117
118#[derive(Debug, Clone, Serialize)]
120#[serde(rename_all = "camelCase")]
121struct EvalBody {
122 profile: Profile,
123 #[serde(skip_serializing_if = "BTreeMap::is_empty")]
124 profile_variants: BTreeMap<ProfileVariantName, Profile>,
125 payload: EvalPayload,
126 #[serde(skip_serializing_if = "Option::is_none")]
129 red_at: Option<Priority>,
130 pass_schema: Option<std::sync::Arc<Map<String, Value>>>,
132 fail_schema: Option<std::sync::Arc<Map<String, Value>>>,
133}
134
135impl EvalDeclaration {
136 pub fn profile(&self) -> &Profile {
137 &self.body.profile
138 }
139 pub fn payload(&self) -> Option<&EvalPayload> {
140 Some(&self.body.payload)
141 }
142 pub fn profile_variants(&self) -> &BTreeMap<ProfileVariantName, Profile> {
143 &self.body.profile_variants
144 }
145 pub fn red_at(&self) -> Option<Priority> {
146 self.body.red_at
147 }
148 pub fn pass_schema(&self) -> Option<&Map<String, Value>> {
149 self.body.pass_schema.as_deref()
150 }
151 pub fn fail_schema(&self) -> Option<&Map<String, Value>> {
152 self.body.fail_schema.as_deref()
153 }
154 #[cfg(test)]
155 pub(crate) fn profile_mut(&mut self) -> &mut Profile {
156 &mut self.body.profile
157 }
158 pub(crate) fn select_profile(&mut self, name: &ProfileVariantName) -> Result<(), String> {
159 self.body.profile = self
160 .body
161 .profile_variants
162 .get(name)
163 .ok_or_else(|| format!("Unknown profile variant: {name}"))?
164 .clone();
165 Ok(())
166 }
167}
168
169#[derive(Deserialize)]
170#[serde(rename_all = "snake_case", deny_unknown_fields)]
171struct EvalFields {
172 title: String,
173 #[serde(default, deserialize_with = "present")]
174 mutex: Option<Vec<MutexTag>>,
175 profile: Profile,
176 #[serde(default, deserialize_with = "present")]
177 profile_variants: Option<BTreeMap<ProfileVariantName, Profile>>,
178 #[serde(default, deserialize_with = "present")]
179 payload: Option<EvalPayload>,
180 #[serde(default, deserialize_with = "present")]
181 red_at: Option<Priority>,
182 #[serde(default, deserialize_with = "present")]
183 pass_schema: Option<Map<String, Value>>,
184 #[serde(default, deserialize_with = "present")]
185 fail_schema: Option<Map<String, Value>>,
186}
187
188#[derive(Deserialize)]
189#[serde(rename_all = "snake_case", deny_unknown_fields)]
190struct EvalNonProfileFields {
191 title: String,
192 #[serde(default, deserialize_with = "present")]
193 mutex: Option<Vec<MutexTag>>,
194 #[serde(default, deserialize_with = "present")]
195 payload: Option<EvalPayload>,
196 #[serde(default, deserialize_with = "present")]
197 red_at: Option<Priority>,
198 #[serde(default, deserialize_with = "present")]
199 pass_schema: Option<Map<String, Value>>,
200 #[serde(default, deserialize_with = "present")]
201 fail_schema: Option<Map<String, Value>>,
202}
203
204impl EvalDeclaration {
205 pub(super) fn parse_map(
208 location: &Location<'_, '_>,
209 source: &str,
210 masked: &Masked,
211 settings: &settings::Settings,
212 consumed: &mut [bool],
213 ) -> Result<Vec<Self>, String> {
214 let mut parsed = BTreeMap::new();
215 for (id_key, _) in location.table()? {
216 let id_str = id_key.get_ref().as_ref();
217 let eval_location = location.key(id_str);
218 let id: LocalEvalId = eval_location.check(id_str.parse())?;
219 let eval_table = eval_location.table()?;
220 if eval_table.get("profile").is_none() {
221 return Err(eval_location.error("missing field `profile`"));
222 }
223 let profile = parse_profile(
224 &eval_location.child("profile"),
225 source,
226 masked,
227 settings,
228 consumed,
229 )?;
230 let profile_variants = if eval_table.contains_key("profile_variants") {
231 let variants_location = eval_location.child("profile_variants");
232 let variants_table = variants_location.table()?;
233 if variants_table.len() > MAX_DECLARED_ITEMS {
234 return Err(variants_location
235 .error("profile_variants must contain at most 64 named profiles."));
236 }
237 let mut variants = BTreeMap::new();
238 for (variant_key, _) in variants_table {
239 let name = variant_key.get_ref().as_ref();
240 let name_location = variants_location.key(name);
241 let variant_name: ProfileVariantName = name_location.check(name.parse())?;
242 let variant_profile = parse_profile(
243 &variants_location.child(name),
244 source,
245 masked,
246 settings,
247 consumed,
248 )?;
249 variants.insert(variant_name, variant_profile);
250 }
251 Some(variants)
252 } else {
253 None
254 };
255 let mut rest_table = eval_table.clone();
256 rest_table.remove("profile");
257 rest_table.remove("profile_variants");
258 let rest_value = toml::Spanned::new(
259 eval_location.value().span(),
260 toml::de::DeValue::Table(rest_table),
261 );
262 let rest =
263 EvalNonProfileFields::deserialize(toml::de::ValueDeserializer::from(rest_value))
264 .map_err(|mut error| {
265 if !masked.invocations().is_empty() {
266 let offset = error.span().map_or(
267 eval_location.original_offset(eval_location.value().span().start),
268 |span| masked.original_offset(span.start),
269 );
270 return location::positioned(
271 source,
272 offset,
273 eval_location.path(),
274 error.message(),
275 );
276 }
277 error.set_input(Some(source));
278 eval_location.error(error)
279 })?;
280 let fields = EvalFields {
281 title: rest.title,
282 mutex: rest.mutex,
283 profile,
284 profile_variants,
285 payload: rest.payload,
286 red_at: rest.red_at,
287 pass_schema: rest.pass_schema,
288 fail_schema: rest.fail_schema,
289 };
290 let declaration = eval_location.check(Self::new(id.clone(), fields))?;
291 parsed.insert(id, declaration);
292 }
293 Ok(parsed.into_values().collect())
294 }
295
296 fn new(id: LocalEvalId, fields: EvalFields) -> Result<Self, String> {
298 if fields.mutex.is_some()
299 && !matches!(
300 fields.profile.kind(),
301 ProfileKind::Runtime | ProfileKind::Agent
302 )
303 {
304 return Err("mutex is supported only on runtime and agent Evals.".into());
305 }
306 let agent = fields.profile.kind() == ProfileKind::Agent;
307 if agent && (fields.pass_schema.is_some() || fields.fail_schema.is_some()) {
308 return Err("An Agent eval reports prioritized findings; remove pass_schema and fail_schema, and set red_at for the priority that makes it RED.".into());
309 }
310 if !agent && fields.red_at.is_some() {
311 return Err("red_at is supported only on agent Evals.".into());
312 }
313 let body = EvalBody {
314 profile: fields.profile,
315 profile_variants: fields.profile_variants.unwrap_or_default(),
316 payload: fields
317 .payload
318 .ok_or("Eval payload is required for runtime, agent and human profiles.")?,
319 red_at: fields.red_at,
320 pass_schema: fields.pass_schema.map(std::sync::Arc::new),
321 fail_schema: fields.fail_schema.map(std::sync::Arc::new),
322 };
323 Ok(Self {
324 id,
325 title: fields.title,
326 mutex: fields.mutex.unwrap_or_default(),
327 body,
328 })
329 }
330}
331
332impl EvalDeclaration {
333 pub(super) fn share(&mut self, schemas: &mut schemas::Schemas) {
334 for schema in [&mut self.body.pass_schema, &mut self.body.fail_schema]
335 .into_iter()
336 .flatten()
337 {
338 *schema = schemas.verdict(schema);
339 }
340 }
341
342 pub(super) fn validate(
343 &self,
344 location: &Location<'_, '_>,
345 schemas: &mut schemas::Schemas,
346 ) -> Result<(), String> {
347 location
348 .child("title")
349 .check(text(&self.title, "Eval title"))?;
350 if let Some(payload) = self.payload() {
351 location
352 .child("payload")
353 .child("instruction")
354 .check(text(&payload.instruction, "Eval payload.instruction"))?;
355 }
356 location
357 .child("mutex")
358 .check(mutex::validate(&self.mutex))?;
359 self.profile().validate(&location.child("profile"))?;
360 for (key, schema) in [
361 ("pass_schema", &self.body.pass_schema),
362 ("fail_schema", &self.body.fail_schema),
363 ] {
364 if let Some(schema) = schema {
365 location
366 .child(key)
367 .check(schemas.check(schema, crate::agent::verdict::validate_schema))?;
368 if self.profile().kind() == ProfileKind::Human {
370 location
371 .child(key)
372 .check(crate::review::Specification::parse(Some(schema)).map(drop))?;
373 }
374 }
375 }
376 if self.profile_variants().len() > MAX_DECLARED_ITEMS {
377 return Err(location
378 .child("profile_variants")
379 .error("profile_variants must contain at most 64 named profiles."));
380 }
381 for (name, profile) in self.profile_variants() {
382 let variant = location.child("profile_variants").child(name);
383 location
384 .child("profile_variants")
385 .key(name)
386 .check(identifier(name, "Profile variant name"))?;
387 profile.validate(&variant)?;
388 if std::mem::discriminant(profile) != std::mem::discriminant(self.profile()) {
389 return Err(
390 variant.error("Profile variants must retain the declared reviewer kind.")
391 );
392 }
393 }
394 Ok(())
395 }
396}
397
398pub(super) fn declared_evals<'de, D: serde::Deserializer<'de>>(
400 deserializer: D,
401) -> Result<Vec<EvalDeclaration>, D::Error> {
402 use serde::de::Error;
403 BTreeMap::<String, EvalFields>::deserialize(deserializer)?
404 .into_iter()
405 .map(|(id, fields)| {
406 let id = id.parse().map_err(D::Error::custom)?;
407 EvalDeclaration::new(id, fields).map_err(D::Error::custom)
408 })
409 .collect()
410}
411
412fn parse_profile(
413 location: &Location<'_, '_>,
414 source: &str,
415 masked: &Masked,
416 settings: &settings::Settings,
417 consumed: &mut [bool],
418) -> Result<Profile, String> {
419 if let toml::de::DeValue::String(text_value) = location.value().get_ref()
420 && let Some(index) = masked.invocation_index(text_value)
421 {
422 consumed[index] = true;
423 return resolve_alias(location, source, &masked.invocations()[index], settings);
424 }
425 if let Some(model) = location.value().get_ref().get("model")
426 && let toml::de::DeValue::String(model) = model.get_ref()
427 {
428 location
429 .child("model")
430 .check(text(model, "Agent profile model"))?;
431 }
432 location.deserialize()
433}
434
435fn resolve_alias(
436 location: &Location<'_, '_>,
437 source: &str,
438 invocation: &AliasInvocation,
439 settings: &settings::Settings,
440) -> Result<Profile, String> {
441 let path = location.path();
442 identifier(&invocation.name, "Profile alias name").map_err(|message| {
443 location::positioned(source, invocation.name_span.start, path, message)
444 })?;
445 let base = settings
446 .profiles
447 .get(invocation.name.as_str())
448 .ok_or_else(|| {
449 location::positioned(
450 source,
451 invocation.name_span.start,
452 path,
453 format!(
454 "Unknown profile alias `{}`. Define `[profiles.{}]` in .artifactize/settings.toml.",
455 invocation.name, invocation.name
456 ),
457 )
458 })?;
459 let Some(span) = &invocation.overrides_span else {
460 return Ok(base.clone());
461 };
462 let map_offset =
463 |sub: usize| (span.start + sub.saturating_sub(OVERRIDE_WRAPPER_PREFIX.len())).min(span.end);
464 let wrapped = format!("{OVERRIDE_WRAPPER_PREFIX}{}}}", &source[span.clone()]);
465 let parsed = toml::de::DeTable::parse(&wrapped).map_err(|error| {
466 let offset = error.span().map_or(span.start, |s| map_offset(s.start));
467 location::positioned(source, offset, path, error.message())
468 })?;
469 let inner_spanned = parsed
470 .get_ref()
471 .get("_")
472 .filter(|value| parsed.get_ref().len() == 1 && value.span().end == wrapped.len())
473 .ok_or_else(|| {
474 location::positioned(source, span.start, path, "Invalid profile alias override.")
475 })?;
476 let inner_table = inner_spanned.get_ref().as_table().ok_or_else(|| {
477 location::positioned(source, span.start, path, "Invalid profile alias override.")
478 })?;
479 for (key, value) in inner_table {
480 reject_non_json_values(
481 value,
482 &format!("{path}.{}", key.get_ref()),
483 source,
484 map_offset,
485 )?;
486 }
487 if let Some((kind_key, _)) = inner_table.get_key_value("kind") {
488 return Err(location::positioned(
489 source,
490 map_offset(kind_key.span().start),
491 &format!("{path}.kind"),
492 "Profile alias overrides cannot set `kind`.",
493 ));
494 }
495 if let Some(model) = inner_table.get("model")
496 && let toml::de::DeValue::String(model_text) = model.get_ref()
497 {
498 text(model_text, "Agent profile model").map_err(|message| {
499 location::positioned(
500 source,
501 map_offset(model.span().start),
502 &format!("{path}.model"),
503 message,
504 )
505 })?;
506 }
507 let overrides = AgentProfileOverrides::deserialize(toml::de::ValueDeserializer::from(
508 inner_spanned.clone(),
509 ))
510 .map_err(|error| {
511 let offset = error.span().map_or(span.start, |s| map_offset(s.start));
512 location::positioned(source, offset, path, error.message())
513 })?;
514 let resolved = base
515 .apply_overrides(overrides)
516 .map_err(|message| location::positioned(source, invocation.span.start, path, message))?;
517 if let Profile::Agent {
518 backend, reasoning, ..
519 } = &resolved
520 {
521 if let Some(provider) = backend.builtin() {
522 provider.validate_eval().map_err(|message| {
523 let offset = inner_table
524 .get("backend")
525 .map_or(invocation.span.start, |value| {
526 map_offset(value.span().start)
527 });
528 location::positioned(source, offset, &format!("{path}.backend"), message)
529 })?;
530 }
531 if let (Some(reasoning), Some(provider)) = (reasoning, backend.builtin()) {
532 crate::llm::Api::from(provider)
533 .validate_reasoning(reasoning.as_str())
534 .map_err(|message| {
535 let (offset, field) = if let Some(value) = inner_table.get("reasoning") {
536 (map_offset(value.span().start), "reasoning")
537 } else if let Some(value) = inner_table.get("backend") {
538 (map_offset(value.span().start), "backend")
539 } else {
540 (invocation.span.start, "reasoning")
541 };
542 location::positioned(source, offset, &format!("{path}.{field}"), message)
543 })?;
544 }
545 }
546 Ok(resolved)
547}