Skip to main content

artifactize_core/config/
stored.rs

1//! Profiles saved by schema 5. Unlike declarations, their optional fields may be null.
2//! Missing and null remain distinct: profile comparison drives the otherProfile tally.
3
4use super::{Backend, ModelId, Profile, ProfileKind, Reasoning};
5use serde::{Deserialize, Deserializer, Serialize, Serializer};
6use std::time::Duration;
7
8#[derive(Debug, Clone, Default, PartialEq, Eq)]
9pub enum Field<T> {
10    #[default]
11    Missing,
12    Null,
13    Value(T),
14}
15impl<T> Field<T> {
16    pub fn value(&self) -> Option<&T> {
17        match self {
18            Self::Value(value) => Some(value),
19            _ => None,
20        }
21    }
22    pub(crate) fn missing(&self) -> bool {
23        matches!(self, Self::Missing)
24    }
25}
26impl<T: Serialize> Serialize for Field<T> {
27    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
28        match self {
29            Self::Value(value) => value.serialize(serializer),
30            _ => serializer.serialize_none(),
31        }
32    }
33}
34impl<'de, T: Deserialize<'de>> Deserialize<'de> for Field<T> {
35    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
36        Ok(Option::<T>::deserialize(deserializer)?.map_or(Self::Null, Self::Value))
37    }
38}
39impl<T> From<Option<T>> for Field<T> {
40    fn from(value: Option<T>) -> Self {
41        value.map_or(Self::Null, Self::Value)
42    }
43}
44
45/// Read schema-5 payloads without inventing an instruction field for older audits.
46/// Declarations still require a String; omission/null tolerance belongs only here.
47#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
48pub struct StoredPayload {
49    #[serde(default, skip_serializing_if = "Field::missing")]
50    instruction: Field<String>,
51    #[serde(flatten)]
52    pub extra: serde_json::Map<String, serde_json::Value>,
53}
54
55impl StoredPayload {
56    pub fn instruction(&self) -> &str {
57        match &self.instruction {
58            Field::Value(value) => value,
59            Field::Missing | Field::Null => "",
60        }
61    }
62}
63
64impl From<&Option<super::EvalPayload>> for StoredPayload {
65    fn from(payload: &Option<super::EvalPayload>) -> Self {
66        payload.as_ref().map_or_else(
67            || Self {
68                instruction: Field::Missing,
69                extra: Default::default(),
70            },
71            Self::from,
72        )
73    }
74}
75
76impl From<&super::EvalPayload> for StoredPayload {
77    fn from(payload: &super::EvalPayload) -> Self {
78        Self {
79            instruction: Field::Value(payload.instruction.clone()),
80            extra: payload.extra.clone(),
81        }
82    }
83}
84
85#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
86#[serde(tag = "kind", rename_all = "lowercase")]
87pub enum StoredProfile {
88    Agent {
89        backend: Backend,
90        model: ModelId,
91        #[serde(default, skip_serializing_if = "Field::missing")]
92        reasoning: Field<Reasoning>,
93        #[serde(
94            rename = "timeoutMs",
95            default,
96            skip_serializing_if = "Field::missing",
97            with = "milliseconds"
98        )]
99        timeout_ms: Field<Duration>,
100        #[serde(
101            rename = "maxToolCalls",
102            default,
103            skip_serializing_if = "Field::missing"
104        )]
105        max_tool_calls: Field<u64>,
106        #[serde(rename = "maxTokens", default, skip_serializing_if = "Field::missing")]
107        max_tokens: Field<u64>,
108    },
109    Human {},
110    Runtime {
111        #[serde(serialize_with = "crate::platform::serialize_program")]
112        command: String,
113        args: Vec<String>,
114        #[serde(
115            rename = "timeoutMs",
116            default,
117            skip_serializing_if = "Field::missing",
118            with = "milliseconds"
119        )]
120        timeout_ms: Field<Duration>,
121    },
122}
123impl StoredProfile {
124    pub fn kind(&self) -> ProfileKind {
125        match self {
126            Self::Agent { .. } => ProfileKind::Agent,
127            Self::Human {} => ProfileKind::Human,
128            Self::Runtime { .. } => ProfileKind::Runtime,
129        }
130    }
131}
132impl From<&Profile> for StoredProfile {
133    fn from(profile: &Profile) -> Self {
134        match profile {
135            Profile::Agent {
136                backend,
137                model,
138                reasoning,
139                timeout_ms,
140                max_tool_calls,
141                max_tokens,
142            } => Self::Agent {
143                backend: backend.clone(),
144                model: model.clone(),
145                reasoning: (*reasoning).into(),
146                timeout_ms: (*timeout_ms).into(),
147                max_tool_calls: (*max_tool_calls).into(),
148                max_tokens: (*max_tokens).into(),
149            },
150            Profile::Human {} => Self::Human {},
151            Profile::Runtime {
152                command,
153                args,
154                timeout_ms,
155            } => Self::Runtime {
156                // A program path is saved with `/`, as every stored path is.
157                command: crate::platform::path_text(std::path::Path::new(command)),
158                args: args.iter().map(ToString::to_string).collect(),
159                timeout_ms: (*timeout_ms).into(),
160            },
161        }
162    }
163}
164mod milliseconds {
165    use super::*;
166    pub fn serialize<S: Serializer>(
167        value: &Field<Duration>,
168        serializer: S,
169    ) -> Result<S::Ok, S::Error> {
170        match value {
171            Field::Value(value) => serializer.serialize_u128(value.as_millis()),
172            _ => serializer.serialize_none(),
173        }
174    }
175    pub fn deserialize<'de, D: Deserializer<'de>>(
176        deserializer: D,
177    ) -> Result<Field<Duration>, D::Error> {
178        // Saved profiles can contain null; declarations use the strict timeout parser.
179        let value = Option::<serde_json::Number>::deserialize(deserializer)?;
180        value.map_or(Ok(Field::Null), |value| {
181            super::super::validation::timeout_number::<D::Error>(value).map(Field::Value)
182        })
183    }
184}
185
186impl From<Option<&super::EvalPayload>> for StoredPayload {
187    fn from(payload: Option<&super::EvalPayload>) -> Self {
188        payload.map_or_else(
189            || Self {
190                instruction: Field::Missing,
191                extra: Default::default(),
192            },
193            Self::from,
194        )
195    }
196}
197
198#[cfg(test)]
199mod tests {
200    use super::*;
201    use serde_json::json;
202    #[test]
203    fn stored_payloads_preserve_schema_5_missing_null_and_owner_context() {
204        for (value, instruction) in [
205            (json!({}), ""),
206            (json!({"instruction":null,"owner":[true,null,42]}), ""),
207            (
208                json!({"instruction":"Inspect {input}.","owner":{"nested":[]}}),
209                "Inspect {input}.",
210            ),
211        ] {
212            let stored: StoredPayload = serde_json::from_value(value.clone()).unwrap();
213            assert_eq!(serde_json::to_value(&stored).unwrap(), value);
214            assert_eq!(stored.instruction(), instruction);
215            if value["instruction"].is_null() {
216                assert!(serde_json::from_value::<super::super::EvalPayload>(value).is_err());
217            }
218        }
219    }
220
221    #[test]
222    fn stored_profiles_preserve_missing_and_null_without_weakening_config() {
223        for value in [
224            json!({"kind":"agent","backend":"openai","model":"fixture"}),
225            json!({
226                "kind":"agent",
227                "backend":"openai",
228                "model":"fixture",
229                "reasoning":null,
230                "timeoutMs":null,
231                "maxToolCalls":null,
232                "maxTokens":null,
233            }),
234            json!({"kind":"runtime","command":"fixture","args":[],"timeoutMs":null}),
235            json!({"kind":"runtime","command":"fixture","args":[],"timeoutMs":1000}),
236            json!({"kind":"human"}),
237        ] {
238            let stored: StoredProfile = serde_json::from_value(value.clone()).unwrap();
239            assert_eq!(serde_json::to_value(&stored).unwrap(), value);
240            if value
241                .get("timeoutMs")
242                .is_some_and(serde_json::Value::is_null)
243            {
244                let mut declaration = value;
245                let object = declaration.as_object_mut().unwrap();
246                for (camel, snake) in [
247                    ("timeoutMs", "timeout_ms"),
248                    ("maxToolCalls", "max_tool_calls"),
249                    ("maxTokens", "max_tokens"),
250                ] {
251                    if let Some(value) = object.remove(camel) {
252                        object.insert(snake.into(), value);
253                    }
254                }
255                // Only the timeout is invalid, so another optional field cannot mask it.
256                for field in ["reasoning", "max_tool_calls", "max_tokens"] {
257                    object.remove(field);
258                }
259                let error = serde_json::from_value::<Profile>(declaration)
260                    .unwrap_err()
261                    .to_string();
262                assert!(
263                    error.contains("null") && !error.contains("unknown field"),
264                    "{error}"
265                );
266            }
267        }
268        let missing: StoredProfile =
269            serde_json::from_value(json!({"kind":"runtime","command":"fixture","args":[]}))
270                .unwrap();
271        let null: StoredProfile = serde_json::from_value(
272            json!({"kind":"runtime","command":"fixture","args":[],"timeoutMs":null}),
273        )
274        .unwrap();
275        assert_ne!(missing, null);
276        let config: Profile =
277            serde_json::from_value(json!({"kind":"agent","backend":"openai","model":"fixture"}))
278                .unwrap();
279        assert_eq!(
280            serde_json::to_value(StoredProfile::from(&config)).unwrap(),
281            json!({
282                "kind":"agent",
283                "backend":"openai",
284                "model":"fixture",
285                "reasoning":null,
286                "timeoutMs":null,
287                "maxToolCalls":null,
288                "maxTokens":null,
289            })
290        );
291    }
292}