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