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            Gating::default(),
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, Gating::default())
325    }
326
327    /// Evaluate the whole graph under a Run's [`Gating`].
328    pub(crate) fn evaluate_for_run(
329        &self,
330        evidence: &BTreeMap<EvalId, Evidence>,
331        gating: Gating,
332    ) -> Evaluation<'_> {
333        self.evaluate_in(
334            evidence,
335            gating,
336            &self.schedule.order,
337            self.artifacts.keys(),
338            (0..self.components.len()).map(ComponentId),
339        )
340    }
341
342    fn evaluate_in<'g>(
343        &'g self,
344        evidence: &BTreeMap<EvalId, Evidence>,
345        Gating {
346            errors_block,
347            ignore_dependencies,
348        }: Gating,
349        eval_order: &[&'a EvalId],
350        required: impl Iterator<Item = &'g ArtifactName>,
351        components: impl Iterator<Item = ComponentId>,
352    ) -> Evaluation<'g> {
353        let mut evals: BTreeMap<EvalId, EvalEvaluation<'_>> = BTreeMap::new();
354        for &id in eval_order {
355            // Only a Human eval's sibling machine evals share its Artifact; their ERROR blocks
356            // it too, since a person signs off only on passing machine evals.
357            let target = self.evals[id.as_str()];
358            let gates = || {
359                self.schedule.gates[id]
360                    .iter()
361                    .copied()
362                    .filter(|gate| !ignore_dependencies || self.evals[gate.as_str()] == target)
363            };
364            let unmet_gates: Vec<_> = gates()
365                .filter(|id| !evals[id.as_str()].status.passes_gate())
366                .collect();
367            // A BLOCKED gate passes on its own causes: the root is always a RED upstream.
368            let causes: Vec<_> = unmet_gates
369                .iter()
370                .flat_map(|&gate| {
371                    let eval = &evals[gate.as_str()];
372                    let sibling = self.evals[gate.as_str()] == target;
373                    match eval.status {
374                        EvalStatus::Red if sibling => vec![Cause::SiblingRed(gate)],
375                        EvalStatus::Red => vec![Cause::Red(gate)],
376                        EvalStatus::Error if sibling => vec![Cause::SiblingError(gate)],
377                        EvalStatus::Error if errors_block => vec![Cause::Error(gate)],
378                        EvalStatus::Blocked => {
379                            eval.causes.iter().map(|cause| cause.upstream()).collect()
380                        }
381                        _ => Vec::new(),
382                    }
383                })
384                .collect::<BTreeSet<_>>()
385                .into_iter()
386                .collect();
387            let readiness = if !causes.is_empty() {
388                Readiness::Blocked
389            } else if unmet_gates.is_empty() {
390                Readiness::Ready
391            } else {
392                Readiness::Wait
393            };
394            let provisional = gates().any(|id| {
395                matches!(
396                    evals[id.as_str()].status,
397                    EvalStatus::Deferred | EvalStatus::Provisional
398                )
399            });
400            let evidence = evidence.get(id.as_str()).copied();
401            let status = match readiness {
402                Readiness::Blocked => EvalStatus::Blocked,
403                Readiness::Wait => match evidence {
404                    Some(Evidence::Current(Verdict::Red)) if errors_block => EvalStatus::Red,
405                    Some(Evidence::OperationalError) if errors_block => EvalStatus::Error,
406                    _ => EvalStatus::Wait,
407                },
408                Readiness::Ready => match evidence {
409                    Some(Evidence::Deferred) => EvalStatus::Deferred,
410                    Some(Evidence::Current(Verdict::Green)) if provisional => {
411                        EvalStatus::Provisional
412                    }
413                    Some(Evidence::Current(Verdict::Green)) => EvalStatus::Green,
414                    Some(Evidence::Current(Verdict::Red)) => EvalStatus::Red,
415                    Some(Evidence::OperationalError) => EvalStatus::Error,
416                    Some(Evidence::Stale) => EvalStatus::Stale,
417                    None => EvalStatus::Unreviewed,
418                },
419            };
420            let blocked_by = if causes.is_empty() {
421                unmet_gates
422                    .iter()
423                    .copied()
424                    .map(BlockedReference::Eval)
425                    .collect()
426            } else {
427                causes
428                    .iter()
429                    .map(|cause| BlockedReference::Eval(cause.eval()))
430                    .collect()
431            };
432            evals.insert(
433                id.clone(),
434                EvalEvaluation {
435                    readiness,
436                    status,
437                    evidence,
438                    unmet_gates,
439                    blocked_by,
440                    causes,
441                },
442            );
443        }
444        let own_satisfied: BTreeMap<_, _> = required
445            .map(|id| {
446                let artifact = &self.artifacts[id];
447                // An Artifact without evals that is composed of others takes its verdict from
448                // them, which the components below require.
449                let satisfied = artifact.basis
450                    || (artifact.evals.is_empty() && !artifact.parts.is_empty())
451                    || (!artifact.evals.is_empty()
452                        && artifact
453                            .evals
454                            .iter()
455                            .all(|id| evals[id.as_str()].status == EvalStatus::Green));
456                (id, satisfied)
457            })
458            .collect();
459        let mut satisfied = HashSet::new();
460        for id in components {
461            let component = &self.components[id.index()];
462            if component.artifacts.iter().all(|id| own_satisfied[id])
463                && component
464                    .dependencies
465                    .iter()
466                    .all(|id| satisfied.contains(id))
467            {
468                satisfied.insert(id);
469            }
470        }
471        // A part's status is part of its parent's, so parts go first; parts never form a cycle.
472        let mut order = Vec::with_capacity(own_satisfied.len());
473        let mut placed = BTreeSet::new();
474        for &root in own_satisfied.keys() {
475            let mut pending = vec![(root, false)];
476            while let Some((id, expanded)) = pending.pop() {
477                if expanded {
478                    order.push((id, &self.artifacts[id]));
479                } else if placed.insert(id) {
480                    pending.push((id, true));
481                    pending.extend(self.artifacts[id].parts.iter().map(|part| (*part, false)));
482                }
483            }
484        }
485        let mut artifacts: BTreeMap<ArtifactName, ArtifactEvaluation> = BTreeMap::new();
486        for (id, artifact) in order {
487            let satisfied = satisfied.contains(&artifact.component);
488            let status = if satisfied {
489                if artifact.basis {
490                    ArtifactStatus::Basis
491                } else {
492                    ArtifactStatus::Green
493                }
494            } else {
495                [
496                    (EvalStatus::Error, ArtifactStatus::Error),
497                    (EvalStatus::Red, ArtifactStatus::Red),
498                    (EvalStatus::Blocked, ArtifactStatus::Blocked),
499                    (EvalStatus::Wait, ArtifactStatus::Wait),
500                    (EvalStatus::Deferred, ArtifactStatus::Deferred),
501                    (EvalStatus::Provisional, ArtifactStatus::Provisional),
502                    (EvalStatus::Stale, ArtifactStatus::Stale),
503                    (EvalStatus::Unreviewed, ArtifactStatus::Unreviewed),
504                ]
505                .into_iter()
506                .find_map(|(eval_status, artifact_status)| {
507                    (artifact
508                        .evals
509                        .iter()
510                        .any(|id| evals[id.as_str()].status == eval_status)
511                        || artifact
512                            .parts
513                            .iter()
514                            .any(|id| artifacts[id.as_str()].status == artifact_status))
515                    .then_some(artifact_status)
516                })
517                .unwrap_or(if own_satisfied[id] {
518                    ArtifactStatus::Incomplete
519                } else {
520                    ArtifactStatus::Unreviewed
521                })
522            };
523            artifacts.insert(
524                id.clone(),
525                ArtifactEvaluation {
526                    status,
527                    own_satisfied: own_satisfied[id],
528                    passed: artifact
529                        .evals
530                        .iter()
531                        .filter(|id| evals[id.as_str()].status == EvalStatus::Green)
532                        .count(),
533                    total: artifact.evals.len(),
534                },
535            );
536        }
537        let obligations: Vec<_> = own_satisfied
538            .into_iter()
539            .filter_map(|(id, satisfied)| (!satisfied).then_some(id))
540            .collect();
541        let status = if evals.values().any(|c| c.status == EvalStatus::Error) {
542            FinalStatus::Error
543        } else if evals.values().any(|c| c.status == EvalStatus::Red) {
544            FinalStatus::Red
545        } else if obligations.is_empty() {
546            FinalStatus::Green
547        } else {
548            FinalStatus::Incomplete
549        };
550        Evaluation {
551            evals,
552            artifacts,
553            obligations,
554            status,
555        }
556    }
557
558    pub(crate) fn gates(&self, id: &EvalId) -> Vec<&'a EvalId> {
559        self.schedule.gates[id].clone()
560    }
561
562    pub fn eval_target(&self, id: &EvalId) -> Option<&'a ArtifactName> {
563        self.evals.get(id).copied()
564    }
565}
566
567/// Current means usable for this input/run, not merely the latest stored result.
568/// Stale evidence carries no current verdict; operational failure is not RED.
569#[derive(Debug, Clone, Copy, PartialEq, Eq)]
570pub enum Evidence {
571    Current(Verdict),
572    Deferred,
573    OperationalError,
574    Stale,
575}
576
577/// How a Run treats an eval's gates; the default is the policy of reads and plain `verify`.
578#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
579pub(crate) struct Gating {
580    /// An operational failure blocks downstream at once (`--speculate`) instead of waiting
581    /// for replacement evidence.
582    pub errors_block: bool,
583    /// Dependency gates are not considered (`--ignore-gates`); a Human eval is still gated by
584    /// the machine evals of its own Artifact.
585    pub ignore_dependencies: bool,
586}
587
588#[derive(Debug, Clone, Copy, PartialEq, Eq)]
589pub enum Readiness {
590    Ready,
591    Wait,
592    Blocked,
593}
594
595#[derive(Debug, Clone, Copy, PartialEq, Eq)]
596pub enum EvalStatus {
597    Deferred,
598    Provisional,
599    Green,
600    Red,
601    Error,
602    Stale,
603    Unreviewed,
604    Wait,
605    Blocked,
606}
607
608#[derive(Debug, Clone, PartialEq, Eq)]
609pub struct EvalEvaluation<'a> {
610    /// Gate readiness only; READY never requests re-execution of existing evidence.
611    pub readiness: Readiness,
612    pub status: EvalStatus,
613    /// Retained for audit even when gates mask its effective status.
614    pub evidence: Option<Evidence>,
615    pub unmet_gates: Vec<&'a EvalId>,
616    /// BLOCKED: the root causes; otherwise the unmet gates it waits for.
617    pub blocked_by: Vec<BlockedReference<'a>>,
618    /// Why the eval is BLOCKED, followed through BLOCKED gates to the failed evals upstream;
619    /// empty unless BLOCKED.
620    pub causes: Vec<Cause<'a>>,
621}
622
623/// The failed eval at the root of a block: a RED verdict, or in a Run that treats
624/// operational failures as blockers (`--speculate`), an ERROR. A Human eval is also blocked
625/// by a RED or ERROR machine eval of its own Artifact, its sibling.
626#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
627pub enum Cause<'a> {
628    Red(&'a EvalId),
629    Error(&'a EvalId),
630    SiblingRed(&'a EvalId),
631    SiblingError(&'a EvalId),
632}
633
634impl<'a> Cause<'a> {
635    pub fn eval(self) -> &'a EvalId {
636        match self {
637            Self::Red(id) | Self::Error(id) | Self::SiblingRed(id) | Self::SiblingError(id) => id,
638        }
639    }
640
641    /// The same failure as seen from downstream, where it is an upstream dependency.
642    fn upstream(self) -> Self {
643        match self {
644            Self::SiblingRed(id) => Self::Red(id),
645            Self::SiblingError(id) => Self::Error(id),
646            cause => cause,
647        }
648    }
649}
650
651/// A blocked dependency names either material or an Eval, never an unclassified string.
652#[derive(Debug, Clone, Copy, PartialEq, Eq)]
653pub enum BlockedReference<'a> {
654    Artifact(&'a ArtifactName),
655    Eval(&'a EvalId),
656}
657impl BlockedReference<'_> {
658    pub fn as_str(&self) -> &str {
659        match self {
660            Self::Artifact(id) => id.as_str(),
661            Self::Eval(id) => id.as_str(),
662        }
663    }
664}
665impl std::fmt::Display for BlockedReference<'_> {
666    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
667        formatter.write_str(self.as_str())
668    }
669}
670
671impl EvalStatus {
672    pub fn passes_gate(self) -> bool {
673        matches!(self, Self::Green | Self::Deferred | Self::Provisional)
674    }
675}
676
677impl EvalEvaluation<'_> {
678    /// Operational errors require an explicit retry, not automatic redispatch.
679    pub fn can_execute(&self) -> bool {
680        self.readiness == Readiness::Ready && matches!(self.evidence, None | Some(Evidence::Stale))
681    }
682
683    /// Names the failed evals that block this one, RED verdicts first; `None` unless BLOCKED.
684    /// Each cause is final within a Run, but more can follow, so settlement saves it again.
685    pub fn blocked_reason(&self) -> Option<String> {
686        let names = |kind: fn(&Cause<'_>) -> bool| {
687            self.causes
688                .iter()
689                .filter(|cause| kind(cause))
690                .map(|cause| cause.eval().as_str())
691                .collect::<Vec<_>>()
692                .join(", ")
693        };
694        let parts: Vec<_> = [
695            (
696                "Sibling machine eval RED",
697                names(|cause| matches!(cause, Cause::SiblingRed(_))),
698            ),
699            (
700                "Sibling machine eval ERROR",
701                names(|cause| matches!(cause, Cause::SiblingError(_))),
702            ),
703            (
704                "Dependency verdict RED",
705                names(|cause| matches!(cause, Cause::Red(_))),
706            ),
707            (
708                "Dependency ERROR",
709                names(|cause| matches!(cause, Cause::Error(_))),
710            ),
711        ]
712        .into_iter()
713        .filter(|(_, names)| !names.is_empty())
714        .map(|(label, names)| format!("{label}: {names}"))
715        .collect();
716        (!parts.is_empty()).then(|| parts.join("; "))
717    }
718}
719
720#[derive(Debug, Clone, Copy, PartialEq, Eq)]
721pub enum ArtifactStatus {
722    Deferred,
723    Provisional,
724    Basis,
725    Green,
726    Incomplete,
727    Error,
728    Red,
729    Blocked,
730    Wait,
731    Stale,
732    Unreviewed,
733}
734
735impl From<ArtifactStatus> for crate::types::ArtifactValidationStatus {
736    fn from(status: ArtifactStatus) -> Self {
737        match status {
738            ArtifactStatus::Deferred => Self::Deferred,
739            ArtifactStatus::Provisional => Self::Provisional,
740            ArtifactStatus::Basis => Self::Basis,
741            ArtifactStatus::Green => Self::Green,
742            ArtifactStatus::Incomplete => Self::Incomplete,
743            ArtifactStatus::Error => Self::Error,
744            ArtifactStatus::Red => Self::Red,
745            ArtifactStatus::Blocked => Self::Blocked,
746            ArtifactStatus::Wait => Self::Wait,
747            ArtifactStatus::Stale => Self::Stale,
748            ArtifactStatus::Unreviewed => Self::Unreviewed,
749        }
750    }
751}
752
753#[derive(Debug, Clone, PartialEq, Eq)]
754pub struct ArtifactEvaluation {
755    pub status: ArtifactStatus,
756    pub own_satisfied: bool,
757    pub passed: usize,
758    pub total: usize,
759}
760
761impl ArtifactEvaluation {
762    /// Includes all required dependencies and SCC peers, even without Evals.
763    pub fn satisfied(&self) -> bool {
764        matches!(self.status, ArtifactStatus::Green | ArtifactStatus::Basis)
765    }
766}
767
768/// Aggregate validation status, never a fabricated Eval verdict.
769#[derive(Debug, Clone, Copy, PartialEq, Eq)]
770pub enum FinalStatus {
771    Green,
772    Red,
773    Error,
774    Incomplete,
775}
776
777#[derive(Debug, Clone, PartialEq, Eq)]
778pub struct Evaluation<'a> {
779    pub evals: BTreeMap<EvalId, EvalEvaluation<'a>>,
780    pub artifacts: BTreeMap<ArtifactName, ArtifactEvaluation>,
781    /// Artifacts whose own obligations are unmet, not execution gates.
782    pub obligations: Vec<&'a ArtifactName>,
783    pub status: FinalStatus,
784}
785
786#[cfg(test)]
787mod tests;
788
789impl serde::Serialize for BlockedReference<'_> {
790    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
791        serializer.serialize_str(self.as_str())
792    }
793}
794
795impl From<BlockedReference<'_>> for crate::store::Blocker {
796    fn from(reference: BlockedReference<'_>) -> Self {
797        match reference {
798            BlockedReference::Artifact(id) => Self::Artifact(id.clone()),
799            BlockedReference::Eval(id) => Self::Eval(id.clone()),
800        }
801    }
802}
803
804pub(crate) mod schedule;