vtcode-indexer 0.163.2

Workspace file indexer, fuzzy search, and markdown-backed storage for VT Code
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
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
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
#![expect(
    unused_results,
    reason = "File-search walker and heap operations intentionally use fluent/configuration mutation for side effects."
)]

//! Fast fuzzy file search library for VT Code.
//!
//! Uses the `ignore` crate (same as ripgrep) for parallel directory traversal
//! and `nucleo-matcher` for fuzzy matching.
//!
//! # Example
//!
//! ```ignore
//! use std::num::NonZero;
//! use std::path::Path;
//! use std::sync::Arc;
//! use std::sync::atomic::AtomicBool;
//! use vtcode_indexer::file_search::run;
//!
//! let results = run(
//!     "main",
//!     NonZero::new(100).unwrap(),
//!     Path::new("."),
//!     vec![],
//!     NonZero::new(4).unwrap(),
//!     Arc::new(AtomicBool::new(false)),
//!     false,
//!     true,
//! )?;
//!
//! for m in results.matches {
//!     println!("{}: {}", m.path, m.score);
//! }
//! # Ok::<(), anyhow::Error>(())
//! ```

use arc_swap::ArcSwapOption;
use parking_lot::Mutex;
use serde::{Deserialize, Serialize};
use std::cmp::Reverse;
use std::collections::BinaryHeap;
use std::num::NonZero;
use std::path::Path;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use tokio::sync::RwLock;

use rayon::prelude::*;
use vtcode_commons::StringId;

/// Pre-computed file index for instant queries.
///
/// This index is built in the background and cached to avoid
/// repeated directory traversals on every search.
pub struct FileIndex {
    files: Vec<StringId>,
    directories: Vec<StringId>,
    /// Immutable path text indexed by the corresponding [`StringId`].
    /// Searches only read this table, so scoring never contends on the
    /// incremental-update interner or allocates a candidate string.
    path_texts_by_id: Arc<Vec<Arc<str>>>,
    /// Used only while applying incremental index updates.
    interner: vtcode_commons::StringInterner,
    last_built: std::time::Instant,
}

/// Build a parallel walker with the given configuration.
fn build_parallel_walker(
    search_directory: &Path,
    exclude: &[String],
    threads: usize,
    respect_gitignore: bool,
    follow_links: bool,
) -> anyhow::Result<ignore::WalkParallel> {
    let mut walk_builder = ignore::WalkBuilder::new(search_directory);
    vtcode_commons::walk::apply_defaults(&mut walk_builder);

    // File-search-specific overrides
    walk_builder.threads(threads);
    walk_builder.follow_links(follow_links);
    walk_builder.require_git(false); // Search works outside git repos

    if !respect_gitignore {
        walk_builder
            .git_ignore(false)
            .git_global(false)
            .git_exclude(false)
            .ignore(false)
            .parents(false);
    }

    if !exclude.is_empty() {
        let mut override_builder = ignore::overrides::OverrideBuilder::new(search_directory);
        for exclude_pattern in exclude {
            let pattern = format!("!{exclude_pattern}");
            override_builder.add(&pattern)?;
        }
        walk_builder.overrides(override_builder.build()?);
    }

    Ok(walk_builder.build_parallel())
}

impl FileIndex {
    /// Build a file index by traversing the directory tree.
    /// This is expensive but only done once.
    fn build_from_directory(
        search_directory: &Path,
        exclude: &[String],
        respect_gitignore: bool,
        threads: usize,
    ) -> anyhow::Result<Self> {
        let walker = build_parallel_walker(search_directory, exclude, threads, respect_gitignore, true)?;

        // Collect all files and directories
        let worker_results = Arc::new(Mutex::new(Vec::new()));

        walker.run(|| {
            let search_dir = search_directory.to_path_buf();
            let mut state = IndexWorkerGuard {
                results: Arc::clone(&worker_results),
                files: Vec::new(),
                directories: Vec::new(),
            };

            Box::new(move |result| {
                let entry = match result {
                    Ok(e) => e,
                    Err(_) => return ignore::WalkState::Continue,
                };

                // Make path relative to search directory
                if let Some(rel_path) = entry.path().strip_prefix(&search_dir).ok().and_then(|p| p.to_str())
                    && !rel_path.is_empty()
                {
                    if entry.file_type().is_some_and(|file_type| file_type.is_dir()) {
                        state.directories.push(rel_path.to_string());
                    } else {
                        state.files.push(rel_path.to_string());
                    }
                }

                ignore::WalkState::Continue
            })
        });

        let worker_results = Arc::try_unwrap(worker_results)
            .map_err(|results| {
                anyhow::anyhow!("file index worker results still referenced: {}", Arc::strong_count(&results))
            })?
            .into_inner();
        let (files, directories) =
            worker_results
                .into_iter()
                .fold((Vec::new(), Vec::new()), |(mut files, mut directories), result| {
                    files.extend(result.files);
                    directories.extend(result.directories);
                    (files, directories)
                });

        let mut interner = vtcode_commons::StringInterner::new();
        let mut path_texts_by_id = Vec::with_capacity(files.len() + directories.len());
        let interned_files: Vec<StringId> = files
            .iter()
            .map(|path| intern_path(path, &mut interner, &mut path_texts_by_id))
            .collect();
        let interned_dirs: Vec<StringId> = directories
            .iter()
            .map(|path| intern_path(path, &mut interner, &mut path_texts_by_id))
            .collect();

        Ok(Self {
            files: interned_files,
            directories: interned_dirs,
            path_texts_by_id: Arc::new(path_texts_by_id),
            interner,
            last_built: std::time::Instant::now(),
        })
    }

    /// Query the index for matching paths.
    /// Much faster than re-traversing the filesystem.
    fn query(
        &self,
        pattern_text: &str,
        limit: usize,
        match_type_filter: Option<MatchType>,
    ) -> Vec<(u32, StringId, MatchType)> {
        // `query` stays serial and declarative: the parallel scoring strategy
        // is isolated behind `score_paths_top_k`, and the per-chunk top-K heaps
        // are merged by the shared `merge_top_k` helper. This keeps the index
        // query logic testable without a rayon runtime in the loop.
        let mut heaps = Vec::new();

        if match_type_filter.is_none_or(|t| t == MatchType::File) {
            heaps.push(score_paths_top_k(
                &self.files,
                self.path_texts_by_id.as_slice(),
                limit,
                pattern_text,
                MatchType::File,
            ));
        }

        if match_type_filter.is_none_or(|t| t == MatchType::Directory) {
            heaps.push(score_paths_top_k(
                &self.directories,
                self.path_texts_by_id.as_slice(),
                limit,
                pattern_text,
                MatchType::Directory,
            ));
        }

        merge_top_k(heaps, limit)
            .into_sorted_vec()
            .into_iter()
            .map(|Reverse(item)| item)
            .collect()
    }
}

fn intern_path(
    path: &str,
    interner: &mut vtcode_commons::StringInterner,
    path_texts_by_id: &mut Vec<Arc<str>>,
) -> StringId {
    let path_id = interner.intern(path);
    let path_index = path_id.as_u32() as usize;
    if path_index == path_texts_by_id.len() {
        path_texts_by_id.push(Arc::from(path));
    }
    path_id
}

/// Score `paths` in parallel rayon chunks, returning the worker-merged top-K
/// heap for `match_type`.
///
/// This is the single boundary for the parallel scoring strategy: each worker
/// thread gets its own `BestMatchesList` (matcher + haystack buffer reused via
/// `map_init`), keeps its own top-K heap, and the partial heaps are merged by
/// `merge_top_k`. Callers must not depend on equal-score ordering.
fn score_paths_top_k(
    paths: &[StringId],
    path_texts_by_id: &[Arc<str>],
    limit: usize,
    pattern_text: &str,
    match_type: MatchType,
) -> BinaryHeap<Reverse<(u32, StringId, MatchType)>> {
    const CHUNK: usize = 1024;

    // Serial fast path for small inputs: avoids the rayon thread-pool spawn
    // overhead and keeps equal-score ordering deterministic.
    if paths.len() <= CHUNK {
        let mut list = BestMatchesList::new(limit, pattern_text);
        for &path_id in paths {
            if let Some(path) = path_texts_by_id.get(path_id.as_u32() as usize) {
                list.record_match(path_id, path, match_type);
            }
        }
        return list.matches;
    }

    let heaps: Vec<_> = paths
        .par_chunks(CHUNK)
        .map_init(
            || BestMatchesList::new(limit, pattern_text),
            |list, chunk| {
                for &path_id in chunk {
                    if let Some(path) = path_texts_by_id.get(path_id.as_u32() as usize) {
                        list.record_match(path_id, path, match_type);
                    }
                }
                std::mem::take(&mut list.matches)
            },
        )
        .collect();

    merge_top_k(heaps, limit)
}

/// Merge worker-local top-K heaps into a single top-K heap.
///
/// Because each input heap already holds only its own highest-scoring `limit`
/// entries, the global top-K is a subset of their union; merging and re-keeping
/// the top-K yields the correct global result.
fn merge_top_k(
    heaps: Vec<BinaryHeap<Reverse<(u32, StringId, MatchType)>>>,
    limit: usize,
) -> BinaryHeap<Reverse<(u32, StringId, MatchType)>> {
    let mut merged = BinaryHeap::with_capacity(limit);
    for heap in heaps {
        for Reverse(item) in heap.into_vec() {
            push_top_match(&mut merged, limit, item.0, item.1, item.2);
        }
    }
    merged
}

/// A cached file index that can be shared across searches.
pub struct FileIndexCache {
    cache: Arc<RwLock<Option<Arc<FileIndex>>>>,
    /// Lock-free copy of the latest published index for synchronous callers.
    /// This keeps `refresh_background` from blocking or panicking when called
    /// on a Tokio worker that is concurrently publishing a replacement.
    snapshot: Arc<ArcSwapOption<FileIndex>>,
    /// Serializes full index builds so concurrent cache misses do not launch
    /// duplicate workspace traversals and Rayon jobs.
    build_gate: Arc<tokio::sync::Semaphore>,
    search_directory: std::path::PathBuf,
    exclude: Vec<String>,
    respect_gitignore: bool,
    threads: usize,
}

impl FileIndexCache {
    pub fn new(
        search_directory: std::path::PathBuf,
        exclude: impl IntoIterator<Item = String>,
        respect_gitignore: bool,
        threads: usize,
    ) -> Self {
        Self {
            cache: Arc::new(RwLock::new(None)),
            snapshot: Arc::new(ArcSwapOption::empty()),
            build_gate: Arc::new(tokio::sync::Semaphore::new(1)),
            search_directory,
            exclude: exclude.into_iter().collect(),
            respect_gitignore,
            threads,
        }
    }

    /// Get or build the file index.
    pub async fn get_or_build(&self) -> anyhow::Result<Arc<FileIndex>> {
        // Check if we have a cached index
        {
            let guard = self.cache.read().await;
            if let Some(index) = guard.as_ref() {
                // Check if index is stale (older than 5 minutes)
                if index.last_built.elapsed() < std::time::Duration::from_secs(300) {
                    return Ok(Arc::clone(index));
                }
            }
        }

        // Re-check after waiting for another caller's build. This avoids a
        // cache-stampede when several searches arrive on an empty/stale cache.
        let _build_permit = self.build_gate.acquire().await?;
        {
            let guard = self.cache.read().await;
            if let Some(index) = guard.as_ref()
                && index.last_built.elapsed() < std::time::Duration::from_secs(300)
            {
                return Ok(Arc::clone(index));
            }
        }

        // Directory traversal and index construction are synchronous and can
        // touch a large workspace. Keep that work off the Tokio worker so a
        // cache miss cannot delay unrelated async tasks.
        let search_directory = self.search_directory.clone();
        let exclude = self.exclude.clone();
        let respect_gitignore = self.respect_gitignore;
        let threads = self.threads;
        let index = Arc::new(
            tokio::task::spawn_blocking(move || {
                FileIndex::build_from_directory(&search_directory, &exclude, respect_gitignore, threads)
            })
            .await??,
        );

        // Cache and return
        {
            let mut guard = self.cache.write().await;
            *guard = Some(Arc::clone(&index));
            self.snapshot.store(Some(Arc::clone(&index)));
        }
        Ok(index)
    }

    /// Force refresh the index in the background.
    ///
    /// Returns the latest published index immediately while rebuilding happens
    /// asynchronously. If no Tokio runtime is available, no refresh is
    /// scheduled and the latest published index is returned unchanged.
    pub fn refresh_background(&self) -> Option<Arc<FileIndex>> {
        let runtime = match tokio::runtime::Handle::try_current() {
            Ok(runtime) => runtime,
            Err(error) => {
                tracing::debug!(%error, "cannot refresh file index without a Tokio runtime");
                return self.snapshot.load_full();
            }
        };

        // Build new index asynchronously
        let search_directory = self.search_directory.clone();
        let exclude = self.exclude.clone();
        let respect_gitignore = self.respect_gitignore;
        let threads = self.threads;
        let cache = self.cache.clone();
        let snapshot = Arc::clone(&self.snapshot);
        let build_gate = Arc::clone(&self.build_gate);

        runtime.spawn(async move {
            let _build_permit = match build_gate.acquire_owned().await {
                Ok(permit) => permit,
                Err(error) => {
                    tracing::error!(%error, "file index build gate closed");
                    return;
                }
            };

            match tokio::task::spawn_blocking(move || {
                FileIndex::build_from_directory(&search_directory, &exclude, respect_gitignore, threads)
            })
            .await
            {
                Ok(Ok(new_index)) => {
                    let new_index = Arc::new(new_index);
                    let mut guard = cache.write().await;
                    *guard = Some(Arc::clone(&new_index));
                    snapshot.store(Some(new_index));
                }
                Ok(Err(error)) => {
                    tracing::error!(%error, "failed to rebuild file index");
                }
                Err(error) => {
                    tracing::error!(%error, "file index rebuild task failed");
                }
            }
        });

        self.snapshot.load_full()
    }

    /// Incrementally update the index when a file change is detected.
    /// This is faster than a full rebuild for single file changes.
    pub fn update_file(&self, path: &str, is_added: bool) {
        let mut guard = self.cache.blocking_write();
        let Some(existing) = guard.take() else { return };

        let mut index = Arc::try_unwrap(existing).unwrap_or_else(|arc| (*arc).clone());
        if is_added {
            let path_id = intern_path(path, &mut index.interner, Arc::make_mut(&mut index.path_texts_by_id));
            let is_directory = self.search_directory.join(path).is_dir();
            if is_directory {
                index.files.retain(|&existing| existing != path_id);
                if !index.directories.contains(&path_id) {
                    index.directories.push(path_id);
                }
            } else {
                index.directories.retain(|&existing| existing != path_id);
                if !index.files.contains(&path_id) {
                    index.files.push(path_id);
                }
            }
        } else {
            let Some(path_id) = index.files.iter().chain(index.directories.iter()).copied().find(|&path_id| {
                index
                    .path_texts_by_id
                    .get(path_id.as_u32() as usize)
                    .is_some_and(|value| value.as_ref() == path)
            }) else {
                let index = Arc::new(index);
                *guard = Some(Arc::clone(&index));
                self.snapshot.store(Some(index));
                return;
            };
            index.files.retain(|&existing| existing != path_id);
            index.directories.retain(|&existing| existing != path_id);
        }
        index.last_built = std::time::Instant::now();
        let index = Arc::new(index);
        *guard = Some(Arc::clone(&index));
        self.snapshot.store(Some(index));
    }

    /// Get the age of the current index.
    pub async fn index_age(&self) -> Option<std::time::Duration> {
        let guard = self.cache.read().await;
        guard.as_ref().map(|idx| idx.last_built.elapsed())
    }
}

// Make FileIndex cloneable
impl Clone for FileIndex {
    fn clone(&self) -> Self {
        Self {
            files: self.files.clone(),
            directories: self.directories.clone(),
            path_texts_by_id: Arc::clone(&self.path_texts_by_id),
            interner: self.interner.clone(),
            last_built: self.last_built,
        }
    }
}

/// A single file match result.
///
/// Fields:
/// - `score`: Relevance score from fuzzy matching (higher is better)
/// - `path`: Path relative to the search directory
/// - `match_type`: Whether the match is a file or directory
/// - `indices`: Optional character positions for highlighting matched characters
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
#[serde(rename_all = "lowercase")]
pub enum MatchType {
    File,
    Directory,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileMatch {
    pub score: u32,
    pub path: String,
    pub match_type: MatchType,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub indices: Option<Vec<u32>>,
}

/// Complete search results with total match count.
#[derive(Debug)]
pub struct FileSearchResults {
    pub matches: Vec<FileMatch>,
    pub total_match_count: usize,
}

/// Configuration for file search operations.
pub struct FileSearchConfig {
    pub pattern_text: String,
    pub limit: NonZero<usize>,
    pub search_directory: std::path::PathBuf,
    pub exclude: Vec<String>,
    pub threads: NonZero<usize>,
    pub cancel_flag: Arc<AtomicBool>,
    pub compute_indices: bool,
    pub respect_gitignore: bool,
}

pub use vtcode_commons::paths::file_name_from_path;

/// Best matches list per worker thread (lock-free collection).
///
/// Each worker thread gets its own instance to avoid locking during
/// directory traversal. Results are merged at the end.
struct BestMatchesList {
    matches: BinaryHeap<Reverse<(u32, StringId, MatchType)>>,
    limit: usize,
    matcher: nucleo_matcher::Matcher,
    haystack_buf: Vec<char>,
    /// Pre-computed pattern - avoids per-match UTF-32 conversion
    pattern: PatternStorage,
    owned_matches: BinaryHeap<Reverse<OwnedMatchCandidate>>,
}

#[derive(Debug, Eq, PartialEq)]
struct OwnedMatchCandidate {
    score: u32,
    path: String,
    match_type: MatchType,
}

impl Ord for OwnedMatchCandidate {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.score
            .cmp(&other.score)
            .then_with(|| other.path.cmp(&self.path))
            .then_with(|| other.match_type.cmp(&self.match_type))
    }
}

impl PartialOrd for OwnedMatchCandidate {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

struct SearchAggregation {
    matches: BinaryHeap<Reverse<OwnedMatchCandidate>>,
    total_match_count: usize,
}

struct IndexWorkerResult {
    files: Vec<String>,
    directories: Vec<String>,
}

struct IndexWorkerGuard {
    results: Arc<Mutex<Vec<IndexWorkerResult>>>,
    files: Vec<String>,
    directories: Vec<String>,
}

impl Drop for IndexWorkerGuard {
    fn drop(&mut self) {
        self.results.lock().push(IndexWorkerResult {
            files: std::mem::take(&mut self.files),
            directories: std::mem::take(&mut self.directories),
        });
    }
}

struct SearchWorkerGuard {
    results: Arc<Mutex<SearchAggregation>>,
    best_list: BestMatchesList,
    total_match_count: usize,
    limit: usize,
}

impl Drop for SearchWorkerGuard {
    fn drop(&mut self) {
        let worker_matches = std::mem::take(&mut self.best_list.owned_matches);
        let mut results = self.results.lock();
        results.total_match_count += self.total_match_count;
        for Reverse(candidate) in worker_matches {
            push_owned_match(&mut results.matches, self.limit, candidate);
        }
    }
}

/// Stores a pattern in the optimal form for Utf32Str creation.
enum PatternStorage {
    /// ASCII pattern - can be used directly with Utf32Str::Ascii
    Ascii(Vec<u8>),
    /// Unicode pattern - stored as chars for Utf32Str::Unicode
    Unicode(Vec<char>),
}

impl BestMatchesList {
    fn new(limit: usize, pattern_text: &str) -> Self {
        // Normalize pattern to lowercase to work around a nucleo-matcher bug:
        // its prefilter only does case-insensitive search for lowercase needle
        // chars, not uppercase. See https://github.com/openai/codex/pull/15772.
        let pattern = if pattern_text.is_ascii() {
            PatternStorage::Ascii(pattern_text.to_ascii_lowercase().into_bytes())
        } else {
            PatternStorage::Unicode(pattern_text.to_lowercase().chars().collect())
        };

        Self {
            matches: BinaryHeap::new(),
            limit,
            matcher: nucleo_matcher::Matcher::new(nucleo_matcher::Config::DEFAULT),
            haystack_buf: Vec::with_capacity(256),
            pattern,
            owned_matches: BinaryHeap::new(),
        }
    }

    /// Score a path using the pre-computed pattern without allocating a
    /// temporary string.
    fn score_path(&mut self, path: &str) -> Option<u32> {
        let haystack = nucleo_matcher::Utf32Str::new(path, &mut self.haystack_buf);
        let needle = match &self.pattern {
            PatternStorage::Ascii(bytes) => nucleo_matcher::Utf32Str::Ascii(bytes),
            PatternStorage::Unicode(chars) => nucleo_matcher::Utf32Str::Unicode(chars),
        };
        self.matcher.fuzzy_match(haystack, needle).map(|score| score as u32)
    }

    /// Record a matching path with an already-known [`StringId`].
    fn record_match(&mut self, path_id: StringId, path: &str, match_type: MatchType) -> bool {
        let Some(score) = self.score_path(path) else {
            return false;
        };
        push_top_match(&mut self.matches, self.limit, score, path_id, match_type);
        true
    }

    fn record_scored_match(&mut self, path_id: StringId, score: u32, match_type: MatchType) {
        push_top_match(&mut self.matches, self.limit, score, path_id, match_type);
    }

    fn record_owned_match(&mut self, path: &str, score: u32, match_type: MatchType) {
        if self.owned_matches.len() == self.limit {
            let Some(Reverse(worst)) = self.owned_matches.peek() else {
                return;
            };
            if !owned_match_is_better(score, path, match_type, worst) {
                return;
            }
        }

        push_owned_match(
            &mut self.owned_matches,
            self.limit,
            OwnedMatchCandidate { score, path: path.to_owned(), match_type },
        );
    }
}

fn push_owned_match(
    matches: &mut BinaryHeap<Reverse<OwnedMatchCandidate>>,
    limit: usize,
    candidate: OwnedMatchCandidate,
) {
    if matches.len() == limit {
        let Some(Reverse(worst)) = matches.peek() else {
            return;
        };
        if !owned_match_is_better(candidate.score, candidate.path.as_str(), candidate.match_type, worst) {
            return;
        }
        matches.pop();
    }

    matches.push(Reverse(candidate));
}

fn owned_match_is_better(score: u32, path: &str, match_type: MatchType, worst: &OwnedMatchCandidate) -> bool {
    score
        .cmp(&worst.score)
        .then_with(|| worst.path.as_str().cmp(path))
        .then_with(|| worst.match_type.cmp(&match_type))
        .is_gt()
}

fn push_top_match(
    matches: &mut BinaryHeap<Reverse<(u32, StringId, MatchType)>>,
    limit: usize,
    score: u32,
    path: StringId,
    match_type: MatchType,
) -> bool {
    let candidate = (score, path, match_type);
    if matches.len() < limit {
        matches.push(Reverse(candidate));
        return true;
    }

    let Some(minimum) = matches.peek().map(|entry| &entry.0) else {
        return false;
    };

    if &candidate <= minimum {
        return false;
    }

    matches.pop();
    matches.push(Reverse(candidate));
    true
}

/// Run fuzzy file search using a pre-computed file index.
///
/// This is much faster than `run()` for repeated queries on the same
/// directory because it avoids re-traversing the filesystem.
///
/// # Arguments
///
/// * `config` - File search configuration
/// * `index_cache` - Shared cache for the pre-computed file index
///
/// # Returns
///
/// FileSearchResults containing matched files and total match count.
pub async fn run_with_index(
    config: FileSearchConfig,
    index_cache: &FileIndexCache,
) -> anyhow::Result<FileSearchResults> {
    let limit = config.limit.get();
    let cancel_flag = &config.cancel_flag;
    let compute_indices = config.compute_indices;

    // Get or build the file index
    let index = index_cache.get_or_build().await?;

    // Check cancellation
    if cancel_flag.load(Ordering::Relaxed) {
        return Ok(FileSearchResults { matches: Vec::new(), total_match_count: 0 });
    }

    // Query the index off the async runtime thread to avoid stalling
    // the tokio worker while rayon parallel-scoring runs.
    let index_for_results = index.clone();
    let matched_paths = tokio::task::spawn_blocking({
        let pattern_text = config.pattern_text.clone();
        move || Ok::<_, anyhow::Error>(index.query(&pattern_text, limit, None))
    })
    .await??;

    let total_match_count = matched_paths.len();

    // Build final results
    let matches = matched_paths
        .into_iter()
        .filter_map(|(score, path_id, match_type)| {
            let path = index_for_results.path_texts_by_id.get(path_id.as_u32() as usize)?.to_string();
            Some(FileMatch {
                score,
                path,
                match_type,
                indices: if compute_indices { Some(Vec::new()) } else { None },
            })
        })
        .collect();

    Ok(FileSearchResults { matches, total_match_count })
}

/// Run fuzzy file search with parallel traversal.
///
/// # Arguments
///
/// * `config` - File search configuration containing all search parameters
///
/// # Returns
///
/// FileSearchResults containing matched files and total match count.
pub fn run(config: FileSearchConfig) -> anyhow::Result<FileSearchResults> {
    run_with_policy(config, true, false)
}

/// Run a bounded fuzzy path search without following symbolic links.
///
/// This focused route is intended for request-scoped code search. It traverses
/// eligible paths in deterministic order and stops at the candidate cap. It
/// deliberately avoids the persistent [`FileIndexCache`].
pub fn run_bounded_no_follow(config: FileSearchConfig) -> anyhow::Result<FileSearchResults> {
    run_bounded_no_follow_with_visit(config, |_| {})
}

fn run_bounded_no_follow_with_visit(
    config: FileSearchConfig,
    mut visit: impl FnMut(&Path),
) -> anyhow::Result<FileSearchResults> {
    let limit = config.limit.get();
    let search_directory = &config.search_directory;
    let mut walk_builder = ignore::WalkBuilder::new(search_directory);
    vtcode_commons::walk::apply_defaults(&mut walk_builder);
    walk_builder
        .follow_links(false)
        .require_git(false)
        .sort_by_file_path(|left, right| left.cmp(right));

    if !config.respect_gitignore {
        walk_builder
            .git_ignore(false)
            .git_global(false)
            .git_exclude(false)
            .ignore(false)
            .parents(false);
    }

    if !config.exclude.is_empty() {
        let mut override_builder = ignore::overrides::OverrideBuilder::new(search_directory);
        for exclude_pattern in &config.exclude {
            override_builder.add(&format!("!{exclude_pattern}"))?;
        }
        walk_builder.overrides(override_builder.build()?);
    }

    let interner = Arc::new(Mutex::new(vtcode_commons::StringInterner::new()));
    let mut matches = BestMatchesList::new(limit, &config.pattern_text);
    let mut matching_count = 0usize;
    for result in walk_builder.build() {
        if config.cancel_flag.load(Ordering::Relaxed) {
            break;
        }
        let entry = match result {
            Ok(entry) => entry,
            Err(_) => continue,
        };
        visit(entry.path());
        if !entry.file_type().is_some_and(|file_type| file_type.is_file()) {
            continue;
        }
        let Some(relative_path) = entry
            .path()
            .strip_prefix(search_directory)
            .ok()
            .and_then(|path| path.to_str())
            .filter(|path| !path.is_empty())
        else {
            continue;
        };
        let Some(score) = matches.score_path(relative_path) else {
            continue;
        };
        let path_id = interner.lock().intern(relative_path);
        matches.record_scored_match(path_id, score, MatchType::File);
        matching_count += 1;
        if matching_count >= limit {
            break;
        }
    }

    let interner_guard = interner.lock();
    let matches = matches
        .matches
        .into_sorted_vec()
        .into_iter()
        .filter_map(|Reverse((score, path_id, match_type))| {
            let path = interner_guard.get(path_id)?.to_string();
            Some(FileMatch {
                score,
                path,
                match_type,
                indices: config.compute_indices.then(Vec::new),
            })
        })
        .collect();

    Ok(FileSearchResults {
        matches,
        // Reaching the cap terminates traversal, so report conservative
        // truncation without scanning the rest of the tree for an exact total.
        total_match_count: matching_count + usize::from(matching_count >= limit),
    })
}

fn run_with_policy(
    config: FileSearchConfig,
    follow_links: bool,
    files_only: bool,
) -> anyhow::Result<FileSearchResults> {
    let limit = config.limit.get();
    let search_directory = &config.search_directory;
    let exclude = &config.exclude;
    let threads = config.threads.get();
    let cancel_flag = &config.cancel_flag;
    let compute_indices = config.compute_indices;
    let respect_gitignore = config.respect_gitignore;

    let walker = build_parallel_walker(search_directory, exclude, threads, respect_gitignore, follow_links)?;

    let worker_results = Arc::new(Mutex::new(SearchAggregation { matches: BinaryHeap::new(), total_match_count: 0 }));
    walker.run(|| {
        let mut state = SearchWorkerGuard {
            results: Arc::clone(&worker_results),
            best_list: BestMatchesList::new(limit, &config.pattern_text),
            total_match_count: 0,
            limit,
        };

        Box::new(move |result| {
            // Check cancellation flag periodically
            if cancel_flag.load(Ordering::Relaxed) {
                return ignore::WalkState::Quit;
            }

            let entry = match result {
                Ok(e) => e,
                Err(_) => return ignore::WalkState::Continue,
            };

            // Make path relative to search directory
            let relative_path = entry.path().strip_prefix(search_directory).ok().and_then(|p| p.to_str());

            let path_to_match = match relative_path {
                Some(p) if !p.is_empty() => p,
                _ => return ignore::WalkState::Continue, // Skip root and non-relative paths
            };

            let Some(file_type) = entry.file_type() else {
                return ignore::WalkState::Continue;
            };
            let match_type = if file_type.is_dir() {
                MatchType::Directory
            } else {
                MatchType::File
            };

            if files_only && match_type == MatchType::Directory {
                return ignore::WalkState::Continue;
            }

            // Try to add to results - no contention with other workers
            let Some(score) = state.best_list.score_path(path_to_match) else {
                return ignore::WalkState::Continue;
            };
            state.best_list.record_owned_match(path_to_match, score, match_type);
            state.total_match_count += 1;

            ignore::WalkState::Continue
        })
    });

    let results = Arc::try_unwrap(worker_results)
        .map_err(|results| {
            anyhow::anyhow!("file search worker results still referenced: {}", Arc::strong_count(&results))
        })?
        .into_inner();
    let total_match_count = results.total_match_count;
    let mut candidates = results
        .matches
        .into_iter()
        .map(|Reverse(candidate)| candidate)
        .collect::<Vec<_>>();
    candidates.sort_by(|left, right| {
        right
            .score
            .cmp(&left.score)
            .then_with(|| left.path.cmp(&right.path))
            .then_with(|| left.match_type.cmp(&right.match_type))
    });
    candidates.truncate(limit);

    // Build final results
    let matches = candidates
        .into_iter()
        .map(|candidate| FileMatch {
            score: candidate.score,
            path: candidate.path,
            match_type: candidate.match_type,
            indices: if compute_indices { Some(Vec::new()) } else { None },
        })
        .collect();

    Ok(FileSearchResults { matches, total_match_count })
}

#[cfg(test)]
mod tests {
    use super::{
        FileIndexCache, FileSearchConfig, MatchType, run, run_bounded_no_follow, run_bounded_no_follow_with_visit,
        run_with_index,
    };
    use std::num::NonZero;
    use std::sync::Arc;
    use std::sync::atomic::AtomicBool;
    use tempfile::TempDir;

    #[tokio::test(flavor = "current_thread")]
    async fn concurrent_index_builds_share_async_cache_entry() {
        let workspace = TempDir::new().expect("workspace");
        std::fs::write(workspace.path().join("widget.rs"), "fn widget() {}\n").expect("fixture source");

        let cache = FileIndexCache::new(workspace.path().to_path_buf(), Vec::new(), true, 1);
        let (first, second) = tokio::join!(cache.get_or_build(), cache.get_or_build());
        let first = first.expect("build file index");
        let second = second.expect("reuse file index");

        assert!(Arc::ptr_eq(&first, &second));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn background_refresh_is_safe_when_called_from_tokio() {
        let workspace = TempDir::new().expect("workspace");
        std::fs::write(workspace.path().join("widget.rs"), "fn widget() {}\n").expect("fixture source");

        let cache = FileIndexCache::new(workspace.path().to_path_buf(), Vec::new(), false, 1);
        cache.get_or_build().await.expect("initial index");

        assert!(cache.refresh_background().is_some());
    }

    #[test]
    fn background_refresh_returns_snapshot_without_runtime() {
        let workspace = TempDir::new().expect("workspace");
        std::fs::write(workspace.path().join("widget.rs"), "fn widget() {}\n").expect("fixture source");

        let runtime = tokio::runtime::Runtime::new().expect("Tokio runtime");
        let cache = FileIndexCache::new(workspace.path().to_path_buf(), Vec::new(), false, 1);
        runtime.block_on(cache.get_or_build()).expect("initial index");
        drop(runtime);

        assert!(cache.refresh_background().is_some());
    }

    #[tokio::test(flavor = "current_thread")]
    async fn incremental_directory_updates_use_the_cache_root() {
        let workspace = TempDir::new().expect("workspace");
        std::fs::write(workspace.path().join("widget.rs"), "fn widget() {}\n").expect("fixture source");
        std::fs::create_dir(workspace.path().join("new_directory")).expect("fixture directory");

        let cache = Arc::new(FileIndexCache::new(workspace.path().to_path_buf(), Vec::new(), false, 1));
        cache.get_or_build().await.expect("initial index");

        tokio::task::spawn_blocking({
            let cache = Arc::clone(&cache);
            move || cache.update_file("new_directory", true)
        })
        .await
        .expect("incremental directory update task");

        let index = cache.get_or_build().await.expect("updated index");
        let matches = index.query("new_directory", 16, None);
        assert!(matches.iter().any(|(_, _, match_type)| *match_type == MatchType::Directory));
    }

    fn indexed_search_config(
        workspace: &std::path::Path,
        pattern: &str,
        cancel_flag: Arc<AtomicBool>,
    ) -> FileSearchConfig {
        FileSearchConfig {
            pattern_text: pattern.to_string(),
            limit: NonZero::new(16).expect("non-zero limit"),
            search_directory: workspace.to_path_buf(),
            exclude: Vec::new(),
            threads: NonZero::new(1).expect("non-zero threads"),
            cancel_flag,
            compute_indices: false,
            respect_gitignore: false,
        }
    }

    fn result_signature(results: &super::FileSearchResults) -> Vec<(u32, String, MatchType)> {
        results
            .matches
            .iter()
            .map(|candidate| (candidate.score, candidate.path.clone(), candidate.match_type))
            .collect()
    }

    #[tokio::test(flavor = "current_thread")]
    async fn indexed_search_preserves_scores_order_and_match_types() {
        let workspace = TempDir::new().expect("workspace");
        std::fs::create_dir_all(workspace.path().join("src/widget_dir")).expect("fixture directory");
        std::fs::write(workspace.path().join("src/widget.rs"), "fn widget() {}\n").expect("fixture source");
        std::fs::write(workspace.path().join("src/widget_test.rs"), "fn widget_test() {}\n").expect("fixture source");
        std::fs::write(workspace.path().join("README.md"), "widget documentation\n").expect("fixture docs");

        let cache = FileIndexCache::new(workspace.path().to_path_buf(), Vec::new(), false, 1);
        let first =
            run_with_index(indexed_search_config(workspace.path(), "widget", Arc::new(AtomicBool::new(false))), &cache)
                .await
                .expect("indexed search");
        let second =
            run_with_index(indexed_search_config(workspace.path(), "widget", Arc::new(AtomicBool::new(false))), &cache)
                .await
                .expect("repeat indexed search");

        assert_eq!(result_signature(&first), result_signature(&second));
        assert!(
            first
                .matches
                .iter()
                .any(|candidate| candidate.match_type == MatchType::Directory)
        );
        assert!(first.matches.iter().any(|candidate| candidate.match_type == MatchType::File));
        assert!(first.matches.windows(2).all(|window| window[0].score >= window[1].score));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn indexed_search_honors_cancellation_before_scoring() {
        let workspace = TempDir::new().expect("workspace");
        std::fs::write(workspace.path().join("widget.rs"), "fn widget() {}\n").expect("fixture source");
        let cache = FileIndexCache::new(workspace.path().to_path_buf(), Vec::new(), false, 1);
        let cancel_flag = Arc::new(AtomicBool::new(true));

        let results = run_with_index(indexed_search_config(workspace.path(), "widget", cancel_flag), &cache)
            .await
            .expect("cancelled indexed search");
        assert!(results.matches.is_empty());
        assert_eq!(results.total_match_count, 0);
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn incremental_updates_do_not_mutate_an_old_search_index() {
        let workspace = TempDir::new().expect("workspace");
        std::fs::write(workspace.path().join("old_widget.rs"), "fn old_widget() {}\n").expect("fixture source");
        let cache = Arc::new(FileIndexCache::new(workspace.path().to_path_buf(), Vec::new(), false, 1));
        let old_index = cache.get_or_build().await.expect("initial index");

        tokio::task::spawn_blocking({
            let cache = Arc::clone(&cache);
            move || cache.update_file("new_widget.rs", true)
        })
        .await
        .expect("incremental update task");

        let old_matches = old_index.query("widget", 16, None);
        let new_index = cache.get_or_build().await.expect("updated index");
        let new_matches = new_index.query("widget", 16, None);
        let old_paths = old_matches
            .iter()
            .filter_map(|(_, path_id, _)| old_index.path_texts_by_id.get(path_id.as_u32() as usize))
            .map(AsRef::as_ref)
            .collect::<Vec<&str>>();
        let new_paths = new_matches
            .iter()
            .filter_map(|(_, path_id, _)| new_index.path_texts_by_id.get(path_id.as_u32() as usize))
            .map(AsRef::as_ref)
            .collect::<Vec<&str>>();

        assert!(!old_paths.contains(&"new_widget.rs"));
        assert!(new_paths.contains(&"new_widget.rs"));
    }

    fn uncached_search_config(
        workspace: &std::path::Path,
        pattern: &str,
        limit: usize,
        cancel_flag: Arc<AtomicBool>,
    ) -> FileSearchConfig {
        FileSearchConfig {
            pattern_text: pattern.to_string(),
            limit: NonZero::new(limit).expect("non-zero limit"),
            search_directory: workspace.to_path_buf(),
            exclude: Vec::new(),
            threads: NonZero::new(4).expect("non-zero threads"),
            cancel_flag,
            compute_indices: false,
            respect_gitignore: false,
        }
    }

    #[test]
    fn uncached_parallel_search_aggregates_worker_paths_and_counts() {
        let workspace = TempDir::new().expect("workspace");
        for index in 0..64 {
            std::fs::create_dir(workspace.path().join(format!("widget_dir_{index:03}"))).expect("fixture directory");
            std::fs::write(workspace.path().join(format!("widget_file_{index:03}.rs")), "fn widget() {}\n")
                .expect("fixture source");
        }

        let results = run(uncached_search_config(workspace.path(), "widget", 32, Arc::new(AtomicBool::new(false))))
            .expect("uncached parallel search");

        assert_eq!(results.total_match_count, 128);
        assert_eq!(results.matches.len(), 32);
        let unique_paths = results
            .matches
            .iter()
            .map(|candidate| candidate.path.as_str())
            .collect::<std::collections::HashSet<_>>();
        assert_eq!(unique_paths.len(), results.matches.len());
        assert!(results.matches.iter().all(|candidate| candidate.path.contains("widget")));
    }

    #[test]
    fn uncached_parallel_search_honors_cancellation() {
        let workspace = TempDir::new().expect("workspace");
        for index in 0..32 {
            std::fs::write(workspace.path().join(format!("widget_{index:03}.rs")), "fn widget() {}\n")
                .expect("fixture source");
        }
        let cancel_flag = Arc::new(AtomicBool::new(true));

        let results = run(uncached_search_config(workspace.path(), "widget", 16, cancel_flag))
            .expect("cancelled uncached search");

        assert!(results.matches.is_empty());
        assert_eq!(results.total_match_count, 0);
    }

    #[test]
    fn uncached_equal_score_results_are_lexically_ordered_and_repeatable() {
        let workspace = TempDir::new().expect("workspace");
        for name in ["a_x.rs", "b_x.rs", "c_x.rs", "d_x.rs", "e_x.rs"] {
            std::fs::write(workspace.path().join(name), "fn x() {}\n").expect("fixture source");
        }

        let search = || {
            run(uncached_search_config(workspace.path(), "x", 3, Arc::new(AtomicBool::new(false))))
                .expect("uncached equal-score search")
                .matches
                .into_iter()
                .map(|candidate| (candidate.score, candidate.path))
                .collect::<Vec<_>>()
        };

        let expected = search();
        for _ in 0..20 {
            assert_eq!(search(), expected);
        }
        assert!(
            expected.windows(2).all(|window| {
                window[0].0 > window[1].0 || (window[0].0 == window[1].0 && window[0].1 <= window[1].1)
            })
        );
    }

    fn bounded_paths(workspace: &std::path::Path) -> Vec<String> {
        run_bounded_no_follow(FileSearchConfig {
            pattern_text: "widget".to_string(),
            limit: NonZero::new(2).expect("non-zero limit"),
            search_directory: workspace.to_path_buf(),
            exclude: Vec::new(),
            threads: NonZero::new(4).expect("non-zero threads"),
            cancel_flag: Arc::new(AtomicBool::new(false)),
            compute_indices: false,
            respect_gitignore: true,
        })
        .expect("bounded path search")
        .matches
        .into_iter()
        .map(|candidate| candidate.path)
        .collect()
    }

    #[test]
    fn bounded_path_selection_is_stable_across_repeated_walks() {
        let workspace = TempDir::new().expect("workspace");
        for directory in ["z", "a", "m", "b", "y"] {
            let directory = workspace.path().join(directory);
            std::fs::create_dir(&directory).expect("fixture directory");
            std::fs::write(directory.join("widget.rs"), "fn widget() {}\n").expect("fixture source");
        }

        let expected = bounded_paths(workspace.path());
        assert_eq!(expected.len(), 2);
        for _ in 0..20 {
            assert_eq!(bounded_paths(workspace.path()), expected);
        }
    }

    #[test]
    fn bounded_path_selection_is_the_sorted_prefix_and_stops_early() {
        let workspace = TempDir::new().expect("workspace");
        for directory in ["z", "a", "m", "b", "y"] {
            let directory = workspace.path().join(directory);
            std::fs::create_dir(&directory).expect("fixture directory");
            std::fs::write(directory.join("widget.rs"), "fn widget() {}\n").expect("fixture source");
        }
        let mut visited = Vec::new();

        let results = run_bounded_no_follow_with_visit(
            FileSearchConfig {
                pattern_text: "widget".to_string(),
                limit: NonZero::new(2).expect("non-zero limit"),
                search_directory: workspace.path().to_path_buf(),
                exclude: Vec::new(),
                threads: NonZero::new(4).expect("non-zero threads"),
                cancel_flag: Arc::new(AtomicBool::new(false)),
                compute_indices: false,
                respect_gitignore: true,
            },
            |path| visited.push(path.to_path_buf()),
        )
        .expect("bounded path search");
        let mut paths = results.matches.into_iter().map(|candidate| candidate.path).collect::<Vec<_>>();
        paths.sort();

        assert_eq!(paths, vec!["a/widget.rs", "b/widget.rs"]);
        assert!(visited.len() < 11, "the bounded route must stop before traversing the complete fixture tree");
        assert_eq!(results.total_match_count, 3);
    }
}