bmrk 0.4.0

A fast TUI for directory navigation and bookmark management
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
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
// Allow many arguments for the background scan function - it needs context for BFS traversal
#![allow(clippy::too_many_arguments)]

use crate::dir_index::DirIndex;
use crate::tree_node::TreeNodeRef;
use crossbeam_channel::{unbounded, Receiver, Sender};
use std::collections::{HashSet, VecDeque};
use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::sync::{
    atomic::{AtomicBool, Ordering},
    Arc,
};
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant};

/// Delay after a Phase-1 (in-memory) miss before Phase 2 (disk scan) starts, so fast typing
/// doesn't spawn a scan thread per keystroke.
const PHASE2_DEBOUNCE_MS: u64 = 150;

/// Upper bound on how many matches are collected for a single buffer, in both Phase 1 (in-memory)
/// and Phase 2 (disk scan). Bounds memory/scan cost for a broad prefix while still giving
/// `Shift+Tab` cycling something to work with.
pub(crate) const MAX_MATCHES: usize = 20;

/// Messages from the background scan thread to the main thread.
enum QuickJumpMessage {
    /// The first directory matching the prefix — the initial jump target.
    Found(PathBuf),
    /// An additional matching directory found after the first, for the cycle list.
    MoreFound(PathBuf),
    /// Progress update: number of directories scanned.
    Progress(usize),
    /// The scan finished (cap reached or subtree exhausted); no more messages will follow.
    Done,
}

/// Incremental type-ahead: jumps to the first folder (BFS, shallowest first) matching a typed
/// prefix anywhere under the current navigation root. When more than one folder matches,
/// `Shift+Tab` cycles through the rest via [`QuickJump::cycle_next`].
pub struct QuickJump {
    /// Whether quick-jump mode is currently active.
    pub active: bool,
    /// The typed prefix, accumulated character by character.
    pub buffer: String,
    /// Whether a Phase-2 background disk scan is currently running.
    pub is_scanning: bool,
    /// Number of directories scanned by the current/last Phase-2 scan.
    pub scanned_count: usize,
    /// Whether the current buffer has a match (in memory or on disk). Used by the UI to style
    /// the indicator bar; always `true` for an empty buffer.
    pub has_match: bool,
    /// All folders currently known to match the buffer, in the order they were found (shallowest
    /// first). Populated from Phase 1 (in-memory) or incrementally from Phase 2 (disk scan), and
    /// capped at [`MAX_MATCHES`]. `matches[0]` is always the folder that was jumped to;
    /// `Shift+Tab` cycles through the rest via [`QuickJump::cycle_next`].
    pub matches: Vec<PathBuf>,
    /// Index into `matches` of the folder currently jumped to.
    pub current_index: usize,
    /// Stack of locked path segments, one per `/` pressed so far — the search scope is
    /// `scan_stack.last()`, or the entire subtree of the navigation root when empty (the
    /// default, pre-`/` behavior). Each `/` pushes the currently matched folder (see
    /// [`push_segment`](Self::push_segment)); each `Backspace` at a segment boundary pops one
    /// back off (see [`pop_segment`](Self::pop_segment)).
    pub scan_stack: Vec<PathBuf>,

    scan_thread: Option<JoinHandle<()>>,
    cancel_flag: Option<Arc<AtomicBool>>,
    result_receiver: Option<Receiver<QuickJumpMessage>>,
    pending_scan_at: Option<Instant>,
}

impl Default for QuickJump {
    fn default() -> Self {
        Self::new()
    }
}

impl QuickJump {
    /// Create a new, inactive `QuickJump`.
    pub fn new() -> Self {
        Self {
            active: false,
            buffer: String::new(),
            is_scanning: false,
            scanned_count: 0,
            has_match: true,
            matches: Vec::new(),
            current_index: 0,
            scan_stack: Vec::new(),
            scan_thread: None,
            cancel_flag: None,
            result_receiver: None,
            pending_scan_at: None,
        }
    }

    /// Enter quick-jump mode, resetting the buffer and search scope.
    pub fn activate(&mut self) {
        self.active = true;
        self.buffer.clear();
        self.has_match = true;
        self.matches.clear();
        self.current_index = 0;
        self.scan_stack.clear();
        self.cancel_scan();
        self.pending_scan_at = None;
    }

    /// Exit quick-jump mode, resetting the buffer, search scope, and cancelling any in-flight
    /// scan.
    pub fn deactivate(&mut self) {
        self.active = false;
        self.buffer.clear();
        self.has_match = true;
        self.matches.clear();
        self.current_index = 0;
        self.scan_stack.clear();
        self.cancel_scan();
        self.pending_scan_at = None;
    }

    /// Lock in the currently matched folder as a new path segment — called when `/` is pressed
    /// with a confirmed match. Pushes `path` onto [`scan_stack`](Self::scan_stack) and appends a
    /// `/` to the buffer instead of clearing it, so the bar keeps showing the whole path built up
    /// so far (e.g. `alpha` then `alpha/shared`). Resets the per-segment match state so the next
    /// keystroke starts a fresh search scoped to `path`. Does not touch `Navigation` or its tree
    /// state — the caller is responsible for physically expanding `path` in the tree.
    pub fn push_segment(&mut self, path: PathBuf) {
        self.scan_stack.push(path);
        self.buffer.push('/');
        self.has_match = true;
        self.matches.clear();
        self.current_index = 0;
        self.cancel_scan();
        self.pending_scan_at = None;
    }

    /// Undo the most recently locked path segment — called when `Backspace` removes the buffer's
    /// trailing `/`. A no-op (returns `None`) unless the buffer currently ends with `/`, i.e. the
    /// cursor is exactly at a segment boundary with nothing typed yet in the new segment. Strips
    /// that trailing `/` and pops [`scan_stack`](Self::scan_stack), returning the popped path so
    /// the caller can decide whether/how to collapse it in the tree. Resets the per-segment match
    /// state, mirroring [`push_segment`](Self::push_segment).
    pub fn pop_segment(&mut self) -> Option<PathBuf> {
        if !self.buffer.ends_with('/') {
            return None;
        }
        self.buffer.pop();
        let popped = self.scan_stack.pop();
        self.has_match = true;
        self.matches.clear();
        self.current_index = 0;
        self.cancel_scan();
        self.pending_scan_at = None;
        popped
    }

    /// The active search prefix: the buffer text after the last locked `/` segment (or the whole
    /// buffer if nothing is locked), lowercased. This is the single source of truth for what
    /// Phase 1, Phase 1.5, and Phase 2 all search for — previously computed independently in
    /// `event_handler.rs` (correctly, via `rsplit`) and in `tick` (incorrectly, from the raw
    /// buffer), which let the two drift out of sync (`.debug/BDP.md` Part 5, Findings #2 + #9).
    pub fn active_prefix(&self) -> String {
        self.buffer
            .rsplit('/')
            .next()
            .unwrap_or_default()
            .to_lowercase()
    }

    /// Runs Phase 1 (in-memory BFS) and Phase 1.5 (dir_index lookup) for the current buffer and
    /// current `scan_stack`, merging and capping results the same way for both sources. Does not
    /// touch `Navigation` — jumping to the result stays the caller's responsibility (tree-state
    /// mutation is `Navigation`'s domain per `CLAUDE.md`'s module boundaries).
    ///
    /// A locked scope (`scan_stack.last()`) whose node isn't (or isn't yet) loaded in the tree
    /// yields no Phase 1 matches rather than falling back to searching from the tree root —
    /// widening the search back out in that case would silently ignore the lock the user just set.
    pub fn resolve_sync_matches(
        &self,
        tree_root: &TreeNodeRef,
        dir_index: &DirIndex,
        show_hidden: bool,
    ) -> Vec<PathBuf> {
        let prefix_lower = self.active_prefix();
        let scoped_path = self.scan_stack.last();

        let mut matches = match scoped_path {
            Some(path) => find_node_by_path(tree_root, path)
                .map(|node| find_in_loaded_nodes(&node, &prefix_lower, show_hidden))
                .unwrap_or_default(),
            None => find_in_loaded_nodes(tree_root, &prefix_lower, show_hidden),
        };

        let root_path = scoped_path
            .cloned()
            .unwrap_or_else(|| tree_root.borrow().path.clone());
        for path in dir_index.prefix_matches(&root_path, &prefix_lower, show_hidden, MAX_MATCHES) {
            if !matches.contains(&path) {
                matches.push(path);
            }
        }
        matches.sort_by_key(|p| p.components().count());
        matches.truncate(MAX_MATCHES);
        matches
    }

    /// Cycle forward to the next known match, wrapping around after the last one. Returns the
    /// path to jump to, or `None` if fewer than two matches are known yet (nothing to cycle to).
    pub fn cycle_next(&mut self) -> Option<PathBuf> {
        if self.matches.len() < 2 {
            return None;
        }
        self.current_index = (self.current_index + 1) % self.matches.len();
        self.matches.get(self.current_index).cloned()
    }

    /// Append a character to the buffer. Always accepted, even with no current match —
    /// see the "always-accept buffer" design decision in `.debug/BDP.md`.
    pub fn add_char(&mut self, c: char) {
        self.buffer.push(c);
    }

    /// Remove the last character from the buffer.
    pub fn backspace(&mut self) {
        self.buffer.pop();
    }

    /// Schedule a debounced Phase-2 disk scan for the current buffer, cancelling any scan or
    /// pending schedule for a previous buffer.
    pub fn schedule_scan(&mut self) {
        self.cancel_scan();
        self.pending_scan_at = Some(Instant::now() + Duration::from_millis(PHASE2_DEBOUNCE_MS));
    }

    /// Cancel any in-flight scan and any pending (not yet started) scan request.
    pub fn clear_pending(&mut self) {
        self.cancel_scan();
        self.pending_scan_at = None;
    }

    /// Cancel the current background scan thread, if any. Does not block on the thread —
    /// it checks the cancellation flag frequently and is simply detached.
    fn cancel_scan(&mut self) {
        if let Some(flag) = self.cancel_flag.take() {
            flag.store(true, Ordering::Relaxed);
        }
        self.scan_thread = None;
        self.result_receiver = None;
        self.is_scanning = false;
        self.scanned_count = 0;
    }

    fn start_scan(
        &mut self,
        root_path: PathBuf,
        prefix_lower: String,
        show_hidden: bool,
        follow_symlinks: bool,
    ) {
        self.cancel_scan();

        let (result_tx, result_rx) = unbounded();
        let cancelled = Arc::new(AtomicBool::new(false));
        let cancelled_thread = Arc::clone(&cancelled);

        let handle = thread::spawn(move || {
            deep_scan_bfs(
                &root_path,
                &prefix_lower,
                show_hidden,
                follow_symlinks,
                &result_tx,
                &cancelled_thread,
            );
        });

        self.scan_thread = Some(handle);
        self.cancel_flag = Some(cancelled);
        self.result_receiver = Some(result_rx);
        self.is_scanning = true;
    }

    /// Called on every idle tick of the main event loop. Starts the debounced Phase-2 scan if
    /// due, and drains any results from a running scan.
    ///
    /// `nav_root` is the navigation root — the *unscoped* root, not the locked scope. The scan
    /// root is derived internally from `self.scan_stack.last()` (falling back to `nav_root` when
    /// nothing is locked), the same self-deriving pattern as [`Self::resolve_sync_matches`]
    /// (`.debug/BDP.md` Part 5, Finding #9 — this used to be computed by the caller too, the same
    /// caller/callee split that let Finding #2's prefix bug happen).
    ///
    /// Returns `(has_updates, jump_target)`: `has_updates` is `true` if the UI should redraw
    /// (scan started/finished, progress changed); `jump_target` is `Some(path)` the moment the
    /// *first* match arrives from the background scan. Any further matches found by the same
    /// scan are appended to `matches` for `Shift+Tab` cycling without triggering another jump.
    pub fn tick(
        &mut self,
        nav_root: &Path,
        show_hidden: bool,
        follow_symlinks: bool,
    ) -> (bool, Option<PathBuf>) {
        let mut has_updates = false;

        if let Some(at) = self.pending_scan_at {
            if Instant::now() >= at {
                self.pending_scan_at = None;
                let prefix_lower = self.active_prefix();
                let scan_root = self
                    .scan_stack
                    .last()
                    .cloned()
                    .unwrap_or_else(|| nav_root.to_path_buf());
                self.start_scan(scan_root, prefix_lower, show_hidden, follow_symlinks);
                has_updates = true;
            }
        }

        let (found, updated) = self.poll_results();
        if updated {
            has_updates = true;
        }

        (has_updates, found)
    }

    fn poll_results(&mut self) -> (Option<PathBuf>, bool) {
        let mut found = None;
        let mut done = false;
        let mut has_updates = false;

        if let Some(ref rx) = self.result_receiver {
            while let Ok(msg) = rx.try_recv() {
                has_updates = true;
                match msg {
                    QuickJumpMessage::Found(path) => {
                        found = Some(path.clone());
                        self.matches.push(path);
                        self.current_index = 0;
                    }
                    QuickJumpMessage::MoreFound(path) => {
                        self.matches.push(path);
                    }
                    QuickJumpMessage::Progress(count) => {
                        self.scanned_count = count;
                    }
                    QuickJumpMessage::Done => {
                        done = true;
                    }
                }
            }
        }

        if done {
            self.scan_thread = None;
            self.cancel_flag = None;
            self.result_receiver = None;
            self.is_scanning = false;
            // `matches` accumulates across every tick of this scan (not just the current drain),
            // so it — not the `found` local, which is only set on the tick a message arrives —
            // is the source of truth for whether the scan matched anything.
            self.has_match = !self.matches.is_empty();
        }

        (found, has_updates)
    }
}

impl Drop for QuickJump {
    fn drop(&mut self) {
        self.cancel_scan();
    }
}

/// Phase 1: synchronous BFS search through already-loaded (in-memory) tree nodes for every
/// directory whose name starts with `prefix_lower`, under `root` (not matching `root` itself).
///
/// Unlike `Search::search_loaded_nodes`, this descends into a node's children whenever they are
/// non-empty (loaded at some point), not only into currently-expanded nodes — a folder expanded
/// earlier and since collapsed is still in memory and should still be found at zero I/O cost.
///
/// Returns matches in the order found (shallowest first, then BFS order within a level) — the
/// first entry is the jump target, the rest feed `Shift+Tab` cycling. Since this traversal is
/// purely in-memory (no disk I/O), it collects up to [`MAX_MATCHES`] before stopping, capping
/// memory/time for a broad prefix under a huge already-loaded subtree.
pub fn find_in_loaded_nodes(
    root: &TreeNodeRef,
    prefix_lower: &str,
    show_hidden: bool,
) -> Vec<PathBuf> {
    if prefix_lower.is_empty() {
        return Vec::new();
    }

    let mut matches: Vec<PathBuf> = Vec::new();

    let mut queue: VecDeque<TreeNodeRef> = VecDeque::new();
    {
        let root_borrowed = root.borrow();
        let children_count = root_borrowed.children.len();
        drop(root_borrowed);
        for i in 0..children_count {
            let child = Rc::clone(&root.borrow().children[i]);
            queue.push_back(child);
        }
    }

    while let Some(node) = queue.pop_front() {
        let node_borrowed = node.borrow();

        if !show_hidden && crate::tree_node::is_hidden_name(&node_borrowed.name) {
            continue;
        }

        if node_borrowed.is_dir && node_borrowed.name.to_lowercase().starts_with(prefix_lower) {
            matches.push(node_borrowed.path.clone());
            if matches.len() >= MAX_MATCHES {
                break;
            }
        }

        let children_count = node_borrowed.children.len();
        drop(node_borrowed);
        for i in 0..children_count {
            let child = Rc::clone(&node.borrow().children[i]);
            queue.push_back(child);
        }
    }

    matches
}

/// Read-only lookup of the in-memory node at `target`, by walking down through already-loaded
/// `children` from `root`. Returns `None` if `target` isn't `root` or under it, or if the chain
/// isn't loaded that far — callers must treat a `None` as "Phase 1 has nothing to offer here",
/// not as an error; Phase 2 (disk scan) only ever needs the `Path`, not this node, and still
/// works correctly regardless. Never loads children or mutates the tree — used by quick jump's
/// `/` narrowing, which must not change `Navigation`'s tree state (see `.debug/BDP.md` Part 4).
pub(crate) fn find_node_by_path(root: &TreeNodeRef, target: &Path) -> Option<TreeNodeRef> {
    let root_path = root.borrow().path.clone();
    if root_path == target {
        return Some(Rc::clone(root));
    }
    if !target.starts_with(&root_path) {
        return None;
    }
    let children_count = root.borrow().children.len();
    for i in 0..children_count {
        let child = Rc::clone(&root.borrow().children[i]);
        if let Some(found) = find_node_by_path(&child, target) {
            return Some(found);
        }
    }
    None
}

/// Phase 2: level-order (BFS) disk walk under `root_path`, looking for directory entries whose
/// name starts with `prefix_lower`. Sends `Found` for the first match (this guarantees the
/// shallowest match, since the whole current level is scanned before moving to the next), then
/// keeps scanning and sends `MoreFound` for each additional match, up to [`MAX_MATCHES`] total —
/// so an early `Found` still lands the initial jump quickly, while the rest of the walk (bounded
/// by the cap) fills in the list `Shift+Tab` cycles through. Sends `Done` once the cap is hit or
/// the subtree is exhausted, whichever comes first — with zero matches, `Done` alone means "not
/// found".
fn deep_scan_bfs(
    root_path: &Path,
    prefix_lower: &str,
    show_hidden: bool,
    follow_symlinks: bool,
    result_tx: &Sender<QuickJumpMessage>,
    cancelled: &Arc<AtomicBool>,
) {
    let mut visited: HashSet<PathBuf> = HashSet::new();
    let mut queue: VecDeque<PathBuf> = VecDeque::new();
    queue.push_back(root_path.to_path_buf());
    let mut scanned = 0usize;
    let mut matches_found = 0usize;

    while let Some(dir) = queue.pop_front() {
        if cancelled.load(Ordering::Relaxed) {
            return;
        }

        if follow_symlinks {
            let key = dir.canonicalize().unwrap_or_else(|_| dir.clone());
            if !visited.insert(key) {
                continue;
            }
        }

        scanned += 1;
        if scanned.is_multiple_of(50) {
            let _ = result_tx.send(QuickJumpMessage::Progress(scanned));
        }

        let entries = match std::fs::read_dir(&dir) {
            Ok(e) => e,
            Err(_) => continue,
        };

        let mut subdirs = Vec::new();
        for entry in entries.flatten() {
            if cancelled.load(Ordering::Relaxed) {
                return;
            }

            let path = entry.path();

            if !follow_symlinks {
                if let Ok(metadata) = std::fs::symlink_metadata(&path) {
                    if metadata.is_symlink() {
                        continue;
                    }
                }
            }

            if !path.is_dir() {
                continue;
            }

            if !show_hidden {
                if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
                    if crate::tree_node::is_hidden_name(name) {
                        continue;
                    }
                }
            }

            if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
                if name.to_lowercase().starts_with(prefix_lower) {
                    matches_found += 1;
                    let msg = if matches_found == 1 {
                        QuickJumpMessage::Found(path.clone())
                    } else {
                        QuickJumpMessage::MoreFound(path.clone())
                    };
                    let _ = result_tx.send(msg);
                    if matches_found >= MAX_MATCHES {
                        let _ = result_tx.send(QuickJumpMessage::Done);
                        return;
                    }
                }
            }

            subdirs.push(path);
        }

        queue.extend(subdirs);
    }

    let _ = result_tx.send(QuickJumpMessage::Done);
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::cell::RefCell;
    use std::time::Duration as StdDuration;
    use tempfile::TempDir;

    fn node(path: PathBuf, depth: usize) -> TreeNodeRef {
        Rc::new(RefCell::new(
            crate::tree_node::TreeNode::new(path, depth).unwrap(),
        ))
    }

    // --- buffer editing ---

    #[test]
    fn activate_resets_buffer_and_state() {
        let mut qj = QuickJump::new();
        qj.buffer = "stale".to_string();
        qj.has_match = false;
        qj.activate();
        assert!(qj.active);
        assert_eq!(qj.buffer, "");
        assert!(qj.has_match);
    }

    // --- scan_stack / push_segment / pop_segment ---

    #[test]
    fn push_segment_appends_slash_and_resets_match_state() {
        let mut qj = QuickJump::new();
        qj.buffer = "sr".to_string();
        qj.matches = vec![PathBuf::from("/a"), PathBuf::from("/b")];
        qj.current_index = 1;
        qj.has_match = true;

        let target = PathBuf::from("/a/src");
        qj.push_segment(target.clone());

        assert_eq!(qj.scan_stack, vec![target]);
        assert_eq!(
            qj.buffer, "sr/",
            "buffer must NOT be cleared, only appended to"
        );
        assert!(qj.matches.is_empty());
        assert_eq!(qj.current_index, 0);
        assert!(qj.has_match);
        assert!(!qj.is_scanning);
    }

    #[test]
    fn push_segment_cancels_pending_and_in_flight_scan() {
        let tmp = std::env::temp_dir().join("bmrk_test_quick_jump_push_segment_cancel");
        std::fs::create_dir_all(&tmp).unwrap();

        let mut qj = QuickJump::new();
        qj.activate();
        qj.start_scan(tmp.clone(), "zzz_no_match".to_string(), false, false);
        assert!(qj.is_scanning);

        qj.push_segment(tmp.clone());
        assert!(!qj.is_scanning);
        assert!(qj.pending_scan_at.is_none());

        let _ = std::fs::remove_dir_all(&tmp);
    }

    #[test]
    fn pop_segment_strips_trailing_slash_and_pops_stack() {
        let mut qj = QuickJump::new();
        qj.buffer = "alpha/".to_string();
        qj.scan_stack = vec![PathBuf::from("/root/alpha")];
        qj.matches = vec![PathBuf::from("/root/alpha/x")];
        qj.current_index = 0;

        let popped = qj.pop_segment();

        assert_eq!(popped, Some(PathBuf::from("/root/alpha")));
        assert_eq!(qj.buffer, "alpha");
        assert!(qj.scan_stack.is_empty());
        assert!(qj.matches.is_empty());
        assert!(qj.has_match);
    }

    #[test]
    fn pop_segment_is_noop_when_buffer_does_not_end_with_slash() {
        let mut qj = QuickJump::new();
        qj.buffer = "alpha/shared".to_string();
        qj.scan_stack = vec![PathBuf::from("/root/alpha")];

        assert_eq!(qj.pop_segment(), None);
        assert_eq!(
            qj.buffer, "alpha/shared",
            "buffer must be untouched on a no-op pop"
        );
        assert_eq!(qj.scan_stack, vec![PathBuf::from("/root/alpha")]);
    }

    #[test]
    fn activate_and_deactivate_clear_scan_stack() {
        let mut qj = QuickJump::new();
        qj.push_segment(PathBuf::from("/a/src"));
        assert!(!qj.scan_stack.is_empty());

        qj.activate();
        assert!(
            qj.scan_stack.is_empty(),
            "a fresh Tab press must reset any prior scope"
        );

        qj.push_segment(PathBuf::from("/a/src"));
        qj.deactivate();
        assert!(
            qj.scan_stack.is_empty(),
            "leaving quick jump must reset the scope"
        );
    }

    #[test]
    fn deactivate_clears_buffer_and_active_flag() {
        let mut qj = QuickJump::new();
        qj.activate();
        qj.add_char('a');
        qj.add_char('b');
        qj.deactivate();
        assert!(!qj.active);
        assert_eq!(qj.buffer, "");
    }

    #[test]
    fn add_char_and_backspace_round_trip() {
        let mut qj = QuickJump::new();
        qj.add_char('s');
        qj.add_char('r');
        qj.add_char('c');
        assert_eq!(qj.buffer, "src");
        qj.backspace();
        assert_eq!(qj.buffer, "sr");
        qj.backspace();
        qj.backspace();
        assert_eq!(qj.buffer, "");
        // Backspace on an empty buffer must not panic.
        qj.backspace();
        assert_eq!(qj.buffer, "");
    }

    // --- Phase 1: find_in_loaded_nodes ---

    #[test]
    fn phase1_finds_direct_child_by_prefix() {
        let tmp = TempDir::new().unwrap();
        let root = node(tmp.path().to_path_buf(), 0);
        let child_path = tmp.path().join("documents");
        std::fs::create_dir(&child_path).unwrap();
        root.borrow_mut().children.push(node(child_path.clone(), 1));

        let matches = find_in_loaded_nodes(&root, "doc", false);
        assert_eq!(matches, vec![child_path]);
    }

    #[test]
    fn phase1_prefix_does_not_match_substring() {
        let tmp = TempDir::new().unwrap();
        let root = node(tmp.path().to_path_buf(), 0);
        let child_path = tmp.path().join("xdocs");
        std::fs::create_dir(&child_path).unwrap();
        root.borrow_mut().children.push(node(child_path, 1));

        // "docs" is a substring of "xdocs" but not a prefix — must not match.
        let matches = find_in_loaded_nodes(&root, "docs", false);
        assert!(matches.is_empty());
    }

    #[test]
    fn phase1_lists_multiple_matches_beyond_the_first() {
        let tmp = TempDir::new().unwrap();
        let root = node(tmp.path().to_path_buf(), 0);

        let doc1 = tmp.path().join("documents");
        std::fs::create_dir(&doc1).unwrap();
        root.borrow_mut().children.push(node(doc1.clone(), 1));

        let doc2 = tmp.path().join("docs_backup");
        std::fs::create_dir(&doc2).unwrap();
        root.borrow_mut().children.push(node(doc2, 1));

        let doc3 = tmp.path().join("docker");
        std::fs::create_dir(&doc3).unwrap();
        root.borrow_mut().children.push(node(doc3, 1));

        // Non-matching sibling must not affect the count.
        let other = tmp.path().join("alpha");
        std::fs::create_dir(&other).unwrap();
        root.borrow_mut().children.push(node(other, 1));

        let matches = find_in_loaded_nodes(&root, "doc", false);
        assert_eq!(
            matches.first(),
            Some(&doc1),
            "shallowest/first-encountered match wins the jump"
        );
        assert_eq!(matches.len(), 3, "all three 'doc*' folders must be listed");
    }

    #[test]
    fn phase1_returns_shallowest_match_first() {
        let tmp = TempDir::new().unwrap();
        let root = node(tmp.path().to_path_buf(), 0);

        // Deep match: root -> a -> match_deep (name must itself start with "match" to count
        // as a match — a name like "deep_match" would NOT satisfy a prefix match on "match").
        let a_path = tmp.path().join("a");
        std::fs::create_dir(&a_path).unwrap();
        let a = node(a_path, 1);
        let deep_path = a.borrow().path.join("match_deep");
        std::fs::create_dir(&deep_path).unwrap();
        a.borrow_mut().children.push(node(deep_path, 2));
        root.borrow_mut().children.push(a);

        // Shallow match: root -> match_shallow
        let shallow_path = tmp.path().join("match_shallow");
        std::fs::create_dir(&shallow_path).unwrap();
        root.borrow_mut()
            .children
            .push(node(shallow_path.clone(), 1));

        let matches = find_in_loaded_nodes(&root, "match", false);
        assert_eq!(matches.first(), Some(&shallow_path));
        assert_eq!(matches.len(), 2);
    }

    #[test]
    fn phase1_skips_hidden_folders_and_their_children() {
        let tmp = TempDir::new().unwrap();
        let root = node(tmp.path().to_path_buf(), 0);

        let hidden_path = tmp.path().join(".docs");
        std::fs::create_dir(&hidden_path).unwrap();
        let hidden = node(hidden_path, 1);
        let hidden_child_path = hidden.borrow().path.join("docs_inner");
        std::fs::create_dir(&hidden_child_path).unwrap();
        hidden
            .borrow_mut()
            .children
            .push(node(hidden_child_path, 2));
        root.borrow_mut().children.push(hidden);

        assert!(find_in_loaded_nodes(&root, "doc", false).is_empty());
        assert!(find_in_loaded_nodes(&root, "docs_inner", false).is_empty());
    }

    #[test]
    fn phase1_matches_hidden_folders_when_show_hidden_true() {
        let tmp = TempDir::new().unwrap();
        let root = node(tmp.path().to_path_buf(), 0);
        let hidden_path = tmp.path().join(".docs");
        std::fs::create_dir(&hidden_path).unwrap();
        root.borrow_mut()
            .children
            .push(node(hidden_path.clone(), 1));

        let matches = find_in_loaded_nodes(&root, ".doc", true);
        assert_eq!(matches, vec![hidden_path]);
    }

    #[test]
    fn phase1_does_not_match_files() {
        let tmp = TempDir::new().unwrap();
        let root = node(tmp.path().to_path_buf(), 0);
        let file_path = tmp.path().join("document.txt");
        std::fs::write(&file_path, b"hi").unwrap();
        root.borrow_mut().children.push(node(file_path, 1));

        assert!(find_in_loaded_nodes(&root, "doc", false).is_empty());
    }

    #[test]
    fn phase1_finds_children_loaded_but_currently_collapsed() {
        let tmp = TempDir::new().unwrap();
        let root = node(tmp.path().to_path_buf(), 0);
        let a_path = tmp.path().join("a");
        std::fs::create_dir(&a_path).unwrap();
        let a = node(a_path, 1);
        // Children present in memory even though `a` itself is not expanded (is_expanded=false
        // by default from TreeNode::new).
        let match_path = a.borrow().path.join("matchme");
        std::fs::create_dir(&match_path).unwrap();
        a.borrow_mut().children.push(node(match_path.clone(), 2));
        assert!(!a.borrow().is_expanded);
        root.borrow_mut().children.push(a);

        let matches = find_in_loaded_nodes(&root, "match", false);
        assert_eq!(matches, vec![match_path]);
    }

    #[test]
    fn phase1_empty_prefix_returns_none() {
        let tmp = TempDir::new().unwrap();
        let root = node(tmp.path().to_path_buf(), 0);
        let child_path = tmp.path().join("anything");
        std::fs::create_dir(&child_path).unwrap();
        root.borrow_mut().children.push(node(child_path, 1));

        assert!(find_in_loaded_nodes(&root, "", false).is_empty());
    }

    #[test]
    fn phase1_caps_matches_at_max_matches() {
        let tmp = TempDir::new().unwrap();
        let root = node(tmp.path().to_path_buf(), 0);

        for i in 0..(MAX_MATCHES + 5) {
            let path = tmp.path().join(format!("doc{i:02}"));
            std::fs::create_dir(&path).unwrap();
            root.borrow_mut().children.push(node(path, 1));
        }

        let matches = find_in_loaded_nodes(&root, "doc", false);
        assert_eq!(matches.len(), MAX_MATCHES);
    }

    // --- find_node_by_path ---

    #[test]
    fn find_node_by_path_returns_root_itself() {
        let tmp = TempDir::new().unwrap();
        let root = node(tmp.path().to_path_buf(), 0);

        let found = find_node_by_path(&root, tmp.path());
        assert!(found.is_some());
        assert_eq!(found.unwrap().borrow().path, tmp.path());
    }

    #[test]
    fn find_node_by_path_finds_nested_child() {
        let tmp = TempDir::new().unwrap();
        let root = node(tmp.path().to_path_buf(), 0);

        let a_path = tmp.path().join("a");
        std::fs::create_dir(&a_path).unwrap();
        let a = node(a_path.clone(), 1);

        let b_path = a_path.join("b");
        std::fs::create_dir(&b_path).unwrap();
        a.borrow_mut().children.push(node(b_path.clone(), 2));
        root.borrow_mut().children.push(a);

        let found = find_node_by_path(&root, &b_path);
        assert!(found.is_some());
        assert_eq!(found.unwrap().borrow().path, b_path);
    }

    #[test]
    fn find_node_by_path_returns_none_outside_subtree() {
        let tmp = TempDir::new().unwrap();
        let root = node(tmp.path().join("root"), 0);

        let unrelated = tmp.path().join("elsewhere");
        assert!(find_node_by_path(&root, &unrelated).is_none());
    }

    #[test]
    fn find_node_by_path_returns_none_when_not_yet_loaded() {
        let tmp = TempDir::new().unwrap();
        let root = node(tmp.path().to_path_buf(), 0);

        // `a` exists on disk but was never loaded into the in-memory tree (no children pushed),
        // so descending into it must fail gracefully rather than panic.
        let a_path = tmp.path().join("a");
        std::fs::create_dir(&a_path).unwrap();
        let deep_target = a_path.join("not_loaded");

        assert!(find_node_by_path(&root, &deep_target).is_none());
    }

    // --- cycle_next ---

    #[test]
    fn cycle_next_wraps_around_and_updates_index() {
        let mut qj = QuickJump::new();
        qj.matches = vec![
            PathBuf::from("/a"),
            PathBuf::from("/b"),
            PathBuf::from("/c"),
        ];
        qj.current_index = 0;

        assert_eq!(qj.cycle_next(), Some(PathBuf::from("/b")));
        assert_eq!(qj.current_index, 1);
        assert_eq!(qj.cycle_next(), Some(PathBuf::from("/c")));
        assert_eq!(qj.current_index, 2);
        assert_eq!(
            qj.cycle_next(),
            Some(PathBuf::from("/a")),
            "cycling past the last match must wrap back to the first"
        );
        assert_eq!(qj.current_index, 0);
    }

    #[test]
    fn cycle_next_returns_none_with_fewer_than_two_matches() {
        let mut qj = QuickJump::new();
        assert_eq!(qj.cycle_next(), None);

        qj.matches = vec![PathBuf::from("/a")];
        assert_eq!(qj.cycle_next(), None);
    }

    // --- Phase 2 / threading behavior ---

    #[test]
    fn cancel_scan_does_not_block() {
        let tmp = std::env::temp_dir().join("bmrk_test_quick_jump_cancel");
        std::fs::create_dir_all(&tmp).unwrap();

        let mut qj = QuickJump::new();
        qj.activate();
        qj.start_scan(tmp.clone(), "zzz_no_match".to_string(), false, false);
        std::thread::sleep(StdDuration::from_millis(10));

        let start = Instant::now();
        qj.cancel_scan();
        let elapsed = start.elapsed();

        assert!(
            elapsed < StdDuration::from_millis(50),
            "cancel_scan() took too long: {:?}",
            elapsed
        );

        let _ = std::fs::remove_dir_all(&tmp);
    }

    #[test]
    fn rapid_scan_restart_does_not_hang() {
        let tmp = std::env::temp_dir().join("bmrk_test_quick_jump_rapid");
        std::fs::create_dir_all(&tmp).unwrap();

        let mut qj = QuickJump::new();
        qj.activate();

        let start = Instant::now();
        for i in 0..10 {
            qj.start_scan(tmp.clone(), format!("prefix{}", i), false, false);
            std::thread::sleep(StdDuration::from_millis(5));
        }
        let elapsed = start.elapsed();

        assert!(
            elapsed < StdDuration::from_secs(1),
            "Rapid scan restarts took too long: {:?}",
            elapsed
        );

        qj.cancel_scan();
        let _ = std::fs::remove_dir_all(&tmp);
    }

    #[test]
    fn phase2_finds_match_via_poll() {
        let tmp = TempDir::new().unwrap();
        let target = tmp.path().join("target_folder");
        std::fs::create_dir(&target).unwrap();

        let mut qj = QuickJump::new();
        qj.activate();
        qj.buffer = "target".to_string();
        qj.start_scan(tmp.path().to_path_buf(), "target".to_string(), false, false);

        let start = Instant::now();
        let mut found = None;
        while start.elapsed() < StdDuration::from_secs(5) {
            let (_, jump_to) = qj.tick(tmp.path(), false, false);
            if jump_to.is_some() {
                found = jump_to;
                break;
            }
            std::thread::sleep(StdDuration::from_millis(10));
        }

        assert_eq!(found, Some(target));
        assert!(qj.has_match);
    }

    #[test]
    fn phase2_collects_further_matches_after_the_first() {
        let tmp = TempDir::new().unwrap();
        let doc1 = tmp.path().join("documents");
        let doc2 = tmp.path().join("docs_backup");
        let doc3 = tmp.path().join("docker");
        std::fs::create_dir(&doc1).unwrap();
        std::fs::create_dir(&doc2).unwrap();
        std::fs::create_dir(&doc3).unwrap();

        let mut qj = QuickJump::new();
        qj.activate();
        qj.buffer = "doc".to_string();
        qj.start_scan(tmp.path().to_path_buf(), "doc".to_string(), false, false);

        let start = Instant::now();
        while qj.is_scanning && start.elapsed() < StdDuration::from_secs(5) {
            qj.tick(tmp.path(), false, false);
            std::thread::sleep(StdDuration::from_millis(10));
        }

        assert!(!qj.is_scanning);
        assert!(qj.has_match);
        assert_eq!(
            qj.matches.len(),
            3,
            "scan must keep going past the first match to collect the rest, up to the cap"
        );
        // `read_dir` order is filesystem-dependent, so only the set (not the order) is checked.
        let mut sorted = qj.matches.clone();
        sorted.sort();
        let mut expected = vec![doc1, doc2, doc3];
        expected.sort();
        assert_eq!(sorted, expected);
    }

    #[test]
    fn phase2_not_found_sets_has_match_false() {
        let tmp = TempDir::new().unwrap();

        let mut qj = QuickJump::new();
        qj.activate();
        qj.buffer = "zzz_does_not_exist".to_string();
        qj.start_scan(
            tmp.path().to_path_buf(),
            "zzz_does_not_exist".to_string(),
            false,
            false,
        );

        let start = Instant::now();
        while qj.is_scanning && start.elapsed() < StdDuration::from_secs(5) {
            qj.tick(tmp.path(), false, false);
            std::thread::sleep(StdDuration::from_millis(10));
        }

        assert!(!qj.is_scanning);
        assert!(!qj.has_match);
    }

    // --- Findings #2 + #9 (.debug/BDP.md Part 5): shared prefix derivation ---

    #[test]
    fn active_prefix_strips_locked_segments() {
        let mut qj = QuickJump::new();

        qj.buffer = "abc".to_string();
        assert_eq!(
            qj.active_prefix(),
            "abc",
            "no locked segment: the whole buffer is the prefix"
        );

        qj.buffer = "alpha/".to_string();
        assert_eq!(
            qj.active_prefix(),
            "",
            "immediately after '/' with nothing typed yet: prefix is empty"
        );

        qj.buffer = "alpha/sh".to_string();
        assert_eq!(qj.active_prefix(), "sh", "one locked segment");

        qj.buffer = "alpha/beta/sh".to_string();
        assert_eq!(
            qj.active_prefix(),
            "sh",
            "multiple locked segments: only the text after the last one is the prefix"
        );

        qj.buffer = "ALPHA/SH".to_string();
        assert_eq!(qj.active_prefix(), "sh", "prefix is lowercased");
    }

    #[test]
    fn phase2_scan_prefix_excludes_locked_segments() {
        // Regression test for the empirically-confirmed bug: `tick()`'s debounced Phase-2 scan
        // used to pass the raw buffer (including locked `/`-segments) as the search prefix,
        // so it could never match a bare directory basename once a segment was locked.
        let tmp = TempDir::new().unwrap();
        let alpha = tmp.path().join("alpha");
        let shared = alpha.join("shared");
        std::fs::create_dir_all(&shared).unwrap();

        let mut qj = QuickJump::new();
        qj.activate();
        // Simulates what `/` does: lock "alpha" as a scope segment, then type "sh".
        qj.buffer = "alpha".to_string();
        qj.push_segment(alpha.clone());
        assert_eq!(qj.buffer, "alpha/");
        qj.add_char('s');
        qj.add_char('h');
        assert_eq!(qj.buffer, "alpha/sh");
        assert_eq!(
            qj.active_prefix(),
            "sh",
            "the locked 'alpha/' segment must not leak into the search prefix"
        );

        // Simulates `resolve_quick_jump` scheduling Phase 2 after a Phase 1/1.5 miss; `tick`
        // fires the debounced scan using `active_prefix()` and `scan_stack` internally — note
        // the *unscoped* nav root is passed here, proving `tick` derives the locked "alpha"
        // scope itself rather than relying on the caller to pass it in (Finding #9).
        qj.schedule_scan();

        let start = Instant::now();
        let mut found = None;
        while start.elapsed() < StdDuration::from_secs(5) {
            let (_, jump_to) = qj.tick(tmp.path(), false, false);
            if jump_to.is_some() {
                found = jump_to;
                break;
            }
            if !qj.is_scanning && qj.pending_scan_at.is_none() {
                break;
            }
            std::thread::sleep(StdDuration::from_millis(10));
        }

        assert_eq!(
            found,
            Some(shared),
            "Phase 2 must find 'shared' under the locked 'alpha' scope using the stripped prefix"
        );
        assert!(qj.has_match);
    }

    #[test]
    fn symlink_cycle_does_not_hang() {
        let test_dir = std::env::temp_dir().join("bmrk_test_quick_jump_symlink_cycle");
        let _ = std::fs::remove_dir_all(&test_dir);
        std::fs::create_dir_all(&test_dir).unwrap();

        let dir_a = test_dir.join("dir_a");
        std::fs::create_dir_all(&dir_a).unwrap();
        let dir_b = test_dir.join("dir_b");

        #[cfg(unix)]
        let r1 = std::os::unix::fs::symlink(&dir_a, &dir_b);
        #[cfg(windows)]
        let r1 = std::os::windows::fs::symlink_dir(&dir_a, &dir_b);
        #[cfg(not(any(unix, windows)))]
        let r1: std::io::Result<()> = Err(std::io::Error::other("unsupported platform"));

        if r1.is_err() {
            eprintln!(
                "symlink_cycle_does_not_hang: SKIPPED (symlink creation failed: {:?})",
                r1
            );
            let _ = std::fs::remove_dir_all(&test_dir);
            return;
        }

        let link_in_a = dir_a.join("link_to_b");
        #[cfg(unix)]
        let r2 = std::os::unix::fs::symlink(&dir_b, &link_in_a);
        #[cfg(windows)]
        let r2 = std::os::windows::fs::symlink_dir(&dir_b, &link_in_a);
        #[cfg(not(any(unix, windows)))]
        let r2: std::io::Result<()> = Err(std::io::Error::other("unsupported platform"));

        if r2.is_err() {
            eprintln!(
                "symlink_cycle_does_not_hang: SKIPPED (second symlink failed: {:?})",
                r2
            );
            let _ = std::fs::remove_dir_all(&test_dir);
            return;
        }

        let mut qj = QuickJump::new();
        qj.activate();
        qj.buffer = "zzz_no_match".to_string();
        qj.start_scan(
            test_dir.clone(),
            "zzz_no_match".to_string(),
            true,
            true, // follow_symlinks = true
        );

        let start = Instant::now();
        while qj.is_scanning && start.elapsed() < StdDuration::from_secs(5) {
            qj.tick(&test_dir, true, true);
            std::thread::sleep(StdDuration::from_millis(20));
        }

        let elapsed = start.elapsed();
        assert!(
            !qj.is_scanning,
            "Scan did not complete — likely infinite loop in cyclic symlinks"
        );
        assert!(
            elapsed < StdDuration::from_secs(5),
            "Scan took too long ({:?}): possible infinite loop",
            elapsed
        );

        let _ = std::fs::remove_dir_all(&test_dir);
    }
}