rch 2.1.25

Remote Compilation Helper - PreToolUse hook CLI
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
//! Classification cache for repeated command decisions.
//!
//! This module provides an LRU cache with TTL expiration for caching
//! command classification results. This reduces CPU overhead when agents
//! run the same build/test commands repeatedly.
//!
//! # Design
//!
//! - **LRU eviction**: Least recently used entries are evicted when capacity is reached.
//! - **TTL expiration**: Entries expire after a configurable time (default 30s).
//! - **Config-aware**: Cache is invalidated when relevant config changes.
//!
//! # Thread Safety
//!
//! The cache uses `std::sync::Mutex` for thread safety. In practice, the hook
//! runs single-threaded per invocation, but the cache is global and may be
//! accessed across invocations in long-running processes.

use lru::LruCache;
use rch_common::Classification;
use std::num::NonZeroUsize;
use std::sync::Mutex;
use std::time::{Duration, Instant};

/// Default cache capacity (number of entries).
const DEFAULT_CACHE_CAPACITY: usize = 1000;

/// Default TTL for cache entries (30 seconds).
const DEFAULT_TTL_SECS: u64 = 30;

/// A cached classification result with expiration timestamp.
#[derive(Debug, Clone)]
struct CachedClassification {
    /// The cached classification result.
    classification: Classification,
    /// When this entry was inserted.
    inserted_at: Instant,
    /// TTL for this entry.
    ttl: Duration,
}

impl CachedClassification {
    /// Check if this cached entry has expired.
    fn is_expired(&self) -> bool {
        self.inserted_at.elapsed() > self.ttl
    }
}

/// Configuration for the classification cache.
#[derive(Debug, Clone)]
pub struct CacheConfig {
    /// Maximum number of entries in the cache.
    pub max_entries: usize,
    /// Time-to-live for cache entries.
    pub ttl: Duration,
    /// Whether the cache is enabled.
    pub enabled: bool,
}

impl Default for CacheConfig {
    fn default() -> Self {
        Self {
            max_entries: DEFAULT_CACHE_CAPACITY,
            ttl: Duration::from_secs(DEFAULT_TTL_SECS),
            enabled: true,
        }
    }
}

/// An LRU cache with TTL expiration for command classifications.
pub struct ClassificationCache {
    cache: Mutex<LruCache<String, CachedClassification>>,
    config: CacheConfig,
    /// Tracks cache hits for metrics.
    hits: Mutex<u64>,
    /// Tracks cache misses for metrics.
    misses: Mutex<u64>,
}

impl ClassificationCache {
    /// Create a new classification cache with the given configuration.
    pub fn new(config: CacheConfig) -> Self {
        let capacity = NonZeroUsize::new(config.max_entries.max(1))
            .unwrap_or(NonZeroUsize::new(DEFAULT_CACHE_CAPACITY).unwrap());
        Self {
            cache: Mutex::new(LruCache::new(capacity)),
            config,
            hits: Mutex::new(0),
            misses: Mutex::new(0),
        }
    }

    /// Create a new cache with default configuration.
    pub fn with_defaults() -> Self {
        Self::new(CacheConfig::default())
    }

    /// Get a cached classification for a command.
    ///
    /// Returns `None` if:
    /// - The command is not in the cache
    /// - The cached entry has expired
    /// - The cache is disabled
    ///
    /// **Caller contract:** `command` must already be trimmed. Callers
    /// using [`classify_cached`] get this for free; callers driving the
    /// cache directly are responsible. Trimming inside `get` would be a
    /// double-trim against [`classify_cached`] which already trims once.
    pub fn get(&self, command: &str) -> Option<Classification> {
        if !self.config.enabled {
            return None;
        }

        // Use &str directly for lookup — LruCache supports Borrow<str> on
        // String keys, avoiding a String allocation on every cache probe.
        let key = command;
        let mut cache = self.cache.lock().ok()?;

        // Check if entry exists and is not expired
        if let Some(entry) = cache.get(key) {
            if entry.is_expired() {
                // Remove expired entry
                cache.pop(key);
                if let Ok(mut misses) = self.misses.lock() {
                    *misses += 1;
                }
                tracing::trace!(command = %command, "Classification cache miss (expired)");
                None
            } else {
                if let Ok(mut hits) = self.hits.lock() {
                    *hits += 1;
                }
                tracing::trace!(command = %command, "Classification cache hit");
                Some(entry.classification.clone())
            }
        } else {
            if let Ok(mut misses) = self.misses.lock() {
                *misses += 1;
            }
            tracing::trace!(command = %command, "Classification cache miss");
            None
        }
    }

    /// Store a classification result in the cache.
    ///
    /// **Caller contract:** `command` must already be trimmed. See [`Self::get`].
    pub fn put(&self, command: &str, classification: Classification) {
        if !self.config.enabled {
            return;
        }

        // Only put() needs an owned String for the LRU key.
        let key = command.to_string();
        let entry = CachedClassification {
            classification,
            inserted_at: Instant::now(),
            ttl: self.config.ttl,
        };

        if let Ok(mut cache) = self.cache.lock() {
            cache.put(key, entry);
            tracing::trace!(command = %command, "Classification cached");
        }
    }

    /// Clear the entire cache.
    #[allow(dead_code)] // Available for future cache invalidation
    pub fn clear(&self) {
        if let Ok(mut cache) = self.cache.lock() {
            cache.clear();
        }
    }

    /// Get cache statistics.
    #[allow(dead_code)] // Available for future metrics integration
    pub fn stats(&self) -> CacheStats {
        let hits = self.hits.lock().map(|g| *g).unwrap_or(0);
        let misses = self.misses.lock().map(|g| *g).unwrap_or(0);
        let len = self.cache.lock().map(|c| c.len()).unwrap_or(0);

        CacheStats { hits, misses, len }
    }
}

impl Default for ClassificationCache {
    fn default() -> Self {
        Self::with_defaults()
    }
}

/// Cache statistics for monitoring.
#[allow(dead_code)] // Available for future metrics integration
#[derive(Debug, Clone, Default)]
pub struct CacheStats {
    /// Number of cache hits.
    pub hits: u64,
    /// Number of cache misses.
    pub misses: u64,
    /// Current number of entries in the cache.
    pub len: usize,
}

impl CacheStats {
    /// Calculate the hit rate as a percentage (0.0 - 100.0).
    #[allow(dead_code)] // Available for future metrics integration
    pub fn hit_rate(&self) -> f64 {
        let total = self.hits + self.misses;
        if total == 0 {
            0.0
        } else {
            (self.hits as f64 / total as f64) * 100.0
        }
    }
}

/// Global classification cache instance.
///
/// This is initialized lazily on first use with default configuration.
static GLOBAL_CACHE: std::sync::OnceLock<ClassificationCache> = std::sync::OnceLock::new();

/// Get the global classification cache.
pub fn global_cache() -> &'static ClassificationCache {
    GLOBAL_CACHE.get_or_init(ClassificationCache::with_defaults)
}

/// Get a cached classification or compute it.
///
/// This is the main entry point for cached classification. It:
/// 1. Trims the input ONCE (downstream `Cache::get`/`put` consume the
///    trimmed slice; `classify_command` also trims internally but the
///    cost is bounded by `&str::trim` on a typically-short slice).
/// 2. **Hook-mode bypass**: when `RCH_HOOK_MODE=1`, the hook is one-shot
///    so the cache never delivers a hit — but it still pays for 3
///    `Mutex::lock()` acquires per call. We bypass the cache entirely
///    in hook mode and call `classify_fn(trimmed)` directly. Saves
///    ~3-9µs per hook invocation against the project's <5ms hot path.
/// 3. Long-lived consumers (`rchd`, `rch exec`) keep the cached path —
///    detected by the absence of `RCH_HOOK_MODE`.
/// 4. On cache miss: call `classify_fn`, store, return.
#[allow(dead_code)] // Reserved for long-lived classification callers outside one-shot hook mode.
pub fn classify_cached<F>(command: &str, classify_fn: F) -> Classification
where
    F: FnOnce(&str) -> Classification,
{
    classify_cached_inner(command, classify_fn, is_hook_mode())
}

/// Classify a command on the real hook path.
///
/// The no-subcommand hook entry point is already known to be hook mode even
/// when `RCH_HOOK_MODE` is not set, so callers on that path should bypass the
/// cache directly instead of depending on environment detection.
pub(crate) fn classify_hook_command<F>(command: &str, classify_fn: F) -> Classification
where
    F: FnOnce(&str) -> Classification,
{
    classify_cached_inner(command, classify_fn, true)
}

fn classify_cached_inner<F>(command: &str, classify_fn: F, hook_mode: bool) -> Classification
where
    F: FnOnce(&str) -> Classification,
{
    // Single trim — downstream consumers honor the pre-trimmed contract.
    let trimmed = command.trim();

    // Hook-mode bypass: skip cache (and its 3 mutex acquires) entirely.
    // The hook is process-per-invocation, so the cache always starts
    // empty; lookup overhead is pure cost with no benefit.
    if hook_mode {
        return classify_fn(trimmed);
    }

    let cache = global_cache();

    // Try cache first
    if let Some(cached) = cache.get(trimmed) {
        return cached;
    }

    // Compute and cache
    let classification = classify_fn(trimmed);
    cache.put(trimmed, classification.clone());
    classification
}

/// Detect hook mode via the `RCH_HOOK_MODE` env var. Accepts truthy
/// strings `"1"` / `"true"` (case-insensitive), matching the existing
/// project convention from `rch/src/hook.rs`.
#[allow(dead_code)] // Used by classify_cached when long-lived callers opt into the cache.
fn is_hook_mode() -> bool {
    std::env::var_os("RCH_HOOK_MODE").is_some_and(|v| {
        let s = v.to_string_lossy().to_lowercase();
        s == "1" || s == "true"
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use rch_common::{CompilationKind, classify_command};
    use std::borrow::Cow;

    fn make_classification(is_compilation: bool) -> Classification {
        Classification {
            is_compilation,
            confidence: if is_compilation { 0.95 } else { 0.0 },
            kind: if is_compilation {
                Some(CompilationKind::CargoBuild)
            } else {
                None
            },
            reason: Cow::Borrowed("test"),
            command_prefix: None,
            extracted_command: None,
        }
    }

    #[test]
    fn test_cache_basic_operations() {
        let cache = ClassificationCache::with_defaults();

        // Initially empty
        assert!(cache.get("cargo build").is_none());

        // Store a classification
        let class = make_classification(true);
        cache.put("cargo build", class.clone());

        // Should be retrievable
        let cached = cache.get("cargo build");
        assert!(cached.is_some());
        assert!(cached.unwrap().is_compilation);

        // Different command should not be cached
        assert!(cache.get("cargo test").is_none());
    }

    #[test]
    fn test_cache_ttl_expiration() {
        let config = CacheConfig {
            max_entries: 100,
            ttl: Duration::from_millis(50), // Very short TTL for testing
            enabled: true,
        };
        let cache = ClassificationCache::new(config);

        let class = make_classification(true);
        cache.put("cargo build", class);

        // Should be cached immediately
        assert!(cache.get("cargo build").is_some());

        // Wait for expiration
        std::thread::sleep(Duration::from_millis(60));

        // Should be expired now
        assert!(cache.get("cargo build").is_none());
    }

    #[test]
    fn test_cache_lru_eviction() {
        let config = CacheConfig {
            max_entries: 2, // Very small cache
            ttl: Duration::from_secs(30),
            enabled: true,
        };
        let cache = ClassificationCache::new(config);

        // Fill the cache
        cache.put("cmd1", make_classification(true));
        cache.put("cmd2", make_classification(true));

        // Both should be present
        assert!(cache.get("cmd1").is_some());
        assert!(cache.get("cmd2").is_some());

        // Access cmd1 to make it most recently used
        cache.get("cmd1");

        // Add a third entry, should evict cmd2 (least recently used)
        cache.put("cmd3", make_classification(true));

        // cmd1 and cmd3 should be present, cmd2 evicted
        assert!(cache.get("cmd1").is_some());
        assert!(cache.get("cmd3").is_some());
        assert!(cache.get("cmd2").is_none());
    }

    #[test]
    fn test_cache_disabled() {
        let config = CacheConfig {
            max_entries: 100,
            ttl: Duration::from_secs(30),
            enabled: false,
        };
        let cache = ClassificationCache::new(config);

        let class = make_classification(true);
        cache.put("cargo build", class);

        // Should not be cached when disabled
        assert!(cache.get("cargo build").is_none());
    }

    #[test]
    fn test_cache_stats() {
        let cache = ClassificationCache::with_defaults();

        // Initial stats
        let stats = cache.stats();
        assert_eq!(stats.hits, 0);
        assert_eq!(stats.misses, 0);
        assert_eq!(stats.len, 0);

        // Miss
        cache.get("cargo build");
        let stats = cache.stats();
        assert_eq!(stats.misses, 1);

        // Put and hit
        cache.put("cargo build", make_classification(true));
        cache.get("cargo build");
        let stats = cache.stats();
        assert_eq!(stats.hits, 1);
        assert_eq!(stats.len, 1);
    }

    #[test]
    fn test_cache_assumes_pretrimmed_keys() {
        // Caller contract (since t16): the cache itself does NOT trim.
        // Whitespace must be normalized by the caller (classify_cached
        // does this once at its entry, eliminating the prior double-trim).
        let cache = ClassificationCache::with_defaults();

        cache.put("cargo build", make_classification(true));
        // Same trimmed key hits.
        assert!(cache.get("cargo build").is_some());
        // Untrimmed lookup is now a MISS — the cache surface is honest
        // about its contract.
        assert!(cache.get("  cargo build  ").is_none());
    }

    #[test]
    fn test_classify_cached_normalizes_whitespace_via_single_trim() {
        // The end-user-observable behavior is unchanged: classify_cached
        // does the trimming once at its entry, so callers see "  cargo
        // build  " classify identically to "cargo build". This test
        // pins the invariant against future regressions.
        let trimmed_result = classify_cached("cargo build", classify_command);
        let padded_result = classify_cached("  cargo build  ", classify_command);
        assert_eq!(trimmed_result.is_compilation, padded_result.is_compilation);
        assert_eq!(trimmed_result.kind, padded_result.kind);
    }

    #[test]
    fn test_classify_cached_hook_mode_bypasses_cache() {
        let unique_cmd = "cargo build --t16-hook-bypass-marker";

        for _ in 0..50 {
            let _ = classify_cached_inner(unique_cmd, classify_command, true);
        }

        // Unique entry must not be present (bypass means no put).
        assert!(global_cache().get(unique_cmd).is_none());
    }

    #[test]
    fn test_classify_hook_command_bypasses_cache_without_env() {
        let unique_cmd = "cargo build --hook-entry-bypass-without-env-marker";

        for _ in 0..50 {
            let _ = classify_hook_command(unique_cmd, classify_command);
        }

        // The explicit hook-path helper must not populate the cache; real hook
        // invocations do not necessarily set RCH_HOOK_MODE.
        assert!(global_cache().get(unique_cmd).is_none());
    }

    #[test]
    fn test_classify_cached_default_mode_uses_cache() {
        let unique_cmd = "cargo test --t16-default-mode-marker";

        let r1 = classify_cached_inner(unique_cmd, classify_command, false);
        let r2 = classify_cached_inner(unique_cmd, classify_command, false);
        assert_eq!(r1.is_compilation, r2.is_compilation);
        assert_eq!(r1.kind, r2.kind);

        // Cache MUST contain the entry.
        assert!(
            global_cache().get(unique_cmd).is_some(),
            "default mode should populate the cache"
        );
    }

    #[test]
    fn test_is_hook_mode_truthy_env_values() {
        // Verify the env-var parser accepts "1" and "true" (case-insensitive).
        // We can't mutate env vars under forbid(unsafe_code), so parse logic
        // is verified inline against the same predicate.
        let truthy = ["1", "true", "TRUE", "True"];
        let falsy = ["0", "false", "no", "yes", ""];
        for val in truthy {
            let lc = val.to_lowercase();
            assert!(lc == "1" || lc == "true", "expected {val:?} to be truthy");
        }
        for val in falsy {
            let lc = val.to_lowercase();
            assert!(
                !(lc == "1" || lc == "true"),
                "expected {val:?} to NOT be truthy"
            );
        }
    }

    #[test]
    fn test_classify_cached() {
        // Reset global cache state for this test
        let call_count = std::sync::atomic::AtomicUsize::new(0);

        let classify = |_cmd: &str| {
            call_count.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            make_classification(true)
        };

        // First call should invoke the function
        let result = classify_cached("cargo build", classify);
        assert!(result.is_compilation);
        // Note: can't easily test call count with global cache,
        // but we can verify the result is correct
    }

    #[test]
    fn test_hit_rate_calculation() {
        let stats = CacheStats {
            hits: 80,
            misses: 20,
            len: 10,
        };
        assert!((stats.hit_rate() - 80.0).abs() < 0.001);

        let empty_stats = CacheStats::default();
        assert_eq!(empty_stats.hit_rate(), 0.0);
    }

    // ==================== Additional Coverage Tests ====================

    #[test]
    fn test_cache_config_default() {
        let config = CacheConfig::default();
        assert_eq!(config.max_entries, DEFAULT_CACHE_CAPACITY);
        assert_eq!(config.ttl, Duration::from_secs(DEFAULT_TTL_SECS));
        assert!(config.enabled);
    }

    #[test]
    fn test_cache_config_clone() {
        let config = CacheConfig {
            max_entries: 500,
            ttl: Duration::from_secs(60),
            enabled: false,
        };

        let cloned = config.clone();
        assert_eq!(cloned.max_entries, 500);
        assert_eq!(cloned.ttl, Duration::from_secs(60));
        assert!(!cloned.enabled);
    }

    #[test]
    fn test_cache_config_debug() {
        let config = CacheConfig {
            max_entries: 100,
            ttl: Duration::from_secs(10),
            enabled: true,
        };

        let debug = format!("{:?}", config);
        assert!(debug.contains("max_entries"));
        assert!(debug.contains("100"));
        assert!(debug.contains("enabled"));
    }

    #[test]
    fn test_cache_stats_clone() {
        let stats = CacheStats {
            hits: 100,
            misses: 50,
            len: 25,
        };

        let cloned = stats.clone();
        assert_eq!(cloned.hits, 100);
        assert_eq!(cloned.misses, 50);
        assert_eq!(cloned.len, 25);
    }

    #[test]
    fn test_cache_stats_debug() {
        let stats = CacheStats {
            hits: 42,
            misses: 13,
            len: 10,
        };

        let debug = format!("{:?}", stats);
        assert!(debug.contains("hits"));
        assert!(debug.contains("42"));
        assert!(debug.contains("misses"));
        assert!(debug.contains("13"));
    }

    #[test]
    fn test_cache_stats_default() {
        let stats = CacheStats::default();
        assert_eq!(stats.hits, 0);
        assert_eq!(stats.misses, 0);
        assert_eq!(stats.len, 0);
        assert_eq!(stats.hit_rate(), 0.0);
    }

    #[test]
    fn test_classification_cache_default() {
        let cache = ClassificationCache::default();
        // Default cache should be enabled with default capacity
        let stats = cache.stats();
        assert_eq!(stats.len, 0);

        // Should be able to store and retrieve
        cache.put("test cmd", make_classification(true));
        assert!(cache.get("test cmd").is_some());
    }

    #[test]
    fn test_cache_clear() {
        let cache = ClassificationCache::with_defaults();

        // Add some entries
        cache.put("cmd1", make_classification(true));
        cache.put("cmd2", make_classification(true));
        cache.put("cmd3", make_classification(false));

        let stats = cache.stats();
        assert_eq!(stats.len, 3);

        // Clear the cache
        cache.clear();

        let stats = cache.stats();
        assert_eq!(stats.len, 0);

        // All entries should be gone
        assert!(cache.get("cmd1").is_none());
        assert!(cache.get("cmd2").is_none());
        assert!(cache.get("cmd3").is_none());
    }

    #[test]
    fn test_cache_zero_capacity() {
        // Zero capacity should be clamped to 1
        let config = CacheConfig {
            max_entries: 0,
            ttl: Duration::from_secs(30),
            enabled: true,
        };
        let cache = ClassificationCache::new(config);

        // Should still be able to cache one entry
        cache.put("cmd1", make_classification(true));
        assert!(cache.get("cmd1").is_some());

        // Adding another will evict the first
        cache.put("cmd2", make_classification(true));
        assert!(cache.get("cmd2").is_some());
        assert!(cache.get("cmd1").is_none());
    }

    #[test]
    fn test_global_cache_returns_same_instance() {
        let cache1 = global_cache();
        let cache2 = global_cache();

        // Should be the same instance (pointer equality)
        assert!(std::ptr::eq(cache1, cache2));
    }

    #[test]
    fn test_cache_hit_rate_various_scenarios() {
        // 50% hit rate
        let stats = CacheStats {
            hits: 50,
            misses: 50,
            len: 10,
        };
        assert!((stats.hit_rate() - 50.0).abs() < 0.001);

        // 100% hit rate
        let stats = CacheStats {
            hits: 100,
            misses: 0,
            len: 5,
        };
        assert!((stats.hit_rate() - 100.0).abs() < 0.001);

        // 0% hit rate
        let stats = CacheStats {
            hits: 0,
            misses: 100,
            len: 0,
        };
        assert!((stats.hit_rate() - 0.0).abs() < 0.001);
    }

    #[test]
    fn test_cache_put_overwrites_existing() {
        let cache = ClassificationCache::with_defaults();

        // Store initial classification
        let class1 = make_classification(true);
        cache.put("cmd", class1);

        let cached = cache.get("cmd").unwrap();
        assert!(cached.is_compilation);

        // Overwrite with different classification
        let class2 = make_classification(false);
        cache.put("cmd", class2);

        let cached = cache.get("cmd").unwrap();
        assert!(!cached.is_compilation);
    }

    #[test]
    fn test_cache_direct_keys_are_byte_exact() {
        let cache = ClassificationCache::with_defaults();

        // Direct cache callers are responsible for trimming. The cache
        // itself treats keys byte-exactly.
        cache.put("  command  ", make_classification(true));
        assert!(cache.get("  command  ").is_some());
        assert!(cache.get("command").is_none());
        assert!(cache.get("  command").is_none());
        assert!(cache.get("command  ").is_none());

        // Stats should show only 1 entry
        let stats = cache.stats();
        assert_eq!(stats.len, 1);
    }

    #[test]
    fn test_cache_multiple_misses_tracked() {
        let cache = ClassificationCache::with_defaults();

        // Multiple misses on different commands
        cache.get("missing1");
        cache.get("missing2");
        cache.get("missing3");
        cache.get("missing4");
        cache.get("missing5");

        let stats = cache.stats();
        assert_eq!(stats.misses, 5);
        assert_eq!(stats.hits, 0);
    }

    #[test]
    fn test_cache_multiple_hits_tracked() {
        let cache = ClassificationCache::with_defaults();

        cache.put("cmd", make_classification(true));

        // Multiple hits on same command
        cache.get("cmd");
        cache.get("cmd");
        cache.get("cmd");

        let stats = cache.stats();
        assert_eq!(stats.hits, 3);
    }

    #[test]
    fn test_cached_classification_debug() {
        // Test CachedClassification Debug trait
        let entry = CachedClassification {
            classification: make_classification(true),
            inserted_at: Instant::now(),
            ttl: Duration::from_secs(30),
        };

        let debug = format!("{:?}", entry);
        assert!(debug.contains("classification"));
        assert!(debug.contains("inserted_at"));
        assert!(debug.contains("ttl"));
    }

    #[test]
    fn test_cached_classification_clone() {
        let entry = CachedClassification {
            classification: make_classification(true),
            inserted_at: Instant::now(),
            ttl: Duration::from_secs(60),
        };

        let cloned = entry.clone();
        assert_eq!(
            cloned.classification.is_compilation,
            entry.classification.is_compilation
        );
        assert_eq!(cloned.ttl, entry.ttl);
    }

    #[test]
    fn test_cached_classification_is_expired() {
        let entry = CachedClassification {
            classification: make_classification(true),
            inserted_at: Instant::now(),
            ttl: Duration::from_millis(10),
        };

        // Should not be expired immediately
        assert!(!entry.is_expired());

        // Wait for expiration
        std::thread::sleep(Duration::from_millis(15));

        // Should be expired now
        assert!(entry.is_expired());
    }

    #[test]
    fn test_cache_non_compilation_classification() {
        let cache = ClassificationCache::with_defaults();

        // Cache a non-compilation command
        let class = make_classification(false);
        cache.put("echo hello", class);

        let cached = cache.get("echo hello").unwrap();
        assert!(!cached.is_compilation);
        assert!(cached.kind.is_none());
    }
}