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