ferralk 0.9.2

Portable filesystem walking for ferralk.
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
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
#![deny(unsafe_code)]
#![warn(missing_docs)]
#![doc = "Portable filesystem walking."]

//! A safe std::fs walker with a portable `std::fs` backend.
//!
//! Paths stay as PathBuf throughout the public API. Patterns are matched
//! against root-relative encoded path bytes; no filesystem result is converted
//! through UTF-8.

use std::{
    borrow::Cow,
    collections::HashSet,
    error::Error,
    ffi::{OsStr, OsString},
    fmt, fs,
    path::{Path, PathBuf},
    sync::{
        Arc, Mutex,
        atomic::{AtomicBool, Ordering},
    },
};

use ferralk_glob::{Pattern, PatternError, PatternOptions, WalkerPathViability};

pub use ferralk_glob;

#[cfg(all(feature = "native-linux", target_os = "linux"))]
#[allow(unsafe_code)]
mod linux_native;
#[cfg(all(feature = "native-macos", target_os = "macos"))]
#[allow(unsafe_code)]
mod macos_native;
/// Differential parity between the active native backend and the portable one.
#[cfg(all(
    test,
    any(
        all(feature = "native-macos", target_os = "macos"),
        all(feature = "native-linux", target_os = "linux")
    )
))]
mod native_parity;
#[cfg(all(feature = "native-linux", target_os = "linux"))]
#[doc(hidden)]
pub use linux_native::fuzz_validate_records as fuzz_validate_linux_dirent_records;
#[cfg(all(feature = "native-macos", target_os = "macos"))]
#[doc(hidden)]
pub use macos_native::fuzz_validate_bulk_record as fuzz_validate_macos_bulk_record;
#[cfg(all(feature = "native-macos", target_os = "macos"))]
#[doc(hidden)]
pub use macos_native::fuzz_validate_records as fuzz_validate_macos_dirent_records;
mod absolute;

/// Walker-pattern entry point for the corpus harness, exported the way the
/// fuzz entry points are: for `tools/`, not for consumers.
///
/// Returns the pattern after the walker's absolute-root rewrite, or `None`
/// when the pattern names paths outside `root` and so can select nothing. The
/// walker additionally compiles and validates this spelling before using it.
/// `windows_paths`
/// chooses which spelling of a path the rules read instead of the host's, so
/// one corpus case describes one rule on every platform - including the rules
/// that only apply to Windows, which would otherwise be recorded where nothing
/// replays them.
#[doc(hidden)]
pub fn corpus_rewrite_absolute_pattern(
    pattern: &[u8],
    root: &[u8],
    windows_paths: bool,
) -> Result<Option<Vec<u8>>, PatternError> {
    let syntax = if windows_paths {
        absolute::Syntax::Windows
    } else {
        absolute::Syntax::Posix
    };
    rewrite_pattern_for_root(pattern, root, syntax)
}
mod classify;
mod gitignore;
mod ignore_rules;

/// Fuzz entry point for the gitignore rule layer (ADR-0014), exported the way
/// the native dirent parsers are: for the harness in `fuzz/`, not for consumers.
#[doc(hidden)]
pub use ignore_rules::fuzz_rule as fuzz_ignore_rule;
#[doc(hidden)]
pub use ignore_rules::fuzz_rule_bytes as fuzz_ignore_rule_bytes;
mod parallel;
mod scheduler;

use classify::{DirectoryTask, EmittedEntry, EntryAction, TraversalContext, classify_entry};
use gitignore::{IgnoreReadError, IgnoreScope};

/// Controls what a walk does after a recoverable filesystem error.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ErrorPolicy {
    /// Stop immediately and return the first error.
    Abort,
    /// Continue walking and do not retain recoverable errors discovered below
    /// a root. A caller-supplied root that cannot be opened is still retained
    /// (or yielded by [`Walker::stream`]), so it cannot look like an empty
    /// tree.
    Skip,
    /// Continue walking and return accumulated recoverable errors.
    #[default]
    Collect,
}

/// Cloneable, caller-controlled cooperative cancellation handle for a walk.
///
/// A walker only observes this handle; internal aborts, worker startup
/// failures, visitor stops, and panics never cancel it. This lets callers
/// share one token across walks or reuse it after an individual walk fails.
#[derive(Debug, Clone, Default)]
pub struct CancellationToken {
    cancelled: Arc<AtomicBool>,
}

impl CancellationToken {
    /// Requests that the walker stop before its next filesystem operation.
    pub fn cancel(&self) {
        self.cancelled.store(true, Ordering::Release);
    }

    /// Reports whether cancellation has been requested.
    #[must_use]
    pub fn is_cancelled(&self) -> bool {
        self.cancelled.load(Ordering::Acquire)
    }
}

/// How far an ordinary wildcard reaches in a walker pattern.
///
/// `*`, `?` and character classes are the ordinary wildcards; `**` crosses
/// separators under either mode.
///
/// ```
/// use ferralk::{WildcardMode, Walker};
///
/// // The default. `*.ts` selects a TypeScript file in the walk root, the way
/// // a shell glob does, and `src/*.ts` selects one directly inside `src`.
/// let scoped = Walker::new(".").include("*.ts")?;
///
/// // A wildcard spans separators, the way `globset` and `fast-glob` read a
/// // pattern by default: `*.ts` now also selects `a/b.ts`.
/// let crossing = Walker::new(".")
///     .wildcard_mode(WildcardMode::SeparatorCrossing)
///     .include("*.ts")?;
/// # Ok::<(), ferralk::ferralk_glob::PatternError>(())
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum WildcardMode {
    /// A wildcard stays inside one path component: `*.ts` matches `main.ts`
    /// and not `src/main.ts`. Filesystem-glob semantics, and the default.
    #[default]
    ComponentScoped,
    /// A wildcard spans separators: `*.ts` matches `main.ts` and `src/main.ts`
    /// alike. This is how `globset` and `fast-glob` read an unconfigured
    /// pattern, so it is the mode to pick when porting patterns from them.
    SeparatorCrossing,
}

/// Behaviour switches for a Walker.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct WalkOptions {
    follow_symlinks: bool,
    sort: bool,
    metadata: bool,
    directories_only: bool,
    files_only: bool,
    resolve_symlink_kind: bool,
    skip_hidden: bool,
    keep_git_dir: bool,
    max_depth: Option<usize>,
}

impl WalkOptions {
    /// Follows directory symlinks discovered below a walk root while retaining
    /// a canonical-path cycle guard.
    ///
    /// A root supplied to [`Walker::new`] or [`Walker::add_root`] is always
    /// opened as a directory, so a root that is a symlink to a directory is
    /// traversed even when this option is `false`. This option controls only
    /// symlink entries discovered while walking that root.
    #[must_use]
    pub const fn follow_symlinks(mut self, enabled: bool) -> Self {
        self.follow_symlinks = enabled;
        self
    }

    /// Sorts final entries by their native path representation.
    #[must_use]
    pub const fn sort(mut self, enabled: bool) -> Self {
        self.sort = enabled;
        self
    }

    /// Collects filesystem metadata for every returned entry.
    #[must_use]
    pub const fn metadata(mut self, enabled: bool) -> Self {
        self.metadata = enabled;
        self
    }

    /// Returns only directories while continuing to traverse through them.
    ///
    /// A symlink is reported by its own kind, so a link pointing at a directory
    /// is *not* a directory here unless the walk resolves it - by following
    /// symlinks, or by [`WalkOptions::resolve_symlink_kind`].
    #[must_use]
    pub const fn directories_only(mut self, enabled: bool) -> Self {
        self.directories_only = enabled;
        self
    }

    /// Returns only files while continuing to traverse through directories.
    ///
    /// A symlink is reported by its own kind, so every symlink counts as a file
    /// here - including a broken one and one pointing at a directory - unless
    /// the walk resolves it. [`WalkOptions::resolve_symlink_kind`] is what makes
    /// this filter agree with `Path::is_file`.
    #[must_use]
    pub const fn files_only(mut self, enabled: bool) -> Self {
        self.files_only = enabled;
        self
    }

    /// Classifies symlink entries by what they point at, for the
    /// [`files_only`](WalkOptions::files_only) and
    /// [`directories_only`](WalkOptions::directories_only) filters.
    ///
    /// A directory listing reports a symlink as a symlink and says nothing
    /// about its target, so without this the kind filters see every symlink as
    /// a non-directory: `files_only` keeps broken links and links to
    /// directories, and `directories_only` drops links to directories. Callers
    /// who mean `Path::is_file` - which follows the link - get neither.
    ///
    /// With this enabled, one `metadata` call per symlink entry decides:
    ///
    /// | the link points at | `files_only` | `directories_only` |
    /// |---|---|---|
    /// | a file | kept | dropped |
    /// | a directory | dropped | kept |
    /// | nothing (broken) | dropped | dropped |
    ///
    /// A broken link is an answer rather than a failure - there is no target,
    /// so the entry is neither a file nor a directory - and is dropped without
    /// an error. A `metadata` call that fails for any other reason leaves the
    /// kind unknown, and that *is* reported through the configured
    /// [`ErrorPolicy`], with the entry dropped either way.
    ///
    /// The stat is paid only for symlink entries, only when one of the two kind
    /// filters is on, and only when the walk is not already following symlinks -
    /// following resolves the same question on its own. It does not change what
    /// [`WalkEntry::kind`] reports, which stays what the listing observed, nor
    /// which entries a pattern matches, nor where the walk descends: this
    /// switch answers "what is this", while
    /// [`follow_symlinks`](WalkOptions::follow_symlinks) answers "does the walk
    /// go through it".
    ///
    /// Off by default, because turning it on changes which entries a walk
    /// returns.
    #[must_use]
    pub const fn resolve_symlink_kind(mut self, enabled: bool) -> Self {
        self.resolve_symlink_kind = enabled;
        self
    }

    /// Excludes entries with a leading-period path component and does not
    /// descend into hidden directories.
    ///
    /// This is a traversal filter, not matcher semantics, and therefore not the
    /// same switch as [`Walker::match_hidden`]: it removes hidden entries from
    /// the walk before any include or exclude pattern is consulted, while
    /// `match_hidden` decides whether a wildcard is allowed to cover a leading
    /// period at all. They compose in one direction only - with `skip_hidden`
    /// enabled no hidden path survives long enough for `match_hidden` to have
    /// anything to say about it.
    #[must_use]
    pub const fn skip_hidden(mut self, enabled: bool) -> Self {
        self.skip_hidden = enabled;
        self
    }

    /// Keeps `.git` directories when Gitignore matching is enabled.
    #[must_use]
    pub const fn keep_git_dir(mut self, enabled: bool) -> Self {
        self.keep_git_dir = enabled;
        self
    }

    /// Includes entries through `max_depth` components below the root without
    /// descending into directories at that depth.
    #[must_use]
    pub const fn max_depth(mut self, max_depth: usize) -> Self {
        self.max_depth = Some(max_depth);
        self
    }
}

/// Filesystem kind observed for one walked entry.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WalkEntryKind {
    /// A regular non-directory, non-symlink entry.
    File,
    /// A directory entry.
    Directory,
    /// A symbolic link, including one followed for traversal.
    Symlink,
}

/// One matching filesystem entry.
///
/// Entries are [`Clone`], so callers can retain an entry in more than one
/// collection. Cloning preserves the captured path, walk-root identity, entry
/// flags, depth, and optional metadata snapshot.
#[derive(Debug, Clone)]
pub struct WalkEntry {
    path: PathBuf,
    /// The walk root this entry was found under. Shared per root rather than
    /// copied per entry.
    root: Arc<Path>,
    is_dir: bool,
    is_symlink: bool,
    depth: usize,
    /// Boxed rather than inline: `fs::Metadata` is the platform `stat` struct,
    /// around 144 bytes on Unix, and carrying it in the entry made every
    /// `WalkEntry` that size whether or not
    /// [`WalkOptions::metadata`](WalkOptions::metadata) was ever asked for. A
    /// walk collects millions of these into one `Vec`, and the default walk
    /// leaves the option off. The box costs one allocation per entry on the
    /// walks that do ask, which already paid a `stat` syscall for it.
    metadata: Option<Box<fs::Metadata>>,
}

impl WalkEntry {
    /// Absolute or caller-relative path preserved from the walker.
    #[must_use]
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Encoded bytes of [`Self::path`], ready for byte-first matchers.
    ///
    /// This is exactly [`OsStr::as_encoded_bytes`] on the path's native
    /// representation: raw filesystem bytes on Unix and lossless WTF-8 on
    /// Windows. It performs no allocation or Unicode conversion, so it is the
    /// bridge to [`ferralk_glob::Pattern`] when a visitor needs to match the
    /// entry itself.
    ///
    /// ```no_run
    /// use ferralk::{Verdict, Walker, ferralk_glob::{Pattern, PatternOptions}};
    ///
    /// let matcher = Pattern::compile("**/*.rs", PatternOptions::default().recursive_double_star(true))?;
    /// let result = Walker::new("src").visit(|entry| {
    ///     matcher.is_match(entry.path_bytes()).then_some(Verdict::Keep).unwrap_or(Verdict::Skip)
    /// })?;
    /// # let _ = result;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    #[must_use]
    pub fn path_bytes(&self) -> &[u8] {
        self.path.as_os_str().as_encoded_bytes()
    }

    /// The walk root this entry was found under, exactly as it was given to
    /// [`Walker::new`] or [`Walker::add_root`].
    ///
    /// A single-root walk answers with that one root, so the accessor means the
    /// same thing however many roots there are. It exists because a path alone
    /// does not settle the question once roots may contain one another: an
    /// entry under both `/a` and `/a/b` is produced once per root, and only the
    /// root it came from distinguishes the two. [`WalkEntry::depth`] is counted
    /// from this root as well.
    ///
    /// ```no_run
    /// # use ferralk::Walker;
    /// let result = Walker::new("crates").add_root("tools")?.collect()?;
    /// for entry in result.entries() {
    ///     let inside = entry.path().strip_prefix(entry.root()).expect("under its root");
    ///     println!("{} in {}", inside.display(), entry.root().display());
    /// }
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    #[must_use]
    pub fn root(&self) -> &Path {
        &self.root
    }

    /// Whether this entry is a directory according to the selected backend.
    #[must_use]
    pub const fn is_dir(&self) -> bool {
        self.is_dir
    }

    /// Whether this entry was observed as a symbolic link.
    #[must_use]
    pub const fn is_symlink(&self) -> bool {
        self.is_symlink
    }

    /// Filesystem kind observed for this entry.
    #[must_use]
    pub const fn kind(&self) -> WalkEntryKind {
        if self.is_symlink {
            WalkEntryKind::Symlink
        } else if self.is_dir {
            WalkEntryKind::Directory
        } else {
            WalkEntryKind::File
        }
    }

    /// Number of path components between the walk root and this entry.
    #[must_use]
    pub const fn depth(&self) -> usize {
        self.depth
    }

    /// Native basename of this entry, when the path has a final component.
    #[must_use]
    pub fn basename(&self) -> Option<&std::ffi::OsStr> {
        self.path.file_name()
    }

    /// Metadata collected when WalkOptions metadata is enabled.
    #[must_use]
    pub fn metadata(&self) -> Option<&fs::Metadata> {
        self.metadata.as_deref()
    }
}

/// A recoverable I/O failure observed while walking.
#[derive(Debug)]
pub struct WalkError {
    operation: &'static str,
    path: PathBuf,
    source: std::io::Error,
}

impl WalkError {
    fn new(operation: &'static str, path: PathBuf, source: std::io::Error) -> Self {
        Self {
            operation,
            path,
            source,
        }
    }

    /// Operation that produced the error.
    #[must_use]
    pub const fn operation(&self) -> &'static str {
        self.operation
    }

    /// Path passed to the failed operation.
    #[must_use]
    pub fn path(&self) -> &Path {
        &self.path
    }
}

impl fmt::Display for WalkError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            formatter,
            "{} {}: {}",
            self.operation,
            self.path.display(),
            self.source
        )
    }
}

impl Error for WalkError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        Some(&self.source)
    }
}

/// What a [`Walker::visit`] visitor decides about one entry.
///
/// The visitor runs on the thread that produced the entry, so a caller with a
/// matcher of its own filters in parallel instead of over the returned list.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Verdict {
    /// Keep the entry in the result.
    Keep,
    /// Leave the entry out of the result. Traversal is unaffected: a directory
    /// is still descended into, because pruning a subtree is what
    /// [`Walker::exclude`] expresses, and one verdict meaning different things
    /// for files and directories would be a trap.
    Skip,
    /// Leave the entry out and end the walk, the way a cancellation request
    /// does. A caller that wants the entry which stopped the walk records it in
    /// the visitor, where the decision was made anyway.
    Stop,
}

/// Completed entries and recoverable errors.
#[derive(Debug)]
pub struct WalkResult {
    entries: Vec<WalkEntry>,
    errors: Vec<WalkError>,
    cancelled: bool,
}

impl WalkResult {
    /// Entries accepted by the include/exclude filters.
    #[must_use]
    pub fn entries(&self) -> &[WalkEntry] {
        &self.entries
    }

    /// Recoverable traversal failures retained by the configured error policy.
    #[must_use]
    pub fn errors(&self) -> &[WalkError] {
        &self.errors
    }

    /// Consumes the result and returns its two result channels.
    #[must_use]
    pub fn into_parts(self) -> (Vec<WalkEntry>, Vec<WalkError>) {
        (self.entries, self.errors)
    }

    /// Whether a cancellation request or a [`Verdict::Stop`] stopped traversal
    /// before completion.
    #[must_use]
    pub const fn was_cancelled(&self) -> bool {
        self.cancelled
    }
}

/// A borrowed per-entry visitor, shared by every worker of one walk.
///
/// Behind a reference rather than a generic parameter: the walk already reaches
/// its filesystem through `&dyn DirectoryBackend`, and one indirect call per
/// entry is not measurable against a traversal made of syscalls.
pub(crate) type EntryVisitor<'a> = &'a (dyn Fn(&WalkEntry) -> Verdict + Sync + 'a);

/// The visitor [`Walker::collect`] runs: every entry survives.
pub(crate) fn keep_every_entry(_: &WalkEntry) -> Verdict {
    Verdict::Keep
}

/// One root of a walk, with the patterns as they read for it.
///
/// A relative pattern means the same thing under every root, but an absolute
/// one does not: `/repo/src/**` selects everything under a root of `/repo` and
/// nothing at all under a root of `/other`. Compiling per root is what lets one
/// pattern list serve several roots, and it is why the rewrite in
/// [`crate::absolute`] takes the root as an argument.
#[derive(Debug, Clone)]
struct RootPlan {
    path: PathBuf,
    /// Shared with every entry produced under this root, so an entry can name
    /// its root without each one owning a copy of the path.
    shared_path: Arc<Path>,
    /// Byte index at which the root-relative part of any path built under this
    /// root begins. See [`RootPlan::relative_start`].
    relative_start: usize,
    includes: Vec<TraversalPattern>,
    excludes: Vec<TraversalPattern>,
}

/// Builder for a portable serial traversal.
#[derive(Debug, Clone)]
pub struct Walker {
    /// Never empty: [`Walker::new`] establishes the first one.
    roots: Vec<RootPlan>,
    /// Include patterns as the caller wrote them, kept so that a root added
    /// later can be given its own reading of each one.
    include_sources: Vec<Vec<u8>>,
    /// Exclude patterns, on the same terms.
    exclude_sources: Vec<Vec<u8>>,
    match_hidden: bool,
    options: WalkOptions,
    error_policy: ErrorPolicy,
    cancellation: Option<CancellationToken>,
    respect_git_ignore: bool,
    /// Explicit effective Git settings. `None` reads supported
    /// repository-local config; `Some` wins over it.
    git_ignore_case: Option<bool>,
    git_precompose_unicode: Option<bool>,
    wildcard_mode: WildcardMode,
    threads: usize,
}

/// Hard ceiling for eagerly allocated worker slots. The scheduler still
/// starts helpers lazily, but every configured slot owns queues and scratch
/// buffers as soon as a walk widens.
const MAX_WORKERS: usize = 256;

impl RootPlan {
    /// Where the root-relative part of a walked path starts, in bytes.
    ///
    /// Every path the walk produces is the root with names pushed onto it, so
    /// the offset is the same for all of them and is worth deriving once
    /// instead of running `strip_prefix` — a component-by-component comparison
    /// — over every entry. Pushing a name is what settles the question: it is
    /// what inserts the separator, and it inserts none when the root already
    /// ends with one or is empty.
    fn relative_start(root: &Path) -> usize {
        let mut probe = root.to_path_buf();
        probe.push("x");
        probe.as_os_str().as_encoded_bytes().len() - 1
    }

    /// A root with no patterns compiled for it yet.
    fn new(path: PathBuf) -> Self {
        Self {
            relative_start: Self::relative_start(&path),
            shared_path: Arc::from(path.as_path()),
            path,
            includes: Vec::new(),
            excludes: Vec::new(),
        }
    }
}

impl Walker {
    /// Starts a walk rooted at root.
    ///
    /// Further roots may be added with [`Walker::add_root`] or
    /// [`Walker::try_add_root`]. `root` must name
    /// a readable directory: a plain file produces a `read_dir` not-a-directory
    /// error and no entry for the file. A directory symlink supplied as the
    /// root is traversed regardless of [`WalkOptions::follow_symlinks`], which
    /// only controls symlinks discovered below the root.
    #[must_use]
    pub fn new(root: impl Into<PathBuf>) -> Self {
        Self {
            roots: vec![RootPlan::new(root.into())],
            include_sources: Vec::new(),
            exclude_sources: Vec::new(),
            match_hidden: false,
            options: WalkOptions::default(),
            error_policy: ErrorPolicy::default(),
            cancellation: None,
            respect_git_ignore: false,
            git_ignore_case: None,
            git_precompose_unicode: None,
            wildcard_mode: WildcardMode::default(),
            threads: std::thread::available_parallelism()
                .map(std::num::NonZeroUsize::get)
                .unwrap_or(1)
                .min(MAX_WORKERS),
        }
    }

    /// Adds an OR-ed include pattern and returns the builder for consuming
    /// chains. No includes means every non-excluded entry is returned.
    ///
    /// The pattern may be absolute. See [`Walker::exclude`] for what that
    /// means and when it is rejected.
    ///
    /// ```
    /// use ferralk::Walker;
    ///
    /// // These select the same entries. The absolute spelling follows the
    /// // host's path syntax: `/repo` on Unix and `C:/repo` on Windows.
    /// let (root, absolute) = if cfg!(windows) {
    ///     ("C:/repo", "C:/repo/src/**/*.ts")
    /// } else {
    ///     ("/repo", "/repo/src/**/*.ts")
    /// };
    /// let written_relative = Walker::new(root).include("src/**/*.ts")?;
    /// let held_absolute = Walker::new(root).include(absolute)?;
    /// # Ok::<(), ferralk::ferralk_glob::PatternError>(())
    /// ```
    ///
    /// For a caller-supplied list that may contain invalid patterns, use
    /// [`Walker::try_include`] instead. It borrows the builder, so rejecting a
    /// pattern leaves the caller's configured walker available for the next
    /// pattern.
    pub fn include(mut self, pattern: impl AsRef<[u8]>) -> Result<Self, PatternError> {
        self.try_include(pattern)?;
        Ok(self)
    }

    /// Adds an OR-ed include pattern without consuming the builder.
    ///
    /// This is the borrowed counterpart to [`Walker::include`]. It is useful
    /// when applying a user-supplied pattern list: an invalid pattern returns
    /// its [`PatternError`] and leaves this walker unchanged, so later entries
    /// can still be considered. A valid pattern has the same semantics as
    /// [`Walker::include`] and composes with every root and matcher mode
    /// already configured on this walker.
    ///
    /// ```no_run
    /// use ferralk::Walker;
    ///
    /// let mut walker = Walker::new("workspace");
    /// for pattern in ["src/**/*.rs", "[a", "tests/**/*.rs"] {
    ///     if let Err(error) = walker.try_include(pattern) {
    ///         eprintln!("skipping {pattern:?}: {error}");
    ///     }
    /// }
    ///
    /// // The two valid patterns remain configured despite the rejected `[a`.
    /// let result = walker.collect()?;
    /// # let _ = result;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn try_include(&mut self, pattern: impl AsRef<[u8]>) -> Result<&mut Self, PatternError> {
        let pattern = pattern.as_ref();
        // Compiled for every root before any of them is changed, so a pattern
        // one root rejects leaves the walker as it was rather than half updated.
        let compiled = self.compile_for_every_root(pattern)?;
        for (root, pattern) in self.roots.iter_mut().zip(compiled) {
            root.includes.push(pattern);
        }
        self.include_sources.push(pattern.to_vec());
        Ok(self)
    }

    /// Adds an OR-ed exclude pattern. Excluded directories are not descended.
    ///
    /// # Absolute patterns
    ///
    /// A pattern that starts at a filesystem root is understood as naming
    /// absolute paths, and the walk root is removed from it so that it selects
    /// the same entries a caller would have written by hand. This is detected
    /// rather than requested, because a caller holding a mixed list of patterns
    /// would otherwise have to sort them itself - which is the arithmetic this
    /// exists to remove. What counts as absolute is the platform's own rule:
    /// a leading `/` on Unix, a drive letter or a UNC share on Windows, where a
    /// single leading separator is drive-relative and so is compiled as a
    /// walker pattern rather than treated as absolute.
    ///
    /// A pattern that names paths outside the walk root selects nothing, which
    /// is what it would have selected had it been matched against absolute
    /// paths. It is not an error: a caller filtering one list across several
    /// roots expects the patterns meant for other roots to fall away here.
    ///
    /// Three shapes are rejected with a [`PatternError`], because guessing at
    /// them would silently select the wrong entries:
    ///
    /// - a wildcard at or above the walk root (`/*/x.ts`, `/**/*.ts`, or
    ///   `/repo*/x.ts` for a root of `/repo`), which may or may not cover the
    ///   root and cannot be decided without matching. Write the part below the
    ///   root instead: `**/*.ts` selects everything under it.
    /// - a `..` component, which is not resolved here. Folding it away
    ///   lexically is wrong across a symlink, and resolving it properly would
    ///   mean touching the filesystem to compile a pattern.
    /// - a pattern naming the walk root itself, which selects nothing because
    ///   the walk emits what is inside the root. Add `/**`.
    ///
    /// Separators, repeated or trailing, and `.` components are ignored on
    /// both sides, so `/repo//src/*.ts` against a root of `/repo/` rewrites the
    /// same as the tidy spelling.
    ///
    /// # Patterns are written with `/`
    ///
    /// On every platform, per ADR-0005: `\` is the escape character, not a
    /// separator, so a pattern built by joining `PathBuf`s on Windows asks for
    /// each separator's next byte literally and matches nothing. On Windows
    /// such a pattern is rejected rather than left to fail silently, but only
    /// where the plain text of the pattern demands a byte Windows forbids in a
    /// name - `C:\repo\**`, `src\*.ts`, `\\server\share`. Escaping an
    /// ordinary byte is legal, so `a\b\c` selects a file named `abc`; and
    /// inside a group the escape is one member among several, so `[a\*]` and
    /// `{a,\*}` still select `a`. Build the pattern as a pattern and let
    /// [`Walker::new`] hold the path.
    ///
    /// ```
    /// use ferralk::Walker;
    ///
    /// // Both of these are about Unix spelling, where a leading `/` is what
    /// // makes a path absolute.
    /// if cfg!(unix) {
    ///     // Selects nothing: the pattern is about a different tree.
    ///     let elsewhere = Walker::new("/repo").exclude("/other/**").unwrap();
    ///
    ///     // Rejected: the wildcard sits above the root.
    ///     assert!(Walker::new("/repo").exclude("/**/*.tmp").is_err());
    /// }
    /// ```
    ///
    /// For a caller-supplied list that may contain invalid patterns, use
    /// [`Walker::try_exclude`] instead. It preserves the configured builder
    /// when a pattern is rejected.
    pub fn exclude(mut self, pattern: impl AsRef<[u8]>) -> Result<Self, PatternError> {
        self.try_exclude(pattern)?;
        Ok(self)
    }

    /// Adds an OR-ed exclude pattern without consuming the builder.
    ///
    /// This is the borrowed counterpart to [`Walker::exclude`]. It has the
    /// same all-or-nothing compilation rule as [`Walker::try_include`]: a
    /// rejected pattern leaves every root and previously configured filter
    /// unchanged, while a valid one composes with them.
    pub fn try_exclude(&mut self, pattern: impl AsRef<[u8]>) -> Result<&mut Self, PatternError> {
        let pattern = pattern.as_ref();
        let compiled = self.compile_for_every_root(pattern)?;
        for (root, pattern) in self.roots.iter_mut().zip(compiled) {
            root.excludes.push(pattern);
        }
        self.exclude_sources.push(pattern.to_vec());
        Ok(self)
    }

    /// Adds another root to the same walk.
    ///
    /// One walker, one thread pool, several trees: the roots become the walk's
    /// initial directories and share the scheduler and helper-spawn floor. Each
    /// root keeps its own visited-directory guard, so following symlinks still
    /// preserves the same concatenation semantics as separate walks. A caller
    /// with several source trees no longer pays pool startup per tree.
    ///
    /// # Semantics
    ///
    /// - **Patterns are per root.** Include and exclude patterns stay
    ///   root-relative and are applied under every root, so `src/**/*.ts`
    ///   selects that subtree of each. An absolute pattern is rewritten for
    ///   each root separately, which means a pattern naming one root's tree
    ///   selects nothing under the others - the reading
    ///   [`Walker::exclude`] describes, and the reason it treats an
    ///   out-of-root pattern as a verdict rather than an error.
    /// - **`depth` and [`WalkEntry::root`] are relative to the root the entry
    ///   came from**, so a walk of several trees says the same thing about each
    ///   entry that a walk of that one tree would.
    /// - **Overlapping roots deliver their overlap more than once.** Adding
    ///   `/a` and `/a/b` yields everything under `/a/b` twice, because a
    ///   multi-root walk is defined as the concatenation of the single-root
    ///   walks. Suppressing that would need the identity of every directory, a
    ///   `stat` per directory that only the symlink-following mode pays today,
    ///   and would make adding a root able to remove entries. A caller who
    ///   wants each path once passes roots that do not contain one another.
    /// - **A root that cannot be read is an ordinary walk error** for that
    ///   root's path, and the other roots are still walked, subject to
    ///   [`ErrorPolicy`]. Even [`ErrorPolicy::Skip`] reports that root error,
    ///   because a caller-supplied root must not be indistinguishable from an
    ///   empty tree.
    ///
    /// The order roots are visited in is not part of the contract, any more
    /// than the order of entries within one root is: the scheduler hands the
    /// initial tasks out like any others. `WalkOptions::sort(true)` is what
    /// orders a result.
    ///
    /// # Errors
    ///
    /// Returns the error an already-added absolute pattern produces when it is
    /// rewritten for this root - the same rejections [`Walker::exclude`] lists.
    /// Builder order does not matter: adding the root first and the pattern
    /// second reports the same error from [`Walker::include`] instead.
    ///
    /// ```
    /// use ferralk::Walker;
    ///
    /// let walker = Walker::new("crates")
    ///     .add_root("tools")?
    ///     .include("**/*.rs")?;
    /// # Ok::<(), ferralk::ferralk_glob::PatternError>(())
    /// ```
    pub fn add_root(mut self, root: impl Into<PathBuf>) -> Result<Self, PatternError> {
        self.try_add_root(root)?;
        Ok(self)
    }

    /// Adds another root without consuming the builder.
    ///
    /// This is the borrowed counterpart to [`Walker::add_root`]. It is useful
    /// when applying a caller-supplied root list: if an already-added absolute
    /// pattern cannot be rewritten for one root, this method returns its
    /// [`PatternError`] and leaves the configured walker unchanged, so later
    /// roots can still be considered. A valid root has the same semantics as
    /// [`Walker::add_root`].
    ///
    /// ```no_run
    /// use ferralk::Walker;
    ///
    /// let mut walker = Walker::new("workspace");
    /// for root in ["generated", "vendor"] {
    ///     if let Err(error) = walker.try_add_root(root) {
    ///         eprintln!("skipping {root:?}: {error}");
    ///     }
    /// }
    ///
    /// let result = walker.collect()?;
    /// # let _ = result;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn try_add_root(&mut self, root: impl Into<PathBuf>) -> Result<&mut Self, PatternError> {
        let mut plan = RootPlan::new(root.into());
        let options = traversal_pattern_options(self.match_hidden);
        let root_bytes = glob_path_bytes(&plan.path);
        for source in &self.include_sources {
            plan.includes
                .push(compile_for_root(source, root_bytes.as_ref(), options)?);
        }
        for source in &self.exclude_sources {
            plan.excludes
                .push(compile_for_root(source, root_bytes.as_ref(), options)?);
        }
        drop(root_bytes);
        self.roots.push(plan);
        Ok(self)
    }

    /// Adds several roots, in order.
    ///
    /// # Errors
    ///
    /// The failures [`Walker::add_root`] reports, for the first root that
    /// produces one.
    pub fn add_roots<P: Into<PathBuf>>(
        mut self,
        roots: impl IntoIterator<Item = P>,
    ) -> Result<Self, PatternError> {
        for root in roots {
            self = self.add_root(root)?;
        }
        Ok(self)
    }

    /// The roots this walk starts from, in the order they were added.
    #[must_use]
    pub fn roots(&self) -> impl ExactSizeIterator<Item = &Path> {
        self.roots.iter().map(|root| root.path.as_path())
    }

    /// Compiles one pattern once per root, or reports the first rejection.
    fn compile_for_every_root(
        &self,
        pattern: &[u8],
    ) -> Result<Vec<TraversalPattern>, PatternError> {
        let options = traversal_pattern_options(self.match_hidden);
        self.roots
            .iter()
            .map(|root| compile_for_root(pattern, glob_path_bytes(&root.path).as_ref(), options))
            .collect()
    }

    /// Lets an ordinary wildcard cover a leading period, so `**/*.ts` also
    /// reaches `.react-router/routes.ts`. Off by default, per ADR-0011.
    ///
    /// The switch is matcher semantics and applies to include and exclude
    /// patterns alike: what a wildcard may reach, a wildcard may also prune.
    /// It is not [`WalkOptions::skip_hidden`], which drops hidden entries from
    /// the traversal before any pattern sees them; a literal `.cache/**`
    /// selects a hidden path with either setting, because a literal period is
    /// not a wildcard.
    ///
    /// Builder order does not matter: patterns added before this call are
    /// recompiled under the new setting.
    #[must_use]
    pub fn match_hidden(mut self, enabled: bool) -> Self {
        if self.match_hidden == enabled {
            return self;
        }
        self.match_hidden = enabled;
        let options = traversal_pattern_options(enabled);
        for root in &mut self.roots {
            for pattern in root.includes.iter_mut().chain(root.excludes.iter_mut()) {
                pattern.recompile(options);
            }
        }
        self
    }

    /// Chooses how far an ordinary wildcard reaches.
    ///
    /// The default, [`WildcardMode::ComponentScoped`], keeps `*`, `?` and
    /// character classes inside one path component, so `*.ts` selects a file in
    /// the walk root and `src/*.ts` one directly inside `src`.
    ///
    /// [`WildcardMode::SeparatorCrossing`] lets them span separators, which is
    /// how `globset` and `fast-glob` read a pattern that was not configured
    /// otherwise. Under it `*.ts` also selects `src/deep/main.ts`. Patterns
    /// carried over from those crates keep their meaning here instead of
    /// quietly selecting less; see the migration note in the compatibility
    /// guide.
    ///
    /// The mode applies to includes and excludes alike, and builder order does
    /// not matter.
    ///
    /// ```
    /// use ferralk::{WildcardMode, Walker};
    ///
    /// let walker = Walker::new(".")
    ///     .wildcard_mode(WildcardMode::SeparatorCrossing)
    ///     .include("*.ts")?;
    /// # Ok::<(), ferralk::ferralk_glob::PatternError>(())
    /// ```
    #[must_use]
    pub const fn wildcard_mode(mut self, mode: WildcardMode) -> Self {
        self.wildcard_mode = mode;
        self
    }

    /// Replaces all traversal options.
    #[must_use]
    pub const fn options(mut self, options: WalkOptions) -> Self {
        self.options = options;
        self
    }

    /// Chooses the recoverable error policy.
    #[must_use]
    pub const fn error_policy(mut self, error_policy: ErrorPolicy) -> Self {
        self.error_policy = error_policy;
        self
    }

    /// Associates an externally owned cooperative cancellation handle.
    #[must_use]
    pub fn cancellation(mut self, cancellation: CancellationToken) -> Self {
        self.cancellation = Some(cancellation);
        self
    }

    /// Applies `.gitignore` rules plus zlob-compatible `.ignore` supplements.
    #[must_use]
    pub const fn respect_git_ignore(mut self, enabled: bool) -> Self {
        self.respect_git_ignore = enabled;
        self
    }

    /// Overrides the repository-local `core.ignoreCase` value used by
    /// [`Walker::respect_git_ignore`].
    ///
    /// Git sets this value when `git init` or `git clone` probes a
    /// case-insensitive filesystem. When enabled, Ferralk mirrors Git's
    /// ASCII-only ignore-rule case folding. The override takes precedence over
    /// the repository's local config and is useful when Git's effective value
    /// comes from a global config, include, or environment that Ferralk does
    /// not read.
    #[must_use]
    pub const fn git_ignore_case(mut self, enabled: bool) -> Self {
        self.git_ignore_case = Some(enabled);
        self
    }

    /// Clears an explicit [`Walker::git_ignore_case`] override.
    ///
    /// Subsequent Git-ignore walks resume detection from each repository's
    /// local config. This is useful for a reusable builder whose caller first
    /// supplied Git's effective value and then wants its normal local-config
    /// behaviour back.
    #[must_use]
    pub const fn clear_git_ignore_case(mut self) -> Self {
        self.git_ignore_case = None;
        self
    }

    /// Overrides the repository-local `core.precomposeUnicode` value used by
    /// [`Walker::respect_git_ignore`].
    ///
    /// Git implements this filesystem adaptation only on macOS. There, an
    /// enabled value converts valid UTF-8 candidate path components to NFC
    /// before ignore matching; invalid bytes remain byte-exact. On other
    /// platforms this method is retained for portable builder code but has no
    /// effect, matching Git's platform applicability. The override takes
    /// precedence over repository-local config.
    #[must_use]
    pub const fn git_precompose_unicode(mut self, enabled: bool) -> Self {
        self.git_precompose_unicode = Some(enabled);
        self
    }

    /// Clears an explicit [`Walker::git_precompose_unicode`] override.
    ///
    /// Subsequent Git-ignore walks resume detection from each repository's
    /// local config. On non-macOS platforms this retains Git's no-op
    /// applicability for this setting.
    #[must_use]
    pub const fn clear_git_precompose_unicode(mut self) -> Self {
        self.git_precompose_unicode = None;
        self
    }

    /// Limits `collect()` to this many workers. Values are clamped to
    /// `1..=256`; `stream()` remains single-threaded to preserve incremental
    /// delivery. The upper bound caps the queues, scratch buffers, and
    /// potential operating-system threads one walk can reserve.
    #[must_use]
    pub const fn threads(mut self, threads: usize) -> Self {
        self.threads = if threads == 0 {
            1
        } else if threads > MAX_WORKERS {
            MAX_WORKERS
        } else {
            threads
        };
        self
    }

    /// Runs the selected filesystem backend to completion, using the configured workers.
    ///
    /// A panic inside a worker stops the sibling workers and is resumed on the
    /// calling thread after they have been joined.
    pub fn collect(self) -> Result<WalkResult, WalkError> {
        self.collect_with(&SystemBackend)
    }

    /// Runs the walk and asks `visitor` about every entry, on the worker that
    /// produced it.
    ///
    /// This is [`Walker::collect`] with a filter that runs in parallel. A
    /// caller whose predicate is not expressible as a ferralk glob — another
    /// glob engine, a content check, a lookup — otherwise pays a
    /// single-threaded pass over every entry after the walk, which is enough to
    /// cancel out the threads the walk just used.
    ///
    /// The visitor is shared rather than cloned per worker, so it takes `&self`
    /// and must be `Sync`. Per-worker state belongs in a thread-local, which is
    /// how ferralk's own matcher keeps its scratch buffers.
    ///
    /// Cancellation, the error policy, panic propagation and sorting behave
    /// exactly as they do for [`Walker::collect`]; only which entries survive
    /// differs. A [`Verdict::Stop`] ends the walk and is reported by
    /// [`WalkResult::was_cancelled`].
    ///
    /// ```no_run
    /// use ferralk::{Verdict, Walker};
    ///
    /// let result = Walker::new(".")
    ///     .threads(4)
    ///     .visit(|entry| {
    ///         if entry.path().extension().is_some_and(|kind| kind == "rs") {
    ///             Verdict::Keep
    ///         } else {
    ///             Verdict::Skip
    ///         }
    ///     })?;
    /// # Ok::<(), ferralk::WalkError>(())
    /// ```
    ///
    /// # Errors
    ///
    /// The same failures [`Walker::collect`] reports.
    pub fn visit<V>(self, visitor: V) -> Result<WalkResult, WalkError>
    where
        V: Fn(&WalkEntry) -> Verdict + Sync,
    {
        self.walk(&SystemBackend, &visitor)
    }

    /// The collect implementation both frontends share, with the filesystem
    /// behind a backend so tests can drive either of them with a mock.
    fn collect_with<B: DirectoryBackend + Sync>(
        self,
        backend: &B,
    ) -> Result<WalkResult, WalkError> {
        self.walk(backend, &keep_every_entry)
    }

    /// The one traversal `collect` and `visit` share, so a visitor cannot
    /// observe a different tree than a plain collect would.
    fn walk<B: DirectoryBackend + Sync>(
        self,
        backend: &B,
        visitor: EntryVisitor<'_>,
    ) -> Result<WalkResult, WalkError> {
        if self.threads > 1 {
            return parallel::collect(self, backend, visitor);
        }
        let mut state = WalkState::new(&self, visitor);
        // Use the same injector-to-worker transfer as the parallel backend. The
        // serial baseline owns one local queue and deliberately drains it
        // before returning.
        let scheduler = scheduler::Scheduler::new();
        for task in self.root_tasks(backend) {
            scheduler.push(task);
        }
        let worker = scheduler.worker();
        while let Some(task) = scheduler.steal_into(&worker).or_else(|| worker.pop()) {
            state.walk_directory(backend, task)?;
        }
        if self.options.sort {
            state
                .entries
                .sort_by(|left, right| left.path.cmp(&right.path));
        }
        Ok(WalkResult {
            entries: state.entries,
            errors: state.errors,
            cancelled: state.cancelled,
        })
    }

    /// Starts an incremental unsorted traversal. Unlike collect, recoverable
    /// errors are yielded as individual iterator items under Collect; sorting
    /// is intentionally a collect-only global operation.
    #[must_use]
    pub fn stream(self) -> WalkStream {
        // Reversed, because the stream pops from the back and the roots are
        // walked in the order the caller added them.
        let mut pending_directories = self.root_tasks(&SystemBackend);
        pending_directories.reverse();
        WalkStream {
            pending_directories,
            walker: self,
            listing: Listing::default(),
            next_entry: 0,
            path: PathBuf::new(),
            directory: PathBuf::new(),
            cycle_guard: Arc::new(CycleGuard::default()),
            ignores: IgnoreScope::default(),
            depth: 0,
            root: 0,
            pending_errors: Vec::new(),
            cancelled: false,
            stopped: false,
        }
    }

    fn may_descend_into(&self, root: usize, relative: &[u8]) -> bool {
        let includes = &self.roots[root].includes;
        includes.is_empty()
            || includes
                .iter()
                .any(|pattern| pattern.could_match_descendant(relative))
    }

    /// Whether the walk may traverse into a directory found at `depth`. The
    /// caller counted the components once and passes the result in.
    fn may_descend_at(&self, root: usize, depth: usize, bytes: &[u8]) -> bool {
        self.options
            .max_depth
            .is_none_or(|max_depth| depth < max_depth)
            && self.may_descend_into(root, bytes)
    }

    fn may_include_file(&self, root: usize, relative: &[u8]) -> bool {
        let includes = &self.roots[root].includes;
        includes.is_empty()
            || includes
                .iter()
                .any(|pattern| pattern.matches_extension(relative))
    }

    /// The tasks a walk starts from: one per root, in order.
    fn root_tasks<B: DirectoryBackend + ?Sized>(&self, backend: &B) -> Vec<DirectoryTask> {
        self.roots
            .iter()
            .enumerate()
            .map(|(index, plan)| {
                let (ignores, ignore_errors) = IgnoreScope::for_root(self, backend, &plan.path);
                DirectoryTask {
                    path: plan.path.clone(),
                    open: DirectoryOpen::default(),
                    depth: 0,
                    root: index,
                    cycle_guard: Arc::new(CycleGuard::default()),
                    ignores,
                    ignore_errors,
                }
            })
            .collect()
    }
}

fn has_hidden_component(path: &[u8]) -> bool {
    path.split(is_path_separator)
        .any(|component| component.first() == Some(&b'.'))
}

/// Gives glob matchers a root-relative path with `/` separators on every
/// platform. Native `Path` values retain their platform representation; only
/// the byte-oriented pattern language is normalized.
pub(crate) fn glob_path_bytes(path: &Path) -> Cow<'_, [u8]> {
    glob_bytes(path.as_os_str().as_encoded_bytes())
}

/// The same normalization for a path the caller already has as bytes.
pub(crate) fn glob_bytes(bytes: &[u8]) -> Cow<'_, [u8]> {
    #[cfg(windows)]
    {
        Cow::Owned(
            bytes
                .iter()
                .map(|&byte| if byte == b'\\' { b'/' } else { byte })
                .collect(),
        )
    }
    #[cfg(not(windows))]
    {
        Cow::Borrowed(bytes)
    }
}

/// Compiles one include or exclude for one root, rewriting it if it is
/// absolute.
///
/// Free rather than a method, because a root is compiled against before it
/// belongs to the walker, and because it is the unit a multi-root walk repeats.
fn compile_for_root(
    pattern: &[u8],
    root: &[u8],
    options: PatternOptions,
) -> Result<TraversalPattern, PatternError> {
    match walker_pattern_for_root(pattern, root, absolute::Syntax::NATIVE, options)? {
        Some(usable) => TraversalPattern::compile(&usable, options),
        // Compiled even though it can never match, so that a pattern the caller
        // wrote badly is still reported, and kept rather than dropped, because
        // dropping an include would widen the walk to everything instead of
        // narrowing it to nothing.
        None => {
            let mut compiled = TraversalPattern::compile(pattern, options)?;
            compiled.never_matches = true;
            Ok(compiled)
        }
    }
}

/// The bytes the walker will compile for `root`, or the reason it will not.
///
/// `None` is the verdict that the pattern names paths outside this root and can
/// select nothing here. The path-shaped check runs after the rewrite and only
/// on the outcomes that still have to match something: a pattern already known
/// to select nothing needs no second reason, and refusing it would turn the
/// verdict a multi-root walk depends on into an error.
fn walker_pattern_for_root(
    pattern: &[u8],
    root: &[u8],
    syntax: absolute::Syntax,
    options: PatternOptions,
) -> Result<Option<Vec<u8>>, PatternError> {
    let Some(rewritten) = rewrite_pattern_for_root(pattern, root, syntax)? else {
        return Ok(None);
    };
    let parsed = Pattern::compile(pattern_without_directory_marker(&rewritten), options)?;
    reject_unwalkable_relative_pattern(
        parsed.walker_path_viability(),
        parsed.walker_path_problem_offset(),
    )?;
    Ok(Some(rewritten))
}

/// Applies only the root-to-pattern relation shared by the walk and corpus
/// harness. Walker construction adds the compiled root-relative candidate
/// validation afterwards; the corpus records absolute rewrite semantics even
/// for synthetic platform spellings that do not describe this host's walker.
fn rewrite_pattern_for_root(
    pattern: &[u8],
    root: &[u8],
    syntax: absolute::Syntax,
) -> Result<Option<Vec<u8>>, PatternError> {
    match absolute::rewrite_in(pattern, root, syntax)? {
        absolute::Rewrite::Relative => {
            absolute::reject_path_shaped(pattern, syntax)?;
            Ok(Some(pattern.to_vec()))
        }
        absolute::Rewrite::Rooted(rooted) => {
            absolute::reject_path_shaped(&rooted, syntax)?;
            Ok(Some(rooted))
        }
        absolute::Rewrite::Outside => Ok(None),
    }
}

/// The one trailing slash [`TraversalPattern`] treats as a directory-only
/// marker is not part of the root-relative candidate spelling. Validation uses
/// the same marker-free bytes so `aaa/` remains valid while `src//bar` and
/// other leading or interior empty components stay unselectable.
fn pattern_without_directory_marker(pattern: &[u8]) -> &[u8] {
    if pattern.len() > 1 {
        pattern.strip_suffix(b"/").unwrap_or(pattern)
    } else {
        pattern
    }
}

/// Rejects root-relative path spellings that name no walk candidate.
///
/// A leading `./` remains the conventional harmless spelling for a pattern
/// below the root, but `.` and `./` name the root itself, which a walk never
/// emits. Any other real `.` component (`src/./x` or `src/.`) likewise names
/// a spelling no root-relative candidate uses. Brace alternatives are expanded
/// and therefore reject forms such as `{.,..}`, while an extglob-only
/// component such as `@(.)` remains deliberately opaque matcher text and
/// selects nothing. The glob compiler summarizes its actual expanded
/// alternatives and extglob branches, so this policy never reparses matcher
/// syntax.
fn reject_unwalkable_relative_pattern(
    viability: WalkerPathViability,
    offset: Option<usize>,
) -> Result<(), PatternError> {
    let message = match viability {
        WalkerPathViability::Viable => return Ok(()),
        WalkerPathViability::ParentComponent => {
            "`..` in a walker-relative pattern is not resolved, because resolving it lexically would be wrong across a symlink"
        }
        WalkerPathViability::Root => {
            "a walker-relative pattern that names the walk root itself selects nothing; add `/**` to select what is inside it"
        }
        WalkerPathViability::TrailingDot => {
            "a walker-relative pattern ending in `/.` selects that directory itself; add `/**` to select what is inside it"
        }
        WalkerPathViability::DotComponent => {
            "a walker-relative pattern with a `.` component is not normalized; remove `/.` to name the entry below that directory"
        }
    };
    // Brace expansion can create several equally valid source locations. The
    // compiler carries an offset whenever it is determinate and uses this
    // established fallback only for genuinely ambiguous expanded branches.
    Err(PatternError::new(offset.unwrap_or(0), message))
}

/// The pattern dialect every walker pattern is compiled in. Only
/// `match_hidden` is caller-selectable; the other three are what a filesystem
/// glob means here and are not negotiable per walk.
fn traversal_pattern_options(match_hidden: bool) -> PatternOptions {
    PatternOptions::default()
        .braces(true)
        .recursive_double_star(true)
        .extglob(true)
        .match_hidden(match_hidden)
}

#[derive(Debug, Clone)]
struct TraversalPattern {
    /// The pattern as the caller wrote it, so a later
    /// [`Walker::match_hidden`] can recompile it instead of forcing the caller
    /// to order the builder calls.
    source: Vec<u8>,
    matcher: Pattern,
    directories_only: bool,
    subtree_root: Option<Pattern>,
    /// Literal root of every brace alternative, or `None` when one of them has
    /// none. A prefilter that does not hold for every alternative would prune
    /// something the pattern can still match.
    literal_roots: Option<Vec<Vec<u8>>>,
    /// Literal final extension of every brace alternative, on the same terms.
    extensions: Option<Vec<Vec<u8>>>,
    /// Set for an absolute pattern that named paths outside this walk root.
    /// Such a pattern selects nothing and prunes nothing, and saying so once
    /// here keeps the decision out of every caller of the four predicates.
    never_matches: bool,
}

impl TraversalPattern {
    fn compile(source: &[u8], options: PatternOptions) -> Result<Self, PatternError> {
        // Walker candidates are always root-relative, so retain zlob glob's
        // conventional leading `./` spelling without making it part of the
        // candidate path representation.
        let pattern = source.strip_prefix(b"./").unwrap_or(source);
        let directories_only = pattern.len() > 1 && pattern.ends_with(b"/");
        let pattern = if directories_only {
            &pattern[..pattern.len() - 1]
        } else {
            pattern
        };
        let subtree_root = pattern
            .strip_suffix(b"/**")
            .map(|root| Pattern::compile(root, options))
            .transpose()?;
        // The matcher expands braces before it compiles; the prefilters are
        // derived from the same expansion, so `**/*.{ts,tsx}` keeps the
        // extension filter and `{src,lib}/**` keeps its roots. A pattern
        // without braces expands to itself, which is the previous behaviour.
        let alternatives = ferralk_glob::expand_braces(pattern, options)?;
        Ok(Self {
            source: source.to_vec(),
            matcher: Pattern::compile(pattern, options)?,
            directories_only,
            subtree_root,
            // The prefilters are literal prefixes and literal extensions, so
            // they are the same under either `match_hidden`: a hidden
            // component below a visible literal root stays reachable, and a
            // hidden literal root stays its own root.
            literal_roots: prefilter_of_every_alternative(&alternatives, literal_pattern_root),
            extensions: prefilter_of_every_alternative(&alternatives, literal_extension),
            never_matches: false,
        })
    }

    /// Recompiles the pattern under changed matcher options.
    ///
    /// `match_hidden` is a matching-time policy - it decides whether a wildcard
    /// may cover a leading period - and never a question of syntax, so a source
    /// that compiled once compiles again.
    fn recompile(&mut self, options: PatternOptions) {
        let source = std::mem::take(&mut self.source);
        // Whether the pattern can reach this root is a question about the root,
        // which `match_hidden` does not change.
        let never_matches = self.never_matches;
        *self = Self::compile(&source, options)
            .expect("a compiled pattern stays valid when only match_hidden changes");
        self.never_matches = never_matches;
    }

    /// Whether the pattern selects this candidate under `mode`.
    ///
    /// The two readings differ only in how far an ordinary wildcard reaches, so
    /// they are the same compiled pattern asked a different question rather
    /// than two compilations.
    fn matches(&self, path: &[u8], is_dir: bool, mode: WildcardMode) -> bool {
        if self.never_matches || (self.directories_only && !is_dir) {
            return false;
        }
        match mode {
            WildcardMode::ComponentScoped => self.matcher.is_match_glob_path(path),
            WildcardMode::SeparatorCrossing => self.matcher.is_match(path),
        }
    }

    /// Whether the exclude covers everything below `path`, so the walk may skip
    /// opening it.
    ///
    /// The subtree root is asked under the same mode as the pattern itself.
    /// Reading it as separator-crossing while the walk scopes wildcards to a
    /// component prunes subtrees the exclude does not cover: `*.tmp/**` would
    /// close `a/b.tmp` even though a component-scoped `*.tmp` cannot match the
    /// component `a`.
    fn covers_subtree(&self, path: &[u8], mode: WildcardMode) -> bool {
        if self.never_matches {
            return false;
        }
        self.subtree_root.as_ref().is_some_and(|root| match mode {
            WildcardMode::ComponentScoped => root.is_match_glob_path(path),
            WildcardMode::SeparatorCrossing => root.is_match(path),
        })
    }

    fn could_match_descendant(&self, path: &[u8]) -> bool {
        if self.never_matches {
            return false;
        }
        let Some(roots) = &self.literal_roots else {
            return true;
        };
        roots
            .iter()
            .any(|root| shares_a_line_of_descent(root, path))
    }

    fn matches_extension(&self, path: &[u8]) -> bool {
        if self.never_matches {
            return false;
        }
        let Some(extensions) = &self.extensions else {
            return true;
        };
        final_extension(path)
            .is_some_and(|candidate| extensions.iter().any(|extension| extension == candidate))
    }
}

/// Whether `path` is the literal root, or one of the two contains the other:
/// only then can something under `path` still match.
fn shares_a_line_of_descent(root: &[u8], path: &[u8]) -> bool {
    root == path
        || root
            .strip_prefix(path)
            .is_some_and(|suffix| suffix.starts_with(b"/"))
        || path
            .strip_prefix(root)
            .is_some_and(|suffix| suffix.starts_with(b"/"))
}

/// Collects one prefilter value per brace alternative, or `None` as soon as an
/// alternative has none. Pruning on a value that only some alternatives share
/// would drop paths the pattern still matches, so the filter is either complete
/// or off.
fn prefilter_of_every_alternative(
    alternatives: &[Vec<u8>],
    of_alternative: impl Fn(&[u8]) -> Option<Vec<u8>>,
) -> Option<Vec<Vec<u8>>> {
    if alternatives.is_empty() {
        return None;
    }
    let mut values = alternatives
        .iter()
        .map(|alternative| of_alternative(alternative))
        .collect::<Option<Vec<_>>>()?;
    values.sort_unstable();
    values.dedup();
    Some(values)
}

/// Offset of the first byte that stops the pattern from being a literal path.
///
/// A brace or an extglob opener only counts once its closer is present, because
/// an unpaired one is an ordinary byte. Shared with the absolute-pattern rewrite
/// so that "how far is this pattern a plain path" has one answer.
pub(crate) fn first_metacharacter(pattern: &[u8]) -> Option<usize> {
    pattern.iter().enumerate().position(|(index, byte)| {
        matches!(byte, b'*' | b'?' | b'[')
            || (*byte == b'\\')
            || (*byte == b'{' && has_closing_brace(pattern, index))
            || (matches!(byte, b'@' | b'+' | b'!')
                && pattern.get(index + 1) == Some(&b'(')
                && has_closing_parenthesis(pattern, index + 1))
    })
}

fn literal_pattern_root(pattern: &[u8]) -> Option<Vec<u8>> {
    let magic = first_metacharacter(pattern);
    let prefix = &pattern[..magic.unwrap_or(pattern.len())];
    let root = if magic.is_some() {
        match prefix.strip_suffix(b"/") {
            // The wildcard starts its own component, so everything before it is
            // a proven prefix.
            Some(complete) => complete,
            // Otherwise the wildcard shares a component with the literal before
            // it, and that literal proves nothing about a directory: `src*`
            // selects inside `srcfoo` as readily as inside `src`. Only what
            // precedes the last separator is proven, and a prefix without one
            // proves nothing at all.
            None => {
                let separator = prefix.iter().rposition(|byte| *byte == b'/')?;
                &prefix[..separator]
            }
        }
    } else {
        prefix
    };
    (!root.is_empty()).then(|| root.to_vec())
}

fn literal_extension(pattern: &[u8]) -> Option<Vec<u8>> {
    let extension = final_extension(pattern)?;
    if extension.is_empty()
        || extension.iter().any(|byte| {
            matches!(
                byte,
                b'*' | b'?' | b'[' | b']' | b'{' | b'}' | b'\\' | b'(' | b')' | b'|'
            )
        })
    {
        return None;
    }
    Some(extension.to_vec())
}

fn final_extension(path: &[u8]) -> Option<&[u8]> {
    let name = path.rsplit(is_path_separator).next().unwrap_or(path);
    let dot = name.iter().rposition(|byte| *byte == b'.')?;
    name.get(dot + 1..)
}

fn is_path_separator(byte: &u8) -> bool {
    *byte == b'/' || (cfg!(windows) && *byte == b'\\')
}

fn has_closing_brace(pattern: &[u8], open: usize) -> bool {
    let mut depth = 0_usize;
    let mut index = open;
    while index < pattern.len() {
        if pattern[index] == b'\\' {
            index += 2;
            continue;
        }
        match pattern[index] {
            b'{' => depth += 1,
            b'}' => {
                depth -= 1;
                if depth == 0 {
                    return true;
                }
            }
            _ => {}
        }
        index += 1;
    }
    false
}

fn has_closing_parenthesis(pattern: &[u8], open: usize) -> bool {
    let mut depth = 0_usize;
    let mut index = open;
    while index < pattern.len() {
        if pattern[index] == b'\\' {
            index += 2;
            continue;
        }
        match pattern[index] {
            b'(' => depth += 1,
            b')' => {
                depth -= 1;
                if depth == 0 {
                    return true;
                }
            }
            _ => {}
        }
        index += 1;
    }
    false
}

/// A backend-specific capability retained when a child directory is queued.
#[derive(Debug, Clone, Default)]
pub(crate) struct DirectoryOpen {
    #[cfg(all(feature = "native-macos", target_os = "macos"))]
    relative: Option<macos_native::RelativeDirectoryOpen>,
}

/// The filesystem calls that traversal and classification make, so one mock
/// can drive the serial and the parallel frontend alike.
trait DirectoryBackend {
    /// Reads one directory into `listing`, replacing whatever it held.
    ///
    /// The listing is the caller's, and the caller reuses it for every
    /// directory it reads, so a backend that can name an entry without
    /// allocating leaves the walk allocating nothing per entry at all.
    fn read_directory(
        &self,
        path: &Path,
        follow_symlinks: bool,
        refuse_final_symlink: bool,
        listing: &mut Listing,
    ) -> std::io::Result<()>;

    /// Reads a queued directory through a retained capability when the backend
    /// has one. Path-based backends and tests keep the ordinary method above.
    fn read_scheduled_directory(
        &self,
        path: &Path,
        open: &DirectoryOpen,
        follow_symlinks: bool,
        refuse_final_symlink: bool,
        listing: &mut Listing,
    ) -> std::io::Result<()> {
        let _ = open;
        self.read_directory(path, follow_symlinks, refuse_final_symlink, listing)
    }

    /// Retains what this backend needs to open one child relative to the
    /// directory represented by `listing`.
    fn child_directory_open(&self, listing: &Listing, name: &OsStr) -> DirectoryOpen {
        let _ = (listing, name);
        DirectoryOpen::default()
    }

    /// Follows symlinks; decides whether a link points at a directory.
    fn metadata(&self, path: &Path) -> std::io::Result<fs::Metadata> {
        fs::metadata(path)
    }

    /// Does not follow symlinks; fills in the metadata option of an entry.
    fn symlink_metadata(&self, path: &Path) -> std::io::Result<fs::Metadata> {
        fs::symlink_metadata(path)
    }

    /// Resolves a directory for the follow-symlinks loop guard.
    #[cfg(not(unix))]
    fn canonicalize(&self, path: &Path) -> std::io::Result<PathBuf> {
        fs::canonicalize(path)
    }

    /// Reads an in-tree ignore file. Missing files are the common case and
    /// are reported as an error rather than probed for beforehand.
    ///
    /// On Unix this refuses symlinks atomically. Git likewise refuses an
    /// in-tree `.gitignore` that resolves through a link, so its rules cannot
    /// redirect a walk to an arbitrary file outside the tree.
    fn read_ignore_file(&self, path: &Path) -> std::io::Result<Vec<u8>> {
        read_in_tree_ignore_file(path)
    }

    /// Reads repository metadata such as `.git/info/exclude`.
    ///
    /// Unlike in-tree rule files, Git permits this file to be a link. Keeping
    /// this separate prevents a repository-wide exclude from weakening the
    /// in-tree no-follow rule above.
    fn read_repository_file(&self, path: &Path) -> std::io::Result<Vec<u8>> {
        read_bounded_file(path)
    }

    /// Identifies a directory for the follow-symlinks loop guard.
    ///
    /// The call follows symlinks, which is what the guard needs: every path
    /// that reaches one directory has to produce one key.
    fn cycle_key(&self, path: &Path) -> std::io::Result<CycleKey> {
        #[cfg(unix)]
        {
            use std::os::unix::fs::MetadataExt;

            let metadata = self.metadata(path)?;
            Ok((metadata.dev(), metadata.ino()))
        }
        #[cfg(not(unix))]
        {
            self.canonicalize(path)
        }
    }
}

/// Ignore and repository-metadata files are configuration, not bulk input.
/// Eight MiB leaves orders of magnitude above measured repository files while
/// bounding one attacker-controlled read below the matcher's own 64 MiB brace
/// expansion ceiling.
pub(crate) const MAX_IGNORE_FILE_BYTES: u64 = 8 * 1024 * 1024;

pub(crate) fn read_bounded_file(path: &Path) -> std::io::Result<Vec<u8>> {
    read_bounded(fs::File::open(path)?)
}

fn read_bounded(file: fs::File) -> std::io::Result<Vec<u8>> {
    use std::io::Read;

    let mut contents = Vec::new();
    file.take(MAX_IGNORE_FILE_BYTES + 1)
        .read_to_end(&mut contents)?;
    if contents.len() as u64 > MAX_IGNORE_FILE_BYTES {
        return Err(std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            "configuration file exceeds the 8 MiB safety limit",
        ));
    }
    Ok(contents)
}

/// Reads a rule file found in the tree being walked.
///
/// Unix opens the final path component with `O_NOFOLLOW`, so exchanging a
/// regular rule file for a symlink between a metadata check and an open cannot
/// make a walk read a target outside the tree. Other supported platforms do
/// not expose an equivalent through `std`, so they reject a symlink before the
/// regular `fs::read`; Windows will receive an atomic implementation once its
/// stable standard-library API exposes one.
#[cfg(unix)]
fn read_in_tree_ignore_file(path: &Path) -> std::io::Result<Vec<u8>> {
    use std::{fs::OpenOptions, os::unix::fs::OpenOptionsExt};

    let file = OpenOptions::new()
        .read(true)
        .custom_flags(libc::O_NOFOLLOW)
        .open(path)?;
    read_bounded(file)
}

#[cfg(not(unix))]
fn read_in_tree_ignore_file(path: &Path) -> std::io::Result<Vec<u8>> {
    if fs::symlink_metadata(path)?.file_type().is_symlink() {
        return Err(std::io::Error::from(std::io::ErrorKind::InvalidInput));
    }
    read_bounded_file(path)
}

/// What identifies a directory that the follow-symlinks guard has seen.
///
/// On Unix this is `(st_dev, st_ino)`: sixteen `Copy` bytes from the one
/// `metadata` call the guard already has to make, with no path resolution and
/// no allocation. Two names for one directory, a symlink and the real path
/// among them, share an inode and are therefore recognised as one place --
/// which a resolved path only manages when the resolution agrees.
///
/// Elsewhere the resolved path stays the key. Windows exposes a file index
/// through `std::os::windows::fs::MetadataExt`, but only on the unstable
/// `windows_by_handle` feature, and a walker on stable cannot depend on that.
#[cfg(unix)]
type CycleKey = (u64, u64);
#[cfg(not(unix))]
type CycleKey = PathBuf;

/// Directories one root traversal has already entered while following links.
///
/// A separately supplied root receives its own guard; descendant tasks share
/// their root's guard, which breaks cycles without deduplicating overlaps.
#[derive(Debug, Default)]
pub(crate) struct CycleGuard(Mutex<HashSet<CycleKey>>);

impl CycleGuard {
    fn mark(&self, key: CycleKey) -> bool {
        self.0
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .insert(key)
    }
}

/// Names the call whose failure ends a directory in follow mode, so the
/// reported operation stays the one that actually ran.
#[cfg(unix)]
const CYCLE_KEY_OPERATION: &str = "metadata";
#[cfg(not(unix))]
const CYCLE_KEY_OPERATION: &str = "canonicalize";

const IGNORE_FILE_OPERATION: &str = "read_ignore";

/// One directory's entries, held in buffers the walk reuses.
///
/// An entry is its name, not its path. The walk builds a whole path only for
/// the entries it acts on, by pushing the name onto the scratch path it
/// already holds for the directory — where a `PathBuf` per entry copied the
/// parent path as well and allocated for it, once for every entry the walk
/// was about to throw away.
///
/// The name buffers are cleared rather than dropped between directories, so a
/// listing that has been used once names further entries without allocating.
/// It holds no more than the `Vec<PathBuf>` it replaced: a name is a suffix of
/// the path that used to be stored whole.
#[derive(Debug, Default)]
pub(crate) struct Listing {
    entries: Vec<ListedEntry>,
    #[cfg(all(feature = "native-macos", target_os = "macos"))]
    native_directory: Option<Arc<macos_native::RetainedDirectory>>,
    /// Entries in use. `entries` may be longer: the tail is buffers kept for
    /// the next directory.
    len: usize,
    /// Per-entry failures discovered while a backend was completing an
    /// otherwise usable listing. They are delivered after its siblings, so a
    /// persistent stat failure cannot make those siblings disappear.
    deferred_errors: Vec<DeferredListingError>,
}

#[derive(Debug)]
pub(crate) struct DeferredListingError {
    path: PathBuf,
    source: DeferredIoError,
}

/// An `io::Error` representation that can live in the public stream without
/// changing its auto-trait contract. `std::io::Error` may carry an arbitrary
/// error object, which is not necessarily unwind-safe; a deferred listing
/// error needs only the externally observable kind and message until it is
/// delivered as a fresh `io::Error`.
#[derive(Debug)]
struct DeferredIoError {
    kind: std::io::ErrorKind,
    message: String,
}

impl From<std::io::Error> for DeferredIoError {
    fn from(source: std::io::Error) -> Self {
        Self {
            kind: source.kind(),
            message: source.to_string(),
        }
    }
}

impl DeferredIoError {
    fn into_io_error(self) -> std::io::Error {
        std::io::Error::new(self.kind, self.message)
    }
}

/// One entry of a [`Listing`].
#[derive(Debug, Default, Clone)]
pub(crate) struct ListedEntry {
    name: OsString,
    is_dir: bool,
    is_symlink: bool,
}

impl ListedEntry {
    pub(crate) fn name(&self) -> &OsStr {
        &self.name
    }

    pub(crate) const fn is_dir(&self) -> bool {
        self.is_dir
    }

    pub(crate) const fn is_symlink(&self) -> bool {
        self.is_symlink
    }
}

impl Listing {
    /// Drops the previous directory's entries, keeping their buffers.
    pub(crate) fn clear(&mut self) {
        self.len = 0;
        #[cfg(all(feature = "native-macos", target_os = "macos"))]
        {
            self.native_directory = None;
        }
        self.deferred_errors.clear();
    }

    /// Adds one entry, reusing the buffer left by the directory before.
    pub(crate) fn push(&mut self, name: &OsStr, is_dir: bool, is_symlink: bool) {
        if self.len == self.entries.len() {
            self.entries.push(ListedEntry::default());
        }
        let entry = &mut self.entries[self.len];
        entry.name.clear();
        entry.name.push(name);
        entry.is_dir = is_dir;
        entry.is_symlink = is_symlink;
        self.len += 1;
    }

    pub(crate) fn entries(&self) -> &[ListedEntry] {
        &self.entries[..self.len]
    }

    /// Records a failure for one entry without throwing away the successfully
    /// read siblings. Consumers report these after the listing is consumed.
    pub(crate) fn defer_error(&mut self, path: PathBuf, source: std::io::Error) {
        self.deferred_errors.push(DeferredListingError {
            path,
            source: source.into(),
        });
    }

    pub(crate) fn take_deferred_error(&mut self) -> Option<DeferredListingError> {
        (!self.deferred_errors.is_empty()).then(|| self.deferred_errors.remove(0))
    }

    /// Whether the directory holds an entry of this name, which is how the
    /// ignore chain recognizes its own files without probing for them.
    pub(crate) fn contains(&self, name: &str) -> bool {
        self.entries().iter().any(|entry| entry.name == *name)
    }

    /// Whether a directory contains a possible spelling of a Git ignore file.
    /// The caller still opens the canonical name: on a case-sensitive
    /// filesystem that open fails for `.GITIGNORE`, while on APFS/NTFS it
    /// resolves exactly as Git's `open(".gitignore")` does.
    pub(crate) fn contains_git_ignore_name(&self, name: &str) -> bool {
        self.contains(name)
            || self.entries().iter().any(|entry| {
                entry
                    .name
                    .as_encoded_bytes()
                    .eq_ignore_ascii_case(name.as_bytes())
            })
    }
}

#[cfg_attr(
    any(
        all(feature = "native-macos", target_os = "macos"),
        all(feature = "native-linux", target_os = "linux")
    ),
    allow(dead_code)
)]
struct StdBackend;

impl DirectoryBackend for StdBackend {
    fn read_directory(
        &self,
        path: &Path,
        _follow_symlinks: bool,
        _refuse_final_symlink: bool,
        listing: &mut Listing,
    ) -> std::io::Result<()> {
        read_portable_directory(path, path, listing)
    }
}

/// Reads a directory through the portable `std::fs` backend. `directory` is
/// the path opened by the operating system; `reported_path` keeps deferred
/// per-entry errors anchored at the caller's path when a native no-follow
/// descriptor is exposed through `/dev/fd` for a safe fallback.
#[cfg_attr(
    any(
        all(feature = "native-macos", target_os = "macos"),
        all(feature = "native-linux", target_os = "linux")
    ),
    allow(dead_code)
)]
fn read_portable_directory(
    directory: &Path,
    reported_path: &Path,
    listing: &mut Listing,
) -> std::io::Result<()> {
    listing.clear();
    for entry in fs::read_dir(directory)? {
        let entry = match entry {
            Ok(entry) => entry,
            Err(error) => {
                defer_entry_stat_error(listing, reported_path.to_path_buf(), error)?;
                continue;
            }
        };
        // `DirEntry` only exposes its name by value. Retain that one
        // allocation for the listing and do not construct a full path unless
        // the uncommon `file_type` failure needs it for error reporting.
        let name = entry.file_name();
        let file_type = match entry.file_type() {
            Ok(file_type) => file_type,
            Err(error) => {
                defer_entry_stat_error(listing, reported_path.join(&name), error)?;
                continue;
            }
        };
        // The standard library's one `file_name` allocation is the portable
        // backend's floor. The native backends read names out of a buffer they
        // own and reach zero.
        listing.push(&name, file_type.is_dir(), file_type.is_symlink());
    }
    Ok(())
}

/// Keeps the three directory readers on the same `DT_UNKNOWN` contract.
///
/// `NotFound` and `NotADirectory` describe a path that changed after its
/// directory record was read, so that one entry is dropped. `PermissionDenied`
/// is persistent often enough that silently treating it as a race loses data;
/// it is delayed until the usable listing has been delivered. Other failures
/// make the directory read fail normally.
pub(crate) fn defer_entry_stat_error(
    listing: &mut Listing,
    path: PathBuf,
    error: std::io::Error,
) -> std::io::Result<()> {
    match error.kind() {
        std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory => Ok(()),
        std::io::ErrorKind::PermissionDenied => {
            listing.defer_error(path, error);
            Ok(())
        }
        _ => Err(error),
    }
}

/// Selects the feature-gated native backend where it is available and the
/// portable backend everywhere else.
struct SystemBackend;

#[cfg(any(
    all(feature = "native-macos", target_os = "macos"),
    all(feature = "native-linux", target_os = "linux")
))]
#[cfg_attr(
    any(
        all(feature = "native-macos", target_os = "macos"),
        all(feature = "native-linux", target_os = "linux")
    ),
    allow(dead_code)
)]
fn read_native_or_portable(
    listing: &mut Listing,
    native: impl FnOnce(&mut Listing) -> std::io::Result<()>,
    fallback: impl FnOnce(&mut Listing) -> std::io::Result<()>,
) -> std::io::Result<()> {
    match native(listing) {
        Ok(()) => Ok(()),
        Err(error) if error.kind() == std::io::ErrorKind::Unsupported => fallback(listing),
        Err(error) => Err(error),
    }
}

impl DirectoryBackend for SystemBackend {
    fn read_directory(
        &self,
        path: &Path,
        follow_symlinks: bool,
        refuse_final_symlink: bool,
        listing: &mut Listing,
    ) -> std::io::Result<()> {
        #[cfg(all(feature = "native-macos", target_os = "macos"))]
        {
            // macOS performs its capability fallback inside the native module,
            // where it still owns the protected directory descriptor. Keeping
            // ordinary `Unsupported` I/O errors out of the generic adapter is
            // essential: a DT_UNKNOWN stat may report that kind after a batch,
            // and a path fallback would discard the usable siblings.
            let _ = follow_symlinks;
            macos_native::read_directory(path, None, refuse_final_symlink, listing)
                .map_err(macos_native::NativeDirectoryReadError::into_io_error)
        }
        #[cfg(all(
            feature = "native-linux",
            target_os = "linux",
            not(all(feature = "native-macos", target_os = "macos"))
        ))]
        {
            // Linux performs its capability fallback inside the native module,
            // where it still owns the `O_NOFOLLOW` directory descriptor. A
            // generic path fallback would reopen a scheduled descendant after
            // a replacement race; an ordinary Unsupported after a batch must
            // also remain an ordinary walker error rather than restart it.
            let _ = follow_symlinks;
            linux_native::read_directory(path, refuse_final_symlink, listing)
        }
        #[cfg(not(any(
            all(feature = "native-macos", target_os = "macos"),
            all(feature = "native-linux", target_os = "linux")
        )))]
        StdBackend.read_directory(path, follow_symlinks, refuse_final_symlink, listing)
    }

    fn read_scheduled_directory(
        &self,
        path: &Path,
        _open: &DirectoryOpen,
        follow_symlinks: bool,
        refuse_final_symlink: bool,
        listing: &mut Listing,
    ) -> std::io::Result<()> {
        #[cfg(all(feature = "native-macos", target_os = "macos"))]
        {
            let _ = follow_symlinks;
            macos_native::read_directory(
                path,
                _open.relative.as_ref(),
                refuse_final_symlink,
                listing,
            )
            .map_err(macos_native::NativeDirectoryReadError::into_io_error)
        }
        #[cfg(not(all(feature = "native-macos", target_os = "macos")))]
        self.read_directory(path, follow_symlinks, refuse_final_symlink, listing)
    }

    fn child_directory_open(&self, listing: &Listing, name: &OsStr) -> DirectoryOpen {
        #[cfg(all(feature = "native-macos", target_os = "macos"))]
        {
            DirectoryOpen {
                relative: listing.native_directory.as_ref().map(|directory| {
                    macos_native::RelativeDirectoryOpen {
                        parent: Arc::clone(directory),
                        name: name.to_os_string(),
                    }
                }),
            }
        }
        #[cfg(not(all(feature = "native-macos", target_os = "macos")))]
        {
            let _ = (listing, name);
            DirectoryOpen::default()
        }
    }
}

/// Incremental portable traversal produced by Walker stream.
#[derive(Debug)]
pub struct WalkStream {
    walker: Walker,
    pending_directories: Vec<DirectoryTask>,
    /// The directory being delivered and how far through it the stream is.
    listing: Listing,
    next_entry: usize,
    /// That directory's path, with the entry being classified pushed onto it.
    path: PathBuf,
    /// The same directory without an entry on it, kept so `path` can be reset
    /// by [`reset_to_directory`] rather than by `PathBuf::pop`.
    directory: PathBuf,
    /// The guard belonging to the directory currently being delivered.
    cycle_guard: Arc<CycleGuard>,
    /// Ignore rules of the directory whose entries are being delivered.
    ignores: IgnoreScope,
    /// Depth of that same directory, so its entries need not recount it.
    depth: usize,
    /// Which root that directory sits under, for the same reason.
    root: usize,
    /// Ignore-file failures discovered while preparing the current directory.
    pending_errors: Vec<PendingWalkError>,
    cancelled: bool,
    stopped: bool,
}

/// Unwind-safe error data kept between iterator calls. `std::io::Error` may own
/// arbitrary error objects that are not unwind-safe, while `WalkStream` has
/// historically guaranteed the standard unwind auto traits.
#[derive(Debug)]
struct PendingWalkError {
    operation: &'static str,
    path: PathBuf,
    kind: std::io::ErrorKind,
    message: String,
}

impl PendingWalkError {
    fn from_ignore(error: IgnoreReadError) -> Self {
        let (path, source) = error.into_parts();
        Self {
            operation: IGNORE_FILE_OPERATION,
            path,
            kind: source.kind(),
            message: source.to_string(),
        }
    }

    fn into_walk_error(self) -> WalkError {
        WalkError::new(
            self.operation,
            self.path,
            std::io::Error::new(self.kind, self.message),
        )
    }
}

impl WalkStream {
    /// Whether a cancellation request ended this stream.
    #[must_use]
    pub const fn was_cancelled(&self) -> bool {
        self.cancelled
    }

    fn check_cancellation(&mut self) -> bool {
        self.cancelled |= self
            .walker
            .cancellation
            .as_ref()
            .is_some_and(CancellationToken::is_cancelled);
        self.cancelled
    }

    fn error(
        &mut self,
        operation: &'static str,
        path: PathBuf,
        source: std::io::Error,
        is_root: bool,
    ) -> Option<Result<WalkEntry, WalkError>> {
        let error = WalkError::new(operation, path, source);
        match self.walker.error_policy {
            ErrorPolicy::Abort => {
                self.stopped = true;
                Some(Err(error))
            }
            ErrorPolicy::Skip if !is_root => None,
            ErrorPolicy::Skip | ErrorPolicy::Collect => Some(Err(error)),
        }
    }

    fn queue_ignore_errors(
        &mut self,
        errors: Vec<IgnoreReadError>,
    ) -> Option<Result<WalkEntry, WalkError>> {
        match self.walker.error_policy {
            ErrorPolicy::Skip => None,
            ErrorPolicy::Abort => errors.into_iter().next().map(|error| {
                self.stopped = true;
                let (path, source) = error.into_parts();
                Err(WalkError::new(IGNORE_FILE_OPERATION, path, source))
            }),
            ErrorPolicy::Collect => {
                self.pending_errors
                    .extend(errors.into_iter().rev().map(PendingWalkError::from_ignore));
                self.pending_errors
                    .pop()
                    .map(PendingWalkError::into_walk_error)
                    .map(Err)
            }
        }
    }

    fn prepare_directory(&mut self, task: DirectoryTask) -> Option<Result<WalkEntry, WalkError>> {
        let DirectoryTask {
            path,
            open,
            depth,
            root,
            cycle_guard,
            ignores,
            mut ignore_errors,
        } = task;
        if self.walker.options.follow_symlinks {
            match SystemBackend.cycle_key(&path) {
                Ok(key) => {
                    if !cycle_guard.mark(key) {
                        return None;
                    }
                }
                Err(source) => return self.error(CYCLE_KEY_OPERATION, path, source, depth == 0),
            }
        }
        match SystemBackend.read_scheduled_directory(
            &path,
            &open,
            self.walker.options.follow_symlinks,
            !self.walker.options.follow_symlinks && depth > 0,
            &mut self.listing,
        ) {
            Ok(()) => {
                // The directory's own ignore files join the chain here, once,
                // recognized in the listing that was just read.
                let (ignores, mut entered_errors) =
                    ignores.enter(&self.walker, &SystemBackend, &path, &self.listing);
                self.ignores = ignores;
                ignore_errors.append(&mut entered_errors);
                self.depth = depth;
                self.root = root;
                self.cycle_guard = cycle_guard;
                self.next_entry = 0;
                self.directory = path;
                reset_to_directory(&mut self.path, &self.directory);
                self.queue_ignore_errors(ignore_errors)
            }
            Err(source) => {
                // A backend can fail after appending entries. They belong to
                // the failed directory and must never be classified against
                // the directory the stream delivered previously.
                self.listing.clear();
                self.next_entry = 0;
                self.error("read_dir", path, source, depth == 0)
            }
        }
    }

    /// Classifies the entry at `index` of the directory being delivered.
    ///
    /// The entry's path is assembled onto the scratch buffer and taken back off
    /// it again, so the stream holds one path buffer rather than one per entry.
    fn process_entry(&mut self, index: usize) -> Option<Result<WalkEntry, WalkError>> {
        self.path.push(self.listing.entries()[index].name());
        let action = classify_entry(
            &self.walker,
            &SystemBackend,
            &self.path,
            &self.listing.entries()[index],
            &self.ignores,
            self.depth,
            TraversalContext {
                root: self.root,
                cycle_guard: &self.cycle_guard,
                listing: &self.listing,
            },
        );
        // Only an emitted entry needs a path of its own, and the stream hands
        // every one of them to the caller.
        let emitted = match action {
            EntryAction::Skip => None,
            EntryAction::Descend(task) => {
                self.pending_directories.push(task);
                None
            }
            EntryAction::Emit(entry) => Some(Ok(entry.with_path(self.path.clone()))),
            EntryAction::DescendAndEmit(entry, task) => {
                let entry = entry.with_path(self.path.clone());
                self.pending_directories.push(task);
                Some(Ok(entry))
            }
            EntryAction::Failed { failure, descend } => {
                if let Some(task) = descend {
                    self.pending_directories.push(task);
                }
                self.error(failure.operation, failure.path, failure.source, false)
            }
        };
        reset_to_directory(&mut self.path, &self.directory);
        emitted
    }
}

impl Iterator for WalkStream {
    type Item = Result<WalkEntry, WalkError>;

    fn next(&mut self) -> Option<Self::Item> {
        while !self.stopped {
            if self.check_cancellation() {
                self.stopped = true;
                return None;
            }
            if let Some(error) = self.pending_errors.pop() {
                return Some(Err(error.into_walk_error()));
            }
            if self.next_entry < self.listing.entries().len() {
                let index = self.next_entry;
                self.next_entry += 1;
                if let Some(result) = self.process_entry(index) {
                    return Some(result);
                }
                continue;
            }
            if let Some(error) = self.listing.take_deferred_error() {
                if let Some(result) =
                    self.error("read_dir", error.path, error.source.into_io_error(), false)
                {
                    return Some(result);
                }
                continue;
            }
            let task = self.pending_directories.pop()?;
            if let Some(result) = self.prepare_directory(task) {
                return Some(result);
            }
        }
        None
    }
}

struct WalkState<'walker> {
    walker: &'walker Walker,
    visitor: EntryVisitor<'walker>,
    entries: Vec<WalkEntry>,
    errors: Vec<WalkError>,
    /// Buffers of directories this frontend has finished with. It descends by
    /// recursion, so several directories are open at once and each needs its
    /// own; a pool hands the deepest frame the buffers the last one returned.
    scratch: Vec<DirectoryScratch>,
    /// The path buffer the last dropped entry left behind. See [`own_path`].
    spare: PathBuf,
    cancelled: bool,
}

/// What reading one directory needs: its listing, and the path buffer its
/// entries are assembled onto.
#[derive(Default)]
struct DirectoryScratch {
    listing: Listing,
    path: PathBuf,
}

/// Entries between two cancellation checks inside one directory.
///
/// Both frontends check when they take a directory and then once every this
/// many entries. Checking per entry bought a granularity nothing observes: a
/// walk is already free to finish the directory it has started, and the check
/// reads shared state — an atomic the parallel frontend's workers all load, and
/// a token behind an `Arc` in the serial one.
///
/// A power of two, so the test is a mask, and small enough that a cancelled
/// walk keeps classifying for the width of a stride rather than the width of a
/// listing.
const CANCELLATION_STRIDE: usize = 64;

/// Puts `path` back to the directory its entries are assembled onto.
///
/// `PathBuf::pop` finds the parent by walking the path's components backwards,
/// which is a question the caller already knows the answer to: it pushed one
/// name onto a directory whose length it recorded. `OsString::truncate` would
/// say exactly that, but it is unstable (rust#133262) and this crate denies
/// unsafe, so the directory is re-copied instead — a `memcpy` of a short path,
/// with no component parsing and no separator scan.
fn reset_to_directory(path: &mut PathBuf, directory: &Path) {
    path.clear();
    path.as_mut_os_string().push(directory.as_os_str());
}

/// Copies `path` into a buffer of its own, reusing `spare` when an entry the
/// walk dropped left one behind.
///
/// This is what makes a `Verdict::Skip` free: the visitor needs a `WalkEntry`
/// and a `WalkEntry` owns its path, so one has to be built — but the buffer it
/// is built in can be the one the previous skipped entry gave back, and then
/// no allocator call happens at all.
fn own_path(spare: &mut PathBuf, path: &Path) -> PathBuf {
    let mut owned = std::mem::take(spare);
    if owned.capacity() == 0 {
        // Nothing came back, so this entry buys its own buffer, sized exactly.
        return path.to_path_buf();
    }
    owned.clear();
    owned.as_mut_os_string().push(path.as_os_str());
    owned
}

impl<'walker> WalkState<'walker> {
    fn new(walker: &'walker Walker, visitor: EntryVisitor<'walker>) -> Self {
        Self {
            walker,
            visitor,
            entries: Vec::new(),
            errors: Vec::new(),
            scratch: Vec::new(),
            spare: PathBuf::new(),
            cancelled: false,
        }
    }

    /// Asks the visitor about one entry and keeps it if it said so.
    ///
    /// A verdict that drops the entry hands its path buffer back, so the next
    /// entry is assembled in it rather than in a fresh allocation.
    fn emit(&mut self, path: &Path, emitted: EmittedEntry) {
        let entry = emitted.with_path(own_path(&mut self.spare, path));
        match (self.visitor)(&entry) {
            Verdict::Keep => self.entries.push(entry),
            Verdict::Skip => self.spare = entry.path,
            Verdict::Stop => {
                self.spare = entry.path;
                self.cancelled = true;
            }
        }
    }

    fn walk_directory(
        &mut self,
        backend: &impl DirectoryBackend,
        mut task: DirectoryTask,
    ) -> Result<(), WalkError> {
        if self.check_cancellation() {
            return Ok(());
        }
        let is_root = task.depth == 0;
        for error in std::mem::take(&mut task.ignore_errors) {
            let (path, source) = error.into_parts();
            self.handle_error(IGNORE_FILE_OPERATION, path, source, false)?;
        }
        if self.walker.options.follow_symlinks
            && !self.mark_directory(backend, &task.cycle_guard, &task.path, is_root)?
        {
            return Ok(());
        }
        let mut scratch = self.scratch.pop().unwrap_or_default();
        let outcome = self.walk_listing(backend, task, &mut scratch);
        scratch.listing.clear();
        self.scratch.push(scratch);
        outcome
    }

    /// The body of [`WalkState::walk_directory`], with the directory's buffers
    /// held apart so they are returned to the pool however it ends.
    fn walk_listing(
        &mut self,
        backend: &impl DirectoryBackend,
        task: DirectoryTask,
        scratch: &mut DirectoryScratch,
    ) -> Result<(), WalkError> {
        let path = task.path.as_path();
        let depth = task.depth;
        let is_root = depth == 0;
        if let Err(source) = backend.read_scheduled_directory(
            path,
            &task.open,
            self.walker.options.follow_symlinks,
            !self.walker.options.follow_symlinks && depth > 0,
            &mut scratch.listing,
        ) {
            return self.handle_error("read_dir", path.to_path_buf(), source, is_root);
        }
        // The directory's own ignore files join the chain here, once,
        // recognized in the listing that was just read.
        let (ignores, ignore_errors) =
            task.ignores
                .enter(self.walker, backend, path, &scratch.listing);
        for error in ignore_errors {
            let (path, source) = error.into_parts();
            self.handle_error(IGNORE_FILE_OPERATION, path, source, false)?;
        }
        scratch.path.clear();
        scratch.path.push(path);
        for index in 0..scratch.listing.entries().len() {
            // A `Verdict::Stop` is this walk's own decision, already on a local
            // field, and is honoured on the very next entry. The caller's token
            // is polled every [`CANCELLATION_STRIDE`] entries instead of every
            // one, which is what costs a load through the shared `Arc`.
            if self.cancelled
                || (index.is_multiple_of(CANCELLATION_STRIDE) && self.check_cancellation())
            {
                return Ok(());
            }
            // The entry's path exists only for as long as it is being decided
            // about; anything that outlives that copies it out.
            scratch.path.push(scratch.listing.entries()[index].name());
            let action = classify_entry(
                self.walker,
                backend,
                &scratch.path,
                &scratch.listing.entries()[index],
                &ignores,
                depth,
                TraversalContext {
                    root: task.root,
                    cycle_guard: &task.cycle_guard,
                    listing: &scratch.listing,
                },
            );
            let outcome = self.act(backend, action, &scratch.path);
            reset_to_directory(&mut scratch.path, path);
            outcome?;
        }
        while let Some(error) = scratch.listing.take_deferred_error() {
            self.handle_error("read_dir", error.path, error.source.into_io_error(), false)?;
        }
        Ok(())
    }

    fn mark_directory(
        &mut self,
        backend: &impl DirectoryBackend,
        cycle_guard: &CycleGuard,
        directory: &Path,
        is_root: bool,
    ) -> Result<bool, WalkError> {
        match backend.cycle_key(directory) {
            Ok(key) => Ok(cycle_guard.mark(key)),
            Err(source) => {
                self.handle_error(
                    CYCLE_KEY_OPERATION,
                    directory.to_path_buf(),
                    source,
                    is_root,
                )?;
                Ok(false)
            }
        }
    }

    /// Carries out what classification decided about one entry.
    ///
    /// `path` is the entry's path, borrowed from the scratch of the directory
    /// being read. A subtree walked from here takes its buffers from the pool,
    /// so it never disturbs that scratch and the path stays valid across the
    /// descent.
    fn act(
        &mut self,
        backend: &impl DirectoryBackend,
        action: EntryAction,
        path: &Path,
    ) -> Result<(), WalkError> {
        match action {
            EntryAction::Skip => Ok(()),
            EntryAction::Descend(task) => self.walk_directory(backend, task),
            EntryAction::Emit(entry) => {
                self.emit(path, entry);
                Ok(())
            }
            // The subtree is walked before the directory itself is recorded,
            // which is the depth-first order this frontend has always had.
            EntryAction::DescendAndEmit(entry, task) => {
                self.walk_directory(backend, task)?;
                self.emit(path, entry);
                Ok(())
            }
            EntryAction::Failed { failure, descend } => {
                self.handle_error(failure.operation, failure.path, failure.source, false)?;
                if let Some(task) = descend {
                    self.walk_directory(backend, task)?;
                }
                Ok(())
            }
        }
    }

    fn handle_error(
        &mut self,
        operation: &'static str,
        path: PathBuf,
        source: std::io::Error,
        is_root: bool,
    ) -> Result<(), WalkError> {
        let error = WalkError::new(operation, path, source);
        match self.walker.error_policy {
            ErrorPolicy::Abort => Err(error),
            ErrorPolicy::Skip if !is_root => Ok(()),
            ErrorPolicy::Skip | ErrorPolicy::Collect => {
                self.errors.push(error);
                Ok(())
            }
        }
    }

    fn check_cancellation(&mut self) -> bool {
        self.cancelled |= self
            .walker
            .cancellation
            .as_ref()
            .is_some_and(CancellationToken::is_cancelled);
        self.cancelled
    }
}

fn should_skip_git_directory(walker: &Walker, name: &OsStr) -> bool {
    walker.respect_git_ignore && !walker.options.keep_git_dir && name == ".git"
}

/// Crate version exposed for build and integration diagnostics.
pub const VERSION: &str = env!("CARGO_PKG_VERSION");

#[cfg(test)]
mod tests {
    use std::{
        cell::RefCell,
        collections::{HashMap, HashSet},
        fs,
        path::{Path, PathBuf},
        process::Command,
        sync::{
            Mutex,
            atomic::{AtomicUsize, Ordering},
        },
        time::{SystemTime, UNIX_EPOCH},
    };

    use super::{
        CancellationToken, ErrorPolicy, Pattern, PatternOptions, TraversalPattern, Verdict,
        WalkEntry, WalkEntryKind, WalkOptions, WalkStream, Walker, WildcardMode, glob_path_bytes,
        literal_extension, literal_pattern_root, traversal_pattern_options,
    };

    static NEXT_FIXTURE: AtomicUsize = AtomicUsize::new(0);

    const HOSTILE_GIT_CONFIG_FIXTURE: &str = "FERRALK_HOSTILE_GIT_CONFIG_FIXTURE";

    #[test]
    fn walk_stream_keeps_its_unwind_auto_traits() {
        fn assert_unwind_safe<T: std::panic::UnwindSafe + std::panic::RefUnwindSafe>() {}

        assert_unwind_safe::<WalkStream>();
    }

    #[test]
    fn worker_budget_is_bounded_at_both_ends() {
        assert_eq!(Walker::new(".").threads(0).threads, 1);
        assert_eq!(
            Walker::new(".").threads(usize::MAX).threads,
            super::MAX_WORKERS
        );
    }

    /// Compiles one walker pattern the way `include` and `exclude` do, in the
    /// default dialect where a wildcard does not cover a leading period.
    fn traversal_pattern(pattern: &[u8]) -> TraversalPattern {
        TraversalPattern::compile(pattern, traversal_pattern_options(false))
            .expect("valid walker pattern")
    }

    struct Fixture {
        root: PathBuf,
    }

    impl Fixture {
        fn new() -> Self {
            let unique = format!(
                "ferralk-test-{}-{}",
                std::process::id(),
                SystemTime::now()
                    .duration_since(UNIX_EPOCH)
                    .expect("system clock is after unix epoch")
                    .as_nanos()
                    + NEXT_FIXTURE.fetch_add(1, Ordering::Relaxed) as u128
            );
            let root = std::env::temp_dir().join(unique);
            fs::create_dir_all(&root).expect("create fixture root");
            Self { root }
        }

        fn write(&self, relative: impl AsRef<Path>) {
            let path = self.root.join(relative);
            fs::create_dir_all(path.parent().expect("fixture file has parent"))
                .expect("create fixture parent");
            fs::write(path, b"fixture").expect("write fixture file");
        }
    }

    impl Fixture {
        /// The fixture root spelled the way an absolute pattern must spell it:
        /// `/` separators on every platform, drive letter and all. Built at run
        /// time so the absolute-pattern tests are the same test everywhere
        /// rather than one test per platform.
        fn absolute(&self, suffix: &str) -> String {
            let root = String::from_utf8(glob_path_bytes(&self.root).into_owned())
                .expect("the temporary directory is UTF-8 on a test host");
            format!("{root}{suffix}")
        }
    }

    impl Drop for Fixture {
        fn drop(&mut self) {
            let _ = fs::remove_dir_all(&self.root);
        }
    }

    /// What one frontend observed for a walk. Under `Abort` only the operation
    /// that stopped the walk is comparable: which entry loses the race is up to
    /// the traversal order, which the three frontends are free to differ on.
    #[derive(Debug, PartialEq, Eq)]
    enum FrontendOutcome {
        Completed {
            entries: Vec<PathBuf>,
            errors: Vec<(&'static str, PathBuf)>,
        },
        Aborted(&'static str),
    }

    fn error_multiset(errors: &[super::WalkError], root: &Path) -> Vec<(&'static str, PathBuf)> {
        let mut errors = errors
            .iter()
            .map(|error| {
                (
                    error.operation(),
                    error
                        .path()
                        .strip_prefix(root)
                        .unwrap_or(error.path())
                        .to_path_buf(),
                )
            })
            .collect::<Vec<_>>();
        errors.sort_unstable();
        errors
    }

    fn collect_outcome(
        result: Result<super::WalkResult, super::WalkError>,
        root: &Path,
    ) -> FrontendOutcome {
        match result {
            Ok(result) => {
                let mut entries = relative_paths(result.entries(), root);
                entries.sort_unstable();
                FrontendOutcome::Completed {
                    entries,
                    errors: error_multiset(result.errors(), root),
                }
            }
            Err(error) => FrontendOutcome::Aborted(error.operation()),
        }
    }

    fn stream_outcome(
        stream: super::WalkStream,
        root: &Path,
        policy: ErrorPolicy,
    ) -> FrontendOutcome {
        let mut entries = Vec::new();
        let mut errors = Vec::new();
        for item in stream {
            match item {
                Ok(entry) => entries.push(
                    entry
                        .path()
                        .strip_prefix(root)
                        .expect("entry is rooted in fixture")
                        .to_path_buf(),
                ),
                Err(error) => {
                    if policy == ErrorPolicy::Abort {
                        return FrontendOutcome::Aborted(error.operation());
                    }
                    errors.push(error);
                }
            }
        }
        entries.sort_unstable();
        FrontendOutcome::Completed {
            entries,
            errors: error_multiset(&errors, root),
        }
    }

    /// Serial `collect`, parallel `collect`, `stream` and `visit` share one
    /// classification pipeline, so they have to report the same entries and the
    /// same errors for the same tree under every policy.
    ///
    /// `visit` is checked twice: keeping everything has to reproduce `collect`
    /// exactly, and filtering in the visitor has to reproduce the same filter
    /// applied to `collect`'s result. The second is the property the API
    /// exists for — a caller moves its predicate into the workers and must get
    /// the same set back.
    fn assert_frontends_agree(label: &str, root: &Path, build: impl Fn() -> Walker) {
        for policy in [ErrorPolicy::Collect, ErrorPolicy::Skip, ErrorPolicy::Abort] {
            let serial = collect_outcome(build().threads(1).error_policy(policy).collect(), root);
            let parallel = collect_outcome(build().threads(4).error_policy(policy).collect(), root);
            let streamed = stream_outcome(build().error_policy(policy).stream(), root, policy);
            assert_eq!(
                parallel, serial,
                "{label}: parallel and serial disagree under {policy:?}"
            );
            assert_eq!(
                streamed, serial,
                "{label}: stream and serial disagree under {policy:?}"
            );

            for threads in [1, 4] {
                let visited = collect_outcome(
                    build()
                        .threads(threads)
                        .error_policy(policy)
                        .visit(|_| Verdict::Keep),
                    root,
                );
                assert_eq!(
                    visited, serial,
                    "{label}: keep-everything visit on {threads} threads disagrees under {policy:?}"
                );

                // An arbitrary predicate that splits the tree, applied in the
                // workers here and to the collected list below.
                let keeps = |entry: &WalkEntry| {
                    entry
                        .path()
                        .to_string_lossy()
                        .bytes()
                        .filter(|byte| *byte == b'a')
                        .count()
                        % 2
                        == 0
                };
                let filtered = collect_outcome(
                    build()
                        .threads(threads)
                        .error_policy(policy)
                        .visit(|entry| {
                            if keeps(entry) {
                                Verdict::Keep
                            } else {
                                Verdict::Skip
                            }
                        }),
                    root,
                );
                let expected = match &serial {
                    FrontendOutcome::Aborted(operation) => FrontendOutcome::Aborted(operation),
                    FrontendOutcome::Completed { errors, .. } => {
                        let mut entries = collect_outcome(
                            build().threads(threads).error_policy(policy).collect(),
                            root,
                        );
                        if let FrontendOutcome::Completed {
                            entries: collected, ..
                        } = &mut entries
                        {
                            collected.retain(|path| keeps_relative(path, root, keeps));
                        }
                        match entries {
                            FrontendOutcome::Completed { entries, .. } => {
                                FrontendOutcome::Completed {
                                    entries,
                                    errors: errors.clone(),
                                }
                            }
                            aborted => aborted,
                        }
                    }
                };
                assert_eq!(
                    filtered, expected,
                    "{label}: filtering visit on {threads} threads disagrees under {policy:?}"
                );
            }
        }
    }

    /// Re-applies a visitor predicate to a path `collect_outcome` made relative.
    fn keeps_relative(relative: &Path, root: &Path, keeps: impl Fn(&WalkEntry) -> bool) -> bool {
        let entry = WalkEntry {
            path: root.join(relative),
            root: std::sync::Arc::from(root),
            is_dir: false,
            is_symlink: false,
            depth: 0,
            metadata: None,
        };
        keeps(&entry)
    }

    /// Builds the root task the way the walk frontends do, for tests that
    /// drive `WalkState` directly.
    fn directory_task(
        walker: &Walker,
        backend: &impl super::DirectoryBackend,
        path: PathBuf,
    ) -> super::DirectoryTask {
        let (ignores, ignore_errors) = super::IgnoreScope::for_root(walker, backend, &path);
        super::DirectoryTask {
            path: path.clone(),
            open: super::DirectoryOpen::default(),
            depth: 0,
            root: 0,
            cycle_guard: std::sync::Arc::new(super::CycleGuard::default()),
            ignores,
            ignore_errors,
        }
    }

    #[test]
    fn stream_discards_partial_listing_after_a_directory_read_error() {
        let fixture = Fixture::new();
        let missing = fixture.root.join("missing");
        let mut stream = Walker::new(&missing)
            .error_policy(ErrorPolicy::Collect)
            .stream();

        // Model a backend that appended an entry before it reported its error.
        stream
            .listing
            .push(std::ffi::OsStr::new("must-not-leak"), false, false);

        let task = stream
            .pending_directories
            .pop()
            .expect("the root is queued for reading");
        let error = stream
            .prepare_directory(task)
            .expect("the failed root produces an error")
            .expect_err("a missing root cannot yield an entry");
        assert_eq!(error.operation(), "read_dir");
        assert!(stream.listing.entries().is_empty());
        assert!(stream.next().is_none(), "partial entries must not leak");
    }

    /// Counts what a walk reads, so tests can pin how often it happens.
    #[derive(Default)]
    struct CountingBackend {
        ignore_reads: std::sync::Mutex<HashMap<PathBuf, usize>>,
    }

    impl CountingBackend {
        fn ignore_reads(&self) -> Vec<(PathBuf, usize)> {
            let mut reads = self
                .ignore_reads
                .lock()
                .unwrap_or_else(|poisoned| poisoned.into_inner())
                .iter()
                .map(|(path, count)| (path.clone(), *count))
                .collect::<Vec<_>>();
            reads.sort_unstable();
            reads
        }
    }

    impl super::DirectoryBackend for CountingBackend {
        fn read_directory(
            &self,
            path: &Path,
            follow_symlinks: bool,
            refuse_final_symlink: bool,
            listing: &mut super::Listing,
        ) -> std::io::Result<()> {
            super::StdBackend.read_directory(path, follow_symlinks, refuse_final_symlink, listing)
        }

        fn read_ignore_file(&self, path: &Path) -> std::io::Result<Vec<u8>> {
            *self
                .ignore_reads
                .lock()
                .unwrap_or_else(|poisoned| poisoned.into_inner())
                .entry(path.to_path_buf())
                .or_default() += 1;
            fs::read(path)
        }
    }

    fn relative_paths(entries: &[WalkEntry], root: &Path) -> Vec<PathBuf> {
        entries
            .iter()
            .map(|entry| {
                entry
                    .path()
                    .strip_prefix(root)
                    .expect("entry is rooted in fixture")
                    .to_path_buf()
            })
            .collect()
    }

    fn relative_paths_and_depths(entries: &[WalkEntry], root: &Path) -> Vec<(PathBuf, usize)> {
        entries
            .iter()
            .map(|entry| {
                (
                    entry
                        .path()
                        .strip_prefix(root)
                        .expect("entry is rooted in fixture")
                        .to_path_buf(),
                    entry.depth(),
                )
            })
            .collect()
    }

    fn rooted_relative_paths(entries: &[WalkEntry]) -> Vec<(PathBuf, PathBuf)> {
        let mut paths = entries
            .iter()
            .map(|entry| {
                (
                    entry.root().to_path_buf(),
                    entry
                        .path()
                        .strip_prefix(entry.root())
                        .expect("entry is rooted in its declared root")
                        .to_path_buf(),
                )
            })
            .collect::<Vec<_>>();
        paths.sort_unstable();
        paths
    }

    type RootFilterSources = (Vec<Vec<u8>>, Vec<Vec<u8>>);

    fn configured_filter_sources(walker: &Walker) -> Vec<RootFilterSources> {
        walker
            .roots
            .iter()
            .map(|root| {
                (
                    root.includes
                        .iter()
                        .map(|pattern| pattern.source.clone())
                        .collect(),
                    root.excludes
                        .iter()
                        .map(|pattern| pattern.source.clone())
                        .collect(),
                )
            })
            .collect()
    }

    #[test]
    fn include_exclude_and_sort_are_applied_to_relative_paths() {
        let fixture = Fixture::new();
        fixture.write("src/main.rs");
        fixture.write("src/lib.txt");
        fixture.write("target/generated.rs");

        let result = Walker::new(&fixture.root)
            .include("**/*.rs")
            .expect("valid include")
            .exclude("**/target/**")
            .expect("valid exclude")
            .options(WalkOptions::default().sort(true))
            .collect()
            .expect("walk succeeds");

        assert_eq!(
            relative_paths(result.entries(), &fixture.root),
            vec![PathBuf::from("src/main.rs")]
        );
        assert!(result.errors().is_empty());
    }

    #[test]
    fn borrowed_pattern_lists_keep_the_builder_and_filter_every_frontend() {
        let fixture = Fixture::new();
        let alpha = fixture.root.join("alpha");
        let beta = fixture.root.join("beta");
        for root in ["alpha", "beta"] {
            fixture.write(format!("{root}/src/keep.rs"));
            fixture.write(format!("{root}/src/remove.rs"));
            fixture.write(format!("{root}/src/ignore.txt"));
            fixture.write(format!("{root}/.hidden.rs"));
        }

        let mut walker = Walker::new(&alpha)
            .add_root(&beta)
            .expect("valid second root")
            .match_hidden(true)
            .wildcard_mode(WildcardMode::SeparatorCrossing)
            .options(WalkOptions::default().files_only(true).sort(true));

        walker
            .try_include("*.rs")
            .expect("first supplied include is valid");
        let before_bad_include = walker.clone();
        assert!(walker.try_include("[a").is_err());
        assert_eq!(walker.include_sources, before_bad_include.include_sources);
        assert_eq!(walker.exclude_sources, before_bad_include.exclude_sources);
        assert_eq!(
            configured_filter_sources(&walker),
            configured_filter_sources(&before_bad_include),
            "a rejected include must not update any root"
        );
        walker
            .try_include("**/also.rs")
            .expect("a later supplied include still composes");

        walker
            .try_exclude("**/remove.rs")
            .expect("first supplied exclude is valid");
        let before_bad_exclude = walker.clone();
        assert!(walker.try_exclude("[a").is_err());
        assert_eq!(walker.include_sources, before_bad_exclude.include_sources);
        assert_eq!(walker.exclude_sources, before_bad_exclude.exclude_sources);
        assert_eq!(
            configured_filter_sources(&walker),
            configured_filter_sources(&before_bad_exclude),
            "a rejected exclude must not update any root"
        );
        walker
            .try_exclude("**/generated/**")
            .expect("a later supplied exclude still composes");

        let expected = vec![
            (alpha.clone(), PathBuf::from(".hidden.rs")),
            (alpha.clone(), PathBuf::from("src/keep.rs")),
            (beta.clone(), PathBuf::from(".hidden.rs")),
            (beta.clone(), PathBuf::from("src/keep.rs")),
        ];
        for threads in [1, 4] {
            let collected = walker
                .clone()
                .threads(threads)
                .collect()
                .expect("collect succeeds");
            assert_eq!(rooted_relative_paths(collected.entries()), expected);

            let visited = walker
                .clone()
                .threads(threads)
                .visit(|_| Verdict::Keep)
                .expect("visit succeeds");
            assert_eq!(rooted_relative_paths(visited.entries()), expected);
        }
        let streamed = walker
            .stream()
            .collect::<Result<Vec<_>, _>>()
            .expect("stream succeeds");
        assert_eq!(rooted_relative_paths(&streamed), expected);
    }

    #[test]
    fn source_walk_glob_patterns_filter_recursive_anchored_and_brace_paths() {
        let fixture = Fixture::new();
        fixture.write("src/a.rs");
        fixture.write("src/b.txt");
        fixture.write("src/deep/e.rs");
        fixture.write("lib/c.rs");
        fixture.write("docs/d.md");
        fixture.write("top.rs");
        let options = WalkOptions::default().sort(true);

        let recursive = Walker::new(&fixture.root)
            .include("**/*.rs")
            .expect("valid recursive include")
            .options(options)
            .collect()
            .expect("recursive walk succeeds");
        assert_eq!(
            relative_paths(recursive.entries(), &fixture.root),
            vec![
                PathBuf::from("lib/c.rs"),
                PathBuf::from("src/a.rs"),
                PathBuf::from("src/deep/e.rs"),
                PathBuf::from("top.rs"),
            ]
        );

        let anchored = Walker::new(&fixture.root)
            .include("src/**")
            .expect("valid anchored include")
            .options(options)
            .collect()
            .expect("anchored walk succeeds");
        assert_eq!(
            relative_paths(anchored.entries(), &fixture.root),
            vec![
                PathBuf::from("src"),
                PathBuf::from("src/a.rs"),
                PathBuf::from("src/b.txt"),
                PathBuf::from("src/deep"),
                PathBuf::from("src/deep/e.rs"),
            ]
        );

        let brace = Walker::new(&fixture.root)
            .include("**/*.{md,txt}")
            .expect("valid brace include")
            .options(options)
            .collect()
            .expect("brace walk succeeds");
        assert_eq!(
            relative_paths(brace.entries(), &fixture.root),
            vec![PathBuf::from("docs/d.md"), PathBuf::from("src/b.txt")]
        );
    }

    #[test]
    fn relative_patterns_that_name_no_candidate_are_rejected_with_guidance() {
        let fixture = Fixture::new();
        fixture.write("src/main.rs");
        fixture.write("src/a.rs");
        fixture.write("src/].rs");
        // Windows normalizes a path component ending in dots, so these two
        // valid matcher strings cannot be represented as fixture paths there.
        #[cfg(not(windows))]
        {
            fixture.write("prefix../bar");
            fixture.write("foo/..suffix/bar");
        }

        for mode in [
            WildcardMode::ComponentScoped,
            WildcardMode::SeparatorCrossing,
        ] {
            for add in [
                |walker: Walker| walker.include("."),
                |walker: Walker| walker.include("./"),
                |walker: Walker| walker.include("src/."),
                |walker: Walker| walker.include("src/./main.rs"),
                |walker: Walker| walker.include("././src/**"),
                |walker: Walker| walker.include("src/../main.rs"),
                |walker: Walker| walker.include("+(dead/../branch)"),
                |walker: Walker| walker.exclude("."),
                |walker: Walker| walker.exclude("./"),
                |walker: Walker| walker.exclude("src/."),
                |walker: Walker| walker.exclude("src/./main.rs"),
                |walker: Walker| walker.exclude("././src/**"),
                |walker: Walker| walker.exclude("src/../main.rs"),
                |walker: Walker| walker.exclude("+(dead/../branch)"),
            ] {
                let error = add(Walker::new(&fixture.root).wildcard_mode(mode))
                    .expect_err("unwalkable relative pattern is refused");
                assert!(
                    error.message().contains("select")
                        || error.message().contains("not normalized")
                        || error.message().starts_with("`..`"),
                    "the rejection explains why the pattern cannot select: {error}"
                );
            }
        }

        // On a relative walk root `/bar` cannot be rewritten as an absolute
        // pattern; on Windows it remains a root-relative empty-leading
        // spelling. Either path must refuse it at pattern-add time.
        for mode in [
            WildcardMode::ComponentScoped,
            WildcardMode::SeparatorCrossing,
        ] {
            assert!(
                Walker::new(".")
                    .wildcard_mode(mode)
                    .include("/bar")
                    .is_err(),
                "include rejects an unselectable leading empty component under {mode:?}"
            );
            assert!(
                Walker::new(".")
                    .wildcard_mode(mode)
                    .exclude("/bar")
                    .is_err(),
                "exclude rejects an unselectable leading empty component under {mode:?}"
            );
        }

        // Dots that are matcher text, rather than slash-delimited path
        // components, remain valid in every mode. In particular this keeps
        // escaped, class, brace and extglob literals out of the path check.
        for pattern in [
            "./src/**",
            "...",
            ".hidden",
            r"\.\.",
            r"src\..\main.rs",
            "[.]",
            "{..,src}",
            "@(..)",
            "src/[[:alpha:]/../].rs",
            "src/[]/../].rs",
            "{dead/../branch,src/main.rs}",
            "@(dead/../branch|src/main.rs)",
            "src/[{],a}/../].rs",
            "@(dead/{),x}/../branch|src/main.rs)",
            "prefix@(../bar)",
            "@(foo/..)suffix/bar",
        ] {
            for mode in [
                WildcardMode::ComponentScoped,
                WildcardMode::SeparatorCrossing,
            ] {
                Walker::new(&fixture.root)
                    .wildcard_mode(mode)
                    .include(pattern)
                    .unwrap_or_else(|error| panic!("{pattern} must stay matcher text: {error}"));
            }
        }

        // Braces expose literal path components to the viability analysis, so
        // their dot forms are rejected. An extglob remains one opaque matcher
        // component; it cannot name `.` or `..` as a walk path component and
        // therefore stays valid while selecting no entry.
        let brace_dot_components = "{.,..}";
        assert!(
            Walker::new(&fixture.root)
                .include(brace_dot_components)
                .is_err(),
            "brace-expanded {brace_dot_components:?} is an unwalkable path spelling"
        );
        for pattern in ["@(.)", "@(..)/x", "?(.)/x"] {
            Walker::new(&fixture.root)
                .include(pattern)
                .unwrap_or_else(|error| panic!("{pattern} remains opaque matcher text: {error}"));
        }

        // A dead brace or extglob arm must not reject a viable one. Character
        // classes use the glob parser's POSIX and leading-`]` grammar, so a
        // slash or `..` text inside either class stays matcher syntax too.
        // Extglobs retain their component-scoped matching rule, so only the
        // separator-crossing walk reads its slash-containing arm as one path.
        for (pattern, matching_paths, component_scoped_paths) in [
            (
                "{dead/../branch,src/main.rs}",
                &["src/main.rs"][..],
                &["src/main.rs"][..],
            ),
            (
                "@(dead/../branch|src/main.rs)",
                &["src/main.rs"][..],
                &[][..],
            ),
            (
                "src/[[:alpha:]/../].rs",
                &["src/a.rs"][..],
                &["src/a.rs"][..],
            ),
            ("src/[]/../].rs", &["src/].rs"][..], &["src/].rs"][..]),
            (
                "src/[{],a}/../].rs",
                &["src/a.rs", "src/].rs"][..],
                &["src/a.rs", "src/].rs"][..],
            ),
            (
                "@(dead/{),x}/../branch|src/main.rs)",
                &["src/main.rs"][..],
                &[][..],
            ),
            ("prefix@(../bar)", &["prefix../bar"][..], &[][..]),
            ("@(foo/..)suffix/bar", &["foo/..suffix/bar"][..], &[][..]),
        ] {
            let matcher = Pattern::compile(pattern, traversal_pattern_options(false))
                .expect("the reviewer regression is valid matcher syntax");
            for matching_path in matching_paths {
                assert!(matcher.is_match(matching_path));
            }
            let matching_paths_on_disk =
                if cfg!(windows) && matches!(pattern, "prefix@(../bar)" | "@(foo/..)suffix/bar") {
                    &[][..]
                } else {
                    matching_paths
                };
            for mode in [
                WildcardMode::ComponentScoped,
                WildcardMode::SeparatorCrossing,
            ] {
                Walker::new(&fixture.root)
                    .wildcard_mode(mode)
                    .exclude(pattern)
                    .expect("the viable group arm is accepted for excludes");
                for threads in [1, 4] {
                    let result = Walker::new(&fixture.root)
                        .wildcard_mode(mode)
                        .threads(threads)
                        .include(pattern)
                        .expect("the viable group arm is accepted")
                        .options(WalkOptions::default().sort(true).files_only(true))
                        .collect()
                        .expect("walk succeeds");
                    let mut expected = if mode == WildcardMode::ComponentScoped {
                        component_scoped_paths
                    } else {
                        matching_paths_on_disk
                    }
                    .iter()
                    .map(PathBuf::from)
                    .collect::<Vec<_>>();
                    expected.sort();
                    assert_eq!(
                        relative_paths(result.entries(), &fixture.root),
                        expected,
                        "{pattern} must keep its viable arm under {mode:?} on {threads} threads"
                    );
                }
                let streamed = Walker::new(&fixture.root)
                    .wildcard_mode(mode)
                    .include(pattern)
                    .expect("the viable group arm is accepted")
                    .options(WalkOptions::default().files_only(true))
                    .stream()
                    .collect::<Result<Vec<_>, _>>()
                    .expect("stream succeeds");
                let mut actual = relative_paths(&streamed, &fixture.root);
                actual.sort();
                let mut expected = if mode == WildcardMode::ComponentScoped {
                    component_scoped_paths
                } else {
                    matching_paths_on_disk
                }
                .iter()
                .map(PathBuf::from)
                .collect::<Vec<_>>();
                expected.sort();
                assert_eq!(actual, expected);
            }
        }

        for pattern in [
            "src/../main.rs",
            "src/{live,dead}/../main.rs",
            "{dead/[}]]/../x,src/main.rs}",
            "@(dead/[)]]/../x|src/main.rs)",
            "{dead/../branch}",
            "@(dead/../branch)",
            "@(dead|src)/../main.rs",
            "src/@(./a.rs)",
            "@(./a.rs)",
            "{./a.rs}",
            "src/?(./a.rs)",
            "src/*(./a.rs)",
            "src/?(./a.rs)/bar",
            "src/*(./a.rs)/bar",
            "src/?()/bar",
            "src/*()/bar",
            "?()/bar",
            "*()/bar",
            "src//bar",
            "src/{}/bar",
            "src/{,./a.rs}/bar",
        ] {
            assert!(
                Walker::new(&fixture.root).include(pattern).is_err(),
                "a parser-top-level `..` component stays invalid: {pattern}"
            );
        }
        for mode in [
            WildcardMode::ComponentScoped,
            WildcardMode::SeparatorCrossing,
        ] {
            for pattern in [
                "{dead/[}]]/../x,src/main.rs}",
                "@(dead/[)]]/../x|src/main.rs)",
                "{dead/../branch}",
                "@(dead/../branch)",
                "@(dead|src)/../main.rs",
                "src/@(./a.rs)",
                "@(./a.rs)",
                "{./a.rs}",
                "src/?(./a.rs)",
                "src/*(./a.rs)",
                "src/?(./a.rs)/bar",
                "src/*(./a.rs)/bar",
                "src/?()/bar",
                "src/*()/bar",
                "?()/bar",
                "*()/bar",
                "src//bar",
                "src/{}/bar",
                "src/{,./a.rs}/bar",
            ] {
                assert!(
                    Walker::new(&fixture.root)
                        .wildcard_mode(mode)
                        .include(pattern)
                        .is_err(),
                    "include rejects parser-top-level `..` under {mode:?}: {pattern}"
                );
                assert!(
                    Walker::new(&fixture.root)
                        .wildcard_mode(mode)
                        .exclude(pattern)
                        .is_err(),
                    "exclude rejects parser-top-level `..` under {mode:?}: {pattern}"
                );
            }
        }
    }

    #[test]
    fn relative_pattern_errors_keep_determinate_component_offsets() {
        for (pattern, offset) in [
            ("src/../main.rs", 4),
            ("src/./main.rs", 4),
            ("src/.", 4),
            ("é/../main.rs", 3),
            ("src/@(./a.rs)", 6),
            ("{src}/../main.rs", 6),
            ("{a,b}/../main.rs", 6),
            ("src/{x}/.", 8),
        ] {
            for mode in [
                WildcardMode::ComponentScoped,
                WildcardMode::SeparatorCrossing,
            ] {
                for error in [
                    Walker::new(".")
                        .wildcard_mode(mode)
                        .include(pattern)
                        .expect_err("unwalkable include is refused"),
                    Walker::new(".")
                        .wildcard_mode(mode)
                        .exclude(pattern)
                        .expect_err("unwalkable exclude is refused"),
                ] {
                    assert_eq!(
                        error.offset(),
                        offset,
                        "{pattern} keeps its component offset under {mode:?}"
                    );
                }
            }
        }

        for pattern in [r"src/\./main.rs", r"src/\../main.rs", "src/@(..)suffix"] {
            Walker::new(".")
                .include(pattern)
                .unwrap_or_else(|error| panic!("{pattern} remains matcher text: {error}"));
        }
    }

    #[test]
    fn source_rust_glob_patterns_replay_as_walker_filters() {
        // Ported from the root-relative pattern cases in
        // zlob/test/test_rust_glob.zig. The Walker deliberately returns its
        // own entries instead of zlob's C-shaped glob result buffer.
        let fixture = Fixture::new();
        for path in [
            "xyz/x",
            "xyz/y",
            "xyz/z",
            "aaa/tomato/tomato.txt",
            "aaa/tomato/tomoto.txt",
            "bbb/specials/[",
            "bbb/specials/!",
            "bbb/specials/]",
        ] {
            fixture.write(path);
        }
        for path in ["aaa/apple", "aaa/orange"] {
            fs::create_dir_all(fixture.root.join(path)).expect("create source fixture directory");
        }

        let paths_for = |pattern: &str| {
            let result = Walker::new(&fixture.root)
                .threads(1)
                .include(pattern)
                .expect("valid source pattern")
                .options(WalkOptions::default().sort(true))
                .collect()
                .expect("source walk succeeds");
            relative_paths(result.entries(), &fixture.root)
        };

        assert_eq!(paths_for("aaa"), vec![PathBuf::from("aaa")]);
        assert_eq!(paths_for("./aaa"), vec![PathBuf::from("aaa")]);
        assert_eq!(paths_for("aaa/"), vec![PathBuf::from("aaa")]);
        assert!(paths_for("aaa/tomato/tomato.txt/").is_empty());
        assert!(paths_for("nope").is_empty());
        assert_eq!(paths_for("a*"), vec![PathBuf::from("aaa")]);
        assert_eq!(paths_for("@(a*)"), vec![PathBuf::from("aaa")]);
        assert_eq!(paths_for("a*a"), vec![PathBuf::from("aaa")]);
        assert_eq!(paths_for("*a*a*a*"), vec![PathBuf::from("aaa")]);
        assert_eq!(paths_for("aaa/apple"), vec![PathBuf::from("aaa/apple")]);
        assert_eq!(paths_for("./*"), paths_for("*"));
        assert_eq!(
            paths_for("???/"),
            vec![
                PathBuf::from("aaa"),
                PathBuf::from("bbb"),
                PathBuf::from("xyz"),
            ]
        );
        assert_eq!(
            paths_for("xyz/?"),
            vec![
                PathBuf::from("xyz/x"),
                PathBuf::from("xyz/y"),
                PathBuf::from("xyz/z"),
            ]
        );
        assert_eq!(
            paths_for("aaa/tomato/tom?to.txt"),
            vec![
                PathBuf::from("aaa/tomato/tomato.txt"),
                PathBuf::from("aaa/tomato/tomoto.txt"),
            ]
        );
        assert_eq!(
            paths_for("aaa/*"),
            vec![
                PathBuf::from("aaa/apple"),
                PathBuf::from("aaa/orange"),
                PathBuf::from("aaa/tomato"),
            ]
        );
        let component_local = paths_for("aaa/*");
        let parallel = Walker::new(&fixture.root)
            .threads(4)
            .include("aaa/*")
            .expect("valid source pattern")
            .options(WalkOptions::default().sort(true))
            .collect()
            .expect("parallel source walk succeeds");
        assert_eq!(
            relative_paths(parallel.entries(), &fixture.root),
            component_local
        );
        let mut streamed = Walker::new(&fixture.root)
            .include("aaa/*")
            .expect("valid source pattern")
            .stream()
            .collect::<Result<Vec<_>, _>>()
            .expect("stream source walk succeeds");
        streamed.sort_by(|left, right| left.path().cmp(right.path()));
        assert_eq!(relative_paths(&streamed, &fixture.root), component_local);
        let trailing_directory = paths_for("aaa/");
        let trailing_parallel = Walker::new(&fixture.root)
            .threads(4)
            .include("aaa/")
            .expect("valid trailing directory pattern")
            .options(WalkOptions::default().sort(true))
            .collect()
            .expect("parallel trailing directory walk succeeds");
        assert_eq!(
            relative_paths(trailing_parallel.entries(), &fixture.root),
            trailing_directory
        );
        let mut trailing_streamed = Walker::new(&fixture.root)
            .include("aaa/")
            .expect("valid trailing directory pattern")
            .stream()
            .collect::<Result<Vec<_>, _>>()
            .expect("stream trailing directory walk succeeds");
        trailing_streamed.sort_by(|left, right| left.path().cmp(right.path()));
        assert_eq!(
            relative_paths(&trailing_streamed, &fixture.root),
            trailing_directory
        );
        assert_eq!(
            paths_for("*/*/*.txt"),
            vec![
                PathBuf::from("aaa/tomato/tomato.txt"),
                PathBuf::from("aaa/tomato/tomoto.txt"),
            ]
        );
        assert_eq!(paths_for("aa[a]"), vec![PathBuf::from("aaa")]);
        assert_eq!(paths_for("aa[!b]"), vec![PathBuf::from("aaa")]);
        assert!(paths_for("aa[b]").is_empty());
        assert_eq!(
            paths_for("*/*/t[aob]m?to[.]t[!y]t"),
            vec![
                PathBuf::from("aaa/tomato/tomato.txt"),
                PathBuf::from("aaa/tomato/tomoto.txt"),
            ]
        );
        assert_eq!(
            paths_for("bbb/specials/[[]"),
            vec![PathBuf::from("bbb/specials/["),]
        );
        assert_eq!(
            paths_for("bbb/specials/[]]"),
            vec![PathBuf::from("bbb/specials/]"),]
        );
    }

    #[test]
    fn source_walk_entry_depths_are_relative_component_counts() {
        let fixture = Fixture::new();
        fixture.write("a.txt");
        fixture.write("src/b.txt");
        fixture.write("src/sub/c.txt");
        let options = WalkOptions::default().sort(true);
        let expected = vec![
            (PathBuf::from("a.txt"), 1),
            (PathBuf::from("src"), 1),
            (PathBuf::from("src/b.txt"), 2),
            (PathBuf::from("src/sub"), 2),
            (PathBuf::from("src/sub/c.txt"), 3),
        ];

        let serial = Walker::new(&fixture.root)
            .threads(1)
            .options(options)
            .collect()
            .expect("serial walk succeeds");
        let parallel = Walker::new(&fixture.root)
            .threads(4)
            .options(options)
            .collect()
            .expect("parallel walk succeeds");
        let mut streamed = Walker::new(&fixture.root)
            .options(options)
            .stream()
            .collect::<Result<Vec<_>, _>>()
            .expect("stream succeeds");
        streamed.sort_by(|left, right| left.path.cmp(&right.path));

        assert_eq!(
            relative_paths_and_depths(serial.entries(), &fixture.root),
            expected
        );
        assert_eq!(
            relative_paths_and_depths(parallel.entries(), &fixture.root),
            expected
        );
        assert_eq!(
            relative_paths_and_depths(&streamed, &fixture.root),
            expected
        );

        let a = serial
            .entries()
            .iter()
            .find(|entry| entry.basename() == Some(std::ffi::OsStr::new("a.txt")))
            .expect("a.txt is present");
        assert!(!a.is_dir());
        assert_eq!(a.kind(), WalkEntryKind::File);
        assert_eq!(a.depth(), 1);

        let src = serial
            .entries()
            .iter()
            .find(|entry| entry.basename() == Some(std::ffi::OsStr::new("src")))
            .expect("src is present");
        assert!(src.is_dir());
        assert_eq!(src.kind(), WalkEntryKind::Directory);
        assert_eq!(src.depth(), 1);

        let c = serial
            .entries()
            .iter()
            .find(|entry| entry.basename() == Some(std::ffi::OsStr::new("c.txt")))
            .expect("c.txt is present");
        assert!(!c.is_dir());
        assert_eq!(c.kind(), WalkEntryKind::File);
        assert_eq!(c.depth(), 3);
    }

    /// Depth is now carried down the tree instead of being recounted from each
    /// entry's path. The two have to agree, so the definition it replaced is
    /// the oracle: the components between the walk root and the entry.
    #[test]
    fn carried_depth_matches_the_component_count_it_replaced() {
        let fixture = Fixture::new();
        fixture.write("a.txt");
        fixture.write("one/b.txt");
        fixture.write("one/two/c.txt");
        fixture.write("one/two/three/d.txt");
        fixture.write("one/two/three/four/e.txt");

        for threads in [1, 4] {
            let walked = Walker::new(&fixture.root)
                .threads(threads)
                .collect()
                .expect("walk succeeds");
            assert!(!walked.entries().is_empty());
            for entry in walked.entries() {
                let counted = entry
                    .path()
                    .strip_prefix(&fixture.root)
                    .expect("entry is rooted in the fixture")
                    .components()
                    .count();
                assert_eq!(
                    entry.depth(),
                    counted,
                    "{} on {threads} thread(s)",
                    entry.path().display()
                );
            }
        }
    }

    /// The root-relative part of a path is taken as a byte suffix at a fixed
    /// offset. Deriving that offset by pushing a name is what makes it survive
    /// a root that already ends in a separator, where adding one would put the
    /// slice one byte out.
    #[test]
    fn a_root_with_a_trailing_separator_walks_like_one_without() {
        let fixture = Fixture::new();
        fixture.write("src/main.rs");
        fixture.write("src/nested/lib.rs");
        let options = WalkOptions::default().sort(true);

        let plain = Walker::new(&fixture.root)
            .threads(1)
            .include("src/**/*.rs")
            .expect("valid include")
            .options(options)
            .collect()
            .expect("walk succeeds");
        // The platform's own separator, so the walked paths are comparable
        // byte for byte. A hardcoded `/` would leave one forward slash in an
        // otherwise backslash path on Windows, and the test would be measuring
        // that rather than the offset it is about.
        let mut trailing_root = fixture.root.clone().into_os_string();
        trailing_root.push(std::path::MAIN_SEPARATOR_STR);
        let trailing = Walker::new(PathBuf::from(trailing_root))
            .threads(1)
            .include("src/**/*.rs")
            .expect("valid include")
            .options(options)
            .collect()
            .expect("walk succeeds");

        let paths = |result: &super::WalkResult| {
            result
                .entries()
                .iter()
                .map(|entry| entry.path().to_path_buf())
                .collect::<Vec<_>>()
        };
        assert_eq!(paths(&trailing), paths(&plain));
        assert_eq!(plain.entries().len(), 2);
    }

    /// The serial frontend descends by recursion while the parent directory is
    /// still being listed. Entries after a subdirectory must therefore still be
    /// built on the parent's path, not on whatever the descent left behind.
    #[test]
    fn entries_after_a_subdirectory_keep_their_own_paths() {
        let fixture = Fixture::new();
        // Several of each, interleaved by name, so the listing order the
        // filesystem happens to return still puts a file after a directory.
        for index in 0..4 {
            fixture.write(format!("outer/dir-{index}/inner.txt"));
            fixture.write(format!("outer/file-{index}.txt"));
        }
        let options = WalkOptions::default().sort(true).files_only(true);

        for threads in [1, 4] {
            let walked = Walker::new(&fixture.root)
                .threads(threads)
                .options(options)
                .collect()
                .expect("walk succeeds");
            let mut relative = relative_paths(walked.entries(), &fixture.root);
            relative.sort();
            let mut expected = (0..4)
                .flat_map(|index| {
                    [
                        PathBuf::from(format!("outer/dir-{index}/inner.txt")),
                        PathBuf::from(format!("outer/file-{index}.txt")),
                    ]
                })
                .collect::<Vec<_>>();
            expected.sort();
            assert_eq!(relative, expected, "on {threads} thread(s)");
        }
    }

    /// One listing buffer serves every directory a worker reads. A directory
    /// with fewer entries than the one before it must report only its own, and
    /// not the tail the longer listing left in the buffer.
    #[test]
    fn a_short_directory_after_a_long_one_reports_only_its_own_entries() {
        let fixture = Fixture::new();
        for index in 0..40 {
            fixture.write(format!("crowded/file-{index:02}.txt"));
        }
        fixture.write("sparse/only.txt");

        // One thread, so both directories go through the same buffer, and the
        // crowded one is read first.
        let walked = Walker::new(&fixture.root)
            .threads(1)
            .include("sparse/**")
            .expect("valid include")
            .options(WalkOptions::default().sort(true).files_only(true))
            .collect()
            .expect("walk succeeds");

        assert_eq!(
            relative_paths(walked.entries(), &fixture.root),
            vec![PathBuf::from("sparse/only.txt")]
        );
    }

    #[test]
    fn directories_only_filters_results_without_pruning_descendants() {
        let fixture = Fixture::new();
        fixture.write("src/main.rs");
        fixture.write("src/nested/lib.rs");
        let options = WalkOptions::default().directories_only(true).sort(true);

        let serial = Walker::new(&fixture.root)
            .threads(1)
            .options(options)
            .collect()
            .expect("serial walk succeeds");
        let parallel = Walker::new(&fixture.root)
            .threads(4)
            .options(options)
            .collect()
            .expect("parallel walk succeeds");
        let streamed = Walker::new(&fixture.root)
            .options(options)
            .stream()
            .collect::<Result<Vec<_>, _>>()
            .expect("stream succeeds");
        let expected = vec![PathBuf::from("src"), PathBuf::from("src/nested")];

        assert_eq!(relative_paths(serial.entries(), &fixture.root), expected);
        assert_eq!(relative_paths(parallel.entries(), &fixture.root), expected);
        assert_eq!(relative_paths(&streamed, &fixture.root), expected);
        assert!(streamed.iter().all(WalkEntry::is_dir));
    }

    #[test]
    fn max_depth_keeps_boundary_entries_without_descending() {
        let fixture = Fixture::new();
        fixture.write("top.txt");
        fixture.write("d1/mid.txt");
        fixture.write("d1/d2/bottom.txt");

        for (max_depth, expected) in [
            (0, vec![]),
            (1, vec![PathBuf::from("d1"), PathBuf::from("top.txt")]),
            (
                2,
                vec![
                    PathBuf::from("d1"),
                    PathBuf::from("d1/d2"),
                    PathBuf::from("d1/mid.txt"),
                    PathBuf::from("top.txt"),
                ],
            ),
        ] {
            let options = WalkOptions::default().max_depth(max_depth).sort(true);
            let serial = Walker::new(&fixture.root)
                .threads(1)
                .options(options)
                .collect()
                .expect("serial walk succeeds");
            let parallel = Walker::new(&fixture.root)
                .threads(4)
                .options(options)
                .collect()
                .expect("parallel walk succeeds");
            let mut streamed = Walker::new(&fixture.root)
                .options(options)
                .stream()
                .collect::<Result<Vec<_>, _>>()
                .expect("stream succeeds");
            streamed.sort_by(|left, right| left.path.cmp(&right.path));

            assert_eq!(relative_paths(serial.entries(), &fixture.root), expected);
            assert_eq!(relative_paths(parallel.entries(), &fixture.root), expected);
            assert_eq!(relative_paths(&streamed, &fixture.root), expected);
        }
    }

    #[test]
    fn parallel_collect_matches_the_serial_result_multiset() {
        let fixture = Fixture::new();
        fixture.write("wide/a.txt");
        fixture.write("wide/b.txt");
        fixture.write("deep/one/two/three/leaf.txt");
        fixture.write("ignored.tmp");
        fs::write(fixture.root.join(".gitignore"), b"*.tmp\n").expect("write gitignore");

        let serial = Walker::new(&fixture.root)
            .respect_git_ignore(true)
            .threads(1)
            .options(WalkOptions::default().sort(true))
            .collect()
            .expect("serial walk succeeds");
        let parallel = Walker::new(&fixture.root)
            .respect_git_ignore(true)
            .threads(4)
            .options(WalkOptions::default().sort(true))
            .collect()
            .expect("parallel walk succeeds");

        assert_eq!(
            relative_paths(parallel.entries(), &fixture.root),
            relative_paths(serial.entries(), &fixture.root)
        );
        assert!(parallel.errors().is_empty());
        assert!(serial.errors().is_empty());
    }

    #[test]
    fn parallel_collect_stress_covers_empty_shallow_and_imbalanced_trees() {
        let empty = Fixture::new();
        assert!(
            Walker::new(&empty.root)
                .threads(8)
                .collect()
                .expect("empty parallel walk succeeds")
                .entries()
                .is_empty()
        );

        let fixture = Fixture::new();
        fixture.write("shallow.txt");
        for branch in 0..8 {
            fixture.write(format!("wide/{branch}/leaf.txt"));
        }
        for depth in 0..20 {
            fixture.write(format!("deep/{depth}/next/leaf.txt"));
        }

        let serial = Walker::new(&fixture.root)
            .threads(1)
            .options(WalkOptions::default().sort(true))
            .collect()
            .expect("serial walk succeeds");
        let expected = relative_paths(serial.entries(), &fixture.root);
        for _ in 0..32 {
            let actual = Walker::new(&fixture.root)
                .threads(8)
                .options(WalkOptions::default().sort(true))
                .collect()
                .expect("parallel stress walk succeeds");
            assert_eq!(relative_paths(actual.entries(), &fixture.root), expected);
            assert!(actual.errors().is_empty());
        }
    }

    #[test]
    fn source_walk_metadata_preserves_portable_and_unix_fields() {
        // Ported from zlob/test/test_walk.zig's metadata scenario. Ferralk
        // exposes std::fs::Metadata directly instead of a validity bitset.
        let fixture = Fixture::new();
        fs::write(fixture.root.join("five.bin"), b"12345").expect("write metadata fixture");

        let without_metadata = Walker::new(&fixture.root)
            .options(WalkOptions::default().sort(true))
            .collect()
            .expect("walk succeeds");
        assert!(
            without_metadata
                .entries()
                .iter()
                .all(|entry| entry.metadata().is_none())
        );

        let with_metadata = Walker::new(&fixture.root)
            .options(WalkOptions::default().sort(true).metadata(true))
            .collect()
            .expect("walk succeeds");
        let metadata = with_metadata
            .entries()
            .iter()
            .find(|entry| entry.path().ends_with("five.bin"))
            .expect("fixture file is returned")
            .metadata()
            .expect("metadata is requested");
        assert_eq!(metadata.len(), 5);
        assert!(metadata.is_file());
        assert!(metadata.modified().is_ok());
        #[cfg(unix)]
        {
            use std::os::unix::fs::MetadataExt;

            assert_ne!(metadata.ino(), 0);
            assert_ne!(metadata.mode() & 0o400, 0);
        }
    }

    #[test]
    fn walk_entries_are_cloneable_with_their_metadata_snapshot() {
        let fixture = Fixture::new();
        fs::write(fixture.root.join("five.bin"), b"12345").expect("write clone fixture");

        let result = Walker::new(&fixture.root)
            .options(WalkOptions::default().sort(true).metadata(true))
            .collect()
            .expect("walk succeeds");
        let entry = result
            .entries()
            .iter()
            .find(|entry| entry.path().ends_with("five.bin"))
            .expect("fixture file is returned");
        let clone = entry.clone();

        assert_eq!(clone.path(), entry.path());
        assert_eq!(clone.root(), entry.root());
        assert_eq!(clone.kind(), entry.kind());
        assert_eq!(clone.depth(), entry.depth());
        assert_eq!(clone.metadata().map(fs::Metadata::len), Some(5));
    }

    #[test]
    fn root_gitignore_rules_and_negation_apply_to_collect_and_stream() {
        let fixture = Fixture::new();
        fixture.write("generated.tmp");
        fixture.write("keep.tmp");
        fixture.write("src/main.rs");
        fixture.write("src/keep.tmp");
        fixture.write("build/keep.txt");
        fs::write(
            fixture.root.join(".gitignore"),
            b"*.tmp\n!keep.tmp\nbuild/\n",
        )
        .expect("write root gitignore");
        fs::write(fixture.root.join("src/.gitignore"), b"!keep.tmp\n")
            .expect("write nested gitignore");
        fs::write(fixture.root.join("build/.gitignore"), b"!keep.txt\n")
            .expect("write nested re-include");

        let collected = Walker::new(&fixture.root)
            .respect_git_ignore(true)
            .options(WalkOptions::default().sort(true))
            .collect()
            .expect("walk succeeds");
        let collected_paths = relative_paths(collected.entries(), &fixture.root);
        assert!(!collected_paths.contains(&PathBuf::from("generated.tmp")));
        assert!(collected_paths.contains(&PathBuf::from("keep.tmp")));
        assert!(collected_paths.contains(&PathBuf::from("src/keep.tmp")));
        // `build/` is excluded, so Git never reads the ignore file inside it
        // and its negation never applies. The walker does the same.
        assert!(!collected_paths.contains(&PathBuf::from("build/keep.txt")));
        assert!(!collected_paths.contains(&PathBuf::from("build")));

        let streamed = Walker::new(&fixture.root)
            .respect_git_ignore(true)
            .stream()
            .collect::<Result<Vec<_>, _>>()
            .expect("stream has no I/O errors");
        let streamed_paths = relative_paths(&streamed, &fixture.root);
        assert!(!streamed_paths.contains(&PathBuf::from("generated.tmp")));
        assert!(streamed_paths.contains(&PathBuf::from("keep.tmp")));
        assert!(streamed_paths.contains(&PathBuf::from("src/keep.tmp")));
        assert!(!streamed_paths.contains(&PathBuf::from("build/keep.txt")));
        assert!(!streamed_paths.contains(&PathBuf::from("build")));
    }

    /// Starts a Git oracle process that is independent of the developer's
    /// global and system configuration, just like the corpus harness.
    fn git_command() -> Command {
        let mut command = Command::new("git");
        command
            .env("GIT_CONFIG_GLOBAL", "/dev/null")
            .env("GIT_CONFIG_SYSTEM", "/dev/null")
            .env("GIT_CONFIG_NOSYSTEM", "1");
        command
    }

    fn git_check_ignore(root: &Path, candidate: &str) -> bool {
        let status = git_command()
            .args(["check-ignore", "--no-index", "--quiet", "--", candidate])
            .current_dir(root)
            .status()
            .expect("run Git ignore oracle");
        match status.code() {
            Some(0) => true,
            Some(1) => false,
            other => panic!("git check-ignore failed with {other:?}"),
        }
    }

    fn git_config_bool(root: &Path, key: &str) -> bool {
        let output = git_command()
            .args(["config", "--type=bool", "--get", key])
            .current_dir(root)
            .output()
            .expect("run Git config boolean oracle");
        assert!(
            output.status.success(),
            "Git config boolean oracle failed: {}",
            String::from_utf8_lossy(&output.stderr)
        );
        match String::from_utf8(output.stdout)
            .expect("Git config boolean output is UTF-8")
            .trim()
        {
            "true" => true,
            "false" => false,
            value => panic!("unexpected Git config boolean output: {value:?}"),
        }
    }

    fn git_config_file_bool(config: &Path, key: &str) -> bool {
        let output = git_command()
            .args(["config", "--file"])
            .arg(config)
            .args(["--type=bool", "--get", key])
            .output()
            .expect("run Git config file boolean oracle");
        assert!(
            output.status.success(),
            "Git config file boolean oracle failed: {}",
            String::from_utf8_lossy(&output.stderr)
        );
        match String::from_utf8(output.stdout)
            .expect("Git config boolean output is UTF-8")
            .trim()
        {
            "true" => true,
            "false" => false,
            value => panic!("unexpected Git config boolean output: {value:?}"),
        }
    }

    #[test]
    fn git_oracle_ignores_an_inherited_global_excludes_file() {
        if let Some(root) = std::env::var_os(HOSTILE_GIT_CONFIG_FIXTURE) {
            let root = PathBuf::from(root);
            assert!(
                !git_check_ignore(&root, "unignored.log"),
                "the oracle must not read the hostile inherited excludes file"
            );
            return;
        }

        let fixture = Fixture::new();
        fixture.write("unignored.log");
        let initialized = git_command()
            .args(["init", "--quiet"])
            .current_dir(&fixture.root)
            .status()
            .expect("initialize hostile-config Git fixture");
        assert!(initialized.success());
        let excludes = fixture.root.join("hostile-excludes");
        fs::write(&excludes, b"*.log\n").expect("write hostile global excludes file");
        let config = fixture.root.join("hostile-gitconfig");
        let excludes = excludes.display().to_string();
        let excludes = excludes.replace('\\', "\\\\").replace('"', "\\\"");
        fs::write(
            &config,
            format!("[core]\n\texcludesFile = \"{excludes}\"\n"),
        )
        .expect("write hostile global Git config");

        // Environment mutation is process-global, so run a second copy of
        // this one test instead. It inherits the hostile config just as a
        // developer's test process would, while Git itself is still spawned
        // exclusively through `git_command`.
        let status = Command::new(std::env::current_exe().expect("locate test binary"))
            .args([
                "tests::git_oracle_ignores_an_inherited_global_excludes_file",
                "--exact",
            ])
            .env(HOSTILE_GIT_CONFIG_FIXTURE, &fixture.root)
            .env("GIT_CONFIG_GLOBAL", &config)
            .status()
            .expect("run isolated Git oracle regression test");
        assert!(
            status.success(),
            "hostile-config child test failed: {status}"
        );
    }

    #[test]
    fn repository_ignorecase_matches_git_for_rules_negation_and_anchors() {
        let fixture = Fixture::new();
        fs::create_dir_all(fixture.root.join(".git")).expect("create Git metadata");
        fs::write(
            fixture.root.join(".git/config"),
            b"[CoRe]\nignoreCase = YeS\n",
        )
        .expect("write local config");
        fs::write(
            fixture.root.join(".gitignore"),
            b"Build.LOG\nDist/\n!Kept.LOG\n/src/Anchored.LOG\n",
        )
        .expect("write ignore rules");
        for path in [
            "BUILD.log",
            "DIST/deep.txt",
            "kept.log",
            "SRC/ANCHORED.log",
            "other/ANCHORED.log",
        ] {
            fixture.write(path);
        }

        // The Git oracle is configured exactly as the repository is. This
        // catches the rule compilation, not merely a hand-written expectation.
        let initialized = git_command()
            .args(["init", "--quiet"])
            .current_dir(&fixture.root)
            .status()
            .expect("initialize Git oracle");
        assert!(initialized.success());
        let configured = git_command()
            .args(["config", "core.ignoreCase", "true"])
            .current_dir(&fixture.root)
            .status()
            .expect("configure Git oracle");
        assert!(configured.success());

        let serial = Walker::new(&fixture.root)
            .respect_git_ignore(true)
            .threads(1)
            .options(WalkOptions::default().sort(true))
            .collect()
            .expect("serial walk succeeds");
        let parallel = Walker::new(&fixture.root)
            .respect_git_ignore(true)
            .threads(4)
            .options(WalkOptions::default().sort(true))
            .collect()
            .expect("parallel walk succeeds");
        let streamed = Walker::new(&fixture.root)
            .respect_git_ignore(true)
            .stream()
            .collect::<Result<Vec<_>, _>>()
            .expect("stream succeeds");
        for paths in [
            relative_paths(serial.entries(), &fixture.root),
            relative_paths(parallel.entries(), &fixture.root),
            relative_paths(&streamed, &fixture.root),
        ] {
            for candidate in [
                "BUILD.log",
                "DIST/deep.txt",
                "kept.log",
                "SRC/ANCHORED.log",
                "other/ANCHORED.log",
            ] {
                assert_eq!(
                    !paths.contains(&PathBuf::from(candidate)),
                    git_check_ignore(&fixture.root, candidate),
                    "Ferralk must agree with Git for {candidate}",
                );
            }
        }
    }

    #[test]
    fn non_utf8_unrelated_config_value_does_not_hide_repository_ignorecase() {
        let fixture = Fixture::new();
        fixture.write("BUILD.log");
        fs::write(fixture.root.join(".gitignore"), b"build.log\n").expect("write rule");
        let initialized = git_command()
            .args(["init", "--quiet"])
            .current_dir(&fixture.root)
            .status()
            .expect("initialize Git oracle");
        assert!(initialized.success());
        fs::write(
            fixture.root.join(".git/config"),
            b"[user]\nname = Jos\xe9\n[core]\nignorecase = true\n",
        )
        .expect("write Latin-1 local config");

        assert!(git_config_bool(&fixture.root, "core.ignoreCase"));
        assert!(git_check_ignore(&fixture.root, "BUILD.log"));
        let walked = Walker::new(&fixture.root)
            .respect_git_ignore(true)
            .collect()
            .expect("walk with non-UTF-8 config");
        assert!(
            !relative_paths(walked.entries(), &fixture.root).contains(&PathBuf::from("BUILD.log")),
            "Ferralk must retain core.ignoreCase and agree with Git"
        );
    }

    #[test]
    fn explicit_ignorecase_false_and_walker_override_take_precedence() {
        let fixture = Fixture::new();
        fixture.write("BUILD.log");
        fs::create_dir_all(fixture.root.join(".git")).expect("create Git metadata");
        fs::write(
            fixture.root.join(".git/config"),
            b"[core]\nignorecase = true\nIGNORECASE = off\n",
        )
        .expect("write last-value local config");
        fs::write(fixture.root.join(".gitignore"), b"build.log\n").expect("write rule");

        let local_false = Walker::new(&fixture.root)
            .respect_git_ignore(true)
            .collect()
            .expect("walk local false");
        assert!(
            relative_paths(local_false.entries(), &fixture.root)
                .contains(&PathBuf::from("BUILD.log"))
        );

        let override_true = Walker::new(&fixture.root)
            .respect_git_ignore(true)
            .git_ignore_case(true)
            .collect()
            .expect("walk override true");
        assert!(
            !relative_paths(override_true.entries(), &fixture.root)
                .contains(&PathBuf::from("BUILD.log"))
        );

        let cleared = Walker::new(&fixture.root)
            .respect_git_ignore(true)
            .git_ignore_case(true)
            .clear_git_ignore_case()
            .collect()
            .expect("cleared override resumes local config");
        assert!(
            relative_paths(cleared.entries(), &fixture.root).contains(&PathBuf::from("BUILD.log")),
            "clearing an override restores the repository-local false value"
        );
    }

    #[test]
    fn numeric_and_empty_ignorecase_values_match_the_git_oracle() {
        let fixture = Fixture::new();
        fixture.write("BUILD.log");
        let initialized = git_command()
            .args(["init", "--quiet"])
            .current_dir(&fixture.root)
            .status()
            .expect("initialize Git oracle");
        assert!(initialized.success());
        fs::write(fixture.root.join(".gitignore"), b"build.log\n").expect("write rule");
        let config = fixture.root.join(".git/config");

        for (value, expected) in [
            ("", false),
            ("\"\"", false),
            ("+0", false),
            ("-0", false),
            ("+2", true),
            ("-7", true),
            ("  +2  # whitespace and comment", true),
        ] {
            fs::write(
                &config,
                format!("[core]\nignoreCase = {}\nIGNORECASE = {value}\n", !expected),
            )
            .expect("write duplicate config");
            assert_eq!(
                git_config_bool(&fixture.root, "core.ignoreCase"),
                expected,
                "Git must accept {value:?}",
            );
            let walked = Walker::new(&fixture.root)
                .respect_git_ignore(true)
                .collect()
                .expect("walk with Git boolean value");
            assert_eq!(
                !relative_paths(walked.entries(), &fixture.root)
                    .contains(&PathBuf::from("BUILD.log")),
                expected,
                "the later {value:?} value must override the earlier opposite value",
            );
        }

        fs::write(&config, b"[core]\nignoreCase = false\nIGNORECASE\n")
            .expect("write bare boolean config");
        assert!(git_config_bool(&fixture.root, "core.ignoreCase"));
        let bare_true = Walker::new(&fixture.root)
            .respect_git_ignore(true)
            .collect()
            .expect("walk with bare true");
        assert!(
            !relative_paths(bare_true.entries(), &fixture.root)
                .contains(&PathBuf::from("BUILD.log")),
            "a bare key must retain Git's true behavior"
        );

        fs::write(
            &config,
            b"[core]\nignoreCase = false\nIGNORECASE = t\\\nr\\\nue\n\
              [core \"unrelated\"]\nignoreCase = false\n",
        )
        .expect("write continued and subsection config");
        assert!(git_config_bool(&fixture.root, "core.ignoreCase"));
        let continued_true = Walker::new(&fixture.root)
            .respect_git_ignore(true)
            .collect()
            .expect("walk with continued boolean config");
        assert!(
            !relative_paths(continued_true.entries(), &fixture.root)
                .contains(&PathBuf::from("BUILD.log")),
            "a later subsection must not override the top-level continued true value"
        );
    }

    #[test]
    fn case_variant_ignore_file_follows_the_filesystem_canonical_open() {
        let fixture = Fixture::new();
        fixture.write("build.log");
        fs::write(fixture.root.join(".GITIGNORE"), b"build.log\n")
            .expect("write case variant ignore file");
        let canonical_open_resolves = fs::read(fixture.root.join(".gitignore")).is_ok();

        let walked = Walker::new(&fixture.root)
            .respect_git_ignore(true)
            .options(WalkOptions::default().sort(true))
            .collect()
            .expect("walk succeeds");
        let paths = relative_paths(walked.entries(), &fixture.root);
        assert!(paths.contains(&PathBuf::from(".GITIGNORE")));
        assert_eq!(
            !paths.contains(&PathBuf::from("build.log")),
            canonical_open_resolves,
            "a case variant is a rule file only if Git's canonical open resolves it"
        );
    }

    #[test]
    fn multi_root_walks_keep_each_repository_ignorecase_setting() {
        let fixture = Fixture::new();
        let nested = fixture.root.join("nested");
        fixture.write("nested/BUILD.log");
        fs::create_dir_all(fixture.root.join(".git")).expect("create outer Git metadata");
        fs::create_dir_all(nested.join(".git")).expect("create nested Git metadata");
        fs::write(
            fixture.root.join(".git/config"),
            b"[core]\nignorecase = true\n",
        )
        .expect("write outer config");
        fs::write(nested.join(".git/config"), b"[core]\nignorecase = false\n")
            .expect("write nested config");
        fs::write(fixture.root.join(".gitignore"), b"build.log\n").expect("write outer rule");
        fs::write(nested.join(".gitignore"), b"build.log\n").expect("write nested rule");

        let walked = Walker::new(&fixture.root)
            .add_root(&nested)
            .expect("add nested root")
            .add_root(&nested)
            .expect("add duplicate nested root")
            .respect_git_ignore(true)
            .collect()
            .expect("multi-root walk succeeds");
        let emitted = walked
            .entries()
            .iter()
            .filter(|entry| entry.path() == nested.join("BUILD.log"))
            .count();
        // The outer root folds and suppresses this entry. Each independent
        // nested root uses its explicit false setting and emits one copy.
        assert_eq!(emitted, 2);
    }

    #[test]
    fn try_add_root_keeps_the_builder_after_a_rejected_root() {
        let fixture = Fixture::new();
        let first_extra = fixture.root.clone();
        let last_extra = fixture.root.clone();
        let mut walker = Walker::new(&fixture.root)
            .include(fixture.absolute("/**"))
            .expect("absolute pattern applies to the first absolute root");

        walker
            .try_add_root(&first_extra)
            .expect("the absolute pattern applies to an equal root");
        let error = walker
            .try_add_root("relative-root")
            .expect_err("an absolute pattern needs an absolute added root");
        assert_eq!(
            error.message(),
            "an absolute pattern needs an absolute walk root"
        );
        assert_eq!(
            walker.roots().collect::<Vec<_>>(),
            vec![fixture.root.as_path(), first_extra.as_path()],
            "a rejected borrowed addition cannot partially append a root"
        );
        walker
            .try_add_root(&last_extra)
            .expect("the retained builder can consider later roots");
        assert_eq!(
            walker.roots().collect::<Vec<_>>(),
            vec![
                fixture.root.as_path(),
                first_extra.as_path(),
                last_extra.as_path(),
            ]
        );
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn repository_precomposeunicode_matches_the_macos_git_oracle() {
        let fixture = Fixture::new();
        let decomposed = "cafe\u{301}.txt";
        fs::write(fixture.root.join(".gitignore"), "caf\u{e9}.txt\n").expect("write NFC rule");
        fixture.write(decomposed);
        let initialized = git_command()
            .args(["init", "--quiet"])
            .current_dir(&fixture.root)
            .status()
            .expect("initialize Git oracle");
        assert!(initialized.success());
        let config = fixture.root.join(".git/config");
        fs::write(
            &config,
            b"[core]\nprecomposeUnicode = false\nPRECOMPOSEUNICODE = t\\\nr\\\nue\n\
              [core \"unrelated\"]\nprecomposeUnicode = false\n",
        )
        .expect("write continued precompose Unicode config");
        assert!(git_config_bool(&fixture.root, "core.precomposeUnicode"));

        assert!(git_check_ignore(&fixture.root, decomposed));
        let enabled = Walker::new(&fixture.root)
            .respect_git_ignore(true)
            .collect()
            .expect("walk with NFC adaptation");
        assert!(
            !relative_paths(enabled.entries(), &fixture.root).contains(&PathBuf::from(decomposed))
        );

        let forced_false = Walker::new(&fixture.root)
            .respect_git_ignore(true)
            .git_precompose_unicode(false)
            .collect()
            .expect("walk with explicit false override");
        assert!(
            relative_paths(forced_false.entries(), &fixture.root)
                .contains(&PathBuf::from(decomposed))
        );

        fs::write(
            &config,
            b"[core]\nprecomposeUnicode = \"\"\n\
              [core \"unrelated\"]\nprecomposeUnicode = true\n",
        )
        .expect("write empty precompose Unicode config");
        assert!(!git_config_bool(&fixture.root, "core.precomposeUnicode"));
        assert!(!git_check_ignore(&fixture.root, decomposed));
        let disabled = Walker::new(&fixture.root)
            .respect_git_ignore(true)
            .collect()
            .expect("walk without NFC adaptation");
        assert!(
            relative_paths(disabled.entries(), &fixture.root).contains(&PathBuf::from(decomposed))
        );

        let forced_true = Walker::new(&fixture.root)
            .respect_git_ignore(true)
            .git_precompose_unicode(true)
            .collect()
            .expect("walk with explicit true override");
        assert!(
            !relative_paths(forced_true.entries(), &fixture.root)
                .contains(&PathBuf::from(decomposed))
        );

        let cleared = Walker::new(&fixture.root)
            .respect_git_ignore(true)
            .git_precompose_unicode(true)
            .clear_git_precompose_unicode()
            .collect()
            .expect("cleared override resumes local config");
        assert!(
            relative_paths(cleared.entries(), &fixture.root).contains(&PathBuf::from(decomposed)),
            "clearing an override restores the repository-local false value"
        );
    }

    #[test]
    fn clearing_git_adaptation_overrides_restores_the_unset_state() {
        let walker = Walker::new("workspace")
            .git_ignore_case(true)
            .clear_git_ignore_case()
            .git_precompose_unicode(true)
            .clear_git_precompose_unicode();
        assert_eq!(walker.git_ignore_case, None);
        assert_eq!(walker.git_precompose_unicode, None);
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn source_walk_gitignore_matches_non_utf8_file_names_on_linux() {
        use std::os::unix::ffi::OsStringExt;

        let fixture = Fixture::new();
        let name = std::ffi::OsString::from_vec(b"\xE9latin1.txt".to_vec());
        fs::write(fixture.root.join(".gitignore"), b"\xE9latin1.txt\n")
            .expect("write byte-pattern gitignore");
        fixture.write(Path::new(&name));

        let ignored = fixture.root.join(&name);
        let result = Walker::new(&fixture.root)
            .respect_git_ignore(true)
            .collect()
            .expect("walk succeeds");
        assert!(
            !result
                .entries()
                .iter()
                .any(|entry| entry.path() == ignored.as_path()),
            "the byte-pattern rule has to hide its byte-named file"
        );
    }

    #[test]
    fn source_walk_nested_gitignore_overrides_and_skips_dot_git() {
        // Ported from zlob/test/test_walk.zig's nested Gitignore scenario.
        // Ferralk makes Gitignore application explicit at the Walker boundary.
        let fixture = Fixture::new();
        for path in [
            "build/artifact.o",
            "root.log",
            "keep.txt",
            "sub/important.log",
            "sub/other.log",
            "sub/temp/scratch.txt",
            ".git/config",
        ] {
            fixture.write(path);
        }
        fs::write(fixture.root.join(".gitignore"), b"*.log\nbuild/\n")
            .expect("write root gitignore");
        fs::write(
            fixture.root.join("sub/.gitignore"),
            b"!important.log\ntemp/\n",
        )
        .expect("write nested gitignore");

        let result = Walker::new(&fixture.root)
            .respect_git_ignore(true)
            .threads(1)
            .options(WalkOptions::default().sort(true))
            .collect()
            .expect("Gitignore walk succeeds");
        let paths = relative_paths(result.entries(), &fixture.root);
        for ignored in [
            "build",
            "build/artifact.o",
            "root.log",
            "sub/other.log",
            "sub/temp",
            "sub/temp/scratch.txt",
            ".git",
            ".git/config",
        ] {
            assert!(
                !paths.contains(&PathBuf::from(ignored)),
                "ignored source path {ignored} was returned"
            );
        }
        for kept in ["keep.txt", "sub", "sub/.gitignore", "sub/important.log"] {
            assert!(
                paths.contains(&PathBuf::from(kept)),
                "kept source path {kept} was omitted"
            );
        }

        let parallel = Walker::new(&fixture.root)
            .respect_git_ignore(true)
            .threads(4)
            .options(WalkOptions::default().sort(true))
            .collect()
            .expect("parallel Gitignore walk succeeds");
        assert_eq!(relative_paths(parallel.entries(), &fixture.root), paths);
        let mut streamed = Walker::new(&fixture.root)
            .respect_git_ignore(true)
            .stream()
            .collect::<Result<Vec<_>, _>>()
            .expect("stream Gitignore walk succeeds");
        streamed.sort_by(|left, right| left.path().cmp(right.path()));
        assert_eq!(relative_paths(&streamed, &fixture.root), paths);

        let without_ignore = Walker::new(&fixture.root)
            .threads(1)
            .options(WalkOptions::default().sort(true))
            .collect()
            .expect("unfiltered source walk succeeds");
        let unfiltered_paths = relative_paths(without_ignore.entries(), &fixture.root);
        assert!(unfiltered_paths.contains(&PathBuf::from(".git/config")));
        assert!(unfiltered_paths.len() > paths.len());
    }

    #[test]
    fn source_walk_ignore_file_overrides_gitignore_rules() {
        // Ported from zlob/test/test_walk.zig's reusable IgnoreRules scenario.
        let fixture = Fixture::new();
        for path in [
            "app.log",
            "keep.log",
            "scratch.tmp",
            "important.tmp",
            "old.bak",
            "src/main.rs",
            "src/old.bak",
            "build/artifact.txt",
        ] {
            fixture.write(path);
        }
        fs::write(
            fixture.root.join(".gitignore"),
            b"*.log\nbuild/\n!keep.log\n*.tmp\n",
        )
        .expect("write root gitignore");
        fs::write(fixture.root.join(".ignore"), b"!important.tmp\n")
            .expect("write root ignore supplement");
        fs::write(fixture.root.join("src/.gitignore"), b"*.bak\n").expect("write nested gitignore");

        let expected = vec![
            PathBuf::from(".gitignore"),
            PathBuf::from(".ignore"),
            PathBuf::from("important.tmp"),
            PathBuf::from("keep.log"),
            PathBuf::from("old.bak"),
            PathBuf::from("src"),
            PathBuf::from("src/.gitignore"),
            PathBuf::from("src/main.rs"),
        ];
        let options = WalkOptions::default().sort(true);
        let serial = Walker::new(&fixture.root)
            .respect_git_ignore(true)
            .threads(1)
            .options(options)
            .collect()
            .expect("serial ignore walk succeeds");
        let parallel = Walker::new(&fixture.root)
            .respect_git_ignore(true)
            .threads(4)
            .options(options)
            .collect()
            .expect("parallel ignore walk succeeds");
        let mut streamed = Walker::new(&fixture.root)
            .respect_git_ignore(true)
            .options(options)
            .stream()
            .collect::<Result<Vec<_>, _>>()
            .expect("stream ignore walk succeeds");
        streamed.sort_by(|left, right| left.path().cmp(right.path()));

        assert_eq!(relative_paths(serial.entries(), &fixture.root), expected);
        assert_eq!(relative_paths(parallel.entries(), &fixture.root), expected);
        assert_eq!(relative_paths(&streamed, &fixture.root), expected);
    }

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

        for ignore_file in [".gitignore", ".ignore"] {
            let fixture = Fixture::new();
            fixture.write("linked.tmp");
            fs::write(fixture.root.join("rules-source"), b"linked.tmp\n")
                .expect("write linked ignore source");
            symlink("rules-source", fixture.root.join(ignore_file))
                .expect("create linked in-tree ignore file");

            let result = Walker::new(&fixture.root)
                .respect_git_ignore(true)
                .options(WalkOptions::default().sort(true))
                .collect()
                .expect("walk succeeds when a linked ignore file is refused");
            assert!(
                relative_paths(result.entries(), &fixture.root)
                    .contains(&PathBuf::from("linked.tmp")),
                "{ignore_file} must not redirect in-tree rules through its target"
            );
        }

        let fixture = Fixture::new();
        fixture.write("repository-only.tmp");
        fs::write(fixture.root.join("rules-source"), b"repository-only.tmp\n")
            .expect("write repository exclude source");
        fs::create_dir_all(fixture.root.join(".git/info")).expect("create git info directory");
        symlink("../../rules-source", fixture.root.join(".git/info/exclude"))
            .expect("link repository exclude");

        let result = Walker::new(&fixture.root)
            .respect_git_ignore(true)
            .collect()
            .expect("walk succeeds when repository exclude is linked");
        assert!(
            !relative_paths(result.entries(), &fixture.root)
                .contains(&PathBuf::from("repository-only.tmp")),
            ".git/info/exclude remains allowed to follow links"
        );
    }

    #[test]
    fn linked_worktree_and_submodule_gitdir_pointers_read_the_right_info_exclude() {
        let fixture = Fixture::new();

        // This is the shape `git worktree add` writes: the checkout's `.git`
        // points at a private worktree directory, whose `commondir` points
        // back at the main repository's `.git` directory.
        let worktree = fixture.root.join("linked-worktree");
        let common_git = fixture.root.join("main/.git");
        let private_git = common_git.join("worktrees/linked-worktree");
        fs::create_dir_all(private_git.join("refs")).expect("create private git directory");
        fs::create_dir_all(common_git.join("info")).expect("create common git info");
        fs::write(common_git.join("info/exclude"), b"worktree-secret.txt\n")
            .expect("write common exclude");
        fs::write(private_git.join("commondir"), b"../..\n").expect("write commondir");
        fs::create_dir_all(&worktree).expect("create linked worktree");
        fs::write(
            worktree.join(".git"),
            b"gitdir: ../main/.git/worktrees/linked-worktree\n",
        )
        .expect("write linked-worktree pointer");
        fs::write(worktree.join("worktree-secret.txt"), b"fixture")
            .expect("write linked-worktree secret");

        let worktree_result = Walker::new(&worktree)
            .respect_git_ignore(true)
            .collect()
            .expect("walk linked worktree");
        assert!(
            !relative_paths(worktree_result.entries(), &worktree)
                .contains(&PathBuf::from("worktree-secret.txt")),
            "the linked worktree must use its common info/exclude"
        );

        // A submodule has the same pointer-file form but normally points
        // directly at `.git/modules/<name>` with no `commondir` file.
        let submodule = fixture.root.join("super/dependency");
        let submodule_git = fixture.root.join("super/.git/modules/dependency");
        fs::create_dir_all(submodule_git.join("info")).expect("create submodule git info");
        fs::write(
            submodule_git.join("info/exclude"),
            b"submodule-secret.txt\n",
        )
        .expect("write submodule exclude");
        fs::create_dir_all(&submodule).expect("create submodule checkout");
        fs::write(
            submodule.join(".git"),
            b"gitdir: ../.git/modules/dependency\n",
        )
        .expect("write submodule pointer");
        fs::write(submodule.join("submodule-secret.txt"), b"fixture")
            .expect("write submodule secret");

        let submodule_result = Walker::new(&submodule)
            .respect_git_ignore(true)
            .collect()
            .expect("walk submodule checkout");
        assert!(
            !relative_paths(submodule_result.entries(), &submodule)
                .contains(&PathBuf::from("submodule-secret.txt")),
            "the submodule pointer must use its own info/exclude"
        );
    }

    #[test]
    fn linked_worktree_config_overrides_the_common_repository_setting() {
        let fixture = Fixture::new();
        let checkout = fixture.root.join("linked-worktree");
        let common_git = fixture.root.join("main/.git");
        let private_git = common_git.join("worktrees/linked-worktree");
        fs::create_dir_all(&checkout).expect("create linked checkout");
        fs::create_dir_all(&private_git).expect("create private Git directory");
        fs::write(private_git.join("commondir"), b"../..\n").expect("write commondir");
        fs::create_dir_all(&common_git).expect("create common Git directory");
        fs::write(
            common_git.join("config"),
            b"[extensions]\nworktreeConfig = f\\\nalse\nWORKTREECONFIG = t\\\nr\\\nue\n\
              [extensions \"unrelated\"]\nworktreeConfig = false\n\
              [core]\nignorecase = false\n",
        )
        .expect("write continued common config");
        fs::write(
            private_git.join("config.worktree"),
            b"[CORE]\nignoreCASE = t\\\nr\\\nue\n\
              [core \"unrelated\"]\nignoreCASE = false\n",
        )
        .expect("write continued private worktree config");
        fs::write(
            checkout.join(".git"),
            b"gitdir: ../main/.git/worktrees/linked-worktree\n",
        )
        .expect("write worktree pointer");
        fs::write(checkout.join(".gitignore"), b"build.log\n").expect("write ignore rule");
        fs::write(checkout.join("BUILD.log"), b"fixture").expect("write mixed-case candidate");

        assert!(git_config_file_bool(
            &common_git.join("config"),
            "extensions.worktreeConfig"
        ));

        let walked = Walker::new(&checkout)
            .respect_git_ignore(true)
            .collect()
            .expect("walk linked worktree");
        assert!(
            !relative_paths(walked.entries(), &checkout).contains(&PathBuf::from("BUILD.log")),
            "private config.worktree must win after the common config"
        );
    }

    #[test]
    fn absolute_and_malformed_gitdir_pointers_are_handled_without_rules() {
        let fixture = Fixture::new();
        let checkout = fixture.root.join("absolute-worktree");
        let git_directory = fixture.root.join("separate-git-directory");
        fs::create_dir_all(git_directory.join("info")).expect("create separate git info");
        fs::write(git_directory.join("info/exclude"), b"absolute-secret.txt\n")
            .expect("write absolute exclude");
        fs::create_dir_all(&checkout).expect("create absolute checkout");
        fs::write(
            checkout.join(".git"),
            format!("gitdir: {}\n", git_directory.display()),
        )
        .expect("write absolute pointer");
        fs::write(checkout.join("absolute-secret.txt"), b"fixture").expect("write absolute secret");

        let absolute_result = Walker::new(&checkout)
            .respect_git_ignore(true)
            .collect()
            .expect("walk absolute pointer checkout");
        assert!(
            !relative_paths(absolute_result.entries(), &checkout)
                .contains(&PathBuf::from("absolute-secret.txt"))
        );

        let malformed = fixture.root.join("malformed-pointer");
        fs::create_dir_all(&malformed).expect("create malformed checkout");
        fs::write(malformed.join(".git"), b"gitdir: \nextra data\n")
            .expect("write malformed pointer");
        fs::write(malformed.join("not-excluded.txt"), b"fixture")
            .expect("write malformed candidate");
        let malformed_result = Walker::new(&malformed)
            .respect_git_ignore(true)
            .collect()
            .expect("malformed metadata is skipped");
        assert!(
            relative_paths(malformed_result.entries(), &malformed)
                .contains(&PathBuf::from("not-excluded.txt")),
            "a malformed pointer must add no repository rules"
        );
    }

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

        let fixture = Fixture::new();
        let checkout = fixture.root.join("unreadable-pointer");
        fs::create_dir_all(&checkout).expect("create checkout");
        let pointer = checkout.join(".git");
        fs::write(&pointer, b"gitdir: ../missing-git-directory\n").expect("write pointer file");
        fs::write(checkout.join("not-excluded.txt"), b"fixture").expect("write candidate");

        let original_permissions = fs::metadata(&pointer)
            .expect("read pointer metadata")
            .permissions();
        fs::set_permissions(&pointer, fs::Permissions::from_mode(0o000))
            .expect("make pointer unreadable");
        if fs::read(&pointer).is_ok() {
            // A privileged test process can bypass mode bits. There is no
            // portable way to arrange an unreadable regular file for it.
            fs::set_permissions(&pointer, original_permissions)
                .expect("restore pointer permissions");
            return;
        }

        let result = Walker::new(&checkout)
            .respect_git_ignore(true)
            .collect()
            .expect("unreadable metadata is skipped rather than reported");
        fs::set_permissions(&pointer, original_permissions).expect("restore pointer permissions");

        assert!(
            result.errors().is_empty(),
            "unreadable repository metadata follows the existing silent policy"
        );
        assert!(
            relative_paths(result.entries(), &checkout)
                .contains(&PathBuf::from("not-excluded.txt")),
            "an unreadable pointer must add no repository rules"
        );
    }

    #[test]
    fn nested_repositories_remain_traversed_with_the_outer_ignore_chain() {
        let fixture = Fixture::new();
        fixture.write("nested/.git/config");
        fixture.write("nested/outer.tmp");
        fixture.write("nested/keep.tmp");
        fixture.write("nested/inner-only.tmp");
        fs::write(fixture.root.join(".gitignore"), b"*.tmp\n").expect("write outer ignore rules");
        fs::write(
            fixture.root.join("nested/.gitignore"),
            b"!keep.tmp\ninner-only.tmp\n",
        )
        .expect("write nested repository rules");

        let result = Walker::new(&fixture.root)
            .respect_git_ignore(true)
            .options(WalkOptions::default().sort(true))
            .collect()
            .expect("walk nested repository");
        let paths = relative_paths(result.entries(), &fixture.root);
        assert!(paths.contains(&PathBuf::from("nested/keep.tmp")));
        assert!(!paths.contains(&PathBuf::from("nested/outer.tmp")));
        assert!(!paths.contains(&PathBuf::from("nested/inner-only.tmp")));
        assert!(
            !paths.contains(&PathBuf::from("nested/.git/config")),
            "the nested repository's control directory remains skipped"
        );
    }

    #[test]
    fn source_walk_allowlist_gitignore_descends_into_reincluded_directories() {
        // Ported from zlob/test/test_walk.zig's allowlist Gitignore regression.
        let fixture = Fixture::new();
        for path in [
            "main.rs",
            "Makefile",
            ".keep",
            "src/lib.rs",
            "src/noext",
            "src/deep/a.txt",
            "dir.d/x.md",
            "dir.d/noext",
            "plain/y.txt",
            ".git/config",
        ] {
            fixture.write(path);
        }
        fs::write(
            fixture.root.join(".gitignore"),
            b"# Ignore all\n*\n\n# Unignore all with extensions\n!*.*\n\n# Unignore all dirs\n!/**/\n",
        )
        .expect("write root gitignore");

        let expected = vec![
            PathBuf::from(".gitignore"),
            PathBuf::from(".keep"),
            PathBuf::from("dir.d"),
            PathBuf::from("dir.d/x.md"),
            PathBuf::from("main.rs"),
            PathBuf::from("plain"),
            PathBuf::from("plain/y.txt"),
            PathBuf::from("src"),
            PathBuf::from("src/deep"),
            PathBuf::from("src/deep/a.txt"),
            PathBuf::from("src/lib.rs"),
        ];
        let options = WalkOptions::default().sort(true);
        let serial = Walker::new(&fixture.root)
            .respect_git_ignore(true)
            .threads(1)
            .options(options)
            .collect()
            .expect("serial Gitignore walk succeeds");
        let parallel = Walker::new(&fixture.root)
            .respect_git_ignore(true)
            .threads(4)
            .options(options)
            .collect()
            .expect("parallel Gitignore walk succeeds");
        let mut streamed = Walker::new(&fixture.root)
            .respect_git_ignore(true)
            .options(options)
            .stream()
            .collect::<Result<Vec<_>, _>>()
            .expect("stream Gitignore walk succeeds");
        streamed.sort_by(|left, right| left.path().cmp(right.path()));

        assert_eq!(relative_paths(serial.entries(), &fixture.root), expected);
        assert_eq!(relative_paths(parallel.entries(), &fixture.root), expected);
        assert_eq!(relative_paths(&streamed, &fixture.root), expected);
    }

    /// The ignore chain travels with the directory tasks, so no directory is
    /// read twice however many workers share the walk.
    #[test]
    fn every_ignore_file_is_read_once_per_walk() {
        let fixture = Fixture::new();
        fixture.write(".gitignore");
        fixture.write("src/.gitignore");
        fixture.write("src/nested/.gitignore");
        for branch in 0..6 {
            fixture.write(format!("src/nested/branch-{branch}/leaf.txt"));
            fixture.write(format!("docs/branch-{branch}/leaf.md"));
        }

        for threads in [1, 4] {
            let backend = CountingBackend::default();
            Walker::new(&fixture.root)
                .threads(threads)
                .respect_git_ignore(true)
                .collect_with(&backend)
                .expect("walk succeeds");

            let repeated = backend
                .ignore_reads()
                .into_iter()
                .filter(|(_, reads)| *reads > 1)
                .collect::<Vec<_>>();
            assert!(
                repeated.is_empty(),
                "with {threads} threads these ignore files were read more than once: {repeated:?}"
            );
            assert!(
                backend
                    .ignore_reads()
                    .iter()
                    .any(|(path, _)| path.ends_with("src/.gitignore")),
                "the walk has to read the nested ignore files through the backend"
            );
        }
    }

    #[test]
    fn oversized_ignore_files_follow_the_configured_error_policy() {
        let fixture = Fixture::new();
        fixture.write("visible.txt");
        let ignore_path = fixture.root.join(".gitignore");
        let ignore_file = fs::File::create(&ignore_path).expect("create oversized ignore file");
        ignore_file
            .set_len(super::MAX_IGNORE_FILE_BYTES + 1)
            .expect("size oversized ignore file");

        for threads in [1, 4] {
            let result = Walker::new(&fixture.root)
                .respect_git_ignore(true)
                .threads(threads)
                .error_policy(ErrorPolicy::Collect)
                .collect()
                .expect("collect policy keeps walking");
            assert_eq!(result.errors().len(), 1);
            assert_eq!(result.errors()[0].operation(), "read_ignore");
            assert_eq!(result.errors()[0].path(), ignore_path);
            assert!(
                relative_paths(result.entries(), &fixture.root)
                    .contains(&PathBuf::from("visible.txt")),
                "an unreadable rule file cannot silently hide unrelated entries"
            );
        }

        let skipped = Walker::new(&fixture.root)
            .respect_git_ignore(true)
            .threads(1)
            .error_policy(ErrorPolicy::Skip)
            .collect()
            .expect("skip policy keeps walking");
        assert!(skipped.errors().is_empty());

        let aborted = Walker::new(&fixture.root)
            .respect_git_ignore(true)
            .threads(1)
            .error_policy(ErrorPolicy::Abort)
            .collect()
            .expect_err("abort policy reports the ignore failure immediately");
        assert_eq!(aborted.operation(), "read_ignore");
        assert_eq!(aborted.path(), ignore_path);

        let streamed = Walker::new(&fixture.root)
            .respect_git_ignore(true)
            .error_policy(ErrorPolicy::Collect)
            .stream()
            .collect::<Vec<_>>();
        assert_eq!(
            streamed.iter().filter(|item| item.is_err()).count(),
            1,
            "the stream yields the ignore failure exactly once"
        );
        assert!(streamed.iter().any(|item| {
            item.as_ref()
                .is_ok_and(|entry| entry.path().ends_with("visible.txt"))
        }));
    }

    /// The chain is rebuilt per directory now, so a rule at the root still has
    /// to reach an entry several levels down, and a rule closer to the entry
    /// still has to win.
    #[test]
    fn root_rules_reach_deep_entries_and_deeper_rules_win() {
        let fixture = Fixture::new();
        fixture.write("a/b/c/deep.log");
        fixture.write("a/b/other.log");
        fixture.write("a/b/c/keep.txt");
        fs::write(fixture.root.join(".gitignore"), b"*.log\n").expect("write root gitignore");
        fs::write(fixture.root.join("a/b/c/.gitignore"), b"!deep.log\n")
            .expect("write nested gitignore");

        let walked = Walker::new(&fixture.root)
            .respect_git_ignore(true)
            .options(WalkOptions::default().sort(true))
            .collect()
            .expect("walk succeeds");
        let paths = relative_paths(walked.entries(), &fixture.root);

        assert!(
            !paths.contains(&PathBuf::from("a/b/other.log")),
            "a root rule has to reach entries below it"
        );
        assert!(
            paths.contains(&PathBuf::from("a/b/c/deep.log")),
            "the ignore file closest to the entry decides"
        );
        assert!(paths.contains(&PathBuf::from("a/b/c/keep.txt")));
    }

    /// Directory-only rules and rules that span levels have to behave the same
    /// however the entry is reached.
    #[test]
    fn directory_rules_and_spanning_rules_apply_per_directory() {
        let fixture = Fixture::new();
        fixture.write("logs");
        fixture.write("build/main.o");
        fixture.write("a/b/temp/c/note.txt");
        fixture.write("a/b/kept.txt");
        fs::write(
            fixture.root.join(".gitignore"),
            b"logs/\nbuild/\n**/temp/**\n",
        )
        .expect("write root gitignore");

        let walked = Walker::new(&fixture.root)
            .respect_git_ignore(true)
            .options(WalkOptions::default().sort(true))
            .collect()
            .expect("walk succeeds");
        let paths = relative_paths(walked.entries(), &fixture.root);

        assert!(
            paths.contains(&PathBuf::from("logs")),
            "a directory-only rule must not match a file of the same name"
        );
        assert!(!paths.contains(&PathBuf::from("build")));
        assert!(!paths.contains(&PathBuf::from("build/main.o")));
        assert!(!paths.contains(&PathBuf::from("a/b/temp/c/note.txt")));
        assert!(paths.contains(&PathBuf::from("a/b/kept.txt")));
    }

    /// Each frontend now builds the ignore chain along its own descent, so the
    /// three have to agree on a tree that exercises it.
    #[test]
    fn the_three_frontends_agree_on_nested_ignore_files() {
        let fixture = Fixture::new();
        fixture.write("src/main.rs");
        fixture.write("src/debug.log");
        fixture.write("src/keep.log");
        fixture.write("src/nested/deep.log");
        fixture.write("docs/guide.md");
        fixture.write("build/main.o");
        fixture.write("build/keep.txt");
        fs::write(fixture.root.join(".gitignore"), b"*.log\nbuild/\n")
            .expect("write root gitignore");
        fs::write(fixture.root.join("src/.gitignore"), b"!keep.log\n")
            .expect("write nested gitignore");
        fs::write(fixture.root.join("build/.gitignore"), b"!keep.txt\n").expect("write re-include");
        fs::create_dir_all(fixture.root.join(".git/info")).expect("create git directory");
        fs::write(fixture.root.join(".git/info/exclude"), b"*.md\n")
            .expect("write repository excludes");

        assert_frontends_agree("nested ignore files", &fixture.root, || {
            Walker::new(&fixture.root).respect_git_ignore(true)
        });

        let walked = Walker::new(&fixture.root)
            .respect_git_ignore(true)
            .options(WalkOptions::default().sort(true))
            .collect()
            .expect("walk succeeds");
        let paths = relative_paths(walked.entries(), &fixture.root);
        assert!(
            !paths.contains(&PathBuf::from("docs/guide.md")),
            "the repository excludes have to apply"
        );
        assert!(paths.contains(&PathBuf::from("src/keep.log")));
        assert!(!paths.contains(&PathBuf::from("src/nested/deep.log")));
    }

    /// Git-verified ignore cases the walker does not reproduce yet.
    ///
    /// Empty since ADR-0014: the last entry was `ignore-034`, a POSIX class
    /// name in a rule, which the borrowed matcher could not read and the
    /// walker's own rule layer does. A case belongs here only while Git and
    /// the walker are known to disagree, never as a way to quiet a failure.
    const KNOWN_WALKER_GAPS: &[&str] = &[];

    #[test]
    fn git_ignore_corpus_replays_through_the_walker() {
        let corpus_path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus/ignore.jsonl");
        for line in fs::read_to_string(corpus_path)
            .expect("read ignore corpus")
            .lines()
            .filter(|line| !line.trim().is_empty())
        {
            let case: corpus::Case = serde_json::from_str(line).expect("valid ignore corpus case");
            if KNOWN_WALKER_GAPS.contains(&case.id.as_str()) {
                continue;
            }
            let fixture = Fixture::new();
            fs::write(
                fixture.root.join(".gitignore"),
                case.ignore_rules.join("\n").as_bytes(),
            )
            .expect("write fixture gitignore");
            // A case may place further ignore files below the root; Git reads
            // the one closest to the candidate last, and so does the walker.
            for nested in &case.nested_ignore_rules {
                let directory = fixture.root.join(&nested.directory);
                fs::create_dir_all(&directory).expect("create nested ignore directory");
                fs::write(
                    directory.join(".gitignore"),
                    nested.rules.join("\n").as_bytes(),
                )
                .expect("write nested fixture gitignore");
            }
            // Repository-wide excludes live outside the ignore file chain.
            if !case.exclude_rules.is_empty() {
                let info = fixture.root.join(".git/info");
                fs::create_dir_all(&info).expect("create repository info directory");
                fs::write(
                    info.join("exclude"),
                    case.exclude_rules.join("\n").as_bytes(),
                )
                .expect("write repository excludes");
            }
            fixture.write(&case.path);

            let result = Walker::new(&fixture.root)
                .respect_git_ignore(true)
                .collect()
                .expect("walk succeeds");
            let returned =
                relative_paths(result.entries(), &fixture.root).contains(&PathBuf::from(case.path));
            assert_eq!(
                !returned, case.expected,
                "walker verdict for corpus case {}",
                case.id
            );
        }
    }

    /// Both prefilters are derived from the expanded alternatives, and both go
    /// quiet as soon as one alternative cannot contribute a value.
    #[test]
    fn brace_alternatives_carry_the_planner_prefilters() {
        let sources = traversal_pattern(b"**/*.{ts,tsx}");
        assert!(sources.matches_extension(b"src/app.ts"));
        assert!(sources.matches_extension(b"src/app.tsx"));
        assert!(!sources.matches_extension(b"src/app.js"));
        assert!(!sources.matches_extension(b"src/app"));

        let scoped = traversal_pattern(b"{src,lib}/**/*.ts");
        assert!(scoped.could_match_descendant(b"src"));
        assert!(scoped.could_match_descendant(b"lib"));
        assert!(scoped.could_match_descendant(b"src/nested"));
        assert!(!scoped.could_match_descendant(b"docs"));
        assert!(!scoped.could_match_descendant(b"node_modules"));

        let nested = traversal_pattern(b"{src/{a,b},lib}/**");
        assert!(nested.could_match_descendant(b"src"));
        assert!(nested.could_match_descendant(b"src/a"));
        assert!(!nested.could_match_descendant(b"src/c"));

        // One alternative without a literal root, or without a literal
        // extension, switches the whole prefilter off rather than pruning what
        // that alternative could still match.
        let partial_root = traversal_pattern(b"{src,*}/**/*.ts");
        assert!(partial_root.could_match_descendant(b"docs"));
        let partial_extension = traversal_pattern(b"**/*.{ts,*}");
        assert!(partial_extension.matches_extension(b"src/app.js"));
    }

    /// The planner prefilters are literal prefixes and literal extensions, so
    /// `match_hidden` changes what the matcher accepts without changing what
    /// the planner is allowed to prune.
    #[test]
    fn match_hidden_widens_the_matcher_without_moving_the_planner_prefilters() {
        let hidden = traversal_pattern_options(true);
        let scoped = TraversalPattern::compile(b"site/**/*.ts", hidden).expect("valid include");
        assert!(scoped.could_match_descendant(b"site/.react-router"));
        assert!(scoped.matches(
            b"site/.react-router/routes.ts",
            false,
            WildcardMode::ComponentScoped
        ));
        assert!(scoped.matches_extension(b"site/.react-router/routes.ts"));
        assert!(!scoped.could_match_descendant(b".react-router"));

        // Same pattern, same prefilters, and only the matcher verdict differs.
        let default = traversal_pattern(b"site/**/*.ts");
        assert!(default.could_match_descendant(b"site/.react-router"));
        assert!(!default.matches(
            b"site/.react-router/routes.ts",
            false,
            WildcardMode::ComponentScoped
        ));
        assert_eq!(default.literal_roots, scoped.literal_roots);
        assert_eq!(default.extensions, scoped.extensions);

        // A hidden literal root is its own prefilter under either setting: a
        // literal period is not a wildcard.
        let literal = TraversalPattern::compile(b".claude/**/*.ts", hidden).expect("valid include");
        assert!(literal.could_match_descendant(b".claude"));
        assert!(traversal_pattern(b".claude/**/*.ts").matches(
            b".claude/agents/run.ts",
            false,
            WildcardMode::ComponentScoped
        ));
    }

    /// The option and the patterns are set in either order, so a builder that
    /// enables it last still compiles every pattern under it.
    #[test]
    fn match_hidden_applies_to_patterns_added_before_and_after_it() {
        let fixture = Fixture::new();
        fixture.write(".react-router/types.ts");
        fixture.write("src/app.ts");

        let walk = |walker: Walker| {
            relative_paths(
                walker
                    .options(WalkOptions::default().sort(true))
                    .collect()
                    .expect("walk succeeds")
                    .entries(),
                &fixture.root,
            )
        };
        let before = walk(
            Walker::new(&fixture.root)
                .match_hidden(true)
                .include("**/*.ts")
                .expect("valid include"),
        );
        let after = walk(
            Walker::new(&fixture.root)
                .include("**/*.ts")
                .expect("valid include")
                .match_hidden(true),
        );
        assert_eq!(
            before,
            vec![
                PathBuf::from(".react-router/types.ts"),
                PathBuf::from("src/app.ts"),
            ]
        );
        assert_eq!(after, before);

        // And switching it back off returns the default verdict.
        assert_eq!(
            walk(
                Walker::new(&fixture.root)
                    .match_hidden(true)
                    .include("**/*.ts")
                    .expect("valid include")
                    .match_hidden(false),
            ),
            vec![PathBuf::from("src/app.ts")]
        );
    }

    /// The planner expands before it compiles, so a pattern the expansion
    /// itself rejects has to reach the caller as that rejection.
    #[test]
    fn an_unexpandable_include_is_reported_as_a_pattern_error() {
        let beyond = "{a,b}".repeat(13);
        let error = Walker::new(".")
            .include(&beyond)
            .expect_err("the expansion budget rejects this pattern");
        assert_eq!(error.message(), "too many brace alternatives");
        assert_eq!(
            error.offset(),
            ferralk_glob::Pattern::compile(&beyond, traversal_pattern_options(false))
                .expect_err("the matcher rejects it the same way")
                .offset()
        );
    }

    /// A braced include may return exactly what its alternatives return
    /// together: the prefilters must not narrow that, and must not widen it.
    #[test]
    fn a_brace_include_returns_the_union_of_its_alternatives() {
        let fixture = Fixture::new();
        fixture.write("src/app.ts");
        fixture.write("src/app.tsx");
        fixture.write("src/app.js");
        fixture.write("src/nested/deep.ts");
        fixture.write("lib/util.ts");
        fixture.write("lib/util.rs");
        fixture.write("docs/guide.md");
        fixture.write("docs/nested/notes.md");
        fixture.write("node_modules/pkg/index.ts");

        let walk = |pattern: &str| -> Vec<PathBuf> {
            let result = Walker::new(&fixture.root)
                .include(pattern)
                .expect("valid include")
                .options(WalkOptions::default().sort(true))
                .collect()
                .expect("walk succeeds");
            relative_paths(result.entries(), &fixture.root)
        };

        for pattern in [
            "**/*.{ts,tsx}",
            "{src,lib}/**/*.ts",
            "{src,docs}/**",
            "src/{app,nested}*",
            "{src,lib}/**/*.{ts,rs}",
        ] {
            let alternatives =
                ferralk_glob::expand_braces(pattern, traversal_pattern_options(false))
                    .expect("expandable pattern");
            let mut union = alternatives
                .iter()
                .flat_map(|alternative| {
                    walk(std::str::from_utf8(alternative).expect("ASCII fixture pattern"))
                })
                .collect::<Vec<_>>();
            union.sort_unstable();
            union.dedup();
            assert_eq!(walk(pattern), union, "{pattern}");
        }
    }

    /// The two readings, through the walker rather than the matcher.
    ///
    /// This is the whole point of the option: a pattern carried over from
    /// `globset` selects what it selected there.
    #[test]
    fn the_wildcard_mode_decides_how_far_a_wildcard_reaches() {
        let fixture = Fixture::new();
        fixture.write("main.ts");
        fixture.write("src/app.ts");
        fixture.write("src/deep/nested.ts");
        fixture.write("other/stray.ts");

        let walk = |mode: WildcardMode, pattern: &str| -> Vec<PathBuf> {
            let result = Walker::new(&fixture.root)
                .wildcard_mode(mode)
                .include(pattern)
                .expect("valid include")
                .options(WalkOptions::default().sort(true).files_only(true))
                .collect()
                .expect("walk succeeds");
            relative_paths(result.entries(), &fixture.root)
        };

        assert_eq!(
            walk(WildcardMode::ComponentScoped, "*.ts"),
            vec![PathBuf::from("main.ts")],
            "the default keeps a wildcard inside its component"
        );
        assert_eq!(
            walk(WildcardMode::SeparatorCrossing, "*.ts"),
            vec![
                PathBuf::from("main.ts"),
                PathBuf::from("other/stray.ts"),
                PathBuf::from("src/app.ts"),
                PathBuf::from("src/deep/nested.ts"),
            ],
            "crossing reads the pattern the way globset does"
        );

        // A literal prefix still holds under crossing, which is what keeps the
        // planner allowed to prune on it.
        assert_eq!(
            walk(WildcardMode::SeparatorCrossing, "src/*.ts"),
            vec![
                PathBuf::from("src/app.ts"),
                PathBuf::from("src/deep/nested.ts")
            ],
            "crossing reaches below the prefix, never outside it"
        );
        assert_eq!(
            walk(WildcardMode::ComponentScoped, "src/*.ts"),
            vec![PathBuf::from("src/app.ts")]
        );
    }

    /// Excludes are read the same way as includes, so one mode governs the
    /// whole walk rather than half of it.
    #[test]
    fn the_wildcard_mode_governs_excludes_too() {
        let fixture = Fixture::new();
        fixture.write("keep.rs");
        fixture.write("drop.tmp");
        fixture.write("src/drop.tmp");

        let walk = |mode: WildcardMode| -> Vec<PathBuf> {
            let result = Walker::new(&fixture.root)
                .wildcard_mode(mode)
                .exclude("*.tmp")
                .expect("valid exclude")
                .options(WalkOptions::default().sort(true).files_only(true))
                .collect()
                .expect("walk succeeds");
            relative_paths(result.entries(), &fixture.root)
        };

        assert_eq!(
            walk(WildcardMode::ComponentScoped),
            vec![PathBuf::from("keep.rs"), PathBuf::from("src/drop.tmp")],
            "a component-scoped exclude only reaches the root component"
        );
        assert_eq!(
            walk(WildcardMode::SeparatorCrossing),
            vec![PathBuf::from("keep.rs")],
            "a crossing exclude reaches every level"
        );
    }

    /// How far a wildcard reaches and whether it may reach a dot-leading name
    /// are separate questions, and the mode answers only the first.
    #[test]
    fn the_wildcard_mode_leaves_the_hidden_policy_alone() {
        let fixture = Fixture::new();
        fixture.write("visible.ts");
        fixture.write(".hidden.ts");
        fixture.write("src/visible.ts");
        fixture.write("src/.hidden.ts");
        fixture.write(".config/inside.ts");

        let walk = |match_hidden: bool| -> Vec<PathBuf> {
            let result = Walker::new(&fixture.root)
                .wildcard_mode(WildcardMode::SeparatorCrossing)
                .match_hidden(match_hidden)
                .include("*.ts")
                .expect("valid include")
                .options(WalkOptions::default().sort(true).files_only(true))
                .collect()
                .expect("walk succeeds");
            relative_paths(result.entries(), &fixture.root)
        };

        assert_eq!(
            walk(false),
            vec![PathBuf::from("src/visible.ts"), PathBuf::from("visible.ts")],
            "crossing reaches deeper, not into hidden names"
        );
        assert_eq!(
            walk(true),
            vec![
                PathBuf::from(".config/inside.ts"),
                PathBuf::from(".hidden.ts"),
                PathBuf::from("src/.hidden.ts"),
                PathBuf::from("src/visible.ts"),
                PathBuf::from("visible.ts"),
            ],
            "match_hidden opens hidden names at every level a crossing wildcard reaches"
        );

        // Traversal still decides what the matcher ever sees.
        let skipped = Walker::new(&fixture.root)
            .wildcard_mode(WildcardMode::SeparatorCrossing)
            .match_hidden(true)
            .include("*.ts")
            .expect("valid include")
            .options(
                WalkOptions::default()
                    .sort(true)
                    .files_only(true)
                    .skip_hidden(true),
            )
            .collect()
            .expect("walk succeeds");
        assert_eq!(
            relative_paths(skipped.entries(), &fixture.root),
            vec![PathBuf::from("src/visible.ts"), PathBuf::from("visible.ts")],
            "skip_hidden keeps hidden entries away from the matcher under either mode"
        );
    }

    /// An absolute pattern selects what the same pattern written relative to
    /// the root selects, which is the whole point of rewriting it.
    #[test]
    fn an_absolute_pattern_means_what_its_relative_spelling_means() {
        let fixture = Fixture::new();
        fixture.write("src/a.ts");
        fixture.write("src/deep/b.ts");
        fixture.write("other/c.ts");

        let walk = |pattern: &str| -> Vec<PathBuf> {
            let result = Walker::new(&fixture.root)
                .include(pattern)
                .expect("valid include")
                .options(WalkOptions::default().sort(true).files_only(true))
                .collect()
                .expect("walk succeeds");
            relative_paths(result.entries(), &fixture.root)
        };

        for (absolute, relative) in [
            ("/src/*.ts", "src/*.ts"),
            ("/**/*.ts", "**/*.ts"),
            ("/src/**", "src/**"),
            // A brace root from #20 survives the rewrite.
            ("/{src,other}/*.ts", "{src,other}/*.ts"),
            // The separator that joins the root to the rest is not doubled
            // into the pattern, which is what a root ending in one produces.
            ("//src/*.ts", "src/*.ts"),
            ("/./src/*.ts", "src/*.ts"),
        ] {
            assert_eq!(
                walk(&fixture.absolute(absolute)),
                walk(relative),
                "absolute {absolute} must select what {relative} selects"
            );
        }
        // Not vacuously equal.
        assert_eq!(
            walk(&fixture.absolute("/src/*.ts")),
            vec![PathBuf::from("src/a.ts")]
        );
    }

    /// The mode from #83 is about how far a wildcard reaches, and rewriting is
    /// about where the pattern starts, so the two compose without either
    /// knowing about the other.
    #[test]
    fn an_absolute_pattern_is_read_under_the_walk_s_wildcard_mode() {
        let fixture = Fixture::new();
        fixture.write("src/a.ts");
        fixture.write("src/deep/b.ts");

        let walk = |mode: WildcardMode| -> Vec<PathBuf> {
            let result = Walker::new(&fixture.root)
                .wildcard_mode(mode)
                .include(fixture.absolute("/src/*.ts"))
                .expect("valid include")
                .options(WalkOptions::default().sort(true).files_only(true))
                .collect()
                .expect("walk succeeds");
            relative_paths(result.entries(), &fixture.root)
        };

        assert_eq!(
            walk(WildcardMode::ComponentScoped),
            vec![PathBuf::from("src/a.ts")]
        );
        assert_eq!(
            walk(WildcardMode::SeparatorCrossing),
            vec![PathBuf::from("src/a.ts"), PathBuf::from("src/deep/b.ts")]
        );
    }

    /// A pattern about a different tree selects nothing, and - the part worth
    /// pinning - prunes nothing either. An exclude that cannot reach this walk
    /// must not close a directory in it.
    #[test]
    fn an_absolute_pattern_outside_the_root_selects_and_prunes_nothing() {
        let fixture = Fixture::new();
        fixture.write("src/a.ts");
        fixture.write("keep/b.ts");

        let elsewhere = format!("{}-elsewhere/**", fixture.absolute(""));

        let included = Walker::new(&fixture.root)
            .include(&elsewhere)
            .expect("an unrelated tree is not an error")
            .options(WalkOptions::default().sort(true).files_only(true))
            .collect()
            .expect("walk succeeds");
        assert!(
            relative_paths(included.entries(), &fixture.root).is_empty(),
            "an include about another tree selects nothing here"
        );

        let excluded = Walker::new(&fixture.root)
            .exclude(&elsewhere)
            .expect("an unrelated tree is not an error")
            .options(WalkOptions::default().sort(true).files_only(true))
            .collect()
            .expect("walk succeeds");
        assert_eq!(
            relative_paths(excluded.entries(), &fixture.root),
            vec![PathBuf::from("keep/b.ts"), PathBuf::from("src/a.ts")],
            "an exclude about another tree removes nothing here"
        );
    }

    /// The rewrite happens before compilation, so the traversal prefilters see
    /// an ordinary relative pattern and keep working. Without this an absolute
    /// include would open every directory in the tree.
    #[test]
    fn the_planner_prefilters_still_apply_to_a_rewritten_pattern() {
        let fixture = Fixture::new();
        let walker = Walker::new(&fixture.root)
            .include(fixture.absolute("/src/**/*.ts"))
            .expect("valid include");
        let pattern = &walker.roots[0].includes[0];

        assert_eq!(
            pattern.literal_roots,
            Some(vec![b"src".to_vec()]),
            "the root prefilter survives the rewrite"
        );
        assert_eq!(
            pattern.extensions,
            Some(vec![b"ts".to_vec()]),
            "the extension prefilter survives the rewrite"
        );
        assert!(pattern.could_match_descendant(b"src"));
        assert!(!pattern.could_match_descendant(b"node_modules"));
        assert!(pattern.matches_extension(b"src/app.ts"));
        assert!(!pattern.matches_extension(b"src/app.js"));

        // A pattern about another tree proves the strongest prefilter of all:
        // nothing under this root is worth opening for it.
        let outside = Walker::new(&fixture.root)
            .include(format!("{}-elsewhere/**/*.ts", fixture.absolute("")))
            .expect("an unrelated tree is not an error");
        assert!(!outside.roots[0].includes[0].could_match_descendant(b"src"));
        assert!(
            !outside.roots[0].includes[0].covers_subtree(b"src", WildcardMode::ComponentScoped)
        );
    }

    /// The shapes the rewrite refuses to guess at, reported instead of quietly
    /// selecting the wrong entries.
    #[test]
    fn an_unprovable_absolute_pattern_is_rejected() {
        let fixture = Fixture::new();
        let parent = fixture
            .root
            .parent()
            .expect("the fixture root has a parent")
            .to_path_buf();
        let parent = String::from_utf8(glob_path_bytes(&parent).into_owned())
            .expect("the temporary directory is UTF-8 on a test host");

        // A wildcard standing where the root's own components are.
        let above = Walker::new(&fixture.root)
            .include(format!("{parent}/*/x.ts"))
            .expect_err("a wildcard above the root is rejected");
        assert!(
            above
                .message()
                .starts_with("a wildcard at or above the walk root"),
        );

        // `..`, which is not resolved here.
        let dot_dot = Walker::new(&fixture.root)
            .include(fixture.absolute("/../x.ts"))
            .expect_err("`..` is rejected");
        assert!(dot_dot.message().starts_with("`..`"));

        // The root itself, which the walk never emits.
        let root_itself = Walker::new(&fixture.root)
            .exclude(fixture.absolute(""))
            .expect_err("naming the root is rejected");
        assert!(
            root_itself
                .message()
                .starts_with("an absolute pattern that names the walk root itself")
        );

        // An absolute pattern cannot be placed against a relative root without
        // reading the process's working directory.
        let relative_root = Walker::new("relative/dir")
            .include(fixture.absolute("/x.ts"))
            .expect_err("a relative root is rejected");
        assert_eq!(
            relative_root.message(),
            "an absolute pattern needs an absolute walk root"
        );
    }

    /// Subtree pruning must decide what the per-entry exclude would have
    /// decided, under either mode.
    ///
    /// What a multi-root walk observed, in the form the acceptance criterion
    /// compares: every entry with the root it was found under and its depth
    /// below that root, plus the recoverable errors. Sorted, so it is a
    /// multiset and a duplicate stays a duplicate.
    #[derive(Debug, PartialEq, Eq)]
    struct RootedOutcome {
        entries: Vec<(PathBuf, PathBuf, usize)>,
        errors: Vec<(&'static str, PathBuf)>,
    }

    impl RootedOutcome {
        fn of(result: &super::WalkResult) -> Self {
            let mut entries = result
                .entries()
                .iter()
                .map(|entry| {
                    (
                        entry.root().to_path_buf(),
                        entry.path().to_path_buf(),
                        entry.depth(),
                    )
                })
                .collect::<Vec<_>>();
            let mut errors = result
                .errors()
                .iter()
                .map(|error| (error.operation(), error.path().to_path_buf()))
                .collect::<Vec<_>>();
            entries.sort_unstable();
            errors.sort_unstable();
            Self { entries, errors }
        }

        /// The concatenation two single-root walks would have produced.
        fn concatenated(parts: impl IntoIterator<Item = Self>) -> Self {
            let mut joined = Self {
                entries: Vec::new(),
                errors: Vec::new(),
            };
            for part in parts {
                joined.entries.extend(part.entries);
                joined.errors.extend(part.errors);
            }
            joined.entries.sort_unstable();
            joined.errors.sort_unstable();
            joined
        }
    }

    /// The frontends a multi-root walk has to agree across.
    #[derive(Debug, Clone, Copy)]
    enum Frontend {
        Collect,
        Visit,
        Stream,
    }

    /// Runs one frontend over `roots` and reports what it saw.
    fn multi_root_outcome(
        roots: &[PathBuf],
        include: Option<&str>,
        threads: usize,
        frontend: Frontend,
    ) -> RootedOutcome {
        multi_root_outcome_with_following(roots, include, threads, frontend, false)
    }

    /// The same acceptance harness under either symlink policy. Keeping the
    /// policy explicit lets the multi-root contract pin the cycle guard too:
    /// following links must change what one root sees, never whether another
    /// root gets to see its own traversal.
    fn multi_root_outcome_with_following(
        roots: &[PathBuf],
        include: Option<&str>,
        threads: usize,
        frontend: Frontend,
        follow_symlinks: bool,
    ) -> RootedOutcome {
        let (first, rest) = roots.split_first().expect("at least one root");
        let mut walker = Walker::new(first).threads(threads).options(
            WalkOptions::default()
                .files_only(true)
                .follow_symlinks(follow_symlinks),
        );
        for root in rest {
            walker = walker.add_root(root).expect("the root takes the patterns");
        }
        if let Some(pattern) = include {
            walker = walker.include(pattern).expect("valid include");
        }
        match frontend {
            Frontend::Collect => {
                RootedOutcome::of(&walker.collect().expect("collect walks under Collect"))
            }
            Frontend::Visit => RootedOutcome::of(
                &walker
                    .visit(|_| Verdict::Keep)
                    .expect("visit walks under Collect"),
            ),
            Frontend::Stream => {
                // The stream reports errors as items rather than in a result,
                // so it is reassembled into the same shape.
                let mut entries = Vec::new();
                let mut errors = Vec::new();
                for item in walker.stream() {
                    match item {
                        Ok(entry) => entries.push(entry),
                        Err(error) => errors.push(error),
                    }
                }
                RootedOutcome::of(&super::WalkResult {
                    entries,
                    errors,
                    cancelled: false,
                })
            }
        }
    }

    /// The acceptance criterion for multi-root walks: walking several roots at
    /// once observes exactly what walking each of them separately observes,
    /// counted as a multiset, on every frontend and at every thread count.
    ///
    /// Entries carry the root they were found under and their depth below it,
    /// so this pins more than the path set: an entry from a multi-root walk has
    /// to say the same things about itself as its single-root counterpart.
    #[test]
    fn a_multi_root_walk_is_the_concatenation_of_the_single_root_walks() {
        let fixture = Fixture::new();
        fixture.write("alpha/src/one.rs");
        fixture.write("alpha/src/deep/two.rs");
        fixture.write("alpha/notes.txt");
        fixture.write("beta/src/three.rs");
        fixture.write("beta/four.txt");
        fixture.write("gamma/src/five.rs");

        let roots = [
            fixture.root.join("alpha"),
            fixture.root.join("beta"),
            fixture.root.join("gamma"),
            // A root that does not exist, so the invariant covers errors too.
            fixture.root.join("missing"),
        ];

        for include in [None, Some("src/**/*.rs"), Some("**/*.rs")] {
            for threads in [1, 4] {
                for frontend in [Frontend::Collect, Frontend::Visit, Frontend::Stream] {
                    let together = multi_root_outcome(&roots, include, threads, frontend);
                    let separately = RootedOutcome::concatenated(roots.iter().map(|root| {
                        multi_root_outcome(std::slice::from_ref(root), include, threads, frontend)
                    }));
                    assert_eq!(
                        together, separately,
                        "{frontend:?} on {threads} threads with include {include:?}"
                    );
                }
            }
        }

        // Not vacuous: the walk really did see all three trees and the failure.
        let all = multi_root_outcome(&roots, None, 4, Frontend::Collect);
        assert_eq!(all.entries.len(), 6);
        assert_eq!(all.errors.len(), 1);
        assert_eq!(all.errors[0].0, "read_dir");
    }

    /// Roots that contain one another deliver their overlap once per root.
    ///
    /// This is the concatenation rule taken seriously rather than an oversight:
    /// suppressing the second copy would need every directory's identity - a
    /// `stat` per directory that only the symlink-following mode pays today -
    /// and would make adding a root able to remove entries.
    #[test]
    fn overlapping_roots_deliver_their_overlap_once_per_root() {
        let fixture = Fixture::new();
        fixture.write("outer/inner/shared.rs");
        fixture.write("outer/own.rs");

        let outer = fixture.root.join("outer");
        let inner = outer.join("inner");
        let result = Walker::new(&outer)
            .add_root(&inner)
            .expect("nested roots are allowed")
            .threads(1)
            .options(WalkOptions::default().sort(true).files_only(true))
            .collect()
            .expect("walk succeeds");

        let shared = inner.join("shared.rs");
        let copies = result
            .entries()
            .iter()
            .filter(|entry| entry.path() == shared)
            .collect::<Vec<_>>();
        assert_eq!(copies.len(), 2, "the overlap is delivered once per root");
        // The two copies differ in exactly what the root makes different.
        let mut seen = copies
            .iter()
            .map(|entry| (entry.root().to_path_buf(), entry.depth()))
            .collect::<Vec<_>>();
        seen.sort_unstable();
        assert_eq!(
            seen,
            vec![(outer.clone(), 2), (inner.clone(), 1)],
            "each copy is one level below the root it came from"
        );
    }

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

        // `back` makes a genuine cycle for every root traversal. The nested
        // and duplicate roots must nevertheless reproduce their corresponding
        // single-root walks exactly, including the root and depth carried by
        // every overlapping path.
        let fixture = Fixture::new();
        fixture.write("outer/own.txt");
        fixture.write("outer/inner/shared.txt");
        fixture.write("outer/inner/deep/leaf.txt");
        symlink("..", fixture.root.join("outer/inner/back")).expect("create cycle");

        let outer = fixture.root.join("outer");
        let inner = outer.join("inner");
        let alias = fixture.root.join("outer-alias");
        symlink("outer", &alias).expect("create root alias");
        let overlapping = [outer.clone(), inner.clone()];
        let duplicate = [outer.clone(), outer.clone()];
        let aliases = [outer.clone(), alias];
        for roots in [&overlapping[..], &duplicate[..], &aliases[..]] {
            for (frontend, threads) in [
                (Frontend::Collect, 1),
                (Frontend::Collect, 4),
                (Frontend::Visit, 1),
                (Frontend::Visit, 4),
                (Frontend::Stream, 1),
            ] {
                let together =
                    multi_root_outcome_with_following(roots, None, threads, frontend, true);
                let separately = RootedOutcome::concatenated(roots.iter().map(|root| {
                    multi_root_outcome_with_following(
                        std::slice::from_ref(root),
                        None,
                        threads,
                        frontend,
                        true,
                    )
                }));
                assert_eq!(
                    together, separately,
                    "{frontend:?} with {threads} thread(s) and roots {roots:?}"
                );
            }
        }
    }

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

        let fixture = Fixture::new();
        let outer = fixture.root.join("outer");
        let inner = outer.join("inner");
        for branch in 0..32 {
            for leaf in 0..8 {
                fixture.write(format!("outer/inner/branch-{branch}/leaf-{leaf}.txt"));
            }
        }
        symlink("..", inner.join("back")).expect("create cycle");
        let roots = [outer, inner];
        let expected = RootedOutcome::concatenated(roots.iter().map(|root| {
            multi_root_outcome_with_following(
                std::slice::from_ref(root),
                None,
                1,
                Frontend::Collect,
                true,
            )
        }));

        // The workers can race over the two roots' overlapping subtrees on
        // every run. A shared guard used to make which root won observable in
        // both `root()` and `depth()`; repeat far beyond one schedule.
        for run in 0..24 {
            assert_eq!(
                multi_root_outcome_with_following(&roots, None, 4, Frontend::Collect, true),
                expected,
                "parallel run {run} changed overlap attribution"
            );
        }
    }

    /// Patterns are root-relative and apply under every root; an absolute one
    /// is rewritten per root, so it selects only under the root it names.
    #[test]
    fn patterns_are_read_once_per_root() {
        let fixture = Fixture::new();
        fixture.write("alpha/src/one.rs");
        fixture.write("alpha/other/two.rs");
        fixture.write("beta/src/three.rs");
        fixture.write("beta/other/four.rs");
        let alpha = fixture.root.join("alpha");
        let beta = fixture.root.join("beta");

        let walk = |pattern: String| -> Vec<PathBuf> {
            let result = Walker::new(&alpha)
                .add_root(&beta)
                .expect("the root takes the patterns")
                .include(pattern)
                .expect("valid include")
                .options(WalkOptions::default().sort(true).files_only(true))
                .collect()
                .expect("walk succeeds");
            result
                .entries()
                .iter()
                .map(|entry| entry.path().to_path_buf())
                .collect()
        };

        // A relative pattern selects that subtree of every root.
        assert_eq!(
            walk("src/*.rs".to_owned()),
            vec![alpha.join("src/one.rs"), beta.join("src/three.rs")],
        );

        // An absolute pattern names one tree, and #85's out-of-root reading is
        // what makes it select nothing under the other.
        let alpha_glob = String::from_utf8(glob_path_bytes(&alpha).into_owned())
            .expect("the temporary directory is UTF-8 on a test host");
        assert_eq!(
            walk(format!("{alpha_glob}/src/*.rs")),
            vec![alpha.join("src/one.rs")],
        );
    }

    /// Builder order does not matter, including for the rejection an absolute
    /// pattern can produce: the pattern meets every root either way.
    #[test]
    fn a_root_and_a_pattern_meet_whichever_order_they_arrive_in() {
        let fixture = Fixture::new();
        fixture.write("alpha/src/one.rs");
        fixture.write("beta/src/two.rs");
        let alpha = fixture.root.join("alpha");
        let beta = fixture.root.join("beta");

        let entries = |walker: Walker| -> Vec<PathBuf> {
            walker
                .options(WalkOptions::default().sort(true).files_only(true))
                .collect()
                .expect("walk succeeds")
                .entries()
                .iter()
                .map(|entry| entry.path().to_path_buf())
                .collect()
        };

        let root_first = entries(
            Walker::new(&alpha)
                .add_root(&beta)
                .expect("root")
                .include("src/*.rs")
                .expect("include"),
        );
        let pattern_first = entries(
            Walker::new(&alpha)
                .include("src/*.rs")
                .expect("include")
                .add_root(&beta)
                .expect("root"),
        );
        assert_eq!(root_first, pattern_first);
        assert_eq!(root_first.len(), 2);

        // A pattern no root can be given is refused from whichever side it is
        // added, rather than only when the root happens to come first.
        let unprovable = fixture.absolute("/../x.rs");
        assert!(
            Walker::new(&alpha)
                .add_root(&beta)
                .expect("root")
                .include(&unprovable)
                .is_err()
        );
        assert!(
            Walker::new(&alpha)
                .include(&unprovable)
                .expect_err("`..` is refused for the first root already")
                .message()
                .starts_with("`..`")
        );
    }

    /// A root that cannot be read is that root's error, and the walk goes on to
    /// the others under `Collect`.
    #[test]
    fn an_unreadable_root_does_not_stop_the_other_roots() {
        let fixture = Fixture::new();
        fixture.write("alpha/one.rs");
        fixture.write("gamma/two.rs");
        let missing = fixture.root.join("beta");

        for threads in [1, 4] {
            let result = Walker::new(fixture.root.join("alpha"))
                .add_root(&missing)
                .expect("root")
                .add_root(fixture.root.join("gamma"))
                .expect("root")
                .threads(threads)
                .options(WalkOptions::default().sort(true).files_only(true))
                .collect()
                .expect("Collect keeps walking");
            assert_eq!(
                relative_paths(result.entries(), &fixture.root),
                vec![PathBuf::from("alpha/one.rs"), PathBuf::from("gamma/two.rs")],
                "the readable roots are walked on {threads} threads"
            );
            assert_eq!(result.errors().len(), 1);
            assert_eq!(result.errors()[0].operation(), "read_dir");
            assert_eq!(result.errors()[0].path(), missing);
        }
    }

    #[test]
    fn skip_reports_a_failed_root_while_walking_the_other_roots() {
        let fixture = Fixture::new();
        fixture.write("alpha/one.rs");
        fixture.write("gamma/two.rs");
        let missing = fixture.root.join("beta");
        let build = || {
            Walker::new(fixture.root.join("alpha"))
                .add_root(&missing)
                .expect("root")
                .add_root(fixture.root.join("gamma"))
                .expect("root")
                .error_policy(ErrorPolicy::Skip)
                .options(WalkOptions::default().sort(true).files_only(true))
        };

        for threads in [1, 4] {
            let result = build()
                .threads(threads)
                .collect()
                .expect("Skip preserves the other roots");
            assert_eq!(
                relative_paths(result.entries(), &fixture.root),
                vec![PathBuf::from("alpha/one.rs"), PathBuf::from("gamma/two.rs")]
            );
            assert_eq!(result.errors().len(), 1);
            assert_eq!(result.errors()[0].path(), missing);
        }

        let mut stream = build().stream();
        let mut entries = Vec::new();
        let mut errors = Vec::new();
        for item in &mut stream {
            match item {
                Ok(entry) => entries.push(entry),
                Err(error) => errors.push(error),
            }
        }
        entries.sort_by(|left, right| left.path().cmp(right.path()));
        assert_eq!(
            relative_paths(&entries, &fixture.root),
            vec![PathBuf::from("alpha/one.rs"), PathBuf::from("gamma/two.rs")]
        );
        assert_eq!(errors.len(), 1);
        assert_eq!(errors[0].path(), missing);
    }

    /// `*.tmp/**` used to close `a/b.tmp` in both modes, because the subtree
    /// root was always read as separator-crossing. In the default mode the
    /// exclude does not reach that directory at all - `*.tmp` cannot match the
    /// component `a` - so its contents went missing from the walk without any
    /// pattern saying they should.
    /// The trap from #94, on the one host that can observe it.
    ///
    /// A pattern built by joining `PathBuf`s carries `\` separators, which this
    /// dialect reads as escapes. Every one of these used to compile without
    /// complaint and select nothing; each is now refused with a message that
    /// names the cause.
    #[cfg(windows)]
    #[test]
    fn a_windows_path_handed_over_as_a_pattern_is_refused() {
        let fixture = Fixture::new();
        fixture.write("src/main.ts");
        fixture.write("src/deep/other.ts");
        let root = fixture.root.display().to_string();

        for pattern in [
            format!(r"{root}\src\**\*.ts"),
            format!(r"{root}\src\*.ts"),
            r"src\*.ts".to_owned(),
            r"src\**\*.ts".to_owned(),
        ] {
            let refused = Walker::new(&fixture.root)
                .include(&pattern)
                .expect_err("a path spelled as a pattern is refused");
            assert!(
                refused
                    .message()
                    .starts_with("this looks like a Windows path"),
                "{pattern:?} reported {refused}"
            );
            // Excludes are read by the same rules, so they are refused too -
            // an exclude that silently matches nothing is just as invisible.
            assert!(Walker::new(&fixture.root).exclude(&pattern).is_err());
        }

        // The spelling the dialect wants keeps working, absolute or relative.
        for pattern in [
            "src/**/*.ts",
            &format!("{}/src/**/*.ts", root.replace('\\', "/")),
        ] {
            let result = Walker::new(&fixture.root)
                .include(pattern)
                .expect("valid include")
                .options(WalkOptions::default().sort(true).files_only(true))
                .collect()
                .expect("walk succeeds");
            assert_eq!(result.entries().len(), 2, "{pattern} selects both files");
        }

        // An escaped forbidden byte inside a group is one member among
        // several, so the pattern still selects - and must still be accepted.
        // The review of #94 found the first version refusing exactly these.
        for pattern in [
            r"src/[m\*]ain.ts",
            r"src/{main,\*}.ts",
            r"src/@(main|\*).ts",
        ] {
            let result = Walker::new(&fixture.root)
                .include(pattern)
                .unwrap_or_else(|error| panic!("{pattern} can match, got {error}"))
                .options(WalkOptions::default().sort(true).files_only(true))
                .collect()
                .expect("walk succeeds");
            assert_eq!(
                relative_paths(result.entries(), &fixture.root),
                vec![PathBuf::from("src/main.ts")],
                "{pattern} selects through its group"
            );
        }
    }

    /// `*.tmp/**` used to close `a/b.tmp` in both modes, because the subtree
    /// root was always read as separator-crossing. In the default mode the
    /// exclude does not reach that directory at all - `*.tmp` cannot match the
    /// component `a` - so its contents went missing from the walk without any
    /// pattern saying they should.
    #[test]
    fn subtree_pruning_agrees_with_the_exclude_it_came_from() {
        let fixture = Fixture::new();
        fixture.write("a/b.tmp/keep.rs");
        fixture.write("b.tmp/gone.rs");
        fixture.write("a/plain/keep.rs");

        let walk = |mode: WildcardMode| -> Vec<PathBuf> {
            let result = Walker::new(&fixture.root)
                .wildcard_mode(mode)
                .exclude("*.tmp/**")
                .expect("valid exclude")
                .options(WalkOptions::default().sort(true).files_only(true))
                .collect()
                .expect("walk succeeds");
            relative_paths(result.entries(), &fixture.root)
        };

        assert_eq!(
            walk(WildcardMode::ComponentScoped),
            vec![
                PathBuf::from("a/b.tmp/keep.rs"),
                PathBuf::from("a/plain/keep.rs"),
            ],
            "a nested `.tmp` directory is out of a component-scoped exclude's reach"
        );
        assert_eq!(
            walk(WildcardMode::SeparatorCrossing),
            vec![PathBuf::from("a/plain/keep.rs")],
            "a crossing exclude reaches the nested one, and pruning may follow it"
        );
    }

    /// A literal that shares a component with a wildcard proves nothing about a
    /// directory, so the planner may not prune on it.
    ///
    /// `src*` selects inside `srcfoo` as readily as inside `src`; the root
    /// prefilter used to cut at the last separator even when there was none,
    /// keeping the walk out of `srcfoo` entirely. The matcher was always right
    /// about this - corpus case `wildcard-mode-046-scoped` - only the traversal
    /// never asked it.
    #[test]
    fn a_partial_component_literal_does_not_prune_its_siblings() {
        let fixture = Fixture::new();
        fixture.write("src/x.ts");
        fixture.write("srcfoo/x.ts");
        fixture.write("other/x.ts");

        for mode in [
            WildcardMode::ComponentScoped,
            WildcardMode::SeparatorCrossing,
        ] {
            let result = Walker::new(&fixture.root)
                .wildcard_mode(mode)
                .include("src*/x.ts")
                .expect("valid include")
                .options(WalkOptions::default().sort(true).files_only(true))
                .collect()
                .expect("walk succeeds");
            assert_eq!(
                relative_paths(result.entries(), &fixture.root),
                vec![PathBuf::from("src/x.ts"), PathBuf::from("srcfoo/x.ts")],
                "{mode:?}: a partial-component literal must not prune a sibling it matches"
            );
        }

        // What is still proven, and still pruned: a literal that ends at a
        // separator.
        assert_eq!(
            literal_pattern_root(b"src/*.ts"),
            Some(b"src".to_vec()),
            "a complete component is still a root"
        );
        assert_eq!(
            literal_pattern_root(b"src*/x.ts"),
            None,
            "a partial component is not"
        );
        assert_eq!(
            literal_pattern_root(b"docs/api*/x.ts"),
            Some(b"docs".to_vec()),
            "what precedes the last separator is still proven"
        );
    }

    #[test]
    fn prune_planner_only_accepts_explicit_whole_subtree_excludes() {
        let scoped = WildcardMode::ComponentScoped;
        let subtree = traversal_pattern(b"src/**");
        assert!(subtree.covers_subtree(b"src", scoped));
        assert!(!subtree.covers_subtree(b"src/nested", scoped));

        let suffix = traversal_pattern(b"*.tmp");
        assert!(!suffix.covers_subtree(b"cache", scoped));

        let nested = traversal_pattern(b"**/target/**");
        assert!(nested.covers_subtree(b"target", scoped));
        assert!(nested.covers_subtree(b"crates/ferralk/target", scoped));

        // The subtree root is read under the walk's own mode. A component-scoped
        // `*.tmp` cannot match the component `a`, so `a/b.tmp` must stay open;
        // a crossing one matches the whole path, so it may be closed.
        let wildcard_subtree = traversal_pattern(b"*.tmp/**");
        assert!(!wildcard_subtree.covers_subtree(b"a/b.tmp", scoped));
        assert!(wildcard_subtree.covers_subtree(b"b.tmp", scoped));
        assert!(wildcard_subtree.covers_subtree(b"a/b.tmp", WildcardMode::SeparatorCrossing));

        assert_eq!(
            literal_pattern_root(b"src/foo/*.rs"),
            Some(b"src/foo".to_vec())
        );
        assert_eq!(literal_pattern_root(b"src/foo*.rs"), Some(b"src".to_vec()));
        assert_eq!(literal_pattern_root(b"**/*.rs"), None);
        assert_eq!(
            literal_pattern_root(b"foo+bar/**/*.rs"),
            Some(b"foo+bar".to_vec())
        );
        assert_eq!(
            literal_pattern_root(b"foo@(bar/**/*.rs"),
            Some(b"foo@(bar".to_vec())
        );

        let rust_sources = traversal_pattern(b"src/**/*.rs");
        assert!(rust_sources.matches_extension(b"src/lib.rs"));
        assert!(!rust_sources.matches_extension(b"src/lib.txt"));
        assert_eq!(literal_extension(b"src/**/*.{rs,ts}"), None);
        assert_eq!(literal_extension(b"src/**/*.rs"), Some(b"rs".to_vec()));
    }

    #[test]
    fn a_visitor_skip_drops_the_entry_without_pruning_the_subtree() {
        // Skip is a result filter, not a traversal filter: excluding a
        // directory from the result must leave its children reachable.
        let fixture = Fixture::new();
        fixture.write("keep/inside.txt");

        for threads in [1, 4] {
            let result = Walker::new(&fixture.root)
                .threads(threads)
                .visit(|entry| {
                    if entry.path().file_name().is_some_and(|name| name == "keep") {
                        Verdict::Skip
                    } else {
                        Verdict::Keep
                    }
                })
                .expect("visited walk succeeds");
            let paths = relative_paths(result.entries(), &fixture.root);
            assert_eq!(
                paths,
                vec![PathBuf::from("keep/inside.txt")],
                "the skipped directory must still have been descended into"
            );
            assert!(!result.was_cancelled());
        }
    }

    #[test]
    fn a_visitor_stop_ends_the_walk_and_is_reported() {
        let fixture = Fixture::new();
        for index in 0..64 {
            fixture.write(format!("file-{index}.txt"));
        }

        for threads in [1, 4] {
            let seen = AtomicUsize::new(0);
            let result = Walker::new(&fixture.root)
                .threads(threads)
                .visit(|_| {
                    if seen.fetch_add(1, Ordering::AcqRel) >= 8 {
                        Verdict::Stop
                    } else {
                        Verdict::Keep
                    }
                })
                .expect("visited walk succeeds");
            assert!(
                result.was_cancelled(),
                "a stop must be reported the way a cancellation is"
            );
            assert!(result.entries().len() <= 64);
        }
    }

    #[test]
    fn a_visitor_stop_leaves_a_caller_owned_cancellation_token_alone() {
        // The token belongs to the caller and may drive other work, so ending
        // one walk must not cancel it.
        let fixture = Fixture::new();
        fixture.write("only.txt");
        let cancellation = CancellationToken::default();

        for threads in [1, 4] {
            let result = Walker::new(&fixture.root)
                .threads(threads)
                .cancellation(cancellation.clone())
                .visit(|_| Verdict::Stop)
                .expect("visited walk succeeds");
            assert!(result.was_cancelled());
            assert!(
                !cancellation.is_cancelled(),
                "a stop must not cancel the caller's token"
            );
        }
    }

    #[test]
    fn a_visitor_panic_is_resumed_on_the_caller() {
        let fixture = Fixture::new();
        for branch in 0..12 {
            fixture.write(format!("branch-{branch}/file.txt"));
        }

        for threads in [1, 4] {
            let root = fixture.root.clone();
            let panicked = std::panic::catch_unwind(move || {
                let _ = Walker::new(&root)
                    .threads(threads)
                    .visit(|_| panic!("visitor panic"));
            });
            assert!(
                panicked.is_err(),
                "a panic inside the visitor must reach the caller on {threads} threads"
            );
        }
    }

    #[test]
    fn a_small_tree_stays_on_one_thread() {
        // The size floor: every parallel arm of the Palamedes trial lost to its
        // own serial form on a twelve-file tree.
        let fixture = Fixture::new();
        for index in 0..12 {
            fixture.write(format!("one/file-{index}.txt"));
        }
        fixture.write("two/only.txt");

        let threads = Mutex::new(HashSet::new());
        let result = Walker::new(&fixture.root)
            .threads(4)
            .visit(|_| {
                threads
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner)
                    .insert(std::thread::current().id());
                Verdict::Keep
            })
            .expect("visited walk succeeds");

        let observed = threads
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .len();
        assert_eq!(
            observed, 1,
            "a tree below the size floor must not pay for helper threads"
        );
        // Two directories and the thirteen files under them.
        assert_eq!(result.entries().len(), 2 + 13);
    }

    #[test]
    fn the_three_frontends_agree_on_entries_and_errors() {
        let fixture = Fixture::new();
        fixture.write("src/lib.rs");
        fixture.write("src/nested/mod.rs");
        fixture.write("docs/guide.md");
        fixture.write("docs/notes/todo.md");
        fs::create_dir_all(fixture.root.join("empty")).expect("create empty fixture directory");

        assert_frontends_agree("plain tree", &fixture.root, || Walker::new(&fixture.root));
        assert_frontends_agree("with metadata", &fixture.root, || {
            Walker::new(&fixture.root).options(WalkOptions::default().metadata(true))
        });
        assert_frontends_agree("include filtered", &fixture.root, || {
            Walker::new(&fixture.root)
                .options(WalkOptions::default().metadata(true))
                .include("**/*.md")
                .expect("valid include")
        });
        assert_frontends_agree("directories only", &fixture.root, || {
            Walker::new(&fixture.root).options(
                WalkOptions::default()
                    .metadata(true)
                    .directories_only(true)
                    .max_depth(2),
            )
        });
    }

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

        let fixture = Fixture::new();
        fixture.write("src/lib.rs");
        fixture.write("docs/guide.md");
        symlink("missing-target", fixture.root.join("src/dangling"))
            .expect("create dangling symlink");
        symlink("missing-target", fixture.root.join("docs/dangling"))
            .expect("create second dangling symlink");

        // Following the links stats them, and both stats fail: every frontend
        // has to report that the same way.
        assert_frontends_agree("dangling symlinks", &fixture.root, || {
            Walker::new(&fixture.root).options(
                WalkOptions::default()
                    .metadata(true)
                    .follow_symlinks(true)
                    .sort(true),
            )
        });
    }

    /// An entry whose `stat` would fail but that no filter emits must not be
    /// stat-ed at all, so the walk stays silent about it. The filters used here
    /// are the ones that only decide emission - `directories_only` and an
    /// include pattern without a literal extension - because those are exactly
    /// the ones the serial walk used to apply *after* its stat, which made it
    /// report an error the other two frontends never saw.
    #[cfg(unix)]
    #[test]
    fn a_filtered_entry_is_never_stat_ed() {
        use std::os::unix::fs::PermissionsExt;

        let fixture = Fixture::new();
        fixture.write("keep/note.md");
        fixture.write("blocked/hidden.txt");
        let blocked = fixture.root.join("blocked");
        // Readable but not searchable: the directory still lists, stat-ing what
        // is inside it does not.
        fs::set_permissions(&blocked, fs::Permissions::from_mode(0o400))
            .expect("restrict fixture directory");

        // Running as root, or a filesystem that needs a stat to report the file
        // type, would not exercise this at all; leave it rather than fail.
        let listable = fs::read_dir(&blocked).is_ok_and(|entries| {
            entries
                .into_iter()
                .all(|entry| entry.is_ok_and(|entry| entry.file_type().is_ok()))
        });
        let stat_fails = fs::symlink_metadata(blocked.join("hidden.txt")).is_err();
        let outcomes = (listable && stat_fails).then(|| {
            let directories_only = || {
                Walker::new(&fixture.root)
                    .options(WalkOptions::default().metadata(true).directories_only(true))
            };
            let included = || {
                Walker::new(&fixture.root)
                    .options(WalkOptions::default().metadata(true))
                    .include("**/keep/**")
                    .expect("valid include")
            };
            assert_frontends_agree(
                "unreadable file, directories only",
                &fixture.root,
                directories_only,
            );
            assert_frontends_agree("unreadable file, not included", &fixture.root, included);
            (
                collect_outcome(directories_only().threads(1).collect(), &fixture.root),
                collect_outcome(included().threads(1).collect(), &fixture.root),
            )
        });
        // Restore before the fixture removes itself, and before any assertion
        // below can unwind past this point.
        fs::set_permissions(&blocked, fs::Permissions::from_mode(0o700))
            .expect("restore fixture directory");

        let Some((directories_only, included)) = outcomes else {
            return;
        };
        assert_eq!(
            directories_only,
            FrontendOutcome::Completed {
                entries: vec![PathBuf::from("blocked"), PathBuf::from("keep")],
                errors: Vec::new(),
            },
            "a file dropped by directories_only must not be stat-ed"
        );
        assert_eq!(
            included,
            FrontendOutcome::Completed {
                entries: vec![PathBuf::from("keep"), PathBuf::from("keep/note.md")],
                errors: Vec::new(),
            },
            "an entry dropped by the include patterns must not be stat-ed"
        );
    }

    #[test]
    fn a_mock_backend_drives_the_parallel_walker() {
        struct InjectingBackend {
            failing_stat: PathBuf,
            reads: std::sync::Mutex<Vec<PathBuf>>,
        }

        impl super::DirectoryBackend for InjectingBackend {
            fn read_directory(
                &self,
                path: &Path,
                follow_symlinks: bool,
                refuse_final_symlink: bool,
                listing: &mut super::Listing,
            ) -> std::io::Result<()> {
                self.reads
                    .lock()
                    .unwrap_or_else(|poisoned| poisoned.into_inner())
                    .push(path.to_path_buf());
                super::StdBackend.read_directory(
                    path,
                    follow_symlinks,
                    refuse_final_symlink,
                    listing,
                )
            }

            fn symlink_metadata(&self, path: &Path) -> std::io::Result<fs::Metadata> {
                if path == self.failing_stat {
                    return Err(std::io::Error::from(std::io::ErrorKind::PermissionDenied));
                }
                fs::symlink_metadata(path)
            }
        }

        let fixture = Fixture::new();
        fixture.write("src/lib.rs");
        fixture.write("src/nested/mod.rs");
        fixture.write("docs/guide.md");
        let failing_stat = fixture.root.join("src/nested/mod.rs");
        let backend = InjectingBackend {
            failing_stat: failing_stat.clone(),
            reads: std::sync::Mutex::new(Vec::new()),
        };

        let result = Walker::new(&fixture.root)
            .threads(4)
            .options(WalkOptions::default().metadata(true).sort(true))
            .collect_with(&backend)
            .expect("collect policy retains the injected error");

        let reads = backend
            .reads
            .into_inner()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        assert!(
            reads.contains(&fixture.root.join("src")),
            "the parallel walker has to read through the injected backend"
        );
        assert_eq!(result.errors().len(), 1);
        assert_eq!(result.errors()[0].operation(), "symlink_metadata");
        assert_eq!(result.errors()[0].path(), failing_stat);
        assert!(
            !result
                .entries()
                .iter()
                .any(|entry| entry.path() == failing_stat)
        );

        // The same injected failure on an entry that is dropped before the
        // stat stays invisible. `directories_only` is the filter to use here:
        // it decides emission alone, so nothing rejects the file earlier.
        let backend = InjectingBackend {
            failing_stat: failing_stat.clone(),
            reads: std::sync::Mutex::new(Vec::new()),
        };
        let filtered = Walker::new(&fixture.root)
            .threads(4)
            .options(
                WalkOptions::default()
                    .metadata(true)
                    .directories_only(true)
                    .sort(true),
            )
            .collect_with(&backend)
            .expect("filtered walk succeeds");
        assert!(
            filtered.errors().is_empty(),
            "a filtered entry must not be stat-ed on the parallel path either"
        );
        assert_eq!(
            relative_paths(filtered.entries(), &fixture.root),
            vec![
                PathBuf::from("docs"),
                PathBuf::from("src"),
                PathBuf::from("src/nested")
            ]
        );
    }

    /// Native directory records on DT_UNKNOWN filesystems and portable
    /// `DirEntry::file_type` both use this channel. Keeping the test at the
    /// backend boundary pins the policy independently of the local filesystem
    /// (whose dirents normally already carry a type).
    #[test]
    fn deferred_entry_stat_failures_keep_siblings_and_report_permissions() {
        struct UnknownTypeBackend {
            root: PathBuf,
            failure: std::io::ErrorKind,
        }

        impl super::DirectoryBackend for UnknownTypeBackend {
            fn read_directory(
                &self,
                path: &Path,
                _follow_symlinks: bool,
                _refuse_final_symlink: bool,
                listing: &mut super::Listing,
            ) -> std::io::Result<()> {
                listing.clear();
                if path == self.root {
                    listing.push("before".as_ref(), false, false);
                    super::defer_entry_stat_error(
                        listing,
                        self.root.join("unknown"),
                        std::io::Error::from(self.failure),
                    )?;
                    listing.push("after".as_ref(), false, false);
                }
                Ok(())
            }
        }

        let fixture = Fixture::new();
        let permission = UnknownTypeBackend {
            root: fixture.root.clone(),
            failure: std::io::ErrorKind::PermissionDenied,
        };
        let walker = Walker::new(&fixture.root)
            .threads(1)
            .error_policy(ErrorPolicy::Collect);
        let mut state = super::WalkState::new(&walker, &super::keep_every_entry);
        state
            .walk_directory(
                &permission,
                directory_task(&walker, &permission, fixture.root.clone()),
            )
            .expect("collect keeps the usable listing");
        assert_eq!(
            relative_paths(&state.entries, &fixture.root),
            [PathBuf::from("before"), PathBuf::from("after")]
        );
        assert_eq!(state.errors.len(), 1);
        assert_eq!(state.errors[0].operation(), "read_dir");
        assert_eq!(state.errors[0].path(), fixture.root.join("unknown"));
        assert_eq!(
            state.errors[0].source.kind(),
            std::io::ErrorKind::PermissionDenied
        );

        let parallel = UnknownTypeBackend {
            root: fixture.root.clone(),
            failure: std::io::ErrorKind::PermissionDenied,
        };
        let result = Walker::new(&fixture.root)
            .threads(4)
            .error_policy(ErrorPolicy::Collect)
            .collect_with(&parallel)
            .expect("parallel collect keeps the usable listing");
        assert_eq!(
            relative_paths(result.entries(), &fixture.root),
            [PathBuf::from("before"), PathBuf::from("after")]
        );
        assert_eq!(result.errors().len(), 1);
        assert_eq!(result.errors()[0].path(), fixture.root.join("unknown"));

        for race in [
            std::io::ErrorKind::NotFound,
            std::io::ErrorKind::NotADirectory,
        ] {
            let backend = UnknownTypeBackend {
                root: fixture.root.clone(),
                failure: race,
            };
            let mut state = super::WalkState::new(&walker, &super::keep_every_entry);
            state
                .walk_directory(
                    &backend,
                    directory_task(&walker, &backend, fixture.root.clone()),
                )
                .expect("a changed entry costs only that entry");
            assert_eq!(
                relative_paths(&state.entries, &fixture.root),
                [PathBuf::from("before"), PathBuf::from("after")]
            );
            assert!(state.errors.is_empty(), "{race:?} is a replacement race");
        }
    }

    #[test]
    fn stream_delivers_deferred_entry_errors_after_listing_siblings() {
        let fixture = Fixture::new();
        let mut stream = Walker::new(&fixture.root)
            .error_policy(ErrorPolicy::Collect)
            .stream();
        // Feed the stream the same completed listing native and portable
        // readers create. This isolates delivery order from a host filesystem
        // that usually supplies a file type without a fallible stat.
        stream.pending_directories.clear();
        stream.directory = fixture.root.clone();
        stream.path = fixture.root.clone();
        stream.listing.push("before".as_ref(), false, false);
        super::defer_entry_stat_error(
            &mut stream.listing,
            fixture.root.join("unknown"),
            std::io::Error::from(std::io::ErrorKind::PermissionDenied),
        )
        .expect("permission failure is deferred");
        stream.listing.push("after".as_ref(), false, false);

        let delivered = stream
            .map(|item| match item {
                Ok(entry) => Ok(entry
                    .path()
                    .strip_prefix(&fixture.root)
                    .expect("entry belongs to fixture")
                    .to_path_buf()),
                Err(error) => Err((
                    error.operation(),
                    error.path().to_path_buf(),
                    error.source.kind(),
                )),
            })
            .collect::<Vec<_>>();
        assert_eq!(
            delivered,
            vec![
                Ok(PathBuf::from("before")),
                Ok(PathBuf::from("after")),
                Err((
                    "read_dir",
                    fixture.root.join("unknown"),
                    std::io::ErrorKind::PermissionDenied,
                )),
            ],
            "the stream must not let one deferred entry failure hide its siblings"
        );
    }

    #[test]
    fn literal_include_roots_prune_unrelated_sibling_directories() {
        /// One directory of the mock tree: entry names and whether each is a
        /// directory.
        type MockDirectory = Vec<(&'static str, bool)>;

        struct RecordingBackend {
            entries: HashMap<PathBuf, MockDirectory>,
            reads: RefCell<Vec<PathBuf>>,
        }

        impl super::DirectoryBackend for RecordingBackend {
            fn read_directory(
                &self,
                path: &Path,
                _follow_symlinks: bool,
                _refuse_final_symlink: bool,
                listing: &mut super::Listing,
            ) -> std::io::Result<()> {
                self.reads.borrow_mut().push(path.to_path_buf());
                listing.clear();
                for &(name, is_dir) in self.entries.get(path).into_iter().flatten() {
                    listing.push(name.as_ref(), is_dir, false);
                }
                Ok(())
            }
        }

        let root = PathBuf::from("/fixture");
        let source = root.join("src");
        let mut entries = HashMap::new();
        entries.insert(root.clone(), vec![("src", true), ("docs", true)]);
        entries.insert(source.clone(), vec![("main.rs", false)]);
        let backend = RecordingBackend {
            entries,
            reads: RefCell::new(Vec::new()),
        };
        let walker = Walker::new(&root)
            .include("src/**/*.rs")
            .expect("valid include");
        let mut state = super::WalkState::new(&walker, &super::keep_every_entry);

        state
            .walk_directory(&backend, directory_task(&walker, &backend, root.clone()))
            .expect("backend walk succeeds");

        assert_eq!(backend.reads.into_inner(), vec![root, source]);
        assert_eq!(state.entries.len(), 1);
        assert_eq!(state.entries[0].path(), Path::new("/fixture/src/main.rs"));
    }

    #[test]
    fn metadata_error_is_retained_when_a_dirent_disappears_before_stat() {
        struct DisappearingFileBackend {
            root: PathBuf,
            disappeared: PathBuf,
        }

        impl super::DirectoryBackend for DisappearingFileBackend {
            fn read_directory(
                &self,
                path: &Path,
                _follow_symlinks: bool,
                _refuse_final_symlink: bool,
                listing: &mut super::Listing,
            ) -> std::io::Result<()> {
                listing.clear();
                if path == self.root {
                    let name = self
                        .disappeared
                        .file_name()
                        .expect("the disappearing entry has a name");
                    listing.push(name, false, false);
                }
                Ok(())
            }
        }

        let fixture = Fixture::new();
        let disappeared = fixture.root.join("gone.rs");
        let walker = Walker::new(&fixture.root)
            .threads(1)
            .options(WalkOptions::default().metadata(true));
        let backend = DisappearingFileBackend {
            root: fixture.root.clone(),
            disappeared: disappeared.clone(),
        };
        let mut state = super::WalkState::new(&walker, &super::keep_every_entry);

        state
            .walk_directory(
                &backend,
                directory_task(&walker, &backend, fixture.root.clone()),
            )
            .expect("collect policy retains the metadata error");

        assert!(state.entries.is_empty());
        assert_eq!(state.errors.len(), 1);
        assert_eq!(state.errors[0].operation(), "symlink_metadata");
        assert_eq!(state.errors[0].path(), disappeared);
    }

    /// Resolving a symlink's kind treats a missing target as an answer, but a
    /// `metadata` failure for any other reason leaves the kind genuinely
    /// unknown - and that goes to the error policy rather than being swallowed.
    ///
    /// A mock backend, because a stat that fails with anything other than
    /// `NotFound` is not something a portable fixture can arrange.
    #[test]
    fn an_unreadable_symlink_target_is_reported_rather_than_silently_dropped() {
        struct UnreadableLinkBackend {
            root: PathBuf,
            kind: std::io::ErrorKind,
        }

        impl super::DirectoryBackend for UnreadableLinkBackend {
            fn read_directory(
                &self,
                path: &Path,
                _follow_symlinks: bool,
                _refuse_final_symlink: bool,
                listing: &mut super::Listing,
            ) -> std::io::Result<()> {
                listing.clear();
                if path == self.root {
                    listing.push("link".as_ref(), false, true);
                }
                Ok(())
            }

            fn metadata(&self, _path: &Path) -> std::io::Result<fs::Metadata> {
                Err(std::io::Error::from(self.kind))
            }
        }

        let fixture = Fixture::new();
        let walker = Walker::new(&fixture.root).threads(1).options(
            WalkOptions::default()
                .files_only(true)
                .resolve_symlink_kind(true),
        );

        // A target that is not there answers the question: dropped, no error.
        let backend = UnreadableLinkBackend {
            root: fixture.root.clone(),
            kind: std::io::ErrorKind::NotFound,
        };
        let mut state = super::WalkState::new(&walker, &super::keep_every_entry);
        state
            .walk_directory(
                &backend,
                directory_task(&walker, &backend, fixture.root.clone()),
            )
            .expect("a broken link does not end the walk");
        assert!(state.entries.is_empty(), "a broken link is not a file");
        assert!(state.errors.is_empty(), "a broken link is not an error");

        // A target we were not allowed to look at does not: dropped and
        // reported, so the walk cannot silently lose an entry it could not
        // classify.
        let backend = UnreadableLinkBackend {
            root: fixture.root.clone(),
            kind: std::io::ErrorKind::PermissionDenied,
        };
        let mut state = super::WalkState::new(&walker, &super::keep_every_entry);
        state
            .walk_directory(
                &backend,
                directory_task(&walker, &backend, fixture.root.clone()),
            )
            .expect("the collect policy retains the metadata error");
        assert!(state.entries.is_empty());
        assert_eq!(state.errors.len(), 1);
        assert_eq!(state.errors[0].operation(), "metadata");
        assert_eq!(state.errors[0].path(), fixture.root.join("link"));
    }

    /// The stat is not paid for entries that cannot need it: an ordinary file,
    /// and a symlink in a walk that has no kind filter to answer.
    #[test]
    fn resolving_stats_only_symlinks_that_a_kind_filter_asks_about() {
        struct CountingLinkBackend {
            root: PathBuf,
            stats: std::cell::Cell<usize>,
        }

        impl super::DirectoryBackend for CountingLinkBackend {
            fn read_directory(
                &self,
                path: &Path,
                _follow_symlinks: bool,
                _refuse_final_symlink: bool,
                listing: &mut super::Listing,
            ) -> std::io::Result<()> {
                listing.clear();
                if path == self.root {
                    listing.push("plain.txt".as_ref(), false, false);
                    listing.push("link".as_ref(), false, true);
                }
                Ok(())
            }

            fn metadata(&self, _path: &Path) -> std::io::Result<fs::Metadata> {
                self.stats.set(self.stats.get() + 1);
                fs::metadata(&self.root)
            }
        }

        let count = |options: WalkOptions| {
            let fixture = Fixture::new();
            let walker = Walker::new(&fixture.root).threads(1).options(options);
            let backend = CountingLinkBackend {
                root: fixture.root.clone(),
                stats: std::cell::Cell::new(0),
            };
            let mut state = super::WalkState::new(&walker, &super::keep_every_entry);
            state
                .walk_directory(
                    &backend,
                    directory_task(&walker, &backend, fixture.root.clone()),
                )
                .expect("walk succeeds");
            backend.stats.get()
        };

        assert_eq!(
            count(WalkOptions::default().resolve_symlink_kind(true)),
            0,
            "no kind filter is asking, so there is nothing to resolve"
        );
        assert_eq!(
            count(WalkOptions::default().files_only(true)),
            0,
            "the option is off"
        );
        assert_eq!(
            count(
                WalkOptions::default()
                    .files_only(true)
                    .resolve_symlink_kind(true)
            ),
            1,
            "one stat, for the symlink only"
        );
    }

    #[cfg(any(
        all(feature = "native-macos", target_os = "macos"),
        all(feature = "native-linux", target_os = "linux")
    ))]
    #[test]
    fn native_backend_matches_portable_across_walker_option_matrix() {
        use std::os::unix::fs::symlink;

        let fixture = Fixture::new();
        fixture.write("src/lib.rs");
        fixture.write("src/nested/mod.rs");
        fixture.write("src/generated.tmp");
        fixture.write("ignored/skip.rs");
        fixture.write(".hidden/skip.rs");
        for index in 0..192 {
            fixture.write(format!("many/{index:03}-{}", "x".repeat(180)));
        }
        fixture.write(".gitignore");
        fs::write(fixture.root.join(".gitignore"), b"ignored/\n").expect("write ignore rule");
        symlink("src", fixture.root.join("source-link")).expect("create directory symlink");
        symlink("missing-target", fixture.root.join("dangling-link"))
            .expect("create dangling symlink");

        let cases = [
            ("baseline", WalkOptions::default().sort(true)),
            ("metadata", WalkOptions::default().sort(true).metadata(true)),
            (
                "directories_only",
                WalkOptions::default().sort(true).directories_only(true),
            ),
            (
                "files_only",
                WalkOptions::default().sort(true).files_only(true),
            ),
            (
                "skip_hidden",
                WalkOptions::default().sort(true).skip_hidden(true),
            ),
            (
                "follow_symlinks",
                WalkOptions::default().sort(true).follow_symlinks(true),
            ),
            ("max_depth", WalkOptions::default().sort(true).max_depth(1)),
        ];
        for (name, options) in cases {
            let walker = Walker::new(&fixture.root)
                .threads(1)
                .include("**/*")
                .expect("valid include")
                .exclude("**/*.tmp")
                .expect("valid exclude")
                .respect_git_ignore(true)
                .error_policy(ErrorPolicy::Collect)
                .options(options);
            let native = walker.clone().collect().expect("native walk succeeds");
            let (portable_entries, portable_errors) = collect_with_portable_backend(&walker);

            assert_eq!(
                describe_entries(native.entries(), &fixture.root),
                describe_entries(&portable_entries, &fixture.root),
                "native {name} differs from portable"
            );
            assert_eq!(
                describe_errors(native.errors(), &fixture.root),
                describe_errors(&portable_errors, &fixture.root),
                "native {name} errors differ from portable"
            );
            if name == "follow_symlinks" {
                assert_eq!(
                    describe_errors(native.errors(), &fixture.root),
                    vec![(PathBuf::from("dangling-link"), "metadata")]
                );
            } else {
                assert!(native.errors().is_empty(), "native {name} errors");
            }
        }
    }

    #[cfg(any(
        all(feature = "native-macos", target_os = "macos"),
        all(feature = "native-linux", target_os = "linux")
    ))]
    #[test]
    fn native_backend_matches_portable_unreadable_directory_error() {
        use std::os::unix::fs::{MetadataExt, PermissionsExt};

        let fixture = Fixture::new();
        if fs::metadata(&fixture.root)
            .expect("fixture root metadata")
            .uid()
            == 0
        {
            return;
        }
        fixture.write("visible.rs");
        fixture.write("locked/secret.rs");
        let locked = fixture.root.join("locked");
        let original_permissions = fs::metadata(&locked)
            .expect("locked directory metadata")
            .permissions();
        fs::set_permissions(&locked, fs::Permissions::from_mode(0o0))
            .expect("make locked directory unreadable");

        let walker = Walker::new(&fixture.root)
            .threads(1)
            .error_policy(ErrorPolicy::Collect)
            .options(WalkOptions::default().sort(true));
        let native = walker.clone().collect().expect("native walk succeeds");
        let (portable_entries, portable_errors) = collect_with_portable_backend(&walker);

        fs::set_permissions(&locked, original_permissions)
            .expect("restore locked directory permissions");
        assert_eq!(
            describe_entries(native.entries(), &fixture.root),
            describe_entries(&portable_entries, &fixture.root),
            "native unreadable-directory entries differ from portable"
        );
        assert_eq!(
            describe_errors(native.errors(), &fixture.root),
            describe_errors(&portable_errors, &fixture.root),
            "native unreadable-directory errors differ from portable"
        );
        assert_eq!(
            describe_errors(native.errors(), &fixture.root),
            vec![(PathBuf::from("locked"), "read_dir")]
        );
    }

    #[cfg(any(
        all(feature = "native-macos", target_os = "macos"),
        all(feature = "native-linux", target_os = "linux")
    ))]
    type DescribedEntry = (PathBuf, bool, bool, usize, Option<(u64, bool, bool)>);

    #[cfg(any(
        all(feature = "native-macos", target_os = "macos"),
        all(feature = "native-linux", target_os = "linux")
    ))]
    fn collect_with_portable_backend(walker: &Walker) -> (Vec<WalkEntry>, Vec<super::WalkError>) {
        let mut state = super::WalkState::new(walker, &super::keep_every_entry);
        state
            .walk_directory(
                &super::StdBackend,
                directory_task(
                    walker,
                    &super::StdBackend,
                    walker
                        .roots()
                        .next()
                        .expect("a walk has a root")
                        .to_path_buf(),
                ),
            )
            .expect("portable walk succeeds");
        if walker.options.sort {
            state
                .entries
                .sort_by(|left, right| left.path.cmp(&right.path));
        }
        (state.entries, state.errors)
    }

    #[cfg(any(
        all(feature = "native-macos", target_os = "macos"),
        all(feature = "native-linux", target_os = "linux")
    ))]
    fn describe_entries(entries: &[WalkEntry], root: &Path) -> Vec<DescribedEntry> {
        entries
            .iter()
            .map(|entry| {
                (
                    entry
                        .path()
                        .strip_prefix(root)
                        .expect("entry belongs to fixture")
                        .to_path_buf(),
                    entry.is_dir(),
                    entry.is_symlink(),
                    entry.depth(),
                    entry.metadata().map(|metadata| {
                        (
                            metadata.len(),
                            metadata.file_type().is_dir(),
                            metadata.file_type().is_symlink(),
                        )
                    }),
                )
            })
            .collect()
    }

    #[cfg(any(
        all(feature = "native-macos", target_os = "macos"),
        all(feature = "native-linux", target_os = "linux")
    ))]
    fn describe_errors(errors: &[super::WalkError], root: &Path) -> Vec<(PathBuf, &'static str)> {
        errors
            .iter()
            .map(|error| {
                (
                    error
                        .path()
                        .strip_prefix(root)
                        .expect("error belongs to fixture")
                        .to_path_buf(),
                    error.operation(),
                )
            })
            .collect()
    }

    #[test]
    fn a_failed_root_is_reported_under_every_error_policy() {
        let missing = std::env::temp_dir().join(format!(
            "ferralk-missing-{}",
            NEXT_FIXTURE.fetch_add(1, Ordering::Relaxed)
        ));
        let collected = Walker::new(&missing)
            .error_policy(ErrorPolicy::Collect)
            .collect()
            .expect("collect policy retains the error");
        assert_eq!(collected.errors().len(), 1);
        for threads in [1, 4] {
            let skipped = Walker::new(&missing)
                .threads(threads)
                .error_policy(ErrorPolicy::Skip)
                .collect()
                .expect("Skip keeps walking after a caller-supplied root failure");
            assert_eq!(skipped.errors().len(), 1);
            assert_eq!(skipped.errors()[0].operation(), "read_dir");
            assert_eq!(skipped.errors()[0].path(), missing);
        }
        let streamed = Walker::new(&missing)
            .error_policy(ErrorPolicy::Skip)
            .stream()
            .collect::<Result<Vec<_>, _>>()
            .expect_err("stream reports a failed caller-supplied root under Skip");
        assert_eq!(streamed.operation(), "read_dir");
        assert_eq!(streamed.path(), missing);
        assert!(
            Walker::new(&missing)
                .error_policy(ErrorPolicy::Abort)
                .collect()
                .is_err()
        );
    }

    #[test]
    fn a_plain_file_root_reports_not_a_directory_without_emitting_it() {
        let fixture = Fixture::new();
        let file = fixture.root.join("not-a-directory.txt");
        fs::write(&file, b"fixture").expect("write file root");

        for threads in [1, 4] {
            let result = Walker::new(&file)
                .threads(threads)
                .error_policy(ErrorPolicy::Skip)
                .collect()
                .expect("root error is collected while the walk completes");
            assert!(result.entries().is_empty());
            assert_eq!(result.errors().len(), 1);
            assert_eq!(result.errors()[0].operation(), "read_dir");
            assert_eq!(result.errors()[0].path(), file);
        }
    }

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

        let fixture = Fixture::new();
        fixture.write("real/inside.txt");
        let link = fixture.root.join("linked-root");
        symlink("real", &link).expect("create directory symlink root");

        for threads in [1, 4] {
            for follow_symlinks in [false, true] {
                let result = Walker::new(&link)
                    .threads(threads)
                    .options(WalkOptions::default().follow_symlinks(follow_symlinks))
                    .collect()
                    .expect("directory symlink root is opened");
                assert_eq!(
                    relative_paths(result.entries(), &link),
                    vec![PathBuf::from("inside.txt")]
                );
            }
        }
    }

    #[test]
    fn cancellation_returns_a_partial_result_without_an_io_error() {
        let fixture = Fixture::new();
        fixture.write("src/main.rs");
        let cancellation = CancellationToken::default();
        cancellation.cancel();

        let result = Walker::new(&fixture.root)
            .cancellation(cancellation)
            .collect()
            .expect("cancellation is a normal partial result");
        assert!(result.was_cancelled());
        assert!(result.entries().is_empty());
        assert!(result.errors().is_empty());
    }

    #[test]
    fn stream_yields_filtered_entries_incrementally_and_honours_cancellation() {
        let fixture = Fixture::new();
        fixture.write("src/main.rs");
        fixture.write("src/lib.txt");

        let mut stream = Walker::new(&fixture.root)
            .include("**/*.rs")
            .expect("valid include")
            .stream();
        let entries = stream
            .by_ref()
            .map(|entry| entry.expect("fixture has no I/O errors"))
            .collect::<Vec<_>>();
        assert_eq!(
            relative_paths(&entries, &fixture.root),
            vec![PathBuf::from("src/main.rs")]
        );
        assert!(!stream.was_cancelled());

        let cancellation = CancellationToken::default();
        cancellation.cancel();
        let mut cancelled = Walker::new(&fixture.root)
            .cancellation(cancellation)
            .stream();
        assert!(cancelled.next().is_none());
        assert!(cancelled.was_cancelled());
    }

    #[test]
    fn path_bytes_bridge_entries_to_byte_first_matchers() {
        let fixture = Fixture::new();
        fixture.write("src/main.rs");

        let result = Walker::new(&fixture.root)
            .collect()
            .expect("fixture has no I/O errors");
        let entry = result
            .entries()
            .iter()
            .find(|entry| entry.path().ends_with("src/main.rs"))
            .expect("walk reports the fixture file");
        let matcher = Pattern::compile(
            "**/main.rs",
            PatternOptions::default().recursive_double_star(true),
        )
        .expect("valid pattern");

        assert_eq!(
            entry.path_bytes(),
            entry.path().as_os_str().as_encoded_bytes()
        );
        assert!(matcher.is_match(entry.path_bytes()));
    }

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

        // Three names, one directory. The guard keys on what a name reaches,
        // not on the name, so whichever one the walk happens to take first,
        // the other two are recognised as the same place. Each frontend keeps
        // its own visited set, so each is checked.
        let fixture = Fixture::new();
        fixture.write("real/inside.txt");
        symlink("real", fixture.root.join("first")).expect("create first directory symlink");
        symlink("real", fixture.root.join("second")).expect("create second directory symlink");
        let options = WalkOptions::default().follow_symlinks(true).sort(true);

        let count_inside = |paths: Vec<PathBuf>| {
            paths
                .iter()
                .filter(|path| path.file_name().is_some_and(|name| name == "inside.txt"))
                .count()
        };

        for threads in [1, 4] {
            let result = Walker::new(&fixture.root)
                .threads(threads)
                .options(options)
                .collect()
                .expect("walk succeeds");
            assert_eq!(
                count_inside(relative_paths(result.entries(), &fixture.root)),
                1,
                "collect with {threads} thread(s) entered the directory more than once"
            );
        }

        let streamed = Walker::new(&fixture.root)
            .options(options)
            .stream()
            .map(|entry| entry.expect("fixture has no I/O errors"))
            .collect::<Vec<_>>();
        assert_eq!(
            count_inside(relative_paths(&streamed, &fixture.root)),
            1,
            "the stream entered the directory more than once"
        );
    }

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

        let fixture = Fixture::new();
        fixture.write("real/inside.txt");
        symlink("real", fixture.root.join("linked")).expect("create directory symlink");

        let without_following = Walker::new(&fixture.root)
            .options(WalkOptions::default().sort(true))
            .collect()
            .expect("walk succeeds");
        assert!(
            !relative_paths(without_following.entries(), &fixture.root)
                .contains(&PathBuf::from("linked/inside.txt"))
        );
        let link = without_following
            .entries()
            .iter()
            .find(|entry| entry.basename() == Some(std::ffi::OsStr::new("linked")))
            .expect("symlink is reported");
        assert!(link.is_symlink());
        assert_eq!(link.kind(), WalkEntryKind::Symlink);

        let with_following = Walker::new(&fixture.root)
            .options(WalkOptions::default().follow_symlinks(true).sort(true))
            .collect()
            .expect("walk succeeds");
        assert_eq!(
            relative_paths(with_following.entries(), &fixture.root)
                .iter()
                .filter(|path| path.file_name().is_some_and(|name| name == "inside.txt"))
                .count(),
            1
        );
    }

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

        let fixture = Fixture::new();
        fixture.write("left/ok.txt");
        fixture.write("right/ok.txt");
        symlink("missing-left", fixture.root.join("left/dangling"))
            .expect("create left dangling symlink");
        symlink("missing-right", fixture.root.join("right/dangling"))
            .expect("create right dangling symlink");

        let options = WalkOptions::default().follow_symlinks(true).sort(true);
        let serial = Walker::new(&fixture.root)
            .threads(1)
            .options(options)
            .error_policy(ErrorPolicy::Collect)
            .collect()
            .expect("serial walk retains errors");
        let parallel = Walker::new(&fixture.root)
            .threads(4)
            .options(options)
            .error_policy(ErrorPolicy::Collect)
            .collect()
            .expect("parallel walk retains errors");

        let error_paths = |result: &super::WalkResult| {
            let mut errors = result
                .errors()
                .iter()
                .map(|error| {
                    (
                        error.operation(),
                        error
                            .path()
                            .strip_prefix(&fixture.root)
                            .expect("error is rooted in fixture")
                            .to_path_buf(),
                    )
                })
                .collect::<Vec<_>>();
            errors.sort_unstable();
            errors
        };
        assert_eq!(error_paths(&parallel), error_paths(&serial));
        assert_eq!(parallel.errors().len(), 2);
    }

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

        let fixture = Fixture::new();
        fixture.write("left/ok.txt");
        fixture.write("right/ok.txt");
        symlink("missing-left", fixture.root.join("left/dangling"))
            .expect("create left dangling symlink");
        symlink("missing-right", fixture.root.join("right/dangling"))
            .expect("create right dangling symlink");
        let cancellation = CancellationToken::default();
        let serial_cancellation = CancellationToken::default();

        let serial_error = Walker::new(&fixture.root)
            .threads(1)
            .options(WalkOptions::default().follow_symlinks(true))
            .error_policy(ErrorPolicy::Abort)
            .cancellation(serial_cancellation.clone())
            .collect()
            .expect_err("serial abort returns the first metadata error");

        let error = Walker::new(&fixture.root)
            .threads(4)
            .options(WalkOptions::default().follow_symlinks(true))
            .error_policy(ErrorPolicy::Abort)
            .cancellation(cancellation.clone())
            .collect()
            .expect_err("abort policy returns the first metadata error");

        assert_eq!(error.operation(), "metadata");
        assert_eq!(serial_error.operation(), error.operation());
        assert!(
            !serial_cancellation.is_cancelled(),
            "serial abort leaves the caller-owned token alone"
        );
        assert!(
            !cancellation.is_cancelled(),
            "parallel abort must match serial token ownership"
        );

        let reused = Walker::new(&fixture.root)
            .threads(4)
            .cancellation(cancellation.clone())
            .collect()
            .expect("the same token can drive a later walk");
        assert!(!reused.was_cancelled());
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn preserves_non_utf8_native_paths() {
        use std::os::unix::ffi::OsStringExt;

        let fixture = Fixture::new();
        let name = std::ffi::OsString::from_vec(vec![b'n', 0xFF]);
        fixture.write(PathBuf::from(&name));

        let result = Walker::new(&fixture.root)
            .options(WalkOptions::default().sort(true))
            .collect()
            .expect("walk succeeds");
        assert_eq!(
            relative_paths(result.entries(), &fixture.root),
            vec![PathBuf::from(name)]
        );
    }
}