1mod graph;
3pub use graph::{Graph, GraphEdge, GraphNode, Light, graph};
4mod node_id;
5pub use node_id::NodeId;
6mod states;
7mod status;
8#[cfg(test)]
9mod tests;
10pub(crate) mod tree;
11pub use states::{Activity, Busy, Completion, EvalView, NotRun, Queue, Source, Upstream, Waits};
12pub use status::Status;
13pub use tree::{Clock, Kind, Node, Segment, Tally, Tone, Weight, completion, tree, upstream_index};
14
15use serde_json::Value;
16use time::OffsetDateTime;
17
18use crate::{
19 query,
20 store::{RequestView, RunSummary, RunView},
21 types::{ArtifactName, EvalId},
22};
23
24#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
26pub enum Target {
27 Run,
29 Artifact(crate::types::ArtifactName),
30 Eval(crate::types::EvalId),
31}
32
33impl Target {
34 pub fn parse(id: &str) -> Option<Self> {
35 let (kind, name) = id.split_once(':')?;
36 match kind {
37 "run" => name.parse::<crate::types::RunId>().ok().map(|_| Self::Run),
38 "a" => name.parse().ok().map(Self::Artifact),
39 "e" => name.parse().ok().map(Self::Eval),
40 _ => None,
41 }
42 }
43}
44
45#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
47pub enum Section {
48 Outcome,
49 Waits,
51 What,
52 Provenance,
53 Technical,
54}
55
56impl Section {
57 pub const ALL: [Self; 5] = [
58 Self::Outcome,
59 Self::Waits,
60 Self::What,
61 Self::Provenance,
62 Self::Technical,
63 ];
64
65 pub fn of(key: &str) -> Self {
67 match key {
68 "Status" | "Error" | "Reason" | "Blocked by" | "Result" | "Claim" | "Source"
69 | "At Run end" | "Validation" | "Counts" | "Errors" | "Waiting" | "Running"
70 | "Evals" | "Gates" => Self::Outcome,
71 "Waits for" => Self::Waits,
72 "Timing" | "Usage" | "Budget" | "Work" | "Saved usage" => Self::Provenance,
73 "Execution" | "Fingerprint" | "Key" | "Key covers" | "Path" | "Tags" | "Cycle"
74 | "Run" | "Repository" => Self::Technical,
75 _ => Self::What,
76 }
77 }
78
79 pub fn name(self) -> &'static str {
80 match self {
81 Self::Outcome => "Outcome",
82 Self::Waits => "Waits for",
83 Self::What => "What",
84 Self::Provenance => "Provenance",
85 Self::Technical => "Technical",
86 }
87 }
88}
89
90#[derive(Debug, Clone, PartialEq, Eq)]
91pub struct RunRow {
92 pub id: crate::types::RunId,
93 pub repo: std::path::PathBuf,
94 pub status: crate::types::RunStatus,
95 pub counts: String,
97 pub age: String,
98 pub took: String,
100 pub comment: String,
102}
103
104#[derive(Debug, Clone)]
105pub struct Progress {
106 pub status: Status,
107 pub repo: String,
108 pub comment: Option<String>,
110 pub validation: String,
111 pub timing: String,
112 pub elapsed: String,
114 pub finished: bool,
115 pub satisfied: Option<bool>,
117 pub counts: Vec<(Status, u64)>,
118 pub budget: String,
120 pub work: String,
122 pub usage: String,
124 pub saved: String,
125 pub tokens: Option<u64>,
127 pub running: Vec<(String, String)>,
129 pub waiting: Vec<(String, String)>,
131 pub errors: Vec<(String, String)>,
133 pub needs: Vec<(Status, String)>,
136}
137
138#[derive(Debug, Clone, PartialEq, Eq)]
140pub struct Strip {
141 pub status: Status,
142 pub headline: String,
143 pub attention: Vec<(Status, String)>,
145 pub more: usize,
147}
148
149#[derive(Debug, Clone, Default)]
150pub struct Detail {
151 pub title: String,
152 pub summary: String,
154 pub fields: Vec<(&'static str, String)>,
155}
156
157impl Detail {
158 pub fn field(&self, name: &str) -> Option<&str> {
159 self.fields
160 .iter()
161 .find(|(key, _)| *key == name)
162 .map(|(_, value)| value.as_str())
163 }
164
165 fn push(&mut self, key: &'static str, value: impl Into<String>) {
166 let value = value.into();
167 if !value.is_empty() {
168 self.fields.push((key, value));
169 }
170 }
171
172 fn insert_after(&mut self, after: &str, key: &'static str, value: String) {
173 if value.is_empty() {
174 return;
175 }
176 let index = self.fields.iter().position(|(name, _)| *name == after);
177 let index = index.map_or(self.fields.len(), |index| index + 1);
178 self.fields.insert(index, (key, value));
179 }
180}
181
182const ATTENTION_LINES: usize = 3;
184
185const ABSENT: &str = "not in Run";
186
187pub fn glyph(status: Option<Status>) -> &'static str {
189 status.map_or("-", Status::glyph)
190}
191
192fn join<T: AsRef<str>>(items: impl IntoIterator<Item = T>, separator: &str) -> String {
193 let items: Vec<_> = items
194 .into_iter()
195 .map(|item| item.as_ref().to_owned())
196 .collect();
197 items.join(separator)
198}
199
200fn mark(name: &EvalId, status: Option<Status>) -> String {
201 format!(
202 "{} {name} {}",
203 glyph(status),
204 status.map_or(ABSENT, Status::as_str)
205 )
206}
207
208const MINUTE: i64 = 60;
210const HOUR: i64 = 60 * MINUTE;
211const DAY: i64 = 24 * HOUR;
212
213pub fn duration(elapsed: time::Duration) -> String {
214 let seconds = elapsed.whole_seconds().max(0);
215 match seconds {
216 0..MINUTE => format!("{seconds}s"),
217 MINUTE..HOUR => format!("{}m {:02}s", seconds / MINUTE, seconds % MINUTE),
218 HOUR..DAY => format!("{}h {:02}m", seconds / HOUR, seconds % HOUR / MINUTE),
219 _ => format!("{}d {}h", seconds / DAY, seconds % DAY / HOUR),
220 }
221}
222
223#[cfg(test)]
224#[test]
225fn typed_durations_keep_the_display_units_and_clamp_clock_skew() {
226 for (elapsed, expected) in [
227 (time::Duration::seconds(-1), "0s"),
228 (time::Duration::ZERO, "0s"),
229 (time::Duration::milliseconds(59_999), "59s"),
230 (time::Duration::minutes(1), "1m 00s"),
231 (time::Duration::seconds(125), "2m 05s"),
232 (time::Duration::hours(1), "1h 00m"),
233 (time::Duration::minutes(61), "1h 01m"),
234 (time::Duration::days(1), "1d 0h"),
235 (time::Duration::hours(25), "1d 1h"),
236 ] {
237 assert_eq!(duration(elapsed), expected);
238 }
239}
240
241pub(crate) fn attempt_tokens(attempts: &[crate::llm::Attempt]) -> Option<u64> {
244 let tokens = attempts
245 .iter()
246 .filter_map(|attempt| attempt.usage.get("totalTokens"))
247 .fold(0u64, |total, tokens| total.saturating_add(*tokens));
248 (tokens > 0).then_some(tokens)
249}
250
251#[test]
252fn attempt_tokens_saturate_on_saved_counts() {
253 let attempt = |tokens: u64| -> crate::llm::Attempt {
254 serde_json::from_value(serde_json::json!({ "usage": { "totalTokens": tokens } }))
255 .expect("a saved attempt")
256 };
257 assert_eq!(attempt_tokens(&[]), None);
258 assert_eq!(attempt_tokens(&[attempt(0)]), None);
259 assert_eq!(attempt_tokens(&[attempt(14), attempt(8)]), Some(22));
260 assert_eq!(
261 attempt_tokens(&[attempt(u64::MAX), attempt(1)]),
262 Some(u64::MAX)
263 );
264}
265
266pub(crate) fn span(
268 start: crate::types::Timestamp,
269 end: Option<crate::types::Timestamp>,
270 now: OffsetDateTime,
271) -> Option<String> {
272 let end = end.map_or(now, crate::types::Timestamp::time);
273 Some(duration(end - start.time()))
274}
275
276pub fn counts(counts: impl IntoIterator<Item = (Status, u64)>) -> String {
278 let mut counts: Vec<_> = counts.into_iter().filter(|(_, n)| *n > 0).collect();
279 counts.sort_by_key(|(status, _)| *status);
280 join(
281 counts
282 .into_iter()
283 .map(|(status, n)| format!("{}{n}", status.glyph())),
284 " ",
285 )
286}
287
288pub fn tokens(total: u64) -> String {
290 const THOUSAND: u64 = 1_000;
292 const MILLION: u64 = 1_000_000;
293 match total {
294 0..THOUSAND => total.to_string(),
295 THOUSAND..MILLION => format!("{:.1}k", total as f64 / THOUSAND as f64),
296 _ => format!("{:.1}M", total as f64 / MILLION as f64),
297 }
298}
299
300pub fn run_rows(runs: &[RunSummary], now: OffsetDateTime) -> Vec<RunRow> {
301 runs.iter()
302 .map(|run| RunRow {
303 id: run.id.clone(),
304 repo: run.repo_path.clone(),
305 status: run.status,
306 counts: counts(run.counts.iter().map(|(status, n)| ((*status).into(), *n))),
307 age: span(run.created_at, None, now).unwrap_or_default(),
308 took: run
309 .completed_at
310 .and_then(|end| span(run.created_at, Some(end), now))
311 .unwrap_or_default(),
312 comment: run.comment.as_deref().unwrap_or_default().to_owned(),
313 })
314 .collect()
315}
316
317fn reused(view: &RequestView) -> bool {
318 query::reused(&view.request)
319}
320
321fn elapsed(view: &RequestView, now: OffsetDateTime) -> Option<String> {
322 let request = &view.request;
323 if reused(view) {
324 return Some("reused".into());
325 }
326 let active = matches!(
327 request.status(),
328 crate::types::RequestStatus::Running
329 | crate::types::RequestStatus::WaitingHuman
330 | crate::types::RequestStatus::Deferred
331 );
332 let start = request
333 .started_at
334 .or(active.then_some(request.created_at))?;
335 span(start, request.completed_at(), now)
336}
337
338fn claim(view: &RequestView) -> String {
339 view.claim.as_ref().map_or("unclaimed".into(), |claim| {
340 format!("claimed by {} at {}", claim.reviewer, claim.claimed_at)
341 })
342}
343
344fn error(view: &RequestView) -> Option<String> {
345 let request = &view.request;
346 let error = request.error().map(str::to_owned)?;
347 Some(match &request.error_code() {
348 Some(code) => format!("[{code}] {error}"),
349 None => error,
350 })
351}
352
353pub fn progress(view: &RunView, requests: &[RequestView], now: OffsetDateTime) -> Progress {
354 let run = &view.run;
355 let (summary, saved_usage) = query::run_summary(view, now);
356 let with = |status: crate::types::RequestStatus| {
357 requests
358 .iter()
359 .filter(move |view| view.request.status() == status)
360 };
361 let usage = counter_pairs(&summary.usage.usage);
362 let saved = counter_pairs(&saved_usage);
363 let spent = &summary.usage.usage;
364 let tokens = spent.get("totalTokens").copied().or_else(|| {
365 let input = spent.get("inputTokens").copied();
366 let output = spent.get("outputTokens").copied();
367 (input.is_some() || output.is_some())
368 .then(|| input.unwrap_or(0).saturating_add(output.unwrap_or(0)))
369 });
370 let validation = run.validation.snapshot();
371 let unmet = validation
372 .and_then(|v| v.obligations.value())
373 .map(|ids| {
374 ids.iter()
375 .map(ToString::to_string)
376 .collect::<Vec<_>>()
377 .join(", ")
378 })
379 .unwrap_or_default();
380 let wall = span(run.created_at, run.completed_at(), now).unwrap_or_default();
381 Progress {
382 status: run.status().into(),
383 repo: crate::platform::path_text(&run.repo_path),
384 comment: run.comment.as_ref().map(ToString::to_string),
385 validation: match validation.and_then(|v| v.satisfied.value()) {
387 None => "pending".into(),
388 Some(true) => "SATISFIED at Run end".into(),
389 Some(_) if unmet.is_empty() => "NOT SATISFIED at Run end".into(),
390 Some(_) => format!("NOT SATISFIED at Run end (unmet: {unmet})"),
391 },
392 timing: format!(
393 "started {} · {} {wall}",
394 run.created_at,
395 if run.completed_at().is_some() {
396 "took"
397 } else {
398 "elapsed"
399 },
400 ),
401 elapsed: wall,
402 finished: run.completed_at().is_some(),
403 satisfied: validation.and_then(|v| v.satisfied.value()).copied(),
404 counts: summary
405 .counts
406 .iter()
407 .map(|(status, count)| ((*status).into(), *count))
408 .collect(),
409 budget: format!(
410 "executions {}/{} · jobs {}",
411 run.executions_started,
412 run.max_executions
413 .map_or("unlimited".into(), |max| max.to_string()),
414 run.jobs
415 .map_or("unlimited".into(), |limit| limit.to_string()),
416 ),
417 work: format!(
418 "executed {} · reused {}",
419 summary.executed.total, summary.reused.kinds.total,
420 ),
421 usage,
422 saved,
423 tokens,
424 running: with(crate::types::RequestStatus::Running)
425 .map(|view| {
426 (
427 view.request.eval_id.to_string(),
428 elapsed(view, now).unwrap_or_default(),
429 )
430 })
431 .collect(),
432 waiting: requests
433 .iter()
434 .filter(|view| view.request.status().is_human_wait())
435 .map(|view| (view.request.eval_id.to_string(), claim(view)))
436 .collect(),
437 errors: with(crate::types::RequestStatus::Error)
438 .map(|view| {
439 (
440 view.request.eval_id.to_string(),
441 error(view).unwrap_or_default(),
442 )
443 })
444 .chain(
445 run.error()
446 .map(str::to_owned)
447 .map(|error| ("Run".into(), error)),
448 )
449 .chain(
450 view.unreadable
451 .iter()
452 .map(|record| (record.id.clone(), record.to_string())),
453 )
454 .collect(),
455 needs: with(crate::types::RequestStatus::Red)
456 .chain(with(crate::types::RequestStatus::Error))
457 .chain(
458 requests
459 .iter()
460 .filter(|view| view.request.status().is_human_wait()),
461 )
462 .map(|view| {
463 (
464 Status::from(view.request.status()),
465 view.request.eval_id.to_string(),
466 )
467 })
468 .collect(),
469 }
470}
471
472pub fn strip(progress: &Progress) -> Strip {
474 let validation = match progress.satisfied {
475 None => "validation pending".to_owned(),
476 Some(true) => "SATISFIED at Run end".to_owned(),
477 Some(false) => "NOT SATISFIED at Run end".to_owned(),
478 };
479 let counts = counts(progress.counts.iter().copied());
480 let time = format!(
481 "{} {}",
482 if progress.finished { "took" } else { "elapsed" },
483 progress.elapsed
484 );
485 let tokens = progress
486 .tokens
487 .map(|total| format!("tokens {}", tokens(total)));
488 let headline = join(
489 [Some(validation), Some(counts), Some(time), tokens]
490 .into_iter()
491 .flatten()
492 .filter(|part| !part.is_empty()),
493 " · ",
494 );
495 let mut attention: Vec<(Status, String)> = progress
496 .errors
497 .iter()
498 .map(|(eval, error)| (Status::Error, format!("{eval} {error}")))
499 .chain(progress.waiting.iter().map(|(eval, claim)| {
500 (
501 Status::WaitingHuman,
502 format!("{eval} waiting Human · {claim}"),
503 )
504 }))
505 .chain(progress.running.iter().map(|(eval, time)| {
506 (
507 Status::Running,
508 format!("{eval} running {time}").trim_end().to_owned(),
509 )
510 }))
511 .collect();
512 let more = attention.len().saturating_sub(ATTENTION_LINES);
513 attention.truncate(ATTENTION_LINES);
514 Strip {
515 status: progress.status,
516 headline,
517 attention,
518 more,
519 }
520}
521
522pub fn run_node(run: &RunView) -> Node {
524 let status = Status::from(run.run.status());
525 Node {
526 id: NodeId::run(&run.run.id),
527 clock: None,
528 kind: Kind::Artifact {
529 completion: Completion::Complete,
530 basis: false,
531 },
532 glyph: status.glyph(),
533 tone: match status {
534 Status::Green => Tone::Green,
535 Status::Red => Tone::Red,
536 Status::Error => Tone::Error,
537 Status::Running => Tone::Running,
538 Status::Blocked | Status::BudgetExhausted | Status::Incomplete => Tone::Blocked,
539 _ => Tone::Muted,
540 },
541 weight: Weight::Normal,
542 name: "Run".into(),
543 marks: String::new(),
544 text: vec![Segment {
545 text: "Enter: usage, budgets, counts".into(),
546 tone: Some(Tone::Muted),
547 }],
548 right: String::new(),
549 compact: String::new(),
550 tally: None,
551 changed: false,
552 upstream: Vec::new(),
553 held: false,
554 parts: Vec::new(),
555 children: Vec::new(),
556 }
557}
558
559fn result_summary(result: &crate::store::ExecutionResult) -> String {
562 let result = result.to_json();
563 let Some(object) = result.as_object() else {
564 return result
565 .to_string()
566 .lines()
567 .next()
568 .unwrap_or_default()
569 .to_owned();
570 };
571 let mut entries: Vec<_> = object
573 .iter()
574 .filter(|(key, _)| !matches!(key.as_str(), "stdout" | "stderr"))
575 .collect();
576 entries.sort_by_key(|(key, _)| *key != "verdict");
577 let parts = entries.into_iter().map(|(key, value)| match value {
578 Value::String(text) => {
579 let line = text.lines().next().unwrap_or_default();
580 if line.len() < text.trim_end().len() {
581 format!("{key} {line} …")
582 } else {
583 format!("{key} {line}")
584 }
585 }
586 Value::Array(items) => format!("{key} [{} items]", items.len()),
587 Value::Object(fields) => format!("{key} {{{} fields}}", fields.len()),
588 other => format!("{key} {other}"),
589 });
590 join(parts, "\n")
591}
592
593struct Saved<'a> {
595 run: &'a RunView,
596 requests: &'a [RequestView],
597}
598
599impl<'a> Saved<'a> {
600 fn definitions(&self) -> Option<&'a crate::store::definitions::Graph> {
601 self.run.run.definitions.graph()
602 }
603 fn artifacts(
604 &self,
605 ) -> impl Iterator<
606 Item = (
607 &'a crate::types::ArtifactName,
608 &'a crate::store::definitions::Artifact,
609 ),
610 > {
611 self.definitions()
612 .into_iter()
613 .flat_map(|graph| graph.artifacts())
614 }
615 fn artifact(&self, id: &ArtifactName) -> Option<&'a crate::store::definitions::Artifact> {
616 self.definitions().and_then(|graph| graph.artifact(id))
617 }
618 fn eval_definitions(&self) -> &'a [crate::store::definitions::Eval] {
619 self.definitions().map_or(&[], |graph| graph.evals())
620 }
621 fn components(&self) -> &'a [crate::store::definitions::Component] {
622 self.definitions().map_or(&[], |graph| graph.components())
623 }
624
625 fn request(&self, eval: &EvalId) -> Option<&'a RequestView> {
626 self.requests
627 .iter()
628 .find(|view| &view.request.eval_id == eval)
629 }
630
631 fn status(&self, eval: &EvalId) -> Option<Status> {
632 self.request(eval).map(|view| view.request.status().into())
633 }
634
635 fn artifact_ids(&self) -> Vec<&'a ArtifactName> {
638 let components = self.components().iter();
639 let saved = components
640 .flat_map(|component| {
641 let mut members: Vec<_> =
642 component.artifacts.value().into_iter().flatten().collect();
643 members.sort_unstable();
644 members
645 })
646 .chain(self.artifacts().map(|(id, _)| id))
647 .chain(self.requests.iter().map(|view| &view.request.target));
648 let mut seen = std::collections::HashSet::new();
649 saved.filter(|id| seen.insert(*id)).collect()
650 }
651
652 fn evals(
654 &self,
655 artifact: &ArtifactName,
656 ) -> Vec<(&'a EvalId, Option<&'a crate::store::definitions::Eval>)> {
657 let mut evals: Vec<_> = self
658 .eval_definitions()
659 .iter()
660 .filter(|eval| &eval.target == artifact)
661 .map(|eval| (&eval.id, Some(eval)))
662 .collect();
663 for request in self.requests.iter().map(|view| &view.request) {
664 if &request.target == artifact && !evals.iter().any(|(id, _)| *id == &request.eval_id) {
665 evals.push((&request.eval_id, None));
666 }
667 }
668 evals
669 }
670
671 fn validation(&self, artifact: &ArtifactName) -> Option<&'a crate::store::ArtifactValidation> {
672 self.run
673 .run
674 .validation
675 .snapshot()?
676 .artifacts
677 .value()?
678 .iter()
679 .find(|a| &a.id == artifact)
680 }
681
682 fn component(&self, id: &ArtifactName) -> Option<&'a crate::store::definitions::Component> {
683 self.components().iter().find(|component| {
684 component
685 .artifacts
686 .value()
687 .is_some_and(|artifacts| artifacts.iter().any(|artifact| artifact == id))
688 })
689 }
690
691 fn parts(&self) -> std::collections::BTreeMap<&'a ArtifactName, Vec<&'a ArtifactName>> {
693 let mut parts: std::collections::BTreeMap<_, Vec<_>> = Default::default();
694 for relation in self
695 .definitions()
696 .into_iter()
697 .flat_map(|graph| graph.relations())
698 {
699 if matches!(relation.kind, crate::store::definitions::RelationKind::Part) {
700 parts
701 .entry(&relation.target)
702 .or_default()
703 .push(&relation.source);
704 }
705 }
706 parts
707 }
708
709 fn relations(
710 &self,
711 artifact: &ArtifactName,
712 input: bool,
713 ) -> Vec<&'a crate::store::definitions::Relation> {
714 self.definitions()
715 .into_iter()
716 .flat_map(|graph| graph.relations())
717 .filter(|relation| {
718 if input {
719 &relation.target == artifact
720 } else {
721 &relation.source == artifact
722 }
723 })
724 .collect()
725 }
726}
727
728fn relation_kind(relation: &crate::store::definitions::Relation) -> String {
729 use crate::store::definitions::RelationKind;
730 let kind = match &relation.kind {
731 RelationKind::Unknown { .. } => serde_json::to_string(relation).unwrap_or_default(),
732 RelationKind::Part => "part".into(),
733 RelationKind::Child { path } => format!(
734 "child {}",
735 path.value().map_or("", crate::config::ChildPrefix::as_str)
736 ),
737 RelationKind::Instruction { name, eval_id } => format!("{{{name}}} in {eval_id}"),
738 RelationKind::Argument {
739 eval_id,
740 index,
741 name,
742 ..
743 } => format!("argv {eval_id}[{index}] {{{name}}}"),
744 };
745 if relation.cyclic.value() == Some(&true) {
746 format!("{kind} ↻")
747 } else {
748 kind
749 }
750}
751
752fn profile(profile: &crate::config::StoredProfile) -> String {
753 use crate::config::{Field, StoredProfile};
754 match profile {
755 StoredProfile::Agent {
756 backend,
757 model,
758 reasoning,
759 ..
760 } => {
761 let reasoning = match reasoning {
762 Field::Value(reasoning) => format!(" reasoning {reasoning}"),
763 _ => String::new(),
764 };
765 format!(
766 "agent {} {model}{reasoning}",
767 serde_json::to_value(backend)
768 .expect("backend is JSON")
769 .as_str()
770 .expect("backend is a string")
771 )
772 }
773 StoredProfile::Runtime { command, args, .. } => {
774 format!("runtime {command} {}", args.join(" "))
775 }
776 StoredProfile::Human {} => "human".into(),
777 }
778}
779
780fn options(options: &crate::store::ExecutionOptions) -> String {
782 let value = serde_json::to_value(options).unwrap_or_default();
783 let set: Vec<_> = value
784 .as_object()
785 .into_iter()
786 .flatten()
787 .map(|(key, value)| match value.as_str() {
788 Some(text) => format!("{key} {text}"),
789 None => format!("{key} {value}"),
790 })
791 .collect();
792 if set.is_empty() {
793 "declared defaults".into()
794 } else {
795 set.join(" · ")
796 }
797}
798
799fn request_detail(view: &RequestView, now: OffsetDateTime) -> Detail {
800 let request = &view.request;
801 let summary = query::request_summary(view, now);
802 let deps = join(&request.deps, ", ");
803 let mut detail = Detail {
804 title: format!("{} · {}", request.eval_id, request.title),
805 summary: join(
806 [
807 format!(
808 "{}{}",
809 request.status(),
810 elapsed(view, now).map_or(String::new(), |time| format!(" {time}"))
811 ),
812 profile(&request.profile),
813 if deps.is_empty() {
814 deps
815 } else {
816 format!("← {deps}")
817 },
818 ]
819 .into_iter()
820 .filter(|part| !part.is_empty()),
821 " · ",
822 ),
823 fields: Vec::new(),
824 };
825 detail.push(
826 "Status",
827 format!(
828 "{} — {}",
829 request.status(),
830 Status::from(request.status()).meaning()
831 ),
832 );
833 detail.push("Request", request.id.as_str());
834 detail.push("Reason", request.blocked_reason.clone().unwrap_or_default());
835 detail.push("Error", error(view).unwrap_or_default());
836 detail.push("Instruction", request.payload.instruction());
837 detail.push("Profile", profile(&request.profile));
838 if request.requested_profile != request.profile {
839 detail.push("Requested", profile(&request.requested_profile));
840 }
841 detail.push("Options", options(&request.options));
842 detail.push(
843 "Fingerprint",
844 request.fingerprint.as_deref().unwrap_or("none"),
845 );
846 detail.push("Key", request.key.as_deref().unwrap_or("none (no reuse)"));
847 detail.push(
848 "Key covers",
849 join(
850 request
851 .fingerprints
852 .iter()
853 .map(|(name, fingerprint)| format!("{name} {fingerprint}")),
854 "\n",
855 ),
856 );
857 if let Some(source) = &request.provenance {
858 detail.push(
859 "Source",
860 if reused(view) {
861 format!(
862 "reused from Run {} request {} ({}, {}) completed {}{}",
863 source.run_id,
864 source.request_id,
865 source.eval_id,
866 crate::platform::path_text(&source.repo_path),
867 source
868 .completed_at
869 .map_or_else(|| "?".to_owned(), |time| time.to_string()),
870 request
871 .producer
872 .as_ref()
873 .map_or(String::new(), |producer| format!(" by {}", producer.name))
874 )
875 } else {
876 "executed in this Run".into()
877 },
878 );
879 }
880 if let Some(execution) = &view.execution {
881 let owner = execution
882 .owner
883 .map_or(String::new(), |owner| format!(" · owner pid {}", owner.pid));
884 detail.push(
885 "Execution",
886 format!("{} {}{owner}", execution.id, execution.status()),
887 );
888 }
889 if request.profile.kind() == crate::config::ProfileKind::Human || view.claim.is_some() {
890 detail.push("Claim", claim(view));
891 }
892 detail.push(
893 "Timing",
894 format!(
895 "created {} · started {} · completed {}{}",
896 request.created_at,
897 request
898 .started_at
899 .map_or_else(|| "-".to_owned(), |time| time.to_string()),
900 request
901 .completed_at()
902 .map_or_else(|| "-".to_owned(), |time| time.to_string()),
903 elapsed(view, now).map_or(String::new(), |time| format!(" · {time}"))
904 ),
905 );
906 detail.push("Deps", request.deps.join(", "));
907 detail.push(
908 "Argv",
909 request
910 .argv
911 .as_ref()
912 .map_or(String::new(), |argv| argv.join(" ")),
913 );
914 if let Some(result) = &request.result() {
915 detail.push("Result", result_summary(result));
916 detail.push(
917 "Raw result",
918 serde_json::to_string_pretty(result).unwrap_or_default(),
919 );
920 }
921 let total = counter_pairs(&summary.usage.usage);
922 let attempts = request.usage.as_ref().or(request.reused_usage.as_ref());
923 let attempts = attempts.map_or(&[][..], Vec::as_slice);
924 let original = attempts.len();
925 let attempts = attempts.iter().map(|attempt| {
926 let error = attempt.error.as_deref();
927 let error = error.map_or(String::new(), |error| format!(" error: {error}"));
928 format!(
929 "turn {} attempt {}: {}{error}",
930 attempt.turn,
931 attempt.attempt,
932 counter_pairs(&attempt.usage)
933 )
934 });
935 let state = if reused(view) {
936 format!("reused: spent none · original attempts {original}")
937 } else {
938 format!(
939 "{} · attempts {}{}",
940 summary.usage.usage_state,
941 summary.usage.attempts,
942 if total.is_empty() {
943 total
944 } else {
945 format!(" · total {total}")
946 }
947 )
948 };
949 detail.push("Usage", join(std::iter::once(state).chain(attempts), "\n"));
950 detail
951}
952
953#[derive(Debug, Clone, Default, PartialEq)]
957pub struct Card {
958 pub instruction: String,
959 pub result: Option<serde_json::Map<String, Value>>,
961 pub exit_code: Option<i32>,
962 pub error: Option<String>,
963 pub reused: bool,
964 pub took: Option<String>,
966 pub tokens: Option<u64>,
968 pub model: Option<String>,
969}
970
971pub(crate) fn entries(result: &crate::store::ExecutionResult) -> serde_json::Map<String, Value> {
973 let mut entries = result.to_json().as_object().cloned().unwrap_or_default();
974 for key in [
975 "verdict",
976 "stdout",
977 "stderr",
978 "exitCode",
979 "durationMs",
980 "truncated",
981 ] {
982 entries.remove(key);
983 }
984 entries
985}
986
987pub fn card(view: &RequestView, now: OffsetDateTime) -> Card {
988 use crate::config::StoredProfile;
989 use crate::store::ExecutionResult;
990 let request = &view.request;
991 let reused = reused(view);
992 let result = request.result();
993 let attempts = if reused {
994 request.reused_usage.as_ref()
995 } else {
996 request.usage.as_ref()
997 };
998 let tokens = attempts.and_then(|attempts| attempt_tokens(attempts));
999 Card {
1000 instruction: request.payload.instruction().to_owned(),
1001 result: result.map(entries),
1002 exit_code: match result {
1003 Some(ExecutionResult::Runtime(result)) => result.exit_code.value().copied(),
1004 _ => None,
1005 },
1006 error: error(view),
1007 reused,
1008 took: view
1009 .execution
1010 .as_ref()
1011 .and_then(|execution| span(execution.started_at, execution.completed_at(), now)),
1012 tokens,
1013 model: match &request.profile {
1014 StoredProfile::Agent { model, .. } => Some(model.to_string()),
1015 _ => None,
1016 },
1017 }
1018}
1019
1020pub fn detail(
1021 run: &RunView,
1022 requests: &[RequestView],
1023 target: &Target,
1024 now: OffsetDateTime,
1025) -> Detail {
1026 let saved = Saved { run, requests };
1027 let mut detail = Detail::default();
1028 match target {
1029 Target::Run => {
1030 let progress = progress(run, requests, now);
1031 let strip = strip(&progress);
1032 detail.title = format!("Run {}", run.run.id);
1033 detail.summary = format!("{} · {}", progress.status, strip.headline);
1034 detail.push("Status", progress.status.as_str());
1035 detail.push("Comment", progress.comment.clone().unwrap_or_default());
1036 detail.push("Validation", progress.validation.as_str());
1037 detail.push(
1038 "Counts",
1039 join(
1040 progress
1041 .counts
1042 .iter()
1043 .filter(|(_, n)| *n > 0)
1044 .map(|(status, n)| format!("{} {status} {n}", status.glyph())),
1045 " · ",
1046 ),
1047 );
1048 let lines = |items: &[(String, String)]| {
1049 join(
1050 items.iter().map(|(eval, text)| format!("{eval} {text}")),
1051 "\n",
1052 )
1053 };
1054 detail.push("Errors", lines(&progress.errors));
1055 detail.push("Waiting", lines(&progress.waiting));
1056 detail.push("Running", lines(&progress.running));
1057 detail.push("Timing", progress.timing.as_str());
1058 detail.push("Budget", progress.budget.as_str());
1059 detail.push("Work", progress.work.as_str());
1060 detail.push("Usage", progress.usage.as_str());
1061 detail.push("Saved usage", progress.saved.as_str());
1062 detail.push("Run", run.run.id.as_str());
1063 detail.push("Repository", progress.repo.as_str());
1064 }
1065 Target::Eval(id) => {
1066 let waits = tree::waits_for(&saved, id, now);
1067 if let Some(view) = saved.request(id) {
1068 let mut detail = request_detail(view, now);
1069 detail.insert_after("Status", "Waits for", waits);
1070 return detail;
1071 }
1072 let declaration = saved
1073 .eval_definitions()
1074 .iter()
1075 .find(|eval| &eval.id == id)
1076 .and_then(|eval| eval.declaration.value());
1077 detail.title = format!(
1078 "{id} · {}",
1079 declaration
1080 .and_then(|declaration| declaration.title.value())
1081 .map_or("", String::as_str)
1082 );
1083 detail.push("Status", "not in this Run (outside the selection)");
1084 detail.push("Waits for", waits);
1085 detail.push(
1086 "Instruction",
1087 declaration
1088 .and_then(|declaration| declaration.payload.value())
1089 .map_or("", |payload| payload.instruction()),
1090 );
1091 detail.push(
1092 "Profile",
1093 declaration
1094 .and_then(|declaration| declaration.profile.value())
1095 .map_or_else(|| "unknown".into(), |saved| profile(&saved.known)),
1096 );
1097 }
1098 Target::Artifact(id) => {
1099 let artifact = saved.artifact(id);
1100 let basis = if artifact.and_then(|artifact| artifact.basis.value()) == Some(&true) {
1101 " [basis]"
1102 } else {
1103 ""
1104 };
1105 let kind = if artifact.and_then(|artifact| artifact.kind.value())
1106 == Some(&crate::config::ArtifactKind::File)
1107 {
1108 " [file]"
1109 } else {
1110 ""
1111 };
1112 detail.title = format!("Artifact {id}{basis}{kind}");
1113 detail.push(
1114 "Tags",
1115 artifact
1116 .and_then(|artifact| artifact.tags.value())
1117 .map_or_else(String::new, |tags| tags.join(", ")),
1118 );
1119 detail.summary = tree::artifact_status(&saved, id, now);
1120 detail.push("Status", detail.summary.clone());
1121 detail.push("Waits for", tree::artifact_waits(&saved, id, now));
1122 let snapshot = saved.validation(id);
1123 if let Some(status) = snapshot.and_then(|s| s.status.value()) {
1124 detail.push(
1125 "At Run end",
1126 format!(
1127 "{status} · {}/{} Evals GREEN",
1128 snapshot
1129 .and_then(|s| s.passed.value())
1130 .copied()
1131 .unwrap_or(0),
1132 snapshot.and_then(|s| s.total.value()).copied().unwrap_or(0)
1133 ),
1134 );
1135 }
1136 detail.push(
1137 "Path",
1138 artifact
1139 .and_then(|artifact| artifact.path.value())
1140 .map_or_else(
1141 || "-".into(),
1142 |path| {
1143 if path.as_os_str().is_empty() {
1144 ".".into()
1145 } else {
1146 crate::platform::path_text(path)
1147 }
1148 },
1149 ),
1150 );
1151 detail.push(
1152 "Fingerprint",
1153 saved
1154 .validation(id)
1155 .and_then(|s| s.fingerprint.value())
1156 .map(|f| f.as_str())
1157 .unwrap_or_default(),
1158 );
1159 let component = saved.component(id);
1160 if component.and_then(|component| component.cyclic.value()) == Some(&true) {
1161 detail.push(
1162 "Cycle",
1163 format!(
1164 "↻ {}",
1165 join(
1166 component
1167 .and_then(|component| component.artifacts.value())
1168 .into_iter()
1169 .flatten(),
1170 ", "
1171 )
1172 ),
1173 );
1174 }
1175 let gates = component
1176 .and_then(|component| component.gates.value())
1177 .into_iter()
1178 .flatten()
1179 .map(|gate| mark(gate, saved.status(gate)));
1180 detail.push("Gates", join(gates, "\n"));
1181 let evals = saved.evals(id).into_iter();
1182 detail.push(
1183 "Evals",
1184 join(evals.map(|(eval, _)| mark(eval, saved.status(eval))), "\n"),
1185 );
1186 for (key, input) in [("Inputs", true), ("Used by", false)] {
1187 let relations = saved.relations(id, input).into_iter();
1188 let relations = relations.map(|relation| {
1189 format!(
1190 "{} — {}",
1191 if input {
1192 &relation.source
1193 } else {
1194 &relation.target
1195 },
1196 relation_kind(relation)
1197 )
1198 });
1199 detail.push(key, join(relations, "\n"));
1200 }
1201 }
1202 }
1203 detail
1204}
1205
1206fn counter_pairs(counters: &std::collections::BTreeMap<String, u64>) -> String {
1207 join(
1208 counters
1209 .iter()
1210 .map(|(name, value)| format!("{name} {value}")),
1211 ", ",
1212 )
1213}
1214
1215#[cfg(any(test, feature = "test-support"))]
1216pub fn derivation_count(run: &RunView, requests: &[RequestView]) -> usize {
1217 states::States::new(&Saved { run, requests })
1218 .derivations
1219 .get()
1220}