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`, a `cost_usd` that is `null` when pricing is
108 /// unavailable, and (#2823) a `build` object naming the binary that produced
109 /// the run. Pretty-printed for readability without affecting parseability.
110 /// Test: `run_task::tests::report_renders_json`,
111 /// `report::tests::report_json_carries_build_provenance`.
112 pub fn render_json(&self) -> String {
113 let value = json!({
114 "status": self.status_str(),
115 // Build provenance is read from compile-time constants rather than
116 // carried on `RunReport`: the binary rendering the report is by
117 // construction the binary that produced the run, so threading a
118 // constant through every construction site could only introduce
119 // drift.
120 "build": crate::build_info::provenance_json(),
121 "exit_code": self.exit.code(),
122 "agent": self.agent,
123 "task": self.task,
124 "diff": self.diff,
125 "transcript": self.transcript,
126 "usage": {
127 "prompt_tokens": self.usage.prompt_tokens,
128 "completion_tokens": self.usage.completion_tokens,
129 "cache_read_tokens": self.usage.cache_read_tokens,
130 "cache_creation_tokens": self.usage.cache_creation_tokens,
131 },
132 "cost_usd": self.cost_usd,
133 });
134 serde_json::to_string_pretty(&value).unwrap_or_else(|_| "{}".to_string())
135 }
136
137 /// Render the report as a human-readable summary.
138 ///
139 /// Why: On a normal terminal the operator wants a scannable summary, not raw
140 /// JSON. The diff is shown verbatim; the transcript is condensed to one line
141 /// per turn; usage and cost are a footer.
142 /// What: Builds a multi-section string: a header (including the #2823 build
143 /// stamp, so a pasted terminal summary is as attributable as the JSON form),
144 /// the transcript (role, model, truncated text, tool calls), the diff (or
145 /// "no changes"), and a usage/cost footer.
146 /// Test: `run_task::tests::report_renders_human`,
147 /// `report::tests::report_human_carries_build_provenance`.
148 pub fn render_human(&self) -> String {
149 let mut out = String::new();
150 out.push_str(&format!(
151 "tcode run-task: agent={} status={}\n",
152 self.agent,
153 self.status_str()
154 ));
155 out.push_str(&format!(
156 "build: {} ({} {})\n",
157 crate::build_info::VERSION,
158 crate::build_info::GIT_HASH,
159 crate::build_info::COMMIT_DATE,
160 ));
161 out.push_str(&format!("task: {}\n\n", self.task));
162
163 out.push_str("── Transcript ──\n");
164 if self.transcript.is_empty() {
165 out.push_str("(no turns recorded)\n");
166 } else {
167 for (i, turn) in self.transcript.iter().enumerate() {
168 let text_preview: String = turn.text.chars().take(120).collect();
169 let tools = if turn.tool_calls.is_empty() {
170 String::new()
171 } else {
172 format!(" tools=[{}]", turn.tool_calls.join(", "))
173 };
174 out.push_str(&format!(
175 "{n}. [{role}|{model}]{tools} {text}\n",
176 n = i + 1,
177 role = turn.role,
178 model = turn.model,
179 text = text_preview,
180 ));
181 }
182 }
183
184 out.push_str("\n── Diff ──\n");
185 if self.diff.trim().is_empty() {
186 out.push_str("(no changes)\n");
187 } else {
188 out.push_str(&self.diff);
189 if !self.diff.ends_with('\n') {
190 out.push('\n');
191 }
192 }
193
194 out.push_str("\n── Usage ──\n");
195 let cost = match self.cost_usd {
196 Some(c) => format!("${c:.6}"),
197 None => "(pricing unavailable)".to_string(),
198 };
199 out.push_str(&format!(
200 "prompt={} completion={} cache_read={} cache_creation={} cost={}\n",
201 self.usage.prompt_tokens,
202 self.usage.completion_tokens,
203 self.usage.cache_read_tokens,
204 self.usage.cache_creation_tokens,
205 cost,
206 ));
207 out
208 }
209
210 /// Map the exit outcome to a stable status string.
211 ///
212 /// Why: Both output forms label the outcome with the same vocabulary.
213 /// What: Returns `"success"`, `"no_changes"`, `"config_error"`,
214 /// `"run_failure"`, (#2207) `"deadline_exceeded"`, or (#2265) `"partial"`.
215 /// Test: `run_task::tests::report_renders_json`,
216 /// `run_task::tests::exit_code_reflects_deadline_exceeded_distinct_from_run_failure`.
217 fn status_str(&self) -> &'static str {
218 match self.exit {
219 ExitCode::Success => "success",
220 ExitCode::NoChanges => "no_changes",
221 ExitCode::ConfigError => "config_error",
222 ExitCode::RunFailure => "run_failure",
223 ExitCode::DeadlineExceeded => "deadline_exceeded",
224 ExitCode::Partial => "partial",
225 }
226 }
227}
228
229/// Sum every transcript turn's usage, pricing EACH turn against its OWN
230/// role's resolved model rather than blending the whole transcript under
231/// one model (#1475 bug 1 fix).
232///
233/// Why: The PM's `AgentOutput.usage` only covers the PM's own turns — the
234/// engineer's usage is lost when its output flows back as a tool-result
235/// string. The transcript recorder, by contrast, captures the
236/// provider-reported usage of *every* PM and engineer turn, so summing
237/// those turns is the faithful run total. Pricing the WHOLE total against a
238/// single (PM) model — the original #1475 bug — silently mis-prices every
239/// engineer turn whenever the engineer routes to a different, often more
240/// expensive, model: directly undercuts the #1035 cost-comparison use case
241/// this run exists to support. This is the SAME fix `task::executor`
242/// applied for the daemon path (#2056); this is now the ONE shared
243/// implementation both paths call, so they can never independently drift.
244/// What: Field-wise sums each turn's `usage` into a single `TokenUsage`
245/// (unchanged). Per turn, PREFERS the turn's own `usage.cost_usd` —
246/// OpenRouter's authoritative, already cache-discount-aware cost
247/// (response-side cache-usage fix) — when present; only falls back to the
248/// static per-token recompute (priced per role: `pm_model` for
249/// `role == "pm"`, `engineer_model` otherwise) when the turn carries no
250/// authoritative cost. Sums the per-turn costs. Returns `(total_usage,
251/// cost)`.
252/// Test: `run_task::tests::usage_and_cost_aggregate_end_to_end`,
253/// `report::tests::aggregate_usage_per_role_prices_each_role_separately`,
254/// `report::tests::aggregate_usage_per_role_prefers_authoritative_cost`.
255pub fn aggregate_usage_per_role(
256 turns: &[TurnRecord],
257 pm_model: &str,
258 engineer_model: &str,
259) -> (TokenUsage, f64) {
260 let mut total = TokenUsage::default();
261 let mut cost = 0.0;
262 for turn in turns {
263 total.add(&turn.usage);
264 cost += turn.usage.cost_usd.unwrap_or_else(|| {
265 let model = if turn.role == "pm" {
266 pm_model
267 } else {
268 engineer_model
269 };
270 crate::perf::cost_usd(
271 model,
272 turn.usage.prompt_tokens,
273 turn.usage.completion_tokens,
274 turn.usage.cache_read_tokens,
275 turn.usage.cache_creation_tokens,
276 )
277 });
278 }
279 (total, cost)
280}
281
282// ── Tests ─────────────────────────────────────────────────────────────────────
283
284#[cfg(test)]
285mod tests {
286 use super::*;
287
288 fn sample_report(exit: ExitCode, diff: &str) -> RunReport {
289 RunReport {
290 agent: "pm".into(),
291 task: "do the thing".into(),
292 diff: diff.into(),
293 transcript: vec![
294 TurnRecord {
295 role: "pm".into(),
296 model: "openai/gpt-4o-mini".into(),
297 text: String::new(),
298 tool_calls: vec!["delegate_to_agent".into()],
299 ran_test_command: false,
300 usage: TokenUsage::new(60, 20, 0, 0),
301 },
302 TurnRecord {
303 role: "python-engineer".into(),
304 model: "deepseek/deepseek-chat".into(),
305 text: "wrote the file".into(),
306 tool_calls: vec!["write_file".into()],
307 ran_test_command: false,
308 usage: TokenUsage::new(40, 20, 0, 0),
309 },
310 ],
311 usage: TokenUsage::new(100, 40, 0, 0),
312 cost_usd: Some(0.001),
313 exit,
314 }
315 }
316
317 /// Exit codes are distinct and stable.
318 ///
319 /// Why: Scripts branch on these; collisions would be silent breakage.
320 /// What: Assert the six codes are 0/2/3/4/5/6 and pairwise distinct.
321 /// Test: this test.
322 #[test]
323 fn exit_codes_are_distinct() {
324 assert_eq!(ExitCode::Success.code(), 0);
325 assert_eq!(ExitCode::ConfigError.code(), 2);
326 assert_eq!(ExitCode::RunFailure.code(), 3);
327 assert_eq!(ExitCode::NoChanges.code(), 4);
328 assert_eq!(ExitCode::DeadlineExceeded.code(), 5);
329 assert_eq!(ExitCode::Partial.code(), 6);
330 }
331
332 /// The `"partial"` status string renders for `ExitCode::Partial` (#2265).
333 ///
334 /// Why: Downstream callers (the bake-off harness) branch on this exact
335 /// string; it must render distinctly from `"run_failure"`.
336 /// What: Render a report with `exit: ExitCode::Partial`; assert the JSON
337 /// `status` field and the human summary line both say `"partial"`.
338 /// Test: this test.
339 #[test]
340 fn partial_status_renders_distinctly_from_run_failure() {
341 let report = sample_report(ExitCode::Partial, "+++ added: x.py\n");
342 let rendered = report.render_json();
343 let parsed: serde_json::Value = serde_json::from_str(&rendered).expect("valid JSON");
344 assert_eq!(parsed["status"], "partial");
345 assert_eq!(parsed["exit_code"], 6);
346 assert!(report.render_human().contains("status=partial"));
347 }
348
349 /// JSON render carries status, diff, transcript, usage, and cost.
350 ///
351 /// Why: `--json` consumers depend on this exact shape.
352 /// What: Render a success report; parse it back; assert key fields.
353 /// Test: this test.
354 #[test]
355 fn report_renders_json() {
356 let report = sample_report(ExitCode::Success, "+++ added: x.py\n");
357 let rendered = report.render_json();
358 let parsed: serde_json::Value = serde_json::from_str(&rendered).expect("valid JSON");
359
360 assert_eq!(parsed["status"], "success");
361 assert_eq!(parsed["exit_code"], 0);
362 assert_eq!(parsed["agent"], "pm");
363 assert!(parsed["diff"].as_str().unwrap().contains("added: x.py"));
364 assert_eq!(parsed["transcript"].as_array().unwrap().len(), 2);
365 assert_eq!(parsed["usage"]["prompt_tokens"], 100);
366 assert_eq!(parsed["cost_usd"], 0.001);
367 // The engineer turn must carry its own model slug for #1035 assertions.
368 assert_eq!(parsed["transcript"][1]["model"], "deepseek/deepseek-chat");
369 }
370
371 /// The JSON report carries build provenance identifying the binary (#2823).
372 ///
373 /// Why: This is the acceptance criterion for #2823 — a run's artifacts must
374 /// be attributable to the build that produced them without resorting to
375 /// install-timestamp archaeology (which yielded a WRONG conclusion during
376 /// the 2026-07-16 L4 validation). The bake-off harness reads these exact
377 /// keys, so they are a wire contract.
378 /// What: Render a report; assert `build.version` matches the crate semver
379 /// and that `build.commit` / `build.commit_date` are present, non-null
380 /// strings (either real values or the `"unknown"` fallback).
381 /// Test: this test.
382 #[test]
383 fn report_json_carries_build_provenance() {
384 let report = sample_report(ExitCode::Success, "+++ added: x.py\n");
385 let parsed: serde_json::Value =
386 serde_json::from_str(&report.render_json()).expect("valid JSON");
387
388 assert_eq!(parsed["build"]["version"], env!("CARGO_PKG_VERSION"));
389 assert_eq!(parsed["build"]["commit"], crate::build_info::GIT_HASH);
390 assert_eq!(
391 parsed["build"]["commit_date"],
392 crate::build_info::COMMIT_DATE
393 );
394 assert!(
395 parsed["build"]["commit"]
396 .as_str()
397 .is_some_and(|s| !s.is_empty()),
398 "build.commit must be a non-empty string"
399 );
400 }
401
402 /// The human report header carries the same build stamp (#2823).
403 ///
404 /// Why: Operators paste terminal summaries into issues; that summary should
405 /// be exactly as attributable as the JSON form, or the provenance gap just
406 /// moves rather than closes.
407 /// What: Assert the header contains a `build:` line naming the semver and
408 /// the commit SHA.
409 /// Test: this test.
410 #[test]
411 fn report_human_carries_build_provenance() {
412 let text = sample_report(ExitCode::Success, "+++ added: x.py\n").render_human();
413 assert!(
414 text.contains(&format!("build: {}", env!("CARGO_PKG_VERSION"))),
415 "missing build stamp, got: {text}"
416 );
417 assert!(text.contains(crate::build_info::GIT_HASH), "got: {text}");
418 }
419
420 /// Human render summarises transcript, diff, and usage.
421 ///
422 /// Why: Operators read this; key facts must be present.
423 /// What: Render a success report; assert role labels, the diff, and usage line.
424 /// Test: this test.
425 #[test]
426 fn report_renders_human() {
427 let report = sample_report(ExitCode::Success, "+++ added: x.py\n");
428 let text = report.render_human();
429 assert!(text.contains("status=success"));
430 assert!(text.contains("[pm|openai/gpt-4o-mini]"));
431 assert!(text.contains("[python-engineer|deepseek/deepseek-chat]"));
432 assert!(text.contains("added: x.py"));
433 assert!(text.contains("prompt=100 completion=40"));
434 }
435
436 /// A no-changes report renders "(no changes)" in the human form.
437 ///
438 /// Why: The no-op outcome must be visible to a human reader.
439 /// What: Render with an empty diff; assert the marker.
440 /// Test: this test.
441 #[test]
442 fn human_render_shows_no_changes() {
443 let report = sample_report(ExitCode::NoChanges, "");
444 let text = report.render_human();
445 assert!(text.contains("(no changes)"), "text: {text}");
446 assert!(text.contains("status=no_changes"));
447 }
448
449 /// `aggregate_usage_per_role` sums every turn's usage and prices the total.
450 ///
451 /// Why: The run cost is the combined cost across PM + engineer turns; the math
452 /// must be exact and span the whole transcript.
453 /// What: Sum two turns' usages (same model for both roles here — the
454 /// per-role split itself is covered by
455 /// `aggregate_usage_per_role_prices_each_role_separately` below), assert
456 /// field-wise totals and a non-negative cost.
457 /// Test: this test.
458 #[test]
459 fn usage_and_cost_aggregate() {
460 let turns = vec![
461 TurnRecord {
462 role: "pm".into(),
463 model: "openai/gpt-4o-mini".into(),
464 text: String::new(),
465 tool_calls: vec![],
466 ran_test_command: false,
467 usage: TokenUsage::new(10, 5, 0, 0),
468 },
469 TurnRecord {
470 role: "python-engineer".into(),
471 model: "openai/gpt-4o-mini".into(),
472 text: "done".into(),
473 tool_calls: vec![],
474 ran_test_command: false,
475 usage: TokenUsage::new(20, 8, 0, 0),
476 },
477 ];
478 let (total, cost) =
479 aggregate_usage_per_role(&turns, "openai/gpt-4o-mini", "openai/gpt-4o-mini");
480 assert_eq!(total.prompt_tokens, 30);
481 assert_eq!(total.completion_tokens, 13);
482 assert!(cost >= 0.0, "cost must be non-negative");
483 }
484
485 /// `aggregate_usage_per_role` must price the PM's and the engineer's
486 /// turns against their OWN resolved models — the #1475 bug 1 fix.
487 ///
488 /// Why: When the engineer routes to a different (here, deliberately
489 /// pricier) model than the PM, pricing the whole transcript against the
490 /// PM model alone would be wrong by construction; this pins the fix.
491 /// What: One PM turn priced at a cheap model, one engineer turn priced
492 /// at an expensive model; assert the per-role total differs from (and
493 /// exceeds) what blending everything under the PM model would produce.
494 /// Test: this test.
495 #[test]
496 fn aggregate_usage_per_role_prices_each_role_separately() {
497 let turns = vec![
498 TurnRecord {
499 role: "pm".into(),
500 model: "anthropic/claude-haiku-4".into(),
501 text: String::new(),
502 tool_calls: vec!["delegate_to_agent".into()],
503 ran_test_command: false,
504 usage: TokenUsage::new(1000, 500, 0, 0),
505 },
506 TurnRecord {
507 role: "python-engineer".into(),
508 model: "anthropic/claude-sonnet-4-5".into(),
509 text: "done".into(),
510 tool_calls: vec![],
511 ran_test_command: false,
512 usage: TokenUsage::new(2000, 1000, 0, 0),
513 },
514 ];
515 let (_, per_role_cost) = aggregate_usage_per_role(
516 &turns,
517 "anthropic/claude-haiku-4",
518 "anthropic/claude-sonnet-4-5",
519 );
520 // Blending everything under the PM (haiku, cheaper) model would
521 // understate the true cost since the engineer's turn actually ran
522 // on the pricier sonnet model.
523 let blended_cost = crate::perf::cost_usd("anthropic/claude-haiku-4", 3000, 1500, 0, 0);
524 assert_ne!(
525 per_role_cost, blended_cost,
526 "per-role pricing must differ from blending everything under the PM model"
527 );
528 }
529
530 /// `aggregate_usage_per_role` prefers a turn's own authoritative
531 /// `usage.cost_usd` over the static per-token recompute (response-side
532 /// cache-usage fix).
533 ///
534 /// Why: The static pricing table cannot see OpenRouter's cache discount;
535 /// only the provider-reported `cost` reflects it. This is the exact gap
536 /// that made #2156's cost thesis unverifiable end-to-end.
537 /// What: One turn carries an authoritative cost that is deliberately far
538 /// below what static pricing would compute for its token counts; one turn
539 /// carries no authoritative cost (static fallback). Assert the total cost
540 /// is exactly the authoritative value plus the static fallback for the
541 /// second turn — i.e. the first turn's static price is NOT used.
542 /// Test: this test.
543 #[test]
544 fn aggregate_usage_per_role_prefers_authoritative_cost() {
545 let mut authoritative_usage = TokenUsage::new(1_000_000, 0, 900_000, 100_000);
546 authoritative_usage.cost_usd = Some(0.0005); // far below static per-token price
547 let turns = vec![
548 TurnRecord {
549 role: "pm".into(),
550 model: "anthropic/claude-sonnet-4-5".into(),
551 text: String::new(),
552 tool_calls: vec![],
553 ran_test_command: false,
554 usage: authoritative_usage,
555 },
556 TurnRecord {
557 role: "python-engineer".into(),
558 model: "anthropic/claude-sonnet-4-5".into(),
559 text: "done".into(),
560 tool_calls: vec![],
561 ran_test_command: false,
562 usage: TokenUsage::new(100, 50, 0, 0),
563 },
564 ];
565 let (_, cost) = aggregate_usage_per_role(
566 &turns,
567 "anthropic/claude-sonnet-4-5",
568 "anthropic/claude-sonnet-4-5",
569 );
570 let expected_fallback = crate::perf::cost_usd("anthropic/claude-sonnet-4-5", 100, 50, 0, 0);
571 assert!(
572 (cost - (0.0005 + expected_fallback)).abs() < 1e-12,
573 "expected authoritative cost + static fallback, got {cost}"
574 );
575 }
576}