artifactize-core 0.13.0

The library behind artifactize: Artifacts, evals, reviews, the monitor and review models, and the shared operations every interface calls.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
//! The Artifacts and evals tree: one row per eval, Artifact rows rolled up from them.
use crate::types::{ArtifactName, EvalId};
use serde_json::Value;
use time::OffsetDateTime;

use super::{
    Saved,
    states::{
        Activity, Busy, Completion, EvalView, NotRun, Queue, Rank, Source, States, Upstream, Waits,
    },
};
use crate::store::{RequestView, RunView};

/// Colour classes; the renderer maps them to terminal colours.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Tone {
    Green,
    Red,
    Error,
    Running,
    Human,
    Queued,
    Blocked,
    Muted,
}

/// In-progress rows are bold; rows that wait or did not run are dimmed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Weight {
    Bold,
    Normal,
    Dim,
}

/// Status text; a toned segment (an X token) keeps its colour inside a dimmed row.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Segment {
    pub text: String,
    pub tone: Option<Tone>,
}

impl Segment {
    fn plain(text: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            tone: None,
        }
    }
    fn toned(text: impl Into<String>, tone: Tone) -> Self {
        Self {
            text: text.into(),
            tone: Some(tone),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Kind {
    /// An Artifact rolled up from its eval rows; basis Artifacts are complete.
    Artifact {
        completion: Completion,
        basis: bool,
    },
    Eval(EvalView),
}

#[derive(Debug, Clone)]
pub struct Node {
    /// Stable tree identifier: `a:<artifact>` or `e:<eval>`.
    pub id: super::NodeId,
    pub kind: Kind,
    pub glyph: &'static str,
    pub tone: Tone,
    pub weight: Weight,
    pub name: String,
    /// Dim markers after the name: `↻ peer`, `[file]`.
    pub marks: String,
    pub text: Vec<Segment>,
    /// Right column: elapsed time for evals, `passed/total` for Artifacts.
    pub right: String,
    /// Right column of the compact tree: elapsed time, `←X`/`←N`, or `passed/total`.
    pub compact: String,
    /// The state changed after the Run ended (rendered as a dim `*`).
    pub changed: bool,
    /// Eval rows: every dependency Artifact, unmet ones first in X order.
    pub upstream: Vec<Upstream>,
    /// A waiting Eval cannot proceed in this Run because an actual external gate failed.
    pub(crate) held: bool,
    /// Timed eval rows, so a cached tree can redraw its elapsed times.
    pub clock: Option<Clock>,
    pub children: Vec<Node>,
}

/// When a timed eval started and, once settled, ended.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Clock {
    pub start: OffsetDateTime,
    pub end: Option<OffsetDateTime>,
}

impl Clock {
    pub fn elapsed(self, now: OffsetDateTime) -> String {
        super::duration(self.end.unwrap_or(now) - self.start)
    }
}

impl Node {
    /// The right column (or the compact one) as of `now`.
    pub fn right_at(&self, now: OffsetDateTime, compact: bool) -> String {
        match self.clock {
            Some(clock) => clock.elapsed(now),
            None if compact => self.compact.clone(),
            None => self.right.clone(),
        }
    }

    /// The status text without styling.
    pub fn status(&self) -> String {
        self.text
            .iter()
            .map(|segment| segment.text.as_str())
            .collect()
    }

    /// The whole row as plain text, for tests and logs.
    pub fn line(&self) -> String {
        let mut line = format!("{} {}{}", self.glyph, self.name, self.marks);
        for part in [self.status(), self.right.clone()] {
            if !part.is_empty() {
                line = format!("{line}  {part}");
            }
        }
        if self.changed {
            line.push_str(" *");
        }
        line
    }

    /// An Artifact whose evals are all done; folded by default.
    pub fn done(&self) -> bool {
        matches!(
            self.kind,
            Kind::Artifact {
                completion: Completion::Complete,
                ..
            }
        ) && !self.children.is_empty()
    }

    /// An ERROR, RED or waiting Human eval row: what `!` (next attention) visits.
    pub fn urgent(&self) -> bool {
        matches!(
            self.kind,
            Kind::Eval(EvalView::Failed { .. } | EvalView::InProgress(Activity::Human(_)))
        )
    }

    /// An eval row that is in progress or failed: where the cursor starts.
    pub fn attention(&self) -> bool {
        matches!(
            self.kind,
            Kind::Eval(EvalView::InProgress(_) | EvalView::Failed { .. })
        )
    }
}

/// Glyph, colour and word of an Artifact's completion where another row names it.
pub fn completion(completion: Completion) -> (&'static str, Tone, &'static str) {
    match completion {
        Completion::Complete => ("✓", Tone::Green, "complete"),
        Completion::InProgress(Busy::Running) => ("◐", Tone::Running, "in progress"),
        Completion::InProgress(Busy::Human) => ("?", Tone::Human, "in progress"),
        Completion::InProgress(Busy::Queued) => ("·", Tone::Queued, "in progress"),
        Completion::Waiting { blocked: false } => ("…", Tone::Muted, "waiting"),
        Completion::Waiting { blocked: true } => ("⊘", Tone::Blocked, "blocked"),
        Completion::Failed { verdict: true } => ("✗", Tone::Red, "failed"),
        Completion::Failed { verdict: false } => ("!", Tone::Error, "failed"),
    }
}

/// Glyph, colour and weight of one eval row.
fn style(view: &EvalView) -> (&'static str, Tone, Weight) {
    match view {
        EvalView::Done(Source::Provisional) => ("○", Tone::Muted, Weight::Normal),
        EvalView::Done(_) => ("✓", Tone::Green, Weight::Normal),
        EvalView::Failed { verdict: true } => ("✗", Tone::Red, Weight::Normal),
        EvalView::Failed { verdict: false } => ("!", Tone::Error, Weight::Normal),
        EvalView::InProgress(Activity::Running) => ("◐", Tone::Running, Weight::Bold),
        EvalView::InProgress(Activity::Human(_)) => ("?", Tone::Human, Weight::Bold),
        EvalView::InProgress(Activity::Queued(_)) => ("·", Tone::Queued, Weight::Normal),
        EvalView::WaitingOn(_) => ("…", Tone::Muted, Weight::Dim),
        EvalView::BlockedBy(_) => ("⊘", Tone::Blocked, Weight::Normal),
        EvalView::NotRun(NotRun::Budget) => ("$", Tone::Blocked, Weight::Normal),
        EvalView::NotRun(NotRun::Absent) => ("-", Tone::Muted, Weight::Dim),
        EvalView::NotRun(_) => ("○", Tone::Muted, Weight::Dim),
    }
}

/// Shown X per row; the rest become `+N`.
const SHOWN: usize = 2;
/// A shown text field keeps this many characters of its first line, enough for a short value
/// or the start of a sentence while two fields still fit on one row.
const SHOWN_TEXT: usize = 24;

/// `cli ◐ in progress`, or `a ◐, b ? +1`; an ERROR-failed X asks for a retry.
fn tokens(states: &States, x: &[crate::types::ArtifactName], glyphs: bool) -> Vec<Segment> {
    let mut segments = Vec::new();
    for (index, id) in x.iter().take(SHOWN).enumerate() {
        if index > 0 {
            segments.push(Segment::plain(", "));
        }
        let (glyph, tone, word) = completion(states.completion(id));
        let text = match (glyphs, x.len()) {
            (false, _) => id.to_string(),
            (true, 1) => format!("{id} {glyph} {word}"),
            (true, _) => format!("{id} {glyph}"),
        };
        segments.push(Segment::toned(text, tone));
    }
    if x.len() > SHOWN {
        segments.push(Segment::plain(format!(" +{}", x.len() - SHOWN)));
    }
    if glyphs
        && let Some(failed) = x
            .iter()
            .find(|id| states.completion(id) == Completion::Failed { verdict: false })
    {
        segments.push(Segment::plain(format!(" (retry {failed} first)")));
    }
    segments
}

fn waits(states: &States, prefix: &str, waits: &Waits) -> Vec<Segment> {
    let mut segments = vec![Segment::plain(prefix)];
    segments.extend(tokens(states, &waits.artifacts, true));
    if let Some((via, root)) = &waits.root {
        segments.push(Segment::plain(format!(" ({via} waits for ")));
        let (_, tone, _) = completion(states.completion(root));
        segments.push(Segment::toned(root.clone(), tone));
        segments.push(Segment::plain(")"));
    }
    segments
}

/// The top-level Result keys behind a RED verdict, such as `violations 3`.
fn findings(result: Option<&crate::store::ExecutionResult>) -> String {
    let result = result.map(crate::store::ExecutionResult::to_json);
    let fields = result
        .as_ref()
        .and_then(Value::as_object)
        .into_iter()
        .flatten();
    let fields = fields.filter(|(key, _)| {
        !matches!(
            key.as_str(),
            "verdict" | "stdout" | "stderr" | "truncated" | "durationMs"
        )
    });
    let parts: Vec<_> = fields
        .take(SHOWN)
        .map(|(key, value)| match value {
            Value::Array(items) => format!("{key} {}", items.len()),
            Value::Object(fields) => format!("{key} {{{}}}", fields.len()),
            Value::String(text) => {
                let text = text.lines().next().unwrap_or_default();
                let mut short: String = text.chars().take(SHOWN_TEXT).collect();
                if short.len() < text.len() {
                    short.push('…');
                }
                format!("{key} {short}")
            }
            value => format!("{key} {value}"),
        })
        .collect();
    parts.join(", ")
}

fn short_profile(profile: &crate::config::StoredProfile) -> String {
    use crate::config::StoredProfile;
    match profile {
        StoredProfile::Agent { backend, model, .. } => format!(
            "agent {} {model}",
            serde_json::to_value(backend)
                .ok()
                .and_then(|value| value.as_str().map(str::to_owned))
                .unwrap_or_default()
        ),
        StoredProfile::Runtime { command, .. } => format!("runtime {command}"),
        StoredProfile::Human {} => "human".into(),
    }
}

fn text(states: &States, view: &EvalView, request: Option<&RequestView>) -> Vec<Segment> {
    let plain = |text: &str| vec![Segment::plain(text)];
    match view {
        EvalView::Done(Source::Provisional) => plain("PROVISIONAL · sign-offs remain"),
        EvalView::Done(Source::Executed) => plain("GREEN"),
        EvalView::Done(Source::Reused) => plain("GREEN · reused"),
        EvalView::Done(Source::Saved) => plain("GREEN · saved result, not in this Run"),
        EvalView::Failed { verdict: true } => {
            let findings = findings(request.and_then(|view| view.request.result()));
            if request.is_none() {
                plain("RED · saved result, not in this Run")
            } else if findings.is_empty() {
                plain("RED")
            } else {
                vec![Segment::plain(format!("RED · {findings}"))]
            }
        }
        EvalView::Failed { verdict: false } => match request.and_then(super::error) {
            Some(error) => vec![Segment::plain(format!(
                "ERROR · {}",
                error.lines().next().unwrap_or_default()
            ))],
            None if request.is_none() => plain("ERROR · saved result, not in this Run"),
            None => plain("ERROR"),
        },
        EvalView::InProgress(Activity::Running) => vec![Segment::plain(format!(
            "running · {}",
            request.map_or_else(String::new, |view| short_profile(&view.request.profile))
        ))],
        EvalView::InProgress(Activity::Human(None))
            if request.is_some_and(|view| {
                view.request.status() == crate::types::RequestStatus::Deferred
            }) =>
        {
            plain("DEFERRED · Human sign-off · unclaimed")
        }
        EvalView::InProgress(Activity::Human(None)) => plain("Human sign-off · unclaimed"),
        EvalView::InProgress(Activity::Human(Some(reviewer))) => vec![Segment::plain(format!(
            "Human sign-off · claimed by {reviewer}"
        ))],
        EvalView::InProgress(Activity::Queued(Queue::Ready)) => plain("queued"),
        EvalView::InProgress(Activity::Queued(Queue::Jobs)) => plain("queued · --jobs slots full"),
        EvalView::InProgress(Activity::Queued(Queue::Slot(backend))) => {
            vec![Segment::plain(format!("queued · {backend} slots full"))]
        }
        EvalView::InProgress(Activity::Queued(Queue::Joined)) => {
            plain("queued · joins the running review")
        }
        EvalView::WaitingOn(x) => waits(states, "waits for ", x),
        EvalView::BlockedBy(x) => {
            let mut segments = vec![Segment::plain(if states.running {
                "blocked by "
            } else {
                "not run: blocked by "
            })];
            segments.extend(tokens(states, x, true));
            segments
        }
        EvalView::NotRun(NotRun::Dependency(x)) => waits(states, "not run: waited for ", x),
        EvalView::NotRun(NotRun::Budget) => plain("not started · maxExecutions reached"),
        EvalView::NotRun(NotRun::Stale) => plain("not run · no reusable result"),
        EvalView::NotRun(NotRun::Unreviewed) => plain("not reviewed"),
        EvalView::NotRun(NotRun::Absent) => plain("not in this Run"),
    }
}

/// Start and end of executed, failed, running and Human evals; an open end runs to now.
fn clock(view: &EvalView, request: Option<&RequestView>) -> Option<Clock> {
    let timed = matches!(
        view,
        EvalView::Done(Source::Executed)
            | EvalView::Failed { .. }
            | EvalView::InProgress(Activity::Running | Activity::Human(_))
    );
    let request = &request.filter(|_| timed)?.request;
    let start = request.started_at.unwrap_or(request.created_at).time();
    let end = request.completed_at().map(crate::types::Timestamp::time);
    Some(Clock { start, end })
}

fn compact(view: &EvalView, right: &str) -> String {
    let x = match view {
        EvalView::WaitingOn(waits) | EvalView::NotRun(NotRun::Dependency(waits)) => {
            &waits.artifacts
        }
        EvalView::BlockedBy(x) => x,
        _ => return right.to_owned(),
    };
    match x.as_slice() {
        [one] => format!("←{one}"),
        many => format!("←{}", many.len()),
    }
}

fn local(eval: &EvalId) -> &str {
    eval.rsplit_once('/')
        .map_or(eval.as_str(), |(_, local)| local)
}

fn eval_node<'a>(states: &States<'a>, eval: &'a EvalId, now: OffsetDateTime) -> Node {
    let view = states.view(eval);
    let request = states.request(eval);
    let (glyph, tone, weight) = style(&view);
    let clock = clock(&view, request);
    let right = clock.map_or_else(String::new, |clock| clock.elapsed(now));
    Node {
        clock,
        id: super::NodeId::eval(eval.clone()),
        glyph,
        tone,
        weight,
        name: local(eval).to_owned(),
        marks: String::new(),
        text: text(states, &view, request),
        compact: compact(&view, &right),
        right,
        changed: false,
        upstream: states.upstream_states(eval),
        held: states.held_for_run(eval),
        children: Vec::new(),
        kind: Kind::Eval(view),
    }
}

/// Up to two eval names, then `+N`.
fn names(nodes: &[&Node]) -> String {
    let mut names = nodes
        .iter()
        .take(SHOWN)
        .map(|node| node.name.as_str())
        .collect::<Vec<_>>()
        .join(", ");
    if nodes.len() > SHOWN {
        names = format!("{names} +{}", nodes.len() - SHOWN);
    }
    names
}

/// One clause for the most urgent class of eval rows, plus in-progress ones after a failure.
fn summary(states: &States, id: &ArtifactName, children: &[Node]) -> Vec<Segment> {
    let view = |node: &Node| match &node.kind {
        Kind::Eval(view) => Some(view.clone()),
        Kind::Artifact { .. } => None,
    };
    let Some(top) = children
        .iter()
        .filter_map(view)
        .map(|view| view.rank())
        .min()
    else {
        return Vec::new();
    };
    let class = |rank: Rank| -> Vec<&Node> {
        children
            .iter()
            .filter(|node| view(node).is_some_and(|view| view.rank() == rank))
            .collect()
    };
    let x = |ids: Vec<crate::types::ArtifactName>| tokens(states, &ids, false);
    let mut segments = match top {
        Rank::Failed => {
            let failed = class(Rank::Failed);
            let errors: Vec<_> = failed
                .iter()
                .copied()
                .filter(|node| node.kind == Kind::Eval(EvalView::Failed { verdict: false }))
                .collect();
            let (label, nodes) = if errors.is_empty() {
                ("RED", failed)
            } else {
                ("ERROR", errors)
            };
            vec![Segment::plain(format!("{label}: {}", names(&nodes)))]
        }
        Rank::InProgress => vec![Segment::plain(format!(
            "in progress: {}",
            names(&class(Rank::InProgress))
        ))],
        Rank::Blocked => {
            let mut segments = vec![Segment::plain(if states.running {
                "blocked by "
            } else {
                "not run: blocked by "
            })];
            segments.extend(x(states.blockers_of(id)));
            segments
        }
        Rank::Waiting => {
            let mut segments = vec![Segment::plain("waits for ")];
            segments.extend(x(states.waits_of(id)));
            segments
        }
        Rank::NotRun => {
            let first = class(Rank::NotRun)[0];
            match &first.kind {
                Kind::Eval(EvalView::NotRun(NotRun::Dependency(_))) => {
                    let mut segments = vec![Segment::plain("not run: waited for ")];
                    segments.extend(x(states.waits_of(id)));
                    segments
                }
                _ => first.text.clone(),
            }
        }
        // Every eval row is done, but graph.rs still holds them on their own gates.
        Rank::Done => match states.completion(id) {
            Completion::Waiting { blocked: true } => {
                let mut segments = vec![Segment::plain("done, but blocked by ")];
                segments.extend(x(states.blockers_of(id)));
                segments
            }
            Completion::Waiting { blocked: false } => {
                let mut segments = vec![Segment::plain("done, but waits for ")];
                segments.extend(x(states.waits_of(id)));
                segments
            }
            _ => Vec::new(),
        },
    };
    if top == Rank::Failed {
        let busy = class(Rank::InProgress);
        if !busy.is_empty() {
            segments.push(Segment::plain(format!(" · in progress: {}", names(&busy))));
        }
    }
    segments
}

fn artifact_node<'a>(
    states: &States<'a>,
    saved: &Saved<'a>,
    id: &ArtifactName,
    now: OffsetDateTime,
) -> Node {
    let artifact = saved.artifact(id);
    let basis = artifact.and_then(|artifact| artifact.basis.value()) == Some(&true);
    let children: Vec<_> = states
        .evals(id)
        .iter()
        .map(|&eval| eval_node(states, eval, now))
        .collect();
    let mut marks = String::new();
    if states.index.cyclic.contains(id) {
        let peers = states.index.peers.get(id).map_or(&[][..], Vec::as_slice);
        marks = match peers {
            [] => "  ↻".into(),
            [peer] => format!("  ↻ {peer}"),
            [peer, rest @ ..] => format!("  ↻ {peer} +{}", rest.len()),
        };
    }
    if artifact.and_then(|artifact| artifact.kind.value())
        == Some(&crate::config::ArtifactKind::File)
    {
        marks.push_str("  [file]");
    }
    let completion = states.completion(id);
    // GREEN as the graph counts it: a done eval held on its own gates does not pass.
    let passed = states
        .evals(id)
        .iter()
        .filter(|eval| states.effective(eval) == crate::graph::EvalStatus::Green)
        .count();
    let right = if children.is_empty() {
        String::new()
    } else {
        format!("{passed}/{}", children.len())
    };
    let (glyph, tone, weight, text) = if basis {
        ("◇", Tone::Muted, Weight::Dim, vec![Segment::plain("basis")])
    } else if children.is_empty() {
        (
            "○",
            Tone::Muted,
            Weight::Dim,
            vec![Segment::plain("no evals")],
        )
    } else {
        // The row takes the glyph of its most urgent eval row; ERROR before RED.
        let top = children
            .iter()
            .min_by_key(|node| match &node.kind {
                Kind::Eval(EvalView::Failed { verdict: false }) => (Rank::Failed, false),
                Kind::Eval(view) => (view.rank(), true),
                Kind::Artifact { .. } => (Rank::Done, true),
            })
            .expect("children");
        let (glyph, tone, weight) = match (&top.kind, completion) {
            (_, Completion::InProgress(busy)) => {
                let (glyph, tone, _) = self::completion(Completion::InProgress(busy));
                (glyph, tone, Weight::Bold)
            }
            // Every eval row is done, yet the graph holds them on their own gates.
            (Kind::Eval(EvalView::Done(_)), Completion::Waiting { blocked }) => {
                let (glyph, tone, _) = self::completion(Completion::Waiting { blocked });
                let weight = if blocked { Weight::Normal } else { Weight::Dim };
                (glyph, tone, weight)
            }
            _ => (top.glyph, top.tone, top.weight),
        };
        (glyph, tone, weight, summary(states, id, &children))
    };
    Node {
        id: super::NodeId::artifact(id.clone()),
        clock: None,
        kind: Kind::Artifact { completion, basis },
        glyph,
        tone,
        weight,
        name: id.to_string(),
        marks,
        text,
        compact: right.clone(),
        right,
        changed: false,
        upstream: Vec::new(),
        held: false,
        children,
    }
}

/// Every saved or requested Artifact appears exactly once, upstream first where the graph
/// allows: dependency-first component order, cycle peers by name.
pub fn tree(run: &RunView, requests: &[RequestView], now: OffsetDateTime) -> Vec<Node> {
    let mut nodes = build(run, requests, now);
    // A finished Run: derive the same snapshot once more as of its end and mark every row
    // whose derived state differs.
    if let Some(ended) = at_end(run, requests) {
        mark(&mut nodes, &build(run, &ended, now));
    }
    nodes
}

fn build(run: &RunView, requests: &[RequestView], now: OffsetDateTime) -> Vec<Node> {
    let saved = Saved { run, requests };
    let states = States::new(&saved);
    states
        .index
        .order
        .iter()
        .map(|id| artifact_node(&states, &saved, id, now))
        .collect()
}

/// The requests as they stood when the Run ended, or `None` when nothing changed since
/// (or the Run has not ended). A request that completed later goes back to waiting for its
/// Human (or running), and a later claim is dropped; the Run's recorded evidence is fixed.
fn at_end(run: &RunView, requests: &[RequestView]) -> Option<Vec<RequestView>> {
    let end = run.run.completed_at()?;
    let late = |time: Option<crate::types::Timestamp>| time.is_some_and(|time| time > end);
    let changed = requests.iter().any(|view| {
        late(view.request.completed_at()) || late(view.claim.as_ref().map(|claim| claim.claimed_at))
    });
    if !changed {
        return None;
    }
    let mut ended = requests.to_vec();
    for view in &mut ended {
        if late(view.claim.as_ref().map(|claim| claim.claimed_at)) {
            view.claim = None;
        }
        let request = &mut view.request;
        if late(request.completed_at()) {
            request.state = if request.profile.kind() == crate::config::ProfileKind::Human {
                if run.run.modes.defer_human
                    && request.profile.kind() == crate::config::ProfileKind::Human
                    && run
                        .run
                        .definitions
                        .graph()
                        .and_then(|graph| {
                            graph.evals().iter().find(|eval| eval.id == request.eval_id)
                        })
                        .and_then(|eval| eval.declaration.value())
                        .is_some_and(|declaration| {
                            declaration.gate.value() != Some(&crate::config::Gate::Blocking)
                        })
                {
                    crate::store::RequestState::Deferred
                } else {
                    crate::store::RequestState::WaitingHuman
                }
            } else {
                crate::store::RequestState::Running
            };
        }
    }
    Some(ended)
}

/// The state a row derives, without the root-cause note (an explanation, not a state).
fn state(node: &Node) -> (Kind, &'static str, String) {
    let kind = match &node.kind {
        Kind::Eval(EvalView::WaitingOn(waits)) => Kind::Eval(EvalView::WaitingOn(Waits {
            artifacts: waits.artifacts.clone(),
            root: None,
        })),
        Kind::Eval(EvalView::NotRun(NotRun::Dependency(waits))) => {
            Kind::Eval(EvalView::NotRun(NotRun::Dependency(Waits {
                artifacts: waits.artifacts.clone(),
                root: None,
            })))
        }
        kind => kind.clone(),
    };
    // Artifact rows compare their whole summary; eval rows their state and glyph.
    let summary = match node.kind {
        Kind::Artifact { .. } => format!("{} {}", node.status(), node.right),
        Kind::Eval(_) => String::new(),
    };
    (kind, node.glyph, summary)
}

/// Mark the rows whose derived state differs from the Run-end derivation.
fn mark(nodes: &mut [Node], ended: &[Node]) {
    let mut before = std::collections::HashMap::new();
    for node in ended {
        before.insert(&node.id, state(node));
        for child in &node.children {
            before.insert(&child.id, state(child));
        }
    }
    for node in nodes {
        node.changed = before.get(&node.id) != Some(&state(node));
        for child in &mut node.children {
            child.changed = before.get(&child.id) != Some(&state(child));
        }
    }
}

/// Every eval's direct dependency Artifacts, from the Run's saved definitions.
pub fn upstream_index(run: &RunView, requests: &[RequestView]) -> Vec<(EvalId, Vec<ArtifactName>)> {
    let saved = Saved { run, requests };
    let index = super::states::Index::new(&saved);
    index
        .upstream
        .iter()
        .map(|(eval, artifacts)| {
            (
                (*eval).clone(),
                artifacts.iter().map(|id| (*id).clone()).collect(),
            )
        })
        .collect()
}

/// The Artifact detail's current status, rolled up like its tree row.
pub(super) fn artifact_status(saved: &Saved, id: &ArtifactName, now: OffsetDateTime) -> String {
    let states = States::new(saved);
    let node = artifact_node(&states, saved, id, now);
    let (_, _, word) = completion(states.completion(id));
    let status = node.status();
    let status = if status.is_empty() {
        word.to_owned()
    } else {
        status
    };
    if node.right.is_empty() {
        format!("{} {status}", node.glyph)
    } else {
        format!("{} {status} · {} Evals GREEN", node.glyph, node.right)
    }
}

/// The eval detail's `Waits for`: every dependency Artifact in the tree's order, with its
/// completion and why the eval depends on it, then its evals that are not done yet.
pub(super) fn waits_for(saved: &Saved, eval: &EvalId, now: OffsetDateTime) -> String {
    let states = States::new(saved);
    format_waits(
        saved,
        &states,
        eval,
        now,
        &mut std::collections::HashSet::new(),
    )
}

/// An Artifact combines its evals' input groups by identity, not by rendered text:
/// different inputs may each have a pending eval named `check`.
pub(super) fn artifact_waits(
    saved: &Saved,
    artifact: &ArtifactName,
    now: OffsetDateTime,
) -> String {
    let states = States::new(saved);
    let mut seen = std::collections::HashSet::new();
    let blocks = states
        .evals(artifact)
        .iter()
        .map(|eval| format_waits(saved, &states, eval, now, &mut seen))
        .filter(|block| !block.is_empty());
    super::join(blocks, "\n")
}

fn format_waits(
    saved: &Saved,
    states: &States<'_>,
    eval: &EvalId,
    now: OffsetDateTime,
    seen: &mut std::collections::HashSet<ArtifactName>,
) -> String {
    let Some((&target, _)) = states
        .index
        .evals
        .iter()
        .find(|(_, evals)| evals.contains(&eval))
    else {
        return String::new();
    };
    let peers = |id: &ArtifactName| states.index.peers.get(id).cloned().unwrap_or_default();
    let mut own = peers(target);
    own.push(target);
    let mut lines = Vec::new();
    for upstream in states.upstream_states(eval) {
        if !seen.insert(upstream.artifact.clone()) {
            continue;
        }
        let (glyph, _, word) = completion(upstream.completion);
        let id = &upstream.artifact;
        let mut origins: Vec<String> = saved
            .relations(id, false)
            .into_iter()
            .filter(|relation| own.contains(&&relation.target))
            .map(|relation| {
                let kind = super::relation_kind(relation);
                if &relation.target == target {
                    kind
                } else {
                    format!("{kind} → {}", relation.target)
                }
            })
            .collect();
        if origins.is_empty() && !peers(id).is_empty() {
            origins.push(format!("↻ peer of {}", super::join(peers(id), ", ")));
        }
        let origins = if origins.is_empty() {
            String::new()
        } else {
            format!(" · {}", origins.join(", "))
        };
        lines.push(format!("↑ {id} {glyph} {word}{origins}"));
        if upstream.completion == Completion::Complete {
            continue;
        }
        for &pending in states.evals(id) {
            let node = eval_node(states, pending, now);
            if !matches!(node.kind, Kind::Eval(EvalView::Done(_))) {
                lines.push(format!("  {} {}  {}", node.glyph, node.name, node.status()));
            }
        }
    }
    lines.join("\n")
}