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
173/// Scan the workspace at `repo` as it is now against the state at `state`, as `artifactize
174/// status` does: it hashes files and may run fingerprint scripts or ask the review store, and
175/// records nothing. `publish` gets the graph as soon as the declarations are read, every
176/// Artifact still being checked, then again each time fingerprints come in.
177pub async fn scan(
178    repo: &Path,
179    state: &Path,
180    cancellation: CancellationToken,
181    publish: impl FnMut(Current) + Send,
182) -> Result<Current, String> {
183    let current = read(repo, state, cancellation, publish).await;
184    // What the scan read is several times what it keeps: give it back, or a long-lived
185    // monitor keeps the largest scan's memory after the scan is gone.
186    crate::platform::release_free_memory();
187    current
188}
189
190async fn read(
191    repo: &Path,
192    state: &Path,
193    cancellation: CancellationToken,
194    mut publish: impl FnMut(Current) + Send,
195) -> Result<Current, String> {
196    // One read of the declarations serves both: the structure depends on them alone.
197    let config = crate::config::read_workspace_config(repo).map_err(|error| error.to_string())?;
198    let structure = graph_structure::extract(&config);
199    // Every step of the scan shows the same declarations: describe them once.
200    let declared = Declared {
201        tree: structure.tree().into(),
202        fingerprint: structure.fingerprint(),
203        structure: &structure,
204    };
205    let (status, cached) = crate::project::scan(
206        config,
207        Some(state),
208        &Selection::All,
209        &VerifyOptions::default(),
210        cancellation,
211        Some(&mut |progress: crate::project::Progress<'_>| {
212            publish(project(
213                &declared,
214                &progress.view,
215                progress.cached,
216                &progress.checking,
217                OffsetDateTime::now_utc(),
218            ));
219        }),
220    )
221    .await?;
222    Ok(project(
223        &declared,
224        &status,
225        &cached,
226        &BTreeSet::new(),
227        OffsetDateTime::now_utc(),
228    ))
229}
230
231/// What running `profile` costs as Execution options name it.
232fn profile(profile: &Profile) -> String {
233    match profile {
234        Profile::Agent { backend, model, .. } => format!("agent · {} · {model}", backend.as_str()),
235        other => other.kind().name().to_owned(),
236    }
237}
238
239fn card(
240    instruction: &str,
241    profile: &Profile,
242    plan: Plan,
243    reused: Option<&Execution>,
244    now: OffsetDateTime,
245) -> Card {
246    let result = reused.and_then(Execution::result);
247    Card {
248        instruction: instruction.to_owned(),
249        result: result.map(model::entries),
250        raw: result.map(model::raw),
251        exit_code: match result {
252            Some(ExecutionResult::Runtime(result)) => result.exit_code.value().copied(),
253            _ => None,
254        },
255        error: None,
256        reused: plan == Plan::Reuse,
257        took: reused
258            .and_then(|execution| model::span(execution.started_at, execution.completed_at(), now)),
259        tokens: reused
260            .and_then(|execution| execution.usage.as_deref())
261            .and_then(model::attempt_tokens),
262        model: match profile {
263            Profile::Agent { model, .. } => Some(model.to_string()),
264            _ => None,
265        },
266    }
267}
268
269/// The declarations a scan read, as every one of its steps shows them.
270struct Declared<'s> {
271    structure: &'s Structure,
272    tree: Arc<str>,
273    fingerprint: Fingerprint,
274}
275
276/// The scan of `declared` as `status` found it, with the claims it found, the evals still
277/// being `checking` marked so.
278fn project(
279    declared: &Declared<'_>,
280    status: &StatusView,
281    cached: &BTreeMap<EvalId, Claim>,
282    checking: &BTreeSet<&EvalId>,
283    now: OffsetDateTime,
284) -> Current {
285    let mut by_target: BTreeMap<&ArtifactName, Vec<&EvalState>> = BTreeMap::new();
286    for eval in &status.evals {
287        by_target.entry(&eval.target).or_default().push(eval);
288    }
289    let mut parts: BTreeMap<&ArtifactName, Vec<ArtifactName>> = BTreeMap::new();
290    for relation in &declared.structure.relations {
291        if relation.kind == graph_structure::Edge::Part {
292            parts
293                .entry(&relation.target)
294                .or_default()
295                .push(relation.source.clone());
296        }
297    }
298    let mut artifacts: Vec<CurrentArtifact> = status
299        .artifacts
300        .iter()
301        .map(|artifact| {
302            let evals: Vec<CurrentEval> =
303                by_target
304                    .get(&artifact.id)
305                    .into_iter()
306                    .flatten()
307                    .map(|eval| {
308                        let plan = if checking.contains(&eval.id) {
309                            Plan::Check
310                        } else {
311                            Plan::from(eval.action)
312                        };
313                        let reused = match cached.get(&eval.id) {
314                            Some(Claim::Reuse(execution)) => Some(&**execution),
315                            _ => None,
316                        };
317                        let instruction = declared
318                            .structure
319                            .evals
320                            .get(&eval.id)
321                            .and_then(|declared| declared.payload.as_ref())
322                            .map_or("", |payload| payload.instruction.as_str());
323                        let mut facts = vec![("Profile", profile(&eval.profile))];
324                        facts.extend(
325                            eval.fingerprint
326                                .as_ref()
327                                .map(|fingerprint| ("Fingerprint", fingerprint.to_string())),
328                        );
329                        facts.push(("Eval", eval.id.to_string()));
330                        facts.push(("Verify would", eval.action.to_string()));
331                        facts.push(("State", eval.state.to_string()));
332                        facts.extend(eval.key.as_ref().map(|key| ("Reuse key", key.to_string())));
333                        facts.push(("Definition hash", eval.eval_def_hash.to_string()));
334                        facts.extend(eval.last.as_ref().map(|last| {
335                            ("Last Run", format!("{} · {}", last.run_id, last.verdict))
336                        }));
337                        if let Some(changes) = &eval.changes {
338                            facts.push(("Changes", changes.summary.clone()));
339                            facts.extend(
340                                changes
341                                    .files
342                                    .as_ref()
343                                    .map(|files| ("Changed files", files.join("\n"))),
344                            );
345                            facts.extend(
346                                changes
347                                    .dependencies
348                                    .as_ref()
349                                    .map(|names| ("Changed dependencies", names.join("\n"))),
350                            );
351                        }
352                        CurrentEval {
353                            id: eval.id.clone(),
354                            name: crate::monitor::model::tree::local(&eval.id).to_owned(),
355                            title: eval.title.clone(),
356                            kind: eval.profile.kind(),
357                            plan,
358                            state: eval.state,
359                            reason: if plan == Plan::Check {
360                                CHECKING.into()
361                            } else {
362                                eval.reason.clone()
363                            },
364                            card: card(instruction, &eval.profile, plan, reused, now),
365                            facts,
366                        }
367                    })
368                    .collect();
369            CurrentArtifact {
370                definition: artifact.definition.clone(),
371                target_missing: artifact.target_missing,
372                name: artifact.id.clone(),
373                kind: artifact.kind,
374                plan: evals
375                    .iter()
376                    .map(|eval| eval.plan)
377                    .min()
378                    .unwrap_or(Plan::Reuse),
379                runs: evals.iter().filter(|eval| eval.plan == Plan::Run).count(),
380                path: artifact.path.clone(),
381                state: artifact.state,
382                reason: artifact.reason.clone(),
383                evals,
384                parts: parts.remove(&artifact.id).unwrap_or_default(),
385            }
386        })
387        .collect();
388    let mut plans: BTreeMap<ArtifactName, Plan> = artifacts
389        .iter()
390        .map(|artifact| (artifact.name.clone(), artifact.plan))
391        .collect();
392    // Without evals of its own, an Artifact does what the first of its parts in plan order
393    // does; parts are acyclic, so passes over the wholes settle.
394    let wholes: Vec<usize> = (0..artifacts.len())
395        .filter(|&at| artifacts[at].evals.is_empty() && !artifacts[at].parts.is_empty())
396        .collect();
397    let mut changed = true;
398    while changed {
399        changed = false;
400        for &at in &wholes {
401            let artifact = &mut artifacts[at];
402            let plan = artifact
403                .parts
404                .iter()
405                .filter_map(|part| plans.get(part).copied())
406                .min()
407                .unwrap_or(Plan::Reuse);
408            if plan != artifact.plan {
409                artifact.plan = plan;
410                plans.insert(artifact.name.clone(), plan);
411                changed = true;
412            }
413        }
414    }
415    let pairs: BTreeSet<(&ArtifactName, &ArtifactName)> = declared
416        .structure
417        .relations
418        .iter()
419        .filter(|relation| {
420            relation.source != relation.target && relation.kind != graph_structure::Edge::Part
421        })
422        .map(|relation| (&relation.source, &relation.target))
423        .collect();
424    let edges = pairs
425        .into_iter()
426        .filter_map(|(from, to)| {
427            Some(CurrentEdge {
428                plan: *plans.get(from)?,
429                from: from.clone(),
430                to: plans.contains_key(to).then(|| to.clone())?,
431            })
432        })
433        .collect();
434    Current {
435        scanned_at: now,
436        fingerprint: declared.fingerprint.clone(),
437        structure: declared.tree.clone(),
438        artifacts,
439        edges,
440    }
441}
442
443#[cfg(test)]
444mod tests;