1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
26pub enum Plan {
27 Run,
29 Check,
32 Blocked,
34 Wait,
36 Reuse,
39}
40
41impl Plan {
42 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 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 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 pub fn text(&self) -> String {
93 match (self.plan, self.runs) {
94 (Plan::Run, 1) => "would run (1 eval)".into(),
95 (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
114const 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#[derive(Debug, Clone)]
119pub struct CurrentEval {
120 pub id: EvalId,
121 pub name: String,
123 pub title: String,
124 pub kind: ProfileKind,
125 pub plan: Plan,
126 pub state: EvalCondition,
127 pub reason: String,
129 pub card: Card,
131 pub facts: Vec<(&'static str, String)>,
133}
134
135#[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 pub runs: usize,
145 pub path: crate::config::Target,
146 pub state: ArtifactCondition,
147 pub reason: String,
148 pub evals: Vec<CurrentEval>,
149 pub parts: Vec<ArtifactName>,
151}
152
153#[derive(Debug, Clone, PartialEq, Eq)]
155pub struct CurrentEdge {
156 pub from: ArtifactName,
157 pub to: ArtifactName,
158 pub plan: Plan,
159}
160
161#[derive(Debug, Clone)]
163pub struct Current {
164 pub scanned_at: OffsetDateTime,
165 pub fingerprint: Fingerprint,
166 pub structure: Arc<str>,
168 pub artifacts: Vec<CurrentArtifact>,
170 pub edges: Vec<CurrentEdge>,
171}
172
173impl Current {
174 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
192pub 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 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 let config = crate::config::read_workspace_config(repo).map_err(|error| error.to_string())?;
217 let structure = graph_structure::extract(&config);
218 let declared = Declared {
220 tree: structure.tree().into(),
221 fingerprint: structure.fingerprint(),
222 structure: &structure,
223 };
224 let (status, cached) = crate::project::scan(
225 config,
226 Some(state),
227 &Selection::All,
228 &VerifyOptions::default(),
229 cancellation,
230 Some(&mut |progress: crate::project::Progress<'_>| {
231 publish(project(
232 &declared,
233 &progress.view,
234 progress.cached,
235 &progress.checking,
236 OffsetDateTime::now_utc(),
237 ));
238 }),
239 )
240 .await?;
241 Ok(project(
242 &declared,
243 &status,
244 &cached,
245 &BTreeSet::new(),
246 OffsetDateTime::now_utc(),
247 ))
248}
249
250fn profile(profile: &Profile) -> String {
252 match profile {
253 Profile::Agent { backend, model, .. } => format!("agent · {} · {model}", backend.as_str()),
254 other => other.kind().name().to_owned(),
255 }
256}
257
258fn card(
259 instruction: &str,
260 profile: &Profile,
261 plan: Plan,
262 reused: Option<&Execution>,
263 now: OffsetDateTime,
264) -> Card {
265 let result = reused.and_then(Execution::result);
266 Card {
267 instruction: instruction.to_owned(),
268 issues: result.map(ExecutionResult::issues),
269 raw: result.map(model::raw),
270 exit_code: result.and_then(ExecutionResult::exit_code),
271 error: None,
272 reused: plan == Plan::Reuse,
273 took: reused
274 .and_then(|execution| model::span(execution.started_at, execution.completed_at(), now)),
275 tokens: reused
276 .and_then(|execution| execution.usage.as_deref())
277 .and_then(model::attempt_tokens),
278 model: match profile {
279 Profile::Agent { model, .. } => Some(model.to_string()),
280 _ => None,
281 },
282 }
283}
284
285struct Declared<'s> {
287 structure: &'s Structure,
288 tree: Arc<str>,
289 fingerprint: Fingerprint,
290}
291
292fn project(
295 declared: &Declared<'_>,
296 status: &StatusView,
297 cached: &BTreeMap<EvalId, Claim>,
298 checking: &BTreeSet<&EvalId>,
299 now: OffsetDateTime,
300) -> Current {
301 let mut by_target: BTreeMap<&ArtifactName, Vec<&EvalState>> = BTreeMap::new();
302 for eval in &status.evals {
303 by_target.entry(&eval.target).or_default().push(eval);
304 }
305 let mut parts: BTreeMap<&ArtifactName, Vec<ArtifactName>> = BTreeMap::new();
306 for relation in &declared.structure.relations {
307 if relation.kind == graph_structure::Edge::Part {
308 parts
309 .entry(&relation.target)
310 .or_default()
311 .push(relation.source.clone());
312 }
313 }
314 let mut artifacts: Vec<CurrentArtifact> = status
315 .artifacts
316 .iter()
317 .map(|artifact| {
318 let evals: Vec<CurrentEval> =
319 by_target
320 .get(&artifact.id)
321 .into_iter()
322 .flatten()
323 .map(|eval| {
324 let plan = if checking.contains(&eval.id) {
325 Plan::Check
326 } else {
327 Plan::from(eval.action)
328 };
329 let reused = match cached.get(&eval.id) {
330 Some(Claim::Reuse(execution)) => Some(&**execution),
331 _ => None,
332 };
333 let instruction = declared
334 .structure
335 .evals
336 .get(&eval.id)
337 .and_then(|declared| declared.instruction.as_deref())
338 .unwrap_or("");
339 let mut facts = vec![("Profile", profile(&eval.profile))];
340 facts.extend(
341 eval.fingerprint
342 .as_ref()
343 .map(|fingerprint| ("Fingerprint", fingerprint.to_string())),
344 );
345 facts.push(("Eval", eval.id.to_string()));
346 facts.push(("Verify would", eval.action.to_string()));
347 facts.push(("State", eval.state.to_string()));
348 facts.extend(eval.key.as_ref().map(|key| ("Reuse key", key.to_string())));
349 facts.push(("Definition hash", eval.eval_def_hash.to_string()));
350 facts.extend(eval.last.as_ref().map(|last| {
351 ("Last Run", format!("{} · {}", last.run_id, last.verdict))
352 }));
353 if let Some(changes) = &eval.changes {
354 facts.push(("Changes", changes.summary.clone()));
355 facts.extend(
356 changes
357 .files
358 .as_ref()
359 .map(|files| ("Changed files", files.join("\n"))),
360 );
361 facts.extend(
362 changes
363 .dependencies
364 .as_ref()
365 .map(|names| ("Changed dependencies", names.join("\n"))),
366 );
367 }
368 CurrentEval {
369 id: eval.id.clone(),
370 name: crate::monitor::model::tree::local(&eval.id).to_owned(),
371 title: eval.title.clone(),
372 kind: eval.profile.kind(),
373 plan,
374 state: eval.state,
375 reason: if plan == Plan::Check {
376 CHECKING.into()
377 } else {
378 eval.reason.clone()
379 },
380 card: card(instruction, &eval.profile, plan, reused, now),
381 facts,
382 }
383 })
384 .collect();
385 CurrentArtifact {
386 definition: artifact.definition.clone(),
387 target_missing: artifact.target_missing,
388 name: artifact.id.clone(),
389 kind: artifact.kind,
390 plan: evals
391 .iter()
392 .map(|eval| eval.plan)
393 .min()
394 .unwrap_or(Plan::Reuse),
395 runs: evals.iter().filter(|eval| eval.plan == Plan::Run).count(),
396 path: artifact.path.clone(),
397 state: artifact.state,
398 reason: artifact.reason.clone(),
399 evals,
400 parts: parts.remove(&artifact.id).unwrap_or_default(),
401 }
402 })
403 .collect();
404 let mut plans: BTreeMap<ArtifactName, Plan> = artifacts
405 .iter()
406 .map(|artifact| (artifact.name.clone(), artifact.plan))
407 .collect();
408 let wholes: Vec<usize> = (0..artifacts.len())
411 .filter(|&at| artifacts[at].evals.is_empty() && !artifacts[at].parts.is_empty())
412 .collect();
413 let mut changed = true;
414 while changed {
415 changed = false;
416 for &at in &wholes {
417 let artifact = &mut artifacts[at];
418 let plan = artifact
419 .parts
420 .iter()
421 .filter_map(|part| plans.get(part).copied())
422 .min()
423 .unwrap_or(Plan::Reuse);
424 if plan != artifact.plan {
425 artifact.plan = plan;
426 plans.insert(artifact.name.clone(), plan);
427 changed = true;
428 }
429 }
430 }
431 let pairs: BTreeSet<(&ArtifactName, &ArtifactName)> = declared
432 .structure
433 .relations
434 .iter()
435 .filter(|relation| {
436 relation.source != relation.target && relation.kind != graph_structure::Edge::Part
437 })
438 .map(|relation| (&relation.source, &relation.target))
439 .collect();
440 let edges = pairs
441 .into_iter()
442 .filter_map(|(from, to)| {
443 Some(CurrentEdge {
444 plan: *plans.get(from)?,
445 from: from.clone(),
446 to: plans.contains_key(to).then(|| to.clone())?,
447 })
448 })
449 .collect();
450 Current {
451 scanned_at: now,
452 fingerprint: declared.fingerprint.clone(),
453 structure: declared.tree.clone(),
454 artifacts,
455 edges,
456 }
457}
458
459#[cfg(test)]
460mod tests;