Skip to main content

artifactize_core/store/
definitions.rs

1//! Typed schema-5 saved graph snapshots, distinct from strict live declarations.
2//! Unknown saved fields survive round-trips; owner schemas and payload extensions stay JSON.
3mod authored;
4mod extensions;
5#[cfg(test)]
6mod tests;
7use crate::config::{self, Field, StoredPayload};
8pub use extensions::{Profile, SavedSelection};
9use serde::{Deserialize, Deserializer, Serialize, Serializer};
10use serde_json::{Map, Value};
11use std::{collections::BTreeMap, path::PathBuf, sync::Arc};
12
13fn missing<T>(field: &Field<T>) -> bool {
14    matches!(field, Field::Missing)
15}
16
17/// A Run's saved definitions. They are fixed for the Run's life and can be the largest part of
18/// its record, so copies of a Run share one decoded graph.
19#[derive(Debug, Clone, Default)]
20pub struct Definitions(Option<Arc<Graph>>);
21impl Definitions {
22    pub fn graph(&self) -> Option<&Graph> {
23        self.0.as_deref()
24    }
25    /// Another share in the decoded graph, for what keeps a place in it.
26    pub(crate) fn share(&self) -> Option<Arc<Graph>> {
27        self.0.clone()
28    }
29    pub fn from_view(view: &crate::query::GraphView<'_>) -> Result<Self, serde_json::Error> {
30        // A large graph's typed snapshot should not require a second, untyped tree.
31        serde_json::from_slice(&serde_json::to_vec(view)?)
32    }
33    /// The environment values the project's profiles read when these definitions were saved.
34    pub fn environment(&self) -> BTreeMap<String, Option<String>> {
35        self.graph()
36            .and_then(|graph| graph.extra.get("environment"))
37            .and_then(|environment| serde_json::from_value(environment.clone()).ok())
38            .unwrap_or_default()
39    }
40}
41impl Serialize for Definitions {
42    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
43        self.graph().serialize(serializer)
44    }
45}
46impl<'de> Deserialize<'de> for Definitions {
47    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
48        Option::<Graph>::deserialize(deserializer).map(|graph| Self(graph.map(Arc::new)))
49    }
50}
51
52#[derive(Debug, Clone, Default, Serialize, Deserialize)]
53#[serde(rename_all = "camelCase")]
54pub struct Graph {
55    #[serde(default, skip_serializing_if = "missing")]
56    pub version: Field<u32>,
57    #[serde(default, skip_serializing_if = "missing", with = "path_field")]
58    pub repo_path: Field<PathBuf>,
59    #[serde(default, skip_serializing_if = "missing")]
60    pub selection: Field<SavedSelection>,
61    #[serde(
62        default,
63        skip_serializing_if = "Field::missing",
64        deserialize_with = "artifact_targets"
65    )]
66    pub artifacts: Field<BTreeMap<crate::types::ArtifactName, Artifact>>,
67    #[serde(default, skip_serializing_if = "missing")]
68    pub evals: Field<Vec<Eval>>,
69    #[serde(default, skip_serializing_if = "missing")]
70    pub relations: Field<Vec<Relation>>,
71    #[serde(default, skip_serializing_if = "missing")]
72    pub components: Field<Vec<Component>>,
73    #[serde(flatten)]
74    pub extra: Map<String, Value>,
75}
76impl Graph {
77    pub fn artifacts(&self) -> impl Iterator<Item = (&crate::types::ArtifactName, &Artifact)> {
78        match &self.artifacts {
79            Field::Value(map) => Some(map),
80            _ => None,
81        }
82        .into_iter()
83        .flatten()
84    }
85    pub fn artifact(&self, id: &str) -> Option<&Artifact> {
86        match &self.artifacts {
87            Field::Value(map) => map.get(id),
88            _ => None,
89        }
90    }
91    pub fn evals(&self) -> &[Eval] {
92        match &self.evals {
93            Field::Value(evals) => evals,
94            _ => &[],
95        }
96    }
97    pub fn relations(&self) -> &[Relation] {
98        match &self.relations {
99            Field::Value(relations) => relations,
100            _ => &[],
101        }
102    }
103    pub fn components(&self) -> &[Component] {
104        match &self.components {
105            Field::Value(components) => components,
106            _ => &[],
107        }
108    }
109}
110
111#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
112#[serde(rename_all = "camelCase")]
113pub struct Artifact {
114    #[serde(default, skip_serializing_if = "missing", with = "path_field")]
115    pub definition: Field<PathBuf>,
116    #[serde(
117        default,
118        skip_serializing_if = "missing",
119        serialize_with = "saved_kind"
120    )]
121    pub kind: Field<config::ArtifactKind>,
122    #[serde(default, skip_serializing_if = "missing")]
123    pub path: Field<config::Target>,
124    #[serde(default, skip_serializing_if = "missing")]
125    pub select: Field<Vec<config::LogicalPath>>,
126    #[serde(default, skip_serializing_if = "missing")]
127    pub nested: Field<BTreeMap<config::ChildPrefix, crate::types::ArtifactName>>,
128    #[serde(default, skip_serializing_if = "missing")]
129    pub name: Field<crate::types::ArtifactName>,
130    #[serde(default, skip_serializing_if = "missing")]
131    pub tags: Field<Vec<String>>,
132    #[serde(default, skip_serializing_if = "missing")]
133    pub views: Field<Views>,
134    #[serde(default, skip_serializing_if = "missing")]
135    pub basis: Field<bool>,
136    #[serde(default, skip_serializing_if = "missing")]
137    pub fingerprint: Field<Fingerprint>,
138    #[serde(flatten)]
139    pub extra: Map<String, Value>,
140}
141// Schema 10's older readers accept a null kind and preserve the URI path. The new reader
142// recovers Live from that typed path, whose spelling is the source of truth for its kind.
143fn saved_kind<S: Serializer>(
144    kind: &Field<config::ArtifactKind>,
145    serializer: S,
146) -> Result<S::Ok, S::Error> {
147    if matches!(kind, Field::Value(config::ArtifactKind::Live)) {
148        serializer.serialize_none()
149    } else {
150        kind.serialize(serializer)
151    }
152}
153pub(super) fn artifact_targets<'de, D: Deserializer<'de>>(
154    deserializer: D,
155) -> Result<Field<BTreeMap<crate::types::ArtifactName, Artifact>>, D::Error> {
156    let mut field =
157        Field::<BTreeMap<crate::types::ArtifactName, Artifact>>::deserialize(deserializer)?;
158    if let Field::Value(artifacts) = &mut field {
159        for artifact in artifacts.values_mut() {
160            if let Field::Value(path) = &artifact.path {
161                let kind = if path.uri().is_some() {
162                    if !matches!(
163                        artifact.kind,
164                        Field::Missing | Field::Null | Field::Value(config::ArtifactKind::Live)
165                    ) {
166                        return Err(serde::de::Error::custom(
167                            "Saved Live URI has a filesystem kind",
168                        ));
169                    }
170                    artifact.kind = Field::Value(config::ArtifactKind::Live);
171                    config::ArtifactKind::Live
172                } else {
173                    artifact
174                        .kind
175                        .value()
176                        .copied()
177                        .unwrap_or(config::ArtifactKind::Folder)
178                };
179                let select = artifact.select.value().cloned().unwrap_or_default();
180                artifact.path = Field::Value(
181                    path.clone()
182                        .with_kind(kind, select)
183                        .map_err(serde::de::Error::custom)?,
184                );
185            }
186        }
187    }
188    Ok(field)
189}
190#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
191#[serde(rename_all = "camelCase")]
192pub struct Views {
193    #[serde(default, skip_serializing_if = "missing")]
194    pub agent_tools: Field<BTreeMap<config::ToolFqn, AgentTool>>,
195    #[serde(default, skip_serializing_if = "missing")]
196    pub human_tools: Field<BTreeMap<config::ToolFqn, HumanTool>>,
197    #[serde(flatten)]
198    pub extra: Map<String, Value>,
199}
200#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
201#[serde(untagged)]
202pub enum AgentTool {
203    Command(CommandTool),
204    Builtin(BuiltinTool),
205}
206#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
207#[serde(rename_all = "camelCase")]
208pub struct CommandTool {
209    pub description: String,
210    pub input_schema: InputSchema,
211    pub protocol: config::ToolProtocol,
212    #[serde(serialize_with = "crate::platform::serialize_program")]
213    pub command: String,
214    pub args: Vec<String>,
215    #[serde(default, skip_serializing_if = "missing", with = "duration_field")]
216    pub timeout_ms: Field<std::time::Duration>,
217    #[serde(default, skip_serializing_if = "missing")]
218    pub execution_paths: Field<Vec<config::LogicalPath>>,
219    #[serde(flatten)]
220    pub extra: Map<String, Value>,
221}
222/// An owner-authored JSON Schema, decoded at the store boundary and shared across copies.
223#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
224#[serde(transparent)]
225pub struct InputSchema(Arc<Value>);
226impl InputSchema {
227    pub fn value(&self) -> &Value {
228        &self.0
229    }
230}
231#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
232pub struct BuiltinTool {
233    pub builtin: config::Builtin,
234    #[serde(default, skip_serializing_if = "missing")]
235    pub args: Field<Vec<String>>,
236    #[serde(default, skip_serializing_if = "missing")]
237    pub description: Field<String>,
238    #[serde(flatten)]
239    pub extra: Map<String, Value>,
240}
241#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
242#[serde(untagged)]
243pub enum HumanTool {
244    Command(HumanCommandTool),
245    Builtin(HumanBuiltinTool),
246    Viewer(HumanViewerTool),
247}
248/// A viewer tool as a Run saved it. Runs saved before viewer tools named their plugin have
249/// none: only what the tool is and says is read back, and a viewer opens from the current
250/// declarations.
251#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
252pub struct HumanViewerTool {
253    pub kind: config::ViewerKind,
254    pub description: String,
255    #[serde(default, skip_serializing_if = "Option::is_none")]
256    pub plugin: Option<config::PluginName>,
257}
258#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
259#[serde(rename_all = "camelCase")]
260pub struct HumanCommandTool {
261    pub description: String,
262    pub kind: config::HumanToolKind,
263    #[serde(serialize_with = "crate::platform::serialize_program")]
264    pub command: String,
265    pub args: Vec<String>,
266    #[serde(flatten)]
267    pub extra: Map<String, Value>,
268}
269#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
270pub struct HumanBuiltinTool {
271    pub builtin: config::Builtin,
272    pub description: String,
273    pub kind: config::HumanToolKind,
274    pub args: Vec<String>,
275    #[serde(flatten)]
276    pub extra: Map<String, Value>,
277}
278#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
279#[serde(rename_all = "camelCase")]
280pub struct Fingerprint {
281    #[serde(default, skip_serializing_if = "missing")]
282    pub script: Field<Script>,
283    #[serde(default, skip_serializing_if = "missing")]
284    pub files: Field<Vec<config::LogicalPath>>,
285    #[serde(default, skip_serializing_if = "missing")]
286    pub ignore: Field<Vec<String>>,
287    #[serde(flatten)]
288    pub extra: Map<String, Value>,
289}
290#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
291#[serde(rename_all = "camelCase")]
292pub struct Script {
293    #[serde(serialize_with = "crate::platform::serialize_program")]
294    pub command: String,
295    pub args: Vec<String>,
296    #[serde(default, skip_serializing_if = "missing")]
297    pub files: Field<Vec<config::LogicalPath>>,
298    #[serde(default, skip_serializing_if = "missing", with = "duration_field")]
299    pub timeout_ms: Field<std::time::Duration>,
300    #[serde(flatten)]
301    pub extra: Map<String, Value>,
302}
303#[derive(Debug, Clone, Serialize, Deserialize)]
304pub struct Eval {
305    pub id: crate::types::EvalId,
306    pub target: crate::types::ArtifactName,
307    #[serde(default, skip_serializing_if = "missing")]
308    pub references: Field<BTreeMap<crate::config::ReferenceName, crate::types::ArtifactName>>,
309    #[serde(default, skip_serializing_if = "missing")]
310    pub deps: Field<Vec<crate::types::ArtifactName>>,
311    #[serde(default, skip_serializing_if = "missing")]
312    pub declaration: Field<Declaration>,
313    #[serde(flatten)]
314    pub extra: Map<String, Value>,
315}
316#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
317#[serde(rename_all = "camelCase")]
318pub struct Declaration {
319    #[serde(default, skip_serializing_if = "missing")]
320    pub mutex: Field<Vec<config::MutexTag>>,
321    #[serde(default, skip_serializing_if = "missing")]
322    pub id: Field<crate::config::LocalEvalId>,
323    #[serde(default, skip_serializing_if = "missing")]
324    pub title: Field<String>,
325    #[serde(default, skip_serializing_if = "missing")]
326    pub profile: Field<Profile>,
327    /// The named profile it referred to; absent before 0.27.
328    #[serde(default, skip_serializing_if = "missing")]
329    pub profile_name: Field<String>,
330    /// Variants saved before 0.27, read for history only.
331    #[serde(default, skip_serializing_if = "missing")]
332    pub profile_variants: Field<BTreeMap<String, Profile>>,
333    #[serde(default, skip_serializing_if = "missing")]
334    pub payload: Field<StoredPayload>,
335    /// A runtime eval's inputs; absent before 0.27.
336    #[serde(default, skip_serializing_if = "missing")]
337    pub inputs: Field<Vec<config::ArtifactName>>,
338    #[serde(default, skip_serializing_if = "missing")]
339    pub red_at: Field<config::Priority>,
340    /// Human result schemas saved before 0.27, read for history only.
341    #[serde(default, skip_serializing_if = "missing")]
342    pub pass_schema: Field<Map<String, Value>>,
343    #[serde(default, skip_serializing_if = "missing")]
344    pub fail_schema: Field<Map<String, Value>>,
345    #[serde(flatten)]
346    pub extra: Map<String, Value>,
347}
348#[derive(Debug, Clone, Default, Serialize, Deserialize)]
349pub struct Component {
350    #[serde(default, skip_serializing_if = "missing")]
351    pub id: Field<crate::graph::ComponentId>,
352    #[serde(default, skip_serializing_if = "missing")]
353    pub artifacts: Field<Vec<crate::types::ArtifactName>>,
354    #[serde(default, skip_serializing_if = "missing")]
355    pub dependencies: Field<Vec<crate::graph::ComponentId>>,
356    #[serde(default, skip_serializing_if = "missing")]
357    pub gates: Field<Vec<crate::types::EvalId>>,
358    #[serde(default, skip_serializing_if = "missing")]
359    pub cyclic: Field<bool>,
360    #[serde(flatten)]
361    pub extra: Map<String, Value>,
362}
363#[derive(Debug, Clone, Serialize)]
364pub struct Relation {
365    pub source: crate::types::ArtifactName,
366    pub target: crate::types::ArtifactName,
367    #[serde(flatten)]
368    pub kind: RelationKind,
369    #[serde(default, skip_serializing_if = "missing")]
370    pub cyclic: Field<bool>,
371    #[serde(flatten)]
372    pub extra: Map<String, Value>,
373}
374impl<'de> Deserialize<'de> for Relation {
375    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
376        // Flattened internally-tagged enums do not consume their fields from a second
377        // flatten map. Split at the saved boundary so reserialization never duplicates kind.
378        let mut fields = Map::<String, Value>::deserialize(deserializer)?;
379        let mut take = |name: &str| {
380            fields
381                .remove(name)
382                .ok_or_else(|| serde::de::Error::custom(format!("missing relation {name}")))
383        };
384        let source = serde_json::from_value(take("source")?).map_err(serde::de::Error::custom)?;
385        let target = serde_json::from_value(take("target")?).map_err(serde::de::Error::custom)?;
386        let kind_name: String =
387            serde_json::from_value(take("kind")?).map_err(serde::de::Error::custom)?;
388        let names: Option<&[&str]> = match kind_name.as_str() {
389            "child" => Some(&["path"]),
390            "part" => Some(&[]),
391            "instruction" => Some(&["evalId", "name"]),
392            "argv" => Some(&["evalId", "index", "name", "path"]),
393            _ => None,
394        };
395        let unknown = names.is_none();
396        let names = names.unwrap_or_default();
397        let mut kind = Map::from_iter([("kind".into(), Value::String(kind_name.clone()))]);
398        for name in names {
399            if let Some(value) = fields.remove(*name) {
400                kind.insert((*name).into(), value);
401            }
402        }
403        let kind = if unknown {
404            RelationKind::Unknown { kind: kind_name }
405        } else {
406            let parsed =
407                serde_json::from_value(Value::Object(kind)).map_err(serde::de::Error::custom)?;
408            if matches!(parsed, RelationKind::Unknown { .. }) {
409                return Err(serde::de::Error::custom(format!(
410                    "Invalid saved {kind_name} relation."
411                )));
412            }
413            parsed
414        };
415        let cyclic = match fields.remove("cyclic") {
416            Some(value) => serde_json::from_value(value).map_err(serde::de::Error::custom)?,
417            None => Field::Missing,
418        };
419        Ok(Self {
420            source,
421            target,
422            kind,
423            cyclic,
424            extra: fields,
425        })
426    }
427}
428#[derive(Debug, Clone, Serialize, Deserialize)]
429#[serde(tag = "kind", rename_all = "lowercase")]
430pub enum RelationKind {
431    /// A folder child that Runs saved before parts recorded; it is no part relation.
432    Child {
433        #[serde(default, skip_serializing_if = "missing")]
434        path: Field<config::ChildPrefix>,
435    },
436    /// The source is a part of the target.
437    Part,
438    Instruction {
439        #[serde(rename = "evalId")]
440        eval_id: crate::types::EvalId,
441        name: config::ReferenceName,
442    },
443    #[serde(rename = "argv")]
444    Argument {
445        #[serde(rename = "evalId")]
446        eval_id: crate::types::EvalId,
447        index: usize,
448        name: config::ReferenceName,
449        path: crate::scope::LogicalTarget,
450    },
451    #[serde(untagged)]
452    Unknown { kind: String },
453}
454
455mod duration_field {
456    use crate::config::Field;
457    use serde::{Deserializer, Serializer};
458    use std::time::Duration;
459    pub fn serialize<S: Serializer>(
460        value: &Field<Duration>,
461        serializer: S,
462    ) -> Result<S::Ok, S::Error> {
463        match value {
464            Field::Value(value) => {
465                let milliseconds = value.as_millis();
466                if !(1..=u128::from(crate::config::validation::MAX_TIMEOUT_MS))
467                    .contains(&milliseconds)
468                    || Duration::from_millis(milliseconds as u64) != *value
469                {
470                    return Err(serde::ser::Error::custom(
471                        "Saved definition timeoutMs must be whole milliseconds from 1 through 2147483647.",
472                    ));
473                }
474                serializer.serialize_u128(milliseconds)
475            }
476            _ => serializer.serialize_none(),
477        }
478    }
479    pub fn deserialize<'de, D: Deserializer<'de>>(
480        deserializer: D,
481    ) -> Result<Field<Duration>, D::Error> {
482        crate::config::validation::milliseconds::deserialize(deserializer)
483            .map(|value| value.map_or(Field::Null, Field::Value))
484    }
485}
486
487pub(super) mod path_field {
488    use crate::config::Field;
489    use serde::{Deserializer, Serializer};
490    use std::path::PathBuf;
491    pub fn serialize<S: Serializer>(
492        value: &Field<PathBuf>,
493        serializer: S,
494    ) -> Result<S::Ok, S::Error> {
495        match value {
496            Field::Value(path) => crate::platform::path_serde::serialize(path, serializer),
497            _ => serializer.serialize_none(),
498        }
499    }
500    pub fn deserialize<'de, D: Deserializer<'de>>(
501        deserializer: D,
502    ) -> Result<Field<PathBuf>, D::Error> {
503        crate::platform::path_serde::option::deserialize(deserializer)
504            .map(|value| value.map_or(Field::Null, Field::Value))
505    }
506}