aft-base 0.67.1

Shared foundation for Agent Foundational Toolkit
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
//! Bound first access to a protection/filesystem boundary, not every file read.
//!
//! A request probes each directory once. Ordinary files in accessible local
//! directories stay on the caller's hot path. Network/removable/unknown volumes
//! and symlinks retain per-file isolation. Helpers own no actor or epoch guard.
use std::any::Any;
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::io::{self, Read};
use std::path::{Path, PathBuf};
#[cfg(any(test, feature = "test-support"))]
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
#[cfg(any(test, feature = "test-support"))]
use std::sync::LazyLock;
use std::sync::{Arc, Condvar, Mutex, OnceLock};
use std::time::{Duration, Instant};

use crate::protocol::Response;

pub const IO_BUDGET: Duration = Duration::from_secs(5);
/// Wall-clock budget for grep/glob index-unavailable fallback walks on the dispatch thread.
pub const FALLBACK_WALK_BUDGET: Duration = Duration::from_secs(10);
pub(crate) const WALK_PARTIAL_GAP: &str =
    "Directory walk reached its time budget; only examined entries are reported.";
/// Request budget for a mutation's path checks when no caller budget exists.
/// It matches the budget agent tool calls already run under, so a native
/// request and a tool call wait equally long for a helper to be scheduled.
pub(crate) const MUTATION_BUDGET: Duration = Duration::from_secs(25);
const MAX_IO_THREADS: usize = 64;
const IO_POOL_SIZE: usize = 8;
static NEXT_BUDGET: AtomicU64 = AtomicU64::new(1);
static HELPERS: OnceLock<Arc<Limiter>> = OnceLock::new();
#[cfg(any(test, feature = "test-support"))]
pub static THREAD_SPAWNS: AtomicUsize = AtomicUsize::new(0);
#[cfg(any(test, feature = "test-support"))]
#[derive(Default)]
pub struct Measurements {
    pub(crate) dispatches: AtomicUsize,
    pub round_trips: AtomicUsize,
    pub directory_probes: AtomicUsize,
    pub traversal_probes: AtomicUsize,
}

#[derive(Clone, Debug)]
struct Failure {
    code: &'static str,
    message: String,
}
impl std::fmt::Display for Failure {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(&self.message)
    }
}
impl std::error::Error for Failure {}

/// Keep admission timeouts distinct when callers turn I/O errors into responses.
pub fn timeout_code(error: &io::Error) -> &'static str {
    error
        .get_ref()
        .and_then(|error| error.downcast_ref::<Failure>())
        .map_or("read_blocked", |failure| failure.code)
}

#[derive(Clone)]
struct ProbeError {
    kind: io::ErrorKind,
    message: String,
    raw_os_error: Option<i32>,
    failure: Option<Failure>,
}
impl ProbeError {
    fn from(error: &io::Error) -> Self {
        Self {
            kind: error.kind(),
            message: error.to_string(),
            raw_os_error: error.raw_os_error(),
            failure: error
                .get_ref()
                .and_then(|error| error.downcast_ref::<Failure>())
                .cloned(),
        }
    }
    fn error(&self) -> io::Error {
        if let Some(failure) = &self.failure {
            return io::Error::new(self.kind, failure.clone());
        }
        self.raw_os_error
            .map(io::Error::from_raw_os_error)
            .unwrap_or_else(|| io::Error::new(self.kind, self.message.clone()))
    }
}
#[derive(Clone, Copy)]
struct Access {
    direct: bool,
}
struct Probe {
    state: Mutex<ProbeState>,
    ready: Condvar,
    activity: Mutex<ProbeActivity>,
}
#[derive(Default)]
struct ProbeActivity {
    path: Option<PathBuf>,
    progress: Option<Instant>,
    walking: bool,
    cancelled: Option<Arc<AtomicBool>>,
}
struct ProbeState {
    result: Option<Result<Access, ProbeError>>,
    deadline: Instant,
    started: Option<Instant>,
}
impl Probe {
    fn queued(deadline: Instant) -> Self {
        Self {
            state: Mutex::new(ProbeState {
                result: None,
                deadline,
                started: None,
            }),
            ready: Condvar::new(),
            activity: Mutex::new(ProbeActivity::default()),
        }
    }
    fn set_deadline(&self, deadline: Instant, started: Option<Instant>) {
        let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
        state.deadline = deadline;
        state.started = started;
        self.ready.notify_all();
    }
}
#[derive(Clone)]
pub struct Budget {
    id: u64,
    disclosure_only: bool,
    pub deadline: Instant,
    failure: Arc<Mutex<Option<Failure>>>,
    failed: Arc<AtomicBool>,
    walk_partial: Arc<AtomicBool>,
    /// A read stall alone does not mean the walk reached its own deadline.
    walk_time_limit_reached: Arc<AtomicBool>,
    walk_gap: Arc<Mutex<Option<String>>>,
    large_read_skips: Arc<Mutex<SkipCollector>>,
    directories: Arc<Mutex<HashMap<PathBuf, Arc<Probe>>>>,
    traversable: Arc<Mutex<HashSet<PathBuf>>>,
    permissions: Arc<Mutex<Vec<PermissionObservation>>>,
    /// Keep unreadable walk descendants out of `permissions`: consent uses that
    /// list to ask the user to grant access to explicitly named folders.
    walk_permissions:
        Arc<Mutex<std::collections::BTreeMap<PathBuf, std::collections::BTreeSet<PathBuf>>>>,
    walk_names: Arc<Mutex<HashMap<PathBuf, PathBuf>>>,
    walk_root: Option<PathBuf>,
    /// Set once the end of the budget has been kept back for the reply.
    reply_margin_kept: bool,
    #[cfg(any(test, feature = "test-support"))]
    pub measurements: Arc<Measurements>,
    #[cfg(any(test, feature = "test-support"))]
    access_budget: Duration,
    #[cfg(any(test, feature = "test-support"))]
    access_budget_by_path: Arc<HashMap<PathBuf, Duration>>,
}

#[derive(Default)]
struct SkipCollector {
    files: std::collections::BTreeMap<PathBuf, std::collections::BTreeSet<String>>,
    scopes: usize,
}
impl Budget {
    /// Collect skips for native search without adding a request deadline or
    /// sticky read failures. I/O helpers see no budget; parallel readers carry
    /// the disclosure context with `capture` instead.
    pub(crate) fn disclosure_only() -> Self {
        let mut budget = Self::after(IO_BUDGET);
        budget.disclosure_only = true;
        budget
    }
    pub fn capped(&self, deadline: Instant) -> Self {
        let mut budget = self.clone();
        budget.deadline = budget.deadline.min(deadline);
        budget
    }
    pub fn after(duration: Duration) -> Self {
        Self {
            id: NEXT_BUDGET.fetch_add(1, Ordering::Relaxed),
            disclosure_only: false,
            deadline: Instant::now() + duration,
            failure: Arc::new(Mutex::new(None)),
            failed: Arc::new(AtomicBool::new(false)),
            walk_partial: Arc::new(AtomicBool::new(false)),
            walk_time_limit_reached: Arc::new(AtomicBool::new(false)),
            walk_gap: Arc::new(Mutex::new(None)),
            large_read_skips: capture()
                .map(|budget| budget.large_read_skips)
                .unwrap_or_default(),
            directories: Arc::new(Mutex::new(HashMap::new())),
            traversable: Arc::new(Mutex::new(HashSet::new())),
            permissions: Arc::new(Mutex::new(Vec::new())),
            walk_permissions: Arc::default(),
            walk_names: Arc::default(),
            walk_root: None,
            reply_margin_kept: false,
            #[cfg(any(test, feature = "test-support"))]
            measurements: Arc::new(Measurements::default()),
            #[cfg(any(test, feature = "test-support"))]
            access_budget: IO_BUDGET,
            #[cfg(any(test, feature = "test-support"))]
            access_budget_by_path: Arc::new(HashMap::new()),
        }
    }
    pub fn permissions(&self) -> Vec<PermissionObservation> {
        self.permissions
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .clone()
    }
    #[cfg(any(test, feature = "test-support"))]
    pub fn measurements(&self) -> (usize, usize) {
        (
            self.measurements.dispatches.load(Ordering::Relaxed),
            self.measurements.round_trips.load(Ordering::Relaxed),
        )
    }
    #[cfg(any(test, feature = "test-support"))]
    pub fn with_access_budget(mut self, duration: Duration) -> Self {
        self.access_budget = duration;
        self
    }
    #[cfg(all(
        any(test, feature = "test-support"),
        any(target_os = "macos", target_os = "linux")
    ))]
    pub fn with_path_access_budget(mut self, path: &Path, duration: Duration) -> Self {
        Arc::make_mut(&mut self.access_budget_by_path).insert(path.to_path_buf(), duration);
        self
    }
}

#[derive(Clone, Debug)]
pub struct PermissionObservation {
    pub folder: PathBuf,
    pub readable: bool,
}

pub fn name_walk_root(root: &Path, name: &Path) {
    if let Some(budget) = current() {
        budget
            .walk_names
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .entry(crate::path_identity::lexical_normalize(root))
            .or_insert_with(|| name.to_path_buf());
    }
}

fn walk_permission_gap(root: &Path, display_root: &Path, folders: &[PathBuf]) -> String {
    let count = folders.len();
    let mut names = folders
        .iter()
        .take(3)
        .map(|folder| {
            folder
                .strip_prefix(root)
                .ok()
                .filter(|relative| !relative.as_os_str().is_empty())
                .unwrap_or(folder)
                .display()
                .to_string()
        })
        .collect::<Vec<_>>();
    if count > 3 {
        names.push(format!("and {} more", count - 3));
    }
    let (folders, pronoun) = if count == 1 {
        ("folder", "it")
    } else {
        ("folders", "them")
    };
    format!(
        "macOS did not let AFT read {count} {folders} under {}, so the result skips {pronoun}: {}.",
        display_root.display(),
        names.join(", ")
    )
}

#[cfg(test)]
mod walk_permission_gap_tests {
    use super::*;

    #[test]
    fn macos_walk_permission_gap_counts_and_relative_paths() {
        let root = Path::new("/walk");
        let folders = (1..=38)
            .map(|index| root.join(format!("protected-{index}")))
            .collect::<Vec<_>>();
        for (count, expected) in [
            (1, "macOS did not let AFT read 1 folder under /walk, so the result skips it: protected-1."),
            (2, "macOS did not let AFT read 2 folders under /walk, so the result skips them: protected-1, protected-2."),
            (3, "macOS did not let AFT read 3 folders under /walk, so the result skips them: protected-1, protected-2, protected-3."),
            (38, "macOS did not let AFT read 38 folders under /walk, so the result skips them: protected-1, protected-2, protected-3, and 35 more."),
        ] {
            assert_eq!(walk_permission_gap(root, root, &folders[..count]), expected);
        }
    }

    #[test]
    fn macos_walk_permission_gap_preserves_other_gaps_and_is_not_a_card_observation() {
        let mut budget = Budget::after(Duration::from_secs(10));
        budget.walk_root = Some(PathBuf::from("/walk"));
        budget
            .walk_names
            .lock()
            .unwrap()
            .insert(PathBuf::from("/walk"), PathBuf::from("."));
        budget.walk_partial.store(true, Ordering::Release);
        budget
            .walk_time_limit_reached
            .store(true, Ordering::Release);
        with_budget(Some(budget.clone()), || {
            for _ in 0..2 {
                observe_permission(
                    Path::new("/walk/protected"),
                    &Err(io::Error::from_raw_os_error(1)),
                    true,
                );
            }
            assert!(
                budget.permissions().is_empty(),
                "a walk denial must never reach card creation"
            );
            let response = finish_response(Response::success(
                "walk",
                serde_json::json!({"text":"readable.rs\n\nshown 1 of 1 files"}),
            ));
            let response = finish_response(response);
            assert!(response.success);
            assert_eq!(response.data["complete"], false);
            assert_eq!(
                response.data["gaps"],
                serde_json::json!([
                WALK_PARTIAL_GAP,
                "macOS did not let AFT read 1 folder under ., so the result skips it: protected."
            ])
            );
            let text = response.data["text"].as_str().unwrap();
            assert_eq!(text.matches("macOS did not let").count(), 1);
            assert!(text.contains(WALK_PARTIAL_GAP));
            assert!(text.ends_with("shown 1 of 1 files"));
        });
    }
}

fn observe_permission(path: &Path, result: &io::Result<Access>, macos: bool) {
    if !macos {
        return;
    }
    let readable = match result {
        Ok(_) => true,
        Err(error) if error.raw_os_error() == Some(1) => false,
        _ => return,
    };
    if let Some(budget) = current() {
        let folder = permission_folder(path);
        if let Some(root) = budget
            .walk_root
            .as_ref()
            .filter(|root| !readable && folder != **root && folder.starts_with(root))
        {
            budget
                .walk_permissions
                .lock()
                .unwrap_or_else(|e| e.into_inner())
                .entry(root.clone())
                .or_default()
                .insert(folder);
            return;
        }
        budget
            .permissions
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .push(PermissionObservation { folder, readable });
    }
}

// macOS privacy permissions apply to the enclosing protected folder, not each
// descendant directory.
// This is only a display/deduplication identity; it never changes path policy.
fn permission_folder(path: &Path) -> PathBuf {
    let home = std::env::var_os("HOME").map(PathBuf::from);
    if let Some(home) = home {
        for folder in [
            "Desktop",
            "Documents",
            "Downloads",
            "Pictures",
            "Music",
            "Movies",
        ] {
            let folder = home.join(folder);
            if path.starts_with(&folder) {
                return folder;
            }
        }
    }
    path.to_path_buf()
}

/// The helper only probes access. The caller may mutate only after this returns.
pub fn probe_access(req_id: &str, path: &Path) -> Result<(), Response> {
    // A new target may have several nonexistent ancestors. Probe the nearest
    // existing directory without creating any of those missing components.
    let result = probe_target(path);
    match result {
        Ok(()) => Ok(()),
        Err(error) if missing_probe_target(&error, path, cfg!(windows)) => {
            let mut parent = path.parent();
            while let Some(folder) = parent {
                match probe_directory(folder, None) {
                    Ok(()) => return Ok(()),
                    Err(error) if missing_probe_target(&error, folder, cfg!(windows)) => {
                        parent = folder.parent()
                    }
                    Err(error) => return Err(access_error(req_id, folder, error)),
                }
            }
            Ok(())
        }
        Err(error) => Err(access_error(req_id, path, error)),
    }
}

fn missing_probe_target(error: &io::Error, path: &Path, windows: bool) -> bool {
    error.kind() == io::ErrorKind::NotFound
        // Win32 rejects a literal glob with ERROR_INVALID_NAME (123). Probe its
        // existing ancestor; the handler expands and validates concrete files.
        // Access-denied errors and ordinary invalid names still fail closed.
        || (windows
            && error.raw_os_error() == Some(123)
            && path.components().any(|component| {
                matches!(component, std::path::Component::Normal(name)
                    if name.to_string_lossy().contains(['*', '?', '[', ']', '{', '}']))
            }))
}

fn access_error(req_id: &str, path: &Path, error: io::Error) -> Response {
    let code = if cfg!(target_os = "macos") && error.raw_os_error() == Some(1) {
        let folder = current()
            .and_then(|budget| {
                budget
                    .permissions()
                    .into_iter()
                    .find(|p| !p.readable)
                    .map(|p| p.folder)
            })
            .unwrap_or_else(|| permission_folder(path.parent().unwrap_or(path)));
        observe_permission(&folder, &Err(io::Error::from_raw_os_error(1)), true);
        return Response::error_with_data(req_id, "macos_permission_denied", format!("macOS denied access to {}; grant ck-aft access in System Settings → Privacy & Security, then retry", folder.display()), serde_json::json!({"folder":folder,"program":"ck-aft"}));
    } else if error.kind() == io::ErrorKind::TimedOut {
        timeout_code(&error)
    } else {
        "path_access_denied"
    };
    Response::error_with_data(
        req_id,
        code,
        format!("{}: {error}", path.display()),
        serde_json::json!({"path":path,"os_error":error.raw_os_error()}),
    )
}

pub fn finish_response(mut response: Response) -> Response {
    response = finish_response_without_skips(response);
    response
}

fn finish_response_without_skips(mut response: Response) -> Response {
    if matches!(
        response.data["code"].as_str(),
        Some("denied_floor" | "path_outside_root" | "access_read_only")
    ) {
        return response;
    }
    if let Some(folder) = current().and_then(|budget| {
        budget
            .permissions()
            .into_iter()
            .find(|p| !p.readable)
            .map(|p| p.folder)
    }) {
        return Response::error_with_data(&response.id, "macos_permission_denied", format!("macOS denied access to {}; grant ck-aft access in System Settings → Privacy & Security, then retry", folder.display()), serde_json::json!({"folder":folder,"program":"ck-aft"}));
    }
    let error = current().and_then(|budget| {
        budget
            .failure
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .clone()
    });
    let permission_gaps = current().map_or_else(Vec::new, |budget| {
        let names = budget.walk_names.lock().unwrap_or_else(|e| e.into_inner());
        budget
            .walk_permissions
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .iter()
            .map(|(root, folders)| {
                walk_permission_gap(
                    root,
                    names.get(root).unwrap_or(root),
                    &folders.iter().cloned().collect::<Vec<_>>(),
                )
            })
            .collect::<Vec<_>>()
    });
    if response.success
        && (current().is_some_and(|b| b.walk_partial.load(Ordering::Acquire))
            || !permission_gaps.is_empty())
    {
        let named_gap = error.map(|error| error.message).or_else(|| {
            current().and_then(|budget| {
                budget
                    .walk_gap
                    .lock()
                    .unwrap_or_else(|e| e.into_inner())
                    .clone()
            })
        });
        let mut gaps = Vec::new();
        if current().is_some_and(|b| b.walk_time_limit_reached.load(Ordering::Acquire)) {
            gaps.push(WALK_PARTIAL_GAP.to_string());
        }
        if let Some(gap) = named_gap {
            if gap != WALK_PARTIAL_GAP {
                gaps.push(gap);
            }
        }
        gaps.extend(permission_gaps);
        if let Some(existing) = response.data["gaps"].as_array() {
            gaps.retain(|gap| !existing.iter().any(|value| value.as_str() == Some(gap)));
        }
        if gaps.is_empty() {
            return response;
        }
        let gap = gaps.join("\n");
        response.data["complete"] = serde_json::json!(false);
        if let Some(existing) = response.data["gaps"].as_array_mut() {
            existing.extend(gaps.into_iter().map(serde_json::Value::String));
        } else {
            response.data["gaps"] = serde_json::json!(gaps);
        }
        let text = response.data["text"].as_str().unwrap_or_default();
        // Coverage details precede the shared trailer so the last line remains
        // the list's machine-readable count and narrowing advice.
        let text = match text.rsplit_once("\n\n") {
            Some((body, trailer)) if trailer.starts_with("shown ") => {
                format!("{body}\n\n{gap}\n\n{trailer}")
            }
            _ => format!("{text}\n\n{gap}"),
        };
        response.data["text"] = serde_json::json!(text);
        return response;
    }
    match error {
        Some(error) => Response::error(&response.id, error.code, error.message),
        None => response,
    }
}

test_support_visibility! {
/// A ceiling skip is a coverage gap, not a sticky I/O failure: other files
/// in the same request must still be readable.
pub(crate) fn note_large_read_skip(path: &Path) {
    note_skipped_file(path, crate::large_read_counts::WHOLE_READ_SKIP_REASON);
}
}

pub fn note_skipped_file(path: &Path, reason: &str) {
    if let Some(budget) = capture() {
        budget
            .large_read_skips
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .files
            .entry(path.to_path_buf())
            .or_default()
            .insert(reason.to_string());
    }
}

/// Keep all omission categories until the outer command has finished. Nested
/// commands and workers that inherit the budget share the collector rather
/// than adding a response field.
pub fn with_skip_disclosure(run: impl FnOnce() -> Response) -> Response {
    let _scope = enter_disclosure_if_absent();
    let budget = capture().unwrap();
    let root = {
        let mut skips = budget
            .large_read_skips
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let root = skips.scopes == 0;
        skips.scopes += 1;
        root
    };
    struct Depth(Arc<Mutex<SkipCollector>>);
    impl Drop for Depth {
        fn drop(&mut self) {
            self.0.lock().unwrap_or_else(|e| e.into_inner()).scopes -= 1;
        }
    }
    let depth = Depth(budget.large_read_skips);
    let mut response = run();
    drop(depth);
    if root {
        disclose_large_read_skips(&mut response);
    }
    response
}

pub fn skip_disclosure_active() -> bool {
    capture().is_some_and(|budget| {
        budget
            .large_read_skips
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .scopes
            != 0
    })
}

test_support_visibility! {
pub(crate) fn disclose_large_read_skips(response: &mut Response) {
    if !response.success {
        return;
    }
    let Some(budget) = capture() else { return };
    let mut skipped = budget
        .large_read_skips
        .lock()
        .unwrap_or_else(|e| e.into_inner());
    if skipped.scopes != 0 {
        return;
    }
    if let Some(existing) = response.data["skipped_files"].as_array() {
        for entry in existing {
            if let (Some(file), Some(reason)) = (entry["file"].as_str(), entry["reason"].as_str()) {
                let reasons = skipped.files.entry(PathBuf::from(file)).or_default();
                if let Some(all) = entry["reasons"].as_array() {
                    reasons.extend(
                        all.iter()
                            .filter_map(|reason| reason.as_str().map(str::to_string)),
                    );
                } else {
                    reasons.insert(reason.to_string());
                }
            }
        }
    }
    if skipped.files.is_empty() {
        return;
    }
    let total = skipped.files.len();
    let names = skipped.files.iter().take(20).map(|(path, reasons)| {
        let mut entry = serde_json::json!({"file":path,"reason":reasons.iter().cloned().collect::<Vec<_>>().join("; ")});
        if reasons.len() > 1 { entry["reasons"] = serde_json::json!(reasons); }
        entry
    }).collect::<Vec<_>>();
    response.data["complete"] = serde_json::json!(false);
    response.data["skipped_files"] = serde_json::json!(names);
    response.data["skipped_files_remaining"] = serde_json::json!(total - names.len());
    let envelope = crate::list_surfaces::search::skipped_files_envelope(names.len(), total);
    response.data["skipped_files_list_envelope"] = serde_json::json!(envelope);
    // Leave empty search text for format_search to supply "No results." and
    // notes about capped enumeration, more available rows and degraded search.
    if let Some(text) = response.data["text"]
        .as_str()
        .filter(|text| !text.is_empty())
    {
        response.data["text"] =
            serde_json::json!(append_skipped_files_text(text.to_string(), &response.data));
    }
}

}

pub fn append_skipped_files_text(text: String, data: &serde_json::Value) -> String {
    let gap = skipped_files_text(data);
    if gap.is_empty() {
        return text;
    }
    let text = strip_skipped_files_text(&text, data);
    match text.rsplit_once("\n\n") {
        Some((body, trailer)) if trailer.starts_with("shown ") => {
            format!("{body}\n\n{gap}\n\n{trailer}")
        }
        _ if text.is_empty() => gap,
        _ => format!("{text}\n\n{gap}"),
    }
}

pub fn strip_skipped_files_text(text: &str, data: &serde_json::Value) -> String {
    let gap = skipped_files_text(data);
    if gap.is_empty() {
        return text.to_string();
    }
    if text == gap {
        return String::new();
    }
    text.replacen(&format!("\n\n{gap}"), "", 1)
}

fn skipped_files_text(data: &serde_json::Value) -> String {
    if data.get("skipped_files_list_envelope").is_none() {
        return String::new();
    }
    let Some(files) = data["skipped_files"].as_array() else {
        return String::new();
    };
    let mut groups = std::collections::BTreeMap::<&str, Vec<&str>>::new();
    for file in files {
        if let (Some(path), Some(reason)) = (file["file"].as_str(), file["reason"].as_str()) {
            groups.entry(reason).or_default().push(path);
        }
    }
    let mut gap = groups
        .into_iter()
        .map(|(reason, names)| format!("{reason}\n{}", names.join("\n")))
        .collect::<Vec<_>>()
        .join("\n\n");
    let trailer =
        crate::ndjson_text::build_ndjson_text("", data, Some("payload.skipped_files"), false);
    if !trailer.is_empty() {
        gap.push_str("\n\n");
        gap.push_str(&trailer);
    }
    gap
}
thread_local! {
    static CURRENT: RefCell<Option<Budget>> = const { RefCell::new(None) };
    static ACTIVE_PROBE: RefCell<Option<Arc<Probe>>> = const { RefCell::new(None) };
    // Rayon shares the request's single-flight probes, but does not contend on
    // that map per file. Its workers remember successful lookups locally.
    static DIRECTORIES: RefCell<(u64, HashMap<PathBuf, Access>)> = RefCell::new((0, HashMap::new()));
    static HELPER_DEADLINE: std::cell::Cell<Option<Instant>> = const { std::cell::Cell::new(None) };
    static MUTATION_ADMISSION: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
    static CARRY_FACTORY: RefCell<Option<CarryFactory>> = const { RefCell::new(None) };
    static CARRY_RESTORE: RefCell<Option<Option<CarryRestore>>> = const { RefCell::new(None) };
}

/// Higher layers carry request-local state without exposing its type to I/O.
pub(crate) type Carry = Box<dyn FnOnce() -> io::Result<Box<dyn Any + Send>> + Send>;
pub type CarryFactory = Arc<dyn Fn() -> io::Result<Carry> + Send + Sync>;
type CarryRestore = Box<dyn FnOnce() + Send>;

#[cfg(any(test, feature = "test-support"))]
static TEST_HELPER_SCOPE: std::sync::OnceLock<fn() -> Box<dyn Any>> = std::sync::OnceLock::new();

#[cfg(any(test, feature = "test-support"))]
pub fn register_test_helper_scope(scope: fn() -> Box<dyn Any>) {
    // Tool-owned counters live above this module. Their owner supplies the
    // reset scope so reused helpers start each test job with clean counters.
    let _ = TEST_HELPER_SCOPE.set(scope);
}

/// Updated alongside the higher layer's thread-local state, including restores.
/// A helper also restores state first installed by its work, even if the
/// helper was entered with no carried state at all.
pub fn replace_carry_factory(factory: Option<CarryFactory>, restore: CarryRestore) {
    CARRY_RESTORE.with(|pending| {
        if let Some(first @ None) = &mut *pending.borrow_mut() {
            *first = Some(restore);
        }
    });
    CARRY_FACTORY.with(|current| *current.borrow_mut() = factory);
}

struct CarryJobScope {
    factory: Option<CarryFactory>,
    restore: Option<Option<CarryRestore>>,
}

impl CarryJobScope {
    fn enter() -> Self {
        Self {
            factory: CARRY_FACTORY.with(|current| current.borrow().clone()),
            restore: CARRY_RESTORE.with(|pending| pending.replace(Some(None))),
        }
    }
}

impl Drop for CarryJobScope {
    fn drop(&mut self) {
        let restore = CARRY_RESTORE
            .with(|pending| pending.replace(self.restore.take()))
            .flatten();
        if let Some(restore) = restore {
            restore();
        }
        CARRY_FACTORY.with(|current| *current.borrow_mut() = self.factory.take());
    }
}

#[cfg(any(test, feature = "test-support"))]
pub fn has_carry_factory() -> bool {
    CARRY_FACTORY.with(|current| current.borrow().is_some())
}

#[cfg(any(test, feature = "test-support"))]
pub fn dirty_helper_job_state() {
    MUTATION_ADMISSION.with(|flag| flag.set(true));
    DIRECTORIES.with(|cache| {
        let mut cache = cache.borrow_mut();
        cache.0 = 42;
        cache
            .1
            .insert(PathBuf::from("old"), Access { direct: true });
    });
}

#[cfg(any(test, feature = "test-support"))]
pub fn helper_job_state() -> (bool, bool) {
    (
        DIRECTORIES.with(|cache| cache.borrow().1.is_empty()),
        MUTATION_ADMISSION.with(|flag| flag.get()),
    )
}

fn carry_refusal(path: &Path) -> io::Error {
    failure(
        path,
        "read_io_queue_timeout",
        "filesystem helper did not start before the deadline; this call did not start",
    )
}

fn capture_carry(path: &Path) -> io::Result<Option<Carry>> {
    let factory = CARRY_FACTORY.with(|current| current.borrow().clone());
    factory
        .map(|factory| {
            std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| factory()))
                .ok()
                .and_then(Result::ok)
                .ok_or_else(|| carry_refusal(path))
        })
        .transpose()
}

fn enter_carry(path: &Path, carry: Option<Carry>) -> io::Result<Option<Box<dyn Any + Send>>> {
    carry
        .map(|carry| {
            std::panic::catch_unwind(std::panic::AssertUnwindSafe(carry))
                .ok()
                .and_then(Result::ok)
                .ok_or_else(|| carry_refusal(path))
        })
        .transpose()
}
pub struct Scope(Option<Budget>);
impl Drop for Scope {
    fn drop(&mut self) {
        CURRENT.with(|current| *current.borrow_mut() = self.0.take());
    }
}
pub fn current() -> Option<Budget> {
    capture().filter(|budget| !budget.disclosure_only)
}

/// Carry the request's skip collector even when native search has no I/O budget.
pub fn capture() -> Option<Budget> {
    CURRENT.with(|current| current.borrow().clone())
}

test_support_visibility! {
pub(crate) fn enter_disclosure_if_absent() -> Scope {
    enter(capture().or_else(|| Some(Budget::disclosure_only())))
}
}

/// Person approval has its own deadline; preserve the remaining filesystem and
/// reply budget when a held fetch resumes on this tool thread.
pub(crate) fn exclude_secret_approval_wait(elapsed: Duration) {
    CURRENT.with(|current| {
        if let Some(budget) = current.borrow_mut().as_mut() {
            budget.deadline += elapsed;
        }
    });
}
pub fn enter_if_absent(duration: Duration) -> Scope {
    let budget = current().unwrap_or_else(|| Budget::after(duration));
    Scope(CURRENT.with(|current| current.replace(Some(budget))))
}
/// Scope for the path checks of a mutation the user asked for (delete, edit,
/// write, ...). A helper that has not started yet has touched nothing, and a
/// mutation has no partial answer to return, so a slow-to-schedule helper (a
/// loaded machine, or a Windows process whose thread start waits on a
/// long-running DLL load) may wait for admission until the request deadline
/// instead of the per-access cap. Once the helper starts, the usual access
/// cap applies unchanged, so a blocked filesystem still fails as
/// `read_blocked` within that cap.
pub struct MutationScope {
    previous: bool,
    _scope: Scope,
}
impl Drop for MutationScope {
    fn drop(&mut self) {
        MUTATION_ADMISSION.with(|flag| flag.set(self.previous));
    }
}
pub fn enter_mutation() -> MutationScope {
    let scope = enter_if_absent(MUTATION_BUDGET);
    MutationScope {
        previous: MUTATION_ADMISSION.with(|flag| flag.replace(true)),
        _scope: scope,
    }
}
pub fn with_budget<T>(budget: Option<Budget>, work: impl FnOnce() -> T) -> T {
    let _scope = enter(budget);
    work()
}
pub fn enter(budget: Option<Budget>) -> Scope {
    Scope(CURRENT.with(|current| current.replace(budget)))
}
/// Keep the last `margin` of the current request's budget for its reply:
/// move the filesystem deadline `margin` earlier for the rest of the
/// command. A request calls this before its last filesystem work, so a
/// stalled read fails while the reply can still reach the caller in time.
/// Only the first call moves the deadline, so a command that reads several
/// documents keeps one margin, not one per document.
pub fn keep_reply_margin(margin: Duration) {
    CURRENT.with(|current| {
        if let Some(budget) = current.borrow_mut().as_mut() {
            if !budget.reply_margin_kept {
                budget.reply_margin_kept = true;
                budget.deadline = budget
                    .deadline
                    .checked_sub(margin)
                    .unwrap_or(budget.deadline);
            }
        }
    });
}
fn deadline(at: Option<Instant>) -> Instant {
    request_deadline(at)
        .into_iter()
        .fold(Instant::now() + IO_BUDGET, Instant::min)
}
fn request_deadline(at: Option<Instant>) -> Option<Instant> {
    at.into_iter()
        .chain(current().map(|budget| budget.deadline))
        .min()
}

/// Check a synchronous mutation loop without dispatching another I/O helper.
/// Record the same timeout as a bounded filesystem call so response formatting
/// returns the existing read_deadline_exceeded reply.
pub fn check_request_deadline(path: &Path, now: Instant) -> io::Result<()> {
    if let Some(error) = prior_failure() {
        return Err(error);
    }
    if request_deadline(None).is_some_and(|deadline| now >= deadline) {
        return Err(failure(
            path,
            "read_deadline_exceeded",
            "filesystem deadline elapsed before this call started",
        ));
    }
    Ok(())
}
fn failure(path: &Path, code: &'static str, reason: &str) -> io::Error {
    let message = format!("{code}: {}: {reason}", path.display());
    if let Some(budget) = current() {
        budget
            .failure
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .get_or_insert_with(|| Failure {
                code,
                message: message.clone(),
            });
        budget.failed.store(true, Ordering::Release);
    }
    io::Error::new(io::ErrorKind::TimedOut, Failure { code, message })
}
fn prior_failure() -> Option<io::Error> {
    CURRENT.with(|current| {
        let current = current.borrow();
        let budget = current.as_ref()?;
        if !budget.failed.load(Ordering::Acquire) {
            return None;
        }
        let error = budget
            .failure
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .as_ref()
            .map(|failure| io::Error::new(io::ErrorKind::TimedOut, failure.clone()));
        error
    })
}

type IoJob = Box<dyn FnOnce() + Send + 'static>;

/// A published walk snapshot never holds its lock while accessing the filesystem.
/// The caller can take the last examined prefix even if the helper is stuck in `next`.
pub struct WalkProgress<T> {
    cancellation: Option<crate::executor::JobCancellation>,
    snapshot: Arc<Mutex<T>>,
    stopped: Arc<AtomicBool>,
    deadline: Instant,
    published: Arc<AtomicBool>,
}
pub struct WalkCompletion {
    pub incomplete: bool,
    pub time_limit: bool,
}
impl<T> WalkProgress<T> {
    pub fn stopped(&self) -> bool {
        self.stopped.load(Ordering::Acquire)
            || self
                .cancellation
                .as_ref()
                .is_some_and(|token| token.cancel_requested_before_commit())
            || Instant::now() >= self.deadline
            || prior_failure().is_some()
    }
    pub fn update(&self, update: impl FnOnce(&mut T)) {
        let mut snapshot = self.snapshot.lock().unwrap_or_else(|e| e.into_inner());
        if self.stopped.load(Ordering::Acquire) {
            return;
        }
        update(&mut snapshot);
        drop(snapshot);
        self.published.store(true, Ordering::Release);
        if let Some(token) = &self.cancellation {
            token.report_progress();
        }
        ACTIVE_PROBE.with(|probe| {
            if let Some(probe) = probe.borrow().as_ref() {
                probe
                    .activity
                    .lock()
                    .unwrap_or_else(|e| e.into_inner())
                    .progress = Some(Instant::now());
            }
        });
    }
}

pub fn run_walk<T: Clone + Send + 'static>(
    path: &Path,
    at: Option<Instant>,
    initial: T,
    work: impl FnOnce(PathBuf, WalkProgress<T>) -> io::Result<T> + Send + 'static,
) -> (T, WalkCompletion) {
    if prior_failure().is_some() {
        return (
            initial,
            WalkCompletion {
                incomplete: true,
                time_limit: false,
            },
        );
    }
    let deadline = request_deadline(at).unwrap_or_else(|| Instant::now() + IO_BUDGET);
    let snapshot = Arc::new(Mutex::new(initial));
    let stopped = Arc::new(AtomicBool::new(false));
    let published = Arc::new(AtomicBool::new(false));
    let progress = WalkProgress {
        cancellation: crate::executor::current_job_cancellation(),
        snapshot: snapshot.clone(),
        stopped: stopped.clone(),
        deadline,
        published: published.clone(),
    };
    let probe = Arc::new(Probe::queued(deadline));
    {
        let mut activity = probe.activity.lock().unwrap_or_else(|e| e.into_inner());
        activity.walking = true;
        activity.cancelled = Some(stopped.clone());
    }
    // A stalled descendant is a gap in this walk, not a reason to discard
    // already-discovered paths when the caller reads or admits them afterward.
    let parent = current();
    let local = parent.clone().map(|mut budget| {
        budget.failure = Arc::new(Mutex::new(None));
        budget.failed = Arc::new(AtomicBool::new(false));
        budget.walk_root = Some(path.to_path_buf());
        budget
    });
    let (result, failure) = with_budget(local, || {
        let result = run_with_timeout(
            path,
            Some(deadline),
            Arc::clone(HELPERS.get_or_init(|| Limiter::new(IO_POOL_SIZE))),
            access_budget(path),
            Some(probe),
            move |path| work(path, progress),
        );
        let failure = current()
            .and_then(|budget| {
                budget
                    .failure
                    .lock()
                    .unwrap_or_else(|e| e.into_inner())
                    .clone()
            })
            .or_else(|| {
                result
                    .as_ref()
                    .err()
                    .and_then(|error| error.get_ref()?.downcast_ref::<Failure>().cloned())
            });
        (result, failure)
    });
    stopped.store(true, Ordering::Release);
    let failed = failure.is_some();
    let time_limit = Instant::now() >= deadline;
    let partial = result.is_err() || failed || time_limit;
    let named_gap = failure
        .as_ref()
        .map(|failure| failure.message.clone())
        .or_else(|| {
            result
                .as_ref()
                .err()
                .filter(|_| !time_limit)
                .map(ToString::to_string)
        });
    if partial && (published.load(Ordering::Acquire) || !failed) {
        if let Some(budget) = &parent {
            budget.walk_partial.store(true, Ordering::Release);
            if time_limit {
                budget
                    .walk_time_limit_reached
                    .store(true, Ordering::Release);
            }
            if let Some(gap) = named_gap {
                budget
                    .walk_gap
                    .lock()
                    .unwrap_or_else(|e| e.into_inner())
                    .get_or_insert(gap);
            }
        }
    } else if let (Some(budget), Some(failure)) = (parent, failure) {
        budget
            .failure
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .get_or_insert(failure);
        budget.failed.store(true, Ordering::Release);
    }
    (
        result.unwrap_or_else(|_| snapshot.lock().unwrap_or_else(|e| e.into_inner()).clone()),
        WalkCompletion {
            incomplete: partial,
            time_limit,
        },
    )
}

/// Attribute nested access to the entry being checked, not the walk's root.
pub(crate) fn reading_path(path: &Path) -> impl Drop {
    struct ReadingPath(Option<(Arc<Probe>, Option<PathBuf>)>);
    impl Drop for ReadingPath {
        fn drop(&mut self) {
            if let Some((probe, previous)) = self.0.take() {
                probe
                    .activity
                    .lock()
                    .unwrap_or_else(|e| e.into_inner())
                    .path = previous;
            }
        }
    }
    ReadingPath(ACTIVE_PROBE.with(|probe| {
        probe.borrow().as_ref().map(|probe| {
            let previous = probe
                .activity
                .lock()
                .unwrap_or_else(|e| e.into_inner())
                .path
                .replace(path.to_path_buf());
            (probe.clone(), previous)
        })
    }))
}

pub fn walk_path(path: &Path) -> bool {
    let keep_going = ACTIVE_PROBE.with(|probe| {
        if let Some(probe) = probe.borrow().as_ref() {
            let mut activity = probe.activity.lock().unwrap_or_else(|e| e.into_inner());
            if activity
                .cancelled
                .as_ref()
                .is_some_and(|cancelled| cancelled.load(Ordering::Acquire))
            {
                return false;
            }
            activity.path = Some(path.to_path_buf());
            activity.progress = Some(Instant::now());
        }
        true
    });
    #[cfg(all(any(test, feature = "test-support"), unix))]
    stall_running_helper_if_requested(path);
    keep_going
}

struct Worker {
    sender: std::sync::mpsc::Sender<IoJob>,
    retired: Arc<AtomicBool>,
}
#[derive(Default)]
struct PoolState {
    idle: Vec<Worker>,
    usable: usize,
    live: usize,
    abandoned: usize,
    spawned: u64,
    retired_total: u64,
    replacements: u64,
    queue_timeouts: u64,
    cap_hits: u64,
}
struct Limiter {
    state: Mutex<PoolState>,
    available: Condvar,
    max: usize,
    max_live: usize,
    create: std::sync::mpsc::SyncSender<()>,
    #[cfg(any(test, feature = "test-support"))]
    test_scope: Option<fn() -> Box<dyn Any>>,
}
impl Limiter {
    fn new(max: usize) -> Arc<Self> {
        Self::with_limits(max, MAX_IO_THREADS)
    }
    fn with_limits(max: usize, max_live: usize) -> Arc<Self> {
        Self::with_options(
            max,
            max_live,
            #[cfg(any(test, feature = "test-support"))]
            None,
        )
    }
    fn with_options(
        max: usize,
        max_live: usize,
        #[cfg(any(test, feature = "test-support"))] test_scope: Option<fn() -> Box<dyn Any>>,
    ) -> Arc<Self> {
        assert!(max > 0 && max <= max_live);
        let (create, requests) = std::sync::mpsc::sync_channel(1);
        Arc::new_cyclic(|weak: &std::sync::Weak<Self>| {
            let pool = weak.clone();
            // Creating a worker can stall, for example on Windows DLL
            // initialization. After this one-time factory startup, admission
            // callers only enqueue creation requests and wait to their deadline;
            // worker creation never holds the pool state lock.
            let _ = std::thread::Builder::new()
                .name("aft-filesystem-probe-factory".into())
                .spawn(move || {
                    while requests.recv().is_ok() {
                        let Some(pool) = pool.upgrade() else { break };
                        pool.create_worker();
                    }
                });
            Self {
                state: Mutex::new(PoolState::default()),
                available: Condvar::new(),
                max,
                max_live,
                create,
                #[cfg(any(test, feature = "test-support"))]
                test_scope,
            }
        })
    }
    fn create_worker(self: &Arc<Self>) {
        {
            let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
            if !state.idle.is_empty() || state.usable >= self.max || state.live >= self.max_live {
                return;
            }
            state.live += 1;
            state.usable += 1;
        }
        let (sender, receiver) = std::sync::mpsc::channel::<IoJob>();
        let retired = Arc::new(AtomicBool::new(false));
        let worker_retired = Arc::clone(&retired);
        let pool = Arc::downgrade(self);
        #[cfg(any(test, feature = "test-support"))]
        let test_scope = self.test_scope;
        let spawned = std::thread::Builder::new()
            .name("aft-filesystem-probe".into())
            .spawn(move || {
                let _exit = WorkerExit {
                    pool,
                    retired: worker_retired,
                };
                while let Ok(job) = receiver.recv() {
                    // A panicking job disconnects its result channel. Keep this
                    // worker alive until its caller retires it and closes sender.
                    let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                        let _state = HelperJobScope::enter();
                        #[cfg(any(test, feature = "test-support"))]
                        let _test_state = test_scope
                            .or_else(|| TEST_HELPER_SCOPE.get().copied())
                            .map(|scope| scope());
                        job();
                    }));
                }
            });
        let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
        if spawned.is_ok() {
            #[cfg(any(test, feature = "test-support"))]
            THREAD_SPAWNS.fetch_add(1, Ordering::Relaxed);
            state.replacements += u64::from(state.retired_total > state.replacements);
            state.spawned += 1;
            state.idle.push(Worker { sender, retired });
        } else {
            state.live -= 1;
            state.usable -= 1;
        }
        self.available.notify_all();
    }
    fn acquire(self: &Arc<Self>, at: Instant) -> Option<Permit> {
        let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
        let mut counted_cap = false;
        loop {
            let remaining = at.saturating_duration_since(Instant::now());
            if remaining.is_zero() {
                state.queue_timeouts += 1;
                return None;
            }
            if let Some(worker) = state.idle.pop() {
                return Some(Permit {
                    pool: Arc::clone(self),
                    worker: Some(worker),
                    reusable: true,
                });
            }
            if state.usable < self.max && state.live < self.max_live {
                if matches!(
                    self.create.try_send(()),
                    Err(std::sync::mpsc::TrySendError::Disconnected(_))
                ) {
                    return None;
                }
            }
            if state.live >= self.max_live && !counted_cap {
                state.cap_hits += 1;
                counted_cap = true;
            }
            state = self
                .available
                .wait_timeout(state, remaining)
                .unwrap_or_else(|e| e.into_inner())
                .0;
        }
    }
    fn health(&self) -> serde_json::Value {
        match self.state.try_lock() {
            Ok(state) => pool_health_snapshot(&state, self.max, self.max_live, "ready"),
            Err(error) => serde_json::json!({
                "pool_size": self.max,
                "thread_cap": self.max_live,
                "status": "unavailable",
                "reason": match error {
                    std::sync::TryLockError::WouldBlock => "state_busy",
                    std::sync::TryLockError::Poisoned(_) => "state_poisoned",
                },
            }),
        }
    }
}
struct HelperJobScope {
    _carry: CarryJobScope,
    directories: (u64, HashMap<PathBuf, Access>),
    mutation_admission: bool,
    #[cfg(any(test, feature = "test-support"))]
    canonicalize_calls: Option<Vec<PathBuf>>,
}
impl HelperJobScope {
    fn enter() -> Self {
        // Reset only at the dispatched job boundary. Nested probes run inline
        // and must keep the enclosing job's cache, counters and test hooks.
        Self {
            _carry: CarryJobScope::enter(),
            directories: DIRECTORIES.with(|cache| cache.replace(Default::default())),
            mutation_admission: MUTATION_ADMISSION.with(|flag| flag.replace(false)),
            #[cfg(any(test, feature = "test-support"))]
            canonicalize_calls: crate::path_identity::CANONICALIZE_CALLS
                .with(|calls| calls.replace(None)),
        }
    }
}
impl Drop for HelperJobScope {
    fn drop(&mut self) {
        DIRECTORIES.with(|cache| cache.replace(std::mem::take(&mut self.directories)));
        MUTATION_ADMISSION.with(|flag| flag.set(self.mutation_admission));
        #[cfg(any(test, feature = "test-support"))]
        crate::path_identity::CANONICALIZE_CALLS
            .with(|calls| *calls.borrow_mut() = self.canonicalize_calls.take());
    }
}
fn pool_health_snapshot(
    state: &PoolState,
    max: usize,
    max_live: usize,
    status: &str,
) -> serde_json::Value {
    serde_json::json!({
        "pool_size": max,
        "thread_cap": max_live,
        "status": status,
        "live": state.live,
        "idle": state.idle.len(),
        "usable": state.usable,
        "abandoned": state.abandoned,
        "spawned_total": state.spawned,
        "abandoned_total": state.retired_total,
        "replacements_total": state.replacements,
        "cap_hits_total": state.cap_hits,
        "queue_timeouts_total": state.queue_timeouts,
    })
}
pub fn helper_health() -> serde_json::Value {
    helper_health_from(&HELPERS)
}

/// Start every worker the shared filesystem helper pool keeps. The pool
/// starts workers on demand, up to its configured size, and keeps reusable
/// workers idle for later calls (only a worker abandoned after a timeout
/// exits). A test that compares this process's threads before and after some
/// work fills it first; otherwise the pool growing to meet that work reads as
/// threads the work kept.
#[cfg(any(test, feature = "test-support"))]
pub fn fill_helper_pool_for_test() {
    let pool = Arc::clone(HELPERS.get_or_init(|| Limiter::new(IO_POOL_SIZE)));
    let deadline = Instant::now() + Duration::from_secs(30);
    // Holding every permit at once leaves no idle worker to reuse, so each
    // acquire starts a new one until the pool is at its size.
    let permits: Vec<Permit> = (0..pool.max)
        .map(|_| {
            pool.acquire(deadline)
                .expect("the filesystem helper pool did not fill")
        })
        .collect();
    drop(permits);
}
fn helper_health_from(helpers: &OnceLock<Arc<Limiter>>) -> serde_json::Value {
    // Health runs on the frame loop: observing an unused pool must not start
    // its factory, and observing a busy pool must not wait for its state lock.
    match helpers.get() {
        Some(pool) => pool.health(),
        None => pool_health_snapshot(
            &PoolState::default(),
            IO_POOL_SIZE,
            MAX_IO_THREADS,
            "not_started",
        ),
    }
}
struct WorkerExit {
    pool: std::sync::Weak<Limiter>,
    retired: Arc<AtomicBool>,
}
impl Drop for WorkerExit {
    fn drop(&mut self) {
        if let Some(pool) = self.pool.upgrade() {
            let mut state = pool.state.lock().unwrap_or_else(|e| e.into_inner());
            state.live -= 1;
            if self.retired.load(Ordering::Relaxed) {
                state.abandoned -= 1;
            }
            pool.available.notify_all();
        }
    }
}
struct Permit {
    pool: Arc<Limiter>,
    worker: Option<Worker>,
    reusable: bool,
}
impl Permit {
    fn send(&mut self, job: IoJob) -> io::Result<()> {
        self.reusable = false;
        self.worker
            .as_ref()
            .unwrap()
            .sender
            .send(job)
            .map_err(|_| io::Error::other("filesystem helper stopped"))
    }
}
impl Drop for Permit {
    fn drop(&mut self) {
        let worker = self.worker.take().unwrap();
        let mut state = self.pool.state.lock().unwrap_or_else(|e| e.into_inner());
        if self.reusable {
            state.idle.push(worker);
        } else {
            // A timed-out job cannot be cancelled inside the OS. Remove its
            // healthy slot, but count its thread against the hard cap until it
            // actually exits. Closing the sender makes a late return exit.
            worker.retired.store(true, Ordering::Relaxed);
            state.usable -= 1;
            state.abandoned += 1;
            state.retired_total += 1;
        }
        self.pool.available.notify_all();
    }
}
/// Isolate boundary probes, whole walks, and reads on risky filesystems.
/// Stuck helpers retain the submitted job closure and its owned captures.
pub fn run<T: Send + 'static>(
    path: &Path,
    at: Option<Instant>,
    work: impl FnOnce(PathBuf) -> io::Result<T> + Send + 'static,
) -> io::Result<T> {
    run_with_limiter(
        path,
        at,
        Arc::clone(HELPERS.get_or_init(|| Limiter::new(IO_POOL_SIZE))),
        work,
    )
}

/// A separate helper pool whose stalled jobs cannot consume file-read workers.
#[derive(Clone)]
pub struct IsolatedPool(Arc<Limiter>);

impl IsolatedPool {
    #[cfg(any(test, feature = "test-support"))]
    pub fn with_test_scope(thread_cap: usize, scope: fn() -> Box<dyn Any>) -> Self {
        Self(Limiter::with_options(thread_cap, thread_cap, Some(scope)))
    }
    pub fn new(thread_cap: usize) -> Self {
        Self(Limiter::with_limits(thread_cap, thread_cap))
    }

    pub fn run<T: Send + 'static>(
        &self,
        path: &Path,
        at: Option<Instant>,
        work: impl FnOnce(PathBuf) -> io::Result<T> + Send + 'static,
    ) -> io::Result<T> {
        run_with_limiter(path, at, Arc::clone(&self.0), work)
    }
}

/// Reserves time for a bounded walk to return partial results before the bounded I/O helper's
/// deadline; a helper still stuck in one OS call remains a `read_blocked`.
pub fn deadline_before_io_timeout(
    path: &Path,
    budget: Duration,
    return_margin: Duration,
) -> Instant {
    let now = Instant::now();
    let access_deadline = now + access_budget(path);
    let hard_deadline =
        request_deadline(None).map_or(access_deadline, |request| request.min(access_deadline));
    let walk_deadline = now + budget;
    let return_deadline = hard_deadline.checked_sub(return_margin).unwrap_or(now);
    walk_deadline.min(return_deadline)
}
fn run_with_limiter<T: Send + 'static>(
    path: &Path,
    at: Option<Instant>,
    limiter: Arc<Limiter>,
    work: impl FnOnce(PathBuf) -> io::Result<T> + Send + 'static,
) -> io::Result<T> {
    run_with_timeout(path, at, limiter, access_budget(path), None, work)
}
fn access_budget(path: &Path) -> Duration {
    #[cfg(any(test, feature = "test-support"))]
    return current().map_or(IO_BUDGET, |budget| {
        budget
            .access_budget_by_path
            .get(path)
            .copied()
            .unwrap_or(budget.access_budget)
    });
    #[cfg(not(any(test, feature = "test-support")))]
    {
        let _ = path;
        IO_BUDGET
    }
}
fn run_with_timeout<T: Send + 'static>(
    path: &Path,
    at: Option<Instant>,
    limiter: Arc<Limiter>,
    access_budget: Duration,
    probe: Option<Arc<Probe>>,
    work: impl FnOnce(PathBuf) -> io::Result<T> + Send + 'static,
) -> io::Result<T> {
    let _reading = reading_path(path);
    if let Some(error) = prior_failure() {
        return Err(error);
    }
    let queued = Instant::now();
    let request_deadline = request_deadline(at);
    // Without a request deadline, queueing and access each get their own cap.
    // Inside a mutation, a helper may wait to be admitted and scheduled until
    // the request deadline, because nothing has run yet; see `MutationScope`.
    let queue_deadline = match request_deadline {
        Some(at) if MUTATION_ADMISSION.with(std::cell::Cell::get) => at,
        Some(at) => at.min(queued + access_budget),
        None => queued + access_budget,
    };
    if let Some(probe) = &probe {
        probe.set_deadline(queue_deadline, None);
    }
    if queued >= queue_deadline {
        return Err(failure(
            path,
            "read_deadline_exceeded",
            "filesystem deadline elapsed before this call started",
        ));
    }
    // A bounded walk already owns an isolated helper. Do not consume another
    // slot per nested directory probe (or let healthy walks deadlock each
    // other on admission). Its caller's deadline must be no later than ours.
    let walking = ACTIVE_PROBE.with(|probe| {
        probe.borrow().as_ref().is_some_and(|probe| {
            probe
                .activity
                .lock()
                .unwrap_or_else(|e| e.into_inner())
                .walking
        })
    });
    if let Some(outer) = HELPER_DEADLINE.with(|outer| {
        outer.get().filter(|outer| {
            *outer <= queue_deadline || (walking && request_deadline.is_some_and(|at| at >= *outer))
        })
    }) {
        if let Some(probe) = &probe {
            probe.set_deadline(outer, Some(Instant::now()));
        }
        return work(path.to_path_buf());
    }
    let Some(mut permit) = limiter.acquire(queue_deadline) else {
        return Err(failure(path, "read_io_queue_timeout", "no filesystem helper slot became available before the deadline; this call did not start"));
    };
    let owned = path.to_path_buf();
    let budget = current();
    let alloc_label = crate::alloc_trace::carry();
    let carry = capture_carry(path)?;
    #[cfg(any(test, feature = "test-support"))]
    let measurements = budget.as_ref().map(|b| Arc::clone(&b.measurements));
    let (tx, rx) = std::sync::mpsc::sync_channel(1);
    let probe = probe.unwrap_or_else(|| Arc::new(Probe::queued(queue_deadline)));
    let helper_probe = Arc::clone(&probe);
    #[cfg(any(test, feature = "test-support"))]
    if let Some(counts) = &measurements {
        counts.round_trips.fetch_add(1, Ordering::Relaxed);
    }
    permit.send(Box::new(move || {
            let _alloc_label = alloc_label.enter();
            #[cfg(any(test, feature = "test-support"))]
            regression_tests::before_helper(&owned);
            let result = (|| {
                let _carry = enter_carry(&owned, carry)?;
                with_budget(budget, || {
                // Owning a slot does not mean the OS has scheduled this helper.
                // Never start expired work or blame its scheduling delay on I/O.
                // Publish the phase under the same lock used by the owner and
                // shared waiters, so neither can mistake a started access for
                // an expired queue while the helper is being scheduled.
                let mut state = helper_probe.state.lock().unwrap_or_else(|e| e.into_inner());
                let started = Instant::now();
                if started >= queue_deadline {
                    return Err(failure(&owned, "read_io_queue_timeout", "filesystem helper did not start before the deadline; this call did not start"));
                }
                // Admission and scheduling are not OS access. Start the access
                // cap here, while retaining the caller's hard request deadline.
                let at = request_deadline
                    .map_or(started + access_budget, |at| at.min(started + access_budget));
                state.started = Some(started);
                state.deadline = at;
                helper_probe.ready.notify_all();
                drop(state);
                struct DeadlineScope(Option<Instant>);
                impl Drop for DeadlineScope {
                    fn drop(&mut self) {
                        HELPER_DEADLINE.with(|deadline| deadline.set(self.0));
                    }
                }
                let helper_at = if helper_probe.activity.lock().unwrap_or_else(|e| e.into_inner()).walking {
                    request_deadline.unwrap_or(at)
                } else { at };
                let _deadline = DeadlineScope(HELPER_DEADLINE.with(|deadline| deadline.replace(Some(helper_at))));
                struct ActiveProbeScope(Option<Arc<Probe>>);
                impl Drop for ActiveProbeScope {
                    fn drop(&mut self) {
                        ACTIVE_PROBE.with(|probe| *probe.borrow_mut() = self.0.take());
                    }
                }
                let _active = ActiveProbeScope(ACTIVE_PROBE.with(|probe| probe.replace(Some(helper_probe.clone()))));
                helper_probe.activity.lock().unwrap_or_else(|e| e.into_inner()).progress = Some(started);
                #[cfg(any(test, feature = "test-support"))]
                regression_tests::after_helper_start(&owned);
                work(owned)
                })
            })();
            let _ = tx.send(result);
        }))?;
    #[cfg(any(test, feature = "test-support"))]
    if let Some(counts) = &measurements {
        counts.dispatches.fetch_add(1, Ordering::Relaxed);
    }
    let mut wait_until = queue_deadline.min(queued + access_budget);
    loop {
        match rx.recv_timeout(wait_until.saturating_duration_since(Instant::now())) {
            Ok(result) => {
                permit.reusable = true;
                return result;
            }
            Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {
                let state = probe.state.lock().unwrap_or_else(|e| e.into_inner());
                let Some(started) = state.started else {
                    // A mutation may wait for admission past one access cap.
                    // Look again at least once per cap, so a helper that
                    // starts late and then hangs still fails at its own
                    // access deadline instead of at the request deadline.
                    let now = Instant::now();
                    if now < queue_deadline {
                        wait_until = queue_deadline.min(now + access_budget);
                        continue;
                    }
                    return Err(failure(
                    path,
                    "read_io_queue_timeout",
                    "filesystem helper did not start before the deadline; this call did not start",
                ));
                };
                let mut at = state.deadline;
                drop(state);
                let activity = probe.activity.lock().unwrap_or_else(|e| e.into_inner());
                let access_started = if activity.walking {
                    activity.progress.unwrap_or(started)
                } else {
                    started
                };
                let stalled_at = access_started + access_budget;
                if activity.walking {
                    at = request_deadline.map_or(stalled_at, |deadline| deadline.min(stalled_at));
                }
                let blocked_path = activity.path.clone().unwrap_or_else(|| path.to_path_buf());
                let walk_deadline = activity.walking
                    && request_deadline.is_some_and(|deadline| deadline <= stalled_at);
                drop(activity);
                if Instant::now() < at {
                    wait_until = at;
                    continue;
                }
                if walk_deadline {
                    return Err(io::Error::new(
                        io::ErrorKind::TimedOut,
                        "walk deadline elapsed",
                    ));
                }
                let hint = if cfg!(target_os = "macos") {
                    "; on macOS, check ck-aft access in Privacy & Security, then retry"
                } else {
                    ""
                };
                return Err(failure(
                    &blocked_path,
                    "read_blocked",
                    &format!(
                        "OS access did not finish within {:.3} s{hint}",
                        at.saturating_duration_since(access_started).as_secs_f64()
                    ),
                ));
            }
            Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => {
                return Err(io::Error::other("filesystem helper stopped"));
            }
        }
    }
}
fn directory(path: &Path, at: Option<Instant>) -> io::Result<Access> {
    let _reading = reading_path(path);
    if let Some(error) = prior_failure() {
        return Err(error);
    }
    let id = CURRENT.with(|current| current.borrow().as_ref().map(|b| b.id));
    if let Some(access) = DIRECTORIES.with(|dirs| {
        let dirs = dirs.borrow();
        (Some(dirs.0) == id)
            .then(|| dirs.1.get(path).copied())
            .flatten()
    }) {
        return Ok(access);
    }
    let budget = current().unwrap_or_else(|| Budget::after(IO_BUDGET));
    let (probe, owner) = {
        let mut dirs = budget.directories.lock().unwrap_or_else(|e| e.into_inner());
        match dirs.entry(path.to_path_buf()) {
            std::collections::hash_map::Entry::Occupied(entry) => (Arc::clone(entry.get()), false),
            std::collections::hash_map::Entry::Vacant(entry) => {
                let probe = Arc::new(Probe::queued(
                    at.map_or(budget.deadline, |at| at.min(budget.deadline)),
                ));
                entry.insert(Arc::clone(&probe));
                (probe, true)
            }
        }
    };
    let access = if owner {
        #[cfg(any(test, feature = "test-support"))]
        budget
            .measurements
            .directory_probes
            .fetch_add(1, Ordering::Relaxed);
        let result = run_with_timeout(
            path,
            at,
            Arc::clone(HELPERS.get_or_init(|| Limiter::new(IO_POOL_SIZE))),
            access_budget(path),
            Some(Arc::clone(&probe)),
            |path| {
                #[cfg(any(test, feature = "test-support"))]
                regression_tests::before_directory_probe(&path)?;
                #[cfg(all(any(test, feature = "test-support"), unix))]
                tests::before_directory_probe(&path)?;
                // Opening and advancing ReadDir probes consent, not just existence.
                let mut entries = std::fs::read_dir(&path)?;
                let _ = entries.next().transpose()?;
                let access = Access {
                    direct: local_filesystem(&path)?,
                };
                #[cfg(all(any(test, feature = "test-support"), unix))]
                tests::after_directory_probe(&path);
                Ok(access)
            },
        );
        let macos = cfg!(target_os = "macos");
        #[cfg(all(any(test, feature = "test-support"), unix))]
        let macos = macos || tests::macos_directory(path);
        observe_permission(path, &result, macos);
        let result = result.map_err(|error| ProbeError::from(&error));
        probe.state.lock().unwrap_or_else(|e| e.into_inner()).result = Some(result.clone());
        probe.ready.notify_all();
        result.map_err(|error| error.error())?
    } else {
        let request_deadline = request_deadline(at);
        let mut state = probe.state.lock().unwrap_or_else(|e| e.into_inner());
        while state.result.is_none() {
            // The owner may still be queued. Once it starts, all waiters follow
            // its new access deadline, without extending their own request.
            let at = request_deadline.map_or(state.deadline, |at| at.min(state.deadline));
            let remaining = at.saturating_duration_since(Instant::now());
            if remaining.is_zero() {
                let blocked = state.started.is_some() && at == state.deadline;
                return Err(failure(
                    path,
                    if blocked {
                        "read_blocked"
                    } else {
                        "read_io_queue_timeout"
                    },
                    if blocked {
                        "OS access deadline elapsed waiting for this directory's running probe"
                    } else {
                        "deadline elapsed waiting for this directory's shared probe"
                    },
                ));
            }
            state = probe
                .ready
                .wait_timeout(state, remaining)
                .unwrap_or_else(|e| e.into_inner())
                .0;
        }
        state
            .result
            .as_ref()
            .unwrap()
            .clone()
            .map_err(|error| error.error())?
    };
    DIRECTORIES.with(|dirs| {
        let mut dirs = dirs.borrow_mut();
        if dirs.0 != budget.id {
            dirs.0 = budget.id;
            dirs.1.clear();
        }
        dirs.1.insert(path.to_path_buf(), access);
    });
    Ok(access)
}
pub(crate) fn probe_directory(path: &Path, at: Option<Instant>) -> io::Result<()> {
    directory(path, at).map(|_| ())
}

/// Only descendants discovered by a read-only walk are coverage gaps. The
/// starting folder and its ancestors still require a named access error.
pub fn probe_walk_directory(root: &Path, path: &Path) -> io::Result<()> {
    let budget = current().map(|mut budget| {
        budget.walk_root = Some(root.to_path_buf());
        budget
    });
    with_budget(budget, || probe_directory(path, None))
}
fn parent(path: &Path, at: Option<Instant>) -> io::Result<Access> {
    directory(
        path.parent()
            .filter(|p| !p.as_os_str().is_empty())
            .unwrap_or(Path::new(".")),
        at,
    )
}
fn cached_directory(path: &Path) -> Option<Access> {
    let id = CURRENT.with(|budget| budget.borrow().as_ref().map(|b| b.id))?;
    let local = DIRECTORIES.with(|dirs| {
        let dirs = dirs.borrow();
        (dirs.0 == id).then(|| dirs.1.get(path).copied()).flatten()
    });
    if local.is_some() {
        return local;
    }
    // Another thread of this request may already have probed the directory:
    // grep reads files on rayon workers, then stats every match again on the
    // thread that sorts the results. Reuse that finished probe, as
    // `directory` would, instead of spawning a helper per directory this
    // thread did not read itself. A probe still running is not waited for
    // here; callers then take their normal bounded path.
    let budget = current()?;
    let probe = budget
        .directories
        .lock()
        .unwrap_or_else(|e| e.into_inner())
        .get(path)
        .cloned()?;
    let access = match probe.state.lock().unwrap_or_else(|e| e.into_inner()).result {
        Some(Ok(access)) => access,
        _ => return None,
    };
    // Remember it on this thread too, so later files under the same
    // directory do not take the request-wide lock again.
    DIRECTORIES.with(|dirs| {
        let mut dirs = dirs.borrow_mut();
        if dirs.0 != budget.id {
            dirs.0 = budget.id;
            dirs.1.clear();
        }
        dirs.1.insert(path.to_path_buf(), access);
    });
    Some(access)
}
fn traversal_parent(path: &Path) -> Option<&Path> {
    path.parent().map(|parent| {
        if parent.as_os_str().is_empty() {
            Path::new(".")
        } else {
            parent
        }
    })
}
// A successful stat on a local filesystem permits sibling stats, not directory
// enumeration or file reads. Keep this weaker evidence out of the listing cache.
fn cached_traversal(path: &Path) -> bool {
    cached_directory(path).is_some_and(|access| access.direct)
        || CURRENT.with(|current| {
            current.borrow().as_ref().is_some_and(|budget| {
                budget
                    .traversable
                    .lock()
                    .unwrap_or_else(|e| e.into_inner())
                    .contains(path)
            })
        })
}
fn run_traversal<T: Send + 'static>(
    path: &Path,
    work: impl FnOnce(PathBuf) -> io::Result<T> + Send + 'static,
) -> io::Result<T> {
    #[cfg(any(test, feature = "test-support"))]
    if let Some(budget) = current() {
        budget
            .measurements
            .traversal_probes
            .fetch_add(1, Ordering::Relaxed);
    }
    let (result, traversable) = run(path, None, move |path| {
        let parent = traversal_parent(&path).map(Path::to_path_buf);
        let result = work(path)?;
        // Filesystem identification can itself block, so keep it in the helper.
        let traversable = parent.filter(|parent| local_filesystem(parent).unwrap_or(false));
        Ok((result, traversable))
    })?;
    // Publish only after the caller receives success, never from a late helper.
    if let (Some(parent), Some(budget)) = (traversable, current()) {
        budget
            .traversable
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .insert(parent);
    }
    Ok(result)
}
pub fn probe_target(path: &Path) -> io::Result<()> {
    if cached_directory(path).is_some() {
        return Ok(());
    }
    let metadata = if path
        .parent()
        .and_then(cached_directory)
        .is_some_and(|access| access.direct)
    {
        let metadata = std::fs::symlink_metadata(path)?;
        if metadata.file_type().is_symlink() {
            run(path, None, std::fs::metadata)?
        } else {
            metadata
        }
    } else {
        match run(path, None, std::fs::metadata) {
            Ok(metadata) => metadata,
            Err(error) => {
                if error.raw_os_error() == Some(1) {
                    let folder = permission_folder(path);
                    observe_permission(
                        &folder,
                        &Err(io::Error::from_raw_os_error(1)),
                        cfg!(target_os = "macos"),
                    );
                }
                return Err(error);
            }
        }
    };
    if metadata.is_dir() {
        directory(path, None)?;
    } else {
        parent(path, None)?;
    }
    Ok(())
}
// Only positively identified local filesystems are eligible for direct reads.
// Network/FUSE/unknown mounts stay bounded per file even after a successful
// directory probe; a mount that stops responding mid-request cannot park a root.
#[cfg(any(target_os = "macos", target_os = "linux"))]
fn local_filesystem(path: &Path) -> io::Result<bool> {
    #[cfg(target_os = "macos")]
    {
        let resolved = std::fs::canonicalize(path)?;
        let text = resolved.to_string_lossy();
        // Local APFS directory access does not guarantee a cloud placeholder's
        // contents are resident. Hydration may still block on first file read.
        if text.contains("/Library/Mobile Documents/") || text.contains("/Library/CloudStorage/") {
            return Ok(false);
        }
    }
    let path = std::ffi::CString::new(path.as_os_str().as_encoded_bytes())?;
    let mut stat = std::mem::MaybeUninit::<libc::statfs>::uninit();
    if unsafe { libc::statfs(path.as_ptr(), stat.as_mut_ptr()) } != 0 {
        return Err(io::Error::last_os_error());
    }
    let stat = unsafe { stat.assume_init() };
    #[cfg(target_os = "macos")]
    {
        let name = unsafe { std::ffi::CStr::from_ptr(stat.f_mntonname.as_ptr()) };
        Ok(
            stat.f_flags & libc::MNT_LOCAL as u32 != 0
                && !name.to_bytes().starts_with(b"/Volumes/"),
        )
    }
    #[cfg(target_os = "linux")]
    {
        Ok(matches!(
            stat.f_type as u64,
            0xEF53 | 0x58465342 | 0x9123683E | 0x01021994 | 0x794c7630 | 0x2FC12FC1
        ))
    }
}
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
fn local_filesystem(_: &Path) -> io::Result<bool> {
    Ok(false)
}

pub fn read(path: &Path, at: Option<Instant>) -> io::Result<Vec<u8>> {
    if Instant::now() >= deadline(at) {
        return Err(failure(
            path,
            "read_deadline_exceeded",
            "scan deadline elapsed before file access",
        ));
    }
    let access = parent(path, at)?;
    if !access.direct {
        return run(path, at, |path| regular_read(&path, false));
    }
    let metadata = std::fs::symlink_metadata(path)?;
    if metadata.file_type().is_symlink() {
        return run(path, at, |path| regular_read(&path, false));
    }
    if !metadata.is_file() {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            "not a regular file",
        ));
    }
    match regular_read(path, true) {
        #[cfg(unix)]
        Err(error) if error.raw_os_error() == Some(libc::ELOOP) => {
            run(path, at, |path| regular_read(&path, false))
        }
        result => result,
    }
}

/// A regular file whose chunk reads retain the same access checks and helper
/// deadlines as a whole-file read. The descriptor stays open between chunks.
pub struct Reader {
    path: PathBuf,
    file: Option<std::fs::File>,
    direct: bool,
    at: Option<Instant>,
    /// The opened descriptor's size, taken when it was opened.
    size_at_open: u64,
}

pub fn reader(path: &Path, at: Option<Instant>) -> io::Result<Reader> {
    if Instant::now() >= deadline(at) {
        return Err(failure(
            path,
            "read_deadline_exceeded",
            "scan deadline elapsed before file access",
        ));
    }
    let access = parent(path, at)?;
    let metadata = access
        .direct
        .then(|| std::fs::symlink_metadata(path))
        .transpose()?;
    let direct = metadata
        .as_ref()
        .is_some_and(|metadata| !metadata.file_type().is_symlink());
    if direct && !metadata.as_ref().unwrap().is_file() {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            "not a regular file",
        ));
    }
    let ((file, size_at_open), direct) = if direct {
        match regular_open_sized(path, true) {
            #[cfg(unix)]
            Err(error) if error.raw_os_error() == Some(libc::ELOOP) => (
                run(path, at, |path| regular_open_sized(&path, false))?,
                false,
            ),
            result => (result?, true),
        }
    } else {
        (
            run(path, at, |path| regular_open_sized(&path, false))?,
            false,
        )
    };
    Ok(Reader {
        path: path.to_path_buf(),
        file: Some(file),
        direct,
        at,
        size_at_open,
    })
}

impl Reader {
    pub fn chunk(&mut self, mut buffer: Vec<u8>, size: usize) -> io::Result<Vec<u8>> {
        if Instant::now() >= deadline(self.at) {
            return Err(failure(
                &self.path,
                "read_deadline_exceeded",
                "scan deadline elapsed during file read",
            ));
        }
        let mut file = self
            .file
            .take()
            .ok_or_else(|| io::Error::other("file read already failed"))?;
        let read = move || {
            buffer.resize(size, 0);
            let mut count = 0;
            while count < buffer.len() {
                match file.read(&mut buffer[count..]) {
                    Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
                    Ok(0) => break,
                    result => count += result?,
                }
            }
            buffer.truncate(count);
            crate::io_accounting::WORK
                .content_read_bytes
                .fetch_add(count as u64, std::sync::atomic::Ordering::Relaxed);
            Ok((file, buffer))
        };
        let (file, buffer) = if self.direct {
            read()?
        } else {
            run(&self.path, self.at, move |_| read())?
        };
        self.file = Some(file);
        Ok(buffer)
    }

    /// The file's size when it was opened. A large-file read stops there, so
    /// bytes a writer appends during the read are not read.
    pub fn size_at_open(&self) -> u64 {
        self.size_at_open
    }

    /// Append at most `size` more bytes to `buffer`, reading until that many
    /// arrived or the file ended, with the same deadline and helper handling
    /// as [`Self::chunk`]. Unlike `chunk` it writes into spare capacity
    /// without zeroing it first.
    ///
    /// The buffer grows by at most `size` bytes: the reservation is exact, so
    /// it never doubles, and `read_to_end` through `take(size)` only fills
    /// the room already reserved. When that room is full it probes with a
    /// stack buffer before growing (std's `default_read_to_end`), and the
    /// probe of an exhausted `Take` reads nothing.
    pub fn append(&mut self, mut buffer: Vec<u8>, size: usize) -> io::Result<Vec<u8>> {
        if Instant::now() >= deadline(self.at) {
            return Err(failure(
                &self.path,
                "read_deadline_exceeded",
                "scan deadline elapsed during file read",
            ));
        }
        let mut file = self
            .file
            .take()
            .ok_or_else(|| io::Error::other("file read already failed"))?;
        let read = move || {
            let before = buffer.len();
            buffer.try_reserve_exact(size).map_err(io::Error::other)?;
            (&mut file).take(size as u64).read_to_end(&mut buffer)?;
            crate::io_accounting::WORK.content_read_bytes.fetch_add(
                (buffer.len() - before) as u64,
                std::sync::atomic::Ordering::Relaxed,
            );
            Ok((file, buffer))
        };
        let (file, buffer) = if self.direct {
            read()?
        } else {
            run(&self.path, self.at, move |_| read())?
        };
        self.file = Some(file);
        Ok(buffer)
    }
}

fn regular_open(path: &Path, no_follow: bool) -> io::Result<std::fs::File> {
    regular_open_sized(path, no_follow).map(|(file, _)| file)
}

/// Open project content without waiting for a FIFO writer. Judge the opened
/// handle so replacing an admitted path cannot bypass the regular-file check.
pub fn open_content_file(path: &Path) -> io::Result<std::fs::File> {
    open_content_file_sized(path, false).map(|(file, _)| file)
}

/// Read UTF-8 project content with the same opened-handle requirement.
pub fn read_content_to_string(path: impl AsRef<Path>) -> io::Result<String> {
    std::io::read_to_string(open_content_file(path.as_ref())?)
}

/// The same handle check without following a final symlink, for scratch reads.
pub(crate) fn open_content_file_no_follow(path: &Path) -> io::Result<std::fs::File> {
    open_content_file_sized(path, true).map(|(file, _)| file)
}

fn open_content_file_sized(path: &Path, _no_follow: bool) -> io::Result<(std::fs::File, u64)> {
    let mut options = std::fs::OpenOptions::new();
    options.read(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        options.custom_flags(libc::O_NONBLOCK | if _no_follow { libc::O_NOFOLLOW } else { 0 });
    }
    let file = options.open(path)?;
    let metadata = file.metadata()?;
    if !metadata.is_file() {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            "not a regular file",
        ));
    }
    Ok((file, metadata.len()))
}

/// [`regular_open`], with the opened descriptor's size.
fn regular_open_sized(path: &Path, _no_follow: bool) -> io::Result<(std::fs::File, u64)> {
    if !_no_follow && !std::fs::metadata(path)?.is_file() {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            "not a regular file",
        ));
    }
    #[cfg(all(any(test, feature = "test-support"), unix))]
    tests::before_regular_open(path)?;
    let scratch_check = crate::task_temp_reads::check_path(path)?;
    crate::io_accounting::WORK
        .content_reads
        .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    let (file, size) = open_content_file_sized(path, _no_follow)?;
    crate::task_temp_reads::check_opened(path, scratch_check.as_ref(), &file)?;
    Ok((file, size))
}

fn regular_read(path: &Path, no_follow: bool) -> io::Result<Vec<u8>> {
    let mut file = regular_open(path, no_follow)?;
    let metadata = file.metadata()?;
    let mut bytes = Vec::new();
    bytes
        .try_reserve(usize::try_from(metadata.len()).map_err(io::Error::other)?)
        .map_err(io::Error::other)?;
    file.read_to_end(&mut bytes)?;
    crate::io_accounting::WORK
        .content_read_bytes
        .fetch_add(bytes.len() as u64, std::sync::atomic::Ordering::Relaxed);
    Ok(bytes)
}
pub fn read_to_string(path: &Path) -> io::Result<String> {
    String::from_utf8(read(path, None)?)
        .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))
}
pub fn canonicalize(path: &Path) -> io::Result<PathBuf> {
    if let Some(error) = prior_failure() {
        return Err(error);
    }
    if cached_directory(path).is_some_and(|access| access.direct) {
        return std::fs::canonicalize(path);
    }
    // Resolving a path needs traversal, not permission to enumerate its parent.
    // Reuse a known-safe parent, otherwise isolate only canonicalize itself.
    if traversal_parent(path).is_some_and(cached_traversal)
        && std::fs::symlink_metadata(path).is_ok_and(|m| !m.file_type().is_symlink())
    {
        std::fs::canonicalize(path)
    } else {
        run_traversal(path, std::fs::canonicalize)
    }
}
pub fn metadata(path: &Path) -> io::Result<std::fs::Metadata> {
    if let Some(error) = prior_failure() {
        return Err(error);
    }
    // A stat must not turn into an unrelated ancestor's directory listing.
    let direct = cached_directory(path).map_or_else(
        || cached_traversal(path) || traversal_parent(path).is_some_and(cached_traversal),
        |access| access.direct,
    );
    if direct {
        let metadata = std::fs::symlink_metadata(path)?;
        if !metadata.file_type().is_symlink() {
            return Ok(metadata);
        }
    }
    run_traversal(path, std::fs::metadata)
}

#[cfg(any(test, feature = "test-support"))]
#[cfg_attr(not(test), allow(dead_code, unused_imports))]
#[path = "bounded_io_tests.rs"]
pub mod regression_tests;
#[cfg(all(any(test, feature = "test-support"), unix))]
pub use regression_tests::{stall_helper, stall_running_helper};
#[cfg(all(any(test, feature = "test-support"), unix))]
pub fn stall_helper_if_requested(path: &Path) {
    regression_tests::before_helper(path);
}
#[cfg(all(any(test, feature = "test-support"), unix))]
pub(crate) fn stall_running_helper_if_requested(path: &Path) {
    regression_tests::after_helper_start(path);
}

#[cfg(all(any(test, feature = "test-support"), unix))]
#[cfg_attr(not(test), allow(dead_code, unused_imports))]
pub mod tests {
    use super::*;

    #[test]
    fn carry_factory_errors_and_panics_refuse_work() {
        for phase in 0..4 {
            std::thread::spawn(move || {
                let factory: CarryFactory = Arc::new(move || match phase {
                    0 => Err(io::Error::other("injected capture failure")),
                    1 => panic!("injected capture panic"),
                    2 => Ok(Box::new(|| Err(io::Error::other("injected entry failure")))),
                    _ => Ok(Box::new(|| panic!("injected entry panic"))),
                });
                replace_carry_factory(Some(factory), Box::new(|| {}));
                let ran = Arc::new(AtomicBool::new(false));
                let called = ran.clone();
                let result = IsolatedPool::new(1).run(Path::new("carry"), None, move |_| {
                    called.store(true, Ordering::SeqCst);
                    Ok(())
                });
                assert_eq!(timeout_code(&result.unwrap_err()), "read_io_queue_timeout");
                assert!(!ran.load(Ordering::SeqCst));
                replace_carry_factory(None, Box::new(|| {}));
            })
            .join()
            .unwrap();
        }
    }
    use std::os::unix::fs::OpenOptionsExt;

    static MACOS_DIRECTORIES: LazyLock<Mutex<HashMap<PathBuf, bool>>> =
        LazyLock::new(|| Mutex::new(HashMap::new()));
    pub struct MacosProbe(PathBuf);
    impl MacosProbe {
        pub fn allow(&self) {
            MACOS_DIRECTORIES
                .lock()
                .unwrap()
                .insert(self.0.clone(), true);
        }
    }
    impl Drop for MacosProbe {
        fn drop(&mut self) {
            MACOS_DIRECTORIES.lock().unwrap().remove(&self.0);
        }
    }
    pub fn deny_macos_directory(path: &Path) -> MacosProbe {
        let path = std::fs::canonicalize(path).unwrap();
        MACOS_DIRECTORIES
            .lock()
            .unwrap()
            .insert(path.clone(), false);
        MacosProbe(path)
    }
    pub(super) fn macos_directory(path: &Path) -> bool {
        MACOS_DIRECTORIES.lock().unwrap().contains_key(path)
    }
    static BLOCKERS: LazyLock<Mutex<HashMap<PathBuf, (PathBuf, Arc<AtomicUsize>)>>> =
        LazyLock::new(|| Mutex::new(HashMap::new()));
    static PROBE_FINISHERS: LazyLock<Mutex<HashMap<PathBuf, std::sync::mpsc::Sender<()>>>> =
        LazyLock::new(|| Mutex::new(HashMap::new()));
    static FIFO_REPLACEMENTS: LazyLock<
        Mutex<HashMap<PathBuf, (Arc<AtomicUsize>, std::sync::mpsc::Sender<()>)>>,
    > = LazyLock::new(|| Mutex::new(HashMap::new()));
    pub struct BlockProbe {
        keys: Vec<PathBuf>,
        pub fired: Arc<AtomicUsize>,
        pub finished: std::sync::mpsc::Receiver<()>,
    }
    impl Drop for BlockProbe {
        fn drop(&mut self) {
            let mut blockers = BLOCKERS.lock().unwrap();
            for key in &self.keys {
                blockers.remove(key);
                PROBE_FINISHERS.lock().unwrap().remove(key);
            }
        }
    }
    pub fn block_directory_probe(directory: &Path, fifo: &Path) -> BlockProbe {
        let mut keys = vec![
            directory.to_path_buf(),
            std::fs::canonicalize(directory).unwrap(),
        ];
        keys.dedup();
        let fired = Arc::new(AtomicUsize::new(0));
        let (sender, finished) = std::sync::mpsc::channel();
        let mut blockers = BLOCKERS.lock().unwrap();
        for key in &keys {
            blockers.insert(key.clone(), (fifo.to_path_buf(), Arc::clone(&fired)));
            PROBE_FINISHERS
                .lock()
                .unwrap()
                .insert(key.clone(), sender.clone());
        }
        BlockProbe {
            keys,
            fired,
            finished,
        }
    }
    pub(super) fn after_directory_probe(path: &Path) {
        if let Some(sender) = PROBE_FINISHERS.lock().unwrap().remove(path) {
            let _ = sender.send(());
        }
    }
    pub(super) fn before_directory_probe(directory: &Path) -> io::Result<()> {
        if MACOS_DIRECTORIES.lock().unwrap().get(directory) == Some(&false) {
            return Err(io::Error::from_raw_os_error(libc::EPERM));
        }
        let blocker = BLOCKERS.lock().unwrap().get(directory).cloned();
        if let Some((path, fired)) = blocker {
            fired.fetch_add(1, Ordering::Relaxed);
            let _file = std::fs::File::open(path)?;
        }
        Ok(())
    }
    pub(super) fn before_regular_open(path: &Path) -> io::Result<()> {
        note_open(path);
        let fired = FIFO_REPLACEMENTS.lock().unwrap().remove(path);
        if let Some((fired, reached)) = fired {
            std::fs::remove_file(path)?;
            fifo(path);
            fired.fetch_add(1, Ordering::Relaxed);
            let _ = reached.send(());
        }
        Ok(())
    }
    static OPEN_WATCHES: LazyLock<Mutex<HashMap<PathBuf, Arc<AtomicUsize>>>> =
        LazyLock::new(|| Mutex::new(HashMap::new()));
    /// Counts the opens of one file's contents while it is alive, so a test
    /// can prove a file was never read.
    pub struct OpenWatch {
        path: PathBuf,
        pub opens: Arc<AtomicUsize>,
    }
    impl Drop for OpenWatch {
        fn drop(&mut self) {
            OPEN_WATCHES.lock().unwrap().remove(&self.path);
        }
    }
    pub fn watch_opens(path: &Path) -> OpenWatch {
        let opens = Arc::new(AtomicUsize::new(0));
        OPEN_WATCHES
            .lock()
            .unwrap()
            .insert(path.to_path_buf(), Arc::clone(&opens));
        OpenWatch {
            path: path.to_path_buf(),
            opens,
        }
    }
    /// Record an open of `path`'s contents for an [`OpenWatch`] on it.
    pub fn note_open(path: &Path) {
        if let Some(opens) = OPEN_WATCHES.lock().unwrap().get(path) {
            opens.fetch_add(1, Ordering::Relaxed);
        }
    }
    pub fn fifo(path: &Path) {
        let path = std::ffi::CString::new(path.as_os_str().as_encoded_bytes()).unwrap();
        assert_eq!(unsafe { libc::mkfifo(path.as_ptr(), 0o600) }, 0);
    }
    pub fn release_fifo(path: &Path) {
        use std::io::Write;
        let mut file = std::fs::OpenOptions::new()
            .read(true)
            .write(true)
            .custom_flags(libc::O_NONBLOCK)
            .open(path)
            .unwrap();
        let _ = file.write_all(b"released\n");
    }
    #[test]
    fn blocked_open_returns_before_fifo_writer_arrives() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("blocked");
        fifo(&path);
        let (tx, rx) = std::sync::mpsc::channel();
        let input = path.clone();
        let thread = std::thread::spawn(move || {
            tx.send(run(
                &input,
                Some(Instant::now() + Duration::from_millis(80)),
                std::fs::read,
            ))
            .unwrap()
        });
        let before_writer = rx.recv_timeout(Duration::from_millis(800));
        release_fifo(&path);
        thread.join().unwrap();
        let error = before_writer
            .expect("read waited for a FIFO writer instead of its deadline")
            .unwrap_err();
        assert_eq!(error.kind(), io::ErrorKind::TimedOut);
        assert!(error.to_string().contains("read_blocked"));
    }
    #[test]
    fn sequential_probes_reuse_helper_threads() {
        let limiter = Limiter::new(4);
        let budget = Budget::after(Duration::from_secs(5));
        let mut threads = HashSet::new();
        with_budget(Some(budget.clone()), || {
            for _ in 0..40 {
                threads.insert(
                    run_with_limiter(Path::new("healthy"), None, limiter.clone(), |_| {
                        Ok(std::thread::current().id())
                    })
                    .unwrap(),
                );
            }
        });
        assert!(
            threads.len() <= 4,
            "spawned {} helpers for 40 sequential probes",
            threads.len()
        );
    }

    #[test]
    fn timed_out_helper_is_replaced_without_delaying_later_probes() {
        let limiter = Limiter::new(1);
        let (release_tx, release_rx) = std::sync::mpsc::channel();
        let (started_tx, started_rx) = std::sync::mpsc::channel();
        let first_pool = limiter.clone();
        let first = std::thread::spawn(move || {
            run_with_limiter(
                Path::new("blocked"),
                Some(Instant::now() + Duration::from_millis(150)),
                first_pool,
                move |_| {
                    started_tx.send(()).unwrap();
                    release_rx.recv().unwrap();
                    Ok(())
                },
            )
        });
        started_rx.recv_timeout(Duration::from_secs(2)).unwrap();
        let blocked = first.join().unwrap().unwrap_err();
        let before = Instant::now();
        let later = run_with_limiter(
            Path::new("healthy"),
            Some(before + Duration::from_millis(150)),
            limiter.clone(),
            |_| Ok(42),
        );
        let health = limiter.health();
        release_tx.send(()).unwrap();
        assert_eq!(timeout_code(&blocked), "read_blocked");
        assert_eq!(
            later.unwrap(),
            42,
            "a timed-out helper must not retain the healthy slot"
        );
        assert!(before.elapsed() < Duration::from_millis(300));
        assert_eq!(health["abandoned"], 1);
        assert_eq!(health["replacements_total"], 1);
        assert_eq!(health["spawned_total"], 2);
    }

    #[test]
    fn abandoned_helper_cap_bounds_threads_and_recovers_after_release() {
        let pool = Limiter::with_limits(1, 2);
        let mut releases = Vec::new();
        for _ in 0..2 {
            let (release, blocked) = std::sync::mpsc::channel();
            releases.push(release);
            let error = run_with_limiter(
                Path::new("blocked"),
                Some(Instant::now() + Duration::from_millis(200)),
                pool.clone(),
                move |_| {
                    blocked.recv().unwrap();
                    Ok(())
                },
            )
            .unwrap_err();
            assert_eq!(timeout_code(&error), "read_blocked");
        }
        let fired = Arc::new(AtomicBool::new(false));
        let work_fired = fired.clone();
        let before = Instant::now();
        let error = run_with_limiter(
            Path::new("queued"),
            Some(before + Duration::from_millis(80)),
            pool.clone(),
            move |_| {
                work_fired.store(true, Ordering::Relaxed);
                Ok(())
            },
        )
        .unwrap_err();
        let health = pool.health();
        for release in releases {
            release.send(()).unwrap();
        }
        assert_eq!(timeout_code(&error), "read_io_queue_timeout");
        assert!(!fired.load(Ordering::Relaxed));
        assert!(before.elapsed() < Duration::from_millis(300));
        assert_eq!(health["live"], 2);
        assert_eq!(health["abandoned"], 2);
        assert_eq!(health["spawned_total"], 2);
        assert_eq!(health["replacements_total"], 1);
        assert_eq!(health["cap_hits_total"], 1);
        assert_eq!(health["queue_timeouts_total"], 1);
        run_with_limiter(
            Path::new("recovered"),
            Some(Instant::now() + Duration::from_secs(2)),
            pool,
            |_| Ok(()),
        )
        .unwrap();
    }

    #[test]
    fn reused_helper_resets_deadline_and_request_context() {
        let pool = Limiter::new(1);
        let first = Budget::after(IO_BUDGET);
        let first_id = first.id;
        with_budget(Some(first), || {
            run_with_limiter(Path::new("first"), None, pool.clone(), move |_| {
                assert_eq!(current().unwrap().id, first_id);
                assert!(HELPER_DEADLINE.with(|at| at.get()).is_some());
                Ok(())
            })
        })
        .unwrap();
        let mut permit = pool.acquire(Instant::now() + IO_BUDGET).unwrap();
        let (tx, rx) = std::sync::mpsc::channel();
        permit
            .send(Box::new(move || {
                tx.send((
                    current().is_none(),
                    HELPER_DEADLINE.with(|at| at.get()).is_none(),
                ))
                .unwrap();
            }))
            .unwrap();
        let (request_cleared, deadline_cleared) = rx.recv_timeout(IO_BUDGET).unwrap();
        permit.reusable = true;
        assert!(
            request_cleared,
            "a reused helper retained the previous request"
        );
        assert!(
            deadline_cleared,
            "a reused helper retained the previous deadline"
        );
    }

    #[test]
    fn saturation_waits_for_a_healthy_helper_instead_of_claiming_blocked_access() {
        let limiter = Limiter::new(1);
        let (started_tx, started_rx) = std::sync::mpsc::channel();
        let (release_tx, release_rx) = std::sync::mpsc::channel();
        let first_limiter = Arc::clone(&limiter);
        let first = std::thread::spawn(move || {
            run_with_limiter(Path::new("first"), None, first_limiter, move |_| {
                started_tx.send(()).unwrap();
                release_rx.recv().unwrap();
                Ok(1)
            })
        });
        started_rx.recv_timeout(Duration::from_secs(2)).unwrap();
        let (tx, rx) = std::sync::mpsc::channel();
        let second = std::thread::spawn(move || {
            tx.send(run_with_limiter(Path::new("second"), None, limiter, |_| {
                Ok(2)
            }))
            .unwrap()
        });
        assert!(rx.recv_timeout(Duration::from_millis(30)).is_err());
        release_tx.send(()).unwrap();
        assert_eq!(first.join().unwrap().unwrap(), 1);
        assert_eq!(rx.recv_timeout(Duration::from_secs(2)).unwrap().unwrap(), 2);
        second.join().unwrap();
    }
    #[test]
    fn saturation_deadline_is_queue_timeout_not_read_blocked() {
        let limiter = Limiter::new(1);
        let permit = limiter
            .acquire(Instant::now() + Duration::from_secs(1))
            .unwrap();
        let fired = Arc::new(AtomicUsize::new(0));
        let work_fired = Arc::clone(&fired);
        let budget = Budget::after(Duration::from_millis(80));
        let error = with_budget(Some(budget.clone()), || {
            run_with_limiter(Path::new("queued"), None, limiter, move |_| {
                work_fired.fetch_add(1, Ordering::Relaxed);
                Ok(())
            })
        })
        .unwrap_err();
        drop(permit);
        assert!(error.to_string().contains("read_io_queue_timeout"));
        assert!(!error.to_string().contains("read_blocked"));
        assert_eq!(fired.load(Ordering::Relaxed), 0);
        assert_eq!(
            budget.failure.lock().unwrap().as_ref().unwrap().code,
            "read_io_queue_timeout"
        );
    }
    #[test]
    fn accessible_directory_never_opens_a_fifo_as_a_file() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("fifo");
        fifo(&path);
        let error = with_budget(Some(Budget::after(IO_BUDGET)), || read(&path, None)).unwrap_err();
        assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
    }
    #[test]
    fn fifo_replacement_after_admission_cannot_block_direct_open() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("regular.txt");
        std::fs::write(&path, "regular\n").unwrap();
        let fired = Arc::new(AtomicUsize::new(0));
        let (reached_tx, reached_rx) = std::sync::mpsc::channel();
        FIFO_REPLACEMENTS
            .lock()
            .unwrap()
            .insert(path.clone(), (Arc::clone(&fired), reached_tx));
        let input = path.clone();
        let (tx, rx) = std::sync::mpsc::channel();
        let thread = std::thread::spawn(move || tx.send(read(&input, None)).unwrap());
        let reached = reached_rx.recv_timeout(IO_BUDGET + Duration::from_secs(1));
        let before_writer = rx.recv_timeout(Duration::from_millis(800));
        if fired.load(Ordering::Relaxed) > 0 {
            release_fifo(&path);
        }
        thread.join().unwrap();
        reached.expect("the replacement must happen after file admission");
        let error = before_writer
            .expect("a FIFO replacement blocked the direct open")
            .unwrap_err();
        assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
        assert_eq!(fired.load(Ordering::Relaxed), 1);
    }
}

#[cfg(all(test, unix))]
mod modes_macos_tests {
    use super::*;

    #[test]
    fn macos_permission_observation_preserves_eperm_and_named_folder() {
        let dir = tempfile::tempdir().unwrap();
        let budget = Budget::after(IO_BUDGET);
        let _scope = enter(Some(budget.clone()));
        let error = ProbeError::from(&io::Error::from_raw_os_error(libc::EPERM));
        assert_eq!(error.error().raw_os_error(), Some(libc::EPERM));
        observe_permission(dir.path(), &Err(error.error()), true);
        let response = finish_response(Response::success("probe", serde_json::json!({})));
        assert_eq!(response.data["code"], "macos_permission_denied");
        assert_eq!(response.data["folder"], serde_json::json!(dir.path()));
        assert_eq!(response.data["program"], "ck-aft");
        assert_eq!(budget.permissions().len(), 1);
        let non_macos = Budget::after(IO_BUDGET);
        let _scope = enter(Some(non_macos.clone()));
        observe_permission(dir.path(), &Err(error.error()), false);
        assert!(non_macos.permissions().is_empty());
    }
}

#[cfg(test)]
mod probe_target_tests {
    use super::*;

    #[test]
    fn windows_invalid_glob_name_probes_ancestors_but_access_denial_does_not() {
        let invalid_name = io::Error::from_raw_os_error(123);
        let glob = Path::new(r"C:\project\*.txt");
        assert!(missing_probe_target(&invalid_name, glob, true));
        assert!(!missing_probe_target(&invalid_name, glob, false));
        assert!(!missing_probe_target(
            &invalid_name,
            Path::new(r"C:\project\file.txt"),
            true
        ));
        assert!(!missing_probe_target(
            &io::Error::from_raw_os_error(5),
            glob,
            true
        ));
        assert!(missing_probe_target(
            &io::Error::new(io::ErrorKind::NotFound, "missing"),
            glob,
            true
        ));
    }
}