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