pulpod 0.1.0

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

use std::collections::{HashMap, HashSet};
use std::path::Path;

use chrono::{DateTime, Utc};

use super::{ExactUsage, RateOverrides, SOURCE_CLAUDE, resolve_rates, token_field};

/// Sanitize a working directory into Claude Code's project-directory name.
/// Claude Code replaces every non-alphanumeric character with `-`
/// (`/Users/dario/.pulpo` becomes `-Users-dario--pulpo`).
pub fn sanitize_workdir(workdir: &str) -> String {
    workdir
        .chars()
        .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
        .collect()
}

/// Running totals while parsing transcript records.
#[derive(Debug, Default)]
struct Totals {
    input: u64,
    output: u64,
    cache_write: u64,
    cache_read: u64,
    cost_usd: f64,
    unknown_model: bool,
    records: u64,
    /// Per-model breakdown, for the usage scan's by-model rollup.
    by_model: HashMap<String, ModelAgg>,
}

/// Tokens and cost accumulated for a single model.
#[derive(Debug, Default)]
struct ModelAgg {
    tokens: u64,
    cost_usd: f64,
    /// Set when a record used a model with no known rate — cost is then withheld.
    unknown: bool,
}

/// Parse one transcript line and fold its usage into `totals`.
///
/// Lines are skipped when they are not JSON, predate `since`, carry no
/// `message.usage`, or repeat an already-seen `message.id` + `requestId` pair
/// (streaming writes the same usage on multiple records).
fn apply_transcript_line(
    line: &str,
    since: DateTime<Utc>,
    seen: &mut HashSet<String>,
    totals: &mut Totals,
    rates: &RateOverrides,
) {
    let Ok(value) = serde_json::from_str::<serde_json::Value>(line) else {
        return;
    };
    let Some(timestamp) = value
        .get("timestamp")
        .and_then(serde_json::Value::as_str)
        .and_then(|ts| DateTime::parse_from_rfc3339(ts).ok())
    else {
        return;
    };
    if timestamp.with_timezone(&Utc) < since {
        return;
    }
    let Some(message) = value.get("message") else {
        return;
    };
    let Some(usage) = message.get("usage") else {
        return;
    };

    let message_id = message.get("id").and_then(serde_json::Value::as_str);
    let request_id = value.get("requestId").and_then(serde_json::Value::as_str);
    if let (Some(mid), Some(rid)) = (message_id, request_id)
        && !seen.insert(format!("{mid}:{rid}"))
    {
        return;
    }

    let input = token_field(usage, "input_tokens");
    let output = token_field(usage, "output_tokens");
    let cache_read = token_field(usage, "cache_read_input_tokens");
    // Prefer the TTL breakdown (priced differently) over the flat total.
    let (five_min, one_hour) = usage.get("cache_creation").map_or_else(
        || (token_field(usage, "cache_creation_input_tokens"), 0),
        |breakdown| {
            (
                token_field(breakdown, "ephemeral_5m_input_tokens"),
                token_field(breakdown, "ephemeral_1h_input_tokens"),
            )
        },
    );

    totals.input += input;
    totals.output += output;
    totals.cache_read += cache_read;
    totals.cache_write += five_min + one_hour;
    totals.records += 1;

    let tokens = input + output + cache_read + five_min + one_hour;
    let model = message
        .get("model")
        .and_then(serde_json::Value::as_str)
        .unwrap_or_default();
    let agg = totals.by_model.entry(model.to_owned()).or_default();
    agg.tokens += tokens;
    #[allow(clippy::cast_precision_loss)]
    match resolve_rates(model, rates) {
        Some(rates) => {
            let cost = (input as f64).mul_add(
                rates.input,
                (output as f64).mul_add(
                    rates.output,
                    (cache_read as f64).mul_add(
                        rates.cache_read,
                        (five_min as f64).mul_add(
                            rates.cache_write_5m,
                            (one_hour as f64) * rates.cache_write_1h,
                        ),
                    ),
                ),
            ) / 1_000_000.0;
            totals.cost_usd += cost;
            agg.cost_usd += cost;
        }
        None => {
            if tokens > 0 {
                totals.unknown_model = true;
                agg.unknown = true;
            }
        }
    }
}

/// Read exact usage for a Claude Code session running in `workdir`, started at `since`.
///
/// Sums usage records with timestamps at or after `since` across every transcript in
/// the project directory whose mtime is at or after `since`. Returns `None` when the
/// directory does not exist or no matching records are found.
pub fn read_usage(
    claude_dir: &Path,
    workdir: &str,
    since: DateTime<Utc>,
    rates: &RateOverrides,
) -> Option<ExactUsage> {
    let project_dir = claude_dir.join("projects").join(sanitize_workdir(workdir));
    read_usage_dir(&project_dir, since, rates).map(|d| d.usage)
}

/// Usage for one Claude project directory, plus the agent's recorded `cwd`.
///
/// The `cwd` is read from the transcript (Claude records it per line) so callers like the
/// usage scan can label by the real repo path and merge with other agents — not the
/// lossy sanitized directory name.
pub(crate) struct DirUsage {
    pub usage: ExactUsage,
    pub cwd: Option<String>,
    /// Per-model `(model, tokens, cost)` — cost is `None` when the model has no known rate.
    pub by_model: Vec<ModelUsage>,
}

/// One model's tokens and (optional) cost within a project directory.
pub(crate) struct ModelUsage {
    pub model: String,
    pub tokens: u64,
    pub cost_usd: Option<f64>,
}

/// Sum usage across every transcript in a single Claude project directory (already
/// resolved — no workdir sanitization). Returns `None` when the dir is missing or has no
/// matching records. Used by both [`read_usage`] and the usage scan.
pub(crate) fn read_usage_dir(
    project_dir: &Path,
    since: DateTime<Utc>,
    rates: &RateOverrides,
) -> Option<DirUsage> {
    let entries = std::fs::read_dir(project_dir).ok()?;

    let mut totals = Totals::default();
    let mut seen = HashSet::new();
    let mut cwd: Option<String> = None;
    for entry in entries.flatten() {
        let path = entry.path();
        if path.extension().and_then(|ext| ext.to_str()) != Some("jsonl") {
            continue;
        }
        if let Ok(file_meta) = entry.metadata()
            && let Ok(modified) = file_meta.modified()
        {
            let modified: DateTime<Utc> = modified.into();
            if modified < since {
                continue;
            }
        }
        let Ok(content) = std::fs::read_to_string(&path) else {
            continue;
        };
        for line in content.lines() {
            apply_transcript_line(line, since, &mut seen, &mut totals, rates);
            if cwd.is_none()
                && let Ok(value) = serde_json::from_str::<serde_json::Value>(line)
            {
                cwd = value
                    .get("cwd")
                    .and_then(serde_json::Value::as_str)
                    .map(str::to_owned);
            }
        }
    }

    if totals.records == 0 {
        return None;
    }
    let by_model = totals
        .by_model
        .into_iter()
        .map(|(model, agg)| ModelUsage {
            model,
            tokens: agg.tokens,
            cost_usd: (!agg.unknown).then_some(agg.cost_usd),
        })
        .collect();
    Some(DirUsage {
        usage: ExactUsage {
            source: SOURCE_CLAUDE,
            input_tokens: totals.input,
            output_tokens: totals.output,
            cache_write_tokens: totals.cache_write,
            cache_read_tokens: totals.cache_read,
            cost_usd: (!totals.unknown_model).then_some(totals.cost_usd),
            quota: None,
        },
        cwd,
        by_model,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::TimeDelta;
    use std::fs;

    fn transcript_line(timestamp: &str, message_id: &str, request_id: &str, model: &str) -> String {
        format!(
            r#"{{"timestamp":"{timestamp}","requestId":"{request_id}","type":"assistant","message":{{"id":"{message_id}","model":"{model}","usage":{{"input_tokens":1000,"output_tokens":500,"cache_read_input_tokens":2000,"cache_creation_input_tokens":300,"cache_creation":{{"ephemeral_5m_input_tokens":300,"ephemeral_1h_input_tokens":0}}}}}}}}"#
        )
    }

    fn write_project_file(claude_dir: &Path, workdir: &str, name: &str, content: &str) {
        let project_dir = claude_dir.join("projects").join(sanitize_workdir(workdir));
        fs::create_dir_all(&project_dir).unwrap();
        fs::write(project_dir.join(name), content).unwrap();
    }

    #[test]
    fn test_sanitize_workdir_plain_path() {
        assert_eq!(
            sanitize_workdir("/Users/dario/Code/darioblanco/pulpo"),
            "-Users-dario-Code-darioblanco-pulpo"
        );
    }

    #[test]
    fn test_sanitize_workdir_dots_become_dashes() {
        assert_eq!(
            sanitize_workdir("/Users/dario/.pulpo/worktrees/fix-1"),
            "-Users-dario--pulpo-worktrees-fix-1"
        );
    }

    #[test]
    fn test_sanitize_workdir_underscores_and_spaces() {
        assert_eq!(sanitize_workdir("/tmp/my_repo v2"), "-tmp-my-repo-v2");
    }

    #[test]
    fn test_read_usage_missing_project_dir() {
        let tmp = tempfile::tempdir().unwrap();
        assert!(
            read_usage(
                tmp.path(),
                "/tmp/repo",
                Utc::now(),
                &RateOverrides::default()
            )
            .is_none()
        );
    }

    #[test]
    fn test_read_usage_sums_records_and_computes_cost() {
        let tmp = tempfile::tempdir().unwrap();
        let since = Utc::now() - TimeDelta::hours(1);
        let ts = Utc::now().to_rfc3339();
        let content = format!(
            "{}\n{}\n",
            transcript_line(&ts, "msg_1", "req_1", "claude-fable-5"),
            transcript_line(&ts, "msg_2", "req_2", "claude-fable-5"),
        );
        write_project_file(tmp.path(), "/tmp/repo", "abc.jsonl", &content);

        let usage = read_usage(tmp.path(), "/tmp/repo", since, &RateOverrides::default()).unwrap();
        assert_eq!(usage.source, SOURCE_CLAUDE);
        assert_eq!(usage.input_tokens, 2000);
        assert_eq!(usage.output_tokens, 1000);
        assert_eq!(usage.cache_read_tokens, 4000);
        assert_eq!(usage.cache_write_tokens, 600);
        // 2 records × (1000×$10 + 500×$50 + 2000×$1 + 300×$12.5) / 1M
        let expected = 2.0 * (10_000.0 + 25_000.0 + 2_000.0 + 3_750.0) / 1_000_000.0;
        assert!((usage.cost_usd.unwrap() - expected).abs() < 1e-9);
    }

    #[test]
    fn test_read_usage_sums_across_multiple_files_in_project_dir() {
        // The reader sums every transcript in the project dir. This is correct for one
        // session whose history spans multiple files — and is also the documented
        // over-count: a second agent run in the same workdir during the window is
        // attributed here too (session→file mapping is dir+time, not per-session-id).
        let tmp = tempfile::tempdir().unwrap();
        let since = Utc::now() - TimeDelta::hours(1);
        let ts = Utc::now().to_rfc3339();
        write_project_file(
            tmp.path(),
            "/tmp/repo",
            "first.jsonl",
            &transcript_line(&ts, "m1", "r1", "claude-opus-4-8"),
        );
        write_project_file(
            tmp.path(),
            "/tmp/repo",
            "second.jsonl",
            &transcript_line(&ts, "m2", "r2", "claude-opus-4-8"),
        );

        let usage = read_usage(tmp.path(), "/tmp/repo", since, &RateOverrides::default()).unwrap();
        // Both files counted: 2 × 1000 input, 2 × 500 output.
        assert_eq!(usage.input_tokens, 2000);
        assert_eq!(usage.output_tokens, 1000);
    }

    #[test]
    fn test_read_usage_dedupes_repeated_message_and_request_id() {
        let tmp = tempfile::tempdir().unwrap();
        let since = Utc::now() - TimeDelta::hours(1);
        let ts = Utc::now().to_rfc3339();
        let line = transcript_line(&ts, "msg_1", "req_1", "claude-opus-4-8");
        write_project_file(
            tmp.path(),
            "/tmp/repo",
            "abc.jsonl",
            &format!("{line}\n{line}\n"),
        );

        let usage = read_usage(tmp.path(), "/tmp/repo", since, &RateOverrides::default()).unwrap();
        assert_eq!(usage.input_tokens, 1000);
        assert_eq!(usage.output_tokens, 500);
    }

    #[test]
    fn test_read_usage_skips_records_before_since() {
        let tmp = tempfile::tempdir().unwrap();
        let since = Utc::now() - TimeDelta::hours(1);
        let old_ts = (Utc::now() - TimeDelta::hours(5)).to_rfc3339();
        let new_ts = Utc::now().to_rfc3339();
        let content = format!(
            "{}\n{}\n",
            transcript_line(&old_ts, "msg_old", "req_old", "claude-fable-5"),
            transcript_line(&new_ts, "msg_new", "req_new", "claude-fable-5"),
        );
        write_project_file(tmp.path(), "/tmp/repo", "abc.jsonl", &content);

        let usage = read_usage(tmp.path(), "/tmp/repo", since, &RateOverrides::default()).unwrap();
        assert_eq!(usage.input_tokens, 1000);
    }

    #[test]
    fn test_read_usage_all_records_too_old_returns_none() {
        let tmp = tempfile::tempdir().unwrap();
        let old_ts = (Utc::now() - TimeDelta::hours(5)).to_rfc3339();
        let content = transcript_line(&old_ts, "msg_old", "req_old", "claude-fable-5");
        write_project_file(tmp.path(), "/tmp/repo", "abc.jsonl", &content);

        let since = Utc::now() - TimeDelta::hours(1);
        assert!(read_usage(tmp.path(), "/tmp/repo", since, &RateOverrides::default()).is_none());
    }

    #[test]
    fn test_read_usage_unknown_model_withholds_cost() {
        let tmp = tempfile::tempdir().unwrap();
        let since = Utc::now() - TimeDelta::hours(1);
        let ts = Utc::now().to_rfc3339();
        let content = format!(
            "{}\n{}\n",
            transcript_line(&ts, "msg_1", "req_1", "claude-fable-5"),
            transcript_line(&ts, "msg_2", "req_2", "experimental-model"),
        );
        write_project_file(tmp.path(), "/tmp/repo", "abc.jsonl", &content);

        let usage = read_usage(tmp.path(), "/tmp/repo", since, &RateOverrides::default()).unwrap();
        assert_eq!(usage.input_tokens, 2000);
        assert!(usage.cost_usd.is_none());
    }

    #[test]
    fn test_read_usage_config_override_prices_unknown_model() {
        let tmp = tempfile::tempdir().unwrap();
        let since = Utc::now() - TimeDelta::hours(1);
        let ts = Utc::now().to_rfc3339();
        let content = transcript_line(&ts, "msg_1", "req_1", "brand-new-model");
        write_project_file(tmp.path(), "/tmp/repo", "abc.jsonl", &content);

        // No override → unknown model, cost withheld.
        let bare = read_usage(tmp.path(), "/tmp/repo", since, &RateOverrides::default()).unwrap();
        assert!(bare.cost_usd.is_none());

        // With a [rates.brand-new-model] override, cost is computed (no code change).
        let overrides = RateOverrides::new([(
            "brand-new-model".to_owned(),
            crate::usage::ModelRates {
                input: 2.0,
                output: 8.0,
                cache_read: 0.0,
                cache_write_5m: 0.0,
                cache_write_1h: 0.0,
            },
        )]);
        let usage = read_usage(tmp.path(), "/tmp/repo", since, &overrides).unwrap();
        // input 1000×$2 + output 500×$8 (cache priced at $0) = 6000 / 1M
        let expected = (1000.0f64).mul_add(2.0, 500.0 * 8.0) / 1_000_000.0;
        assert!((usage.cost_usd.unwrap() - expected).abs() < 1e-9);
    }

    #[test]
    fn test_read_usage_config_override_reprices_known_model() {
        let tmp = tempfile::tempdir().unwrap();
        let since = Utc::now() - TimeDelta::hours(1);
        let ts = Utc::now().to_rfc3339();
        let content = transcript_line(&ts, "msg_1", "req_1", "claude-opus-4-8");
        write_project_file(tmp.path(), "/tmp/repo", "abc.jsonl", &content);

        // Exact-ID override beats the built-in opus rate.
        let overrides = RateOverrides::new([(
            "claude-opus-4-8".to_owned(),
            crate::usage::ModelRates {
                input: 99.0,
                output: 0.0,
                cache_read: 0.0,
                cache_write_5m: 0.0,
                cache_write_1h: 0.0,
            },
        )]);
        let usage = read_usage(tmp.path(), "/tmp/repo", since, &overrides).unwrap();
        let expected = 1000.0 * 99.0 / 1_000_000.0;
        assert!((usage.cost_usd.unwrap() - expected).abs() < 1e-9);
    }

    #[test]
    fn test_read_usage_prices_1h_cache_writes() {
        let tmp = tempfile::tempdir().unwrap();
        let since = Utc::now() - TimeDelta::hours(1);
        let ts = Utc::now().to_rfc3339();
        let line = format!(
            r#"{{"timestamp":"{ts}","requestId":"req_1","message":{{"id":"msg_1","model":"claude-fable-5","usage":{{"input_tokens":0,"output_tokens":0,"cache_read_input_tokens":0,"cache_creation_input_tokens":1000000,"cache_creation":{{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":1000000}}}}}}}}"#
        );
        write_project_file(tmp.path(), "/tmp/repo", "abc.jsonl", &line);

        let usage = read_usage(tmp.path(), "/tmp/repo", since, &RateOverrides::default()).unwrap();
        assert_eq!(usage.cache_write_tokens, 1_000_000);
        assert!((usage.cost_usd.unwrap() - 20.0).abs() < 1e-9);
    }

    #[test]
    fn test_read_usage_flat_cache_creation_without_breakdown() {
        let tmp = tempfile::tempdir().unwrap();
        let since = Utc::now() - TimeDelta::hours(1);
        let ts = Utc::now().to_rfc3339();
        let line = format!(
            r#"{{"timestamp":"{ts}","requestId":"req_1","message":{{"id":"msg_1","model":"claude-haiku-4-5","usage":{{"input_tokens":100,"output_tokens":50,"cache_creation_input_tokens":400}}}}}}"#
        );
        write_project_file(tmp.path(), "/tmp/repo", "abc.jsonl", &line);

        let usage = read_usage(tmp.path(), "/tmp/repo", since, &RateOverrides::default()).unwrap();
        assert_eq!(usage.cache_write_tokens, 400);
        assert_eq!(usage.cache_read_tokens, 0);
    }

    #[test]
    fn test_read_usage_skips_invalid_and_irrelevant_lines() {
        let tmp = tempfile::tempdir().unwrap();
        let since = Utc::now() - TimeDelta::hours(1);
        let ts = Utc::now().to_rfc3339();
        let content = format!(
            "not json\n{{\"timestamp\":\"{ts}\",\"type\":\"user\"}}\n{{\"timestamp\":\"bad-ts\"}}\n{{\"no_timestamp\":true}}\n{{\"timestamp\":\"{ts}\",\"message\":{{\"id\":\"m\"}}}}\n{}\n",
            transcript_line(&ts, "msg_1", "req_1", "claude-sonnet-4-6"),
        );
        write_project_file(tmp.path(), "/tmp/repo", "abc.jsonl", &content);

        let usage = read_usage(tmp.path(), "/tmp/repo", since, &RateOverrides::default()).unwrap();
        assert_eq!(usage.input_tokens, 1000);
    }

    #[test]
    fn test_read_usage_counts_records_without_ids() {
        // Records missing message.id/requestId can't be deduped — both count.
        let tmp = tempfile::tempdir().unwrap();
        let since = Utc::now() - TimeDelta::hours(1);
        let ts = Utc::now().to_rfc3339();
        let line = format!(
            r#"{{"timestamp":"{ts}","message":{{"model":"claude-opus-4-8","usage":{{"input_tokens":10,"output_tokens":5}}}}}}"#
        );
        write_project_file(
            tmp.path(),
            "/tmp/repo",
            "abc.jsonl",
            &format!("{line}\n{line}\n"),
        );

        let usage = read_usage(tmp.path(), "/tmp/repo", since, &RateOverrides::default()).unwrap();
        assert_eq!(usage.input_tokens, 20);
    }

    #[test]
    fn test_read_usage_ignores_non_jsonl_files() {
        let tmp = tempfile::tempdir().unwrap();
        let since = Utc::now() - TimeDelta::hours(1);
        let ts = Utc::now().to_rfc3339();
        write_project_file(
            tmp.path(),
            "/tmp/repo",
            "notes.txt",
            &transcript_line(&ts, "msg_1", "req_1", "claude-fable-5"),
        );

        assert!(read_usage(tmp.path(), "/tmp/repo", since, &RateOverrides::default()).is_none());
    }

    #[test]
    fn test_read_usage_skips_files_untouched_since_spawn() {
        let tmp = tempfile::tempdir().unwrap();
        let ts = Utc::now().to_rfc3339();
        write_project_file(
            tmp.path(),
            "/tmp/repo",
            "old.jsonl",
            &transcript_line(&ts, "msg_1", "req_1", "claude-fable-5"),
        );
        let file_path = tmp
            .path()
            .join("projects")
            .join(sanitize_workdir("/tmp/repo"))
            .join("old.jsonl");
        let old_mtime = std::time::SystemTime::now() - std::time::Duration::from_secs(7200);
        let file = fs::File::options().write(true).open(&file_path).unwrap();
        file.set_modified(old_mtime).unwrap();

        let since = Utc::now() - TimeDelta::hours(1);
        assert!(read_usage(tmp.path(), "/tmp/repo", since, &RateOverrides::default()).is_none());
    }

    #[test]
    fn test_read_usage_dir_breaks_down_by_model() {
        let tmp = tempfile::tempdir().unwrap();
        let since = Utc::now() - TimeDelta::hours(1);
        let ts = Utc::now().to_rfc3339();
        let content = format!(
            "{}\n{}\n{}\n",
            transcript_line(&ts, "m1", "r1", "claude-opus-4-8"),
            transcript_line(&ts, "m2", "r2", "claude-opus-4-8"),
            transcript_line(&ts, "m3", "r3", "claude-haiku-4-5"),
        );
        let project_dir = tmp
            .path()
            .join("projects")
            .join(sanitize_workdir("/tmp/repo"));
        fs::create_dir_all(&project_dir).unwrap();
        fs::write(project_dir.join("abc.jsonl"), &content).unwrap();

        let d = read_usage_dir(&project_dir, since, &RateOverrides::default()).unwrap();
        assert_eq!(d.by_model.len(), 2);
        let opus = d
            .by_model
            .iter()
            .find(|m| m.model == "claude-opus-4-8")
            .unwrap();
        // Each transcript line: 1000 in + 500 out + 2000 read + 300 write = 3800 tokens.
        assert_eq!(opus.tokens, 7600);
        assert!(opus.cost_usd.unwrap() > 0.0);
        let haiku = d
            .by_model
            .iter()
            .find(|m| m.model == "claude-haiku-4-5")
            .unwrap();
        assert_eq!(haiku.tokens, 3800);
    }

    #[test]
    fn test_read_usage_dir_by_model_withholds_unknown_cost() {
        let tmp = tempfile::tempdir().unwrap();
        let since = Utc::now() - TimeDelta::hours(1);
        let ts = Utc::now().to_rfc3339();
        let content = transcript_line(&ts, "m1", "r1", "experimental-model");
        let project_dir = tmp
            .path()
            .join("projects")
            .join(sanitize_workdir("/tmp/repo"));
        fs::create_dir_all(&project_dir).unwrap();
        fs::write(project_dir.join("abc.jsonl"), &content).unwrap();

        let d = read_usage_dir(&project_dir, since, &RateOverrides::default()).unwrap();
        let m = d
            .by_model
            .iter()
            .find(|m| m.model == "experimental-model")
            .unwrap();
        assert!(m.cost_usd.is_none());
        assert_eq!(m.tokens, 3800);
    }

    #[test]
    fn test_read_usage_sums_across_multiple_files() {
        let tmp = tempfile::tempdir().unwrap();
        let since = Utc::now() - TimeDelta::hours(1);
        let ts = Utc::now().to_rfc3339();
        write_project_file(
            tmp.path(),
            "/tmp/repo",
            "a.jsonl",
            &transcript_line(&ts, "msg_1", "req_1", "claude-fable-5"),
        );
        write_project_file(
            tmp.path(),
            "/tmp/repo",
            "b.jsonl",
            &transcript_line(&ts, "msg_2", "req_2", "claude-fable-5"),
        );

        let usage = read_usage(tmp.path(), "/tmp/repo", since, &RateOverrides::default()).unwrap();
        assert_eq!(usage.input_tokens, 2000);
    }
}