clawft-core 0.6.11

Core engine for clawft (agent loop, message bus, context management)
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
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
//! Cost tracking and budget enforcement for the TieredRouter.
//!
//! Provides per-user daily and monthly cost tracking with configurable budget
//! limits and automatic time-based resets. The [`CostTracker`] is the budget
//! gatekeeper called by `TieredRouter` (Phase C) at routing time.
//!
//! Thread safety: all public methods take `&self` and use interior mutability
//! via [`std::sync::RwLock`]. The struct is `Send + Sync` by construction.
//!
//! # Atomic Budget Reservation (FIX-07)
//!
//! The [`CostTracker::reserve_budget`] method atomically checks all budget
//! dimensions and reserves the estimated cost within a single write-lock
//! acquisition. This prevents TOCTOU race conditions where two concurrent
//! threads could both pass a budget check before either records the spend.
//!
//! # Persistence (FIX-12)
//!
//! Cost state can be persisted to disk as JSON. On Unix, the persistence
//! file is set to mode 0600 (owner read/write only) to protect user IDs
//! and spend amounts from other system users.

use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::RwLock;

use serde::{Deserialize, Serialize};
use tracing::debug;

use crate::pipeline::traits::{BudgetResult, CostTrackable};

// ── UserSpend ───────────────────────────────────────────────────────────

/// Internal per-user spend tracking with reservation support.
///
/// Tracks both committed spend (from reconciled actual costs) and reserved
/// spend (from pending LLM calls whose actual cost is not yet known).
/// Budget checks consider `spent + reserved` to prevent over-allocation.
#[derive(Debug, Clone, Serialize, Deserialize)]
struct UserSpend {
    /// Committed daily spend in USD.
    daily_spent: f64,
    /// Committed monthly spend in USD.
    monthly_spent: f64,
    /// Reserved (pending) daily amount in USD.
    daily_reserved: f64,
    /// Reserved (pending) monthly amount in USD.
    monthly_reserved: f64,
    /// Timestamp of last daily reset.
    last_daily_reset: chrono::DateTime<chrono::Utc>,
    /// Timestamp of last monthly reset.
    last_monthly_reset: chrono::DateTime<chrono::Utc>,
}

impl UserSpend {
    /// Create a new zero-spend entry with the current timestamp.
    fn new() -> Self {
        let now = chrono::Utc::now();
        Self {
            daily_spent: 0.0,
            monthly_spent: 0.0,
            daily_reserved: 0.0,
            monthly_reserved: 0.0,
            last_daily_reset: now,
            last_monthly_reset: now,
        }
    }

    /// Effective daily total (committed + reserved).
    fn daily_effective(&self) -> f64 {
        self.daily_spent + self.daily_reserved
    }

    /// Effective monthly total (committed + reserved).
    fn monthly_effective(&self) -> f64 {
        self.monthly_spent + self.monthly_reserved
    }
}

// ── CostSnapshot ────────────────────────────────────────────────────────

/// Serializable snapshot of cost tracking state for persistence.
#[derive(Debug, Clone, Serialize, Deserialize)]
struct CostSnapshot {
    /// Per-user spend data, keyed by sender_id.
    spends: HashMap<String, UserSpend>,
    /// UTC hour used for daily resets when this snapshot was taken.
    reset_hour_utc: u8,
}

// ── CostTracker ─────────────────────────────────────────────────────────

/// Tracks per-user cost accumulation for budget enforcement.
///
/// Thread-safe via [`RwLock`]. All public methods take `&self`.
///
/// Persistence is best-effort -- a crash may lose recent operations.
/// The loss direction is always under-counting (safe side: users get
/// slightly more budget than intended, never less).
pub struct CostTracker {
    /// Per-user spend tracking. Key is `sender_id` at the API boundary.
    spends: RwLock<HashMap<String, UserSpend>>,
    /// Hour (UTC, 0-23) at which daily budgets reset.
    reset_hour_utc: u8,
    /// Whether to persist to disk.
    persistence_enabled: bool,
    /// Path for the persistence file.
    persistence_path: Option<PathBuf>,
}

impl CostTracker {
    /// Create a new cost tracker with the given daily reset hour.
    ///
    /// `reset_hour_utc` must be 0-23; values >= 24 are clamped to 0.
    pub fn new(reset_hour_utc: u8) -> Self {
        Self {
            spends: RwLock::new(HashMap::new()),
            reset_hour_utc: if reset_hour_utc < 24 {
                reset_hour_utc
            } else {
                0
            },
            persistence_enabled: false,
            persistence_path: None,
        }
    }

    /// Enable persistence at the given path.
    ///
    /// Builder-style method for chaining: `CostTracker::new(0).with_persistence(path)`.
    pub fn with_persistence(mut self, path: PathBuf) -> Self {
        self.persistence_enabled = true;
        self.persistence_path = Some(path);
        self
    }

    // ── Budget reservation (FIX-07) ─────────────────────────────────

    /// Atomically check and reserve budget.
    ///
    /// Acquires a write lock, checks all budget dimensions, and if within
    /// limits, reserves the estimated cost against the user's daily and
    /// monthly totals. On failure, no spend is recorded.
    ///
    /// This replaces the separate check + record pattern to prevent TOCTOU
    /// race conditions. A limit of `0.0` means unlimited (that dimension
    /// is not checked).
    ///
    /// Check order:
    /// 1. Daily limit
    /// 2. Monthly limit
    ///
    /// On success ([`BudgetResult::Approved`]), the estimated cost is
    /// reserved. The caller MUST NOT call [`record_estimated`] separately.
    /// After the LLM response arrives, call [`reconcile_actual`] to adjust.
    pub fn reserve_budget(
        &self,
        sender_id: &str,
        estimated_cost_usd: f64,
        user_daily_limit: f64,
        user_monthly_limit: f64,
    ) -> BudgetResult {
        if estimated_cost_usd <= 0.0 {
            return BudgetResult::Approved;
        }

        let mut spends = self.spends.write().expect("cost tracker lock poisoned");
        let entry = spends
            .entry(sender_id.to_string())
            .or_insert_with(UserSpend::new);

        // Reset counters if a time boundary has been crossed.
        self.maybe_reset_entry(entry);

        // Check daily limit (0.0 = unlimited).
        if user_daily_limit > 0.0 {
            let effective = entry.daily_effective();
            if effective + estimated_cost_usd > user_daily_limit {
                return BudgetResult::DailyLimitExceeded {
                    spent: effective,
                    limit: user_daily_limit,
                };
            }
        }

        // Check monthly limit (0.0 = unlimited).
        if user_monthly_limit > 0.0 {
            let effective = entry.monthly_effective();
            if effective + estimated_cost_usd > user_monthly_limit {
                return BudgetResult::MonthlyLimitExceeded {
                    spent: effective,
                    limit: user_monthly_limit,
                };
            }
        }

        // All checks passed -- commit the reservation.
        entry.daily_reserved += estimated_cost_usd;
        entry.monthly_reserved += estimated_cost_usd;

        BudgetResult::Approved
    }

    /// Adjust a previous reservation after the actual LLM cost is known.
    ///
    /// Moves the estimated cost from `reserved` to `spent`, then adjusts
    /// spent by the delta between actual and estimated. The net effect:
    /// - reserved decreases by estimated_cost
    /// - spent increases by actual_cost
    ///
    /// Per-user spend is clamped to 0.0 minimum.
    pub fn reconcile_actual(
        &self,
        sender_id: &str,
        estimated_cost_usd: f64,
        actual_cost_usd: f64,
    ) {
        let mut spends = self.spends.write().expect("cost tracker lock poisoned");
        let entry = spends
            .entry(sender_id.to_string())
            .or_insert_with(UserSpend::new);

        // Remove reservation.
        entry.daily_reserved = (entry.daily_reserved - estimated_cost_usd).max(0.0);
        entry.monthly_reserved = (entry.monthly_reserved - estimated_cost_usd).max(0.0);

        // Add actual cost to committed spend.
        entry.daily_spent = (entry.daily_spent + actual_cost_usd).max(0.0);
        entry.monthly_spent = (entry.monthly_spent + actual_cost_usd).max(0.0);
    }

    // ── Non-reserving budget check ──────────────────────────────────

    /// Read-only budget check (no reservation).
    ///
    /// Useful for display or pre-check purposes. For the router hot path,
    /// use [`reserve_budget`] instead to avoid TOCTOU races.
    pub fn check_budget(
        &self,
        sender_id: &str,
        estimated_cost_usd: f64,
        user_daily_limit: f64,
        user_monthly_limit: f64,
    ) -> BudgetResult {
        if estimated_cost_usd <= 0.0 {
            return BudgetResult::Approved;
        }

        let mut spends = self.spends.write().expect("cost tracker lock poisoned");
        let entry = spends
            .entry(sender_id.to_string())
            .or_insert_with(UserSpend::new);

        self.maybe_reset_entry(entry);

        // Check daily.
        if user_daily_limit > 0.0 {
            let effective = entry.daily_effective();
            if effective + estimated_cost_usd > user_daily_limit {
                return BudgetResult::DailyLimitExceeded {
                    spent: effective,
                    limit: user_daily_limit,
                };
            }
        }

        // Check monthly.
        if user_monthly_limit > 0.0 {
            let effective = entry.monthly_effective();
            if effective + estimated_cost_usd > user_monthly_limit {
                return BudgetResult::MonthlyLimitExceeded {
                    spent: effective,
                    limit: user_monthly_limit,
                };
            }
        }

        BudgetResult::Approved
    }

    // ── Legacy recording interface ──────────────────────────────────

    /// Record estimated cost (legacy interface).
    ///
    /// Prefer [`reserve_budget`] in the router hot path, which atomically
    /// checks and reserves. This method is retained for backward
    /// compatibility and the `CostTrackable` trait.
    pub fn record_estimated(&self, sender_id: &str, estimated_cost: f64) {
        if estimated_cost <= 0.0 {
            return;
        }

        let mut spends = self.spends.write().expect("cost tracker lock poisoned");
        let entry = spends
            .entry(sender_id.to_string())
            .or_insert_with(UserSpend::new);

        self.maybe_reset_entry(entry);

        entry.daily_spent += estimated_cost;
        entry.monthly_spent += estimated_cost;
    }

    /// Record actual cost, reconciling with a previous [`record_estimated`] call.
    ///
    /// Replaces the estimate in `spent` with the actual cost:
    /// `spent = spent - estimated + actual`.
    ///
    /// If the estimate was placed via [`reserve_budget`] instead (in `reserved`),
    /// use [`reconcile_actual`] directly.
    pub fn record_actual(&self, sender_id: &str, estimated_cost: f64, actual_cost: f64) {
        let mut spends = self.spends.write().expect("cost tracker lock poisoned");
        let entry = spends
            .entry(sender_id.to_string())
            .or_insert_with(UserSpend::new);

        // Remove previous estimate from committed spend, add actual.
        let delta = actual_cost - estimated_cost;
        entry.daily_spent = (entry.daily_spent + delta).max(0.0);
        entry.monthly_spent = (entry.monthly_spent + delta).max(0.0);
    }

    // ── Cost estimation helper ──────────────────────────────────────

    /// Estimate cost for a request based on tier pricing.
    ///
    /// Pure function. `cost_per_1k_tokens` is the blended $/1K rate,
    /// `estimated_tokens` is the total token count (input + output).
    pub fn estimate_cost(cost_per_1k_tokens: f64, estimated_tokens: usize) -> f64 {
        cost_per_1k_tokens * (estimated_tokens as f64) / 1000.0
    }

    // ── Spend queries ───────────────────────────────────────────────

    /// Get current spend for a user as `(daily_effective, monthly_effective)`.
    ///
    /// Returns `(0.0, 0.0)` if the user has no recorded spend.
    pub fn get_spend(&self, sender_id: &str) -> (f64, f64) {
        let spends = self.spends.read().expect("cost tracker lock poisoned");
        match spends.get(sender_id) {
            Some(entry) => (entry.daily_effective(), entry.monthly_effective()),
            None => (0.0, 0.0),
        }
    }

    // ── Persistence ─────────────────────────────────────────────────

    /// Persist current state to disk (if enabled).
    ///
    /// Uses atomic write (temp file + rename) to prevent corruption.
    /// Sets file permissions to 0o600 on Unix (FIX-12).
    pub fn persist(&self) -> std::io::Result<()> {
        let Some(ref path) = self.persistence_path else {
            return Ok(());
        };

        if !self.persistence_enabled {
            return Ok(());
        }

        // Ensure parent directory exists.
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)?;
        }

        let snapshot = {
            let spends = self.spends.read().expect("cost tracker lock poisoned");
            CostSnapshot {
                spends: spends.clone(),
                reset_hour_utc: self.reset_hour_utc,
            }
        };

        let json = serde_json::to_string_pretty(&snapshot)
            .map_err(std::io::Error::other)?;

        // Write to temp file then rename for atomic replacement.
        let tmp_path = path.with_extension("json.tmp");
        std::fs::write(&tmp_path, &json)?;
        std::fs::rename(&tmp_path, path)?;

        // FIX-12: Set restrictive permissions on the persistence file.
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let perms = std::fs::Permissions::from_mode(0o600);
            std::fs::set_permissions(path, perms)?;
        }

        debug!("saved cost tracking state to {}", path.display());
        Ok(())
    }

    /// Load state from disk into a new [`CostTracker`].
    ///
    /// If the file does not exist or is corrupt, returns an error.
    /// The caller can fall back to [`CostTracker::new`] in that case.
    pub fn load(path: &std::path::Path) -> std::io::Result<Self> {
        let data = std::fs::read_to_string(path)?;
        let snapshot: CostSnapshot = serde_json::from_str(&data)
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;

        let tracker = Self {
            spends: RwLock::new(snapshot.spends),
            reset_hour_utc: snapshot.reset_hour_utc,
            persistence_enabled: true,
            persistence_path: Some(path.to_path_buf()),
        };

        debug!("loaded cost tracking state from {}", path.display());
        Ok(tracker)
    }

    // ── Internal helpers ────────────────────────────────────────────

    /// Check and apply time-based resets to a single user's entry.
    ///
    /// Daily reset: when the current UTC day (adjusted by `reset_hour_utc`)
    /// differs from the entry's last reset day.
    /// Monthly reset: when the current UTC month differs from the entry's
    /// last reset month.
    fn maybe_reset_entry(&self, entry: &mut UserSpend) {
        let now = chrono::Utc::now();

        // Check monthly reset first (it implies daily reset).
        if self.should_reset_monthly(now, entry.last_monthly_reset) {
            debug!("resetting monthly cost counters");
            entry.daily_spent = 0.0;
            entry.daily_reserved = 0.0;
            entry.monthly_spent = 0.0;
            entry.monthly_reserved = 0.0;
            entry.last_daily_reset = now;
            entry.last_monthly_reset = now;
            return;
        }

        // Check daily reset.
        if self.should_reset_daily(now, entry.last_daily_reset) {
            debug!("resetting daily cost counters");
            entry.daily_spent = 0.0;
            entry.daily_reserved = 0.0;
            entry.last_daily_reset = now;
        }
    }

    /// Determine if a daily reset boundary has been crossed.
    ///
    /// Adjusts timestamps by `reset_hour_utc` so that "days" align with
    /// the configured reset hour rather than midnight.
    fn should_reset_daily(
        &self,
        now: chrono::DateTime<chrono::Utc>,
        last_reset: chrono::DateTime<chrono::Utc>,
    ) -> bool {
        let reset_offset = chrono::Duration::hours(self.reset_hour_utc as i64);
        let adjusted_now = now - reset_offset;
        let adjusted_last = last_reset - reset_offset;

        let day_now = adjusted_now.date_naive();
        let day_last = adjusted_last.date_naive();

        day_now > day_last
    }

    /// Determine if a monthly reset boundary has been crossed.
    fn should_reset_monthly(
        &self,
        now: chrono::DateTime<chrono::Utc>,
        last_reset: chrono::DateTime<chrono::Utc>,
    ) -> bool {
        use chrono::Datelike;
        (now.year(), now.month()) != (last_reset.year(), last_reset.month())
    }
}

impl std::fmt::Debug for CostTracker {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let user_count = self
            .spends
            .read()
            .map(|s| s.len())
            .unwrap_or(0);
        f.debug_struct("CostTracker")
            .field("users", &user_count)
            .field("reset_hour_utc", &self.reset_hour_utc)
            .field("persistence_enabled", &self.persistence_enabled)
            .field("persistence_path", &self.persistence_path)
            .finish()
    }
}

impl CostTrackable for CostTracker {
    fn check_budget(
        &self,
        sender_id: &str,
        estimated_cost: f64,
        daily_limit: f64,
        monthly_limit: f64,
    ) -> BudgetResult {
        CostTracker::check_budget(self, sender_id, estimated_cost, daily_limit, monthly_limit)
    }

    fn record_estimated(&self, sender_id: &str, estimated_cost: f64) {
        CostTracker::record_estimated(self, sender_id, estimated_cost);
    }

    fn record_actual(&self, sender_id: &str, estimated_cost: f64, actual_cost: f64) {
        CostTracker::record_actual(self, sender_id, estimated_cost, actual_cost);
    }
}

// ── Tests ───────────────────────────────────────────────────────────────

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

    // ── Helper ──────────────────────────────────────────────────────

    fn tracker() -> CostTracker {
        CostTracker::new(0)
    }

    // ── Basic reserve and check ─────────────────────────────────────

    #[test]
    fn reserve_budget_approved_within_limits() {
        let t = tracker();
        let result = t.reserve_budget("alice", 1.0, 5.0, 100.0);
        assert_eq!(result, BudgetResult::Approved);
    }

    #[test]
    fn check_budget_approved_within_limits() {
        let t = tracker();
        let result = t.check_budget("alice", 1.0, 5.0, 100.0);
        assert_eq!(result, BudgetResult::Approved);
    }

    // ── Daily limit exceeded ────────────────────────────────────────

    #[test]
    fn reserve_budget_daily_limit_exceeded() {
        let t = tracker();
        // Reserve 4.5 of 5.0 daily limit.
        assert_eq!(t.reserve_budget("alice", 4.5, 5.0, 100.0), BudgetResult::Approved);
        // Next 1.0 would exceed.
        let result = t.reserve_budget("alice", 1.0, 5.0, 100.0);
        assert!(matches!(result, BudgetResult::DailyLimitExceeded { .. }));
    }

    #[test]
    fn check_budget_daily_limit_exceeded_after_record() {
        let t = tracker();
        t.record_estimated("alice", 4.5);
        let result = t.check_budget("alice", 1.0, 5.0, 100.0);
        assert!(matches!(result, BudgetResult::DailyLimitExceeded { .. }));
    }

    // ── Monthly limit exceeded ──────────────────────────────────────

    #[test]
    fn reserve_budget_monthly_limit_exceeded() {
        let t = tracker();
        assert_eq!(t.reserve_budget("alice", 9.5, 20.0, 10.0), BudgetResult::Approved);
        let result = t.reserve_budget("alice", 1.0, 20.0, 10.0);
        assert!(matches!(result, BudgetResult::MonthlyLimitExceeded { .. }));
    }

    #[test]
    fn check_budget_monthly_limit_exceeded_after_record() {
        let t = tracker();
        t.record_estimated("alice", 99.5);
        let result = t.check_budget("alice", 1.0, 200.0, 100.0);
        assert!(matches!(result, BudgetResult::MonthlyLimitExceeded { .. }));
    }

    // ── Reserve then reconcile (lower actual) ───────────────────────

    #[test]
    fn reconcile_actual_lower_cost() {
        let t = tracker();
        assert_eq!(t.reserve_budget("alice", 3.00, 10.0, 100.0), BudgetResult::Approved);
        t.reconcile_actual("alice", 3.00, 2.00);
        let (daily, monthly) = t.get_spend("alice");
        // After reconcile: reserved removed (3.0), spent added (2.0).
        // effective daily = 2.0 + 0.0 = 2.0
        assert!((daily - 2.0).abs() < 1e-10);
        assert!((monthly - 2.0).abs() < 1e-10);
    }

    // ── Reserve then reconcile (higher actual) ──────────────────────

    #[test]
    fn reconcile_actual_higher_cost() {
        let t = tracker();
        assert_eq!(t.reserve_budget("alice", 2.00, 10.0, 100.0), BudgetResult::Approved);
        t.reconcile_actual("alice", 2.00, 3.50);
        let (daily, monthly) = t.get_spend("alice");
        // reserved removed (2.0), spent added (3.5). effective = 3.5
        assert!((daily - 3.5).abs() < 1e-10);
        assert!((monthly - 3.5).abs() < 1e-10);
    }

    // ── Multiple users independent tracking ─────────────────────────

    #[test]
    fn independent_user_tracking() {
        let t = tracker();
        t.record_estimated("alice", 3.0);
        t.record_estimated("bob", 7.0);
        t.record_estimated("alice", 2.0);

        let (alice_d, alice_m) = t.get_spend("alice");
        let (bob_d, bob_m) = t.get_spend("bob");

        assert!((alice_d - 5.0).abs() < 1e-10);
        assert!((alice_m - 5.0).abs() < 1e-10);
        assert!((bob_d - 7.0).abs() < 1e-10);
        assert!((bob_m - 7.0).abs() < 1e-10);
    }

    // ── Budget reset (daily) ────────────────────────────────────────

    #[test]
    fn daily_reset_boundary_detection() {
        let t = CostTracker::new(0);
        // Use a fixed noon timestamp to avoid flaking near midnight UTC.
        let now = chrono::DateTime::parse_from_rfc3339("2025-06-15T12:00:00Z")
            .unwrap()
            .with_timezone(&chrono::Utc);
        let yesterday = now - chrono::Duration::hours(25);

        // Same day: no reset.
        assert!(!t.should_reset_daily(now, now));
        assert!(!t.should_reset_daily(now, now - chrono::Duration::hours(1)));

        // Different day: reset.
        assert!(t.should_reset_daily(now, yesterday));
    }

    #[test]
    fn daily_reset_respects_reset_hour() {
        let t = CostTracker::new(6); // Reset at 06:00 UTC.
        let now = chrono::Utc::now();
        // 25 hours ago always crosses a day boundary.
        let long_ago = now - chrono::Duration::hours(25);
        assert!(t.should_reset_daily(now, long_ago));
    }

    // ── Budget reset (monthly) ──────────────────────────────────────

    #[test]
    fn monthly_reset_boundary_detection() {
        let t = tracker();
        let now = chrono::Utc::now();

        // Same month: no reset.
        assert!(!t.should_reset_monthly(now, now));

        // Different month: reset.
        let different_month = now - chrono::Duration::days(35);
        assert!(t.should_reset_monthly(now, different_month));
    }

    // ── Estimate cost calculation ───────────────────────────────────

    #[test]
    fn estimate_cost_calculation() {
        // Standard: 0.001 per 1K tokens, 1000 tokens -> $0.001
        let cost = CostTracker::estimate_cost(0.001, 1000);
        assert!((cost - 0.001).abs() < 1e-10);

        // Free tier: always zero.
        let cost = CostTracker::estimate_cost(0.0, 2000);
        assert!(cost.abs() < 1e-10);

        // Elite: 0.05 per 1K, 10000 tokens -> $0.50
        let cost = CostTracker::estimate_cost(0.05, 10000);
        assert!((cost - 0.50).abs() < 1e-10);

        // Premium: 0.01 per 1K, 6096 tokens -> $0.06096
        let cost = CostTracker::estimate_cost(0.01, 6096);
        assert!((cost - 0.06096).abs() < 1e-10);
    }

    // ── Zero limit means unlimited ──────────────────────────────────

    #[test]
    fn zero_limit_means_unlimited() {
        let t = tracker();
        t.record_estimated("alice", 999.0);
        // Both limits 0.0 = unlimited.
        let result = t.check_budget("alice", 100.0, 0.0, 0.0);
        assert_eq!(result, BudgetResult::Approved);
    }

    // ── Concurrent access safety ────────────────────────────────────

    #[test]
    fn concurrent_record_no_panic() {
        let t = Arc::new(CostTracker::new(0));
        let mut handles = vec![];

        for i in 0..10 {
            let tracker = Arc::clone(&t);
            handles.push(std::thread::spawn(move || {
                for _ in 0..100 {
                    let user = format!("user_{i}");
                    tracker.record_estimated(&user, 0.01);
                    let _ = tracker.check_budget(&user, 0.01, 50.0, 500.0);
                }
            }));
        }

        for h in handles {
            h.join().expect("thread panicked");
        }

        // 10 users * 100 records * $0.01 = $1.00 each, $10.00 total.
        let total: f64 = (0..10)
            .map(|i| t.get_spend(&format!("user_{i}")).0)
            .sum();
        assert!((total - 10.0).abs() < 0.01);
    }

    #[test]
    fn concurrent_reserve_budget_same_user() {
        let t = Arc::new(CostTracker::new(0));
        let mut handles = vec![];

        // 20 threads each try to reserve $0.50 for the same user with $8.00 daily limit.
        for _ in 0..20 {
            let tracker = Arc::clone(&t);
            handles.push(std::thread::spawn(move || {
                tracker.reserve_budget("alice", 0.50, 8.0, 100.0)
            }));
        }

        let results: Vec<BudgetResult> = handles
            .into_iter()
            .map(|h| h.join().expect("thread panicked"))
            .collect();

        let ok_count = results.iter().filter(|r| r.is_approved()).count();
        let over_count = results.iter().filter(|r| !r.is_approved()).count();

        // With $8.00 limit and $0.50 per request, at most 16 can succeed.
        assert!(ok_count <= 16);
        assert_eq!(ok_count + over_count, 20);
        let (daily, _) = t.get_spend("alice");
        assert!(daily <= 8.0 + 1e-10);
    }

    // ── Persistence roundtrip ───────────────────────────────────────

    #[test]
    fn persistence_roundtrip() {
        let dir = std::env::temp_dir().join("clawft_cost_tracker_test_roundtrip");
        let _ = std::fs::create_dir_all(&dir);
        let path = dir.join("cost_tracking.json");
        let _ = std::fs::remove_file(&path);

        // Create, record, persist.
        {
            let t = CostTracker::new(0).with_persistence(path.clone());
            t.record_estimated("alice", 3.50);
            t.record_estimated("bob", 1.25);
            t.persist().expect("persist failed");
        }

        // Load into a fresh tracker.
        {
            let t = CostTracker::load(&path).expect("load failed");
            let (alice_d, alice_m) = t.get_spend("alice");
            let (bob_d, bob_m) = t.get_spend("bob");
            assert!((alice_d - 3.50).abs() < 1e-10);
            assert!((alice_m - 3.50).abs() < 1e-10);
            assert!((bob_d - 1.25).abs() < 1e-10);
            assert!((bob_m - 1.25).abs() < 1e-10);
        }

        // Cleanup.
        let _ = std::fs::remove_file(&path);
        let _ = std::fs::remove_dir(&dir);
    }

    // ── Empty sender_id handling ────────────────────────────────────

    #[test]
    fn empty_sender_id_works() {
        let t = tracker();
        let result = t.reserve_budget("", 1.0, 5.0, 100.0);
        assert_eq!(result, BudgetResult::Approved);
        let (daily, monthly) = t.get_spend("");
        assert!((daily - 1.0).abs() < 1e-10);
        assert!((monthly - 1.0).abs() < 1e-10);
    }

    // ── get_spend returns correct values ────────────────────────────

    #[test]
    fn get_spend_unknown_user_returns_zero() {
        let t = tracker();
        let (daily, monthly) = t.get_spend("nonexistent");
        assert!(daily.abs() < 1e-10);
        assert!(monthly.abs() < 1e-10);
    }

    #[test]
    fn get_spend_reflects_committed_and_reserved() {
        let t = tracker();
        // Reserve: adds to reserved, not spent.
        t.reserve_budget("alice", 2.0, 10.0, 100.0);
        let (daily, monthly) = t.get_spend("alice");
        assert!((daily - 2.0).abs() < 1e-10);
        assert!((monthly - 2.0).abs() < 1e-10);

        // Reconcile: moves from reserved to spent.
        t.reconcile_actual("alice", 2.0, 1.5);
        let (daily, monthly) = t.get_spend("alice");
        assert!((daily - 1.5).abs() < 1e-10);
        assert!((monthly - 1.5).abs() < 1e-10);
    }

    // ── BudgetResult helpers ────────────────────────────────────────

    #[test]
    fn budget_result_is_approved() {
        assert!(BudgetResult::Approved.is_approved());
        assert!(!BudgetResult::DailyLimitExceeded { spent: 5.0, limit: 5.0 }.is_approved());
        assert!(!BudgetResult::MonthlyLimitExceeded { spent: 100.0, limit: 100.0 }.is_approved());
    }

    // ── Reserve does not record on failure ──────────────────────────

    #[test]
    fn reserve_budget_no_record_on_failure() {
        let t = tracker();
        assert_eq!(t.reserve_budget("alice", 4.0, 5.0, 100.0), BudgetResult::Approved);
        // This should fail and NOT add 2.0.
        let result = t.reserve_budget("alice", 2.0, 5.0, 100.0);
        assert!(matches!(result, BudgetResult::DailyLimitExceeded { .. }));
        // Daily spend should still be 4.0 (only the first reservation).
        let (daily, _) = t.get_spend("alice");
        assert!((daily - 4.0).abs() < 1e-10);
    }

    // ── Zero cost always approved ───────────────────────────────────

    #[test]
    fn reserve_budget_zero_cost_approved() {
        let t = tracker();
        let result = t.reserve_budget("alice", 0.0, 5.0, 100.0);
        assert_eq!(result, BudgetResult::Approved);
        let (daily, _) = t.get_spend("alice");
        assert!(daily.abs() < 1e-10);
    }

    #[test]
    fn reserve_budget_negative_cost_approved() {
        let t = tracker();
        let result = t.reserve_budget("alice", -1.0, 5.0, 100.0);
        assert_eq!(result, BudgetResult::Approved);
        let (daily, _) = t.get_spend("alice");
        assert!(daily.abs() < 1e-10);
    }

    // ── Reconcile clamps to zero ────────────────────────────────────

    #[test]
    fn reconcile_actual_clamps_to_zero() {
        let t = tracker();
        t.reserve_budget("alice", 1.0, 10.0, 100.0);
        // Actual was free: delta removes reservation and adds 0.
        t.reconcile_actual("alice", 1.0, 0.0);
        let (daily, monthly) = t.get_spend("alice");
        assert!(daily >= 0.0);
        assert!(monthly >= 0.0);
    }

    // ── record_estimated zero is noop ───────────────────────────────

    #[test]
    fn record_estimated_zero_is_noop() {
        let t = tracker();
        t.record_estimated("alice", 0.0);
        let (daily, _) = t.get_spend("alice");
        assert!(daily.abs() < 1e-10);
    }

    // ── record_actual delegates to reconcile_actual ─────────────────

    #[test]
    fn record_actual_delegates_correctly() {
        let t = tracker();
        t.record_estimated("alice", 2.0);
        t.record_actual("alice", 2.0, 1.5);
        // reconcile: remove estimated from reserved (noop since it's in spent),
        // add delta to spent. Net: 2.0 + (1.5 - 2.0) = 1.5
        let (daily, monthly) = t.get_spend("alice");
        assert!((daily - 1.5).abs() < 1e-10);
        assert!((monthly - 1.5).abs() < 1e-10);
    }

    // ── Persistence file permissions (Unix) ─────────────────────────

    #[cfg(unix)]
    #[test]
    fn persistence_file_permissions() {
        use std::os::unix::fs::PermissionsExt;

        let dir = std::env::temp_dir().join("clawft_cost_tracker_test_perms");
        let _ = std::fs::create_dir_all(&dir);
        let path = dir.join("cost_tracking.json");
        let _ = std::fs::remove_file(&path);

        let t = CostTracker::new(0).with_persistence(path.clone());
        t.record_estimated("alice", 1.0);
        t.persist().expect("persist failed");

        let metadata = std::fs::metadata(&path).expect("metadata failed");
        let mode = metadata.permissions().mode() & 0o777;
        assert_eq!(mode, 0o600, "persistence file should have 0600 permissions");

        // Cleanup.
        let _ = std::fs::remove_file(&path);
        let _ = std::fs::remove_dir(&dir);
    }

    // ── Debug impl ──────────────────────────────────────────────────

    #[test]
    fn debug_impl_does_not_panic() {
        let t = tracker();
        t.record_estimated("alice", 1.0);
        let debug_str = format!("{:?}", t);
        assert!(debug_str.contains("CostTracker"));
        assert!(debug_str.contains("users"));
    }

    // ── Daily check priority over monthly ───────────────────────────

    #[test]
    fn daily_checked_before_monthly() {
        let t = tracker();
        // Spend 9.5 which exceeds daily (5.0) and monthly (10.0).
        t.record_estimated("alice", 9.5);
        let result = t.check_budget("alice", 1.0, 5.0, 10.0);
        // Should hit daily first since daily is checked before monthly.
        assert!(matches!(result, BudgetResult::DailyLimitExceeded { .. }));
    }
}