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