1use super::*;
3
4#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
6pub enum Section {
7 Outcome,
8 Waits,
10 What,
11 Provenance,
12 Technical,
13}
14
15impl Section {
16 pub const ALL: [Self; 5] = [
17 Self::Outcome,
18 Self::Waits,
19 Self::What,
20 Self::Provenance,
21 Self::Technical,
22 ];
23
24 pub fn of(key: &str) -> Self {
26 match key {
27 "Status" | "Error" | "Reason" | "Blocked by" | "Result" | "Claim" | "Source"
28 | "At Run end" | "Validation" | "Counts" | "Errors" | "Waiting" | "Running"
29 | "Evals" | "Gates" => Self::Outcome,
30 "Waits for" => Self::Waits,
31 "Timing" | "Usage" | "Budget" | "Work" | "Saved usage" => Self::Provenance,
32 "Execution" | "Fingerprint" | "Key" | "Key covers" | "Path" | "Tags" | "Cycle"
33 | "Run" | "Repository" => Self::Technical,
34 _ => Self::What,
35 }
36 }
37
38 pub fn name(self) -> &'static str {
39 match self {
40 Self::Outcome => "Outcome",
41 Self::Waits => "Waits for",
42 Self::What => "What",
43 Self::Provenance => "Provenance",
44 Self::Technical => "Technical",
45 }
46 }
47}
48
49#[derive(Debug, Clone, Default)]
50pub struct Detail {
51 pub title: String,
52 pub summary: String,
54 pub fields: Vec<(&'static str, String)>,
55}
56
57impl Detail {
58 pub fn field(&self, name: &str) -> Option<&str> {
59 self.fields
60 .iter()
61 .find(|(key, _)| *key == name)
62 .map(|(_, value)| value.as_str())
63 }
64
65 fn push(&mut self, key: &'static str, value: impl Into<String>) {
66 let value = value.into();
67 if !value.is_empty() {
68 self.fields.push((key, value));
69 }
70 }
71
72 fn insert_after(&mut self, after: &str, key: &'static str, value: String) {
73 if value.is_empty() {
74 return;
75 }
76 let index = self.fields.iter().position(|(name, _)| *name == after);
77 let index = index.map_or(self.fields.len(), |index| index + 1);
78 self.fields.insert(index, (key, value));
79 }
80}
81
82fn result_summary(result: &crate::store::ExecutionResult) -> String {
85 let verdict = format!("verdict {}", result.verdict().as_str());
86 let issues = result.issues().into_iter().map(|issue| {
87 let lead = match (issue.priority, issue.exit_code) {
88 (Some(priority), _) => format!("{priority} "),
89 (None, Some(code)) => format!("exit {code}: "),
90 (None, None) => String::new(),
91 };
92 let line = issue.reason.lines().next().unwrap_or_default();
93 if line.len() < issue.reason.trim_end().len() {
94 format!("{lead}{line} …")
95 } else {
96 format!("{lead}{line}")
97 }
98 });
99 join(std::iter::once(verdict).chain(issues), "\n")
100}
101
102fn profile(profile: &crate::config::StoredProfile) -> String {
103 use crate::config::{Field, StoredProfile};
104 match profile {
105 StoredProfile::Agent {
106 backend,
107 model,
108 reasoning,
109 ..
110 } => {
111 let reasoning = match reasoning {
112 Field::Value(reasoning) => format!(" reasoning {reasoning}"),
113 _ => String::new(),
114 };
115 format!("agent {backend} {model}{reasoning}")
116 }
117 StoredProfile::Runtime { command, args, .. } => {
118 format!(
119 "runtime {} {}",
120 crate::platform::program_text(command),
121 args.join(" ")
122 )
123 }
124 StoredProfile::Human {} => "human".into(),
125 }
126}
127
128fn options(options: &crate::store::ExecutionOptions) -> String {
130 let set: Vec<_> = [
131 options.backend.as_ref().map(|x| format!("backend {x}")),
132 options.max_tokens.map(|x| format!("maxTokens {x}")),
133 options.max_tool_calls.map(|x| format!("maxToolCalls {x}")),
134 options.model.as_ref().map(|x| format!("model {x}")),
135 (!options.mutex.is_empty()).then(|| {
136 format!(
138 "mutex [\"{}\"]",
139 join(options.mutex.iter().map(|x| x.as_str()), "\",\"")
140 )
141 }),
142 options.reasoning.map(|x| format!("reasoning {x}")),
143 options
144 .timeout_ms
145 .map(|x| format!("timeoutMs {}", x.as_millis())),
146 options.variant.as_ref().map(|x| format!("variant {x}")),
147 ]
148 .into_iter()
149 .flatten()
150 .collect();
151 if set.is_empty() {
152 "declared defaults".into()
153 } else {
154 set.join(" · ")
155 }
156}
157
158fn request_detail(view: &RequestView, now: OffsetDateTime) -> Detail {
159 let request = &view.request;
160 let summary = query::request_summary(view, now);
161 let deps = join(&request.deps, ", ");
162 let mut detail = Detail {
163 title: format!("{} · {}", request.eval_id, request.title),
164 summary: join(
165 [
166 format!(
167 "{}{}",
168 request.status(),
169 elapsed(view, now).map_or(String::new(), |time| format!(" {time}"))
170 ),
171 profile(&request.profile),
172 if deps.is_empty() {
173 deps
174 } else {
175 format!("← {deps}")
176 },
177 ]
178 .into_iter()
179 .filter(|part| !part.is_empty()),
180 " · ",
181 ),
182 fields: Vec::new(),
183 };
184 detail.push(
185 "Status",
186 format!(
187 "{} — {}",
188 request.status(),
189 Status::from(request.status()).meaning()
190 ),
191 );
192 detail.push("Request", request.id.as_str());
193 detail.push("Reason", request.blocked_reason.clone().unwrap_or_default());
194 detail.push("Error", error(view).unwrap_or_default());
195 detail.push("Instruction", request.payload.instruction());
196 detail.push("Profile", profile(&request.profile));
197 if request.requested_profile != request.profile {
198 detail.push("Requested", profile(&request.requested_profile));
199 }
200 detail.push("Options", options(&request.options));
201 detail.push(
202 "Fingerprint",
203 request.fingerprint.as_deref().unwrap_or("none"),
204 );
205 detail.push("Key", request.key.as_deref().unwrap_or("none (no reuse)"));
206 detail.push(
207 "Key covers",
208 join(
209 request
210 .fingerprints
211 .iter()
212 .map(|(name, fingerprint)| format!("{name} {fingerprint}")),
213 "\n",
214 ),
215 );
216 if let Some(source) = &request.provenance {
217 detail.push(
218 "Source",
219 if reused(view) {
220 format!(
221 "reused from Run {} request {} ({}, {}) completed {}{}",
222 source.run_id,
223 source.request_id,
224 source.eval_id,
225 crate::platform::path_text(&source.repo_path),
226 source
227 .completed_at
228 .map_or_else(|| "?".to_owned(), |time| time.to_string()),
229 request
230 .producer
231 .as_ref()
232 .map_or(String::new(), |producer| format!(" by {}", producer.name))
233 )
234 } else {
235 "executed in this Run".into()
236 },
237 );
238 }
239 if let Some(execution) = &view.execution {
240 let owner = execution
241 .owner
242 .map_or(String::new(), |owner| format!(" · owner pid {}", owner.pid));
243 detail.push(
244 "Execution",
245 format!("{} {}{owner}", execution.id, execution.status()),
246 );
247 }
248 if request.profile.kind() == crate::config::ProfileKind::Human || view.claim.is_some() {
249 detail.push("Claim", claim(view));
250 }
251 detail.push(
252 "Timing",
253 format!(
254 "created {} · started {} · completed {}{}",
255 request.created_at,
256 request
257 .started_at
258 .map_or_else(|| "-".to_owned(), |time| time.to_string()),
259 request
260 .completed_at()
261 .map_or_else(|| "-".to_owned(), |time| time.to_string()),
262 elapsed(view, now).map_or(String::new(), |time| format!(" · {time}"))
263 ),
264 );
265 detail.push("Deps", request.deps.join(", "));
266 detail.push(
267 "Argv",
268 request
269 .argv
270 .as_ref()
271 .map_or(String::new(), |argv| argv.join(" ")),
272 );
273 if let Some(result) = &request.result() {
274 detail.push("Result", result_summary(result));
275 detail.push(
276 "Raw result",
277 serde_json::to_string_pretty(result).unwrap_or_default(),
278 );
279 }
280 let total = counter_pairs(&summary.usage.usage);
281 let attempts = request.usage.as_ref().or(request.reused_usage.as_ref());
282 let attempts = attempts.map_or(&[][..], Vec::as_slice);
283 let original = attempts.len();
284 let attempts = attempts.iter().map(|attempt| {
285 let error = attempt.error.as_deref();
286 let error = error.map_or(String::new(), |error| format!(" error: {error}"));
287 format!(
288 "turn {} attempt {}: {}{error}",
289 attempt.turn,
290 attempt.attempt,
291 counter_pairs(&attempt.usage)
292 )
293 });
294 let state = if reused(view) {
295 format!("reused: spent none · original attempts {original}")
296 } else {
297 format!(
298 "{} · attempts {}{}",
299 summary.usage.usage_state,
300 summary.usage.attempts,
301 if total.is_empty() {
302 total
303 } else {
304 format!(" · total {total}")
305 }
306 )
307 };
308 detail.push("Usage", join(std::iter::once(state).chain(attempts), "\n"));
309 detail
310}
311
312#[derive(Debug, Clone, Default, PartialEq)]
316pub struct Card {
317 pub instruction: String,
318 pub issues: Option<Vec<crate::store::Issue>>,
320 pub raw: Option<String>,
322 pub exit_code: Option<i32>,
323 pub error: Option<String>,
324 pub reused: bool,
325 pub took: Option<String>,
327 pub tokens: Option<u64>,
329 pub model: Option<String>,
330}
331
332pub(crate) fn raw(result: &crate::store::ExecutionResult) -> String {
334 serde_json::to_string_pretty(&result.to_json()).expect("a saved result is JSON")
335}
336
337pub fn card(view: &RequestView, now: OffsetDateTime) -> Card {
338 use crate::config::StoredProfile;
339 use crate::store::ExecutionResult;
340 let request = &view.request;
341 let reused = reused(view);
342 let result = request.result();
343 let attempts = if reused {
344 request.reused_usage.as_ref()
345 } else {
346 request.usage.as_ref()
347 };
348 let tokens = attempts.and_then(|attempts| attempt_tokens(attempts));
349 Card {
350 instruction: request.payload.instruction().to_owned(),
351 issues: result.map(ExecutionResult::issues),
352 raw: result.map(raw),
353 exit_code: result.and_then(ExecutionResult::exit_code),
354 error: error(view),
355 reused,
356 took: view
357 .execution
358 .as_ref()
359 .and_then(|execution| span(execution.started_at, execution.completed_at(), now)),
360 tokens,
361 model: match &request.profile {
362 StoredProfile::Agent { model, .. } => Some(model.to_string()),
363 _ => None,
364 },
365 }
366}
367
368pub fn detail(
369 run: &RunView,
370 requests: &[RequestView],
371 target: &Target,
372 now: OffsetDateTime,
373) -> Detail {
374 let saved = Saved { run, requests };
375 let mut detail = Detail::default();
376 match target {
377 Target::Run => {
378 let progress = progress(run, requests, now);
379 let strip = strip(&progress);
380 detail.title = format!("Run {}", run.run.id);
381 detail.summary = format!("{} · {}", progress.status, strip.headline);
382 detail.push("Status", progress.status.as_str());
383 detail.push("Comment", progress.comment.clone().unwrap_or_default());
384 detail.push("Validation", progress.validation.as_str());
385 detail.push(
386 "Counts",
387 join(
388 progress
389 .counts
390 .iter()
391 .filter(|(_, n)| *n > 0)
392 .map(|(status, n)| format!("{} {status} {n}", status.glyph())),
393 " · ",
394 ),
395 );
396 let lines = |items: &[(String, String)]| {
397 join(
398 items.iter().map(|(eval, text)| format!("{eval} {text}")),
399 "\n",
400 )
401 };
402 detail.push("Errors", lines(&progress.errors));
403 detail.push("Waiting", lines(&progress.waiting));
404 detail.push("Running", lines(&progress.running));
405 detail.push("Timing", progress.timing.as_str());
406 detail.push("Budget", progress.budget.as_str());
407 detail.push("Work", progress.work.as_str());
408 detail.push("Usage", progress.usage.as_str());
409 detail.push("Saved usage", progress.saved.as_str());
410 detail.push("Run", run.run.id.as_str());
411 detail.push("Repository", progress.repo.as_str());
412 }
413 Target::Eval(id) => {
414 let waits = tree::waits_for(&saved, id, now);
415 if let Some(view) = saved.request(id) {
416 let mut detail = request_detail(view, now);
417 detail.insert_after("Status", "Waits for", waits);
418 return detail;
419 }
420 let declaration = saved
421 .eval_definitions()
422 .iter()
423 .find(|eval| &eval.id == id)
424 .and_then(|eval| eval.declaration.value());
425 detail.title = format!(
426 "{id} · {}",
427 declaration
428 .and_then(|declaration| declaration.title.value())
429 .map_or("", String::as_str)
430 );
431 detail.push("Status", "not in this Run (outside the selection)");
432 detail.push("Waits for", waits);
433 detail.push(
434 "Instruction",
435 declaration
436 .and_then(|declaration| declaration.payload.value())
437 .map_or("", |payload| payload.instruction()),
438 );
439 detail.push(
440 "Profile",
441 declaration
442 .and_then(|declaration| declaration.profile.value())
443 .map_or_else(|| "unknown".into(), |saved| profile(&saved.known)),
444 );
445 }
446 Target::Artifact(id) => {
447 let artifact = saved.artifact(id);
448 let basis = if artifact.and_then(|artifact| artifact.basis.value()) == Some(&true) {
449 " [basis]"
450 } else {
451 ""
452 };
453 let kind = if artifact.and_then(|artifact| artifact.kind.value())
454 == Some(&crate::config::ArtifactKind::File)
455 {
456 " [file]"
457 } else {
458 ""
459 };
460 detail.title = format!("Artifact {id}{basis}{kind}");
461 detail.push(
462 "Tags",
463 artifact
464 .and_then(|artifact| artifact.tags.value())
465 .map_or_else(String::new, |tags| tags.join(", ")),
466 );
467 detail.summary = tree::artifact_status(&saved, id, now);
468 detail.push("Status", detail.summary.clone());
469 detail.push("Waits for", tree::artifact_waits(&saved, id, now));
470 let snapshot = saved.validation(id);
471 if let Some(status) = snapshot.and_then(|s| s.status.value()) {
472 detail.push(
473 "At Run end",
474 format!(
475 "{status} · {}/{} Evals GREEN",
476 snapshot
477 .and_then(|s| s.passed.value())
478 .copied()
479 .unwrap_or(0),
480 snapshot.and_then(|s| s.total.value()).copied().unwrap_or(0)
481 ),
482 );
483 }
484 detail.push(
485 "Path",
486 artifact
487 .and_then(|artifact| artifact.path.value())
488 .map_or_else(
489 || "-".into(),
490 |path| {
491 if path.local().is_some_and(|path| path.as_os_str().is_empty()) {
492 ".".into()
493 } else {
494 path.to_string()
495 }
496 },
497 ),
498 );
499 if let Some(address) = artifact
501 .and_then(|artifact| artifact.path.value())
502 .and_then(crate::config::Target::uri)
503 {
504 detail.push("Target kind", "Live");
505 detail.push("Address", address.as_str());
506 }
507 detail.push(
508 "Fingerprint",
509 saved
510 .validation(id)
511 .and_then(|s| s.fingerprint.value())
512 .map(|f| f.as_str())
513 .unwrap_or_default(),
514 );
515 let component = saved.component(id);
516 if component.and_then(|component| component.cyclic.value()) == Some(&true) {
517 detail.push(
518 "Cycle",
519 format!(
520 "↻ {}",
521 join(
522 component
523 .and_then(|component| component.artifacts.value())
524 .into_iter()
525 .flatten(),
526 ", "
527 )
528 ),
529 );
530 }
531 let gates = component
532 .and_then(|component| component.gates.value())
533 .into_iter()
534 .flatten()
535 .map(|gate| mark(gate, saved.status(gate)));
536 detail.push("Gates", join(gates, "\n"));
537 let evals = saved.evals(id).into_iter();
538 detail.push(
539 "Evals",
540 join(evals.map(|(eval, _)| mark(eval, saved.status(eval))), "\n"),
541 );
542 for (key, input) in [("Inputs", true), ("Used by", false)] {
543 let relations = saved.relations(id, input).into_iter();
544 let relations = relations.map(|relation| {
545 format!(
546 "{} — {}",
547 if input {
548 &relation.source
549 } else {
550 &relation.target
551 },
552 relation_kind(relation)
553 )
554 });
555 detail.push(key, join(relations, "\n"));
556 }
557 }
558 }
559 detail
560}