Skip to main content

artifactize_core/monitor/live/
current.rs

1//! A branch's worktree as it is now, scanned as `artifactize status` does: the graph of its
2//! current declarations, each Artifact marked by what verify would do with it now.
3use crate::{
4    config::{ArtifactKind, Profile, ProfileKind},
5    graph_structure::{self, Structure},
6    monitor::model::{self, Card, Status, Tone},
7    project::{
8        ArtifactCondition, EvalCondition, EvalState, StatusView, VerifyAction, VerifyOptions,
9        selection::Selection,
10    },
11    store::{Claim, Execution, ExecutionResult},
12    types::{ArtifactName, EvalId, Fingerprint},
13};
14use std::{
15    collections::{BTreeMap, BTreeSet},
16    path::{Path, PathBuf},
17    sync::Arc,
18};
19use time::OffsetDateTime;
20use tokio_util::sync::CancellationToken;
21
22/// What verify would do now. Declared in precedence order: an Artifact takes the first plan
23/// any of its evals has (one to run before one still being checked before blocked before
24/// waiting before reused).
25#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
26pub enum Plan {
27    /// Evaluated again: at least one eval has no result to reuse.
28    Run,
29    /// Not known yet: a fingerprint it needs, or the plan of an eval it waits for, is still
30    /// being computed.
31    Check,
32    /// Cannot be evaluated: an upstream eval is RED.
33    Blocked,
34    /// Waits: for its dependencies' evidence, or a live execution.
35    Wait,
36    /// Every eval's result would be reused without evaluation (an Artifact without evals has
37    /// nothing to evaluate).
38    Reuse,
39}
40
41impl Plan {
42    /// The plan as a Current names it: `reused`, `would run`, `checking`, `waiting` or
43    /// `blocked`.
44    pub fn word(self) -> &'static str {
45        match self {
46            Self::Run => "would run",
47            Self::Check => "checking",
48            Self::Blocked => "blocked",
49            Self::Wait => "waiting",
50            Self::Reuse => "reused",
51        }
52    }
53
54    /// Its one-character mark: reused as a peer's reuse is marked, the others as the statuses
55    /// they lead to.
56    pub fn glyph(self) -> &'static str {
57        match self {
58            Self::Run => "○",
59            Self::Check => "…",
60            Self::Blocked => Status::Blocked.glyph(),
61            Self::Wait => Status::Wait.glyph(),
62            Self::Reuse => "↻",
63        }
64    }
65
66    pub fn tone(self) -> Tone {
67        match self {
68            Self::Run => Tone::Running,
69            Self::Check => Tone::Muted,
70            Self::Blocked => Tone::Blocked,
71            Self::Wait => Tone::Queued,
72            Self::Reuse => Tone::Green,
73        }
74    }
75}
76
77impl CurrentArtifact {
78    /// How many of its evals would be reused, of how many it has, as its graph node counts
79    /// them; `None` without evals of its own or while it is still being checked.
80    pub fn tally(&self) -> Option<model::Tally> {
81        (!self.evals.is_empty() && self.plan != Plan::Check).then(|| model::Tally {
82            passed: self
83                .evals
84                .iter()
85                .filter(|eval| eval.plan == Plan::Reuse)
86                .count(),
87            of: self.evals.len(),
88        })
89    }
90
91    /// Its plan as its node and row read: `would run (2 evals)`, `reused`, ….
92    pub fn text(&self) -> String {
93        match (self.plan, self.runs) {
94            (Plan::Run, 1) => "would run (1 eval)".into(),
95            // Without evals of its own, what its parts would do.
96            (plan, 0) => plan.word().into(),
97            (Plan::Run, runs) => format!("would run ({runs} evals)"),
98            (plan, _) => plan.word().into(),
99        }
100    }
101}
102
103impl From<VerifyAction> for Plan {
104    fn from(action: VerifyAction) -> Self {
105        match action {
106            VerifyAction::Execute => Self::Run,
107            VerifyAction::Blocked => Self::Blocked,
108            VerifyAction::Wait => Self::Wait,
109            VerifyAction::Reuse => Self::Reuse,
110        }
111    }
112}
113
114/// Why an eval is still being checked.
115const CHECKING: &str = "Still being checked: a fingerprint its key needs, or the plan of an eval it waits for, is not known yet.";
116
117/// One eval of the scan.
118#[derive(Debug, Clone)]
119pub struct CurrentEval {
120    pub id: EvalId,
121    /// Its id within its Artifact, as a Run's tree names it.
122    pub name: String,
123    pub title: String,
124    pub kind: ProfileKind,
125    pub plan: Plan,
126    pub state: EvalCondition,
127    /// Why it would run, wait, be blocked or be reused.
128    pub reason: String,
129    /// Its instruction and the result it would reuse, as an eval's Summary shows them.
130    pub card: Card,
131    /// Every other fact by name: its profile, fingerprint, reuse key and what changed.
132    pub facts: Vec<(&'static str, String)>,
133}
134
135/// One Artifact of the scan.
136#[derive(Debug, Clone)]
137pub struct CurrentArtifact {
138    pub definition: PathBuf,
139    pub target_missing: bool,
140    pub name: ArtifactName,
141    pub kind: ArtifactKind,
142    pub plan: Plan,
143    /// How many of its evals would run.
144    pub runs: usize,
145    pub path: crate::config::Target,
146    pub state: ArtifactCondition,
147    pub reason: String,
148    pub evals: Vec<CurrentEval>,
149    /// The Artifacts it is made of directly, in name order.
150    pub parts: Vec<ArtifactName>,
151}
152
153/// `to`'s evals use `from`, lit by `from`'s plan; a part is no edge but drawn in its whole.
154#[derive(Debug, Clone, PartialEq, Eq)]
155pub struct CurrentEdge {
156    pub from: ArtifactName,
157    pub to: ArtifactName,
158    pub plan: Plan,
159}
160
161/// The scan of one worktree.
162#[derive(Debug, Clone)]
163pub struct Current {
164    pub scanned_at: OffsetDateTime,
165    pub fingerprint: Fingerprint,
166    /// Every Artifact, eval criterion and labeled relation as text, shared by a scan's steps.
167    pub structure: Arc<str>,
168    /// In name order.
169    pub artifacts: Vec<CurrentArtifact>,
170    pub edges: Vec<CurrentEdge>,
171}
172
173impl Current {
174    /// Whether `other` has the same Artifacts, parts and edges in the same order, whatever they
175    /// would do: a view can keep where it placed them and only relight them.
176    pub fn same_shape(&self, other: &Self) -> bool {
177        self.artifacts
178            .iter()
179            .map(|artifact| (&artifact.name, &artifact.parts))
180            .eq(other
181                .artifacts
182                .iter()
183                .map(|artifact| (&artifact.name, &artifact.parts)))
184            && self
185                .edges
186                .iter()
187                .map(|edge| (&edge.from, &edge.to))
188                .eq(other.edges.iter().map(|edge| (&edge.from, &edge.to)))
189    }
190}
191
192/// Scan the workspace at `repo` as it is now against the state at `state`, as `artifactize
193/// status` does: it hashes files and may run fingerprint scripts or ask the review store, and
194/// records nothing. `publish` gets the graph as soon as the declarations are read, every
195/// Artifact still being checked, then again each time fingerprints come in.
196pub async fn scan(
197    repo: &Path,
198    state: &Path,
199    cancellation: CancellationToken,
200    publish: impl FnMut(Current) + Send,
201) -> Result<Current, String> {
202    let current = read(repo, state, cancellation, publish).await;
203    // What the scan read is several times what it keeps: give it back, or a long-lived
204    // monitor keeps the largest scan's memory after the scan is gone.
205    crate::platform::release_free_memory();
206    current
207}
208
209async fn read(
210    repo: &Path,
211    state: &Path,
212    cancellation: CancellationToken,
213    mut publish: impl FnMut(Current) + Send,
214) -> Result<Current, String> {
215    // One read of the declarations serves both: the structure depends on them alone.
216    let config =
217        crate::config::read_workspace_declarations(repo).map_err(|error| error.to_string())?;
218    let structure = graph_structure::extract(&config);
219    // Every step of the scan shows the same declarations: describe them once.
220    let declared = Declared {
221        tree: structure.tree().into(),
222        fingerprint: structure.fingerprint(),
223        structure: &structure,
224    };
225    let (status, cached) = crate::project::scan(
226        config,
227        Some(state),
228        &Selection::All,
229        &VerifyOptions::default(),
230        cancellation,
231        Some(&mut |progress: crate::project::Progress<'_>| {
232            publish(project(
233                &declared,
234                &progress.view,
235                progress.cached,
236                &progress.checking,
237                OffsetDateTime::now_utc(),
238            ));
239        }),
240    )
241    .await?;
242    Ok(project(
243        &declared,
244        &status,
245        &cached,
246        &BTreeSet::new(),
247        OffsetDateTime::now_utc(),
248    ))
249}
250
251/// What running `profile` costs as Execution options name it.
252fn profile(profile: &Profile) -> String {
253    match profile {
254        Profile::Agent { backend, model, .. } => format!("agent · {} · {model}", backend.as_str()),
255        other => other.kind().name().to_owned(),
256    }
257}
258
259fn card(
260    instruction: &str,
261    profile: &Profile,
262    plan: Plan,
263    reused: Option<&Execution>,
264    now: OffsetDateTime,
265) -> Card {
266    let result = reused.and_then(Execution::result);
267    Card {
268        instruction: instruction.to_owned(),
269        issues: result.map(ExecutionResult::issues),
270        raw: result.map(model::raw),
271        exit_code: result.and_then(ExecutionResult::exit_code),
272        error: None,
273        reused: plan == Plan::Reuse,
274        took: reused
275            .and_then(|execution| model::span(execution.started_at, execution.completed_at(), now)),
276        tokens: reused
277            .and_then(|execution| execution.usage.as_deref())
278            .and_then(model::attempt_tokens),
279        model: match profile {
280            Profile::Agent { model, .. } => Some(model.to_string()),
281            _ => None,
282        },
283    }
284}
285
286/// The declarations a scan read, as every one of its steps shows them.
287struct Declared<'s> {
288    structure: &'s Structure,
289    tree: Arc<str>,
290    fingerprint: Fingerprint,
291}
292
293/// The scan of `declared` as `status` found it, with the claims it found, the evals still
294/// being `checking` marked so.
295fn project(
296    declared: &Declared<'_>,
297    status: &StatusView,
298    cached: &BTreeMap<EvalId, Claim>,
299    checking: &BTreeSet<&EvalId>,
300    now: OffsetDateTime,
301) -> Current {
302    let mut by_target: BTreeMap<&ArtifactName, Vec<&EvalState>> = BTreeMap::new();
303    for eval in &status.evals {
304        by_target.entry(&eval.target).or_default().push(eval);
305    }
306    let mut parts: BTreeMap<&ArtifactName, Vec<ArtifactName>> = BTreeMap::new();
307    for relation in &declared.structure.relations {
308        if relation.kind == graph_structure::Edge::Part {
309            parts
310                .entry(&relation.target)
311                .or_default()
312                .push(relation.source.clone());
313        }
314    }
315    let mut artifacts: Vec<CurrentArtifact> = status
316        .artifacts
317        .iter()
318        .map(|artifact| {
319            let evals: Vec<CurrentEval> =
320                by_target
321                    .get(&artifact.id)
322                    .into_iter()
323                    .flatten()
324                    .map(|eval| {
325                        let plan = if checking.contains(&eval.id) {
326                            Plan::Check
327                        } else {
328                            Plan::from(eval.action)
329                        };
330                        let reused = match cached.get(&eval.id) {
331                            Some(Claim::Reuse(execution)) => Some(&**execution),
332                            _ => None,
333                        };
334                        let instruction = declared
335                            .structure
336                            .evals
337                            .get(&eval.id)
338                            .and_then(|declared| declared.instruction.as_deref())
339                            .unwrap_or("");
340                        let mut facts = vec![("Profile", profile(&eval.profile))];
341                        facts.extend(
342                            eval.fingerprint
343                                .as_ref()
344                                .map(|fingerprint| ("Fingerprint", fingerprint.to_string())),
345                        );
346                        facts.push(("Eval", eval.id.to_string()));
347                        facts.push(("Verify would", eval.action.to_string()));
348                        facts.push(("State", eval.state.to_string()));
349                        facts.extend(eval.key.as_ref().map(|key| ("Reuse key", key.to_string())));
350                        facts.push(("Definition hash", eval.eval_def_hash.to_string()));
351                        facts.extend(eval.last.as_ref().map(|last| {
352                            ("Last Run", format!("{} · {}", last.run_id, last.verdict))
353                        }));
354                        if let Some(changes) = &eval.changes {
355                            facts.push(("Changes", changes.summary.clone()));
356                            facts.extend(
357                                changes
358                                    .files
359                                    .as_ref()
360                                    .map(|files| ("Changed files", files.join("\n"))),
361                            );
362                            facts.extend(
363                                changes
364                                    .dependencies
365                                    .as_ref()
366                                    .map(|names| ("Changed dependencies", names.join("\n"))),
367                            );
368                        }
369                        CurrentEval {
370                            id: eval.id.clone(),
371                            name: crate::monitor::model::tree::local(&eval.id).to_owned(),
372                            title: eval.title.clone(),
373                            kind: eval.profile.kind(),
374                            plan,
375                            state: eval.state,
376                            reason: if plan == Plan::Check {
377                                CHECKING.into()
378                            } else {
379                                eval.reason.clone()
380                            },
381                            card: card(instruction, &eval.profile, plan, reused, now),
382                            facts,
383                        }
384                    })
385                    .collect();
386            CurrentArtifact {
387                definition: artifact.definition.clone(),
388                target_missing: artifact.target_missing,
389                name: artifact.id.clone(),
390                kind: artifact.kind,
391                plan: evals
392                    .iter()
393                    .map(|eval| eval.plan)
394                    .min()
395                    .unwrap_or(Plan::Reuse),
396                runs: evals.iter().filter(|eval| eval.plan == Plan::Run).count(),
397                path: artifact.path.clone(),
398                state: artifact.state,
399                reason: artifact.reason.clone(),
400                evals,
401                parts: parts.remove(&artifact.id).unwrap_or_default(),
402            }
403        })
404        .collect();
405    let mut plans: BTreeMap<ArtifactName, Plan> = artifacts
406        .iter()
407        .map(|artifact| (artifact.name.clone(), artifact.plan))
408        .collect();
409    // Without evals of its own, an Artifact does what the first of its parts in plan order
410    // does; parts are acyclic, so passes over the wholes settle.
411    let wholes: Vec<usize> = (0..artifacts.len())
412        .filter(|&at| artifacts[at].evals.is_empty() && !artifacts[at].parts.is_empty())
413        .collect();
414    let mut changed = true;
415    while changed {
416        changed = false;
417        for &at in &wholes {
418            let artifact = &mut artifacts[at];
419            let plan = artifact
420                .parts
421                .iter()
422                .filter_map(|part| plans.get(part).copied())
423                .min()
424                .unwrap_or(Plan::Reuse);
425            if plan != artifact.plan {
426                artifact.plan = plan;
427                plans.insert(artifact.name.clone(), plan);
428                changed = true;
429            }
430        }
431    }
432    let pairs: BTreeSet<(&ArtifactName, &ArtifactName)> = declared
433        .structure
434        .relations
435        .iter()
436        .filter(|relation| {
437            relation.source != relation.target && relation.kind != graph_structure::Edge::Part
438        })
439        .map(|relation| (&relation.source, &relation.target))
440        .collect();
441    let edges = pairs
442        .into_iter()
443        .filter_map(|(from, to)| {
444            Some(CurrentEdge {
445                plan: *plans.get(from)?,
446                from: from.clone(),
447                to: plans.contains_key(to).then(|| to.clone())?,
448            })
449        })
450        .collect();
451    Current {
452        scanned_at: now,
453        fingerprint: declared.fingerprint.clone(),
454        structure: declared.tree.clone(),
455        artifacts,
456        edges,
457    }
458}
459
460#[cfg(test)]
461mod tests;