返回 CodeWhale
metrics.rs
根目录 / crates / cli / src / metrics.rs
1 //! `codewhale metrics` / `stats` — reads native and legacy stores and prints
2 //! a human-readable usage rollup.
3 //!
4 //! Legacy receipt sources, resolved through the shared Codewhale state resolvers so
5 //! the reader lands on the same files the writers use:
6 //! - `~/.codewhale/audit.log` — one JSON line per event (approvals, credentials)
7 //! - `~/.codewhale/sessions/` — saved session JSON files (tool call history)
8 //! - `~/.codewhale/tasks/runtime/events/` — runtime thread JSONL event streams
9 //! - `~/.codewhale/sessions/<id>/runtime/events/` — session-scoped runtime
10 //! stores (`default_runtime_store_root` in `crates/engine/src/runtime_threads.rs`)
11 //!
12 //! `CODEWHALE_RUNTIME_DIR` / `DEEPSEEK_RUNTIME_DIR` is an *exclusive* store root
13 //! for every Runtime store in the writing process, so when it is set the reader
14 //! uses it alone. Mixing it with the default roots would count one call twice.
15 //!
16 //! Default-root audit history includes retained rotations and legacy receipts,
17 //! excluding records copied across roots. An explicit `CODEWHALE_HOME` never
18 //! reads outside that root.
19 //!
20 //! The three legacy views overlap and are deliberately not de-duplicated against
21 //! each other: an approval receipt, a saved-session transcript entry, and a
22 //! runtime `item.*` receipt each describe one tool call from a different
23 //! vantage point, and collapsing them would assert an identity the data does
24 //! not carry. Cross-reference with `--json` when an exact count matters.
25 //!
26 //! The opt-in tool audit file behind `CODEWHALE_TOOL_AUDIT_LOG` /
27 //! `DEEPSEEK_TOOL_AUDIT_LOG` (`emit_tool_audit`) is separate from
28 //! `~/.codewhale/audit.log`; the legacy receipt projection does not discover
29 //! it. Because that variable can be pointed at the audit log itself, and
30 //! because `emit_tool_audit` puts `tool_name` and `success` at the JSON top
31 //! level rather than under `details`, the audit reader accepts both shapes.
32
33 mod stats;
34
35 use std::collections::{HashMap, HashSet};
36 use std::io::{self, BufRead, Read};
37 use std::path::{Path, PathBuf};
38
39 use anyhow::Result;
40 use chrono::{DateTime, Duration, Utc};
41 use serde_json::Value;
42 use sha2::{Digest, Sha256};
43
44 // ──────────────────────────────────────────────────────────────────────────────
45 // Public entry-point
46 // ──────────────────────────────────────────────────────────────────────────────
47
48 /// Arguments accepted by `codewhale metrics`.
49 #[derive(Debug, Default)]
50 pub struct MetricsArgs {
51 /// Emit machine-readable JSON instead of human text.
52 pub json: bool,
53 /// Restrict to events newer than this cutoff (inclusive).
54 pub since: Option<DateTime<Utc>>,
55 pub models: Option<usize>,
56 pub tools: Option<usize>,
57 pub project: Option<PathBuf>,
58 pub roles: Option<usize>,
59 }
60
61 pub fn run(args: MetricsArgs) -> Result<()> {
62 // `resolve_state_dir` is the shared read-path resolver already used by
63 // `doctor` and the session store; the runtime thread store hangs its event
64 // streams off `<tasks>/runtime`. Resolving the home is fallible, and a
65 // rollup of zeros is indistinguishable from real emptiness, so a home we
66 // cannot resolve is an error rather than a silent all-zero report.
67 let audit_roots = resolve_audit_roots()?;
68 let sessions = codewhale_config::resolve_state_dir("sessions")?;
69 let tasks = codewhale_config::resolve_state_dir("tasks")?;
70 let state_dir = codewhale_config::resolve_state_dir("state")?;
71 let runtime_events = runtime_event_dirs(&tasks, &sessions);
72 anyhow::ensure!(
73 [args.models, args.tools, args.roles]
74 .into_iter()
75 .flatten()
76 .all(|limit| limit > 0),
77 "--models, --tools and --roles must be positive"
78 );
79 let report = stats::collect(&args, &sessions, &runtime_events, &audit_roots)?;
80 if args.project.is_some() {
81 if args.json {
82 println!(
83 "{}",
84 serde_json::to_string_pretty(&serde_json::json!({
85 "stats": report,
86 "legacy_receipt_projections": null,
87 "legacy_receipt_projection_scope": "unavailable for a workspace filter; old receipts do not all carry that scope",
88 }))?
89 );
90 } else {
91 stats::print_human(&report);
92 println!("Legacy receipt projections: unavailable for a workspace filter.");
93 }
94 return Ok(());
95 }
96
97 let workspace_ids = report.workspace_ids.clone();
98 let mut rollup = Rollup {
99 stats: Some(report),
100 ..Default::default()
101 };
102 read_audit_history(&audit_roots, args.since, &mut rollup);
103 read_session_files(&sessions, args.since, &mut rollup);
104 read_runtime_events(&runtime_events, args.since, &mut rollup);
105 read_subagent_state_files(&state_dir, &workspace_ids, args.since, &mut rollup);
106
107 if args.json {
108 print_json(&rollup)?;
109 } else {
110 if let Some(report) = &rollup.stats {
111 stats::print_human(report);
112 }
113 println!(
114 "\nLegacy receipt projections below overlap and are not added to native-source money or unique execution counts."
115 );
116 print_human(&rollup, args.since);
117 }
118
119 Ok(())
120 }
121
122 // ──────────────────────────────────────────────────────────────────────────────
123 // Duration-string parser ("7d", "24h", "30m", "2h", "now-2h", "2h30m")
124 // ──────────────────────────────────────────────────────────────────────────────
125
126 /// Parse a loose humantime-ish duration string into an absolute `DateTime<Utc>`
127 /// cutoff (i.e. `Utc::now() - duration`).
128 ///
129 /// Accepted forms:
130 /// - `7d` / `24h` / `30m` / `90s`
131 /// - `2h30m`, `1d12h`
132 /// - `now-2h` (leading `now-` is stripped before parsing)
133 pub fn parse_since(s: &str) -> Result<DateTime<Utc>> {
134 let s = s.trim().to_ascii_lowercase();
135 let s = s.strip_prefix("now-").unwrap_or(&s);
136 let secs = parse_duration_secs(s)?;
137 let delta = Duration::try_seconds(secs)
138 .ok_or_else(|| anyhow::anyhow!("duration {s:?} is too large"))?;
139 Utc::now()
140 .checked_sub_signed(delta)
141 .ok_or_else(|| anyhow::anyhow!("duration {s:?} reaches before the earliest supported time"))
142 }
143
144 fn parse_duration_secs(s: &str) -> Result<i64> {
145 // Walk through the string accumulating numbers and consuming unit suffixes.
146 let mut total: i64 = 0;
147 let mut num_buf = String::new();
148
149 for ch in s.chars() {
150 match ch {
151 '0'..='9' => num_buf.push(ch),
152 'd' | 'h' | 'm' | 's' => {
153 if num_buf.is_empty() {
154 anyhow::bail!("unit {ch:?} in duration {s:?} has no number before it");
155 }
156 let n: i64 = num_buf
157 .parse()
158 .map_err(|_| anyhow::anyhow!("duration component {num_buf:?} is too large"))?;
159 num_buf.clear();
160 let factor = match ch {
161 'd' => 86_400,
162 'h' => 3_600,
163 'm' => 60,
164 's' => 1,
165 _ => unreachable!(),
166 };
167 total = n
168 .checked_mul(factor)
169 .and_then(|secs| total.checked_add(secs))
170 .ok_or_else(|| anyhow::anyhow!("duration {s:?} is too large"))?;
171 }
172 _ => anyhow::bail!("unrecognised character {ch:?} in duration {s:?}"),
173 }
174 }
175
176 if !num_buf.is_empty() {
177 // Trailing bare number — treat as seconds.
178 let n: i64 = num_buf
179 .parse()
180 .map_err(|_| anyhow::anyhow!("duration component {num_buf:?} is too large"))?;
181 total = total
182 .checked_add(n)
183 .ok_or_else(|| anyhow::anyhow!("duration {s:?} is too large"))?;
184 }
185
186 if total == 0 {
187 anyhow::bail!("duration {s:?} resolved to zero seconds");
188 }
189
190 Ok(total)
191 }
192
193 // ──────────────────────────────────────────────────────────────────────────────
194 // Rollup data model
195 // ──────────────────────────────────────────────────────────────────────────────
196
197 /// Per-tool aggregated counters.
198 #[derive(Debug, Default, serde::Serialize)]
199 pub struct ToolStats {
200 pub calls: u64,
201 /// Calls that were auto-approved (no prompt required).
202 pub auto_approved: u64,
203 /// Calls that required a manual prompt.
204 pub prompted: u64,
205 /// Total elapsed ms (from events that carry this field).
206 pub total_elapsed_ms: u64,
207 /// Number of elapsed_ms samples included in `total_elapsed_ms`.
208 pub elapsed_samples: u64,
209 /// Successful calls (where we have result data).
210 pub successes: u64,
211 /// Failed calls.
212 pub failures: u64,
213 /// Calls an approval receipt blocked before they ran. A denial is neither
214 /// a success nor a failure, so it stays out of `success_rate_pct`.
215 pub denied: u64,
216 /// Durable receipts whose outcome could not be read. Never folded into
217 /// `failures`: an unrecorded outcome is unknown, not a failure.
218 pub outcome_unknown: u64,
219 /// Terminal receipts with no usable `started_at`/`ended_at` pair. Counted
220 /// rather than contributing a 0 ms sample, which would understate a call
221 /// that was actually slow.
222 pub elapsed_unavailable: u64,
223 }
224
225 impl ToolStats {
226 fn success_rate_pct(&self) -> Option<f64> {
227 let judged = self.successes + self.failures;
228 if judged == 0 {
229 None
230 } else {
231 Some(self.successes as f64 / judged as f64 * 100.0)
232 }
233 }
234
235 fn avg_elapsed_ms(&self) -> Option<u64> {
236 self.total_elapsed_ms.checked_div(self.elapsed_samples)
237 }
238 }
239
240 /// Compaction event stats.
241 #[derive(Debug, Default, serde::Serialize)]
242 pub struct CompactionStats {
243 pub events: u64,
244 pub refusals: HashMap<String, u64>,
245 pub triggers: HashMap<String, u64>,
246 pub paths: HashMap<String, u64>,
247 pub summarizer_usage_samples: u64,
248 pub summarizer_input_tokens: u64,
249 pub summarizer_output_tokens: u64,
250 #[serde(skip)]
251 receipt_ids: HashSet<String>,
252 /// Sum of `reduction_ratio` from events that carry it (0.0–1.0 each).
253 pub ratio_sum: f64,
254 pub ratio_samples: u64,
255 }
256
257 impl CompactionStats {
258 fn avg_reduction_pct(&self) -> Option<f64> {
259 if self.ratio_samples == 0 {
260 None
261 } else {
262 Some(self.ratio_sum / self.ratio_samples as f64 * 100.0)
263 }
264 }
265 }
266
267 /// Sub-agent lifecycle receipt counts; these are not unique worker totals.
268 #[derive(Debug, Default, serde::Serialize)]
269 pub struct AgentStats {
270 pub spawns: u64,
271 pub successes: u64,
272 pub failures: u64,
273 pub cancelled: u64,
274 pub interrupted: u64,
275 pub budget_exhausted: u64,
276 /// Terminal receipts with missing, malformed, or unrecognized outcomes.
277 pub unknown_outcomes: u64,
278 /// Completions carrying a usage receipt. Token sums cover exactly these;
279 /// a completion without usage is a missing receipt, never zero tokens.
280 pub usage_receipts: u64,
281 pub input_tokens: u64,
282 pub output_tokens: u64,
283 pub total_tokens: u64,
284 /// Summed priced subtotal in microdollars, JSON consumers only.
285 pub cost_microusd: u64,
286 #[serde(skip)]
287 recorded_spawn_ids: HashSet<String>,
288 #[serde(skip)]
289 recorded_completion_ids: HashSet<String>,
290 }
291
292 impl AgentStats {
293 fn event_agent_id(event: &Value) -> Option<String> {
294 event
295 .pointer("/details/agent_id")
296 .or_else(|| event.pointer("/payload/agent_id"))
297 .and_then(Value::as_str)
298 .filter(|id| !id.is_empty())
299 .map(ToString::to_string)
300 }
301
302 fn record_spawn(&mut self, event: &Value) {
303 if let Some(id) = Self::event_agent_id(event)
304 && !self.recorded_spawn_ids.insert(id)
305 {
306 return;
307 }
308 self.spawns = self.spawns.saturating_add(1);
309 }
310
311 fn record_completion(&mut self, event: &Value) {
312 if let Some(id) = Self::event_agent_id(event)
313 && !self.recorded_completion_ids.insert(id)
314 {
315 return;
316 }
317 let status = event
318 .pointer("/details/worker_status")
319 .or_else(|| event.pointer("/payload/worker_status"))
320 .or_else(|| event.pointer("/details/status"))
321 .or_else(|| event.pointer("/payload/status"));
322 let count = if let Some(status) = status {
323 match status.as_str() {
324 Some("completed") => &mut self.successes,
325 Some("failed") => &mut self.failures,
326 Some("cancelled") => &mut self.cancelled,
327 Some("interrupted") => &mut self.interrupted,
328 Some("budget_exhausted") => &mut self.budget_exhausted,
329 _ => &mut self.unknown_outcomes,
330 }
331 } else {
332 match event
333 .pointer("/details/success")
334 .or_else(|| event.pointer("/payload/success"))
335 .and_then(Value::as_bool)
336 {
337 Some(true) => &mut self.successes,
338 Some(false) => &mut self.failures,
339 None => &mut self.unknown_outcomes,
340 }
341 };
342 *count = count.saturating_add(1);
343 let usage = event
344 .pointer("/payload/usage")
345 .or_else(|| event.pointer("/details/usage"));
346 if let Some(usage) = usage
347 && usage.is_object()
348 {
349 self.record_usage_object(usage);
350 }
351 }
352
353 fn record_usage_object(&mut self, usage: &Value) {
354 let input = usage.get("input_tokens").and_then(Value::as_u64);
355 let output = usage.get("output_tokens").and_then(Value::as_u64);
356 let total = usage.get("total_tokens").and_then(Value::as_u64);
357 let cost = usage.get("cost_microusd").and_then(Value::as_u64);
358 if input.is_none() && output.is_none() && total.is_none() && cost.is_none() {
359 return;
360 }
361 self.usage_receipts = self.usage_receipts.saturating_add(1);
362 if let Some(n) = input {
363 self.input_tokens = self.input_tokens.saturating_add(n);
364 }
365 if let Some(n) = output {
366 self.output_tokens = self.output_tokens.saturating_add(n);
367 }
368 if let Some(n) = total {
369 self.total_tokens = self.total_tokens.saturating_add(n);
370 }
371 if let Some(n) = cost {
372 self.cost_microusd = self.cost_microusd.saturating_add(n);
373 }
374 }
375
376 fn summary(&self) -> String {
377 let outcomes = [
378 (self.successes, "completed"),
379 (self.failures, "failed"),
380 (self.cancelled, "cancelled"),
381 (self.interrupted, "interrupted"),
382 (self.budget_exhausted, "budget exhausted"),
383 (self.unknown_outcomes, "outcome unconfirmed"),
384 ]
385 .into_iter()
386 .filter(|(count, _)| *count > 0)
387 .map(|(count, label)| format!("{} {label}", fmt_num(count)))
388 .collect::<Vec<_>>();
389 if self.spawns == 0 && outcomes.is_empty() {
390 return "Sub-agents: (no data)".to_string();
391 }
392 let mut summary = format!("Sub-agents: {} spawn receipts", fmt_num(self.spawns));
393 if !outcomes.is_empty() {
394 summary.push_str(&format!("; outcomes: {}", outcomes.join(", ")));
395 }
396 if self.usage_receipts > 0 {
397 summary.push_str(&format!(
398 "; tokens: {} in/{} out/{} total ({} {})",
399 fmt_num(self.input_tokens),
400 fmt_num(self.output_tokens),
401 fmt_num(self.total_tokens),
402 fmt_num(self.usage_receipts),
403 if self.usage_receipts == 1 {
404 "receipt"
405 } else {
406 "receipts"
407 },
408 ));
409 }
410 summary
411 }
412 }
413
414 /// Capacity-controller / rate-limit intervention stats.
415 #[derive(Debug, Default, serde::Serialize)]
416 pub struct CapacityStats {
417 pub total: u64,
418 pub by_category: HashMap<String, u64>,
419 }
420
421 /// Credential / session event stats (from audit log).
422 #[derive(Debug, Default, serde::Serialize)]
423 pub struct CredentialStats {
424 pub saves: u64,
425 pub clears: u64,
426 }
427
428 /// Runtime receipts for model-client dispatch and provider-reported usage.
429 ///
430 /// These are deliberately not billing records: the terminal diagnostics count
431 /// parent model-client calls, while `turn.usage` exists only when a provider
432 /// supplied usage for one call. Client-internal HTTP retries and invoices are
433 /// outside both receipts.
434 #[derive(Debug, Default, serde::Serialize)]
435 pub struct RuntimeRequestStats {
436 /// Distinct durable `turn.completed` receipts with a usable `(thread, turn)` identity.
437 pub terminal_turn_receipts: u64,
438 /// Terminal receipts carrying the optional request diagnostics projection.
439 pub diagnostics_turn_receipts: u64,
440 /// Terminal receipts from older or partial logs with no diagnostics projection.
441 pub diagnostics_unavailable_turn_receipts: u64,
442 /// Present-but-incomplete diagnostics are unknown rather than zero.
443 pub diagnostics_incomplete_turn_receipts: u64,
444 /// Terminal receipts omitted because their identity could not be verified.
445 pub terminal_receipts_without_identity: u64,
446 /// Repeated terminal snapshots for one `(thread, turn)` omitted from the rollup.
447 pub duplicate_terminal_receipts_skipped: u64,
448 /// Parent model-client calls recorded by terminal diagnostics, not HTTP retries or invoices.
449 pub model_requests_started: u64,
450 pub transparent_stream_retries: u64,
451 pub stream_resumes: u64,
452 /// Distinct `turn.usage` receipts with a verified runtime event identity.
453 pub provider_usage_receipts: u64,
454 /// `turn.usage` records that could not be identified, so their values are unknown.
455 pub provider_usage_receipts_without_identity: u64,
456 /// Repeated runtime event identities omitted from provider usage totals.
457 pub duplicate_provider_usage_receipts_skipped: u64,
458 /// `turn.usage` records missing either required token total are not treated as zero.
459 pub provider_usage_receipts_incomplete: u64,
460 /// Provider-reported per-request input tokens only; terminal cumulative snapshots are excluded.
461 pub provider_reported_input_tokens: u64,
462 /// Provider-reported per-request output tokens only; terminal cumulative snapshots are excluded.
463 pub provider_reported_output_tokens: u64,
464 }
465
466 #[derive(Debug, Default, serde::Serialize)]
467 pub struct SessionUsageStats {
468 pub sessions: u64,
469 pub usage_receipts: u64,
470 pub usage_receipts_incomplete: u64,
471 pub provider_reported_input_tokens: u64,
472 pub provider_reported_output_tokens: u64,
473 pub sessions_with_total_tokens_only: u64,
474 pub total_tokens_only: u64,
475 }
476
477 fn record_session_usage(v: &Value, rollup: &mut Rollup) {
478 let Some(sources) = v
479 .pointer("/metadata/cost/accounted_usage_sources")
480 .and_then(Value::as_object)
481 else {
482 let total = v
483 .pointer("/metadata/total_tokens")
484 .and_then(Value::as_u64)
485 .unwrap_or(0);
486 if total > 0 {
487 let stats = &mut rollup.session_usage;
488 stats.sessions_with_total_tokens_only =
489 stats.sessions_with_total_tokens_only.saturating_add(1);
490 stats.total_tokens_only = stats.total_tokens_only.saturating_add(total);
491 }
492 return;
493 };
494 let stats = &mut rollup.session_usage;
495 let mut counted = false;
496 for contribution in sources.values() {
497 let record = contribution.get("record");
498 let reported = match record
499 .and_then(|record| record.pointer("/settlement/coverage"))
500 .and_then(Value::as_str)
501 {
502 Some(coverage) => matches!(coverage, "reported" | "incomplete"),
503 None => record
504 .and_then(|record| record.pointer("/usage/usage"))
505 .is_some_and(|usage| {
506 usage.get("input_tokens").and_then(Value::as_u64) != Some(0)
507 || usage.get("output_tokens").and_then(Value::as_u64) != Some(0)
508 }),
509 };
510 if !reported {
511 continue;
512 }
513 let tokens = |name: &str| {
514 record
515 .and_then(|record| record.pointer(&format!("/usage/usage/{name}")))
516 .and_then(Value::as_u64)
517 };
518 let (Some(input), Some(output)) = (tokens("input_tokens"), tokens("output_tokens")) else {
519 stats.usage_receipts_incomplete = stats.usage_receipts_incomplete.saturating_add(1);
520 continue;
521 };
522 stats.usage_receipts = stats.usage_receipts.saturating_add(1);
523 stats.provider_reported_input_tokens =
524 stats.provider_reported_input_tokens.saturating_add(input);
525 stats.provider_reported_output_tokens =
526 stats.provider_reported_output_tokens.saturating_add(output);
527 counted = true;
528 }
529 if counted {
530 stats.sessions = stats.sessions.saturating_add(1);
531 }
532 }
533
534 /// Top-level rollup.
535 #[derive(Debug, Default, serde::Serialize)]
536 pub struct Rollup {
537 stats: Option<stats::StatsReport>,
538 pub receipt_read_gaps: u64,
539 #[serde(skip)]
540 receipt_inspection_bytes: usize,
541 #[serde(default)]
542 pub receipt_inspection_exhausted: bool,
543 /// UTC timestamp of the earliest event we've seen.
544 pub earliest_ts: Option<DateTime<Utc>>,
545 /// UTC timestamp of the latest event we've seen.
546 pub latest_ts: Option<DateTime<Utc>>,
547 /// Per-tool stats keyed by tool name.
548 pub tools: HashMap<String, ToolStats>,
549 pub compaction: CompactionStats,
550 pub agents: AgentStats,
551 pub capacity: CapacityStats,
552 pub credentials: CredentialStats,
553 pub runtime_requests: RuntimeRequestStats,
554 pub session_usage: SessionUsageStats,
555 /// Total lines read across all sources.
556 pub total_lines: u64,
557 /// Lines successfully parsed.
558 pub parsed_lines: u64,
559 }
560
561 #[derive(Default)]
562 struct RuntimeEventDedup {
563 terminal_turns: HashSet<(String, String)>,
564 event_records: HashSet<(String, u64)>,
565 }
566
567 impl Rollup {
568 fn admit_receipt_inspection(&mut self, value: &Value) -> bool {
569 if self.receipt_inspection_exhausted {
570 return false;
571 }
572 let bytes = value.to_string().len();
573 let next = self.receipt_inspection_bytes.checked_add(bytes);
574 match next {
575 Some(next)
576 if next <= codewhale_engine::session_manager::SESSION_METADATA_READ_LIMIT =>
577 {
578 self.receipt_inspection_bytes = next;
579 true
580 }
581 _ => {
582 self.receipt_read_gaps = self.receipt_read_gaps.saturating_add(1);
583 self.receipt_inspection_exhausted = true;
584 false
585 }
586 }
587 }
588
589 fn touch_ts(&mut self, ts: &DateTime<Utc>) {
590 match self.earliest_ts {
591 None => self.earliest_ts = Some(*ts),
592 Some(ref cur) if ts < cur => self.earliest_ts = Some(*ts),
593 _ => {}
594 }
595 match self.latest_ts {
596 None => self.latest_ts = Some(*ts),
597 Some(ref cur) if ts > cur => self.latest_ts = Some(*ts),
598 _ => {}
599 }
600 }
601
602 fn tool_mut(&mut self, name: &str) -> &mut ToolStats {
603 self.tools.entry(name.to_string()).or_default()
604 }
605
606 fn total_tool_calls(&self) -> u64 {
607 self.tools.values().map(|t| t.calls).sum()
608 }
609 }
610
611 // ──────────────────────────────────────────────────────────────────────────────
612 // Source readers
613 // ──────────────────────────────────────────────────────────────────────────────
614
615 fn open_diagnostic_file(path: &Path) -> io::Result<std::fs::File> {
616 let parent = path.parent().ok_or_else(|| {
617 io::Error::new(
618 io::ErrorKind::InvalidInput,
619 "diagnostic record has no parent",
620 )
621 })?;
622 let name = path.file_name().ok_or_else(|| {
623 io::Error::new(
624 io::ErrorKind::InvalidInput,
625 "diagnostic record has no filename",
626 )
627 })?;
628 codewhale_util::files::WorkspaceFile::open_resolved_root(parent, Path::new(name), false)?
629 .open_file_shared()
630 }
631
632 fn read_diagnostic_text(path: &Path) -> io::Result<String> {
633 let mut raw = Vec::new();
634 let limit = codewhale_engine::session_manager::SESSION_METADATA_READ_LIMIT;
635 open_diagnostic_file(path)?
636 .take(limit as u64 + 1)
637 .read_to_end(&mut raw)?;
638 if raw.len() > limit {
639 return Err(io::Error::new(
640 io::ErrorKind::FileTooLarge,
641 "diagnostic record exceeds the session inspection limit",
642 ));
643 }
644 String::from_utf8(raw)
645 .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "diagnostic record is not UTF-8"))
646 }
647
648 fn read_diagnostic_json(path: &Path) -> Result<Value> {
649 Ok(serde_json::from_str(&read_diagnostic_text(path)?)?)
650 }
651
652 struct DiagnosticLines {
653 reader: std::io::BufReader<std::fs::File>,
654 finished: bool,
655 }
656
657 impl Iterator for DiagnosticLines {
658 type Item = io::Result<String>;
659
660 fn next(&mut self) -> Option<Self::Item> {
661 if self.finished {
662 return None;
663 }
664 let mut raw = Vec::new();
665 let limit = codewhale_engine::session_manager::SESSION_METADATA_READ_LIMIT;
666 let result = self
667 .reader
668 .by_ref()
669 .take(limit as u64 + 1)
670 .read_until(b'\n', &mut raw);
671 match result {
672 Ok(0) => {
673 self.finished = true;
674 None
675 }
676 Ok(_) if raw.len() > limit => {
677 self.finished = true;
678 Some(Err(io::Error::new(
679 io::ErrorKind::FileTooLarge,
680 "diagnostic frame exceeds the session inspection limit",
681 )))
682 }
683 Ok(_) => Some(String::from_utf8(raw).map_err(|_| {
684 io::Error::new(io::ErrorKind::InvalidData, "diagnostic frame is not UTF-8")
685 })),
686 Err(error) => {
687 self.finished = true;
688 Some(Err(error))
689 }
690 }
691 }
692 }
693
694 fn diagnostic_lines(file: std::fs::File) -> DiagnosticLines {
695 DiagnosticLines {
696 reader: std::io::BufReader::new(file),
697 finished: false,
698 }
699 }
700
701 /// Read both retained generations from each root. A copied legacy record is
702 /// counted once across roots, while repeated records within one root retain
703 /// their multiplicity. No source log is rewritten or removed.
704 fn read_audit_history(roots: &[PathBuf], since: Option<DateTime<Utc>>, rollup: &mut Rollup) {
705 if rollup.receipt_inspection_exhausted {
706 return;
707 }
708 let mut earlier_roots = HashMap::new();
709 for root in roots {
710 let mut root_counts = HashMap::new();
711 for name in ["audit.log.1", "audit.log"] {
712 read_audit_log(
713 &root.join(name),
714 since,
715 rollup,
716 &earlier_roots,
717 &mut root_counts,
718 );
719 }
720 for (record, count) in root_counts {
721 let prior = earlier_roots.entry(record).or_insert(0);
722 *prior = (*prior).max(count);
723 }
724 }
725 }
726
727 /// Read one JSON event per line, excluding copies already seen in other roots.
728 fn read_audit_log(
729 path: &Path,
730 since: Option<DateTime<Utc>>,
731 rollup: &mut Rollup,
732 earlier_roots: &HashMap<[u8; 32], u64>,
733 root_counts: &mut HashMap<[u8; 32], u64>,
734 ) {
735 if rollup.receipt_inspection_exhausted {
736 return;
737 }
738 let file = match open_diagnostic_file(path) {
739 Ok(file) => file,
740 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return,
741 Err(e) => {
742 rollup.receipt_read_gaps = rollup.receipt_read_gaps.saturating_add(1);
743 tracing::trace!(
744 "metrics: could not read audit log {}: {}",
745 path.display(),
746 e
747 );
748 return;
749 }
750 };
751
752 // Streamed line by line: an append-only log is unbounded, and holding it
753 // whole only to aggregate one line at a time made allocation scale with it.
754 for raw_line in diagnostic_lines(file) {
755 let Ok(raw_line) = raw_line.inspect_err(|e| {
756 rollup.receipt_read_gaps = rollup.receipt_read_gaps.saturating_add(1);
757 tracing::trace!("metrics: stopped reading audit log {}: {e}", path.display());
758 }) else {
759 break;
760 };
761 rollup.total_lines += 1;
762 let line = raw_line.trim();
763 if line.is_empty() {
764 continue;
765 }
766
767 let v: Value = match serde_json::from_str(line) {
768 Ok(v) => v,
769 Err(e) => {
770 rollup.receipt_read_gaps = rollup.receipt_read_gaps.saturating_add(1);
771 tracing::trace!("metrics: skipping malformed audit line: {e}");
772 continue;
773 }
774 };
775
776 if let Some(cutoff) = since
777 && parse_ts_field(&v, "ts").is_some_and(|timestamp| timestamp < cutoff)
778 {
779 continue;
780 }
781 if !rollup.admit_receipt_inspection(&v) {
782 break;
783 }
784
785 // Copy migration preserves the complete event, including its timestamp.
786 // Count occurrences so two identical legitimate records in one source
787 // are not collapsed into one merely because another root also exists.
788 let fingerprint: [u8; 32] = Sha256::digest(v.to_string().as_bytes()).into();
789 let count = root_counts.entry(fingerprint).or_insert(0);
790 *count += 1;
791 if *count <= earlier_roots.get(&fingerprint).copied().unwrap_or(0) {
792 continue;
793 }
794
795 // Parse timestamp — field is "ts" in audit log.
796 let ts = parse_ts_field(&v, "ts");
797
798 if let Some(cutoff) = since {
799 match ts {
800 Some(t) if t < cutoff => continue,
801 _ => {}
802 }
803 }
804
805 rollup.parsed_lines += 1;
806 if let Some(t) = &ts {
807 rollup.touch_ts(t);
808 }
809
810 let event = v.get("event").and_then(|e| e.as_str()).unwrap_or("");
811
812 match event {
813 // `log_sensitive_event` emits `auto_approve_session`
814 // (`crates/tui/src/tui/ui/event_loop.rs`). The bare `auto_approve`
815 // name only ever appears in older logs; keep it as an alias.
816 "tool.approval.auto_approve" | "tool.approval.auto_approve_session" => {
817 let tool_name = audit_tool_name(&v);
818 let stats = rollup.tool_mut(tool_name);
819 stats.calls += 1;
820 stats.auto_approved += 1;
821 }
822 // Every denial name written by `log_sensitive_event` and
823 // `auto_deny_session_approval`. The call never ran, so it is
824 // counted as its own class rather than as a failed execution.
825 "tool.approval.auto_deny"
826 | "tool.approval.auto_deny_session"
827 | "tool.approval.auto_deny_auto_review"
828 | "tool.approval.auto_deny_full_access_policy" => {
829 let tool_name = audit_tool_name(&v);
830 let stats = rollup.tool_mut(tool_name);
831 stats.calls += 1;
832 stats.denied += 1;
833 }
834 "tool.approval.prompted" => {
835 let tool_name = audit_tool_name(&v);
836 let stats = rollup.tool_mut(tool_name);
837 stats.calls += 1;
838 stats.prompted += 1;
839 }
840 "tool.completed" | "tool.result" => {
841 let tool_name = audit_tool_name(&v);
842 let stats = rollup.tool_mut(tool_name);
843 stats.calls += 1;
844
845 // Optional elapsed_ms
846 if let Some(ms) = v
847 .pointer("/details/elapsed_ms")
848 .or_else(|| v.pointer("/payload/elapsed_ms"))
849 .or_else(|| v.get("elapsed_ms"))
850 .and_then(|v| v.as_u64())
851 {
852 stats.total_elapsed_ms += ms;
853 stats.elapsed_samples += 1;
854 }
855
856 // Success / failure. An absent outcome is unknown, not a
857 // success — the previous default silently graded every
858 // outcome-free receipt as passing.
859 match v
860 .pointer("/details/success")
861 .or_else(|| v.pointer("/payload/success"))
862 .or_else(|| v.get("success"))
863 .and_then(|b| b.as_bool())
864 {
865 Some(true) => stats.successes += 1,
866 Some(false) => stats.failures += 1,
867 None => stats.outcome_unknown += 1,
868 }
869 }
870 "compaction.refused" => {
871 let reason = v
872 .pointer("/details/reason")
873 .and_then(Value::as_str)
874 .unwrap_or("unknown");
875 *rollup
876 .compaction
877 .refusals
878 .entry(reason.to_string())
879 .or_default() += 1;
880 }
881 "compaction.completed" | "context.compaction" => {
882 if let Some(id) = compaction_receipt_identity(&v, false)
883 && !rollup.compaction.receipt_ids.insert(id)
884 {
885 continue;
886 }
887 for (field, counts) in [
888 ("trigger", &mut rollup.compaction.triggers),
889 ("path", &mut rollup.compaction.paths),
890 ] {
891 if let Some(value) = v
892 .pointer(&format!("/details/{field}"))
893 .and_then(Value::as_str)
894 {
895 *counts.entry(value.to_string()).or_default() += 1;
896 }
897 }
898 if let (Some(input), Some(output)) = (
899 v.pointer("/details/summarizer_usage/input_tokens")
900 .and_then(Value::as_u64),
901 v.pointer("/details/summarizer_usage/output_tokens")
902 .and_then(Value::as_u64),
903 ) {
904 rollup.compaction.summarizer_usage_samples += 1;
905 rollup.compaction.summarizer_input_tokens += input;
906 rollup.compaction.summarizer_output_tokens += output;
907 }
908 rollup.compaction.events += 1;
909 if let Some(ratio) = v
910 .pointer("/details/reduction_ratio")
911 .or_else(|| v.pointer("/payload/reduction_ratio"))
912 .and_then(|r| r.as_f64())
913 {
914 rollup.compaction.ratio_sum += ratio;
915 rollup.compaction.ratio_samples += 1;
916 }
917 }
918 "agent.spawn" | "agent.spawned" | "subagent.spawned" => {
919 rollup.agents.record_spawn(&v);
920 }
921 "agent.completed" | "subagent.completed" => {
922 rollup.agents.record_completion(&v);
923 }
924 e if e.starts_with("capacity.") => {
925 rollup.capacity.total += 1;
926 let category = v
927 .pointer("/details/category")
928 .or_else(|| v.pointer("/payload/category"))
929 .and_then(|c| c.as_str())
930 .unwrap_or(e.trim_start_matches("capacity."));
931 *rollup
932 .capacity
933 .by_category
934 .entry(category.to_string())
935 .or_insert(0) += 1;
936 }
937 "credential.save" => {
938 rollup.credentials.saves += 1;
939 }
940 "credential.clear" => {
941 rollup.credentials.clears += 1;
942 }
943 _ => {
944 // Unknown event — tracked in parsed_lines but otherwise ignored.
945 }
946 }
947 }
948 }
949
950 /// Read session JSON files under `sessions/` (one per session).
951 /// These carry tool call history with optional elapsed_ms and result data.
952 fn read_session_files(sessions_dir: &Path, since: Option<DateTime<Utc>>, rollup: &mut Rollup) {
953 if rollup.receipt_inspection_exhausted {
954 return;
955 }
956 let rd = match std::fs::read_dir(sessions_dir) {
957 Ok(rd) => rd,
958 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return,
959 Err(e) => {
960 rollup.receipt_read_gaps = rollup.receipt_read_gaps.saturating_add(1);
961 tracing::trace!(
962 "metrics: could not list sessions dir {}: {}",
963 sessions_dir.display(),
964 e
965 );
966 return;
967 }
968 };
969
970 for entry in rd {
971 let entry = match entry {
972 Ok(entry) => entry,
973 Err(_) => {
974 rollup.receipt_read_gaps = rollup.receipt_read_gaps.saturating_add(1);
975 continue;
976 }
977 };
978 if rollup.receipt_inspection_exhausted {
979 break;
980 }
981 let path = entry.path();
982 // Only look at .json files directly in sessions/; skip sub-dirs.
983 if path.is_dir() || path.extension().map(|e| e != "json").unwrap_or(true) {
984 continue;
985 }
986 read_session_file(&path, since, rollup);
987 }
988 }
989
990 fn read_session_file(path: &Path, since: Option<DateTime<Utc>>, rollup: &mut Rollup) {
991 if rollup.receipt_inspection_exhausted {
992 return;
993 }
994 if let Some(cutoff) = since
995 && let Ok(metadata) =
996 codewhale_engine::session_manager::SessionManager::load_session_metadata(path)
997 && metadata.updated_at < cutoff
998 {
999 return;
1000 }
1001 let content = match read_diagnostic_text(path) {
1002 Ok(c) => c,
1003 Err(e) => {
1004 rollup.receipt_read_gaps = rollup.receipt_read_gaps.saturating_add(1);
1005 tracing::trace!(
1006 "metrics: could not read session file {}: {}",
1007 path.display(),
1008 e
1009 );
1010 return;
1011 }
1012 };
1013
1014 rollup.total_lines += 1;
1015
1016 let v: Value = match serde_json::from_str(&content) {
1017 Ok(v) => v,
1018 Err(e) => {
1019 rollup.receipt_read_gaps = rollup.receipt_read_gaps.saturating_add(1);
1020 tracing::trace!(
1021 "metrics: skipping malformed session file {}: {}",
1022 path.display(),
1023 e
1024 );
1025 return;
1026 }
1027 };
1028
1029 let session_ts = v
1030 .pointer("/metadata/updated_at")
1031 .or_else(|| v.pointer("/metadata/created_at"))
1032 .and_then(|t| t.as_str())
1033 .and_then(|s| s.parse::<DateTime<Utc>>().ok());
1034
1035 if let Some(cutoff) = since
1036 && let Some(ts) = &session_ts
1037 && *ts < cutoff
1038 {
1039 return;
1040 }
1041
1042 if !rollup.admit_receipt_inspection(&v) {
1043 return;
1044 }
1045
1046 rollup.parsed_lines += 1;
1047
1048 if let Some(ts) = session_ts {
1049 rollup.touch_ts(&ts);
1050 }
1051
1052 record_session_usage(&v, rollup);
1053
1054 // Walk messages looking for tool_use calls with associated results.
1055 let messages = match v.get("messages").and_then(|m| m.as_array()) {
1056 Some(m) => m,
1057 None => return,
1058 };
1059
1060 // Build a map from tool_use_id → (tool_name, elapsed_ms_option, started_at_option).
1061 let mut pending: HashMap<String, (String, Option<u64>)> = HashMap::new();
1062
1063 for msg in messages {
1064 let role = msg.get("role").and_then(|r| r.as_str()).unwrap_or("");
1065 let content_arr = match msg.get("content").and_then(|c| c.as_array()) {
1066 Some(c) => c,
1067 None => continue,
1068 };
1069
1070 for block in content_arr {
1071 let block_type = block.get("type").and_then(|t| t.as_str()).unwrap_or("");
1072 match (role, block_type) {
1073 ("assistant", "tool_use") => {
1074 let id = block.get("id").and_then(|i| i.as_str()).unwrap_or("");
1075 let name = block
1076 .get("name")
1077 .and_then(|n| n.as_str())
1078 .unwrap_or("unknown");
1079 let elapsed_ms = block.get("elapsed_ms").and_then(|e| e.as_u64());
1080 if !id.is_empty() {
1081 pending.insert(id.to_string(), (name.to_string(), elapsed_ms));
1082 }
1083 }
1084 ("user", "tool_result") => {
1085 let id = block
1086 .get("tool_use_id")
1087 .and_then(|i| i.as_str())
1088 .unwrap_or("");
1089 if let Some((name, elapsed_ms)) = pending.remove(id) {
1090 let stats = rollup.tool_mut(&name);
1091 // Only count if not already counted via audit log (we don't de-dup, so
1092 // session files may double-count approvals; that's acceptable — users who
1093 // want precise counts should use --json and cross-reference).
1094 stats.calls += 1;
1095 if let Some(ms) = elapsed_ms {
1096 stats.total_elapsed_ms += ms;
1097 stats.elapsed_samples += 1;
1098 }
1099 // Tool result success: absence of "is_error": true
1100 let is_error = block
1101 .get("is_error")
1102 .and_then(|e| e.as_bool())
1103 .unwrap_or(false);
1104 if is_error {
1105 stats.failures += 1;
1106 } else {
1107 stats.successes += 1;
1108 }
1109 }
1110 }
1111 _ => {}
1112 }
1113 }
1114 }
1115
1116 // Walk messages for compaction events embedded as special user messages.
1117 for msg in messages {
1118 if let Some(compaction) = msg
1119 .get("compaction")
1120 .or_else(|| msg.pointer("/metadata/compaction"))
1121 {
1122 rollup.compaction.events += 1;
1123 if let Some(ratio) = compaction.get("reduction_ratio").and_then(|r| r.as_f64()) {
1124 rollup.compaction.ratio_sum += ratio;
1125 rollup.compaction.ratio_samples += 1;
1126 }
1127 }
1128 }
1129 }
1130
1131 fn read_subagent_state_files(
1132 state_dir: &Path,
1133 workspace_ids: &std::collections::BTreeSet<String>,
1134 since: Option<DateTime<Utc>>,
1135 rollup: &mut Rollup,
1136 ) {
1137 if rollup.receipt_inspection_exhausted {
1138 return;
1139 }
1140 let mut dirs = Vec::new();
1141 let mut seen_dirs = HashSet::new();
1142 if seen_dirs.insert(state_dir.to_path_buf()) {
1143 dirs.push(state_dir.to_path_buf());
1144 }
1145 for workspace in workspace_ids {
1146 let dir = PathBuf::from(workspace).join(".codewhale").join("state");
1147 if seen_dirs.insert(dir.clone()) {
1148 dirs.push(dir);
1149 }
1150 }
1151 for dir in dirs {
1152 if rollup.receipt_inspection_exhausted {
1153 break;
1154 }
1155 let v3 = dir.join("subagents.v3.json");
1156 let v1 = dir.join("subagents.v1.json");
1157 let path = if v3.is_file() {
1158 v3
1159 } else if v1.is_file() {
1160 v1
1161 } else {
1162 continue;
1163 };
1164 read_subagent_state_file(&path, since, rollup);
1165 }
1166 }
1167
1168 fn subagent_ms_timestamp(value: &Value, keys: &[&str]) -> Option<DateTime<Utc>> {
1169 keys.iter()
1170 .find_map(|key| value.get(*key).and_then(Value::as_u64))
1171 .and_then(|ms| i64::try_from(ms).ok())
1172 .and_then(DateTime::<Utc>::from_timestamp_millis)
1173 }
1174
1175 fn subagent_terminal_status(status: &Value) -> Option<&'static str> {
1176 if let Some(s) = status.as_str() {
1177 return match s.to_ascii_lowercase().as_str() {
1178 "completed" => Some("completed"),
1179 "failed" => Some("failed"),
1180 "cancelled" => Some("cancelled"),
1181 "interrupted" => Some("interrupted"),
1182 "budget_exhausted" | "budgetexhausted" => Some("budget_exhausted"),
1183 _ => None,
1184 };
1185 }
1186 if let Some(map) = status.as_object() {
1187 if map.contains_key("Failed") || map.contains_key("failed") {
1188 return Some("failed");
1189 }
1190 if map.contains_key("Interrupted") || map.contains_key("interrupted") {
1191 return Some("interrupted");
1192 }
1193 }
1194 None
1195 }
1196
1197 fn read_subagent_state_file(path: &Path, since: Option<DateTime<Utc>>, rollup: &mut Rollup) {
1198 if rollup.receipt_inspection_exhausted {
1199 return;
1200 }
1201 let value = match read_diagnostic_json(path) {
1202 Ok(value) => value,
1203 Err(_) => {
1204 rollup.receipt_read_gaps = rollup.receipt_read_gaps.saturating_add(1);
1205 return;
1206 }
1207 };
1208 let state = value
1209 .get("state")
1210 .filter(|state| state.is_object())
1211 .unwrap_or(&value);
1212 if let Some(workers) = state.get("workers").and_then(Value::as_array) {
1213 for worker in workers {
1214 let ts = subagent_ms_timestamp(
1215 worker,
1216 &["completed_at_ms", "updated_at_ms", "created_at_ms"],
1217 );
1218 if let Some(cutoff) = since
1219 && ts.is_some_and(|t| t < cutoff)
1220 {
1221 continue;
1222 }
1223 if !rollup.admit_receipt_inspection(worker) {
1224 return;
1225 }
1226 if let Some(t) = &ts {
1227 rollup.touch_ts(t);
1228 }
1229 let id = worker
1230 .pointer("/spec/worker_id")
1231 .or_else(|| worker.pointer("/spec/id"))
1232 .or_else(|| worker.get("id"))
1233 .and_then(Value::as_str)
1234 .filter(|id| !id.is_empty());
1235 if let Some(id) = id {
1236 if rollup.agents.recorded_spawn_ids.insert(id.to_string()) {
1237 rollup.agents.spawns = rollup.agents.spawns.saturating_add(1);
1238 }
1239 } else {
1240 rollup.agents.spawns = rollup.agents.spawns.saturating_add(1);
1241 }
1242 if let Some(status) = worker.get("status").and_then(subagent_terminal_status) {
1243 if let Some(id) = id
1244 && !rollup.agents.recorded_completion_ids.insert(id.to_string())
1245 {
1246 continue;
1247 }
1248 let counter = match status {
1249 "completed" => &mut rollup.agents.successes,
1250 "failed" => &mut rollup.agents.failures,
1251 "cancelled" => &mut rollup.agents.cancelled,
1252 "interrupted" => &mut rollup.agents.interrupted,
1253 "budget_exhausted" => &mut rollup.agents.budget_exhausted,
1254 _ => &mut rollup.agents.unknown_outcomes,
1255 };
1256 *counter = counter.saturating_add(1);
1257 if let Some(usage) = worker.get("usage").filter(|u| u.is_object()) {
1258 rollup.agents.record_usage_object(usage);
1259 }
1260 }
1261 }
1262 }
1263 if let Some(agents) = state.get("agents").and_then(Value::as_array) {
1264 for agent in agents {
1265 let ts = subagent_ms_timestamp(agent, &["updated_at_ms"]);
1266 if let Some(cutoff) = since
1267 && ts.is_some_and(|t| t < cutoff)
1268 {
1269 continue;
1270 }
1271 if !rollup.admit_receipt_inspection(agent) {
1272 return;
1273 }
1274 if let Some(t) = &ts {
1275 rollup.touch_ts(t);
1276 }
1277 let id = agent
1278 .get("id")
1279 .and_then(Value::as_str)
1280 .filter(|id| !id.is_empty());
1281 if let Some(id) = id {
1282 if rollup.agents.recorded_spawn_ids.insert(id.to_string()) {
1283 rollup.agents.spawns = rollup.agents.spawns.saturating_add(1);
1284 }
1285 } else {
1286 rollup.agents.spawns = rollup.agents.spawns.saturating_add(1);
1287 }
1288 if let Some(status) = agent.get("status").and_then(subagent_terminal_status) {
1289 if let Some(id) = id
1290 && !rollup.agents.recorded_completion_ids.insert(id.to_string())
1291 {
1292 continue;
1293 }
1294 let counter = match status {
1295 "completed" => &mut rollup.agents.successes,
1296 "failed" => &mut rollup.agents.failures,
1297 "cancelled" => &mut rollup.agents.cancelled,
1298 "interrupted" => &mut rollup.agents.interrupted,
1299 "budget_exhausted" => &mut rollup.agents.budget_exhausted,
1300 _ => &mut rollup.agents.unknown_outcomes,
1301 };
1302 *counter = counter.saturating_add(1);
1303 if let Some(usage) = agent.get("usage").filter(|u| u.is_object()) {
1304 rollup.agents.record_usage_object(usage);
1305 }
1306 }
1307 }
1308 }
1309 }
1310
1311 /// Every Runtime event directory this install can have written to.
1312 ///
1313 /// Mirrors `default_runtime_store_root` / `runtime_dir_override` in
1314 /// `crates/engine/src/runtime_threads.rs`: the task-scoped store lives at
1315 /// `<tasks>/runtime`, a session-scoped store at `<sessions>/<id>/runtime`, and
1316 /// an explicit `CODEWHALE_RUNTIME_DIR` replaces both. Missing directories are
1317 /// simply empty; the walk stays inside the resolved state roots.
1318 fn runtime_event_dirs(tasks: &Path, sessions: &Path) -> Vec<PathBuf> {
1319 if let Some(root) = runtime_dir_override() {
1320 return vec![root.join("events")];
1321 }
1322 let mut dirs = vec![tasks.join("runtime").join("events")];
1323 let Ok(rd) = std::fs::read_dir(sessions) else {
1324 return dirs;
1325 };
1326 let mut session_dirs: Vec<PathBuf> = rd
1327 .flatten()
1328 // `DirEntry::file_type` does not follow symlinks, so a link planted in
1329 // `sessions/` cannot walk the reader into another root.
1330 .filter(|entry| entry.file_type().is_ok_and(|ty| ty.is_dir()))
1331 .map(|entry| entry.path().join("runtime").join("events"))
1332 .collect();
1333 session_dirs.sort();
1334 dirs.append(&mut session_dirs);
1335 dirs
1336 }
1337
1338 /// The writer's exclusive store-root override (`runtime_dir_override`).
1339 fn runtime_dir_override() -> Option<PathBuf> {
1340 std::env::var("CODEWHALE_RUNTIME_DIR")
1341 .or_else(|_| std::env::var("DEEPSEEK_RUNTIME_DIR"))
1342 .ok()
1343 .filter(|dir| !dir.trim().is_empty())
1344 .map(PathBuf::from)
1345 }
1346
1347 /// Read every runtime event root under one de-duplication scope, so the same
1348 /// `(thread_id, seq)` receipt is counted once however many roots list it.
1349 fn read_runtime_events(events_dirs: &[PathBuf], since: Option<DateTime<Utc>>, rollup: &mut Rollup) {
1350 if rollup.receipt_inspection_exhausted {
1351 return;
1352 }
1353 let mut dedup = RuntimeEventDedup::default();
1354 for dir in events_dirs {
1355 read_runtime_events_dir(dir, since, rollup, &mut dedup);
1356 }
1357 }
1358
1359 /// Read JSONL event streams from one runtime events directory.
1360 fn read_runtime_events_dir(
1361 events_dir: &Path,
1362 since: Option<DateTime<Utc>>,
1363 rollup: &mut Rollup,
1364 dedup: &mut RuntimeEventDedup,
1365 ) {
1366 if rollup.receipt_inspection_exhausted {
1367 return;
1368 }
1369 match std::fs::symlink_metadata(events_dir) {
1370 Ok(metadata) if metadata.is_dir() => {}
1371 Err(error) if error.kind() == io::ErrorKind::NotFound => return,
1372 _ => {
1373 rollup.receipt_read_gaps = rollup.receipt_read_gaps.saturating_add(1);
1374 return;
1375 }
1376 }
1377 let rd = match std::fs::read_dir(events_dir) {
1378 Ok(rd) => rd,
1379 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return,
1380 Err(e) => {
1381 rollup.receipt_read_gaps = rollup.receipt_read_gaps.saturating_add(1);
1382 tracing::trace!(
1383 "metrics: could not list events dir {}: {}",
1384 events_dir.display(),
1385 e
1386 );
1387 return;
1388 }
1389 };
1390
1391 for entry in rd {
1392 let entry = match entry {
1393 Ok(entry) => entry,
1394 Err(_) => {
1395 rollup.receipt_read_gaps = rollup.receipt_read_gaps.saturating_add(1);
1396 continue;
1397 }
1398 };
1399 let path = entry.path();
1400 if path.extension().map(|e| e != "jsonl").unwrap_or(true) {
1401 continue;
1402 }
1403 read_events_jsonl(&path, since, rollup, dedup);
1404 }
1405 }
1406
1407 fn read_events_jsonl(
1408 path: &Path,
1409 since: Option<DateTime<Utc>>,
1410 rollup: &mut Rollup,
1411 dedup: &mut RuntimeEventDedup,
1412 ) {
1413 if rollup.receipt_inspection_exhausted {
1414 return;
1415 }
1416 let file = match open_diagnostic_file(path) {
1417 Ok(file) => file,
1418 Err(e) => {
1419 rollup.receipt_read_gaps = rollup.receipt_read_gaps.saturating_add(1);
1420 tracing::trace!(
1421 "metrics: could not read events file {}: {}",
1422 path.display(),
1423 e
1424 );
1425 return;
1426 }
1427 };
1428
1429 // Streamed like the audit log: allocation follows one line, not the file.
1430 for raw_line in diagnostic_lines(file) {
1431 let Ok(raw_line) = raw_line.inspect_err(|e| {
1432 rollup.receipt_read_gaps = rollup.receipt_read_gaps.saturating_add(1);
1433 tracing::trace!(
1434 "metrics: stopped reading events file {}: {e}",
1435 path.display()
1436 );
1437 }) else {
1438 break;
1439 };
1440 rollup.total_lines += 1;
1441 let line = raw_line.trim();
1442 if line.is_empty() {
1443 continue;
1444 }
1445
1446 let v: Value = match serde_json::from_str(line) {
1447 Ok(v) => v,
1448 Err(e) => {
1449 rollup.receipt_read_gaps = rollup.receipt_read_gaps.saturating_add(1);
1450 tracing::trace!("metrics: skipping malformed event line: {e}");
1451 continue;
1452 }
1453 };
1454
1455 let ts = parse_ts_field(&v, "timestamp");
1456
1457 if let Some(cutoff) = since {
1458 match ts {
1459 Some(t) if t < cutoff => continue,
1460 _ => {}
1461 }
1462 }
1463
1464 if !rollup.admit_receipt_inspection(&v) {
1465 break;
1466 }
1467
1468 rollup.parsed_lines += 1;
1469 if let Some(t) = &ts {
1470 rollup.touch_ts(t);
1471 }
1472
1473 let event = v.get("event").and_then(|e| e.as_str()).unwrap_or("");
1474
1475 match event {
1476 "turn.completed" => record_terminal_request_diagnostics(&v, rollup, dedup),
1477 "turn.usage" => record_provider_usage_receipt(&v, rollup, dedup),
1478 // Tool and compaction receipts are durable *item* records. The
1479 // `tool.started` / `tool.completed` names this reader used to
1480 // match are synthesized for HTTP clients by
1481 // `map_compat_stream_event` (`crates/app-server/src/runtime_api.rs`) and
1482 // are never persisted, so those arms counted nothing.
1483 "item.started" | "item.completed" | "item.failed" => {
1484 record_runtime_item_receipt(event, &v, rollup, dedup);
1485 }
1486 "agent.spawned" | "subagent.spawned" => {
1487 rollup.agents.record_spawn(&v);
1488 }
1489 "agent.completed" | "subagent.completed" => {
1490 rollup.agents.record_completion(&v);
1491 }
1492 e if e.starts_with("capacity.") => {
1493 rollup.capacity.total += 1;
1494 let category = v
1495 .pointer("/payload/category")
1496 .and_then(|c| c.as_str())
1497 .unwrap_or(e.trim_start_matches("capacity."));
1498 *rollup
1499 .capacity
1500 .by_category
1501 .entry(category.to_string())
1502 .or_insert(0) += 1;
1503 }
1504 _ => {}
1505 }
1506 }
1507 }
1508
1509 fn runtime_event_identity(v: &Value) -> Option<(String, u64)> {
1510 Some((
1511 v.get("thread_id")?.as_str()?.to_string(),
1512 v.get("seq")?.as_u64()?,
1513 ))
1514 }
1515
1516 fn terminal_turn_identity(v: &Value) -> Option<(String, String)> {
1517 Some((
1518 v.get("thread_id")?.as_str()?.to_string(),
1519 v.get("turn_id")?.as_str()?.to_string(),
1520 ))
1521 }
1522
1523 fn record_terminal_request_diagnostics(
1524 v: &Value,
1525 rollup: &mut Rollup,
1526 dedup: &mut RuntimeEventDedup,
1527 ) {
1528 let Some(identity) = terminal_turn_identity(v) else {
1529 rollup.runtime_requests.terminal_receipts_without_identity = rollup
1530 .runtime_requests
1531 .terminal_receipts_without_identity
1532 .saturating_add(1);
1533 return;
1534 };
1535 if !dedup.terminal_turns.insert(identity) {
1536 rollup.runtime_requests.duplicate_terminal_receipts_skipped = rollup
1537 .runtime_requests
1538 .duplicate_terminal_receipts_skipped
1539 .saturating_add(1);
1540 return;
1541 }
1542
1543 let stats = &mut rollup.runtime_requests;
1544 stats.terminal_turn_receipts = stats.terminal_turn_receipts.saturating_add(1);
1545 let Some(diagnostics) = v.pointer("/payload/turn/modelRequestDiagnostics") else {
1546 stats.diagnostics_unavailable_turn_receipts = stats
1547 .diagnostics_unavailable_turn_receipts
1548 .saturating_add(1);
1549 return;
1550 };
1551 let Some(model_requests_started) = diagnostics
1552 .get("modelRequestsStarted")
1553 .and_then(Value::as_u64)
1554 else {
1555 stats.diagnostics_incomplete_turn_receipts =
1556 stats.diagnostics_incomplete_turn_receipts.saturating_add(1);
1557 return;
1558 };
1559 let Some(transparent_stream_retries) = diagnostics
1560 .get("transparentStreamRetries")
1561 .and_then(Value::as_u64)
1562 else {
1563 stats.diagnostics_incomplete_turn_receipts =
1564 stats.diagnostics_incomplete_turn_receipts.saturating_add(1);
1565 return;
1566 };
1567 let Some(stream_resumes) = diagnostics.get("streamResumes").and_then(Value::as_u64) else {
1568 stats.diagnostics_incomplete_turn_receipts =
1569 stats.diagnostics_incomplete_turn_receipts.saturating_add(1);
1570 return;
1571 };
1572
1573 stats.diagnostics_turn_receipts = stats.diagnostics_turn_receipts.saturating_add(1);
1574 stats.model_requests_started = stats
1575 .model_requests_started
1576 .saturating_add(model_requests_started);
1577 stats.transparent_stream_retries = stats
1578 .transparent_stream_retries
1579 .saturating_add(transparent_stream_retries);
1580 stats.stream_resumes = stats.stream_resumes.saturating_add(stream_resumes);
1581 }
1582
1583 /// Fold one durable `item.*` receipt into the tool or compaction rollup.
1584 ///
1585 /// Reads only the fields a rollup needs — `kind`, `metadata.tool_name`,
1586 /// `metadata.is_error`, the two timestamps, and the compaction message counts.
1587 /// `item.detail` and `metadata.tool_input` carry tool output and arguments and
1588 /// are deliberately never read here.
1589 fn record_runtime_item_receipt(
1590 event: &str,
1591 v: &Value,
1592 rollup: &mut Rollup,
1593 dedup: &mut RuntimeEventDedup,
1594 ) {
1595 let Some(item) = v.pointer("/payload/item") else {
1596 return;
1597 };
1598 let kind = item.get("kind").and_then(Value::as_str).unwrap_or_default();
1599 let is_tool = matches!(kind, "tool_call" | "file_change" | "command_execution");
1600 if !is_tool && kind != "context_compaction" {
1601 return;
1602 }
1603 // One receipt, counted once. A record with no verifiable runtime identity
1604 // cannot be de-duplicated, so it is counted without one rather than
1605 // dropped — `thread_id` and `seq` are required fields of every record the
1606 // store writes, so this only affects hand-edited logs.
1607 if let Some(identity) = runtime_event_identity(v)
1608 && !dedup.event_records.insert(identity)
1609 {
1610 return;
1611 }
1612
1613 if !is_tool {
1614 record_compaction_item_receipt(event, v, rollup);
1615 return;
1616 }
1617
1618 // `tool_name` is copied forward into the completion metadata, but the
1619 // redaction and error branches rewrite or leave that object alone, so fall
1620 // back to the started record's `tool` projection before giving up. An
1621 // unresolvable name is bucketed, never dropped.
1622 let tool_name = item
1623 .pointer("/metadata/tool_name")
1624 .or_else(|| v.pointer("/payload/tool/name"))
1625 .and_then(Value::as_str)
1626 .unwrap_or("unknown");
1627 let elapsed_ms = item_elapsed_ms(item);
1628 let stats = rollup.tool_mut(tool_name);
1629 match event {
1630 "item.started" => stats.calls += 1,
1631 "item.completed" => match item.pointer("/metadata/is_error").and_then(Value::as_bool) {
1632 Some(false) => stats.successes += 1,
1633 Some(true) => stats.failures += 1,
1634 None => stats.outcome_unknown += 1,
1635 },
1636 // `item.failed` is the engine's own error branch: the tool call did
1637 // run and did not succeed.
1638 _ => stats.failures += 1,
1639 }
1640 if event != "item.started" {
1641 match elapsed_ms {
1642 Some(ms) => {
1643 stats.total_elapsed_ms = stats.total_elapsed_ms.saturating_add(ms);
1644 stats.elapsed_samples += 1;
1645 }
1646 None => stats.elapsed_unavailable += 1,
1647 }
1648 }
1649 }
1650
1651 fn compaction_receipt_identity(v: &Value, runtime: bool) -> Option<String> {
1652 let (session, id) = if runtime {
1653 (
1654 v.get("thread_id")?,
1655 v.pointer("/payload/item/metadata/compaction_id")?,
1656 )
1657 } else {
1658 (
1659 v.pointer("/details/thread_id")
1660 .filter(|id| id.is_string())
1661 .or_else(|| v.pointer("/details/session_id"))?,
1662 v.pointer("/details/compaction_id")?,
1663 )
1664 };
1665 Some(format!("{}:{}", session.as_str()?, id.as_str()?))
1666 }
1667
1668 /// A compaction is only counted when it completed. The size reduction comes
1669 /// from the two persisted message counts or it stays unknown — a compaction
1670 /// with no counts must never average in as a 0% reduction.
1671 fn record_compaction_item_receipt(event: &str, v: &Value, rollup: &mut Rollup) {
1672 if event != "item.completed" {
1673 return;
1674 }
1675 if let Some(id) = compaction_receipt_identity(v, true)
1676 && !rollup.compaction.receipt_ids.insert(id)
1677 {
1678 return;
1679 }
1680 rollup.compaction.events += 1;
1681 let before = v
1682 .pointer("/payload/messages_before")
1683 .and_then(Value::as_u64);
1684 let after = v.pointer("/payload/messages_after").and_then(Value::as_u64);
1685 let (Some(before), Some(after)) = (before, after) else {
1686 return;
1687 };
1688 if before == 0 {
1689 return;
1690 }
1691 rollup.compaction.ratio_sum += 1.0 - (after as f64 / before as f64);
1692 rollup.compaction.ratio_samples += 1;
1693 }
1694
1695 /// Exact interval between two persisted item timestamps, or `None`.
1696 ///
1697 /// Both fields are optional on the record, and a reversed pair is not a
1698 /// measurement. Neither case may contribute a 0 ms sample, and neither is
1699 /// evidence about a provider charge.
1700 fn item_elapsed_ms(item: &Value) -> Option<u64> {
1701 let started = parse_ts_field(item, "started_at")?;
1702 let ended = parse_ts_field(item, "ended_at")?;
1703 u64::try_from((ended - started).num_milliseconds()).ok()
1704 }
1705
1706 fn record_provider_usage_receipt(v: &Value, rollup: &mut Rollup, dedup: &mut RuntimeEventDedup) {
1707 let Some(identity) = runtime_event_identity(v) else {
1708 rollup
1709 .runtime_requests
1710 .provider_usage_receipts_without_identity = rollup
1711 .runtime_requests
1712 .provider_usage_receipts_without_identity
1713 .saturating_add(1);
1714 return;
1715 };
1716 if !dedup.event_records.insert(identity) {
1717 rollup
1718 .runtime_requests
1719 .duplicate_provider_usage_receipts_skipped = rollup
1720 .runtime_requests
1721 .duplicate_provider_usage_receipts_skipped
1722 .saturating_add(1);
1723 return;
1724 }
1725
1726 let stats = &mut rollup.runtime_requests;
1727 let Some(input_tokens) = v
1728 .pointer("/payload/usage/input_tokens")
1729 .and_then(Value::as_u64)
1730 else {
1731 stats.provider_usage_receipts_incomplete =
1732 stats.provider_usage_receipts_incomplete.saturating_add(1);
1733 return;
1734 };
1735 let Some(output_tokens) = v
1736 .pointer("/payload/usage/output_tokens")
1737 .and_then(Value::as_u64)
1738 else {
1739 stats.provider_usage_receipts_incomplete =
1740 stats.provider_usage_receipts_incomplete.saturating_add(1);
1741 return;
1742 };
1743 stats.provider_usage_receipts = stats.provider_usage_receipts.saturating_add(1);
1744 stats.provider_reported_input_tokens = stats
1745 .provider_reported_input_tokens
1746 .saturating_add(input_tokens);
1747 stats.provider_reported_output_tokens = stats
1748 .provider_reported_output_tokens
1749 .saturating_add(output_tokens);
1750 }
1751
1752 // ──────────────────────────────────────────────────────────────────────────────
1753 // Output formatters
1754 // ──────────────────────────────────────────────────────────────────────────────
1755
1756 fn print_json(rollup: &Rollup) -> Result<()> {
1757 println!("{}", serde_json::to_string_pretty(rollup)?);
1758 Ok(())
1759 }
1760
1761 fn legacy_partial_report_warning(rollup: &Rollup) -> Option<String> {
1762 if rollup.receipt_inspection_exhausted {
1763 let detail = if rollup.receipt_read_gaps > 0 {
1764 let gap_word = if rollup.receipt_read_gaps == 1 {
1765 "gap"
1766 } else {
1767 "gaps"
1768 };
1769 format!(" ({} read {gap_word})", fmt_num(rollup.receipt_read_gaps))
1770 } else {
1771 String::new()
1772 };
1773 Some(format!(
1774 "Warning: partial legacy receipt report — inspection reached the 16 MiB cap{detail}; remaining receipts were skipped (narrow --days or --since)."
1775 ))
1776 } else if rollup.receipt_read_gaps > 0 {
1777 let gap_word = if rollup.receipt_read_gaps == 1 {
1778 "gap"
1779 } else {
1780 "gaps"
1781 };
1782 Some(format!(
1783 "Warning: partial legacy receipt report — {} receipt read {gap_word}; some receipts could not be read or parsed.",
1784 fmt_num(rollup.receipt_read_gaps)
1785 ))
1786 } else {
1787 None
1788 }
1789 }
1790
1791 fn print_human(rollup: &Rollup, since: Option<DateTime<Utc>>) {
1792 if let Some(warning) = legacy_partial_report_warning(rollup) {
1793 println!("{warning}");
1794 }
1795 // Period header. When a --since cutoff yields nothing, print it: a bare
1796 // `--since 7` is seven seconds, and the empty window must not read the
1797 // same as a genuinely idle period (#6315).
1798 match (rollup.earliest_ts, rollup.latest_ts) {
1799 (Some(start), Some(end)) => {
1800 let days = (end - start).num_days();
1801 println!(
1802 "Period: {} → {} ({} days)",
1803 start.format("%Y-%m-%d"),
1804 end.format("%Y-%m-%d"),
1805 days
1806 );
1807 }
1808 (Some(start), None) | (None, Some(start)) => {
1809 println!("Period: {} → (unknown)", start.format("%Y-%m-%d"));
1810 }
1811 (None, None) => match since {
1812 Some(cutoff) => println!(
1813 "Period: (no data since {})",
1814 cutoff.format("%Y-%m-%d %H:%M UTC")
1815 ),
1816 None => println!("Period: (no data)"),
1817 },
1818 }
1819
1820 // ── Tools ──────────────────────────────────────────────────────────────
1821 let total_calls = rollup.total_tool_calls();
1822 if total_calls > 0 {
1823 // Overall success rate from session-file data (where we have result info).
1824 let total_ok: u64 = rollup.tools.values().map(|t| t.successes).sum();
1825 let total_judged: u64 = rollup
1826 .tools
1827 .values()
1828 .map(|t| t.successes + t.failures)
1829 .sum();
1830 let mut overall_rate = if total_judged > 0 {
1831 format!(
1832 "{:.1}% success",
1833 total_ok as f64 / total_judged as f64 * 100.0
1834 )
1835 } else {
1836 // Only approval events — show prompt breakdown.
1837 let auto: u64 = rollup.tools.values().map(|t| t.auto_approved).sum();
1838 let prompted: u64 = rollup.tools.values().map(|t| t.prompted).sum();
1839 format!("{auto} auto-approved, {prompted} prompted")
1840 };
1841 // Denied and outcome-unknown calls are excluded from the rate above by
1842 // construction, so they are named rather than silently dropped.
1843 let total_denied: u64 = rollup.tools.values().map(|t| t.denied).sum();
1844 if total_denied > 0 {
1845 overall_rate.push_str(&format!(", {} denied", fmt_num(total_denied)));
1846 }
1847 let total_unknown: u64 = rollup.tools.values().map(|t| t.outcome_unknown).sum();
1848 if total_unknown > 0 {
1849 overall_rate.push_str(&format!(", {} outcome unknown", fmt_num(total_unknown)));
1850 }
1851
1852 println!(
1853 "Tools: {:>6} calls ({})",
1854 fmt_num(total_calls),
1855 overall_rate
1856 );
1857
1858 // Sort tools by call count descending, top 15.
1859 let mut tools: Vec<(&String, &ToolStats)> = rollup.tools.iter().collect();
1860 tools.sort_by_key(|b| std::cmp::Reverse(b.1.calls));
1861 for (name, stats) in tools.iter().take(15) {
1862 let rate_str = match stats.success_rate_pct() {
1863 Some(pct) => format!("{pct:5.1}%"),
1864 None if stats.denied > 0 => {
1865 // Nothing ran, so an approval breakdown would read as if
1866 // it had.
1867 format!("{} denied", fmt_num(stats.denied))
1868 }
1869 None if stats.outcome_unknown > 0 => {
1870 format!("{} unknown", fmt_num(stats.outcome_unknown))
1871 }
1872 None => {
1873 // Only approval data available — show auto/prompted breakdown.
1874 let a = stats.auto_approved;
1875 let p = stats.prompted;
1876 if p == 0 {
1877 format!("auto×{a} ")
1878 } else {
1879 format!("auto×{a}/prompted×{p}")
1880 }
1881 }
1882 };
1883 let avg_str = match stats.avg_elapsed_ms() {
1884 Some(ms) => format!(" avg {ms}ms"),
1885 None => String::new(),
1886 };
1887 println!(
1888 " {name:<22} {:>6} {rate_str}{avg_str}",
1889 fmt_num(stats.calls)
1890 );
1891 }
1892 if tools.len() > 15 {
1893 println!(" … and {} more tools", tools.len() - 15);
1894 }
1895 } else {
1896 println!("Tools: (no data)");
1897 }
1898
1899 // ── Compaction ─────────────────────────────────────────────────────────
1900 let compaction_refusals: u64 = rollup.compaction.refusals.values().sum();
1901 if rollup.compaction.events > 0 || compaction_refusals > 0 {
1902 let avg_str = match rollup.compaction.avg_reduction_pct() {
1903 Some(pct) => format!(", avg {pct:.0}% size reduction"),
1904 // No message counts were recorded. Saying nothing here reads as
1905 // "no reduction"; say that it is unknown.
1906 None => ", size reduction unknown".to_string(),
1907 };
1908 let usage = if rollup.compaction.summarizer_usage_samples > 0 {
1909 format!(
1910 "{} input / {} output tokens across {} measured passes",
1911 fmt_num(rollup.compaction.summarizer_input_tokens),
1912 fmt_num(rollup.compaction.summarizer_output_tokens),
1913 fmt_num(rollup.compaction.summarizer_usage_samples)
1914 )
1915 } else {
1916 "usage unavailable".to_string()
1917 };
1918 println!(
1919 "Compaction: {} completed, {} refused{}; summarizer {}",
1920 fmt_num(rollup.compaction.events),
1921 fmt_num(compaction_refusals),
1922 avg_str,
1923 usage
1924 );
1925 } else {
1926 println!("Compaction: (no data)");
1927 }
1928
1929 // ── Sub-agents ─────────────────────────────────────────────────────────
1930 println!("{}", rollup.agents.summary());
1931
1932 // ── Capacity interventions ─────────────────────────────────────────────
1933 if rollup.capacity.total > 0 {
1934 let cat_str: String = {
1935 let mut cats: Vec<(&String, &u64)> = rollup.capacity.by_category.iter().collect();
1936 cats.sort_by(|a, b| b.1.cmp(a.1));
1937 cats.iter()
1938 .map(|(k, v)| format!("{v} {k}"))
1939 .collect::<Vec<_>>()
1940 .join(", ")
1941 };
1942 println!(
1943 "Capacity interventions: {} ({})",
1944 fmt_num(rollup.capacity.total),
1945 cat_str
1946 );
1947 } else {
1948 println!("Capacity interventions: (no data)");
1949 }
1950
1951 // ── Runtime request and provider-usage receipts ───────────────────────
1952 let runtime = &rollup.runtime_requests;
1953 if runtime.terminal_turn_receipts == 0 {
1954 println!("Runtime requests: (no terminal receipts; model-client counts unknown)");
1955 } else if runtime.diagnostics_turn_receipts == 0 {
1956 println!(
1957 "Runtime requests: (diagnostics unavailable for all {} terminal receipts)",
1958 fmt_num(runtime.terminal_turn_receipts)
1959 );
1960 } else {
1961 println!(
1962 "Runtime requests: {} model-client calls, {} stream resumes, {} transparent retries (diagnostics for {}/{} terminal receipts; status events excluded)",
1963 fmt_num(runtime.model_requests_started),
1964 fmt_num(runtime.stream_resumes),
1965 fmt_num(runtime.transparent_stream_retries),
1966 fmt_num(runtime.diagnostics_turn_receipts),
1967 fmt_num(runtime.terminal_turn_receipts),
1968 );
1969 }
1970 if runtime.provider_usage_receipts == 0 {
1971 println!(
1972 "Provider usage receipts (Runtime events): (none recorded; this is not zero usage)"
1973 );
1974 } else {
1975 println!(
1976 "Provider usage receipts (Runtime events): {} records, {} input tokens, {} output tokens",
1977 fmt_num(runtime.provider_usage_receipts),
1978 fmt_num(runtime.provider_reported_input_tokens),
1979 fmt_num(runtime.provider_reported_output_tokens),
1980 );
1981 }
1982 let session_usage = &rollup.session_usage;
1983 if session_usage.usage_receipts == 0 {
1984 println!(
1985 "Provider usage receipts (saved terminal sessions): (none recorded; this is not zero usage)"
1986 );
1987 } else {
1988 println!(
1989 "Provider usage receipts (saved terminal sessions): {} records in {} sessions, {} input tokens, {} output tokens",
1990 fmt_num(session_usage.usage_receipts),
1991 fmt_num(session_usage.sessions),
1992 fmt_num(session_usage.provider_reported_input_tokens),
1993 fmt_num(session_usage.provider_reported_output_tokens),
1994 );
1995 }
1996 if session_usage.sessions_with_total_tokens_only > 0 {
1997 println!(
1998 "Saved sessions with a combined token total only: {} sessions, {} tokens (no per-call usage receipts saved)",
1999 fmt_num(session_usage.sessions_with_total_tokens_only),
2000 fmt_num(session_usage.total_tokens_only),
2001 );
2002 }
2003 if session_usage.usage_receipts_incomplete > 0 {
2004 println!(
2005 "Saved-session usage coverage: {} usage receipts incomplete, not counted as zero",
2006 fmt_num(session_usage.usage_receipts_incomplete),
2007 );
2008 }
2009 if runtime.diagnostics_unavailable_turn_receipts > 0
2010 || runtime.diagnostics_incomplete_turn_receipts > 0
2011 || runtime.terminal_receipts_without_identity > 0
2012 || runtime.provider_usage_receipts_without_identity > 0
2013 || runtime.provider_usage_receipts_incomplete > 0
2014 || runtime.duplicate_terminal_receipts_skipped > 0
2015 || runtime.duplicate_provider_usage_receipts_skipped > 0
2016 {
2017 println!(
2018 "Runtime receipt coverage: {} diagnostics unavailable, {} diagnostics incomplete, {} terminal receipts without identity, {} usage receipts without identity, {} usage receipts incomplete, {} duplicate terminal receipts skipped, {} duplicate usage receipts skipped",
2019 fmt_num(runtime.diagnostics_unavailable_turn_receipts),
2020 fmt_num(runtime.diagnostics_incomplete_turn_receipts),
2021 fmt_num(runtime.terminal_receipts_without_identity),
2022 fmt_num(runtime.provider_usage_receipts_without_identity),
2023 fmt_num(runtime.provider_usage_receipts_incomplete),
2024 fmt_num(runtime.duplicate_terminal_receipts_skipped),
2025 fmt_num(runtime.duplicate_provider_usage_receipts_skipped),
2026 );
2027 }
2028
2029 // ── Credentials ────────────────────────────────────────────────────────
2030 if rollup.credentials.saves > 0 || rollup.credentials.clears > 0 {
2031 println!(
2032 "Credentials: {} saves, {} clears",
2033 rollup.credentials.saves, rollup.credentials.clears
2034 );
2035 }
2036 }
2037
2038 // ──────────────────────────────────────────────────────────────────────────────
2039 // Helpers
2040 // ──────────────────────────────────────────────────────────────────────────────
2041
2042 /// An explicit home is an isolation boundary. Default installs can have
2043 /// distinct audit histories in both roots, even after a copied migration.
2044 fn resolve_audit_roots() -> Result<Vec<PathBuf>> {
2045 let primary = codewhale_config::codewhale_home()?;
2046 let mut roots = vec![primary];
2047 if !codewhale_config::codewhale_home_is_explicit() {
2048 let legacy = codewhale_config::legacy_deepseek_home()?;
2049 if !roots.contains(&legacy) {
2050 roots.push(legacy);
2051 }
2052 }
2053 Ok(roots)
2054 }
2055
2056 /// Resolve the tool a durable audit record is about.
2057 ///
2058 /// `~/.codewhale/audit.log` nests its payload under `details`; the opt-in
2059 /// `CODEWHALE_TOOL_AUDIT_LOG` file writes `tool_name` at the top level.
2060 fn audit_tool_name(v: &Value) -> &str {
2061 v.pointer("/details/tool_name")
2062 .or_else(|| v.pointer("/payload/tool_name"))
2063 .or_else(|| v.get("tool_name"))
2064 .and_then(Value::as_str)
2065 .unwrap_or("unknown")
2066 }
2067
2068 /// Parse a timestamp from a JSON value field (tries RFC3339).
2069 fn parse_ts_field(v: &Value, field: &str) -> Option<DateTime<Utc>> {
2070 v.get(field)?.as_str()?.parse::<DateTime<Utc>>().ok()
2071 }
2072
2073 /// Format a number with thousands separators.
2074 fn fmt_num(n: u64) -> String {
2075 let s = n.to_string();
2076 let mut result = String::with_capacity(s.len() + s.len() / 3);
2077 for (i, ch) in s.chars().rev().enumerate() {
2078 if i > 0 && i % 3 == 0 {
2079 result.push(',');
2080 }
2081 result.push(ch);
2082 }
2083 result.chars().rev().collect()
2084 }
2085
2086 // ──────────────────────────────────────────────────────────────────────────────
2087 // Tests
2088 // ──────────────────────────────────────────────────────────────────────────────
2089
2090 #[cfg(test)]
2091 mod tests {
2092 use super::*;
2093
2094 #[test]
2095 fn compaction_audit_counts_usage_refusals_and_deduplicates_runtime_receipt() {
2096 let tmp = tempfile::NamedTempFile::new().unwrap();
2097 let completed = serde_json::json!({"ts": "2026-09-19T12:00:00Z", "event": "compaction.completed", "details": {
2098 "session_id": "engine-session-a", "thread_id": "thread-a", "compaction_id": "pass-a", "trigger": "manual", "path": "summary",
2099 "reduction_ratio": 0.75, "summarizer_usage": {"input_tokens": 120, "output_tokens": 15}
2100 }});
2101 let refused = serde_json::json!({"ts": "2026-09-19T12:01:00Z", "event": "compaction.refused", "details": {"reason": "retained_floor"}});
2102 std::fs::write(tmp.path(), format!("{completed}\n{completed}\n{refused}\n")).unwrap();
2103 let mut rollup = Rollup::default();
2104 read_audit_test_log(tmp.path(), None, &mut rollup);
2105 record_compaction_item_receipt(
2106 "item.completed",
2107 &serde_json::json!({
2108 "thread_id": "thread-a", "payload": {"item": {"metadata": {"compaction_id": "pass-a"}}, "messages_before": 4, "messages_after": 1}
2109 }),
2110 &mut rollup,
2111 );
2112 assert_eq!(rollup.compaction.events, 1);
2113 assert_eq!(rollup.compaction.ratio_samples, 1);
2114 assert_eq!(rollup.compaction.avg_reduction_pct(), Some(75.0));
2115 assert_eq!(rollup.compaction.refusals["retained_floor"], 1);
2116 assert_eq!(rollup.compaction.triggers["manual"], 1);
2117 assert_eq!(rollup.compaction.paths["summary"], 1);
2118 assert_eq!(rollup.compaction.summarizer_input_tokens, 120);
2119 assert_eq!(rollup.compaction.summarizer_output_tokens, 15);
2120 }
2121
2122 fn read_audit_test_log(path: &Path, since: Option<DateTime<Utc>>, rollup: &mut Rollup) {
2123 super::read_audit_log(path, since, rollup, &HashMap::new(), &mut HashMap::new());
2124 }
2125
2126 fn read_runtime_test_log(path: &Path, since: Option<DateTime<Utc>>, rollup: &mut Rollup) {
2127 super::read_events_jsonl(path, since, rollup, &mut RuntimeEventDedup::default());
2128 }
2129
2130 fn runtime_event(
2131 seq: u64,
2132 timestamp: &str,
2133 thread_id: &str,
2134 turn_id: Option<&str>,
2135 event: &str,
2136 payload: Value,
2137 ) -> Value {
2138 serde_json::json!({
2139 "schema_version": 4,
2140 "seq": seq,
2141 "timestamp": timestamp,
2142 "thread_id": thread_id,
2143 "turn_id": turn_id,
2144 "event": event,
2145 "payload": payload,
2146 })
2147 }
2148
2149 fn write_runtime_events(events: &[Value]) -> tempfile::NamedTempFile {
2150 use std::io::Write;
2151
2152 let mut tmp = tempfile::NamedTempFile::new().unwrap();
2153 for event in events {
2154 writeln!(tmp, "{event}").unwrap();
2155 }
2156 tmp
2157 }
2158
2159 #[test]
2160 fn runtime_worker_completion_uses_owner_outcome_not_completed_receipt_status() {
2161 let statuses = [
2162 serde_json::json!("completed"),
2163 serde_json::json!("failed"),
2164 serde_json::json!("cancelled"),
2165 serde_json::json!("interrupted"),
2166 serde_json::json!("budget_exhausted"),
2167 Value::Null,
2168 ];
2169 let events: Vec<_> = statuses
2170 .into_iter()
2171 .enumerate()
2172 .map(|(seq, worker_status)| {
2173 runtime_event(
2174 seq as u64,
2175 "2026-09-08T10:00:00Z",
2176 "thread-a",
2177 Some("turn-a"),
2178 "agent.completed",
2179 serde_json::json!({
2180 "item": { "kind": "status", "status": "completed" },
2181 "agent_id": format!("worker-{seq}"),
2182 "worker_status": worker_status,
2183 "parent_run_id": "run-a",
2184 "spawn_depth": 1,
2185 "continuable": false,
2186 }),
2187 )
2188 })
2189 .collect();
2190 let tmp = write_runtime_events(&events);
2191 let mut rollup = Rollup::default();
2192 read_runtime_test_log(tmp.path(), None, &mut rollup);
2193 let agents = &rollup.agents;
2194 assert_eq!(agents.successes, 1, "a settled item is not worker success");
2195 assert_eq!(agents.failures, 1);
2196 assert_eq!(agents.cancelled, 1);
2197 assert_eq!(agents.interrupted, 1);
2198 assert_eq!(agents.budget_exhausted, 1);
2199 assert_eq!(agents.unknown_outcomes, 1);
2200 assert_eq!(agents.spawns, 0);
2201 let summary = agents.summary();
2202 assert!(summary.contains("1 failed"));
2203 assert!(summary.contains("1 outcome unconfirmed"));
2204 assert!(
2205 !summary.contains("no data"),
2206 "terminal-only windows have data"
2207 );
2208 assert!(
2209 !summary.contains("%"),
2210 "partial receipts are not a success rate"
2211 );
2212 }
2213
2214 #[test]
2215 fn runtime_worker_usage_sums_tokens_across_completion_receipts() {
2216 // #6315: completions with usage receipts sum into the rollup; a
2217 // completion without usage is a missing receipt, never zero tokens.
2218 let events = vec![
2219 runtime_event(
2220 0,
2221 "2026-09-08T10:00:00Z",
2222 "thread-a",
2223 Some("turn-a"),
2224 "agent.completed",
2225 serde_json::json!({
2226 "agent_id": "worker-0",
2227 "worker_status": "completed",
2228 "usage": {
2229 "status": "completed",
2230 "input_tokens": 800,
2231 "output_tokens": 200,
2232 "total_tokens": 1000,
2233 "cost_microusd": 50,
2234 },
2235 }),
2236 ),
2237 runtime_event(
2238 1,
2239 "2026-09-08T10:01:00Z",
2240 "thread-a",
2241 Some("turn-a"),
2242 "agent.completed",
2243 serde_json::json!({
2244 "agent_id": "worker-1",
2245 "worker_status": "completed",
2246 }),
2247 ),
2248 ];
2249 let tmp = write_runtime_events(&events);
2250 let mut rollup = Rollup::default();
2251 read_runtime_test_log(tmp.path(), None, &mut rollup);
2252 let agents = &rollup.agents;
2253 assert_eq!(agents.successes, 2);
2254 assert_eq!(agents.usage_receipts, 1);
2255 assert_eq!(agents.input_tokens, 800);
2256 assert_eq!(agents.output_tokens, 200);
2257 assert_eq!(agents.total_tokens, 1000);
2258 assert_eq!(agents.cost_microusd, 50);
2259 let summary = agents.summary();
2260 assert!(summary.contains("800 in/200 out/1,000 total (1 receipt)"));
2261 }
2262
2263 #[test]
2264 fn runtime_legacy_worker_receipts_require_explicit_success_evidence() {
2265 let payloads = [
2266 serde_json::json!({ "success": true }),
2267 serde_json::json!({ "success": false }),
2268 serde_json::json!({}),
2269 serde_json::json!({ "success": "true" }),
2270 serde_json::json!({ "worker_status": "failed", "success": true }),
2271 serde_json::json!({ "worker_status": null, "success": true }),
2272 serde_json::json!({ "worker_status": "running", "success": true }),
2273 serde_json::json!({ "worker_status": { "completed": true }, "success": true }),
2274 serde_json::json!({ "worker_status": "future_outcome", "success": true }),
2275 ];
2276 let events: Vec<_> = payloads
2277 .into_iter()
2278 .enumerate()
2279 .map(|(seq, payload)| {
2280 runtime_event(
2281 seq as u64,
2282 "2026-09-08T10:00:00Z",
2283 "thread-a",
2284 Some("turn-a"),
2285 "agent.completed",
2286 payload,
2287 )
2288 })
2289 .collect();
2290 let tmp = write_runtime_events(&events);
2291 let mut rollup = Rollup::default();
2292 read_runtime_test_log(tmp.path(), None, &mut rollup);
2293 assert_eq!(rollup.agents.successes, 1);
2294 assert_eq!(rollup.agents.failures, 2);
2295 assert_eq!(rollup.agents.unknown_outcomes, 6);
2296 }
2297
2298 #[test]
2299 fn audit_worker_receipts_share_typed_and_legacy_outcome_rules() {
2300 let events = [
2301 serde_json::json!({ "event": "agent.completed", "details": { "worker_status": "failed", "success": true } }),
2302 serde_json::json!({ "event": "subagent.completed", "payload": { "status": "cancelled", "success": true } }),
2303 serde_json::json!({ "event": "subagent.completed", "details": { "status": "completed" } }),
2304 serde_json::json!({ "event": "agent.completed", "details": { "success": false } }),
2305 serde_json::json!({ "event": "agent.completed", "payload": { "success": true } }),
2306 serde_json::json!({ "event": "agent.completed", "details": { "worker_status": null, "success": true } }),
2307 serde_json::json!({ "event": "agent.completed", "details": {} }),
2308 ];
2309 let tmp = write_runtime_events(&events);
2310 let mut rollup = Rollup::default();
2311 read_audit_test_log(tmp.path(), None, &mut rollup);
2312 assert_eq!(rollup.agents.successes, 2);
2313 assert_eq!(rollup.agents.failures, 2);
2314 assert_eq!(rollup.agents.cancelled, 1);
2315 assert_eq!(rollup.agents.unknown_outcomes, 2);
2316 let json = serde_json::to_value(&rollup).unwrap();
2317 assert_eq!(json["agents"]["unknown_outcomes"], 2);
2318 assert_eq!(json["agents"]["cancelled"], 1);
2319 }
2320
2321 // ── Duration parser ──
2322
2323 #[test]
2324 fn parse_since_7d() {
2325 let cutoff = parse_since("7d").unwrap();
2326 let expected = Utc::now() - Duration::days(7);
2327 // Allow ±2s for test execution time.
2328 assert!((cutoff - expected).num_seconds().abs() < 2);
2329 }
2330
2331 #[test]
2332 fn parse_since_24h() {
2333 let cutoff = parse_since("24h").unwrap();
2334 let expected = Utc::now() - Duration::hours(24);
2335 assert!((cutoff - expected).num_seconds().abs() < 2);
2336 }
2337
2338 #[test]
2339 fn parse_since_30m() {
2340 let cutoff = parse_since("30m").unwrap();
2341 let expected = Utc::now() - Duration::minutes(30);
2342 assert!((cutoff - expected).num_seconds().abs() < 2);
2343 }
2344
2345 #[test]
2346 fn parse_since_now_prefix() {
2347 // "now-2h" should strip "now-" and parse "2h".
2348 let cutoff = parse_since("now-2h").unwrap();
2349 let expected = Utc::now() - Duration::hours(2);
2350 assert!((cutoff - expected).num_seconds().abs() < 2);
2351 }
2352
2353 #[test]
2354 fn parse_since_compound() {
2355 let cutoff = parse_since("2h30m").unwrap();
2356 let expected = Utc::now() - Duration::seconds(2 * 3600 + 30 * 60);
2357 assert!((cutoff - expected).num_seconds().abs() < 2);
2358 }
2359
2360 #[test]
2361 fn parse_since_compound_days_hours() {
2362 let cutoff = parse_since("1d12h").unwrap();
2363 let expected = Utc::now() - Duration::seconds(36 * 3600);
2364 assert!((cutoff - expected).num_seconds().abs() < 2);
2365 }
2366
2367 #[test]
2368 fn parse_since_error_on_invalid() {
2369 assert!(parse_since("xyz").is_err());
2370 assert!(parse_since("").is_err());
2371 }
2372
2373 #[test]
2374 fn parse_since_rejects_bare_unit() {
2375 let err = parse_since("d").unwrap_err().to_string();
2376 assert!(err.contains("no number"), "{err}");
2377 }
2378
2379 #[test]
2380 fn parse_since_rejects_overflow_without_panicking() {
2381 // n * factor overflows i64.
2382 let err = parse_since("106751991167301d").unwrap_err().to_string();
2383 assert!(err.contains("too large"), "{err}");
2384 // Sum of components overflows i64.
2385 assert!(parse_since("9223372036854775807s1s").is_err());
2386 // Fits in i64 seconds but exceeds TimeDelta's range.
2387 assert!(parse_since("9223372036854775807").is_err());
2388 // Valid TimeDelta, but before the earliest representable DateTime.
2389 assert!(parse_since("100000000000d").is_err());
2390 // Component too large to parse as i64.
2391 assert!(parse_since("99999999999999999999h").is_err());
2392 }
2393
2394 // ── fmt_num ──
2395
2396 #[test]
2397 fn fmt_num_zero() {
2398 assert_eq!(fmt_num(0), "0");
2399 }
2400
2401 #[test]
2402 fn fmt_num_thousands() {
2403 assert_eq!(fmt_num(1_000), "1,000");
2404 assert_eq!(fmt_num(12_453), "12,453");
2405 assert_eq!(fmt_num(1_000_000), "1,000,000");
2406 }
2407
2408 // ── Rollup from audit log ──
2409
2410 fn make_audit_line(event: &str, tool: &str, ts: &str) -> String {
2411 format!(
2412 r#"{{"details":{{"mode":"YOLO","session_id":null,"tool_name":"{tool}"}},"event":"{event}","ts":"{ts}"}}"#
2413 )
2414 }
2415
2416 #[test]
2417 fn audit_log_empty_file() {
2418 let mut rollup = Rollup::default();
2419 // Non-existent path — should not panic, rollup stays empty.
2420 read_audit_test_log(Path::new("/nonexistent/audit.log"), None, &mut rollup);
2421 assert_eq!(rollup.total_lines, 0);
2422 }
2423
2424 #[test]
2425 fn audit_log_parses_auto_approve() {
2426 use std::io::Write;
2427 let mut tmp = tempfile::NamedTempFile::new().unwrap();
2428 let line1 = make_audit_line(
2429 "tool.approval.auto_approve",
2430 "exec_shell",
2431 "2026-04-01T10:00:00+00:00",
2432 );
2433 let line2 = make_audit_line(
2434 "tool.approval.auto_approve",
2435 "read_file",
2436 "2026-04-02T10:00:00+00:00",
2437 );
2438 writeln!(tmp, "{line1}").unwrap();
2439 writeln!(tmp, "{line2}").unwrap();
2440
2441 let mut rollup = Rollup::default();
2442 read_audit_test_log(tmp.path(), None, &mut rollup);
2443
2444 assert_eq!(rollup.parsed_lines, 2);
2445 assert_eq!(rollup.tools["exec_shell"].calls, 1);
2446 assert_eq!(rollup.tools["exec_shell"].auto_approved, 1);
2447 assert_eq!(rollup.tools["read_file"].calls, 1);
2448 }
2449
2450 #[test]
2451 fn audit_log_skips_malformed_lines() {
2452 use std::io::Write;
2453 let mut tmp = tempfile::NamedTempFile::new().unwrap();
2454 writeln!(tmp, "not json at all").unwrap();
2455 writeln!(
2456 tmp,
2457 r#"{{"event":"credential.save","ts":"2026-04-01T10:00:00+00:00"}}"#
2458 )
2459 .unwrap();
2460
2461 let mut rollup = Rollup::default();
2462 read_audit_test_log(tmp.path(), None, &mut rollup);
2463
2464 // 2 lines total, 1 malformed skipped, 1 parsed.
2465 assert_eq!(rollup.total_lines, 2);
2466 assert_eq!(rollup.parsed_lines, 1);
2467 assert_eq!(rollup.credentials.saves, 1);
2468 }
2469
2470 #[test]
2471 fn audit_log_since_filter() {
2472 use std::io::Write;
2473 let mut tmp = tempfile::NamedTempFile::new().unwrap();
2474 let line_old = make_audit_line(
2475 "tool.approval.auto_approve",
2476 "exec_shell",
2477 "2025-01-01T00:00:00+00:00",
2478 );
2479 let line_new = make_audit_line(
2480 "tool.approval.auto_approve",
2481 "read_file",
2482 "2026-04-01T00:00:00+00:00",
2483 );
2484 writeln!(tmp, "{line_old}").unwrap();
2485 writeln!(tmp, "{line_new}").unwrap();
2486
2487 let cutoff: DateTime<Utc> = "2026-01-01T00:00:00Z".parse().unwrap();
2488 let mut rollup = Rollup::default();
2489 read_audit_test_log(tmp.path(), Some(cutoff), &mut rollup);
2490
2491 // Only the newer line should be counted.
2492 assert_eq!(rollup.parsed_lines, 1);
2493 assert!(!rollup.tools.contains_key("exec_shell"));
2494 assert_eq!(rollup.tools["read_file"].calls, 1);
2495 }
2496
2497 #[test]
2498 fn total_tool_calls_sums_across_tools() {
2499 let mut rollup = Rollup::default();
2500 rollup.tool_mut("read_file").calls = 4_012;
2501 rollup.tool_mut("exec_shell").calls = 1_118;
2502 assert_eq!(rollup.total_tool_calls(), 5_130);
2503 }
2504
2505 // ── Runtime request and provider-usage receipts ──
2506
2507 #[test]
2508 fn runtime_receipts_separate_terminal_requests_from_per_request_usage() {
2509 let timestamp = "2026-09-08T10:00:00Z";
2510 let terminal = runtime_event(
2511 2,
2512 timestamp,
2513 "thread-a",
2514 Some("turn-a"),
2515 "turn.completed",
2516 serde_json::json!({
2517 "turn": {
2518 "usage": { "input_tokens": 10_000, "output_tokens": 9_000 },
2519 "modelRequestDiagnostics": {
2520 "modelRequestsStarted": 2,
2521 "transparentStreamRetries": 1,
2522 "streamResumes": 1,
2523 },
2524 },
2525 }),
2526 );
2527 let usage_one = runtime_event(
2528 3,
2529 timestamp,
2530 "thread-a",
2531 Some("turn-a"),
2532 "turn.usage",
2533 serde_json::json!({ "usage": { "input_tokens": 7, "output_tokens": 2 } }),
2534 );
2535 let usage_two = runtime_event(
2536 4,
2537 timestamp,
2538 "thread-a",
2539 Some("turn-a"),
2540 "turn.usage",
2541 serde_json::json!({ "usage": { "input_tokens": 11, "output_tokens": 3 } }),
2542 );
2543 let duplicate_terminal = runtime_event(
2544 5,
2545 timestamp,
2546 "thread-a",
2547 Some("turn-a"),
2548 "turn.completed",
2549 serde_json::json!({
2550 "turn": {
2551 "modelRequestDiagnostics": {
2552 "modelRequestsStarted": 99,
2553 "transparentStreamRetries": 99,
2554 "streamResumes": 99,
2555 },
2556 },
2557 }),
2558 );
2559 let legacy_terminal = runtime_event(
2560 6,
2561 timestamp,
2562 "thread-a",
2563 Some("turn-b"),
2564 "turn.completed",
2565 serde_json::json!({ "turn": { "usage": { "input_tokens": 50, "output_tokens": 5 } } }),
2566 );
2567 let status = runtime_event(
2568 7,
2569 timestamp,
2570 "thread-a",
2571 Some("turn-a"),
2572 "item.completed",
2573 serde_json::json!({ "item": { "kind": "status" } }),
2574 );
2575 let tmp = write_runtime_events(&[
2576 terminal,
2577 usage_one,
2578 usage_two,
2579 duplicate_terminal,
2580 legacy_terminal,
2581 status,
2582 ]);
2583 let mut rollup = Rollup::default();
2584 read_runtime_test_log(tmp.path(), None, &mut rollup);
2585
2586 let runtime = &rollup.runtime_requests;
2587 assert_eq!(runtime.terminal_turn_receipts, 2);
2588 assert_eq!(runtime.diagnostics_turn_receipts, 1);
2589 assert_eq!(runtime.diagnostics_unavailable_turn_receipts, 1);
2590 assert_eq!(runtime.duplicate_terminal_receipts_skipped, 1);
2591 assert_eq!(runtime.model_requests_started, 2);
2592 assert_eq!(runtime.transparent_stream_retries, 1);
2593 assert_eq!(runtime.stream_resumes, 1);
2594 assert_eq!(runtime.provider_usage_receipts, 2);
2595 assert_eq!(runtime.provider_reported_input_tokens, 18);
2596 assert_eq!(runtime.provider_reported_output_tokens, 5);
2597 assert_ne!(runtime.provider_reported_input_tokens, 10_018);
2598 assert_eq!(runtime.model_requests_started, 2, "status is not a request");
2599 }
2600
2601 #[test]
2602 fn saved_terminal_session_usage_is_counted_apart_from_runtime_events() {
2603 let session = serde_json::json!({
2604 "metadata": { "cost": { "accounted_usage_sources": {
2605 "a": { "record": { "settlement": { "coverage": "reported" }, "usage": { "usage": { "input_tokens": 40, "output_tokens": 6 } } } },
2606 "b": { "record": { "settlement": { "coverage": "missing" }, "usage": { "usage": { "input_tokens": 0, "output_tokens": 0 } } } },
2607 "c": { "record": { "settlement": { "coverage": "incomplete" }, "usage": { "usage": { "input_tokens": 3 } } } }
2608 } } }
2609 });
2610 let mut rollup = Rollup::default();
2611 record_session_usage(&session, &mut rollup);
2612 let usage = &rollup.session_usage;
2613 assert_eq!(usage.usage_receipts, 1);
2614 assert_eq!(usage.usage_receipts_incomplete, 1);
2615 assert_eq!(usage.sessions, 1);
2616 assert_eq!(usage.provider_reported_input_tokens, 40);
2617 assert_eq!(usage.provider_reported_output_tokens, 6);
2618 record_session_usage(&serde_json::json!({ "metadata": {} }), &mut rollup);
2619 assert_eq!(rollup.session_usage.sessions, 1);
2620 record_session_usage(
2621 &serde_json::json!({ "metadata": { "total_tokens": 900 } }),
2622 &mut rollup,
2623 );
2624 assert_eq!(rollup.session_usage.sessions_with_total_tokens_only, 1);
2625 assert_eq!(rollup.session_usage.total_tokens_only, 900);
2626 }
2627
2628 #[test]
2629 fn runtime_usage_receipts_deduplicate_by_runtime_event_identity() {
2630 let usage = runtime_event(
2631 20,
2632 "2026-09-08T10:00:00Z",
2633 "thread-a",
2634 Some("turn-a"),
2635 "turn.usage",
2636 serde_json::json!({ "usage": { "input_tokens": 7, "output_tokens": 2 } }),
2637 );
2638 let tmp = write_runtime_events(&[usage.clone(), usage]);
2639 let mut rollup = Rollup::default();
2640 read_runtime_test_log(tmp.path(), None, &mut rollup);
2641
2642 let runtime = &rollup.runtime_requests;
2643 assert_eq!(runtime.provider_usage_receipts, 1);
2644 assert_eq!(runtime.provider_reported_input_tokens, 7);
2645 assert_eq!(runtime.provider_reported_output_tokens, 2);
2646 assert_eq!(runtime.duplicate_provider_usage_receipts_skipped, 1);
2647 }
2648
2649 #[test]
2650 fn runtime_receipt_coverage_marks_unidentified_or_incomplete_old_records_unknown() {
2651 let terminal_without_identity = serde_json::json!({
2652 "timestamp": "2026-09-08T10:00:00Z",
2653 "event": "turn.completed",
2654 "payload": {
2655 "turn": {
2656 "modelRequestDiagnostics": {
2657 "modelRequestsStarted": 3,
2658 "transparentStreamRetries": 1,
2659 "streamResumes": 2,
2660 },
2661 },
2662 },
2663 });
2664 let usage_without_identity = serde_json::json!({
2665 "timestamp": "2026-09-08T10:00:00Z",
2666 "event": "turn.usage",
2667 "payload": { "usage": { "input_tokens": 9, "output_tokens": 4 } },
2668 });
2669 let incomplete_diagnostics = runtime_event(
2670 30,
2671 "2026-09-08T10:00:00Z",
2672 "thread-a",
2673 Some("turn-b"),
2674 "turn.completed",
2675 serde_json::json!({
2676 "turn": { "modelRequestDiagnostics": { "modelRequestsStarted": 3 } },
2677 }),
2678 );
2679 let incomplete_usage = runtime_event(
2680 31,
2681 "2026-09-08T10:00:00Z",
2682 "thread-a",
2683 Some("turn-b"),
2684 "turn.usage",
2685 serde_json::json!({ "usage": { "input_tokens": 9 } }),
2686 );
2687 let tmp = write_runtime_events(&[
2688 terminal_without_identity,
2689 usage_without_identity,
2690 incomplete_diagnostics,
2691 incomplete_usage,
2692 ]);
2693 let mut rollup = Rollup::default();
2694 read_runtime_test_log(tmp.path(), None, &mut rollup);
2695
2696 let runtime = &rollup.runtime_requests;
2697 assert_eq!(runtime.terminal_receipts_without_identity, 1);
2698 assert_eq!(runtime.terminal_turn_receipts, 1);
2699 assert_eq!(runtime.diagnostics_incomplete_turn_receipts, 1);
2700 assert_eq!(runtime.model_requests_started, 0);
2701 assert_eq!(runtime.provider_usage_receipts_without_identity, 1);
2702 assert_eq!(runtime.provider_usage_receipts_incomplete, 1);
2703 assert_eq!(runtime.provider_usage_receipts, 0);
2704 assert_eq!(runtime.provider_reported_input_tokens, 0);
2705 }
2706
2707 #[test]
2708 fn runtime_receipts_respect_since_cutoff_without_crossing_snapshot_boundaries() {
2709 let old_terminal = runtime_event(
2710 40,
2711 "2026-09-01T10:00:00Z",
2712 "thread-a",
2713 Some("turn-old"),
2714 "turn.completed",
2715 serde_json::json!({
2716 "turn": { "modelRequestDiagnostics": {
2717 "modelRequestsStarted": 4,
2718 "transparentStreamRetries": 1,
2719 "streamResumes": 2,
2720 } },
2721 }),
2722 );
2723 let old_usage = runtime_event(
2724 41,
2725 "2026-09-01T10:00:00Z",
2726 "thread-a",
2727 Some("turn-old"),
2728 "turn.usage",
2729 serde_json::json!({ "usage": { "input_tokens": 40, "output_tokens": 4 } }),
2730 );
2731 let new_terminal = runtime_event(
2732 42,
2733 "2026-09-08T10:00:00Z",
2734 "thread-a",
2735 Some("turn-new"),
2736 "turn.completed",
2737 serde_json::json!({
2738 "turn": { "modelRequestDiagnostics": {
2739 "modelRequestsStarted": 1,
2740 "transparentStreamRetries": 0,
2741 "streamResumes": 0,
2742 } },
2743 }),
2744 );
2745 let new_usage = runtime_event(
2746 43,
2747 "2026-09-08T10:00:00Z",
2748 "thread-a",
2749 Some("turn-new"),
2750 "turn.usage",
2751 serde_json::json!({ "usage": { "input_tokens": 10, "output_tokens": 1 } }),
2752 );
2753 let tmp = write_runtime_events(&[old_terminal, old_usage, new_terminal, new_usage]);
2754 let mut rollup = Rollup::default();
2755 read_runtime_test_log(
2756 tmp.path(),
2757 Some("2026-09-08T00:00:00Z".parse().unwrap()),
2758 &mut rollup,
2759 );
2760
2761 let runtime = &rollup.runtime_requests;
2762 assert_eq!(runtime.terminal_turn_receipts, 1);
2763 assert_eq!(runtime.model_requests_started, 1);
2764 assert_eq!(runtime.provider_usage_receipts, 1);
2765 assert_eq!(runtime.provider_reported_input_tokens, 10);
2766 assert_eq!(runtime.provider_reported_output_tokens, 1);
2767 }
2768
2769 // ── Durable runtime item receipts ──
2770 //
2771 // These pin *which* runtime event names carry tool and compaction data.
2772 // Before the fix this reader matched `tool.started` / `tool.completed` /
2773 // `tool.failed` and `compaction.completed`, none of which the Runtime
2774 // store has ever written, so every per-tool counter was structurally 0.
2775
2776 fn tool_item(kind: &str, tool_name: &str, extra: Value) -> Value {
2777 let mut item = serde_json::json!({
2778 "schema_version": 4,
2779 "id": "item_abc",
2780 "turn_id": "turn-a",
2781 "kind": kind,
2782 "status": "completed",
2783 "summary": "exec_shell: ok",
2784 "metadata": { "tool_use_id": "call-1", "tool_name": tool_name },
2785 "started_at": "2026-09-08T10:00:00Z",
2786 });
2787 merge_json(&mut item, extra);
2788 item
2789 }
2790
2791 fn merge_json(target: &mut Value, extra: Value) {
2792 let Value::Object(extra) = extra else { return };
2793 let Some(target) = target.as_object_mut() else {
2794 return;
2795 };
2796 for (key, value) in extra {
2797 let nested = matches!(value, Value::Object(_))
2798 && matches!(target.get(&key), Some(Value::Object(_)));
2799 if nested {
2800 merge_json(target.get_mut(&key).expect("checked above"), value);
2801 } else {
2802 target.insert(key, value);
2803 }
2804 }
2805 }
2806
2807 #[test]
2808 fn runtime_tool_receipts_come_from_durable_item_events() {
2809 let started = runtime_event(
2810 60,
2811 "2026-09-08T10:00:00Z",
2812 "thread-a",
2813 Some("turn-a"),
2814 "item.started",
2815 serde_json::json!({
2816 "item": tool_item("tool_call", "exec_shell", serde_json::json!({
2817 "status": "in_progress",
2818 "metadata": { "tool_input": "{}" },
2819 })),
2820 "tool": { "id": "call-1", "name": "exec_shell", "input": {} },
2821 }),
2822 );
2823 let completed = runtime_event(
2824 61,
2825 "2026-09-08T10:00:02Z",
2826 "thread-a",
2827 Some("turn-a"),
2828 "item.completed",
2829 serde_json::json!({
2830 "item": tool_item("tool_call", "exec_shell", serde_json::json!({
2831 "ended_at": "2026-09-08T10:00:02Z",
2832 "metadata": { "is_error": false },
2833 })),
2834 }),
2835 );
2836 let tmp = write_runtime_events(&[started, completed]);
2837 let mut rollup = Rollup::default();
2838 read_runtime_test_log(tmp.path(), None, &mut rollup);
2839
2840 let stats = &rollup.tools["exec_shell"];
2841 assert_eq!(stats.calls, 1);
2842 assert_eq!(stats.successes, 1);
2843 assert_eq!(stats.failures, 0);
2844 assert_eq!(stats.outcome_unknown, 0);
2845 assert_eq!(stats.elapsed_samples, 1);
2846 assert_eq!(stats.total_elapsed_ms, 2_000);
2847 assert_eq!(stats.elapsed_unavailable, 0);
2848 }
2849
2850 #[test]
2851 fn runtime_file_change_and_command_execution_items_count_as_tools() {
2852 // `tool_kind_for_name` splits one tool call across three item kinds;
2853 // dropping two of them would hide every shell and edit receipt.
2854 let events: Vec<_> = [
2855 ("file_change", "apply_patch"),
2856 ("command_execution", "exec_shell"),
2857 ]
2858 .into_iter()
2859 .enumerate()
2860 .map(|(i, (kind, name))| {
2861 runtime_event(
2862 70 + i as u64,
2863 "2026-09-08T10:00:00Z",
2864 "thread-a",
2865 Some("turn-a"),
2866 "item.completed",
2867 serde_json::json!({
2868 "item": tool_item(kind, name, serde_json::json!({
2869 "ended_at": "2026-09-08T10:00:01Z",
2870 "metadata": { "is_error": false },
2871 })),
2872 }),
2873 )
2874 })
2875 .collect();
2876 let tmp = write_runtime_events(&events);
2877 let mut rollup = Rollup::default();
2878 read_runtime_test_log(tmp.path(), None, &mut rollup);
2879
2880 assert_eq!(rollup.tools["apply_patch"].successes, 1);
2881 assert_eq!(rollup.tools["exec_shell"].successes, 1);
2882 assert_eq!(rollup.tools["exec_shell"].total_elapsed_ms, 1_000);
2883 }
2884
2885 #[test]
2886 fn runtime_tool_outcome_without_is_error_is_unknown_not_success() {
2887 let completed = runtime_event(
2888 80,
2889 "2026-09-08T10:00:00Z",
2890 "thread-a",
2891 Some("turn-a"),
2892 "item.completed",
2893 serde_json::json!({
2894 "item": tool_item("tool_call", "exec_shell", serde_json::json!({})),
2895 }),
2896 );
2897 let tmp = write_runtime_events(&[completed]);
2898 let mut rollup = Rollup::default();
2899 read_runtime_test_log(tmp.path(), None, &mut rollup);
2900
2901 let stats = &rollup.tools["exec_shell"];
2902 assert_eq!(stats.successes, 0);
2903 assert_eq!(stats.failures, 0, "unknown is never folded into failures");
2904 assert_eq!(stats.outcome_unknown, 1);
2905 assert_eq!(stats.success_rate_pct(), None);
2906 assert_eq!(
2907 stats.elapsed_unavailable, 1,
2908 "a missing ended_at is not a 0 ms call"
2909 );
2910 assert_eq!(stats.elapsed_samples, 0);
2911 assert_eq!(stats.avg_elapsed_ms(), None);
2912 }
2913
2914 #[test]
2915 fn sse_only_tool_event_names_are_not_durable_receipts() {
2916 // `tool.started` / `tool.completed` / `tool.failed` are synthesized by
2917 // `map_compat_stream_event` for HTTP clients and never persisted.
2918 let events: Vec<_> = ["tool.started", "tool.completed", "tool.failed"]
2919 .into_iter()
2920 .enumerate()
2921 .map(|(i, event)| {
2922 runtime_event(
2923 90 + i as u64,
2924 "2026-09-08T10:00:00Z",
2925 "thread-a",
2926 Some("turn-a"),
2927 event,
2928 serde_json::json!({ "tool_name": "exec_shell", "elapsed_ms": 5 }),
2929 )
2930 })
2931 .collect();
2932 let tmp = write_runtime_events(&events);
2933 let mut rollup = Rollup::default();
2934 read_runtime_test_log(tmp.path(), None, &mut rollup);
2935
2936 assert_eq!(rollup.total_tool_calls(), 0);
2937 assert!(rollup.tools.is_empty());
2938 }
2939
2940 #[test]
2941 fn duplicate_item_receipts_are_counted_once() {
2942 let completed = runtime_event(
2943 100,
2944 "2026-09-08T10:00:00Z",
2945 "thread-a",
2946 Some("turn-a"),
2947 "item.completed",
2948 serde_json::json!({
2949 "item": tool_item("tool_call", "exec_shell", serde_json::json!({
2950 "ended_at": "2026-09-08T10:00:01Z",
2951 "metadata": { "is_error": false },
2952 })),
2953 }),
2954 );
2955 let tmp = write_runtime_events(&[completed.clone(), completed]);
2956 let mut rollup = Rollup::default();
2957 read_runtime_test_log(tmp.path(), None, &mut rollup);
2958
2959 let stats = &rollup.tools["exec_shell"];
2960 assert_eq!(stats.successes, 1);
2961 assert_eq!(stats.elapsed_samples, 1);
2962 assert_eq!(stats.total_elapsed_ms, 1_000);
2963 }
2964
2965 #[test]
2966 fn compaction_reduction_is_computed_from_message_counts() {
2967 let completed = runtime_event(
2968 110,
2969 "2026-09-08T10:00:00Z",
2970 "thread-a",
2971 Some("turn-a"),
2972 "item.completed",
2973 serde_json::json!({
2974 "item": { "kind": "context_compaction", "status": "completed" },
2975 "auto": true,
2976 "messages_before": 40,
2977 "messages_after": 10,
2978 }),
2979 );
2980 let tmp = write_runtime_events(&[completed]);
2981 let mut rollup = Rollup::default();
2982 read_runtime_test_log(tmp.path(), None, &mut rollup);
2983
2984 assert_eq!(rollup.compaction.events, 1);
2985 assert_eq!(rollup.compaction.ratio_samples, 1);
2986 assert_eq!(rollup.compaction.avg_reduction_pct(), Some(75.0));
2987 }
2988
2989 #[test]
2990 fn compaction_without_message_counts_stays_unknown() {
2991 let completed = runtime_event(
2992 120,
2993 "2026-09-08T10:00:00Z",
2994 "thread-a",
2995 Some("turn-a"),
2996 "item.completed",
2997 serde_json::json!({
2998 "item": { "kind": "context_compaction", "status": "completed" },
2999 "auto": true,
3000 }),
3001 );
3002 let tmp = write_runtime_events(&[completed]);
3003 let mut rollup = Rollup::default();
3004 read_runtime_test_log(tmp.path(), None, &mut rollup);
3005
3006 assert_eq!(rollup.compaction.events, 1);
3007 assert_eq!(rollup.compaction.ratio_samples, 0);
3008 assert_eq!(
3009 rollup.compaction.avg_reduction_pct(),
3010 None,
3011 "no counts is unknown, never a 0% reduction"
3012 );
3013 }
3014
3015 // ── Approval receipts ──
3016
3017 #[test]
3018 fn session_auto_approvals_are_counted_under_their_emitted_name() {
3019 let events = [
3020 serde_json::json!({
3021 "ts": "2026-09-08T10:00:00Z",
3022 "event": "tool.approval.auto_approve_session",
3023 "details": { "tool_name": "exec_shell" },
3024 }),
3025 serde_json::json!({
3026 "ts": "2026-09-08T10:00:01Z",
3027 "event": "tool.approval.auto_approve",
3028 "details": { "tool_name": "exec_shell" },
3029 }),
3030 ];
3031 let tmp = write_runtime_events(&events);
3032 let mut rollup = Rollup::default();
3033 read_audit_test_log(tmp.path(), None, &mut rollup);
3034
3035 let stats = &rollup.tools["exec_shell"];
3036 assert_eq!(stats.auto_approved, 2, "emitted name plus legacy alias");
3037 assert_eq!(stats.calls, 2);
3038 }
3039
3040 #[test]
3041 fn tool_denials_are_a_class_of_their_own() {
3042 let events: Vec<_> = [
3043 "tool.approval.auto_deny",
3044 "tool.approval.auto_deny_session",
3045 "tool.approval.auto_deny_auto_review",
3046 "tool.approval.auto_deny_full_access_policy",
3047 ]
3048 .into_iter()
3049 .map(|event| {
3050 serde_json::json!({
3051 "ts": "2026-09-08T10:00:00Z",
3052 "event": event,
3053 "details": { "tool_name": "exec_shell" },
3054 })
3055 })
3056 .collect();
3057 let tmp = write_runtime_events(&events);
3058 let mut rollup = Rollup::default();
3059 read_audit_test_log(tmp.path(), None, &mut rollup);
3060
3061 let stats = &rollup.tools["exec_shell"];
3062 assert_eq!(stats.denied, 4);
3063 assert_eq!(stats.calls, 4);
3064 assert_eq!(stats.successes, 0);
3065 assert_eq!(stats.failures, 0);
3066 assert_eq!(
3067 stats.success_rate_pct(),
3068 None,
3069 "a blocked call is not a judged outcome"
3070 );
3071 }
3072
3073 #[test]
3074 fn opt_in_tool_audit_records_resolve_their_top_level_tool_name() {
3075 // `emit_tool_audit` writes `tool_name` at the top level, not under
3076 // `details`, so pointing `--since` at that file used to bucket every
3077 // record as "unknown" and grade an absent outcome as a success.
3078 let events = [
3079 serde_json::json!({
3080 "event": "tool.result",
3081 "tool_id": "call-1",
3082 "tool_name": "exec_shell",
3083 "success": false,
3084 }),
3085 serde_json::json!({
3086 "event": "tool.result",
3087 "tool_id": "call-2",
3088 "tool_name": "exec_shell",
3089 }),
3090 ];
3091 let tmp = write_runtime_events(&events);
3092 let mut rollup = Rollup::default();
3093 read_audit_test_log(tmp.path(), None, &mut rollup);
3094
3095 let stats = &rollup.tools["exec_shell"];
3096 assert_eq!(stats.calls, 2);
3097 assert_eq!(stats.failures, 1);
3098 assert_eq!(stats.successes, 0);
3099 assert_eq!(stats.outcome_unknown, 1);
3100 assert!(!rollup.tools.contains_key("unknown"));
3101 }
3102
3103 #[test]
3104 fn rollup_json_exposes_the_new_tool_classes() {
3105 let mut rollup = Rollup::default();
3106 let stats = rollup.tool_mut("exec_shell");
3107 stats.denied = 2;
3108 stats.outcome_unknown = 1;
3109 stats.elapsed_unavailable = 3;
3110 let json = serde_json::to_value(&rollup).unwrap();
3111 assert_eq!(json["tools"]["exec_shell"]["denied"], 2);
3112 assert_eq!(json["tools"]["exec_shell"]["outcome_unknown"], 1);
3113 assert_eq!(json["tools"]["exec_shell"]["elapsed_unavailable"], 3);
3114 // Existing keys keep their names and positions for JSON consumers.
3115 assert_eq!(json["tools"]["exec_shell"]["calls"], 0);
3116 assert_eq!(json["tools"]["exec_shell"]["successes"], 0);
3117 assert_eq!(json["tools"]["exec_shell"]["failures"], 0);
3118 }
3119
3120 // ── Runtime store roots ──
3121
3122 #[test]
3123 fn every_runtime_store_root_is_read_including_session_scoped_stores() {
3124 let dir = tempfile::TempDir::new().unwrap();
3125 let tasks = dir.path().join("tasks");
3126 let sessions = dir.path().join("sessions");
3127 std::fs::create_dir_all(sessions.join("sess-1").join("runtime").join("events")).unwrap();
3128 std::fs::create_dir_all(&tasks).unwrap();
3129 std::fs::write(sessions.join("loose.json"), "{}").unwrap();
3130
3131 let _lock = crate::tests::env_lock();
3132 let _override = crate::tests::ScopedEnvVar::remove("CODEWHALE_RUNTIME_DIR");
3133 let _legacy = crate::tests::ScopedEnvVar::remove("DEEPSEEK_RUNTIME_DIR");
3134 assert_eq!(
3135 runtime_event_dirs(&tasks, &sessions),
3136 vec![
3137 tasks.join("runtime").join("events"),
3138 sessions.join("sess-1").join("runtime").join("events"),
3139 ],
3140 "a loose session file is not a store root"
3141 );
3142 }
3143
3144 #[test]
3145 fn an_explicit_runtime_dir_override_is_the_only_root_read() {
3146 let dir = tempfile::TempDir::new().unwrap();
3147 let override_dir = dir.path().join("elsewhere");
3148 let _lock = crate::tests::env_lock();
3149 let _override = crate::tests::ScopedEnvVar::set(
3150 "CODEWHALE_RUNTIME_DIR",
3151 &override_dir.to_string_lossy(),
3152 );
3153 assert_eq!(
3154 runtime_event_dirs(&dir.path().join("tasks"), &dir.path().join("sessions")),
3155 vec![override_dir.join("events")],
3156 "mixing an override with the default roots would double count"
3157 );
3158 }
3159
3160 // ── State-root resolution ──
3161 //
3162 // These pin *which* files the rollup reads. Before the fix the reader
3163 // resolved `$HOME/.deepseek`, which nothing has written since the v0.8.44
3164 // rename, so `codewhale metrics` printed an all-zero rollup as truth.
3165
3166 /// Isolate the ambient home so the resolver sees a clean, empty install.
3167 ///
3168 /// The returned guards must stay bound for the life of the test: dropping
3169 /// them restores the previous environment. Destructure the tuple so the
3170 /// bindings drop in reverse order — the environment is restored *before*
3171 /// the lock is released, or a concurrent env-mutating test sees a torn HOME.
3172 fn isolated_home() -> (
3173 tempfile::TempDir,
3174 std::sync::MutexGuard<'static, ()>,
3175 Vec<crate::tests::ScopedEnvVar>,
3176 ) {
3177 let guard = crate::tests::env_lock();
3178 let home = tempfile::TempDir::new().expect("tempdir");
3179 let vars = vec![
3180 crate::tests::ScopedEnvVar::set("HOME", &home.path().to_string_lossy()),
3181 crate::tests::ScopedEnvVar::set("USERPROFILE", &home.path().to_string_lossy()),
3182 crate::tests::ScopedEnvVar::remove("CODEWHALE_HOME"),
3183 crate::tests::ScopedEnvVar::remove("DEEPSEEK_HOME"),
3184 ];
3185 (home, guard, vars)
3186 }
3187
3188 #[test]
3189 fn default_audit_history_includes_both_roots_without_requiring_existing_files() {
3190 let (home, _lock, _env) = isolated_home();
3191 assert_eq!(
3192 resolve_audit_roots().expect("resolves"),
3193 vec![
3194 home.path().join(".codewhale"),
3195 home.path().join(".deepseek")
3196 ],
3197 );
3198 }
3199
3200 #[test]
3201 fn copied_audit_history_keeps_unique_legacy_and_rotated_records() {
3202 let dir = tempfile::TempDir::new().expect("tempdir");
3203 let primary = dir.path().join("primary");
3204 let legacy = dir.path().join("legacy");
3205 std::fs::create_dir_all(&primary).unwrap();
3206 std::fs::create_dir_all(&legacy).unwrap();
3207 let shared = r#"{"ts":"2026-09-01T00:00:00Z","event":"credential.save","details":{}}"#;
3208 let old = r#"{"ts":"2026-08-01T00:00:00Z","event":"credential.clear","details":{}}"#;
3209 let new = r#"{"ts":"2026-09-02T00:00:00Z","event":"credential.save","details":{}}"#;
3210 std::fs::write(primary.join("audit.log.1"), format!("{shared}\n{shared}\n")).unwrap();
3211 std::fs::write(primary.join("audit.log"), format!("{new}\nmalformed\n")).unwrap();
3212 std::fs::write(
3213 legacy.join("audit.log"),
3214 format!("{shared}\n{shared}\n{shared}\n"),
3215 )
3216 .unwrap();
3217 std::fs::write(legacy.join("audit.log.1"), format!("{old}\n")).unwrap();
3218 let roots = [primary, legacy];
3219 let before: Vec<_> = roots
3220 .iter()
3221 .flat_map(|root| {
3222 ["audit.log.1", "audit.log"].map(|name| {
3223 let path = root.join(name);
3224 (path.clone(), std::fs::read(path).unwrap())
3225 })
3226 })
3227 .collect();
3228 let mut rollup = Rollup::default();
3229 read_audit_history(&roots, None, &mut rollup);
3230 assert_eq!(
3231 rollup.credentials.saves, 4,
3232 "maximum occurrence count across copied roots"
3233 );
3234 assert_eq!(
3235 rollup.credentials.clears, 1,
3236 "unique old rotation is retained"
3237 );
3238 assert_eq!(rollup.parsed_lines, 5);
3239 for (path, bytes) in before {
3240 assert_eq!(
3241 std::fs::read(path).unwrap(),
3242 bytes,
3243 "source history is read-only"
3244 );
3245 }
3246 let mut recent = Rollup::default();
3247 read_audit_history(
3248 &roots,
3249 Some("2026-09-01T00:00:00Z".parse().unwrap()),
3250 &mut recent,
3251 );
3252 assert_eq!(recent.credentials.saves, 4);
3253 assert_eq!(recent.credentials.clears, 0);
3254 }
3255
3256 #[test]
3257 fn an_explicit_codewhale_home_is_an_audit_isolation_boundary() {
3258 let (home, _lock, _env) = isolated_home();
3259 let legacy = home.path().join(".deepseek");
3260 std::fs::create_dir_all(&legacy).unwrap();
3261 std::fs::write(legacy.join("audit.log"), r#"{"event":"credential.save"}"#).unwrap();
3262 let explicit = tempfile::TempDir::new().unwrap();
3263 let _pin =
3264 crate::tests::ScopedEnvVar::set("CODEWHALE_HOME", &explicit.path().to_string_lossy());
3265 let roots = resolve_audit_roots().unwrap();
3266 assert_eq!(roots, vec![explicit.path().to_path_buf()]);
3267 let mut rollup = Rollup::default();
3268 read_audit_history(&roots, None, &mut rollup);
3269 assert_eq!(rollup.parsed_lines, 0);
3270 }
3271
3272 #[test]
3273 fn the_legacy_deepseek_home_variable_is_no_longer_honoured() {
3274 let (home, _lock, _env) = isolated_home();
3275 let stale = tempfile::TempDir::new().unwrap();
3276 let _stale =
3277 crate::tests::ScopedEnvVar::set("DEEPSEEK_HOME", &stale.path().to_string_lossy());
3278 assert_eq!(
3279 resolve_audit_roots().unwrap(),
3280 vec![
3281 home.path().join(".codewhale"),
3282 home.path().join(".deepseek")
3283 ],
3284 );
3285 }
3286
3287 #[test]
3288 fn terminal_subagent_audit_and_state_files_populate_without_double_counting() {
3289 let temp = tempfile::TempDir::new().unwrap();
3290 let audit_root = temp.path().join("home");
3291 let state_dir = audit_root.join("state");
3292 std::fs::create_dir_all(&state_dir).unwrap();
3293 let audit_log = audit_root.join("audit.log");
3294 let audit_lines = [
3295 serde_json::json!({
3296 "ts": "2026-11-29T10:00:00Z",
3297 "event": "agent.spawned",
3298 "details": { "agent_id": "agent-1", "session_id": "sess-1" }
3299 }),
3300 serde_json::json!({
3301 "ts": "2026-11-29T10:01:00Z",
3302 "event": "agent.completed",
3303 "details": {
3304 "agent_id": "agent-1",
3305 "session_id": "sess-1",
3306 "worker_status": "completed",
3307 "usage": {
3308 "status": "measured",
3309 "input_tokens": 70510,
3310 "output_tokens": 1413,
3311 "total_tokens": 71923,
3312 "cost_microusd": 1500
3313 }
3314 }
3315 }),
3316 ]
3317 .iter()
3318 .map(ToString::to_string)
3319 .collect::<Vec<_>>()
3320 .join("\n");
3321 std::fs::write(&audit_log, audit_lines).unwrap();
3322
3323 let ts_ms = "2026-11-29T10:02:00Z"
3324 .parse::<DateTime<Utc>>()
3325 .unwrap()
3326 .timestamp_millis() as u64;
3327 let state_json = serde_json::json!({
3328 "schema_version": 3,
3329 "workers": [
3330 {
3331 "spec": { "id": "agent-1" },
3332 "status": "completed",
3333 "updated_at_ms": ts_ms,
3334 "usage": {
3335 "status": "measured",
3336 "input_tokens": 70510,
3337 "output_tokens": 1413,
3338 "total_tokens": 71923
3339 }
3340 },
3341 {
3342 "spec": { "id": "worker-2" },
3343 "status": "failed",
3344 "updated_at_ms": ts_ms,
3345 "usage": {
3346 "status": "measured",
3347 "input_tokens": 1000,
3348 "output_tokens": 200,
3349 "total_tokens": 1200
3350 }
3351 }
3352 ],
3353 "agents": [
3354 {
3355 "id": "agent-3",
3356 "status": "BudgetExhausted",
3357 "updated_at_ms": ts_ms
3358 }
3359 ]
3360 });
3361 std::fs::write(state_dir.join("subagents.v3.json"), state_json.to_string()).unwrap();
3362
3363 let mut rollup = Rollup::default();
3364 read_audit_history(&[audit_root], None, &mut rollup);
3365 read_subagent_state_files(
3366 &state_dir,
3367 &std::collections::BTreeSet::new(),
3368 None,
3369 &mut rollup,
3370 );
3371
3372 assert_eq!(rollup.agents.spawns, 3);
3373 assert_eq!(rollup.agents.successes, 1);
3374 assert_eq!(rollup.agents.failures, 1);
3375 assert_eq!(rollup.agents.budget_exhausted, 1);
3376 assert_eq!(rollup.agents.usage_receipts, 2);
3377 assert_eq!(rollup.agents.input_tokens, 71510);
3378 assert_eq!(rollup.agents.output_tokens, 1613);
3379 assert_eq!(rollup.agents.total_tokens, 73123);
3380 assert!(
3381 rollup
3382 .agents
3383 .summary()
3384 .contains("71,510 in/1,613 out/73,123 total (2 receipts)")
3385 );
3386 }
3387
3388 #[test]
3389 fn session_file_older_than_since_does_not_consume_inspection_budget() {
3390 let temp = tempfile::TempDir::new().unwrap();
3391 let path = temp.path().join("old.json");
3392 let old = serde_json::json!({
3393 "metadata": {
3394 "updated_at": "2025-01-01T00:00:00Z"
3395 },
3396 "messages": []
3397 });
3398 std::fs::write(&path, old.to_string()).unwrap();
3399
3400 let mut rollup = Rollup::default();
3401 let cutoff = "2026-11-01T00:00:00Z".parse::<DateTime<Utc>>().unwrap();
3402 read_session_file(&path, Some(cutoff), &mut rollup);
3403
3404 assert_eq!(rollup.receipt_inspection_bytes, 0);
3405 assert_eq!(rollup.parsed_lines, 0);
3406 }
3407
3408 #[test]
3409 fn subagent_state_v3_agents_usage_round_trips_deduplicates_and_keeps_unmeasured_unknown() {
3410 let temp = tempfile::TempDir::new().unwrap();
3411 let audit_root = temp.path().join("home");
3412 let state_dir = audit_root.join("state");
3413 std::fs::create_dir_all(&state_dir).unwrap();
3414
3415 let audit_log = audit_root.join("audit.log");
3416 let audit_lines = [
3417 serde_json::json!({
3418 "ts": "2026-11-29T10:00:00Z",
3419 "event": "agent.spawned",
3420 "details": { "agent_id": "agent-audit", "session_id": "sess-1" }
3421 }),
3422 serde_json::json!({
3423 "ts": "2026-11-29T10:01:00Z",
3424 "event": "agent.completed",
3425 "details": {
3426 "agent_id": "agent-audit",
3427 "session_id": "sess-1",
3428 "worker_status": "completed",
3429 "usage": {
3430 "status": "reported",
3431 "input_tokens": 500,
3432 "output_tokens": 100,
3433 "total_tokens": 600,
3434 "cost_microusd": 40
3435 }
3436 }
3437 }),
3438 ]
3439 .iter()
3440 .map(ToString::to_string)
3441 .collect::<Vec<_>>()
3442 .join("\n");
3443 std::fs::write(&audit_log, audit_lines).unwrap();
3444
3445 let ts_ms = "2026-11-29T10:02:00Z"
3446 .parse::<DateTime<Utc>>()
3447 .unwrap()
3448 .timestamp_millis() as u64;
3449 let state_json = serde_json::json!({
3450 "store_schema": 3,
3451 "revision": 2,
3452 "state": {
3453 "schema_version": 2,
3454 "workers": [
3455 {
3456 "spec": { "worker_id": "agent-audit" },
3457 "status": "completed",
3458 "updated_at_ms": ts_ms,
3459 "usage": {
3460 "status": "reported",
3461 "input_tokens": 500,
3462 "output_tokens": 100,
3463 "total_tokens": 600,
3464 "cost_microusd": 40
3465 }
3466 }
3467 ],
3468 "agents": [
3469 {
3470 "id": "agent-audit",
3471 "status": "Completed",
3472 "updated_at_ms": ts_ms,
3473 "usage": {
3474 "status": "reported",
3475 "input_tokens": 500,
3476 "output_tokens": 100,
3477 "total_tokens": 600,
3478 "cost_microusd": 40
3479 }
3480 },
3481 {
3482 "id": "agent-measured",
3483 "status": "Completed",
3484 "updated_at_ms": ts_ms,
3485 "usage": {
3486 "status": "reported",
3487 "input_tokens": 1200,
3488 "output_tokens": 300,
3489 "total_tokens": 1500,
3490 "cost_microusd": 90
3491 }
3492 },
3493 {
3494 "id": "agent-unmeasured-none",
3495 "status": "Completed",
3496 "updated_at_ms": ts_ms
3497 },
3498 {
3499 "id": "agent-unmeasured-unknown",
3500 "status": { "Failed": "timeout" },
3501 "updated_at_ms": ts_ms,
3502 "usage": {
3503 "status": "unknown",
3504 "note": "Token usage is not yet reported by the sub-agent worker ledger."
3505 }
3506 }
3507 ]
3508 }
3509 });
3510 std::fs::write(state_dir.join("subagents.v3.json"), state_json.to_string()).unwrap();
3511
3512 let mut rollup = Rollup::default();
3513 read_audit_history(&[audit_root], None, &mut rollup);
3514 read_subagent_state_files(
3515 &state_dir,
3516 &std::collections::BTreeSet::new(),
3517 None,
3518 &mut rollup,
3519 );
3520
3521 assert_eq!(rollup.agents.spawns, 4);
3522 assert_eq!(rollup.agents.successes, 3);
3523 assert_eq!(rollup.agents.failures, 1);
3524 assert_eq!(rollup.agents.usage_receipts, 2);
3525 assert_eq!(rollup.agents.input_tokens, 1700);
3526 assert_eq!(rollup.agents.output_tokens, 400);
3527 assert_eq!(rollup.agents.total_tokens, 2100);
3528 assert_eq!(rollup.agents.cost_microusd, 130);
3529 }
3530
3531 #[test]
3532 fn legacy_partial_report_warning_surfaces_read_gaps_and_exhausted_cap() {
3533 let mut rollup = Rollup::default();
3534 assert_eq!(legacy_partial_report_warning(&rollup), None);
3535
3536 rollup.receipt_read_gaps = 2;
3537 let gap_warning = legacy_partial_report_warning(&rollup).expect("gap warning");
3538 assert!(gap_warning.contains("partial legacy receipt report"));
3539 assert!(gap_warning.contains("2 receipt read gaps"));
3540
3541 rollup.receipt_inspection_exhausted = true;
3542 let cap_warning = legacy_partial_report_warning(&rollup).expect("cap warning");
3543 assert!(cap_warning.contains("16 MiB cap"));
3544 assert!(cap_warning.contains("2 read gaps"));
3545 }
3546
3547 #[test]
3548 fn legacy_json_exposes_receipt_inspection_exhausted_and_prefilters_sessions_via_metadata() {
3549 let temp = tempfile::TempDir::new().unwrap();
3550 let workspace = temp.path().join("workspace");
3551 std::fs::create_dir_all(&workspace).unwrap();
3552 let path = temp.path().join("old-corrupt-body.json");
3553 let metadata = serde_json::json!({
3554 "id": "old-corrupt-body",
3555 "title": "old session",
3556 "created_at": "2025-01-01T00:00:00Z",
3557 "updated_at": "2025-01-01T00:00:00Z",
3558 "message_count": 2,
3559 "total_tokens": 50,
3560 "model": "test-model",
3561 "workspace": workspace
3562 });
3563 let raw = format!(
3564 r#"{{"schema_version":{},"metadata":{metadata},"messages":[not-valid-json"#,
3565 codewhale_engine::session_manager::CURRENT_SESSION_SCHEMA_VERSION
3566 );
3567 std::fs::write(&path, raw).unwrap();
3568
3569 let mut rollup = Rollup::default();
3570 let cutoff = "2026-11-01T00:00:00Z".parse::<DateTime<Utc>>().unwrap();
3571 read_session_file(&path, Some(cutoff), &mut rollup);
3572
3573 assert_eq!(rollup.total_lines, 0);
3574 assert_eq!(rollup.parsed_lines, 0);
3575 assert_eq!(rollup.receipt_read_gaps, 0);
3576 assert_eq!(rollup.receipt_inspection_bytes, 0);
3577 assert!(!rollup.receipt_inspection_exhausted);
3578 let initial_json = serde_json::to_value(&rollup).unwrap();
3579 assert_eq!(
3580 initial_json["receipt_inspection_exhausted"].as_bool(),
3581 Some(false)
3582 );
3583
3584 rollup.receipt_inspection_bytes =
3585 codewhale_engine::session_manager::SESSION_METADATA_READ_LIMIT;
3586 assert!(!rollup.admit_receipt_inspection(&serde_json::json!({"event": "x"})));
3587 assert!(rollup.receipt_inspection_exhausted);
3588 let exhausted_json = serde_json::to_value(&rollup).unwrap();
3589 assert_eq!(
3590 exhausted_json["receipt_inspection_exhausted"].as_bool(),
3591 Some(true)
3592 );
3593 }
3594
3595 #[test]
3596 fn subagent_state_filters_since_before_charging_receipt_inspection_budget() {
3597 let temp = tempfile::TempDir::new().unwrap();
3598 let path = temp.path().join("subagents.v3.json");
3599 let old_ms = "2025-01-01T00:00:00Z"
3600 .parse::<DateTime<Utc>>()
3601 .unwrap()
3602 .timestamp_millis() as u64;
3603 let recent_ms = "2026-11-10T00:00:00Z"
3604 .parse::<DateTime<Utc>>()
3605 .unwrap()
3606 .timestamp_millis() as u64;
3607 let cutoff = "2026-11-01T00:00:00Z".parse::<DateTime<Utc>>().unwrap();
3608 let big_blob = "x".repeat(4096);
3609 let state_json = serde_json::json!({
3610 "state": {
3611 "schema_version": 2,
3612 "workers": [
3613 {
3614 "spec": { "worker_id": "old-worker", "note": big_blob },
3615 "status": "completed",
3616 "updated_at_ms": old_ms
3617 },
3618 {
3619 "spec": { "worker_id": "recent-worker" },
3620 "status": "completed",
3621 "updated_at_ms": recent_ms
3622 }
3623 ],
3624 "agents": [
3625 {
3626 "id": "old-agent",
3627 "status": "Completed",
3628 "updated_at_ms": old_ms,
3629 "note": "y".repeat(4096)
3630 },
3631 {
3632 "id": "recent-agent",
3633 "status": "Completed",
3634 "updated_at_ms": recent_ms
3635 }
3636 ]
3637 }
3638 });
3639 std::fs::write(&path, state_json.to_string()).unwrap();
3640
3641 let mut filtered = Rollup {
3642 receipt_inspection_bytes: codewhale_engine::session_manager::SESSION_METADATA_READ_LIMIT
3643 - 1024,
3644 ..Default::default()
3645 };
3646 read_subagent_state_file(&path, Some(cutoff), &mut filtered);
3647
3648 assert!(!filtered.receipt_inspection_exhausted);
3649 assert_eq!(filtered.receipt_read_gaps, 0);
3650 assert_eq!(filtered.agents.spawns, 2);
3651 assert_eq!(filtered.agents.successes, 2);
3652
3653 let mut unfiltered = Rollup {
3654 receipt_inspection_bytes: codewhale_engine::session_manager::SESSION_METADATA_READ_LIMIT
3655 - 1024,
3656 ..Default::default()
3657 };
3658 read_subagent_state_file(&path, None, &mut unfiltered);
3659 assert!(unfiltered.receipt_inspection_exhausted);
3660 }
3661 }
3662
3662 lines RUST