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    let result = result.map(crate::store::ExecutionResult::to_json);
266    let fields = result
267        .as_ref()
268        .and_then(Value::as_object)
269        .into_iter()
270        .flatten();
271    let fields = fields.filter(|(key, _)| {
272        !matches!(
273            key.as_str(),
274            "verdict" | "stdout" | "stderr" | "truncated" | "durationMs"
275        )
276    });
277    let parts: Vec<_> = fields
278        .take(SHOWN)
279        .map(|(key, value)| match value {
280            Value::Array(items) => format!("{key} {}", items.len()),
281            Value::Object(fields) => format!("{key} {{{}}}", fields.len()),
282            Value::String(text) => {
283                let text = text.lines().next().unwrap_or_default();
284                let mut short: String = text.chars().take(SHOWN_TEXT).collect();
285                if short.len() < text.len() {
286                    short.push('…');
287                }
288                format!("{key} {short}")
289            }
290            value => format!("{key} {value}"),
291        })
292        .collect();
293    parts.join(", ")
294}
295
296fn short_profile(profile: &crate::config::StoredProfile) -> String {
297    use crate::config::StoredProfile;
298    match profile {
299        StoredProfile::Agent { backend, model, .. } => format!(
300            "agent {} {model}",
301            serde_json::to_value(backend)
302                .ok()
303                .and_then(|value| value.as_str().map(str::to_owned))
304                .unwrap_or_default()
305        ),
306        StoredProfile::Runtime { command, .. } => format!("runtime {command}"),
307        StoredProfile::Human {} => "human".into(),
308    }
309}
310
311fn text(states: &States, view: &EvalView, request: Option<&RequestView>) -> Vec<Segment> {
312    let plain = |text: &str| vec![Segment::plain(text)];
313    match view {
314        EvalView::Done(Source::Provisional) => plain("PROVISIONAL · sign-offs remain"),
315        EvalView::Done(Source::Executed) => plain("GREEN"),
316        EvalView::Done(Source::Reused) => plain("GREEN · reused"),
317        EvalView::Done(Source::Saved) => plain("GREEN · saved result, not in this Run"),
318        EvalView::Failed { verdict: true } => {
319            let findings = findings(request.and_then(|view| view.request.result()));
320            if request.is_none() {
321                plain("RED · saved result, not in this Run")
322            } else if findings.is_empty() {
323                plain("RED")
324            } else {
325                vec![Segment::plain(format!("RED · {findings}"))]
326            }
327        }
328        EvalView::Failed { verdict: false } => match request.and_then(super::error) {
329            Some(error) => vec![Segment::plain(format!(
330                "ERROR · {}",
331                error.lines().next().unwrap_or_default()
332            ))],
333            None if request.is_none() => plain("ERROR · saved result, not in this Run"),
334            None => plain("ERROR"),
335        },
336        EvalView::InProgress(Activity::Running) => vec![Segment::plain(format!(
337            "running · {}",
338            request.map_or_else(String::new, |view| short_profile(&view.request.profile))
339        ))],
340        EvalView::InProgress(Activity::Human(None)) => plain("Human sign-off · unclaimed"),
341        EvalView::InProgress(Activity::Human(Some(reviewer))) => vec![Segment::plain(format!(
342            "Human sign-off · claimed by {reviewer}"
343        ))],
344        EvalView::InProgress(Activity::Queued(Queue::Ready)) => plain("queued"),
345        EvalView::InProgress(Activity::Queued(Queue::Jobs)) => plain("queued · --jobs slots full"),
346        EvalView::InProgress(Activity::Queued(Queue::Slot(backend))) => {
347            vec![Segment::plain(format!("queued · {backend} slots full"))]
348        }
349        EvalView::InProgress(Activity::Queued(Queue::Joined)) => {
350            plain("queued · joins the running review")
351        }
352        EvalView::WaitingOn(x) => waits(states, "waits for ", x),
353        EvalView::BlockedBy(x) => {
354            let mut segments = vec![Segment::plain(if states.running {
355                "blocked by "
356            } else {
357                "not run: blocked by "
358            })];
359            segments.extend(tokens(states, x, true));
360            segments
361        }
362        EvalView::NotRun(NotRun::Dependency(x)) => waits(states, "not run: waited for ", x),
363        EvalView::NotRun(NotRun::Budget) => plain("not started · maxExecutions reached"),
364        EvalView::NotRun(NotRun::Stale) => plain("not run · no reusable result"),
365        EvalView::NotRun(NotRun::Unreviewed) => plain("not reviewed"),
366        EvalView::NotRun(NotRun::Absent) => plain("not in this Run"),
367    }
368}
369
370/// Start and end of executed, failed, running and Human evals; an open end runs to now.
371fn clock(view: &EvalView, request: Option<&RequestView>) -> Option<Clock> {
372    let timed = matches!(
373        view,
374        EvalView::Done(Source::Executed)
375            | EvalView::Failed { .. }
376            | EvalView::InProgress(Activity::Running | Activity::Human(_))
377    );
378    let request = &request.filter(|_| timed)?.request;
379    let start = request.started_at.unwrap_or(request.created_at).time();
380    let end = request.completed_at().map(crate::types::Timestamp::time);
381    Some(Clock { start, end })
382}
383
384fn compact(view: &EvalView, right: &str) -> String {
385    let x = match view {
386        EvalView::WaitingOn(waits) | EvalView::NotRun(NotRun::Dependency(waits)) => {
387            &waits.artifacts
388        }
389        EvalView::BlockedBy(x) => x,
390        _ => return right.to_owned(),
391    };
392    match x.as_slice() {
393        [one] => format!("←{one}"),
394        many => format!("←{}", many.len()),
395    }
396}
397
398pub(crate) fn local(eval: &EvalId) -> &str {
399    eval.rsplit_once('/')
400        .map_or(eval.as_str(), |(_, local)| local)
401}
402
403fn eval_node<'a>(states: &States<'a>, eval: &'a EvalId, now: OffsetDateTime) -> Node {
404    let view = states.view(eval);
405    let request = states.request(eval);
406    let (glyph, tone, weight) = style(&view);
407    let clock = clock(&view, request);
408    let right = clock.map_or_else(String::new, |clock| clock.elapsed(now));
409    Node {
410        clock,
411        id: super::NodeId::eval(eval.clone()),
412        glyph,
413        tone,
414        weight,
415        name: local(eval).to_owned(),
416        marks: String::new(),
417        text: text(states, &view, request),
418        compact: compact(&view, &right),
419        right,
420        tally: None,
421        changed: false,
422        upstream: states.upstream_states(eval),
423        held: states.held_for_run(eval),
424        parts: Vec::new(),
425        children: Vec::new(),
426        kind: Kind::Eval(view),
427    }
428}
429
430/// Up to two eval names, then `+N`.
431fn names(nodes: &[&Node]) -> String {
432    let mut names = nodes
433        .iter()
434        .take(SHOWN)
435        .map(|node| node.name.as_str())
436        .collect::<Vec<_>>()
437        .join(", ");
438    if nodes.len() > SHOWN {
439        names = format!("{names} +{}", nodes.len() - SHOWN);
440    }
441    names
442}
443
444/// One clause for the most urgent class of eval rows, plus in-progress ones after a failure.
445fn summary(states: &States, id: &ArtifactName, children: &[Node]) -> Vec<Segment> {
446    let view = |node: &Node| match &node.kind {
447        Kind::Eval(view) => Some(view.clone()),
448        Kind::Artifact { .. } => None,
449    };
450    let Some(top) = children
451        .iter()
452        .filter_map(view)
453        .map(|view| view.rank())
454        .min()
455    else {
456        return Vec::new();
457    };
458    let class = |rank: Rank| -> Vec<&Node> {
459        children
460            .iter()
461            .filter(|node| view(node).is_some_and(|view| view.rank() == rank))
462            .collect()
463    };
464    let x = |ids: Vec<crate::types::ArtifactName>| tokens(states, &ids, false);
465    let mut segments = match top {
466        Rank::Failed => {
467            let failed = class(Rank::Failed);
468            let errors: Vec<_> = failed
469                .iter()
470                .copied()
471                .filter(|node| node.kind == Kind::Eval(EvalView::Failed { verdict: false }))
472                .collect();
473            let (label, nodes) = if errors.is_empty() {
474                ("RED", failed)
475            } else {
476                ("ERROR", errors)
477            };
478            vec![Segment::plain(format!("{label}: {}", names(&nodes)))]
479        }
480        Rank::InProgress => vec![Segment::plain(format!(
481            "in progress: {}",
482            names(&class(Rank::InProgress))
483        ))],
484        Rank::Blocked => {
485            let mut segments = vec![Segment::plain(if states.running {
486                "blocked by "
487            } else {
488                "not run: blocked by "
489            })];
490            segments.extend(x(states.blockers_of(id)));
491            segments
492        }
493        Rank::Waiting => {
494            let mut segments = vec![Segment::plain("waits for ")];
495            segments.extend(x(states.waits_of(id)));
496            segments
497        }
498        Rank::NotRun => {
499            let first = class(Rank::NotRun)[0];
500            match &first.kind {
501                Kind::Eval(EvalView::NotRun(NotRun::Dependency(_))) => {
502                    let mut segments = vec![Segment::plain("not run: waited for ")];
503                    segments.extend(x(states.waits_of(id)));
504                    segments
505                }
506                _ => first.text.clone(),
507            }
508        }
509        // Every eval row is done, but graph.rs still holds them on their own gates.
510        Rank::Done => match states.completion(id) {
511            Completion::Waiting { blocked: true } => {
512                let mut segments = vec![Segment::plain("done, but blocked by ")];
513                segments.extend(x(states.blockers_of(id)));
514                segments
515            }
516            Completion::Waiting { blocked: false } => {
517                let mut segments = vec![Segment::plain("done, but waits for ")];
518                segments.extend(x(states.waits_of(id)));
519                segments
520            }
521            _ => Vec::new(),
522        },
523    };
524    if top == Rank::Failed {
525        let busy = class(Rank::InProgress);
526        if !busy.is_empty() {
527            segments.push(Segment::plain(format!(" · in progress: {}", names(&busy))));
528        }
529    }
530    segments
531}
532
533fn artifact_node<'a>(
534    states: &States<'a>,
535    saved: &Saved<'a>,
536    id: &ArtifactName,
537    now: OffsetDateTime,
538) -> Node {
539    let artifact = saved.artifact(id);
540    let basis = artifact.and_then(|artifact| artifact.basis.value()) == Some(&true);
541    let children: Vec<_> = states
542        .evals(id)
543        .iter()
544        .map(|&eval| eval_node(states, eval, now))
545        .collect();
546    let mut marks = String::new();
547    if states.index.cyclic.contains(id) {
548        let peers = states.index.peers.get(id).map_or(&[][..], Vec::as_slice);
549        marks = match peers {
550            [] => "  ↻".into(),
551            [peer] => format!("  ↻ {peer}"),
552            [peer, rest @ ..] => format!("  ↻ {peer} +{}", rest.len()),
553        };
554    }
555    if artifact.and_then(|artifact| artifact.kind.value())
556        == Some(&crate::config::ArtifactKind::File)
557    {
558        marks.push_str("  [file]");
559    }
560    let completion = states.completion(id);
561    // GREEN as the graph counts it: a done eval held on its own gates does not pass.
562    let passed = states
563        .evals(id)
564        .iter()
565        .filter(|eval| states.effective(eval) == crate::graph::EvalStatus::Green)
566        .count();
567    let tally = (!children.is_empty()).then_some(Tally {
568        passed,
569        of: children.len(),
570    });
571    let right = tally.map_or_else(String::new, |tally| tally.to_string());
572    let parts = states.index.parts.get(id).map_or(&[][..], Vec::as_slice);
573    // Parts that keep the Artifact from passing, most urgent first.
574    let mut pending: Vec<_> = parts
575        .iter()
576        .filter(|part| states.completion(part) != Completion::Complete)
577        .collect();
578    pending.sort_by_key(|part| states.completion(part).rank());
579    let listed = |label: &str| {
580        let shown: Vec<_> = pending.iter().take(SHOWN).map(|id| id.as_str()).collect();
581        let more = pending.len().saturating_sub(SHOWN);
582        let more = if more > 0 {
583            format!(" +{more}")
584        } else {
585            String::new()
586        };
587        Segment::plain(format!("{label}{}{more}", shown.join(", ")))
588    };
589    let (glyph, tone, weight, mut text) = if basis && pending.is_empty() {
590        ("◇", Tone::Muted, Weight::Dim, vec![Segment::plain("basis")])
591    } else if children.is_empty() && !parts.is_empty() {
592        // Without evals of its own, it is what its parts are.
593        let (glyph, tone, _) = self::completion(completion);
594        let text = if pending.is_empty() {
595            Segment::plain(format!("made of {}", parts.len()))
596        } else {
597            listed("pending: ")
598        };
599        (glyph, tone, Weight::Normal, vec![text])
600    } else if children.is_empty() {
601        (
602            "○",
603            Tone::Muted,
604            Weight::Dim,
605            vec![Segment::plain("no evals")],
606        )
607    } else {
608        // The row takes the glyph of its most urgent eval row; ERROR before RED.
609        let top = children
610            .iter()
611            .min_by_key(|node| match &node.kind {
612                Kind::Eval(EvalView::Failed { verdict: false }) => (Rank::Failed, false),
613                Kind::Eval(view) => (view.rank(), true),
614                Kind::Artifact { .. } => (Rank::Done, true),
615            })
616            .expect("children");
617        let (glyph, tone, weight) = match (&top.kind, completion) {
618            (_, Completion::InProgress(busy)) => {
619                let (glyph, tone, _) = self::completion(Completion::InProgress(busy));
620                (glyph, tone, Weight::Bold)
621            }
622            // Every eval row passes, yet a part fails.
623            (Kind::Eval(EvalView::Done(_)), Completion::Failed { verdict }) => {
624                let (glyph, tone, _) = self::completion(Completion::Failed { verdict });
625                (glyph, tone, Weight::Bold)
626            }
627            // Every eval row is done, yet the graph holds them on their own gates.
628            (Kind::Eval(EvalView::Done(_)), Completion::Waiting { blocked }) => {
629                let (glyph, tone, _) = self::completion(Completion::Waiting { blocked });
630                let weight = if blocked { Weight::Normal } else { Weight::Dim };
631                (glyph, tone, weight)
632            }
633            _ => (top.glyph, top.tone, top.weight),
634        };
635        (glyph, tone, weight, summary(states, id, &children))
636    };
637    if !children.is_empty() && !pending.is_empty() {
638        text.push(listed(if text.is_empty() {
639            "parts: "
640        } else {
641            " · parts: "
642        }));
643    }
644    Node {
645        id: super::NodeId::artifact(id.clone()),
646        clock: None,
647        kind: Kind::Artifact { completion, basis },
648        glyph,
649        tone,
650        weight,
651        name: id.to_string(),
652        marks,
653        text,
654        compact: right.clone(),
655        right,
656        tally,
657        changed: false,
658        upstream: Vec::new(),
659        held: false,
660        parts: parts.iter().map(|&part| part.clone()).collect(),
661        children,
662    }
663}
664
665/// Every saved or requested Artifact appears exactly once, upstream first where the graph
666/// allows: dependency-first component order, cycle peers by name.
667pub fn tree(run: &RunView, requests: &[RequestView], now: OffsetDateTime) -> Vec<Node> {
668    let mut nodes = build(run, requests, now);
669    // A finished Run: derive the same snapshot once more as of its end and mark every row
670    // whose derived state differs.
671    if let Some(ended) = at_end(run, requests) {
672        mark(&mut nodes, &build(run, &ended, now));
673    }
674    nodes
675}
676
677fn build(run: &RunView, requests: &[RequestView], now: OffsetDateTime) -> Vec<Node> {
678    let saved = Saved { run, requests };
679    let states = States::new(&saved);
680    states
681        .index
682        .order
683        .iter()
684        .map(|id| artifact_node(&states, &saved, id, now))
685        .collect()
686}
687
688/// The requests as they stood when the Run ended, or `None` when nothing changed since
689/// (or the Run has not ended). A request that completed later goes back to waiting for its
690/// Human (or running), and a later claim is dropped; the Run's recorded evidence is fixed.
691fn at_end(run: &RunView, requests: &[RequestView]) -> Option<Vec<RequestView>> {
692    let end = run.run.completed_at()?;
693    let late = |time: Option<crate::types::Timestamp>| time.is_some_and(|time| time > end);
694    let changed = requests.iter().any(|view| {
695        late(view.request.completed_at()) || late(view.claim.as_ref().map(|claim| claim.claimed_at))
696    });
697    if !changed {
698        return None;
699    }
700    // The views share their records: only a request that completed later is copied to change.
701    let mut ended = requests.to_vec();
702    for view in &mut ended {
703        if late(view.claim.as_ref().map(|claim| claim.claimed_at)) {
704            view.claim = None;
705        }
706        if late(view.request.completed_at()) {
707            let request = std::sync::Arc::make_mut(&mut view.request);
708            request.state = if request.profile.kind() == crate::config::ProfileKind::Human {
709                crate::store::RequestState::Deferred
710            } else {
711                crate::store::RequestState::Running
712            };
713        }
714    }
715    Some(ended)
716}
717
718/// The state a row derives, without the root-cause note (an explanation, not a state).
719fn state(node: &Node) -> (Kind, &'static str, String) {
720    let kind = match &node.kind {
721        Kind::Eval(EvalView::WaitingOn(waits)) => Kind::Eval(EvalView::WaitingOn(Waits {
722            artifacts: waits.artifacts.clone(),
723            root: None,
724        })),
725        Kind::Eval(EvalView::NotRun(NotRun::Dependency(waits))) => {
726            Kind::Eval(EvalView::NotRun(NotRun::Dependency(Waits {
727                artifacts: waits.artifacts.clone(),
728                root: None,
729            })))
730        }
731        kind => kind.clone(),
732    };
733    // Artifact rows compare their whole summary; eval rows their state and glyph.
734    let summary = match node.kind {
735        Kind::Artifact { .. } => format!("{} {}", node.status(), node.right),
736        Kind::Eval(_) => String::new(),
737    };
738    (kind, node.glyph, summary)
739}
740
741/// Mark the rows whose derived state differs from the Run-end derivation.
742fn mark(nodes: &mut [Node], ended: &[Node]) {
743    let mut before = std::collections::HashMap::new();
744    for node in ended {
745        before.insert(&node.id, state(node));
746        for child in &node.children {
747            before.insert(&child.id, state(child));
748        }
749    }
750    for node in nodes {
751        node.changed = before.get(&node.id) != Some(&state(node));
752        for child in &mut node.children {
753            child.changed = before.get(&child.id) != Some(&state(child));
754        }
755    }
756}
757
758/// Every eval's direct dependency Artifacts, from the Run's saved definitions.
759pub fn upstream_index(run: &RunView, requests: &[RequestView]) -> Vec<(EvalId, Vec<ArtifactName>)> {
760    let saved = Saved { run, requests };
761    let index = super::states::Index::new(&saved);
762    index
763        .upstream
764        .iter()
765        .map(|(eval, artifacts)| {
766            (
767                (*eval).clone(),
768                artifacts.iter().map(|id| (*id).clone()).collect(),
769            )
770        })
771        .collect()
772}
773
774/// The Artifact detail's current status, rolled up like its tree row.
775pub(super) fn artifact_status(saved: &Saved, id: &ArtifactName, now: OffsetDateTime) -> String {
776    let states = States::new(saved);
777    let node = artifact_node(&states, saved, id, now);
778    let (_, _, word) = completion(states.completion(id));
779    let status = node.status();
780    let status = if status.is_empty() {
781        word.to_owned()
782    } else {
783        status
784    };
785    if node.right.is_empty() {
786        format!("{} {status}", node.glyph)
787    } else {
788        format!("{} {status} · {} Evals GREEN", node.glyph, node.right)
789    }
790}
791
792/// The eval detail's `Waits for`: every dependency Artifact in the tree's order, with its
793/// completion and why the eval depends on it, then its evals that are not done yet.
794pub(super) fn waits_for(saved: &Saved, eval: &EvalId, now: OffsetDateTime) -> String {
795    let states = States::new(saved);
796    format_waits(
797        saved,
798        &states,
799        eval,
800        now,
801        &mut std::collections::HashSet::new(),
802    )
803}
804
805/// An Artifact combines its evals' input groups by identity, not by rendered text:
806/// different inputs may each have a pending eval named `check`.
807pub(super) fn artifact_waits(
808    saved: &Saved,
809    artifact: &ArtifactName,
810    now: OffsetDateTime,
811) -> String {
812    let states = States::new(saved);
813    let mut seen = std::collections::HashSet::new();
814    let blocks = states
815        .evals(artifact)
816        .iter()
817        .map(|eval| format_waits(saved, &states, eval, now, &mut seen))
818        .filter(|block| !block.is_empty());
819    super::join(blocks, "\n")
820}
821
822fn format_waits(
823    saved: &Saved,
824    states: &States<'_>,
825    eval: &EvalId,
826    now: OffsetDateTime,
827    seen: &mut std::collections::HashSet<ArtifactName>,
828) -> String {
829    let Some((&target, _)) = states
830        .index
831        .evals
832        .iter()
833        .find(|(_, evals)| evals.contains(&eval))
834    else {
835        return String::new();
836    };
837    let peers = |id: &ArtifactName| states.index.peers.get(id).cloned().unwrap_or_default();
838    let mut own = peers(target);
839    own.push(target);
840    let mut lines = Vec::new();
841    for upstream in states.upstream_states(eval) {
842        if !seen.insert(upstream.artifact.clone()) {
843            continue;
844        }
845        let (glyph, _, word) = completion(upstream.completion);
846        let id = &upstream.artifact;
847        let mut origins: Vec<String> = saved
848            .relations(id, false)
849            .into_iter()
850            .filter(|relation| own.contains(&&relation.target))
851            .map(|relation| {
852                let kind = super::relation_kind(relation);
853                if &relation.target == target {
854                    kind
855                } else {
856                    format!("{kind} → {}", relation.target)
857                }
858            })
859            .collect();
860        if origins.is_empty() && !peers(id).is_empty() {
861            origins.push(format!("↻ peer of {}", super::join(peers(id), ", ")));
862        }
863        let origins = if origins.is_empty() {
864            String::new()
865        } else {
866            format!(" · {}", origins.join(", "))
867        };
868        lines.push(format!("↑ {id} {glyph} {word}{origins}"));
869        if upstream.completion == Completion::Complete {
870            continue;
871        }
872        for &pending in states.evals(id) {
873            let node = eval_node(states, pending, now);
874            if !matches!(node.kind, Kind::Eval(EvalView::Done(_))) {
875                lines.push(format!("  {} {}  {}", node.glyph, node.name, node.status()));
876            }
877        }
878    }
879    lines.join("\n")
880}