Skip to main content

artifactize_core/
query.rs

1//! Read-only state queries and result projections.
2
3mod summary;
4pub use summary::{
5    Kinds, RunOutput, Source, SourceKind, profile_name, request_output, request_summary, reused,
6    run_output, run_summary, source,
7};
8
9use std::{collections::BTreeMap, path::Path};
10
11use serde::Serialize;
12
13use crate::{
14    config::{Artifact, Eval, RepoConfig},
15    graph::Graph,
16    project::selection::Selection,
17    scope::Relation,
18};
19
20/// The format version of the printed graph: the shape of its Artifacts, evals, relations
21/// and components. It changes when a field is removed or changes meaning, so that scripts
22/// reading the output can refuse a shape they do not know.
23const GRAPH_FORMAT_VERSION: u32 = 3;
24
25#[derive(Debug, Serialize)]
26#[serde(rename_all = "camelCase")]
27pub struct GraphView<'a> {
28    pub version: u32,
29    #[serde(serialize_with = "crate::platform::path_serde::serialize")]
30    pub repo_path: &'a Path,
31    pub selection: &'a Selection,
32    pub artifacts: BTreeMap<&'a crate::config::ArtifactName, &'a Artifact>,
33    pub evals: Vec<&'a Eval>,
34    pub relations: Vec<GraphRelation<'a>>,
35    pub components: Vec<GraphComponent<'a>>,
36    /// The environment variables the project's profiles read, each with its value (`null`
37    /// while unset); a Run's saved graph records the branch every Agent eval ran with.
38    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
39    pub environment: BTreeMap<&'a str, Option<&'a str>>,
40}
41
42#[derive(Debug, Serialize)]
43pub struct GraphRelation<'a> {
44    #[serde(flatten)]
45    pub relation: &'a Relation,
46    pub cyclic: bool,
47}
48
49#[derive(Debug, Serialize)]
50pub struct GraphComponent<'a> {
51    pub id: crate::graph::ComponentId,
52    pub artifacts: Vec<&'a crate::config::ArtifactName>,
53    pub dependencies: Vec<crate::graph::ComponentId>,
54    pub gates: Vec<&'a crate::config::EvalId>,
55    pub cyclic: bool,
56}
57
58/// Full static definitions, restricted to the selected dependency closure.
59pub fn graph<'a>(
60    config: &'a RepoConfig,
61    selection: &'a Selection,
62) -> Result<GraphView<'a>, String> {
63    let graph = Graph::new(config).map_err(|error| error.to_string())?;
64    let selected = selection.resolve(config)?;
65    let required = graph
66        .dependency_closure(&selected.roots)
67        .map_err(|error| error.to_string())?;
68    let artifacts: BTreeMap<_, _> = required
69        .iter()
70        .map(|&id| (id, &config.artifacts[id]))
71        .collect();
72    let evals = config
73        .evals
74        .iter()
75        .filter(|eval| artifacts.contains_key(&eval.target))
76        .collect();
77    let relations: Vec<_> = config
78        .relations
79        .iter()
80        .filter(|relation| {
81            artifacts.contains_key(&relation.source) && artifacts.contains_key(&relation.target)
82        })
83        .map(|relation| GraphRelation {
84            relation,
85            cyclic: graph.artifacts()[relation.source.as_str()].component
86                == graph.artifacts()[relation.target.as_str()].component,
87        })
88        .collect();
89    let components = graph
90        .components()
91        .iter()
92        .enumerate()
93        .filter(|(_, component)| artifacts.contains_key(component.artifacts[0]))
94        .map(|(id, component)| GraphComponent {
95            id: crate::graph::ComponentId::from_position(id),
96            artifacts: component.artifacts.clone(),
97            dependencies: component.dependencies.clone(),
98            gates: component.gates.clone(),
99            cyclic: component.artifacts.len() > 1
100                || relations.iter().any(|edge| {
101                    edge.cyclic && component.artifacts.contains(&&edge.relation.source)
102                }),
103        })
104        .collect();
105    Ok(GraphView {
106        version: GRAPH_FORMAT_VERSION,
107        repo_path: &config.root,
108        selection,
109        artifacts,
110        evals,
111        relations,
112        components,
113        environment: config
114            .program
115            .iter()
116            .flat_map(|program| &program.environment)
117            .map(|(name, value)| (name.as_str(), value.as_deref()))
118            .collect(),
119    })
120}
121
122/// Conservative change impact: consumers of the selected roots, including cycle peers.
123/// This is structural reachability, not a prediction that every eval's reuse key changed.
124pub fn impact(config: &RepoConfig, selection: &Selection) -> Result<Selection, String> {
125    let resolved = selection.resolve(config)?;
126    let mut affected: std::collections::BTreeSet<_> = resolved.roots.into_iter().cloned().collect();
127    loop {
128        let consumers: Vec<_> = config
129            .relations
130            .iter()
131            .filter(|edge| affected.contains(&edge.source))
132            .map(|edge| edge.target.clone())
133            .collect();
134        let before = affected.len();
135        affected.extend(consumers);
136        if affected.len() == before {
137            break;
138        }
139    }
140    Ok(Selection::Artifacts {
141        artifact_ids: affected.into_iter().collect(),
142    })
143}