agent-file-tools 0.42.0

Agent File Tools — tree-sitter powered code analysis for AI agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
use std::collections::{BTreeMap, BTreeSet};
use std::io::{self, BufWriter};
use std::path::{Component, Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
use std::sync::{mpsc, Arc, Mutex, RwLock};
use std::time::{Duration, Instant};

use lsp_types::FileChangeType;
use notify::RecommendedWatcher;
use rusqlite::Connection;

use crate::backup::hash_session;
use crate::backup::BackupStore;
use crate::bash_background::{BgCompletion, BgTaskRegistry};
use crate::callgraph_store::{CallGraphStore, CallGraphStoreError};
use crate::checkpoint::CheckpointStore;
use crate::config::Config;
use crate::harness::Harness;
use crate::inspect::{
    InspectCategory, InspectManager, InspectSnapshot, Tier2RefreshScheduler, Tier2TriggerReason,
};
use crate::language::LanguageProvider;
use crate::lsp::manager::LspManager;
use crate::lsp::registry::is_config_file_path_with_custom;
use crate::parser::{SharedSymbolCache, SymbolCache, TreeSitterProvider};
use crate::protocol::{
    ConfigureWarningsFrame, ProgressFrame, PushFrame, StatusChangedFrame, StatusPayload,
};
use crate::watcher_filter::{SharedGitignore, WatcherDispatchEvent, WatcherThreadHandle};

pub type ProgressSender = Arc<Box<dyn Fn(PushFrame) + Send + Sync>>;
pub type SharedProgressSender = Arc<Mutex<Option<ProgressSender>>>;
pub type SharedStdoutWriter = Arc<Mutex<BufWriter<io::Stdout>>>;
const STATUS_DEBOUNCE_MS: u64 = 1_000;

/// Agent status-bar counts — the IDE-style "status bar" surfaced to the agent
/// on every tool result (emit-on-change). `errors`/`warnings` are read LIVE
/// from the continuously-drained LSP diagnostics store; the Tier-2 counts
/// (`dead_code`/`unused_exports`/`duplicates`) and `todos` are last-known,
/// refreshed when `aft_inspect` runs or a background Tier-2 scan completes.
/// `tier2_stale` marks the Tier-2 counts as not-yet-reconciled with the latest
/// edits (rendered with a `~` marker so the agent never reads them as live).
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct StatusBarCounts {
    pub errors: usize,
    pub warnings: usize,
    pub dead_code: usize,
    pub unused_exports: usize,
    pub duplicates: usize,
    pub todos: usize,
    pub tier2_stale: bool,
}

/// Last-known Tier-2 + todos counts, refreshed off the hot path. `errors` and
/// `warnings` are intentionally NOT cached here — they're read live per attach.
///
/// Each Tier-2 category is `Option`: `None` means "no scan has ever produced a
/// count for this category", so we never fabricate a `0`. The bar is only
/// surfaced once all three Tier-2 categories hold a real value — a partially
/// completed cold scan (e.g. dead_code done, unused_exports/duplicates still
/// running) must not render `D<real> U0 C0` and lie about project health (#1).
#[derive(Debug, Clone, Default)]
struct StatusBarTier2 {
    dead_code: Option<usize>,
    unused_exports: Option<usize>,
    duplicates: Option<usize>,
    todos: Option<usize>,
    stale: bool,
}

pub struct StatusEmitter {
    latest: Arc<Mutex<Option<StatusPayload>>>,
    notify: mpsc::Sender<()>,
}

impl StatusEmitter {
    fn new(progress_sender: SharedProgressSender) -> Self {
        let (notify, rx) = mpsc::channel();
        let latest = Arc::new(Mutex::new(None));
        let latest_for_thread = Arc::clone(&latest);
        std::thread::spawn(move || {
            status_debounce_loop(rx, latest_for_thread, progress_sender);
        });
        Self { latest, notify }
    }

    pub fn signal(&self, snapshot: StatusPayload) {
        if let Ok(mut latest) = self.latest.lock() {
            *latest = Some(snapshot);
        }
        let _ = self.notify.send(());
    }
}

fn status_debounce_loop(
    rx: mpsc::Receiver<()>,
    latest: Arc<Mutex<Option<StatusPayload>>>,
    progress_sender: SharedProgressSender,
) {
    while rx.recv().is_ok() {
        let deadline = Instant::now() + Duration::from_millis(STATUS_DEBOUNCE_MS);
        while let Some(remaining) = deadline.checked_duration_since(Instant::now()) {
            match rx.recv_timeout(remaining) {
                Ok(()) => continue,
                Err(mpsc::RecvTimeoutError::Timeout) => break,
                Err(mpsc::RecvTimeoutError::Disconnected) => return,
            }
        }

        let snapshot = latest.lock().ok().and_then(|mut latest| latest.take());
        let Some(snapshot) = snapshot else { continue };
        let sender = progress_sender
            .lock()
            .ok()
            .and_then(|sender| sender.clone());
        if let Some(sender) = sender {
            sender(PushFrame::StatusChanged(StatusChangedFrame::new(
                None, snapshot,
            )));
        }
    }
}
use crate::cache_freshness::FileFreshness;
use crate::search_index::SearchIndex;
use crate::semantic_index::{EmbeddingEntry, SemanticIndex};

// `SemanticIndexStatus::Ready` exposes a unique `refreshing` path list. Keep
// per-path queue accounting separately so repeated edits to the same file do not
// let an older refresh completion remove the path while newer work is pending.
#[derive(Debug, Default, Clone)]
#[doc(hidden)]
pub struct SemanticRefreshAccounting {
    #[doc(hidden)]
    pub pending: usize,
    #[doc(hidden)]
    pub in_flight: usize,
}

#[derive(Debug, Default)]
struct SemanticRefreshCircuit {
    consecutive_transient_failures: AtomicUsize,
    open: AtomicBool,
    probe_in_flight: AtomicBool,
    probe_ready: AtomicBool,
}

fn ensure_refreshing_path(refreshing: &mut Vec<PathBuf>, path: PathBuf) {
    if !refreshing.iter().any(|existing| existing == &path) {
        refreshing.push(path);
        refreshing.sort();
    }
}

fn remove_refreshing_path(refreshing: &mut Vec<PathBuf>, path: &Path) {
    refreshing.retain(|existing| existing != path);
}

#[derive(Debug, Clone)]
pub enum SemanticIndexStatus {
    Disabled,
    Building {
        /// Cold-build only — index is not queryable.
        stage: String,
        files: Option<usize>,
        entries_done: Option<usize>,
        entries_total: Option<usize>,
    },
    Ready {
        /// Files currently being re-embedded after recent edits. The index is
        /// still queryable; results for these files may be temporarily missing.
        refreshing: Vec<PathBuf>,
        /// Per-root queue accounting for repeated refreshes of the same path.
        /// Kept on the status value so two AppContexts in one process cannot
        /// share refresh-completion state.
        #[doc(hidden)]
        accounting: BTreeMap<PathBuf, SemanticRefreshAccounting>,
    },
    Failed(String),
}

impl SemanticIndexStatus {
    pub fn ready() -> Self {
        Self::Ready {
            refreshing: Vec::new(),
            accounting: BTreeMap::new(),
        }
    }

    pub fn add_refreshing_file(&mut self, path: PathBuf) {
        if let Self::Ready {
            refreshing,
            accounting,
        } = self
        {
            let state = accounting.entry(path.clone()).or_default();
            state.pending = state.pending.saturating_add(1);
            ensure_refreshing_path(refreshing, path);
        }
    }

    pub fn start_refreshing_file(&mut self, path: PathBuf) {
        if let Self::Ready {
            refreshing,
            accounting,
        } = self
        {
            let state = accounting.entry(path.clone()).or_default();
            if state.pending == 0 {
                state.pending = 1;
            }
            if state.in_flight == 0 {
                state.in_flight = state.pending;
            }
            ensure_refreshing_path(refreshing, path);
        }
    }

    pub fn cancel_refreshing_file(&mut self, path: &Path) {
        self.finish_refreshing_file(path, false);
    }

    pub fn complete_refreshing_file(&mut self, path: &Path) {
        self.finish_refreshing_file(path, true);
    }

    pub fn remove_refreshing_file(&mut self, path: &Path) {
        self.complete_refreshing_file(path);
    }

    fn finish_refreshing_file(&mut self, path: &Path, complete_in_flight: bool) {
        if let Self::Ready {
            refreshing,
            accounting,
        } = self
        {
            let mut keep_refreshing = false;
            if let Some(state) = accounting.get_mut(path) {
                let finished = if complete_in_flight {
                    state.in_flight.max(1)
                } else {
                    1
                };
                state.pending = state.pending.saturating_sub(finished);
                if complete_in_flight {
                    state.in_flight = 0;
                } else {
                    state.in_flight = state.in_flight.min(state.pending);
                }
                keep_refreshing = state.pending > 0;
                if !keep_refreshing {
                    accounting.remove(path);
                }
            }

            if !keep_refreshing {
                remove_refreshing_path(refreshing, path);
            }
        }
    }

    pub fn refreshing_count(&self) -> usize {
        match self {
            Self::Ready { refreshing, .. } => refreshing.len(),
            _ => 0,
        }
    }
}

pub enum SemanticIndexEvent {
    Progress {
        stage: String,
        files: Option<usize>,
        entries_done: Option<usize>,
        entries_total: Option<usize>,
    },
    /// Emitted when the semantic worker avoids or pauses full project corpus
    /// collection before reaching terminal Ready/Failed, such as after loading a
    /// cached index or while waiting to retry an embedding backend with no vectors
    /// retained. Work that was waiting for the full index can proceed.
    ColdSeedGateCleared,
    Ready(SemanticIndex),
    Failed(String),
}

#[derive(Debug, Clone)]
pub enum SemanticRefreshRequest {
    Files {
        paths: Vec<PathBuf>,
    },
    /// Refresh the whole semantic corpus on the refresh worker. The worker owns
    /// the project walk so watcher/configure drains never do corpus-scale work
    /// on the single dispatch thread before scheduling embedding.
    Corpus,
}

#[derive(Debug)]
pub enum SemanticRefreshEvent {
    Started {
        paths: Vec<PathBuf>,
    },
    CorpusStarted {
        files: usize,
    },
    Completed {
        added_entries: Vec<EmbeddingEntry>,
        updated_metadata: Vec<(PathBuf, FileFreshness)>,
        completed_paths: Vec<PathBuf>,
    },
    CorpusCompleted {
        index: SemanticIndex,
        changed: usize,
        added: usize,
        deleted: usize,
        total_processed: usize,
    },
    Failed {
        paths: Vec<PathBuf>,
        error: String,
    },
    CorpusFailed {
        error: String,
    },
}

pub type SemanticRefreshWorkerSlot = Arc<Mutex<Option<std::thread::JoinHandle<()>>>>;

/// Normalize a path by resolving `.` and `..` components lexically,
/// without touching the filesystem. This prevents path traversal
/// attacks when `fs::canonicalize` fails (e.g. for non-existent paths).
fn normalize_path(path: &Path) -> PathBuf {
    let mut result = PathBuf::new();
    for component in path.components() {
        match component {
            Component::ParentDir => {
                // Pop the last component unless we're at root or have no components
                if !result.pop() {
                    result.push(component);
                }
            }
            Component::CurDir => {} // Skip `.`
            _ => result.push(component),
        }
    }
    result
}

fn resolve_with_existing_ancestors(path: &Path) -> PathBuf {
    let mut existing = path.to_path_buf();
    let mut tail_segments = Vec::new();

    while !existing.exists() {
        if let Some(name) = existing.file_name() {
            tail_segments.push(name.to_owned());
        } else {
            break;
        }

        existing = match existing.parent() {
            Some(parent) => parent.to_path_buf(),
            None => break,
        };
    }

    let mut resolved = std::fs::canonicalize(&existing).unwrap_or(existing);
    for segment in tail_segments.into_iter().rev() {
        resolved.push(segment);
    }

    resolved
}

fn path_error_response(
    req_id: &str,
    path: &Path,
    resolved_root: &Path,
) -> crate::protocol::Response {
    crate::protocol::Response::error(
        req_id,
        "path_outside_root",
        format!(
            "path '{}' is outside the project root '{}'",
            path.display(),
            resolved_root.display()
        ),
    )
}

/// Walk `candidate` component-by-component. For any component that is a
/// symlink on disk, iteratively follow the full chain (up to 40 hops) and
/// reject if any hop's resolved target lies outside `resolved_root`.
///
/// This is the fallback path used when `fs::canonicalize` fails (e.g. on
/// Linux with broken symlink chains pointing to non-existent destinations).
/// On macOS `canonicalize` also fails for broken symlinks but the returned
/// `/var/...` tempdir paths diverge from `resolved_root`'s `/private/var/...`
/// form, so we must accept either form when deciding which symlinks to check.
fn reject_escaping_symlink(
    req_id: &str,
    original_path: &Path,
    candidate: &Path,
    resolved_root: &Path,
    raw_root: &Path,
) -> Result<(), crate::protocol::Response> {
    let mut current = PathBuf::new();

    for component in candidate.components() {
        current.push(component);

        let Ok(metadata) = std::fs::symlink_metadata(&current) else {
            continue;
        };

        if !metadata.file_type().is_symlink() {
            continue;
        }

        // Only check symlinks that live inside the project root. This skips
        // OS-level prefix symlinks (macOS /var → /private/var) that are not
        // inside our project directory and whose "escaping" is harmless.
        //
        // We compare against BOTH the canonicalized root (resolved_root, e.g.
        // /private/var/.../project) AND the raw root (e.g. /var/.../project)
        // because tempdir() returns raw paths while fs::canonicalize returns
        // the resolved form — and our `current` may be in either form.
        let inside_root = current.starts_with(resolved_root) || current.starts_with(raw_root);
        if !inside_root {
            continue;
        }

        iterative_follow_chain(req_id, original_path, &current, resolved_root)?;
    }

    Ok(())
}

/// Iteratively follow a symlink chain from `link` and reject if any hop's
/// resolved target is outside `resolved_root`. Depth-capped at 40 hops.
fn iterative_follow_chain(
    req_id: &str,
    original_path: &Path,
    start: &Path,
    resolved_root: &Path,
) -> Result<(), crate::protocol::Response> {
    let mut link = start.to_path_buf();
    let mut depth = 0usize;

    loop {
        if depth > 40 {
            return Err(path_error_response(req_id, original_path, resolved_root));
        }

        let target = match std::fs::read_link(&link) {
            Ok(t) => t,
            Err(_) => {
                // Can't read the link — treat as escaping to be safe.
                return Err(path_error_response(req_id, original_path, resolved_root));
            }
        };

        let resolved_target = if target.is_absolute() {
            normalize_path(&target)
        } else {
            let parent = link.parent().unwrap_or_else(|| Path::new(""));
            normalize_path(&parent.join(&target))
        };

        // Check boundary: use canonicalized target when available (handles
        // macOS /var → /private/var aliasing), fall back to the normalized
        // path when canonicalize fails (e.g. broken symlink on Linux).
        let canonical_target =
            std::fs::canonicalize(&resolved_target).unwrap_or_else(|_| resolved_target.clone());

        if !canonical_target.starts_with(resolved_root)
            && !resolved_target.starts_with(resolved_root)
        {
            return Err(path_error_response(req_id, original_path, resolved_root));
        }

        // If the target is itself a symlink, follow the next hop.
        match std::fs::symlink_metadata(&resolved_target) {
            Ok(meta) if meta.file_type().is_symlink() => {
                link = resolved_target;
                depth += 1;
            }
            _ => break, // Non-symlink or non-existent target — chain ends here.
        }
    }

    Ok(())
}

pub type LanguageProviderFactory = fn() -> Box<dyn LanguageProvider>;

pub fn default_language_provider_factory() -> Box<dyn LanguageProvider> {
    Box::new(TreeSitterProvider::new())
}

/// Process-global services shared by all project actors in this AFT process.
///
/// `App` owns only true process services. Per-root caches and the live
/// language provider instance stay in [`AppContext`].
pub struct App {
    db: parking_lot::Mutex<Option<Arc<Mutex<Connection>>>>,
    lsp_child_registry: crate::lsp::child_registry::LspChildRegistry,
    stdout_writer: SharedStdoutWriter,
    provider_factory: LanguageProviderFactory,
}

impl App {
    pub fn new(provider_factory: LanguageProviderFactory) -> Self {
        Self {
            db: parking_lot::Mutex::new(None),
            lsp_child_registry: crate::lsp::child_registry::LspChildRegistry::new(),
            stdout_writer: Arc::new(Mutex::new(BufWriter::new(io::stdout()))),
            provider_factory,
        }
    }

    /// Create the shared process `App` handle required by the actor split.
    pub fn shared(provider_factory: LanguageProviderFactory) -> Arc<Self> {
        Arc::new(Self::new(provider_factory))
    }

    pub fn default_shared() -> Arc<Self> {
        Self::shared(default_language_provider_factory)
    }

    pub fn create_provider(&self) -> Box<dyn LanguageProvider> {
        (self.provider_factory)()
    }

    pub fn lsp_child_registry(&self) -> crate::lsp::child_registry::LspChildRegistry {
        self.lsp_child_registry.clone()
    }

    pub fn stdout_writer(&self) -> SharedStdoutWriter {
        Arc::clone(&self.stdout_writer)
    }

    pub fn set_db(&self, conn: Arc<Mutex<Connection>>) {
        *self.db.lock() = Some(conn);
    }

    pub fn clear_db(&self) {
        *self.db.lock() = None;
    }

    pub fn db(&self) -> Option<Arc<Mutex<Connection>>> {
        self.db.lock().clone()
    }
}

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

const _: fn() = || {
    fn assert_send_sync<T: Send + Sync>() {}
    fn assert_send<T: Send>() {}

    assert_send_sync::<App>();
    assert_send_sync::<AppContext>();
    assert_send::<crate::lsp::manager::LspManager>();
    assert_send::<crate::semantic_index::EmbeddingModel>();
};

/// Shared application context threaded through all command handlers.
///
/// Holds the language provider, backup/checkpoint stores, and configuration.
/// Constructed once at startup and passed by
/// reference to `dispatch`.
///
/// Write-rarely stores use `parking_lot::Mutex` for interior mutability so this
/// context can become thread-safe while preserving the current single-request
/// dispatch behavior. `config` is a thread-safe owned snapshot so future
/// read-only dispatch can hold configuration across other work without holding
/// a lock guard.
pub struct AppContext {
    app: Arc<App>,
    provider: Box<dyn LanguageProvider>,
    backup: parking_lot::Mutex<BackupStore>,
    checkpoint: parking_lot::Mutex<CheckpointStore>,
    config: RwLock<Arc<Config>>,
    pub harness: parking_lot::Mutex<Option<Harness>>,
    canonical_cache_root: parking_lot::Mutex<Option<PathBuf>>,
    is_worktree_bridge: parking_lot::Mutex<bool>,
    git_common_dir: parking_lot::Mutex<Option<PathBuf>>,
    /// Reasons (if any) why heavy AFT subsystems were auto-disabled for the
    /// current project root. Populated by `handle_configure` based on the
    /// canonical project root. Each reason is a stable machine-readable string
    /// (e.g. `"home_root"`, `"watcher_unavailable"`) so the plugin can render
    /// distinct degraded-mode UI states without re-deriving the reason locally.
    /// Empty when the project is healthy / full-featured.
    degraded_reasons: parking_lot::Mutex<Vec<String>>,
    callgraph_store: RwLock<Option<Arc<CallGraphStore>>>,
    callgraph_store_force_rebuild: parking_lot::Mutex<bool>,
    callgraph_store_rx: parking_lot::Mutex<Option<crossbeam_channel::Receiver<CallGraphStore>>>,
    pending_callgraph_store_paths: parking_lot::Mutex<BTreeSet<PathBuf>>,
    search_index: RwLock<Option<SearchIndex>>,
    search_index_rx: RwLock<Option<crossbeam_channel::Receiver<SearchIndex>>>,
    pending_search_index_paths: parking_lot::Mutex<BTreeSet<PathBuf>>,
    symbol_cache: SharedSymbolCache,
    inspect_manager: Arc<InspectManager>,
    tier2_refresh_scheduler: parking_lot::Mutex<Tier2RefreshScheduler>,
    pending_tier2_paths: parking_lot::Mutex<BTreeSet<PathBuf>>,
    semantic_index: RwLock<Option<SemanticIndex>>,
    semantic_index_rx: parking_lot::Mutex<Option<crossbeam_channel::Receiver<SemanticIndexEvent>>>,
    semantic_index_status: RwLock<SemanticIndexStatus>,
    /// True while this context has a cold semantic seed scheduled or actively
    /// collecting/embedding/persisting the full project corpus. The semantic
    /// worker clears it as soon as it proves the cached/incremental path is in use.
    semantic_cold_seed_active: Arc<AtomicBool>,
    /// Monotonic generation that prevents a superseded semantic worker from
    /// reopening the cold-seed gate after a later configure has reset it.
    semantic_cold_seed_generation: Arc<AtomicU64>,
    semantic_callgraph_warm_deferred: AtomicBool,
    pending_semantic_index_paths: parking_lot::Mutex<BTreeSet<PathBuf>>,
    pending_semantic_corpus_refresh: parking_lot::Mutex<bool>,
    semantic_refresh_tx:
        parking_lot::Mutex<Option<crossbeam_channel::Sender<SemanticRefreshRequest>>>,
    semantic_refresh_event_rx:
        parking_lot::Mutex<Option<crossbeam_channel::Receiver<SemanticRefreshEvent>>>,
    semantic_refresh_worker: parking_lot::Mutex<Option<SemanticRefreshWorkerSlot>>,
    semantic_refresh_retry_attempts: parking_lot::Mutex<BTreeMap<PathBuf, usize>>,
    semantic_refresh_circuit: Arc<SemanticRefreshCircuit>,
    semantic_embedding_model: parking_lot::Mutex<Option<crate::semantic_index::EmbeddingModel>>,
    watcher: parking_lot::Mutex<Option<RecommendedWatcher>>,
    watcher_rx: parking_lot::Mutex<Option<crossbeam_channel::Receiver<WatcherDispatchEvent>>>,
    watcher_thread: parking_lot::Mutex<Option<WatcherThreadHandle>>,
    lsp_manager: parking_lot::Mutex<LspManager>,
    configure_generation: AtomicU64,
    /// Last-seen value of `InspectManager::reuse_completion_count()`, so the
    /// per-request inspect drain can detect watcher-driven Tier-2 scans that
    /// finished since the previous tick and refresh the status bar (#3).
    last_seen_reuse_completions: AtomicU64,
    configure_warnings_tx: crossbeam_channel::Sender<(u64, ConfigureWarningsFrame)>,
    configure_warnings_rx: crossbeam_channel::Receiver<(u64, ConfigureWarningsFrame)>,
    /// Per-context push sender slot. Status and background-bash emitters share
    /// this Arc so a sender installed after construction is observed at emit time.
    progress_sender: SharedProgressSender,
    status_emitter: StatusEmitter,
    /// Last status-bar payload attached to a tool response for this project root.
    /// Deduping here (not in a process-global static) lets daemon roots emit the
    /// same counts independently.
    status_bar_last_emitted: RwLock<Option<StatusBarCounts>>,
    bash_background: BgTaskRegistry,
    /// Thread-safe registry of TOML output filters. Lazy-built on first
    /// access; populated atomically via `RwLock`. Shared between command
    /// handlers (which use it through `filter_registry()` -> read guard) and
    /// the `BgTaskRegistry` watchdog thread (which uses it through
    /// `compress::compress_with_registry`). Reloaded when configure changes
    /// the project root or storage_dir; see [`AppContext::reset_filter_registry`].
    filter_registry: crate::compress::SharedFilterRegistry,
    /// Set to true once the filter_registry has been populated. Avoids
    /// double-loading on hot paths without holding a write lock.
    filter_registry_loaded: std::sync::atomic::AtomicBool,
    /// Live `experimental.bash.compress` flag, kept in sync with `config`
    /// from the configure handler. Exposed via [`AppContext::bash_compress_flag`]
    /// so the BgTaskRegistry's watchdog-thread compressor can read it without
    /// holding the config refcell.
    bash_compress_flag: Arc<std::sync::atomic::AtomicBool>,
    /// Project gitignore matcher, rebuilt by [`AppContext::rebuild_gitignore`]
    /// whenever `project_root` changes or a watcher event reports a
    /// `.gitignore` write. Used by the watcher event filter to decide which
    /// path-changes are interesting to AFT's caches. `None` when no project
    /// root is configured or when the project has no gitignore files; in that
    /// case the watcher falls back to a small hardcoded infra-directory skip.
    gitignore: SharedGitignore,
    gitignore_generation: Arc<AtomicU64>,
    /// Last-known Tier-2 + todos counts for the agent status bar, refreshed off
    /// the hot path (on `aft_inspect` reads and background Tier-2 completions).
    /// Errors/warnings are read live and not stored here.
    status_bar_tier2: RwLock<StatusBarTier2>,
    /// Persistent TypeScript-project membership cache for the status-bar E/W
    /// count. The bar reads E/W live on every tool result, so resolving the
    /// nearest tsconfig (read + parse + glob-compile) per drain is too costly;
    /// this memoizes per tsconfig dir. Invalidated wholesale on any
    /// tsconfig-like watcher event and on `configure`. Owned here (not in
    /// `DiagnosticsStore`, which stays raw policy-free) per the v0.35 council.
    tsconfig_membership:
        parking_lot::Mutex<crate::lsp::tsconfig_membership::TsconfigMembershipCache>,
}

impl Drop for AppContext {
    fn drop(&mut self) {
        if let Some(runtime) = self.watcher_thread.get_mut().take() {
            runtime.shutdown_and_join();
        }
    }
}

/// Result of requesting the persisted callgraph store for a store-backed op.
///
/// The five edge-query ops never block the request thread on a cold build:
/// a genuine cold build is kicked off in the background and `Building` is
/// returned so the agent retries, mirroring how semantic search reports a
/// build in progress. Warm restarts open the on-disk DB synchronously, so
/// `Building` is only ever seen during a true first cold build.
pub enum CallgraphStoreAccess {
    /// Store is resident and queryable.
    Ready(Arc<CallGraphStore>),
    /// A cold build is in flight (or was just started); retry shortly.
    Building,
    /// Not configured, or a read-only worktree whose store was never built.
    Unavailable,
    /// A store open/build check failed with a real error (DB/IO).
    Error(CallGraphStoreError),
}

/// Inline wait window for a callgraph-store cold build before returning
/// `Building`. Default `0` (pure-async: never block the request thread).
/// Tests set `AFT_CALLGRAPH_BUILD_WAIT_MS` large so small fixture builds
/// resolve to `Ready` synchronously and exercise query correctness directly.
fn callgraph_build_wait_window() -> Duration {
    std::env::var("AFT_CALLGRAPH_BUILD_WAIT_MS")
        .ok()
        .and_then(|raw| raw.parse::<u64>().ok())
        .map(Duration::from_millis)
        .unwrap_or(Duration::ZERO)
}

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

#[doc(hidden)]
pub fn reset_callgraph_cold_build_spawn_count_for_test() {
    CALLGRAPH_COLD_BUILD_SPAWN_COUNT.store(0, Ordering::SeqCst);
}

#[doc(hidden)]
pub fn callgraph_cold_build_spawn_count_for_test() -> usize {
    CALLGRAPH_COLD_BUILD_SPAWN_COUNT.load(Ordering::SeqCst)
}

impl AppContext {
    pub fn new(provider: Box<dyn LanguageProvider>, config: Config) -> Self {
        Self::with_app_and_provider(App::default_shared(), provider, config)
    }

    pub fn from_app(app: Arc<App>, config: Config) -> Self {
        let provider = app.create_provider();
        Self::with_app_and_provider(app, provider, config)
    }

    pub fn with_app_and_provider(
        app: Arc<App>,
        provider: Box<dyn LanguageProvider>,
        config: Config,
    ) -> Self {
        let bash_compress_enabled = config.experimental_bash_compress;
        let (configure_warnings_tx, configure_warnings_rx) = crossbeam_channel::unbounded();
        let progress_sender: SharedProgressSender = Arc::new(Mutex::new(None));
        let status_emitter = StatusEmitter::new(Arc::clone(&progress_sender));
        let symbol_cache = provider
            .as_any()
            .downcast_ref::<TreeSitterProvider>()
            .map(|provider| provider.symbol_cache())
            .unwrap_or_else(|| Arc::new(std::sync::RwLock::new(SymbolCache::new())));
        let mut lsp_manager = LspManager::new();
        lsp_manager.set_child_registry(app.lsp_child_registry());
        // Apply the configured diagnostic LRU cap (default 5000, 0 = unbounded)
        // so the documented `lsp.diagnostic_cache_size` knob takes effect.
        lsp_manager.set_diagnostic_capacity(config.diagnostic_cache_size);
        AppContext {
            app: Arc::clone(&app),
            provider,
            backup: parking_lot::Mutex::new(BackupStore::new()),
            checkpoint: parking_lot::Mutex::new(CheckpointStore::new()),
            config: RwLock::new(Arc::new(config)),
            harness: parking_lot::Mutex::new(None),
            canonical_cache_root: parking_lot::Mutex::new(None),
            is_worktree_bridge: parking_lot::Mutex::new(false),
            git_common_dir: parking_lot::Mutex::new(None),
            degraded_reasons: parking_lot::Mutex::new(Vec::new()),
            callgraph_store: RwLock::new(None),
            callgraph_store_force_rebuild: parking_lot::Mutex::new(false),
            callgraph_store_rx: parking_lot::Mutex::new(None),
            pending_callgraph_store_paths: parking_lot::Mutex::new(BTreeSet::new()),
            search_index: RwLock::new(None),
            search_index_rx: RwLock::new(None),
            pending_search_index_paths: parking_lot::Mutex::new(BTreeSet::new()),
            symbol_cache,
            inspect_manager: Arc::new(InspectManager::new()),
            tier2_refresh_scheduler: parking_lot::Mutex::new(Tier2RefreshScheduler::new()),
            pending_tier2_paths: parking_lot::Mutex::new(BTreeSet::new()),
            semantic_index: RwLock::new(None),
            semantic_index_rx: parking_lot::Mutex::new(None),
            semantic_index_status: RwLock::new(SemanticIndexStatus::Disabled),
            semantic_cold_seed_active: Arc::new(AtomicBool::new(false)),
            semantic_cold_seed_generation: Arc::new(AtomicU64::new(0)),
            semantic_callgraph_warm_deferred: AtomicBool::new(false),
            pending_semantic_index_paths: parking_lot::Mutex::new(BTreeSet::new()),
            pending_semantic_corpus_refresh: parking_lot::Mutex::new(false),
            semantic_refresh_tx: parking_lot::Mutex::new(None),
            semantic_refresh_event_rx: parking_lot::Mutex::new(None),
            semantic_refresh_worker: parking_lot::Mutex::new(None),
            semantic_refresh_retry_attempts: parking_lot::Mutex::new(BTreeMap::new()),
            semantic_refresh_circuit: Arc::new(SemanticRefreshCircuit::default()),
            semantic_embedding_model: parking_lot::Mutex::new(None),
            watcher: parking_lot::Mutex::new(None),
            watcher_rx: parking_lot::Mutex::new(None),
            watcher_thread: parking_lot::Mutex::new(None),
            lsp_manager: parking_lot::Mutex::new(lsp_manager),
            configure_generation: AtomicU64::new(0),
            last_seen_reuse_completions: AtomicU64::new(0),
            configure_warnings_tx,
            configure_warnings_rx,
            progress_sender: Arc::clone(&progress_sender),
            status_emitter,
            status_bar_last_emitted: RwLock::new(None),
            bash_background: BgTaskRegistry::new(Arc::clone(&progress_sender)),
            filter_registry: Arc::new(std::sync::RwLock::new(
                crate::compress::toml_filter::FilterRegistry::default(),
            )),
            filter_registry_loaded: std::sync::atomic::AtomicBool::new(false),
            bash_compress_flag: Arc::new(std::sync::atomic::AtomicBool::new(bash_compress_enabled)),
            gitignore: Arc::new(std::sync::RwLock::new(None)),
            gitignore_generation: Arc::new(AtomicU64::new(0)),
            status_bar_tier2: RwLock::new(StatusBarTier2::default()),
            tsconfig_membership: parking_lot::Mutex::new(
                crate::lsp::tsconfig_membership::TsconfigMembershipCache::new(),
            ),
        }
    }

    /// Current agent status-bar counts. `errors`/`warnings` are read LIVE from
    /// the LSP diagnostics store (continuously drained, no round-trip); the
    /// Tier-2 + todos counts are the last-known cached values. Returns `None`
    /// until the Tier-2 cache has been populated at least once, so we never
    /// surface a bar that misleadingly claims "0 dead code" before any scan.
    pub fn status_bar_counts(&self) -> Option<StatusBarCounts> {
        // All three Tier-2 categories must hold a real value before the bar is
        // surfaced — otherwise a partially-scanned cold run would render a
        // fabricated `0` for the not-yet-completed categories (#1). Extract the
        // values under a short read guard, drop it, then compute E/W (which
        // touches other state) with no status-bar guard held.
        let (dead_code, unused_exports, duplicates, todos, tier2_stale) = {
            let tier2 = self
                .status_bar_tier2
                .read()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            let (Some(dead_code), Some(unused_exports), Some(duplicates)) =
                (tier2.dead_code, tier2.unused_exports, tier2.duplicates)
            else {
                return None;
            };
            (
                dead_code,
                unused_exports,
                duplicates,
                tier2.todos.unwrap_or(0),
                tier2.stale,
            )
        };
        let (errors, warnings) = self.status_bar_error_warning_counts();
        Some(StatusBarCounts {
            errors,
            warnings,
            dead_code,
            unused_exports,
            duplicates,
            todos,
            tier2_stale,
        })
    }

    pub fn should_emit_status_bar(&self, counts: &StatusBarCounts) -> bool {
        let mut last = self
            .status_bar_last_emitted
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if last.as_ref() == Some(counts) {
            return false;
        }
        *last = Some(counts.clone());
        true
    }

    /// Error/warning counts for the agent status bar, filtered to match
    /// `aft_inspect`/`tsc` (v0.35 council): only diagnostics under the canonical
    /// project root, with build-excluded TS/JS files skipped via the persistent
    /// tsconfig-membership cache, and cross-server duplicates collapsed. Falls
    /// back to the raw warm count before configure has set a canonical root.
    fn status_bar_error_warning_counts(&self) -> (usize, usize) {
        let Some(root) = self.canonical_cache_root_opt() else {
            // Pre-configure: no project root to scope against. Raw count is the
            // best available signal (and the bar is gated on Tier-2 anyway).
            return self.lsp_manager.lock().warm_error_warning_counts();
        };
        let lsp = self.lsp_manager.lock();
        let mut membership = self.tsconfig_membership.lock();
        lsp.filtered_error_warning_counts(|file| {
            file.starts_with(&root) && !membership.should_skip_diagnostics(file)
        })
    }

    /// Invalidate the status-bar tsconfig-membership cache. Called from the
    /// watcher seam when a tsconfig-like file changes and from `configure`
    /// when the project root changes, so the next bar count re-reads from disk.
    pub fn clear_tsconfig_membership_cache(&self) {
        self.tsconfig_membership.lock().clear();
    }

    /// Mark the status-bar Tier-2 counts stale (rendered with `~`) without
    /// changing the numbers — called when the watcher sees a source-file change,
    /// so the bar honestly signals the counts predate the latest edit until the
    /// next background scan completes. Returns true only when the visible stale
    /// bit flips. No-op before the first populate.
    pub fn mark_status_bar_tier2_stale(&self) -> bool {
        let mut tier2 = self
            .status_bar_tier2
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        // No-op before the first full populate (nothing real to mark stale).
        if tier2.dead_code.is_some() && tier2.unused_exports.is_some() && tier2.duplicates.is_some()
        {
            let changed = !tier2.stale;
            tier2.stale = true;
            return changed;
        }
        false
    }

    /// Refresh the cached Tier-2 + todos counts for the status bar. Each count
    /// is `Option`: `None` preserves the last-known value (the category wasn't
    /// recomputed or has no real aggregate yet) so we never overwrite a real
    /// count with a fabricated `0`. `stale` marks the Tier-2 numbers as
    /// not-yet-reconciled with the latest edits.
    pub fn update_status_bar_tier2(
        &self,
        dead_code: Option<usize>,
        unused_exports: Option<usize>,
        duplicates: Option<usize>,
        todos: Option<usize>,
        stale: bool,
    ) {
        let mut tier2 = self
            .status_bar_tier2
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if let Some(dead_code) = dead_code {
            tier2.dead_code = Some(dead_code);
        }
        if let Some(unused_exports) = unused_exports {
            tier2.unused_exports = Some(unused_exports);
        }
        if let Some(duplicates) = duplicates {
            tier2.duplicates = Some(duplicates);
        }
        if let Some(todos) = todos {
            tier2.todos = Some(todos);
        }
        tier2.stale = stale;
    }

    /// Borrow the cached project gitignore matcher. Returns `None` when no
    /// project_root is configured or when the project has no gitignore files.
    pub fn gitignore(&self) -> Option<Arc<ignore::gitignore::Gitignore>> {
        self.gitignore
            .read()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .clone()
    }

    /// Shared gitignore matcher handle for the watcher filter thread.
    pub fn shared_gitignore(&self) -> SharedGitignore {
        Arc::clone(&self.gitignore)
    }

    /// Monotonic generation bumped after every matcher rebuild/clear. The
    /// watcher filter thread uses it to wait until the main thread has rebuilt
    /// ignore rules after it reports an ignore-file change.
    pub fn gitignore_generation(&self) -> Arc<AtomicU64> {
        Arc::clone(&self.gitignore_generation)
    }

    fn set_gitignore(&self, matcher: Option<Arc<ignore::gitignore::Gitignore>>) {
        *self
            .gitignore
            .write()
            .unwrap_or_else(|poisoned| poisoned.into_inner()) = matcher;
        self.gitignore_generation.fetch_add(1, Ordering::SeqCst);
    }

    /// Rebuild the gitignore matcher from the current `project_root` and
    /// cache it. Called by the configure handler whenever the project root
    /// changes, and by the watcher event drain when a `.gitignore` file
    /// itself is modified.
    ///
    /// The builder honors:
    /// - `<project_root>/.gitignore`
    /// - Git's global excludes file (the same source used by `ignore::WalkBuilder`)
    /// - the repository's real `info/exclude` file, resolved through Git's
    ///   common dir for linked worktrees
    /// - nested `.gitignore` files (each `.gitignore` discovered during
    ///   the recursive walk)
    ///
    /// Stores `None` if there's no project_root or no matchable gitignore
    /// files. Logs build errors but never fails configure.
    /// Clear any cached gitignore matcher without rebuilding.
    ///
    /// Used by `handle_configure` in degraded mode (e.g. `project_root == $HOME`)
    /// where running the gitignore-discovery walk would exceed the configure
    /// budget. The watcher event filter falls back to the hardcoded infra-dir
    /// skip list when no matcher is present.
    pub fn clear_gitignore(&self) {
        self.set_gitignore(None);
    }

    pub fn rebuild_gitignore(&self) {
        use ignore::gitignore::GitignoreBuilder;
        use std::path::Path;
        let root_raw = match self.config().project_root.clone() {
            Some(r) => r,
            None => {
                self.set_gitignore(None);
                return;
            }
        };
        // Canonicalize the root so symlink-prefix mismatches don't cause
        // `Gitignore::matched_path_or_any_parents` to panic on watcher event
        // paths. macOS routinely surfaces `/private/var/...` while `project_root`
        // arrives as `/var/...` (a symlink to `/private/var`); the `ignore`
        // crate's matcher panics when a query path isn't lexically under the
        // matcher's root. Canonicalizing both ends (here for root, naturally
        // for watcher events on macOS) keeps them in the same prefix space.
        let root = std::fs::canonicalize(&root_raw).unwrap_or(root_raw);
        let mut builder = GitignoreBuilder::new(&root);
        // Git's global excludes file — keep the live watcher matcher aligned
        // with the project walkers (`WalkBuilder::git_global(true)`). The
        // ignore crate exposes the same path discovery it uses internally, so
        // this handles the default XDG location and configured excludesFile.
        if let Some(global_ignore) = ignore::gitignore::gitconfig_excludes_path() {
            if global_ignore.is_file() {
                if let Some(err) = builder.add(&global_ignore) {
                    crate::slog_warn!(
                        "global gitignore parse error in {}: {}",
                        global_ignore.display(),
                        err
                    );
                }
            }
        }
        // Add root .gitignore (the most common case)
        let root_ignore = Path::new(&root).join(".gitignore");
        if root_ignore.exists() {
            if let Some(err) = builder.add(&root_ignore) {
                crate::slog_warn!(
                    "gitignore parse error in {}: {}",
                    root_ignore.display(),
                    err
                );
            }
        }
        // Root .aftignore — AFT-specific ignores layered on top of .gitignore.
        // Lets users exclude paths git can't (e.g. submodules) from AFT's
        // walks/indexes. Honored by the watcher matcher too, so edits under an
        // aftignored path don't trigger reindexing.
        let root_aftignore = Path::new(&root).join(".aftignore");
        if root_aftignore.exists() {
            if let Some(err) = builder.add(&root_aftignore) {
                crate::slog_warn!(
                    "aftignore parse error in {}: {}",
                    root_aftignore.display(),
                    err
                );
            }
        }
        // .git/info/exclude — manually added because GitignoreBuilder::new()
        // does not auto-discover it (verified against ignore-0.4.25 source).
        // In linked worktrees this lives under the repository common dir, not
        // under `<worktree>/.git/info/exclude` (where `.git` is only a file).
        let info_exclude = self
            .git_common_dir
            .lock()
            .clone()
            .unwrap_or_else(|| Path::new(&root).join(".git"))
            .join("info")
            .join("exclude");
        if info_exclude.exists() {
            if let Some(err) = builder.add(&info_exclude) {
                crate::slog_warn!(
                    "gitignore parse error in {}: {}",
                    info_exclude.display(),
                    err
                );
            }
        }
        // Walk the project to pick up nested .gitignore/.aftignore files at
        // arbitrary depth. The main project walkers honor deeply nested ignore
        // files, so the watcher matcher must do the same or live invalidation
        // can disagree with startup indexing. Skip obvious infra dirs so we
        // don't accidentally load a vendored repo's ignore file as ours.
        let walker = ignore::WalkBuilder::new(&root)
            .standard_filters(true)
            // Hidden files are filtered by default, but `.gitignore` starts with
            // `.` so we need to traverse "hidden" entries to find nested ones.
            // No `max_depth`: nested `.gitignore`/`.aftignore` files are honored
            // at arbitrary depth (see configure_watcher_honors_deep_nested_aftignore).
            // The walk is pruned by standard gitignore filters plus the infra
            // skip below; configure never runs this against `$HOME` (guarded by
            // `home_match`), and tests use bounded roots rather than `/`.
            .hidden(false)
            .filter_entry(|entry| {
                let name = entry.file_name().to_string_lossy();
                !matches!(
                    name.as_ref(),
                    "node_modules" | "target" | ".git" | ".opencode" | ".alfonso"
                )
            })
            .build();
        for entry in walker.flatten() {
            let file_name = entry.file_name();
            let is_nested_gitignore = file_name == ".gitignore" && entry.path() != root_ignore;
            let is_nested_aftignore = file_name == ".aftignore" && entry.path() != root_aftignore;
            if is_nested_gitignore || is_nested_aftignore {
                if let Some(err) = builder.add(entry.path()) {
                    crate::slog_warn!(
                        "nested ignore parse error in {}: {}",
                        entry.path().display(),
                        err
                    );
                }
            }
        }
        match builder.build() {
            Ok(gi) => {
                let count = gi.num_ignores();
                if count > 0 {
                    crate::slog_info!("gitignore matcher built: {} pattern(s)", count);
                    self.set_gitignore(Some(Arc::new(gi)));
                } else {
                    self.set_gitignore(None);
                }
            }
            Err(err) => {
                crate::slog_warn!("gitignore matcher build failed: {}", err);
                self.set_gitignore(None);
            }
        }
    }

    /// Shared atomic mirror of `experimental.bash.compress`. Updated by the
    /// configure handler. Read by the BgTaskRegistry compressor closure.
    pub fn bash_compress_flag(&self) -> Arc<std::sync::atomic::AtomicBool> {
        Arc::clone(&self.bash_compress_flag)
    }

    /// Update the shared `bash_compress_flag` mirror. Call this from the
    /// configure handler whenever `experimental.bash.compress` changes so the
    /// BgTaskRegistry watchdog sees the new value on the next completion.
    pub fn sync_bash_compress_flag(&self) {
        let value = self.config().experimental_bash_compress;
        self.bash_compress_flag
            .store(value, std::sync::atomic::Ordering::Relaxed);
    }

    pub fn set_bash_compress_enabled(&self, enabled: bool) {
        self.update_config(|config| {
            config.experimental_bash_compress = enabled;
        });
        self.bash_compress_flag
            .store(enabled, std::sync::atomic::Ordering::Relaxed);
    }

    /// Read-only access to the TOML filter registry, building it lazily on
    /// first use. Returns an `RwLockReadGuard` that callers can `lookup`
    /// against directly.
    pub fn filter_registry(
        &self,
    ) -> std::sync::RwLockReadGuard<'_, crate::compress::toml_filter::FilterRegistry> {
        self.ensure_filter_registry_loaded();
        match self.filter_registry.read() {
            Ok(g) => g,
            Err(poisoned) => poisoned.into_inner(),
        }
    }

    /// Returns the shared `Arc<RwLock<FilterRegistry>>` handle so threads
    /// outside `AppContext` (notably the bash watchdog) can read it without
    /// touching the rest of the context.
    pub fn shared_filter_registry(&self) -> crate::compress::SharedFilterRegistry {
        self.ensure_filter_registry_loaded();
        Arc::clone(&self.filter_registry)
    }

    /// Force a fresh load of the TOML filter registry. Called when configure
    /// changes the project root, storage_dir, or trust state so subsequent
    /// `compress::compress` calls pick up new filters.
    pub fn reset_filter_registry(&self) {
        let new_registry = crate::compress::build_registry_for_context(self);
        match self.filter_registry.write() {
            Ok(mut slot) => *slot = new_registry,
            Err(poisoned) => *poisoned.into_inner() = new_registry,
        }
        self.filter_registry_loaded
            .store(true, std::sync::atomic::Ordering::Release);
    }

    fn ensure_filter_registry_loaded(&self) {
        use std::sync::atomic::Ordering;
        if self.filter_registry_loaded.load(Ordering::Acquire) {
            return;
        }
        // Build outside the lock to avoid blocking other readers during a
        // multi-file TOML parse.
        let new_registry = crate::compress::build_registry_for_context(self);
        if let Ok(mut slot) = self.filter_registry.write() {
            *slot = new_registry;
            self.filter_registry_loaded.store(true, Ordering::Release);
        }
    }

    pub fn app(&self) -> Arc<App> {
        Arc::clone(&self.app)
    }

    /// Clone the LSP child registry handle. Used by main.rs to give the
    /// signal handler thread a way to SIGKILL LSP children on shutdown.
    pub fn lsp_child_registry(&self) -> crate::lsp::child_registry::LspChildRegistry {
        self.app.lsp_child_registry()
    }

    pub fn stdout_writer(&self) -> SharedStdoutWriter {
        self.app.stdout_writer()
    }

    pub fn set_progress_sender(&self, sender: Option<ProgressSender>) {
        if let Ok(mut progress_sender) = self.progress_sender.lock() {
            *progress_sender = sender;
        }
    }

    pub fn emit_progress(&self, frame: ProgressFrame) {
        let Ok(progress_sender) = self.progress_sender.lock().map(|sender| sender.clone()) else {
            return;
        };
        if let Some(sender) = progress_sender.as_ref() {
            sender(PushFrame::Progress(frame));
        }
    }

    pub fn status_emitter(&self) -> &StatusEmitter {
        &self.status_emitter
    }

    /// Get a clone of the current progress sender for use from background
    /// threads. Returns `None` when the main loop hasn't installed one (tests,
    /// CLI without push frames).
    ///
    /// Used by `configure`'s deferred file-walk thread to push warnings after
    /// configure has already returned, so configure latency stays sub-100 ms
    /// even on huge directories.
    pub fn progress_sender_handle(&self) -> Option<ProgressSender> {
        self.progress_sender
            .lock()
            .ok()
            .and_then(|sender| sender.clone())
    }

    pub fn advance_configure_generation(&self) -> u64 {
        self.configure_generation
            .fetch_add(1, Ordering::SeqCst)
            .wrapping_add(1)
    }

    pub fn configure_generation(&self) -> u64 {
        self.configure_generation.load(Ordering::SeqCst)
    }

    pub fn configure_warnings_sender(
        &self,
    ) -> crossbeam_channel::Sender<(u64, ConfigureWarningsFrame)> {
        self.configure_warnings_tx.clone()
    }

    pub fn drain_configure_warnings(&self) -> Vec<(u64, ConfigureWarningsFrame)> {
        let mut warnings = Vec::new();
        while let Ok(warning) = self.configure_warnings_rx.try_recv() {
            warnings.push(warning);
        }
        warnings
    }

    pub fn bash_background(&self) -> &BgTaskRegistry {
        &self.bash_background
    }

    pub fn drain_bg_completions(&self) -> Vec<BgCompletion> {
        self.bash_background.drain_completions()
    }

    /// Access the language provider.
    pub fn provider(&self) -> &dyn LanguageProvider {
        self.provider.as_ref()
    }

    /// Access the backup store.
    pub fn backup(&self) -> &parking_lot::Mutex<BackupStore> {
        &self.backup
    }

    /// Access the checkpoint store.
    pub fn checkpoint(&self) -> &parking_lot::Mutex<CheckpointStore> {
        &self.checkpoint
    }

    pub fn set_db(&self, conn: Arc<Mutex<Connection>>) {
        self.app.set_db(conn);
    }

    pub fn clear_db(&self) {
        self.app.clear_db();
    }

    pub fn db(&self) -> Option<Arc<Mutex<Connection>>> {
        self.app.db()
    }

    /// Access an owned configuration snapshot.
    pub fn config(&self) -> Arc<Config> {
        let guard = match self.config.read() {
            Ok(guard) => guard,
            Err(poisoned) => poisoned.into_inner(),
        };
        Arc::clone(&*guard)
    }

    /// Atomically publish a fully-built configuration snapshot.
    pub fn set_config(&self, config: Config) {
        let next = Arc::new(config);
        match self.config.write() {
            Ok(mut guard) => *guard = next,
            Err(poisoned) => *poisoned.into_inner() = next,
        }
    }

    /// Clone-mutate-publish the current configuration without returning a guard.
    pub fn update_config(&self, update: impl FnOnce(&mut Config)) {
        let mut next = self.config().as_ref().clone();
        update(&mut next);
        self.set_config(next);
    }

    pub fn set_harness(&self, harness: Harness) {
        self.bash_background.set_harness(harness.clone());
        *self.harness.lock() = Some(harness);
    }

    pub fn harness_opt(&self) -> Option<Harness> {
        self.harness.lock().clone()
    }

    pub fn harness(&self) -> Harness {
        self.harness_opt()
            .expect("harness set by configure before any tool call")
    }

    pub fn storage_dir(&self) -> PathBuf {
        crate::bash_background::storage_dir(self.config().storage_dir.as_deref())
    }

    pub fn harness_dir(&self) -> PathBuf {
        self.storage_dir().join(self.harness().storage_segment())
    }

    pub fn inspect_dir(&self) -> PathBuf {
        self.harness_dir().join("inspect")
    }

    pub fn bash_tasks_dir(&self, session_id: &str) -> PathBuf {
        self.harness_dir()
            .join("bash-tasks")
            .join(hash_session(session_id))
    }

    pub fn backups_dir(&self, session_id: &str, path_hash: &str) -> PathBuf {
        self.harness_dir()
            .join("backups")
            .join(hash_session(session_id))
            .join(path_hash)
    }

    pub fn filters_dir(&self) -> PathBuf {
        self.harness_dir().join("filters")
    }

    /// HOST-GLOBAL — NOT under harness_dir. Read by trust.rs across both harnesses.
    pub fn trust_file(&self) -> PathBuf {
        self.storage_dir().join("trusted-filter-projects.json")
    }

    pub fn set_canonical_cache_root(&self, root: PathBuf) {
        debug_assert!(root.is_absolute());
        *self.canonical_cache_root.lock() = Some(root);
    }

    pub fn canonical_cache_root(&self) -> PathBuf {
        self.canonical_cache_root
            .lock()
            .clone()
            .expect("canonical_cache_root accessed before handle_configure")
    }

    pub fn canonical_cache_root_opt(&self) -> Option<PathBuf> {
        self.canonical_cache_root.lock().clone()
    }

    pub fn set_cache_role(&self, is_worktree_bridge: bool, git_common_dir: Option<PathBuf>) {
        *self.is_worktree_bridge.lock() = is_worktree_bridge;
        *self.git_common_dir.lock() = git_common_dir;
    }

    pub fn is_worktree_bridge(&self) -> bool {
        *self.is_worktree_bridge.lock()
    }

    pub fn git_common_dir(&self) -> Option<PathBuf> {
        self.git_common_dir.lock().clone()
    }

    /// Replace the current degraded-mode reasons. Empty vec = full-featured
    /// mode (no degradation). Called by `handle_configure` after deciding
    /// which subsystems to disable for this project root.
    pub fn set_degraded_reasons(&self, reasons: Vec<String>) {
        *self.degraded_reasons.lock() = reasons;
    }

    pub fn add_degraded_reason(&self, reason: impl Into<String>) -> bool {
        let reason = reason.into();
        let mut reasons = self.degraded_reasons.lock();
        if reasons.iter().any(|existing| existing == &reason) {
            return false;
        }
        reasons.push(reason);
        true
    }

    /// Snapshot of current degraded-mode reasons. Order is stable
    /// (insertion order from `set_degraded_reasons`) so UI rendering and
    /// snapshot diffs are deterministic.
    pub fn degraded_reasons(&self) -> Vec<String> {
        self.degraded_reasons.lock().clone()
    }

    /// True iff at least one degraded reason is recorded.
    pub fn is_degraded(&self) -> bool {
        !self.degraded_reasons.lock().is_empty()
    }

    pub fn cache_role(&self) -> &'static str {
        if self.canonical_cache_root.lock().is_none() {
            "not_initialized"
        } else if self.is_worktree_bridge() {
            "worktree"
        } else {
            "main"
        }
    }

    /// Access the persisted call graph store.
    pub fn callgraph_store(&self) -> &RwLock<Option<Arc<CallGraphStore>>> {
        &self.callgraph_store
    }

    pub fn mark_callgraph_store_force_rebuild(&self) {
        *self.callgraph_store_force_rebuild.lock() = true;
    }

    fn take_callgraph_store_force_rebuild(&self) -> bool {
        let mut force = self.callgraph_store_force_rebuild.lock();
        let was_forced = *force;
        *force = false;
        was_forced
    }

    pub fn callgraph_store_dir(&self) -> PathBuf {
        match self.harness_opt() {
            Some(harness) => self
                .storage_dir()
                .join(harness.storage_segment())
                .join("callgraph"),
            None => self.storage_dir().join("callgraph"),
        }
    }

    pub fn ensure_callgraph_store(
        &self,
    ) -> Result<Option<Arc<CallGraphStore>>, CallGraphStoreError> {
        self.ensure_callgraph_store_with_flag(true)
    }

    fn ensure_callgraph_store_with_flag(
        &self,
        respect_config_flag: bool,
    ) -> Result<Option<Arc<CallGraphStore>>, CallGraphStoreError> {
        if respect_config_flag && !self.config().callgraph_store {
            return Ok(None);
        }
        if let Some(store) = {
            let guard = self
                .callgraph_store
                .read()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            guard.as_ref().map(Arc::clone)
        } {
            return Ok(Some(store));
        }

        let Some(project_root) = self.callgraph_project_root() else {
            return Ok(None);
        };
        let callgraph_dir = self.callgraph_store_dir();
        let force_rebuild = self.take_callgraph_store_force_rebuild();
        let store = if self.is_worktree_bridge() {
            CallGraphStore::open_readonly(callgraph_dir, project_root)?
        } else if force_rebuild {
            let files = crate::callgraph::walk_project_files(&project_root).collect::<Vec<_>>();
            let (store, _stats) = CallGraphStore::cold_build_with_lease_chunked(
                callgraph_dir,
                project_root,
                &files,
                self.config().callgraph_chunk_size,
            )?;
            Some(store)
        } else if CallGraphStore::needs_cold_build(&callgraph_dir, &project_root)? {
            let files = crate::callgraph::walk_project_files(&project_root).collect::<Vec<_>>();
            let (store, _stats) = CallGraphStore::ensure_built_with_lease_chunked(
                callgraph_dir,
                project_root,
                &files,
                self.config().callgraph_chunk_size,
            )?;
            Some(store)
        } else {
            Some(CallGraphStore::open(callgraph_dir, project_root)?)
        };

        let Some(store) = store else {
            return Ok(None);
        };
        let store = Arc::new(store);
        {
            let mut guard = self
                .callgraph_store
                .write()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            *guard = Some(Arc::clone(&store));
        }
        Ok(Some(store))
    }

    /// Resolve the project root used for the callgraph store: prefer the
    /// canonical cache root, falling back to the configured project root.
    fn callgraph_project_root(&self) -> Option<PathBuf> {
        self.canonical_cache_root_opt().or_else(|| {
            self.config()
                .project_root
                .clone()
                .map(|root| std::fs::canonicalize(&root).unwrap_or(root))
        })
    }

    /// Access the persisted callgraph store for the five store-backed edge-query
    /// ops **without ever blocking the request thread on a cold build**.
    ///
    /// - Store resident          -> `Ready`.
    /// - Warm on-disk DB present  -> opened synchronously (cheap) -> `Ready`.
    /// - Genuine cold build needed -> kicked off in the background, returns
    ///   `Building`; the watcher keeps the store fresh once it lands.
    /// - Worktree without a built store, or not configured -> `Unavailable`.
    ///
    /// A build already in flight (`callgraph_store_rx` set) also returns
    /// `Building` without starting a second build.
    /// Drop the resident callgraph store when another process (or a local cold
    /// rebuild) has published a newer generation, so the next access reopens via
    /// the pointer. No-op when no store is resident, a build is in flight, or the
    /// store is still current. Must run before serving ops AND before any
    /// incremental write, so every process converges on the current generation
    /// rather than writing to a stale one.
    pub fn revalidate_callgraph_store_generation(&self) {
        // Never disturb the store while a background build's result is pending
        // install (the rx-install path replaces it wholesale).
        if self.callgraph_store_rx.lock().is_some() {
            return;
        }
        let superseded = {
            let guard = self
                .callgraph_store
                .read()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            guard.as_ref().is_some_and(|store| !store.is_current())
        };
        if superseded {
            let mut guard = self
                .callgraph_store
                .write()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            *guard = None;
        }
    }

    pub fn callgraph_store_for_ops(&self) -> CallgraphStoreAccess {
        // Converge to a newer generation another process (or a local cold
        // rebuild) may have published: if our resident store is superseded, drop
        // it so the open path below reopens via the pointer. Cheap pointer read.
        self.revalidate_callgraph_store_generation();
        if let Some(store) = {
            let guard = self
                .callgraph_store
                .read()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            guard.as_ref().map(Arc::clone)
        } {
            return CallgraphStoreAccess::Ready(store);
        }

        // A background build is already running; don't start a second one.
        if self.callgraph_store_rx.lock().is_some() {
            return CallgraphStoreAccess::Building;
        }

        let Some(project_root) = self.callgraph_project_root() else {
            return CallgraphStoreAccess::Unavailable;
        };
        let callgraph_dir = self.callgraph_store_dir();

        // Worktree bridges are read-only: open whatever the main checkout built,
        // never cold-build here.
        if self.is_worktree_bridge() {
            match CallGraphStore::open_readonly(callgraph_dir, project_root) {
                Ok(Some(store)) => {
                    let store = Arc::new(store);
                    {
                        let mut guard = self
                            .callgraph_store
                            .write()
                            .unwrap_or_else(std::sync::PoisonError::into_inner);
                        *guard = Some(Arc::clone(&store));
                    }
                    return CallgraphStoreAccess::Ready(store);
                }
                Ok(None) | Err(_) => return CallgraphStoreAccess::Unavailable,
            }
        }

        let force_rebuild = *self.callgraph_store_force_rebuild.lock();
        // Warm path: a fresh on-disk DB exists -> open synchronously (cheap, no
        // "building" delay). Only a genuine cold build goes to the background.
        if !force_rebuild {
            match CallGraphStore::needs_cold_build(&callgraph_dir, &project_root) {
                Ok(false) => match CallGraphStore::open(callgraph_dir, project_root) {
                    Ok(store) => {
                        let store = Arc::new(store);
                        {
                            let mut guard = self
                                .callgraph_store
                                .write()
                                .unwrap_or_else(std::sync::PoisonError::into_inner);
                            *guard = Some(Arc::clone(&store));
                        }
                        return CallgraphStoreAccess::Ready(store);
                    }
                    Err(error) => return CallgraphStoreAccess::Error(error),
                },
                Ok(true) => {}
                Err(error) => return CallgraphStoreAccess::Error(error),
            }
        }

        if self.semantic_cold_seed_active() {
            self.defer_callgraph_store_warm_for_semantic_cold_seed();
            return CallgraphStoreAccess::Building;
        }

        // Cold build required: run it off the request thread and return
        // `Building` so the agent retries (the watcher keeps the store fresh
        // once it lands). By default this never blocks the request thread.
        //
        // `AFT_CALLGRAPH_BUILD_WAIT_MS` (default 0) optionally waits a bounded
        // window inline for the build to land before returning `Building`; tests
        // set it large so fixture builds resolve to `Ready` synchronously.
        if !self.spawn_callgraph_store_cold_build(project_root, callgraph_dir, force_rebuild) {
            return CallgraphStoreAccess::Building;
        }

        let wait = callgraph_build_wait_window();
        if !wait.is_zero() {
            let received = {
                let rx_ref = self.callgraph_store_rx.lock();
                let Some(rx) = rx_ref.as_ref() else {
                    return CallgraphStoreAccess::Building;
                };
                rx.recv_timeout(wait)
            };
            match received {
                Ok(store) => {
                    // Replay any source files the watcher saw during the wait so
                    // the installed store reflects mid-build edits (mirrors the
                    // drain install path). Empty in the common case.
                    let pending = self.take_pending_callgraph_store_paths();
                    if !pending.is_empty() {
                        if let Err(error) = store.refresh_files(&pending) {
                            crate::slog_warn!(
                                "callgraph store inline post-build refresh failed: {}",
                                error
                            );
                            let _ = store.mark_files_stale(&pending);
                        }
                    }
                    let store = Arc::new(store);
                    {
                        let mut guard = self
                            .callgraph_store
                            .write()
                            .unwrap_or_else(std::sync::PoisonError::into_inner);
                        *guard = Some(Arc::clone(&store));
                    }
                    *self.callgraph_store_rx.lock() = None;
                    return CallgraphStoreAccess::Ready(store);
                }
                Err(crossbeam_channel::RecvTimeoutError::Timeout) => {}
                Err(crossbeam_channel::RecvTimeoutError::Disconnected) => {
                    // Build failed before sending; clear the receiver so a later
                    // op restarts the build instead of waiting on a dead channel.
                    *self.callgraph_store_rx.lock() = None;
                }
            }
        }
        CallgraphStoreAccess::Building
    }

    /// Atomically mark a cold build in-flight and spawn the background builder.
    ///
    /// The `callgraph_store_rx` lock covers the full check + receiver install +
    /// thread spawn sequence, so concurrent cold callers cannot both observe an
    /// empty in-flight slot and double-spawn builders. Returns `false` when
    /// another caller already has a build in flight.
    fn spawn_callgraph_store_cold_build(
        &self,
        project_root: PathBuf,
        callgraph_dir: PathBuf,
        force_rebuild: bool,
    ) -> bool {
        let session_id = crate::log_ctx::current_session();
        let chunk_size = self.config().callgraph_chunk_size;

        let mut rx_guard = self.callgraph_store_rx.lock();
        if rx_guard.is_some() {
            return false;
        }

        if force_rebuild {
            // Consume the force flag now so a follow-up request doesn't queue a
            // second forced build while this one is in flight.
            self.take_callgraph_store_force_rebuild();
        }
        let (tx, rx) = crossbeam_channel::unbounded::<CallGraphStore>();
        *rx_guard = Some(rx);

        CALLGRAPH_COLD_BUILD_SPAWN_COUNT.fetch_add(1, Ordering::SeqCst);

        std::thread::spawn(move || {
            crate::log_ctx::with_session(session_id, || {
                let files = crate::callgraph::walk_project_files(&project_root).collect::<Vec<_>>();
                let built = if force_rebuild {
                    CallGraphStore::cold_build_with_lease_chunked(
                        callgraph_dir,
                        project_root,
                        &files,
                        chunk_size,
                    )
                    .map(|(store, _)| store)
                } else {
                    CallGraphStore::ensure_built_with_lease_chunked(
                        callgraph_dir,
                        project_root,
                        &files,
                        chunk_size,
                    )
                    .map(|(store, _)| store)
                };
                match built {
                    Ok(store) => {
                        let _ = tx.send(store);
                    }
                    Err(error) => {
                        crate::slog_warn!("callgraph store cold build failed: {}", error);
                        // Dropping tx disconnects the channel; the drain clears
                        // the receiver so a later op can retry the build.
                    }
                }
            });
        });
        true
    }

    /// Access the callgraph-store background-build receiver (drained by the
    /// main loop once the cold build completes).
    pub fn callgraph_store_rx(
        &self,
    ) -> &parking_lot::Mutex<Option<crossbeam_channel::Receiver<CallGraphStore>>> {
        &self.callgraph_store_rx
    }

    /// Record source-file paths that changed while a cold build was in flight,
    /// so they can be refreshed once the freshly-built store is installed.
    pub fn add_pending_callgraph_store_paths<I>(&self, paths: I)
    where
        I: IntoIterator<Item = PathBuf>,
    {
        self.pending_callgraph_store_paths.lock().extend(paths);
    }

    /// Take and clear the paths that changed during a background cold build.
    pub fn take_pending_callgraph_store_paths(&self) -> Vec<PathBuf> {
        std::mem::take(&mut *self.pending_callgraph_store_paths.lock())
            .into_iter()
            .collect()
    }

    /// Access the search index.
    pub fn search_index(&self) -> &RwLock<Option<SearchIndex>> {
        &self.search_index
    }

    /// Access the search-index build receiver.
    pub fn search_index_rx(&self) -> &RwLock<Option<crossbeam_channel::Receiver<SearchIndex>>> {
        &self.search_index_rx
    }

    pub fn add_pending_search_index_paths<I>(&self, paths: I)
    where
        I: IntoIterator<Item = PathBuf>,
    {
        self.pending_search_index_paths.lock().extend(paths);
    }

    pub fn take_pending_search_index_paths(&self) -> Vec<PathBuf> {
        std::mem::take(&mut *self.pending_search_index_paths.lock())
            .into_iter()
            .collect()
    }

    pub fn add_pending_semantic_index_paths<I>(&self, paths: I)
    where
        I: IntoIterator<Item = PathBuf>,
    {
        self.pending_semantic_index_paths.lock().extend(paths);
    }

    pub fn take_pending_semantic_index_paths(&self) -> Vec<PathBuf> {
        std::mem::take(&mut *self.pending_semantic_index_paths.lock())
            .into_iter()
            .collect()
    }

    pub fn mark_pending_semantic_corpus_refresh(&self) {
        *self.pending_semantic_corpus_refresh.lock() = true;
    }

    pub fn take_pending_semantic_corpus_refresh(&self) -> bool {
        std::mem::take(&mut *self.pending_semantic_corpus_refresh.lock())
    }

    pub fn clear_pending_index_updates(&self) {
        self.pending_search_index_paths.lock().clear();
        self.pending_callgraph_store_paths.lock().clear();
        self.pending_tier2_paths.lock().clear();
        self.pending_semantic_index_paths.lock().clear();
        *self.pending_semantic_corpus_refresh.lock() = false;
    }

    pub fn inspect_manager(&self) -> Arc<InspectManager> {
        Arc::clone(&self.inspect_manager)
    }

    pub fn add_pending_tier2_paths<I>(&self, paths: I)
    where
        I: IntoIterator<Item = PathBuf>,
    {
        self.pending_tier2_paths.lock().extend(paths);
    }

    pub fn pending_tier2_paths(&self) -> Vec<PathBuf> {
        self.pending_tier2_paths.lock().iter().cloned().collect()
    }

    pub fn remove_pending_tier2_paths<I>(&self, paths: I)
    where
        I: IntoIterator<Item = PathBuf>,
    {
        let mut pending = self.pending_tier2_paths.lock();
        for path in paths {
            pending.remove(&path);
        }
    }

    /// Returns true when one or more watcher-driven (reuse-path) Tier-2 scans
    /// have completed since the last call, advancing the last-seen marker. The
    /// per-request inspect drain uses this to refresh the status bar after a
    /// background scan — those completions bypass `drain_completions`.
    pub fn take_new_reuse_completions(&self) -> bool {
        let current = self.inspect_manager.reuse_completion_count();
        let previous = self
            .last_seen_reuse_completions
            .swap(current, Ordering::SeqCst);
        current != previous
    }

    pub fn reset_tier2_refresh_scheduler(&self) {
        self.reset_tier2_refresh_scheduler_at(Instant::now());
    }

    #[doc(hidden)]
    pub fn reset_tier2_refresh_scheduler_at(&self, now: Instant) {
        self.tier2_refresh_scheduler
            .lock()
            .reset_after_configure(now);
    }

    pub fn request_tier2_refresh_pull(&self) -> bool {
        self.tier2_refresh_scheduler
            .lock()
            .request_pull(!self.is_worktree_bridge())
    }

    pub fn tick_tier2_refresh_scheduler(
        &self,
        changed_path_count: usize,
    ) -> Option<Tier2TriggerReason> {
        self.tick_tier2_refresh_scheduler_at(Instant::now(), changed_path_count)
    }

    #[doc(hidden)]
    pub fn tick_tier2_refresh_scheduler_at(
        &self,
        now: Instant,
        changed_path_count: usize,
    ) -> Option<Tier2TriggerReason> {
        let manager = self.inspect_manager();
        let can_write = !self.is_worktree_bridge();
        let in_flight = manager.tier2_any_in_flight();
        let semantic_cold_seed_active = self.semantic_cold_seed_active();
        let decision = self.tier2_refresh_scheduler.lock().tick_with_semantic_gate(
            now,
            changed_path_count,
            can_write,
            in_flight,
            semantic_cold_seed_active,
        );

        if let Some(reason) = decision {
            self.start_tier2_refresh(reason, manager);
        }

        decision
    }

    pub fn note_tier2_refresh_started(&self) {
        self.note_tier2_refresh_started_at(Instant::now());
    }

    #[doc(hidden)]
    pub fn note_tier2_refresh_started_at(&self, now: Instant) {
        self.tier2_refresh_scheduler
            .lock()
            .note_external_scan_started(now);
    }

    pub fn tier2_trigger_reason(&self) -> Option<&'static str> {
        self.tier2_refresh_scheduler
            .lock()
            .last_trigger_reason()
            .map(Tier2TriggerReason::as_str)
    }

    #[doc(hidden)]
    pub fn tier2_pull_demand_pending(&self) -> bool {
        self.tier2_refresh_scheduler.lock().pull_demand_pending()
    }

    fn start_tier2_refresh(&self, reason: Tier2TriggerReason, manager: Arc<InspectManager>) {
        if self.is_worktree_bridge()
            || self
                .degraded_reasons
                .lock()
                .iter()
                .any(|r| r == "home_root")
            || !self.config().inspect.enabled
        {
            return;
        }
        let Some(snapshot) = self.tier2_refresh_snapshot() else {
            return;
        };
        let categories = InspectCategory::active()
            .iter()
            .copied()
            .filter(|category| category.is_tier2())
            .collect::<Vec<_>>();
        let submission =
            manager.submit_tier2_run_with_reuse_serial_background(snapshot, categories);
        if submission.has_new_work() {
            crate::slog_info!(
                "tier2 refresh scheduled: reason={}, categories={:?}",
                reason.as_str(),
                submission
                    .newly_queued_categories
                    .iter()
                    .map(|category| category.as_str())
                    .collect::<Vec<_>>()
            );
        }
        for error in submission.errors {
            crate::slog_warn!(
                "tier2 refresh schedule failed for {}: {}",
                error.category,
                error.message
            );
        }
    }

    fn tier2_refresh_snapshot(&self) -> Option<InspectSnapshot> {
        self.harness_opt()?;
        let config = self.config();
        let project_root = config
            .project_root
            .clone()
            .unwrap_or_else(|| std::env::current_dir().unwrap_or_default());
        let project_root = std::fs::canonicalize(&project_root).unwrap_or(project_root);
        Some(InspectSnapshot::new(
            project_root,
            self.inspect_dir(),
            config,
            self.symbol_cache(),
        ))
    }

    /// Access the shared symbol cache.
    pub fn symbol_cache(&self) -> SharedSymbolCache {
        Arc::clone(&self.symbol_cache)
    }

    /// Clear the shared symbol cache and return the new active generation.
    pub fn reset_symbol_cache(&self) -> u64 {
        self.symbol_cache
            .write()
            .map(|mut cache| cache.reset())
            .unwrap_or(0)
    }

    /// Access the semantic search index.
    pub fn semantic_index(&self) -> &RwLock<Option<SemanticIndex>> {
        &self.semantic_index
    }

    /// Access the semantic-index build receiver.
    pub fn semantic_index_rx(
        &self,
    ) -> &parking_lot::Mutex<Option<crossbeam_channel::Receiver<SemanticIndexEvent>>> {
        &self.semantic_index_rx
    }

    pub fn semantic_index_status(&self) -> &RwLock<SemanticIndexStatus> {
        &self.semantic_index_status
    }

    /// Reset this context's cold semantic seed gate for a newly accepted
    /// configure and return the generation token for the worker being spawned.
    pub fn reset_semantic_cold_seed_gate_for_configure(&self) -> u64 {
        self.semantic_cold_seed_active
            .store(false, Ordering::SeqCst);
        self.semantic_callgraph_warm_deferred
            .store(false, Ordering::SeqCst);
        self.semantic_cold_seed_generation
            .fetch_add(1, Ordering::SeqCst)
            .wrapping_add(1)
    }

    pub fn semantic_cold_seed_active_flag(&self) -> Arc<AtomicBool> {
        Arc::clone(&self.semantic_cold_seed_active)
    }

    pub fn semantic_cold_seed_generation_flag(&self) -> Arc<AtomicU64> {
        Arc::clone(&self.semantic_cold_seed_generation)
    }

    pub fn semantic_cold_seed_active(&self) -> bool {
        self.semantic_cold_seed_active.load(Ordering::SeqCst)
    }

    pub fn schedule_semantic_cold_seed_gate_for_configure(&self) {
        self.semantic_cold_seed_active.store(true, Ordering::SeqCst);
    }

    pub fn defer_callgraph_store_warm_for_semantic_cold_seed(&self) {
        self.semantic_callgraph_warm_deferred
            .store(true, Ordering::SeqCst);
    }

    fn semantic_callgraph_warm_deferred(&self) -> bool {
        self.semantic_callgraph_warm_deferred.load(Ordering::SeqCst)
    }

    /// Clear the cold-seed gate and resume work that was intentionally held back
    /// while the full semantic corpus was accumulating. This entry point is used
    /// by the code that drains events from the semantic worker.
    pub fn clear_semantic_cold_seed_gate_and_resume_deferred_work(&self) {
        self.resume_semantic_cold_seed_deferred_work(false);
    }

    /// Resume work after the semantic worker has already cleared the atomic gate
    /// itself, such as on cached-index load or before a retry backoff sleep.
    pub fn resume_deferred_work_after_semantic_cold_seed_gate_cleared(&self) {
        self.resume_semantic_cold_seed_deferred_work(true);
    }

    fn resume_semantic_cold_seed_deferred_work(&self, force: bool) {
        let was_active = self.semantic_cold_seed_active.swap(false, Ordering::SeqCst);
        let had_deferred_callgraph = self.semantic_callgraph_warm_deferred();

        if force || was_active || had_deferred_callgraph {
            let _ = self.request_tier2_refresh_pull();
        }

        if self
            .semantic_callgraph_warm_deferred
            .swap(false, Ordering::SeqCst)
        {
            if !self.config().callgraph_store
                || self
                    .degraded_reasons
                    .lock()
                    .iter()
                    .any(|reason| reason == "home_root")
            {
                return;
            }

            match self.callgraph_store_for_ops() {
                CallgraphStoreAccess::Ready(_) => {
                    crate::slog_debug!(
                        "deferred callgraph store warm completed after semantic cold seed gate cleared"
                    );
                }
                CallgraphStoreAccess::Building => {
                    crate::slog_info!(
                        "deferred callgraph store warm scheduled after semantic cold seed gate cleared"
                    );
                }
                CallgraphStoreAccess::Unavailable => {
                    crate::slog_info!(
                        "deferred callgraph store warm unavailable after semantic cold seed gate cleared"
                    );
                }
                CallgraphStoreAccess::Error(error) => {
                    crate::slog_warn!(
                        "deferred callgraph store warm failed after semantic cold seed gate cleared: {}",
                        error
                    );
                }
            }
        }
    }

    #[doc(hidden)]
    pub fn set_semantic_cold_seed_active_for_test(&self, active: bool) {
        self.semantic_cold_seed_active
            .store(active, Ordering::SeqCst);
    }

    #[doc(hidden)]
    pub fn semantic_callgraph_warm_deferred_for_test(&self) -> bool {
        self.semantic_callgraph_warm_deferred()
    }

    pub fn install_semantic_refresh_worker(
        &self,
        sender: crossbeam_channel::Sender<SemanticRefreshRequest>,
        event_rx: crossbeam_channel::Receiver<SemanticRefreshEvent>,
        worker_slot: SemanticRefreshWorkerSlot,
    ) {
        self.clear_semantic_refresh_worker();
        *self.semantic_refresh_tx.lock() = Some(sender);
        *self.semantic_refresh_event_rx.lock() = Some(event_rx);
        *self.semantic_refresh_worker.lock() = Some(worker_slot);
    }

    pub fn clear_semantic_refresh_worker(&self) {
        *self.semantic_refresh_tx.lock() = None;
        *self.semantic_refresh_event_rx.lock() = None;
        if let Some(worker_slot) = self.semantic_refresh_worker.lock().take() {
            if let Ok(mut handle) = worker_slot.lock() {
                drop(handle.take());
            }
        }
    }

    pub fn semantic_refresh_sender(
        &self,
    ) -> Option<crossbeam_channel::Sender<SemanticRefreshRequest>> {
        self.semantic_refresh_tx.lock().clone()
    }

    pub fn semantic_refresh_event_rx(
        &self,
    ) -> &parking_lot::Mutex<Option<crossbeam_channel::Receiver<SemanticRefreshEvent>>> {
        &self.semantic_refresh_event_rx
    }

    pub fn with_semantic_refresh_retry_attempts_mut<R>(
        &self,
        f: impl FnOnce(&mut BTreeMap<PathBuf, usize>) -> R,
    ) -> R {
        let mut attempts = self.semantic_refresh_retry_attempts.lock();
        f(&mut attempts)
    }

    pub fn clear_semantic_refresh_retry_attempts(&self, paths: &[PathBuf]) {
        let mut attempts = self.semantic_refresh_retry_attempts.lock();
        for path in paths {
            attempts.remove(path);
        }
    }

    pub fn clear_all_semantic_refresh_retry_attempts(&self) {
        self.semantic_refresh_retry_attempts.lock().clear();
    }

    pub fn semantic_refresh_circuit_is_open(&self) -> bool {
        self.semantic_refresh_circuit.open.load(Ordering::SeqCst)
    }

    pub fn record_semantic_refresh_transient_failure(&self, trip_threshold: usize) -> bool {
        let failures = self
            .semantic_refresh_circuit
            .consecutive_transient_failures
            .fetch_add(1, Ordering::SeqCst)
            .saturating_add(1);
        if failures >= trip_threshold
            && !self
                .semantic_refresh_circuit
                .open
                .swap(true, Ordering::SeqCst)
        {
            crate::slog_warn!(
                "embedding backend appears down; suspending active retries, will resume on next change or successful probe"
            );
        }
        self.semantic_refresh_circuit_is_open()
    }

    pub fn reset_semantic_refresh_transient_failure_count(&self) {
        self.semantic_refresh_circuit
            .consecutive_transient_failures
            .store(0, Ordering::SeqCst);
    }

    pub fn reset_semantic_refresh_circuit_after_success(&self) {
        self.reset_semantic_refresh_transient_failure_count();
        self.semantic_refresh_circuit
            .probe_ready
            .store(false, Ordering::SeqCst);
        if self
            .semantic_refresh_circuit
            .open
            .swap(false, Ordering::SeqCst)
        {
            crate::slog_info!("embedding backend recovered; resuming normal refresh retries");
        }
    }

    pub fn semantic_refresh_transient_failure_count(&self) -> usize {
        self.semantic_refresh_circuit
            .consecutive_transient_failures
            .load(Ordering::SeqCst)
    }

    pub fn semantic_refresh_probe_is_scheduled(&self) -> bool {
        self.semantic_refresh_circuit
            .probe_in_flight
            .load(Ordering::SeqCst)
            || self
                .semantic_refresh_circuit
                .probe_ready
                .load(Ordering::SeqCst)
    }

    pub fn take_semantic_refresh_probe_ready(&self) -> bool {
        self.semantic_refresh_circuit
            .probe_ready
            .swap(false, Ordering::SeqCst)
    }

    pub fn ensure_semantic_refresh_probe_scheduled(&self, delay: Duration) {
        if self
            .semantic_refresh_circuit
            .probe_ready
            .load(Ordering::SeqCst)
        {
            return;
        }
        if self
            .semantic_refresh_circuit
            .probe_in_flight
            .swap(true, Ordering::SeqCst)
        {
            return;
        }
        if self
            .semantic_refresh_circuit
            .probe_ready
            .load(Ordering::SeqCst)
        {
            self.semantic_refresh_circuit
                .probe_in_flight
                .store(false, Ordering::SeqCst);
            return;
        }

        let circuit = Arc::clone(&self.semantic_refresh_circuit);
        let session_id = crate::log_ctx::current_session();
        std::thread::spawn(move || {
            crate::log_ctx::with_session(session_id, || {
                std::thread::sleep(delay);
                circuit.probe_ready.store(true, Ordering::SeqCst);
                circuit.probe_in_flight.store(false, Ordering::SeqCst);
            });
        });
    }

    /// Access the cached semantic embedding model.
    pub fn semantic_embedding_model(
        &self,
    ) -> &parking_lot::Mutex<Option<crate::semantic_index::EmbeddingModel>> {
        &self.semantic_embedding_model
    }

    /// Access the file watcher handle (kept alive to continue watching).
    pub fn watcher(&self) -> &parking_lot::Mutex<Option<RecommendedWatcher>> {
        &self.watcher
    }

    /// Access the pre-filtered watcher event receiver.
    pub fn watcher_rx(
        &self,
    ) -> &parking_lot::Mutex<Option<crossbeam_channel::Receiver<WatcherDispatchEvent>>> {
        &self.watcher_rx
    }

    /// Install a watcher filter thread and its dispatch receiver. The caller
    /// must have stopped any previous watcher runtime first.
    pub fn install_watcher_runtime(
        &self,
        rx: crossbeam_channel::Receiver<WatcherDispatchEvent>,
        runtime: WatcherThreadHandle,
    ) {
        *self.watcher_rx.lock() = Some(rx);
        *self.watcher_thread.lock() = Some(runtime);
    }

    /// Stop the watcher filter thread (if any) and clear the dispatch receiver.
    /// Used on reconfigure, watcher failure, root deletion, and test teardown.
    pub fn stop_watcher_runtime(&self) {
        if let Some(runtime) = self.watcher_thread.lock().take() {
            runtime.shutdown_and_join();
        }
        *self.watcher_rx.lock() = None;
        *self.watcher.lock() = None;
    }

    /// Access the LSP manager.
    pub fn lsp(&self) -> parking_lot::MutexGuard<'_, LspManager> {
        self.lsp_manager.lock()
    }

    /// Notify LSP servers that a file was written.
    /// Call this after write_format_validate in command handlers.
    pub fn lsp_notify_file_changed(&self, file_path: &Path, content: &str) {
        let config = self.config();
        if let Some(mut lsp) = self.lsp_manager.try_lock() {
            if let Err(e) = lsp.notify_file_changed(file_path, content, &config) {
                crate::slog_warn!("sync error for {}: {}", file_path.display(), e);
            }
        }
    }

    /// Drop cached LSP diagnostics for a deleted/renamed-away file so its
    /// errors/warnings don't linger in the warm set (no server republishes for
    /// a vanished path), keeping the status bar and `aft_inspect` honest.
    /// Returns true if any entry was removed. Best-effort: a contended borrow is
    /// skipped silently (the watcher drain retries on subsequent events).
    pub fn lsp_clear_diagnostics_for_file(&self, file_path: &Path) -> bool {
        if let Some(mut lsp) = self.lsp_manager.try_lock() {
            lsp.clear_diagnostics_for_file(file_path)
        } else {
            false
        }
    }

    /// Notify LSP and optionally wait for diagnostics.
    ///
    /// Call this after `write_format_validate` when the request has `"diagnostics": true`.
    /// Sends didChange to the server, waits briefly for publishDiagnostics, and returns
    /// any diagnostics for the file. If no server is running, returns empty immediately.
    ///
    /// v0.17.3: this is the version-aware path. Pre-edit cached diagnostics
    /// are NEVER returned — only entries whose `version` matches the
    /// post-edit document version (or, for unversioned servers, whose
    /// `epoch` advanced past the pre-edit snapshot).
    pub fn lsp_notify_and_collect_diagnostics(
        &self,
        file_path: &Path,
        content: &str,
        timeout: std::time::Duration,
    ) -> crate::lsp::manager::PostEditWaitOutcome {
        let config = self.config();
        let Some(mut lsp) = self.lsp_manager.try_lock() else {
            return crate::lsp::manager::PostEditWaitOutcome::default();
        };

        // Clear any queued notifications before this write so the wait loop only
        // observes diagnostics triggered by the current change.
        lsp.drain_events();

        // Snapshot per-server epochs and document versions BEFORE sending
        // didChange so the wait loop can prove freshness without accepting
        // stale pre-edit publishes that arrived late.
        let pre_snapshot = lsp.snapshot_pre_edit_state(file_path);

        // Send didChange/didOpen and capture per-server target version.
        let expected_versions = match lsp.notify_file_changed_versioned(file_path, content, &config)
        {
            Ok(v) => v,
            Err(e) => {
                crate::slog_warn!("sync error for {}: {}", file_path.display(), e);
                return crate::lsp::manager::PostEditWaitOutcome::default();
            }
        };

        // No server matched this file — return an empty outcome that's
        // honestly `complete: true` (nothing to wait for).
        if expected_versions.is_empty() {
            return crate::lsp::manager::PostEditWaitOutcome::default();
        }

        lsp.wait_for_post_edit_diagnostics(
            file_path,
            &config,
            &expected_versions,
            &pre_snapshot,
            timeout,
        )
    }

    /// Collect custom server root_markers from user config for use in
    /// `is_config_file_path_with_custom` checks (#25).
    fn custom_lsp_root_markers(&self) -> Vec<String> {
        self.config()
            .lsp_servers
            .iter()
            .flat_map(|s| s.root_markers.iter().cloned())
            .collect()
    }

    fn notify_watched_config_files(&self, file_paths: &[PathBuf]) {
        let custom_markers = self.custom_lsp_root_markers();
        let config_paths: Vec<(PathBuf, FileChangeType)> = file_paths
            .iter()
            .filter(|path| is_config_file_path_with_custom(path, &custom_markers))
            .cloned()
            .map(|path| {
                let change_type = if path.exists() {
                    FileChangeType::CHANGED
                } else {
                    FileChangeType::DELETED
                };
                (path, change_type)
            })
            .collect();

        self.notify_watched_config_events(&config_paths);
    }

    fn multi_file_write_paths(params: &serde_json::Value) -> Option<Vec<PathBuf>> {
        let paths = params
            .get("multi_file_write_paths")
            .and_then(|value| value.as_array())?
            .iter()
            .filter_map(|value| value.as_str())
            .map(PathBuf::from)
            .collect::<Vec<_>>();

        (!paths.is_empty()).then_some(paths)
    }

    /// Parse config-file watched events from `multi_file_write_paths` when the
    /// array contains object entries `{ "path": "...", "type": "created|changed|deleted" }`.
    ///
    /// This handles the OBJECT variant of `multi_file_write_paths`. The STRING
    /// variant (bare path strings) is handled by `multi_file_write_paths()` and
    /// `notify_watched_config_files()`. Both variants read the same JSON key but
    /// with different per-entry schemas — they are NOT redundant.
    ///
    /// #18 note: in older code this function also existed alongside `multi_file_write_paths()`
    /// and was reachable via the `else if` branch when all entries were objects.
    /// Restoring both is correct.
    fn watched_file_events_from_params(
        params: &serde_json::Value,
        extra_markers: &[String],
    ) -> Option<Vec<(PathBuf, FileChangeType)>> {
        let events = params
            .get("multi_file_write_paths")
            .and_then(|value| value.as_array())?
            .iter()
            .filter_map(|entry| {
                // Only handle object entries — string entries go through multi_file_write_paths()
                let path = entry
                    .get("path")
                    .and_then(|value| value.as_str())
                    .map(PathBuf::from)?;

                if !is_config_file_path_with_custom(&path, extra_markers) {
                    return None;
                }

                let change_type = entry
                    .get("type")
                    .and_then(|value| value.as_str())
                    .and_then(Self::parse_file_change_type)
                    .unwrap_or_else(|| Self::change_type_from_current_state(&path));

                Some((path, change_type))
            })
            .collect::<Vec<_>>();

        (!events.is_empty()).then_some(events)
    }

    fn parse_file_change_type(value: &str) -> Option<FileChangeType> {
        match value {
            "created" | "CREATED" | "Created" => Some(FileChangeType::CREATED),
            "changed" | "CHANGED" | "Changed" => Some(FileChangeType::CHANGED),
            "deleted" | "DELETED" | "Deleted" => Some(FileChangeType::DELETED),
            _ => None,
        }
    }

    fn change_type_from_current_state(path: &Path) -> FileChangeType {
        if path.exists() {
            FileChangeType::CHANGED
        } else {
            FileChangeType::DELETED
        }
    }

    fn notify_watched_config_events(&self, config_paths: &[(PathBuf, FileChangeType)]) {
        if config_paths.is_empty() {
            return;
        }

        let config = self.config();
        if let Some(mut lsp) = self.lsp_manager.try_lock() {
            if let Err(e) = lsp.notify_files_watched_changed(config_paths, &config) {
                crate::slog_warn!("watched-file sync error: {}", e);
            }
        }
    }

    pub fn lsp_notify_watched_config_file(&self, file_path: &Path, change_type: FileChangeType) {
        let custom_markers = self.custom_lsp_root_markers();
        if !is_config_file_path_with_custom(file_path, &custom_markers) {
            return;
        }

        self.notify_watched_config_events(&[(file_path.to_path_buf(), change_type)]);
    }

    /// Post-write LSP hook for multi-file edits. When the patch includes
    /// config-file edits, notify active workspace servers via
    /// `workspace/didChangeWatchedFiles` before sending the per-document
    /// didOpen/didChange for the current file.
    pub fn lsp_post_multi_file_write(
        &self,
        file_path: &Path,
        content: &str,
        file_paths: &[PathBuf],
        params: &serde_json::Value,
    ) -> Option<crate::lsp::manager::PostEditWaitOutcome> {
        self.notify_watched_config_files(file_paths);
        self.add_pending_tier2_paths(file_paths.iter().cloned());
        let _ = self.mark_status_bar_tier2_stale();

        let wants_diagnostics = params
            .get("diagnostics")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);

        if !wants_diagnostics {
            self.lsp_notify_file_changed(file_path, content);
            return None;
        }

        let wait_ms = params
            .get("wait_ms")
            .and_then(|v| v.as_u64())
            .unwrap_or(3000)
            .min(10_000);

        Some(self.lsp_notify_and_collect_diagnostics(
            file_path,
            content,
            std::time::Duration::from_millis(wait_ms),
        ))
    }

    /// Post-write LSP hook: notify server and optionally collect diagnostics.
    ///
    /// This is the single call site for all command handlers after `write_format_validate`.
    /// Behavior:
    /// - When `diagnostics: true` is in `params`, notifies the server, waits
    ///   until matching diagnostics arrive or the timeout expires, and returns
    ///   `Some(outcome)` with the verified-fresh diagnostics + per-server
    ///   status.
    /// - When `diagnostics: false` (or absent), just notifies (fire-and-forget)
    ///   and returns `None`. Callers must NOT wrap this in `Some(...)`; the
    ///   `None` is what tells the response builder to omit the LSP fields
    ///   entirely (preserves the no-diagnostics-requested response shape).
    ///
    /// v0.17.3: default `wait_ms` raised from 1500 to 3000 because real-world
    /// tsserver re-analysis on monorepo files routinely takes 2-5s. Still
    /// capped at 10000ms.
    pub fn lsp_post_write(
        &self,
        file_path: &Path,
        content: &str,
        params: &serde_json::Value,
    ) -> Option<crate::lsp::manager::PostEditWaitOutcome> {
        let wants_diagnostics = params
            .get("diagnostics")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);

        let custom_markers = self.custom_lsp_root_markers();
        if let Some(file_paths) = Self::multi_file_write_paths(params) {
            self.add_pending_tier2_paths(file_paths);
        } else {
            self.add_pending_tier2_paths([file_path.to_path_buf()]);
        }
        let _ = self.mark_status_bar_tier2_stale();

        if !wants_diagnostics {
            if let Some(file_paths) = Self::multi_file_write_paths(params) {
                self.notify_watched_config_files(&file_paths);
            } else if let Some(config_events) =
                Self::watched_file_events_from_params(params, &custom_markers)
            {
                self.notify_watched_config_events(&config_events);
            }
            self.lsp_notify_file_changed(file_path, content);
            return None;
        }

        let wait_ms = params
            .get("wait_ms")
            .and_then(|v| v.as_u64())
            .unwrap_or(3000)
            .min(10_000); // Cap at 10 seconds to prevent hangs from adversarial input

        if let Some(file_paths) = Self::multi_file_write_paths(params) {
            return self.lsp_post_multi_file_write(file_path, content, &file_paths, params);
        }

        if let Some(config_events) = Self::watched_file_events_from_params(params, &custom_markers)
        {
            self.notify_watched_config_events(&config_events);
        }

        Some(self.lsp_notify_and_collect_diagnostics(
            file_path,
            content,
            std::time::Duration::from_millis(wait_ms),
        ))
    }

    /// Validate that a file path falls within the configured project root.
    ///
    /// When `project_root` is configured (normal plugin usage), this resolves the
    /// path and checks it starts with the root. Returns the canonicalized path on
    /// success, or an error response on violation.
    ///
    /// When no `project_root` is configured (direct CLI usage), all paths pass
    /// through unrestricted for backward compatibility.
    pub fn validate_path(
        &self,
        req_id: &str,
        path: &Path,
    ) -> Result<std::path::PathBuf, crate::protocol::Response> {
        let config = self.config();
        // When restrict_to_project_root is false (default), allow all paths
        if !config.restrict_to_project_root {
            return Ok(path.to_path_buf());
        }
        let root = match &config.project_root {
            Some(r) => r.clone(),
            None => return Ok(path.to_path_buf()), // No root configured, allow all
        };
        drop(config);

        // Keep the raw root for symlink-guard comparisons. On macOS, tempdir()
        // returns /var/... paths while canonicalize gives /private/var/...; we
        // need both forms so reject_escaping_symlink can recognise in-root
        // symlinks regardless of which prefix form `current` happens to have.
        let raw_root = root.clone();
        let resolved_root = std::fs::canonicalize(&root).unwrap_or(root);

        // Resolve the path (follow symlinks, normalize ..). If canonicalization
        // fails (e.g. path does not exist or traverses a broken symlink), inspect
        // every existing component with lstat before falling back lexically so a
        // broken in-root symlink cannot be used to write outside project_root.
        let path_for_resolution = if path.is_relative() {
            raw_root.join(path)
        } else {
            path.to_path_buf()
        };
        let resolved = match std::fs::canonicalize(&path_for_resolution) {
            Ok(resolved) => resolved,
            Err(_) => {
                let normalized = normalize_path(&path_for_resolution);
                reject_escaping_symlink(
                    req_id,
                    &path_for_resolution,
                    &normalized,
                    &resolved_root,
                    &raw_root,
                )?;
                resolve_with_existing_ancestors(&normalized)
            }
        };

        if !resolved.starts_with(&resolved_root) {
            return Err(path_error_response(req_id, path, &resolved_root));
        }

        Ok(resolved)
    }

    /// Count active LSP server instances.
    pub fn lsp_server_count(&self) -> usize {
        self.lsp_manager
            .try_lock()
            .map(|lsp| lsp.server_count())
            .unwrap_or(0)
    }

    /// Symbol cache statistics from the language provider.
    pub fn symbol_cache_stats(&self) -> serde_json::Value {
        let entries = self
            .symbol_cache
            .read()
            .map(|cache| cache.len())
            .unwrap_or(0);
        serde_json::json!({
            "local_entries": entries,
            "warm_entries": 0,
        })
    }
}

#[cfg(test)]
mod callgraph_store_for_ops_tests {
    use super::*;
    use crate::parser::TreeSitterProvider;
    use std::ffi::OsString;
    use std::sync::{Barrier, Mutex as StdMutex, MutexGuard, OnceLock};
    use tempfile::TempDir;

    struct CallgraphWaitWindowEnvGuard {
        _guard: MutexGuard<'static, ()>,
        previous: Option<OsString>,
    }

    impl Drop for CallgraphWaitWindowEnvGuard {
        fn drop(&mut self) {
            // SAFETY: serialized by the process-local guard held for this
            // helper's lifetime, and restored before the guard is released.
            unsafe {
                match &self.previous {
                    Some(value) => std::env::set_var("AFT_CALLGRAPH_BUILD_WAIT_MS", value),
                    None => std::env::remove_var("AFT_CALLGRAPH_BUILD_WAIT_MS"),
                }
            }
        }
    }

    fn force_async_callgraph_builds() -> CallgraphWaitWindowEnvGuard {
        static LOCK: OnceLock<StdMutex<()>> = OnceLock::new();
        let guard = LOCK
            .get_or_init(|| StdMutex::new(()))
            .lock()
            .unwrap_or_else(|error| error.into_inner());
        let previous = std::env::var_os("AFT_CALLGRAPH_BUILD_WAIT_MS");
        // SAFETY: serialized by LOCK above and restored by the returned guard.
        unsafe {
            std::env::set_var("AFT_CALLGRAPH_BUILD_WAIT_MS", "0");
        }
        CallgraphWaitWindowEnvGuard {
            _guard: guard,
            previous,
        }
    }

    fn cold_build_context() -> Arc<AppContext> {
        let project = TempDir::new().expect("project tempdir");
        let storage = TempDir::new().expect("storage tempdir");
        let source_dir = project.path().join("src");
        std::fs::create_dir_all(&source_dir).expect("source dir");
        std::fs::write(
            source_dir.join("lib.rs"),
            "pub fn caller() { callee(); }\npub fn callee() {}\n",
        )
        .expect("source file");

        Arc::new(AppContext::new(
            Box::new(TreeSitterProvider::new()),
            Config {
                project_root: Some(project.keep()),
                storage_dir: Some(storage.keep()),
                callgraph_chunk_size: 1,
                ..Config::default()
            },
        ))
    }

    fn empty_semantic_index_for_ctx(ctx: &AppContext) -> SemanticIndex {
        let project_root = ctx
            .config()
            .project_root
            .clone()
            .expect("test context has a project root");
        let files: Vec<PathBuf> = Vec::new();
        let mut embed = |_texts: Vec<String>| -> Result<Vec<Vec<f32>>, String> { Ok(Vec::new()) };
        SemanticIndex::build(&project_root, &files, &mut embed, 1)
            .expect("empty semantic index should build")
    }

    #[test]
    fn semantic_ready_event_resumes_deferred_callgraph_and_tier2() {
        let _env_guard = force_async_callgraph_builds();
        CALLGRAPH_COLD_BUILD_SPAWN_COUNT.store(0, Ordering::SeqCst);
        let ctx = cold_build_context();
        let (tx, rx) = crossbeam_channel::unbounded();
        *ctx.semantic_index_rx().lock() = Some(rx);
        ctx.schedule_semantic_cold_seed_gate_for_configure();

        assert!(matches!(
            ctx.callgraph_store_for_ops(),
            CallgraphStoreAccess::Building
        ));
        assert_eq!(CALLGRAPH_COLD_BUILD_SPAWN_COUNT.load(Ordering::SeqCst), 0);
        tx.send(SemanticIndexEvent::Ready(empty_semantic_index_for_ctx(
            &ctx,
        )))
        .expect("send ready event");

        crate::runtime_drain::drain_semantic_index_events(&ctx);

        assert!(
            !ctx.semantic_cold_seed_active(),
            "semantic Ready must clear the scheduled cold gate"
        );
        assert!(
            ctx.tier2_pull_demand_pending(),
            "semantic Ready must resume deferred Tier-2 work"
        );
        assert_eq!(
            CALLGRAPH_COLD_BUILD_SPAWN_COUNT.load(Ordering::SeqCst),
            1,
            "semantic Ready must resume the deferred callgraph warm"
        );
        let rx = ctx
            .callgraph_store_rx
            .lock()
            .as_ref()
            .cloned()
            .expect("ready resume should install an in-flight callgraph receiver");
        rx.recv_timeout(Duration::from_secs(30))
            .expect("background cold build should complete");
        *ctx.callgraph_store_rx.lock() = None;
    }

    #[test]
    fn semantic_gate_cleared_event_resumes_deferred_callgraph_and_tier2() {
        let _env_guard = force_async_callgraph_builds();
        CALLGRAPH_COLD_BUILD_SPAWN_COUNT.store(0, Ordering::SeqCst);
        let ctx = cold_build_context();
        ctx.schedule_semantic_cold_seed_gate_for_configure();

        assert!(matches!(
            ctx.callgraph_store_for_ops(),
            CallgraphStoreAccess::Building
        ));
        assert_eq!(CALLGRAPH_COLD_BUILD_SPAWN_COUNT.load(Ordering::SeqCst), 0);
        ctx.resume_deferred_work_after_semantic_cold_seed_gate_cleared();

        assert!(
            !ctx.semantic_cold_seed_active(),
            "cached-load or retry-wait clear must reopen the semantic cold gate"
        );
        assert!(
            ctx.tier2_pull_demand_pending(),
            "cached-load or retry-wait clear must resume deferred Tier-2 work"
        );
        assert_eq!(
            CALLGRAPH_COLD_BUILD_SPAWN_COUNT.load(Ordering::SeqCst),
            1,
            "cached-load or retry-wait clear must resume deferred callgraph warm"
        );
        let rx = ctx
            .callgraph_store_rx
            .lock()
            .as_ref()
            .cloned()
            .expect("gate-clear resume should install an in-flight callgraph receiver");
        rx.recv_timeout(Duration::from_secs(30))
            .expect("background cold build should complete");
        *ctx.callgraph_store_rx.lock() = None;
    }

    #[test]
    fn semantic_cold_seed_gate_defers_callgraph_cold_spawn_until_resume() {
        let _env_guard = force_async_callgraph_builds();
        CALLGRAPH_COLD_BUILD_SPAWN_COUNT.store(0, Ordering::SeqCst);
        let ctx = cold_build_context();

        ctx.set_semantic_cold_seed_active_for_test(true);
        assert!(
            matches!(
                ctx.callgraph_store_for_ops(),
                CallgraphStoreAccess::Building
            ),
            "callgraph ops should degrade as building while the semantic cold gate is active"
        );
        assert_eq!(
            CALLGRAPH_COLD_BUILD_SPAWN_COUNT.load(Ordering::SeqCst),
            0,
            "semantic cold gate must not spawn a competing callgraph cold build"
        );
        assert!(ctx.semantic_callgraph_warm_deferred_for_test());

        ctx.clear_semantic_cold_seed_gate_and_resume_deferred_work();
        assert_eq!(
            CALLGRAPH_COLD_BUILD_SPAWN_COUNT.load(Ordering::SeqCst),
            1,
            "clearing the semantic cold gate should resume the deferred callgraph warm"
        );

        let rx = ctx
            .callgraph_store_rx
            .lock()
            .as_ref()
            .cloned()
            .expect("deferred warm should install an in-flight receiver");
        rx.recv_timeout(Duration::from_secs(30))
            .expect("background cold build should complete");
        *ctx.callgraph_store_rx.lock() = None;
    }

    #[test]
    fn semantic_cold_seed_gate_clear_requests_tier2_pull() {
        let ctx = AppContext::new(Box::new(TreeSitterProvider::new()), Config::default());
        ctx.schedule_semantic_cold_seed_gate_for_configure();

        ctx.resume_deferred_work_after_semantic_cold_seed_gate_cleared();

        assert!(
            !ctx.semantic_cold_seed_active(),
            "retry-wait or cached-load events must reopen the semantic cold gate"
        );
        assert!(
            ctx.tier2_pull_demand_pending(),
            "clearing the semantic cold gate should kick a Tier-2 pull refresh"
        );
    }

    #[test]
    fn semantic_failed_event_clears_scheduled_gate_and_requests_tier2_pull() {
        let ctx = AppContext::new(Box::new(TreeSitterProvider::new()), Config::default());
        let (tx, rx) = crossbeam_channel::unbounded();
        *ctx.semantic_index_rx().lock() = Some(rx);
        ctx.schedule_semantic_cold_seed_gate_for_configure();
        tx.send(SemanticIndexEvent::Failed(
            "embedding backend failed".to_string(),
        ))
        .expect("send failed event");

        crate::runtime_drain::drain_semantic_index_events(&ctx);

        assert!(
            !ctx.semantic_cold_seed_active(),
            "semantic Failed must clear the scheduled cold gate"
        );
        assert!(
            ctx.tier2_pull_demand_pending(),
            "semantic Failed must resume deferred Tier-2 work"
        );
    }

    #[test]
    fn semantic_disconnect_clears_scheduled_gate_and_requests_tier2_pull() {
        let ctx = AppContext::new(Box::new(TreeSitterProvider::new()), Config::default());
        let (tx, rx) = crossbeam_channel::unbounded::<SemanticIndexEvent>();
        *ctx.semantic_index_rx().lock() = Some(rx);
        ctx.schedule_semantic_cold_seed_gate_for_configure();
        drop(tx);

        crate::runtime_drain::drain_semantic_index_events(&ctx);

        assert!(
            !ctx.semantic_cold_seed_active(),
            "semantic worker disconnect must clear the scheduled cold gate"
        );
        assert!(
            ctx.tier2_pull_demand_pending(),
            "semantic worker disconnect must resume deferred Tier-2 work"
        );
    }

    #[test]
    fn semantic_cold_seed_gate_is_per_context_for_tier2_scheduler() {
        let ctx_a = AppContext::new(Box::new(TreeSitterProvider::new()), Config::default());
        let ctx_b = AppContext::new(Box::new(TreeSitterProvider::new()), Config::default());
        let base = Instant::now();
        ctx_a.reset_tier2_refresh_scheduler_at(base);
        ctx_b.reset_tier2_refresh_scheduler_at(base);
        ctx_a.set_semantic_cold_seed_active_for_test(true);

        assert_eq!(
            ctx_a.tick_tier2_refresh_scheduler_at(
                base + crate::inspect::tier2_scheduler::TIER2_REFRESH_COLD_CACHE_DELAY,
                0,
            ),
            None,
            "root A should defer Tier-2 while its semantic cold seed is active"
        );
        assert_eq!(
            ctx_b.tick_tier2_refresh_scheduler_at(
                base + crate::inspect::tier2_scheduler::TIER2_REFRESH_COLD_CACHE_DELAY,
                0,
            ),
            Some(Tier2TriggerReason::ConfigureWarm),
            "root B must not inherit root A's semantic cold gate"
        );
    }

    #[test]
    fn concurrent_cold_callgraph_store_for_ops_spawns_one_build() {
        let _env_guard = force_async_callgraph_builds();
        CALLGRAPH_COLD_BUILD_SPAWN_COUNT.store(0, Ordering::SeqCst);

        let project = TempDir::new().expect("project tempdir");
        let storage = TempDir::new().expect("storage tempdir");
        let source_dir = project.path().join("src");
        std::fs::create_dir_all(&source_dir).expect("source dir");
        std::fs::write(
            source_dir.join("lib.rs"),
            "pub fn caller() { callee(); }\npub fn callee() {}\n",
        )
        .expect("source file");

        let ctx = Arc::new(AppContext::new(
            Box::new(TreeSitterProvider::new()),
            Config {
                project_root: Some(project.path().to_path_buf()),
                storage_dir: Some(storage.path().to_path_buf()),
                callgraph_chunk_size: 1,
                ..Config::default()
            },
        ));

        let barrier = Arc::new(Barrier::new(3));
        let handles = (0..2)
            .map(|_| {
                let ctx = Arc::clone(&ctx);
                let barrier = Arc::clone(&barrier);
                std::thread::spawn(move || {
                    barrier.wait();
                    matches!(
                        ctx.callgraph_store_for_ops(),
                        CallgraphStoreAccess::Building | CallgraphStoreAccess::Ready(_)
                    )
                })
            })
            .collect::<Vec<_>>();

        barrier.wait();
        for handle in handles {
            assert!(
                handle.join().expect("callgraph caller thread"),
                "cold callgraph ops should report Building or observe the installed store"
            );
        }

        assert_eq!(
            CALLGRAPH_COLD_BUILD_SPAWN_COUNT.load(Ordering::SeqCst),
            1,
            "concurrent cold callers must share one background build"
        );

        let rx = ctx
            .callgraph_store_rx
            .lock()
            .as_ref()
            .cloned()
            .expect("in-flight receiver installed before spawn");
        rx.recv_timeout(Duration::from_secs(30))
            .expect("background cold build should complete");
        *ctx.callgraph_store_rx.lock() = None;
    }
}

#[cfg(test)]
mod status_emitter_tests {
    use super::*;
    use crate::parser::TreeSitterProvider;

    fn ctx_with_frame_rx() -> (AppContext, mpsc::Receiver<PushFrame>) {
        let ctx = AppContext::new(Box::new(TreeSitterProvider::new()), Config::default());
        let (tx, rx) = mpsc::channel();
        ctx.set_progress_sender(Some(Arc::new(Box::new(move |frame| {
            let _ = tx.send(frame);
        }))));
        (ctx, rx)
    }

    #[test]
    fn status_emitter_signal_triggers_push() {
        let (ctx, rx) = ctx_with_frame_rx();
        ctx.status_emitter().signal(ctx.build_status_snapshot());
        let frame = rx
            .recv_timeout(Duration::from_millis(STATUS_DEBOUNCE_MS + 500))
            .expect("status_changed push");
        assert!(matches!(frame, PushFrame::StatusChanged(_)));
    }

    #[test]
    fn status_emitter_debounces_burst() {
        let (ctx, rx) = ctx_with_frame_rx();
        for _ in 0..10 {
            ctx.status_emitter().signal(ctx.build_status_snapshot());
        }
        let frame = rx
            .recv_timeout(Duration::from_millis(STATUS_DEBOUNCE_MS + 500))
            .expect("status_changed push");
        assert!(matches!(frame, PushFrame::StatusChanged(_)));
        assert!(rx.try_recv().is_err());
    }

    #[test]
    fn status_emitter_separate_windows_separate_pushes() {
        let (ctx, rx) = ctx_with_frame_rx();
        ctx.status_emitter().signal(ctx.build_status_snapshot());
        rx.recv_timeout(Duration::from_millis(STATUS_DEBOUNCE_MS + 500))
            .expect("first push");
        ctx.status_emitter().signal(ctx.build_status_snapshot());
        rx.recv_timeout(Duration::from_millis(STATUS_DEBOUNCE_MS + 500))
            .expect("second push");
    }

    #[test]
    fn status_emitter_no_signal_no_push() {
        let (_ctx, rx) = ctx_with_frame_rx();
        assert!(rx
            .recv_timeout(Duration::from_millis(STATUS_DEBOUNCE_MS + 100))
            .is_err());
    }

    #[test]
    fn status_emitter_shutdown_cleanly_exits_debounce_thread() {
        let (ctx, rx) = ctx_with_frame_rx();
        drop(ctx);
        assert!(rx.recv_timeout(Duration::from_millis(50)).is_err());
    }

    #[test]
    fn progress_sender_slot_is_per_context_for_shared_app() {
        let app = App::default_shared();
        let ctx_a = AppContext::from_app(Arc::clone(&app), Config::default());
        let ctx_b = AppContext::from_app(app, Config::default());
        let (tx_a, rx_a) = mpsc::channel();
        let (tx_b, rx_b) = mpsc::channel();

        ctx_a.set_progress_sender(Some(Arc::new(Box::new(move |frame| {
            let _ = tx_a.send(frame);
        }))));
        ctx_b.set_progress_sender(Some(Arc::new(Box::new(move |frame| {
            let _ = tx_b.send(frame);
        }))));

        ctx_a.emit_progress(ProgressFrame {
            frame_type: "progress",
            request_id: "ctx-a".to_string(),
            kind: crate::protocol::ProgressKind::Stdout,
            chunk: "a".to_string(),
        });
        ctx_b.emit_progress(ProgressFrame {
            frame_type: "progress",
            request_id: "ctx-b".to_string(),
            kind: crate::protocol::ProgressKind::Stdout,
            chunk: "b".to_string(),
        });

        match rx_a
            .recv_timeout(Duration::from_millis(50))
            .expect("ctx A progress frame")
        {
            PushFrame::Progress(frame) => assert_eq!(frame.request_id, "ctx-a"),
            other => panic!("unexpected frame for ctx A: {other:?}"),
        }
        assert!(rx_a.try_recv().is_err());

        match rx_b
            .recv_timeout(Duration::from_millis(50))
            .expect("ctx B progress frame")
        {
            PushFrame::Progress(frame) => assert_eq!(frame.request_id, "ctx-b"),
            other => panic!("unexpected frame for ctx B: {other:?}"),
        }
        assert!(rx_b.try_recv().is_err());
    }
}

#[cfg(test)]
mod status_bar_tests {
    use super::*;
    use crate::parser::TreeSitterProvider;

    fn ctx() -> AppContext {
        AppContext::new(Box::new(TreeSitterProvider::new()), Config::default())
    }

    #[test]
    fn status_bar_counts_none_until_tier2_populated() {
        let ctx = ctx();
        // No scan has run yet — never surface a bar claiming "0 dead code".
        assert!(ctx.status_bar_counts().is_none());

        ctx.update_status_bar_tier2(Some(5), Some(3), Some(7), Some(2), false);
        let counts = ctx.status_bar_counts().expect("populated");
        assert_eq!(counts.dead_code, 5);
        assert_eq!(counts.unused_exports, 3);
        assert_eq!(counts.duplicates, 7);
        assert_eq!(counts.todos, 2);
        assert!(!counts.tier2_stale);
        // Errors/warnings are read live from an empty LSP store → 0.
        assert_eq!(counts.errors, 0);
        assert_eq!(counts.warnings, 0);
    }

    #[test]
    fn partial_tier2_does_not_fabricate_zeros() {
        let ctx = ctx();
        // Only dead_code has completed (the slow first serial category); the
        // other two are still in flight. The bar must stay suppressed rather
        // than render `D5 U0 C0` with fabricated zeros (#1).
        ctx.update_status_bar_tier2(Some(5), None, None, None, true);
        assert!(
            ctx.status_bar_counts().is_none(),
            "bar must not surface until all three Tier-2 categories are real"
        );

        // Second category completes — still incomplete, still suppressed.
        ctx.update_status_bar_tier2(None, Some(3), None, None, true);
        assert!(ctx.status_bar_counts().is_none());

        // Final category completes → bar surfaces with all real counts, and
        // none of them were ever fabricated.
        ctx.update_status_bar_tier2(None, None, Some(7), None, false);
        let counts = ctx.status_bar_counts().expect("all three real now");
        assert_eq!(counts.dead_code, 5);
        assert_eq!(counts.unused_exports, 3);
        assert_eq!(counts.duplicates, 7);
    }

    #[test]
    fn update_with_none_todos_preserves_last_known_todos() {
        let ctx = ctx();
        ctx.update_status_bar_tier2(Some(1), Some(1), Some(1), Some(9), false);
        // A background-scan refresh passes todos=None → todo count preserved.
        ctx.update_status_bar_tier2(Some(2), Some(2), Some(2), None, false);
        let counts = ctx.status_bar_counts().expect("populated");
        assert_eq!(counts.todos, 9);
        assert_eq!(counts.dead_code, 2);
    }

    #[test]
    fn update_with_none_count_preserves_last_known_count() {
        let ctx = ctx();
        ctx.update_status_bar_tier2(Some(10), Some(20), Some(30), None, false);
        // A refresh that only recomputed dead_code preserves the other two
        // real counts rather than overwriting them with a fabricated 0.
        ctx.update_status_bar_tier2(Some(11), None, None, None, false);
        let counts = ctx.status_bar_counts().expect("populated");
        assert_eq!(counts.dead_code, 11);
        assert_eq!(counts.unused_exports, 20);
        assert_eq!(counts.duplicates, 30);
    }

    #[test]
    fn mark_stale_sets_flag_only_after_populate() {
        let ctx = ctx();
        // No-op before first populate.
        ctx.mark_status_bar_tier2_stale();
        assert!(ctx.status_bar_counts().is_none());

        ctx.update_status_bar_tier2(Some(4), Some(0), Some(0), Some(0), false);
        ctx.mark_status_bar_tier2_stale();
        assert!(ctx.status_bar_counts().expect("populated").tier2_stale);

        // A completed scan clears stale.
        ctx.update_status_bar_tier2(Some(4), Some(0), Some(0), None, false);
        assert!(!ctx.status_bar_counts().expect("populated").tier2_stale);
    }

    // End-to-end wiring: a diagnostic for a file inflates the status-bar `E`
    // count (read live from the warm LSP set); clearing that file's diagnostics
    // (the deleted-file path) drops it back. This is the AppContext glue between
    // the watcher-drain clear and the agent-visible bar.
    #[test]
    fn clearing_diagnostics_for_deleted_file_drops_status_bar_errors() {
        use crate::lsp::diagnostics::{DiagnosticSeverity, StoredDiagnostic};
        use crate::lsp::registry::ServerKind;
        use crate::lsp::roots::ServerKey;

        let ctx = ctx();
        ctx.update_status_bar_tier2(Some(0), Some(0), Some(0), Some(0), false); // populate so the bar surfaces

        let file = std::path::PathBuf::from("/proj/gone.ts");
        {
            let mut lsp = ctx.lsp();
            lsp.diagnostics_store_mut_for_test().publish(
                ServerKey {
                    kind: ServerKind::TypeScript,
                    root: std::path::PathBuf::from("/proj"),
                },
                file.clone(),
                vec![StoredDiagnostic {
                    file: file.clone(),
                    line: 1,
                    column: 1,
                    end_line: 1,
                    end_column: 2,
                    severity: DiagnosticSeverity::Error,
                    message: "boom".into(),
                    code: None,
                    source: None,
                }],
            );
        }

        // Bar reflects the live warm-set error.
        assert_eq!(ctx.status_bar_counts().expect("populated").errors, 1);

        // Clearing the (now-deleted) file's diagnostics drops the count.
        let removed = ctx.lsp_clear_diagnostics_for_file(&file);
        assert!(removed);
        assert_eq!(ctx.status_bar_counts().expect("populated").errors, 0);
    }

    #[test]
    fn status_bar_filtered_counts_ignore_environmental_flap() {
        use crate::lsp::diagnostics::{DiagnosticSeverity, StoredDiagnostic};
        use crate::lsp::registry::ServerKind;
        use crate::lsp::roots::ServerKey;

        let ctx = ctx();
        let root = if cfg!(windows) {
            std::path::PathBuf::from(r"C:\proj")
        } else {
            std::path::PathBuf::from("/proj")
        };
        ctx.set_canonical_cache_root(root.clone());
        ctx.update_status_bar_tier2(Some(0), Some(0), Some(0), Some(0), false);

        let file = root.join("aft.jsonc");
        let key = ServerKey {
            kind: ServerKind::TypeScript,
            root: root.clone(),
        };
        let env = StoredDiagnostic {
            file: file.clone(),
            line: 1,
            column: 1,
            end_line: 1,
            end_column: 2,
            severity: DiagnosticSeverity::Error,
            message: "Failed to load schema from https://example.com/schema.json".into(),
            code: None,
            source: Some("json".into()),
        };

        assert_eq!(ctx.status_bar_counts().expect("populated").errors, 0);

        {
            let mut lsp = ctx.lsp();
            lsp.diagnostics_store_mut_for_test()
                .publish(key.clone(), file.clone(), vec![env]);
        }
        assert_eq!(
            ctx.status_bar_counts().expect("populated").errors,
            0,
            "environmental publish must not change status-bar E"
        );

        {
            let mut lsp = ctx.lsp();
            lsp.diagnostics_store_mut_for_test()
                .publish(key, file, vec![]);
        }
        assert_eq!(
            ctx.status_bar_counts().expect("populated").errors,
            0,
            "environmental clear must not change status-bar E"
        );
    }
}

#[cfg(test)]
mod harness_path_tests {
    use super::*;
    use crate::harness::Harness;
    use crate::parser::TreeSitterProvider;

    fn ctx_with_storage_and_harness(storage_dir: PathBuf, harness: Harness) -> AppContext {
        let ctx = AppContext::new(Box::new(TreeSitterProvider::new()), Config::default());
        ctx.update_config(|config| {
            config.storage_dir = Some(storage_dir);
        });
        ctx.set_harness(harness);
        ctx
    }

    #[test]
    fn harness_dir_resolves_correctly() {
        let storage = PathBuf::from("/tmp/cortexkit/aft");
        let ctx = ctx_with_storage_and_harness(storage.clone(), Harness::Pi);

        assert_eq!(ctx.harness_dir(), storage.join("pi"));
    }

    #[test]
    fn bash_tasks_dir_uses_hash_session() {
        let storage = PathBuf::from("/tmp/cortexkit/aft");
        let ctx = ctx_with_storage_and_harness(storage.clone(), Harness::Opencode);

        assert_eq!(
            ctx.bash_tasks_dir("ses_abc"),
            storage
                .join("opencode")
                .join("bash-tasks")
                .join(hash_session("ses_abc"))
        );
    }

    #[test]
    fn backups_dir_includes_path_hash() {
        let storage = PathBuf::from("/tmp/cortexkit/aft");
        let ctx = ctx_with_storage_and_harness(storage.clone(), Harness::Pi);

        assert_eq!(
            ctx.backups_dir("ses_abc", "pathhash"),
            storage
                .join("pi")
                .join("backups")
                .join(hash_session("ses_abc"))
                .join("pathhash")
        );
    }

    #[test]
    fn filters_dir_under_harness() {
        let storage = PathBuf::from("/tmp/cortexkit/aft");
        let ctx = ctx_with_storage_and_harness(storage.clone(), Harness::Opencode);

        assert_eq!(ctx.filters_dir(), storage.join("opencode").join("filters"));
    }

    #[test]
    fn trust_file_is_host_global() {
        let storage = PathBuf::from("/tmp/cortexkit/aft");
        let ctx = ctx_with_storage_and_harness(storage.clone(), Harness::Pi);

        assert_eq!(
            ctx.trust_file(),
            storage.join("trusted-filter-projects.json")
        );
    }

    #[test]
    fn same_session_different_harness_resolve_different_paths() {
        let storage = PathBuf::from("/tmp/cortexkit/aft");
        let opencode = ctx_with_storage_and_harness(storage.clone(), Harness::Opencode);
        let pi = ctx_with_storage_and_harness(storage, Harness::Pi);

        assert_ne!(
            opencode.bash_tasks_dir("ses_same"),
            pi.bash_tasks_dir("ses_same")
        );
    }
}

#[cfg(test)]
mod gitignore_tests {
    use super::*;
    use std::fs;
    use std::path::Path;
    use tempfile::TempDir;

    fn make_ctx_with_root(root: &Path) -> AppContext {
        let provider = Box::new(crate::parser::TreeSitterProvider::new());
        let config = Config {
            project_root: Some(root.to_path_buf()),
            ..Config::default()
        };
        AppContext::new(provider, config)
    }

    /// Helper: returns true when the matcher would skip `path` (as if it
    /// arrived via a watcher event for this project root). Canonicalizes
    /// the query path so symlink prefixes (e.g. macOS `/var` → `/private/var`)
    /// don't trip the `ignore` crate's "path is expected to be under the
    /// root" panic — production code does the same guard via
    /// `path.starts_with(matcher.path())` in `drain_watcher_events`.
    fn is_ignored(ctx: &AppContext, path: &Path) -> bool {
        let Some(matcher) = ctx.gitignore() else {
            return false;
        };
        let canonical = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
        if !canonical.starts_with(matcher.path()) {
            return false;
        }
        let is_dir = canonical.is_dir();
        matcher
            .matched_path_or_any_parents(&canonical, is_dir)
            .is_ignore()
    }

    /// Run `f` with global git-ignore discovery neutralized.
    ///
    /// `rebuild_gitignore` loads git's global excludes (the `ignore` crate
    /// resolves `$XDG_CONFIG_HOME/git/ignore`, falling back to
    /// `$HOME/.config/git/ignore`). A developer machine commonly has that file,
    /// so a "no project ignore → None" assertion is only deterministic when
    /// global discovery is pointed at an empty directory. Pointing
    /// `XDG_CONFIG_HOME` at a fresh tempdir does that without touching `HOME`
    /// (so it can't race the `HOME`-mutating configure tests). Serialized by a
    /// process-local mutex; env is restored before the closure result is used.
    fn with_neutralized_global_gitignore<R>(f: impl FnOnce() -> R) -> R {
        use std::sync::{Mutex, OnceLock};
        static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
        let _guard = LOCK
            .get_or_init(|| Mutex::new(()))
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let tmp = TempDir::new().unwrap();
        let prev = std::env::var_os("XDG_CONFIG_HOME");
        // SAFETY: serialized by LOCK above; restored immediately after `f`.
        unsafe {
            std::env::set_var("XDG_CONFIG_HOME", tmp.path());
        }
        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f));
        unsafe {
            match prev {
                Some(v) => std::env::set_var("XDG_CONFIG_HOME", v),
                None => std::env::remove_var("XDG_CONFIG_HOME"),
            }
        }
        match result {
            Ok(r) => r,
            Err(p) => std::panic::resume_unwind(p),
        }
    }

    #[test]
    fn rebuild_gitignore_returns_none_without_project_root() {
        let provider = Box::new(crate::parser::TreeSitterProvider::new());
        let ctx = AppContext::new(provider, Config::default());
        with_neutralized_global_gitignore(|| ctx.rebuild_gitignore());
        assert!(ctx.gitignore().is_none());
    }

    #[test]
    fn rebuild_gitignore_returns_none_for_project_with_no_gitignore() {
        let tmp = TempDir::new().unwrap();
        let ctx = make_ctx_with_root(tmp.path());
        with_neutralized_global_gitignore(|| ctx.rebuild_gitignore());
        assert!(ctx.gitignore().is_none());
    }

    #[test]
    fn matcher_filters_files_in_ignored_dist_dir() {
        let tmp = TempDir::new().unwrap();
        fs::write(tmp.path().join(".gitignore"), "dist/\nbuild/\n").unwrap();
        fs::create_dir_all(tmp.path().join("dist")).unwrap();
        fs::create_dir_all(tmp.path().join("src")).unwrap();
        let dist_file = tmp.path().join("dist").join("bundle.js");
        let src_file = tmp.path().join("src").join("app.ts");
        fs::write(&dist_file, "x").unwrap();
        fs::write(&src_file, "y").unwrap();

        let ctx = make_ctx_with_root(tmp.path());
        ctx.rebuild_gitignore();

        assert!(ctx.gitignore().is_some());
        assert!(
            is_ignored(&ctx, &dist_file),
            "dist/bundle.js should be ignored"
        );
        assert!(
            !is_ignored(&ctx, &src_file),
            "src/app.ts should NOT be ignored"
        );
    }

    #[test]
    fn matcher_handles_node_modules_and_target() {
        let tmp = TempDir::new().unwrap();
        fs::write(tmp.path().join(".gitignore"), "node_modules/\ntarget/\n").unwrap();
        fs::create_dir_all(tmp.path().join("node_modules/foo")).unwrap();
        fs::create_dir_all(tmp.path().join("target/debug")).unwrap();
        let nm_file = tmp.path().join("node_modules/foo/index.js");
        let target_file = tmp.path().join("target/debug/aft");
        fs::write(&nm_file, "x").unwrap();
        fs::write(&target_file, "x").unwrap();

        let ctx = make_ctx_with_root(tmp.path());
        ctx.rebuild_gitignore();

        assert!(is_ignored(&ctx, &nm_file));
        assert!(is_ignored(&ctx, &target_file));
    }

    #[test]
    fn matcher_honors_negation_pattern() {
        // .gitignore: ignore all *.log files EXCEPT important.log
        let tmp = TempDir::new().unwrap();
        fs::write(tmp.path().join(".gitignore"), "*.log\n!important.log\n").unwrap();
        let random_log = tmp.path().join("random.log");
        let important_log = tmp.path().join("important.log");
        fs::write(&random_log, "x").unwrap();
        fs::write(&important_log, "y").unwrap();

        let ctx = make_ctx_with_root(tmp.path());
        ctx.rebuild_gitignore();

        assert!(is_ignored(&ctx, &random_log));
        assert!(
            !is_ignored(&ctx, &important_log),
            "negation pattern should un-ignore important.log"
        );
    }

    #[test]
    fn rebuild_picks_up_gitignore_changes() {
        let tmp = TempDir::new().unwrap();
        let ignore_path = tmp.path().join(".gitignore");
        fs::write(&ignore_path, "foo.txt\n").unwrap();
        let foo = tmp.path().join("foo.txt");
        let bar = tmp.path().join("bar.txt");
        fs::write(&foo, "").unwrap();
        fs::write(&bar, "").unwrap();

        let ctx = make_ctx_with_root(tmp.path());
        ctx.rebuild_gitignore();
        assert!(is_ignored(&ctx, &foo));
        assert!(!is_ignored(&ctx, &bar));

        // Now flip the rules: ignore bar.txt instead of foo.txt
        fs::write(&ignore_path, "bar.txt\n").unwrap();
        ctx.rebuild_gitignore();
        assert!(!is_ignored(&ctx, &foo));
        assert!(is_ignored(&ctx, &bar));
    }

    #[test]
    fn gitignore_loads_info_exclude_when_present() {
        let tmp = TempDir::new().unwrap();
        let info_dir = tmp.path().join(".git/info");
        fs::create_dir_all(&info_dir).unwrap();
        fs::write(info_dir.join("exclude"), "secrets.txt\n").unwrap();
        let secrets = tmp.path().join("secrets.txt");
        let public = tmp.path().join("public.txt");
        fs::write(&secrets, "token").unwrap();
        fs::write(&public, "ok").unwrap();

        let ctx = make_ctx_with_root(tmp.path());
        ctx.rebuild_gitignore();

        assert!(is_ignored(&ctx, &secrets));
        assert!(!is_ignored(&ctx, &public));
    }

    #[test]
    fn matcher_picks_up_nested_gitignore() {
        let tmp = TempDir::new().unwrap();
        // Root .gitignore is intentionally empty — only the nested one ignores
        fs::write(tmp.path().join(".gitignore"), "").unwrap();
        let sub = tmp.path().join("packages/foo");
        fs::create_dir_all(&sub).unwrap();
        fs::write(sub.join(".gitignore"), "generated/\n").unwrap();
        let generated_file = sub.join("generated").join("out.js");
        fs::create_dir_all(generated_file.parent().unwrap()).unwrap();
        fs::write(&generated_file, "x").unwrap();

        let ctx = make_ctx_with_root(tmp.path());
        ctx.rebuild_gitignore();

        assert!(
            is_ignored(&ctx, &generated_file),
            "nested gitignore in packages/foo/.gitignore should ignore generated/"
        );
    }
}