1use crate::{
4 config::{ArtifactKind, Profile, ProfileKind, RepoConfig},
5 monitor::model::{self, Card, Status, Tone},
6 project::{
7 ArtifactCondition, EvalCondition, EvalState, StatusView, VerifyAction, VerifyOptions,
8 selection::Selection,
9 },
10 store::{Claim, Execution, ExecutionResult},
11 types::{ArtifactName, EvalId},
12};
13use std::{
14 collections::{BTreeMap, BTreeSet},
15 path::{Path, PathBuf},
16 sync::Arc,
17};
18use time::OffsetDateTime;
19use tokio_util::sync::CancellationToken;
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
25pub enum Plan {
26 Run,
28 Check,
31 Unchecked,
33 Blocked,
35 Wait,
37 Reuse,
40}
41
42impl Plan {
43 pub fn word(self) -> &'static str {
46 match self {
47 Self::Run => "would run",
48 Self::Check => "checking",
49 Self::Unchecked => "not checked",
50 Self::Blocked => "blocked",
51 Self::Wait => "waiting",
52 Self::Reuse => "reused",
53 }
54 }
55
56 pub fn glyph(self) -> &'static str {
59 match self {
60 Self::Run => "○",
61 Self::Check => "…",
62 Self::Unchecked => "–",
63 Self::Blocked => Status::Blocked.glyph(),
64 Self::Wait => Status::Wait.glyph(),
65 Self::Reuse => "↻",
66 }
67 }
68
69 pub fn tone(self) -> Tone {
70 match self {
71 Self::Run => Tone::Running,
72 Self::Check | Self::Unchecked => Tone::Muted,
73 Self::Blocked => Tone::Blocked,
74 Self::Wait => Tone::Queued,
75 Self::Reuse => Tone::Green,
76 }
77 }
78}
79
80impl CurrentArtifact {
81 pub fn tally(&self) -> Option<model::Tally> {
84 (!self.evals.is_empty() && !matches!(self.plan, Plan::Check | Plan::Unchecked)).then(|| {
85 model::Tally {
86 passed: self
87 .evals
88 .iter()
89 .filter(|eval| eval.plan == Plan::Reuse)
90 .count(),
91 of: self.evals.len(),
92 }
93 })
94 }
95
96 pub fn text(&self) -> String {
98 match (self.plan, self.runs) {
99 (Plan::Run, 1) => "would run (1 eval)".into(),
100 (plan, 0) => plan.word().into(),
102 (Plan::Run, runs) => format!("would run ({runs} evals)"),
103 (plan, _) => plan.word().into(),
104 }
105 }
106}
107
108impl From<VerifyAction> for Plan {
109 fn from(action: VerifyAction) -> Self {
110 match action {
111 VerifyAction::Execute => Self::Run,
112 VerifyAction::Blocked => Self::Blocked,
113 VerifyAction::Wait => Self::Wait,
114 VerifyAction::Reuse => Self::Reuse,
115 }
116 }
117}
118
119const UNCHECKED: &str = "Status has not been requested.";
121
122#[derive(Debug, Clone)]
124pub struct CurrentEval {
125 pub id: EvalId,
126 pub name: String,
128 pub title: String,
129 pub kind: ProfileKind,
130 pub plan: Plan,
131 pub state: EvalCondition,
132 pub reason: String,
134 pub card: Card,
136 pub facts: Vec<(&'static str, String)>,
138 observed_at: Option<OffsetDateTime>,
139}
140
141#[derive(Debug, Clone)]
143pub struct CurrentArtifact {
144 pub definition: PathBuf,
145 pub binding: Option<crate::config::Binding>,
146 pub tools: Option<String>,
147 pub target_missing: bool,
148 pub name: ArtifactName,
149 pub kind: ArtifactKind,
150 pub plan: Plan,
151 pub runs: usize,
153 pub path: crate::config::Target,
154 pub written_path: String,
155 pub state: ArtifactCondition,
156 pub reason: String,
157 pub evals: Vec<CurrentEval>,
158 pub parts: Vec<ArtifactName>,
160}
161
162#[derive(Debug, Clone, PartialEq, Eq)]
164pub struct CurrentEdge {
165 pub from: ArtifactName,
166 pub to: ArtifactName,
167 pub plan: Plan,
168}
169
170#[derive(Debug, Clone)]
172pub struct Current {
173 pub scanned_at: Option<OffsetDateTime>,
174 pub artifacts: Vec<CurrentArtifact>,
176 pub edges: Vec<CurrentEdge>,
177 pub sites: Arc<crate::config::SiteIndex>,
179 pub parents: Arc<BTreeMap<ArtifactName, Vec<ArtifactName>>>,
181 incoming: Arc<BTreeMap<ArtifactName, Vec<usize>>>,
182}
183
184impl Current {
185 pub fn from_shape(
186 mut artifacts: Vec<CurrentArtifact>,
187 mut edges: Vec<CurrentEdge>,
188 sites: Arc<crate::config::SiteIndex>,
189 ) -> Self {
190 artifacts.sort_by(|one, other| one.name.cmp(&other.name));
191 edges.sort_by(|one, other| (&one.from, &one.to).cmp(&(&other.from, &other.to)));
192 let mut parents: BTreeMap<_, Vec<_>> = BTreeMap::new();
193 for whole in &artifacts {
194 for part in &whole.parts {
195 parents
196 .entry(part.clone())
197 .or_default()
198 .push(whole.name.clone());
199 }
200 }
201 let mut incoming: BTreeMap<_, Vec<_>> = BTreeMap::new();
202 for (index, edge) in edges.iter().enumerate() {
203 incoming.entry(edge.to.clone()).or_default().push(index);
204 }
205 Self {
206 scanned_at: None,
207 artifacts,
208 edges,
209 sites,
210 parents: Arc::new(parents),
211 incoming: Arc::new(incoming),
212 }
213 }
214
215 pub fn adjacent(&self, name: &ArtifactName) -> (Vec<&CurrentEdge>, Vec<&CurrentEdge>) {
217 let incoming = self
218 .incoming
219 .get(name)
220 .into_iter()
221 .flatten()
222 .map(|&at| &self.edges[at])
223 .collect();
224 let start = self.edges.partition_point(|edge| &edge.from < name);
225 let outgoing = self.edges[start..]
226 .iter()
227 .take_while(|edge| &edge.from == name)
228 .collect();
229 (incoming, outgoing)
230 }
231
232 pub fn copies(&self, name: &ArtifactName) -> u32 {
234 fn count<'a>(
235 current: &'a Current,
236 name: &'a ArtifactName,
237 memo: &mut BTreeMap<&'a ArtifactName, u32>,
238 ) -> u32 {
239 if let Some(copies) = memo.get(name) {
240 return *copies;
241 }
242 let copies = current.parents.get(name).map_or(1, |parents| {
243 parents.iter().fold(0u32, |total, parent| {
244 total.saturating_add(count(current, parent, memo))
245 })
246 });
247 memo.insert(name, copies);
248 copies
249 }
250 count(self, name, &mut BTreeMap::new())
251 }
252
253 pub fn same_shape(&self, other: &Self) -> bool {
256 self.artifacts
257 .iter()
258 .map(|artifact| (&artifact.name, &artifact.parts))
259 .eq(other
260 .artifacts
261 .iter()
262 .map(|artifact| (&artifact.name, &artifact.parts)))
263 && self
264 .edges
265 .iter()
266 .map(|edge| (&edge.from, &edge.to))
267 .eq(other.edges.iter().map(|edge| (&edge.from, &edge.to)))
268 }
269}
270
271pub fn outline(repo: &Path) -> Result<Current, String> {
273 let outline = crate::config::read_workspace_declarations(repo)
274 .map(|config| declared(&config))
275 .map_err(|error| error.to_string());
276 crate::platform::release_free_memory();
277 outline
278}
279
280pub async fn scan(
283 repo: &Path,
284 state: &Path,
285 cancellation: CancellationToken,
286 mut publish: impl FnMut(Current) + Send,
287) -> Result<Current, String> {
288 let result = async {
289 let config = read_config(repo, &Selection::All, None).await?;
290 let mut current = declared(&config);
291 for artifact in &mut current.artifacts {
292 artifact.plan = Plan::Check;
293 artifact.reason = "Waiting for the requested status check.".into();
294 for eval in &mut artifact.evals {
295 eval.plan = Plan::Check;
296 eval.reason.clone_from(&artifact.reason);
297 }
298 }
299 for edge in &mut current.edges {
300 edge.plan = Plan::Check;
301 }
302 publish(current.clone());
303 let current = scan_config(
304 config,
305 current,
306 state,
307 &Selection::All,
308 cancellation,
309 |_| {},
310 )
311 .await?;
312 publish(current.clone());
313 Ok(current)
314 }
315 .await;
316 crate::platform::release_free_memory();
317 result
318}
319
320pub async fn scan_scope(
322 repo: &Path,
323 state: &Path,
324 selection: &Selection,
325 sites: Option<Arc<crate::config::SiteIndex>>,
326 cancellation: CancellationToken,
327 progress: impl FnMut(usize) + Send,
328) -> Result<Current, String> {
329 let result = async {
330 let config = read_config(repo, selection, sites).await?;
331 let current = declared(&config);
332 scan_config(config, current, state, selection, cancellation, progress).await
333 }
334 .await;
335 crate::platform::release_free_memory();
336 result
337}
338
339async fn read_config(
340 repo: &Path,
341 selection: &Selection,
342 sites: Option<Arc<crate::config::SiteIndex>>,
343) -> Result<RepoConfig, String> {
344 let repo = repo.to_path_buf();
345 let indexed = sites.zip(selection.roots());
346 crate::task::blocking(move || {
347 let scoped = indexed.and_then(|(sites, names)| {
348 sites
349 .subset(
350 &repo,
351 names,
352 crate::config::Evals::All,
353 &crate::config::lang::process_environment,
354 )
355 .ok()
356 });
357 scoped.map_or_else(|| crate::config::read_workspace_declarations(&repo), Ok)
358 })
359 .await?
360 .map_err(|error| error.to_string())
361}
362
363async fn scan_config(
364 config: RepoConfig,
365 mut current: Current,
366 state: &Path,
367 selection: &Selection,
368 cancellation: CancellationToken,
369 mut progress: impl FnMut(usize) + Send,
370) -> Result<Current, String> {
371 let (status, cached) = crate::project::scan(
372 config,
373 Some(state),
374 selection,
375 &VerifyOptions::default(),
376 cancellation,
377 Some(&mut progress),
378 )
379 .await?;
380 current.apply_status(&status, &cached);
381 Ok(current)
382}
383
384fn declared(config: &RepoConfig) -> Current {
385 let mut evals: BTreeMap<&ArtifactName, Vec<CurrentEval>> = BTreeMap::new();
386 let now = OffsetDateTime::now_utc();
387 for eval in &config.evals {
388 let profile = eval.declaration.profile();
389 evals.entry(&eval.target).or_default().push(CurrentEval {
390 id: eval.id.clone(),
391 name: crate::monitor::model::tree::local(&eval.id).into(),
392 title: eval.declaration.title.clone(),
393 kind: profile.kind(),
394 plan: Plan::Unchecked,
395 state: EvalCondition::Unreviewed,
396 reason: UNCHECKED.into(),
397 card: card(
398 crate::scope::Instruction::declared(config, eval),
399 profile,
400 Plan::Unchecked,
401 None,
402 now,
403 ),
404 facts: vec![("Profile", self::profile(profile))],
405 observed_at: None,
406 });
407 }
408 let artifacts = config
409 .artifacts
410 .values()
411 .map(|artifact| CurrentArtifact {
412 definition: artifact.definition.clone(),
413 binding: artifact.binding.clone(),
414 tools: artifact.tools.clone(),
415 target_missing: artifact.target_error.is_some(),
416 name: artifact.name.clone(),
417 kind: artifact.kind(),
418 plan: Plan::Unchecked,
419 runs: 0,
420 path: artifact.path.clone(),
421 written_path: artifact.written_path(),
422 state: ArtifactCondition::Unreviewed,
423 reason: UNCHECKED.into(),
424 evals: evals.remove(&artifact.name).unwrap_or_default(),
425 parts: artifact.parts.iter().cloned().collect(),
426 })
427 .collect();
428 let edges = config
429 .relations
430 .iter()
431 .filter(|rel| rel.source != rel.target && rel.kind != crate::scope::RelationKind::Part)
432 .map(|rel| (&rel.source, &rel.target))
433 .collect::<BTreeSet<_>>()
434 .into_iter()
435 .map(|(from, to)| CurrentEdge {
436 from: from.clone(),
437 to: to.clone(),
438 plan: Plan::Unchecked,
439 })
440 .collect();
441 Current::from_shape(
442 artifacts,
443 edges,
444 Arc::new(crate::config::SiteIndex::new(config)),
445 )
446}
447
448fn profile(profile: &Profile) -> String {
450 match profile {
451 Profile::Agent { backend, model, .. } => format!("agent · {} · {model}", backend.as_str()),
452 other => other.kind().name().to_owned(),
453 }
454}
455
456fn card(
457 instruction: crate::scope::Instruction,
458 profile: &Profile,
459 plan: Plan,
460 reused: Option<&Execution>,
461 now: OffsetDateTime,
462) -> Card {
463 let result = reused.and_then(Execution::result);
464 Card {
465 instruction,
466 issues: result.map(ExecutionResult::issues),
467 raw: result.map(model::raw),
468 exit_code: result.and_then(ExecutionResult::exit_code),
469 error: None,
470 reused: plan == Plan::Reuse,
471 took: reused
472 .and_then(|execution| model::span(execution.started_at, execution.completed_at(), now)),
473 tokens: reused
474 .and_then(|execution| execution.usage.as_deref())
475 .and_then(model::attempt_tokens),
476 model: match profile {
477 Profile::Agent { model, .. } => Some(model.to_string()),
478 _ => None,
479 },
480 }
481}
482
483pub struct CurrentRun(Vec<crate::store::Request>);
485
486pub async fn current_run(
487 state: &Path,
488 place: &super::Place,
489 run: &crate::types::RunId,
490) -> Result<CurrentRun, String> {
491 let (repo, identity) = crate::store::run_checkout(state, run).await?;
492 if super::Place::for_checkout(&repo, &identity) != *place {
493 return Err("Run belongs to a different checkout.".into());
494 }
495 crate::store::read_run_requests_only(state, run)
496 .await
497 .map(CurrentRun)
498}
499
500impl Current {
501 pub fn artifact(&self, name: &ArtifactName) -> Option<&CurrentArtifact> {
502 let at = self
503 .artifacts
504 .binary_search_by(|node| node.name.cmp(name))
505 .ok()?;
506 Some(&self.artifacts[at])
507 }
508
509 fn artifact_mut(&mut self, name: &ArtifactName) -> Option<&mut CurrentArtifact> {
510 let at = self
511 .artifacts
512 .binary_search_by(|node| node.name.cmp(name))
513 .ok()?;
514 Some(&mut self.artifacts[at])
515 }
516
517 fn apply_status(&mut self, status: &StatusView, cached: &BTreeMap<EvalId, Claim>) {
518 let now = OffsetDateTime::now_utc();
519 for artifact in &status.artifacts {
520 if let Some(node) = self.artifact_mut(&artifact.id) {
521 node.target_missing = artifact.target_missing;
522 node.state = artifact.state;
523 node.reason.clone_from(&artifact.reason);
524 node.plan = Plan::Reuse;
525 }
526 }
527 for eval in &status.evals {
528 if let Some(node) = self.artifact_mut(&eval.target)
529 && let Some(found) = node.evals.iter_mut().find(|item| item.id == eval.id)
530 {
531 forecast(found, eval, cached.get(&eval.id), now);
532 }
533 }
534 self.scanned_at = Some(now);
535 self.relight(
536 status
537 .artifacts
538 .iter()
539 .map(|artifact| artifact.id.clone())
540 .collect(),
541 );
542 }
543
544 pub fn merge_scope(&mut self, scoped: Current) {
546 let mut changed = BTreeSet::new();
547 for node in scoped
548 .artifacts
549 .into_iter()
550 .filter(|node| node.plan != Plan::Unchecked)
551 {
552 if let Some(old) = self.artifact_mut(&node.name)
553 && old.parts == node.parts
554 && old
555 .evals
556 .iter()
557 .map(|e| &e.id)
558 .eq(node.evals.iter().map(|e| &e.id))
559 {
560 changed.insert(node.name.clone());
561 *old = node;
562 }
563 }
564 self.relight(changed);
565 }
566
567 pub fn apply_run(&mut self, run: CurrentRun) -> bool {
569 use crate::types::RequestStatus;
570 let mut changed = BTreeSet::new();
571 for request in &run.0 {
572 let completed = if request.key.is_some() {
573 Plan::Reuse
574 } else {
575 Plan::Run
576 };
577 let (plan, state) = match request.status() {
578 RequestStatus::Green => (completed, EvalCondition::Pass),
579 RequestStatus::Red => (completed, EvalCondition::Red),
580 RequestStatus::Error => (Plan::Run, EvalCondition::Error),
581 RequestStatus::Deferred => (Plan::Wait, EvalCondition::Deferred),
582 RequestStatus::WaitingHuman => (Plan::Wait, EvalCondition::WaitingHuman),
583 RequestStatus::Blocked => (Plan::Blocked, EvalCondition::Blocked),
584 _ => continue,
585 };
586 let Some(node) = self.artifact_mut(&request.target) else {
587 continue;
588 };
589 let Some(eval) = node
590 .evals
591 .iter_mut()
592 .find(|eval| eval.id == request.eval_id)
593 else {
594 continue;
595 };
596 let observed = request.completed_at().unwrap_or(request.created_at).time();
597 if eval
598 .observed_at
599 .is_some_and(|previous| previous >= observed)
600 {
601 continue;
602 }
603 eval.observed_at = Some(observed);
604 eval.plan = plan;
605 eval.state = state;
606 eval.reason = format!(
607 "As recorded by {}. Check status for changes since that Run.",
608 request.run_id
609 );
610 eval.facts
611 .retain(|(name, _)| *name == "Profile" || *name == "Eval");
612 if let Some(key) = &request.key {
613 eval.facts.push(("Reuse key", key.to_string()));
614 }
615 if let Some(fingerprint) = &request.fingerprint {
616 eval.facts.push(("Fingerprint", fingerprint.to_string()));
617 }
618 eval.facts.push(("Last Run", request.run_id.to_string()));
619 let result = request.result();
620 eval.card.issues = result.map(ExecutionResult::issues);
621 eval.card.raw = result.map(model::raw);
622 eval.card.exit_code = result.and_then(ExecutionResult::exit_code);
623 eval.card.error = request.error().map(str::to_owned);
624 eval.card.took = None;
625 eval.card.tokens = None;
626 eval.card.reused = plan == Plan::Reuse;
627 node.reason.clone_from(&eval.reason);
628 changed.insert(request.target.clone());
629 }
630 let any = !changed.is_empty();
631 self.relight(changed);
632 any
633 }
634
635 fn relight(&mut self, mut affected: BTreeSet<ArtifactName>) {
636 let mut work: Vec<_> = affected.iter().cloned().collect();
637 while let Some(part) = work.pop() {
638 for whole in self.parents.get(&part).into_iter().flatten() {
639 if self
640 .artifact(whole)
641 .is_some_and(|node| node.evals.is_empty())
642 && affected.insert(whole.clone())
643 {
644 work.push(whole.clone());
645 }
646 }
647 }
648 let mut plans = BTreeMap::new();
649 let mut pending = Vec::new();
650 for node in affected.iter().filter_map(|name| self.artifact(name)) {
651 pending.push((node, false));
652 while let Some((item, ready)) = pending.pop() {
653 if plans.contains_key(&item.name) {
654 continue;
655 }
656 let plan = if !item.evals.is_empty() {
657 item.evals
658 .iter()
659 .map(|eval| eval.plan)
660 .min()
661 .expect("nonempty evals")
662 } else if item.parts.is_empty() {
663 item.plan
664 } else if ready {
665 item.parts
666 .iter()
667 .filter_map(|part| {
668 plans
669 .get(part)
670 .copied()
671 .or_else(|| self.artifact(part).map(|part| part.plan))
672 })
673 .min()
674 .unwrap_or(item.plan)
675 } else {
676 pending.push((item, true));
677 pending.extend(
678 item.parts
679 .iter()
680 .filter(|part| affected.contains(*part))
681 .filter_map(|part| self.artifact(part))
682 .map(|part| (part, false)),
683 );
684 continue;
685 };
686 plans.insert(&item.name, plan);
687 }
688 }
689 let plans: BTreeMap<_, _> = plans
690 .into_iter()
691 .map(|(name, plan)| (name.clone(), plan))
692 .collect();
693 for (name, plan) in plans {
694 if let Some(node) = self.artifact_mut(&name) {
695 node.plan = plan;
696 node.runs = node
697 .evals
698 .iter()
699 .filter(|eval| eval.plan == Plan::Run)
700 .count();
701 }
702 let start = self.edges.partition_point(|edge| edge.from < name);
704 for edge in self.edges[start..]
705 .iter_mut()
706 .take_while(|edge| edge.from == name)
707 {
708 edge.plan = plan;
709 }
710 }
711 }
712}
713
714fn forecast(
715 found: &mut CurrentEval,
716 eval: &EvalState,
717 cached: Option<&Claim>,
718 now: OffsetDateTime,
719) {
720 let plan = Plan::from(eval.action);
721 let reused = match cached {
722 Some(Claim::Reuse(execution)) => Some(&**execution),
723 _ => None,
724 };
725 let mut facts = vec![("Profile", profile(&eval.profile))];
726 facts.extend(
727 eval.fingerprint
728 .as_ref()
729 .map(|hash| ("Fingerprint", hash.to_string())),
730 );
731 facts.push(("Eval", eval.id.to_string()));
732 facts.push(("Verify would", eval.action.to_string()));
733 facts.push(("State", eval.state.to_string()));
734 facts.extend(eval.key.as_ref().map(|key| ("Reuse key", key.to_string())));
735 facts.push(("Definition hash", eval.eval_def_hash.to_string()));
736 facts.extend(
737 eval.last
738 .as_ref()
739 .map(|last| ("Last Run", format!("{} · {}", last.run_id, last.verdict))),
740 );
741 if let Some(changes) = &eval.changes {
742 facts.push(("Changes", changes.summary.clone()));
743 facts.extend(
744 changes
745 .files
746 .as_ref()
747 .map(|files| ("Changed files", files.join("\n"))),
748 );
749 facts.extend(
750 changes
751 .dependencies
752 .as_ref()
753 .map(|names| ("Changed dependencies", names.join("\n"))),
754 );
755 }
756 found.plan = plan;
757 found.observed_at = Some(now);
758 found.state = eval.state;
759 found.reason.clone_from(&eval.reason);
760 let instruction = std::mem::take(&mut found.card.instruction);
761 found.card = card(instruction, &eval.profile, plan, reused, now);
762 found.facts = facts;
763}
764
765#[cfg(test)]
766mod tests;