trusty-code 0.8.2

Per-project Claude-Code-compatible MPM orchestration harness (bin: tcode) — an original coding harness, tracked under epic #2052.
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
//! Unit tests for cost computation and the `PerfCollector` lifecycle.
//!
//! Why: Cost math underpins every billing/UX figure; the collector's
//! record/flush behavior is the persistence contract.
//! What: `cost_usd_*` pricing cases, `truncate_preview`/`filename_stamp`
//! formatters, and collector record/total/flush tests.
//! Test: This module is itself the test coverage.

use super::*;

#[test]
fn token_usage_default_is_zeros() {
    let u = TokenUsage::default();
    assert_eq!(u.prompt_tokens, 0);
    assert_eq!(u.completion_tokens, 0);
    assert_eq!(u.cache_read_tokens, 0);
    assert_eq!(u.cache_creation_tokens, 0);
}

#[test]
fn token_usage_accumulates() {
    let mut a = TokenUsage::new(10, 5, 2, 1);
    a.add(&TokenUsage::new(3, 7, 0, 4));
    assert_eq!(a, TokenUsage::new(13, 12, 2, 5));
}

/// `TokenUsage::add` sums `cost_usd` when both sides have an authoritative
/// cost, preserves the one present side when only one does, and stays `None`
/// only when neither side has one.
///
/// Why: The response-side cache-usage fix threads OpenRouter's authoritative
/// per-call `cost` through `TokenUsage`; accumulation across turns must not
/// silently drop it.
/// What: Exercise all three `(Some, Some)` / `(Some, None)` / `(None, None)`
/// cases.
/// Test: this test.
#[test]
fn token_usage_cost_accumulates() {
    let mut both = TokenUsage::new(10, 5, 2, 1);
    both.cost_usd = Some(0.01);
    let mut other = TokenUsage::new(3, 7, 0, 4);
    other.cost_usd = Some(0.02);
    both.add(&other);
    assert_eq!(both.cost_usd, Some(0.03));

    let mut one_sided = TokenUsage::new(10, 5, 2, 1);
    one_sided.cost_usd = Some(0.01);
    one_sided.add(&TokenUsage::new(3, 7, 0, 4));
    assert_eq!(one_sided.cost_usd, Some(0.01));

    let mut neither = TokenUsage::new(10, 5, 2, 1);
    neither.add(&TokenUsage::new(3, 7, 0, 4));
    assert_eq!(neither.cost_usd, None);
}

#[test]
fn cost_usd_known_sonnet() {
    // 1M prompt tokens of sonnet = $3.00
    let c = cost_usd("anthropic/claude-sonnet-4-5", 1_000_000, 0, 0, 0);
    assert!((c - 3.0).abs() < 1e-9, "got {c}");
}

#[test]
fn cost_usd_known_haiku() {
    // 1M output tokens of haiku = $4.00
    let c = cost_usd("anthropic/claude-haiku-4", 0, 1_000_000, 0, 0);
    assert!((c - 4.0).abs() < 1e-9, "got {c}");
}

// --- #8128: explicit Claude 5 / Haiku 4.5 rows ---

/// `anthropic/claude-opus-5` prices at Opus 5's published rates, not the
/// `opus-4` fallback it used to land on.
///
/// Why (#8128): `RunReport.cost_usd` is compared against Claude Code's own
/// `total_cost_usd` in the #8127 bake-off; the 4.x fallback priced Opus 5
/// input at $15/MTok against a real $5/MTok — a 3x overstatement.
/// What: one million tokens in each bucket, asserted against $5 / $25 /
/// $0.50 / $6.25 per MTok.
/// Test: this test.
#[test]
fn cost_usd_opus_5_matches_published_rates() {
    assert!((cost_usd("anthropic/claude-opus-5", 1_000_000, 0, 0, 0) - 5.0).abs() < 1e-9);
    assert!((cost_usd("anthropic/claude-opus-5", 0, 1_000_000, 0, 0) - 25.0).abs() < 1e-9);
    assert!((cost_usd("anthropic/claude-opus-5", 0, 0, 1_000_000, 0) - 0.50).abs() < 1e-9);
    assert!((cost_usd("anthropic/claude-opus-5", 0, 0, 0, 1_000_000) - 6.25).abs() < 1e-9);
}

/// `anthropic/claude-sonnet-5` prices at Sonnet 5's published rates, not the
/// `sonnet-4` fallback.
///
/// Why (#8128): Sonnet 5 is what the `sonnet` alias and `DEFAULT_MODEL` now
/// resolve to, so this row prices the DEFAULT run — the 4.x fallback
/// overstated its input by 50%.
/// What: $2 / $10 / $0.20 / $2.50 per MTok.
/// Test: this test.
#[test]
fn cost_usd_sonnet_5_matches_published_rates() {
    assert!((cost_usd("anthropic/claude-sonnet-5", 1_000_000, 0, 0, 0) - 2.0).abs() < 1e-9);
    assert!((cost_usd("anthropic/claude-sonnet-5", 0, 1_000_000, 0, 0) - 10.0).abs() < 1e-9);
    assert!((cost_usd("anthropic/claude-sonnet-5", 0, 0, 1_000_000, 0) - 0.20).abs() < 1e-9);
    assert!((cost_usd("anthropic/claude-sonnet-5", 0, 0, 0, 1_000_000) - 2.50).abs() < 1e-9);
}

/// `claude-haiku-4.5` prices at Haiku 4.5's own published rates in BOTH
/// slug spellings, ahead of the generic `haiku-4` row.
///
/// Why (#8128): `claude-haiku-4.5` contains the substring `haiku-4`, so the
/// explicit row only works if it is matched first — this is the ordering
/// guard. The published rate ($1/$5) is also higher than the legacy Haiku
/// 3/4 row's $0.80/$4, so the fallback understated it.
/// What: the OpenRouter spelling (`-4.5`) and the Anthropic/Bedrock one
/// (`-4-5`), both at $1 / $5 / $0.10 / $1.25 per MTok.
/// Test: this test.
#[test]
fn cost_usd_haiku_4_5_matches_published_rates() {
    for slug in ["anthropic/claude-haiku-4.5", "claude-haiku-4-5"] {
        assert!(
            (cost_usd(slug, 1_000_000, 0, 0, 0) - 1.0).abs() < 1e-9,
            "input rate for {slug}"
        );
        assert!(
            (cost_usd(slug, 0, 1_000_000, 0, 0) - 5.0).abs() < 1e-9,
            "output rate for {slug}"
        );
        assert!(
            (cost_usd(slug, 0, 0, 1_000_000, 0) - 0.10).abs() < 1e-9,
            "cache-read rate for {slug}"
        );
        assert!(
            (cost_usd(slug, 0, 0, 0, 1_000_000) - 1.25).abs() < 1e-9,
            "cache-write rate for {slug}"
        );
    }
}

/// The pre-#8128 4.x rows still price exactly as they did.
///
/// Why: the new rows are additive. A stored perf record from a 4.x run must
/// keep reproducing the same cost, or historical bake-off comparisons shift
/// under a change that was only meant to add three rows.
/// What: Sonnet 4.x at $3 in, Opus 4.x at $75 out, Haiku 3/4 at $0.80 in,
/// and the unknown-model default still Sonnet-4-class at $3 in.
/// Test: this test.
#[test]
fn cost_usd_legacy_4x_rows_are_unchanged() {
    assert!((cost_usd("anthropic/claude-sonnet-4-5", 1_000_000, 0, 0, 0) - 3.0).abs() < 1e-9);
    assert!((cost_usd("anthropic/claude-opus-4-5", 0, 1_000_000, 0, 0) - 75.0).abs() < 1e-9);
    assert!((cost_usd("anthropic/claude-haiku-4", 1_000_000, 0, 0, 0) - 0.80).abs() < 1e-9);
    assert!((cost_usd("some-vendor/unheard-of", 1_000_000, 0, 0, 0) - 3.0).abs() < 1e-9);
}

#[test]
fn cost_usd_cache_read_is_cheaper() {
    // Cache-read is 10x cheaper than fresh input on Sonnet.
    let fresh = cost_usd("claude-sonnet-4-6", 1_000_000, 0, 0, 0);
    let cached = cost_usd("claude-sonnet-4-6", 0, 0, 1_000_000, 0);
    assert!(cached < fresh);
    assert!((cached - 0.30).abs() < 1e-9);
}

// --- #29: Cost calculation tests for cache hits ---

#[test]
fn cost_usd_sonnet_cache_creation_matches_spec() {
    // #29: Cache write rate for claude-sonnet-4-6 is $3.75/MTok.
    // 1M cache_creation tokens should cost exactly $3.75.
    let c = cost_usd("anthropic/claude-sonnet-4-6", 0, 0, 0, 1_000_000);
    assert!(
        (c - 3.75).abs() < 1e-9,
        "expected $3.75 for 1M cache write tokens on sonnet-4-6, got {c}"
    );
}

#[test]
fn cost_usd_sonnet_cache_read_is_one_tenth_of_input() {
    // #29: Cache read is $0.30/MTok vs input $3.00/MTok — exactly 10%.
    // This is the headline savings figure for prompt caching.
    let fresh_input = cost_usd("claude-sonnet-4-6", 1_000_000, 0, 0, 0);
    let cache_read = cost_usd("claude-sonnet-4-6", 0, 0, 1_000_000, 0);
    let ratio = cache_read / fresh_input;
    assert!(
        (ratio - 0.10).abs() < 1e-9,
        "cache_read should be 10% of input cost, got {ratio} (fresh={fresh_input}, cached={cache_read})"
    );
}

#[test]
fn cost_usd_sonnet_mixed_cache_hit_scenario() {
    // #29: Realistic scenario — a turn where most input is a cache hit:
    // 100 fresh prompt tokens + 50 completion + 9000 cache_read + 1000 cache_creation.
    // Sonnet rates: $3/MTok in, $15/MTok out, $0.30/MTok cache_r, $3.75/MTok cache_w.
    let c = cost_usd("anthropic/claude-sonnet-4-6", 100, 50, 9_000, 1_000);
    // 100 * 3e-6 = 0.0003, 50 * 15e-6 = 0.00075, 9000 * 0.30e-6 = 0.0027,
    // 1000 * 3.75e-6 = 0.00375. Total = 0.00750.
    let expected = 0.0003 + 0.00075 + 0.0027 + 0.00375;
    assert!((c - expected).abs() < 1e-9, "expected {expected}, got {c}");
}

#[test]
fn cost_usd_unknown_defaults_to_sonnet() {
    let u = cost_usd("some/unknown-model", 1_000_000, 0, 0, 0);
    assert!((u - 3.0).abs() < 1e-9);
}

#[test]
fn collector_records_phases() {
    let mut c = PerfCollector::new(7, "prescriptive", "write x");
    c.record_phase(
        "research",
        500,
        "claude-sonnet-4-5",
        &TokenUsage::new(1000, 500, 0, 0),
    );
    c.record_phase(
        "code",
        1200,
        "claude-sonnet-4-5",
        &TokenUsage::new(2000, 1000, 500, 200),
    );
    let r = c.build_record();
    assert_eq!(r.phases.len(), 2);
    assert_eq!(r.phases[0].prompt_tokens, 1000);
    assert_eq!(r.totals.prompt_tokens, 3000);
    assert_eq!(r.totals.completion_tokens, 1500);
    assert_eq!(r.totals.cache_read_tokens, 500);
    assert_eq!(r.totals.cache_creation_tokens, 200);
    // Sanity: some cost accrued.
    assert!(r.totals.cost_usd > 0.0);
    assert_eq!(r.build, 7);
    assert_eq!(r.workflow, "prescriptive");
}

/// `record_phase` uses `usage.cost_usd` verbatim when the provider reported
/// an authoritative cost, instead of recomputing from the static pricing
/// table (which cannot see the cache discount).
///
/// Why: This is the exact behaviour the response-side cache-usage fix
/// depends on to make OpenRouter's cache discount visible in the perf record.
/// What: Record a phase with a `TokenUsage` carrying a deliberately
/// implausible static-vs-authoritative mismatch cost, assert the phase's
/// `cost_usd` is the authoritative value, not the static recompute.
/// Test: this test.
#[test]
fn record_phase_prefers_authoritative_cost() {
    let mut c = PerfCollector::new(1, "wf", "task");
    let mut usage = TokenUsage::new(1_000_000, 0, 0, 0);
    usage.cost_usd = Some(0.000001); // far below the static per-token price
    c.record_phase("turn", 10, "anthropic/claude-sonnet-4-5", &usage);
    let r = c.build_record();
    assert_eq!(r.phases[0].cost_usd, 0.000001);
}

#[test]
fn truncate_preview_respects_limit() {
    let s = "x".repeat(200);
    let p = truncate_preview(&s, 120);
    assert_eq!(p.chars().count(), 123, "120 chars + ellipsis");
    assert!(p.ends_with("..."));
}

#[test]
fn truncate_preview_short_string_unchanged() {
    let p = truncate_preview("hi", 120);
    assert_eq!(p, "hi");
}

#[test]
fn filename_stamp_format() {
    let s = filename_stamp("2026-04-22T17:31:30Z", 42);
    assert_eq!(s, "20260422-173130-build42");
}

#[tokio::test]
async fn collector_flush_records_failed_status() {
    // #56: When a workflow phase fails, the engine sets status=partial
    // and records the failing phase, then flushes. Verify the JSON round-
    // trips those fields.
    let tmp = tempfile::tempdir().unwrap();
    let mut c = PerfCollector::new(11, "test-wf", "broken task");
    c.record_phase(
        "research",
        50,
        "claude-sonnet-4-6",
        &TokenUsage::new(100, 50, 0, 0),
    );
    c.set_status("partial");
    c.set_failed_phase("plan");
    c.flush(tmp.path()).await.unwrap();

    let runs = tmp.path().join("runs");
    let mut entries = tokio::fs::read_dir(&runs).await.unwrap();
    let mut rec: Option<PerfRecord> = None;
    while let Some(e) = entries.next_entry().await.unwrap() {
        if e.path().extension().and_then(|s| s.to_str()) == Some("json") {
            let bytes = tokio::fs::read(e.path()).await.unwrap();
            rec = Some(serde_json::from_slice(&bytes).unwrap());
        }
    }
    let rec = rec.expect("perf json written");
    assert_eq!(rec.status, "partial");
    assert_eq!(rec.failed_phase.as_deref(), Some("plan"));
}

#[test]
fn collector_default_status_is_success() {
    // #56: New collectors default to status=success so clean runs don't
    // need to explicitly call set_status.
    let c = PerfCollector::new(1, "wf", "task");
    let r = c.build_record();
    assert_eq!(r.status, "success");
    assert!(r.failed_phase.is_none());
}

/// Why: Fix 3 / claude-mpm parity — when the QA agent emits structured
/// pass/fail counts, those counts must round-trip through the perf
/// record's JSON form AND appear in the `runs.log` summary line.
/// What: Constructs a `PerfCollector`, sets test counts, flushes, and
/// asserts both the JSON file and the log line carry "42" and "0".
/// Test: this function (`test_run_record_serializes_test_counts`).
#[tokio::test]
async fn test_run_record_serializes_test_counts() {
    let tmp = tempfile::tempdir().unwrap();
    let mut c = PerfCollector::new(99, "test-wf", "task with tests");
    c.record_phase("qa", 10, "claude-sonnet-4-6", &TokenUsage::new(10, 5, 0, 0));
    c.set_test_counts(42, 0);
    c.flush(tmp.path()).await.unwrap();

    // JSON round-trip retains the counts.
    let runs = tmp.path().join("runs");
    let mut entries = tokio::fs::read_dir(&runs).await.unwrap();
    let mut rec: Option<PerfRecord> = None;
    while let Some(e) = entries.next_entry().await.unwrap() {
        if e.path().extension().and_then(|s| s.to_str()) == Some("json") {
            let bytes = tokio::fs::read(e.path()).await.unwrap();
            rec = Some(serde_json::from_slice(&bytes).unwrap());
        }
    }
    let rec = rec.expect("perf json written");
    assert_eq!(rec.tests_passed, Some(42));
    assert_eq!(rec.tests_failed, Some(0));

    // Raw JSON bytes contain the literal "42" and "0" values.
    let json_str = serde_json::to_string(&rec).unwrap();
    assert!(json_str.contains("\"tests_passed\":42"));
    assert!(json_str.contains("\"tests_failed\":0"));

    // runs.log line ends with the new columns.
    let log = tokio::fs::read_to_string(tmp.path().join("runs.log"))
        .await
        .unwrap();
    assert!(
        log.contains("tests_passed=42"),
        "runs.log missing tests_passed=42: {log}"
    );
    assert!(
        log.contains("tests_failed=0"),
        "runs.log missing tests_failed=0: {log}"
    );
}

/// Why: Back-compat — when QA didn't run or emitted no JSON envelope,
/// the counts must be `None`, omitted from JSON via `skip_serializing_if`,
/// and rendered as `-` in `runs.log`.
#[tokio::test]
async fn run_record_omits_test_counts_when_none() {
    let tmp = tempfile::tempdir().unwrap();
    let mut c = PerfCollector::new(100, "test-wf", "no qa");
    c.record_phase(
        "research",
        5,
        "claude-sonnet-4-6",
        &TokenUsage::new(10, 5, 0, 0),
    );
    c.flush(tmp.path()).await.unwrap();

    let log = tokio::fs::read_to_string(tmp.path().join("runs.log"))
        .await
        .unwrap();
    assert!(
        log.contains("tests_passed=-"),
        "expected '-' placeholder: {log}"
    );
    assert!(
        log.contains("tests_failed=-"),
        "expected '-' placeholder: {log}"
    );
}

#[tokio::test]
async fn collector_flush_writes_json_and_log() {
    let tmp = tempfile::tempdir().unwrap();
    let mut c = PerfCollector::new(5, "test-wf", "hello task");
    c.record_phase(
        "plan",
        100,
        "claude-sonnet-4-5",
        &TokenUsage::new(100, 50, 0, 0),
    );
    c.flush(tmp.path()).await.unwrap();

    // A runs/ dir was created with at least one .json inside.
    let runs = tmp.path().join("runs");
    assert!(runs.exists());
    let mut entries = tokio::fs::read_dir(&runs).await.unwrap();
    let mut found_json = false;
    while let Some(e) = entries.next_entry().await.unwrap() {
        if e.path().extension().and_then(|s| s.to_str()) == Some("json") {
            found_json = true;
            let bytes = tokio::fs::read(e.path()).await.unwrap();
            let rec: PerfRecord = serde_json::from_slice::<PerfRecord>(&bytes).unwrap();
            assert_eq!(rec.build, 5);
            assert_eq!(rec.workflow, "test-wf");
            assert_eq!(rec.phases.len(), 1);
            assert_eq!(rec.phases[0].name, "plan");
        }
    }
    assert!(found_json, "expected at least one .json run file");

    // runs.log exists and contains the build tag.
    let log = tokio::fs::read_to_string(tmp.path().join("runs.log"))
        .await
        .unwrap();
    assert!(log.contains("build=5"));
    assert!(log.contains("workflow=test-wf"));
}