Skip to main content

artifactize_core/monitor/model/
tree.rs

1//! The Artifacts and evals tree: one row per eval, Artifact rows rolled up from them.
2use crate::types::{ArtifactName, EvalId};
3use serde_json::Value;
4use time::OffsetDateTime;
5
6use super::{
7    Saved,
8    states::{
9        Activity, Busy, Completion, EvalView, NotRun, Queue, Rank, Source, States, Upstream, Waits,
10    },
11};
12use crate::store::{RequestView, RunView};
13
14/// Colour classes; the renderer maps them to terminal colours.
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub enum Tone {
17    Green,
18    Red,
19    Error,
20    Running,
21    Human,
22    Queued,
23    Blocked,
24    Muted,
25}
26
27/// In-progress rows are bold; rows that wait or did not run are dimmed.
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub enum Weight {
30    Bold,
31    Normal,
32    Dim,
33}
34
35/// Status text; a toned segment (an X token) keeps its colour inside a dimmed row.
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct Segment {
38    pub text: String,
39    pub tone: Option<Tone>,
40}
41
42impl Segment {
43    fn plain(text: impl Into<String>) -> Self {
44        Self {
45            text: text.into(),
46            tone: None,
47        }
48    }
49    fn toned(text: impl Into<String>, tone: Tone) -> Self {
50        Self {
51            text: text.into(),
52            tone: Some(tone),
53        }
54    }
55}
56
57#[derive(Debug, Clone, PartialEq, Eq)]
58pub enum Kind {
59    /// An Artifact rolled up from its eval rows; basis Artifacts are complete.
60    Artifact {
61        completion: Completion,
62        basis: bool,
63    },
64    Eval(EvalView),
65}
66
67#[derive(Debug, Clone)]
68pub struct Node {
69    /// Stable tree identifier: `a:<artifact>` or `e:<eval>`.
70    pub id: super::NodeId,
71    pub kind: Kind,
72    pub glyph: &'static str,
73    pub tone: Tone,
74    pub weight: Weight,
75    pub name: String,
76    /// Dim markers after the name: `↻ peer`, `[file]`.
77    pub marks: String,
78    pub text: Vec<Segment>,
79    /// Right column: elapsed time for evals, `passed/total` for Artifacts.
80    pub right: String,
81    /// Artifact rows with evals: how many of them pass, of how many (the `right` column).
82    pub tally: Option<Tally>,
83    /// Right column of the compact tree: elapsed time, `←X`/`←N`, or `passed/total`.
84    pub compact: String,
85    /// The state changed after the Run ended (rendered as a dim `*`).
86    pub changed: bool,
87    /// Eval rows: every dependency Artifact, unmet ones first in X order.
88    pub upstream: Vec<Upstream>,
89    /// A waiting Eval cannot proceed in this Run because an actual external gate failed.
90    pub(crate) held: bool,
91    /// Artifact rows: the Artifacts it is made of directly, by name.
92    pub parts: Vec<ArtifactName>,
93    /// Timed eval rows, so a cached tree can redraw its elapsed times.
94    pub clock: Option<Clock>,
95    pub children: Vec<Node>,
96}
97
98/// How many of an Artifact's evals are GREEN, of how many it has: its row's right column and
99/// its graph node's count.
100#[derive(Debug, Clone, Copy, PartialEq, Eq)]
101pub struct Tally {
102    pub passed: usize,
103    pub of: usize,
104}
105
106impl std::fmt::Display for Tally {
107    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
108        write!(formatter, "{}/{}", self.passed, self.of)
109    }
110}
111
112/// When a timed eval started and, once settled, ended.
113#[derive(Debug, Clone, Copy, PartialEq, Eq)]
114pub struct Clock {
115    pub start: OffsetDateTime,
116    pub end: Option<OffsetDateTime>,
117}
118
119impl Clock {
120    pub fn elapsed(self, now: OffsetDateTime) -> String {
121        super::duration(self.end.unwrap_or(now) - self.start)
122    }
123}
124
125impl Node {
126    /// The right column (or the compact one) as of `now`.
127    pub fn right_at(&self, now: OffsetDateTime, compact: bool) -> String {
128        match self.clock {
129            Some(clock) => clock.elapsed(now),
130            None if compact => self.compact.clone(),
131            None => self.right.clone(),
132        }
133    }
134
135    /// The status text without styling.
136    pub fn status(&self) -> String {
137        self.text
138            .iter()
139            .map(|segment| segment.text.as_str())
140            .collect()
141    }
142
143    /// The whole row as plain text, for tests and logs.
144    pub fn line(&self) -> String {
145        let mut line = format!("{} {}{}", self.glyph, self.name, self.marks);
146        for part in [self.status(), self.right.clone()] {
147            if !part.is_empty() {
148                line = format!("{line}  {part}");
149            }
150        }
151        if self.changed {
152            line.push_str(" *");
153        }
154        line
155    }
156
157    /// An Artifact whose evals are all done; folded by default.
158    pub fn done(&self) -> bool {
159        matches!(
160            self.kind,
161            Kind::Artifact {
162                completion: Completion::Complete,
163                ..
164            }
165        ) && !self.children.is_empty()
166    }
167
168    /// An ERROR, RED or waiting Human eval row: what `!` (next attention) visits.
169    pub fn urgent(&self) -> bool {
170        matches!(
171            self.kind,
172            Kind::Eval(EvalView::Failed { .. } | EvalView::InProgress(Activity::Human(_)))
173        )
174    }
175
176    /// An eval row that is in progress or failed: where the cursor starts.
177    pub fn attention(&self) -> bool {
178        matches!(
179            self.kind,
180            Kind::Eval(EvalView::InProgress(_) | EvalView::Failed { .. })
181        )
182    }
183}
184
185/// Glyph, colour and word of an Artifact's completion where another row names it.
186pub fn completion(completion: Completion) -> (&'static str, Tone, &'static str) {
187    match completion {
188        Completion::Complete => ("✓", Tone::Green, "complete"),
189        Completion::InProgress(Busy::Running) => ("◐", Tone::Running, "in progress"),
190        Completion::InProgress(Busy::Human) => ("?", Tone::Human, "in progress"),
191        Completion::InProgress(Busy::Queued) => ("·", Tone::Queued, "in progress"),
192        Completion::Waiting { blocked: false } => ("…", Tone::Muted, "waiting"),
193        Completion::Waiting { blocked: true } => ("⊘", Tone::Blocked, "blocked"),
194        Completion::Failed { verdict: true } => ("✗", Tone::Red, "failed"),
195        Completion::Failed { verdict: false } => ("!", Tone::Error, "failed"),
196    }
197}
198
199/// Glyph, colour and weight of one eval row.
200fn style(view: &EvalView) -> (&'static str, Tone, Weight) {
201    match view {
202        EvalView::Done(Source::Provisional) => ("○", Tone::Muted, Weight::Normal),
203        EvalView::Done(_) => ("✓", Tone::Green, Weight::Normal),
204        EvalView::Failed { verdict: true } => ("✗", Tone::Red, Weight::Normal),
205        EvalView::Failed { verdict: false } => ("!", Tone::Error, Weight::Normal),
206        EvalView::InProgress(Activity::Running) => ("◐", Tone::Running, Weight::Bold),
207        EvalView::InProgress(Activity::Human(_)) => ("?", Tone::Human, Weight::Bold),
208        EvalView::InProgress(Activity::Queued(_)) => ("·", Tone::Queued, Weight::Normal),
209        EvalView::WaitingOn(_) => ("…", Tone::Muted, Weight::Dim),
210        EvalView::BlockedBy(_) => ("⊘", Tone::Blocked, Weight::Normal),
211        EvalView::NotRun(NotRun::Budget) => ("$", Tone::Blocked, Weight::Normal),
212        EvalView::NotRun(NotRun::Absent) => ("-", Tone::Muted, Weight::Dim),
213        EvalView::NotRun(_) => ("○", Tone::Muted, Weight::Dim),
214    }
215}
216
217/// Shown X per row; the rest become `+N`.
218const SHOWN: usize = 2;
219/// A shown text field keeps this many characters of its first line, enough for a short value
220/// or the start of a sentence while two fields still fit on one row.
221const SHOWN_TEXT: usize = 24;
222
223/// `cli ◐ in progress`, or `a ◐, b ? +1`; an ERROR-failed X asks for a retry.
224fn tokens(states: &States, x: &[crate::types::ArtifactName], glyphs: bool) -> Vec<Segment> {
225    let mut segments = Vec::new();
226    for (index, id) in x.iter().take(SHOWN).enumerate() {
227        if index > 0 {
228            segments.push(Segment::plain(", "));
229        }
230        let (glyph, tone, word) = completion(states.completion(id));
231        let text = match (glyphs, x.len()) {
232            (false, _) => id.to_string(),
233            (true, 1) => format!("{id} {glyph} {word}"),
234            (true, _) => format!("{id} {glyph}"),
235        };
236        segments.push(Segment::toned(text, tone));
237    }
238    if x.len() > SHOWN {
239        segments.push(Segment::plain(format!(" +{}", x.len() - SHOWN)));
240    }
241    if glyphs
242        && let Some(failed) = x
243            .iter()
244            .find(|id| states.completion(id) == Completion::Failed { verdict: false })
245    {
246        segments.push(Segment::plain(format!(" (retry {failed} first)")));
247    }
248    segments
249}
250
251fn waits(states: &States, prefix: &str, waits: &Waits) -> Vec<Segment> {
252    let mut segments = vec![Segment::plain(prefix)];
253    segments.extend(tokens(states, &waits.artifacts, true));
254    if let Some((via, root)) = &waits.root {
255        segments.push(Segment::plain(format!(" ({via} waits for ")));
256        let (_, tone, _) = completion(states.completion(root));
257        segments.push(Segment::toned(root.clone(), tone));
258        segments.push(Segment::plain(")"));
259    }
260    segments
261}
262
263/// The top-level Result keys behind a RED verdict, such as `violations 3`.
264fn findings(result: Option<&crate::store::ExecutionResult>) -> String {
265    use crate::store::{ExecutionResult, ResultField};
266    let Some(result) = result else {
267        return String::new();
268    };
269    let mut fields = result.owner_fields().clone();
270    if let ExecutionResult::Runtime(runtime) = result {
271        match runtime.exit_code {
272            ResultField::Missing => {}
273            ResultField::Null => {
274                fields.insert("exitCode".into(), Value::Null);
275            }
276            ResultField::Value(code) => {
277                fields.insert("exitCode".into(), Value::from(code));
278            }
279        }
280    }
281    let fields = fields.iter().filter(|(key, _)| {
282        !matches!(
283            key.as_str(),
284            "verdict" | "stdout" | "stderr" | "truncated" | "durationMs"
285        )
286    });
287    let parts: Vec<_> = fields
288        .take(SHOWN)
289        .map(|(key, value)| match value {
290            Value::Array(items) => format!("{key} {}", items.len()),
291            Value::Object(fields) => format!("{key} {{{}}}", fields.len()),
292            Value::String(text) => {
293                let text = text.lines().next().unwrap_or_default();
294                let mut short: String = text.chars().take(SHOWN_TEXT).collect();
295                if short.len() < text.len() {
296                    short.push('…');
297                }
298                format!("{key} {short}")
299            }
300            value => format!("{key} {value}"),
301        })
302        .collect();
303    parts.join(", ")
304}
305
306fn short_profile(profile: &crate::config::StoredProfile) -> String {
307    use crate::config::StoredProfile;
308    match profile {
309        StoredProfile::Agent { backend, model, .. } => format!(
310            "agent {} {model}",
311            serde_json::to_value(backend)
312                .ok()
313                .and_then(|value| value.as_str().map(str::to_owned))
314                .unwrap_or_default()
315        ),
316        StoredProfile::Runtime { command, .. } => {
317            format!("runtime {}", crate::platform::program_text(command))
318        }
319        StoredProfile::Human {} => "human".into(),
320    }
321}
322
323fn text(states: &States, view: &EvalView, request: Option<&RequestView>) -> Vec<Segment> {
324    let plain = |text: &str| vec![Segment::plain(text)];
325    match view {
326        EvalView::Done(Source::Provisional) => plain("PROVISIONAL · sign-offs remain"),
327        EvalView::Done(Source::Executed) => plain("GREEN"),
328        EvalView::Done(Source::Reused) => plain("GREEN · reused"),
329        EvalView::Done(Source::Saved) => plain("GREEN · saved result, not in this Run"),
330        EvalView::Failed { verdict: true } => {
331            let findings = findings(request.and_then(|view| view.request.result()));
332            if request.is_none() {
333                plain("RED · saved result, not in this Run")
334            } else if findings.is_empty() {
335                plain("RED")
336            } else {
337                vec![Segment::plain(format!("RED · {findings}"))]
338            }
339        }
340        EvalView::Failed { verdict: false } => match request.and_then(super::error) {
341            Some(error) => vec![Segment::plain(format!(
342                "ERROR · {}",
343                error.lines().next().unwrap_or_default()
344            ))],
345            None if request.is_none() => plain("ERROR · saved result, not in this Run"),
346            None => plain("ERROR"),
347        },
348        EvalView::InProgress(Activity::Running) => vec![Segment::plain(format!(
349            "running · {}",
350            request.map_or_else(String::new, |view| short_profile(&view.request.profile))
351        ))],
352        EvalView::InProgress(Activity::Human(None)) => plain("Human sign-off · unclaimed"),
353        EvalView::InProgress(Activity::Human(Some(reviewer))) => vec![Segment::plain(format!(
354            "Human sign-off · claimed by {reviewer}"
355        ))],
356        EvalView::InProgress(Activity::Queued(Queue::Ready)) => plain("queued"),
357        EvalView::InProgress(Activity::Queued(Queue::Jobs)) => plain("queued · --jobs slots full"),
358        EvalView::InProgress(Activity::Queued(Queue::Slot(backend))) => {
359            vec![Segment::plain(format!("queued · {backend} slots full"))]
360        }
361        EvalView::InProgress(Activity::Queued(Queue::Joined)) => {
362            plain("queued · joins the running review")
363        }
364        EvalView::WaitingOn(x) => waits(states, "waits for ", x),
365        EvalView::BlockedBy(x) => {
366            let mut segments = vec![Segment::plain(if states.running {
367                "blocked by "
368            } else {
369                "not run: blocked by "
370            })];
371            segments.extend(tokens(states, x, true));
372            segments
373        }
374        EvalView::NotRun(NotRun::Dependency(x)) => waits(states, "not run: waited for ", x),
375        EvalView::NotRun(NotRun::Budget) => plain("not started · maxExecutions reached"),
376        EvalView::NotRun(NotRun::Stale) => plain("not run · no reusable result"),
377        EvalView::NotRun(NotRun::Unreviewed) => plain("not reviewed"),
378        EvalView::NotRun(NotRun::Absent) => plain("not in this Run"),
379    }
380}
381
382/// Start and end of executed, failed, running and Human evals; an open end runs to now.
383fn clock(view: &EvalView, request: Option<&RequestView>) -> Option<Clock> {
384    let timed = matches!(
385        view,
386        EvalView::Done(Source::Executed)
387            | EvalView::Failed { .. }
388            | EvalView::InProgress(Activity::Running | Activity::Human(_))
389    );
390    let request = &request.filter(|_| timed)?.request;
391    let start = request.started_at.unwrap_or(request.created_at).time();
392    let end = request.completed_at().map(crate::types::Timestamp::time);
393    Some(Clock { start, end })
394}
395
396fn compact(view: &EvalView, right: &str) -> String {
397    let x = match view {
398        EvalView::WaitingOn(waits) | EvalView::NotRun(NotRun::Dependency(waits)) => {
399            &waits.artifacts
400        }
401        EvalView::BlockedBy(x) => x,
402        _ => return right.to_owned(),
403    };
404    match x.as_slice() {
405        [one] => format!("←{one}"),
406        many => format!("←{}", many.len()),
407    }
408}
409
410pub(crate) fn local(eval: &EvalId) -> &str {
411    eval.rsplit_once('/')
412        .map_or(eval.as_str(), |(_, local)| local)
413}
414
415fn eval_node<'a>(states: &States<'a>, eval: &'a EvalId, now: OffsetDateTime) -> Node {
416    let view = states.view(eval);
417    let request = states.request(eval);
418    let (glyph, tone, weight) = style(&view);
419    let clock = clock(&view, request);
420    let right = clock.map_or_else(String::new, |clock| clock.elapsed(now));
421    Node {
422        clock,
423        id: super::NodeId::eval(eval.clone()),
424        glyph,
425        tone,
426        weight,
427        name: local(eval).to_owned(),
428        marks: String::new(),
429        text: text(states, &view, request),
430        compact: compact(&view, &right),
431        right,
432        tally: None,
433        changed: false,
434        upstream: states.upstream_states(eval),
435        held: states.held_for_run(eval),
436        parts: Vec::new(),
437        children: Vec::new(),
438        kind: Kind::Eval(view),
439    }
440}
441
442/// Up to two eval names, then `+N`.
443fn names(nodes: &[&Node]) -> String {
444    let mut names = nodes
445        .iter()
446        .take(SHOWN)
447        .map(|node| node.name.as_str())
448        .collect::<Vec<_>>()
449        .join(", ");
450    if nodes.len() > SHOWN {
451        names = format!("{names} +{}", nodes.len() - SHOWN);
452    }
453    names
454}
455
456/// One clause for the most urgent class of eval rows, plus in-progress ones after a failure.
457fn summary(states: &States, id: &ArtifactName, children: &[Node]) -> Vec<Segment> {
458    let view = |node: &Node| match &node.kind {
459        Kind::Eval(view) => Some(view.clone()),
460        Kind::Artifact { .. } => None,
461    };
462    let Some(top) = children
463        .iter()
464        .filter_map(view)
465        .map(|view| view.rank())
466        .min()
467    else {
468        return Vec::new();
469    };
470    let class = |rank: Rank| -> Vec<&Node> {
471        children
472            .iter()
473            .filter(|node| view(node).is_some_and(|view| view.rank() == rank))
474            .collect()
475    };
476    let x = |ids: Vec<crate::types::ArtifactName>| tokens(states, &ids, false);
477    let mut segments = match top {
478        Rank::Failed => {
479            let failed = class(Rank::Failed);
480            let errors: Vec<_> = failed
481                .iter()
482                .copied()
483                .filter(|node| node.kind == Kind::Eval(EvalView::Failed { verdict: false }))
484                .collect();
485            let (label, nodes) = if errors.is_empty() {
486                ("RED", failed)
487            } else {
488                ("ERROR", errors)
489            };
490            vec![Segment::plain(format!("{label}: {}", names(&nodes)))]
491        }
492        Rank::InProgress => vec![Segment::plain(format!(
493            "in progress: {}",
494            names(&class(Rank::InProgress))
495        ))],
496        Rank::Blocked => {
497            let mut segments = vec![Segment::plain(if states.running {
498                "blocked by "
499            } else {
500                "not run: blocked by "
501            })];
502            segments.extend(x(states.blockers_of(id)));
503            segments
504        }
505        Rank::Waiting => {
506            let mut segments = vec![Segment::plain("waits for ")];
507            segments.extend(x(states.waits_of(id)));
508            segments
509        }
510        Rank::NotRun => {
511            let first = class(Rank::NotRun)[0];
512            match &first.kind {
513                Kind::Eval(EvalView::NotRun(NotRun::Dependency(_))) => {
514                    let mut segments = vec![Segment::plain("not run: waited for ")];
515                    segments.extend(x(states.waits_of(id)));
516                    segments
517                }
518                _ => first.text.clone(),
519            }
520        }
521        // Every eval row is done, but graph.rs still holds them on their own gates.
522        Rank::Done => match states.completion(id) {
523            Completion::Waiting { blocked: true } => {
524                let mut segments = vec![Segment::plain("done, but blocked by ")];
525                segments.extend(x(states.blockers_of(id)));
526                segments
527            }
528            Completion::Waiting { blocked: false } => {
529                let mut segments = vec![Segment::plain("done, but waits for ")];
530                segments.extend(x(states.waits_of(id)));
531                segments
532            }
533            _ => Vec::new(),
534        },
535    };
536    if top == Rank::Failed {
537        let busy = class(Rank::InProgress);
538        if !busy.is_empty() {
539            segments.push(Segment::plain(format!(" · in progress: {}", names(&busy))));
540        }
541    }
542    segments
543}
544
545fn artifact_node<'a>(
546    states: &States<'a>,
547    saved: &Saved<'a>,
548    id: &ArtifactName,
549    now: OffsetDateTime,
550) -> Node {
551    let artifact = saved.artifact(id);
552    let basis = artifact.and_then(|artifact| artifact.basis.value()) == Some(&true);
553    let children: Vec<_> = states
554        .evals(id)
555        .iter()
556        .map(|&eval| eval_node(states, eval, now))
557        .collect();
558    let mut marks = String::new();
559    if states.index.cyclic.contains(id) {
560        let peers = states.index.peers.get(id).map_or(&[][..], Vec::as_slice);
561        marks = match peers {
562            [] => "  ↻".into(),
563            [peer] => format!("  ↻ {peer}"),
564            [peer, rest @ ..] => format!("  ↻ {peer} +{}", rest.len()),
565        };
566    }
567    if artifact.and_then(|artifact| artifact.kind.value())
568        == Some(&crate::config::ArtifactKind::File)
569    {
570        marks.push_str("  [file]");
571    }
572    let completion = states.completion(id);
573    // GREEN as the graph counts it: a done eval held on its own gates does not pass.
574    let passed = states
575        .evals(id)
576        .iter()
577        .filter(|eval| states.effective(eval) == crate::graph::EvalStatus::Green)
578        .count();
579    let tally = (!children.is_empty()).then_some(Tally {
580        passed,
581        of: children.len(),
582    });
583    let right = tally.map_or_else(String::new, |tally| tally.to_string());
584    let parts = states.index.parts.get(id).map_or(&[][..], Vec::as_slice);
585    // Parts that keep the Artifact from passing, most urgent first.
586    let mut pending: Vec<_> = parts
587        .iter()
588        .filter(|part| states.completion(part) != Completion::Complete)
589        .collect();
590    pending.sort_by_key(|part| states.completion(part).rank());
591    let listed = |label: &str| {
592        let shown: Vec<_> = pending.iter().take(SHOWN).map(|id| id.as_str()).collect();
593        let more = pending.len().saturating_sub(SHOWN);
594        let more = if more > 0 {
595            format!(" +{more}")
596        } else {
597            String::new()
598        };
599        Segment::plain(format!("{label}{}{more}", shown.join(", ")))
600    };
601    let (glyph, tone, weight, mut text) = if basis && pending.is_empty() {
602        ("◇", Tone::Muted, Weight::Dim, vec![Segment::plain("basis")])
603    } else if children.is_empty() && !parts.is_empty() {
604        // Without evals of its own, it is what its parts are.
605        let (glyph, tone, _) = self::completion(completion);
606        let text = if pending.is_empty() {
607            Segment::plain(format!("made of {}", parts.len()))
608        } else {
609            listed("pending: ")
610        };
611        (glyph, tone, Weight::Normal, vec![text])
612    } else if children.is_empty() {
613        (
614            "○",
615            Tone::Muted,
616            Weight::Dim,
617            vec![Segment::plain("no evals")],
618        )
619    } else {
620        // The row takes the glyph of its most urgent eval row; ERROR before RED.
621        let top = children
622            .iter()
623            .min_by_key(|node| match &node.kind {
624                Kind::Eval(EvalView::Failed { verdict: false }) => (Rank::Failed, false),
625                Kind::Eval(view) => (view.rank(), true),
626                Kind::Artifact { .. } => (Rank::Done, true),
627            })
628            .expect("children");
629        let (glyph, tone, weight) = match (&top.kind, completion) {
630            (_, Completion::InProgress(busy)) => {
631                let (glyph, tone, _) = self::completion(Completion::InProgress(busy));
632                (glyph, tone, Weight::Bold)
633            }
634            // Every eval row passes, yet a part fails.
635            (Kind::Eval(EvalView::Done(_)), Completion::Failed { verdict }) => {
636                let (glyph, tone, _) = self::completion(Completion::Failed { verdict });
637                (glyph, tone, Weight::Bold)
638            }
639            // Every eval row is done, yet the graph holds them on their own gates.
640            (Kind::Eval(EvalView::Done(_)), Completion::Waiting { blocked }) => {
641                let (glyph, tone, _) = self::completion(Completion::Waiting { blocked });
642                let weight = if blocked { Weight::Normal } else { Weight::Dim };
643                (glyph, tone, weight)
644            }
645            _ => (top.glyph, top.tone, top.weight),
646        };
647        (glyph, tone, weight, summary(states, id, &children))
648    };
649    if !children.is_empty() && !pending.is_empty() {
650        text.push(listed(if text.is_empty() {
651            "parts: "
652        } else {
653            " · parts: "
654        }));
655    }
656    Node {
657        id: super::NodeId::artifact(id.clone()),
658        clock: None,
659        kind: Kind::Artifact { completion, basis },
660        glyph,
661        tone,
662        weight,
663        name: id.to_string(),
664        marks,
665        text,
666        compact: right.clone(),
667        right,
668        tally,
669        changed: false,
670        upstream: Vec::new(),
671        held: false,
672        parts: parts.iter().map(|&part| part.clone()).collect(),
673        children,
674    }
675}
676
677/// Every saved or requested Artifact appears exactly once, upstream first where the graph
678/// allows: dependency-first component order, cycle peers by name.
679pub fn tree(run: &RunView, requests: &[RequestView], now: OffsetDateTime) -> Vec<Node> {
680    let mut nodes = build(run, requests, now);
681    // A finished Run: derive the same snapshot once more as of its end and mark every row
682    // whose derived state differs.
683    if let Some(ended) = at_end(run, requests) {
684        mark(&mut nodes, &build(run, &ended, now));
685    }
686    nodes
687}
688
689fn build(run: &RunView, requests: &[RequestView], now: OffsetDateTime) -> Vec<Node> {
690    let saved = Saved { run, requests };
691    let states = States::new(&saved);
692    states
693        .index
694        .order
695        .iter()
696        .map(|id| artifact_node(&states, &saved, id, now))
697        .collect()
698}
699
700/// The requests as they stood when the Run ended, or `None` when nothing changed since
701/// (or the Run has not ended). A request that completed later goes back to waiting for its
702/// Human (or running), and a later claim is dropped; the Run's recorded evidence is fixed.
703fn at_end(run: &RunView, requests: &[RequestView]) -> Option<Vec<RequestView>> {
704    let end = run.run.completed_at()?;
705    let late = |time: Option<crate::types::Timestamp>| time.is_some_and(|time| time > end);
706    let changed = requests.iter().any(|view| {
707        late(view.request.completed_at()) || late(view.claim.as_ref().map(|claim| claim.claimed_at))
708    });
709    if !changed {
710        return None;
711    }
712    // The views share their records: only a request that completed later is copied to change.
713    let mut ended = requests.to_vec();
714    for view in &mut ended {
715        if late(view.claim.as_ref().map(|claim| claim.claimed_at)) {
716            view.claim = None;
717        }
718        if late(view.request.completed_at()) {
719            let request = std::sync::Arc::make_mut(&mut view.request);
720            request.state = if request.profile.kind() == crate::config::ProfileKind::Human {
721                crate::store::RequestState::Deferred
722            } else {
723                crate::store::RequestState::Running
724            };
725        }
726    }
727    Some(ended)
728}
729
730/// The state a row derives, without the root-cause note (an explanation, not a state).
731fn state(node: &Node) -> (Kind, &'static str, String) {
732    let kind = match &node.kind {
733        Kind::Eval(EvalView::WaitingOn(waits)) => Kind::Eval(EvalView::WaitingOn(Waits {
734            artifacts: waits.artifacts.clone(),
735            root: None,
736        })),
737        Kind::Eval(EvalView::NotRun(NotRun::Dependency(waits))) => {
738            Kind::Eval(EvalView::NotRun(NotRun::Dependency(Waits {
739                artifacts: waits.artifacts.clone(),
740                root: None,
741            })))
742        }
743        kind => kind.clone(),
744    };
745    // Artifact rows compare their whole summary; eval rows their state and glyph.
746    let summary = match node.kind {
747        Kind::Artifact { .. } => format!("{} {}", node.status(), node.right),
748        Kind::Eval(_) => String::new(),
749    };
750    (kind, node.glyph, summary)
751}
752
753/// Mark the rows whose derived state differs from the Run-end derivation.
754fn mark(nodes: &mut [Node], ended: &[Node]) {
755    let before: std::collections::HashMap<_, _> = ended
756        .iter()
757        .flat_map(|node| std::iter::once(node).chain(&node.children))
758        .map(|node| (&node.id, state(node)))
759        .collect();
760    for node in nodes {
761        node.changed = before.get(&node.id) != Some(&state(node));
762        for child in &mut node.children {
763            child.changed = before.get(&child.id) != Some(&state(child));
764        }
765    }
766}
767
768/// Every eval's direct dependency Artifacts, from the Run's saved definitions.
769pub fn upstream_index(run: &RunView, requests: &[RequestView]) -> Vec<(EvalId, Vec<ArtifactName>)> {
770    let saved = Saved { run, requests };
771    let index = super::states::Index::new(&saved);
772    index
773        .upstream
774        .iter()
775        .map(|(eval, artifacts)| {
776            (
777                (*eval).clone(),
778                artifacts.iter().map(|id| (*id).clone()).collect(),
779            )
780        })
781        .collect()
782}
783
784/// The Artifact detail's current status, rolled up like its tree row.
785pub(super) fn artifact_status(saved: &Saved, id: &ArtifactName, now: OffsetDateTime) -> String {
786    let states = States::new(saved);
787    let node = artifact_node(&states, saved, id, now);
788    let (_, _, word) = completion(states.completion(id));
789    let status = node.status();
790    let status = if status.is_empty() {
791        word.to_owned()
792    } else {
793        status
794    };
795    if node.right.is_empty() {
796        format!("{} {status}", node.glyph)
797    } else {
798        format!("{} {status} · {} Evals GREEN", node.glyph, node.right)
799    }
800}
801
802/// The eval detail's `Waits for`: every dependency Artifact in the tree's order, with its
803/// completion and why the eval depends on it, then its evals that are not done yet.
804pub(super) fn waits_for(saved: &Saved, eval: &EvalId, now: OffsetDateTime) -> String {
805    let states = States::new(saved);
806    format_waits(
807        saved,
808        &states,
809        eval,
810        now,
811        &mut std::collections::HashSet::new(),
812    )
813}
814
815/// An Artifact combines its evals' input groups by identity, not by rendered text:
816/// different inputs may each have a pending eval named `check`.
817pub(super) fn artifact_waits(
818    saved: &Saved,
819    artifact: &ArtifactName,
820    now: OffsetDateTime,
821) -> String {
822    let states = States::new(saved);
823    let mut seen = std::collections::HashSet::new();
824    let blocks = states
825        .evals(artifact)
826        .iter()
827        .map(|eval| format_waits(saved, &states, eval, now, &mut seen))
828        .filter(|block| !block.is_empty());
829    super::join(blocks, "\n")
830}
831
832fn format_waits(
833    saved: &Saved,
834    states: &States<'_>,
835    eval: &EvalId,
836    now: OffsetDateTime,
837    seen: &mut std::collections::HashSet<ArtifactName>,
838) -> String {
839    let Some((&target, _)) = states
840        .index
841        .evals
842        .iter()
843        .find(|(_, evals)| evals.contains(&eval))
844    else {
845        return String::new();
846    };
847    let peers = |id: &ArtifactName| states.index.peers.get(id).cloned().unwrap_or_default();
848    let mut own = peers(target);
849    own.push(target);
850    let mut lines = Vec::new();
851    for upstream in states.upstream_states(eval) {
852        if !seen.insert(upstream.artifact.clone()) {
853            continue;
854        }
855        let (glyph, _, word) = completion(upstream.completion);
856        let id = &upstream.artifact;
857        let mut origins: Vec<String> = saved
858            .relations(id, false)
859            .into_iter()
860            .filter(|relation| own.contains(&&relation.target))
861            .map(|relation| {
862                let kind = super::relation_kind(relation);
863                if &relation.target == target {
864                    kind
865                } else {
866                    format!("{kind} → {}", relation.target)
867                }
868            })
869            .collect();
870        if origins.is_empty() && !peers(id).is_empty() {
871            origins.push(format!("↻ peer of {}", super::join(peers(id), ", ")));
872        }
873        let origins = if origins.is_empty() {
874            String::new()
875        } else {
876            format!(" · {}", origins.join(", "))
877        };
878        lines.push(format!("↑ {id} {glyph} {word}{origins}"));
879        if upstream.completion == Completion::Complete {
880            continue;
881        }
882        for &pending in states.evals(id) {
883            let node = eval_node(states, pending, now);
884            if !matches!(node.kind, Kind::Eval(EvalView::Done(_))) {
885                lines.push(format!("  {} {}  {}", node.glyph, node.name, node.status()));
886            }
887        }
888    }
889    lines.join("\n")
890}