code-search-please 0.1.10

Hybrid code search for agents — core library (Rust rewrite of MinishLab/semble).
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
//! MCP server core — the session index cache, the source-safety layer, and the
//! `search` / `find_related` tool handlers. Port of the verifiable core of
//! `src/mcp/server.ts` (← semble `mcp.py`).
//!
//! The handlers and [`IndexCache`] are transport-agnostic and fully tested here.
//! The rmcp stdio server in the `csp` binary (`src/bin/csp/mcp_server.rs`, behind
//! the `cli` feature) wires these handlers onto
//! the live MCP protocol; this core is kept transport-free so it stays unit-
//! testable. [`IndexCache`] holds `Arc<CspIndex>` so it can be shared across the
//! async server's tokio tasks.

use std::collections::BTreeSet;
use std::path::Path;
use std::sync::Arc;
use std::time::{Duration, Instant};

use indexmap::IndexMap;
use serde_json::json;

use crate::indexing::index::{
    load_or_build_index, source_fingerprint, CspIndex, LoadOrBuildOptions, QueryOptions,
};
use crate::stats::save_search_stats;
use crate::types::{CallType, ContentType};
use crate::utils::{format_results, is_git_url, resolve_chunk};

/// Server instructions advertised to MCP clients (preserved for the transport).
pub const SERVER_INSTRUCTIONS: &str = concat!(
    "Instant code search for any local or remote git repository. ",
    "Call `search` to find relevant code; call `find_related` on a result to discover similar code elsewhere. ",
    "Pass `content` (`code`, `docs`, `config`, or `all`) to choose what a single call searches; ",
    "it defaults to the server's configured content. ",
    "Prefer these tools over Grep, Glob, or Read for any question about how code works."
);

/// Every content type in canonical (enum) order — the expansion of `all` and
/// the ordering used to normalize cache keys.
const ALL_CONTENT: [ContentType; 3] = [ContentType::Code, ContentType::Docs, ContentType::Config];

/// Per-call content selection accepted by the MCP tools (`code | docs | config
/// | all`). Mirrors upstream semble's `ContentSelection` literal (#247).
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "cli", derive(schemars::JsonSchema))]
#[serde(rename_all = "lowercase")]
pub enum ContentSelection {
    Code,
    Docs,
    Config,
    All,
}

/// Canonical form of a content list: every [`ContentType`] present, once, in
/// enum (`Ord`) order — so `[Docs, Code, Docs]` and `[Code, Docs]` name the
/// same index.
pub fn normalize_content(content: &[ContentType]) -> Vec<ContentType> {
    content
        .iter()
        .copied()
        .collect::<BTreeSet<_>>()
        .into_iter()
        .collect()
}

/// Resolve a per-call `content` selection to exact index content types:
/// `None` → the server's configured default, `All` → every type, otherwise the
/// single named type (mirrors upstream `_resolve_content_selection`).
pub fn resolve_content_selection(
    selection: Option<ContentSelection>,
    default_content: &[ContentType],
) -> Vec<ContentType> {
    match selection {
        None => normalize_content(default_content),
        Some(ContentSelection::All) => ALL_CONTENT.to_vec(),
        Some(ContentSelection::Code) => vec![ContentType::Code],
        Some(ContentSelection::Docs) => vec![ContentType::Docs],
        Some(ContentSelection::Config) => vec![ContentType::Config],
    }
}

/// Maximum number of distinct sources held in the session cache (LRU).
const CACHE_MAX_SIZE: usize = 10;

/// Don't re-check a cached local path for staleness sooner than this many times
/// the last build's duration — so a slow-to-build repo isn't re-walked on every
/// query (mirrors semble#211's `_MIN_REVALIDATE_FACTOR`).
const MIN_REVALIDATE_FACTOR: u32 = 3;

/// Floor for local-path revalidation so fast disk-cache hits do not trigger a
/// full source-tree fingerprint on nearly every query.
const MIN_REVALIDATE_COOLDOWN: Duration = Duration::from_secs(2);

/// Build-or-reuse seam — defaults to [`load_or_build_index`]; tests inject a stub
/// to count calls and assert git-vs-path routing.
pub trait LoadOrBuild {
    fn load_or_build(
        &self,
        source: &str,
        content: &[ContentType],
        git_ref: Option<&str>,
    ) -> Result<CspIndex, String>;

    /// Live validity fingerprint for a local `source` (`None` for git URLs, which
    /// are URL+ref keyed and never revalidated). A change from the value captured
    /// at build time means the cached index is stale and must be rebuilt.
    fn fingerprint(&self, source: &str, content: &[ContentType]) -> Option<String>;
}

/// Default seam: route through the shared on-disk cache.
pub struct DiskLoadOrBuild;

impl LoadOrBuild for DiskLoadOrBuild {
    fn load_or_build(
        &self,
        source: &str,
        content: &[ContentType],
        git_ref: Option<&str>,
    ) -> Result<CspIndex, String> {
        load_or_build_index(
            source,
            &LoadOrBuildOptions {
                content: Some(content.to_vec()),
                git_ref: git_ref.map(str::to_string),
                ..Default::default()
            },
        )
    }

    fn fingerprint(&self, source: &str, content: &[ContentType]) -> Option<String> {
        source_fingerprint(source, content)
    }
}

/// A cached index plus the metadata needed to revalidate it on later queries.
struct CacheEntry {
    index: Arc<CspIndex>,
    /// Source fingerprint captured at build time; `None` for git URLs (never
    /// revalidated). A live fingerprint that differs means the entry is stale.
    fingerprint: Option<String>,
    /// Staleness re-checks for this entry are skipped until this instant, so a
    /// slow-to-build repo isn't re-walked on every query.
    revalidate_after: Instant,
    /// Cooldown restored after each successful fingerprint revalidation.
    revalidate_cooldown: std::time::Duration,
}

/// Identity of one exact index variant in the session cache: the source (git
/// URL `@ref`, or the absolutized local path) plus its normalized content list
/// (upstream `_CacheKey = tuple[str, tuple[ContentType, ...]]`, #247).
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct CacheKey {
    source: String,
    content: Vec<ContentType>,
}

/// Session cache of indexed repos/paths, keyed by source (git URL `@ref`, or the
/// absolutized local path) **and** content selection, so one repo searched as
/// `code` and as `docs` holds two independent entries. LRU-bounded to
/// [`CACHE_MAX_SIZE`]. Local-path entries are revalidated against their live
/// source fingerprint on query (subject to a build-time-scaled cooldown), so an
/// entry is rebuilt once its files change.
pub struct IndexCache<S: LoadOrBuild = DiskLoadOrBuild> {
    tasks: IndexMap<CacheKey, CacheEntry>,
    seam: S,
}

impl IndexCache<DiskLoadOrBuild> {
    /// A cache backed by the real on-disk `load_or_build_index`.
    pub fn new() -> Self {
        Self::with_seam(DiskLoadOrBuild)
    }
}

impl Default for IndexCache<DiskLoadOrBuild> {
    fn default() -> Self {
        Self::new()
    }
}

impl<S: LoadOrBuild> IndexCache<S> {
    pub fn with_seam(seam: S) -> Self {
        Self {
            tasks: IndexMap::new(),
            seam,
        }
    }

    fn compute_key(
        &self,
        source: &str,
        git_ref: Option<&str>,
        content: &[ContentType],
    ) -> CacheKey {
        let source = if is_git_url(source) {
            match git_ref {
                Some(r) if !r.is_empty() => format!("{source}@{r}"),
                _ => source.to_string(),
            }
        } else {
            // Local paths go through the same normalizer as the on-disk cache
            // key, so `.`, `./r/../r`, and `/abs/r` name one session entry too —
            // a second spelling of the same repo must not cost a duplicate
            // `Arc<CspIndex>` and an LRU slot, or make `evict` silently miss.
            crate::indexing::cache::normalize_source(source)
        };
        CacheKey {
            source,
            content: normalize_content(content),
        }
    }

    /// Return an index for `source` restricted to `content`, building and
    /// caching it on first access. Each distinct (source, content) pair is its
    /// own entry. A build failure is not cached (the next call retries).
    ///
    /// A cached local-path entry is revalidated against its live source
    /// fingerprint once its cooldown has elapsed; a mismatch evicts it so the
    /// index is rebuilt below. Git URLs are never revalidated.
    pub fn get(
        &mut self,
        source: &str,
        git_ref: Option<&str>,
        content: &[ContentType],
    ) -> Result<Arc<CspIndex>, String> {
        let key = self.compute_key(source, git_ref, content);
        let content = key.content.as_slice();

        let mut entry = self.tasks.shift_remove(&key);
        let stale = if let Some(entry) = entry.as_mut() {
            if entry.fingerprint.is_some() && Instant::now() >= entry.revalidate_after {
                if self.seam.fingerprint(source, content) != entry.fingerprint {
                    true
                } else {
                    entry.revalidate_after = Instant::now() + entry.revalidate_cooldown;
                    false
                }
            } else {
                false
            }
        } else {
            false
        };

        if stale {
            entry = None;
        }

        if let Some(entry) = entry {
            // Fresh (or git) → serve; touch for LRU (re-insert at the recent end).
            let index = entry.index.clone();
            self.tasks.insert(key, entry);
            return Ok(index);
        }

        // LRU eviction: drop the oldest entry when full.
        if self.tasks.len() >= CACHE_MAX_SIZE {
            self.tasks.shift_remove_index(0);
        }

        let start = Instant::now();
        let index = Arc::new(self.seam.load_or_build(source, content, git_ref)?);
        let build_elapsed = start.elapsed();
        let fingerprint = self.seam.fingerprint(source, content);
        let revalidate_cooldown =
            (build_elapsed * MIN_REVALIDATE_FACTOR).max(MIN_REVALIDATE_COOLDOWN);
        self.tasks.insert(
            key,
            CacheEntry {
                index: index.clone(),
                fingerprint,
                revalidate_after: Instant::now() + revalidate_cooldown,
                revalidate_cooldown,
            },
        );
        Ok(index)
    }

    /// Remove the cached entry for `source` at this exact `content` selection.
    pub fn evict(&mut self, source: &str, git_ref: Option<&str>, content: &[ContentType]) {
        let key = self.compute_key(source, git_ref, content);
        self.tasks.shift_remove(&key);
    }

    /// Number of cached entries.
    pub fn size(&self) -> usize {
        self.tasks.len()
    }
}

/// Resolve a cached index for a repo at the given (already resolved) `content`
/// selection, rejecting unsafe git transport schemes and missing-source cases
/// with descriptive errors.
pub fn get_index<S: LoadOrBuild>(
    repo: Option<&str>,
    default_source: Option<&str>,
    default_ref: Option<&str>,
    content: &[ContentType],
    cache: &mut IndexCache<S>,
) -> Result<Arc<CspIndex>, String> {
    if let Some(r) = repo {
        if is_git_url(r) && !r.starts_with("https://") && !r.starts_with("http://") {
            return Err(format!(
                "Only https://, http://, or local directory paths are accepted as `repo`. Got: {}",
                json!(r)
            ));
        }
    }
    // An explicit per-call `repo` carries no ref; `default_ref` applies only when
    // falling back to the server's default source (so `csp mcp <url> --ref X`
    // actually pins the indexed revision instead of being silently ignored).
    let use_default = repo.filter(|s| !s.is_empty()).is_none();
    let source = repo.or(default_source).filter(|s| !s.is_empty());
    let Some(source) = source else {
        return Err("No repo specified and no default index. \
             Pass an https:// or http:// git URL or local directory path as `repo`."
            .to_string());
    };
    let git_ref = if use_default { default_ref } else { None };
    cache
        .get(source, git_ref, content)
        .map_err(|e| format!("Failed to index {}: {e}", json!(source)))
}

/// `search` tool handler. Returns a JSON string (results or `{error}`), or an
/// error message string on failure (mirroring the TS handler's catch).
/// `content` is the per-call selection already resolved against the server
/// default (see [`resolve_content_selection`]). `stats_file`, when `Some`,
/// records token-savings telemetry (tests pass `None`).
// Positional transport params mirror the MCP tool signature; a struct would just
// move the plumbing without clarifying it (same call as `find_related_tool`).
#[allow(clippy::too_many_arguments)]
pub fn search_tool<S: LoadOrBuild>(
    cache: &mut IndexCache<S>,
    default_source: Option<&str>,
    default_ref: Option<&str>,
    query: &str,
    repo: Option<&str>,
    content: &[ContentType],
    top_k: usize,
    max_snippet_lines: Option<usize>,
    stats_file: Option<&Path>,
) -> String {
    let index = match get_index(repo, default_source, default_ref, content, cache) {
        Ok(idx) => idx,
        Err(e) => return e,
    };
    let results = index.search(
        query,
        &QueryOptions {
            top_k: Some(top_k),
            ..Default::default()
        },
    );
    if let Some(stats_file) = stats_file {
        save_search_stats(
            stats_file,
            &results,
            CallType::Search,
            &index.file_sizes,
            max_snippet_lines,
        );
    }
    if results.is_empty() {
        json!({ "error": "No results found." }).to_string()
    } else {
        format_results(query, &results, max_snippet_lines).to_string()
    }
}

/// `find_related` tool handler.
// Positional transport params mirror the MCP tool signature; a struct would just
// move the plumbing without clarifying it.
#[allow(clippy::too_many_arguments)]
pub fn find_related_tool<S: LoadOrBuild>(
    cache: &mut IndexCache<S>,
    default_source: Option<&str>,
    default_ref: Option<&str>,
    file_path: &str,
    line: i64,
    repo: Option<&str>,
    content: &[ContentType],
    top_k: usize,
    max_snippet_lines: Option<usize>,
    stats_file: Option<&Path>,
) -> String {
    let index = match get_index(repo, default_source, default_ref, content, cache) {
        Ok(idx) => idx,
        Err(e) => return e,
    };
    // Guard the full u32 range, not just the lower bound — a line number above
    // u32::MAX would otherwise wrap on `as u32` and resolve the wrong chunk.
    let chunk = if (0..=i64::from(u32::MAX)).contains(&line) {
        resolve_chunk(&index.chunks, file_path, line as u32)
    } else {
        None
    };
    let Some(chunk) = chunk else {
        return format!(
            "No chunk found at {file_path}:{line}. \
             Make sure the file is indexed and the line number is within a known chunk."
        );
    };
    let results = index.find_related(
        &chunk.clone(),
        &QueryOptions {
            top_k: Some(top_k),
            ..Default::default()
        },
    );
    if let Some(stats_file) = stats_file {
        save_search_stats(
            stats_file,
            &results,
            CallType::FindRelated,
            &index.file_sizes,
            max_snippet_lines,
        );
    }
    if results.is_empty() {
        json!({ "error": format!("No related chunks found for {file_path}:{line}.") }).to_string()
    } else {
        format_results(
            &format!("Chunks related to {file_path}:{line}"),
            &results,
            max_snippet_lines,
        )
        .to_string()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::indexing::dense::make_stub_model;
    use crate::indexing::dense::SelectableBasicBackend;
    use crate::indexing::index::CspIndexState;
    use crate::indexing::sparse::Bm25Index;
    use crate::types::Chunk;
    use std::cell::RefCell;

    const CODE: &[ContentType] = &[ContentType::Code];

    fn empty_index() -> CspIndex {
        CspIndex::new(CspIndexState {
            model: make_stub_model(4),
            bm25_index: Bm25Index::build(&[]),
            semantic_index: SelectableBasicBackend::from_vectors(vec![]).unwrap(),
            chunks: vec![],
            model_path: "test".to_string(),
            root: None,
            content: vec![ContentType::Code],
            files: Default::default(),
        })
    }

    fn index_with_chunk() -> CspIndex {
        let chunk = Chunk {
            content: "fn main() {}".to_string(),
            file_path: "a.ts".to_string(),
            start_line: 1,
            end_line: 10,
            language: Some("typescript".to_string()),
        };
        CspIndex::new(CspIndexState {
            model: make_stub_model(4),
            bm25_index: Bm25Index::build(&[vec!["main".to_string()]]),
            semantic_index: SelectableBasicBackend::from_vectors(vec![vec![1.0, 0.0, 0.0, 0.0]])
                .unwrap(),
            chunks: vec![chunk],
            model_path: "test".to_string(),
            root: None,
            content: vec![ContentType::Code],
            files: Default::default(),
        })
    }

    /// Stub seam: counts git vs path builds, never touches disk. `fingerprint`
    /// simulates a local source's live validity token (mutate it to fake a file
    /// change); git URLs report `None` like the real seam.
    struct Stub {
        git_calls: RefCell<usize>,
        path_calls: RefCell<usize>,
        fail: bool,
        fingerprint: RefCell<Option<String>>,
    }
    impl Stub {
        fn new() -> Self {
            Self {
                git_calls: RefCell::new(0),
                path_calls: RefCell::new(0),
                fail: false,
                fingerprint: RefCell::new(Some("fp1".to_string())),
            }
        }
    }
    impl LoadOrBuild for Stub {
        fn load_or_build(
            &self,
            source: &str,
            _c: &[ContentType],
            _r: Option<&str>,
        ) -> Result<CspIndex, String> {
            if self.fail {
                return Err("boom".to_string());
            }
            if is_git_url(source) {
                *self.git_calls.borrow_mut() += 1;
            } else {
                *self.path_calls.borrow_mut() += 1;
            }
            Ok(empty_index())
        }

        fn fingerprint(&self, source: &str, _c: &[ContentType]) -> Option<String> {
            if is_git_url(source) {
                None
            } else {
                self.fingerprint.borrow().clone()
            }
        }
    }

    #[test]
    fn cache_reuses_second_call() {
        let mut cache = IndexCache::with_seam(Stub::new());
        let first = cache.get("/tmp/repo", None, CODE).unwrap();
        let second = cache.get("/tmp/repo", None, CODE).unwrap();
        assert!(Arc::ptr_eq(&first, &second));
        assert_eq!(*cache.seam.path_calls.borrow(), 1);
    }

    #[test]
    fn cache_keys_on_content() {
        let mut cache = IndexCache::with_seam(Stub::new());
        let code = cache.get("/tmp/repo", None, CODE).unwrap();
        let docs = cache
            .get("/tmp/repo", None, &[ContentType::Code, ContentType::Docs])
            .unwrap();
        // Same repo, different content → a distinct index, not a cache hit.
        assert!(!Arc::ptr_eq(&code, &docs));
        assert_eq!(cache.size(), 2);
        assert_eq!(*cache.seam.path_calls.borrow(), 2);

        // Order and duplicates don't matter: the key is normalized.
        let again = cache
            .get(
                "/tmp/repo",
                None,
                &[ContentType::Docs, ContentType::Code, ContentType::Docs],
            )
            .unwrap();
        assert!(Arc::ptr_eq(&docs, &again));
        assert_eq!(*cache.seam.path_calls.borrow(), 2);

        // Evicting one content variant leaves the other in place.
        cache.evict("/tmp/repo", None, CODE);
        assert_eq!(cache.size(), 1);
        assert!(Arc::ptr_eq(
            &docs,
            &cache
                .get("/tmp/repo", None, &[ContentType::Code, ContentType::Docs])
                .unwrap()
        ));
    }

    #[test]
    fn resolve_content_selection_maps_default_all_and_single() {
        let default = [ContentType::Docs, ContentType::Code];
        // None → the server default, normalized to enum order.
        assert_eq!(
            resolve_content_selection(None, &default),
            vec![ContentType::Code, ContentType::Docs]
        );
        assert_eq!(
            resolve_content_selection(Some(ContentSelection::All), &default),
            vec![ContentType::Code, ContentType::Docs, ContentType::Config]
        );
        assert_eq!(
            resolve_content_selection(Some(ContentSelection::Config), &default),
            vec![ContentType::Config]
        );
    }

    #[test]
    fn content_selection_deserializes_lowercase_only() {
        for (raw, want) in [
            ("code", ContentSelection::Code),
            ("docs", ContentSelection::Docs),
            ("config", ContentSelection::Config),
            ("all", ContentSelection::All),
        ] {
            let got: ContentSelection = serde_json::from_value(json!(raw)).unwrap();
            assert_eq!(got, want);
        }
        assert!(serde_json::from_value::<ContentSelection>(json!("Docs")).is_err());
        assert!(serde_json::from_value::<ContentSelection>(json!("tests")).is_err());
    }

    #[test]
    fn cache_evict_forces_rebuild() {
        let mut cache = IndexCache::with_seam(Stub::new());
        cache.get("/tmp/repo", None, CODE).unwrap();
        assert_eq!(*cache.seam.path_calls.borrow(), 1);
        cache.evict("/tmp/repo", None, CODE);
        assert_eq!(cache.size(), 0);
        cache.get("/tmp/repo", None, CODE).unwrap();
        assert_eq!(*cache.seam.path_calls.borrow(), 2);
    }

    #[test]
    fn cache_lru_evicts_oldest() {
        let mut cache = IndexCache::with_seam(Stub::new());
        for i in 0..10 {
            cache.get(&format!("/tmp/repo-{i}"), None, CODE).unwrap();
        }
        assert_eq!(cache.size(), 10);
        cache.get("/tmp/repo-10", None, CODE).unwrap();
        assert_eq!(cache.size(), 10);
        // repo-0 (oldest) was evicted → re-getting it rebuilds.
        let before = *cache.seam.path_calls.borrow();
        cache.get("/tmp/repo-0", None, CODE).unwrap();
        assert_eq!(*cache.seam.path_calls.borrow(), before + 1);
    }

    #[test]
    fn cache_git_vs_path_routing() {
        let mut cache = IndexCache::with_seam(Stub::new());
        cache
            .get("https://github.com/org/repo.git", None, CODE)
            .unwrap();
        assert_eq!(*cache.seam.git_calls.borrow(), 1);
        assert_eq!(*cache.seam.path_calls.borrow(), 0);
        cache.get("/tmp/local", None, CODE).unwrap();
        assert_eq!(*cache.seam.path_calls.borrow(), 1);
    }

    #[test]
    fn cache_revalidates_stale_local_path() {
        let mut cache = IndexCache::with_seam(Stub::new());
        let key = cache.compute_key("/tmp/repo", None, CODE);

        cache.get("/tmp/repo", None, CODE).unwrap();
        assert_eq!(*cache.seam.path_calls.borrow(), 1);
        assert!(cache.tasks.get(&key).unwrap().revalidate_cooldown >= MIN_REVALIDATE_COOLDOWN);

        // Within the cooldown window the entry is served without a fingerprint
        // check, so it's not rebuilt even if the fingerprint has drifted.
        *cache.seam.fingerprint.borrow_mut() = Some("fp2".to_string());
        cache.get("/tmp/repo", None, CODE).unwrap();
        assert_eq!(*cache.seam.path_calls.borrow(), 1);

        // Force the cooldown to have elapsed → the next get revalidates, sees the
        // changed fingerprint, evicts, and rebuilds.
        cache.tasks.get_mut(&key).unwrap().revalidate_after = Instant::now();
        cache.get("/tmp/repo", None, CODE).unwrap();
        assert_eq!(*cache.seam.path_calls.borrow(), 2);
        assert_eq!(cache.size(), 1);

        // Rebuilt entry captured fp2; past the cooldown with an unchanged
        // fingerprint → revalidated but matches → served, no rebuild, and the
        // next revalidation is deferred by a fresh cooldown window.
        cache.tasks.get_mut(&key).unwrap().revalidate_after = Instant::now();
        cache.get("/tmp/repo", None, CODE).unwrap();
        assert_eq!(*cache.seam.path_calls.borrow(), 2);
        assert!(cache.tasks.get(&key).unwrap().revalidate_after > Instant::now());
    }

    #[test]
    fn cache_git_url_not_revalidated() {
        let mut cache = IndexCache::with_seam(Stub::new());
        let url = "https://github.com/org/repo.git";
        cache.get(url, None, CODE).unwrap();
        assert_eq!(*cache.seam.git_calls.borrow(), 1);

        // Even if the (local-only) fingerprint changes, git URLs are keyed by
        // URL+ref and never revalidated → always served from cache.
        *cache.seam.fingerprint.borrow_mut() = Some("fp2".to_string());
        cache.get(url, None, CODE).unwrap();
        assert_eq!(*cache.seam.git_calls.borrow(), 1);
    }

    #[test]
    fn cache_failure_not_poisoned() {
        let mut seam = Stub::new();
        seam.fail = true;
        let mut cache = IndexCache::with_seam(seam);
        assert!(cache.get("/tmp/will-fail", None, CODE).is_err());
        assert_eq!(cache.size(), 0);
    }

    #[test]
    fn get_index_rejects_unsafe_schemes() {
        let mut cache = IndexCache::with_seam(Stub::new());
        for url in [
            "ssh://git@github.com/o/r.git",
            "git://github.com/o/r.git",
            "file:///tmp/x",
        ] {
            let err = get_index(Some(url), None, None, CODE, &mut cache).unwrap_err();
            assert!(err.contains("Only https://, http://"), "{url}: {err}");
        }
    }

    #[test]
    fn get_index_requires_source() {
        let mut cache = IndexCache::with_seam(Stub::new());
        let err = get_index(None, None, None, CODE, &mut cache).unwrap_err();
        assert!(err.contains("No repo specified"));
    }

    #[test]
    fn get_index_allows_https_and_path() {
        let mut cache = IndexCache::with_seam(Stub::new());
        assert!(get_index(
            Some("https://github.com/o/r.git"),
            None,
            None,
            CODE,
            &mut cache
        )
        .is_ok());
        assert!(get_index(None, Some("/tmp/default"), None, CODE, &mut cache).is_ok());
    }

    #[test]
    fn search_tool_no_results() {
        let mut cache = IndexCache::with_seam(Stub::new());
        let out = search_tool(
            &mut cache,
            Some("/tmp/repo"),
            None,
            "anything",
            None,
            CODE,
            5,
            None,
            None,
        );
        assert_eq!(out, json!({ "error": "No results found." }).to_string());
    }

    struct OneChunkSeam;
    impl LoadOrBuild for OneChunkSeam {
        fn load_or_build(
            &self,
            _s: &str,
            _c: &[ContentType],
            _r: Option<&str>,
        ) -> Result<CspIndex, String> {
            Ok(index_with_chunk())
        }

        fn fingerprint(&self, _s: &str, _c: &[ContentType]) -> Option<String> {
            None
        }
    }

    #[test]
    fn search_tool_returns_results_json() {
        let mut cache = IndexCache::with_seam(OneChunkSeam);
        let out = search_tool(
            &mut cache,
            Some("/tmp/repo"),
            None,
            "main",
            None,
            CODE,
            5,
            None,
            None,
        );
        let value: serde_json::Value = serde_json::from_str(&out).unwrap();
        assert!(value.get("query").is_some());
        assert!(value["results"].as_array().is_some());
        // Full content by default (max_snippet_lines = None).
        assert!(value["results"][0].get("content").is_some());
    }

    #[test]
    fn search_tool_records_savings_when_stats_file_given() {
        let mut cache = IndexCache::with_seam(OneChunkSeam);
        let dir = tempfile::tempdir().unwrap();
        let stats_file = dir.path().join("savings.jsonl");
        let _ = search_tool(
            &mut cache,
            Some("/tmp/repo"),
            None,
            "main",
            None,
            CODE,
            5,
            None,
            Some(&stats_file),
        );
        let content = std::fs::read_to_string(&stats_file).unwrap();
        let lines: Vec<&str> = content.lines().filter(|l| !l.is_empty()).collect();
        assert_eq!(lines.len(), 1);
        assert!(lines[0].contains("\"call\":\"search\""));
    }

    #[test]
    fn search_tool_respects_max_snippet_lines_zero() {
        let mut cache = IndexCache::with_seam(OneChunkSeam);
        let out = search_tool(
            &mut cache,
            Some("/tmp/repo"),
            None,
            "main",
            None,
            CODE,
            5,
            Some(0),
            None,
        );
        let value: serde_json::Value = serde_json::from_str(&out).unwrap();
        let entry = &value["results"][0];
        // 0 lines → no content, but the location metadata is still present.
        assert!(entry.get("content").is_none());
        assert_eq!(entry["file_path"], "a.ts");
    }

    #[test]
    fn find_related_no_chunk_message() {
        let mut cache = IndexCache::with_seam(OneChunkSeam);
        let out = find_related_tool(
            &mut cache,
            Some("/tmp/repo"),
            None,
            "nope.ts",
            1,
            None,
            CODE,
            5,
            None,
            None,
        );
        assert!(out.contains("No chunk found at nope.ts:1"));
    }

    #[test]
    fn find_related_returns_json_for_known_chunk() {
        let mut cache = IndexCache::with_seam(OneChunkSeam);
        let out = find_related_tool(
            &mut cache,
            Some("/tmp/repo"),
            None,
            "a.ts",
            5,
            None,
            CODE,
            5,
            None,
            None,
        );
        // Either related results or the no-related error — both valid JSON.
        let value: serde_json::Value = serde_json::from_str(&out).unwrap();
        assert!(value.get("query").is_some() || value.get("error").is_some());
    }
}