warden-cli 0.1.1

A local, read-only CLI that analyzes your coding agent's session logs and turns that analysis into skills, slash commands, and prompts.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
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
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
//! The named reports and the rollup behind `warden query`.
//!
//! Every report in here is a pure consumer of [`crate::store::Scanner`] — none
//! of them opens an event file itself. A report's whole job is
//! to turn a window of events into a [`Report`]; whether that reaches a terminal
//! or a harness is [`crate::output`]'s problem.
//!
//! Three honesty rules are enforced here rather than in each report:
//!
//! - A figure warden cannot derive is [`Cell::Unsupported`], never `0`.
//! - An absent token count means "not applicable on this record", because usage
//!   is logged once per request and repeated on no sibling. Summing treats it as
//!   contributing nothing, and [`Notes`] says how many records carried usage.
//! - Anything that would make a number differ from what a user sees elsewhere —
//!   sidechain events, unpriced models, skipped lines — becomes a note.

pub mod compare;
pub mod files;
pub mod models;
pub mod projects;
pub mod query;
pub mod sessions;
pub mod summary;
pub mod tools;

use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::io;

use chrono::{TimeZone, Utc};
use serde_json::{Map, Value};

use crate::cli::TimeWindow;
use crate::config::{Pricing, TokenCounts};
use crate::output::{Cell, Report};
use crate::store::{Event, ScanQuery, Scanner};

/// The model name Claude Code writes for records it synthesized itself. It is
/// not a model anyone is billed for, so it is counted in volume and excluded
/// from cost (see [`Cost::add`]).
pub const SYNTHETIC_MODEL: &str = "<synthetic>";

/// The named reports, in their documented order.
pub const NAMES: [&str; 7] = [
    "summary", "projects", "models", "sessions", "tools", "compare", "files",
];

/// Everything a report is given besides the scanner.
#[derive(Debug, Clone)]
pub struct ReportCtx {
    pub window: TimeWindow,
    pub project: Option<String>,
    /// Sidechain (subagent) events are real spend and are included by default.
    pub include_sidechain: bool,
    /// The price table as it is *now*. Cost is derived at read time from this
    /// and the event's stored token counts, so editing `config.toml` re-prices
    /// the existing store without a re-ingest.
    pub pricing: Pricing,
}

impl ReportCtx {
    pub fn new(window: TimeWindow, project: Option<String>, include_sidechain: bool) -> Self {
        Self {
            window,
            project,
            include_sidechain,
            pricing: Pricing::default(),
        }
    }

    /// Price this run from the user's config. Without it the price table is
    /// empty and every cost falls back to what was stored at ingest.
    pub fn with_pricing(mut self, pricing: Pricing) -> Self {
        self.pricing = pricing;
        self
    }

    /// The same context over a different window, for `compare`.
    pub fn with_window(&self, window: TimeWindow) -> Self {
        Self {
            window,
            ..self.clone()
        }
    }

    fn scan_query(&self) -> ScanQuery {
        ScanQuery::new(self.window).with_project(self.project.clone())
    }
}

/// A report by name.
pub type Builder = fn(&Scanner, &ReportCtx) -> Result<Report, ReportError>;

/// Resolve a report name, listing the valid ones when it is not one.
pub fn resolve(name: &str) -> Result<Builder, ReportError> {
    match name {
        "summary" => Ok(summary::build),
        "projects" => Ok(projects::build),
        "models" => Ok(models::build),
        "sessions" => Ok(sessions::build),
        "tools" => Ok(tools::build),
        "compare" => Ok(compare::build),
        "files" => Ok(files::build),
        other => Err(ReportError::Unknown(other.to_string())),
    }
}

/// Build a named report end to end.
pub fn run(scanner: &Scanner, name: &str, ctx: &ReportCtx) -> Result<Report, ReportError> {
    resolve(name)?(scanner, ctx)
}

#[derive(Debug)]
pub enum ReportError {
    /// No such report. Carries the name so the message can list the real ones.
    Unknown(String),
    /// The report is meaningless without a bounded period (`compare`).
    NeedsWindow(&'static str),
    /// `--group-by` named a dimension that does not exist.
    UnknownDimension(String),
    Io(io::Error),
}

impl fmt::Display for ReportError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ReportError::Unknown(name) => write!(
                f,
                "unknown report {:?}: expected one of {}",
                name,
                NAMES.join(", ")
            ),
            ReportError::NeedsWindow(name) => write!(
                f,
                "report {name} compares a period against the one before it, so it needs a bounded \
                 period: pass --since (e.g. --since 7d)"
            ),
            ReportError::UnknownDimension(dim) => write!(
                f,
                "unknown --group-by dimension {:?}: expected one of {}",
                dim,
                query::DIMENSIONS.join(", ")
            ),
            ReportError::Io(err) => write!(f, "{err}"),
        }
    }
}

impl std::error::Error for ReportError {}

impl From<io::Error> for ReportError {
    fn from(err: io::Error) -> Self {
        ReportError::Io(err)
    }
}

/// A completed scan, with the observations every report turns into notes.
pub struct Scanned {
    pub events: Vec<Event>,
    pub notes: Notes,
}

/// Read the window through the one shared scanner.
pub fn scan(scanner: &Scanner, ctx: &ReportCtx) -> Result<Scanned, ReportError> {
    let mut events = Vec::new();
    let mut notes = Notes::new(ctx.include_sidechain, ctx.pricing.clone());
    let stats = scanner.scan_with(&ctx.scan_query(), |event| {
        if event.is_sidechain == Some(true) {
            notes.sidechain_events += 1;
            if !ctx.include_sidechain {
                return;
            }
        }
        notes.observe(&event);
        events.push(event);
    })?;
    notes.lines_skipped = stats.lines_skipped;
    Ok(Scanned { events, notes })
}

/// Running cost for one bucket.
///
/// `priced` and `unpriced` are counted separately so a bucket whose model has no
/// configured rate renders as `–` instead of `$0.00`.
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct Cost {
    pub total: f64,
    /// Events that carried usage and a configured price.
    pub priced: u64,
    /// Events that carried usage but whose model has no configured price.
    pub unpriced: u64,
}

impl Cost {
    fn add(&mut self, event: &Event, pricing: &Pricing) {
        self.add_share(event, pricing, 1.0);
    }

    /// Add `share` of this event's cost — the whole of it for a bucket that owns
    /// the event, a fraction for `report files`, which splits a turn across the
    /// files it touched. The priced/unpriced counters are per event either way,
    /// so a partially-priced bucket is flagged the same however it was built.
    fn add_share(&mut self, event: &Event, pricing: &Pricing, share: f64) {
        if !event.has_usage() || event.model.as_deref() == Some(SYNTHETIC_MODEL) {
            return;
        }
        match event_cost(event, pricing) {
            Some(cost) => {
                self.total += cost * share;
                self.priced += 1;
            }
            None => self.unpriced += 1,
        }
    }

    fn merge(&mut self, other: Cost) {
        self.total += other.total;
        self.priced += other.priced;
        self.unpriced += other.unpriced;
    }

    /// True when part of this bucket's spend could not be priced. The total is
    /// then a floor, not a total, and must not be printed as if it were one.
    pub fn is_partial(&self) -> bool {
        self.priced > 0 && self.unpriced > 0
    }

    /// `–` when nothing in this bucket could be priced, `~+` when only some of
    /// it could, otherwise a plain estimate.
    pub fn cell(&self) -> Cell {
        if self.priced == 0 {
            Cell::Unsupported
        } else if self.is_partial() {
            Cell::money_partial(self.total)
        } else {
            Cell::money_est(self.total)
        }
    }

    /// `null` rather than `0` when nothing could be priced.
    pub fn json(&self) -> Value {
        if self.priced == 0 {
            Value::Null
        } else {
            serde_json::json!(round_money(self.total))
        }
    }
}

/// What one event cost, priced from the current config.
///
/// The config wins; `cost_est` on the record is a cache, used only when the
/// config has no rate for that model. That is what makes editing `config.toml`
/// take effect without a re-ingest, while keeping the JSONL self-describing for
/// `jq` users. `None` — never `0.0` — when neither can price it.
pub fn event_cost(event: &Event, pricing: &Pricing) -> Option<f64> {
    let model = event.model.as_deref()?;
    pricing
        .estimate_cost(
            &event.provider,
            model,
            TokenCounts {
                input: event.input_tok,
                output: event.output_tok,
                cache_read: event.cache_read_tok,
                cache_write: event.cache_write_tok,
            },
        )
        .or(event.cost_est)
}

/// Everything summed for one bucket of events.
#[derive(Debug, Clone, Default)]
pub struct Totals {
    /// Events in the bucket, whether or not they carried usage.
    pub events: u64,
    /// Events that carried usage — i.e. billable requests.
    pub requests: u64,
    pub input: u64,
    pub output: u64,
    pub cache_read: u64,
    pub cache_write: u64,
    pub cost: Cost,
    pub sessions: BTreeSet<String>,
    pub first_ts: Option<i64>,
    pub last_ts: Option<i64>,
}

impl Totals {
    pub fn add(&mut self, event: &Event, pricing: &Pricing) {
        self.events += 1;
        if event.has_usage() {
            self.requests += 1;
        }
        self.input += event.input_tok.unwrap_or(0);
        self.output += event.output_tok.unwrap_or(0);
        self.cache_read += event.cache_read_tok.unwrap_or(0);
        self.cache_write += event.cache_write_tok.unwrap_or(0);
        self.cost.add(event, pricing);
        if let Some(session) = &event.session_id {
            self.sessions.insert(session.clone());
        }
        self.first_ts = Some(self.first_ts.map_or(event.ts, |ts| ts.min(event.ts)));
        self.last_ts = Some(self.last_ts.map_or(event.ts, |ts| ts.max(event.ts)));
    }

    pub fn merge(&mut self, other: &Totals) {
        self.events += other.events;
        self.requests += other.requests;
        self.input += other.input;
        self.output += other.output;
        self.cache_read += other.cache_read;
        self.cache_write += other.cache_write;
        self.cost.merge(other.cost);
        self.sessions.extend(other.sessions.iter().cloned());
        self.first_ts = min_opt(self.first_ts, other.first_ts);
        self.last_ts = max_opt(self.last_ts, other.last_ts);
    }

    pub fn total_tokens(&self) -> u64 {
        self.input + self.output + self.cache_read + self.cache_write
    }

    /// The four columns every report ends with: in, out, cache read, cost.
    pub fn tail_cells(&self) -> Vec<Cell> {
        vec![
            count(self.input),
            count(self.output),
            count(self.cache_read),
            self.cost.cell(),
        ]
    }

    /// The token fields, written into a JSON row.
    pub fn write_json(&self, row: &mut Map<String, Value>) {
        row.insert("requests".into(), serde_json::json!(self.requests));
        row.insert("input_tok".into(), serde_json::json!(self.input));
        row.insert("output_tok".into(), serde_json::json!(self.output));
        row.insert("cache_read_tok".into(), serde_json::json!(self.cache_read));
        row.insert(
            "cache_write_tok".into(),
            serde_json::json!(self.cache_write),
        );
        row.insert("cost_est".into(), self.cost.json());
        // A harness must be able to tell a total from a floor without parsing
        // the notes: `cost_est` covers `cost_priced_requests` of the
        // `cost_priced_requests + cost_unpriced_requests` billable requests here.
        row.insert(
            "cost_partial".into(),
            serde_json::json!(self.cost.is_partial()),
        );
        row.insert(
            "cost_priced_requests".into(),
            serde_json::json!(self.cost.priced),
        );
        row.insert(
            "cost_unpriced_requests".into(),
            serde_json::json!(self.cost.unpriced),
        );
    }
}

fn min_opt(a: Option<i64>, b: Option<i64>) -> Option<i64> {
    match (a, b) {
        (Some(a), Some(b)) => Some(a.min(b)),
        (a, b) => a.or(b),
    }
}

fn max_opt(a: Option<i64>, b: Option<i64>) -> Option<i64> {
    match (a, b) {
        (Some(a), Some(b)) => Some(a.max(b)),
        (a, b) => a.or(b),
    }
}

/// Bucket events by a key. `None` from `key` drops the event from the rollup.
pub fn rollup<K, F>(events: &[Event], pricing: &Pricing, key: F) -> BTreeMap<K, Totals>
where
    K: Ord,
    F: Fn(&Event) -> Option<K>,
{
    let mut buckets: BTreeMap<K, Totals> = BTreeMap::new();
    for event in events {
        if let Some(k) = key(event) {
            buckets.entry(k).or_default().add(event, pricing);
        }
    }
    buckets
}

/// The label for a bucket whose events recorded no working directory. Those
/// events are still real spend, so they get a row rather than being dropped —
/// under one spelling, because `projects` explains it in a note and `sessions`
/// prints it.
pub const NO_PROJECT: &str = "(no project)";

/// Descending float compare. `Ordering::Equal` for a NaN — a weight that cannot
/// be compared must not reorder the rows around it.
pub fn desc(a: f64, b: f64) -> std::cmp::Ordering {
    b.partial_cmp(&a).unwrap_or(std::cmp::Ordering::Equal)
}

/// Heaviest bucket first, ties broken by key so output is deterministic.
pub fn by_weight_desc<K: Ord + Clone>(buckets: BTreeMap<K, Totals>) -> Vec<(K, Totals)> {
    let mut rows: Vec<(K, Totals)> = buckets.into_iter().collect();
    rows.sort_by(|a, b| {
        b.1.total_tokens()
            .cmp(&a.1.total_tokens())
            .then_with(|| a.0.cmp(&b.0))
    });
    rows
}

/// A count cell, saturating rather than wrapping on an implausible total.
pub fn count(n: u64) -> Cell {
    Cell::Int(i64::try_from(n).unwrap_or(i64::MAX))
}

/// `2026-08-04` in UTC. The store is UTC throughout, so days are too.
pub fn day_of(ts_ms: i64) -> Option<String> {
    Utc.timestamp_millis_opt(ts_ms)
        .single()
        .map(|dt| dt.format("%Y-%m-%d").to_string())
}

/// `1h12m`, `4m`, `12s` — a wall-clock span, for `sessions`.
pub fn format_span(ms: i64) -> String {
    let secs = ms.max(0) / 1000;
    let (h, m, s) = (secs / 3600, (secs % 3600) / 60, secs % 60);
    if h > 0 {
        format!("{h}h{m:02}m")
    } else if m > 0 {
        format!("{m}m{s:02}s")
    } else {
        format!("{s}s")
    }
}

/// Money is compared and diffed as a float but published at cent precision.
pub fn round_money(amount: f64) -> f64 {
    (amount * 100.0).round() / 100.0
}

/// Long ids are unreadable in a table; JSON keeps them whole.
pub fn short_id(id: &str) -> String {
    match id.char_indices().nth(8) {
        Some((idx, _)) => format!("{}", &id[..idx]),
        None => id.to_string(),
    }
}

/// The observations that become a report's `notes`.
///
/// Notes exist so a number a user cannot reconcile against what their agent
/// showed them is explained rather than merely printed.
#[derive(Debug, Clone)]
pub struct Notes {
    include_sidechain: bool,
    pub sidechain_events: u64,
    pub lines_skipped: u64,
    pricing: Pricing,
    unpriced_models: BTreeSet<String>,
    synthetic_events: u64,
    events: u64,
    requests: u64,
    extra: Vec<String>,
}

impl Notes {
    fn new(include_sidechain: bool, pricing: Pricing) -> Self {
        Self {
            include_sidechain,
            sidechain_events: 0,
            lines_skipped: 0,
            pricing,
            unpriced_models: BTreeSet::new(),
            synthetic_events: 0,
            events: 0,
            requests: 0,
            extra: Vec::new(),
        }
    }

    fn observe(&mut self, event: &Event) {
        self.events += 1;
        if !event.has_usage() {
            return;
        }
        self.requests += 1;
        if event.model.as_deref() == Some(SYNTHETIC_MODEL) {
            self.synthetic_events += 1;
        } else if event_cost(event, &self.pricing).is_none() {
            self.unpriced_models.insert(
                event
                    .model
                    .clone()
                    .unwrap_or_else(|| "(unknown model)".into()),
            );
        }
    }

    /// Add a report-specific note, kept ahead of the shared ones.
    pub fn push(&mut self, note: impl Into<String>) {
        self.extra.push(note.into());
    }

    /// Merge another window's observations in (`compare` scans twice).
    ///
    /// Destructured rather than field-by-field on purpose: a new observation
    /// added to `Notes` fails to compile here until it says how it merges,
    /// instead of being silently dropped from every `compare`.
    pub fn merge(&mut self, other: &Notes) {
        let Notes {
            // Both windows are scanned through one context, so these are the
            // same on either side and the left-hand copy stands.
            include_sidechain: _,
            pricing: _,
            // Report-specific notes belong to the report, which pushes them
            // once after merging; a merged pair would print them twice.
            extra: _,
            sidechain_events,
            lines_skipped,
            unpriced_models,
            synthetic_events,
            events,
            requests,
        } = other;
        self.sidechain_events += sidechain_events;
        self.lines_skipped += lines_skipped;
        self.unpriced_models.extend(unpriced_models.iter().cloned());
        self.synthetic_events += synthetic_events;
        self.events += events;
        self.requests += requests;
    }

    /// The full note list, report-specific notes first.
    pub fn finish(&self) -> Vec<String> {
        let mut notes = self.extra.clone();

        if self.events > 0 {
            notes.push(format!(
                "usage is recorded once per request: {} of {} events carry token counts, and the \
                 rest contribute nothing rather than zero",
                self.requests, self.events
            ));
        }

        if self.sidechain_events > 0 {
            notes.push(if self.include_sidechain {
                format!(
                    "includes {} sidechain (subagent) events — real spend, but counted in no \
                     per-session figure your agent shows you, so these totals will read higher; \
                     pass --no-sidechain to exclude them",
                    self.sidechain_events
                )
            } else {
                format!(
                    "excludes {} sidechain (subagent) events (--no-sidechain); they are real \
                     spend, so these totals understate it",
                    self.sidechain_events
                )
            });
        }

        if !self.unpriced_models.is_empty() {
            notes.push(format!(
                "no configured price for {} — their spend is in no est. cost figure here: a row \
                 with nothing else in it is blank rather than 0, and a row that also has priced \
                 models is marked ~+ and understates its cost; add rates under \
                 [pricing.<provider>] in config.toml and rerun (no re-ingest needed)",
                self.unpriced_models
                    .iter()
                    .cloned()
                    .collect::<Vec<_>>()
                    .join(", ")
            ));
        }

        if self.synthetic_events > 0 {
            notes.push(format!(
                "{} events report the model as {SYNTHETIC_MODEL}, a placeholder the agent writes \
                 for records it generated itself; their tokens are counted and their cost is not, \
                 because nobody is billed for them",
                self.synthetic_events
            ));
        }

        if self.lines_skipped > 0 {
            notes.push(format!(
                "skipped {} unreadable line(s) in the store (a torn final line, or schema drift)",
                self.lines_skipped
            ));
        }

        notes.push("cost figures are estimates".into());
        notes
    }
}

#[cfg(test)]
pub(crate) mod testkit {
    use crate::store::{Event, StorePaths, StoreWriter, ToolCall};
    use chrono::{TimeZone, Utc};

    pub fn ms(y: i32, mo: u32, d: u32, h: u32) -> i64 {
        Utc.with_ymd_and_hms(y, mo, d, h, 0, 0)
            .unwrap()
            .timestamp_millis()
    }

    /// An assistant event carrying usage.
    pub fn used(id: &str, ts: i64, project: &str, model: &str, input: u64, output: u64) -> Event {
        let mut event = Event::new(id, ts, "claude-code", "anthropic", "assistant");
        event.project = Some(project.into());
        event.model = Some(model.into());
        event.session_id = Some(format!("session-{project}"));
        event.input_tok = Some(input);
        event.output_tok = Some(output);
        event.cache_read_tok = Some(input * 10);
        event.cache_write_tok = Some(0);
        event
    }

    pub fn priced(mut event: Event, cost: f64) -> Event {
        event.cost_est = Some(cost);
        event
    }

    pub fn with_tools(mut event: Event, targets: &[(&str, &str)]) -> Event {
        event.tool_calls = targets
            .iter()
            .map(|(name, target)| ToolCall::new(*name, Some((*target).to_string())))
            .collect();
        event
    }

    pub fn store(events: &[Event]) -> (tempfile::TempDir, StorePaths) {
        let dir = tempfile::tempdir().unwrap();
        let paths = StorePaths::new(dir.path());
        let mut writer = StoreWriter::open(paths.clone()).unwrap();
        for event in events {
            writer.append_event(event).unwrap();
        }
        (dir, paths)
    }
}

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

    fn ctx() -> ReportCtx {
        ReportCtx::new(TimeWindow::all(), None, true)
    }

    #[test]
    fn unknown_report_lists_the_valid_names() {
        let err = resolve("costs").unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("unknown report \"costs\""), "{msg}");
        for name in NAMES {
            assert!(msg.contains(name), "{msg} is missing {name}");
        }
    }

    #[test]
    fn every_documented_name_resolves() {
        for name in NAMES {
            assert!(resolve(name).is_ok(), "{name}");
        }
    }

    #[test]
    fn an_unpriced_bucket_is_unsupported_not_zero() {
        let mut totals = Totals::default();
        totals.add(
            &used("a", 0, "p", "claude-opus-5", 10, 10),
            &Pricing::default(),
        );
        assert_eq!(totals.cost.cell(), Cell::Unsupported);
        assert_eq!(totals.cost.json(), Value::Null);

        // Mixing an unpriced event with a priced one gives a figure that is
        // real but incomplete: marked `~+`, never passed off as a total.
        totals.add(
            &priced(used("b", 0, "p", "claude-opus-5", 10, 10), 0.5),
            &Pricing::default(),
        );
        assert!(totals.cost.is_partial());
        assert_eq!(totals.cost.cell(), Cell::money_partial(0.5));
        assert_eq!(totals.cost.json(), serde_json::json!(0.5));

        let mut row = Map::new();
        totals.write_json(&mut row);
        assert_eq!(row["cost_partial"], serde_json::json!(true));
        assert_eq!(row["cost_priced_requests"], serde_json::json!(1));
        assert_eq!(row["cost_unpriced_requests"], serde_json::json!(1));

        // Everything priced: a plain estimate again.
        let mut whole = Totals::default();
        whole.add(
            &priced(used("c", 0, "p", "claude-opus-5", 10, 10), 0.5),
            &Pricing::default(),
        );
        assert!(!whole.cost.is_partial());
        assert_eq!(whole.cost.cell(), Cell::money_est(0.5));
    }

    /// Finding 2: cost comes from the config at *read* time, so a rate added
    /// after ingest applies without re-ingesting, and the stored `cost_est` is
    /// only a fallback.
    #[test]
    fn config_pricing_wins_over_the_cached_cost_est() {
        let config: crate::config::Config = toml::from_str(
            r#"
[pricing.anthropic]
"claude-opus-5" = { input = 15.0, output = 75.0, cache_read = 1.5 }
"#,
        )
        .unwrap();
        let pricing = config.pricing();

        // 1M in, 1M out, 10M cache read (testkit sets cache_read = input * 10).
        let event = used("a", 0, "p", "claude-opus-5", 1_000_000, 1_000_000);
        let cost = event_cost(&event, &pricing).unwrap();
        assert!((cost - (15.0 + 75.0 + 15.0)).abs() < 1e-9, "got {cost}");

        // A stale ingest-time figure is ignored while the config can price it.
        let stale = priced(event.clone(), 999.0);
        assert_eq!(event_cost(&stale, &pricing), Some(cost));

        // No configured rate: the cached figure, then nothing — never 0.0.
        let empty = Pricing::default();
        assert_eq!(event_cost(&stale, &empty), Some(999.0));
        assert_eq!(event_cost(&event, &empty), None);
    }

    #[test]
    fn a_model_the_config_cannot_price_stays_none_not_zero() {
        let config: crate::config::Config = toml::from_str(
            r#"
[pricing.anthropic]
"claude-sonnet-5" = { input = 3.0, output = 15.0, cache_read = 0.3 }
"#,
        )
        .unwrap();
        let mut totals = Totals::default();
        totals.add(
            &used("a", 0, "p", "claude-opus-5", 10, 10),
            &config.pricing(),
        );
        assert_eq!(totals.cost.priced, 0);
        assert_eq!(totals.cost.unpriced, 1);
        assert_eq!(totals.cost.cell(), Cell::Unsupported);
        assert_eq!(totals.cost.json(), Value::Null);
    }

    #[test]
    fn records_without_usage_contribute_nothing_but_are_still_counted() {
        let mut totals = Totals::default();
        totals.add(&used("a", 0, "p", "m", 100, 20), &Pricing::default());
        let mut sibling = Event::new("b", 0, "claude-code", "anthropic", "assistant");
        sibling.session_id = Some("session-p".into());
        totals.add(&sibling, &Pricing::default());

        assert_eq!(totals.events, 2);
        assert_eq!(totals.requests, 1, "usage is counted once per request");
        assert_eq!(totals.input, 100);
        assert_eq!(totals.sessions.len(), 1);
    }

    #[test]
    fn synthetic_is_counted_in_tokens_and_excluded_from_cost() {
        let mut totals = Totals::default();
        totals.add(
            &priced(used("a", 0, "p", SYNTHETIC_MODEL, 10, 5), 9.99),
            &Pricing::default(),
        );
        assert_eq!(totals.input, 10);
        assert_eq!(
            totals.cost,
            Cost::default(),
            "no cost accrues to {SYNTHETIC_MODEL}"
        );
        assert_eq!(totals.cost.cell(), Cell::Unsupported);
    }

    #[test]
    fn sidechain_events_are_included_by_default_and_always_noted() {
        let mut sidechain = used("s", ms(2026, 8, 4, 9), "p", "m", 5, 5);
        sidechain.is_sidechain = Some(true);
        let (_dir, paths) = store(&[used("a", ms(2026, 8, 4, 8), "p", "m", 10, 10), sidechain]);
        let scanner = Scanner::new(paths);

        let scanned = scan(&scanner, &ctx()).unwrap();
        assert_eq!(scanned.events.len(), 2);
        assert!(scanned
            .notes
            .finish()
            .iter()
            .any(|n| n.contains("includes 1 sidechain")));

        let excluded = scan(&scanner, &ReportCtx::new(TimeWindow::all(), None, false)).unwrap();
        assert_eq!(excluded.events.len(), 1);
        assert!(excluded
            .notes
            .finish()
            .iter()
            .any(|n| n.contains("excludes 1 sidechain")));
    }

    #[test]
    fn unpriced_models_are_named_in_the_notes() {
        let (_dir, paths) = store(&[used("a", ms(2026, 8, 4, 8), "p", "claude-opus-5", 10, 10)]);
        let notes = scan(&Scanner::new(paths), &ctx()).unwrap().notes.finish();
        assert!(
            notes
                .iter()
                .any(|n| n.contains("no configured price for claude-opus-5")),
            "{notes:?}"
        );
        assert!(notes.iter().any(|n| n == "cost figures are estimates"));
    }

    #[test]
    fn spans_and_ids_are_readable() {
        assert_eq!(format_span(0), "0s");
        assert_eq!(format_span(45_000), "45s");
        assert_eq!(format_span(4 * 60_000 + 5_000), "4m05s");
        assert_eq!(format_span(72 * 60_000), "1h12m");
        assert_eq!(short_id("0123456789abcdef"), "01234567…");
        assert_eq!(short_id("short"), "short");
    }

    #[test]
    fn days_are_utc() {
        assert_eq!(day_of(ms(2026, 8, 4, 23)).unwrap(), "2026-08-04");
    }
}