Skip to main content

artifactize_core/monitor/model/
detail.rs

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