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