trusty-code 0.5.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
//! Performance instrumentation — per-phase latency + token/cost capture.
//!
//! Why: (#47) We need to track how long each workflow phase takes, how many
//! tokens it consumed (prompt / completion / Anthropic cache read / cache
//! creation), and the resulting USD cost so we can compare runs build-over-
//! build and catch regressions or prompt-caching wins. Persisting one JSON
//! file per run under `docs/performance/runs/` plus a one-line summary log
//! keeps the data greppable without a database.
//! What: `PerfCollector` is constructed at workflow start, `record_phase`
//! appends a `PhaseRecord` after each phase, and `flush` writes the final
//! JSON + log line. `TokenUsage` is the provider-agnostic shape captured
//! from each LLM call (extended with Anthropic-specific `cache_read` /
//! `cache_creation` fields which are zero for non-Anthropic models).
//! Test: `cost_usd_known_model`, `collector_records_phases`,
//! `collector_totals_sum_phases`, `collector_flush_writes_json_and_log`.
//!
//! Module layout (see #366 split):
//! - `mod.rs` — perf record types + `PerfCollector` lifecycle
//! - `pricing.rs` — `cost_usd` + the model pricing table + formatters
//! - `tests.rs` — unit tests

mod pricing;

#[cfg(test)]
mod tests;

use std::path::Path;
use std::time::Instant;

use anyhow::{Context, Result};
use chrono::Utc;
use serde::{Deserialize, Serialize};

use pricing::{filename_stamp, truncate_preview};

pub use pricing::cost_usd;

/// Token usage captured from a single LLM round-trip.
///
/// Why: (#50) Anthropic's OpenRouter responses carry cache_read_input_tokens
/// and cache_creation_input_tokens alongside the standard prompt/completion
/// counts. Exposing those as first-class fields lets `PerfCollector` track
/// cache effectiveness over time. For non-Anthropic models these stay 0.
/// `cost_usd` (response-side cache-usage fix) carries OpenRouter's
/// authoritative, already cache-discounted USD cost for this one round-trip
/// when the provider reported one; `None` means no authoritative cost was
/// available and callers must fall back to static per-token pricing.
/// What: Plain struct; additive (`+`-style) accumulation is done inline in
/// `PerfCollector::totals`.
/// Test: `token_usage_default_is_zeros`, `token_usage_accumulates`,
/// `token_usage_cost_accumulates`.
#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
pub struct TokenUsage {
    pub prompt_tokens: u32,
    pub completion_tokens: u32,
    pub cache_read_tokens: u32,
    pub cache_creation_tokens: u32,
    /// Authoritative per-call USD cost reported by the provider (OpenRouter),
    /// already netting any cache discount. `None` when unavailable.
    #[serde(default)]
    pub cost_usd: Option<f64>,
}

impl TokenUsage {
    /// Construct a `TokenUsage` from the four individual counts.
    ///
    /// Why: Most call sites (tests, static-pricing paths) don't have an
    /// authoritative provider-reported cost; `cost_usd` starts `None` and
    /// callers set it explicitly (e.g. `UsageBlock::into_token_usage`) when
    /// one is available.
    pub fn new(prompt: u32, completion: u32, cache_read: u32, cache_creation: u32) -> Self {
        Self {
            prompt_tokens: prompt,
            completion_tokens: completion,
            cache_read_tokens: cache_read,
            cache_creation_tokens: cache_creation,
            cost_usd: None,
        }
    }

    /// Add another usage record into this one (in place).
    ///
    /// Why: Each phase may comprise multiple LLM turns (tool loop); we sum
    /// them into a single `PhaseRecord`. `cost_usd` sums the two authoritative
    /// costs when both are present; when only one side carries a cost it is
    /// preserved rather than discarded, and the sum is `None` only when
    /// neither side has one — a partial per-turn cost is still meaningful
    /// signal that must not silently disappear.
    /// What: Field-wise saturating add for token counts; `Option<f64>` sum for
    /// cost.
    /// Test: `token_usage_accumulates`, `token_usage_cost_accumulates`.
    pub fn add(&mut self, other: &TokenUsage) {
        self.prompt_tokens = self.prompt_tokens.saturating_add(other.prompt_tokens);
        self.completion_tokens = self
            .completion_tokens
            .saturating_add(other.completion_tokens);
        self.cache_read_tokens = self
            .cache_read_tokens
            .saturating_add(other.cache_read_tokens);
        self.cache_creation_tokens = self
            .cache_creation_tokens
            .saturating_add(other.cache_creation_tokens);
        self.cost_usd = match (self.cost_usd, other.cost_usd) {
            (Some(a), Some(b)) => Some(a + b),
            (Some(a), None) | (None, Some(a)) => Some(a),
            (None, None) => None,
        };
    }
}

/// One phase's measured performance.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PhaseRecord {
    pub name: String,
    pub duration_ms: u64,
    pub prompt_tokens: u32,
    pub completion_tokens: u32,
    pub cache_read_tokens: u32,
    pub cache_creation_tokens: u32,
    pub cost_usd: f64,
}

/// Totals rolled up from every `PhaseRecord` in a run.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct PerfTotals {
    pub prompt_tokens: u32,
    pub completion_tokens: u32,
    pub cache_read_tokens: u32,
    pub cache_creation_tokens: u32,
    pub cost_usd: f64,
}

/// Full performance record persisted to `docs/performance/runs/`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PerfRecord {
    pub build: u64,
    pub version: String,
    pub workflow: String,
    pub task_preview: String,
    pub started_at: String,
    pub total_duration_ms: u64,
    pub phases: Vec<PhaseRecord>,
    pub totals: PerfTotals,
    /// Run outcome (#56): "success" | "partial" | "failed".
    ///
    /// Why: When a phase fails mid-workflow, we still want to persist the
    /// perf record so we can see where/how the run died. A separate `status`
    /// field distinguishes clean completions from partial runs in tooling
    /// that scans `runs/*.json`.
    /// What: Defaults to "success" for back-compat with older fixtures.
    #[serde(default = "default_status")]
    pub status: String,
    /// Name of the phase that failed, when `status != "success"` (#56).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub failed_phase: Option<String>,
    /// Distinct skill names injected into any phase prompt during this run
    /// (#171).
    ///
    /// Why: Post-run persistence needs to know which skills were used so it
    /// can increment `use_count` and refresh `last_used`. Carrying the list
    /// through `PerfRecord` keeps the data in one place that's already
    /// flushed to disk for analysis.
    /// What: Deduplicated, insertion-order-preserved list of skill names.
    /// Defaults to empty for back-compat with older fixtures.
    #[serde(default)]
    pub skills_used: Vec<String>,
    /// Distinct skill names matched by the pre-plan discovery step (#173).
    ///
    /// Why: Discovery surfaces every skill the engine considered relevant for
    /// a task — even if downstream prompt assembly only injected a subset (or
    /// none). Recording the broader candidate set separately from
    /// `skills_used` lets us measure recall vs. precision over time and
    /// audit which signals the discovery step matched on.
    /// What: Deduplicated, insertion-order-preserved list of skill names.
    /// Defaults to empty for back-compat with older fixtures.
    #[serde(default)]
    pub skills_considered: Vec<String>,
    /// Tests passed in the QA phase, when the QA agent emitted a parsable
    /// JSON envelope with a `passed` count.
    ///
    /// Why: Run-over-run comparisons want raw test counts, not just the
    /// pass/fail status. Tracking `tests_passed`/`tests_failed` separately
    /// from `status` lets dashboards show "1118/1118 passing" without
    /// re-parsing QA output.
    /// What: `Some(N)` when QA returned a JSON envelope with `passed`,
    /// `None` otherwise. Defaults to `None` for back-compat with older
    /// fixtures and for runs that skip the QA phase.
    /// Test: `test_run_record_serializes_test_counts`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tests_passed: Option<u64>,
    /// Tests failed in the QA phase, paired with `tests_passed`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tests_failed: Option<u64>,
}

fn default_status() -> String {
    "success".to_string()
}

/// Accumulator used during workflow execution.
///
/// Why: Keeping the collector off the workflow context lets us evolve perf
/// schema without churning `WorkflowContext`; the engine just calls
/// `record_phase`/`flush`.
/// What: Holds the build stamp, workflow name, a 120-char preview of the
/// user task, the wall-clock start `Instant`, and a growing `Vec<PhaseRecord>`.
/// `flush(out_dir)` writes `runs/YYYYMMDD-HHMMSS-build<N>.json` and appends a
/// summary line to `runs.log`.
/// Test: see unit tests at bottom of this file.
pub struct PerfCollector {
    build: u64,
    workflow: String,
    task_preview: String,
    started_at: Instant,
    started_at_iso: String,
    phases: Vec<PhaseRecord>,
    model: String,
    /// #56: run status; set via `set_status`. Defaults to "success".
    status: String,
    /// #56: name of the phase that failed, if any.
    failed_phase: Option<String>,
    /// #171: distinct skills injected during the run, insertion-ordered.
    skills_used: Vec<String>,
    /// #173: distinct skills matched by pre-plan discovery, insertion-ordered.
    skills_considered: Vec<String>,
    /// QA-emitted passed test count, when available.
    tests_passed: Option<u64>,
    /// QA-emitted failed test count, when available.
    tests_failed: Option<u64>,
}

impl PerfCollector {
    /// Construct a new collector.
    ///
    /// Why: Called at workflow start so the wall-clock anchor is the true
    /// run start, not a lazy "first phase" moment.
    /// What: Captures the build number, workflow name, truncated task preview,
    /// start `Instant`, and start ISO8601 UTC timestamp.
    /// Test: `collector_records_phases`.
    pub fn new(build: u64, workflow: &str, task: &str) -> Self {
        Self {
            build,
            workflow: workflow.to_string(),
            task_preview: truncate_preview(task, 120),
            started_at: Instant::now(),
            started_at_iso: Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string(),
            phases: Vec::new(),
            model: String::new(),
            status: "success".to_string(),
            failed_phase: None,
            skills_used: Vec::new(),
            skills_considered: Vec::new(),
            tests_passed: None,
            tests_failed: None,
        }
    }

    /// Record QA test counts (Fix 3 / parity with claude-mpm).
    ///
    /// Why: When the QA agent emits a parsable JSON envelope, we want the
    /// exact `passed`/`failed` counts on the perf record so dashboards can
    /// chart them over time without re-parsing agent output.
    /// What: Stores the two counts; included in the flushed JSON and the
    /// `runs.log` summary line.
    /// Test: `test_run_record_serializes_test_counts`.
    pub fn set_test_counts(&mut self, passed: u64, failed: u64) {
        self.tests_passed = Some(passed);
        self.tests_failed = Some(failed);
    }

    /// Record that `name` was surfaced by pre-plan skill discovery (#173).
    ///
    /// Why: Discovery considers a broader set of skills than what is actually
    /// injected. Tracking the full candidate set separately preserves the
    /// recall side of the recall/precision picture for post-run analysis.
    /// What: Appends `name` to `skills_considered` if not already present
    /// (insertion-ordered de-dup).
    /// Test: `collector_records_skills_considered`.
    pub fn record_skill_considered(&mut self, name: &str) {
        if !self.skills_considered.iter().any(|s| s == name) {
            self.skills_considered.push(name.to_string());
        }
    }

    /// Record that `name` was injected into a phase prompt during this run
    /// (#171).
    ///
    /// Why: Post-run persistence (`update_skill_usage` in `main.rs`) needs the
    /// list of injected skills to update `use_count` and `last_used`. Tracking
    /// here keeps the collector the single source of truth for the run.
    /// What: Appends `name` to `skills_used` if not already present
    /// (insertion-ordered de-dup).
    /// Test: Indirect via `update_skill_usage` integration in main.
    pub fn record_skill_used(&mut self, name: &str) {
        if !self.skills_used.iter().any(|s| s == name) {
            self.skills_used.push(name.to_string());
        }
    }

    /// Set the run status (#56).
    ///
    /// Why: The workflow engine calls this after the phase loop to record
    /// "success" on clean completion and "partial" / "failed" when a phase
    /// returned an error, so the flushed JSON reflects reality.
    /// What: Stores the status string verbatim; `flush` serializes it.
    /// Test: `collector_flush_records_failed_status`.
    pub fn set_status(&mut self, status: &str) {
        self.status = status.to_string();
    }

    /// Record which phase failed (#56).
    ///
    /// Why: Paired with `set_status`, this lets analysis tooling group failed
    /// runs by failing phase without having to parse the last `phases` entry.
    /// What: Stores the phase name; included in the flushed JSON when set.
    /// Test: `collector_flush_records_failed_status`.
    pub fn set_failed_phase(&mut self, phase: &str) {
        self.failed_phase = Some(phase.to_string());
    }

    /// Record the dominant model used by the run for pricing.
    ///
    /// Why: The LLM pricing table is keyed by model substring. The workflow
    /// engine doesn't know the model up front (each phase's agent may use a
    /// different one), so we let the caller set/override as needed.
    /// What: Stores the latest model string; pricing is looked up per
    /// `record_phase` call using the `model` argument passed there, not this
    /// field (this is retained for future aggregate analysis).
    /// Test: implicit via `collector_flush_writes_json_and_log`.
    #[allow(dead_code)]
    pub fn set_model(&mut self, model: &str) {
        self.model = model.to_string();
    }

    /// Append a phase's measurements, computing its USD cost from `model`.
    ///
    /// Why: Engines call this once per phase with the agent model and the
    /// summed `TokenUsage` from all LLM turns in that phase.
    /// What: Prefers `usage.cost_usd` (OpenRouter's authoritative,
    /// cache-discount-aware cost) when the provider reported one; otherwise
    /// falls back to the static per-token recompute via `cost_usd(model, ...)`
    /// — the static table cannot see the cache discount, so it is a fallback
    /// only, never a substitute when an authoritative figure exists. Pushes a
    /// `PhaseRecord`.
    /// Test: `collector_records_phases`, `record_phase_prefers_authoritative_cost`.
    pub fn record_phase(&mut self, name: &str, duration_ms: u64, model: &str, usage: &TokenUsage) {
        let cost = usage.cost_usd.unwrap_or_else(|| {
            cost_usd(
                model,
                usage.prompt_tokens,
                usage.completion_tokens,
                usage.cache_read_tokens,
                usage.cache_creation_tokens,
            )
        });
        self.phases.push(PhaseRecord {
            name: name.to_string(),
            duration_ms,
            prompt_tokens: usage.prompt_tokens,
            completion_tokens: usage.completion_tokens,
            cache_read_tokens: usage.cache_read_tokens,
            cache_creation_tokens: usage.cache_creation_tokens,
            cost_usd: cost,
        });
    }

    /// Sum all phase records into a single `PerfTotals`.
    fn totals(&self) -> PerfTotals {
        let mut t = PerfTotals::default();
        for p in &self.phases {
            t.prompt_tokens = t.prompt_tokens.saturating_add(p.prompt_tokens);
            t.completion_tokens = t.completion_tokens.saturating_add(p.completion_tokens);
            t.cache_read_tokens = t.cache_read_tokens.saturating_add(p.cache_read_tokens);
            t.cache_creation_tokens = t
                .cache_creation_tokens
                .saturating_add(p.cache_creation_tokens);
            t.cost_usd += p.cost_usd;
        }
        t
    }

    /// Build the final `PerfRecord` without writing to disk.
    ///
    /// Why: Exposed for tests and for in-process consumers (the #151 JSON
    /// envelope projects this record into a `PmResponse`). `flush` calls
    /// this internally.
    pub fn build_record(&self) -> PerfRecord {
        let total_duration_ms = self.started_at.elapsed().as_millis() as u64;
        PerfRecord {
            build: self.build,
            version: env!("CARGO_PKG_VERSION").to_string(),
            workflow: self.workflow.clone(),
            task_preview: self.task_preview.clone(),
            started_at: self.started_at_iso.clone(),
            total_duration_ms,
            phases: self.phases.clone(),
            totals: self.totals(),
            status: self.status.clone(),
            failed_phase: self.failed_phase.clone(),
            skills_used: self.skills_used.clone(),
            skills_considered: self.skills_considered.clone(),
            tests_passed: self.tests_passed,
            tests_failed: self.tests_failed,
        }
    }

    /// Persist the record to `out_dir/runs/<stamp>.json` and append a
    /// summary line to `out_dir/runs.log`.
    ///
    /// Why: A single JSON per run is easy to diff and feed to tooling; the
    /// log line is a human-readable one-liner suitable for `tail -f`.
    /// What: Computes total duration, serializes to pretty JSON, writes the
    /// file atomically-ish (direct write is fine for append-only telemetry),
    /// then appends a one-line summary to `runs.log`.
    /// Test: `collector_flush_writes_json_and_log`.
    pub async fn flush(&self, out_dir: &Path) -> Result<()> {
        let record = self.build_record();
        let runs_dir = out_dir.join("runs");
        tokio::fs::create_dir_all(&runs_dir)
            .await
            .with_context(|| format!("failed to create {}", runs_dir.display()))?;

        // Stamp filename: YYYYMMDD-HHMMSS-build<N>.json
        // Derived from `started_at_iso` (UTC) so filenames are deterministic
        // given the same start time — useful for test fixtures.
        let stamp = filename_stamp(&self.started_at_iso, self.build);
        let json_path = runs_dir.join(format!("{stamp}.json"));
        let pretty = serde_json::to_vec_pretty(&record).context("serialize PerfRecord")?;
        tokio::fs::write(&json_path, &pretty)
            .await
            .with_context(|| format!("failed to write {}", json_path.display()))?;

        // One-line summary: tab-separated key=value pairs.
        // `tests_passed` / `tests_failed` are appended as the LAST two columns
        // for back-compat with log readers that only parse the first N
        // columns. Render `None` as "-" so the column is always present.
        let fmt_opt = |n: Option<u64>| -> String {
            n.map(|v| v.to_string()).unwrap_or_else(|| "-".to_string())
        };
        let line = format!(
            "{ts}\tbuild={b}\tworkflow={w}\tdur_ms={d}\tprompt={p}\tcompletion={c}\tcache_r={cr}\tcache_w={cc}\tcost_usd={cost:.6}\ttests_passed={tp}\ttests_failed={tf}\n",
            ts = self.started_at_iso,
            b = self.build,
            w = self.workflow,
            d = record.total_duration_ms,
            p = record.totals.prompt_tokens,
            c = record.totals.completion_tokens,
            cr = record.totals.cache_read_tokens,
            cc = record.totals.cache_creation_tokens,
            cost = record.totals.cost_usd,
            tp = fmt_opt(record.tests_passed),
            tf = fmt_opt(record.tests_failed),
        );
        let log_path = out_dir.join("runs.log");
        // Ensure parent exists (out_dir itself might not yet).
        if let Some(parent) = log_path.parent() {
            tokio::fs::create_dir_all(parent).await.ok();
        }
        // Append.
        use tokio::io::AsyncWriteExt;
        let mut f = tokio::fs::OpenOptions::new()
            .create(true)
            .append(true)
            .open(&log_path)
            .await
            .with_context(|| format!("failed to open {}", log_path.display()))?;
        f.write_all(line.as_bytes())
            .await
            .context("failed to append perf log line")?;
        f.flush().await.ok();

        tracing::info!(
            path = %json_path.display(),
            build = self.build,
            total_ms = record.total_duration_ms,
            total_cost_usd = record.totals.cost_usd,
            "wrote perf record"
        );
        Ok(())
    }
}