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 name: ArtifactName,
139 pub kind: ArtifactKind,
140 pub plan: Plan,
141 pub runs: usize,
143 pub path: PathBuf,
144 pub state: ArtifactCondition,
145 pub reason: String,
146 pub evals: Vec<CurrentEval>,
147 pub parts: Vec<ArtifactName>,
149}
150
151#[derive(Debug, Clone, PartialEq, Eq)]
153pub struct CurrentEdge {
154 pub from: ArtifactName,
155 pub to: ArtifactName,
156 pub plan: Plan,
157}
158
159#[derive(Debug, Clone)]
161pub struct Current {
162 pub scanned_at: OffsetDateTime,
163 pub fingerprint: Fingerprint,
164 pub structure: Arc<str>,
166 pub artifacts: Vec<CurrentArtifact>,
168 pub edges: Vec<CurrentEdge>,
169}
170
171pub 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 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 let config = crate::config::read_workspace_config(repo).map_err(|error| error.to_string())?;
196 let structure = graph_structure::extract(&config);
197 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
229fn 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
266struct Declared<'s> {
268 structure: &'s Structure,
269 tree: Arc<str>,
270 fingerprint: Fingerprint,
271}
272
273fn 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 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;