Skip to main content

artifactize_core/monitor/model/
detail.rs

1//! Cards and detail-pane presentation for Runs, Artifacts and Evals.
2use super::*;
3
4/// Where a Detail field goes, in display order. Technical is folded by default.
5#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
6pub enum Section {
7    Outcome,
8    /// The Artifacts an eval waits for, each with its pending evals.
9    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    /// The verdict first; technical identifiers and hashes last. The request stays visible.
25    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    /// One-line outcome: state, elapsed time, profile and dependencies.
53    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
82/// A result in a few lines: its verdict, then its issues, one line each. Runtime output is
83/// left to the evidence view.
84fn 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
128/// Execution options that are set, such as `variant fast · timeoutMs 60000`.
129fn 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            // Mutex tags use validated ASCII identifiers with no JSON escape characters.
137            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/// An eval at a glance: what it checks, its result once it has one, and what running it cost.
313/// For a reused result, `took` and `tokens` are what reuse saved. Everything else about the
314/// request stays in its [`Detail`]'s fields.
315#[derive(Debug, Clone, Default, PartialEq)]
316pub struct Card {
317    /// Its instruction, each Artifact it names with that Artifact's path.
318    pub instruction: crate::scope::Instruction,
319    /// What the result says must change, numbered as shown; none before a result.
320    pub issues: Option<Vec<crate::store::Issue>>,
321    /// The whole result as saved, pretty-printed JSON.
322    pub raw: Option<String>,
323    pub exit_code: Option<i32>,
324    pub error: Option<String>,
325    pub reused: bool,
326    /// The execution's own span: from its start to its end, or to `now` while it runs.
327    pub took: Option<String>,
328    /// Total tokens over every attempt.
329    pub tokens: Option<u64>,
330    pub model: Option<String>,
331}
332
333/// The whole result as saved, as a Card's Debug shows it.
334pub(crate) fn raw(result: &crate::store::ExecutionResult) -> String {
335    serde_json::to_string_pretty(&result.to_json()).expect("a saved result is JSON")
336}
337
338/// The Card of `view`, a request of `run`.
339pub fn card(run: &RunView, view: &RequestView, now: OffsetDateTime) -> Card {
340    use crate::config::StoredProfile;
341    use crate::store::ExecutionResult;
342    let request = &view.request;
343    let saved = Saved { run, requests: &[] };
344    let reused = reused(view);
345    let result = request.result();
346    let attempts = if reused {
347        request.reused_usage.as_ref()
348    } else {
349        request.usage.as_ref()
350    };
351    let tokens = attempts.and_then(|attempts| attempt_tokens(attempts));
352    Card {
353        instruction: crate::scope::Instruction::saved(
354            request.payload.instruction(),
355            request.references.values(),
356            |name| {
357                saved
358                    .artifact(name)
359                    .and_then(crate::store::definitions::Artifact::shown_path)
360            },
361        ),
362        issues: result.map(ExecutionResult::issues),
363        raw: result.map(raw),
364        exit_code: result.and_then(ExecutionResult::exit_code),
365        error: error(view),
366        reused,
367        took: view
368            .execution
369            .as_ref()
370            .and_then(|execution| span(execution.started_at, execution.completed_at(), now)),
371        tokens,
372        model: match &request.profile {
373            StoredProfile::Agent { model, .. } => Some(model.to_string()),
374            _ => None,
375        },
376    }
377}
378
379pub fn detail(
380    run: &RunView,
381    requests: &[RequestView],
382    target: &Target,
383    now: OffsetDateTime,
384) -> Detail {
385    let saved = Saved { run, requests };
386    let mut detail = Detail::default();
387    match target {
388        Target::Run => {
389            let progress = progress(run, requests, now);
390            let strip = strip(&progress);
391            detail.title = format!("Run {}", run.run.id);
392            detail.summary = format!("{} · {}", progress.status, strip.headline);
393            detail.push("Status", progress.status.as_str());
394            detail.push("Comment", progress.comment.clone().unwrap_or_default());
395            detail.push("Validation", progress.validation.as_str());
396            detail.push(
397                "Counts",
398                join(
399                    progress
400                        .counts
401                        .iter()
402                        .filter(|(_, n)| *n > 0)
403                        .map(|(status, n)| format!("{} {status} {n}", status.glyph())),
404                    " · ",
405                ),
406            );
407            let lines = |items: &[(String, String)]| {
408                join(
409                    items.iter().map(|(eval, text)| format!("{eval}  {text}")),
410                    "\n",
411                )
412            };
413            detail.push("Errors", lines(&progress.errors));
414            detail.push("Waiting", lines(&progress.waiting));
415            detail.push("Running", lines(&progress.running));
416            detail.push("Timing", progress.timing.as_str());
417            detail.push("Budget", progress.budget.as_str());
418            detail.push("Work", progress.work.as_str());
419            detail.push("Usage", progress.usage.as_str());
420            detail.push("Saved usage", progress.saved.as_str());
421            detail.push("Run", run.run.id.as_str());
422            detail.push("Repository", progress.repo.as_str());
423        }
424        Target::Eval(id) => {
425            let waits = tree::waits_for(&saved, id, now);
426            if let Some(view) = saved.request(id) {
427                let mut detail = request_detail(view, now);
428                detail.insert_after("Status", "Waits for", waits);
429                return detail;
430            }
431            let declaration = saved
432                .eval_definitions()
433                .iter()
434                .find(|eval| &eval.id == id)
435                .and_then(|eval| eval.declaration.value());
436            detail.title = format!(
437                "{id} · {}",
438                declaration
439                    .and_then(|declaration| declaration.title.value())
440                    .map_or("", String::as_str)
441            );
442            detail.push("Status", "not in this Run (outside the selection)");
443            detail.push("Waits for", waits);
444            detail.push(
445                "Instruction",
446                declaration
447                    .and_then(|declaration| declaration.payload.value())
448                    .map_or("", |payload| payload.instruction()),
449            );
450            detail.push(
451                "Profile",
452                declaration
453                    .and_then(|declaration| declaration.profile.value())
454                    .map_or_else(|| "unknown".into(), |saved| profile(&saved.known)),
455            );
456        }
457        Target::Artifact(id) => {
458            let artifact = saved.artifact(id);
459            let basis = if artifact.and_then(|artifact| artifact.basis.value()) == Some(&true) {
460                " [basis]"
461            } else {
462                ""
463            };
464            let kind = if artifact.and_then(|artifact| artifact.kind.value())
465                == Some(&crate::config::ArtifactKind::File)
466            {
467                " [file]"
468            } else {
469                ""
470            };
471            detail.title = format!("Artifact {id}{basis}{kind}");
472            detail.push(
473                "Tags",
474                artifact
475                    .and_then(|artifact| artifact.tags.value())
476                    .map_or_else(String::new, |tags| tags.join(", ")),
477            );
478            detail.summary = tree::artifact_status(&saved, id, now);
479            detail.push("Status", detail.summary.clone());
480            detail.push("Waits for", tree::artifact_waits(&saved, id, now));
481            let snapshot = saved.validation(id);
482            if let Some(status) = snapshot.and_then(|s| s.status.value()) {
483                detail.push(
484                    "At Run end",
485                    format!(
486                        "{status} · {}/{} Evals GREEN",
487                        snapshot
488                            .and_then(|s| s.passed.value())
489                            .copied()
490                            .unwrap_or(0),
491                        snapshot.and_then(|s| s.total.value()).copied().unwrap_or(0)
492                    ),
493                );
494            }
495            detail.push(
496                "Path",
497                artifact
498                    .and_then(crate::store::definitions::Artifact::shown_path)
499                    .unwrap_or_else(|| "-".into()),
500            );
501            // A Live Artifact is observed at the address its PATH names.
502            if let Some(address) = artifact
503                .and_then(|artifact| artifact.path.value())
504                .and_then(crate::config::Target::uri)
505            {
506                detail.push("Target kind", "Live");
507                detail.push("Address", address.as_str());
508            }
509            detail.push(
510                "Fingerprint",
511                saved
512                    .validation(id)
513                    .and_then(|s| s.fingerprint.value())
514                    .map(|f| f.as_str())
515                    .unwrap_or_default(),
516            );
517            let component = saved.component(id);
518            if component.and_then(|component| component.cyclic.value()) == Some(&true) {
519                detail.push(
520                    "Cycle",
521                    format!(
522                        "↻ {}",
523                        join(
524                            component
525                                .and_then(|component| component.artifacts.value())
526                                .into_iter()
527                                .flatten(),
528                            ", "
529                        )
530                    ),
531                );
532            }
533            let gates = component
534                .and_then(|component| component.gates.value())
535                .into_iter()
536                .flatten()
537                .map(|gate| mark(gate, saved.status(gate)));
538            detail.push("Gates", join(gates, "\n"));
539            let evals = saved.evals(id).into_iter();
540            detail.push(
541                "Evals",
542                join(evals.map(|(eval, _)| mark(eval, saved.status(eval))), "\n"),
543            );
544            for (key, input) in [("Inputs", true), ("Used by", false)] {
545                let relations = saved.relations(id, input).into_iter();
546                let relations = relations.map(|relation| {
547                    format!(
548                        "{} — {}",
549                        if input {
550                            &relation.source
551                        } else {
552                            &relation.target
553                        },
554                        relation_kind(relation)
555                    )
556                });
557                detail.push(key, join(relations, "\n"));
558            }
559        }
560    }
561    detail
562}