Skip to main content

trusty_code/run_task/
report.rs

1//! Run report: structured result, exit codes, and human/JSON rendering (#1034).
2//!
3//! Why: `run-task` must emit its outcome in two faithful forms — a human-readable
4//! summary on a normal terminal, and a clean machine-readable JSON document when
5//! `--json` is set (stdout must then carry *only* that JSON so callers can parse
6//! it). Both forms draw from one `RunReport` so they never drift. Meaningful exit
7//! codes let scripts branch on success vs. config error vs. run failure vs. a
8//! no-op run.
9//! What: `RunReport` bundles the diff, transcript, and usage/cost; `ExitCode`
10//! enumerates the distinct outcomes; `render_human` / `render_json` produce the
11//! two output forms.
12//! Test: `run_task::tests` assert the JSON shape, the human summary content, and
13//! the exit-code mapping.
14
15use serde_json::json;
16
17use crate::perf::TokenUsage;
18use crate::run_task::recorder::TurnRecord;
19
20/// Distinct process exit codes for a `run-task` invocation.
21///
22/// Why: A caller (CI, the PM smoke-test, a wrapper script) needs to distinguish
23/// outcomes without parsing output. The ladder separates a clean success, a
24/// successful run that changed nothing, a configuration error (bad agent, bad
25/// project), a runtime failure (the loop or LLM errored), (#2207) the
26/// wall-clock deadline firing before the PM reached `finish_task` — a run that
27/// may have made real, useful progress and must not be conflated with a
28/// genuine `RunFailure` (the bug that blocked the M3 bake-off L1 pilot: a
29/// deadline hit at turn 13 on an otherwise fully-passing solution reported the
30/// same `run_failure` a real crash would) — and (#2265) a PM turn-cap or
31/// re-delegation-cap hit that STILL produced a deliverable, the same class of
32/// bug as #2207's but triggered by exhausting turns/re-delegation attempts
33/// rather than wall-clock time.
34/// What: `repr(i32)` so the values are stable and documented; `Success = 0`.
35/// Test: `run_task::tests::exit_codes_are_distinct`.
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37#[repr(i32)]
38pub enum ExitCode {
39    /// The run completed and produced a diff. `0`.
40    Success = 0,
41    /// Configuration error: missing/invalid agent, bad project path, missing key. `2`.
42    ConfigError = 2,
43    /// Runtime failure: the agent loop or LLM call errored (excludes the
44    /// deadline and partial paths — see `DeadlineExceeded` and `Partial`). `3`.
45    RunFailure = 3,
46    /// The run completed but changed nothing (empty diff). `4`.
47    NoChanges = 4,
48    /// The configured wall-clock deadline elapsed before the PM loop reached
49    /// a terminal state (#2207). Distinct from `RunFailure` so a caller (e.g.
50    /// the M3 bake-off runner) can tell "timed out, possibly close to done"
51    /// from "genuinely errored". `5`.
52    DeadlineExceeded = 5,
53    /// The PM's own turn cap, or the (#2265) engineer re-delegation cap, was
54    /// exhausted, but a non-empty diff shows a deliverable was actually
55    /// produced. Distinct from `RunFailure` so a caller does not discard a
56    /// working, on-disk solution as an opaque crash purely because the PM ran
57    /// out of turns/retries absorbing engineer failures — trusty-code cannot
58    /// generically verify correctness, so this status only claims "work was
59    /// produced", leaving scoring to the downstream harness. `6`.
60    Partial = 6,
61}
62
63impl ExitCode {
64    /// The numeric exit code.
65    ///
66    /// Why: `process::exit` takes an `i32`; this is the single conversion point.
67    /// What: Returns `self as i32`.
68    /// Test: `run_task::tests::exit_codes_are_distinct`.
69    pub fn code(self) -> i32 {
70        self as i32
71    }
72}
73
74/// The full result of a `run-task` invocation, ready to render.
75///
76/// Why: One source of truth for both output forms keeps the human and JSON
77/// reports in lockstep and makes the success path trivially testable.
78/// What: `agent` is the top-level (PM) agent name; `task` is the request; `diff`
79/// is the captured working-tree change; `transcript` is the ordered PM+engineer
80/// turns; `usage` is the aggregated token usage; `cost_usd` is the summed cost;
81/// `exit` is the computed outcome.
82/// Test: `run_task::tests::report_renders_json` and `report_renders_human`.
83#[derive(Debug, Clone)]
84pub struct RunReport {
85    /// Top-level agent name (the PM).
86    pub agent: String,
87    /// The task description that was run.
88    pub task: String,
89    /// Captured working-tree diff (empty when nothing changed).
90    pub diff: String,
91    /// Ordered transcript of every PM and engineer turn.
92    pub transcript: Vec<TurnRecord>,
93    /// Aggregated token usage across the whole run.
94    pub usage: TokenUsage,
95    /// Summed USD cost across the whole run (`None` when pricing is unavailable).
96    pub cost_usd: Option<f64>,
97    /// Computed process exit outcome.
98    pub exit: ExitCode,
99}
100
101impl RunReport {
102    /// Render the report as a single machine-readable JSON document.
103    ///
104    /// Why: `--json` mode requires clean, parseable stdout; this is the only thing
105    /// printed in that mode.
106    /// What: Serialises all fields into a stable JSON object, including a `status`
107    /// string derived from `exit` and a `cost_usd` that is `null` when pricing is
108    /// unavailable. Pretty-printed for readability without affecting parseability.
109    /// Test: `run_task::tests::report_renders_json`.
110    pub fn render_json(&self) -> String {
111        let value = json!({
112            "status": self.status_str(),
113            "exit_code": self.exit.code(),
114            "agent": self.agent,
115            "task": self.task,
116            "diff": self.diff,
117            "transcript": self.transcript,
118            "usage": {
119                "prompt_tokens": self.usage.prompt_tokens,
120                "completion_tokens": self.usage.completion_tokens,
121                "cache_read_tokens": self.usage.cache_read_tokens,
122                "cache_creation_tokens": self.usage.cache_creation_tokens,
123            },
124            "cost_usd": self.cost_usd,
125        });
126        serde_json::to_string_pretty(&value).unwrap_or_else(|_| "{}".to_string())
127    }
128
129    /// Render the report as a human-readable summary.
130    ///
131    /// Why: On a normal terminal the operator wants a scannable summary, not raw
132    /// JSON. The diff is shown verbatim; the transcript is condensed to one line
133    /// per turn; usage and cost are a footer.
134    /// What: Builds a multi-section string: a header, the transcript (role, model,
135    /// truncated text, tool calls), the diff (or "no changes"), and a usage/cost
136    /// footer.
137    /// Test: `run_task::tests::report_renders_human`.
138    pub fn render_human(&self) -> String {
139        let mut out = String::new();
140        out.push_str(&format!(
141            "tcode run-task: agent={} status={}\n",
142            self.agent,
143            self.status_str()
144        ));
145        out.push_str(&format!("task: {}\n\n", self.task));
146
147        out.push_str("── Transcript ──\n");
148        if self.transcript.is_empty() {
149            out.push_str("(no turns recorded)\n");
150        } else {
151            for (i, turn) in self.transcript.iter().enumerate() {
152                let text_preview: String = turn.text.chars().take(120).collect();
153                let tools = if turn.tool_calls.is_empty() {
154                    String::new()
155                } else {
156                    format!(" tools=[{}]", turn.tool_calls.join(", "))
157                };
158                out.push_str(&format!(
159                    "{n}. [{role}|{model}]{tools} {text}\n",
160                    n = i + 1,
161                    role = turn.role,
162                    model = turn.model,
163                    text = text_preview,
164                ));
165            }
166        }
167
168        out.push_str("\n── Diff ──\n");
169        if self.diff.trim().is_empty() {
170            out.push_str("(no changes)\n");
171        } else {
172            out.push_str(&self.diff);
173            if !self.diff.ends_with('\n') {
174                out.push('\n');
175            }
176        }
177
178        out.push_str("\n── Usage ──\n");
179        let cost = match self.cost_usd {
180            Some(c) => format!("${c:.6}"),
181            None => "(pricing unavailable)".to_string(),
182        };
183        out.push_str(&format!(
184            "prompt={} completion={} cache_read={} cache_creation={} cost={}\n",
185            self.usage.prompt_tokens,
186            self.usage.completion_tokens,
187            self.usage.cache_read_tokens,
188            self.usage.cache_creation_tokens,
189            cost,
190        ));
191        out
192    }
193
194    /// Map the exit outcome to a stable status string.
195    ///
196    /// Why: Both output forms label the outcome with the same vocabulary.
197    /// What: Returns `"success"`, `"no_changes"`, `"config_error"`,
198    /// `"run_failure"`, (#2207) `"deadline_exceeded"`, or (#2265) `"partial"`.
199    /// Test: `run_task::tests::report_renders_json`,
200    /// `run_task::tests::exit_code_reflects_deadline_exceeded_distinct_from_run_failure`.
201    fn status_str(&self) -> &'static str {
202        match self.exit {
203            ExitCode::Success => "success",
204            ExitCode::NoChanges => "no_changes",
205            ExitCode::ConfigError => "config_error",
206            ExitCode::RunFailure => "run_failure",
207            ExitCode::DeadlineExceeded => "deadline_exceeded",
208            ExitCode::Partial => "partial",
209        }
210    }
211}
212
213/// Sum every transcript turn's usage, pricing EACH turn against its OWN
214/// role's resolved model rather than blending the whole transcript under
215/// one model (#1475 bug 1 fix).
216///
217/// Why: The PM's `AgentOutput.usage` only covers the PM's own turns — the
218/// engineer's usage is lost when its output flows back as a tool-result
219/// string. The transcript recorder, by contrast, captures the
220/// provider-reported usage of *every* PM and engineer turn, so summing
221/// those turns is the faithful run total. Pricing the WHOLE total against a
222/// single (PM) model — the original #1475 bug — silently mis-prices every
223/// engineer turn whenever the engineer routes to a different, often more
224/// expensive, model: directly undercuts the #1035 cost-comparison use case
225/// this run exists to support. This is the SAME fix `task::executor`
226/// applied for the daemon path (#2056); this is now the ONE shared
227/// implementation both paths call, so they can never independently drift.
228/// What: Field-wise sums each turn's `usage` into a single `TokenUsage`
229/// (unchanged). Per turn, PREFERS the turn's own `usage.cost_usd` —
230/// OpenRouter's authoritative, already cache-discount-aware cost
231/// (response-side cache-usage fix) — when present; only falls back to the
232/// static per-token recompute (priced per role: `pm_model` for
233/// `role == "pm"`, `engineer_model` otherwise) when the turn carries no
234/// authoritative cost. Sums the per-turn costs. Returns `(total_usage,
235/// cost)`.
236/// Test: `run_task::tests::usage_and_cost_aggregate_end_to_end`,
237/// `report::tests::aggregate_usage_per_role_prices_each_role_separately`,
238/// `report::tests::aggregate_usage_per_role_prefers_authoritative_cost`.
239pub fn aggregate_usage_per_role(
240    turns: &[TurnRecord],
241    pm_model: &str,
242    engineer_model: &str,
243) -> (TokenUsage, f64) {
244    let mut total = TokenUsage::default();
245    let mut cost = 0.0;
246    for turn in turns {
247        total.add(&turn.usage);
248        cost += turn.usage.cost_usd.unwrap_or_else(|| {
249            let model = if turn.role == "pm" {
250                pm_model
251            } else {
252                engineer_model
253            };
254            crate::perf::cost_usd(
255                model,
256                turn.usage.prompt_tokens,
257                turn.usage.completion_tokens,
258                turn.usage.cache_read_tokens,
259                turn.usage.cache_creation_tokens,
260            )
261        });
262    }
263    (total, cost)
264}
265
266// ── Tests ─────────────────────────────────────────────────────────────────────
267
268#[cfg(test)]
269mod tests {
270    use super::*;
271
272    fn sample_report(exit: ExitCode, diff: &str) -> RunReport {
273        RunReport {
274            agent: "pm".into(),
275            task: "do the thing".into(),
276            diff: diff.into(),
277            transcript: vec![
278                TurnRecord {
279                    role: "pm".into(),
280                    model: "openai/gpt-4o-mini".into(),
281                    text: String::new(),
282                    tool_calls: vec!["delegate_to_agent".into()],
283                    ran_test_command: false,
284                    usage: TokenUsage::new(60, 20, 0, 0),
285                },
286                TurnRecord {
287                    role: "python-engineer".into(),
288                    model: "deepseek/deepseek-chat".into(),
289                    text: "wrote the file".into(),
290                    tool_calls: vec!["write_file".into()],
291                    ran_test_command: false,
292                    usage: TokenUsage::new(40, 20, 0, 0),
293                },
294            ],
295            usage: TokenUsage::new(100, 40, 0, 0),
296            cost_usd: Some(0.001),
297            exit,
298        }
299    }
300
301    /// Exit codes are distinct and stable.
302    ///
303    /// Why: Scripts branch on these; collisions would be silent breakage.
304    /// What: Assert the six codes are 0/2/3/4/5/6 and pairwise distinct.
305    /// Test: this test.
306    #[test]
307    fn exit_codes_are_distinct() {
308        assert_eq!(ExitCode::Success.code(), 0);
309        assert_eq!(ExitCode::ConfigError.code(), 2);
310        assert_eq!(ExitCode::RunFailure.code(), 3);
311        assert_eq!(ExitCode::NoChanges.code(), 4);
312        assert_eq!(ExitCode::DeadlineExceeded.code(), 5);
313        assert_eq!(ExitCode::Partial.code(), 6);
314    }
315
316    /// The `"partial"` status string renders for `ExitCode::Partial` (#2265).
317    ///
318    /// Why: Downstream callers (the bake-off harness) branch on this exact
319    /// string; it must render distinctly from `"run_failure"`.
320    /// What: Render a report with `exit: ExitCode::Partial`; assert the JSON
321    /// `status` field and the human summary line both say `"partial"`.
322    /// Test: this test.
323    #[test]
324    fn partial_status_renders_distinctly_from_run_failure() {
325        let report = sample_report(ExitCode::Partial, "+++ added: x.py\n");
326        let rendered = report.render_json();
327        let parsed: serde_json::Value = serde_json::from_str(&rendered).expect("valid JSON");
328        assert_eq!(parsed["status"], "partial");
329        assert_eq!(parsed["exit_code"], 6);
330        assert!(report.render_human().contains("status=partial"));
331    }
332
333    /// JSON render carries status, diff, transcript, usage, and cost.
334    ///
335    /// Why: `--json` consumers depend on this exact shape.
336    /// What: Render a success report; parse it back; assert key fields.
337    /// Test: this test.
338    #[test]
339    fn report_renders_json() {
340        let report = sample_report(ExitCode::Success, "+++ added: x.py\n");
341        let rendered = report.render_json();
342        let parsed: serde_json::Value = serde_json::from_str(&rendered).expect("valid JSON");
343
344        assert_eq!(parsed["status"], "success");
345        assert_eq!(parsed["exit_code"], 0);
346        assert_eq!(parsed["agent"], "pm");
347        assert!(parsed["diff"].as_str().unwrap().contains("added: x.py"));
348        assert_eq!(parsed["transcript"].as_array().unwrap().len(), 2);
349        assert_eq!(parsed["usage"]["prompt_tokens"], 100);
350        assert_eq!(parsed["cost_usd"], 0.001);
351        // The engineer turn must carry its own model slug for #1035 assertions.
352        assert_eq!(parsed["transcript"][1]["model"], "deepseek/deepseek-chat");
353    }
354
355    /// Human render summarises transcript, diff, and usage.
356    ///
357    /// Why: Operators read this; key facts must be present.
358    /// What: Render a success report; assert role labels, the diff, and usage line.
359    /// Test: this test.
360    #[test]
361    fn report_renders_human() {
362        let report = sample_report(ExitCode::Success, "+++ added: x.py\n");
363        let text = report.render_human();
364        assert!(text.contains("status=success"));
365        assert!(text.contains("[pm|openai/gpt-4o-mini]"));
366        assert!(text.contains("[python-engineer|deepseek/deepseek-chat]"));
367        assert!(text.contains("added: x.py"));
368        assert!(text.contains("prompt=100 completion=40"));
369    }
370
371    /// A no-changes report renders "(no changes)" in the human form.
372    ///
373    /// Why: The no-op outcome must be visible to a human reader.
374    /// What: Render with an empty diff; assert the marker.
375    /// Test: this test.
376    #[test]
377    fn human_render_shows_no_changes() {
378        let report = sample_report(ExitCode::NoChanges, "");
379        let text = report.render_human();
380        assert!(text.contains("(no changes)"), "text: {text}");
381        assert!(text.contains("status=no_changes"));
382    }
383
384    /// `aggregate_usage_per_role` sums every turn's usage and prices the total.
385    ///
386    /// Why: The run cost is the combined cost across PM + engineer turns; the math
387    /// must be exact and span the whole transcript.
388    /// What: Sum two turns' usages (same model for both roles here — the
389    /// per-role split itself is covered by
390    /// `aggregate_usage_per_role_prices_each_role_separately` below), assert
391    /// field-wise totals and a non-negative cost.
392    /// Test: this test.
393    #[test]
394    fn usage_and_cost_aggregate() {
395        let turns = vec![
396            TurnRecord {
397                role: "pm".into(),
398                model: "openai/gpt-4o-mini".into(),
399                text: String::new(),
400                tool_calls: vec![],
401                ran_test_command: false,
402                usage: TokenUsage::new(10, 5, 0, 0),
403            },
404            TurnRecord {
405                role: "python-engineer".into(),
406                model: "openai/gpt-4o-mini".into(),
407                text: "done".into(),
408                tool_calls: vec![],
409                ran_test_command: false,
410                usage: TokenUsage::new(20, 8, 0, 0),
411            },
412        ];
413        let (total, cost) =
414            aggregate_usage_per_role(&turns, "openai/gpt-4o-mini", "openai/gpt-4o-mini");
415        assert_eq!(total.prompt_tokens, 30);
416        assert_eq!(total.completion_tokens, 13);
417        assert!(cost >= 0.0, "cost must be non-negative");
418    }
419
420    /// `aggregate_usage_per_role` must price the PM's and the engineer's
421    /// turns against their OWN resolved models — the #1475 bug 1 fix.
422    ///
423    /// Why: When the engineer routes to a different (here, deliberately
424    /// pricier) model than the PM, pricing the whole transcript against the
425    /// PM model alone would be wrong by construction; this pins the fix.
426    /// What: One PM turn priced at a cheap model, one engineer turn priced
427    /// at an expensive model; assert the per-role total differs from (and
428    /// exceeds) what blending everything under the PM model would produce.
429    /// Test: this test.
430    #[test]
431    fn aggregate_usage_per_role_prices_each_role_separately() {
432        let turns = vec![
433            TurnRecord {
434                role: "pm".into(),
435                model: "anthropic/claude-haiku-4".into(),
436                text: String::new(),
437                tool_calls: vec!["delegate_to_agent".into()],
438                ran_test_command: false,
439                usage: TokenUsage::new(1000, 500, 0, 0),
440            },
441            TurnRecord {
442                role: "python-engineer".into(),
443                model: "anthropic/claude-sonnet-4-5".into(),
444                text: "done".into(),
445                tool_calls: vec![],
446                ran_test_command: false,
447                usage: TokenUsage::new(2000, 1000, 0, 0),
448            },
449        ];
450        let (_, per_role_cost) = aggregate_usage_per_role(
451            &turns,
452            "anthropic/claude-haiku-4",
453            "anthropic/claude-sonnet-4-5",
454        );
455        // Blending everything under the PM (haiku, cheaper) model would
456        // understate the true cost since the engineer's turn actually ran
457        // on the pricier sonnet model.
458        let blended_cost = crate::perf::cost_usd("anthropic/claude-haiku-4", 3000, 1500, 0, 0);
459        assert_ne!(
460            per_role_cost, blended_cost,
461            "per-role pricing must differ from blending everything under the PM model"
462        );
463    }
464
465    /// `aggregate_usage_per_role` prefers a turn's own authoritative
466    /// `usage.cost_usd` over the static per-token recompute (response-side
467    /// cache-usage fix).
468    ///
469    /// Why: The static pricing table cannot see OpenRouter's cache discount;
470    /// only the provider-reported `cost` reflects it. This is the exact gap
471    /// that made #2156's cost thesis unverifiable end-to-end.
472    /// What: One turn carries an authoritative cost that is deliberately far
473    /// below what static pricing would compute for its token counts; one turn
474    /// carries no authoritative cost (static fallback). Assert the total cost
475    /// is exactly the authoritative value plus the static fallback for the
476    /// second turn — i.e. the first turn's static price is NOT used.
477    /// Test: this test.
478    #[test]
479    fn aggregate_usage_per_role_prefers_authoritative_cost() {
480        let mut authoritative_usage = TokenUsage::new(1_000_000, 0, 900_000, 100_000);
481        authoritative_usage.cost_usd = Some(0.0005); // far below static per-token price
482        let turns = vec![
483            TurnRecord {
484                role: "pm".into(),
485                model: "anthropic/claude-sonnet-4-5".into(),
486                text: String::new(),
487                tool_calls: vec![],
488                ran_test_command: false,
489                usage: authoritative_usage,
490            },
491            TurnRecord {
492                role: "python-engineer".into(),
493                model: "anthropic/claude-sonnet-4-5".into(),
494                text: "done".into(),
495                tool_calls: vec![],
496                ran_test_command: false,
497                usage: TokenUsage::new(100, 50, 0, 0),
498            },
499        ];
500        let (_, cost) = aggregate_usage_per_role(
501            &turns,
502            "anthropic/claude-sonnet-4-5",
503            "anthropic/claude-sonnet-4-5",
504        );
505        let expected_fallback = crate::perf::cost_usd("anthropic/claude-sonnet-4-5", 100, 50, 0, 0);
506        assert!(
507            (cost - (0.0005 + expected_fallback)).abs() < 1e-12,
508            "expected authoritative cost + static fallback, got {cost}"
509        );
510    }
511}