trusty-code 0.7.0

Per-project Claude-Code-compatible MPM orchestration harness (bin: tcode) — an original coding harness, tracked under epic #2052.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
//! Run report: structured result, exit codes, and human/JSON rendering (#1034).
//!
//! Why: `run-task` must emit its outcome in two faithful forms — a human-readable
//! summary on a normal terminal, and a clean machine-readable JSON document when
//! `--json` is set (stdout must then carry *only* that JSON so callers can parse
//! it). Both forms draw from one `RunReport` so they never drift. Meaningful exit
//! codes let scripts branch on success vs. config error vs. run failure vs. a
//! no-op run.
//! What: `RunReport` bundles the diff, transcript, and usage/cost; `ExitCode`
//! enumerates the distinct outcomes; `render_human` / `render_json` produce the
//! two output forms.
//! Test: `run_task::tests` assert the JSON shape, the human summary content, and
//! the exit-code mapping.

use serde_json::json;

use crate::perf::TokenUsage;
use crate::run_task::recorder::TurnRecord;

/// Distinct process exit codes for a `run-task` invocation.
///
/// Why: A caller (CI, the PM smoke-test, a wrapper script) needs to distinguish
/// outcomes without parsing output. The ladder separates a clean success, a
/// successful run that changed nothing, a configuration error (bad agent, bad
/// project), a runtime failure (the loop or LLM errored), (#2207) the
/// wall-clock deadline firing before the PM reached `finish_task` — a run that
/// may have made real, useful progress and must not be conflated with a
/// genuine `RunFailure` (the bug that blocked the M3 bake-off L1 pilot: a
/// deadline hit at turn 13 on an otherwise fully-passing solution reported the
/// same `run_failure` a real crash would) — and (#2265) a PM turn-cap or
/// re-delegation-cap hit that STILL produced a deliverable, the same class of
/// bug as #2207's but triggered by exhausting turns/re-delegation attempts
/// rather than wall-clock time.
/// What: `repr(i32)` so the values are stable and documented; `Success = 0`.
/// Test: `run_task::tests::exit_codes_are_distinct`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(i32)]
pub enum ExitCode {
    /// The run completed and produced a diff. `0`.
    Success = 0,
    /// Configuration error: missing/invalid agent, bad project path, missing key. `2`.
    ConfigError = 2,
    /// Runtime failure: the agent loop or LLM call errored (excludes the
    /// deadline and partial paths — see `DeadlineExceeded` and `Partial`). `3`.
    RunFailure = 3,
    /// The run completed but changed nothing (empty diff). `4`.
    NoChanges = 4,
    /// The configured wall-clock deadline elapsed before the PM loop reached
    /// a terminal state (#2207). Distinct from `RunFailure` so a caller (e.g.
    /// the M3 bake-off runner) can tell "timed out, possibly close to done"
    /// from "genuinely errored". `5`.
    DeadlineExceeded = 5,
    /// The PM's own turn cap, or the (#2265) engineer re-delegation cap, was
    /// exhausted, but a non-empty diff shows a deliverable was actually
    /// produced. Distinct from `RunFailure` so a caller does not discard a
    /// working, on-disk solution as an opaque crash purely because the PM ran
    /// out of turns/retries absorbing engineer failures — trusty-code cannot
    /// generically verify correctness, so this status only claims "work was
    /// produced", leaving scoring to the downstream harness. `6`.
    Partial = 6,
}

impl ExitCode {
    /// The numeric exit code.
    ///
    /// Why: `process::exit` takes an `i32`; this is the single conversion point.
    /// What: Returns `self as i32`.
    /// Test: `run_task::tests::exit_codes_are_distinct`.
    pub fn code(self) -> i32 {
        self as i32
    }

    /// Recover the typed outcome from a child process's numeric exit code
    /// (#4351).
    ///
    /// Why: a caller that SPAWNS `tcode` (see
    /// `trusty_agents::tools::pm_bridge_backend::ProcessPmBridge`) gets an
    /// `i32` back and has to classify it. Without this, every such caller
    /// re-types the literals `0`/`4`/`5`/`6`, and renumbering a variant here
    /// silently misclassifies runs at each of those sites — a `Partial` read
    /// as a failure discards working code.
    /// What: the inverse of [`Self::code`], written against `code()` rather
    /// than literals so the two can never disagree. `None` for a number this
    /// enum does not define, which the caller decides how to treat.
    /// Test: `tests::from_code_is_the_inverse_of_code`,
    /// `tests::from_code_rejects_an_undefined_number`.
    pub fn from_code(code: i32) -> Option<Self> {
        [
            Self::Success,
            Self::ConfigError,
            Self::RunFailure,
            Self::NoChanges,
            Self::DeadlineExceeded,
            Self::Partial,
        ]
        .into_iter()
        .find(|candidate| candidate.code() == code)
    }
}

/// The full result of a `run-task` invocation, ready to render.
///
/// Why: One source of truth for both output forms keeps the human and JSON
/// reports in lockstep and makes the success path trivially testable.
/// What: `agent` is the top-level (PM) agent name; `task` is the request; `diff`
/// is the captured working-tree change; `transcript` is the ordered PM+engineer
/// turns; `usage` is the aggregated token usage; `cost_usd` is the summed cost;
/// `exit` is the computed outcome.
/// Test: `run_task::tests::report_renders_json` and `report_renders_human`.
#[derive(Debug, Clone)]
pub struct RunReport {
    /// Top-level agent name (the PM).
    pub agent: String,
    /// The task description that was run.
    pub task: String,
    /// Captured working-tree diff (empty when nothing changed).
    pub diff: String,
    /// Ordered transcript of every PM and engineer turn.
    pub transcript: Vec<TurnRecord>,
    /// Aggregated token usage across the whole run.
    pub usage: TokenUsage,
    /// Summed USD cost across the whole run (`None` when pricing is unavailable).
    pub cost_usd: Option<f64>,
    /// Computed process exit outcome.
    pub exit: ExitCode,
}

impl RunReport {
    /// Render the report as a single machine-readable JSON document.
    ///
    /// Why: `--json` mode requires clean, parseable stdout; this is the only thing
    /// printed in that mode.
    /// What: Serialises all fields into a stable JSON object, including a `status`
    /// string derived from `exit`, a `cost_usd` that is `null` when pricing is
    /// unavailable, and (#2823) a `build` object naming the binary that produced
    /// the run. Pretty-printed for readability without affecting parseability.
    /// Test: `run_task::tests::report_renders_json`,
    /// `report::tests::report_json_carries_build_provenance`.
    pub fn render_json(&self) -> String {
        let value = json!({
            "status": self.status_str(),
            // Build provenance is read from compile-time constants rather than
            // carried on `RunReport`: the binary rendering the report is by
            // construction the binary that produced the run, so threading a
            // constant through every construction site could only introduce
            // drift.
            "build": crate::build_info::provenance_json(),
            "exit_code": self.exit.code(),
            "agent": self.agent,
            "task": self.task,
            "diff": self.diff,
            "transcript": self.transcript,
            "usage": {
                "prompt_tokens": self.usage.prompt_tokens,
                "completion_tokens": self.usage.completion_tokens,
                "cache_read_tokens": self.usage.cache_read_tokens,
                "cache_creation_tokens": self.usage.cache_creation_tokens,
            },
            "cost_usd": self.cost_usd,
        });
        serde_json::to_string_pretty(&value).unwrap_or_else(|_| "{}".to_string())
    }

    /// Render the report as a human-readable summary.
    ///
    /// Why: On a normal terminal the operator wants a scannable summary, not raw
    /// JSON. The diff is shown verbatim; the transcript is condensed to one line
    /// per turn; usage and cost are a footer.
    /// What: Builds a multi-section string: a header (including the #2823 build
    /// stamp, so a pasted terminal summary is as attributable as the JSON form),
    /// the transcript (role, model, truncated text, tool calls), the diff (or
    /// "no changes"), and a usage/cost footer.
    /// Test: `run_task::tests::report_renders_human`,
    /// `report::tests::report_human_carries_build_provenance`.
    pub fn render_human(&self) -> String {
        let mut out = String::new();
        out.push_str(&format!(
            "tcode run-task: agent={} status={}\n",
            self.agent,
            self.status_str()
        ));
        out.push_str(&format!(
            "build: {} ({} {})\n",
            crate::build_info::VERSION,
            crate::build_info::GIT_HASH,
            crate::build_info::COMMIT_DATE,
        ));
        out.push_str(&format!("task: {}\n\n", self.task));

        out.push_str("── Transcript ──\n");
        if self.transcript.is_empty() {
            out.push_str("(no turns recorded)\n");
        } else {
            for (i, turn) in self.transcript.iter().enumerate() {
                let text_preview: String = turn.text.chars().take(120).collect();
                let tools = if turn.tool_calls.is_empty() {
                    String::new()
                } else {
                    format!(" tools=[{}]", turn.tool_calls.join(", "))
                };
                out.push_str(&format!(
                    "{n}. [{role}|{model}]{tools} {text}\n",
                    n = i + 1,
                    role = turn.role,
                    model = turn.model,
                    text = text_preview,
                ));
            }
        }

        out.push_str("\n── Diff ──\n");
        if self.diff.trim().is_empty() {
            out.push_str("(no changes)\n");
        } else {
            out.push_str(&self.diff);
            if !self.diff.ends_with('\n') {
                out.push('\n');
            }
        }

        out.push_str("\n── Usage ──\n");
        let cost = match self.cost_usd {
            Some(c) => format!("${c:.6}"),
            None => "(pricing unavailable)".to_string(),
        };
        out.push_str(&format!(
            "prompt={} completion={} cache_read={} cache_creation={} cost={}\n",
            self.usage.prompt_tokens,
            self.usage.completion_tokens,
            self.usage.cache_read_tokens,
            self.usage.cache_creation_tokens,
            cost,
        ));
        out
    }

    /// Map the exit outcome to a stable status string.
    ///
    /// Why: Both output forms label the outcome with the same vocabulary.
    /// What: Returns `"success"`, `"no_changes"`, `"config_error"`,
    /// `"run_failure"`, (#2207) `"deadline_exceeded"`, or (#2265) `"partial"`.
    /// Test: `run_task::tests::report_renders_json`,
    /// `run_task::tests::exit_code_reflects_deadline_exceeded_distinct_from_run_failure`.
    fn status_str(&self) -> &'static str {
        match self.exit {
            ExitCode::Success => "success",
            ExitCode::NoChanges => "no_changes",
            ExitCode::ConfigError => "config_error",
            ExitCode::RunFailure => "run_failure",
            ExitCode::DeadlineExceeded => "deadline_exceeded",
            ExitCode::Partial => "partial",
        }
    }
}

/// Sum every transcript turn's usage, pricing EACH turn against its OWN
/// role's resolved model rather than blending the whole transcript under
/// one model (#1475 bug 1 fix).
///
/// Why: The PM's `AgentOutput.usage` only covers the PM's own turns — the
/// engineer's usage is lost when its output flows back as a tool-result
/// string. The transcript recorder, by contrast, captures the
/// provider-reported usage of *every* PM and engineer turn, so summing
/// those turns is the faithful run total. Pricing the WHOLE total against a
/// single (PM) model — the original #1475 bug — silently mis-prices every
/// engineer turn whenever the engineer routes to a different, often more
/// expensive, model: directly undercuts the #1035 cost-comparison use case
/// this run exists to support. This is the SAME fix `task::executor`
/// applied for the daemon path (#2056); this is now the ONE shared
/// implementation both paths call, so they can never independently drift.
/// What: Field-wise sums each turn's `usage` into a single `TokenUsage`
/// (unchanged). Per turn, PREFERS the turn's own `usage.cost_usd` —
/// OpenRouter's authoritative, already cache-discount-aware cost
/// (response-side cache-usage fix) — when present; only falls back to the
/// static per-token recompute (priced per role: `pm_model` for
/// `role == "pm"`, `engineer_model` otherwise) when the turn carries no
/// authoritative cost. Sums the per-turn costs. Returns `(total_usage,
/// cost)`.
/// Test: `run_task::tests::usage_and_cost_aggregate_end_to_end`,
/// `report::tests::aggregate_usage_per_role_prices_each_role_separately`,
/// `report::tests::aggregate_usage_per_role_prefers_authoritative_cost`.
pub fn aggregate_usage_per_role(
    turns: &[TurnRecord],
    pm_model: &str,
    engineer_model: &str,
) -> (TokenUsage, f64) {
    let mut total = TokenUsage::default();
    let mut cost = 0.0;
    for turn in turns {
        total.add(&turn.usage);
        cost += turn.usage.cost_usd.unwrap_or_else(|| {
            let model = if turn.role == "pm" {
                pm_model
            } else {
                engineer_model
            };
            crate::perf::cost_usd(
                model,
                turn.usage.prompt_tokens,
                turn.usage.completion_tokens,
                turn.usage.cache_read_tokens,
                turn.usage.cache_creation_tokens,
            )
        });
    }
    (total, cost)
}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    /// Every variant this enum defines must survive `code()` -> `from_code()`.
    /// The list is written out so a NEW variant that `from_code`'s own lookup
    /// forgot shows up here as a failure rather than as a silent `None`.
    #[test]
    fn from_code_is_the_inverse_of_code() {
        for exit in [
            ExitCode::Success,
            ExitCode::ConfigError,
            ExitCode::RunFailure,
            ExitCode::NoChanges,
            ExitCode::DeadlineExceeded,
            ExitCode::Partial,
        ] {
            assert_eq!(
                ExitCode::from_code(exit.code()),
                Some(exit),
                "{exit:?} did not round-trip through its own numeric code"
            );
        }
    }

    /// A number this enum does not define — including a negative one, or the
    /// `1` no variant claims — is `None`, not a wrong variant.
    #[test]
    fn from_code_rejects_an_undefined_number() {
        for code in [-1, 1, 7, 137] {
            assert_eq!(ExitCode::from_code(code), None, "code {code}");
        }
    }

    fn sample_report(exit: ExitCode, diff: &str) -> RunReport {
        RunReport {
            agent: "pm".into(),
            task: "do the thing".into(),
            diff: diff.into(),
            transcript: vec![
                TurnRecord {
                    role: "pm".into(),
                    model: "openai/gpt-4o-mini".into(),
                    text: String::new(),
                    tool_calls: vec!["delegate_to_agent".into()],
                    ran_test_command: false,
                    usage: TokenUsage::new(60, 20, 0, 0),
                },
                TurnRecord {
                    role: "python-engineer".into(),
                    model: "deepseek/deepseek-chat".into(),
                    text: "wrote the file".into(),
                    tool_calls: vec!["write_file".into()],
                    ran_test_command: false,
                    usage: TokenUsage::new(40, 20, 0, 0),
                },
            ],
            usage: TokenUsage::new(100, 40, 0, 0),
            cost_usd: Some(0.001),
            exit,
        }
    }

    /// Exit codes are distinct and stable.
    ///
    /// Why: Scripts branch on these; collisions would be silent breakage.
    /// What: Assert the six codes are 0/2/3/4/5/6 and pairwise distinct.
    /// Test: this test.
    #[test]
    fn exit_codes_are_distinct() {
        assert_eq!(ExitCode::Success.code(), 0);
        assert_eq!(ExitCode::ConfigError.code(), 2);
        assert_eq!(ExitCode::RunFailure.code(), 3);
        assert_eq!(ExitCode::NoChanges.code(), 4);
        assert_eq!(ExitCode::DeadlineExceeded.code(), 5);
        assert_eq!(ExitCode::Partial.code(), 6);
    }

    /// The `"partial"` status string renders for `ExitCode::Partial` (#2265).
    ///
    /// Why: Downstream callers (the bake-off harness) branch on this exact
    /// string; it must render distinctly from `"run_failure"`.
    /// What: Render a report with `exit: ExitCode::Partial`; assert the JSON
    /// `status` field and the human summary line both say `"partial"`.
    /// Test: this test.
    #[test]
    fn partial_status_renders_distinctly_from_run_failure() {
        let report = sample_report(ExitCode::Partial, "+++ added: x.py\n");
        let rendered = report.render_json();
        let parsed: serde_json::Value = serde_json::from_str(&rendered).expect("valid JSON");
        assert_eq!(parsed["status"], "partial");
        assert_eq!(parsed["exit_code"], 6);
        assert!(report.render_human().contains("status=partial"));
    }

    /// JSON render carries status, diff, transcript, usage, and cost.
    ///
    /// Why: `--json` consumers depend on this exact shape.
    /// What: Render a success report; parse it back; assert key fields.
    /// Test: this test.
    #[test]
    fn report_renders_json() {
        let report = sample_report(ExitCode::Success, "+++ added: x.py\n");
        let rendered = report.render_json();
        let parsed: serde_json::Value = serde_json::from_str(&rendered).expect("valid JSON");

        assert_eq!(parsed["status"], "success");
        assert_eq!(parsed["exit_code"], 0);
        assert_eq!(parsed["agent"], "pm");
        assert!(parsed["diff"].as_str().unwrap().contains("added: x.py"));
        assert_eq!(parsed["transcript"].as_array().unwrap().len(), 2);
        assert_eq!(parsed["usage"]["prompt_tokens"], 100);
        assert_eq!(parsed["cost_usd"], 0.001);
        // The engineer turn must carry its own model slug for #1035 assertions.
        assert_eq!(parsed["transcript"][1]["model"], "deepseek/deepseek-chat");
    }

    /// The JSON report carries build provenance identifying the binary (#2823).
    ///
    /// Why: This is the acceptance criterion for #2823 — a run's artifacts must
    /// be attributable to the build that produced them without resorting to
    /// install-timestamp archaeology (which yielded a WRONG conclusion during
    /// the 2026-07-16 L4 validation). The bake-off harness reads these exact
    /// keys, so they are a wire contract.
    /// What: Render a report; assert `build.version` matches the crate semver
    /// and that `build.commit` / `build.commit_date` are present, non-null
    /// strings (either real values or the `"unknown"` fallback).
    /// Test: this test.
    #[test]
    fn report_json_carries_build_provenance() {
        let report = sample_report(ExitCode::Success, "+++ added: x.py\n");
        let parsed: serde_json::Value =
            serde_json::from_str(&report.render_json()).expect("valid JSON");

        assert_eq!(parsed["build"]["version"], env!("CARGO_PKG_VERSION"));
        assert_eq!(parsed["build"]["commit"], crate::build_info::GIT_HASH);
        assert_eq!(
            parsed["build"]["commit_date"],
            crate::build_info::COMMIT_DATE
        );
        assert!(
            parsed["build"]["commit"]
                .as_str()
                .is_some_and(|s| !s.is_empty()),
            "build.commit must be a non-empty string"
        );
    }

    /// The human report header carries the same build stamp (#2823).
    ///
    /// Why: Operators paste terminal summaries into issues; that summary should
    /// be exactly as attributable as the JSON form, or the provenance gap just
    /// moves rather than closes.
    /// What: Assert the header contains a `build:` line naming the semver and
    /// the commit SHA.
    /// Test: this test.
    #[test]
    fn report_human_carries_build_provenance() {
        let text = sample_report(ExitCode::Success, "+++ added: x.py\n").render_human();
        assert!(
            text.contains(&format!("build: {}", env!("CARGO_PKG_VERSION"))),
            "missing build stamp, got: {text}"
        );
        assert!(text.contains(crate::build_info::GIT_HASH), "got: {text}");
    }

    /// Human render summarises transcript, diff, and usage.
    ///
    /// Why: Operators read this; key facts must be present.
    /// What: Render a success report; assert role labels, the diff, and usage line.
    /// Test: this test.
    #[test]
    fn report_renders_human() {
        let report = sample_report(ExitCode::Success, "+++ added: x.py\n");
        let text = report.render_human();
        assert!(text.contains("status=success"));
        assert!(text.contains("[pm|openai/gpt-4o-mini]"));
        assert!(text.contains("[python-engineer|deepseek/deepseek-chat]"));
        assert!(text.contains("added: x.py"));
        assert!(text.contains("prompt=100 completion=40"));
    }

    /// A no-changes report renders "(no changes)" in the human form.
    ///
    /// Why: The no-op outcome must be visible to a human reader.
    /// What: Render with an empty diff; assert the marker.
    /// Test: this test.
    #[test]
    fn human_render_shows_no_changes() {
        let report = sample_report(ExitCode::NoChanges, "");
        let text = report.render_human();
        assert!(text.contains("(no changes)"), "text: {text}");
        assert!(text.contains("status=no_changes"));
    }

    /// `aggregate_usage_per_role` sums every turn's usage and prices the total.
    ///
    /// Why: The run cost is the combined cost across PM + engineer turns; the math
    /// must be exact and span the whole transcript.
    /// What: Sum two turns' usages (same model for both roles here — the
    /// per-role split itself is covered by
    /// `aggregate_usage_per_role_prices_each_role_separately` below), assert
    /// field-wise totals and a non-negative cost.
    /// Test: this test.
    #[test]
    fn usage_and_cost_aggregate() {
        let turns = vec![
            TurnRecord {
                role: "pm".into(),
                model: "openai/gpt-4o-mini".into(),
                text: String::new(),
                tool_calls: vec![],
                ran_test_command: false,
                usage: TokenUsage::new(10, 5, 0, 0),
            },
            TurnRecord {
                role: "python-engineer".into(),
                model: "openai/gpt-4o-mini".into(),
                text: "done".into(),
                tool_calls: vec![],
                ran_test_command: false,
                usage: TokenUsage::new(20, 8, 0, 0),
            },
        ];
        let (total, cost) =
            aggregate_usage_per_role(&turns, "openai/gpt-4o-mini", "openai/gpt-4o-mini");
        assert_eq!(total.prompt_tokens, 30);
        assert_eq!(total.completion_tokens, 13);
        assert!(cost >= 0.0, "cost must be non-negative");
    }

    /// `aggregate_usage_per_role` must price the PM's and the engineer's
    /// turns against their OWN resolved models — the #1475 bug 1 fix.
    ///
    /// Why: When the engineer routes to a different (here, deliberately
    /// pricier) model than the PM, pricing the whole transcript against the
    /// PM model alone would be wrong by construction; this pins the fix.
    /// What: One PM turn priced at a cheap model, one engineer turn priced
    /// at an expensive model; assert the per-role total differs from (and
    /// exceeds) what blending everything under the PM model would produce.
    /// Test: this test.
    #[test]
    fn aggregate_usage_per_role_prices_each_role_separately() {
        let turns = vec![
            TurnRecord {
                role: "pm".into(),
                model: "anthropic/claude-haiku-4".into(),
                text: String::new(),
                tool_calls: vec!["delegate_to_agent".into()],
                ran_test_command: false,
                usage: TokenUsage::new(1000, 500, 0, 0),
            },
            TurnRecord {
                role: "python-engineer".into(),
                model: "anthropic/claude-sonnet-4-5".into(),
                text: "done".into(),
                tool_calls: vec![],
                ran_test_command: false,
                usage: TokenUsage::new(2000, 1000, 0, 0),
            },
        ];
        let (_, per_role_cost) = aggregate_usage_per_role(
            &turns,
            "anthropic/claude-haiku-4",
            "anthropic/claude-sonnet-4-5",
        );
        // Blending everything under the PM (haiku, cheaper) model would
        // understate the true cost since the engineer's turn actually ran
        // on the pricier sonnet model.
        let blended_cost = crate::perf::cost_usd("anthropic/claude-haiku-4", 3000, 1500, 0, 0);
        assert_ne!(
            per_role_cost, blended_cost,
            "per-role pricing must differ from blending everything under the PM model"
        );
    }

    /// `aggregate_usage_per_role` prefers a turn's own authoritative
    /// `usage.cost_usd` over the static per-token recompute (response-side
    /// cache-usage fix).
    ///
    /// Why: The static pricing table cannot see OpenRouter's cache discount;
    /// only the provider-reported `cost` reflects it. This is the exact gap
    /// that made #2156's cost thesis unverifiable end-to-end.
    /// What: One turn carries an authoritative cost that is deliberately far
    /// below what static pricing would compute for its token counts; one turn
    /// carries no authoritative cost (static fallback). Assert the total cost
    /// is exactly the authoritative value plus the static fallback for the
    /// second turn — i.e. the first turn's static price is NOT used.
    /// Test: this test.
    #[test]
    fn aggregate_usage_per_role_prefers_authoritative_cost() {
        let mut authoritative_usage = TokenUsage::new(1_000_000, 0, 900_000, 100_000);
        authoritative_usage.cost_usd = Some(0.0005); // far below static per-token price
        let turns = vec![
            TurnRecord {
                role: "pm".into(),
                model: "anthropic/claude-sonnet-4-5".into(),
                text: String::new(),
                tool_calls: vec![],
                ran_test_command: false,
                usage: authoritative_usage,
            },
            TurnRecord {
                role: "python-engineer".into(),
                model: "anthropic/claude-sonnet-4-5".into(),
                text: "done".into(),
                tool_calls: vec![],
                ran_test_command: false,
                usage: TokenUsage::new(100, 50, 0, 0),
            },
        ];
        let (_, cost) = aggregate_usage_per_role(
            &turns,
            "anthropic/claude-sonnet-4-5",
            "anthropic/claude-sonnet-4-5",
        );
        let expected_fallback = crate::perf::cost_usd("anthropic/claude-sonnet-4-5", 100, 50, 0, 0);
        assert!(
            (cost - (0.0005 + expected_fallback)).abs() < 1e-12,
            "expected authoritative cost + static fallback, got {cost}"
        );
    }
}