Skip to main content

artifactize_core/
graph.rs

1//! Dependency edges, strongly connected components, gates, and obligations.
2
3use std::collections::{BTreeMap, BTreeSet, HashSet};
4
5use petgraph::{algo::kosaraju_scc, graph::DiGraph};
6use thiserror::Error;
7
8use crate::{
9    config::{ArtifactName, EvalId, RepoConfig},
10    runtime::Verdict,
11};
12
13#[derive(Debug, Error)]
14#[error("{0}")]
15pub struct GraphError(pub String);
16
17/// A strongly-connected component's position in `Graph::components`, guarding it from
18/// arbitrary `usize` arithmetic: dependency-first, so a lower id is never a later
19/// component's dependency.
20#[derive(
21    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize,
22)]
23#[serde(transparent)]
24pub struct ComponentId(usize);
25
26impl ComponentId {
27    /// Live graph and legacy saved components derive their identity from a list position.
28    /// Saved explicit IDs deserialize as the same unsigned integer, never arithmetic indices.
29    pub(crate) fn from_position(index: usize) -> Self {
30        Self(index)
31    }
32
33    pub(crate) fn index(self) -> usize {
34        self.0
35    }
36}
37
38impl std::fmt::Display for ComponentId {
39    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
40        self.0.fmt(f)
41    }
42}
43
44#[derive(Debug, Clone, PartialEq, Eq)]
45pub struct ArtifactNode<'a> {
46    pub basis: bool,
47    pub evals: Vec<&'a EvalId>,
48    /// The Artifacts it is directly composed of, by name.
49    pub parts: Vec<&'a ArtifactName>,
50    pub component: ComponentId,
51}
52
53#[derive(Debug, Clone, PartialEq, Eq)]
54pub struct Component<'a> {
55    pub artifacts: Vec<&'a ArtifactName>,
56    /// Direct condensation dependencies, always earlier in the component list.
57    pub dependencies: Vec<ComponentId>,
58    /// Aggregate external obligations for the material projection, not execution gates.
59    /// Each Eval’s actual gates come from the Eval-level schedule.
60    pub gates: Vec<&'a EvalId>,
61}
62
63#[derive(Debug)]
64pub struct Graph<'a> {
65    artifacts: BTreeMap<ArtifactName, ArtifactNode<'a>>,
66    evals: BTreeMap<EvalId, &'a ArtifactName>,
67    components: Vec<Component<'a>>,
68    schedule: schedule::Schedule<'a>,
69}
70
71/// Evaluation order for a dependency-closed selection in a graph.
72pub(crate) struct Projection<'g, 'a> {
73    graph: &'g Graph<'a>,
74    artifacts: Vec<&'g ArtifactName>,
75    components: BTreeSet<ComponentId>,
76    evals: Vec<&'a EvalId>,
77}
78
79impl<'g> Projection<'g, '_> {
80    pub(crate) fn evaluate(&self, evidence: &BTreeMap<EvalId, Evidence>) -> Evaluation<'g> {
81        self.graph.evaluate_in(
82            evidence,
83            false,
84            &self.evals,
85            self.artifacts.iter().copied(),
86            self.components.iter().copied(),
87        )
88    }
89
90    /// Components have the same upstream obligations for every member. Merge them in
91    /// dependency order rather than walking the same subgraph again for every Artifact.
92    pub(crate) fn unmet(
93        &self,
94        evaluation: &Evaluation<'_>,
95    ) -> BTreeMap<ComponentId, BTreeSet<&ArtifactName>> {
96        let mut unmet: BTreeMap<_, BTreeSet<_>> = BTreeMap::new();
97        for &id in &self.components {
98            let component = &self.graph.components[id.index()];
99            if evaluation.artifacts[component.artifacts[0].as_str()].satisfied() {
100                continue;
101            }
102            let own = component
103                .artifacts
104                .iter()
105                .copied()
106                .filter(|name| !evaluation.artifacts[*name].own_satisfied);
107            let upstream = component
108                .dependencies
109                .iter()
110                .filter_map(|dependency| unmet.get(dependency))
111                .flat_map(|names| names.iter().copied());
112            unmet.insert(id, own.chain(upstream).collect());
113        }
114        unmet
115    }
116}
117
118impl<'a> Graph<'a> {
119    /// Build from scope's resolved relations without reading files or running code.
120    pub fn new(config: &'a RepoConfig) -> Result<Self, GraphError> {
121        let mut graph = DiGraph::<&ArtifactName, ()>::new();
122        let nodes: BTreeMap<_, _> = config
123            .artifacts
124            .keys()
125            .map(|id| (id, graph.add_node(id)))
126            .collect();
127        let mut artifacts: BTreeMap<_, _> = config
128            .artifacts
129            .iter()
130            .map(|(id, artifact)| {
131                (
132                    id.clone(),
133                    ArtifactNode {
134                        basis: artifact.basis == Some(true),
135                        evals: Vec::new(),
136                        parts: Vec::new(),
137                        component: ComponentId(0),
138                    },
139                )
140            })
141            .collect();
142        let mut evals = BTreeMap::new();
143        for eval in &config.evals {
144            let artifact = artifacts
145                .get_mut(&eval.target)
146                .ok_or_else(|| GraphError(format!("Unknown Eval target: {}", eval.target)))?;
147            if artifact.basis {
148                return Err(GraphError(format!(
149                    "Basis Artifact {} cannot own Evals.",
150                    eval.target
151                )));
152            }
153            if evals.insert(eval.id.clone(), &eval.target).is_some() {
154                return Err(GraphError(format!("Duplicate Eval: {}", eval.id)));
155            }
156            artifact.evals.push(&eval.id);
157        }
158        for artifact in artifacts.values_mut() {
159            artifact.evals.sort_unstable();
160        }
161        let mut edges = BTreeSet::new();
162        for relation in &config.relations {
163            for id in [&relation.source, &relation.target] {
164                if !nodes.contains_key(id) {
165                    return Err(GraphError(format!("Unknown relation Artifact: {id}")));
166                }
167            }
168            // A parent needs its parts as a consumer needs its inputs, for obligations
169            // only: execution gates come from references alone.
170            edges.insert((&relation.target, &relation.source));
171            if relation.kind == crate::scope::RelationKind::Part {
172                artifacts
173                    .get_mut(&relation.target)
174                    .unwrap()
175                    .parts
176                    .push(&relation.source);
177            }
178        }
179        // Consumer -> input makes iterative SCC traversal dependency-first.
180        for &(consumer, dependency) in &edges {
181            graph.add_edge(nodes[consumer], nodes[dependency], ());
182        }
183        let mut components: Vec<_> = kosaraju_scc(&graph)
184            .into_iter()
185            .map(|members| {
186                let mut artifacts: Vec<_> = members.into_iter().map(|node| graph[node]).collect();
187                artifacts.sort_unstable();
188                Component {
189                    artifacts,
190                    dependencies: Vec::new(),
191                    gates: Vec::new(),
192                }
193            })
194            .collect();
195        for (index, component) in components.iter().enumerate() {
196            for id in &component.artifacts {
197                artifacts.get_mut(id.as_str()).unwrap().component = ComponentId(index);
198            }
199        }
200        let mut dependencies = vec![BTreeSet::new(); components.len()];
201        for (consumer, dependency) in edges {
202            let consumer = artifacts[consumer.as_str()].component;
203            let dependency = artifacts[dependency.as_str()].component;
204            if consumer != dependency {
205                debug_assert!(dependency < consumer);
206                dependencies[consumer.index()].insert(dependency);
207            }
208        }
209        for (index, dependencies) in dependencies.into_iter().enumerate() {
210            let mut gates: Vec<_> = dependencies
211                .iter()
212                .flat_map(|&dependency| &components[dependency.index()].artifacts)
213                .flat_map(|id| &artifacts[id.as_str()].evals)
214                .copied()
215                .collect();
216            gates.sort_unstable();
217            components[index].dependencies = dependencies.into_iter().collect();
218            components[index].gates = gates;
219        }
220        let schedule = schedule::Schedule::new(config.evals.iter().map(|eval| schedule::Input {
221            id: &eval.id,
222            target: &eval.target,
223            deps: eval.deps.iter().collect(),
224            human: eval.declaration.profile().kind() == crate::config::ProfileKind::Human,
225        }));
226        Ok(Self {
227            artifacts,
228            evals,
229            components,
230            schedule,
231        })
232    }
233
234    pub fn artifacts(&self) -> &BTreeMap<ArtifactName, ArtifactNode<'a>> {
235        &self.artifacts
236    }
237
238    /// Components are dependency-first; members and gates are lexically ordered.
239    pub fn components(&self) -> &[Component<'a>] {
240        &self.components
241    }
242
243    /// Required material and verification, including roots and all cycle peers.
244    pub fn dependency_closure(
245        &self,
246        roots: &[&ArtifactName],
247    ) -> Result<Vec<&'a ArtifactName>, GraphError> {
248        let mut pending = Vec::new();
249        for root in roots {
250            let artifact = self
251                .artifacts
252                .get(*root)
253                .ok_or_else(|| GraphError(format!("Unknown Artifact: {root}")))?;
254            pending.push(artifact.component);
255        }
256        let mut visited = BTreeSet::new();
257        let mut required = BTreeSet::new();
258        while let Some(index) = pending.pop() {
259            if !visited.insert(index) {
260                continue;
261            }
262            let component = &self.components[index.index()];
263            required.extend(component.artifacts.iter().copied());
264            pending.extend(&component.dependencies);
265        }
266        Ok(required.into_iter().collect())
267    }
268
269    /// The roots and every Artifact sharing a cycle with one of them, lexically ordered.
270    pub fn cycle_members(
271        &self,
272        roots: &[&ArtifactName],
273    ) -> Result<Vec<&'a ArtifactName>, GraphError> {
274        let components = roots
275            .iter()
276            .map(|root| {
277                self.artifacts
278                    .get(*root)
279                    .map(|artifact| artifact.component)
280                    .ok_or_else(|| GraphError(format!("Unknown Artifact: {root}")))
281            })
282            .collect::<Result<BTreeSet<_>, _>>()?;
283        Ok(components
284            .into_iter()
285            .flat_map(|component| self.components[component.index()].artifacts.iter().copied())
286            .collect::<BTreeSet<_>>()
287            .into_iter()
288            .collect())
289    }
290
291    /// Precompute the orders for a closure containing all upstream gates and parts.
292    pub(crate) fn projection<'g>(
293        &'g self,
294        required: &BTreeSet<&ArtifactName>,
295    ) -> Projection<'g, 'a> {
296        Projection {
297            graph: self,
298            artifacts: required
299                .iter()
300                .map(|id| {
301                    self.artifacts
302                        .get_key_value(*id)
303                        .expect("required Artifact")
304                        .0
305                })
306                .collect(),
307            components: required
308                .iter()
309                .map(|id| self.artifacts[*id].component)
310                .collect(),
311            evals: self
312                .schedule
313                .order
314                .iter()
315                .copied()
316                .filter(|id| required.contains(self.evals[*id]))
317                .collect(),
318        }
319    }
320
321    /// Evaluate the whole graph. Evidence freshness is supplied by the caller;
322    /// absent entries are unreviewed, and unrelated entries are ignored.
323    pub fn evaluate(&self, evidence: &BTreeMap<EvalId, Evidence>) -> Evaluation<'_> {
324        self.evaluate_for_run(evidence, false)
325    }
326
327    /// Speculation turns operational failures into immediate blockers, without changing
328    /// the default read/verification policy of waiting for replacement GREEN evidence.
329    pub(crate) fn evaluate_for_run(
330        &self,
331        evidence: &BTreeMap<EvalId, Evidence>,
332        errors_block: bool,
333    ) -> Evaluation<'_> {
334        self.evaluate_in(
335            evidence,
336            errors_block,
337            &self.schedule.order,
338            self.artifacts.keys(),
339            (0..self.components.len()).map(ComponentId),
340        )
341    }
342
343    fn evaluate_in<'g>(
344        &'g self,
345        evidence: &BTreeMap<EvalId, Evidence>,
346        errors_block: bool,
347        eval_order: &[&'a EvalId],
348        required: impl Iterator<Item = &'g ArtifactName>,
349        components: impl Iterator<Item = ComponentId>,
350    ) -> Evaluation<'g> {
351        let mut evals: BTreeMap<EvalId, EvalEvaluation<'_>> = BTreeMap::new();
352        for &id in eval_order {
353            let gates = &self.schedule.gates[id];
354            let unmet_gates: Vec<_> = gates
355                .iter()
356                .copied()
357                .filter(|id| !evals[id.as_str()].status.passes_gate())
358                .collect();
359            // Only a Human eval's sibling machine evals share its Artifact; their ERROR blocks
360            // it too, since a person signs off only on passing machine evals.
361            let target = self.evals[id.as_str()];
362            // A BLOCKED gate passes on its own causes: the root is always a RED upstream.
363            let causes: Vec<_> = unmet_gates
364                .iter()
365                .flat_map(|&gate| {
366                    let eval = &evals[gate.as_str()];
367                    let sibling = self.evals[gate.as_str()] == target;
368                    match eval.status {
369                        EvalStatus::Red if sibling => vec![Cause::SiblingRed(gate)],
370                        EvalStatus::Red => vec![Cause::Red(gate)],
371                        EvalStatus::Error if sibling => vec![Cause::SiblingError(gate)],
372                        EvalStatus::Error if errors_block => vec![Cause::Error(gate)],
373                        EvalStatus::Blocked => {
374                            eval.causes.iter().map(|cause| cause.upstream()).collect()
375                        }
376                        _ => Vec::new(),
377                    }
378                })
379                .collect::<BTreeSet<_>>()
380                .into_iter()
381                .collect();
382            let readiness = if !causes.is_empty() {
383                Readiness::Blocked
384            } else if unmet_gates.is_empty() {
385                Readiness::Ready
386            } else {
387                Readiness::Wait
388            };
389            let provisional = gates.iter().any(|id| {
390                matches!(
391                    evals[id.as_str()].status,
392                    EvalStatus::Deferred | EvalStatus::Provisional
393                )
394            });
395            let evidence = evidence.get(id.as_str()).copied();
396            let status = match readiness {
397                Readiness::Blocked => EvalStatus::Blocked,
398                Readiness::Wait => match evidence {
399                    Some(Evidence::Current(Verdict::Red)) if errors_block => EvalStatus::Red,
400                    Some(Evidence::OperationalError) if errors_block => EvalStatus::Error,
401                    _ => EvalStatus::Wait,
402                },
403                Readiness::Ready => match evidence {
404                    Some(Evidence::Deferred) => EvalStatus::Deferred,
405                    Some(Evidence::Current(Verdict::Green)) if provisional => {
406                        EvalStatus::Provisional
407                    }
408                    Some(Evidence::Current(Verdict::Green)) => EvalStatus::Green,
409                    Some(Evidence::Current(Verdict::Red)) => EvalStatus::Red,
410                    Some(Evidence::OperationalError) => EvalStatus::Error,
411                    Some(Evidence::Stale) => EvalStatus::Stale,
412                    None => EvalStatus::Unreviewed,
413                },
414            };
415            let blocked_by = if causes.is_empty() {
416                unmet_gates
417                    .iter()
418                    .copied()
419                    .map(BlockedReference::Eval)
420                    .collect()
421            } else {
422                causes
423                    .iter()
424                    .map(|cause| BlockedReference::Eval(cause.eval()))
425                    .collect()
426            };
427            evals.insert(
428                id.clone(),
429                EvalEvaluation {
430                    readiness,
431                    status,
432                    evidence,
433                    unmet_gates,
434                    blocked_by,
435                    causes,
436                },
437            );
438        }
439        let own_satisfied: BTreeMap<_, _> = required
440            .map(|id| {
441                let artifact = &self.artifacts[id];
442                // An Artifact without evals that is composed of others takes its verdict from
443                // them, which the components below require.
444                let satisfied = artifact.basis
445                    || (artifact.evals.is_empty() && !artifact.parts.is_empty())
446                    || (!artifact.evals.is_empty()
447                        && artifact
448                            .evals
449                            .iter()
450                            .all(|id| evals[id.as_str()].status == EvalStatus::Green));
451                (id, satisfied)
452            })
453            .collect();
454        let mut satisfied = HashSet::new();
455        for id in components {
456            let component = &self.components[id.index()];
457            if component.artifacts.iter().all(|id| own_satisfied[id])
458                && component
459                    .dependencies
460                    .iter()
461                    .all(|id| satisfied.contains(id))
462            {
463                satisfied.insert(id);
464            }
465        }
466        // A part's status is part of its parent's, so parts go first; parts never form a cycle.
467        let mut order = Vec::with_capacity(own_satisfied.len());
468        let mut placed = BTreeSet::new();
469        for &root in own_satisfied.keys() {
470            let mut pending = vec![(root, false)];
471            while let Some((id, expanded)) = pending.pop() {
472                if expanded {
473                    order.push((id, &self.artifacts[id]));
474                } else if placed.insert(id) {
475                    pending.push((id, true));
476                    pending.extend(self.artifacts[id].parts.iter().map(|part| (*part, false)));
477                }
478            }
479        }
480        let mut artifacts: BTreeMap<ArtifactName, ArtifactEvaluation> = BTreeMap::new();
481        for (id, artifact) in order {
482            let satisfied = satisfied.contains(&artifact.component);
483            let status = if satisfied {
484                if artifact.basis {
485                    ArtifactStatus::Basis
486                } else {
487                    ArtifactStatus::Green
488                }
489            } else {
490                [
491                    (EvalStatus::Error, ArtifactStatus::Error),
492                    (EvalStatus::Red, ArtifactStatus::Red),
493                    (EvalStatus::Blocked, ArtifactStatus::Blocked),
494                    (EvalStatus::Wait, ArtifactStatus::Wait),
495                    (EvalStatus::Deferred, ArtifactStatus::Deferred),
496                    (EvalStatus::Provisional, ArtifactStatus::Provisional),
497                    (EvalStatus::Stale, ArtifactStatus::Stale),
498                    (EvalStatus::Unreviewed, ArtifactStatus::Unreviewed),
499                ]
500                .into_iter()
501                .find_map(|(eval_status, artifact_status)| {
502                    (artifact
503                        .evals
504                        .iter()
505                        .any(|id| evals[id.as_str()].status == eval_status)
506                        || artifact
507                            .parts
508                            .iter()
509                            .any(|id| artifacts[id.as_str()].status == artifact_status))
510                    .then_some(artifact_status)
511                })
512                .unwrap_or(if own_satisfied[id] {
513                    ArtifactStatus::Incomplete
514                } else {
515                    ArtifactStatus::Unreviewed
516                })
517            };
518            artifacts.insert(
519                id.clone(),
520                ArtifactEvaluation {
521                    status,
522                    own_satisfied: own_satisfied[id],
523                    passed: artifact
524                        .evals
525                        .iter()
526                        .filter(|id| evals[id.as_str()].status == EvalStatus::Green)
527                        .count(),
528                    total: artifact.evals.len(),
529                },
530            );
531        }
532        let obligations: Vec<_> = own_satisfied
533            .into_iter()
534            .filter_map(|(id, satisfied)| (!satisfied).then_some(id))
535            .collect();
536        let status = if evals.values().any(|c| c.status == EvalStatus::Error) {
537            FinalStatus::Error
538        } else if evals.values().any(|c| c.status == EvalStatus::Red) {
539            FinalStatus::Red
540        } else if obligations.is_empty() {
541            FinalStatus::Green
542        } else {
543            FinalStatus::Incomplete
544        };
545        Evaluation {
546            evals,
547            artifacts,
548            obligations,
549            status,
550        }
551    }
552
553    pub(crate) fn gates(&self, id: &EvalId) -> Vec<&'a EvalId> {
554        self.schedule.gates[id].clone()
555    }
556
557    pub fn eval_target(&self, id: &EvalId) -> Option<&'a ArtifactName> {
558        self.evals.get(id).copied()
559    }
560}
561
562/// Current means usable for this input/run, not merely the latest stored result.
563/// Stale evidence carries no current verdict; operational failure is not RED.
564#[derive(Debug, Clone, Copy, PartialEq, Eq)]
565pub enum Evidence {
566    Current(Verdict),
567    Deferred,
568    OperationalError,
569    Stale,
570}
571
572#[derive(Debug, Clone, Copy, PartialEq, Eq)]
573pub enum Readiness {
574    Ready,
575    Wait,
576    Blocked,
577}
578
579#[derive(Debug, Clone, Copy, PartialEq, Eq)]
580pub enum EvalStatus {
581    Deferred,
582    Provisional,
583    Green,
584    Red,
585    Error,
586    Stale,
587    Unreviewed,
588    Wait,
589    Blocked,
590}
591
592#[derive(Debug, Clone, PartialEq, Eq)]
593pub struct EvalEvaluation<'a> {
594    /// Gate readiness only; READY never requests re-execution of existing evidence.
595    pub readiness: Readiness,
596    pub status: EvalStatus,
597    /// Retained for audit even when gates mask its effective status.
598    pub evidence: Option<Evidence>,
599    pub unmet_gates: Vec<&'a EvalId>,
600    /// BLOCKED: the root causes; otherwise the unmet gates it waits for.
601    pub blocked_by: Vec<BlockedReference<'a>>,
602    /// Why the eval is BLOCKED, followed through BLOCKED gates to the failed evals upstream;
603    /// empty unless BLOCKED.
604    pub causes: Vec<Cause<'a>>,
605}
606
607/// The failed eval at the root of a block: a RED verdict, or in a Run that treats
608/// operational failures as blockers (`--speculate`), an ERROR. A Human eval is also blocked
609/// by a RED or ERROR machine eval of its own Artifact, its sibling.
610#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
611pub enum Cause<'a> {
612    Red(&'a EvalId),
613    Error(&'a EvalId),
614    SiblingRed(&'a EvalId),
615    SiblingError(&'a EvalId),
616}
617
618impl<'a> Cause<'a> {
619    pub fn eval(self) -> &'a EvalId {
620        match self {
621            Self::Red(id) | Self::Error(id) | Self::SiblingRed(id) | Self::SiblingError(id) => id,
622        }
623    }
624
625    /// The same failure as seen from downstream, where it is an upstream dependency.
626    fn upstream(self) -> Self {
627        match self {
628            Self::SiblingRed(id) => Self::Red(id),
629            Self::SiblingError(id) => Self::Error(id),
630            cause => cause,
631        }
632    }
633}
634
635/// A blocked dependency names either material or an Eval, never an unclassified string.
636#[derive(Debug, Clone, Copy, PartialEq, Eq)]
637pub enum BlockedReference<'a> {
638    Artifact(&'a ArtifactName),
639    Eval(&'a EvalId),
640}
641impl BlockedReference<'_> {
642    pub fn as_str(&self) -> &str {
643        match self {
644            Self::Artifact(id) => id.as_str(),
645            Self::Eval(id) => id.as_str(),
646        }
647    }
648}
649impl std::fmt::Display for BlockedReference<'_> {
650    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
651        formatter.write_str(self.as_str())
652    }
653}
654
655impl EvalStatus {
656    pub fn passes_gate(self) -> bool {
657        matches!(self, Self::Green | Self::Deferred | Self::Provisional)
658    }
659}
660
661impl EvalEvaluation<'_> {
662    /// Operational errors require an explicit retry, not automatic redispatch.
663    pub fn can_execute(&self) -> bool {
664        self.readiness == Readiness::Ready && matches!(self.evidence, None | Some(Evidence::Stale))
665    }
666
667    /// Names the failed evals that block this one, RED verdicts first; `None` unless BLOCKED.
668    /// Each cause is final within a Run, but more can follow, so settlement saves it again.
669    pub fn blocked_reason(&self) -> Option<String> {
670        let names = |kind: fn(&Cause<'_>) -> bool| {
671            self.causes
672                .iter()
673                .filter(|cause| kind(cause))
674                .map(|cause| cause.eval().as_str())
675                .collect::<Vec<_>>()
676                .join(", ")
677        };
678        let parts: Vec<_> = [
679            (
680                "Sibling machine eval RED",
681                names(|cause| matches!(cause, Cause::SiblingRed(_))),
682            ),
683            (
684                "Sibling machine eval ERROR",
685                names(|cause| matches!(cause, Cause::SiblingError(_))),
686            ),
687            (
688                "Dependency verdict RED",
689                names(|cause| matches!(cause, Cause::Red(_))),
690            ),
691            (
692                "Dependency ERROR",
693                names(|cause| matches!(cause, Cause::Error(_))),
694            ),
695        ]
696        .into_iter()
697        .filter(|(_, names)| !names.is_empty())
698        .map(|(label, names)| format!("{label}: {names}"))
699        .collect();
700        (!parts.is_empty()).then(|| parts.join("; "))
701    }
702}
703
704#[derive(Debug, Clone, Copy, PartialEq, Eq)]
705pub enum ArtifactStatus {
706    Deferred,
707    Provisional,
708    Basis,
709    Green,
710    Incomplete,
711    Error,
712    Red,
713    Blocked,
714    Wait,
715    Stale,
716    Unreviewed,
717}
718
719impl From<ArtifactStatus> for crate::types::ArtifactValidationStatus {
720    fn from(status: ArtifactStatus) -> Self {
721        match status {
722            ArtifactStatus::Deferred => Self::Deferred,
723            ArtifactStatus::Provisional => Self::Provisional,
724            ArtifactStatus::Basis => Self::Basis,
725            ArtifactStatus::Green => Self::Green,
726            ArtifactStatus::Incomplete => Self::Incomplete,
727            ArtifactStatus::Error => Self::Error,
728            ArtifactStatus::Red => Self::Red,
729            ArtifactStatus::Blocked => Self::Blocked,
730            ArtifactStatus::Wait => Self::Wait,
731            ArtifactStatus::Stale => Self::Stale,
732            ArtifactStatus::Unreviewed => Self::Unreviewed,
733        }
734    }
735}
736
737#[derive(Debug, Clone, PartialEq, Eq)]
738pub struct ArtifactEvaluation {
739    pub status: ArtifactStatus,
740    pub own_satisfied: bool,
741    pub passed: usize,
742    pub total: usize,
743}
744
745impl ArtifactEvaluation {
746    /// Includes all required dependencies and SCC peers, even without Evals.
747    pub fn satisfied(&self) -> bool {
748        matches!(self.status, ArtifactStatus::Green | ArtifactStatus::Basis)
749    }
750}
751
752/// Aggregate validation status, never a fabricated Eval verdict.
753#[derive(Debug, Clone, Copy, PartialEq, Eq)]
754pub enum FinalStatus {
755    Green,
756    Red,
757    Error,
758    Incomplete,
759}
760
761#[derive(Debug, Clone, PartialEq, Eq)]
762pub struct Evaluation<'a> {
763    pub evals: BTreeMap<EvalId, EvalEvaluation<'a>>,
764    pub artifacts: BTreeMap<ArtifactName, ArtifactEvaluation>,
765    /// Artifacts whose own obligations are unmet, not execution gates.
766    pub obligations: Vec<&'a ArtifactName>,
767    pub status: FinalStatus,
768}
769
770#[cfg(test)]
771mod tests;
772
773impl serde::Serialize for BlockedReference<'_> {
774    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
775        serializer.serialize_str(self.as_str())
776    }
777}
778
779impl From<BlockedReference<'_>> for crate::store::Blocker {
780    fn from(reference: BlockedReference<'_>) -> Self {
781        match reference {
782            BlockedReference::Artifact(id) => Self::Artifact(id.clone()),
783            BlockedReference::Eval(id) => Self::Eval(id.clone()),
784        }
785    }
786}
787
788pub(crate) mod schedule;