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 =
217 crate::config::read_workspace_declarations(repo).map_err(|error| error.to_string())?;
218 let structure = graph_structure::extract(&config);
219 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
251fn 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
286struct Declared<'s> {
288 structure: &'s Structure,
289 tree: Arc<str>,
290 fingerprint: Fingerprint,
291}
292
293fn 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 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;