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 usage: TokenUsage::new(60, 20, 0, 0),
284 },
285 TurnRecord {
286 role: "python-engineer".into(),
287 model: "deepseek/deepseek-chat".into(),
288 text: "wrote the file".into(),
289 tool_calls: vec!["write_file".into()],
290 usage: TokenUsage::new(40, 20, 0, 0),
291 },
292 ],
293 usage: TokenUsage::new(100, 40, 0, 0),
294 cost_usd: Some(0.001),
295 exit,
296 }
297 }
298
299 /// Exit codes are distinct and stable.
300 ///
301 /// Why: Scripts branch on these; collisions would be silent breakage.
302 /// What: Assert the six codes are 0/2/3/4/5/6 and pairwise distinct.
303 /// Test: this test.
304 #[test]
305 fn exit_codes_are_distinct() {
306 assert_eq!(ExitCode::Success.code(), 0);
307 assert_eq!(ExitCode::ConfigError.code(), 2);
308 assert_eq!(ExitCode::RunFailure.code(), 3);
309 assert_eq!(ExitCode::NoChanges.code(), 4);
310 assert_eq!(ExitCode::DeadlineExceeded.code(), 5);
311 assert_eq!(ExitCode::Partial.code(), 6);
312 }
313
314 /// The `"partial"` status string renders for `ExitCode::Partial` (#2265).
315 ///
316 /// Why: Downstream callers (the bake-off harness) branch on this exact
317 /// string; it must render distinctly from `"run_failure"`.
318 /// What: Render a report with `exit: ExitCode::Partial`; assert the JSON
319 /// `status` field and the human summary line both say `"partial"`.
320 /// Test: this test.
321 #[test]
322 fn partial_status_renders_distinctly_from_run_failure() {
323 let report = sample_report(ExitCode::Partial, "+++ added: x.py\n");
324 let rendered = report.render_json();
325 let parsed: serde_json::Value = serde_json::from_str(&rendered).expect("valid JSON");
326 assert_eq!(parsed["status"], "partial");
327 assert_eq!(parsed["exit_code"], 6);
328 assert!(report.render_human().contains("status=partial"));
329 }
330
331 /// JSON render carries status, diff, transcript, usage, and cost.
332 ///
333 /// Why: `--json` consumers depend on this exact shape.
334 /// What: Render a success report; parse it back; assert key fields.
335 /// Test: this test.
336 #[test]
337 fn report_renders_json() {
338 let report = sample_report(ExitCode::Success, "+++ added: x.py\n");
339 let rendered = report.render_json();
340 let parsed: serde_json::Value = serde_json::from_str(&rendered).expect("valid JSON");
341
342 assert_eq!(parsed["status"], "success");
343 assert_eq!(parsed["exit_code"], 0);
344 assert_eq!(parsed["agent"], "pm");
345 assert!(parsed["diff"].as_str().unwrap().contains("added: x.py"));
346 assert_eq!(parsed["transcript"].as_array().unwrap().len(), 2);
347 assert_eq!(parsed["usage"]["prompt_tokens"], 100);
348 assert_eq!(parsed["cost_usd"], 0.001);
349 // The engineer turn must carry its own model slug for #1035 assertions.
350 assert_eq!(parsed["transcript"][1]["model"], "deepseek/deepseek-chat");
351 }
352
353 /// Human render summarises transcript, diff, and usage.
354 ///
355 /// Why: Operators read this; key facts must be present.
356 /// What: Render a success report; assert role labels, the diff, and usage line.
357 /// Test: this test.
358 #[test]
359 fn report_renders_human() {
360 let report = sample_report(ExitCode::Success, "+++ added: x.py\n");
361 let text = report.render_human();
362 assert!(text.contains("status=success"));
363 assert!(text.contains("[pm|openai/gpt-4o-mini]"));
364 assert!(text.contains("[python-engineer|deepseek/deepseek-chat]"));
365 assert!(text.contains("added: x.py"));
366 assert!(text.contains("prompt=100 completion=40"));
367 }
368
369 /// A no-changes report renders "(no changes)" in the human form.
370 ///
371 /// Why: The no-op outcome must be visible to a human reader.
372 /// What: Render with an empty diff; assert the marker.
373 /// Test: this test.
374 #[test]
375 fn human_render_shows_no_changes() {
376 let report = sample_report(ExitCode::NoChanges, "");
377 let text = report.render_human();
378 assert!(text.contains("(no changes)"), "text: {text}");
379 assert!(text.contains("status=no_changes"));
380 }
381
382 /// `aggregate_usage_per_role` sums every turn's usage and prices the total.
383 ///
384 /// Why: The run cost is the combined cost across PM + engineer turns; the math
385 /// must be exact and span the whole transcript.
386 /// What: Sum two turns' usages (same model for both roles here — the
387 /// per-role split itself is covered by
388 /// `aggregate_usage_per_role_prices_each_role_separately` below), assert
389 /// field-wise totals and a non-negative cost.
390 /// Test: this test.
391 #[test]
392 fn usage_and_cost_aggregate() {
393 let turns = vec![
394 TurnRecord {
395 role: "pm".into(),
396 model: "openai/gpt-4o-mini".into(),
397 text: String::new(),
398 tool_calls: vec![],
399 usage: TokenUsage::new(10, 5, 0, 0),
400 },
401 TurnRecord {
402 role: "python-engineer".into(),
403 model: "openai/gpt-4o-mini".into(),
404 text: "done".into(),
405 tool_calls: vec![],
406 usage: TokenUsage::new(20, 8, 0, 0),
407 },
408 ];
409 let (total, cost) =
410 aggregate_usage_per_role(&turns, "openai/gpt-4o-mini", "openai/gpt-4o-mini");
411 assert_eq!(total.prompt_tokens, 30);
412 assert_eq!(total.completion_tokens, 13);
413 assert!(cost >= 0.0, "cost must be non-negative");
414 }
415
416 /// `aggregate_usage_per_role` must price the PM's and the engineer's
417 /// turns against their OWN resolved models — the #1475 bug 1 fix.
418 ///
419 /// Why: When the engineer routes to a different (here, deliberately
420 /// pricier) model than the PM, pricing the whole transcript against the
421 /// PM model alone would be wrong by construction; this pins the fix.
422 /// What: One PM turn priced at a cheap model, one engineer turn priced
423 /// at an expensive model; assert the per-role total differs from (and
424 /// exceeds) what blending everything under the PM model would produce.
425 /// Test: this test.
426 #[test]
427 fn aggregate_usage_per_role_prices_each_role_separately() {
428 let turns = vec![
429 TurnRecord {
430 role: "pm".into(),
431 model: "anthropic/claude-haiku-4".into(),
432 text: String::new(),
433 tool_calls: vec!["delegate_to_agent".into()],
434 usage: TokenUsage::new(1000, 500, 0, 0),
435 },
436 TurnRecord {
437 role: "python-engineer".into(),
438 model: "anthropic/claude-sonnet-4-5".into(),
439 text: "done".into(),
440 tool_calls: vec![],
441 usage: TokenUsage::new(2000, 1000, 0, 0),
442 },
443 ];
444 let (_, per_role_cost) = aggregate_usage_per_role(
445 &turns,
446 "anthropic/claude-haiku-4",
447 "anthropic/claude-sonnet-4-5",
448 );
449 // Blending everything under the PM (haiku, cheaper) model would
450 // understate the true cost since the engineer's turn actually ran
451 // on the pricier sonnet model.
452 let blended_cost = crate::perf::cost_usd("anthropic/claude-haiku-4", 3000, 1500, 0, 0);
453 assert_ne!(
454 per_role_cost, blended_cost,
455 "per-role pricing must differ from blending everything under the PM model"
456 );
457 }
458
459 /// `aggregate_usage_per_role` prefers a turn's own authoritative
460 /// `usage.cost_usd` over the static per-token recompute (response-side
461 /// cache-usage fix).
462 ///
463 /// Why: The static pricing table cannot see OpenRouter's cache discount;
464 /// only the provider-reported `cost` reflects it. This is the exact gap
465 /// that made #2156's cost thesis unverifiable end-to-end.
466 /// What: One turn carries an authoritative cost that is deliberately far
467 /// below what static pricing would compute for its token counts; one turn
468 /// carries no authoritative cost (static fallback). Assert the total cost
469 /// is exactly the authoritative value plus the static fallback for the
470 /// second turn — i.e. the first turn's static price is NOT used.
471 /// Test: this test.
472 #[test]
473 fn aggregate_usage_per_role_prefers_authoritative_cost() {
474 let mut authoritative_usage = TokenUsage::new(1_000_000, 0, 900_000, 100_000);
475 authoritative_usage.cost_usd = Some(0.0005); // far below static per-token price
476 let turns = vec![
477 TurnRecord {
478 role: "pm".into(),
479 model: "anthropic/claude-sonnet-4-5".into(),
480 text: String::new(),
481 tool_calls: vec![],
482 usage: authoritative_usage,
483 },
484 TurnRecord {
485 role: "python-engineer".into(),
486 model: "anthropic/claude-sonnet-4-5".into(),
487 text: "done".into(),
488 tool_calls: vec![],
489 usage: TokenUsage::new(100, 50, 0, 0),
490 },
491 ];
492 let (_, cost) = aggregate_usage_per_role(
493 &turns,
494 "anthropic/claude-sonnet-4-5",
495 "anthropic/claude-sonnet-4-5",
496 );
497 let expected_fallback = crate::perf::cost_usd("anthropic/claude-sonnet-4-5", 100, 50, 0, 0);
498 assert!(
499 (cost - (0.0005 + expected_fallback)).abs() < 1e-12,
500 "expected authoritative cost + static fallback, got {cost}"
501 );
502 }
503}