Skip to main content

artifactize_core/config/
eval.rs

1//! An Eval declaration: local identity, instruction, profiles, the priority at which an Agent
2//! eval turns RED, and a Human eval's result schemas.
3
4use super::{
5    MAX_DECLARED_ITEMS, MutexTag, Profile, ProfileKind, ProfileVariantName, identifier,
6    location::Location,
7    mutex, schemas,
8    validation::{present, text},
9};
10use serde::{Deserialize, Serialize};
11use serde_json::{Map, Value};
12use std::collections::BTreeMap;
13
14/// The required instruction is typed at the declaration and saved-request boundaries;
15/// owner-defined context remains extensible JSON with the same object representation.
16#[derive(Debug, Clone, Serialize, Deserialize)]
17pub struct EvalPayload {
18    pub instruction: String,
19    #[serde(flatten)]
20    pub extra: Map<String, Value>,
21}
22
23/// An Eval's id within its Artifact, such as `follows-style`: the key of its
24/// `[evals.<id>]` table, validated when the declaration is read.
25#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
26#[serde(transparent)]
27pub struct LocalEvalId(String);
28
29impl<'de> Deserialize<'de> for LocalEvalId {
30    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
31        String::deserialize(deserializer)?
32            .parse()
33            .map_err(serde::de::Error::custom)
34    }
35}
36
37impl std::str::FromStr for LocalEvalId {
38    type Err = String;
39    fn from_str(value: &str) -> Result<Self, Self::Err> {
40        identifier(value, "Eval id")?;
41        Ok(Self(value.to_owned()))
42    }
43}
44
45impl LocalEvalId {
46    pub fn as_str(&self) -> &str {
47        &self.0
48    }
49}
50
51impl PartialEq<&str> for LocalEvalId {
52    fn eq(&self, other: &&str) -> bool {
53        self.0 == *other
54    }
55}
56
57impl std::ops::Deref for LocalEvalId {
58    type Target = str;
59    fn deref(&self) -> &str {
60        &self.0
61    }
62}
63
64impl std::fmt::Display for LocalEvalId {
65    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
66        self.0.fmt(f)
67    }
68}
69
70/// A finding's priority: P0 is the most important and P3 the least. artifactize defines only
71/// their order; the evaluator assigns them by its own judgement.
72#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
73pub enum Priority {
74    P0,
75    P1,
76    P2,
77    P3,
78}
79
80impl Priority {
81    pub const ALL: [Self; 4] = [Self::P0, Self::P1, Self::P2, Self::P3];
82
83    pub fn as_str(self) -> &'static str {
84        match self {
85            Self::P0 => "P0",
86            Self::P1 => "P1",
87            Self::P2 => "P2",
88            Self::P3 => "P3",
89        }
90    }
91}
92
93impl std::fmt::Display for Priority {
94    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
95        f.write_str(self.as_str())
96    }
97}
98
99#[derive(Debug, Clone, Serialize)]
100#[serde(rename_all = "camelCase")]
101pub struct EvalDeclaration {
102    pub id: LocalEvalId,
103    pub title: String,
104    #[serde(skip_serializing_if = "Vec::is_empty")]
105    pub mutex: Vec<MutexTag>,
106    #[serde(flatten)]
107    body: EvalBody,
108}
109
110/// Every Eval has an instruction and a complete execution profile.
111#[derive(Debug, Clone, Serialize)]
112#[serde(rename_all = "camelCase")]
113struct EvalBody {
114    profile: Profile,
115    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
116    profile_variants: BTreeMap<ProfileVariantName, Profile>,
117    payload: EvalPayload,
118    /// An Agent eval's bar: a finding at this priority or a more important one makes it RED.
119    /// Without it, any finding does.
120    #[serde(skip_serializing_if = "Option::is_none")]
121    red_at: Option<Priority>,
122    /// A Human eval's result schemas, each shared with every equal schema in the same read.
123    pass_schema: Option<std::sync::Arc<Map<String, Value>>>,
124    fail_schema: Option<std::sync::Arc<Map<String, Value>>>,
125}
126
127impl EvalDeclaration {
128    pub fn profile(&self) -> &Profile {
129        &self.body.profile
130    }
131    pub fn payload(&self) -> Option<&EvalPayload> {
132        Some(&self.body.payload)
133    }
134    pub fn profile_variants(&self) -> &BTreeMap<ProfileVariantName, Profile> {
135        &self.body.profile_variants
136    }
137    pub fn red_at(&self) -> Option<Priority> {
138        self.body.red_at
139    }
140    pub fn pass_schema(&self) -> Option<&Map<String, Value>> {
141        self.body.pass_schema.as_deref()
142    }
143    pub fn fail_schema(&self) -> Option<&Map<String, Value>> {
144        self.body.fail_schema.as_deref()
145    }
146    #[cfg(test)]
147    pub(crate) fn profile_mut(&mut self) -> &mut Profile {
148        &mut self.body.profile
149    }
150    pub(crate) fn select_profile(&mut self, name: &ProfileVariantName) -> Result<(), String> {
151        self.body.profile = self
152            .body
153            .profile_variants
154            .get(name)
155            .ok_or_else(|| format!("Unknown profile variant: {name}"))?
156            .clone();
157        Ok(())
158    }
159}
160
161#[derive(Deserialize)]
162#[serde(rename_all = "snake_case", deny_unknown_fields)]
163struct EvalFields {
164    title: String,
165    #[serde(default, deserialize_with = "present")]
166    mutex: Option<Vec<MutexTag>>,
167    profile: Profile,
168    #[serde(default, deserialize_with = "present")]
169    profile_variants: Option<BTreeMap<ProfileVariantName, Profile>>,
170    #[serde(default, deserialize_with = "present")]
171    payload: Option<EvalPayload>,
172    #[serde(default, deserialize_with = "present")]
173    red_at: Option<Priority>,
174    #[serde(default, deserialize_with = "present")]
175    pass_schema: Option<Map<String, Value>>,
176    #[serde(default, deserialize_with = "present")]
177    fail_schema: Option<Map<String, Value>>,
178}
179
180impl EvalDeclaration {
181    /// Check the fields of the `[evals.<id>]` table that every profile needs together.
182    fn new(id: LocalEvalId, fields: EvalFields) -> Result<Self, String> {
183        if fields.mutex.is_some()
184            && !matches!(
185                fields.profile.kind(),
186                ProfileKind::Runtime | ProfileKind::Agent
187            )
188        {
189            return Err("mutex is supported only on runtime and agent Evals.".into());
190        }
191        let agent = fields.profile.kind() == ProfileKind::Agent;
192        if agent && (fields.pass_schema.is_some() || fields.fail_schema.is_some()) {
193            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());
194        }
195        if !agent && fields.red_at.is_some() {
196            return Err("red_at is supported only on agent Evals.".into());
197        }
198        let body = EvalBody {
199            profile: fields.profile,
200            profile_variants: fields.profile_variants.unwrap_or_default(),
201            payload: fields
202                .payload
203                .ok_or("Eval payload is required for runtime, agent and human profiles.")?,
204            red_at: fields.red_at,
205            pass_schema: fields.pass_schema.map(std::sync::Arc::new),
206            fail_schema: fields.fail_schema.map(std::sync::Arc::new),
207        };
208        Ok(Self {
209            id,
210            title: fields.title,
211            mutex: fields.mutex.unwrap_or_default(),
212            body,
213        })
214    }
215}
216
217impl EvalDeclaration {
218    pub(super) fn share(&mut self, schemas: &mut schemas::Schemas) {
219        for schema in [&mut self.body.pass_schema, &mut self.body.fail_schema]
220            .into_iter()
221            .flatten()
222        {
223            *schema = schemas.verdict(schema);
224        }
225    }
226
227    pub(super) fn validate(
228        &self,
229        location: &Location<'_, '_>,
230        schemas: &mut schemas::Schemas,
231    ) -> Result<(), String> {
232        location
233            .child("title")
234            .check(text(&self.title, "Eval title"))?;
235        if let Some(payload) = self.payload() {
236            location
237                .child("payload")
238                .child("instruction")
239                .check(text(&payload.instruction, "Eval payload.instruction"))?;
240        }
241        location
242            .child("mutex")
243            .check(mutex::validate(&self.mutex))?;
244        self.profile().validate(&location.child("profile"))?;
245        for (key, schema) in [
246            ("pass_schema", &self.body.pass_schema),
247            ("fail_schema", &self.body.fail_schema),
248        ] {
249            if let Some(schema) = schema {
250                location
251                    .child(key)
252                    .check(schemas.check(schema, crate::agent::verdict::validate_schema))?;
253                // A person enters a Human result in a form: only shapes it can enter.
254                if self.profile().kind() == ProfileKind::Human {
255                    location
256                        .child(key)
257                        .check(crate::review::Specification::parse(Some(schema)).map(drop))?;
258                }
259            }
260        }
261        if self.profile_variants().len() > MAX_DECLARED_ITEMS {
262            return Err(location
263                .child("profile_variants")
264                .error("profile_variants must contain at most 64 named profiles."));
265        }
266        for (name, profile) in self.profile_variants() {
267            let variant = location.child("profile_variants").child(name);
268            location
269                .child("profile_variants")
270                .key(name)
271                .check(identifier(name, "Profile variant name"))?;
272            profile.validate(&variant)?;
273            if std::mem::discriminant(profile) != std::mem::discriminant(self.profile()) {
274                return Err(
275                    variant.error("Profile variants must retain the declared reviewer kind.")
276                );
277            }
278        }
279        Ok(())
280    }
281}
282
283/// Eval ids live in table keys, not fields; BTreeMap also fixes their discovery order.
284pub(super) fn declared_evals<'de, D: serde::Deserializer<'de>>(
285    deserializer: D,
286) -> Result<Vec<EvalDeclaration>, D::Error> {
287    use serde::de::Error;
288    BTreeMap::<String, EvalFields>::deserialize(deserializer)?
289        .into_iter()
290        .map(|(id, fields)| {
291            let id = id.parse().map_err(D::Error::custom)?;
292            EvalDeclaration::new(id, fields).map_err(D::Error::custom)
293        })
294        .collect()
295}