aptu-core 0.8.3

Core library for Aptu - OSS issue triage with AI assistance
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
// SPDX-License-Identifier: Apache-2.0

//! Local contribution history tracking.
//!
//! Stores contribution records in `~/.local/share/aptu/history.json`.
//! Each contribution tracks repo, issue, action, timestamp, and status.

use std::fs;
use std::path::PathBuf;

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

use crate::config::data_dir;

// ETU weight constants. These are the structural Anthropic cache pricing ratios;
// they belong here alongside AiStats rather than in the provider layer.
const ETU_WEIGHT_INPUT: f64 = 1.0;
/// Cache-read tokens cost 0.1× input price (90% discount). Stable since Claude 3.
const ETU_WEIGHT_CACHE_READ: f64 = 0.1;
/// Cache-write tokens cost 1.25× input price (5-min TTL). Confirmed May 2026.
const ETU_WEIGHT_CACHE_WRITE: f64 = 1.25;
/// Output tokens cost 5× input price across all current models. Stable since Claude 3.
const ETU_WEIGHT_OUTPUT: f64 = 5.0;

/// Compute Effective Token Units from raw token counts.
///
/// ETU = 1.0·input + 0.1·`cache_read` + 1.25·`cache_write` + 5.0·output
///
/// Weights are structural Anthropic cache pricing ratios (not per-model prices),
/// stable across all model generations since Claude 3. No pricing table needed.
#[allow(clippy::cast_precision_loss)]
pub(crate) fn compute_etu(input: u64, cache_read: u64, cache_write: u64, output: u64) -> f64 {
    ETU_WEIGHT_INPUT * input as f64
        + ETU_WEIGHT_CACHE_READ * cache_read as f64
        + ETU_WEIGHT_CACHE_WRITE * cache_write as f64
        + ETU_WEIGHT_OUTPUT * output as f64
}

/// AI usage statistics for a contribution.
#[derive(Debug, Clone, Default, Serialize, PartialEq)]
pub struct AiStats {
    /// Provider name (e.g., "openrouter", "anthropic").
    pub provider: String,
    /// Model used for analysis.
    pub model: String,
    /// Number of input tokens.
    pub input_tokens: u64,
    /// Number of output tokens.
    pub output_tokens: u64,
    /// Duration of the API call in milliseconds.
    pub duration_ms: u64,
    /// Cost in USD (from `OpenRouter` API, `None` if not reported).
    #[serde(default)]
    pub cost_usd: Option<f64>,
    /// Fallback provider used if primary failed (None if primary succeeded).
    #[serde(default)]
    pub fallback_provider: Option<String>,
    /// Prompt size in characters.
    #[serde(default)]
    pub prompt_chars: usize,
    /// Number of cache read tokens (from Anthropic API).
    #[serde(default)]
    pub cache_read_tokens: u64,
    /// Number of cache write tokens (from Anthropic API).
    #[serde(default)]
    pub cache_write_tokens: u64,
    /// Effective Token Units: a normalized throughput signal comparable across operations.
    /// Computed via [`compute_etu`]; see that function for the formula and weight rationale.
    #[serde(default)]
    pub effective_token_units: f64,
    /// Trace ID for correlating with context records (optional, not serialized if None).
    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trace_id: Option<String>,
}

impl AiStats {
    /// Recompute and set `effective_token_units` from the current token counts.
    ///
    /// Call at the end of any construction chain to ensure ETU stays consistent
    /// with the token fields rather than being set manually at each site.
    #[must_use]
    pub fn with_computed_etu(mut self) -> Self {
        self.effective_token_units = compute_etu(
            self.input_tokens,
            self.cache_read_tokens,
            self.cache_write_tokens,
            self.output_tokens,
        );
        self
    }
}

impl<'de> Deserialize<'de> for AiStats {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[derive(Deserialize)]
        struct Helper {
            #[serde(default)]
            provider: String,
            #[serde(default)]
            model: String,
            #[serde(default)]
            input_tokens: u64,
            #[serde(default)]
            output_tokens: u64,
            #[serde(default)]
            duration_ms: u64,
            #[serde(default)]
            cost_usd: Option<f64>,
            #[serde(default)]
            fallback_provider: Option<String>,
            #[serde(default)]
            prompt_chars: usize,
            #[serde(default)]
            cache_read_tokens: u64,
            #[serde(default)]
            cache_write_tokens: u64,
            /// Ignored on deserialise; recomputed in the From impl.
            #[serde(default)]
            #[allow(dead_code)]
            effective_token_units: f64,
            #[serde(default)]
            trace_id: Option<String>,
        }

        let h = Helper::deserialize(deserializer)?;
        Ok(AiStats {
            provider: h.provider,
            model: h.model,
            input_tokens: h.input_tokens,
            output_tokens: h.output_tokens,
            duration_ms: h.duration_ms,
            cost_usd: h.cost_usd,
            fallback_provider: h.fallback_provider,
            prompt_chars: h.prompt_chars,
            cache_read_tokens: h.cache_read_tokens,
            cache_write_tokens: h.cache_write_tokens,
            effective_token_units: 0.0,
            trace_id: h.trace_id,
        }
        .with_computed_etu())
    }
}

/// Status of a contribution.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum ContributionStatus {
    /// Contribution submitted, awaiting maintainer response.
    #[default]
    Pending,
    /// Maintainer accepted the contribution.
    Accepted,
    /// Maintainer rejected the contribution.
    Rejected,
}

/// A single contribution record.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Contribution {
    /// Unique identifier.
    pub id: Uuid,
    /// Repository in "owner/repo" format.
    pub repo: String,
    /// Issue number.
    pub issue: u64,
    /// Action type (e.g., "triage").
    pub action: String,
    /// When the contribution was made.
    pub timestamp: DateTime<Utc>,
    /// URL to the posted comment.
    pub comment_url: String,
    /// Current status of the contribution.
    #[serde(default)]
    pub status: ContributionStatus,
    /// AI usage statistics for this contribution.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ai_stats: Option<AiStats>,
}

/// Container for all contribution history.
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct HistoryData {
    /// List of contributions.
    pub contributions: Vec<Contribution>,
}

impl HistoryData {
    /// Calculate total tokens used across all contributions.
    #[must_use]
    pub fn total_tokens(&self) -> u64 {
        self.contributions
            .iter()
            .filter_map(|c| c.ai_stats.as_ref())
            .map(|stats| stats.input_tokens + stats.output_tokens)
            .sum()
    }

    /// Calculate total cost in USD across all contributions.
    #[must_use]
    pub fn total_cost(&self) -> f64 {
        self.contributions
            .iter()
            .filter_map(|c| c.ai_stats.as_ref())
            .filter_map(|stats| stats.cost_usd)
            .sum()
    }

    /// Calculate average tokens per triage.
    #[must_use]
    #[allow(clippy::cast_precision_loss)]
    pub fn avg_tokens_per_triage(&self) -> f64 {
        let contributions_with_stats: Vec<_> = self
            .contributions
            .iter()
            .filter_map(|c| c.ai_stats.as_ref())
            .collect();

        if contributions_with_stats.is_empty() {
            return 0.0;
        }

        let total: u64 = contributions_with_stats
            .iter()
            .map(|stats| stats.input_tokens + stats.output_tokens)
            .sum();

        total as f64 / contributions_with_stats.len() as f64
    }

    /// Calculate total cost grouped by model.
    #[must_use]
    pub fn cost_by_model(&self) -> std::collections::HashMap<String, f64> {
        let mut costs = std::collections::HashMap::new();

        for contribution in &self.contributions {
            if let Some(stats) = &contribution.ai_stats
                && let Some(cost) = stats.cost_usd
            {
                *costs.entry(stats.model.clone()).or_insert(0.0) += cost;
            }
        }

        costs
    }
}

/// Returns the path to the history file.
#[must_use]
pub fn history_file_path() -> PathBuf {
    data_dir().join("history.json")
}

/// Load contribution history from disk.
///
/// Returns empty history if file doesn't exist.
pub fn load() -> Result<HistoryData> {
    let path = history_file_path();

    if !path.exists() {
        return Ok(HistoryData::default());
    }

    let contents = fs::read_to_string(&path)
        .with_context(|| format!("Failed to read history file: {}", path.display()))?;

    let data: HistoryData = serde_json::from_str(&contents)
        .with_context(|| format!("Failed to parse history file: {}", path.display()))?;

    Ok(data)
}

/// Save contribution history to disk.
///
/// Creates parent directories if they don't exist.
pub fn save(data: &HistoryData) -> Result<()> {
    let path = history_file_path();

    // Create parent directories if needed
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)
            .with_context(|| format!("Failed to create directory: {}", parent.display()))?;
    }

    let contents =
        serde_json::to_string_pretty(data).context("Failed to serialize history data")?;

    fs::write(&path, contents)
        .with_context(|| format!("Failed to write history file: {}", path.display()))?;

    Ok(())
}

/// Add a contribution to history.
///
/// Loads existing history, appends the new contribution, and saves.
pub fn add_contribution(contribution: Contribution) -> Result<()> {
    let mut data = load()?;
    data.contributions.push(contribution);
    save(&data)?;
    Ok(())
}

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

    /// Create a test contribution.
    fn test_contribution() -> Contribution {
        Contribution {
            id: Uuid::new_v4(),
            repo: "owner/repo".to_string(),
            issue: 123,
            action: "triage".to_string(),
            timestamp: Utc::now(),
            comment_url: "https://github.com/owner/repo/issues/123#issuecomment-1".to_string(),
            status: ContributionStatus::Pending,
            ai_stats: None,
        }
    }

    #[test]
    fn test_contribution_serialization_roundtrip() {
        let contribution = test_contribution();
        let json = serde_json::to_string(&contribution).expect("serialize");
        let parsed: Contribution = serde_json::from_str(&json).expect("deserialize");

        assert_eq!(contribution.id, parsed.id);
        assert_eq!(contribution.repo, parsed.repo);
        assert_eq!(contribution.issue, parsed.issue);
        assert_eq!(contribution.action, parsed.action);
        assert_eq!(contribution.comment_url, parsed.comment_url);
        assert_eq!(contribution.status, parsed.status);
    }

    #[test]
    fn test_history_data_serialization_roundtrip() {
        let data = HistoryData {
            contributions: vec![test_contribution(), test_contribution()],
        };

        let json = serde_json::to_string_pretty(&data).expect("serialize");
        let parsed: HistoryData = serde_json::from_str(&json).expect("deserialize");

        assert_eq!(parsed.contributions.len(), 2);
    }

    #[test]
    fn test_contribution_status_default() {
        let status = ContributionStatus::default();
        assert_eq!(status, ContributionStatus::Pending);
    }

    #[test]
    fn test_contribution_status_serialization() {
        assert_eq!(
            serde_json::to_string(&ContributionStatus::Pending).unwrap(),
            "\"pending\""
        );
        assert_eq!(
            serde_json::to_string(&ContributionStatus::Accepted).unwrap(),
            "\"accepted\""
        );
        assert_eq!(
            serde_json::to_string(&ContributionStatus::Rejected).unwrap(),
            "\"rejected\""
        );
    }

    #[test]
    fn test_empty_history_default() {
        let data = HistoryData::default();
        assert!(data.contributions.is_empty());
    }

    #[test]
    fn test_ai_stats_serialization_roundtrip() {
        let stats = AiStats {
            provider: "openrouter".to_string(),
            model: "mistralai/mistral-small-2603".to_string(),
            input_tokens: 1000,
            output_tokens: 500,
            duration_ms: 1500,
            cost_usd: Some(0.0),
            fallback_provider: None,
            prompt_chars: 0,
            cache_read_tokens: 0,
            cache_write_tokens: 0,
            effective_token_units: 0.0,
            trace_id: None,
        };

        let json = serde_json::to_string(&stats).expect("serialize");
        let parsed: AiStats = serde_json::from_str(&json).expect("deserialize");

        // After deserialization, ETU is always recomputed from token counts,
        // so we compare all fields except effective_token_units.
        assert_eq!(stats.provider, parsed.provider);
        assert_eq!(stats.model, parsed.model);
        assert_eq!(stats.input_tokens, parsed.input_tokens);
        assert_eq!(stats.output_tokens, parsed.output_tokens);
        assert_eq!(stats.duration_ms, parsed.duration_ms);
        assert_eq!(stats.cost_usd, parsed.cost_usd);
        assert_eq!(stats.fallback_provider, parsed.fallback_provider);
        assert_eq!(stats.prompt_chars, parsed.prompt_chars);
        assert_eq!(stats.cache_read_tokens, parsed.cache_read_tokens);
        assert_eq!(stats.cache_write_tokens, parsed.cache_write_tokens);
        assert_eq!(stats.trace_id, parsed.trace_id);
        // ETU must be recomputed: 1000 input + 500*5 output = 3500.0
        assert!((parsed.effective_token_units - 3500.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_contribution_with_ai_stats() {
        let mut contribution = test_contribution();
        contribution.ai_stats = Some(AiStats {
            provider: "openrouter".to_string(),
            model: "mistralai/mistral-small-2603".to_string(),
            input_tokens: 1000,
            output_tokens: 500,
            duration_ms: 1500,
            cost_usd: Some(0.0),
            fallback_provider: None,
            prompt_chars: 0,
            cache_read_tokens: 0,
            cache_write_tokens: 0,
            effective_token_units: 0.0,
            trace_id: None,
        });

        let json = serde_json::to_string(&contribution).expect("serialize");
        let parsed: Contribution = serde_json::from_str(&json).expect("deserialize");

        assert!(parsed.ai_stats.is_some());
        assert_eq!(
            parsed.ai_stats.unwrap().model,
            "mistralai/mistral-small-2603"
        );
    }

    #[test]
    fn test_contribution_without_ai_stats_backward_compat() {
        let json = r#"{
            "id": "550e8400-e29b-41d4-a716-446655440000",
            "repo": "owner/repo",
            "issue": 123,
            "action": "triage",
            "timestamp": "2024-01-01T00:00:00Z",
            "comment_url": "https://github.com/owner/repo/issues/123#issuecomment-1",
            "status": "pending"
        }"#;

        let parsed: Contribution = serde_json::from_str(json).expect("deserialize");
        assert!(parsed.ai_stats.is_none());
    }

    #[test]
    fn test_total_tokens() {
        let mut data = HistoryData::default();

        let mut c1 = test_contribution();
        c1.ai_stats = Some(AiStats {
            provider: "openrouter".to_string(),
            model: "model1".to_string(),
            input_tokens: 100,
            output_tokens: 50,
            duration_ms: 1000,
            cost_usd: Some(0.01),
            fallback_provider: None,
            prompt_chars: 0,
            cache_read_tokens: 0,
            cache_write_tokens: 0,
            effective_token_units: 0.0,
            trace_id: None,
        });

        let mut c2 = test_contribution();
        c2.ai_stats = Some(AiStats {
            provider: "openrouter".to_string(),
            model: "model2".to_string(),
            input_tokens: 200,
            output_tokens: 100,
            duration_ms: 2000,
            cost_usd: Some(0.02),
            fallback_provider: None,
            prompt_chars: 0,
            cache_read_tokens: 0,
            cache_write_tokens: 0,
            effective_token_units: 0.0,
            trace_id: None,
        });

        data.contributions.push(c1);
        data.contributions.push(c2);
        data.contributions.push(test_contribution()); // No stats

        assert_eq!(data.total_tokens(), 450);
    }

    #[test]
    fn test_total_cost() {
        let mut data = HistoryData::default();

        let mut c1 = test_contribution();
        c1.ai_stats = Some(AiStats {
            provider: "openrouter".to_string(),
            model: "model1".to_string(),
            input_tokens: 100,
            output_tokens: 50,
            duration_ms: 1000,
            cost_usd: Some(0.01),
            fallback_provider: None,
            prompt_chars: 0,
            cache_read_tokens: 0,
            cache_write_tokens: 0,
            effective_token_units: 0.0,
            trace_id: None,
        });

        let mut c2 = test_contribution();
        c2.ai_stats = Some(AiStats {
            provider: "openrouter".to_string(),
            model: "model2".to_string(),
            input_tokens: 200,
            output_tokens: 100,
            duration_ms: 2000,
            cost_usd: Some(0.02),
            fallback_provider: None,
            prompt_chars: 0,
            cache_read_tokens: 0,
            cache_write_tokens: 0,
            effective_token_units: 0.0,
            trace_id: None,
        });

        data.contributions.push(c1);
        data.contributions.push(c2);

        assert!((data.total_cost() - 0.03).abs() < f64::EPSILON);
    }

    #[test]
    fn test_avg_tokens_per_triage() {
        let mut data = HistoryData::default();

        let mut c1 = test_contribution();
        c1.ai_stats = Some(AiStats {
            provider: "openrouter".to_string(),
            model: "model1".to_string(),
            input_tokens: 100,
            output_tokens: 50,
            duration_ms: 1000,
            cost_usd: Some(0.01),
            fallback_provider: None,
            prompt_chars: 0,
            cache_read_tokens: 0,
            cache_write_tokens: 0,
            effective_token_units: 0.0,
            trace_id: None,
        });

        let mut c2 = test_contribution();
        c2.ai_stats = Some(AiStats {
            provider: "openrouter".to_string(),
            model: "model2".to_string(),
            input_tokens: 200,
            output_tokens: 100,
            duration_ms: 2000,
            cost_usd: Some(0.02),
            fallback_provider: None,
            prompt_chars: 0,
            cache_read_tokens: 0,
            cache_write_tokens: 0,
            effective_token_units: 0.0,
            trace_id: None,
        });

        data.contributions.push(c1);
        data.contributions.push(c2);

        assert!((data.avg_tokens_per_triage() - 225.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_avg_tokens_per_triage_empty() {
        let data = HistoryData::default();
        assert!((data.avg_tokens_per_triage() - 0.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_cost_by_model() {
        let mut data = HistoryData::default();

        let mut c1 = test_contribution();
        c1.ai_stats = Some(AiStats {
            provider: "openrouter".to_string(),
            model: "model1".to_string(),
            input_tokens: 100,
            output_tokens: 50,
            duration_ms: 1000,
            cost_usd: Some(0.01),
            fallback_provider: None,
            prompt_chars: 0,
            cache_read_tokens: 0,
            cache_write_tokens: 0,
            effective_token_units: 0.0,
            trace_id: None,
        });

        let mut c2 = test_contribution();
        c2.ai_stats = Some(AiStats {
            provider: "openrouter".to_string(),
            model: "model1".to_string(),
            input_tokens: 200,
            output_tokens: 100,
            duration_ms: 2000,
            cost_usd: Some(0.02),
            fallback_provider: None,
            prompt_chars: 0,
            cache_read_tokens: 0,
            cache_write_tokens: 0,
            effective_token_units: 0.0,
            trace_id: None,
        });

        let mut c3 = test_contribution();
        c3.ai_stats = Some(AiStats {
            provider: "openrouter".to_string(),
            model: "model2".to_string(),
            input_tokens: 150,
            output_tokens: 75,
            duration_ms: 1500,
            cost_usd: Some(0.015),
            fallback_provider: None,
            prompt_chars: 0,
            cache_read_tokens: 0,
            cache_write_tokens: 0,
            effective_token_units: 0.0,
            trace_id: None,
        });

        data.contributions.push(c1);
        data.contributions.push(c2);
        data.contributions.push(c3);

        let costs = data.cost_by_model();
        assert_eq!(costs.len(), 2);
        assert!((costs.get("model1").unwrap() - 0.03).abs() < f64::EPSILON);
        assert!((costs.get("model2").unwrap() - 0.015).abs() < f64::EPSILON);
    }

    #[test]
    fn test_ai_stats_cache_tokens_roundtrip() {
        let stats = AiStats {
            provider: "anthropic".to_string(),
            model: "claude-sonnet-4-6".to_string(),
            input_tokens: 1000,
            output_tokens: 500,
            duration_ms: 1500,
            cost_usd: Some(0.05),
            fallback_provider: None,
            prompt_chars: 5000,
            cache_read_tokens: 100,
            cache_write_tokens: 50,
            effective_token_units: 0.0,
            trace_id: None,
        };

        let json = serde_json::to_string(&stats).expect("serialize");
        let parsed: AiStats = serde_json::from_str(&json).expect("deserialize");

        // After deserialization, ETU is always recomputed from token counts,
        // so we compare all fields except effective_token_units.
        assert_eq!(stats.provider, parsed.provider);
        assert_eq!(stats.model, parsed.model);
        assert_eq!(stats.input_tokens, parsed.input_tokens);
        assert_eq!(stats.output_tokens, parsed.output_tokens);
        assert_eq!(stats.duration_ms, parsed.duration_ms);
        assert_eq!(stats.cost_usd, parsed.cost_usd);
        assert_eq!(stats.fallback_provider, parsed.fallback_provider);
        assert_eq!(stats.prompt_chars, parsed.prompt_chars);
        assert_eq!(stats.cache_read_tokens, 100);
        assert_eq!(stats.cache_write_tokens, 50);
        assert_eq!(parsed.cache_read_tokens, 100);
        assert_eq!(parsed.cache_write_tokens, 50);
        // ETU must be recomputed: 1000 input + 0.1*100 cache_read + 1.25*50 cache_write + 500*5 output = 3572.5
        assert!((parsed.effective_token_units - 3572.5).abs() < f64::EPSILON);
    }

    #[test]
    fn test_ai_stats_cache_tokens_default() {
        let json = r#"{
            "provider": "openrouter",
            "model": "mistralai/mistral-small-2603",
            "input_tokens": 1000,
            "output_tokens": 500,
            "duration_ms": 1500,
            "cost_usd": 0.0,
            "fallback_provider": null,
            "prompt_chars": 0
        }"#;

        let parsed: AiStats = serde_json::from_str(json).expect("deserialize");

        assert_eq!(parsed.cache_read_tokens, 0);
        assert_eq!(parsed.cache_write_tokens, 0);
    }

    #[test]
    fn test_etu_formula() {
        // All four token classes with non-trivial values.
        // input(1000) + cache_read(0.1*500=50) + cache_write(1.25*100=125) + output(5.0*200=1000) = 2175.0
        let stats = AiStats {
            input_tokens: 1000,
            output_tokens: 200,
            cache_read_tokens: 500,
            cache_write_tokens: 100,
            ..AiStats::default()
        }
        .with_computed_etu();
        assert!((stats.effective_token_units - 2175.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_etu_zero_on_default() {
        // Zero inputs produce zero ETU; also covers the serde default path.
        let stats = AiStats::default().with_computed_etu();
        assert_eq!(stats.effective_token_units, 0.0);
    }

    #[test]
    fn test_etu_recomputed_on_deserialize() {
        // A JSON record with a stale/wrong effective_token_units value.
        // After deserialization the field must be recomputed from token counts.
        let json = r#"{
            "provider": "anthropic",
            "model": "claude-sonnet-4-6",
            "input_tokens": 1000,
            "output_tokens": 200,
            "cache_read_tokens": 500,
            "cache_write_tokens": 100,
            "effective_token_units": 99999.0
        }"#;
        let stats: AiStats = serde_json::from_str(json).unwrap();
        // Must equal compute_etu(1000, 500, 100, 200) = 2175.0, not 99999.0
        assert!((stats.effective_token_units - 2175.0).abs() < f64::EPSILON);
    }
}