loctree 0.13.0

Structural code intelligence for AI agents. Scan once, query everything.
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
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
use std::cmp::Ordering;
use std::collections::HashSet;
use std::fs::{self, File};
use std::io::{self, BufRead, BufReader};
use std::path::{Component, Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::Arc;

use crate::types::Options;

/// Newtype proving a path has been:
/// 1. Canonicalized (symlinks resolved)
/// 2. Verified to live underneath an allowed root
/// 3. Free of `..` parent-dir traversal components
/// 4. Free of NUL bytes
///
/// All `std::fs::*` consumers in loctree's path-traversal-sensitive sites
/// receive a `SanitizedPath` (via `as_path()`) rather than a raw `&Path`.
/// This single-source-of-truth pattern lets Semgrep's `tainted-path`
/// data-flow analysis see one explicit sanitization sink
/// (`SanitizedPath::within`) instead of trying to follow canonicalize +
/// `starts_with` patterns scattered across the codebase.
pub struct SanitizedPath {
    canonical: PathBuf,
    #[allow(dead_code)] // kept for diagnostic display in errors
    root: PathBuf,
}

impl SanitizedPath {
    /// Single sanitization gate. Returns `Err(InvalidInput)` for empty
    /// paths, NUL bytes, or `..` components; `Err(PermissionDenied)` for
    /// paths that resolve outside `root`; propagates I/O errors from
    /// `canonicalize`.
    pub fn within(root: &Path, candidate: &Path) -> io::Result<Self> {
        if candidate.as_os_str().is_empty() {
            return Err(io::Error::new(io::ErrorKind::InvalidInput, "path is empty"));
        }
        if candidate.to_string_lossy().contains('\0') {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "path contains NUL byte",
            ));
        }
        for component in candidate.components() {
            if matches!(component, Component::ParentDir) {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidInput,
                    "path contains '..' component",
                ));
            }
        }
        let canonical = candidate.canonicalize()?;
        let root_canon = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
        if !canonical.starts_with(&root_canon) {
            return Err(io::Error::new(
                io::ErrorKind::PermissionDenied,
                format!(
                    "path escapes allowed root: {} (root: {})",
                    canonical.display(),
                    root_canon.display()
                ),
            ));
        }
        Ok(SanitizedPath {
            canonical,
            root: root_canon,
        })
    }

    /// Allow membership under any of multiple trusted roots. Useful when a
    /// caller maintains a cache-root + local-root pair (e.g. snapshot
    /// resolution under both `~/.cache/loctree/...` and `<repo>/.loctree/`).
    pub fn within_any(roots: &[&Path], candidate: &Path) -> io::Result<Self> {
        if candidate.as_os_str().is_empty() {
            return Err(io::Error::new(io::ErrorKind::InvalidInput, "path is empty"));
        }
        if candidate.to_string_lossy().contains('\0') {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "path contains NUL byte",
            ));
        }
        for component in candidate.components() {
            if matches!(component, Component::ParentDir) {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidInput,
                    "path contains '..' component",
                ));
            }
        }
        let canonical = candidate.canonicalize()?;
        let canon_roots: Vec<PathBuf> = roots
            .iter()
            .map(|r| r.canonicalize().unwrap_or_else(|_| r.to_path_buf()))
            .collect();
        if let Some(matched) = canon_roots.iter().find(|root| canonical.starts_with(root)) {
            Ok(SanitizedPath {
                canonical,
                root: matched.clone(),
            })
        } else {
            let allowed = canon_roots
                .iter()
                .map(|r| r.display().to_string())
                .collect::<Vec<_>>()
                .join(" | ");
            Err(io::Error::new(
                io::ErrorKind::PermissionDenied,
                format!(
                    "path escapes allowed roots: {} (allowed: {})",
                    canonical.display(),
                    allowed
                ),
            ))
        }
    }

    /// Borrow the canonicalized, root-verified path for use with
    /// `std::fs::*` APIs. The newtype is the witness that all the
    /// sanitization gates ran; callers MUST funnel fs calls through
    /// `.as_path()` rather than reconstructing a raw `PathBuf`.
    pub fn as_path(&self) -> &Path {
        &self.canonical
    }
}

/// Compile-time-literal asset name. Construct only via `const fn new` so the
/// `&'static str` lifetime constraint guarantees the value cannot be derived
/// from runtime untrusted input.
#[derive(Clone, Copy, Debug)]
pub struct StaticAssetName(&'static str);

impl StaticAssetName {
    pub const fn new(name: &'static str) -> Self {
        Self(name)
    }
    pub fn as_str(&self) -> &'static str {
        self.0
    }
}

/// Sanitize then read bytes. Use instead of `fs::read` on a
/// hand-canonicalized path so the boundary check and the I/O sink share
/// one call site that Semgrep's `tainted-path` analysis can see.
pub fn read_within(root: &Path, candidate: &Path) -> io::Result<Vec<u8>> {
    let sanitized = SanitizedPath::within(root, candidate)?;
    fs::read(sanitized.as_path())
}

/// Sanitize then read UTF-8 string.
pub fn read_to_string_within(root: &Path, candidate: &Path) -> io::Result<String> {
    let sanitized = SanitizedPath::within(root, candidate)?;
    fs::read_to_string(sanitized.as_path())
}

/// Sanitize then read UTF-8 string, allowing membership under any of
/// several trusted roots.
pub fn read_to_string_within_any(roots: &[&Path], candidate: &Path) -> io::Result<String> {
    let sanitized = SanitizedPath::within_any(roots, candidate)?;
    fs::read_to_string(sanitized.as_path())
}

/// Sanitize then `read_dir`.
pub fn read_dir_within(root: &Path, dir: &Path) -> io::Result<fs::ReadDir> {
    let sanitized = SanitizedPath::within(root, dir)?;
    fs::read_dir(sanitized.as_path())
}

/// Copy a static-named asset from a sanitized src directory to a dst
/// directory. Returns `Ok(())` when src does not exist (no-op). Both
/// `src_dir` and `dst_dir` are caller-trusted; we still funnel the source
/// read through `SanitizedPath` so the type system witnesses the gate
/// adjacent to the `fs::copy` sink.
pub fn copy_static_asset_within(
    src_dir: &Path,
    dst_dir: &Path,
    name: StaticAssetName,
) -> io::Result<()> {
    let src = src_dir.join(name.as_str());
    if !src.exists() {
        return Ok(());
    }
    let src_sanitized = SanitizedPath::within(src_dir, &src)?;
    let dst = dst_dir.join(name.as_str());
    fs::copy(src_sanitized.as_path(), &dst)?;
    Ok(())
}

/// Read a static-named artifact from a sanitized src directory under
/// `allowed_root`. The static-string name guarantees the filename
/// component cannot be derived from untrusted input.
pub fn read_static_artifact_within(
    allowed_root: &Path,
    src_dir: &Path,
    name: StaticAssetName,
) -> io::Result<Vec<u8>> {
    let src = src_dir.join(name.as_str());
    let sanitized = SanitizedPath::within(allowed_root, &src)?;
    fs::read(sanitized.as_path())
}

pub struct GitIgnoreChecker {
    repo_root: PathBuf,
    /// In-process libgit2 handle. `git2::Repository` is `Send` but not
    /// `Sync`; the `Mutex` restores `Sync` so shared references stay legal
    /// wherever callers hold `&GitIgnoreChecker` across threads. The hot
    /// path (`is_ignored`) must never spawn a subprocess: the previous
    /// `git check-ignore -q` implementation forked once per walked path,
    /// which alone cost ~13 s per warm `loct context` on an ~900-file repo.
    repo: std::sync::Mutex<git2::Repository>,
}

impl GitIgnoreChecker {
    /// Create a new GitIgnoreChecker for the given path.
    ///
    /// Uses libgit2's repository discovery which properly searches upward
    /// from the given path to find the git repository root. This handles:
    /// - Nested directories (e.g., running from src/deep/nested/)
    /// - Git worktrees (where .git is a file pointing to the main repo)
    /// - Submodules
    ///
    /// Returns `None` if the path is not inside a git repository.
    pub fn new(root: &Path) -> Option<Self> {
        // Use libgit2 to find git root (searches upward properly)
        let repo_root = crate::git::find_git_root(root)?;
        let repo = git2::Repository::discover(root).ok()?;
        Some(Self {
            repo_root,
            repo: std::sync::Mutex::new(repo),
        })
    }

    /// Make `full_path` relative to the repo root so libgit2 can resolve
    /// the ignore-rule source directories (nested .gitignore files).
    ///
    /// `find_git_root` returns libgit2's realpath'd workdir (`/private/var`
    /// on macOS) while walkers hand us paths spelled through symlinks
    /// (`/var/...`), so a raw `strip_prefix` alone is not enough — fall
    /// back to canonicalizing the candidate before giving up. `None` means
    /// "outside this worktree", which is never subject to its ignore rules.
    fn workdir_relative(&self, full_path: &Path) -> Option<PathBuf> {
        if let Ok(relative) = full_path.strip_prefix(&self.repo_root) {
            return Some(relative.to_path_buf());
        }
        let canonical = full_path.canonicalize().ok()?;
        canonical
            .strip_prefix(&self.repo_root)
            .ok()
            .map(Path::to_path_buf)
    }

    pub fn is_ignored(&self, full_path: &Path) -> bool {
        if full_path.as_os_str().is_empty() {
            return false;
        }
        let Some(relative) = self.workdir_relative(full_path) else {
            return false;
        };
        // libgit2 honors nested .gitignore files, .git/info/exclude and the
        // global core.excludesFile — same rule sources as `git check-ignore`.
        // Any error (path outside the worktree, poisoned lock) degrades to
        // "not ignored", matching the old subprocess behavior.
        self.repo
            .lock()
            .ok()
            .and_then(|repo| repo.is_path_ignored(&relative).ok())
            .unwrap_or(false)
    }

    pub fn explain_ignored(&self, full_path: &Path) -> Option<String> {
        if full_path.as_os_str().is_empty() {
            return None;
        }
        let relative = self.workdir_relative(full_path)?;
        let output = Command::new("git")
            .arg("-C")
            .arg(&self.repo_root)
            .arg("check-ignore")
            .arg("-v")
            .arg("--")
            .arg(relative)
            .stdout(Stdio::piped())
            .stderr(Stdio::null())
            .output()
            .ok()?;
        if !output.status.success() {
            return None;
        }
        let stdout = String::from_utf8_lossy(&output.stdout);
        let first = stdout.lines().next()?.trim();
        let (rule, _) = first.split_once('\t').unwrap_or((first, ""));
        let mut parts = rule.rsplitn(3, ':');
        let pattern = parts.next().unwrap_or("").trim();
        let line = parts.next().unwrap_or("").trim();
        let source = parts.next().unwrap_or("").trim();
        if source.is_empty() || pattern.is_empty() {
            return Some(format!("ignored by gitignore rule `{rule}`"));
        }
        Some(format!(
            "ignored by {}:{} pattern `{}`",
            source, line, pattern
        ))
    }
}

#[derive(Debug, Default, Clone)]
pub struct LoctignoreRules {
    /// Ignore patterns for file scanning.
    pub ignore_patterns: Vec<String>,
    /// Glob patterns for suppressing dead-export findings.
    ///
    /// Lines in `.loctignore`:
    /// - `@loctignore:dead-ok <glob>`
    pub dead_ok_globs: Vec<String>,
}

fn parse_loctignore_directive(line: &str) -> Option<(&str, &str)> {
    // Syntax: "@loctignore:<directive> <arg...>"
    let rest = line.strip_prefix("@loctignore:")?.trim_start();
    if rest.is_empty() {
        return None;
    }
    // Split once on whitespace (directive + remainder)
    let mut split_at: Option<usize> = None;
    for (idx, ch) in rest.char_indices() {
        if ch.is_whitespace() {
            split_at = Some(idx);
            break;
        }
    }
    match split_at {
        Some(idx) => Some((&rest[..idx], rest[idx..].trim())),
        None => Some((rest, "")),
    }
}

pub fn load_loctignore_rules(root: &Path) -> LoctignoreRules {
    let Some(ignore_file) = active_loctignore_file(root) else {
        return LoctignoreRules::default();
    };

    let file = match File::open(&ignore_file) {
        Ok(f) => f,
        Err(_) => return LoctignoreRules::default(),
    };

    let reader = BufReader::new(file);
    let mut rules = LoctignoreRules::default();

    for line in reader.lines() {
        let line = match line {
            Ok(l) => l,
            Err(_) => continue,
        };

        let trimmed = line.trim();

        // Skip empty lines and comments
        if trimmed.is_empty() || trimmed.starts_with('#') {
            continue;
        }

        if trimmed.starts_with("@loctignore:") {
            if let Some((directive, arg)) = parse_loctignore_directive(trimmed)
                && directive == "dead-ok"
                && !arg.is_empty()
            {
                rules.dead_ok_globs.push(arg.to_string());
            }
            continue;
        }

        // Treat each non-directive line as an ignore pattern
        rules.ignore_patterns.push(trimmed.to_string());
    }

    rules
}

fn active_loctignore_file(root: &Path) -> Option<PathBuf> {
    let ignore_file = root.join(".loctignore");
    if ignore_file.exists() {
        return Some(ignore_file);
    }
    let legacy = root.join(".loctreeignore");
    legacy.exists().then_some(legacy)
}

/// Load ignore patterns from `.loctignore` (preferred) or `.loctreeignore` (legacy).
///
/// Notes:
/// - Supports `#` comments and empty lines.
/// - Skips `@loctignore:*` directives (handled separately by `load_loctignore_rules`).
/// - Returns empty vec if file doesn't exist.
pub fn load_loctreeignore(root: &Path) -> Vec<String> {
    load_loctignore_rules(root).ignore_patterns
}

pub fn load_loctignore_dead_ok_globs(root: &Path) -> Vec<String> {
    load_loctignore_rules(root).dead_ok_globs
}

fn is_glob_pattern(pattern: &str) -> bool {
    // Minimal, pragmatic detection: if it looks like a glob, treat it as one.
    pattern.contains('*') || pattern.contains('?') || pattern.contains('[')
}

#[derive(Debug, Default, Clone)]
pub struct IgnoreMatchers {
    pub ignore_paths: Vec<PathBuf>,
    pub ignore_globs: Option<Arc<globset::GlobSet>>,
}

pub fn build_ignore_matchers(patterns: &[String], root: &Path) -> IgnoreMatchers {
    let mut ignore_paths: Vec<PathBuf> = Vec::new();
    let mut builder = globset::GlobSetBuilder::new();
    let mut any_globs = false;

    for pattern in patterns {
        let trimmed = pattern.trim();
        if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with("@loctignore:") {
            continue;
        }

        if is_glob_pattern(trimmed) {
            // For relative patterns, anchor at scan root (absolute match against `full_path`).
            let mut add_glob = |glob_pat: &str| {
                let candidate = if Path::new(glob_pat).is_absolute() {
                    PathBuf::from(glob_pat)
                } else {
                    root.join(glob_pat)
                };
                let Some(mut glob_str) = candidate.to_str().map(|s| s.replace('\\', "/")) else {
                    return;
                };
                // Normalize accidental "./" segments for nicer patterns.
                if glob_str.contains("/./") {
                    glob_str = glob_str.replace("/./", "/");
                }
                match globset::Glob::new(&glob_str) {
                    Ok(glob) => {
                        builder.add(glob);
                        any_globs = true;
                    }
                    Err(e) => {
                        eprintln!("[loctree][warn] invalid ignore glob '{}': {}", glob_pat, e);
                    }
                }
            };

            // A trailing slash means "directory" in gitignore-ish conventions.
            // We add both the directory itself and its contents.
            if let Some(base) = trimmed.strip_suffix('/') {
                if !base.is_empty() {
                    add_glob(base);
                    add_glob(&format!("{}/**", base));
                }
            } else {
                add_glob(trimmed);
            }
            continue;
        }

        // Literal path prefix ignore (fast)
        let candidate = PathBuf::from(trimmed);
        let full = if candidate.is_absolute() {
            candidate
        } else {
            root.join(candidate)
        };
        ignore_paths.push(full.canonicalize().unwrap_or(full));
    }

    let ignore_globs = if any_globs {
        match builder.build() {
            Ok(set) => Some(Arc::new(set)),
            Err(e) => {
                eprintln!("[loctree][warn] failed to build ignore globset: {}", e);
                None
            }
        }
    } else {
        None
    };

    IgnoreMatchers {
        ignore_paths,
        ignore_globs,
    }
}

/// Whether `matchers` exclude `abs_path`, using the same two-pronged logic the
/// scanner applies: literal-prefix `ignore_paths` and glob `ignore_globs`.
fn matchers_exclude(matchers: &IgnoreMatchers, abs_path: &Path) -> bool {
    if matchers
        .ignore_paths
        .iter()
        .any(|prefix| abs_path.starts_with(prefix))
    {
        return true;
    }
    if let Some(set) = matchers.ignore_globs.as_ref() {
        let normalized = abs_path.to_string_lossy().replace('\\', "/");
        if set.is_match(&normalized) {
            return true;
        }
    }
    false
}

/// If `target` (relative to `root`) names a path that EXISTS on disk but is
/// excluded from the snapshot by `.loctignore`, return a hint naming the
/// responsible pattern.
///
/// Returns `None` when the target is absent on disk (a genuine wrong path) or is
/// not loctignore-excluded. This lets callers (focus / slice) distinguish
/// "wrong path — check it" from "right path, but parked outside the snapshot by
/// .loctignore", instead of misleadingly telling the user to check a path that
/// is in fact correct (loctree-fail.md: vista `docs/` excluded by .loctignore).
pub fn loctignore_exclusion_hint(root: &Path, target: &str) -> Option<String> {
    let abs = root.join(target);
    if !abs.exists() {
        return None;
    }
    let patterns = load_loctreeignore(root);
    if patterns.is_empty() {
        return None;
    }
    let canon = abs.canonicalize().unwrap_or(abs);

    // Best-effort: isolate the single responsible pattern for a precise hint.
    for pattern in &patterns {
        let single = build_ignore_matchers(std::slice::from_ref(pattern), root);
        if matchers_exclude(&single, &canon) {
            return Some(format!(
                "`{}` exists on disk but is excluded from the snapshot by .loctignore (pattern `{}`) — loctree only indexes scanned files, so this is not a wrong path",
                target,
                pattern.trim()
            ));
        }
    }

    // Matched in aggregate but not isolatable to one pattern.
    let all = build_ignore_matchers(&patterns, root);
    if matchers_exclude(&all, &canon) {
        return Some(format!(
            "`{}` exists on disk but is excluded from the snapshot by .loctignore — loctree only indexes scanned files, so this is not a wrong path",
            target
        ));
    }
    None
}

pub fn normalise_ignore_patterns(patterns: &[String], root: &Path) -> Vec<PathBuf> {
    patterns
        .iter()
        .filter(|pattern| {
            let trimmed = pattern.trim();
            !trimmed.is_empty()
                && !trimmed.starts_with('#')
                && !trimmed.starts_with("@loctignore:")
                && !is_glob_pattern(trimmed)
        })
        .map(|pattern| {
            let candidate = PathBuf::from(pattern);
            let full = if candidate.is_absolute() {
                candidate
            } else {
                root.join(candidate)
            };
            full.canonicalize().unwrap_or(full)
        })
        .collect()
}

pub fn count_lines(path: &Path) -> Option<usize> {
    let file = File::open(path).ok()?;
    let reader = BufReader::new(file);
    let mut count = 0usize;
    for line in reader.lines() {
        if line.is_ok() {
            count += 1;
        }
    }
    Some(count)
}

pub fn matches_extension(
    path: &Path,
    extensions: Option<&std::collections::HashSet<String>>,
) -> bool {
    match extensions {
        None => true,
        Some(set) => {
            if path
                .file_name()
                .and_then(|name| name.to_str())
                .is_some_and(is_hidden_truth_config_filename)
            {
                return true;
            }
            if let Some(ext) = path.extension().and_then(|ext| ext.to_str()) {
                if set.contains(&ext.to_lowercase()) {
                    return true;
                }
            }
            // Filename-based match for extensionless files (Makefile family)
            // — only when the allowed set actually opted into make parsing.
            if set.contains("mk") || set.contains("make") {
                if let Some(filename) = path.file_name().and_then(|n| n.to_str()) {
                    if matches!(
                        filename,
                        "Makefile" | "makefile" | "GNUmakefile" | "BSDmakefile"
                    ) {
                        return true;
                    }
                }
            }
            false
        }
    }
}

pub fn is_loctree_config_filename(filename: &str) -> bool {
    matches!(filename, ".loctignore" | ".loctreeignore")
}

pub fn is_hidden_truth_config_filename(filename: &str) -> bool {
    let lower = filename.to_lowercase();
    matches!(
        lower.as_str(),
        ".loctignore"
            | ".loctreeignore"
            | ".editorconfig"
            | ".envrc"
            | ".gitignore"
            | ".gitattributes"
            | ".npmrc"
            | ".nvmrc"
            | ".node-version"
            | ".python-version"
            | ".ruby-version"
            | ".semgrep.yaml"
            | ".semgrep.yml"
            | ".semgrepignore"
            | ".shellcheckrc"
            | ".tool-versions"
    ) || lower.starts_with(".loctree.")
        || lower.starts_with(".eslintrc")
        || lower.starts_with(".prettierrc")
}

/// Shebang-based fallback for extensionless shell scripts (e.g. `./install`,
/// `./bootstrap`, `./configure`). Only fires when:
///   (a) the caller opted into shell parsing via the extensions allow-list, and
///   (b) the file has no extension (so we don't double-classify `.sh` files).
///
/// Reads only the first line — the shebang is always line 1 or nothing.
/// Returns `false` on any I/O error (fail-closed: don't surface unreadable
/// files as shell scripts).
pub fn shebang_source_extension(first_line: &str) -> Option<&'static str> {
    let line = first_line.trim();
    let shebang = line.strip_prefix("#!")?.trim();
    let mut parts = shebang.split_whitespace();
    let first = parts.next()?;
    let mut interpreter = first.rsplit('/').next().unwrap_or(first);

    if interpreter == "env" {
        interpreter = parts
            .find(|part| !part.starts_with('-') && !part.contains('='))
            .and_then(|part| part.rsplit('/').next())
            .unwrap_or_default();
    }

    match interpreter {
        "python" | "python2" | "python3" => Some("py"),
        "node" | "nodejs" | "deno" => Some("js"),
        "ruby" => Some("rb"),
        "bash" | "zsh" | "fish" | "sh" => Some("sh"),
        _ => None,
    }
}

fn extension_set_accepts_shebang_source(
    ext: &str,
    extensions: Option<&std::collections::HashSet<String>>,
) -> bool {
    let Some(set) = extensions else {
        return true;
    };
    match ext {
        "js" => ["js", "jsx", "mjs", "cjs"]
            .iter()
            .any(|candidate| set.contains(*candidate)),
        "sh" => ["sh", "bash", "zsh", "fish"]
            .iter()
            .any(|candidate| set.contains(*candidate)),
        other => set.contains(other),
    }
}

/// Shebang-based fallback for extensionless source entrypoints (e.g. `./tool`,
/// `./bootstrap`, `./git-agent-blackbox`). Only fires when:
///   (a) the file has no extension, and
///   (b) the first line names a known source interpreter accepted by the
///       current extensions allow-list.
pub fn matches_extensionless_source_shebang(
    path: &Path,
    extensions: Option<&std::collections::HashSet<String>>,
) -> bool {
    if path.extension().is_some() {
        return false;
    }
    // Skip the Makefile-family names we already classify as `make` above.
    if let Some(filename) = path.file_name().and_then(|n| n.to_str()) {
        if matches!(
            filename,
            "Makefile" | "makefile" | "GNUmakefile" | "BSDmakefile"
        ) {
            return false;
        }
    }
    let Ok(file) = File::open(path) else {
        return false;
    };
    let mut reader = BufReader::new(file);
    let mut first_line = String::new();
    // `read_line` returns 0 on EOF; treat both EOF and error as "no shebang".
    if reader.read_line(&mut first_line).unwrap_or(0) == 0 {
        return false;
    }
    shebang_source_extension(&first_line)
        .is_some_and(|ext| extension_set_accepts_shebang_source(ext, extensions))
}

pub fn matches_extensionless_shell(
    path: &Path,
    extensions: Option<&std::collections::HashSet<String>>,
) -> bool {
    if extensions.is_none() {
        return false;
    }
    if path.extension().is_some() {
        return false;
    }
    if let Some(filename) = path.file_name().and_then(|n| n.to_str()) {
        if matches!(
            filename,
            "Makefile" | "makefile" | "GNUmakefile" | "BSDmakefile"
        ) {
            return false;
        }
    }
    let Ok(file) = File::open(path) else {
        return false;
    };
    let mut reader = BufReader::new(file);
    let mut first_line = String::new();
    if reader.read_line(&mut first_line).unwrap_or(0) == 0 {
        return false;
    }
    shebang_source_extension(&first_line) == Some("sh")
        && extension_set_accepts_shebang_source("sh", extensions)
}

pub fn is_allowed_hidden(name: &str) -> bool {
    let lower = name.to_lowercase();
    if lower == ".env" || lower.starts_with(".env.") {
        return true;
    }
    matches!(
        lower.as_str(),
        ".cargo" | ".config" | ".github" | ".example"
    ) || is_hidden_truth_config_filename(&lower)
}

pub fn explain_ignore_for_path(root: &Path, full_path: &Path) -> Option<String> {
    let comparable_path = full_path
        .canonicalize()
        .unwrap_or_else(|_| full_path.to_path_buf());
    if let Some(note) = explain_loctignore_match(root, &comparable_path) {
        return Some(note);
    }
    if let Some(checker) = GitIgnoreChecker::new(root)
        && let Some(note) = checker.explain_ignored(&comparable_path)
    {
        return Some(note);
    }
    let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
    let rel_path = comparable_path
        .strip_prefix(&root)
        .unwrap_or(&comparable_path);
    for component in rel_path.components() {
        let std::path::Component::Normal(name) = component else {
            continue;
        };
        let name = name.to_string_lossy();
        if name.starts_with('.') && !is_allowed_hidden(&name) {
            return Some(format!(
                "skipped by default hidden-file filter for `{}`",
                name
            ));
        }
    }
    let name = comparable_path.file_name()?.to_string_lossy();
    if name.starts_with('.') && !is_allowed_hidden(&name) {
        return Some(format!(
            "skipped by default hidden-file filter for `{}`",
            name
        ));
    }
    None
}

fn explain_loctignore_match(root: &Path, full_path: &Path) -> Option<String> {
    let ignore_file = active_loctignore_file(root)?;
    let file = File::open(&ignore_file).ok()?;
    let reader = BufReader::new(file);
    for (idx, line) in reader.lines().enumerate() {
        let line = line.ok()?;
        let trimmed = line.trim();
        if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with("@loctignore:") {
            continue;
        }
        let matchers = build_ignore_matchers(&[trimmed.to_string()], root);
        let options = Options {
            ignore_paths: matchers.ignore_paths,
            ignore_globs: matchers.ignore_globs,
            use_gitignore: false,
            ..Default::default()
        };
        if should_ignore(full_path, &options, None) {
            let source = ignore_file
                .file_name()
                .and_then(|name| name.to_str())
                .unwrap_or(".loctignore");
            return Some(format!(
                "ignored by {}:{} pattern `{}`",
                source,
                idx + 1,
                trimmed
            ));
        }
    }
    None
}

pub fn should_ignore(
    full_path: &Path,
    options: &Options,
    git_checker: Option<&GitIgnoreChecker>,
) -> bool {
    if options
        .ignore_paths
        .iter()
        .any(|ignored| full_path.starts_with(ignored))
    {
        return true;
    }
    if let Some(globs) = &options.ignore_globs
        && globs.is_match(full_path)
    {
        return true;
    }
    if options.use_gitignore
        && let Some(checker) = git_checker
        && checker.is_ignored(full_path)
    {
        return true;
    }
    false
}

pub fn gather_files(
    dir: &Path,
    options: &Options,
    depth: usize,
    git_checker: Option<&GitIgnoreChecker>,
    visited: &mut HashSet<PathBuf>,
    files: &mut Vec<PathBuf>,
) -> io::Result<()> {
    let dir_canon = dir.canonicalize()?;
    // First call: scan_root = dir_canon. Recursive calls pass it through.
    gather_files_inner(dir, &dir_canon, options, depth, git_checker, visited, files)
}

fn gather_files_inner(
    dir: &Path,
    scan_root: &Path,
    options: &Options,
    depth: usize,
    git_checker: Option<&GitIgnoreChecker>,
    visited: &mut HashSet<PathBuf>,
    files: &mut Vec<PathBuf>,
) -> io::Result<()> {
    let dir_canon = dir.canonicalize()?;
    if !visited.insert(dir_canon.clone()) {
        return Ok(());
    }

    let mut dir_entries: Vec<_> = fs::read_dir(&dir_canon)?
        .filter_map(Result::ok)
        .filter(|entry| {
            let name = entry.file_name();
            let name_str = name.to_string_lossy();

            // Skip common heavy directories unless --scan-all is set
            if !options.scan_all
                && (name_str == "node_modules"
                    || name_str == ".git"
                    || name_str == "target"
                    || name_str == ".venv"
                    || name_str == "venv"
                    || name_str == "__pycache__")
            {
                return false;
            }

            let is_hidden = name_str.starts_with('.');
            options.show_hidden || !is_hidden || is_allowed_hidden(&name_str)
        })
        .collect();

    dir_entries.sort_by(|a, b| {
        a.file_name()
            .to_string_lossy()
            .to_lowercase()
            .cmp(&b.file_name().to_string_lossy().to_lowercase())
    });

    for entry in dir_entries {
        let path = entry.path();
        if should_ignore(&path, options, git_checker) {
            continue;
        }

        let file_type = match entry.file_type() {
            Ok(ft) => ft,
            Err(_) => continue,
        };
        if file_type.is_symlink() {
            let target = match fs::canonicalize(&path) {
                Ok(p) => p,
                Err(_) => continue, // broken symlink
            };
            if visited.contains(&target) {
                continue;
            }
            // Don't follow symlinks that escape the scan root (e.g. DMG staging
            // dirs with /Applications symlink). Compares against the top-level
            // scan root, not the current recursion dir, so intra-repo symlinks
            // like src/data -> ../shared/data still work.
            if !target.starts_with(scan_root) {
                continue;
            }
            let meta = match fs::metadata(&path) {
                Ok(m) => m,
                Err(_) => continue,
            };
            if meta.is_dir() && options.max_depth.is_none_or(|max| depth < max) {
                gather_files_inner(
                    &target,
                    scan_root,
                    options,
                    depth + 1,
                    git_checker,
                    visited,
                    files,
                )?;
            } else if meta.is_file()
                && (matches_extension(&target, options.extensions.as_ref())
                    || matches_extensionless_source_shebang(&target, options.extensions.as_ref()))
            {
                files.push(target);
            }
            continue;
        }

        if path.is_file() {
            let canonical = path.canonicalize().unwrap_or(path.clone());
            if matches_extension(&canonical, options.extensions.as_ref())
                || matches_extensionless_source_shebang(&canonical, options.extensions.as_ref())
            {
                files.push(canonical);
            }
            continue;
        }
        if path.is_dir() && options.max_depth.is_none_or(|max| depth < max) {
            gather_files_inner(
                &path,
                scan_root,
                options,
                depth + 1,
                git_checker,
                visited,
                files,
            )?;
        }
    }

    Ok(())
}

pub fn sort_dir_entries(entries: &mut [std::fs::DirEntry]) {
    entries.sort_by(|a, b| {
        let a_path = a.path();
        let b_path = b.path();
        let a_is_dir = a_path.is_dir();
        let b_is_dir = b_path.is_dir();
        match (a_is_dir, b_is_dir) {
            (true, false) => Ordering::Less,
            (false, true) => Ordering::Greater,
            _ => a
                .file_name()
                .to_string_lossy()
                .to_lowercase()
                .cmp(&b.file_name().to_string_lossy().to_lowercase()),
        }
    });
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::{ColorMode, Options, OutputMode};
    use std::collections::HashSet;
    use std::path::PathBuf;

    fn opts_with_ext(ext: &str) -> Options {
        Options {
            extensions: Some(HashSet::from([ext.to_string()])),
            ignore_paths: Vec::new(),
            ignore_globs: None,
            use_gitignore: false,
            max_depth: Some(3),
            color: ColorMode::Never,
            output: OutputMode::Human,
            summary: false,
            summary_limit: 5,
            summary_only: false,
            show_hidden: false,
            show_ignored: false,
            loc_threshold: crate::types::DEFAULT_LOC_THRESHOLD,
            analyze_limit: 8,
            report_path: None,
            serve: false,
            editor_cmd: None,
            max_graph_nodes: None,
            max_graph_edges: None,
            verbose: false,
            scan_all: false,
            symbol: None,
            impact: None,
            find_artifacts: false,
        }
    }

    fn default_opts() -> Options {
        Options {
            extensions: None,
            ignore_paths: Vec::new(),
            ignore_globs: None,
            use_gitignore: false,
            max_depth: None,
            color: ColorMode::Never,
            output: OutputMode::Human,
            summary: false,
            summary_limit: 5,
            summary_only: false,
            show_hidden: false,
            show_ignored: false,
            loc_threshold: crate::types::DEFAULT_LOC_THRESHOLD,
            analyze_limit: 8,
            report_path: None,
            serve: false,
            editor_cmd: None,
            max_graph_nodes: None,
            max_graph_edges: None,
            verbose: false,
            scan_all: false,
            symbol: None,
            impact: None,
            find_artifacts: false,
        }
    }

    #[test]
    fn gather_files_filters_by_extension_and_depth() {
        let tmp = tempfile::tempdir().expect("tmp dir");
        let root = tmp.path();
        std::fs::create_dir_all(root.join("nested")).expect("tmp nested dir");
        std::fs::write(root.join("keep.rs"), "// ok").expect("write keep.rs");
        std::fs::write(root.join("skip.txt"), "// skip").expect("write skip.txt");
        std::fs::write(root.join(".hidden.rs"), "// hidden").expect("write hidden");
        std::fs::write(root.join("nested").join("deep.rs"), "// deep").expect("write deep.rs");

        let mut files = Vec::new();
        let opts = opts_with_ext("rs");
        let mut visited = HashSet::new();
        gather_files(root, &opts, 0, None, &mut visited, &mut files).expect("gather files");

        let as_strings: Vec<String> = files
            .iter()
            .map(|p| {
                p.file_name()
                    .expect("file name")
                    .to_string_lossy()
                    .to_string()
            })
            .collect();
        assert!(as_strings.contains(&"keep.rs".to_string()));
        assert!(!as_strings.contains(&"skip.txt".to_string()));
        assert!(as_strings.contains(&"deep.rs".to_string()));
        assert!(!as_strings.contains(&".hidden.rs".to_string()));
    }

    #[test]
    fn allows_whitelisted_hidden_files() {
        let tmp = tempfile::tempdir().expect("tmp dir");
        let root = tmp.path();
        std::fs::write(root.join(".env.local"), "KEY=1").expect("env local");
        std::fs::create_dir_all(root.join(".cargo")).expect("cargo dir");
        std::fs::write(root.join(".cargo").join("config.toml"), "[target]\n")
            .expect("cargo config");
        std::fs::create_dir_all(root.join(".config")).expect("config dir");
        std::fs::write(
            root.join(".config").join("loctree.toml"),
            "mode = 'local'\n",
        )
        .expect("config file");
        std::fs::create_dir_all(root.join(".github").join("workflows")).expect("github workflows");
        std::fs::write(
            root.join(".github").join("workflows").join("release.yml"),
            "name: release\n",
        )
        .expect("github workflow");
        std::fs::write(root.join(".loctree.json"), "{}").expect("loctree json");
        std::fs::write(root.join(".example"), "// example").expect("example");
        std::fs::write(root.join(".ignored"), "// ignore").expect("ignored");

        let mut files = Vec::new();
        let opts = Options {
            extensions: None,
            ignore_paths: Vec::new(),
            ignore_globs: None,
            use_gitignore: false,
            max_depth: None,
            color: ColorMode::Never,
            output: OutputMode::Human,
            summary: false,
            summary_limit: 5,
            summary_only: false,
            show_hidden: false,
            show_ignored: false,
            loc_threshold: crate::types::DEFAULT_LOC_THRESHOLD,
            analyze_limit: 8,
            report_path: None,
            serve: false,
            editor_cmd: None,
            max_graph_nodes: None,
            max_graph_edges: None,
            verbose: false,
            scan_all: false,
            symbol: None,
            impact: None,
            find_artifacts: false,
        };
        let mut visited = HashSet::new();
        gather_files(root, &opts, 0, None, &mut visited, &mut files).expect("gather files");
        let names: HashSet<PathBuf> = files
            .iter()
            .filter_map(|p| p.file_name().map(|n| n.into()))
            .collect();
        assert!(names.contains(&PathBuf::from(".env.local")));
        assert!(names.contains(&PathBuf::from("config.toml")));
        assert!(names.contains(&PathBuf::from("loctree.toml")));
        assert!(names.contains(&PathBuf::from("release.yml")));
        assert!(names.contains(&PathBuf::from(".loctree.json")));
        assert!(names.contains(&PathBuf::from(".example")));
        assert!(!names.contains(&PathBuf::from(".ignored")));
    }

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

        let tmp = tempfile::tempdir().expect("tmp dir");
        let root = tmp.path();
        let a = root.join("a");
        let b = root.join("b");
        std::fs::create_dir_all(&a).expect("mkdir a");
        std::fs::create_dir_all(&b).expect("mkdir b");
        std::fs::write(a.join("keep.rs"), "// ok").expect("write keep");
        symlink(&b, a.join("loop_to_b")).expect("symlink b");
        symlink(&a, b.join("loop_to_a")).expect("symlink a");

        let mut files = Vec::new();
        let opts = opts_with_ext("rs");
        let mut visited = HashSet::new();
        gather_files(root, &opts, 0, None, &mut visited, &mut files).expect("gather files");
        let names: Vec<String> = files
            .iter()
            .filter_map(|p| p.file_name().map(|n| n.to_string_lossy().to_string()))
            .collect();
        assert_eq!(names, vec!["keep.rs".to_string()]);
    }

    #[test]
    fn test_count_lines() {
        let tmp = tempfile::tempdir().expect("tmp dir");
        let file_path = tmp.path().join("test.txt");
        std::fs::write(&file_path, "line1\nline2\nline3\n").expect("write file");

        let count = count_lines(&file_path);
        assert_eq!(count, Some(3));
    }

    #[test]
    fn test_count_lines_empty_file() {
        let tmp = tempfile::tempdir().expect("tmp dir");
        let file_path = tmp.path().join("empty.txt");
        std::fs::write(&file_path, "").expect("write file");

        let count = count_lines(&file_path);
        assert_eq!(count, Some(0));
    }

    #[test]
    fn test_count_lines_missing_file() {
        let count = count_lines(Path::new("/nonexistent/file.txt"));
        assert!(count.is_none());
    }

    #[test]
    fn test_matches_extension_with_set() {
        let extensions: HashSet<String> = ["rs", "ts", "js"]
            .into_iter()
            .map(|s| s.to_string())
            .collect();

        assert!(matches_extension(Path::new("file.rs"), Some(&extensions)));
        assert!(matches_extension(Path::new("file.ts"), Some(&extensions)));
        assert!(matches_extension(Path::new("file.RS"), Some(&extensions))); // case insensitive
        assert!(matches_extension(
            Path::new(".loctignore"),
            Some(&extensions)
        ));
        assert!(matches_extension(
            Path::new(".loctreeignore"),
            Some(&extensions)
        ));
        assert!(matches_extension(
            Path::new(".gitignore"),
            Some(&extensions)
        ));
        assert!(matches_extension(
            Path::new(".semgrep.yaml"),
            Some(&extensions)
        ));
        assert!(matches_extension(
            Path::new(".prettierrc.json"),
            Some(&extensions)
        ));
        assert!(!matches_extension(
            Path::new(".env.local"),
            Some(&extensions)
        ));
        assert!(!matches_extension(Path::new("file.py"), Some(&extensions)));
        assert!(!matches_extension(Path::new("noext"), Some(&extensions)));
    }

    #[test]
    fn test_matches_extension_none() {
        // None means no filter - all files match
        assert!(matches_extension(Path::new("file.rs"), None));
        assert!(matches_extension(Path::new("file.txt"), None));
        assert!(matches_extension(Path::new("noext"), None));
    }

    #[test]
    fn test_matches_extension_makefile_filename_fallback() {
        // When `mk` or `make` is in the allowed set, Makefile-family names
        // (which have no extension) should match via filename fallback.
        let exts: HashSet<String> = ["mk", "make"].into_iter().map(|s| s.to_string()).collect();
        assert!(matches_extension(Path::new("Makefile"), Some(&exts)));
        assert!(matches_extension(Path::new("src/GNUmakefile"), Some(&exts)));
        assert!(matches_extension(Path::new("common.mk"), Some(&exts)));
        assert!(!matches_extension(Path::new("Dockerfile"), Some(&exts)));

        // Without `mk`/`make` in the set, Makefile should be excluded.
        let exts_no_make: HashSet<String> = ["rs"].into_iter().map(|s| s.to_string()).collect();
        assert!(!matches_extension(
            Path::new("Makefile"),
            Some(&exts_no_make)
        ));
    }

    #[test]
    fn test_matches_extensionless_shell_shebang() {
        let tmp = tempfile::tempdir().expect("tmp dir");

        // Extensionless shell script with bash shebang
        let install = tmp.path().join("install");
        std::fs::write(&install, "#!/usr/bin/env bash\nset -e\necho hi\n").expect("write install");

        // Extensionless script with non-shell shebang (python) — must NOT match
        let pyscript = tmp.path().join("run-tool");
        std::fs::write(&pyscript, "#!/usr/bin/env python3\nprint('hi')\n").expect("write py");

        // Extensionless file with no shebang — must NOT match
        let random = tmp.path().join("README");
        std::fs::write(&random, "plain text\n").expect("write random");

        // File *with* .sh extension — must NOT be re-classified by this fallback
        // (the primary extension check already catches it).
        let real_sh = tmp.path().join("deploy.sh");
        std::fs::write(&real_sh, "#!/bin/bash\necho ok\n").expect("write sh");

        // Makefile-family names must NOT be re-classified as shell.
        let makefile = tmp.path().join("Makefile");
        std::fs::write(&makefile, "#!/bin/bash\nall:\n").expect("write makefile");

        let exts: HashSet<String> = ["sh", "bash", "zsh", "fish"]
            .into_iter()
            .map(|s| s.to_string())
            .collect();

        assert!(
            matches_extensionless_shell(&install, Some(&exts)),
            "extensionless bash script must match"
        );
        assert!(
            !matches_extensionless_shell(&pyscript, Some(&exts)),
            "python shebang must NOT match"
        );
        assert!(
            !matches_extensionless_shell(&random, Some(&exts)),
            "no shebang must NOT match"
        );
        assert!(
            !matches_extensionless_shell(&real_sh, Some(&exts)),
            "file with .sh extension must be handled by primary check, not fallback"
        );
        assert!(
            !matches_extensionless_shell(&makefile, Some(&exts)),
            "Makefile name must NOT be re-classified as shell"
        );

        // Without shell extensions in the allow-list the fallback must stay quiet.
        let no_shell: HashSet<String> = ["rs", "ts"].into_iter().map(|s| s.to_string()).collect();
        assert!(!matches_extensionless_shell(&install, Some(&no_shell)));
        assert!(!matches_extensionless_shell(&install, None));
    }

    #[test]
    fn test_matches_extensionless_source_shebang() {
        let tmp = tempfile::tempdir().expect("tmp dir");

        let py = tmp.path().join("py-tool");
        std::fs::write(&py, "#!/usr/bin/env python3\nprint('hi')\n").expect("write py");

        let node = tmp.path().join("node-tool");
        std::fs::write(&node, "#!/usr/bin/env node\nconsole.log('hi')\n").expect("write node");

        let deno = tmp.path().join("deno-tool");
        std::fs::write(&deno, "#!/usr/bin/env deno\nconsole.log('hi')\n").expect("write deno");

        let ruby = tmp.path().join("ruby-tool");
        std::fs::write(&ruby, "#!/usr/bin/env ruby\nputs 'hi'\n").expect("write ruby");

        let random = tmp.path().join("README");
        std::fs::write(&random, "plain text\n").expect("write random");

        let exts: HashSet<String> = ["py", "js", "rb"]
            .into_iter()
            .map(|s| s.to_string())
            .collect();
        assert!(matches_extensionless_source_shebang(&py, Some(&exts)));
        assert!(matches_extensionless_source_shebang(&node, Some(&exts)));
        assert!(matches_extensionless_source_shebang(&deno, Some(&exts)));
        assert!(matches_extensionless_source_shebang(&ruby, Some(&exts)));
        assert!(!matches_extensionless_source_shebang(&random, Some(&exts)));

        let no_python: HashSet<String> = ["rs", "ts"].into_iter().map(|s| s.to_string()).collect();
        assert!(!matches_extensionless_source_shebang(&py, Some(&no_python)));
    }

    #[test]
    fn test_gather_files_collects_extensionless_shell() {
        // E2E of the gate: put an extensionless bash script into a temp dir and
        // confirm gather_files picks it up when shell extensions are opted in.
        let tmp = tempfile::tempdir().expect("tmp dir");
        let root = tmp.path();

        std::fs::write(root.join("install"), "#!/usr/bin/env bash\necho ok\n").unwrap();
        std::fs::write(root.join("run-tool"), "#!/usr/bin/env python3\n").unwrap();
        std::fs::write(root.join("deploy.sh"), "#!/bin/bash\n").unwrap();

        let exts: HashSet<String> = ["sh", "bash", "zsh", "fish", "py"]
            .into_iter()
            .map(|s| s.to_string())
            .collect();
        let options = crate::types::Options {
            extensions: Some(exts),
            ..Default::default()
        };
        let mut visited = HashSet::new();
        let mut files: Vec<PathBuf> = Vec::new();
        gather_files(root, &options, 0, None, &mut visited, &mut files).expect("gather");

        let names: Vec<String> = files
            .iter()
            .filter_map(|p| {
                p.file_name()
                    .and_then(|n| n.to_str())
                    .map(|s| s.to_string())
            })
            .collect();

        assert!(
            names.iter().any(|n| n == "install"),
            "extensionless bash script missing from collection: {:?}",
            names
        );
        assert!(
            names.iter().any(|n| n == "deploy.sh"),
            "regular .sh file missing from collection: {:?}",
            names
        );
        assert!(
            names.iter().any(|n| n == "run-tool"),
            "extensionless python script missing from collection: {:?}",
            names
        );
    }

    #[test]
    fn test_is_allowed_hidden() {
        // Allowed hidden files
        assert!(is_allowed_hidden(".env"));
        assert!(is_allowed_hidden(".ENV")); // case insensitive
        assert!(is_allowed_hidden(".env.local"));
        assert!(is_allowed_hidden(".env.production"));
        assert!(is_allowed_hidden(".loctignore"));
        assert!(is_allowed_hidden(".loctreeignore"));
        assert!(is_allowed_hidden(".loctree.json"));
        assert!(is_allowed_hidden(".loctree.yml"));
        assert!(is_allowed_hidden(".example"));
        assert!(is_allowed_hidden(".cargo"));
        assert!(is_allowed_hidden(".config"));
        assert!(is_allowed_hidden(".github"));
        assert!(is_allowed_hidden(".editorconfig"));
        assert!(is_allowed_hidden(".gitignore"));
        assert!(is_allowed_hidden(".npmrc"));
        assert!(is_allowed_hidden(".semgrep.yaml"));
        assert!(is_allowed_hidden(".semgrepignore"));
        assert!(is_allowed_hidden(".tool-versions"));
        assert!(is_allowed_hidden(".prettierrc.json"));
        assert!(is_allowed_hidden(".eslintrc.cjs"));

        // Not allowed
        assert!(!is_allowed_hidden(".hidden"));
        assert!(!is_allowed_hidden(".ssh"));
    }

    #[test]
    fn explain_ignore_for_path_reports_hidden_parent_filter() {
        let tmp = tempfile::TempDir::new().expect("temp dir");
        std::fs::create_dir_all(tmp.path().join(".secret")).expect("mkdir hidden dir");
        let file = tmp.path().join(".secret").join("config.toml");
        std::fs::write(&file, "[tool]\n").expect("write hidden config");

        let note = explain_ignore_for_path(tmp.path(), &file).expect("hidden parent note");
        assert!(
            note.contains("skipped by default hidden-file filter for `.secret`"),
            "hidden ancestor should be named, got: {note}"
        );
    }

    #[test]
    fn test_should_ignore_with_ignore_paths() {
        let opts = Options {
            ignore_paths: vec![PathBuf::from("/ignored/path")],
            ..default_opts()
        };

        assert!(should_ignore(
            Path::new("/ignored/path/file.rs"),
            &opts,
            None
        ));
        assert!(!should_ignore(
            Path::new("/other/path/file.rs"),
            &opts,
            None
        ));
    }

    #[test]
    fn test_load_loctreeignore_nonexistent() {
        let tmp = tempfile::tempdir().expect("tmp dir");
        let patterns = load_loctreeignore(tmp.path());
        assert!(patterns.is_empty());
    }

    #[test]
    fn test_load_loctreeignore_with_patterns() {
        let tmp = tempfile::tempdir().expect("tmp dir");
        let ignore_file = tmp.path().join(".loctreeignore");
        std::fs::write(
            &ignore_file,
            "# Comment\nnode_modules\n\n*.log\n# Another comment\nbuild/\n",
        )
        .expect("write loctreeignore");

        let patterns = load_loctreeignore(tmp.path());
        assert_eq!(patterns.len(), 3);
        assert!(patterns.contains(&"node_modules".to_string()));
        assert!(patterns.contains(&"*.log".to_string()));
        assert!(patterns.contains(&"build/".to_string()));
    }

    #[test]
    fn test_load_loctignore_directives() {
        let tmp = tempfile::tempdir().expect("tmp dir");
        let ignore_file = tmp.path().join(".loctignore");
        std::fs::write(
            &ignore_file,
            "# Comment\nfixtures/\n@loctignore:dead-ok src/generated/**\n",
        )
        .expect("write loctignore");

        let patterns = load_loctreeignore(tmp.path());
        assert_eq!(patterns, vec!["fixtures/".to_string()]);

        let dead_ok = load_loctignore_dead_ok_globs(tmp.path());
        assert_eq!(dead_ok, vec!["src/generated/**".to_string()]);
    }

    #[test]
    fn test_explain_loctignore_match_reports_source_line_and_pattern() {
        let tmp = tempfile::TempDir::new().unwrap();
        std::fs::create_dir(tmp.path().join("fixtures")).expect("mkdir fixtures");
        let ignored = tmp.path().join("fixtures/local.rs");
        std::fs::write(tmp.path().join(".loctignore"), "# Comment\nfixtures/\n")
            .expect("write loctignore");
        std::fs::write(&ignored, "pub fn fixture_only() {}\n").expect("write ignored");

        let note = explain_ignore_for_path(tmp.path(), &ignored).expect("ignore explanation");
        assert_eq!(note, "ignored by .loctignore:2 pattern `fixtures/`");
    }

    #[test]
    fn test_should_ignore_with_ignore_globs() {
        let tmp = tempfile::tempdir().expect("tmp dir");
        let patterns = vec!["**/*.log".to_string()];
        let matchers = build_ignore_matchers(&patterns, tmp.path());
        let opts = Options {
            ignore_paths: matchers.ignore_paths,
            ignore_globs: matchers.ignore_globs,
            ..default_opts()
        };

        assert!(should_ignore(&tmp.path().join("app.log"), &opts, None));
        assert!(!should_ignore(&tmp.path().join("app.txt"), &opts, None));
    }

    #[test]
    fn test_normalise_ignore_patterns_relative() {
        let tmp = tempfile::tempdir().expect("tmp dir");
        let patterns = vec!["src".to_string(), "lib".to_string()];

        let normalized = normalise_ignore_patterns(&patterns, tmp.path());
        assert_eq!(normalized.len(), 2);
        // Normalized paths should be based on root
        assert!(normalized[0].ends_with("src") || normalized[0].to_string_lossy().contains("src"));
    }

    #[test]
    fn test_sort_dir_entries() {
        let tmp = tempfile::tempdir().expect("tmp dir");

        // Create some files and directories
        std::fs::create_dir(tmp.path().join("z_dir")).expect("mkdir");
        std::fs::create_dir(tmp.path().join("a_dir")).expect("mkdir");
        std::fs::write(tmp.path().join("z_file.txt"), "").expect("write");
        std::fs::write(tmp.path().join("a_file.txt"), "").expect("write");

        let mut entries: Vec<_> = std::fs::read_dir(tmp.path())
            .expect("read dir")
            .filter_map(Result::ok)
            .collect();

        sort_dir_entries(&mut entries);

        // After sorting: directories first (a_dir, z_dir), then files (a_file, z_file)
        let names: Vec<_> = entries
            .iter()
            .map(|e| e.file_name().to_string_lossy().to_string())
            .collect();

        // First two should be directories
        assert!(entries[0].path().is_dir());
        assert!(entries[1].path().is_dir());
        // Directories alphabetically
        assert_eq!(names[0], "a_dir");
        assert_eq!(names[1], "z_dir");
        // Files alphabetically
        assert_eq!(names[2], "a_file.txt");
        assert_eq!(names[3], "z_file.txt");
    }

    #[test]
    fn loctignore_exclusion_hint_distinguishes_ignored_from_wrong_path() {
        // loctree-fail.md (2026-06-25, vista): focus(docs)/slice fell back with
        // "No files found. Check the path." when docs/ EXISTS on disk but is
        // excluded by .loctignore. The hint must name .loctignore so the agent
        // does not chase a wrong-path that is actually correct.
        let tmp = tempfile::tempdir().expect("tmp dir");
        let root = tmp.path();
        std::fs::create_dir_all(root.join("docs/operations")).expect("mkdir docs");
        std::fs::write(root.join("docs/operations/lexicon.md"), "# x").expect("write doc");
        std::fs::create_dir_all(root.join("src")).expect("mkdir src");
        std::fs::write(root.join("src/lib.rs"), "pub fn f() {}").expect("write src");
        std::fs::write(root.join(".loctignore"), "docs/\n").expect("write loctignore");

        // On-disk but ignored → precise hint naming .loctignore.
        let hint = loctignore_exclusion_hint(root, "docs").expect("docs is on-disk but ignored");
        assert!(
            hint.contains(".loctignore"),
            "hint must name .loctignore: {hint}"
        );
        assert!(hint.contains("docs"), "hint must name the target: {hint}");
        // A sub-path under the ignored dir is flagged too.
        assert!(loctignore_exclusion_hint(root, "docs/operations").is_some());

        // Genuinely absent path → None (a real wrong path; keep "check it").
        assert!(loctignore_exclusion_hint(root, "nonexistent").is_none());
        // Existing, non-ignored dir → None.
        assert!(loctignore_exclusion_hint(root, "src").is_none());
    }
}