deps-cli 2.0.0

CLI for running deps-lsp's dependency-health checks in CI, pre-commit, and shell workflows
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
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
//! Directory walk and ecosystem routing (FR-001 through FR-004).
//!
//! Not `.gitignore`-aware by default (issue #1109): `check` is a CI security gate over
//! potentially untrusted input, so `.gitignore`/`.ignore` are only consulted when
//! [`crate::cli::CheckArgs::respect_gitignore`] opts back in. A compiled-in `PRUNED_DIRECTORIES`
//! denylist still keeps common dependency/build/VCS trees (`node_modules`, `target`, `vendor`,
//! ...) out of the scan either way — see [`walk`]'s doc.

use deps_core::{Ecosystem, EcosystemRegistry};
use ignore::WalkBuilder;
use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};

/// Upper bound on the number of files a single `check` invocation inspects across every
/// walked root (FR-004).
///
/// Protects against an unbounded walk over a pathological directory tree — the internal
/// `PRUNED_DIRECTORIES` denylist keeps the common offenders (`node_modules`, `target`, ...)
/// out of the scan already, but this cap remains a backstop for anything else pathologically
/// large (a symlink loop `ignore` itself doesn't already guard against, an unusually large
/// tree of a kind not on that denylist, ...). Once reached, the walk stops and
/// [`WalkOutcome::truncated`] is set so the caller can warn instead of silently
/// under-reporting.
pub const MAX_WALKED_FILES: usize = 50_000;

/// Directory basenames pruned from every walk, before `.gitignore`/`.ignore` are ever
/// consulted (critic follow-up on issue #1109's default flip, S1/S2/S4). `.gitignore` was
/// doing double duty: attacker-controlled suppression *and* the only thing keeping
/// `node_modules/`, `target/`, `vendor/`, ... out of the scan; disabling it by default
/// (see [`walk`]'s doc) removed both. This denylist restores the pruning without
/// reintroducing attacker control — it is baked into the binary, so a scanned repository has
/// no way to influence it, unlike a `.gitignore`/`.ignore` file.
///
/// Not exhaustive; covers the common heavy dependency/build/VCS directories across this
/// crate's 14 supported ecosystems. Most VCS and tool-cache directories here (`.git`, `.venv`,
/// `.gradle`, `.dart_tool`, `.build`, `.bundle`, `.tox`, ...) are already dot-prefixed and
/// excluded by `hidden(true)` wherever that's active; they're listed again so pruning stays
/// uniform regardless of a given walk's own `hidden` setting (e.g. the ecosystem
/// dot-directory sub-walk, or [`detect_ignored_manifests`]'s unfiltered detection walk, both
/// of which run with `hidden` lifted for their own reasons).
const PRUNED_DIRECTORIES: &[&str] = &[
    // Version control
    ".git",
    ".hg",
    ".svn",
    ".bzr",
    // JavaScript / TypeScript / Deno
    "node_modules",
    "bower_components",
    // Rust
    "target",
    // Go / PHP (Composer) / Ruby (Bundler, vendor/bundle)
    "vendor",
    // Python
    ".venv",
    "venv",
    "__pycache__",
    ".tox",
    ".mypy_cache",
    ".pytest_cache",
    ".ruff_cache",
    // Ruby (Bundler)
    ".bundle",
    // Dart
    ".dart_tool",
    // Gradle
    ".gradle",
    // Swift
    ".build",
    "Pods",
    "DerivedData",
    // Generic build output, used by several ecosystems (Maven, Dart, npm builds, ...)
    "dist",
    "build",
];

/// Returns `false` for a directory entry [`ignore::WalkBuilder::filter_entry`] should prune —
/// its basename is in [`PRUNED_DIRECTORIES`]. Never prunes depth 0 (the walk root itself), so
/// an explicitly-walked root that happens to be named e.g. `vendor` still works, matching the
/// existing convention that an explicitly-given path is trusted.
fn is_not_pruned_directory(entry: &ignore::DirEntry) -> bool {
    entry.depth() == 0
        || !entry
            .file_type()
            .is_some_and(|file_type| file_type.is_dir())
        || !entry
            .file_name()
            .to_str()
            .is_some_and(|name| PRUNED_DIRECTORIES.contains(&name))
}

/// Returns `false` for a directory entry [`ignore::WalkBuilder::filter_entry`] should prune
/// *before descending into it* — its canonicalized real path falls outside `canonical_root`
/// under `follow_symlinks: true`. Never prunes depth 0 (the walk root itself; already
/// containment-checked by its own caller — see [`walk_with_limit`]'s sub-root check) or a
/// non-directory entry (the per-file [`canonicalize_within_root`] check in [`walk_directory`]'s
/// match loop already covers those).
///
/// Background code-review finding #2: without this, `follow_links(true)` lets `ignore` descend
/// into a symlinked directory that resolves entirely outside the walked root (e.g.
/// `evil -> /some/huge/external/tree`) before the per-file check rejects each descendant
/// individually — on a large enough external tree this can exhaust [`MAX_WALKED_FILES`] on
/// content outside the walked root, silently truncating the walk and dropping legitimate
/// manifests elsewhere in the real tree, reintroducing #1112's own fail-open class through this
/// fix's own new flag. Pruning at the directory level (mirroring [`is_not_pruned_directory`]'s
/// existing prune-before-descend pattern) bounds the cost to one `canonicalize` call per
/// directory rather than one per descendant file — deliberately *not* extended into the
/// existing pruned-directory one-level-deep manifest peek
/// ([`warn_on_pruned_directory_manifest`]), since that helper's `read_dir` is only safe because
/// a *pruned* directory is still inside the trusted walked root; an *escaping* one is not, and
/// must not have its contents listed at all.
///
/// Additive to, not a replacement for, the per-file [`canonicalize_within_root`] check: a leaf
/// file symlink that individually escapes the root without its parent directory itself being a
/// symlink is not a directory-level escape, so this check does not fire for it and the per-file
/// check remains the only guard for that case.
fn is_not_escaping_directory(
    entry: &ignore::DirEntry,
    follow_symlinks: bool,
    canonical_root: Option<&Path>,
) -> bool {
    if !follow_symlinks || entry.depth() == 0 {
        return true;
    }
    if !entry
        .file_type()
        .is_some_and(|file_type| file_type.is_dir())
    {
        return true;
    }
    let Some(canonical_root) = canonical_root else {
        return false;
    };
    let Ok(canonical_path) = std::fs::canonicalize(entry.path()) else {
        return false;
    };
    canonical_path.starts_with(canonical_root)
}

/// One manifest discovered by [`walk`], already routed to its owning ecosystem.
pub struct DiscoveredManifest {
    /// Absolute (or walk-root-relative, when the walked root itself was relative)
    /// filesystem path to read the manifest's content from — for a symlinked manifest under
    /// `--follow-symlinks`, this is the resolved, canonicalized real path (FR-007), never the
    /// symlink itself.
    pub path: PathBuf,
    /// Absolute filesystem path used to derive the manifest's URI for parsing and lockfile/
    /// in-use-version discovery (review finding M2). This must stay the manifest's *encountered*
    /// path — the symlink's own location, not its resolved target's — because lockfile lookup
    /// searches ancestor directories starting from this URI: a manifest symlinked into
    /// directory A, whose target lives in directory B, must find `A`'s adjacent lockfile, not
    /// `B`'s (or `B`'s absence of one), matching US-002's own shared-manifest scenario. Identical
    /// to [`path`](Self::path) for every non-symlinked (or `--follow-symlinks`-disabled)
    /// manifest.
    pub uri_path: PathBuf,
    /// The manifest path as it should be displayed/reported — relative to the walked root
    /// when possible, matching [`crate::report::CheckFinding::manifest_path`].
    pub display_path: PathBuf,
    /// The ecosystem [`deps_core::EcosystemRegistry::for_uri`] routed this file to.
    pub ecosystem: Arc<dyn Ecosystem>,
}

// `WalkOutcome` lives in its own submodule: field privacy is module-scoped, so this confines
// the push bypass to a compile error anywhere else in `walk.rs`, not just a convention (#1305).
pub use outcome::WalkOutcome;

mod outcome {
    use super::DiscoveredManifest;
    use std::path::PathBuf;

    /// The result of walking one or more roots.
    ///
    /// Every collection field (`manifests`, `walk_errors`, `unrecognized_explicit_paths`,
    /// `ignored_manifests`, `broken_manifest_symlinks`) is private to this submodule: each one
    /// ultimately surfaces in `deps-cli`'s terminal/JSON output, built from attacker-controlled
    /// scanned-path content, so the only way to populate them — from anywhere in `walk.rs`, not
    /// merely from outside the crate — is through the `pub(super)` push helpers below, a
    /// type-level guarantee a future call site cannot bypass by pushing a raw value directly
    /// (issue #1305, follow-up to #1304's sanitization chokepoint). Read access is via the
    /// `&[...]`-returning accessor methods.
    #[derive(Default)]
    pub struct WalkOutcome {
        /// Every manifest discovered and routed to an ecosystem. `DiscoveredManifest`'s own
        /// fields (e.g. `display_path`) carry the same attacker-controlled-path risk as the
        /// four collections below, and `deps-cli` is a publishable library crate with `walk` as
        /// a public module — leaving this field `pub` would let an external consumer construct
        /// an arbitrary `DiscoveredManifest` and push it in directly, bypassing `route_file`
        /// (issue #1305 follow-up).
        manifests: Vec<DiscoveredManifest>,
        /// Paths that `ignore` could not read (permission error, broken symlink, ...) — reported
        /// as warnings, never fatal (FR-002's "no ecosystem recognizes / cannot be read" edge
        /// case).
        walk_errors: Vec<String>,
        /// Whether [`super::MAX_WALKED_FILES`] was reached before the walk finished.
        pub truncated: bool,
        /// A `root` that was itself a single file (not a directory) but that no ecosystem's
        /// `manifest_filenames`/`manifest_patterns`/`manifest_extensions`/
        /// `manifest_directory_patterns` claimed (M4, spec 062 review) — spec §6 requires a
        /// warning line for exactly this case: an explicitly-given path, unlike an unmatched
        /// file encountered while walking a directory (the overwhelming majority of files in
        /// any real tree, never worth a warning each).
        unrecognized_explicit_paths: Vec<PathBuf>,
        /// Manifest-shaped files excluded from the scan without the caller asking for that
        /// exclusion — either an ignore rule while [`super::GitignorePolicy::Respect`] was in
        /// effect (issue #1109),
        /// or a `PRUNED_DIRECTORIES` match in *any* mode (reviewer follow-up: an unusual
        /// monorepo layout can have a real subproject's manifest sitting directly inside a
        /// directory named `vendor`/`build`/`dist`/...). Unlike
        /// [`unrecognized_explicit_paths`](Self::unrecognized_explicit_paths), this is a
        /// warning about data loss (a real manifest silently skipped), not a benign non-match.
        ignored_manifests: Vec<PathBuf>,
        /// A manifest-shaped symlink whose target is not a manifest — unresolvable (dangling,
        /// broken chain, unreadable) or resolves to a non-regular-file (issue #1124). Distinct
        /// from [`ignored_manifests`](Self::ignored_manifests): that means "a real file existed
        /// and we chose not to read it" (unfollowed symlink, `.gitignore`, pruned directory);
        /// this means the manifest-shaped path produced no manifest at all, a stronger
        /// tampering signal. Reported regardless of `--follow-symlinks`/`--respect-gitignore`,
        /// except a structural ancestor loop under `--follow-symlinks`, which surfaces via
        /// `walk_errors` instead (still a non-zero exit, just a generic message rather than
        /// this specific one).
        broken_manifest_symlinks: Vec<PathBuf>,
    }

    impl WalkOutcome {
        /// Every manifest discovered and routed to an ecosystem.
        #[must_use]
        pub fn manifests(&self) -> &[DiscoveredManifest] {
            &self.manifests
        }

        /// Every warning produced while walking — an unreadable path, a symlink loop, a path
        /// that could not be resolved to a file URI, ...
        #[must_use]
        pub fn walk_errors(&self) -> &[String] {
            &self.walk_errors
        }

        /// Every explicitly-given root this run's ecosystem registry did not recognize.
        #[must_use]
        pub fn unrecognized_explicit_paths(&self) -> &[PathBuf] {
            &self.unrecognized_explicit_paths
        }

        /// Every manifest-shaped file excluded from the scan without being asked to.
        #[must_use]
        pub fn ignored_manifests(&self) -> &[PathBuf] {
            &self.ignored_manifests
        }

        /// Every manifest-shaped symlink whose target is not itself a manifest.
        #[must_use]
        pub fn broken_manifest_symlinks(&self) -> &[PathBuf] {
            &self.broken_manifest_symlinks
        }

        /// The single mutation point for `manifests` — mirrors `route_file`'s own role as the
        /// sole place a `DiscoveredManifest` is constructed.
        pub(super) fn push_manifest(&mut self, manifest: DiscoveredManifest) {
            self.manifests.push(manifest);
        }

        /// The single mutation point for `walk_errors` — sanitizes (#1304's chokepoint,
        /// folded in here per #1305) before storing, so every caller in `walk.rs` gets
        /// sanitization for free instead of calling a separate helper at each push site.
        /// `pub(super)`, not `pub`: callable from anywhere in `walk.rs` (the parent module),
        /// never from `main.rs` or an external crate.
        pub(super) fn push_walk_error(&mut self, error: String) {
            self.walk_errors
                .push(crate::sanitize::sanitize_message_for_display(&error));
        }

        /// The single mutation point for `unrecognized_explicit_paths` — sanitizes before
        /// storing (see [`Self::push_walk_error`]).
        pub(super) fn push_unrecognized_explicit_path(&mut self, path: PathBuf) {
            self.unrecognized_explicit_paths
                .push(crate::sanitize::sanitize_path_for_display(&path));
        }

        /// The single mutation point for `ignored_manifests` — sanitizes before storing (see
        /// [`Self::push_walk_error`]).
        pub(super) fn push_ignored_manifest(&mut self, path: PathBuf) {
            self.ignored_manifests
                .push(crate::sanitize::sanitize_path_for_display(&path));
        }

        /// The single mutation point for `broken_manifest_symlinks` — sanitizes before storing
        /// (see [`Self::push_walk_error`]).
        pub(super) fn push_broken_manifest_symlink(&mut self, path: PathBuf) {
            self.broken_manifest_symlinks
                .push(crate::sanitize::sanitize_path_for_display(&path));
        }
    }
}

/// Whether `.gitignore`/`.ignore` rules exclude manifests from the walk (issue #1109).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GitignorePolicy {
    /// `.gitignore`/`.ignore` are consulted, matching `git`'s own behavior.
    Respect,
    /// `.gitignore`/`.ignore` are never consulted.
    Ignore,
}

/// Whether symlinked manifests and directories are resolved and walked into (issue #1112).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SymlinkPolicy {
    /// Symlinks are resolved and walked into.
    Follow,
    /// Symlinks are detected but never resolved or descended into.
    Skip,
}

/// Walks every path in `roots`.
///
/// Uses the `ignore` crate, routing every regular file through `registry.for_uri` (FR-002)
/// unchanged from the LSP's own routing.
///
/// A `root` that is itself a single file (not a directory) is checked directly against the
/// registry, bypassing the directory walk — this is what lets `deps-cli check Cargo.toml`
/// work without needing `.gitignore` semantics at all.
///
/// Every directory root is walked twice (spec 062 review, background code-review fix 1):
/// once with `ignore`'s default hidden-file filtering intact (so `.git` — a potentially huge
/// tree in a real checkout, and never a source of manifests — is never even descended into,
/// not merely filtered from the results), and once more per registered ecosystem's own
/// dot-prefixed [`deps_core::Ecosystem::manifest_directory_patterns`] entry (`.github`,
/// `.gitlab`, ...) with hidden-ness lifted for that one subtree specifically. This is derived
/// from the live registry rather than a hardcoded `[".github", ".gitlab"]` list, so a future
/// ecosystem introducing a new dot-directory pattern is picked up automatically.
///
/// **`gitignore_policy` (issue #1109)**: when [`GitignorePolicy::Ignore`] (the `check`
/// subcommand's default — see [`crate::cli::CheckArgs::gitignore_policy`]), `.gitignore` and
/// `.ignore` files are never consulted, because in a CI security-gate invocation (`git
/// checkout && deps-cli check .` against an untrusted fork PR) both are attacker-controlled
/// input: a one-line addition anywhere in the tree would otherwise silently remove a manifest
/// from the scan. `.git` itself is still never descended into (that is `hidden`-filtering, an
/// unrelated concern — see above), and `.git/info/exclude` / the user's global gitignore are
/// always honored regardless of this policy, since neither travels with a cloned/fetched PR and
/// both are operator-, not attacker-, controlled. When [`GitignorePolicy::Respect`], standard
/// `.gitignore`/`.ignore` awareness is restored (matching `git`'s own behavior), and any
/// manifest-shaped file that awareness excludes is additionally reported via
/// [`WalkOutcome::ignored_manifests`]. The internal `PRUNED_DIRECTORIES` denylist is applied
/// regardless of `gitignore_policy` — it is compiled into the binary, not attacker-controlled
/// input, so pruning `node_modules`/`target`/`vendor`/... does not reopen the fail-open gap
/// this policy closes. A manifest sitting directly at the root of a pruned directory (an
/// unusual but real monorepo layout, e.g. a genuine subproject named `vendor`) is still
/// reported via [`WalkOutcome::ignored_manifests`] in every mode, so pruning stays visible
/// rather than a second, narrower silent-omission bug.
///
/// One asymmetry is deliberate rather than accidental: in the default
/// ([`GitignorePolicy::Ignore`]) mode, a manifest excluded only by the always-on
/// `.git/info/exclude` or global gitignore is never diffed against (that costly double-walk
/// only runs under [`GitignorePolicy::Respect`]), so such a suppression is silent beyond
/// [`WalkOutcome::manifests`] coming back emptier than expected — acceptable because both
/// sources are operator-, not attacker-, controlled (see above).
///
/// **`symlink_policy` (issue #1112)**: a directory entry that is itself a symlink to a
/// manifest-shaped file is always detected, regardless of this policy — its path is reported
/// via [`WalkOutcome::ignored_manifests`], the same sink a pruned or `.gitignore`-excluded
/// manifest already uses, so a symlinked manifest can never silently vanish from the report.
/// Detection alone never reads the target's content. When `symlink_policy` is
/// [`SymlinkPolicy::Follow`], such a symlink is additionally resolved and routed like any other
/// manifest (appearing in [`WalkOutcome::manifests`] instead, with [`DiscoveredManifest::path`]
/// set to the resolved real path used for reading and [`DiscoveredManifest::display_path`] kept
/// as the symlink's own encountered path). Every routed entry under [`SymlinkPolicy::Follow`] —
/// not only ones where the leaf itself is a symlink, since an entry reached by descending into
/// a followed symlinked *directory* is otherwise indistinguishable from an ordinary one — is
/// canonicalized and checked against the walked root's own canonicalized absolute path; an
/// entry that resolves outside the root is never routed, and is reported via
/// `ignored_manifests` only when it is itself manifest-shaped (an arbitrary out-of-root symlink
/// to a non-manifest file is silently skipped, matching detection's own never-warn-on-non-manifests
/// invariant). This containment check applies to every registered ecosystem's own dot-directory
/// sub-root (e.g. `.github`) too, and — because `ignore`/`walkdir` always follows a walk's own
/// *root* symlink regardless of `follow_links` — that sub-root containment check runs in every
/// mode, not only under [`SymlinkPolicy::Follow`]. A symlink loop is detected by the underlying
/// `ignore` crate and surfaced via [`WalkOutcome::walk_errors`].
///
/// **Broken symlinks (issue #1124)**: a symlink whose target is not a manifest (unresolvable,
/// or a non-regular-file such as a directory) is classified by its own filename, not its
/// target, and reported via [`WalkOutcome::broken_manifest_symlinks`] instead of
/// `ignored_manifests` — unconditional across every mode, same as the resolvable case, except a
/// structural ancestor loop under `--follow-symlinks`, which reports via `walk_errors` instead.
#[must_use]
pub fn walk(
    roots: &[PathBuf],
    registry: &EcosystemRegistry,
    gitignore_policy: GitignorePolicy,
    symlink_policy: SymlinkPolicy,
) -> WalkOutcome {
    walk_with_limit(
        roots,
        registry,
        MAX_WALKED_FILES,
        gitignore_policy,
        symlink_policy,
    )
}

/// [`walk`]'s implementation, parameterized over the walked-entry cap so a test can exercise
/// truncation against a small fixture instead of needing a real `MAX_WALKED_FILES`-sized tree
/// (spec 062 review, tester gap 2).
///
/// The cap counts every entry the walk visits (S1, spec 062 review) — files, directories, and
/// unreadable entries alike — not just the subset that matched an ecosystem, so
/// [`WalkOutcome::truncated`] actually bounds the walk's own cost against a pathological tree
/// (a huge `node_modules` not excluded by `.gitignore`, a symlink loop) rather than only the
/// count of manifests found. Applies uniformly to the `root.is_file()` explicit-path branch
/// too (background code-review fix 2, spec 062 review) — that branch previously incremented
/// the counter but never checked it, so `WalkOutcome::truncated` could never be set from an
/// explicit path list.
fn walk_with_limit(
    roots: &[PathBuf],
    registry: &EcosystemRegistry,
    limit: usize,
    gitignore_policy: GitignorePolicy,
    symlink_policy: SymlinkPolicy,
) -> WalkOutcome {
    let mut ctx = WalkCtx {
        registry,
        limit,
        entries_walked: 0,
        outcome: WalkOutcome::default(),
    };
    let hidden_ecosystem_dirs = hidden_ecosystem_directories(registry);
    let options = WalkOptions {
        respect_gitignore: matches!(gitignore_policy, GitignorePolicy::Respect),
        follow_symlinks: matches!(symlink_policy, SymlinkPolicy::Follow),
    };

    'roots: for root in roots {
        if ctx.outcome.truncated {
            break;
        }
        // Absolutized (issue #1108): `url::Url::from_file_path` (in `route_file`) and
        // `ignore::WalkBuilder` both require an absolute root to produce absolute entries —
        // a relative root (e.g. `.`, the CLI's own default) otherwise made every discovered
        // file fail `from_file_path` silently, so `deps-cli check` with no arguments always
        // reported zero manifests. `display_path`s below are still derived relative to
        // `root` as given, so reported paths stay exactly as the caller typed them.
        let Ok(absolute_root) = std::path::absolute(root) else {
            ctx.outcome
                .push_walk_error(format!("could not resolve path: {}", root.display()));
            continue;
        };

        if root.is_file() {
            if ctx.entries_walked >= ctx.limit {
                ctx.outcome.truncated = true;
                tracing::warn!(
                    limit,
                    "walk truncated: reached the maximum number of entries per run"
                );
                break;
            }
            ctx.entries_walked += 1;
            let matched_before = ctx.outcome.manifests().len();
            route_file(
                &absolute_root,
                &absolute_root,
                root,
                registry,
                &mut ctx.outcome,
            );
            if ctx.outcome.manifests().len() == matched_before {
                ctx.outcome.push_unrecognized_explicit_path(root.clone());
            }
            continue;
        }

        // Short-circuit a broken/non-file-target manifest-shaped symlink root via the same
        // `classify_symlink` the walk uses, so it can't both fall through as a directory walk
        // and get independently re-flagged as `Broken` at the root entry (S1/S3 contradiction).
        if is_symlink(root) {
            // A fn pointer, not a `&mut Vec<PathBuf>` reference into `ctx.outcome`, since the
            // fields it would point at are private (#1305).
            let sink: Option<fn(&mut WalkOutcome, PathBuf)> =
                match classify_symlink(&absolute_root, registry) {
                    SymlinkClassification::Broken => {
                        Some(WalkOutcome::push_broken_manifest_symlink)
                    }
                    SymlinkClassification::Irrelevant if std::fs::metadata(root).is_err() => {
                        Some(WalkOutcome::push_unrecognized_explicit_path)
                    }
                    SymlinkClassification::Resolvable | SymlinkClassification::Irrelevant => None,
                };
            if let Some(push) = sink {
                if ctx.entries_walked >= ctx.limit {
                    ctx.outcome.truncated = true;
                    tracing::warn!(
                        limit,
                        "walk truncated: reached the maximum number of entries per run"
                    );
                    break;
                }
                ctx.entries_walked += 1;
                push(&mut ctx.outcome, root.clone());
                continue;
            }
        }

        // FR-004: the escape-prevention baseline, canonicalized once per root (not per entry).
        // Computed unconditionally, not only when `follow_symlinks` is set (critic finding S1):
        // `ignore`/`walkdir` always follows a *root* symlink when starting a walk, regardless
        // of `follow_links`, so a symlinked hidden-ecosystem sub-root (e.g. a repository's own
        // `.github` replaced by a symlink) can escape the walked root in every mode, not only
        // under `--follow-symlinks` — this baseline is reused below to close that gap too.
        // `canonicalize` failing here (a root that itself cannot be resolved) is not fatal to
        // the walk: it just means containment can never be proven for anything under this root,
        // so every symlink target falls back to `ignored_manifests` (or the sub-root is simply
        // not walked) rather than being routed.
        let canonical_root = std::fs::canonicalize(&absolute_root).ok();

        // Always hidden-filtered: `hidden(true)` filters entries by their own basename as the
        // walk descends, so `walk_root` itself is never excluded even if its name starts with
        // `.` (e.g. a tempfile dir on macOS) — that previously caused a regression.
        if !walk_directory(
            &absolute_root,
            &absolute_root,
            DotDirs::Skip,
            options,
            canonical_root.as_deref(),
            &mut ctx,
        ) {
            break 'roots;
        }

        for dir_name in &hidden_ecosystem_dirs {
            let sub_root = absolute_root.join(dir_name);
            if !sub_root.is_dir() {
                continue;
            }
            // S1: `sub_root` (e.g. `<root>/.github`) may itself be a symlink escaping the
            // walked root — `ignore`/`walkdir` always follows a walk's own root symlink, so
            // this containment check applies regardless of `follow_symlinks`. A root that
            // could not be canonicalized above means containment can never be proven, so the
            // sub-root is skipped entirely rather than walked unchecked.
            match (
                canonical_root.as_deref(),
                std::fs::canonicalize(&sub_root).ok(),
            ) {
                (Some(canonical_root), Some(canonical_sub_root))
                    if canonical_sub_root.starts_with(canonical_root) => {}
                _ => continue,
            }
            if !walk_directory(
                &sub_root,
                &absolute_root,
                DotDirs::Descend,
                options,
                canonical_root.as_deref(),
                &mut ctx,
            ) {
                break 'roots;
            }
        }
    }

    ctx.outcome
}

/// Bundles the state threaded through every helper in a single walk run, so adding a new
/// piece of shared state doesn't grow each helper's own argument list
/// (`clippy::too_many_arguments`).
struct WalkCtx<'a> {
    registry: &'a EcosystemRegistry,
    limit: usize,
    entries_walked: usize,
    outcome: WalkOutcome,
}

/// The `respect_gitignore`/`follow_symlinks` pair, bundled so the internal walk chain (issue
/// #1135) threads one named value instead of two positional bools whose order a call site can
/// silently transpose.
#[derive(Clone, Copy)]
struct WalkOptions {
    respect_gitignore: bool,
    follow_symlinks: bool,
}

/// Whether a walk skips or descends into dot-prefixed entries — replaces `walk_directory`'s
/// former positional `hidden: bool` parameter (issue #1135), whose meaning is the inverse of
/// what a reader expects: `ignore::WalkBuilder::hidden(true)` means "skip hidden entries".
#[derive(Clone, Copy)]
enum DotDirs {
    /// Dot-prefixed entries are filtered out of the walk.
    Skip,
    /// Dot-prefixed entries are walked normally.
    Descend,
}

impl DotDirs {
    /// The `ignore::WalkBuilder::hidden` argument this variant corresponds to — the single
    /// point where `DotDirs` is converted back to the crate's own inverted-bool convention.
    fn skip_hidden(self) -> bool {
        matches!(self, Self::Skip)
    }
}

/// Walks `walk_root` (a directory), routing every regular file relative to `display_root` —
/// the outer `root` [`walk_with_limit`] was given, so a file under a dot-directory sub-root
/// (e.g. `<repo>/.github`) still displays relative to the repository root, not to `.github`
/// itself. Returns `false` once `limit` is reached (the caller must stop the whole walk, not
/// just this directory); `true` otherwise.
fn walk_directory(
    walk_root: &Path,
    display_root: &Path,
    dot_dirs: DotDirs,
    options: WalkOptions,
    canonical_root: Option<&Path>,
    ctx: &mut WalkCtx<'_>,
) -> bool {
    // `.gitignore`/`.ignore` toggle by `respect_gitignore` (issue #1109) — both are
    // attacker-controlled in a CI scan of untrusted input. `git_exclude` (`.git/info/exclude`)
    // and `git_global` (the user's global gitignore) stay on unconditionally: neither travels
    // with a cloned/fetched PR, so neither is part of the attack surface this flag closes.
    let hidden = dot_dirs.skip_hidden();
    let pruned_dirs: Arc<Mutex<Vec<PathBuf>>> = Arc::new(Mutex::new(Vec::new()));
    let mut builder = WalkBuilder::new(walk_root);
    builder
        .hidden(hidden)
        .parents(true)
        .ignore(options.respect_gitignore)
        .git_ignore(options.respect_gitignore)
        .git_global(true)
        .git_exclude(true)
        .follow_links(options.follow_symlinks);
    {
        let pruned_dirs = Arc::clone(&pruned_dirs);
        let canonical_root_owned = canonical_root.map(Path::to_path_buf);
        let follow_symlinks = options.follow_symlinks;
        builder.filter_entry(move |entry| {
            if !is_not_pruned_directory(entry) {
                pruned_dirs
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner)
                    .push(entry.path().to_path_buf());
                return false;
            }
            is_not_escaping_directory(entry, follow_symlinks, canonical_root_owned.as_deref())
        });
    }

    let mut visited: BTreeSet<PathBuf> = BTreeSet::new();
    for entry in builder.build() {
        if ctx.entries_walked >= ctx.limit {
            ctx.outcome.truncated = true;
            tracing::warn!(
                limit = ctx.limit,
                "walk truncated: reached the maximum number of entries per run"
            );
            return false;
        }
        ctx.entries_walked += 1;
        match entry {
            Ok(entry) if entry.file_type().is_some_and(|t| t.is_file()) => {
                let path = entry.path();
                let display = display_relative_path(path, display_root);
                if options.respect_gitignore {
                    visited.insert(display.clone());
                }
                if options.follow_symlinks {
                    // FR-004/FR-007 (critic C1): canonicalize+containment-check every entry,
                    // not only leaf symlinks — a followed symlinked *directory* ancestor needs
                    // the same check. Resolved path doubles as the real read path (FR-007).
                    match canonicalize_within_root(path, canonical_root) {
                        Some(canonical_path) => {
                            route_file(
                                path,
                                &canonical_path,
                                &display,
                                ctx.registry,
                                &mut ctx.outcome,
                            );
                        }
                        // S4: reachable only via a rare TOCTOU race (metadata failed here after
                        // `is_file()` succeeded above); routed like any other unresolvable path.
                        None => {
                            classify_symlink(path, ctx.registry).record(&mut ctx.outcome, display);
                        }
                    }
                } else {
                    route_file(path, path, &display, ctx.registry, &mut ctx.outcome);
                }
            }
            // #1112/#1124: `file_type()` reports the symlink's own (unresolved) type under
            // `follow_symlinks: false`, or `None` under `follow_symlinks: true` when the
            // target can't be stat'd (a broken symlink) — either way this arm, not the one
            // above, is where detection happens.
            Ok(entry) => {
                if entry.path_is_symlink() {
                    let path = entry.path();
                    let classification = classify_symlink(path, ctx.registry);
                    if !matches!(classification, SymlinkClassification::Irrelevant) {
                        let display = display_relative_path(path, display_root);
                        // Mirrors the `is_file()` arm's `visited` insert — otherwise
                        // `detect_ignored_manifests`'s separate unfiltered walk double-reports.
                        if options.respect_gitignore {
                            visited.insert(display.clone());
                        }
                        classification.record(&mut ctx.outcome, display);
                    }
                }
            }
            Err(error) => {
                // #1124: under `follow_symlinks: true`, a broken symlink surfaces as an `Err`
                // (walkdir must stat to resolve type) instead of the arm above. `is_io()`
                // excludes a structurally different error sharing this path-carrying variant
                // (e.g. a symlink `Loop`); `is_symlink` (S2) excludes a non-symlink permission
                // error from being misreported as tampering.
                let classified_as_broken = if let ignore::Error::WithPath { path, err } = &error
                    && err.is_io()
                    && is_symlink(path)
                    && is_manifest_shaped_by_name(path, ctx.registry)
                {
                    let display = display_relative_path(path, display_root);
                    if options.respect_gitignore {
                        visited.insert(display.clone());
                    }
                    ctx.outcome.push_broken_manifest_symlink(display);
                    true
                } else {
                    false
                };
                // Bug 3 (background review): don't also emit the generic IO error once the
                // specific broken-manifest warning already covers this path.
                if !classified_as_broken {
                    ctx.outcome.push_walk_error(error.to_string());
                }
            }
        }
    }

    // Reviewer follow-up (#2): visible regardless of `respect_gitignore` — pruning is always
    // on, so its (rare) false positives must always be reported, not only under the opt-in
    // ignore-aware mode.
    for pruned_dir in pruned_dirs
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
        .iter()
    {
        warn_on_pruned_directory_manifest(pruned_dir, display_root, ctx);
    }

    if options.respect_gitignore {
        detect_ignored_manifests(walk_root, display_root, hidden, ctx, &visited);
    }
    true
}

/// Checks a directory [`is_not_pruned_directory`] excluded (its basename matched
/// [`PRUNED_DIRECTORIES`]) for a manifest sitting directly at its own root, and records any
/// found onto [`WalkOutcome::ignored_manifests`] or [`WalkOutcome::broken_manifest_symlinks`]
/// (reviewer follow-up on issue #1109's pruning fix, extended for #1124: an unusual monorepo
/// layout can have a *real* subproject's manifest — or a manifest-shaped, possibly broken,
/// symlink — directly inside a directory named `vendor`/`build`/`dist`/...).
///
/// Deliberately one level deep only — a full recursive re-walk of the pruned directory would
/// reintroduce the exact cost [`PRUNED_DIRECTORIES`] exists to avoid for a large vendored tree
/// (a `node_modules` with hundreds of packages has no manifest directly at its own root, only
/// nested under each package directory, so this check costs one cheap `read_dir` per pruned
/// directory and stays silent for it). A manifest nested two or more levels inside a pruned
/// directory remains a known, accepted limitation of this check, not a regression — it was
/// never discovered before this fix either.
fn warn_on_pruned_directory_manifest(
    pruned_dir: &Path,
    display_root: &Path,
    ctx: &mut WalkCtx<'_>,
) {
    let Ok(read_dir) = std::fs::read_dir(pruned_dir) else {
        return;
    };
    for entry in read_dir.flatten() {
        let path = entry.path();
        let display = display_relative_path(&path, display_root);
        classify_symlink(&path, ctx.registry).record(&mut ctx.outcome, display);
    }
}

/// Diffs an unfiltered (but still [`PRUNED_DIRECTORIES`]-pruned) walk of `walk_root` against
/// `visited` (the file set an ignore-aware walk already found) and records any
/// *manifest-shaped* file present only in the unfiltered walk onto
/// [`WalkOutcome::ignored_manifests`] (issue #1109) — reusing [`EcosystemRegistry::for_uri`]
/// (the same routing [`route_file`] uses) rather than reimplementing manifest matching, and
/// never warning on a non-manifest file so this stays silent for the overwhelming majority of
/// ordinary `.gitignore` entries. `git_global`/`git_exclude` are kept `true` here too — the
/// same as the filtered walk (critic S3) — so a file excluded only by the operator-controlled
/// `.git/info/exclude` or global gitignore (out of scope for `respect_gitignore`, see [`walk`]'s
/// doc) is present in *both* walks and never misattributed to `.gitignore`/`.ignore`.
///
/// Only invoked when `respect_gitignore` is `true` — the default (`respect_gitignore: false`)
/// already never consults `.gitignore`/`.ignore`, so there is nothing to diff against. Uses its
/// own entry budget, independent of `ctx.entries_walked`/`ctx.limit` (reviewer follow-up #3):
/// this is a best-effort diagnostic pass over a walk whose *primary* manifest list is already
/// complete by the time this runs, so exhausting its budget must never set
/// [`WalkOutcome::truncated`] (which would misleadingly claim the primary walk, not this
/// diagnostic one, is incomplete) or otherwise affect the primary walk's own truncation state.
fn detect_ignored_manifests(
    walk_root: &Path,
    display_root: &Path,
    hidden: bool,
    ctx: &mut WalkCtx<'_>,
    visited: &BTreeSet<PathBuf>,
) {
    let mut builder = WalkBuilder::new(walk_root);
    builder
        .hidden(hidden)
        .ignore(false)
        .git_ignore(false)
        .git_global(true)
        .git_exclude(true)
        .filter_entry(is_not_pruned_directory);
    for (detection_entries, entry) in builder.build().enumerate() {
        if detection_entries >= ctx.limit {
            tracing::warn!(
                limit = ctx.limit,
                "ignored-manifest detection walk truncated: reached the maximum number of \
                 entries per run; some .gitignore/.ignore exclusions may go unreported"
            );
            return;
        }
        // Reviewer follow-up (#4): both failure paths below now match their counterparts in
        // `walk_directory`/`route_file` — an unreadable entry or an unconvertible path is
        // recorded, not silently skipped, so two structurally identical failure points added
        // by the same change behave identically.
        let entry = match entry {
            Ok(entry) => entry,
            Err(error) => {
                ctx.outcome.push_walk_error(error.to_string());
                continue;
            }
        };
        if !entry.file_type().is_some_and(|t| t.is_file()) {
            // #1112/M5/#1124: a gitignored symlinked (possibly broken) manifest never appears
            // in the primary filtered walk at all, so this unfiltered pass is the only place
            // that still sees it under `--respect-gitignore`.
            let path = entry.path();
            if entry.path_is_symlink() {
                let display = display_relative_path(path, display_root);
                if !visited.contains(&display) {
                    classify_symlink(path, ctx.registry).record(&mut ctx.outcome, display);
                }
            }
            continue;
        }
        let path = entry.path();
        let display = display_relative_path(path, display_root);
        if visited.contains(&display) {
            continue;
        }
        match url::Url::from_file_path(path) {
            Ok(uri) => {
                if ctx.registry.for_uri(&uri).is_some() {
                    ctx.outcome.push_ignored_manifest(display);
                }
            }
            Err(()) => {
                ctx.outcome.push_walk_error(format!(
                    "could not convert to a file URI while checking for ignore-suppressed \
                     manifests, skipping: {}",
                    display.display()
                ));
            }
        }
    }
}

/// The set of top-level dot-directory names (`.github`, `.gitlab`, ...) that at least one
/// registered ecosystem's [`deps_core::Ecosystem::manifest_directory_patterns`] names — the
/// only dot-directories [`walk_with_limit`] walks with hidden-file filtering lifted. Derived
/// from the live registry (not a hardcoded list) so a future ecosystem's own dot-directory
/// pattern is picked up automatically; `.git` is never a match here, since no ecosystem's
/// directory pattern names it.
fn hidden_ecosystem_directories(registry: &EcosystemRegistry) -> BTreeSet<String> {
    let mut dirs = BTreeSet::new();
    for id in registry.ecosystem_ids() {
        let Some(ecosystem) = registry.get(id) else {
            continue;
        };
        for (dir_pattern, _suffix) in ecosystem.manifest_directory_patterns() {
            if let Some(first) = dir_pattern.split('/').next()
                && first.starts_with('.')
            {
                dirs.insert(first.to_string());
            }
        }
    }
    dirs
}

/// FR-004/FR-007: resolves `path` to its canonicalized real path and returns it only when that
/// path is contained within `canonical_root`. `canonical_root` being `None` (symlink-following
/// disabled, or the root itself failed to canonicalize) always yields `None` — a safe default,
/// never routing an entry whose containment cannot be proven. A `canonicalize` failure on `path`
/// itself (e.g. a race between the walk's stat and this check) is likewise treated as "outside
/// root", never as "inside".
///
/// Called for **every** routed file entry under `follow_symlinks: true`, not only ones where
/// the leaf itself is a symlink (critic finding C1): `ignore`/`walkdir` only sets
/// `DirEntry::path_is_symlink()` on the entry actually named as a symlink, so an entry reached
/// by *descending into* a followed symlinked directory reports `path_is_symlink() == false` for
/// its own leaf while still resolving to a real path outside the walked root — canonicalizing
/// unconditionally (rather than gating on `path_is_symlink()`) closes that gap for both leaf
/// symlinks and symlinked ancestors alike.
///
/// The returned path also satisfies FR-007: it is the resolved real path
/// [`DiscoveredManifest::path`] must use for reading, computed once here rather than a second
/// time at read-time, which would otherwise leave a TOCTOU window between this containment
/// check and the actual read.
fn canonicalize_within_root(path: &Path, canonical_root: Option<&Path>) -> Option<PathBuf> {
    let canonical_root = canonical_root?;
    let canonical_path = std::fs::canonicalize(path).ok()?;
    canonical_path
        .starts_with(canonical_root)
        .then_some(canonical_path)
}

/// The result of [`classify_symlink`] (issue #1124).
enum SymlinkClassification {
    /// Target resolved to a manifest-shaped regular file — not followed by choice, or resolved
    /// but excluded for another reason (e.g. it falls outside the walked root, FR-004).
    Resolvable,
    /// Manifest-shaped by name, but the target is not a manifest: unresolvable (dangling,
    /// broken chain hop, unreadable), or resolves to a non-regular-file (directory, fifo,
    /// socket, ...) — the latter is just as much a substitute for the real manifest as a
    /// dangling target, so it is not treated as safe merely because it "resolves".
    Broken,
    /// Not manifest-shaped by name — never worth a warning.
    Irrelevant,
}

impl SymlinkClassification {
    /// Routes `display` to the matching `outcome` sink (no-op for `Irrelevant`) — the one place
    /// this Resolvable/Broken/Irrelevant → push/push/noop mapping lives. Sanitization (#1299
    /// round 2) happens inside the `push_*` methods themselves, not here.
    fn record(self, outcome: &mut WalkOutcome, display: PathBuf) {
        match self {
            Self::Resolvable => outcome.push_ignored_manifest(display),
            Self::Broken => outcome.push_broken_manifest_symlink(display),
            Self::Irrelevant => {}
        }
    }
}

/// Classifies `path` without reading its content — gates `Broken` on `path` actually being a
/// symlink (lstat), not merely non-regular-file, so an ordinary permission-denied directory or
/// file that happens to share a manifest's name is never misreported as tampering.
fn classify_symlink(path: &Path, registry: &EcosystemRegistry) -> SymlinkClassification {
    if !is_manifest_shaped_by_name(path, registry) {
        return SymlinkClassification::Irrelevant;
    }
    match std::fs::metadata(path) {
        Ok(metadata) if metadata.is_file() => SymlinkClassification::Resolvable,
        _ if is_symlink(path) => SymlinkClassification::Broken,
        _ => SymlinkClassification::Irrelevant,
    }
}

/// `symlink_metadata` (lstat, never follows) reporting `path` itself as a symlink — succeeds
/// even for a dangling target, unlike [`std::fs::metadata`]/`Path::is_file`.
fn is_symlink(path: &Path) -> bool {
    std::fs::symlink_metadata(path).is_ok_and(|metadata| metadata.file_type().is_symlink())
}

/// `path` relative to `display_root`; falls back to `path` itself when `strip_prefix` fails or
/// succeeds empty (the latter whenever `path == display_root`, e.g. an explicitly-given root).
fn display_relative_path(path: &Path, display_root: &Path) -> PathBuf {
    let stripped = path.strip_prefix(display_root).unwrap_or(path);
    if stripped.as_os_str().is_empty() {
        path.to_path_buf()
    } else {
        stripped.to_path_buf()
    }
}

/// `EcosystemRegistry::for_uri` on `path`'s own name, never on a resolved target.
fn is_manifest_shaped_by_name(path: &Path, registry: &EcosystemRegistry) -> bool {
    let Ok(uri) = url::Url::from_file_path(path) else {
        return false;
    };
    registry.for_uri(&uri).is_some()
}

/// Routes one already-discovered file through `registry.for_uri`, pushing a
/// [`DiscoveredManifest`] onto `outcome` when an ecosystem claims it.
///
/// `route_path` and `read_path` are the same path for every caller except the
/// `follow_symlinks: true` branch of `walk_directory` (FR-007): ecosystem routing is a
/// basename/pattern match (`manifest_filenames`, `manifest_patterns`, ...), so it must always
/// go through the *encountered* path — a symlink named `Cargo.toml` routes as `Cargo.toml`
/// regardless of what its target is named — while [`DiscoveredManifest::path`] (used later to
/// read the manifest's content) must be the resolved real path a symlink was already
/// containment-checked against, not the symlink itself. `route_path` is also stored as
/// [`DiscoveredManifest::uri_path`] (review finding M2): lockfile/in-use-version discovery
/// must anchor its ancestor-directory search at the symlink's own location, not its target's.
///
/// `route_path` is expected to already be absolute (every caller absolutizes its walk root
/// first — see [`walk_with_limit`]) so `url::Url::from_file_path` should never fail in
/// practice; if it somehow does (issue #1108), that is recorded as a warning rather than
/// silently dropping the file, so a future regression in the absolutization degrades loudly
/// instead of quietly reintroducing the "walk finds zero manifests" bug.
fn route_file(
    route_path: &Path,
    read_path: &Path,
    display_path: &Path,
    registry: &EcosystemRegistry,
    outcome: &mut WalkOutcome,
) {
    // #1299 round 2: sanitized once here, the single place `DiscoveredManifest` is built —
    // every caller's `display_path` (a walk root, a `display_relative_path` result, ...)
    // reaches display-safety through this one chokepoint rather than at each call site.
    let display_path = crate::sanitize::sanitize_path_for_display(display_path);
    let Ok(uri) = url::Url::from_file_path(route_path) else {
        outcome.push_walk_error(format!(
            "could not convert to a file URI, skipping: {}",
            display_path.display()
        ));
        return;
    };
    if let Some(ecosystem) = registry.for_uri(&uri) {
        outcome.push_manifest(DiscoveredManifest {
            path: read_path.to_path_buf(),
            uri_path: route_path.to_path_buf(),
            display_path,
            ecosystem,
        });
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use std::sync::Mutex;

    /// Serializes tests that call `std::env::set_current_dir` — the process CWD is global
    /// state shared across every test in this binary, which otherwise run concurrently.
    static CWD_LOCK: Mutex<()> = Mutex::new(());

    /// Chdirs into `dir` and restores the original cwd on drop — including on an early return
    /// via a panicking assertion mid-test (critic M3), which a plain "restore at the end of the
    /// function" cannot do. Holds `CWD_LOCK` for its own lifetime.
    struct CwdGuard {
        original: PathBuf,
        _lock: std::sync::MutexGuard<'static, ()>,
    }

    impl CwdGuard {
        fn chdir(dir: &Path) -> Self {
            let lock = CWD_LOCK
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            let original = std::env::current_dir().expect("read cwd");
            std::env::set_current_dir(dir).expect("chdir");
            Self {
                original,
                _lock: lock,
            }
        }
    }

    impl Drop for CwdGuard {
        fn drop(&mut self) {
            let _ = std::env::set_current_dir(&self.original);
        }
    }

    fn test_registry() -> EcosystemRegistry {
        let registry = EcosystemRegistry::new();
        let runtime = deps_engine::setup::EcosystemRuntime::from_policy(
            &deps_core::policy_config::PolicyConfig::default(),
        );
        deps_engine::setup::register_ecosystems(
            &registry,
            Arc::new(deps_core::HttpCache::new()),
            &runtime,
        );
        registry
    }

    #[test]
    fn test_walk_empty_directory_finds_nothing() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let outcome = walk(
            &[dir.path().to_path_buf()],
            &test_registry(),
            GitignorePolicy::Ignore,
            SymlinkPolicy::Skip,
        );
        assert!(outcome.manifests().is_empty());
        assert!(!outcome.truncated);
    }

    #[test]
    fn test_walk_finds_cargo_toml() {
        let dir = tempfile::tempdir().expect("create temp dir");
        fs::write(dir.path().join("Cargo.toml"), "[package]\nname = \"x\"\n")
            .expect("write manifest");
        let outcome = walk(
            &[dir.path().to_path_buf()],
            &test_registry(),
            GitignorePolicy::Ignore,
            SymlinkPolicy::Skip,
        );
        assert_eq!(outcome.manifests().len(), 1);
        assert_eq!(
            outcome.manifests()[0].display_path,
            PathBuf::from("Cargo.toml")
        );
        assert_eq!(outcome.manifests()[0].ecosystem.id(), "cargo");
    }

    /// With `respect_gitignore: true` (the opt-in, pre-#1109-fix behavior), a `.gitignore`
    /// entry still suppresses a manifest — this is intentional for a caller who explicitly
    /// asked to restore `git`'s own semantics.
    #[test]
    fn test_walk_respect_gitignore_true_skips_gitignored_manifest() {
        let dir = tempfile::tempdir().expect("create temp dir");
        // `ignore`'s `.gitignore` support only activates inside a git repo by default
        // (`require_git`); an empty `.git` marker is enough for detection.
        fs::create_dir(dir.path().join(".git")).expect("create .git marker");
        fs::write(dir.path().join(".gitignore"), "ignored/\n").expect("write gitignore");
        fs::create_dir(dir.path().join("ignored")).expect("mkdir");
        fs::write(dir.path().join("ignored").join("Cargo.toml"), "[package]\n")
            .expect("write manifest");
        let outcome = walk(
            &[dir.path().to_path_buf()],
            &test_registry(),
            GitignorePolicy::Respect,
            SymlinkPolicy::Skip,
        );
        assert!(outcome.manifests().is_empty());
        assert_eq!(
            outcome.ignored_manifests(),
            vec![PathBuf::from("ignored").join("Cargo.toml")]
        );
    }

    /// Issue #1109 repro 1: a `.gitignore` entry must NOT suppress a manifest under the
    /// default (`respect_gitignore: false`) `check` behavior — this is the fail-open gap the
    /// issue reports (attacker-controlled `.gitignore` silently defeating the CI gate).
    #[test]
    fn test_walk_default_does_not_respect_gitignore() {
        let dir = tempfile::tempdir().expect("create temp dir");
        fs::create_dir(dir.path().join(".git")).expect("create .git marker");
        fs::write(dir.path().join(".gitignore"), "Cargo.toml\n").expect("write gitignore");
        fs::write(dir.path().join("Cargo.toml"), "[package]\n").expect("write manifest");
        let outcome = walk(
            &[dir.path().to_path_buf()],
            &test_registry(),
            GitignorePolicy::Ignore,
            SymlinkPolicy::Skip,
        );
        assert_eq!(outcome.manifests().len(), 1);
        assert!(outcome.ignored_manifests().is_empty());
    }

    /// Issue #1109 repro 2: a nested `sub/.gitignore` (not just a top-level one) must not
    /// suppress a manifest under the default behavior either.
    #[test]
    fn test_walk_default_ignores_nested_gitignore() {
        let dir = tempfile::tempdir().expect("create temp dir");
        fs::create_dir(dir.path().join(".git")).expect("create .git marker");
        fs::create_dir(dir.path().join("sub")).expect("mkdir sub");
        fs::write(dir.path().join("sub").join(".gitignore"), "Cargo.toml\n")
            .expect("write nested gitignore");
        fs::write(dir.path().join("sub").join("Cargo.toml"), "[package]\n")
            .expect("write manifest");
        let outcome = walk(
            &[dir.path().to_path_buf()],
            &test_registry(),
            GitignorePolicy::Ignore,
            SymlinkPolicy::Skip,
        );
        assert_eq!(outcome.manifests().len(), 1);
    }

    /// Issue #1109 repro 3: an `.ignore` file (no `.git` directory at all) must not suppress a
    /// manifest under the default behavior.
    #[test]
    fn test_walk_default_ignores_dot_ignore_file_without_git_repo() {
        let dir = tempfile::tempdir().expect("create temp dir");
        fs::write(dir.path().join(".ignore"), "Cargo.toml\n").expect("write .ignore");
        fs::write(dir.path().join("Cargo.toml"), "[package]\n").expect("write manifest");
        let outcome = walk(
            &[dir.path().to_path_buf()],
            &test_registry(),
            GitignorePolicy::Ignore,
            SymlinkPolicy::Skip,
        );
        assert_eq!(outcome.manifests().len(), 1);
    }

    /// Critic S1 (post-#1109 default-flip regression): disabling `.gitignore`/`.ignore` by
    /// default must not turn a vendored `node_modules/` tree back into hundreds of scanned
    /// manifests — the compiled-in [`PRUNED_DIRECTORIES`] denylist must prune it regardless.
    #[test]
    fn test_walk_default_prunes_node_modules() {
        let dir = tempfile::tempdir().expect("create temp dir");
        fs::write(dir.path().join("Cargo.toml"), "[package]\n").expect("write manifest");
        fs::create_dir_all(dir.path().join("node_modules").join("left-pad"))
            .expect("mkdir node_modules/left-pad");
        fs::write(
            dir.path()
                .join("node_modules")
                .join("left-pad")
                .join("package.json"),
            "{}",
        )
        .expect("write vendored manifest");

        let outcome = walk(
            &[dir.path().to_path_buf()],
            &test_registry(),
            GitignorePolicy::Ignore,
            SymlinkPolicy::Skip,
        );

        assert_eq!(outcome.manifests().len(), 1);
        assert_eq!(
            outcome.manifests()[0].display_path,
            PathBuf::from("Cargo.toml")
        );
    }

    /// Reviewer follow-up #2: an unusual monorepo layout can have a *real* subproject's
    /// manifest sitting directly under a directory named `vendor`/`build`/`dist`/... —
    /// `PRUNED_DIRECTORIES` still excludes it from the primary scan, but the omission must be
    /// visible via `WalkOutcome::ignored_manifests`, in every mode (not only under
    /// `--respect-gitignore`).
    #[test]
    fn test_walk_default_warns_on_manifest_directly_inside_pruned_directory() {
        let dir = tempfile::tempdir().expect("create temp dir");
        fs::create_dir(dir.path().join("vendor")).expect("mkdir vendor");
        fs::write(dir.path().join("vendor").join("Cargo.toml"), "[package]\n")
            .expect("write manifest directly under pruned dir");

        let outcome = walk(
            &[dir.path().to_path_buf()],
            &test_registry(),
            GitignorePolicy::Ignore,
            SymlinkPolicy::Skip,
        );

        assert!(
            outcome.manifests().is_empty(),
            "still pruned from the primary scan"
        );
        assert_eq!(
            outcome.ignored_manifests(),
            vec![PathBuf::from("vendor").join("Cargo.toml")]
        );
    }

    /// Regression test for #1299 round 2: a raw ANSI escape byte or bidi-override character in
    /// a walked directory name must never reach a `WalkOutcome` field unsanitized — exercised
    /// through the real `walk::walk` entry point, not `sanitize`'s own isolated unit tests, so
    /// it actually fails if a future `WalkOutcome` push (`push_walk_error`, `route_file`,
    /// `SymlinkClassification::record`, or a new one) bypasses the sanitization chokepoint.
    /// Mirrors the critic's exact live-repro payload and directory shape (a manifest directly
    /// under a pruned `vendor/`, the same scenario as the test above).
    #[test]
    fn test_walk_sanitizes_bidi_and_ansi_in_a_walked_directory_name() {
        // NTFS rejects ASCII control characters (including the raw ESC byte) in a path
        // component, so a directory literally named with one cannot exist on Windows; the
        // bidi override alone is legal there and still exercises the same chokepoint.
        let payload_name = if cfg!(windows) {
            "ev\u{202E}il"
        } else {
            "ev\u{202E}il\x1B[31m"
        };
        let dir = tempfile::tempdir().expect("create temp dir");
        let payload_dir = dir.path().join(payload_name);
        fs::create_dir(&payload_dir).expect("mkdir payload dir");
        fs::create_dir(payload_dir.join("vendor")).expect("mkdir vendor");
        fs::write(payload_dir.join("vendor").join("Cargo.toml"), "[package]\n")
            .expect("write manifest directly under pruned dir");

        let outcome = walk(
            &[dir.path().to_path_buf()],
            &test_registry(),
            GitignorePolicy::Ignore,
            SymlinkPolicy::Skip,
        );

        assert_eq!(outcome.ignored_manifests().len(), 1);
        let reported = outcome.ignored_manifests()[0]
            .to_string_lossy()
            .into_owned();
        assert!(
            !reported.contains('\u{202E}'),
            "bidi override survived the walk: {reported:?}"
        );
        if !cfg!(windows) {
            assert!(
                !reported.contains('\x1B'),
                "raw ANSI escape byte survived the walk: {reported:?}"
            );
        }
        assert!(reported.contains("vendor"), "legitimate path info lost");
        assert!(reported.contains("Cargo.toml"), "legitimate path info lost");
    }

    /// Companion to the above: a manifest nested two or more levels inside a pruned directory
    /// remains a documented, accepted limitation (checking only the pruned directory's own
    /// root avoids reintroducing the cost a full recursive re-walk would bring back for a
    /// large vendored tree) — not a regression, since it was never found before this fix.
    #[test]
    fn test_walk_manifest_nested_two_levels_inside_pruned_directory_remains_unreported() {
        let dir = tempfile::tempdir().expect("create temp dir");
        fs::create_dir_all(dir.path().join("vendor").join("sub")).expect("mkdir vendor/sub");
        fs::write(
            dir.path().join("vendor").join("sub").join("Cargo.toml"),
            "[package]\n",
        )
        .expect("write nested manifest");

        let outcome = walk(
            &[dir.path().to_path_buf()],
            &test_registry(),
            GitignorePolicy::Ignore,
            SymlinkPolicy::Skip,
        );

        assert!(outcome.manifests().is_empty());
        assert!(outcome.ignored_manifests().is_empty());
    }

    /// Reviewer follow-up #3: `detect_ignored_manifests`'s diagnostic pass must use its own
    /// entry budget, independent of the primary walk's `ctx.entries_walked`/`ctx.limit` — a
    /// small limit that comfortably covers the primary (filtered) walk but not the
    /// diagnostic (unfiltered) pass over an ignored, non-manifest-shaped `noise/` directory
    /// must exhaust only the diagnostic pass, never set `WalkOutcome::truncated`, and never
    /// affect the primary walk's own (already-complete) manifest list.
    #[test]
    fn test_detect_ignored_manifests_uses_its_own_budget_and_does_not_set_truncated() {
        let dir = tempfile::tempdir().expect("create temp dir");
        fs::create_dir(dir.path().join(".git")).expect("create .git marker");
        fs::write(dir.path().join(".gitignore"), "noise/\n").expect("write gitignore");
        fs::write(dir.path().join("Cargo.toml"), "[package]\n").expect("write manifest");
        fs::create_dir(dir.path().join("noise")).expect("mkdir noise");
        for i in 0..20 {
            fs::write(dir.path().join("noise").join(format!("f{i}.txt")), "")
                .expect("write noise file");
        }

        // Comfortably covers the primary walk (root + .gitignore + Cargo.toml == 3 entries,
        // `noise/` itself is `.gitignore`-excluded there) but not the diagnostic pass, which
        // ignores `.gitignore` and must descend into `noise/`'s 20 files.
        let outcome = walk_with_limit(
            &[dir.path().to_path_buf()],
            &test_registry(),
            5,
            GitignorePolicy::Respect,
            SymlinkPolicy::Skip,
        );

        assert!(
            !outcome.truncated,
            "the diagnostic pass' own budget exhaustion must not mark the primary walk truncated"
        );
        assert_eq!(
            outcome.manifests().len(),
            1,
            "primary walk result must still be complete"
        );
    }

    /// Critic S2: with `respect_gitignore: true`, a `node_modules/` excluded by an ordinary,
    /// non-security-relevant `.gitignore` entry must not be reported via
    /// [`WalkOutcome::ignored_manifests`] — [`PRUNED_DIRECTORIES`] removes it from both the
    /// filtered and unfiltered walk, so there is nothing to diff.
    #[test]
    fn test_walk_respect_gitignore_does_not_warn_on_pruned_directory() {
        let dir = tempfile::tempdir().expect("create temp dir");
        fs::create_dir(dir.path().join(".git")).expect("create .git marker");
        fs::write(dir.path().join(".gitignore"), "node_modules/\n").expect("write gitignore");
        fs::create_dir_all(dir.path().join("node_modules").join("left-pad"))
            .expect("mkdir node_modules/left-pad");
        fs::write(
            dir.path()
                .join("node_modules")
                .join("left-pad")
                .join("package.json"),
            "{}",
        )
        .expect("write vendored manifest");

        let outcome = walk(
            &[dir.path().to_path_buf()],
            &test_registry(),
            GitignorePolicy::Respect,
            SymlinkPolicy::Skip,
        );

        assert!(outcome.ignored_manifests().is_empty());
    }

    /// Critic S3: a manifest excluded only by the always-on, operator-controlled
    /// `.git/info/exclude` must not be misattributed to `.gitignore`/`.ignore` — both walks in
    /// [`detect_ignored_manifests`] must apply `git_exclude` identically, so such a file is
    /// absent from *both* and never diffed into [`WalkOutcome::ignored_manifests`].
    #[test]
    fn test_walk_git_info_exclude_suppression_not_misreported_as_ignored_manifest() {
        let dir = tempfile::tempdir().expect("create temp dir");
        fs::create_dir_all(dir.path().join(".git").join("info")).expect("mkdir .git/info");
        fs::write(
            dir.path().join(".git").join("info").join("exclude"),
            "Cargo.toml\n",
        )
        .expect("write git info/exclude");
        fs::write(dir.path().join("Cargo.toml"), "[package]\n").expect("write manifest");

        let outcome = walk(
            &[dir.path().to_path_buf()],
            &test_registry(),
            GitignorePolicy::Respect,
            SymlinkPolicy::Skip,
        );

        assert!(outcome.manifests().is_empty());
        assert!(
            outcome.ignored_manifests().is_empty(),
            ".git/info/exclude is operator-controlled, not a .gitignore/.ignore rule"
        );
    }

    #[test]
    fn test_walk_single_file_path_bypasses_gitignore() {
        let dir = tempfile::tempdir().expect("create temp dir");
        fs::write(dir.path().join(".gitignore"), "Cargo.toml\n").expect("write gitignore");
        let manifest = dir.path().join("Cargo.toml");
        fs::write(&manifest, "[package]\n").expect("write manifest");
        let outcome = walk(
            &[manifest],
            &test_registry(),
            GitignorePolicy::Respect,
            SymlinkPolicy::Skip,
        );
        assert_eq!(outcome.manifests().len(), 1);
    }

    /// Critic finding S3: issue #1124's own repro command shape is `deps-cli check
    /// path/to/Cargo.toml` where that path is itself a broken symlink — the natural
    /// single-manifest CI-gate invocation. Before the fix, `root.is_file()` (which follows
    /// symlinks and so is `false` here) let this fall into the directory-walk branch with
    /// `walk_root == display_root == root`, producing an empty `display_path` once
    /// `strip_prefix` trivially succeeded against itself. Must report the manifest's own given
    /// path, not an empty one.
    #[cfg(unix)]
    #[test]
    fn test_walk_explicit_broken_symlink_manifest_path_reports_the_given_path() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let manifest = dir.path().join("Cargo.toml");
        std::os::unix::fs::symlink(dir.path().join("does-not-exist"), &manifest)
            .expect("create broken symlink");

        let outcome = walk(
            std::slice::from_ref(&manifest),
            &test_registry(),
            GitignorePolicy::Ignore,
            SymlinkPolicy::Skip,
        );

        assert!(outcome.manifests().is_empty());
        assert!(outcome.ignored_manifests().is_empty());
        assert!(outcome.unrecognized_explicit_paths().is_empty());
        assert_eq!(outcome.broken_manifest_symlinks(), vec![manifest]);
    }

    /// Companion to the above: an explicit root that is a symlink to a real *directory* must
    /// still be walked as a directory (existing, legitimate use), not intercepted by S3's fix —
    /// only a symlink whose target fails to resolve at all is a broken-manifest candidate.
    #[cfg(unix)]
    #[test]
    fn test_walk_explicit_symlink_to_directory_root_is_still_walked() {
        let real_dir = tempfile::tempdir().expect("create real dir");
        fs::write(real_dir.path().join("Cargo.toml"), "[package]\n").expect("write manifest");

        let link_parent = tempfile::tempdir().expect("create link parent");
        let link = link_parent.path().join("link-to-real");
        std::os::unix::fs::symlink(real_dir.path(), &link)
            .expect("create symlink to a real directory");

        let outcome = walk(
            std::slice::from_ref(&link),
            &test_registry(),
            GitignorePolicy::Ignore,
            SymlinkPolicy::Skip,
        );

        assert_eq!(outcome.manifests().len(), 1);
        assert!(outcome.broken_manifest_symlinks().is_empty());
    }

    /// Critic S4 + background-review Bug 1: a manifest-shaped symlink resolving to an existing
    /// *directory*, passed as an explicit root (`deps-cli check tree/Cargo.toml`), must be
    /// reported with a non-empty path — and, critically, must NOT also be walked as a
    /// directory: `real_dir` contains a real, findable manifest, so if the old fallthrough
    /// behavior regressed, `manifests` would be non-empty here at the same time
    /// `broken_manifest_symlinks` is populated — a self-contradictory report (found earlier by
    /// background code review: S1's widened policy and S3's directory-walk fallthrough used to
    /// fire simultaneously for this exact path).
    #[cfg(unix)]
    #[test]
    fn test_walk_explicit_manifest_shaped_symlink_to_directory_root_reports_a_non_empty_path() {
        let real_dir = tempfile::tempdir().expect("create real dir");
        fs::write(real_dir.path().join("package.json"), "{}").expect("write real manifest");

        let link_parent = tempfile::tempdir().expect("create link parent");
        let link = link_parent.path().join("Cargo.toml");
        std::os::unix::fs::symlink(real_dir.path(), &link)
            .expect("create manifest-shaped symlink to a real directory");

        let outcome = walk(
            std::slice::from_ref(&link),
            &test_registry(),
            GitignorePolicy::Ignore,
            SymlinkPolicy::Skip,
        );

        assert!(
            outcome.manifests().is_empty(),
            "must not also walk the target directory's contents: {:?}",
            outcome
                .manifests()
                .iter()
                .map(|m| &m.display_path)
                .collect::<Vec<_>>()
        );
        assert!(outcome.ignored_manifests().is_empty());
        assert_eq!(outcome.broken_manifest_symlinks().len(), 1);
        assert!(
            !outcome.broken_manifest_symlinks()[0].as_os_str().is_empty(),
            "must never report an empty display path"
        );
        assert_eq!(
            outcome.broken_manifest_symlinks()[0].file_name(),
            Some(std::ffi::OsStr::new("Cargo.toml")),
            "reported path must still name the manifest: {:?}",
            outcome.broken_manifest_symlinks()
        );
    }

    /// Explicit root that is a broken symlink whose own name is *not* manifest-shaped must be
    /// reported as unrecognized, not as tampering — mirrors the never-warn-on-non-manifests
    /// invariant `classify_symlink` already applies to a discovered (non-root) entry.
    #[cfg(unix)]
    #[test]
    fn test_walk_explicit_broken_symlink_non_manifest_path_is_unrecognized() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let notes = dir.path().join("notes.txt");
        std::os::unix::fs::symlink(dir.path().join("does-not-exist"), &notes)
            .expect("create broken, non-manifest-shaped symlink");

        let outcome = walk(
            std::slice::from_ref(&notes),
            &test_registry(),
            GitignorePolicy::Ignore,
            SymlinkPolicy::Skip,
        );

        assert!(outcome.broken_manifest_symlinks().is_empty());
        assert_eq!(outcome.unrecognized_explicit_paths(), vec![notes]);
    }

    /// Regression test for #1108: a *relative* walk root must still find manifests —
    /// `url::Url::from_file_path` (used to route a discovered file) rejects relative paths, so
    /// before the fix every file under a relative root was silently dropped, and `deps-cli
    /// check`'s own no-argument default (`.`) always reported zero findings.
    ///
    /// `std::env::set_current_dir` mutates process-global state, so this test (and any other
    /// test doing the same) is serialized via [`CwdGuard`]/[`CWD_LOCK`], which also restores
    /// the original cwd even if an assertion below panics.
    #[test]
    fn test_walk_relative_root_finds_manifest() {
        let dir = tempfile::tempdir().expect("create temp dir");
        fs::write(dir.path().join("Cargo.toml"), "[package]\n").expect("write manifest");
        let _guard = CwdGuard::chdir(dir.path());

        let outcome = walk(
            &[PathBuf::from(".")],
            &test_registry(),
            GitignorePolicy::Ignore,
            SymlinkPolicy::Skip,
        );

        assert_eq!(outcome.manifests().len(), 1);
        assert!(outcome.walk_errors().is_empty());
        assert_eq!(
            outcome.manifests()[0].display_path,
            PathBuf::from("Cargo.toml")
        );
    }

    /// Companion to [`test_walk_relative_root_finds_manifest`]: an explicitly-given *relative*
    /// file path must resolve to the real path-conversion issue being fixed, not report the
    /// file as unrecognized by any ecosystem (the previous, misleading failure mode).
    #[test]
    fn test_walk_relative_explicit_file_path_is_found() {
        let dir = tempfile::tempdir().expect("create temp dir");
        fs::write(dir.path().join("Cargo.toml"), "[package]\n").expect("write manifest");
        let _guard = CwdGuard::chdir(dir.path());

        let outcome = walk(
            &[PathBuf::from("Cargo.toml")],
            &test_registry(),
            GitignorePolicy::Ignore,
            SymlinkPolicy::Skip,
        );

        assert_eq!(outcome.manifests().len(), 1);
        assert!(outcome.unrecognized_explicit_paths().is_empty());
    }

    /// Regression test for S1 (spec 062 review): the cap must count every walked entry, not
    /// just matched manifests — a small fixture plus a small `limit` proves truncation fires
    /// without needing a real `MAX_WALKED_FILES`-sized tree.
    #[test]
    fn test_walk_with_limit_truncates_on_walked_entries_not_just_manifests() {
        let dir = tempfile::tempdir().expect("create temp dir");
        for i in 0..5 {
            fs::write(dir.path().join(format!("noise-{i}.txt")), "").expect("write noise file");
        }
        fs::write(dir.path().join("Cargo.toml"), "[package]\n").expect("write manifest");

        let outcome = walk_with_limit(
            &[dir.path().to_path_buf()],
            &test_registry(),
            2,
            GitignorePolicy::Ignore,
            SymlinkPolicy::Skip,
        );
        assert!(
            outcome.truncated,
            "a 2-entry limit against a 6-entry tree must truncate"
        );
    }

    #[test]
    fn test_walk_with_limit_does_not_truncate_when_under_the_cap() {
        let dir = tempfile::tempdir().expect("create temp dir");
        fs::write(dir.path().join("Cargo.toml"), "[package]\n").expect("write manifest");
        let outcome = walk_with_limit(
            &[dir.path().to_path_buf()],
            &test_registry(),
            100,
            GitignorePolicy::Ignore,
            SymlinkPolicy::Skip,
        );
        assert!(!outcome.truncated);
        assert_eq!(outcome.manifests().len(), 1);
    }

    /// Regression test for M4 (spec 062 review): an explicitly-given path no ecosystem
    /// recognizes must be reported, not silently dropped.
    #[test]
    fn test_walk_explicit_unrecognized_path_is_reported() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let unknown = dir.path().join("notes.txt");
        fs::write(&unknown, "not a manifest").expect("write file");
        let outcome = walk(
            std::slice::from_ref(&unknown),
            &test_registry(),
            GitignorePolicy::Ignore,
            SymlinkPolicy::Skip,
        );
        assert!(outcome.manifests().is_empty());
        assert_eq!(outcome.unrecognized_explicit_paths(), vec![unknown]);
    }

    /// A file encountered while walking a directory (as opposed to given explicitly) must
    /// never be reported this way — nearly every file in a real tree doesn't match any
    /// ecosystem, and warning on each would be useless noise.
    #[test]
    fn test_walk_unrecognized_file_found_during_directory_walk_is_not_reported() {
        let dir = tempfile::tempdir().expect("create temp dir");
        fs::write(dir.path().join("notes.txt"), "not a manifest").expect("write file");
        let outcome = walk(
            &[dir.path().to_path_buf()],
            &test_registry(),
            GitignorePolicy::Ignore,
            SymlinkPolicy::Skip,
        );
        assert!(outcome.unrecognized_explicit_paths().is_empty());
    }

    #[test]
    fn test_walk_multiple_ecosystems_in_one_tree() {
        let dir = tempfile::tempdir().expect("create temp dir");
        fs::write(dir.path().join("Cargo.toml"), "[package]\n").expect("write cargo manifest");
        fs::write(dir.path().join("package.json"), "{}").expect("write npm manifest");
        let outcome = walk(
            &[dir.path().to_path_buf()],
            &test_registry(),
            GitignorePolicy::Ignore,
            SymlinkPolicy::Skip,
        );
        assert_eq!(outcome.manifests().len(), 2);
    }

    /// Regression test for background code-review fix 1 (spec 062 review): `.git`'s contents
    /// must never be walked, even though `.github`/`.gitlab` need hidden-ness lifted for the
    /// same tree. Deterministic regardless of directory-enumeration order: `.git` holds 100
    /// dummy files against a `limit` of 3 (comfortable margin over the handful of entries —
    /// the walk root, `.git`'s own directory entry, `Cargo.toml` — a correctly-hidden-filtered
    /// walk actually visits) — if `.git`'s contents were descended into at all, `entries_walked`
    /// would blow past 3 long before reaching `Cargo.toml`, truncating the walk.
    ///
    /// This test caught a real bug during review: an earlier version of this fix special-cased
    /// "the walk root's own basename starts with `.`" to mean "un-hide it, the user chose this
    /// dot-directory on purpose" — but `tempfile::tempdir()` itself creates dot-prefixed
    /// directories on macOS, so *every* test using a tempdir root silently hit that special
    /// case and disabled hidden-file filtering entirely, `.git` included. The fix removes that
    /// special-casing; `hidden(true)` never filters `walk_root` itself regardless of its name
    /// (only entries encountered *while descending*, by their own basename), so it was never
    /// needed in the first place.
    #[test]
    fn test_walk_never_descends_into_dot_git() {
        let dir = tempfile::tempdir().expect("create temp dir");
        fs::create_dir(dir.path().join(".git")).expect("create .git marker");
        for i in 0..100 {
            fs::write(dir.path().join(".git").join(format!("object-{i}")), "")
                .expect("write dummy git-internal file");
        }
        fs::write(dir.path().join("Cargo.toml"), "[package]\n").expect("write manifest");

        let outcome = walk_with_limit(
            &[dir.path().to_path_buf()],
            &test_registry(),
            3,
            GitignorePolicy::Ignore,
            SymlinkPolicy::Skip,
        );
        assert!(
            !outcome.truncated,
            ".git's 100 dummy files must never be walked, so a limit of 3 must suffice"
        );
        assert_eq!(outcome.manifests().len(), 1);
        assert_eq!(
            outcome.manifests()[0].display_path,
            PathBuf::from("Cargo.toml")
        );
    }

    /// Companion test: `.github/workflows/*.yml` must still be found in the same tree that
    /// excludes `.git` — proves the fix distinguishes the two rather than just re-hiding
    /// everything dot-prefixed again.
    #[test]
    fn test_walk_still_finds_github_workflows_alongside_excluded_dot_git() {
        let dir = tempfile::tempdir().expect("create temp dir");
        fs::create_dir(dir.path().join(".git")).expect("create .git marker");
        fs::create_dir_all(dir.path().join(".github").join("workflows")).expect("mkdir");
        fs::write(
            dir.path().join(".github").join("workflows").join("ci.yml"),
            "on: push\njobs:\n  x:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v4\n",
        )
        .expect("write workflow");

        let outcome = walk(
            &[dir.path().to_path_buf()],
            &test_registry(),
            GitignorePolicy::Ignore,
            SymlinkPolicy::Skip,
        );
        assert_eq!(outcome.manifests().len(), 1);
        assert_eq!(
            outcome.manifests()[0].display_path,
            PathBuf::from(".github").join("workflows").join("ci.yml")
        );
        assert_eq!(outcome.manifests()[0].ecosystem.id(), "github-actions");
    }

    /// Regression test for issue #1165: pins the `DotDirs::Descend` wiring at the
    /// hidden-ecosystem sub-root call site (e.g. `.github`) in [`walk_with_limit`].
    /// `hidden(true)` vs `hidden(false)` only differs on *nested* dot-prefixed entries — the
    /// sub-root itself is never filtered either way (depth 0) — so a manifest nested under a
    /// dot-prefixed directory inside `.github` is only discovered under `Descend`. If that call
    /// site were accidentally flipped to `DotDirs::Skip`, this manifest would be silently
    /// dropped and this test would fail.
    #[test]
    fn test_walk_descends_into_nested_dot_dir_under_github_sub_root() {
        let dir = tempfile::tempdir().expect("create temp dir");
        fs::create_dir_all(dir.path().join(".github").join(".hidden")).expect("mkdir");
        fs::write(
            dir.path()
                .join(".github")
                .join(".hidden")
                .join("Cargo.toml"),
            "[package]\n",
        )
        .expect("write nested manifest");

        let outcome = walk(
            &[dir.path().to_path_buf()],
            &test_registry(),
            GitignorePolicy::Ignore,
            SymlinkPolicy::Skip,
        );

        assert_eq!(outcome.manifests().len(), 1);
        assert_eq!(
            outcome.manifests()[0].display_path,
            PathBuf::from(".github").join(".hidden").join("Cargo.toml")
        );
    }

    /// Regression test for background code-review fix 2 (spec 062 review): the cap must be
    /// enforced for explicit file-path arguments too, not only for a directory walk — this
    /// was previously incrementing `entries_walked` without ever checking it in that branch.
    #[test]
    fn test_walk_with_limit_truncates_on_explicit_path_list() {
        let dir = tempfile::tempdir().expect("create temp dir");
        // Each manifest needs its own subdirectory — matched by exact filename, not a
        // pattern, so `Cargo0.toml`..`Cargo4.toml` siblings would never route to any ecosystem.
        let paths: Vec<PathBuf> = (0..5)
            .map(|i| {
                let subdir = dir.path().join(format!("pkg{i}"));
                fs::create_dir(&subdir).expect("mkdir");
                let path = subdir.join("Cargo.toml");
                fs::write(&path, "[package]\n").expect("write manifest");
                path
            })
            .collect();

        let outcome = walk_with_limit(
            &paths,
            &test_registry(),
            2,
            GitignorePolicy::Ignore,
            SymlinkPolicy::Skip,
        );
        assert!(
            outcome.truncated,
            "a 2-entry limit against 5 explicit paths must truncate"
        );
        assert_eq!(outcome.manifests().len(), 2);
    }

    /// Issue #1112, US-001: a symlinked manifest must never silently vanish from the scan
    /// under the default (`follow_symlinks: false`) mode — it is reported via
    /// `ignored_manifests`, not `manifests`.
    #[cfg(unix)]
    #[test]
    fn test_walk_default_detects_symlinked_manifest_without_following() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let real = dir.path().join("real").join("manifest-data");
        fs::create_dir(dir.path().join("real")).expect("mkdir real");
        fs::write(&real, "[package]\n").expect("write real manifest");
        std::os::unix::fs::symlink(&real, dir.path().join("Cargo.toml")).expect("create symlink");

        let outcome = walk(
            &[dir.path().to_path_buf()],
            &test_registry(),
            GitignorePolicy::Ignore,
            SymlinkPolicy::Skip,
        );

        assert!(outcome.manifests().is_empty());
        assert_eq!(
            outcome.ignored_manifests(),
            vec![PathBuf::from("Cargo.toml")]
        );
    }

    /// Issue #1124's own repro: a manifest-shaped broken symlink is reported via the
    /// dedicated `broken_manifest_symlinks` sink, not `ignored_manifests` — the two carry
    /// different signal (see `WalkOutcome::broken_manifest_symlinks`'s doc).
    #[cfg(unix)]
    #[test]
    fn test_walk_default_detects_broken_symlinked_manifest() {
        let dir = tempfile::tempdir().expect("create temp dir");
        std::os::unix::fs::symlink(
            dir.path().join("does-not-exist"),
            dir.path().join("Cargo.toml"),
        )
        .expect("create broken symlink");

        let outcome = walk(
            &[dir.path().to_path_buf()],
            &test_registry(),
            GitignorePolicy::Ignore,
            SymlinkPolicy::Skip,
        );

        assert!(outcome.manifests().is_empty());
        assert!(outcome.ignored_manifests().is_empty());
        assert_eq!(
            outcome.broken_manifest_symlinks(),
            vec![PathBuf::from("Cargo.toml")]
        );
    }

    /// A symlink whose own filename is not manifest-shaped stays silent even when broken —
    /// the never-warn-on-non-manifests invariant applies to `broken_manifest_symlinks` too.
    #[cfg(unix)]
    #[test]
    fn test_walk_broken_symlink_not_manifest_shaped_is_not_reported() {
        let dir = tempfile::tempdir().expect("create temp dir");
        std::os::unix::fs::symlink(
            dir.path().join("does-not-exist"),
            dir.path().join("notes.txt"),
        )
        .expect("create broken, non-manifest-shaped symlink");

        let outcome = walk(
            &[dir.path().to_path_buf()],
            &test_registry(),
            GitignorePolicy::Ignore,
            SymlinkPolicy::Skip,
        );

        assert!(outcome.manifests().is_empty());
        assert!(outcome.ignored_manifests().is_empty());
        assert!(outcome.broken_manifest_symlinks().is_empty());
    }

    /// `--follow-symlinks` does not defeat #1124's detection — a broken symlink still can't be
    /// resolved regardless of the flag, so it must still land in `broken_manifest_symlinks`,
    /// not silently vanish the way it did before this fix. Exercises a different code path
    /// than the default-mode test above: under `follow_symlinks: true`, `ignore`/`walkdir`
    /// must stat the entry to resolve its type and yields an `Err` for a broken target instead
    /// of an `Ok(entry)` with an unresolved type — see the `Err(error)` arm's own doc in
    /// `walk_directory`.
    #[cfg(unix)]
    #[test]
    fn test_walk_follow_symlinks_still_detects_broken_symlinked_manifest() {
        let dir = tempfile::tempdir().expect("create temp dir");
        std::os::unix::fs::symlink(
            dir.path().join("does-not-exist"),
            dir.path().join("Cargo.toml"),
        )
        .expect("create broken symlink");

        let outcome = walk(
            &[dir.path().to_path_buf()],
            &test_registry(),
            GitignorePolicy::Ignore,
            SymlinkPolicy::Follow,
        );

        assert!(outcome.manifests().is_empty());
        assert!(outcome.ignored_manifests().is_empty());
        assert_eq!(
            outcome.broken_manifest_symlinks(),
            vec![PathBuf::from("Cargo.toml")]
        );
        assert!(
            outcome.walk_errors().is_empty(),
            "Bug 3 (background code review): a mid-walk broken symlink already classified must \
             not also emit a duplicate generic IO walk error: {:?}",
            outcome.walk_errors()
        );
    }

    /// A broken hop partway through a symlink chain (`Cargo.toml -> intermediate -> nothing`)
    /// is detected the same way a directly-broken symlink is — `std::fs::metadata` follows the
    /// whole chain, so no separate per-hop handling is needed.
    #[cfg(unix)]
    #[test]
    fn test_walk_broken_symlink_chain_is_detected() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let missing = dir.path().join("does-not-exist");
        let intermediate = dir.path().join("intermediate-link");
        std::os::unix::fs::symlink(&missing, &intermediate)
            .expect("create intermediate broken symlink");
        std::os::unix::fs::symlink(&intermediate, dir.path().join("Cargo.toml"))
            .expect("create Cargo.toml -> intermediate-link -> does-not-exist");

        let outcome = walk(
            &[dir.path().to_path_buf()],
            &test_registry(),
            GitignorePolicy::Ignore,
            SymlinkPolicy::Skip,
        );

        assert!(outcome.manifests().is_empty());
        assert!(outcome.ignored_manifests().is_empty());
        assert_eq!(
            outcome.broken_manifest_symlinks(),
            vec![PathBuf::from("Cargo.toml")]
        );
    }

    /// A symlink target unreadable because of an ancestor directory's permissions (`EACCES`,
    /// not `ENOENT`) is detected the same way a dangling symlink is — `std::fs::metadata`
    /// fails identically for both. Skips its own assertions (rather than failing) when running
    /// with a privilege that bypasses directory permission checks (e.g. root in some CI
    /// containers), since the permission-denied precondition this test needs doesn't hold there.
    #[cfg(unix)]
    #[test]
    fn test_walk_symlink_target_permission_denied_is_detected_as_broken() {
        use std::os::unix::fs::PermissionsExt;

        let dir = tempfile::tempdir().expect("create temp dir");
        let blocked = dir.path().join("blocked");
        fs::create_dir(&blocked).expect("mkdir blocked");
        let target = blocked.join("manifest-data");
        fs::write(&target, "[package]\n").expect("write target");
        fs::set_permissions(&blocked, fs::Permissions::from_mode(0o000)).expect("chmod 000");
        std::os::unix::fs::symlink(&target, dir.path().join("Cargo.toml"))
            .expect("create symlink into a permission-denied directory");

        let outcome = walk(
            &[dir.path().to_path_buf()],
            &test_registry(),
            GitignorePolicy::Ignore,
            SymlinkPolicy::Skip,
        );
        let permission_check_effective = std::fs::metadata(&target).is_err();
        fs::set_permissions(&blocked, fs::Permissions::from_mode(0o755)).expect("restore perms");

        if !permission_check_effective {
            eprintln!(
                "skipping: directory permissions did not block metadata (likely running as root)"
            );
            return;
        }

        assert!(outcome.manifests().is_empty());
        assert!(outcome.ignored_manifests().is_empty());
        assert_eq!(
            outcome.broken_manifest_symlinks(),
            vec![PathBuf::from("Cargo.toml")]
        );
    }

    /// Spec 065 §6 edge case, extended for #1124: a broken, manifest-shaped symlink directly
    /// at a `PRUNED_DIRECTORIES`-excluded directory's own root is reported via
    /// `broken_manifest_symlinks`, mirroring the existing resolvable-symlink case
    /// (`test_walk_pruned_directory_symlinked_manifest_is_still_warned`).
    #[cfg(unix)]
    #[test]
    fn test_walk_pruned_directory_broken_symlinked_manifest_is_reported_as_broken() {
        let dir = tempfile::tempdir().expect("create temp dir");
        fs::create_dir(dir.path().join("vendor")).expect("mkdir vendor");
        std::os::unix::fs::symlink(
            dir.path().join("vendor").join("does-not-exist"),
            dir.path().join("vendor").join("Cargo.toml"),
        )
        .expect("create broken symlink inside pruned directory");

        let outcome = walk(
            &[dir.path().to_path_buf()],
            &test_registry(),
            GitignorePolicy::Ignore,
            SymlinkPolicy::Skip,
        );

        assert!(
            outcome.manifests().is_empty(),
            "still pruned from the primary scan"
        );
        assert!(outcome.ignored_manifests().is_empty());
        assert_eq!(
            outcome.broken_manifest_symlinks(),
            vec![PathBuf::from("vendor").join("Cargo.toml")]
        );
    }

    /// A broken symlink excluded by `.gitignore` under `--respect-gitignore` must still be
    /// detected — mirroring #1112/M5's own gitignored-resolvable-symlink case
    /// (`test_walk_respect_gitignore_does_not_duplicate_symlinked_manifest_warning`), this is
    /// only visible via `detect_ignored_manifests`'s unfiltered diff pass since the primary
    /// (filtered) walk never yields a gitignored entry at all.
    #[cfg(unix)]
    #[test]
    fn test_walk_respect_gitignore_detects_gitignored_broken_symlinked_manifest() {
        let dir = tempfile::tempdir().expect("create temp dir");
        fs::create_dir(dir.path().join(".git")).expect("create .git marker");
        fs::write(dir.path().join(".gitignore"), "Cargo.toml\n").expect("write gitignore");
        std::os::unix::fs::symlink(
            dir.path().join("does-not-exist"),
            dir.path().join("Cargo.toml"),
        )
        .expect("create broken symlink");

        let outcome = walk(
            &[dir.path().to_path_buf()],
            &test_registry(),
            GitignorePolicy::Respect,
            SymlinkPolicy::Skip,
        );

        assert!(outcome.manifests().is_empty());
        assert!(outcome.ignored_manifests().is_empty());
        assert_eq!(
            outcome.broken_manifest_symlinks(),
            vec![PathBuf::from("Cargo.toml")]
        );
    }

    /// Companion to the above: a broken symlinked manifest that is *not* gitignored must be
    /// reported exactly once even when `--respect-gitignore`'s extra unfiltered diff pass also
    /// runs — mirrors the existing resolvable-symlink dedup test
    /// (`test_walk_respect_gitignore_does_not_duplicate_symlinked_manifest_warning`).
    #[cfg(unix)]
    #[test]
    fn test_walk_respect_gitignore_does_not_duplicate_broken_symlink_warning() {
        let dir = tempfile::tempdir().expect("create temp dir");
        fs::create_dir(dir.path().join(".git")).expect("create .git marker");
        fs::write(dir.path().join(".gitignore"), "*.log\n").expect("write gitignore");
        std::os::unix::fs::symlink(
            dir.path().join("does-not-exist"),
            dir.path().join("Cargo.toml"),
        )
        .expect("create broken symlink");

        let outcome = walk(
            &[dir.path().to_path_buf()],
            &test_registry(),
            GitignorePolicy::Respect,
            SymlinkPolicy::Skip,
        );

        assert_eq!(
            outcome.broken_manifest_symlinks(),
            vec![PathBuf::from("Cargo.toml")],
            "a non-gitignored broken symlinked manifest must be reported exactly once"
        );
    }

    /// A symlink to a directory whose own name isn't manifest-shaped is silent — unaffected by
    /// critic finding S1, since the never-warn-on-non-manifests invariant is orthogonal to it.
    #[cfg(unix)]
    #[test]
    fn test_walk_symlink_to_directory_is_not_reported_as_manifest() {
        let dir = tempfile::tempdir().expect("create temp dir");
        fs::create_dir(dir.path().join("real_dir")).expect("mkdir real_dir");
        std::os::unix::fs::symlink(dir.path().join("real_dir"), dir.path().join("link_dir"))
            .expect("create symlink to directory");

        let outcome = walk(
            &[dir.path().to_path_buf()],
            &test_registry(),
            GitignorePolicy::Ignore,
            SymlinkPolicy::Skip,
        );

        assert!(outcome.manifests().is_empty());
        assert!(outcome.ignored_manifests().is_empty());
        assert!(outcome.broken_manifest_symlinks().is_empty());
    }

    /// Critic finding S1: a manifest-shaped symlink resolving to an existing *directory* is a
    /// zero-cost substitute for a dangling symlink from an attacker's perspective — both are
    /// "a manifest-shaped path that produces no manifest" — so it must land in
    /// `broken_manifest_symlinks`, not silently pass as `Irrelevant` just because the target
    /// technically resolves.
    #[cfg(unix)]
    #[test]
    fn test_walk_symlink_to_directory_with_manifest_shaped_name_is_reported_as_broken() {
        let dir = tempfile::tempdir().expect("create temp dir");
        fs::create_dir(dir.path().join("real_dir")).expect("mkdir real_dir");
        std::os::unix::fs::symlink(dir.path().join("real_dir"), dir.path().join("Cargo.toml"))
            .expect("create manifest-shaped symlink to a directory");

        let outcome = walk(
            &[dir.path().to_path_buf()],
            &test_registry(),
            GitignorePolicy::Ignore,
            SymlinkPolicy::Skip,
        );

        assert!(outcome.manifests().is_empty());
        assert!(outcome.ignored_manifests().is_empty());
        assert_eq!(
            outcome.broken_manifest_symlinks(),
            vec![PathBuf::from("Cargo.toml")]
        );
    }

    /// Companion to the above: a manifest-shaped symlink resolving to a non-regular,
    /// non-directory target (a fifo) is the same class of substitution attack and must be
    /// reported identically. Uses the `mkfifo` binary rather than unsafe `libc::mkfifo` (this
    /// workspace forbids `unsafe_code`); skips gracefully if the binary isn't on `PATH`.
    #[cfg(unix)]
    #[test]
    fn test_walk_symlink_to_fifo_with_manifest_shaped_name_is_reported_as_broken() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let fifo = dir.path().join("a-fifo");
        let mkfifo_ok = std::process::Command::new("mkfifo")
            .arg(&fifo)
            .status()
            .is_ok_and(|status| status.success());
        if !mkfifo_ok {
            eprintln!("skipping: `mkfifo` binary not available on PATH");
            return;
        }
        std::os::unix::fs::symlink(&fifo, dir.path().join("Cargo.toml"))
            .expect("create manifest-shaped symlink to a fifo");

        let outcome = walk(
            &[dir.path().to_path_buf()],
            &test_registry(),
            GitignorePolicy::Ignore,
            SymlinkPolicy::Skip,
        );

        assert!(outcome.manifests().is_empty());
        assert!(outcome.ignored_manifests().is_empty());
        assert_eq!(
            outcome.broken_manifest_symlinks(),
            vec![PathBuf::from("Cargo.toml")]
        );
    }

    /// Critic finding S2: an ordinary, non-symlink directory that merely shares a manifest's
    /// name, made unreadable by permissions, must never be reported as symlink tampering — the
    /// `is_symlink` gate in both `classify_symlink` and the walk's `Err(error)` arm must
    /// exclude it. Skips its own assertions when running with a privilege that bypasses
    /// directory permission checks (mirrors the existing EACCES symlink-target test).
    #[cfg(unix)]
    #[test]
    fn test_walk_permission_denied_non_symlink_manifest_named_directory_is_not_reported() {
        use std::os::unix::fs::PermissionsExt;

        let dir = tempfile::tempdir().expect("create temp dir");
        let blocked = dir.path().join("app.csproj");
        fs::create_dir(&blocked).expect("mkdir app.csproj");
        fs::set_permissions(&blocked, fs::Permissions::from_mode(0o000)).expect("chmod 000");

        let outcome = walk(
            &[dir.path().to_path_buf()],
            &test_registry(),
            GitignorePolicy::Ignore,
            SymlinkPolicy::Skip,
        );
        // Background-review test-gap finding: `metadata()`/`stat()` on `blocked` needs only
        // execute permission on its *ancestors*, not on `blocked` itself, so it always succeeds
        // here regardless of the chmod above — checking it (as an earlier version of this test
        // did) made the self-skip fire unconditionally, giving this test zero real coverage.
        // `read_dir()` on `blocked` does need its own execute bit, matching the operation the
        // walker actually performs (and fails) when it tries to descend into this entry.
        let permission_check_effective = std::fs::read_dir(&blocked).is_err();
        fs::set_permissions(&blocked, fs::Permissions::from_mode(0o755)).expect("restore perms");

        if !permission_check_effective {
            eprintln!(
                "skipping: directory permissions did not block read_dir (likely running as root)"
            );
            return;
        }

        assert!(
            !outcome.walk_errors().is_empty(),
            "sanity check: the walker's own descent into `blocked` must have failed for this \
             test to exercise anything"
        );
        assert!(outcome.ignored_manifests().is_empty());
        assert!(
            outcome.broken_manifest_symlinks().is_empty(),
            "a non-symlink, permission-denied directory must never be reported as symlink \
             tampering: {:?}",
            outcome.broken_manifest_symlinks()
        );
    }

    /// Spec §6 edge case: a symlink to a manifest-shaped file sitting directly at a
    /// `PRUNED_DIRECTORIES`-excluded directory's own root is reported via `ignored_manifests`,
    /// mirroring the existing regular-file case
    /// (`test_walk_default_warns_on_manifest_directly_inside_pruned_directory`).
    #[cfg(unix)]
    #[test]
    fn test_walk_pruned_directory_symlinked_manifest_is_still_warned() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let real = dir.path().join("real-cargo.toml");
        fs::write(&real, "[package]\n").expect("write real manifest");
        fs::create_dir(dir.path().join("vendor")).expect("mkdir vendor");
        std::os::unix::fs::symlink(&real, dir.path().join("vendor").join("Cargo.toml"))
            .expect("create symlink inside pruned directory");

        let outcome = walk(
            &[dir.path().to_path_buf()],
            &test_registry(),
            GitignorePolicy::Ignore,
            SymlinkPolicy::Skip,
        );

        assert!(
            outcome.manifests().is_empty(),
            "still pruned from the primary scan"
        );
        assert_eq!(
            outcome.ignored_manifests(),
            vec![PathBuf::from("vendor").join("Cargo.toml")]
        );
    }

    /// Issue #1112, US-002 (FR-003): with `follow_symlinks: true`, a symlinked manifest inside
    /// the walked root is resolved and routed, appearing in `manifests` rather than only
    /// `ignored_manifests`.
    #[cfg(unix)]
    #[test]
    fn test_walk_follow_symlinks_resolves_and_routes_manifest() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let real = dir.path().join("real").join("manifest-data");
        fs::create_dir(dir.path().join("real")).expect("mkdir real");
        fs::write(&real, "[package]\n").expect("write real manifest");
        std::os::unix::fs::symlink(&real, dir.path().join("Cargo.toml")).expect("create symlink");

        let outcome = walk(
            &[dir.path().to_path_buf()],
            &test_registry(),
            GitignorePolicy::Ignore,
            SymlinkPolicy::Follow,
        );

        assert_eq!(outcome.manifests().len(), 1);
        assert!(outcome.ignored_manifests().is_empty());
        assert_eq!(outcome.manifests()[0].ecosystem.id(), "cargo");
        // S3/FR-007: `path` (used for reading) is the resolved real path, not the symlink.
        assert_eq!(
            outcome.manifests()[0]
                .path
                .canonicalize()
                .expect("canonicalize actual path"),
            real.canonicalize()
                .expect("canonicalize expected real path")
        );
        // Review finding M3: canonicalizing both sides above can't actually distinguish
        // "symlink path" from "real path" on its own (both would resolve to the same real
        // file) — assert the *raw*, non-canonicalized paths differ too, proving `path` is
        // genuinely the resolved target, not the symlink verbatim.
        assert_ne!(
            outcome.manifests()[0].path,
            dir.path().join("Cargo.toml"),
            "path must be the resolved real path, not the symlink's own raw path"
        );
    }

    /// FR-002/US-001: the same symlinked-manifest fixture behaves oppositely depending on the
    /// flag — `follow_symlinks: false` never reads the target (empty `manifests`, populated
    /// `ignored_manifests`), `follow_symlinks: true` resolves and routes it (populated
    /// `manifests`, empty `ignored_manifests`) — proving the flag actually gates reading, not
    /// just two independently-plausible outcomes.
    #[cfg(unix)]
    #[test]
    fn test_walk_follow_symlinks_toggles_between_ignored_and_routed() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let real = dir.path().join("real").join("manifest-data");
        fs::create_dir(dir.path().join("real")).expect("mkdir real");
        fs::write(&real, "[package]\n").expect("write real manifest");
        std::os::unix::fs::symlink(&real, dir.path().join("Cargo.toml")).expect("create symlink");

        let disabled = walk(
            &[dir.path().to_path_buf()],
            &test_registry(),
            GitignorePolicy::Ignore,
            SymlinkPolicy::Skip,
        );
        assert!(disabled.manifests().is_empty());
        assert_eq!(
            disabled.ignored_manifests(),
            vec![PathBuf::from("Cargo.toml")]
        );

        let enabled = walk(
            &[dir.path().to_path_buf()],
            &test_registry(),
            GitignorePolicy::Ignore,
            SymlinkPolicy::Follow,
        );
        assert_eq!(enabled.manifests().len(), 1);
        assert!(enabled.ignored_manifests().is_empty());
    }

    /// FR-007: `display_path` reflects the symlink's own encountered path, not the resolved
    /// target's real path.
    #[cfg(unix)]
    #[test]
    fn test_walk_follow_symlinks_display_path_is_symlink_path_not_target() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let real = dir.path().join("real").join("manifest-data");
        fs::create_dir(dir.path().join("real")).expect("mkdir real");
        fs::write(&real, "[package]\n").expect("write real manifest");
        std::os::unix::fs::symlink(&real, dir.path().join("Cargo.toml")).expect("create symlink");

        let outcome = walk(
            &[dir.path().to_path_buf()],
            &test_registry(),
            GitignorePolicy::Ignore,
            SymlinkPolicy::Follow,
        );

        assert_eq!(outcome.manifests().len(), 1);
        assert_eq!(
            outcome.manifests()[0].display_path,
            PathBuf::from("Cargo.toml")
        );
    }

    /// FR-006: `follow_symlinks: true` does not defeat `PRUNED_DIRECTORIES` pruning, even when
    /// the manifest inside the pruned directory is itself reachable through a symlink.
    #[cfg(unix)]
    #[test]
    fn test_walk_follow_symlinks_still_prunes_node_modules() {
        let dir = tempfile::tempdir().expect("create temp dir");
        fs::write(dir.path().join("Cargo.toml"), "[package]\n").expect("write manifest");
        let real_vendored = dir.path().join("real-vendored-manifest");
        fs::write(&real_vendored, "{}").expect("write real vendored manifest");
        fs::create_dir_all(dir.path().join("node_modules").join("left-pad"))
            .expect("mkdir node_modules/left-pad");
        std::os::unix::fs::symlink(
            &real_vendored,
            dir.path()
                .join("node_modules")
                .join("left-pad")
                .join("package.json"),
        )
        .expect("symlink vendored manifest inside pruned directory");

        let outcome = walk(
            &[dir.path().to_path_buf()],
            &test_registry(),
            GitignorePolicy::Ignore,
            SymlinkPolicy::Follow,
        );

        assert_eq!(
            outcome.manifests().len(),
            1,
            "a symlinked manifest inside a pruned directory must still be pruned, not routed"
        );
        assert_eq!(
            outcome.manifests()[0].display_path,
            PathBuf::from("Cargo.toml")
        );
    }

    /// FR-006: `follow_symlinks: true` still respects `walk_with_limit`'s cap when a symlinked
    /// directory inflates the number of entries the walk must visit.
    #[cfg(unix)]
    #[test]
    fn test_walk_follow_symlinks_still_enforces_max_walked_files() {
        let dir = tempfile::tempdir().expect("create temp dir");
        // Review finding M4: the noise source is a *hidden* (dot-prefixed) directory, so the
        // default `hidden(true)` filter excludes it from ever being walked directly by its own
        // name — the only way to reach its 5 files is by following `noise-link`, making the
        // symlink genuinely load-bearing for this test. `limit` is chosen to comfortably cover
        // the baseline tree (walk root + `Cargo.toml` + the `noise-link` entry itself = 3
        // entries, `.noise-source` never yielded at all) but not baseline-plus-5-noise-files —
        // with `follow_symlinks: false` this same fixture and limit does *not* truncate,
        // proving the symlink (not just the raw entry count) is what pushes the walk over.
        let noise_target = dir.path().join(".noise-source");
        fs::create_dir(&noise_target).expect("mkdir .noise-source");
        for i in 0..5 {
            fs::write(noise_target.join(format!("noise-{i}.txt")), "").expect("write noise file");
        }
        std::os::unix::fs::symlink(&noise_target, dir.path().join("noise-link"))
            .expect("symlink noise directory");
        fs::write(dir.path().join("Cargo.toml"), "[package]\n").expect("write manifest");

        let outcome = walk_with_limit(
            &[dir.path().to_path_buf()],
            &test_registry(),
            4,
            GitignorePolicy::Ignore,
            SymlinkPolicy::Follow,
        );
        assert!(
            outcome.truncated,
            "a 4-entry limit against a tree inflated by a symlinked directory must truncate"
        );
    }

    /// FR-004, US-003: a symlink inside the walked root pointing to a manifest-shaped file
    /// *outside* the walked root is never routed, even with `follow_symlinks: true`.
    #[cfg(unix)]
    #[test]
    fn test_walk_follow_symlinks_rejects_target_outside_root() {
        let outside = tempfile::tempdir().expect("create outside temp dir");
        let outside_manifest = outside.path().join("Cargo.toml");
        fs::write(&outside_manifest, "[package]\n").expect("write outside manifest");

        let root = tempfile::tempdir().expect("create walked root");
        std::os::unix::fs::symlink(&outside_manifest, root.path().join("Cargo.toml"))
            .expect("create symlink escaping the walked root");

        let outcome = walk(
            &[root.path().to_path_buf()],
            &test_registry(),
            GitignorePolicy::Ignore,
            SymlinkPolicy::Follow,
        );

        assert!(
            outcome.manifests().is_empty(),
            "must never route a symlink target outside the walked root"
        );
        assert_eq!(
            outcome.ignored_manifests(),
            vec![PathBuf::from("Cargo.toml")]
        );
    }

    /// FR-005, US-003: a symlink loop must not hang or crash the walk; it is reported via
    /// `walk_errors` and the run's other manifests are still found.
    #[cfg(unix)]
    #[test]
    fn test_walk_follow_symlinks_reports_symlink_loop_via_walk_errors() {
        let dir = tempfile::tempdir().expect("create temp dir");
        fs::create_dir_all(dir.path().join("a")).expect("mkdir a");
        fs::create_dir_all(dir.path().join("b")).expect("mkdir b");
        std::os::unix::fs::symlink(dir.path().join("b"), dir.path().join("a").join("loop"))
            .expect("create a/loop -> b");
        std::os::unix::fs::symlink(dir.path().join("a"), dir.path().join("b").join("loop"))
            .expect("create b/loop -> a");
        fs::write(dir.path().join("Cargo.toml"), "[package]\n").expect("write manifest");

        let outcome = walk(
            &[dir.path().to_path_buf()],
            &test_registry(),
            GitignorePolicy::Ignore,
            SymlinkPolicy::Follow,
        );

        assert!(
            outcome
                .walk_errors()
                .iter()
                .any(|error| error.to_lowercase().contains("loop")),
            "a symlink loop must be reported via walk_errors naming the loop, not just any \
             error, and must not hang or crash: {:?}",
            outcome.walk_errors()
        );
        assert!(
            outcome
                .manifests()
                .iter()
                .any(|m| m.display_path == Path::new("Cargo.toml")),
            "other manifests in the same tree must still be found"
        );
    }

    /// M2 (critic follow-up): a self-referential manifest-shaped symlink (`Cargo.toml ->
    /// Cargo.toml`) resolves via a plain OS-level `ELOOP` (`io::Error`), distinct from the
    /// structural ancestor/descendant directory cycle `ignore`'s own `Error::Loop` variant
    /// detects during descent (`test_walk_follow_symlinks_reports_symlink_loop_via_walk_errors`
    /// above, whose names aren't manifest-shaped and whose `Error::Loop` isn't `is_io()`
    /// either way). Since this *is* an IO error on a manifest-shaped symlink, it lands in
    /// `broken_manifest_symlinks`, and — per Bug 3 (background code review) — the generic
    /// `walk_errors` push is skipped once that specific classification already fired, so no
    /// hang/crash but also no duplicate warning.
    #[cfg(unix)]
    #[test]
    fn test_walk_follow_symlinks_self_referential_manifest_symlink_is_reported_as_broken() {
        let dir = tempfile::tempdir().expect("create temp dir");
        std::os::unix::fs::symlink(dir.path().join("Cargo.toml"), dir.path().join("Cargo.toml"))
            .expect("create self-referential Cargo.toml -> Cargo.toml");

        let outcome = walk(
            &[dir.path().to_path_buf()],
            &test_registry(),
            GitignorePolicy::Ignore,
            SymlinkPolicy::Follow,
        );

        assert_eq!(
            outcome.broken_manifest_symlinks(),
            vec![PathBuf::from("Cargo.toml")]
        );
        assert!(
            outcome.walk_errors().is_empty(),
            "must not duplicate the specific broken-manifest classification with a generic \
             IO walk error: {:?}",
            outcome.walk_errors()
        );
    }

    /// M2 (critic follow-up): `--respect-gitignore` and `--follow-symlinks` combined must still
    /// detect a broken, gitignored manifest symlink — no untested interaction between the two
    /// opt-in flags for the broken case specifically (the resolvable case already has
    /// `test_walk_follow_symlinks_and_respect_gitignore_together_still_honors_gitignore`).
    #[cfg(unix)]
    #[test]
    fn test_walk_respect_gitignore_and_follow_symlinks_together_detect_broken_manifest() {
        let dir = tempfile::tempdir().expect("create temp dir");
        fs::create_dir(dir.path().join(".git")).expect("create .git marker");
        fs::write(dir.path().join(".gitignore"), "Cargo.toml\n").expect("write gitignore");
        std::os::unix::fs::symlink(
            dir.path().join("does-not-exist"),
            dir.path().join("Cargo.toml"),
        )
        .expect("create broken symlink");

        let outcome = walk(
            &[dir.path().to_path_buf()],
            &test_registry(),
            GitignorePolicy::Respect,
            SymlinkPolicy::Follow,
        );

        assert!(outcome.manifests().is_empty());
        assert!(outcome.ignored_manifests().is_empty());
        assert_eq!(
            outcome.broken_manifest_symlinks(),
            vec![PathBuf::from("Cargo.toml")]
        );
    }

    /// Spec §6 edge case: `--follow-symlinks` and `--respect-gitignore` are independent flags —
    /// a symlinked manifest excluded by `.gitignore` is still reported via the existing
    /// `.gitignore`-suppression path once resolved, exactly as a non-symlinked manifest would
    /// be, rather than `follow_symlinks` bypassing the ignore rule.
    #[cfg(unix)]
    #[test]
    fn test_walk_follow_symlinks_and_respect_gitignore_together_still_honors_gitignore() {
        let dir = tempfile::tempdir().expect("create temp dir");
        fs::create_dir(dir.path().join(".git")).expect("create .git marker");
        fs::write(dir.path().join(".gitignore"), "Cargo.toml\n").expect("write gitignore");
        let real = dir.path().join("real").join("manifest-data");
        fs::create_dir(dir.path().join("real")).expect("mkdir real");
        fs::write(&real, "[package]\n").expect("write real manifest");
        std::os::unix::fs::symlink(&real, dir.path().join("Cargo.toml")).expect("create symlink");

        let outcome = walk(
            &[dir.path().to_path_buf()],
            &test_registry(),
            GitignorePolicy::Respect,
            SymlinkPolicy::Follow,
        );

        assert!(
            outcome.manifests().is_empty(),
            "a .gitignore-excluded symlinked manifest must not be routed even under \
             --follow-symlinks"
        );
        assert_eq!(
            outcome.ignored_manifests(),
            vec![PathBuf::from("Cargo.toml")]
        );
    }

    /// Critic finding C1 regression: a symlinked *directory* (not a symlinked leaf file) must
    /// not let `--follow-symlinks` escape the walked root — the leaf entry inside it
    /// (`evil/Cargo.toml`) is not itself a symlink, so a containment check keyed only on
    /// `path_is_symlink()` would miss it.
    #[cfg(unix)]
    #[test]
    fn test_walk_follow_symlinks_rejects_directory_symlink_escaping_root() {
        let outside = tempfile::tempdir().expect("create outside temp dir");
        fs::write(outside.path().join("Cargo.toml"), "[package]\n")
            .expect("write outside manifest");

        let root = tempfile::tempdir().expect("create walked root");
        fs::write(root.path().join("Cargo.toml"), "[package]\n").expect("write root manifest");
        std::os::unix::fs::symlink(outside.path(), root.path().join("evil"))
            .expect("symlink a directory escaping the walked root");

        let outcome = walk(
            &[root.path().to_path_buf()],
            &test_registry(),
            GitignorePolicy::Ignore,
            SymlinkPolicy::Follow,
        );

        assert!(
            outcome
                .manifests()
                .iter()
                .all(|m| m.display_path != PathBuf::from("evil").join("Cargo.toml")),
            "a manifest reached only by descending into a symlinked directory outside the \
             walked root must never be routed: {:?}",
            outcome
                .manifests()
                .iter()
                .map(|m| &m.display_path)
                .collect::<Vec<_>>()
        );
        assert_eq!(
            outcome.manifests().len(),
            1,
            "the root's own, non-escaping Cargo.toml must still be found"
        );
    }

    /// Background code-review finding #2: an escaping symlinked directory must be pruned
    /// *before* `ignore`/`walkdir` descends into it, not walked entry-by-entry and rejected
    /// individually — otherwise a large external tree behind the symlink can exhaust
    /// `MAX_WALKED_FILES` on content outside the walked root, silently truncating the walk and
    /// dropping legitimate manifests elsewhere in the real tree (the exact #1112 fail-open
    /// class, reopened through this fix's own flag). Proven by pointing the escaping symlink at
    /// a directory with far more entries than a deliberately tiny `limit`, and asserting the
    /// walk still finds the root's own manifest without truncating.
    #[cfg(unix)]
    #[test]
    fn test_walk_follow_symlinks_escaping_directory_does_not_exhaust_the_budget() {
        let outside = tempfile::tempdir().expect("create outside temp dir");
        for i in 0..50 {
            fs::write(outside.path().join(format!("noise-{i}.txt")), "")
                .expect("write outside noise file");
        }

        let root = tempfile::tempdir().expect("create walked root");
        fs::write(root.path().join("Cargo.toml"), "[package]\n").expect("write root manifest");
        std::os::unix::fs::symlink(outside.path(), root.path().join("evil"))
            .expect("symlink a directory escaping the walked root");

        // Comfortably covers the walked root's own 2 entries (root dir + Cargo.toml) plus the
        // pruned `evil` entry itself, but is far smaller than the 50 files behind it — if the
        // escaping directory were walked instead of pruned, this would truncate long before
        // `Cargo.toml` is guaranteed to be counted.
        let outcome = walk_with_limit(
            &[root.path().to_path_buf()],
            &test_registry(),
            5,
            GitignorePolicy::Ignore,
            SymlinkPolicy::Follow,
        );

        assert!(
            !outcome.truncated,
            "pruning the escaping directory before descent must keep the walk well under the \
             budget, not exhaust it on external content"
        );
        assert_eq!(
            outcome.manifests().len(),
            1,
            "the root's own manifest must still be found"
        );
    }

    /// Background code-review finding #1: a symlinked manifest that is not itself
    /// `.gitignore`-excluded must be reported exactly once in `ignored_manifests`, not twice.
    /// Root cause was the primary walk's symlink-detection arm never inserting into `visited`
    /// (only the `is_file()` arm did), so `detect_ignored_manifests`'s separate unfiltered walk
    /// (run because `respect_gitignore` is true) found the same symlink again and double-counted
    /// it.
    #[cfg(unix)]
    #[test]
    fn test_walk_respect_gitignore_does_not_duplicate_symlinked_manifest_warning() {
        let dir = tempfile::tempdir().expect("create temp dir");
        fs::create_dir(dir.path().join(".git")).expect("create .git marker");
        // Present but irrelevant to this symlink — proves the duplication wasn't specific to
        // an empty .gitignore file being absent.
        fs::write(dir.path().join(".gitignore"), "*.log\n").expect("write gitignore");
        let real = dir.path().join("real").join("manifest-data");
        fs::create_dir(dir.path().join("real")).expect("mkdir real");
        fs::write(&real, "[package]\n").expect("write real manifest");
        std::os::unix::fs::symlink(&real, dir.path().join("Cargo.toml")).expect("create symlink");

        let outcome = walk(
            &[dir.path().to_path_buf()],
            &test_registry(),
            GitignorePolicy::Respect,
            SymlinkPolicy::Skip,
        );

        assert_eq!(
            outcome.ignored_manifests(),
            vec![PathBuf::from("Cargo.toml")],
            "a non-gitignored symlinked manifest must be reported exactly once"
        );
    }

    /// Critic finding S1 regression: a registered ecosystem's own hidden dot-directory (e.g.
    /// `.github`) escaping the walked root via a symlink must not be scanned, regardless of
    /// `follow_symlinks` — `ignore`/`walkdir` always follows a walk's own root symlink, so this
    /// containment check must apply in the default mode too.
    #[cfg(unix)]
    #[test]
    fn test_walk_default_rejects_symlinked_hidden_ecosystem_directory_escaping_root() {
        let outside = tempfile::tempdir().expect("create outside temp dir");
        fs::create_dir_all(outside.path().join("workflows")).expect("mkdir workflows");
        fs::write(
            outside.path().join("workflows").join("ci.yml"),
            "on: push\njobs:\n  x:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v4\n",
        )
        .expect("write workflow");

        let root = tempfile::tempdir().expect("create walked root");
        std::os::unix::fs::symlink(outside.path(), root.path().join(".github"))
            .expect("symlink .github escaping the walked root");

        let outcome = walk(
            &[root.path().to_path_buf()],
            &test_registry(),
            GitignorePolicy::Ignore,
            SymlinkPolicy::Skip,
        );

        assert!(
            outcome.manifests().is_empty(),
            "a symlinked .github escaping the walked root must never be scanned, even in the \
             default mode: {:?}",
            outcome
                .manifests()
                .iter()
                .map(|m| &m.display_path)
                .collect::<Vec<_>>()
        );
    }
}