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
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
//! Read-only usage scan: total agent spend across *all* local history.
//!
//! Unlike [`super::projection`] (which covers pulpo-managed sessions), the scan reads every
//! Claude/Codex/pi session file on the machine and reports spend by agent and by repo — the
//! low-friction "what did my agents cost?" view. It needs no behavior change: it meters
//! sessions you ran however you ran them (raw terminal, another tool, cron), and unifies
//! Claude + Codex + pi into one report — the cross-agent view a single-vendor `/usage`
//! can't give.

use std::collections::HashMap;
use std::path::Path;

use chrono::{DateTime, TimeDelta, Utc};
use pulpo_common::api::{ScanRollup, UsageScanResponse};

use super::{ExactUsage, RateOverrides, ScanEntry, claude, codex, pi};

/// Total tokens across every dimension we track (matches the projection convention).
const fn exact_total_tokens(u: &ExactUsage) -> u64 {
    u.input_tokens + u.output_tokens + u.cache_write_tokens + u.cache_read_tokens
}

/// Fold `(tokens, cost)` into a `label -> (tokens, cost)` accumulator. Costs sum only where
/// present, so an unpriced (Codex / unknown-model) contribution leaves the total `None`.
fn accumulate(
    map: &mut HashMap<String, (u64, Option<f64>)>,
    label: String,
    tokens: u64,
    cost: Option<f64>,
) {
    let e = map.entry(label).or_insert((0, None));
    e.0 += tokens;
    if let Some(c) = cost {
        e.1 = Some(e.1.unwrap_or(0.0) + c);
    }
}

/// Turn a `label -> (tokens, cost)` map into sorted rollup rows (most expensive first).
///
/// Zero-token rows are dropped — agents record synthetic/no-token entries (Claude's
/// `<synthetic>` messages, model-less Codex rollouts) that would otherwise clutter the report.
fn into_rollups(map: HashMap<String, (u64, Option<f64>)>) -> Vec<ScanRollup> {
    let mut rows: Vec<ScanRollup> = map
        .into_iter()
        .filter(|(_, (tokens, _))| *tokens > 0)
        .map(|(label, (total_tokens, total_cost_usd))| ScanRollup {
            label,
            total_tokens,
            total_cost_usd,
        })
        .collect();
    sort_rollups(&mut rows);
    rows
}

/// Scan all local Claude + Codex + pi history into per-agent, per-model, and per-repo
/// rollups.
///
/// `window_days` limits the scan to the last N days (`None` = all-time). `resolve_repo` maps
/// each recorded working directory to the label it's grouped under: pass [`canonical_repo`]
/// to collapse git worktrees and subdirectories onto their origin repository (the default),
/// or the identity function to keep every directory distinct (`--by-worktree`). Resolution is
/// memoized so each distinct directory is resolved at most once.
pub fn scan_usage(
    dirs: &ScanDirs<'_>,
    rates: &RateOverrides,
    node_name: &str,
    now: DateTime<Utc>,
    window_days: Option<u32>,
    resolve_repo: impl Fn(&str) -> String,
) -> UsageScanResponse {
    // Window start: N days back, or the epoch for an all-time scan.
    let since = window_days.map_or_else(
        || DateTime::<Utc>::from_timestamp(0, 0).unwrap_or(now),
        |d| now - TimeDelta::days(i64::from(d)),
    );

    // Memoized directory -> group label, so a repo's worktrees only pay one git call each.
    let mut repo_cache: HashMap<String, String> = HashMap::new();
    let mut resolve = |cwd: String| -> String {
        if let Some(label) = repo_cache.get(&cwd) {
            return label.clone();
        }
        let label = resolve_repo(&cwd);
        repo_cache.insert(cwd, label.clone());
        label
    };

    let mut acc = ScanAccumulator::default();
    fold_claude(dirs.claude, since, rates, &mut resolve, &mut acc);
    fold_entries(
        "codex",
        codex::scan_rollouts(dirs.codex, since),
        &mut resolve,
        &mut acc,
    );
    fold_entries(
        "pi",
        pi::scan_sessions(dirs.pi, since),
        &mut resolve,
        &mut acc,
    );

    // Grand totals derive from the per-agent rows, so a new reader can't be forgotten
    // here; costs sum only where present (Codex contributes tokens but never cost).
    let total_tokens = acc.agents.values().map(|(tokens, _)| *tokens).sum();
    let total_cost_usd = acc
        .agents
        .values()
        .filter_map(|(_, cost)| *cost)
        .reduce(|a, b| a + b);

    UsageScanResponse {
        node_name: node_name.to_owned(),
        generated_at: now.to_rfc3339(),
        window_days,
        total_tokens,
        total_cost_usd,
        by_agent: into_rollups(acc.agents),
        by_model: into_rollups(acc.models),
        by_repo: into_rollups(acc.repos),
    }
}

/// The per-agent history directories the scan reads (typically `~/.claude`, `~/.codex`,
/// `~/.pi`). Named fields, because three same-typed paths are too easy to transpose.
#[derive(Clone, Copy)]
pub struct ScanDirs<'a> {
    pub claude: &'a Path,
    pub codex: &'a Path,
    pub pi: &'a Path,
}

/// Shared by-agent / by-repo / by-model accumulators the per-agent folds write into.
#[derive(Default)]
struct ScanAccumulator {
    agents: HashMap<String, (u64, Option<f64>)>,
    repos: HashMap<String, (u64, Option<f64>)>,
    models: HashMap<String, (u64, Option<f64>)>,
}

/// Claude: one project directory per repo; label by the recorded cwd when present.
fn fold_claude(
    claude_dir: &Path,
    since: DateTime<Utc>,
    rates: &RateOverrides,
    resolve: &mut impl FnMut(String) -> String,
    acc: &mut ScanAccumulator,
) {
    if let Ok(entries) = std::fs::read_dir(claude_dir.join("projects")) {
        for entry in entries.flatten() {
            let dir = entry.path();
            if !dir.is_dir() {
                continue;
            }
            let Some(d) = claude::read_usage_dir(&dir, since, rates) else {
                continue;
            };
            let tokens = exact_total_tokens(&d.usage);
            let cost = d.usage.cost_usd;
            accumulate(&mut acc.agents, "claude".into(), tokens, cost);
            let raw = d.cwd.unwrap_or_else(|| {
                dir.file_name()
                    .and_then(|n| n.to_str())
                    .unwrap_or("unknown")
                    .to_owned()
            });
            let repo = resolve(raw);
            accumulate(&mut acc.repos, repo, tokens, cost);
            for m in d.by_model {
                accumulate(&mut acc.models, m.model, m.tokens, m.cost_usd);
            }
        }
    }
}

/// Fold one agent's scan entries into the shared accumulators. `agent` labels the
/// by-agent row and stands in for entries without a model (model-less Codex rollouts).
fn fold_entries(
    agent: &str,
    entries: Vec<ScanEntry>,
    resolve: &mut impl FnMut(String) -> String,
    acc: &mut ScanAccumulator,
) {
    for entry in entries {
        accumulate(
            &mut acc.agents,
            agent.to_owned(),
            entry.tokens,
            entry.cost_usd,
        );
        let repo = resolve(entry.cwd);
        accumulate(&mut acc.repos, repo, entry.tokens, entry.cost_usd);
        let model = entry.model.unwrap_or_else(|| agent.to_owned());
        accumulate(&mut acc.models, model, entry.tokens, entry.cost_usd);
    }
}

/// Sort rollups most-expensive-first (priced before unpriced), then by tokens, then label.
fn sort_rollups(rollups: &mut [ScanRollup]) {
    rollups.sort_by(|a, b| {
        b.total_cost_usd
            .unwrap_or(-1.0)
            .partial_cmp(&a.total_cost_usd.unwrap_or(-1.0))
            .unwrap_or(std::cmp::Ordering::Equal)
            .then(b.total_tokens.cmp(&a.total_tokens))
            .then(a.label.cmp(&b.label))
    });
}

/// Resolve a working directory to its canonical repository root, collapsing git worktrees
/// and subdirectories onto the origin repo.
///
/// Every worktree of a repo shares one common git dir (`<origin>/.git`); its parent is the
/// origin root, and any subdirectory resolves there too. Falls back to the input path when
/// `cwd` isn't a git repo or `git` is unavailable, so non-repo directories stay distinct —
/// this is what makes per-repo spend mean "this repo" rather than "this checkout".
///
/// Real `git` invocation, hence coverage-excluded: the merge logic is covered with an
/// injected resolver, and this function is exercised against real worktrees in the
/// (non-coverage) test job.
#[cfg(not(coverage))]
pub(crate) fn canonical_repo(cwd: &str) -> String {
    use std::process::Command;
    let output = Command::new("git")
        .args([
            "-C",
            cwd,
            "rev-parse",
            "--path-format=absolute",
            "--git-common-dir",
        ])
        .output();
    if let Ok(output) = output
        && output.status.success()
    {
        let common = String::from_utf8_lossy(&output.stdout);
        if let Some(root) = Path::new(common.trim()).parent().and_then(Path::to_str)
            && !root.is_empty()
        {
            return root.to_owned();
        }
    }
    cwd.to_owned()
}

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

    fn claude_record(cwd: Option<&str>, model: &str, input: u64, output: u64) -> String {
        let ts = Utc::now().to_rfc3339();
        let cwd_field = cwd.map(|c| format!(r#""cwd":"{c}","#)).unwrap_or_default();
        format!(
            r#"{{"timestamp":"{ts}",{cwd_field}"requestId":"r1","type":"assistant","message":{{"id":"m1","model":"{model}","usage":{{"input_tokens":{input},"output_tokens":{output},"cache_read_input_tokens":0,"cache_creation_input_tokens":0}}}}}}"#
        )
    }

    fn write_claude_project(claude_dir: &Path, dir_name: &str, content: &str) {
        let d = claude_dir.join("projects").join(dir_name);
        fs::create_dir_all(&d).unwrap();
        fs::write(d.join("session.jsonl"), content).unwrap();
    }

    fn codex_rollout(cwd: &str, input: u64, cached: u64, output: u64) -> String {
        let meta = format!(
            r#"{{"timestamp":"2026-06-12T10:00:00Z","type":"session_meta","payload":{{"id":"abc","timestamp":"2026-06-12T10:00:00Z","cwd":"{cwd}","originator":"codex_cli_rs"}}}}"#
        );
        let tc = format!(
            r#"{{"timestamp":"2026-06-12T10:00:00Z","type":"event_msg","payload":{{"type":"token_count","info":{{"total_token_usage":{{"input_tokens":{input},"cached_input_tokens":{cached},"output_tokens":{output},"total_tokens":{}}}}}}}}}"#,
            input + output
        );
        format!("{meta}\n{tc}\n")
    }

    fn pi_session(cwd: &str, model: &str, input: u64, output: u64, cost: f64) -> String {
        let header = format!(
            r#"{{"type":"session","version":3,"id":"0197-abc","timestamp":"2026-06-12T10:00:00.000Z","cwd":"{cwd}"}}"#
        );
        let msg = format!(
            r#"{{"type":"message","id":"bbbb2222","parentId":null,"message":{{"role":"assistant","content":[],"model":"{model}","usage":{{"input":{input},"output":{output},"cacheRead":0,"cacheWrite":0,"totalTokens":{},"cost":{{"input":0.0,"output":0.0,"cacheRead":0.0,"cacheWrite":0.0,"total":{cost}}}}},"stopReason":"stop","timestamp":{}}}}}"#,
            input + output,
            Utc::now().timestamp_millis(),
        );
        format!("{header}\n{msg}\n")
    }

    fn write_pi_session(pi_dir: &Path, dir_name: &str, content: &str) {
        let d = pi_dir.join("agent").join("sessions").join(dir_name);
        fs::create_dir_all(&d).unwrap();
        fs::write(d.join("0197-abc.jsonl"), content).unwrap();
    }

    fn write_codex_rollout(codex_dir: &Path, name: &str, content: &str) {
        let d = codex_dir
            .join("sessions")
            .join("2026")
            .join("06")
            .join("12");
        fs::create_dir_all(&d).unwrap();
        fs::write(d.join(name), content).unwrap();
    }

    #[test]
    fn test_scan_empty_dirs() {
        let claude = tempfile::tempdir().unwrap();
        let codex = tempfile::tempdir().unwrap();
        let pi_dir = tempfile::tempdir().unwrap();
        let r = scan_usage(
            &ScanDirs {
                claude: claude.path(),
                codex: codex.path(),
                pi: pi_dir.path(),
            },
            &RateOverrides::default(),
            "n",
            Utc::now(),
            None,
            |s: &str| s.to_owned(),
        );
        assert_eq!(r.total_tokens, 0);
        assert!(r.by_agent.is_empty());
        assert!(r.by_repo.is_empty());
        assert_eq!(r.total_cost_usd, None);
    }

    #[test]
    fn test_scan_merges_agents_by_repo() {
        let claude = tempfile::tempdir().unwrap();
        let codex = tempfile::tempdir().unwrap();
        let pi_dir = tempfile::tempdir().unwrap();
        write_claude_project(
            claude.path(),
            "proj-api",
            &claude_record(Some("/repos/api"), "claude-opus-4-8", 1000, 500),
        );
        write_claude_project(
            claude.path(),
            "proj-web",
            &claude_record(Some("/repos/web"), "claude-opus-4-8", 200, 100),
        );
        // Codex also worked in /repos/api → must merge with Claude's /repos/api.
        write_codex_rollout(
            codex.path(),
            "rollout-2026-06-12-a.jsonl",
            &codex_rollout("/repos/api", 800, 0, 200),
        );

        // Identity resolver: each cwd stays its own row, but Claude+Codex /repos/api still
        // merge (same raw key) — this also exercises the resolver memo's cache-hit path.
        let r = scan_usage(
            &ScanDirs {
                claude: claude.path(),
                codex: codex.path(),
                pi: pi_dir.path(),
            },
            &RateOverrides::default(),
            "node-x",
            Utc::now(),
            None,
            |s: &str| s.to_owned(),
        );

        // Two agents present.
        assert_eq!(r.by_agent.len(), 2);
        // 1500 (claude api) + 300 (claude web) + 1000 (codex api).
        assert_eq!(r.total_tokens, 2800);
        // Cost only from Claude (opus $5/$25 per MTok), Codex contributes none.
        // 1000·5 + 500·25 + 200·5 + 100·25 = 21000 micro-dollars.
        let expected = 21_000.0 / 1_000_000.0;
        assert!((r.total_cost_usd.unwrap() - expected).abs() < 1e-9);

        // /repos/api merges both agents: 1500 + 1000 = 2500 tokens, and is the priciest → first.
        assert_eq!(r.by_repo[0].label, "/repos/api");
        assert_eq!(r.by_repo[0].total_tokens, 2500);
        let web = r.by_repo.iter().find(|x| x.label == "/repos/web").unwrap();
        assert_eq!(web.total_tokens, 300);

        // by_model: Claude opus priced (1800 tokens), Codex bucketed tokens-only (no model).
        assert_eq!(r.by_model.len(), 2);
        let opus = r
            .by_model
            .iter()
            .find(|m| m.label == "claude-opus-4-8")
            .unwrap();
        assert_eq!(opus.total_tokens, 1800);
        assert!(opus.total_cost_usd.unwrap() > 0.0);
        let codex = r.by_model.iter().find(|m| m.label == "codex").unwrap();
        assert_eq!(codex.total_tokens, 1000);
        assert!(codex.total_cost_usd.is_none());
        // Priced model sorts before the unpriced one.
        assert_eq!(r.by_model[0].label, "claude-opus-4-8");
    }

    #[test]
    fn test_scan_includes_pi_with_exact_cost_and_merges_repo() {
        let claude = tempfile::tempdir().unwrap();
        let codex = tempfile::tempdir().unwrap();
        let pi_dir = tempfile::tempdir().unwrap();
        // Claude and pi both worked in /repos/api → one merged repo row.
        write_claude_project(
            claude.path(),
            "proj-api",
            &claude_record(Some("/repos/api"), "claude-opus-4-8", 1000, 500),
        );
        write_pi_session(
            pi_dir.path(),
            "--repos-api--",
            &pi_session("/repos/api", "gemini-3-pro", 800, 200, 0.05),
        );

        let r = scan_usage(
            &ScanDirs {
                claude: claude.path(),
                codex: codex.path(),
                pi: pi_dir.path(),
            },
            &RateOverrides::default(),
            "n",
            Utc::now(),
            None,
            |s: &str| s.to_owned(),
        );

        // pi appears as its own agent with the exact cost it recorded.
        let pi_row = r.by_agent.iter().find(|a| a.label == "pi").unwrap();
        assert_eq!(pi_row.total_tokens, 1000);
        assert!((pi_row.total_cost_usd.unwrap() - 0.05).abs() < 1e-12);

        // Total cost = Claude's rate-table cost + pi's recorded cost.
        // Claude opus: 1000·5 + 500·25 = 17500 micro-dollars.
        let claude_cost = 17_500.0 / 1_000_000.0;
        assert!((r.total_cost_usd.unwrap() - (claude_cost + 0.05)).abs() < 1e-9);
        assert_eq!(r.total_tokens, 2500);

        // Both agents merge into the one repo row, cost included.
        assert_eq!(r.by_repo.len(), 1);
        assert_eq!(r.by_repo[0].label, "/repos/api");
        assert_eq!(r.by_repo[0].total_tokens, 2500);
        assert!((r.by_repo[0].total_cost_usd.unwrap() - (claude_cost + 0.05)).abs() < 1e-9);

        // pi's model shows up in the by-model rollup with its cost.
        let gem = r
            .by_model
            .iter()
            .find(|m| m.label == "gemini-3-pro")
            .unwrap();
        assert_eq!(gem.total_tokens, 1000);
        assert!((gem.total_cost_usd.unwrap() - 0.05).abs() < 1e-12);
    }

    #[test]
    fn test_scan_window_days_filters_old_records_and_sets_field() {
        let claude = tempfile::tempdir().unwrap();
        let codex = tempfile::tempdir().unwrap();
        let pi_dir = tempfile::tempdir().unwrap();
        // One recent Claude record and one 10 days old, both in the same project dir.
        let recent = Utc::now().to_rfc3339();
        let old = (Utc::now() - TimeDelta::days(10)).to_rfc3339();
        let line = |ts: &str, id: &str| {
            format!(
                r#"{{"timestamp":"{ts}","cwd":"/repos/api","requestId":"{id}","type":"assistant","message":{{"id":"{id}","model":"claude-opus-4-8","usage":{{"input_tokens":100,"output_tokens":0,"cache_read_input_tokens":0,"cache_creation_input_tokens":0}}}}}}"#
            )
        };
        write_claude_project(
            claude.path(),
            "proj-api",
            &format!("{}\n{}\n", line(&recent, "a"), line(&old, "b")),
        );

        // 3-day window: only the recent record counts.
        let r = scan_usage(
            &ScanDirs {
                claude: claude.path(),
                codex: codex.path(),
                pi: pi_dir.path(),
            },
            &RateOverrides::default(),
            "n",
            Utc::now(),
            Some(3),
            |s: &str| s.to_owned(),
        );
        assert_eq!(r.window_days, Some(3));
        assert_eq!(r.total_tokens, 100);

        // All-time: both records count.
        let all = scan_usage(
            &ScanDirs {
                claude: claude.path(),
                codex: codex.path(),
                pi: pi_dir.path(),
            },
            &RateOverrides::default(),
            "n",
            Utc::now(),
            None,
            |s: &str| s.to_owned(),
        );
        assert_eq!(all.window_days, None);
        assert_eq!(all.total_tokens, 200);
    }

    #[test]
    fn test_scan_skips_non_dir_and_empty_project_entries() {
        let claude = tempfile::tempdir().unwrap();
        let codex = tempfile::tempdir().unwrap();
        let pi_dir = tempfile::tempdir().unwrap();
        let projects = claude.path().join("projects");
        fs::create_dir_all(&projects).unwrap();
        // A stray file under projects/ (not a directory) is skipped.
        fs::write(projects.join("stray.txt"), "x").unwrap();
        // An empty project dir yields no records → read_usage_dir returns None → skipped.
        fs::create_dir_all(projects.join("empty-proj")).unwrap();

        let r = scan_usage(
            &ScanDirs {
                claude: claude.path(),
                codex: codex.path(),
                pi: pi_dir.path(),
            },
            &RateOverrides::default(),
            "n",
            Utc::now(),
            None,
            |s: &str| s.to_owned(),
        );
        assert_eq!(r.total_tokens, 0);
        assert!(r.by_agent.is_empty());
        assert!(r.by_model.is_empty());
    }

    #[test]
    fn test_scan_drops_zero_token_model_rows() {
        let claude = tempfile::tempdir().unwrap();
        let codex = tempfile::tempdir().unwrap();
        let pi_dir = tempfile::tempdir().unwrap();
        let ts = Utc::now().to_rfc3339();
        // One real record and one synthetic 0-token record (distinct ids → not deduped).
        let line = |model: &str, id: &str, input: u64| {
            format!(
                r#"{{"timestamp":"{ts}","cwd":"/repos/api","requestId":"{id}","type":"assistant","message":{{"id":"{id}","model":"{model}","usage":{{"input_tokens":{input},"output_tokens":0,"cache_read_input_tokens":0,"cache_creation_input_tokens":0}}}}}}"#
            )
        };
        write_claude_project(
            claude.path(),
            "proj-api",
            &format!(
                "{}\n{}\n",
                line("claude-opus-4-8", "a", 100),
                line("<synthetic>", "b", 0)
            ),
        );
        let r = scan_usage(
            &ScanDirs {
                claude: claude.path(),
                codex: codex.path(),
                pi: pi_dir.path(),
            },
            &RateOverrides::default(),
            "n",
            Utc::now(),
            None,
            |s: &str| s.to_owned(),
        );
        // The 0-token synthetic model is dropped; only the real model remains.
        assert_eq!(r.by_model.len(), 1);
        assert_eq!(r.by_model[0].label, "claude-opus-4-8");
    }

    #[test]
    fn test_scan_falls_back_to_dir_name_without_cwd() {
        let claude = tempfile::tempdir().unwrap();
        let codex = tempfile::tempdir().unwrap();
        let pi_dir = tempfile::tempdir().unwrap();
        // No cwd in the record → label is the (sanitized) project dir name.
        write_claude_project(
            claude.path(),
            "-Users-x-repo",
            &claude_record(None, "claude-opus-4-8", 10, 5),
        );
        let r = scan_usage(
            &ScanDirs {
                claude: claude.path(),
                codex: codex.path(),
                pi: pi_dir.path(),
            },
            &RateOverrides::default(),
            "n",
            Utc::now(),
            None,
            |s: &str| s.to_owned(),
        );
        assert_eq!(r.by_repo.len(), 1);
        assert_eq!(r.by_repo[0].label, "-Users-x-repo");
    }

    #[test]
    fn test_scan_collapses_worktrees_via_resolver() {
        let claude = tempfile::tempdir().unwrap();
        let codex = tempfile::tempdir().unwrap();
        let pi_dir = tempfile::tempdir().unwrap();
        // The repo itself and a worktree of it, as two separate Claude project dirs.
        write_claude_project(
            claude.path(),
            "proj-main",
            &claude_record(Some("/repos/api"), "claude-opus-4-8", 1000, 0),
        );
        write_claude_project(
            claude.path(),
            "proj-wt",
            &claude_record(Some("/repos/api-worktrees/feat"), "claude-opus-4-8", 500, 0),
        );
        // Codex worked in a subdirectory of the same repo.
        write_codex_rollout(
            codex.path(),
            "rollout-2026-06-12-a.jsonl",
            &codex_rollout("/repos/api/src", 200, 0, 0),
        );

        // Resolver standing in for `canonical_repo`: everything under the repo collapses.
        let resolve = |cwd: &str| {
            if cwd.starts_with("/repos/api") {
                "/repos/api".to_owned()
            } else {
                cwd.to_owned()
            }
        };
        let r = scan_usage(
            &ScanDirs {
                claude: claude.path(),
                codex: codex.path(),
                pi: pi_dir.path(),
            },
            &RateOverrides::default(),
            "n",
            Utc::now(),
            None,
            resolve,
        );

        // All three checkouts collapse into a single repo row.
        assert_eq!(r.by_repo.len(), 1);
        assert_eq!(r.by_repo[0].label, "/repos/api");
        assert_eq!(r.by_repo[0].total_tokens, 1700);
    }

    /// Exercises the real git-backed resolver in the (non-coverage) test job.
    #[cfg(not(coverage))]
    #[test]
    fn test_canonical_repo_collapses_worktree_and_subdir() {
        use std::process::Command;
        let tmp = tempfile::tempdir().unwrap();
        let repo = tmp.path().join("origin");
        fs::create_dir_all(&repo).unwrap();
        let git = |args: &[&str], dir: &Path| {
            let ok = Command::new("git")
                .args(args)
                .current_dir(dir)
                .output()
                .unwrap()
                .status
                .success();
            assert!(ok, "git {args:?} failed");
        };
        git(&["init", "-q"], &repo);
        git(&["config", "user.email", "t@t"], &repo);
        git(&["config", "user.name", "t"], &repo);
        fs::write(repo.join("f"), "x").unwrap();
        git(&["add", "-A"], &repo);
        git(&["commit", "-qm", "init"], &repo);

        // A subdirectory and a linked worktree both resolve to the same origin root.
        let sub = repo.join("src");
        fs::create_dir_all(&sub).unwrap();
        let wt = tmp.path().join("wt");
        git(&["worktree", "add", "-q", wt.to_str().unwrap()], &repo);

        let root = canonical_repo(repo.to_str().unwrap());
        assert_eq!(canonical_repo(sub.to_str().unwrap()), root);
        assert_eq!(canonical_repo(wt.to_str().unwrap()), root);

        // A non-git directory stays itself.
        let plain = tmp.path().join("plain");
        fs::create_dir_all(&plain).unwrap();
        assert_eq!(
            canonical_repo(plain.to_str().unwrap()),
            plain.to_str().unwrap()
        );
    }
}