artifactize-core 0.28.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
//! A branch's worktree as it is now, scanned as `artifactize status` does: the graph of its
//! current declarations, each Artifact marked by what verify would do with it now.
use crate::{
    config::{ArtifactKind, Profile, ProfileKind, RepoConfig},
    monitor::model::{self, Card, Status, Tone},
    project::{
        ArtifactCondition, EvalCondition, EvalState, StatusView, VerifyAction, VerifyOptions,
        selection::Selection,
    },
    store::{Claim, Execution, ExecutionResult},
    types::{ArtifactName, EvalId},
};
use std::{
    collections::{BTreeMap, BTreeSet},
    path::{Path, PathBuf},
    sync::Arc,
};
use time::OffsetDateTime;
use tokio_util::sync::CancellationToken;

/// What verify would do now. Declared in precedence order: an Artifact takes the first plan
/// any of its evals has (one to run before one still being checked before blocked before
/// waiting before reused).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Plan {
    /// Evaluated again: at least one eval has no result to reuse.
    Run,
    /// Not known yet: a fingerprint it needs, or the plan of an eval it waits for, is still
    /// being computed.
    Check,
    /// No status has been requested for this declaration.
    Unchecked,
    /// Cannot be evaluated: an upstream eval is RED.
    Blocked,
    /// Waits: for its dependencies' evidence, or a live execution.
    Wait,
    /// Every eval's result would be reused without evaluation (an Artifact without evals has
    /// nothing to evaluate).
    Reuse,
}

impl Plan {
    /// The plan as a Current names it: `reused`, `would run`, `checking`, `waiting` or
    /// `blocked`.
    pub fn word(self) -> &'static str {
        match self {
            Self::Run => "would run",
            Self::Check => "checking",
            Self::Unchecked => "not checked",
            Self::Blocked => "blocked",
            Self::Wait => "waiting",
            Self::Reuse => "reused",
        }
    }

    /// Its one-character mark: reused as a peer's reuse is marked, the others as the statuses
    /// they lead to.
    pub fn glyph(self) -> &'static str {
        match self {
            Self::Run => "○",
            Self::Check => "…",
            Self::Unchecked => "–",
            Self::Blocked => Status::Blocked.glyph(),
            Self::Wait => Status::Wait.glyph(),
            Self::Reuse => "↻",
        }
    }

    pub fn tone(self) -> Tone {
        match self {
            Self::Run => Tone::Running,
            Self::Check | Self::Unchecked => Tone::Muted,
            Self::Blocked => Tone::Blocked,
            Self::Wait => Tone::Queued,
            Self::Reuse => Tone::Green,
        }
    }
}

impl CurrentArtifact {
    /// How many of its evals would be reused, of how many it has, as its graph node counts
    /// them; `None` without evals of its own or while it is still being checked.
    pub fn tally(&self) -> Option<model::Tally> {
        (!self.evals.is_empty() && !matches!(self.plan, Plan::Check | Plan::Unchecked)).then(|| {
            model::Tally {
                passed: self
                    .evals
                    .iter()
                    .filter(|eval| eval.plan == Plan::Reuse)
                    .count(),
                of: self.evals.len(),
            }
        })
    }

    /// Its plan as its node and row read: `would run (2 evals)`, `reused`, ….
    pub fn text(&self) -> String {
        match (self.plan, self.runs) {
            (Plan::Run, 1) => "would run (1 eval)".into(),
            // Without evals of its own, what its parts would do.
            (plan, 0) => plan.word().into(),
            (Plan::Run, runs) => format!("would run ({runs} evals)"),
            (plan, _) => plan.word().into(),
        }
    }
}

impl From<VerifyAction> for Plan {
    fn from(action: VerifyAction) -> Self {
        match action {
            VerifyAction::Execute => Self::Run,
            VerifyAction::Blocked => Self::Blocked,
            VerifyAction::Wait => Self::Wait,
            VerifyAction::Reuse => Self::Reuse,
        }
    }
}

/// A declaration by itself says nothing about the current content or saved evidence.
const UNCHECKED: &str = "Status has not been requested.";

/// One eval of the scan.
#[derive(Debug, Clone)]
pub struct CurrentEval {
    pub id: EvalId,
    /// Its id within its Artifact, as a Run's tree names it.
    pub name: String,
    pub title: String,
    pub kind: ProfileKind,
    pub plan: Plan,
    pub state: EvalCondition,
    /// Why it would run, wait, be blocked or be reused.
    pub reason: String,
    /// Its instruction and the result it would reuse, as an eval's Summary shows them.
    pub card: Card,
    /// Every other fact by name: its profile, fingerprint, reuse key and what changed.
    pub facts: Vec<(&'static str, String)>,
    observed_at: Option<OffsetDateTime>,
}

/// One Artifact of the scan.
#[derive(Debug, Clone)]
pub struct CurrentArtifact {
    pub definition: PathBuf,
    pub binding: Option<crate::config::Binding>,
    pub tools: Option<String>,
    pub target_missing: bool,
    pub name: ArtifactName,
    pub kind: ArtifactKind,
    pub plan: Plan,
    /// How many of its evals would run.
    pub runs: usize,
    pub path: crate::config::Target,
    pub written_path: String,
    pub state: ArtifactCondition,
    pub reason: String,
    pub evals: Vec<CurrentEval>,
    /// The Artifacts it is made of directly, in name order.
    pub parts: Vec<ArtifactName>,
}

/// `to`'s evals use `from`, lit by `from`'s plan; a part is no edge but drawn in its whole.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CurrentEdge {
    pub from: ArtifactName,
    pub to: ArtifactName,
    pub plan: Plan,
}

/// The scan of one worktree.
#[derive(Debug, Clone)]
pub struct Current {
    pub scanned_at: Option<OffsetDateTime>,
    /// In name order.
    pub artifacts: Vec<CurrentArtifact>,
    pub edges: Vec<CurrentEdge>,
    /// Compact file lookup, shared with the visible Detail and scoped checks.
    pub sites: Arc<crate::config::SiteIndex>,
    /// Reverse part links, shared across all views of the declaration shape.
    pub parents: Arc<BTreeMap<ArtifactName, Vec<ArtifactName>>>,
    incoming: Arc<BTreeMap<ArtifactName, Vec<usize>>>,
}

impl Current {
    pub fn from_shape(
        mut artifacts: Vec<CurrentArtifact>,
        mut edges: Vec<CurrentEdge>,
        sites: Arc<crate::config::SiteIndex>,
    ) -> Self {
        artifacts.sort_by(|one, other| one.name.cmp(&other.name));
        edges.sort_by(|one, other| (&one.from, &one.to).cmp(&(&other.from, &other.to)));
        let mut parents: BTreeMap<_, Vec<_>> = BTreeMap::new();
        for whole in &artifacts {
            for part in &whole.parts {
                parents
                    .entry(part.clone())
                    .or_default()
                    .push(whole.name.clone());
            }
        }
        let mut incoming: BTreeMap<_, Vec<_>> = BTreeMap::new();
        for (index, edge) in edges.iter().enumerate() {
            incoming.entry(edge.to.clone()).or_default().push(index);
        }
        Self {
            scanned_at: None,
            artifacts,
            edges,
            sites,
            parents: Arc::new(parents),
            incoming: Arc::new(incoming),
        }
    }

    /// Relations incident to the selected Artifact, never a copy of the whole graph.
    pub fn adjacent(&self, name: &ArtifactName) -> (Vec<&CurrentEdge>, Vec<&CurrentEdge>) {
        let incoming = self
            .incoming
            .get(name)
            .into_iter()
            .flatten()
            .map(|&at| &self.edges[at])
            .collect();
        let start = self.edges.partition_point(|edge| &edge.from < name);
        let outgoing = self.edges[start..]
            .iter()
            .take_while(|edge| &edge.from == name)
            .collect();
        (incoming, outgoing)
    }

    /// Count the Artifact's copies along part paths, not by enumerating the rest of the graph.
    pub fn copies(&self, name: &ArtifactName) -> u32 {
        fn count<'a>(
            current: &'a Current,
            name: &'a ArtifactName,
            memo: &mut BTreeMap<&'a ArtifactName, u32>,
        ) -> u32 {
            if let Some(copies) = memo.get(name) {
                return *copies;
            }
            let copies = current.parents.get(name).map_or(1, |parents| {
                parents.iter().fold(0u32, |total, parent| {
                    total.saturating_add(count(current, parent, memo))
                })
            });
            memo.insert(name, copies);
            copies
        }
        count(self, name, &mut BTreeMap::new())
    }

    /// Whether `other` has the same Artifacts, parts and edges in the same order, whatever they
    /// would do: a view can keep where it placed them and only relight them.
    pub fn same_shape(&self, other: &Self) -> bool {
        self.artifacts
            .iter()
            .map(|artifact| (&artifact.name, &artifact.parts))
            .eq(other
                .artifacts
                .iter()
                .map(|artifact| (&artifact.name, &artifact.parts)))
            && self
                .edges
                .iter()
                .map(|edge| (&edge.from, &edge.to))
                .eq(other.edges.iter().map(|edge| (&edge.from, &edge.to)))
    }
}

/// Read the graph's declarations without hashing content or looking up saved status.
pub fn outline(repo: &Path) -> Result<Current, String> {
    let outline = crate::config::read_workspace_declarations(repo)
        .map(|config| declared(&config))
        .map_err(|error| error.to_string());
    crate::platform::release_free_memory();
    outline
}

/// Publish the graph before fingerprinting and the forecast afterward. Consumers that only
/// need progress can use [`scan_scope`] rather than rebuilding views as work advances.
pub async fn scan(
    repo: &Path,
    state: &Path,
    cancellation: CancellationToken,
    mut publish: impl FnMut(Current) + Send,
) -> Result<Current, String> {
    let result = async {
        let config = read_config(repo, &Selection::All, None).await?;
        let mut current = declared(&config);
        for artifact in &mut current.artifacts {
            artifact.plan = Plan::Check;
            artifact.reason = "Waiting for the requested status check.".into();
            for eval in &mut artifact.evals {
                eval.plan = Plan::Check;
                eval.reason.clone_from(&artifact.reason);
            }
        }
        for edge in &mut current.edges {
            edge.plan = Plan::Check;
        }
        publish(current.clone());
        let current = scan_config(
            config,
            current,
            state,
            &Selection::All,
            cancellation,
            |_| {},
        )
        .await?;
        publish(current.clone());
        Ok(current)
    }
    .await;
    crate::platform::release_free_memory();
    result
}

/// An explicit forecast reports only its outstanding fingerprint count until it settles.
pub async fn scan_scope(
    repo: &Path,
    state: &Path,
    selection: &Selection,
    sites: Option<Arc<crate::config::SiteIndex>>,
    cancellation: CancellationToken,
    progress: impl FnMut(usize) + Send,
) -> Result<Current, String> {
    let result = async {
        let config = read_config(repo, selection, sites).await?;
        let current = declared(&config);
        scan_config(config, current, state, selection, cancellation, progress).await
    }
    .await;
    crate::platform::release_free_memory();
    result
}

async fn read_config(
    repo: &Path,
    selection: &Selection,
    sites: Option<Arc<crate::config::SiteIndex>>,
) -> Result<RepoConfig, String> {
    let repo = repo.to_path_buf();
    let indexed = sites.zip(selection.roots());
    crate::task::blocking(move || {
        let scoped = indexed.and_then(|(sites, names)| {
            sites
                .subset(
                    &repo,
                    names,
                    crate::config::Evals::All,
                    &crate::config::lang::process_environment,
                )
                .ok()
        });
        scoped.map_or_else(|| crate::config::read_workspace_declarations(&repo), Ok)
    })
    .await?
    .map_err(|error| error.to_string())
}

async fn scan_config(
    config: RepoConfig,
    mut current: Current,
    state: &Path,
    selection: &Selection,
    cancellation: CancellationToken,
    mut progress: impl FnMut(usize) + Send,
) -> Result<Current, String> {
    let (status, cached) = crate::project::scan(
        config,
        Some(state),
        selection,
        &VerifyOptions::default(),
        cancellation,
        Some(&mut progress),
    )
    .await?;
    current.apply_status(&status, &cached);
    Ok(current)
}

fn declared(config: &RepoConfig) -> Current {
    let mut evals: BTreeMap<&ArtifactName, Vec<CurrentEval>> = BTreeMap::new();
    let now = OffsetDateTime::now_utc();
    for eval in &config.evals {
        let profile = eval.declaration.profile();
        evals.entry(&eval.target).or_default().push(CurrentEval {
            id: eval.id.clone(),
            name: crate::monitor::model::tree::local(&eval.id).into(),
            title: eval.declaration.title.clone(),
            kind: profile.kind(),
            plan: Plan::Unchecked,
            state: EvalCondition::Unreviewed,
            reason: UNCHECKED.into(),
            card: card(
                eval.declaration.instruction().unwrap_or(""),
                profile,
                Plan::Unchecked,
                None,
                now,
            ),
            facts: vec![("Profile", self::profile(profile))],
            observed_at: None,
        });
    }
    let artifacts = config
        .artifacts
        .values()
        .map(|artifact| CurrentArtifact {
            definition: artifact.definition.clone(),
            binding: artifact.binding.clone(),
            tools: artifact.tools.clone(),
            target_missing: artifact.target_error.is_some(),
            name: artifact.name.clone(),
            kind: artifact.kind(),
            plan: Plan::Unchecked,
            runs: 0,
            path: artifact.path.clone(),
            written_path: artifact.written_path(),
            state: ArtifactCondition::Unreviewed,
            reason: UNCHECKED.into(),
            evals: evals.remove(&artifact.name).unwrap_or_default(),
            parts: artifact.parts.iter().cloned().collect(),
        })
        .collect();
    let edges = config
        .relations
        .iter()
        .filter(|rel| rel.source != rel.target && rel.kind != crate::scope::RelationKind::Part)
        .map(|rel| (&rel.source, &rel.target))
        .collect::<BTreeSet<_>>()
        .into_iter()
        .map(|(from, to)| CurrentEdge {
            from: from.clone(),
            to: to.clone(),
            plan: Plan::Unchecked,
        })
        .collect();
    Current::from_shape(
        artifacts,
        edges,
        Arc::new(crate::config::SiteIndex::new(config)),
    )
}

/// What running `profile` costs as Execution options name it.
fn profile(profile: &Profile) -> String {
    match profile {
        Profile::Agent { backend, model, .. } => format!("agent · {} · {model}", backend.as_str()),
        other => other.kind().name().to_owned(),
    }
}

fn card(
    instruction: &str,
    profile: &Profile,
    plan: Plan,
    reused: Option<&Execution>,
    now: OffsetDateTime,
) -> Card {
    let result = reused.and_then(Execution::result);
    Card {
        instruction: instruction.to_owned(),
        issues: result.map(ExecutionResult::issues),
        raw: result.map(model::raw),
        exit_code: result.and_then(ExecutionResult::exit_code),
        error: None,
        reused: plan == Plan::Reuse,
        took: reused
            .and_then(|execution| model::span(execution.started_at, execution.completed_at(), now)),
        tokens: reused
            .and_then(|execution| execution.usage.as_deref())
            .and_then(model::attempt_tokens),
        model: match profile {
            Profile::Agent { model, .. } => Some(model.to_string()),
            _ => None,
        },
    }
}

/// Evidence for one Run in its recorded Current, without loading definitions or reading the worktree.
pub struct CurrentRun(Vec<crate::store::Request>);

pub async fn current_run(
    state: &Path,
    place: &super::Place,
    run: &crate::types::RunId,
) -> Result<CurrentRun, String> {
    let (repo, identity) = crate::store::run_checkout(state, run).await?;
    if super::Place::for_checkout(&repo, &identity) != *place {
        return Err("Run belongs to a different checkout.".into());
    }
    crate::store::read_run_requests_only(state, run)
        .await
        .map(CurrentRun)
}

impl Current {
    pub fn artifact(&self, name: &ArtifactName) -> Option<&CurrentArtifact> {
        let at = self
            .artifacts
            .binary_search_by(|node| node.name.cmp(name))
            .ok()?;
        Some(&self.artifacts[at])
    }

    fn artifact_mut(&mut self, name: &ArtifactName) -> Option<&mut CurrentArtifact> {
        let at = self
            .artifacts
            .binary_search_by(|node| node.name.cmp(name))
            .ok()?;
        Some(&mut self.artifacts[at])
    }

    fn apply_status(&mut self, status: &StatusView, cached: &BTreeMap<EvalId, Claim>) {
        let now = OffsetDateTime::now_utc();
        for artifact in &status.artifacts {
            if let Some(node) = self.artifact_mut(&artifact.id) {
                node.target_missing = artifact.target_missing;
                node.state = artifact.state;
                node.reason.clone_from(&artifact.reason);
                node.plan = Plan::Reuse;
            }
        }
        for eval in &status.evals {
            if let Some(node) = self.artifact_mut(&eval.target)
                && let Some(found) = node.evals.iter_mut().find(|item| item.id == eval.id)
            {
                forecast(found, eval, cached.get(&eval.id), now);
            }
        }
        self.scanned_at = Some(now);
        self.relight(
            status
                .artifacts
                .iter()
                .map(|artifact| artifact.id.clone())
                .collect(),
        );
    }

    /// Keep only checked nodes from an explicitly requested scope; other forecasts stay put.
    pub fn merge_scope(&mut self, scoped: Current) {
        let mut changed = BTreeSet::new();
        for node in scoped
            .artifacts
            .into_iter()
            .filter(|node| node.plan != Plan::Unchecked)
        {
            if let Some(old) = self.artifact_mut(&node.name)
                && old.parts == node.parts
                && old
                    .evals
                    .iter()
                    .map(|e| &e.id)
                    .eq(node.evals.iter().map(|e| &e.id))
            {
                changed.insert(node.name.clone());
                *old = node;
            }
        }
        self.relight(changed);
    }

    /// Only the run's requests contribute. Saved evidence never starts a content scan.
    pub fn apply_run(&mut self, run: CurrentRun) -> bool {
        use crate::types::RequestStatus;
        let mut changed = BTreeSet::new();
        for request in &run.0 {
            let completed = if request.key.is_some() {
                Plan::Reuse
            } else {
                Plan::Run
            };
            let (plan, state) = match request.status() {
                RequestStatus::Green => (completed, EvalCondition::Pass),
                RequestStatus::Red => (completed, EvalCondition::Red),
                RequestStatus::Error => (Plan::Run, EvalCondition::Error),
                RequestStatus::Deferred => (Plan::Wait, EvalCondition::Deferred),
                RequestStatus::WaitingHuman => (Plan::Wait, EvalCondition::WaitingHuman),
                RequestStatus::Blocked => (Plan::Blocked, EvalCondition::Blocked),
                _ => continue,
            };
            let Some(node) = self.artifact_mut(&request.target) else {
                continue;
            };
            let Some(eval) = node
                .evals
                .iter_mut()
                .find(|eval| eval.id == request.eval_id)
            else {
                continue;
            };
            let observed = request.completed_at().unwrap_or(request.created_at).time();
            if eval
                .observed_at
                .is_some_and(|previous| previous >= observed)
            {
                continue;
            }
            eval.observed_at = Some(observed);
            eval.plan = plan;
            eval.state = state;
            eval.reason = format!(
                "As recorded by {}. Check status for changes since that Run.",
                request.run_id
            );
            eval.facts
                .retain(|(name, _)| *name == "Profile" || *name == "Eval");
            if let Some(key) = &request.key {
                eval.facts.push(("Reuse key", key.to_string()));
            }
            if let Some(fingerprint) = &request.fingerprint {
                eval.facts.push(("Fingerprint", fingerprint.to_string()));
            }
            eval.facts.push(("Last Run", request.run_id.to_string()));
            let result = request.result();
            eval.card.issues = result.map(ExecutionResult::issues);
            eval.card.raw = result.map(model::raw);
            eval.card.exit_code = result.and_then(ExecutionResult::exit_code);
            eval.card.error = request.error().map(str::to_owned);
            eval.card.took = None;
            eval.card.tokens = None;
            eval.card.reused = plan == Plan::Reuse;
            node.reason.clone_from(&eval.reason);
            changed.insert(request.target.clone());
        }
        let any = !changed.is_empty();
        self.relight(changed);
        any
    }

    fn relight(&mut self, mut affected: BTreeSet<ArtifactName>) {
        let mut work: Vec<_> = affected.iter().cloned().collect();
        while let Some(part) = work.pop() {
            for whole in self.parents.get(&part).into_iter().flatten() {
                if self
                    .artifact(whole)
                    .is_some_and(|node| node.evals.is_empty())
                    && affected.insert(whole.clone())
                {
                    work.push(whole.clone());
                }
            }
        }
        let mut plans = BTreeMap::new();
        let mut pending = Vec::new();
        for node in affected.iter().filter_map(|name| self.artifact(name)) {
            pending.push((node, false));
            while let Some((item, ready)) = pending.pop() {
                if plans.contains_key(&item.name) {
                    continue;
                }
                let plan = if !item.evals.is_empty() {
                    item.evals
                        .iter()
                        .map(|eval| eval.plan)
                        .min()
                        .expect("nonempty evals")
                } else if item.parts.is_empty() {
                    item.plan
                } else if ready {
                    item.parts
                        .iter()
                        .filter_map(|part| {
                            plans
                                .get(part)
                                .copied()
                                .or_else(|| self.artifact(part).map(|part| part.plan))
                        })
                        .min()
                        .unwrap_or(item.plan)
                } else {
                    pending.push((item, true));
                    pending.extend(
                        item.parts
                            .iter()
                            .filter(|part| affected.contains(*part))
                            .filter_map(|part| self.artifact(part))
                            .map(|part| (part, false)),
                    );
                    continue;
                };
                plans.insert(&item.name, plan);
            }
        }
        let plans: BTreeMap<_, _> = plans
            .into_iter()
            .map(|(name, plan)| (name.clone(), plan))
            .collect();
        for (name, plan) in plans {
            if let Some(node) = self.artifact_mut(&name) {
                node.plan = plan;
                node.runs = node
                    .evals
                    .iter()
                    .filter(|eval| eval.plan == Plan::Run)
                    .count();
            }
            // Edges share the declaration order (source, target), so unrelated edges need not be visited.
            let start = self.edges.partition_point(|edge| edge.from < name);
            for edge in self.edges[start..]
                .iter_mut()
                .take_while(|edge| edge.from == name)
            {
                edge.plan = plan;
            }
        }
    }
}

fn forecast(
    found: &mut CurrentEval,
    eval: &EvalState,
    cached: Option<&Claim>,
    now: OffsetDateTime,
) {
    let plan = Plan::from(eval.action);
    let reused = match cached {
        Some(Claim::Reuse(execution)) => Some(&**execution),
        _ => None,
    };
    let mut facts = vec![("Profile", profile(&eval.profile))];
    facts.extend(
        eval.fingerprint
            .as_ref()
            .map(|hash| ("Fingerprint", hash.to_string())),
    );
    facts.push(("Eval", eval.id.to_string()));
    facts.push(("Verify would", eval.action.to_string()));
    facts.push(("State", eval.state.to_string()));
    facts.extend(eval.key.as_ref().map(|key| ("Reuse key", key.to_string())));
    facts.push(("Definition hash", eval.eval_def_hash.to_string()));
    facts.extend(
        eval.last
            .as_ref()
            .map(|last| ("Last Run", format!("{} · {}", last.run_id, last.verdict))),
    );
    if let Some(changes) = &eval.changes {
        facts.push(("Changes", changes.summary.clone()));
        facts.extend(
            changes
                .files
                .as_ref()
                .map(|files| ("Changed files", files.join("\n"))),
        );
        facts.extend(
            changes
                .dependencies
                .as_ref()
                .map(|names| ("Changed dependencies", names.join("\n"))),
        );
    }
    found.plan = plan;
    found.observed_at = Some(now);
    found.state = eval.state;
    found.reason.clone_from(&eval.reason);
    found.card = card(&found.card.instruction, &eval.profile, plan, reused, now);
    found.facts = facts;
}

#[cfg(test)]
mod tests;