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