aft-base 0.67.1

Shared foundation for Agent Foundational Toolkit
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
//! Pure aft.jsonc tier resolver.
//!
//! This module mirrors the TypeScript config pipeline for the core-consumed
//! slice: raw JSONC tiers -> strict raw schema -> user/project trust merge ->
//! flat [`Config`]. It intentionally performs no IO; callers supply the already
//! read config documents.

use std::collections::{BTreeMap, HashMap, HashSet};
use std::path::PathBuf;

use serde::de;
use serde::{Deserialize, Deserializer};
use serde_json::{Map, Value};

use crate::config::{
    expand_index_root_path, normalize_git_co_author, BackupConfig, Config, GhShimConfig, GitConfig,
    GithubConfig, IdleConfig, IndexConfig, IndexKind, IndexRootConfig, IndexesConfig,
    InspectCategories, InspectConfig, RemoteExecConfig, RerankBackendKind, RerankConfig,
    SandboxConfig, SearchConfig, SemanticBackend, SemanticBackendConfig, UserServerDef,
    DEFAULT_BASH_WATCH_SYNC_MAX_MS, DEFAULT_BASH_WORKER_WAIT_MAX_MS, DEFAULT_IDLE_ROOT_TTL_MINUTES,
    DEFAULT_INSPECT_DIAGNOSTICS_TIMEOUT_MS, MAX_BASH_WATCH_SYNC_MAX_MS, MAX_IDLE_ROOT_TTL_MINUTES,
    MAX_INSPECT_DIAGNOSTICS_TIMEOUT_MS, MAX_SEMANTIC_QUERY_TIMEOUT_MS, MIN_BASH_WATCH_SYNC_MAX_MS,
    MIN_BASH_WORKER_WAIT_MAX_MS, MIN_IDLE_ROOT_TTL_MINUTES, MIN_INSPECT_DIAGNOSTICS_TIMEOUT_MS,
    MIN_SEMANTIC_QUERY_TIMEOUT_MS,
};
use crate::feature_config;
use crate::harness::Harness;
use crate::jsonc::strip_jsonc;

pub mod schema;

const FOREGROUND_WAIT_WINDOW_DEFAULT_MS: u64 = 15_000;
const FOREGROUND_WAIT_WINDOW_MIN_MS: u64 = 5_000;

// Semantic budget clamps — restored from the deleted configure-time
// parse_semantic_config so the tier-resolved Config matches the historical
// clamping (zero-behavior-change relocation, not a new policy).
const MAX_SEMANTIC_TIMEOUT_MS: u64 = 120_000;
const MAX_SEMANTIC_BATCH_SIZE: usize = 1_024;

const USER_ONLY_REASON: &str =
    "security: this setting only honors user-level config and project values are ignored";
const SEMANTIC_SECRET_REASON: &str =
    "security: semantic backend credentials and endpoints must come from user-level config";
const PROTECTED_TOOL_REASON: &str =
    "security: a project config cannot disable aft_safety or a host tool slot (read, write, edit, apply_patch, grep, glob, bash)";
const LSP_USER_ONLY_REASON: &str =
    "security: LSP executable-origin and diagnostic-suppression settings must come from user-level config";
const REMOTE_EXEC_PROJECT_REASON: &str =
    "security: a project config may only turn remote_exec off; enabling remote runs and choosing their runner must come from user-level config";
const RERANK_PROJECT_REASON: &str =
    "security: a project config may only turn search.rerank off; every other rerank setting must come from user-level config";

/// One raw config document supplied by the host plugin.
///
/// `tier` is trusted process metadata stamped by the caller. The document body is
/// never allowed to relabel itself.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConfigTier {
    pub tier: String,
    pub source: String,
    pub doc: String,
}

/// A project-tier key that was intentionally ignored at the user/project trust boundary.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DroppedKey {
    pub key: String,
    pub tier: String,
    pub reason: String,
}

/// A non-fatal config issue reported back to the caller during configuration.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConfigWarning {
    pub code: &'static str,
    pub key: &'static str,
    pub tier: String,
    pub value: String,
    pub message: String,
}

/// Diagnostics produced while resetting an existing runtime config.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ResolveDiagnostics {
    pub dropped: Vec<DroppedKey>,
    pub warnings: Vec<ConfigWarning>,
    /// Rejection diagnostics. When non-empty the candidate was rejected as a
    /// whole and the base config was left untouched.
    pub errors: Vec<String>,
}

/// Fully resolved core config plus trust-boundary diagnostics.
#[derive(Debug, Clone)]
pub struct ResolveResult {
    pub config: Config,
    pub dropped: Vec<DroppedKey>,
    pub warnings: Vec<ConfigWarning>,
    /// Rejection diagnostics: a resolved configuration that is missing its
    /// registration list or an index switch (`invalid_resolved_config:...`).
    /// When non-empty `config` must not be used: the whole candidate load is
    /// rejected rather than continuing with defaults.
    pub errors: Vec<String>,
}

/// Strict raw shape for aft.jsonc. This mirrors the TypeScript Zod schema, not
/// the flat runtime [`Config`]. Privileged process-state fields are deliberately
/// absent and therefore rejected by `deny_unknown_fields`.
#[derive(Debug, Clone, Default, Deserialize, PartialEq, schemars::JsonSchema)]
#[serde(default, deny_unknown_fields)]
#[schemars(
    description = "Configuration schema for the @cortexkit/aft-opencode and @cortexkit/aft-pi plugins. Place as aft.jsonc in ~/.config/opencode/, <project>/.opencode/, ~/.pi/agent/, or <project>/.pi/."
)]
pub struct RawAftConfig {
    #[schemars(
        description = "Machine-local resource profile, user config base only. lean uses less memory and can build more slowly: it uses a smaller shared block cache, four call-graph resolver threads on Linux and macOS, and immediate freed-memory return on Linux. Windows keeps all CPUs. balanced keeps the previous limits. When unset, total physical RAM selects lean below 8 GiB, otherwise balanced; unreadable RAM selects balanced. Changes apply to subsequent builds and shared block cache sizing without a restart. Other limits and meaning-search settings stay unchanged."
    )]
    pub memory: Option<crate::memory_profile::MemoryMode>,
    #[schemars(
        description = "Process-wide file flush policy from the user config base only. Project values and all harness overrides have no effect."
    )]
    pub durability: Option<RawDurability>,
    #[schemars(
        description = "Storage-wide settings from the user config base only. Project values and every harness override are ignored."
    )]
    pub storage: Option<RawStorage>,
    #[serde(rename = "$schema")]
    pub schema: Option<String>,
    #[schemars(
        description = "Select the edit/read surface. Hashline mode renders tagged reads and changes edit arguments to exactly { patch }."
    )]
    pub edit_mode: Option<RawEditMode>,
    #[schemars(
        description = "Auto-format files after edits with the language's configured formatter. Default false: formatting can reflow the file under the agent and stale the next edit's context."
    )]
    pub format_on_edit: Option<bool>,
    #[schemars(
        description = "Let read, aft_outline and aft_zoom take a `ref` argument that reads a file as it is at a git revision (branch, tag, SHA, or forms like HEAD~2) from the repository's object store, without touching the working tree. Default false: the argument is not offered and a call that passes it is refused."
    )]
    pub revision_reads: Option<bool>,
    #[serde(deserialize_with = "deserialize_opt_timeout_secs")]
    #[schemars(range(min = 1, max = 600))]
    #[schemars(
        description = "Maximum seconds an external formatter is allowed to run before AFT kills it and reports `format_skipped_reason: \"timeout\"`. Raise for slow formatters in large projects."
    )]
    pub formatter_timeout_secs: Option<u32>,
    #[serde(deserialize_with = "deserialize_opt_timeout_secs")]
    #[schemars(range(min = 1, max = 600))]
    #[schemars(
        description = "Maximum time in seconds for an external type checker to run. The default is 30 seconds."
    )]
    pub type_checker_timeout_secs: Option<u32>,
    #[schemars(
        description = "Auto-validate after edits: 'syntax' (tree-sitter parse check) or 'full' (also runs type checker)."
    )]
    pub validate_on_edit: Option<RawValidateOnEdit>,
    #[schemars(
        description = "Per-language formatter overrides keyed by language (e.g. 'typescript', 'python', 'rust', 'go')."
    )]
    pub formatter: Option<HashMap<String, RawFormatter>>,
    #[schemars(
        description = "Per-language type checker overrides keyed by language (e.g. 'typescript', 'python', 'rust', 'go')."
    )]
    pub checker: Option<HashMap<String, RawChecker>>,
    #[schemars(
        description = "How missing formatter/checker/LSP binary warnings are shown after configure. 'toast' (default) uses a 10s TUI or HTTP toast without adding session chat messages. 'log' writes to the plugin log only. 'chat' uses legacy ignored user messages in the session transcript. Warnings for formatters/checkers are only emitted when format_on_edit is true or a per-language formatter is set; checker warnings require validate_on_edit 'syntax' or 'full' or an explicit checker. There is no top-level 'formatters' key — use format_on_edit, formatter, and checker instead."
    )]
    pub configure_warnings_delivery: Option<RawConfigureWarningsDelivery>,
    /// Raw presence is preserved: `None` (absent) and `Some([])` (explicit
    /// empty choice) mean different things until user-base resolution.
    #[schemars(
        description = "Tool names that are not registered; every other AFT tool is registered. When absent from the user config it defaults to [\"aft_move\", \"aft_delete\"]; an explicit list (including []) replaces that default. Host tool names ('read', 'grep', 'bash', ...) leave the host's own tool in place. Project config may only add names and cannot disable aft_safety or a host tool slot."
    )]
    pub disabled_tools: Option<Vec<String>>,
    #[schemars(
        description = "Restrict file operations to within project root. When true, write-capable commands reject paths outside project_root. Default: false (matches OpenCode built-in behavior)."
    )]
    pub restrict_to_project_root: Option<bool>,
    #[schemars(
        description = "Background indexes. Each defaults on and builds independently of which tools are registered. Project config can only turn an index off."
    )]
    pub indexes: Option<RawIndexes>,
    #[schemars(
        description = "Configure indexes for folders even when no session is open in them. By default, no folders are configured for standing indexing."
    )]
    pub index: Option<RawIndex>,
    #[schemars(
        description = "Codebase health inspection config. Enabled by default; set inspect.enabled=false to hide aft_inspect."
    )]
    pub inspect: Option<RawInspect>,
    #[schemars(
        description = "Idle windows: when an unbound root's indexes are evicted, and when an unused checkout drops its in-memory index state."
    )]
    pub idle: Option<RawIdle>,
    pub backup: Option<RawBackup>,
    #[schemars(
        description = "User-scoped GitHub integration gates. Project config cannot change capabilities or host-wide tool descriptions."
    )]
    pub github: Option<RawGithub>,
    #[schemars(
        description = "Managed gh shim binary override. Whether the shim is used is github.shim; binary_path is the advanced AFT-image override."
    )]
    pub gh_shim: Option<RawGhShim>,
    #[schemars(
        description = "Agent-child Git attribution injected through environment-scoped core.hooksPath configuration."
    )]
    pub git: Option<RawGit>,
    #[schemars(description = "Pi and OMP harness-specific configuration.")]
    pub pi: Option<RawPi>,
    #[schemars(
        description = "Shell sandbox profiles: stamped workers default to relaxed, all other sessions to off; untrusted routes always use strict."
    )]
    pub sandbox: Option<RawSandbox>,
    #[schemars(
        description = "Bash runtime configuration (runtime gate + rewrite + compress + background execution and user-only environment defaults). Registration of bash and its companions is controlled by disabled_tools. Replaces `experimental.bash.*`."
    )]
    pub bash: Option<RawBashFeatures>,
    #[schemars(
        description = "User-only shell environment settings. Project configuration cannot select an environment provider."
    )]
    pub shell: Option<crate::config::ShellConfig>,
    #[schemars(description = "Experimental opt-in features. May change between releases.")]
    pub experimental: Option<RawExperimental>,
    #[schemars(description = "User-defined and built-in LSP server configuration.")]
    pub lsp: Option<RawLsp>,
    #[schemars(
        description = "Allow `aft_outline`/`aft_zoom` URL fetches to request private/link-local hosts. Default: false (rejects RFC1918, loopback, and link-local)."
    )]
    pub url_fetch_allow_private: Option<bool>,
    #[schemars(
        description = "External semantic backend configuration for embedding and retrieval."
    )]
    pub semantic: Option<RawSemantic>,
    #[schemars(description = "aft_search settings.")]
    pub search: Option<RawSearch>,
    #[schemars(
        description = "OpenCode only: auto-refresh the cached @cortexkit/aft-opencode package when a newer channel version is published. User-scoped only — project configs cannot disable updates silently."
    )]
    pub auto_update: Option<bool>,
    #[schemars(
        description = "Shared NDJSON bridge transport tuning (OpenCode and Pi). User-scoped only — project configs cannot set this block (bridge safety and per-machine transport budget)."
    )]
    pub bridge: Option<RawBridge>,
    #[schemars(
        description = "Subconscious (subc) daemon transport selection. User-scoped only — a project config cannot redirect transport. Presence of connection_file switches AFT from a spawned child process to a daemon-supervised module."
    )]
    pub subc: Option<RawSubc>,

    #[schemars(
        description = "Remote runs requested per bash call with runon. See docs/tools.md (bash: running on the remote build server)."
    )]
    pub remote_exec: Option<RawRemoteExec>,
    /// Set by the resolver, never read from a file: a project tier turned
    /// `remote_exec.enabled` off.
    #[serde(skip)]
    pub remote_exec_project_off: bool,
    /// Raw per-harness objects stay opaque until the resolver knows the active
    /// configure harness. Unknown harness names are intentionally ignored.
    #[schemars(
        description = "Per-harness overrides. The active harness applies its override after the base config within each tier: user base, user override, project base, project override. storage.cache_dir, durability.macos_full_sync and memory apply to the whole process; none can be overridden here. Nested harnesses are ignored; unknown harness names are reserved for forward compatibility."
    )]
    pub harnesses: Option<BTreeMap<String, Value>>,
}

#[derive(Debug, Clone, Default, Deserialize, PartialEq, schemars::JsonSchema)]
#[serde(default, deny_unknown_fields)]
pub struct RawDurability {
    #[schemars(
        description = "On macOS, restore F_FULLFSYNC drive-cache flushes instead of faster plain fsync. Plain fsync can lose recent writes on power loss, but adds no loss on daemon kill or OS crash. Applies to AFT files and directories, not SQLite; ignored on Linux and Windows. Takes effect on the next sync."
    )]
    pub macos_full_sync: Option<bool>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RawEditMode {
    Default,
    Hashline,
    Unknown(String),
}

impl<'de> Deserialize<'de> for RawEditMode {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = String::deserialize(deserializer)?;
        Ok(match value.as_str() {
            "default" => Self::Default,
            "hashline" => Self::Hashline,
            _ => Self::Unknown(value),
        })
    }
}

#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum RawValidateOnEdit {
    Syntax,
    Full,
}

impl RawValidateOnEdit {
    const fn as_str(self) -> &'static str {
        match self {
            Self::Syntax => "syntax",
            Self::Full => "full",
        }
    }
}

#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum RawFormatter {
    Biome,
    Oxfmt,
    Prettier,
    Deno,
    Ruff,
    Black,
    Rustfmt,
    Goimports,
    Gofmt,
    None,
}

impl RawFormatter {
    const fn as_str(self) -> &'static str {
        match self {
            Self::Biome => "biome",
            Self::Oxfmt => "oxfmt",
            Self::Prettier => "prettier",
            Self::Deno => "deno",
            Self::Ruff => "ruff",
            Self::Black => "black",
            Self::Rustfmt => "rustfmt",
            Self::Goimports => "goimports",
            Self::Gofmt => "gofmt",
            Self::None => "none",
        }
    }
}

#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum RawChecker {
    Tsc,
    Tsgo,
    Biome,
    Pyright,
    Ruff,
    Cargo,
    Go,
    Staticcheck,
    None,
}

impl RawChecker {
    const fn as_str(self) -> &'static str {
        match self {
            Self::Tsc => "tsc",
            Self::Tsgo => "tsgo",
            Self::Biome => "biome",
            Self::Pyright => "pyright",
            Self::Ruff => "ruff",
            Self::Cargo => "cargo",
            Self::Go => "go",
            Self::Staticcheck => "staticcheck",
            Self::None => "none",
        }
    }
}

#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum RawConfigureWarningsDelivery {
    Toast,
    Log,
    Chat,
}

/// Raw `indexes` block; each switch keeps its presence until resolution.
#[derive(Debug, Clone, Copy, Default, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
#[serde(default)]
pub struct RawIndexes {
    #[schemars(
        description = "Trigram index for indexed grep/glob and the lexical aft_search lane. With false, no text index is built, and grep and glob walk the folder."
    )]
    pub trigram: Option<bool>,
    #[schemars(
        description = "Semantic (embedding) index for the semantic aft_search lane. The default local backend may download an ONNX runtime and model and use CPU."
    )]
    pub semantic: Option<bool>,
    #[schemars(description = "Persisted call-graph store used by aft_callgraph and enrichment.")]
    pub callgraph: Option<bool>,
}

#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
#[serde(default)]
pub struct RawStorage {
    #[schemars(
        description = "Existing absolute cache parent (~ is expanded); AFT creates only its marked aft/ namespace. A path through symlinks is resolved once when first used and pinned by device and inode; if it later names a different directory, or is missing, unwritable or identity-changed, all disk caches turn off with cache_dir_unavailable and never fall back to storage. Rechecked on binds and at most once a minute. First enrollment requires a different device from durable storage; cache_dir_on_storage_device refuses main-disk mount stubs on every platform. Once a storage root has used a cache directory, removing this key keeps caches off; set it to null to move caches back to the storage root. Only the user config base may set this; harness/project overrides are dropped. Old caches are not migrated; doctor --fix reclaims only identity- and ownership-verified inactive cache domains. Choose default for the same behavior as omitting the setting; choose main_disk to return caches to the storage root (the old null spelling); choose dir with path to use a cache parent.",
        with = "RawCacheDir"
    )]
    pub cache_dir: Option<RawCacheDir>,
}

#[derive(Debug, Clone, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum RawCacheDir {
    Default {},
    MainDisk {},
    Dir { path: String },
}

#[derive(Debug, Clone, Deserialize, PartialEq, schemars::JsonSchema)]
// Nested objects mirror TS sub-schemas, which are non-strict z.object (unknown
// keys are silently stripped, the object survives). Only the TOP-LEVEL
// RawAftConfig is strict (matches AftConfigSchema.strict()). Privileged denylist
// fields are all top-level, so nested unknowns are harmlessly ignored.
pub struct RawSemantic {
    #[schemars(
        description = "Embedding backend. 'fastembed' uses local ONNX runtime, 'openai_compatible' calls a configured OpenAI-style API, 'ollama' calls a local Ollama embedding endpoint, and 'synapse' dials CortexKit Synapse over SubC."
    )]
    pub backend: Option<SemanticBackend>,
    #[serde(default, deserialize_with = "deserialize_opt_trimmed_non_empty_string")]
    #[schemars(
        description = "Model identifier passed to the backend. Required for synapse; fastembed defaults to all-MiniLM-L6-v2."
    )]
    pub model: Option<String>,
    #[serde(default, deserialize_with = "deserialize_opt_trimmed_non_empty_string")]
    #[schemars(
        description = "Base URL of the backend API endpoint. Required for openai_compatible. Default for ollama: http://localhost:11434."
    )]
    pub base_url: Option<String>,
    #[serde(default, deserialize_with = "deserialize_opt_trimmed_non_empty_string")]
    #[schemars(
        description = "Environment variable name containing the API key (e.g. 'OPENAI_API_KEY'). Project-scoped configs cannot set this field — only user-scoped configs can."
    )]
    pub api_key_env: Option<String>,
    /// Background embedding request floor in milliseconds. HTTP batch deadlines
    /// scale above it using measured per-item latency.
    #[serde(default, deserialize_with = "deserialize_opt_positive_u64")]
    #[schemars(description = "Background build embedding request timeout in milliseconds.")]
    pub timeout_ms: Option<u64>,
    #[serde(default, deserialize_with = "deserialize_opt_positive_u64")]
    #[schemars(
        description = "Interactive query embedding deadline in milliseconds. Project-scoped configs cannot set this field; values are clamped to 500..30000."
    )]
    pub query_timeout_ms: Option<u64>,
    #[serde(default, deserialize_with = "deserialize_opt_trimmed_non_empty_string")]
    #[schemars(
        description = "Query-only task instruction sent to the embedding backend: \"auto\" applies the model family's documented recipe (Qwen3-Embedding: the model-card retrieval task; fastembed and other families stay bare), \"off\" sends bare queries, any other value is used as literal task text. Never changes document vectors or the index fingerprint."
    )]
    pub query_instruction: Option<String>,
    #[serde(default, deserialize_with = "deserialize_opt_positive_usize")]
    #[schemars(description = "Maximum batch size used by the semantic embedding pipeline.")]
    pub max_batch_size: Option<usize>,
    #[serde(default, deserialize_with = "deserialize_opt_positive_usize")]
    #[schemars(
        description = "Whole-row input token budget for remote embedding backends. Absent keeps the MiniLM-era chunk caps. Fingerprinted: changing it rebuilds the semantic index."
    )]
    pub max_input_tokens: Option<usize>,
    #[serde(default, deserialize_with = "deserialize_opt_positive_usize")]
    #[schemars(
        description = "Most project files to embed for semantic search (default 20000): a limit on embedding cost and time; files past it are not embedded. Raise it for remote backends that embed server-side."
    )]
    pub max_files: Option<usize>,
}

impl RawSemantic {
    fn is_empty(&self) -> bool {
        self.backend.is_none()
            && self.model.is_none()
            && self.base_url.is_none()
            && self.api_key_env.is_none()
            && self.timeout_ms.is_none()
            && self.query_timeout_ms.is_none()
            && self.query_instruction.is_none()
            && self.max_batch_size.is_none()
            && self.max_input_tokens.is_none()
            && self.max_files.is_none()
    }
}

#[derive(Debug, Clone, Default, Deserialize, PartialEq, schemars::JsonSchema)]
#[serde(default)]
pub struct RawSearch {
    #[schemars(
        description = "Optional cross-encoder reranking of aft_search results. Default off."
    )]
    pub rerank: Option<RawRerank>,
}

/// Raw `search.rerank`. Parsing only: defaults and clamps belong to the search
/// engine, which owns every setting that can change result order.
#[derive(Debug, Clone, Default, Deserialize, PartialEq, schemars::JsonSchema)]
#[serde(default)]
pub struct RawRerank {
    #[schemars(
        description = "Cross-encoder reranker for the head of aft_search results. Only prose questions are reranked, and exact matches keep their order. 'off' keeps fused order, 'onnx' runs a local model through ONNX Runtime (downloaded in the background on first use), 'remote' calls a Cohere-style /rerank endpoint, 'synapse' uses CortexKit Synapse. A project config may only set 'off'."
    )]
    pub backend: Option<RerankBackendKind>,
    #[serde(deserialize_with = "deserialize_opt_trimmed_non_empty_string")]
    #[schemars(
        description = "Reranker model. For onnx: bge-reranker-base (default), bge-reranker-v2-m3, jina-reranker-v1-turbo or gte-reranker-modernbert-base. Required for remote and synapse. User config only."
    )]
    pub model: Option<String>,
    #[serde(deserialize_with = "deserialize_opt_trimmed_non_empty_string")]
    #[schemars(
        description = "Base URL of the remote rerank endpoint; AFT appends /rerank. Prefix with tei+ for a TEI server. User config only."
    )]
    pub endpoint: Option<String>,
    #[serde(deserialize_with = "deserialize_opt_trimmed_non_empty_string")]
    #[schemars(
        description = "Environment variable holding the remote rerank endpoint's API key. User config only."
    )]
    pub api_key_env: Option<String>,
    #[serde(deserialize_with = "deserialize_opt_positive_u64")]
    #[schemars(
        description = "How many leading results are reranked (default 20, at most 200). User config only."
    )]
    pub top_n: Option<u64>,
    #[serde(deserialize_with = "deserialize_opt_positive_u64")]
    #[schemars(
        description = "Reranking budget per search in milliseconds (default 1500, clamped to 50..15000). On timeout the fused order is kept. User config only."
    )]
    pub timeout_ms: Option<u64>,
}

#[derive(Debug, Clone, Default, Deserialize, PartialEq, schemars::JsonSchema)]
pub struct RawLsp {
    #[schemars(
        description = "Minutes since the last AFT tool call on that repository. Default 60; integers are clamped to 5..=1440. Project config may only lower the user value. Applies live."
    )]
    pub idle_minutes: Option<i64>,
    #[schemars(
        description = "Shut down idle language servers (default true). When false, servers still stop on unbind, eviction and shutdown. A project may turn idle shutdown on, never off. Applies live."
    )]
    pub idle_shutdown: Option<bool>,
    #[schemars(
        description = "Maximum live language servers process-wide, including starts in progress. Evicts the least recently used client with no pending requests before refusing a start. Project config may only lower the user value. Zero prevents new starts."
    )]
    pub max_servers: Option<usize>,
    #[serde(default, deserialize_with = "deserialize_opt_lsp_servers")]
    #[schemars(
        description = "User-defined LSP server map keyed by server id (e.g. { 'terraform-ls': { ... } })."
    )]
    pub servers: Option<BTreeMap<String, RawLspServerEntry>>,
    #[serde(
        default,
        deserialize_with = "deserialize_opt_trimmed_non_empty_string_vec"
    )]
    #[schemars(
        description = "Built-in LSP server ids to disable (e.g. ['python', 'biome']). See README for the full list."
    )]
    pub disabled: Option<Vec<String>>,
    #[schemars(
        description = "Which Python LSP to use. 'auto' stays on Pyright while ty is experimental; select 'ty' explicitly to opt in without fallback."
    )]
    pub python: Option<RawPythonLsp>,
    #[schemars(
        description = "Wait for inline LSP diagnostics on every edit/write/apply_patch call. Default: false."
    )]
    pub diagnostics_on_edit: Option<bool>,
    #[schemars(
        description = "Auto-install npm-distributed and GitHub-release LSP servers when the project needs them. Set false to require manual install on PATH."
    )]
    pub auto_install: Option<bool>,
    #[serde(default, deserialize_with = "deserialize_opt_positive_u64")]
    #[schemars(
        description = "Supply-chain grace window. AFT only installs versions that have been on the registry / GitHub releases for at least this many days. User pins via `lsp.versions` bypass this."
    )]
    pub grace_days: Option<u64>,
    #[serde(default, deserialize_with = "deserialize_opt_versions_map")]
    #[schemars(
        description = "Per-package version pin map keyed by npm package or GitHub repo. Pins bypass the grace filter and any weekly version recheck (e.g. { 'typescript-language-server': '5.0.0', 'clangd/clangd': '21.1.0' })."
    )]
    pub versions: Option<HashMap<String, String>>,
}

impl RawLsp {
    fn is_empty(&self) -> bool {
        self.idle_minutes.is_none()
            && self.idle_shutdown.is_none()
            && self.max_servers.is_none()
            && self.servers.is_none()
            && self.disabled.is_none()
            && self.python.is_none()
            && self.diagnostics_on_edit.is_none()
            && self.auto_install.is_none()
            && self.grace_days.is_none()
            && self.versions.is_none()
    }
}

#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum RawPythonLsp {
    Pyright,
    Ty,
    Auto,
}

#[derive(Debug, Clone, Default, Deserialize, PartialEq, schemars::JsonSchema)]
#[serde(default)]
pub struct RawLspServerEntry {
    #[serde(deserialize_with = "deserialize_opt_lsp_extensions")]
    #[schemars(
        description = "File extensions this server handles (e.g. ['.tf', '.tfvars']). Optional when overriding a built-in server — the built-in's extensions are inherited."
    )]
    pub extensions: Option<Vec<String>>,
    #[serde(deserialize_with = "deserialize_opt_trimmed_non_empty_string")]
    #[schemars(
        description = "LSP binary command (must be on PATH or absolute path). Optional when overriding a built-in server — the built-in's binary is inherited."
    )]
    pub binary: Option<String>,
    #[schemars(description = "Extra command-line arguments passed to the LSP binary.")]
    pub args: Option<Vec<String>>,
    #[serde(deserialize_with = "deserialize_opt_trimmed_non_empty_string_vec")]
    #[schemars(
        description = "Workspace root marker files. AFT walks up from each opened file looking for any of these."
    )]
    pub root_markers: Option<Vec<String>>,
    #[schemars(description = "Disable this server entirely without removing the config block.")]
    pub disabled: Option<bool>,
    #[schemars(
        description = "Extra environment variables passed to the LSP server child process."
    )]
    pub env: Option<HashMap<String, String>>,
    #[schemars(
        description = "JSON text passed as `initializationOptions` in the LSP `initialize` request. Invalid JSON prevents this server from starting."
    )]
    pub initialization_options: Option<String>,
}

#[derive(Debug, Clone, Default, Deserialize, PartialEq, schemars::JsonSchema)]
#[serde(default)]
pub struct RawBashFeatures {
    #[schemars(
        description = "Report watcher-observed project changes after bash commands. User opt-in; projects may only set off. Diff mode uses clean git before-images and bounded output."
    )]
    pub changed_files: Option<crate::config::BashChangedFiles>,
    /// Runtime gate for bash execution. Absent means on.
    #[schemars(
        description = "Runtime gate for every bash operation, including bash_status/bash_write/bash_watch/bash_kill. When false they report bash_disabled; registration is controlled by disabled_tools."
    )]
    pub enabled: Option<bool>,
    #[schemars(
        description = "Rewrite common bash commands (cat, grep, find, sed, ls) into AFT tool calls for faster, formatted output."
    )]
    pub rewrite: Option<bool>,
    #[schemars(
        description = "Compress bash output via per-tool compressors (git, cargo, npm, bun, pnpm, pytest, tsc, eslint, biome, vitest, prettier, ruff, mypy, go, golangci-lint, playwright, next) plus TOML filter pipeline. Adds `[cmpaft]` marker."
    )]
    pub compress: Option<bool>,
    #[schemars(
        description = "Allow agents to launch bash with `{ background: true }` for long-running tasks. Foreground bash always auto-promotes to background after the foreground wait window (default 8s) regardless of this flag."
    )]
    pub background: Option<bool>,
    #[schemars(
        description = "Break-glass host execution when AFT's module transport is unavailable. Project-settable. Every fallback command requires a fresh host permission prompt and runs without AFT rewrites, compression, or background support."
    )]
    pub host_fallback: Option<bool>,
    #[schemars(
        description = "Allow subagents to run background bash. Default true because workers are multi-turn and wait with bash_watch; when false, subagent `background: true` requests are converted to foreground calls that block up to the hard cap."
    )]
    pub subagent_background: Option<bool>,
    #[schemars(
        description = "Detach a `wait: true` bash call when a new user message arrives. Default true. Set false to keep the wait blocking; a message containing the literal `&detach` still forces detachment, the token is stripped before delivery and the rest of the message is preserved; a token-only message becomes `(requested background detach)`. Project-safe."
    )]
    pub detach_on_user_message: Option<bool>,
    #[schemars(
        description = "Append AFT read-only database schema hints after missing-table or missing-column errors. SQLite on Unix only; supported literal database paths only. Project-safe."
    )]
    pub db_schema_hints: Option<bool>,
    #[schemars(
        description = "Periodically remind the agent that a background bash task is still running. When false, completion is delivered but mid-flight reminders are suppressed."
    )]
    pub long_running_reminder_enabled: Option<bool>,
    #[serde(deserialize_with = "deserialize_opt_positive_u64")]
    #[schemars(
        description = "Interval in milliseconds between mid-flight reminders for a still-running background bash task."
    )]
    pub long_running_reminder_interval_ms: Option<u64>,
    #[serde(deserialize_with = "deserialize_opt_positive_u64")]
    #[schemars(
        description = "How long foreground bash blocks before auto-promoting the task to background, in milliseconds. Minimum 5000; values below the floor are clamped up."
    )]
    pub foreground_wait_window_ms: Option<u64>,
    #[serde(deserialize_with = "deserialize_opt_positive_u64")]
    #[schemars(
        description = "Maximum synchronous bash_watch wait in milliseconds. Defaults to 120 seconds for short remaining waits; set to 1800000 to restore the old 30-minute cap."
    )]
    pub watch_sync_max_ms: Option<u64>,
    #[serde(deserialize_with = "deserialize_opt_worker_wait_max_ms")]
    #[schemars(
        description = "Longest a delegated worker (subagent) waits on one command before control returns to it, in milliseconds: a bash_watch without a timeout, or a bash call that blocks until the command finishes (wait: true, or every foreground call when subagent_background is false). The command keeps running in the background; the worker is told it is still running and can wait again or kill it. While a worker keeps waiting, the command's default 30-minute hard kill is pushed back by this much. Default 1800000 (30 minutes); values below 60000 are a config error. Project-safe."
    )]
    pub worker_wait_max_ms: Option<u64>,
    #[schemars(
        description = "Linux daemon scopes are on by default (user config only). User config can disable them. Standalone mode, PTY tasks, and native-sandbox launches use the usual spawn path. If systemd-run, the user manager, or cgroup access is unavailable, AFT uses the usual path."
    )]
    pub linux_scope: Option<bool>,
    #[serde(deserialize_with = "deserialize_opt_linux_scope_max_runtime_secs")]
    #[schemars(range(min = 1, max = 4294967295_u64))]
    #[schemars(
        description = "User-only Linux daemon scope ceiling in seconds. Worker waits do not extend it. An explicit timeout uses its own limit plus 60 seconds."
    )]
    pub linux_scope_max_runtime_secs: Option<u64>,
    #[serde(deserialize_with = "deserialize_opt_memory_limit_mib")]
    #[schemars(range(min = 1, max = 4294967295_u64))]
    #[schemars(
        description = "Optional aggregate local-command memory cap in MiB. Off by default; projects may only lower a user cap. Remote runon jobs use server limits."
    )]
    pub memory_limit_mib: Option<u64>,
    #[schemars(
        description = "On macOS, agent shells and governed gh commands do not inherit the supervisor's privacy grants. Default false. Live for future commands; user tier controls it and projects may only enable it. Protected folders such as ~/Downloads should be read with AFT's read tool. Accepted but inert on other platforms; unavailable spawn attributes refuse the command instead of inheriting grants."
    )]
    pub disclaim_privacy: Option<bool>,
    #[schemars(
        description = "Pi-only fallback for manually mirroring Pi's optional PowerShell default tool when the host does not expose its enabled-tool registry. OpenCode never registers this tool."
    )]
    pub powershell_tool: Option<bool>,
    #[schemars(
        description = "Fixed environment variables for local shell commands, at either tier. A project's names apply only while the project is trusted (aft doctor filters trust; a linked worktree inherits its main checkout); a user value wins when both tiers set the same name, and the first bash reply in a session names each applied variable with its tier, never its value. Per-call env values and the command's own export both override these. Names that hijack startup, redirect lookup roots, inject into interpreters or Git, or drive AFT, the sandbox, or a build worker are rejected at every tier; credentials, identity, proxy, and TLS-trust names are rejected at the project tier. These values never reach a runon build-server job unless a user name is listed in bash.runon_env."
    )]
    pub env: Option<BTreeMap<String, String>>,
    /// Project-tier `bash.env` values, carried separately so the user-tier map
    /// stays user-only. Only `project_safe_bash` fills this field.
    #[serde(skip)]
    pub project_env: Option<BTreeMap<String, String>>,
    /// User-only: `bash.env` names that are also sent to a `runon` job.
    #[schemars(
        description = "User-only list of bash.env names that are also sent to a runon build-server job. Every other bash.env value applies to local commands only; a project's values are never sent, even when their name is listed. Unlisted names appear in the job's \"does not receive\" disclosure."
    )]
    pub runon_env: Option<Vec<String>>,
}

#[derive(Debug, Clone, Default, Deserialize, PartialEq, schemars::JsonSchema)]
#[serde(default)]
pub struct RawExperimental {
    #[schemars(
        description = "Run the experimental Python `ty` type checker alongside Pyright. Use lsp.python = 'ty' to select ty exclusively."
    )]
    pub lsp_ty: Option<bool>,
}

impl RawExperimental {
    fn is_empty(&self) -> bool {
        self.lsp_ty.is_none()
    }
}

#[derive(Debug, Clone, Default, Deserialize, PartialEq, schemars::JsonSchema)]
#[serde(default)]
pub struct RawInspect {
    #[schemars(
        description = "Runtime switch for aft_inspect. Defaults to true. When false the registered tool reports inspect_disabled; use disabled_tools to unregister it."
    )]
    pub enabled: Option<bool>,
    #[serde(default, deserialize_with = "deserialize_opt_positive_u64")]
    #[schemars(
        description = "Blocking LSP diagnostics deadline in milliseconds. Values are clamped to 10000..600000. User config sets the baseline; project config may only raise the effective deadline so a repository cannot silently reduce diagnostic completeness for another consumer."
    )]
    pub diagnostics_timeout_ms: Option<u64>,
    #[serde(default, deserialize_with = "deserialize_opt_positive_u64")]
    #[schemars(
        description = "Hard deadline for one Tier-2 pass, including projection and scanning. On expiry AFT cooperatively cancels the pass and releases its cold-build slot."
    )]
    pub tier2_pass_timeout_ms: Option<u64>,
    #[serde(deserialize_with = "deserialize_opt_inspect_categories")]
    #[schemars(with = "Option<InspectCategories>")]
    #[schemars(
        description = "Per-category computation switches, all true by default. Off categories run no scans or refreshes and render as off, never incomplete. Project config may only turn a category off."
    )]
    pub categories: Option<BTreeMap<String, bool>>,
    #[schemars(description = "Duplicate suppression config for the duplicates inspect category.")]
    pub duplicates: Option<RawInspectDuplicates>,
}

impl RawInspect {
    fn is_empty(&self) -> bool {
        self.enabled.is_none()
            && self.diagnostics_timeout_ms.is_none()
            && self.tier2_pass_timeout_ms.is_none()
            && self.categories.is_none()
            && self.duplicates.is_none()
    }
}

/// Only `expected_mirrors` survives here: `lower_bound`, `discard_cost`, and
/// `anonymize` were accepted-but-never-read knobs (the scanner hardcodes its
/// cost bounds and anonymization rules), so they were removed from the schema
/// rather than wired up.
#[derive(Debug, Clone, Default, Deserialize, PartialEq, schemars::JsonSchema)]
#[serde(default)]
pub struct RawInspectDuplicates {
    #[schemars(
        description = "Intentional mirror paths for duplicate suppression. Each source and mirror glob matches project-root-relative forward-slash paths; groups fully straddling the pair are counted as suppressed instead of reported."
    )]
    pub expected_mirrors: Option<Vec<RawExpectedMirror>>,
}

#[derive(Debug, Clone, Deserialize, PartialEq, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct RawExpectedMirror {
    pub source: String,
    pub mirror: String,
}

impl RawInspectDuplicates {
    fn is_empty(&self) -> bool {
        self.expected_mirrors.is_none()
    }
}

#[derive(Debug, Clone, Default, Deserialize, PartialEq, schemars::JsonSchema)]
#[serde(default)]
pub struct RawIdle {
    #[schemars(
        description = "Minutes without tool traffic before an unbound root's indexes are evicted. Default 30; values outside 5..=30 are clamped. Reclaimed state rebuilds on the next request. User and project tiers."
    )]
    pub root_ttl_minutes: Option<Value>,
    #[schemars(
        description = "Hours without use after which a checkout counts as idle and drops its in-memory index state; its state on disk stays. Default 168 (one week); values outside 1..=8760 are clamped. Replaces views.idle_checkout_hours. User and project tiers. Applies live."
    )]
    pub checkout_hours: Option<Value>,
}

impl RawIdle {
    fn is_empty(&self) -> bool {
        self.root_ttl_minutes.is_none() && self.checkout_hours.is_none()
    }
}

#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
#[serde(default)]
pub struct RawBridge {
    #[serde(deserialize_with = "deserialize_opt_bridge_request_timeout_ms")]
    #[schemars(
        description = "Per-request bridge transport timeout in milliseconds. Default 30000. Raise on slow filesystems (WSL/DrvFs/NFS) where cold aft operations exceed the default."
    )]
    pub request_timeout_ms: Option<u64>,
}

#[derive(Debug, Clone, Default, Deserialize, PartialEq, schemars::JsonSchema)]
#[serde(default)]
pub struct RawSubc {
    #[schemars(
        description = "Absolute path to the Subconscious (subc) daemon connection file. When present (non-empty), the plugin talks to AFT as a daemon-supervised module over subc instead of spawning the aft binary; absent/empty means standalone NDJSON (the default). macOS default: ~/.local/share/cortexkit/run/subc-connection.json."
    )]
    pub connection_file: Option<String>,
    #[schemars(
        description = "Close the plugin's Subconscious routes to a checkout after two consecutive checks find the folder missing. Off by default."
    )]
    pub client_reaper: Option<bool>,
}

#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
#[serde(default)]
pub struct RawGithub {
    #[schemars(description = "Interpose the governed gh shim in agent child PATHs.")]
    pub shim: Option<bool>,
    #[schemars(
        description = "Enable structured issue:// and pr:// reads. github.write=true also enables this to keep comment ordinals visible."
    )]
    pub read: Option<bool>,
    #[schemars(
        description = "Enable creating and editing issue and pull-request conversation comments. Implies github.read."
    )]
    pub write: Option<bool>,
}

#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
#[serde(default)]
pub struct RawGhShim {
    #[serde(deserialize_with = "deserialize_opt_trimmed_non_empty_string")]
    #[schemars(
        description = "Absolute deployed or development AFT binary used by the managed gh entry. Defaults to the running AFT image. User-scoped only."
    )]
    pub binary_path: Option<String>,
}

#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
#[serde(default)]
pub struct RawGit {
    #[serde(deserialize_with = "deserialize_opt_git_co_author")]
    #[schemars(
        description = "Git co-author attribution for AFT-spawned agent children: 'off', 'auto', or an explicit 'Name <email>' identity. User and project tiers are accepted with project precedence."
    )]
    pub co_author: Option<String>,
}

#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
#[serde(default)]
pub struct RawPi {
    #[schemars(
        description = "Pi and OMP tool presentation mode. 'top_level' registers tools with loadMode: essential on OMP so they appear at top level (default). 'host_default' uses host default loadMode (mounting tools under xd:// on OMP). User and project tiers are accepted with project precedence."
    )]
    pub tool_presentation: Option<RawPiToolPresentation>,
    /// Plain Pi asks before outside-project access (default on). A project
    /// tier may turn it on, never off; see `merge_pi_config`.
    #[schemars(
        description = "Plain Pi only: ask before an AFT tool reaches a path outside the project. On (default), Pi's own terminal UI asks; print, JSON and RPC sessions have no screen to ask on and allow it without asking. Off, outside access is allowed without asking. Credentials, AFT's data folder, sandbox.read_deny and restrict_to_project_root: true refuse either way. Does not apply on OMP, where OMP's approval mode (tools.approvalMode) decides through the tools' declared approval tiers. A project config may turn it on, never off."
    )]
    pub external_access_ask: Option<bool>,
}

impl RawPi {
    fn is_empty(&self) -> bool {
        self.tool_presentation.is_none() && self.external_access_ask.is_none()
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RawPiToolPresentation {
    TopLevel,
    HostDefault,
    Unknown(String),
}

impl<'de> Deserialize<'de> for RawPiToolPresentation {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        match s.as_str() {
            "top_level" => Ok(Self::TopLevel),
            "host_default" => Ok(Self::HostDefault),
            other => Ok(Self::Unknown(other.to_string())),
        }
    }
}

#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
#[serde(default)]
pub struct RawBackup {
    #[schemars(
        description = "Master switch for agent-facing undo backups. When false aft_safety stays registered and reports that backups are disabled. User-only; project config is ignored."
    )]
    pub enabled: Option<bool>,
    #[serde(default, deserialize_with = "deserialize_opt_positive_usize")]
    #[schemars(description = "Per-file undo stack depth. User-only; project config is ignored.")]
    pub max_depth: Option<usize>,
    #[schemars(
        description = "Maximum existing-file size captured for undo, in bytes. Defaults to 64 MiB. User and project tiers may set it; explicit larger values are honored. Zero disables automatic snapshots. Mutations still proceed when capture is skipped."
    )]
    pub max_file_size: Option<u64>,
}

/// `remote_exec`: whether bash calls may ask to run on the remote build server
/// with `runon`. User tier only, except that a project may turn it off.
#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
#[serde(default)]
pub struct RawRemoteExec {
    #[schemars(
        description = "Offer bash's runon argument, which runs a command line on the remote Linux build server (subc mode only). User-scoped: a project config may set false to turn remote runs off for itself, never true."
    )]
    pub enabled: Option<bool>,
    #[schemars(
        description = "The runner demand a runon call without specifics runs under (today only \"linux\"). Never makes a call remote by itself. User-scoped only."
    )]
    pub default_demand: Option<String>,
}

#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
#[serde(default)]
pub struct RawSandbox {
    #[schemars(
        description = "User-selected sandbox profiles by role. Projects may only select a stricter profile (off < relaxed < strict)."
    )]
    pub profile: Option<RawSandboxRoles>,
    #[schemars(
        description = "Additional absolute writable directories. User-scoped only; project config cannot add write access."
    )]
    pub write_allow: Option<Vec<PathBuf>>,
    #[schemars(
        description = "Additional absolute paths sandboxed commands may not read. Project config may add deny entries but cannot remove user or built-in entries."
    )]
    pub read_deny: Option<Vec<PathBuf>>,
}

#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
#[serde(default)]
pub struct RawSandboxRoles {
    pub worker: Option<crate::config::SandboxMode>,
    pub head: Option<crate::config::SandboxMode>,
}

/// Raw user-tier standing index configuration. Unlike normally stripped nested
/// fields, unknown entry fields are retained only long enough to emit an
/// explicit warn-and-ignore notice.
#[derive(Debug, Clone, Default, Deserialize, PartialEq, schemars::JsonSchema)]
#[serde(default)]
pub struct RawIndex {
    #[schemars(
        description = "List the folders to index, with a path and a list of indexes to build for each folder. The default is an empty list."
    )]
    pub roots: Option<Vec<RawIndexRoot>>,
}

#[derive(Debug, Clone, Default, Deserialize, PartialEq, schemars::JsonSchema)]
#[serde(default)]
pub struct RawIndexRoot {
    pub path: Option<String>,
    pub indexes: Option<Vec<String>>,
    #[serde(flatten)]
    pub unknown: BTreeMap<String, Value>,
}

/// Resolve raw user/project config tiers into the flat core [`Config`].
///
/// Empty input is NOT special-cased: no config file is equivalent to an empty
/// config object, so it still flows through the resolver and picks up the bash
/// surface default (recommended ⇒ bash on), matching the TypeScript pipeline
/// which always runs `resolveProjectOverridesForConfigure` even on `{}`.
pub fn resolve_config(tiers: &[ConfigTier]) -> ResolveResult {
    resolve_config_for_harness(tiers, None)
}

/// Resolve tiers for one active harness. Each tier applies its matching harness
/// object before crossing the user/project trust boundary.
pub fn resolve_config_for_harness(
    tiers: &[ConfigTier],
    harness: Option<&Harness>,
) -> ResolveResult {
    let mut merged = RawAftConfig::default();
    let mut lsp_user_max_servers = 8;
    let mut dropped = Vec::new();
    let mut warnings = Vec::new();

    // A name retired two or more releases ago refuses only the user config,
    // which AFT rewrites itself; a project config's old names are translated
    // below with a notice (see `removed_config_key_errors_for_file`).
    let errors: Vec<String> = tiers
        .iter()
        .map(|tier| {
            serde_json::from_str::<Value>(&strip_jsonc(&tier.doc))
                .ok()
                .and_then(|value| {
                    value.as_object().map(|map| {
                        feature_config::removed_config_key_errors_for_file(map, tier.tier == "user")
                    })
                })
                .unwrap_or_default()
        })
        .find(|errors| !errors.is_empty())
        .unwrap_or_default();
    if !errors.is_empty() {
        return ResolveResult {
            config: rejected_cache_config(tiers, Config::default(), &errors),
            dropped,
            warnings,
            errors,
        };
    }

    let mut parsed = Vec::with_capacity(tiers.len());
    for tier in tiers {
        let outcome = match parse_tier(tier, harness, &mut warnings, &mut dropped) {
            Ok(outcome) => outcome,
            Err(errors) => {
                // A rejected candidate still records where caches belong, or
                // that the user file leaves it unknown, so caches stay off
                // rather than falling back to the storage root.
                let config = cache_location_checked_config(tiers, &mut warnings);
                return ResolveResult {
                    config: rejected_cache_config(tiers, config, &errors),
                    dropped,
                    warnings,
                    errors,
                };
            }
        };
        let (raw, translation) = outcome;
        if translation.legacy_input {
            log_retired_keys_once(tier, &translation);
        }
        for warning in translation.warnings {
            // Migration notices are delivered once per identity by the host
            // plugin or CLI; the engine only records them in its log so the
            // same notice is not re-delivered on every configure. A
            // superseded-legacy note describes a file that is already fixed
            // (it only keeps a runtime gate), so it is logged once per process
            // for the same file and text instead of on every configure.
            if warning.code == "superseded_legacy_config"
                && !first_superseded_note(&tier.source, &warning.key, &warning.message)
            {
                continue;
            }
            crate::slog_info!(
                "config {} [{}]: {} ({})",
                tier.tier,
                warning.key,
                warning.message,
                warning.code
            );
        }
        parsed.push((tier, raw));
    }

    // The absent-base default applies exactly once, to the user base, before
    // any harness override or tier merge. No user file behaves like `{}`.
    let default_disabled = || {
        feature_config::DEFAULT_DISABLED_TOOLS
            .iter()
            .map(|name| (*name).to_string())
            .collect::<Vec<_>>()
    };
    if !parsed.iter().any(|(tier, _)| tier.tier == "user") {
        merged.disabled_tools = Some(default_disabled());
    }

    for (tier, mut raw) in parsed {
        let is_user = tier.tier == "user";
        if is_user && raw.disabled_tools.is_none() {
            raw.disabled_tools = Some(default_disabled());
        }
        let tier_kind = if is_user {
            crate::bash_env::BashEnvTier::User
        } else {
            crate::bash_env::BashEnvTier::Project
        };
        let harness_refusal = apply_harness_override(
            &mut raw,
            harness,
            tier,
            is_user,
            tier_kind,
            &mut warnings,
            &mut dropped,
        );
        if let Some(error) =
            harness_refusal.or_else(|| raw_bash_env_refusal(&raw, tier, tier_kind, None))
        {
            let errors = vec![error];
            return ResolveResult {
                config: rejected_cache_config(tiers, Config::default(), &errors),
                dropped,
                warnings,
                errors,
            };
        }
        if let Some(RawEditMode::Unknown(value)) = raw.edit_mode.as_ref() {
            warnings.push(ConfigWarning {
                code: "invalid_edit_mode",
                key: "edit_mode",
                tier: tier.tier.clone(),
                value: value.clone(),
                message: format!("Unknown edit_mode value {value:?}; falling back to \"default\""),
            });
        }

        if is_user {
            merge_trusted_config(&mut merged, raw);
            lsp_user_max_servers = merged
                .lsp
                .as_ref()
                .and_then(|lsp| lsp.max_servers)
                .unwrap_or(8);
        } else {
            record_project_drops(&raw, &tier.tier, &mut dropped);
            record_resource_loosening(&merged, &raw, &tier.tier, &mut dropped);
            merge_project_config(&mut merged, raw);
        }
    }

    let mut config = cache_location_checked_config(tiers, &mut warnings);
    if let Err(missing) = apply_resolved_config(&merged, &mut config, &mut warnings) {
        return ResolveResult {
            config: rejected_cache_config(tiers, config, &missing),
            dropped,
            warnings,
            errors: missing,
        };
    }
    config.index = resolve_index_config(merged.index.as_ref(), &mut warnings);
    config.lsp_user_max_servers = Some(lsp_user_max_servers);
    let cache_dir = merged.storage.and_then(|storage| storage.cache_dir);
    if let Some(RawCacheDir::Dir { path: raw }) = cache_dir.as_ref() {
        let home = std::env::var_os("HOME")
            .or_else(|| std::env::var_os("USERPROFILE"))
            .map(std::path::PathBuf::from);
        match crate::config::expand_cache_dir_path(raw, home.as_deref()) {
            Ok(path) => config.cache_dir = Some(path),
            Err(error) => {
                let path = std::path::PathBuf::from(raw);
                config.cache_dir = Some(path.clone());
                config.cache_unavailable = Some(error.clone());
                warnings.push(crate::cache_location::unavailable_warning(&path, &error));
            }
        }
    }
    config.cache_dir_opt_out = matches!(cache_dir, Some(RawCacheDir::MainDisk {}));
    config.idle = resolve_idle_config(merged.idle.as_ref(), &mut warnings);
    let resolved = serde_json::to_value(&config).unwrap_or(Value::Null);
    if let Err(invalid) = feature_config::validate_resolved_config(&resolved) {
        return ResolveResult {
            config: rejected_cache_config(tiers, config, &invalid),
            dropped,
            warnings,
            errors: invalid,
        };
    }
    let errors = config
        .cache_config_unknown
        .as_ref()
        .filter(|reason| reason.contains("unknown field"))
        .and_then(|reason| {
            // The warning retains the source and section. Keep rejection codes
            // independent of file paths so every config loader agrees on them.
            let (_, detail) = reason.split_once("unknown field `")?;
            let key = detail.split('`').next().unwrap_or_default();
            Some(vec![format!("invalid_cache_config: unknown field `{key}`")])
        })
        .unwrap_or_default();
    ResolveResult {
        config,
        dropped,
        warnings,
        errors,
    }
}

/// A default config carrying the user tier's cache-location verdict: when the
/// user file is unreadable or its storage section invalid, the cache location
/// is unknown and a `cache_dir_config_unknown` warning says so.
fn cache_location_checked_config(
    tiers: &[ConfigTier],
    warnings: &mut Vec<ConfigWarning>,
) -> Config {
    let mut config = Config::default();
    config.cache_config_unknown = tiers
        .iter()
        .filter(|tier| tier.tier == "user")
        .find_map(cache_location_config_error);
    if let Some(reason) = &config.cache_config_unknown {
        warnings.push(ConfigWarning {
            code: "cache_dir_config_unknown", key: "storage.cache_dir", tier: "user".into(),
            value: "unknown".into(),
            message: format!("User configuration is unreadable or invalid ({reason}); AFT is running without its caches until the configuration is valid."),
        });
    }
    config
}

fn rejected_cache_config(tiers: &[ConfigTier], mut config: Config, errors: &[String]) -> Config {
    if config.cache_dir.is_none() {
        // Read only `storage.cache_dir` from the user document itself: the
        // candidate was rejected, possibly for another section, so the tier
        // as a whole may not parse.
        let mut choice = None;
        for tier in tiers.iter().filter(|tier| tier.tier == "user") {
            if let Some(next) = serde_json::from_str::<Value>(&strip_jsonc(&tier.doc))
                .ok()
                .and_then(|doc| {
                    parse_cache_dir(doc.get("storage")?.get("cache_dir").cloned()?).ok()
                })
            {
                merge_cache_dir(&mut choice, next);
            }
        }
        match choice {
            Some(RawCacheDir::Dir { path: raw }) => {
                let home = std::env::var_os("HOME")
                    .or_else(|| std::env::var_os("USERPROFILE"))
                    .map(std::path::PathBuf::from);
                config.cache_dir = Some(
                    crate::config::expand_cache_dir_path(&raw, home.as_deref())
                        .unwrap_or_else(|_| std::path::PathBuf::from(raw)),
                );
            }
            Some(RawCacheDir::MainDisk {}) => config.cache_dir_opt_out = true,
            Some(RawCacheDir::Default {}) | None => {}
        }
    }
    config
        .cache_config_unknown
        .get_or_insert_with(|| format!("configuration rejected: {}", errors.join(", ")));
    config
}

/// Resolve raw config tiers into the core-domain config and RESET it onto an
/// existing `base`, preserving only `base`'s process-state fields (storage_dir,
/// harness, lsp_paths_extra, bash_permissions, …). This is the configure-path
/// entry.
///
/// RESET, not overlay: the core-domain config is rebuilt from DEFAULT + the
/// supplied tiers, so a field absent from the tiers returns to its default —
/// it NEVER keeps `base`'s prior value. This closes a cross-bind privilege
/// escalation: under the subc daemon a single `AppContext` per project root is
/// shared across harness identities, and `configure` seeds `base` from the
/// previous bind's config. With the old overlay semantics, a later low-trust
/// bind (e.g. `mcp:*` or `fed:*`) that omitted a field inherited an earlier high-trust
/// bind's capability for it (confirmed on the wire: `url_fetch_allow_private`
/// SSRF, and `lsp_servers` arbitrary-binary). Reset-onto-default makes the
/// resolved core config a pure function of this bind's own tiers and harness.
///
/// Parity-safe by construction: this routes through [`resolve_config_for_harness`]
/// (the same harness-aware path the cross-language parity gate validates), which builds onto
/// `Config::default()` — so reset-onto-default == overlay-onto-default there and
/// no parity/unit fixture changes. Only this configure path, seeded from a prior
/// config, changes behavior — which is exactly the leak site.
///
/// Process-state fields are not part of `RawAftConfig`; they are carried from
/// `base` here and re-applied by `handle_configure`'s flat-param parsing
/// afterwards, so plugin-mode behavior is unchanged (the plugin re-sends them on
/// every configure). They are also unreachable as a subc escalation vector: a
/// subc RouteBind sends only `config:[tiers]`, never the flat process-state
/// params, so they stay at default for every subc bind regardless.
pub fn resolve_config_onto(tiers: &[ConfigTier], base: &mut Config) -> Vec<DroppedKey> {
    resolve_config_onto_with_diagnostics(tiers, base).dropped
}

/// Resolve configuration for the active harness into `base`, replacing
/// configurable fields while retaining fields that describe the running process.
pub fn resolve_config_onto_for_harness(
    tiers: &[ConfigTier],
    harness: &Harness,
    base: &mut Config,
) -> Vec<DroppedKey> {
    resolve_config_onto_with_diagnostics_for_harness(tiers, Some(harness), base).dropped
}

/// Reset a runtime config while retaining both trust-boundary drops and
/// non-fatal value warnings for the configure response.
pub fn resolve_config_onto_with_diagnostics(
    tiers: &[ConfigTier],
    base: &mut Config,
) -> ResolveDiagnostics {
    resolve_config_onto_with_diagnostics_for_harness(tiers, None, base)
}

/// Harness-aware variant of [`resolve_config_onto_with_diagnostics`].
pub fn resolve_config_onto_with_diagnostics_for_harness(
    tiers: &[ConfigTier],
    harness: Option<&Harness>,
    base: &mut Config,
) -> ResolveDiagnostics {
    let ResolveResult {
        mut config,
        dropped,
        warnings,
        errors,
    } = resolve_config_for_harness(tiers, harness);
    if !errors.is_empty() {
        // A rejected candidate never publishes: the caller keeps its last-good
        // configuration.
        return ResolveDiagnostics {
            dropped,
            warnings,
            errors,
        };
    }
    carry_process_state(base, &mut config);
    *base = config;
    ResolveDiagnostics {
        dropped,
        warnings,
        errors,
    }
}

/// Carry the process-state (non-`RawAftConfig`) fields from `base` onto a
/// freshly-resolved core config. EVERY `Config` field not copied here is
/// core-domain and intentionally comes from the resolved tiers (reset). Keeping
/// this list complete is load-bearing: a core field accidentally copied here
/// would re-introduce cross-bind inheritance for it.
fn carry_process_state(base: &Config, resolved: &mut Config) {
    resolved.project_root = base.project_root.clone();
    resolved.harness = base.harness.clone();
    resolved.validation_depth = base.validation_depth;
    resolved.checkpoint_ttl_hours = base.checkpoint_ttl_hours;
    resolved.max_symbol_depth = base.max_symbol_depth;
    resolved.diagnostic_cache_size = base.diagnostic_cache_size;
    resolved.max_background_bash_tasks = base.max_background_bash_tasks;
    resolved.bash_permissions = base.bash_permissions;
    resolved.search_index_max_file_size = base.search_index_max_file_size;
    resolved.storage_dir = base.storage_dir.clone();
    resolved.storage_lease = base.storage_lease.clone();
    resolved.lsp_paths_extra = base.lsp_paths_extra.clone();
    resolved.lsp_auto_install_binaries = base.lsp_auto_install_binaries.clone();
    resolved.lsp_inflight_installs = base.lsp_inflight_installs.clone();
}

/// Log, once per config file and set of retired and removed keys in this
/// process, that a tier's retired keys were translated in memory and which
/// removed keys it still sets. Reloads and repeated binds of the same root
/// therefore do not repeat it. The host plugin delivers the user-facing
/// notice; the user file's automatic rewrite reports its own.
fn log_retired_keys_once(tier: &ConfigTier, translation: &feature_config::DocumentTranslation) {
    let keys = translation
        .retired_keys
        .iter()
        .cloned()
        .collect::<Vec<_>>()
        .join(", ");
    if !first_superseded_note(&tier.source, "retired_keys", &keys) {
        return;
    }
    let notice = if tier.tier == "user" {
        let mut parts = Vec::new();
        if translation.legacy_input {
            parts.push(format!(
                "{} uses retired keys ({}); AFT applied their current equivalents in memory",
                tier.source,
                translation.retired_keys.join(", ")
            ));
        }
        parts.retain(|part| !part.is_empty());
        parts.join(". ")
    } else {
        feature_config::project_retired_keys_notice(&tier.source, translation)
    };
    crate::slog_warn!("config {}: {}", tier.tier, notice);
}

/// Whether this note (keyed by file, key and text) is new to this process.
fn first_superseded_note(source: &str, key: &str, message: &str) -> bool {
    static SEEN: std::sync::OnceLock<std::sync::Mutex<std::collections::HashSet<String>>> =
        std::sync::OnceLock::new();
    SEEN.get_or_init(Default::default)
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
        .insert(format!("{source}\u{0}{key}\u{0}{message}"))
}

fn parse_tier(
    tier: &ConfigTier,
    harness: Option<&Harness>,
    warnings: &mut Vec<ConfigWarning>,
    dropped: &mut Vec<DroppedKey>,
) -> Result<(RawAftConfig, feature_config::DocumentTranslation), Vec<String>> {
    let stripped = strip_jsonc(&tier.doc);
    let value = serde_json::from_str::<Value>(&stripped)
        .map_err(|_| vec!["invalid_config_document".to_string()])?;
    let Value::Object(mut map) = value else {
        return Err(vec!["invalid_config_document".to_string()]);
    };
    // Retired keys are translated on the raw document, before the strict
    // schema sees it, so they never reach `RawAftConfig`; the names retired in
    // 0.62 or earlier were already refused by `removed_config_key_errors`. Only the user
    // tier's base block may receive the absent-base default disables.
    let document_tier = if tier.tier == "user" {
        feature_config::DocumentTier::User
    } else {
        feature_config::DocumentTier::Project
    };
    let translation = feature_config::translate_document(&mut map, document_tier);
    // Machine limits cannot be selected by repositories or harness blocks.
    // Drop even malformed values before validating neighbouring security keys.
    if tier.tier != "user" && map.remove("memory").is_some() {
        push_drop(dropped, "memory", &tier.tier, USER_ONLY_REASON);
    }
    if let Some(blocks) = map.get_mut("harnesses").and_then(Value::as_object_mut) {
        for block in blocks.values_mut().filter_map(Value::as_object_mut) {
            if block.remove("memory").is_some() {
                push_drop(dropped, "memory", &tier.tier, USER_ONLY_REASON);
            }
        }
    }
    normalize_config_for_harness(&mut map, harness);

    let security_errors = malformed_security_config_errors(&map, harness);
    if !security_errors.is_empty() {
        return Err(security_errors);
    }
    if let Some(path) = feature_config::settings_shape::null_path(&map) {
        return Err(vec![format!("invalid_config_null:{path}")]);
    }
    if tier.tier == "user" {
        let malformed_choice = |block: &Map<String, Value>| {
            block
                .get("storage")
                .and_then(|storage| storage.get("cache_dir"))
                .filter(|choice| choice.is_object())
                .is_some_and(|choice| {
                    serde_json::from_value::<RawCacheDir>(choice.clone()).is_err()
                })
        };
        if malformed_choice(&map)
            || map
                .get("harnesses")
                .and_then(Value::as_object)
                .is_some_and(|blocks| {
                    blocks
                        .values()
                        .filter_map(Value::as_object)
                        .any(malformed_choice)
                })
        {
            return Err(vec!["invalid_cache_config: storage.cache_dir".into()]);
        }
    }

    let raw = match serde_json::from_value::<RawAftConfig>(Value::Object(map.clone())) {
        Ok(config) => config,
        Err(_) => parse_config_partially(map, tier, warnings),
    };
    Ok((raw, translation))
}

// Mirror the host-owned lists in packages/aft-bridge/src/config-keys.ts.
const OPENCODE_ONLY_CONFIG_KEYS: &[&str] = &["auto_update"];
const PI_ONLY_CONFIG_KEYS: &[&str] = &[];

fn harness_ignored_config_keys(harness: Option<&Harness>) -> &'static [&'static str] {
    match harness {
        Some(Harness::Pi) => OPENCODE_ONLY_CONFIG_KEYS,
        Some(Harness::Opencode) => PI_ONLY_CONFIG_KEYS,
        _ => &[],
    }
}

fn normalize_config_for_harness(map: &mut Map<String, Value>, harness: Option<&Harness>) {
    let ignored = harness_ignored_config_keys(harness);
    for key in ignored {
        map.remove(*key);
    }
    let Some(harness) = harness else { return };
    let Some(block) = map
        .get_mut("harnesses")
        .and_then(Value::as_object_mut)
        .and_then(|blocks| blocks.get_mut(&harness.wire_label()))
        .and_then(Value::as_object_mut)
    else {
        return;
    };
    // Remove ignored fields before validation so valid security settings in the
    // same active harness block are preserved.
    // Other harness blocks remain opaque, just as they do in the host plugins.
    for key in ignored {
        block.remove(*key);
    }
}

// `storage` is deliberately not listed: a malformed `storage.cache_dir` weakens
// no protection; it turns caches off (`cache_config_unknown`) and warns.
fn security_config_section(key: &str, harness: Option<&Harness>) -> bool {
    if harness_ignored_config_keys(harness).contains(&key) {
        return false;
    }
    matches!(
        key,
        "restrict_to_project_root"
            | "url_fetch_allow_private"
            | "sandbox"
            | "indexes"
            | "index"
            | "remote_exec"
            | "disabled_tools"
            | "bash"
            | "lsp"
            | "semantic"
            | "search"
            | "subc"
            | "opencode"
            | "github"
            | "gh_shim"
            | "auto_update"
    )
}

fn malformed_security_config_errors(
    map: &Map<String, Value>,
    harness: Option<&Harness>,
) -> Vec<String> {
    let mut errors = Vec::new();
    for (key, value) in map {
        if !security_config_section(key, harness) {
            continue;
        }
        let mut field = Map::new();
        field.insert(key.clone(), value.clone());
        if value.is_null() || serde_json::from_value::<RawAftConfig>(Value::Object(field)).is_err()
        {
            errors.push(format!("invalid_security_config:{key}"));
        }
    }
    if let Some(harness) = harness {
        let label = harness.wire_label();
        if let Some(blocks) = map.get("harnesses") {
            match blocks.as_object() {
                None => errors.push("invalid_security_config:harnesses".into()),
                Some(blocks) => {
                    if let Some(block) = blocks.get(&label) {
                        if let Some(block) = block.as_object() {
                            let mut block = block.clone();
                            block.remove("harnesses");
                            let invalid: Vec<_> = block
                                .iter()
                                .filter_map(|(key, value)| {
                                    let mut field = Map::new();
                                    field.insert(key.clone(), value.clone());
                                    (value.is_null()
                                        || serde_json::from_value::<RawAftConfig>(Value::Object(
                                            field,
                                        ))
                                        .is_err())
                                    .then_some(key)
                                })
                                .collect();
                            let invalid_security: Vec<_> = invalid
                                .iter()
                                .filter(|key| security_config_section(key, Some(harness)))
                                .collect();
                            if !invalid_security.is_empty() {
                                errors.extend(invalid_security.into_iter().map(|key| {
                                    format!("invalid_security_config:harnesses.{label}.{key}")
                                }));
                            } else if !invalid.is_empty()
                                && block
                                    .keys()
                                    .any(|key| security_config_section(key, Some(harness)))
                            {
                                // A strict harness parse would discard the whole block,
                                // including its otherwise-valid explicit hardening.
                                errors.push(format!("invalid_security_config:harnesses.{label}"));
                            }
                        } else {
                            errors.push(format!("invalid_security_config:harnesses.{label}"));
                        }
                    }
                }
            }
        }
    }
    errors.sort();
    errors.dedup();
    errors
}

fn parse_cache_dir(value: Value) -> serde_json::Result<RawCacheDir> {
    let canonical = feature_config::settings_shape::cache_dir_replacement(&value)
        .map_or(value, |(replacement, _)| replacement);
    serde_json::from_value(canonical)
}

fn merge_cache_dir(base: &mut Option<RawCacheDir>, next: RawCacheDir) {
    // When multiple user tiers are supplied, a path used to take precedence
    // over a null opt-out, and an omitted setting never hid either choice.
    if base.is_none()
        || matches!(next, RawCacheDir::Dir { .. })
        || (matches!(next, RawCacheDir::MainDisk {})
            && !matches!(base, Some(RawCacheDir::Dir { .. })))
    {
        *base = Some(next);
    }
}

/// Recognize storage-section typos without making unrelated user keys strict.
pub(crate) fn storage_like_key(key: &str, value: Option<&Value>) -> bool {
    // This is a distinct process-state field, not a misspelled cache selector.
    if key == "storage_dir" {
        return false;
    }
    let normalized: String = key
        .chars()
        .filter(char::is_ascii_alphanumeric)
        .map(|c| c.to_ascii_lowercase())
        .collect();
    if normalized.starts_with("storage") || matches!(normalized.as_str(), "cachedir" | "cacheroot")
    {
        return true;
    }
    if value
        .and_then(Value::as_object)
        .is_some_and(|fields| fields.contains_key("cache_dir"))
    {
        return true;
    }
    let target = b"storage";
    if normalized.len().abs_diff(target.len()) > 2 {
        return false;
    }
    let mut row: Vec<usize> = (0..=target.len()).collect();
    for (i, byte) in normalized.bytes().enumerate() {
        let mut next = vec![i + 1];
        for (j, expected) in target.iter().enumerate() {
            next.push(
                (row[j] + usize::from(byte != *expected))
                    .min(row[j + 1] + 1)
                    .min(next[j] + 1),
            );
        }
        row = next;
    }
    row[target.len()] <= 2
}

/// Why a user tier leaves its cache location unknown. Storage sections and
/// storage-like typos fail closed; unrelated unknown keys retain partial parsing.
pub fn cache_location_config_error(tier: &ConfigTier) -> Option<String> {
    let stripped = strip_jsonc(&tier.doc);
    let value = match serde_json::from_str::<Value>(&stripped) {
        Ok(value) => value,
        Err(error) => return Some(format!("{} does not parse: {error}", tier.source)),
    };
    let Value::Object(map) = value else {
        return Some(format!("{} is not a JSON object", tier.source));
    };
    if let Some(error) = feature_config::removed_config_key_errors(&map)
        .into_iter()
        .find(|error| error.contains("storage"))
    {
        return Some(format!(
            "{} has a removed storage setting: {error}",
            tier.source
        ));
    }
    let unknown_key = |map: &Map<String, Value>| -> Option<String> {
        let mut map = map.clone();
        feature_config::translate_document(&mut map, feature_config::DocumentTier::User);
        map.keys().find_map(|key| {
            // Validate the name independently of its value: an invalid known
            // setting must not hide a misspelled storage key later in the file.
            let field = Map::from_iter([(key.clone(), Value::Null)]);
            serde_json::from_value::<RawAftConfig>(Value::Object(field))
                .err()
                .map(|error| error.to_string())
                .filter(|error| {
                    error.starts_with("unknown field") && storage_like_key(key, map.get(key))
                })
        })
    };
    if let Some(error) = unknown_key(&map) {
        return Some(format!("{} has an invalid setting: {error}", tier.source));
    }
    // Stricter than the resolver's RawStorage: a misspelled key inside
    // storage (for example `cachedir`) would otherwise leave cache_dir unset
    // and quietly put caches back on the storage root.
    #[derive(Deserialize)]
    #[serde(deny_unknown_fields)]
    #[allow(dead_code)]
    struct StrictStorage {
        cache_dir: Option<RawCacheDir>,
    }
    let invalid_storage = |section: &Value| -> Option<String> {
        if section.is_null() {
            return None;
        }
        if let Some(key) = section
            .as_object()
            .and_then(|fields| fields.keys().find(|key| key.as_str() != "cache_dir"))
        {
            return Some(format!("unknown field `{key}`, expected `cache_dir`"));
        }
        let mut section = section.clone();
        if let Some(cache_dir) = section.get_mut("cache_dir") {
            if let Some((replacement, _)) =
                feature_config::settings_shape::cache_dir_replacement(cache_dir)
            {
                *cache_dir = replacement;
            }
        }
        serde_json::from_value::<StrictStorage>(section)
            .err()
            .map(|error| error.to_string())
    };
    if let Some(error) = map.get("storage").and_then(invalid_storage) {
        return Some(format!(
            "{} has an invalid storage section: {error}",
            tier.source
        ));
    }
    if let Some(Value::Object(harnesses)) = map.get("harnesses") {
        for (name, block) in harnesses {
            if let Some(error) = block.as_object().and_then(unknown_key) {
                return Some(format!(
                    "{} has an invalid harnesses.{name} setting: {error}",
                    tier.source
                ));
            }
            if let Some(error) = block.get("storage").and_then(invalid_storage) {
                return Some(format!(
                    "{} has an invalid harnesses.{name}.storage section: {error}",
                    tier.source
                ));
            }
        }
    }
    None
}

/// Return why a tier would be accepted only by the lenient resolver, or
/// `None` when it passes strict validation.
///
/// Initial configuration rejects malformed security-sensitive settings and
/// reports discarded nonsecurity settings. A live reload rejects every schema
/// error: a typo must not reset
/// a key (possibly a security key the harness block set) to its default while
/// the root stays bound, so the reload calls this first and keeps the last
/// valid configuration instead. Names retired in 0.62 or earlier are refused,
/// and the more recently retired keys are translated first, exactly as the
/// resolver translates them, so they never count as invalid here.
pub fn strict_tier_error(tier: &ConfigTier, harness: Option<&Harness>) -> Option<String> {
    let stripped = strip_jsonc(&tier.doc);
    let value = match serde_json::from_str::<Value>(&stripped) {
        Ok(value) => value,
        Err(error) => return Some(format!("{} does not parse: {error}", tier.source)),
    };
    let Value::Object(mut map) = value else {
        return Some(format!("{} is not a JSON object", tier.source));
    };
    // As in resolution, a long-retired name refuses only the user config.
    let removed = feature_config::removed_config_key_errors_for_file(&map, tier.tier == "user");
    if !removed.is_empty() {
        return Some(removed.join(", "));
    }
    let document_tier = if tier.tier == "user" {
        feature_config::DocumentTier::User
    } else {
        feature_config::DocumentTier::Project
    };
    feature_config::translate_document(&mut map, document_tier);
    normalize_config_for_harness(&mut map, harness);
    if let Some(path) = feature_config::settings_shape::null_path(&map) {
        return Some(format!("invalid_config_null:{path}"));
    }
    let raw = match serde_json::from_value::<RawAftConfig>(Value::Object(map)) {
        Ok(raw) => raw,
        Err(error) => {
            return Some(format!("{} has an invalid setting: {error}", tier.source));
        }
    };
    // A refused name rejects the candidate at either tier, whether or not a
    // project is trusted: a silently dropped variable is exactly the failure
    // mode this list exists to prevent.
    let tier_kind = if tier.tier == "user" {
        crate::bash_env::BashEnvTier::User
    } else {
        crate::bash_env::BashEnvTier::Project
    };
    // The block for the active harness is applied on top of this tier, so it
    // must be as valid as the tier itself. Blocks for other harnesses are
    // never applied here and stay unchecked, as at connect.
    let harness_context = harness.map(|harness| {
        let label = harness.wire_label();
        let block = raw
            .harnesses
            .as_ref()
            .and_then(|blocks| blocks.get(&label))
            .cloned();
        (label, block)
    });
    // A refusal written in the applied harness block is the one to report: it
    // names the block that actually carries the name.
    let harness_refusal = match harness_context.as_ref() {
        Some((label, Some(Value::Object(block)))) => {
            let mut block = block.clone();
            // A nested `harnesses` key is ignored with a warning at connect.
            block.remove("harnesses");
            match serde_json::from_value::<RawAftConfig>(Value::Object(block)) {
                Ok(parsed) => raw_bash_env_refusal(&parsed, tier, tier_kind, Some(label)),
                Err(_) => None,
            }
        }
        _ => None,
    };
    let base_refusal = raw_bash_env_refusal(&raw, tier, tier_kind, None);
    harness_refusal.or(base_refusal)
}

/// The refusal for a `bash.env` name the tier may not set. The message names
/// the key so the author can fix the file: this check runs for every tier and
/// whether or not the project is trusted.
fn refused_bash_env_error(
    tier: &ConfigTier,
    tier_kind: crate::bash_env::BashEnvTier,
    key: &str,
    harness_label: Option<&str>,
) -> String {
    let where_set = match harness_label {
        Some(label) => format!(" in harnesses.{label}"),
        None => String::new(),
    };
    let scope = match tier_kind {
        crate::bash_env::BashEnvTier::User => "cannot be configured",
        crate::bash_env::BashEnvTier::Project => {
            "cannot be configured by a project; set it in user config if you need it"
        }
    };
    format!(
        "{} has blocked bash.env key {key}{where_set}; environment startup hooks, lookup roots, interpreter injectors, Git redirection, AFT controls, sandbox controls and credentials {scope}",
        tier.source
    )
}

/// Refuse a `bash.env` name of the given tier (base block or active harness
/// block). Project values are validated even when the project is untrusted, so
/// a bad commit fails for its author at once rather than on the first machine
/// that trusts it.
fn raw_bash_env_refusal(
    raw: &RawAftConfig,
    tier: &ConfigTier,
    tier_kind: crate::bash_env::BashEnvTier,
    harness_label: Option<&str>,
) -> Option<String> {
    let env = match raw.bash.as_ref() {
        Some(features) => features.env.as_ref(),
        _ => None,
    };
    let found = crate::bash_env::first_refused_env_key(env?, tier_kind);
    let key = found?;
    Some(refused_bash_env_error(tier, tier_kind, key, harness_label))
}

fn parse_config_partially(
    raw_config: Map<String, Value>,
    tier: &ConfigTier,
    warnings: &mut Vec<ConfigWarning>,
) -> RawAftConfig {
    let mut partial = RawAftConfig::default();

    for (key, value) in raw_config {
        let mut one_field = Map::new();
        one_field.insert(key.clone(), value);
        if let Ok(section) = serde_json::from_value::<RawAftConfig>(Value::Object(one_field)) {
            merge_trusted_config(&mut partial, section);
        } else {
            warnings.push(ConfigWarning {
                code: "invalid_config_section",
                key: "config",
                tier: tier.tier.clone(),
                value: "[discarded]".into(),
                message: format!("Discarded invalid configuration section: {key}"),
            });
        }
    }

    partial
}

/// Apply one tier's harness block on top of its base and return the refusal
/// for a `bash.env` name the tier may not set in that block.
///
/// The block is checked before the project trust boundary strips its map: a
/// refused name must reject the candidate at the tier it was written at, and a
/// project harness block must not borrow the user tier's strength.
fn apply_harness_override(
    raw: &mut RawAftConfig,
    harness: Option<&Harness>,
    tier: &ConfigTier,
    trusted: bool,
    tier_kind: crate::bash_env::BashEnvTier,
    warnings: &mut Vec<ConfigWarning>,
    dropped: &mut Vec<DroppedKey>,
) -> Option<String> {
    let Some(overrides) = raw.harnesses.take() else {
        return None;
    };
    let Some(harness) = harness else {
        return None;
    };
    let key = harness.wire_label();
    let Some(value) = overrides.get(&key) else {
        return None;
    };
    let Value::Object(mut override_map) = value.clone() else {
        warnings.push(ConfigWarning {
            code: "invalid_harness_override",
            key: "harnesses",
            tier: tier.tier.clone(),
            value: key,
            message: "Ignoring non-object harness override; overrides must be config objects"
                .to_string(),
        });
        return None;
    };

    if override_map.remove("harnesses").is_some() {
        warnings.push(ConfigWarning {
            code: "nested_harnesses_ignored",
            key: "harnesses",
            tier: tier.tier.clone(),
            value: key.clone(),
            message: format!(
                "Ignoring nested harnesses in harnesses.{key}; harness overrides cannot recurse"
            ),
        });
    }

    normalize_config_for_harness(&mut override_map, Some(harness));

    // The block is refused at the tier it was written at, whether or not the
    // project is trusted, and before the trust boundary below strips the map.
    let refusal = serde_json::from_value::<RawAftConfig>(Value::Object(override_map.clone()))
        .ok()
        .and_then(|parsed| raw_bash_env_refusal(&parsed, tier, tier_kind, Some(&key)));

    match serde_json::from_value::<RawAftConfig>(Value::Object(override_map)) {
        Ok(mut override_config) => {
            if override_config
                .durability
                .take()
                .is_some_and(|durability| durability.macos_full_sync.is_some())
            {
                push_drop(
                    dropped,
                    "durability.macos_full_sync",
                    &tier.tier,
                    "sync policy is process-wide; only the user-tier base may set it",
                );
            }
            if override_config
                .storage
                .take()
                .is_some_and(|storage| storage.cache_dir.is_some())
            {
                push_drop(
                    dropped,
                    "storage.cache_dir",
                    &tier.tier,
                    "cache location is storage-wide; only the user-tier base may set it",
                );
            }
            // A project harness block, like the project base, may only turn an
            // index off; a user harness block overrides the user base.
            let override_indexes = override_config.indexes.take();
            merge_trusted_config(raw, override_config);
            raw.indexes = merge_indexes(raw.indexes, override_indexes, !trusted);
        }
        Err(_) => warnings.push(ConfigWarning {
            code: "invalid_harness_override",
            key: "harnesses",
            tier: tier.tier.clone(),
            value: key,
            message: "Ignoring invalid harness override; it must use the root config shape"
                .to_string(),
        }),
    }
    refusal
}

fn merge_trusted_config(base: &mut RawAftConfig, override_config: RawAftConfig) {
    if override_config.shell.is_some() {
        base.shell = override_config.shell.clone();
    }
    if let Some(value) = override_config
        .durability
        .and_then(|durability| durability.macos_full_sync)
    {
        base.durability
            .get_or_insert_with(RawDurability::default)
            .macos_full_sync = Some(value);
    }
    if let Some(choice) = override_config
        .storage
        .and_then(|storage| storage.cache_dir)
    {
        merge_cache_dir(
            &mut base
                .storage
                .get_or_insert_with(RawStorage::default)
                .cache_dir,
            choice,
        );
    }
    if override_config.harnesses.is_some() {
        base.harnesses = override_config.harnesses.clone();
    }
    if override_config.schema.is_some() {
        base.schema = override_config.schema;
    }
    if override_config.edit_mode.is_some() {
        base.edit_mode = override_config.edit_mode;
    }
    if override_config.format_on_edit.is_some() {
        base.format_on_edit = override_config.format_on_edit;
    }
    if override_config.revision_reads.is_some() {
        base.revision_reads = override_config.revision_reads;
    }
    if override_config.formatter_timeout_secs.is_some() {
        base.formatter_timeout_secs = override_config.formatter_timeout_secs;
    }
    if override_config.type_checker_timeout_secs.is_some() {
        base.type_checker_timeout_secs = override_config.type_checker_timeout_secs;
    }
    if override_config.validate_on_edit.is_some() {
        base.validate_on_edit = override_config.validate_on_edit;
    }
    if override_config.formatter.is_some() {
        base.formatter = override_config.formatter;
    }
    if override_config.checker.is_some() {
        base.checker = override_config.checker;
    }
    if override_config.configure_warnings_delivery.is_some() {
        base.configure_warnings_delivery = override_config.configure_warnings_delivery;
    }
    // Disables only accumulate: a harness block adds to its base list and can
    // never re-enable a base disable.
    union_disabled_tools(&mut base.disabled_tools, override_config.disabled_tools);
    if override_config.restrict_to_project_root.is_some() {
        base.restrict_to_project_root = override_config.restrict_to_project_root;
    }
    base.indexes = merge_indexes(base.indexes, override_config.indexes, false);
    if override_config.index.is_some() {
        base.index = override_config.index;
    }
    if override_config.memory.is_some() {
        base.memory = override_config.memory;
    }
    if override_config.inspect.is_some() {
        base.inspect = override_config.inspect;
    }
    if override_config.idle.is_some() {
        // Per key, so a harness block that sets one idle window keeps the
        // other window from the file's base block.
        base.idle = merge_idle_config(base.idle.take(), override_config.idle);
    }
    if override_config.backup.is_some() {
        base.backup = override_config.backup;
    }
    if override_config.github.is_some() {
        base.github = override_config.github;
    }
    if override_config.gh_shim.is_some() {
        base.gh_shim = override_config.gh_shim;
    }
    if override_config.git.is_some() {
        base.git = override_config.git;
    }
    if override_config.pi.is_some() {
        base.pi = override_config.pi;
    }
    if let Some(next) = override_config.sandbox {
        let sandbox = base.sandbox.get_or_insert_with(RawSandbox::default);
        if let Some(next) = next.profile {
            let profile = sandbox.profile.get_or_insert_with(RawSandboxRoles::default);
            if next.worker.is_some() {
                profile.worker = next.worker;
            }
            if next.head.is_some() {
                profile.head = next.head;
            }
        }
        if next.write_allow.is_some() {
            sandbox.write_allow = next.write_allow;
        }
        if next.read_deny.is_some() {
            sandbox.read_deny = next.read_deny;
        }
    }
    if override_config.bash.is_some() {
        // A harness block merges its `bash.env` names into the base block
        // instead of replacing it, so adding one name under
        // `harnesses.<name>` cannot silently drop every base name. A project
        // harness block is only looked at after this tier's own trust boundary,
        // so a strength reserved for the user tier cannot be borrowed through
        // `harnesses`. A name the boundary strips is still refused by
        // `raw_bash_env_refusal` before this merge.
        base.bash = merge_bash_config(base.bash.take(), override_config.bash);
    }
    if override_config.experimental.is_some() {
        base.experimental = override_config.experimental;
    }
    if override_config.lsp.is_some() {
        base.lsp = override_config.lsp;
    }
    if override_config.url_fetch_allow_private.is_some() {
        base.url_fetch_allow_private = override_config.url_fetch_allow_private;
    }
    if override_config.semantic.is_some() {
        base.semantic = override_config.semantic;
    }
    if override_config.search.is_some() {
        base.search = override_config.search;
    }
    if override_config.auto_update.is_some() {
        base.auto_update = override_config.auto_update;
    }
    if override_config.bridge.is_some() {
        base.bridge = override_config.bridge;
    }
    if override_config.subc.is_some() {
        base.subc = override_config.subc;
    }

    if let Some(remote_exec) = override_config.remote_exec {
        let merged = base.remote_exec.get_or_insert_with(RawRemoteExec::default);
        if remote_exec.enabled.is_some() {
            merged.enabled = remote_exec.enabled;
        }
        if remote_exec.default_demand.is_some() {
            merged.default_demand = remote_exec.default_demand;
        }
    }
}

fn merge_project_config(base: &mut RawAftConfig, project: RawAftConfig) {
    // Project-safe shallow top-level fields.
    if project.edit_mode.is_some() {
        base.edit_mode = project.edit_mode;
    }
    if project.format_on_edit.is_some() {
        base.format_on_edit = project.format_on_edit;
    }
    // Reading git objects of the session's own repository grants nothing the
    // read permission rules do not already allow, so a project may opt in.
    if project.revision_reads.is_some() {
        base.revision_reads = project.revision_reads;
    }
    if project.validate_on_edit.is_some() {
        base.validate_on_edit = project.validate_on_edit;
    }
    if project.configure_warnings_delivery.is_some() {
        base.configure_warnings_delivery = project.configure_warnings_delivery;
    }
    // A project may switch an index off but never back on.
    base.indexes = merge_indexes(base.indexes, project.indexes, true);

    merge_formatter_map(&mut base.formatter, project.formatter);
    merge_checker_map(&mut base.checker, project.checker);
    merge_disabled_tools(&mut base.disabled_tools, project.disabled_tools);
    base.semantic = merge_semantic_config(base.semantic.take(), project.semantic);
    base.search = merge_project_search(base.search.take(), project.search);
    base.lsp = merge_lsp_config(base.lsp.take(), project.lsp);
    base.experimental = merge_experimental_config(base.experimental.take(), project.experimental);
    let ceiling = base.bash.as_ref().and_then(|bash| bash.memory_limit_mib);
    let mut project_bash = project_safe_bash(project.bash);
    if let Some(features) = &mut project_bash {
        features.memory_limit_mib = match (ceiling, features.memory_limit_mib) {
            (Some(user), Some(project)) => Some(user.min(project)),
            (_, value) => value,
        };
    }
    base.bash = merge_bash_config(base.bash.take(), project_bash);
    base.inspect = merge_inspect_config(base.inspect.take(), project.inspect);
    base.idle = merge_idle_config(base.idle.take(), project.idle);
    base.backup = merge_project_backup_config(base.backup.take(), project.backup);
    if project.git.is_some() {
        base.git = project.git;
    }
    base.pi = merge_pi_config(base.pi.take(), project.pi);
    base.sandbox = merge_project_sandbox(base.sandbox.take(), project.sandbox);
    // A project may turn remote runs off for itself, never on: running a
    // repository's commands on a shared build server is the user's decision.
    if project
        .remote_exec
        .as_ref()
        .is_some_and(|remote| remote.enabled == Some(false))
    {
        base.remote_exec_project_off = true;
    }
}

/// A project may set `search.rerank.backend` to `"off"` and nothing else;
/// `record_project_drops` reports every other value it supplied.
fn merge_project_search(base: Option<RawSearch>, project: Option<RawSearch>) -> Option<RawSearch> {
    let disables = project
        .and_then(|search| search.rerank)
        .is_some_and(|rerank| rerank.backend == Some(RerankBackendKind::Off));
    if !disables {
        return base;
    }
    let mut search = base.unwrap_or_default();
    search.rerank.get_or_insert_with(RawRerank::default).backend = Some(RerankBackendKind::Off);
    Some(search)
}

/// Carry the parsed `search` block into the runtime config unchanged. An
/// all-empty `rerank` object is kept as absent so it serializes the same as no
/// block at all.
fn resolve_search_config(raw: Option<&RawSearch>) -> SearchConfig {
    let rerank = raw
        .and_then(|search| search.rerank.as_ref())
        .map(|rerank| RerankConfig {
            backend: rerank.backend,
            model: rerank.model.clone(),
            endpoint: rerank.endpoint.clone(),
            api_key_env: rerank.api_key_env.clone(),
            top_n: rerank.top_n,
            timeout_ms: rerank.timeout_ms,
        });
    SearchConfig {
        rerank: rerank.filter(|rerank| *rerank != RerankConfig::default()),
    }
}

fn merge_project_backup_config(
    base: Option<RawBackup>,
    project: Option<RawBackup>,
) -> Option<RawBackup> {
    let Some(project_max_file_size) = project.and_then(|backup| backup.max_file_size) else {
        return base;
    };
    let mut backup = base.unwrap_or_default();
    backup.max_file_size = Some(project_max_file_size);
    Some(backup)
}

fn merge_project_sandbox(
    base: Option<RawSandbox>,
    project: Option<RawSandbox>,
) -> Option<RawSandbox> {
    let Some(project) = project else {
        return base;
    };
    let mut sandbox = base.unwrap_or_default();
    if let Some(project_denies) = project.read_deny {
        let denies = sandbox.read_deny.get_or_insert_with(Vec::new);
        for path in project_denies {
            if !denies.contains(&path) {
                denies.push(path);
            }
        }
    }
    if let Some(next) = project.profile {
        let floor = resolve_sandbox_config(Some(&sandbox)).profile;
        let profile = sandbox.profile.get_or_insert_with(RawSandboxRoles::default);
        if let Some(worker) = next.worker.filter(|value| *value >= floor.worker) {
            profile.worker = Some(worker);
        }
        if let Some(head) = next.head.filter(|value| *value >= floor.head) {
            profile.head = Some(head);
        }
    }
    (sandbox.profile.is_some() || sandbox.write_allow.is_some() || sandbox.read_deny.is_some())
        .then_some(sandbox)
}

fn merge_formatter_map(
    base: &mut Option<HashMap<String, RawFormatter>>,
    override_map: Option<HashMap<String, RawFormatter>>,
) {
    let Some(override_map) = override_map else {
        return;
    };
    if override_map.is_empty() && base.as_ref().is_none_or(HashMap::is_empty) {
        return;
    }
    let target = base.get_or_insert_with(HashMap::new);
    target.extend(override_map);
}

fn merge_checker_map(
    base: &mut Option<HashMap<String, RawChecker>>,
    override_map: Option<HashMap<String, RawChecker>>,
) {
    let Some(override_map) = override_map else {
        return;
    };
    if override_map.is_empty() && base.as_ref().is_none_or(HashMap::is_empty) {
        return;
    }
    let target = base.get_or_insert_with(HashMap::new);
    target.extend(override_map);
}

fn merge_disabled_tools(base: &mut Option<Vec<String>>, override_tools: Option<Vec<String>>) {
    // Project disables of protected slots (aft_safety and the seven host tool
    // names) are ignored; `record_project_drops` reports them.
    union_disabled_tools(
        base,
        override_tools.map(|tools| {
            tools
                .into_iter()
                .filter(|tool| !feature_config::is_project_protected_tool(tool))
                .collect()
        }),
    );
}

/// Union two raw disabled lists, preserving presence: an explicit empty list
/// on either side yields an explicit (possibly empty) result.
fn union_disabled_tools(base: &mut Option<Vec<String>>, override_tools: Option<Vec<String>>) {
    let Some(override_tools) = override_tools else {
        return;
    };
    let mut merged = base.take().unwrap_or_default();
    merged.extend(override_tools);
    *base = Some(feature_config::normalize_tool_list(merged));
}

/// Merge index switches. Trusted overrides replace each supplied leaf;
/// restricted (project) overrides can only turn a leaf off.
fn merge_indexes(
    base: Option<RawIndexes>,
    override_indexes: Option<RawIndexes>,
    restricted: bool,
) -> Option<RawIndexes> {
    let Some(override_indexes) = override_indexes else {
        return base;
    };
    let mut merged = base.unwrap_or_default();
    let apply = |slot: &mut Option<bool>, value: Option<bool>| match value {
        Some(false) => *slot = Some(false),
        Some(true) if !restricted => *slot = Some(true),
        _ => {}
    };
    apply(&mut merged.trigram, override_indexes.trigram);
    apply(&mut merged.semantic, override_indexes.semantic);
    apply(&mut merged.callgraph, override_indexes.callgraph);
    Some(merged)
}

fn merge_semantic_config(
    base: Option<RawSemantic>,
    override_semantic: Option<RawSemantic>,
) -> Option<RawSemantic> {
    let mut semantic = base.unwrap_or(RawSemantic {
        backend: None,
        model: None,
        base_url: None,
        api_key_env: None,
        timeout_ms: None,
        query_timeout_ms: None,
        query_instruction: None,
        max_batch_size: None,
        max_input_tokens: None,
        max_files: None,
    });

    if let Some(project) = override_semantic {
        if project.model.is_some() {
            semantic.model = project.model;
        }
        if project.timeout_ms.is_some() {
            semantic.timeout_ms = project.timeout_ms;
        }
        if project.query_instruction.is_some() {
            semantic.query_instruction = project.query_instruction;
        }
        if project.max_batch_size.is_some() {
            semantic.max_batch_size = project.max_batch_size;
        }
        if project.max_input_tokens.is_some() {
            semantic.max_input_tokens = project.max_input_tokens;
        }
        if project.max_files.is_some() {
            semantic.max_files = project.max_files;
        }
    }

    (!semantic.is_empty()).then_some(semantic)
}

fn merge_lsp_config(base: Option<RawLsp>, override_lsp: Option<RawLsp>) -> Option<RawLsp> {
    let mut lsp = base.unwrap_or_default();

    if let Some(project) = override_lsp {
        if let Some(max_servers) = project.max_servers {
            if max_servers <= lsp.max_servers.unwrap_or(8) {
                lsp.max_servers = Some(max_servers);
            }
        }
        if let Some(idle) = project.idle_minutes {
            if lsp_idle_minutes(Some(idle)) <= lsp_idle_minutes(lsp.idle_minutes) {
                lsp.idle_minutes = Some(idle);
            }
        }
        if project.idle_shutdown == Some(true) {
            lsp.idle_shutdown = Some(true);
        }
        if project.python.is_some() {
            lsp.python = project.python;
        }
        if project.diagnostics_on_edit.is_some() {
            lsp.diagnostics_on_edit = project.diagnostics_on_edit;
        }
    }

    (!lsp.is_empty()).then_some(lsp)
}

fn merge_experimental_config(
    base: Option<RawExperimental>,
    override_experimental: Option<RawExperimental>,
) -> Option<RawExperimental> {
    let Some(override_experimental) = override_experimental else {
        return base;
    };

    let mut experimental = base.unwrap_or_default();
    experimental.lsp_ty = override_experimental.lsp_ty.or(experimental.lsp_ty);

    (!experimental.is_empty()).then_some(experimental)
}

fn project_safe_bash(project: Option<RawBashFeatures>) -> Option<RawBashFeatures> {
    project.map(|mut features| {
        features.changed_files = features
            .changed_files
            .filter(|mode| *mode == crate::config::BashChangedFiles::Off);
        features.linux_scope = None;
        features.linux_scope_max_runtime_secs = None;
        // Project environment entries retain their own tier through resolution.
        features.project_env = features.env.take();
        features.runon_env = None;
        features.disclaim_privacy = features.disclaim_privacy.filter(|value| *value);
        features
    })
}

#[cfg(any(test, feature = "test-support"))]
#[test]
fn retired_runon_gate_preserves_explicit_user_choice_and_project_cannot_change_it() {
    assert!(!resolve_config(&[]).config.remote_exec.enabled);
    for (legacy, expected) in [(Some(false), false), (Some(true), true), (None, true)] {
        let mut user = serde_json::json!({"remote_exec":{"enabled":true}});
        if let Some(legacy) = legacy {
            user["bash"] = serde_json::json!({"runon_enabled":legacy});
        }
        let result = resolve_config(&[
            ConfigTier {
                tier: "user".into(),
                source: "user.jsonc".into(),
                doc: user.to_string(),
            },
            ConfigTier {
                tier: "project".into(),
                source: "project.jsonc".into(),
                doc: r#"{"bash":{"runon_enabled":false}}"#.into(),
            },
        ]);
        assert!(result.errors.is_empty(), "{:?}", result.errors);
        assert_eq!(result.config.remote_exec.enabled, expected);
    }
}

#[cfg(any(test, feature = "test-support"))]
#[test]
fn macos_full_sync_is_user_only_and_defaults_off() {
    let defaults = resolve_config(&[]);
    assert!(!defaults.config.durability.macos_full_sync);
    assert!(!Config::default().durability.macos_full_sync);
    for enabled in [false, true] {
        let result = resolve_config(&[
            ConfigTier {
                tier: "user".into(),
                source: "user.jsonc".into(),
                doc: format!("{{\"durability\":{{\"macos_full_sync\":{enabled}}}}}"),
            },
            ConfigTier {
                tier: "project".into(),
                source: "project.jsonc".into(),
                doc: format!("{{\"durability\":{{\"macos_full_sync\":{}}}}}", !enabled),
            },
        ]);
        assert!(result.errors.is_empty(), "{:?}", result.errors);
        assert_eq!(result.config.durability.macos_full_sync, enabled);
        assert!(result
            .dropped
            .iter()
            .any(|drop| { drop.key == "durability.macos_full_sync" && drop.tier == "project" }));
    }
    let project = resolve_config(&[ConfigTier {
        tier: "project".into(),
        source: "project.jsonc".into(),
        doc: r#"{"durability":{"macos_full_sync":true}}"#.into(),
    }]);
    assert!(!project.config.durability.macos_full_sync);
    assert_eq!(project.dropped[0].key, "durability.macos_full_sync");
}

#[cfg(test)]
#[test]
fn macos_full_sync_ignores_all_harness_overrides() {
    for harness in [Harness::Opencode, Harness::Pi] {
        for base in [false, true] {
            let key = harness.wire_label();
            let result = resolve_config_for_harness(
                &[
                    ConfigTier {
                        tier: "user".into(),
                        source: "user.jsonc".into(),
                        doc: serde_json::json!({
                            "durability": {"macos_full_sync": base},
                            "harnesses": {(key.clone()): {"durability": {"macos_full_sync": !base}}}
                        })
                        .to_string(),
                    },
                    ConfigTier {
                        tier: "project".into(),
                        source: "project.jsonc".into(),
                        doc: serde_json::json!({
                            "harnesses": {(key.clone()): {"durability": {"macos_full_sync": !base}}}
                        })
                        .to_string(),
                    },
                ],
                Some(&harness),
            );
            assert!(result.errors.is_empty(), "{:?}", result.errors);
            assert_eq!(result.config.durability.macos_full_sync, base);
            for tier in ["user", "project"] {
                assert!(result
                    .dropped
                    .iter()
                    .any(|drop| { drop.key == "durability.macos_full_sync" && drop.tier == tier }));
            }
        }
    }
}

#[cfg(test)]
#[test]
fn bash_memory_limit_parses_and_project_cannot_raise_it() {
    let resolve = |user: &str, project: &str| {
        serde_json::to_value(
            resolve_config(&[
                ConfigTier {
                    tier: "user".into(),
                    source: "user.jsonc".into(),
                    doc: user.into(),
                },
                ConfigTier {
                    tier: "project".into(),
                    source: "project.jsonc".into(),
                    doc: project.into(),
                },
            ])
            .config
            .bash,
        )
        .unwrap()["memory_limit_mib"]
            .clone()
    };
    assert_eq!(
        resolve(r#"{"bash":{"memory_limit_mib":64}}"#, "{}"),
        serde_json::json!(64)
    );
    assert_eq!(
        resolve(
            r#"{"bash":{"memory_limit_mib":64}}"#,
            r#"{"bash":{"memory_limit_mib":128}}"#
        ),
        serde_json::json!(64)
    );
    assert_eq!(
        resolve(
            r#"{"bash":{"memory_limit_mib":64}}"#,
            r#"{"bash":{"memory_limit_mib":32}}"#
        ),
        serde_json::json!(32)
    );
    assert_eq!(
        resolve(r#"{"bash":{"memory_limit_mib":64}}"#, r#"{"bash":false}"#),
        serde_json::json!(64)
    );
}

#[cfg(any(test, feature = "test-support"))]
#[test]
fn bash_memory_limit_rejects_invalid_values() {
    assert!(resolve_config(&[]).config.bash.memory_limit_mib.is_none());
    for value in ["0", "-1", "1.5", "true", "\"4GB\"", "4294967296"] {
        let doc = format!("{{\"bash\":{{\"memory_limit_mib\":{value}}}}}");
        assert!(serde_json::from_str::<RawAftConfig>(&doc).is_err(), "{doc}");
    }
}

fn merge_bash_config(
    base: Option<RawBashFeatures>,
    override_bash: Option<RawBashFeatures>,
) -> Option<RawBashFeatures> {
    match (base, override_bash) {
        (None, None) => None,
        (None, Some(override_bash)) => Some(override_bash),
        (Some(base), None) => Some(base),
        (Some(base), Some(override_bash)) => {
            let override_features = override_bash;
            Some(RawBashFeatures {
                changed_files: override_features.changed_files.or(base.changed_files),
                enabled: override_features.enabled.or(base.enabled),
                rewrite: override_features.rewrite.or(base.rewrite),
                compress: override_features.compress.or(base.compress),
                background: override_features.background.or(base.background),
                host_fallback: override_features.host_fallback.or(base.host_fallback),
                subagent_background: override_features
                    .subagent_background
                    .or(base.subagent_background),
                detach_on_user_message: override_features
                    .detach_on_user_message
                    .or(base.detach_on_user_message),
                db_schema_hints: override_features.db_schema_hints.or(base.db_schema_hints),
                long_running_reminder_enabled: override_features
                    .long_running_reminder_enabled
                    .or(base.long_running_reminder_enabled),
                long_running_reminder_interval_ms: override_features
                    .long_running_reminder_interval_ms
                    .or(base.long_running_reminder_interval_ms),
                foreground_wait_window_ms: override_features
                    .foreground_wait_window_ms
                    .or(base.foreground_wait_window_ms),
                watch_sync_max_ms: override_features
                    .watch_sync_max_ms
                    .or(base.watch_sync_max_ms),
                worker_wait_max_ms: override_features
                    .worker_wait_max_ms
                    .or(base.worker_wait_max_ms),
                linux_scope: override_features.linux_scope.or(base.linux_scope),
                linux_scope_max_runtime_secs: override_features
                    .linux_scope_max_runtime_secs
                    .or(base.linux_scope_max_runtime_secs),
                memory_limit_mib: override_features.memory_limit_mib.or(base.memory_limit_mib),
                disclaim_privacy: override_features.disclaim_privacy.or(base.disclaim_privacy),
                powershell_tool: override_features.powershell_tool.or(base.powershell_tool),
                env: merge_env_maps(base.env, override_features.env),
                project_env: merge_env_maps(base.project_env, override_features.project_env),
                runon_env: override_features.runon_env.or(base.runon_env),
            })
        }
    }
}

/// Merge two `bash.env` maps by name: the override adds or replaces single
/// names and never removes a base name.
fn merge_env_maps(
    base: Option<BTreeMap<String, String>>,
    override_map: Option<BTreeMap<String, String>>,
) -> Option<BTreeMap<String, String>> {
    match (base, override_map) {
        (None, None) => None,
        (Some(base), None) => Some(base),
        (None, Some(override_map)) => Some(override_map),
        (Some(mut base), Some(override_map)) => {
            base.extend(override_map);
            Some(base)
        }
    }
}

fn merge_idle_config(base: Option<RawIdle>, override_idle: Option<RawIdle>) -> Option<RawIdle> {
    let Some(override_idle) = override_idle else {
        return base;
    };
    let mut idle = base.unwrap_or_default();
    if override_idle.root_ttl_minutes.is_some() {
        idle.root_ttl_minutes = override_idle.root_ttl_minutes;
    }
    if override_idle.checkout_hours.is_some() {
        idle.checkout_hours = override_idle.checkout_hours;
    }
    (!idle.is_empty()).then_some(idle)
}

fn merge_inspect_config(
    base: Option<RawInspect>,
    override_inspect: Option<RawInspect>,
) -> Option<RawInspect> {
    let Some(override_inspect) = override_inspect else {
        return base;
    };

    let mut inspect = base.unwrap_or_default();
    inspect.enabled = override_inspect.enabled.or(inspect.enabled);
    if let Some(project_timeout) = override_inspect.diagnostics_timeout_ms {
        // A project may ask for more time, but it must not silently shrink another
        // consumer's diagnostic completeness by reducing the user's effective wait.
        inspect.diagnostics_timeout_ms = Some(
            project_timeout.max(
                inspect
                    .diagnostics_timeout_ms
                    .unwrap_or(DEFAULT_INSPECT_DIAGNOSTICS_TIMEOUT_MS),
            ),
        );
    }
    inspect.tier2_pass_timeout_ms = override_inspect
        .tier2_pass_timeout_ms
        .or(inspect.tier2_pass_timeout_ms);
    if let Some(project) = override_inspect.categories {
        let categories = inspect.categories.get_or_insert_with(BTreeMap::new);
        for (key, enabled) in project {
            let user_enabled = categories.get(&key).copied().unwrap_or(true);
            categories.insert(key, enabled && user_enabled);
        }
    }
    inspect.duplicates = merge_inspect_duplicates(inspect.duplicates, override_inspect.duplicates);

    (!inspect.is_empty()).then_some(inspect)
}

/// Merge a project tier's `pi` block. `external_access_ask: false` is ignored
/// there: a repository must not silence a protection the user has, so a
/// project may only turn the outside-access prompt on. `record_project_drops`
/// reports the ignored value.
fn merge_pi_config(base: Option<RawPi>, override_pi: Option<RawPi>) -> Option<RawPi> {
    let Some(override_pi) = override_pi else {
        return base;
    };

    let mut pi = base.unwrap_or_default();
    pi.tool_presentation = override_pi.tool_presentation.or(pi.tool_presentation);
    pi.external_access_ask = override_pi
        .external_access_ask
        .filter(|ask| *ask)
        .or(pi.external_access_ask);
    (!pi.is_empty()).then_some(pi)
}

fn merge_inspect_duplicates(
    base: Option<RawInspectDuplicates>,
    override_duplicates: Option<RawInspectDuplicates>,
) -> Option<RawInspectDuplicates> {
    let Some(override_duplicates) = override_duplicates else {
        return base;
    };

    let mut duplicates = base.unwrap_or_default();
    duplicates.expected_mirrors = override_duplicates
        .expected_mirrors
        .or(duplicates.expected_mirrors);

    (!duplicates.is_empty()).then_some(duplicates)
}

/// Resource settings are ordered by cost: a shorter idle window or an off
/// category tightens the user's budget. A project cannot increase that budget.
fn record_resource_loosening(
    base: &RawAftConfig,
    project: &RawAftConfig,
    tier: &str,
    dropped: &mut Vec<DroppedKey>,
) {
    let floor = resolve_sandbox_config(base.sandbox.as_ref()).profile;
    if let Some(profile) = project
        .sandbox
        .as_ref()
        .and_then(|sandbox| sandbox.profile.as_ref())
    {
        for (role, next, floor) in [
            ("worker", profile.worker, floor.worker),
            ("head", profile.head, floor.head),
        ] {
            if next.is_some_and(|next| next < floor) {
                push_drop(
                    dropped,
                    &format!("sandbox.profile.{role}"),
                    tier,
                    "projects may only select a stricter sandbox profile",
                );
            }
        }
    }
    const REASON: &str = "resource: project settings may only tighten the user budget";
    if let Some(next) = project.lsp.as_ref().and_then(|lsp| lsp.max_servers) {
        let floor = base
            .lsp
            .as_ref()
            .and_then(|lsp| lsp.max_servers)
            .unwrap_or(8);
        if next > floor {
            push_drop(dropped, "lsp.max_servers", tier, REASON);
        }
    }
    let cap = |raw: &RawAftConfig| raw.bash.as_ref().and_then(|bash| bash.memory_limit_mib);
    if let (Some(user), Some(project)) = (cap(base), cap(project)) {
        if project > user {
            push_drop(dropped, "bash.memory_limit_mib", tier, REASON);
        }
    }
    if let Some(next) = project.lsp.as_ref().and_then(|lsp| lsp.idle_minutes) {
        let floor = base.lsp.as_ref().and_then(|lsp| lsp.idle_minutes);
        if lsp_idle_minutes(Some(next)) > lsp_idle_minutes(floor) {
            push_drop(dropped, "lsp.idle_minutes", tier, REASON);
        }
    }
    if project.lsp.as_ref().and_then(|lsp| lsp.idle_shutdown) == Some(false)
        && base.lsp.as_ref().and_then(|lsp| lsp.idle_shutdown) != Some(false)
    {
        push_drop(dropped, "lsp.idle_shutdown", tier, REASON);
    }
    if let Some(categories) = project
        .inspect
        .as_ref()
        .and_then(|inspect| inspect.categories.as_ref())
    {
        for (key, enabled) in categories {
            let floor = base
                .inspect
                .as_ref()
                .and_then(|inspect| inspect.categories.as_ref())
                .and_then(|categories| categories.get(key))
                .copied()
                .unwrap_or(true);
            if *enabled && !floor {
                push_drop(dropped, &format!("inspect.categories.{key}"), tier, REASON);
            }
        }
    }
}

fn record_project_drops(raw: &RawAftConfig, tier: &str, dropped: &mut Vec<DroppedKey>) {
    if raw
        .shell
        .as_ref()
        .is_some_and(|shell| shell.env_provider.is_some())
    {
        push_drop(dropped, "shell.env_provider", tier, USER_ONLY_REASON);
    }
    if raw
        .durability
        .as_ref()
        .is_some_and(|durability| durability.macos_full_sync.is_some())
    {
        push_drop(
            dropped,
            "durability.macos_full_sync",
            tier,
            USER_ONLY_REASON,
        );
    }
    if raw
        .storage
        .as_ref()
        .is_some_and(|storage| storage.cache_dir.is_some())
    {
        push_drop(dropped, "storage.cache_dir", tier, USER_ONLY_REASON);
    }
    if matches!(&raw.bash, Some(features) if features.disclaim_privacy == Some(false)) {
        push_drop(
            dropped,
            "bash.disclaim_privacy",
            tier,
            "projects may only enable privacy disclaiming",
        );
    }
    // A project's own `bash.env` is not dropped: it is validated and carried in
    // `project_env`, then applied only while the project is trusted.
    if matches!(&raw.bash, Some(features) if features.runon_env.is_some()) {
        push_drop(dropped, "bash.runon_env", tier, USER_ONLY_REASON);
    }
    if raw.restrict_to_project_root.is_some() {
        push_drop(dropped, "restrict_to_project_root", tier, USER_ONLY_REASON);
    }
    if raw.url_fetch_allow_private.is_some() {
        push_drop(dropped, "url_fetch_allow_private", tier, USER_ONLY_REASON);
    }
    if raw.formatter_timeout_secs.is_some() {
        push_drop(dropped, "formatter_timeout_secs", tier, USER_ONLY_REASON);
    }
    if raw.type_checker_timeout_secs.is_some() {
        push_drop(dropped, "type_checker_timeout_secs", tier, USER_ONLY_REASON);
    }
    if raw.auto_update.is_some() {
        push_drop(dropped, "auto_update", tier, USER_ONLY_REASON);
    }
    if raw.bridge.is_some() {
        push_drop(dropped, "bridge", tier, USER_ONLY_REASON);
    }
    if raw.subc.is_some() {
        push_drop(dropped, "subc", tier, USER_ONLY_REASON);
    }
    if raw
        .pi
        .as_ref()
        .is_some_and(|pi| pi.external_access_ask == Some(false))
    {
        push_drop(
            dropped,
            "pi.external_access_ask",
            tier,
            "security: a project config may only turn the outside-access prompt on",
        );
    }

    if raw
        .backup
        .as_ref()
        .is_some_and(|backup| backup.enabled.is_some() || backup.max_depth.is_some())
    {
        push_drop(dropped, "backup", tier, USER_ONLY_REASON);
    }
    if raw.github.is_some() {
        push_drop(dropped, "github", tier, USER_ONLY_REASON);
    }
    if raw.gh_shim.is_some() {
        push_drop(dropped, "gh_shim", tier, USER_ONLY_REASON);
    }
    if let Some(remote_exec) = &raw.remote_exec {
        if remote_exec.enabled == Some(true) {
            push_drop(
                dropped,
                "remote_exec.enabled",
                tier,
                REMOTE_EXEC_PROJECT_REASON,
            );
        }
        if remote_exec.default_demand.is_some() {
            push_drop(
                dropped,
                "remote_exec.default_demand",
                tier,
                REMOTE_EXEC_PROJECT_REASON,
            );
        }
    }
    if raw
        .index
        .as_ref()
        .and_then(|index| index.roots.as_ref())
        .is_some()
    {
        push_drop(dropped, "index.roots", tier, USER_ONLY_REASON);
    }
    if let Some(sandbox) = &raw.sandbox {
        if sandbox.write_allow.is_some() {
            push_drop(dropped, "sandbox.write_allow", tier, USER_ONLY_REASON);
        }
    }
    if raw.bash.as_ref().is_some_and(
        |bash| matches!(bash, features if features.changed_files.is_some_and(|mode| mode != crate::config::BashChangedFiles::Off)),
    ) {
        push_drop(dropped, "bash.changed_files", tier, "a project config may only turn changed-file reporting off");
    }
    if raw
        .bash
        .as_ref()
        .is_some_and(|bash| matches!(bash, features if features.linux_scope.is_some()))
    {
        push_drop(dropped, "bash.linux_scope", tier, USER_ONLY_REASON);
    }
    if raw.bash.as_ref().is_some_and(
        |bash| matches!(bash, features if features.linux_scope_max_runtime_secs.is_some()),
    ) {
        push_drop(
            dropped,
            "bash.linux_scope_max_runtime_secs",
            tier,
            USER_ONLY_REASON,
        );
    }
    for tool in feature_config::normalize_tool_list(
        raw.disabled_tools
            .iter()
            .flatten()
            .filter(|tool| feature_config::is_project_protected_tool(tool))
            .cloned(),
    ) {
        push_drop(
            dropped,
            &format!("disabled_tools.{tool}"),
            tier,
            PROTECTED_TOOL_REASON,
        );
    }

    if let Some(semantic) = &raw.semantic {
        if semantic.backend.is_some() {
            push_drop(dropped, "semantic.backend", tier, SEMANTIC_SECRET_REASON);
        }
        if semantic.base_url.is_some() {
            push_drop(dropped, "semantic.base_url", tier, SEMANTIC_SECRET_REASON);
        }
        if semantic.api_key_env.is_some() {
            push_drop(
                dropped,
                "semantic.api_key_env",
                tier,
                SEMANTIC_SECRET_REASON,
            );
        }
        if semantic.query_timeout_ms.is_some() {
            push_drop(dropped, "semantic.query_timeout_ms", tier, USER_ONLY_REASON);
        }
    }

    if let Some(rerank) = raw
        .search
        .as_ref()
        .and_then(|search| search.rerank.as_ref())
    {
        // `backend: "off"` is the one accepted project value; everything else
        // could start a model download, reach an endpoint, read a credential
        // variable or change how much of the result list is reordered.
        if rerank
            .backend
            .is_some_and(|backend| backend != RerankBackendKind::Off)
        {
            push_drop(
                dropped,
                "search.rerank.backend",
                tier,
                RERANK_PROJECT_REASON,
            );
        }
        for (key, present) in [
            ("search.rerank.model", rerank.model.is_some()),
            ("search.rerank.endpoint", rerank.endpoint.is_some()),
            ("search.rerank.api_key_env", rerank.api_key_env.is_some()),
            ("search.rerank.top_n", rerank.top_n.is_some()),
            ("search.rerank.timeout_ms", rerank.timeout_ms.is_some()),
        ] {
            if present {
                push_drop(dropped, key, tier, RERANK_PROJECT_REASON);
            }
        }
    }

    if let Some(lsp) = &raw.lsp {
        if lsp.servers.is_some() {
            push_drop(dropped, "lsp.servers", tier, LSP_USER_ONLY_REASON);
        }
        if lsp.versions.is_some() {
            push_drop(dropped, "lsp.versions", tier, LSP_USER_ONLY_REASON);
        }
        if lsp.auto_install.is_some() {
            push_drop(dropped, "lsp.auto_install", tier, LSP_USER_ONLY_REASON);
        }
        if lsp.grace_days.is_some() {
            push_drop(dropped, "lsp.grace_days", tier, LSP_USER_ONLY_REASON);
        }
        if lsp.disabled.is_some() {
            push_drop(dropped, "lsp.disabled", tier, LSP_USER_ONLY_REASON);
        }
    }
}

fn push_drop(dropped: &mut Vec<DroppedKey>, key: &str, tier: &str, reason: &str) {
    dropped.push(DroppedKey {
        key: key.to_string(),
        tier: tier.to_string(),
        reason: reason.to_string(),
    });
}

/// Apply merged core-domain fields onto a freshly defaulted `Config`. Absent
/// scalar fields therefore retain defaults, while semantic, inspect, and LSP
/// fields are fully resolved from the tiers. Process-state fields are not part
/// of `RawAftConfig` and are preserved separately by `resolve_config_onto`.
fn apply_resolved_config(
    raw: &RawAftConfig,
    config: &mut Config,
    warnings: &mut Vec<ConfigWarning>,
) -> Result<(), Vec<String>> {
    config.shell = raw.shell.clone().unwrap_or_default();
    if let Some(provider) = &config.shell.env_provider {
        provider.validate().map_err(|error| vec![error])?;
    }
    config.hashline_enabled = matches!(raw.edit_mode, Some(RawEditMode::Hashline));
    config.durability.macos_full_sync = raw
        .durability
        .as_ref()
        .and_then(|durability| durability.macos_full_sync)
        .unwrap_or(false);
    // The user-base default has already been applied; an absent list here is
    // a resolver bug and must not silently become an empty (all-enabled) list.
    let Some(disabled_tools) = &raw.disabled_tools else {
        return Err(vec![
            "invalid_resolved_config:missing:disabled_tools".to_string()
        ]);
    };
    config.disabled_tools = feature_config::normalize_tool_list(disabled_tools.iter().cloned());
    config.aft_search_registered = config.tool_registered("aft_search");
    let indexes = raw.indexes.unwrap_or_default();
    let defaults = IndexesConfig::default();
    config.indexes = IndexesConfig {
        trigram: indexes.trigram.unwrap_or(defaults.trigram),
        semantic: indexes.semantic.unwrap_or(defaults.semantic),
        callgraph: indexes.callgraph.unwrap_or(defaults.callgraph),
    };
    if let Some(value) = raw.format_on_edit {
        config.format_on_edit = value;
    }
    if let Some(value) = raw.revision_reads {
        config.revision_reads = value;
    }
    if let Some(value) = raw.formatter_timeout_secs {
        config.formatter_timeout_secs = value;
    }
    if let Some(value) = raw.type_checker_timeout_secs {
        config.type_checker_timeout_secs = value;
    }
    if let Some(value) = raw.validate_on_edit {
        config.validate_on_edit = Some(value.as_str().to_string());
    }
    if let Some(formatter) = &raw.formatter {
        config.formatter = formatter
            .iter()
            .map(|(language, formatter)| (language.clone(), formatter.as_str().to_string()))
            .collect();
    }
    if let Some(checker) = &raw.checker {
        config.checker = checker
            .iter()
            .map(|(language, checker)| (language.clone(), checker.as_str().to_string()))
            .collect();
    }
    if let Some(value) = raw.restrict_to_project_root {
        config.restrict_to_project_root = value;
    }
    config.memory = raw.memory;
    if let Some(value) = raw.url_fetch_allow_private {
        config.url_fetch_allow_private = value;
    }
    config.semantic = resolve_semantic_config(raw.semantic.as_ref(), raw.subc.as_ref());
    config.search = resolve_search_config(raw.search.as_ref());
    config.inspect = resolve_inspect_config(raw.inspect.as_ref());
    config.backup = resolve_backup_config(raw.backup.as_ref());
    config.github = resolve_github_config(raw.github.as_ref(), warnings);
    config.gh_shim = resolve_gh_shim_config(raw.gh_shim.as_ref());

    config.git = resolve_git_config(raw.git.as_ref());
    config.sandbox = resolve_sandbox_config(raw.sandbox.as_ref());
    config.remote_exec = resolve_remote_exec_config(raw);
    resolve_lsp_config(raw, config);
    resolve_bash_fields(raw, config, warnings);
    Ok(())
}

fn resolve_index_config(raw: Option<&RawIndex>, warnings: &mut Vec<ConfigWarning>) -> IndexConfig {
    let Some(raw) = raw else {
        return IndexConfig::default();
    };
    let Some(roots) = raw.roots.as_ref() else {
        return IndexConfig::default();
    };

    let home = crate::environment::non_empty_os_var("HOME")
        .or_else(|| crate::environment::non_empty_os_var("USERPROFILE"))
        .map(PathBuf::from);
    let mut normalized_roots = Vec::with_capacity(roots.len());

    for (position, root) in roots.iter().enumerate() {
        for field in root.unknown.keys() {
            warnings.push(ConfigWarning {
                code: "unknown_index_root_field",
                key: "index.roots",
                tier: "user".to_string(),
                value: field.clone(),
                message: format!(
                    "Ignoring unknown field index.roots[{position}].{field}; only path and indexes are defined"
                ),
            });
        }

        let result = (|| -> Result<IndexRootConfig, String> {
            let path = root.path.as_deref().ok_or_else(|| {
                "index.roots entry is missing required string field path".to_string()
            })?;
            expand_index_root_path(path, home.as_deref())?;

            let indexes = root.indexes.as_ref().ok_or_else(|| {
                "index.roots entry is missing required non-empty indexes array".to_string()
            })?;
            if indexes.is_empty() {
                return Err("index.roots indexes must be a non-empty array".to_string());
            }

            let mut normalized = Vec::with_capacity(indexes.len() + 1);
            for name in indexes {
                let kind = IndexKind::from_name(name).ok_or_else(|| {
                    format!(
                        "index.roots indexes contains unknown name {name:?}; valid names: search, semantic, callgraph"
                    )
                })?;
                if normalized.contains(&kind) {
                    return Err(format!(
                        "index.roots indexes contains duplicate name {name:?}"
                    ));
                }
                normalized.push(kind);
            }
            if normalized.contains(&IndexKind::Semantic) && !normalized.contains(&IndexKind::Search)
            {
                normalized.push(IndexKind::Search);
                warnings.push(ConfigWarning {
                    code: "index_dependency_closure",
                    key: "index.roots",
                    tier: "user".to_string(),
                    value: path.to_string(),
                    message: format!(
                        "Added search to index.roots[{position}].indexes because semantic depends on search"
                    ),
                });
            }
            normalized.sort_unstable();
            Ok(IndexRootConfig {
                path: path.to_string(),
                indexes: normalized,
            })
        })();

        match result {
            Ok(root) => normalized_roots.push(root),
            Err(message) => {
                warnings.push(ConfigWarning {
                    code: "invalid_index_roots",
                    key: "index.roots",
                    tier: "user".to_string(),
                    value: position.to_string(),
                    message,
                });
                return IndexConfig::default();
            }
        }
    }

    IndexConfig {
        roots: normalized_roots,
    }
}

fn resolve_semantic_config(
    raw: Option<&RawSemantic>,
    subc: Option<&RawSubc>,
) -> SemanticBackendConfig {
    let mut semantic = SemanticBackendConfig::default();
    semantic.subc_connection_file = subc
        .and_then(|subc| subc.connection_file.as_deref())
        .map(str::trim)
        .filter(|path| !path.is_empty())
        .map(PathBuf::from);
    let Some(raw) = raw else {
        return semantic;
    };

    if let Some(value) = raw.backend {
        semantic.backend = value;
        if value == SemanticBackend::Synapse && raw.model.is_none() {
            // Synapse has no implicit vector space. Leaving this empty lets backend
            // initialization return an honest missing-model configuration error.
            semantic.model.clear();
        }
    }
    if let Some(value) = &raw.model {
        semantic.model = value.clone();
    }
    if let Some(value) = &raw.base_url {
        semantic.base_url = Some(value.clone());
    }
    if let Some(value) = &raw.api_key_env {
        semantic.api_key_env = Some(value.clone());
    }
    if let Some(value) = raw.timeout_ms {
        semantic.timeout_ms = value.min(MAX_SEMANTIC_TIMEOUT_MS);
    }
    if let Some(value) = &raw.query_instruction {
        semantic.query_instruction = value.clone();
    }
    if let Some(value) = raw.query_timeout_ms {
        semantic.query_timeout_ms =
            value.clamp(MIN_SEMANTIC_QUERY_TIMEOUT_MS, MAX_SEMANTIC_QUERY_TIMEOUT_MS);
    }
    if let Some(value) = raw.max_batch_size {
        semantic.max_batch_size = value.min(MAX_SEMANTIC_BATCH_SIZE);
    }
    if let Some(value) = raw.max_input_tokens {
        semantic.max_input_tokens = Some(value);
    }
    if let Some(value) = raw.max_files {
        semantic.max_files = value;
    }

    semantic
}

fn resolve_idle_config(raw: Option<&RawIdle>, warnings: &mut Vec<ConfigWarning>) -> IdleConfig {
    let mut idle = IdleConfig::default();
    let Some(raw) = raw else {
        return idle;
    };
    idle.root_ttl_minutes = resolve_clamped_minutes(
        raw.root_ttl_minutes.as_ref(),
        "idle.root_ttl_minutes",
        DEFAULT_IDLE_ROOT_TTL_MINUTES,
        MIN_IDLE_ROOT_TTL_MINUTES,
        MAX_IDLE_ROOT_TTL_MINUTES,
        warnings,
    );
    idle.checkout_hours = resolve_clamped_minutes(
        raw.checkout_hours.as_ref(),
        "idle.checkout_hours",
        crate::config::DEFAULT_IDLE_CHECKOUT_HOURS,
        crate::config::MIN_IDLE_CHECKOUT_HOURS,
        crate::config::MAX_IDLE_CHECKOUT_HOURS,
        warnings,
    );
    idle
}

/// An integer setting clamped to `min..=max`, with a warning when it is out
/// of range or not an integer. Used for the idle windows; the unit (minutes or
/// hours) is the caller's.
fn resolve_clamped_minutes(
    raw: Option<&Value>,
    key: &'static str,
    default: u32,
    min: u32,
    max: u32,
    warnings: &mut Vec<ConfigWarning>,
) -> u32 {
    let Some(value) = raw else {
        return default;
    };
    let Some(parsed) = json_integer(value) else {
        warnings.push(ConfigWarning {
            code: "invalid_idle_ttl",
            key,
            tier: "config".to_string(),
            value: value.to_string(),
            message: format!("{key} must be an integer; using default {default}"),
        });
        return default;
    };
    let clamped = parsed.clamp(i64::from(min), i64::from(max)) as u32;
    if i64::from(clamped) != parsed {
        warnings.push(ConfigWarning {
            code: "clamped_idle_ttl",
            key,
            tier: "config".to_string(),
            value: parsed.to_string(),
            message: format!("{key}={parsed} is outside {min}..={max}; clamped to {clamped}"),
        });
    }
    clamped
}

fn resolve_clamped_bash_watch_sync_max_ms(
    raw: Option<u64>,
    warnings: &mut Vec<ConfigWarning>,
) -> u64 {
    let Some(raw) = raw else {
        return DEFAULT_BASH_WATCH_SYNC_MAX_MS;
    };
    let clamped = raw.clamp(MIN_BASH_WATCH_SYNC_MAX_MS, MAX_BASH_WATCH_SYNC_MAX_MS);
    if clamped != raw {
        warnings.push(ConfigWarning {
            code: "clamped_bash_watch_sync_max_ms",
            key: "bash.watch_sync_max_ms",
            tier: "config".to_string(),
            value: raw.to_string(),
            message: format!(
                "bash.watch_sync_max_ms={raw} is outside {MIN_BASH_WATCH_SYNC_MAX_MS}..={MAX_BASH_WATCH_SYNC_MAX_MS}; clamped to {clamped}"
            ),
        });
    }
    clamped
}

fn json_integer(value: &Value) -> Option<i64> {
    match value {
        Value::Number(number) if number.is_i64() => number.as_i64(),
        Value::Number(number) if number.is_u64() => {
            number.as_u64().and_then(|value| i64::try_from(value).ok())
        }
        _ => None,
    }
}

fn resolve_inspect_config(raw: Option<&RawInspect>) -> InspectConfig {
    let mut inspect = InspectConfig::default();
    let Some(raw) = raw else {
        return inspect;
    };
    if let Some(enabled) = raw.enabled {
        inspect.enabled = enabled;
    }
    if let Some(categories) = &raw.categories {
        inspect.categories = serde_json::from_value(serde_json::to_value(categories).unwrap())
            .expect("validated inspect categories");
    }
    if let Some(value) = raw.diagnostics_timeout_ms {
        inspect.diagnostics_timeout_ms = value.clamp(
            MIN_INSPECT_DIAGNOSTICS_TIMEOUT_MS,
            MAX_INSPECT_DIAGNOSTICS_TIMEOUT_MS,
        );
    }
    if let Some(value) = raw.tier2_pass_timeout_ms {
        inspect.tier2_pass_timeout_ms = value;
    }
    if let Some(expected_mirrors) = raw
        .duplicates
        .as_ref()
        .and_then(|duplicates| duplicates.expected_mirrors.clone())
    {
        inspect.duplicates.expected_mirrors = expected_mirrors
            .into_iter()
            .map(|pair| [pair.source, pair.mirror])
            .collect();
    }
    inspect
}

fn resolve_backup_config(raw: Option<&RawBackup>) -> BackupConfig {
    let mut backup = BackupConfig::default();
    if let Some(raw) = raw {
        if raw.enabled.is_some() {
            backup.enabled = raw.enabled;
        }
        if raw.max_depth.is_some() {
            backup.max_depth = raw.max_depth;
        }
        if raw.max_file_size.is_some() {
            backup.max_file_size = raw.max_file_size;
        }
    }
    backup
}

fn resolve_github_config(
    raw: Option<&RawGithub>,
    warnings: &mut Vec<ConfigWarning>,
) -> GithubConfig {
    let mut github = GithubConfig::default();
    if let Some(value) = raw.and_then(|raw| raw.shim) {
        github.shim = value;
    }
    if let Some(value) = raw.and_then(|raw| raw.read) {
        github.read = value;
    }
    if let Some(value) = raw.and_then(|raw| raw.write) {
        github.write = value;
    }

    // Write implies read; the legacy `github.enabled` master was translated
    // into explicit leaves before this point.
    if github.write && !github.read {
        github.read = true;
        warnings.push(ConfigWarning {
            code: "github_write_requires_read",
            key: "github.write",
            tier: "user".to_string(),
            value: "true".to_string(),
            message: "github.write=true requires github.read=true; treating github.read as enabled"
                .to_string(),
        });
    }

    github
}

fn resolve_gh_shim_config(raw: Option<&RawGhShim>) -> GhShimConfig {
    let mut gh_shim = GhShimConfig::default();
    gh_shim.binary_path = raw
        .and_then(|raw| raw.binary_path.as_ref())
        .map(PathBuf::from);
    gh_shim
}

fn resolve_git_config(raw: Option<&RawGit>) -> GitConfig {
    GitConfig {
        co_author: raw
            .and_then(|raw| raw.co_author.clone())
            .unwrap_or_else(|| "off".to_string()),
    }
}

fn resolve_sandbox_config(raw: Option<&RawSandbox>) -> SandboxConfig {
    let Some(raw) = raw else {
        return SandboxConfig::default();
    };
    SandboxConfig {
        profile: crate::config::SandboxRoles {
            worker: raw
                .profile
                .as_ref()
                .and_then(|profile| profile.worker)
                .unwrap_or(crate::config::SandboxMode::Relaxed),
            head: raw
                .profile
                .as_ref()
                .and_then(|profile| profile.head)
                .unwrap_or(crate::config::SandboxMode::Off),
        },
        write_allow: raw.write_allow.clone().unwrap_or_default(),
        read_deny: raw.read_deny.clone().unwrap_or_default(),
    }
}

fn resolve_remote_exec_config(raw: &RawAftConfig) -> RemoteExecConfig {
    let user = raw.remote_exec.as_ref();
    RemoteExecConfig {
        enabled: user.and_then(|r| r.enabled) == Some(true) && !raw.remote_exec_project_off,
        default_demand: user.and_then(|r| r.default_demand.clone()),
        project_off: raw.remote_exec_project_off,
    }
}

fn resolve_lsp_config(raw: &RawAftConfig, config: &mut Config) {
    let lsp = raw.lsp.as_ref();
    config.lsp_idle_minutes = lsp_idle_minutes(lsp.and_then(|lsp| lsp.idle_minutes));
    config.lsp_idle_shutdown = lsp.and_then(|lsp| lsp.idle_shutdown).unwrap_or(true);
    config.lsp_max_servers = lsp.and_then(|lsp| lsp.max_servers).unwrap_or(8);
    let mut disabled: HashSet<String> = lsp
        .and_then(|lsp| lsp.disabled.as_ref())
        .into_iter()
        .flatten()
        .map(|value| value.to_ascii_lowercase())
        .collect();
    let mut experimental_ty = raw
        .experimental
        .as_ref()
        .and_then(|experimental| experimental.lsp_ty);

    match lsp.and_then(|lsp| lsp.python).unwrap_or(RawPythonLsp::Auto) {
        RawPythonLsp::Ty => {
            experimental_ty = Some(true);
            disabled.insert("python".to_string());
        }
        RawPythonLsp::Pyright => {
            experimental_ty = Some(false);
            disabled.insert("ty".to_string());
        }
        RawPythonLsp::Auto => {}
    }

    if let Some(value) = experimental_ty {
        config.experimental_lsp_ty = value;
    }

    if let Some(value) = lsp.and_then(|lsp| lsp.diagnostics_on_edit) {
        config.diagnostics_on_edit = value;
    }

    if let Some(servers) = lsp.and_then(|lsp| lsp.servers.as_ref()) {
        let invalid = &mut config.invalid_lsp_initialization_options;
        config.lsp_servers = servers
            .iter()
            .map(|(id, server)| UserServerDef {
                id: id.clone(),
                extensions: server
                    .extensions
                    .clone()
                    .unwrap_or_default()
                    .into_iter()
                    .map(|extension| extension.trim_start_matches('.').to_string())
                    .collect(),
                binary: server.binary.clone().unwrap_or_default(),
                args: server.args.clone().unwrap_or_default(),
                root_markers: server
                    .root_markers
                    .clone()
                    .unwrap_or_else(|| vec![".git".to_string()]),
                env: server.env.clone().unwrap_or_default(),
                initialization_options: server.initialization_options.as_deref().and_then(|text| {
                    match serde_json::from_str(text) {
                        Ok(options) => Some(options),
                        Err(_) => {
                            invalid.push(id.clone());
                            None
                        }
                    }
                }),
                disabled: server.disabled.unwrap_or(false),
            })
            .collect();
    }

    if !disabled.is_empty() {
        config.disabled_lsp = disabled;
    }
}

fn lsp_idle_minutes(value: Option<i64>) -> u32 {
    use crate::config::{DEFAULT_LSP_IDLE_MINUTES, MAX_LSP_IDLE_MINUTES, MIN_LSP_IDLE_MINUTES};
    value.unwrap_or(i64::from(DEFAULT_LSP_IDLE_MINUTES)).clamp(
        i64::from(MIN_LSP_IDLE_MINUTES),
        i64::from(MAX_LSP_IDLE_MINUTES),
    ) as u32
}

/// A validated `bash.env` map together with the tier it was written at.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConfiguredBashEnv {
    pub names: BTreeMap<String, String>,
    pub tier: crate::bash_env::BashEnvTier,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct ResolvedBashConfig {
    changed_files: crate::config::BashChangedFiles,
    enabled: bool,
    rewrite: bool,
    compress: bool,
    background: bool,
    host_fallback: bool,
    subagent_background: bool,
    detach_on_user_message: bool,
    db_schema_hints: bool,
    long_running_reminder_enabled: Option<bool>,
    long_running_reminder_interval_ms: Option<u64>,
    foreground_wait_window_ms: u64,
    watch_sync_max_ms: u64,
    worker_wait_max_ms: u64,
    linux_scope: bool,
    linux_scope_max_runtime_secs: u64,
    memory_limit_mib: Option<u64>,
    disclaim_privacy: bool,
    powershell_tool: bool,
    env: BTreeMap<String, String>,
    project_env: BTreeMap<String, String>,
    runon_env: Vec<String>,
}

fn resolve_bash_fields(raw: &RawAftConfig, config: &mut Config, warnings: &mut Vec<ConfigWarning>) {
    let bash = resolve_bash_config(raw, warnings);
    // `subagent_background` is plugin-owned; Rust resolves it only to accept
    // and merge the same config.
    let _plugin_only = bash.subagent_background;
    config.bash.enabled = bash.enabled;
    config.bash.changed_files = bash.changed_files;
    config.bash.host_fallback = bash.host_fallback;
    config.bash.detach_on_user_message = bash.detach_on_user_message;
    config.bash.db_schema_hints = bash.db_schema_hints;
    config.bash.watch_sync_max_ms = bash.watch_sync_max_ms;
    config.bash.worker_wait_max_ms = bash.worker_wait_max_ms;
    config.bash.linux_scope = bash.linux_scope;
    config.bash.linux_scope_max_runtime_secs = bash.linux_scope_max_runtime_secs;
    config.bash.memory_limit_mib = bash.memory_limit_mib;
    config.bash.disclaim_privacy = bash.disclaim_privacy;
    config.bash.powershell_tool = bash.powershell_tool;
    config.bash.env = bash.env;
    config.bash.project_env = bash.project_env;
    config.bash.runon_env = bash.runon_env;
    config.experimental_bash_rewrite = bash.rewrite;
    config.experimental_bash_compress = bash.compress;
    config.experimental_bash_background = bash.background;
    config.foreground_wait_window_ms = bash.foreground_wait_window_ms;
    if let Some(value) = bash.long_running_reminder_enabled {
        config.bash_long_running_reminder_enabled = value;
    }
    if let Some(value) = bash.long_running_reminder_interval_ms {
        config.bash_long_running_reminder_interval_ms = value;
    }
}

fn resolve_bash_config(
    raw: &RawAftConfig,
    warnings: &mut Vec<ConfigWarning>,
) -> ResolvedBashConfig {
    let top = raw.bash.as_ref();

    let top_features = top;
    let reminder_enabled = top_features.and_then(|features| features.long_running_reminder_enabled);
    let reminder_interval =
        top_features.and_then(|features| features.long_running_reminder_interval_ms);
    let top_host_fallback = top_features
        .and_then(|features| features.host_fallback)
        .unwrap_or(false);
    let top_subagent_background = top_features
        .and_then(|features| features.subagent_background)
        .unwrap_or(true);
    let top_detach_on_user_message = top_features
        .and_then(|features| features.detach_on_user_message)
        .unwrap_or(true);
    let raw_foreground_wait = top_features.and_then(|features| features.foreground_wait_window_ms);
    let raw_watch_sync_max = top_features.and_then(|features| features.watch_sync_max_ms);
    let watch_sync_max_ms = resolve_clamped_bash_watch_sync_max_ms(raw_watch_sync_max, warnings);
    // Below-minimum values never get here: the raw schema rejects them, which
    // drops the `bash` block like any other invalid value.
    let worker_wait_max_ms = top_features
        .and_then(|features| features.worker_wait_max_ms)
        .unwrap_or(DEFAULT_BASH_WORKER_WAIT_MAX_MS);
    let top_linux_scope = top_features
        .and_then(|features| features.linux_scope)
        .unwrap_or(true);
    let top_powershell_tool = top_features
        .and_then(|features| features.powershell_tool)
        .unwrap_or(false);
    let foreground_wait_window_ms = raw_foreground_wait
        .unwrap_or(FOREGROUND_WAIT_WINDOW_DEFAULT_MS)
        .max(FOREGROUND_WAIT_WINDOW_MIN_MS);

    let base = ResolvedBashConfig {
        changed_files: top_features
            .and_then(|features| features.changed_files)
            .unwrap_or_default(),
        enabled: false,
        rewrite: false,
        compress: false,
        background: false,
        host_fallback: false,
        subagent_background: true,
        detach_on_user_message: true,
        db_schema_hints: top_features
            .and_then(|features| features.db_schema_hints)
            .unwrap_or(true),
        long_running_reminder_enabled: reminder_enabled,
        long_running_reminder_interval_ms: reminder_interval,
        foreground_wait_window_ms,
        watch_sync_max_ms,
        worker_wait_max_ms,
        linux_scope: top_linux_scope,
        linux_scope_max_runtime_secs: top_features
            .and_then(|features| features.linux_scope_max_runtime_secs)
            .unwrap_or(crate::config::DEFAULT_LINUX_SCOPE_MAX_RUNTIME_SECS),
        memory_limit_mib: top_features.and_then(|features| features.memory_limit_mib),
        disclaim_privacy: top_features
            .and_then(|features| features.disclaim_privacy)
            .unwrap_or(false),
        powershell_tool: false,
        env: BTreeMap::new(),
        project_env: BTreeMap::new(),
        runon_env: Vec::new(),
    };

    match top {
        Some(features) => ResolvedBashConfig {
            enabled: features.enabled.unwrap_or(true),
            rewrite: features.rewrite.unwrap_or(true),
            compress: features.compress.unwrap_or(true),
            background: features.background.unwrap_or(true),
            host_fallback: top_host_fallback,
            subagent_background: top_subagent_background,
            detach_on_user_message: top_detach_on_user_message,
            powershell_tool: top_powershell_tool,
            env: features.env.clone().unwrap_or_default(),
            project_env: features.project_env.clone().unwrap_or_default(),
            runon_env: features.runon_env.clone().unwrap_or_default(),
            ..base
        },
        None => ResolvedBashConfig {
            enabled: true,
            rewrite: true,
            compress: true,
            background: true,
            ..base
        },
    }
}

fn deserialize_opt_git_co_author<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
where
    D: Deserializer<'de>,
{
    let value = Option::<String>::deserialize(deserializer)?;
    value
        .map(|value| {
            normalize_git_co_author(&value).ok_or_else(|| {
                de::Error::custom(
                    "git.co_author must be 'off', 'auto', or an explicit 'Name <email>' identity",
                )
            })
        })
        .transpose()
}

fn deserialize_opt_trimmed_non_empty_string<'de, D>(
    deserializer: D,
) -> Result<Option<String>, D::Error>
where
    D: Deserializer<'de>,
{
    let value = Option::<String>::deserialize(deserializer)?;
    value
        .map(|value| {
            let trimmed = value.trim().to_string();
            if trimmed.is_empty() {
                Err(de::Error::custom("must be a non-empty string"))
            } else {
                Ok(trimmed)
            }
        })
        .transpose()
}

fn deserialize_opt_trimmed_non_empty_string_vec<'de, D>(
    deserializer: D,
) -> Result<Option<Vec<String>>, D::Error>
where
    D: Deserializer<'de>,
{
    let value = Option::<Vec<String>>::deserialize(deserializer)?;
    value
        .map(|values| {
            values
                .into_iter()
                .map(|value| {
                    let trimmed = value.trim().to_string();
                    if trimmed.is_empty() {
                        Err(de::Error::custom("array entries must be non-empty strings"))
                    } else {
                        Ok(trimmed)
                    }
                })
                .collect()
        })
        .transpose()
}

fn deserialize_opt_lsp_extensions<'de, D>(deserializer: D) -> Result<Option<Vec<String>>, D::Error>
where
    D: Deserializer<'de>,
{
    let value = Option::<Vec<String>>::deserialize(deserializer)?;
    value
        .map(|values| {
            if values.is_empty() {
                return Err(de::Error::custom(
                    "extensions must contain at least one entry",
                ));
            }
            values
                .into_iter()
                .map(|value| {
                    let trimmed = value.trim().to_string();
                    if trimmed.is_empty() || trimmed.trim_start_matches('.').is_empty() {
                        Err(de::Error::custom(
                            "extension must include characters other than leading dots",
                        ))
                    } else {
                        Ok(trimmed)
                    }
                })
                .collect()
        })
        .transpose()
}

fn deserialize_opt_lsp_servers<'de, D>(
    deserializer: D,
) -> Result<Option<BTreeMap<String, RawLspServerEntry>>, D::Error>
where
    D: Deserializer<'de>,
{
    let value = Option::<BTreeMap<String, RawLspServerEntry>>::deserialize(deserializer)?;
    value
        .map(|entries| {
            entries
                .into_iter()
                .map(|(key, value)| {
                    let trimmed = key.trim().to_string();
                    if trimmed.is_empty() {
                        Err(de::Error::custom(
                            "lsp.servers keys must be non-empty strings",
                        ))
                    } else {
                        Ok((trimmed, value))
                    }
                })
                .collect()
        })
        .transpose()
}

fn deserialize_opt_versions_map<'de, D>(
    deserializer: D,
) -> Result<Option<HashMap<String, String>>, D::Error>
where
    D: Deserializer<'de>,
{
    let value = Option::<HashMap<String, String>>::deserialize(deserializer)?;
    value
        .map(|entries| {
            entries
                .into_iter()
                .map(|(key, value)| {
                    let trimmed_key = key.trim().to_string();
                    let trimmed_value = value.trim().to_string();
                    if trimmed_key.is_empty() || trimmed_value.is_empty() {
                        Err(de::Error::custom(
                            "lsp.versions keys and values must be non-empty strings",
                        ))
                    } else {
                        Ok((trimmed_key, trimmed_value))
                    }
                })
                .collect()
        })
        .transpose()
}

fn deserialize_opt_positive_u64<'de, D>(deserializer: D) -> Result<Option<u64>, D::Error>
where
    D: Deserializer<'de>,
{
    let value = Option::<u64>::deserialize(deserializer)?;
    match value {
        Some(0) => Err(de::Error::custom("must be a positive integer")),
        other => Ok(other),
    }
}

fn deserialize_opt_linux_scope_max_runtime_secs<'de, D>(
    deserializer: D,
) -> Result<Option<u64>, D::Error>
where
    D: Deserializer<'de>,
{
    let value = Option::<u64>::deserialize(deserializer)
        .map_err(|error| de::Error::custom(format!("linux_scope_max_runtime_secs: {error}")))?;
    if value.is_some_and(|value| !(1..=4_294_967_295).contains(&value)) {
        return Err(de::Error::custom(
            "linux_scope_max_runtime_secs must be from 1 to 4294967295",
        ));
    }
    Ok(value)
}

fn deserialize_opt_memory_limit_mib<'de, D>(deserializer: D) -> Result<Option<u64>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let value = Option::<u64>::deserialize(deserializer)?;
    if value.is_some_and(|value| value == 0 || value > 4_294_967_295) {
        return Err(serde::de::Error::custom(
            "expected memory limit in MiB from 1 to 4294967295",
        ));
    }
    Ok(value)
}

fn deserialize_opt_positive_usize<'de, D>(deserializer: D) -> Result<Option<usize>, D::Error>
where
    D: Deserializer<'de>,
{
    let value = deserialize_opt_positive_u64(deserializer)?;
    value
        .map(|value| usize::try_from(value).map_err(|_| de::Error::custom("value is too large")))
        .transpose()
}

fn deserialize_opt_timeout_secs<'de, D>(deserializer: D) -> Result<Option<u32>, D::Error>
where
    D: Deserializer<'de>,
{
    let value = Option::<u64>::deserialize(deserializer)?;
    match value {
        Some(value) if !(1..=600).contains(&value) => {
            Err(de::Error::custom("timeout must be in 1..=600 seconds"))
        }
        Some(value) => u32::try_from(value)
            .map(Some)
            .map_err(|_| de::Error::custom("timeout is too large")),
        None => Ok(None),
    }
}

fn deserialize_opt_bridge_request_timeout_ms<'de, D>(
    deserializer: D,
) -> Result<Option<u64>, D::Error>
where
    D: Deserializer<'de>,
{
    let value = Option::<u64>::deserialize(deserializer)?;
    match value {
        Some(value) if value < 1_000 => Err(de::Error::custom(
            "bridge.request_timeout_ms must be at least 1000",
        )),
        other => Ok(other),
    }
}

fn deserialize_opt_worker_wait_max_ms<'de, D>(deserializer: D) -> Result<Option<u64>, D::Error>
where
    D: Deserializer<'de>,
{
    let value = Option::<u64>::deserialize(deserializer)?;
    match value {
        Some(value) if value < MIN_BASH_WORKER_WAIT_MAX_MS => Err(de::Error::custom(format!(
            "bash.worker_wait_max_ms must be at least {MIN_BASH_WORKER_WAIT_MAX_MS}"
        ))),
        other => Ok(other),
    }
}

fn deserialize_opt_inspect_categories<'de, D>(
    deserializer: D,
) -> Result<Option<BTreeMap<String, bool>>, D::Error>
where
    D: Deserializer<'de>,
{
    let value = Option::<BTreeMap<String, bool>>::deserialize(deserializer)?;
    if let Some(categories) = &value {
        if categories
            .keys()
            .any(|key| !InspectCategories::KEYS.contains(&key.as_str()))
        {
            return Err(de::Error::custom("unknown inspect category"));
        }
    }
    Ok(value)
}

#[cfg(test)]
mod tests {
    #[test]
    fn storage_cache_dir_is_a_recognized_user_setting() {
        let raw = serde_json::from_str::<super::RawAftConfig>(
            r#"{"storage":{"cache_dir":{"kind":"dir","path":"/cache/aft"}}}"#,
        );
        assert!(raw.is_ok(), "storage.cache_dir must be recognized: {raw:?}");
    }

    #[test]
    fn storage_cache_dir_rejects_malformed_choices() {
        for choice in [
            r#"{"kind":"other"}"#,
            r#"{"kind":"dir"}"#,
            r#"{"kind":"main_disk","path":"/unexpected"}"#,
        ] {
            let candidate = tier(
                "user",
                &format!(r#"{{"storage":{{"cache_dir":{choice}}}}}"#),
            );
            assert!(strict_tier_error(&candidate, None).is_some(), "{choice}");
            let result = resolve_config(&[candidate]);
            assert_eq!(
                result.errors,
                ["invalid_cache_config: storage.cache_dir"],
                "{choice}"
            );
            assert!(result.config.cache_config_unknown.is_some(), "{choice}");
            assert!(!result.config.cache_dir_opt_out, "{choice}");
        }
    }

    #[test]
    fn storage_cache_dir_project_and_harness_choices_are_dropped() {
        for choice in [
            r#"{"kind":"default"}"#,
            r#"{"kind":"main_disk"}"#,
            r#"{"kind":"dir","path":"~/do-not-use"}"#,
        ] {
            let storage = format!(r#""storage":{{"cache_dir":{choice}}}"#);
            let result = resolve_config_for_harness(
                &[
                    tier(
                        "user",
                        &format!(r#"{{"harnesses":{{"pi":{{{storage}}}}}}}"#),
                    ),
                    tier("project", &format!(r#"{{{storage}}}"#)),
                ],
                Some(&Harness::Pi),
            );
            assert!(result.errors.is_empty(), "{choice}: {:?}", result.errors);
            assert!(result.config.cache_dir.is_none());
            assert!(!result.config.cache_dir_opt_out);
            for tier in ["user", "project"] {
                assert!(result
                    .dropped
                    .iter()
                    .any(|drop| drop.tier == tier && drop.key == "storage.cache_dir"));
            }
        }
    }

    #[test]
    fn memory_config_only_user_base_selects_machine_limits() {
        use crate::memory_profile::MemoryMode;
        for (name, expected) in [
            ("lean", MemoryMode::Lean),
            ("balanced", MemoryMode::Balanced),
        ] {
            for harness in [Harness::Pi, Harness::Opencode] {
                let result = resolve_config_for_harness(
                    &[
                        tier(
                            "user",
                            &format!(
                                r#"{{"memory":"{name}","harnesses":{{"pi":{{"memory":{{}},"sandbox":{{"profile":{{"worker":"strict"}}}}}},"opencode":{{"memory":null,"sandbox":{{"profile":{{"worker":"strict"}}}}}}}}}}"#
                            ),
                        ),
                        tier(
                            "project",
                            r#"{"memory":5,"harnesses":{"pi":{"memory":"fast"},"opencode":{"memory":"lean"}}}"#,
                        ),
                    ],
                    Some(&harness),
                );
                assert!(result.errors.is_empty(), "{:?}", result.errors);
                assert_eq!(result.config.memory, Some(expected));
                assert!(result
                    .dropped
                    .iter()
                    .any(|drop| drop.key == "memory" && drop.tier == "user"));
                assert!(result
                    .dropped
                    .iter()
                    .any(|drop| drop.key == "memory" && drop.tier == "project"));
            }
        }
        let project = resolve_config(&[tier("project", r#"{"memory":"lean"}"#)]);
        assert!(project.errors.is_empty());
        assert_eq!(project.config.memory, None);
    }

    #[test]
    fn storage_cache_dir_only_user_base_can_select_storage_wide_root() {
        let result = super::resolve_config_for_harness(&[
            super::ConfigTier { tier: "user".into(), source: "user".into(), doc: r#"{"storage":{"cache_dir":"/cache/base"},"harnesses":{"pi":{"storage":{"cache_dir":"/cache/pi"}}}}"#.into() },
            super::ConfigTier { tier: "project".into(), source: "project".into(), doc: r#"{"storage":{"cache_dir":"/evil"},"harnesses":{"pi":{"storage":{"cache_dir":"/evil/pi"}}}}"#.into() },
        ], Some(&crate::harness::Harness::Pi));
        assert!(result.errors.is_empty());
        assert_eq!(
            result.config.cache_dir,
            Some(std::path::PathBuf::from("/cache/base"))
        );
        assert!(result
            .dropped
            .iter()
            .any(|dropped| dropped.key == "storage.cache_dir"));
    }

    #[test]
    fn cache_dir_and_bash_env_keep_distinct_harness_trust_rules() {
        // `storage.cache_dir` is storage-wide: only the user-tier base may set
        // it, at either level. `bash.env` has its own per-tier rule: a harness
        // block merges names, and a project's names are carried for the
        // per-command trust check instead of being dropped. The two rules must
        // not borrow from each other.
        for harness in [
            crate::harness::Harness::Opencode,
            crate::harness::Harness::Pi,
        ] {
            let result = super::resolve_config_for_harness(
                &[
                    tier(
                        "user",
                        r#"{
                        "storage":{"cache_dir":"/cache/base"},
                        "bash":{"env":{"TZ":"UTC"}},
                        "harnesses":{
                            "opencode":{"storage":{"cache_dir":"/cache/override"},"bash":{"env":{"TZ":"Etc/GMT"}}},
                            "pi":{"storage":{"cache_dir":"/cache/override"},"bash":{"env":{"TZ":"Etc/GMT"}}}
                        }
                    }"#,
                    ),
                    tier(
                        "project",
                        r#"{
                        "storage":{"cache_dir":"/evil"},
                        "bash":{"env":{"PROJECT_MARKER":"/evil/marker"}},
                        "harnesses":{
                            "opencode":{"storage":{"cache_dir":"/evil/override"},"bash":{"env":{"TZ":"project"}}},
                            "pi":{"storage":{"cache_dir":"/evil/override"},"bash":{"env":{"TZ":"project"}}}
                        }
                    }"#,
                    ),
                ],
                Some(&harness),
            );
            assert!(result.errors.is_empty(), "{:?}", result.errors);
            // Only the user-tier base selects the cache root, at either level.
            assert_eq!(result.config.cache_dir, Some("/cache/base".into()));
            assert!(result
                .dropped
                .iter()
                .any(|drop| drop.key == "storage.cache_dir" && drop.tier == "user"));
            assert!(result
                .dropped
                .iter()
                .any(|drop| drop.key == "storage.cache_dir" && drop.tier == "project"));
            // The harness block merges its `bash.env` name over the base one.
            assert_eq!(result.config.bash.env.len(), 1);
            assert_eq!(result.config.bash.env["TZ"], "Etc/GMT");
            // The project's names are carried for the per-command trust check,
            // never merged into the user map and never reported as dropped.
            assert_eq!(
                result.config.bash.project_env.get("TZ").map(String::as_str),
                Some("project")
            );
            assert!(result
                .config
                .bash
                .project_env
                .contains_key("PROJECT_MARKER"));
            assert!(!result.dropped.iter().any(|drop| drop.key == "bash.env"));
        }
    }

    #[test]
    fn cache_dir_stays_fenced_when_bash_env_rejects_the_user_config() {
        for in_harness in [false, true] {
            let mut document = serde_json::json!({"storage":{"cache_dir":"/cache/base"}});
            let blocked = serde_json::json!({"env":{"BASH_ENV":"/evil/startup"}});
            if in_harness {
                document["harnesses"] = serde_json::json!({"pi":{"bash":blocked}});
            } else {
                document["bash"] = blocked;
            }
            let result = super::resolve_config_for_harness(
                &[tier("user", &document.to_string())],
                Some(&crate::harness::Harness::Pi),
            );
            assert!(result
                .errors
                .iter()
                .any(|error| error.contains("blocked bash.env key BASH_ENV")));
            assert_eq!(result.config.cache_dir, Some("/cache/base".into()));
            assert!(result.config.cache_config_unknown.is_some());
            assert!(result.config.bash.env.is_empty());
        }
    }

    #[test]
    fn storage_cache_dir_relative_stays_unavailable_without_redirecting() {
        let result = super::resolve_config(&[super::ConfigTier {
            tier: "user".into(),
            source: "user".into(),
            doc: r#"{"storage":{"cache_dir":{"kind":"dir","path":"relative"}}}"#.into(),
        }]);
        assert_eq!(
            result.config.cache_dir,
            Some(std::path::PathBuf::from("relative"))
        );
        assert!(result.config.cache_unavailable.is_some());
        assert!(result
            .warnings
            .iter()
            .any(|warning| warning.code == "cache_dir_unavailable"
                && warning
                    .message
                    .contains("AFT is running without its caches until it is back.")));
    }

    #[test]
    fn storage_cache_dir_expands_tilde_before_absolute_validation() {
        let home = std::env::var_os("HOME")
            .or_else(|| std::env::var_os("USERPROFILE"))
            .map(std::path::PathBuf::from)
            .unwrap();
        let result = super::resolve_config(&[super::ConfigTier {
            tier: "user".into(),
            source: "user".into(),
            doc: r#"{"storage":{"cache_dir":"~/aft-cache"}}"#.into(),
        }]);
        assert_eq!(result.config.cache_dir, Some(home.join("aft-cache")));
        assert!(!result
            .warnings
            .iter()
            .any(|warning| warning.code == "cache_dir_unavailable"));
    }
    use super::*;

    #[test]
    fn harness_ignored_keys_match_plugin_declarations() {
        let source = include_str!("../../../packages/aft-bridge/src/config-keys.ts");
        let declared = |name: &str| -> Vec<String> {
            let prefix = format!("export const {name} = [");
            let body = source
                .split_once(&prefix)
                .expect("host key declaration")
                .1
                .split_once(']')
                .expect("host key list end")
                .0;
            body.split(',')
                .map(str::trim)
                .filter(|entry| !entry.is_empty())
                .map(|entry| serde_json::from_str(entry).expect("literal host key"))
                .collect()
        };
        for (harness, name) in [
            (Harness::Pi, "OPENCODE_ONLY_KEYS"),
            (Harness::Opencode, "PI_ONLY_KEYS"),
        ] {
            assert_eq!(declared(name), harness_ignored_config_keys(Some(&harness)));
        }
        assert!(harness_ignored_config_keys(None).is_empty());
        assert!(harness_ignored_config_keys(Some(&Harness::Runner)).is_empty());
    }

    #[test]
    fn pi_ignored_keys_do_not_discard_active_harness_hardening() {
        for tier_name in ["user", "project"] {
            for ignored in [
                serde_json::json!("opaque"),
                Value::Null,
                serde_json::json!(false),
                serde_json::json!({"unexpected": true}),
            ] {
                let input = tier(
                    tier_name,
                    &serde_json::json!({"harnesses":{"pi":{
                        "auto_update": ignored,
                        "sandbox":{"profile":{"worker":"strict"}}
                    }}})
                    .to_string(),
                );
                let resolved =
                    resolve_config_for_harness(std::slice::from_ref(&input), Some(&Harness::Pi));
                assert!(resolved.errors.is_empty(), "{:?}", resolved.errors);
                assert_eq!(
                    resolved.config.sandbox.profile.worker,
                    crate::config::SandboxMode::Strict
                );
                assert!(strict_tier_error(&input, Some(&Harness::Pi)).is_none());
                assert!(!resolved
                    .warnings
                    .iter()
                    .any(|warning| warning.code == "invalid_harness_override"));
                let (raw, _) =
                    parse_tier(&input, Some(&Harness::Pi), &mut Vec::new(), &mut Vec::new())
                        .unwrap();
                assert!(raw.harnesses.unwrap()["pi"].get("auto_update").is_none());
            }
        }
    }

    #[test]
    fn pi_ignored_keys_do_not_reject_root_hardening_on_reload() {
        for tier_name in ["user", "project"] {
            for ignored in [
                serde_json::json!("opaque"),
                Value::Null,
                serde_json::json!(false),
                serde_json::json!({"unexpected": true}),
            ] {
                let input = tier(
                    tier_name,
                    &serde_json::json!({
                        "auto_update": ignored,
                        "sandbox":{"profile":{"worker":"strict"}}
                    })
                    .to_string(),
                );
                let resolved =
                    resolve_config_for_harness(std::slice::from_ref(&input), Some(&Harness::Pi));
                assert!(resolved.errors.is_empty(), "{:?}", resolved.errors);
                assert_eq!(
                    resolved.config.sandbox.profile.worker,
                    crate::config::SandboxMode::Strict
                );
                assert!(strict_tier_error(&input, Some(&Harness::Pi)).is_none());
                let (raw, _) =
                    parse_tier(&input, Some(&Harness::Pi), &mut Vec::new(), &mut Vec::new())
                        .unwrap();
                assert_eq!(raw.auto_update, None);
            }
        }
    }

    #[test]
    fn opencode_owned_auto_update_remains_security_validated() {
        let valid = tier("user", r#"{"auto_update":false}"#);
        let (raw, _) = parse_tier(
            &valid,
            Some(&Harness::Opencode),
            &mut Vec::new(),
            &mut Vec::new(),
        )
        .unwrap();
        assert_eq!(raw.auto_update, Some(false));
        for tier_name in ["user", "project"] {
            let root = tier(
                tier_name,
                r#"{"auto_update":"opaque","sandbox":{"profile":{"worker":"strict"}}}"#,
            );
            let active = tier(
                tier_name,
                r#"{"harnesses":{"opencode":{"auto_update":"opaque","sandbox":{"profile":{"worker":"strict"}}}}}"#,
            );
            assert_eq!(
                resolve_config_for_harness(&[root], Some(&Harness::Opencode)).errors,
                ["invalid_security_config:auto_update"]
            );
            assert_eq!(
                resolve_config_for_harness(&[active], Some(&Harness::Opencode)).errors,
                ["invalid_security_config:harnesses.opencode.auto_update"]
            );
        }
    }

    #[test]
    fn discarded_nonsecurity_sections_are_named_without_rejecting_valid_settings() {
        let result = resolve_config(&[tier(
            "user",
            r#"{"inspect":{"categories":{"diagnostics":"off"}},"format_on_edit":true}"#,
        )]);
        assert!(result.errors.is_empty());
        assert!(result.config.format_on_edit);
        assert!(result
            .warnings
            .iter()
            .any(|warning| warning.code == "invalid_config_section"
                && warning.message == "Discarded invalid configuration section: inspect"));
    }

    #[test]
    fn malformed_active_harness_hardening_rejects_but_inactive_blocks_stay_opaque() {
        let tier = tier(
            "user",
            r#"{"harnesses":{"opencode":{"sandbox":{"profile":{"worker":5}}},"pi":{"sandbox":{"profile":{"worker":"strict"}}}}}"#,
        );
        let rejected =
            resolve_config_for_harness(std::slice::from_ref(&tier), Some(&Harness::Opencode));
        assert_eq!(
            rejected.errors,
            ["invalid_security_config:harnesses.opencode.sandbox"]
        );
        let accepted = resolve_config_for_harness(&[tier], Some(&Harness::Pi));
        assert!(accepted.errors.is_empty());
        assert_eq!(
            accepted.config.sandbox.profile.worker,
            crate::config::SandboxMode::Strict
        );
    }

    #[test]
    fn malformed_security_sections_reject_candidate_without_resetting_last_good() {
        for (key, value) in [
            ("sandbox", serde_json::json!({"profile": {"worker": 5}})),
            ("indexes", serde_json::json!({"semantic":"off"})),
            ("remote_exec", serde_json::json!({"enabled":"off"})),
            ("disabled_tools", serde_json::json!("aft_write")),
            ("restrict_to_project_root", serde_json::json!(1)),
        ] {
            let tier = ConfigTier {
                tier: "user".into(),
                source: "malformed-security.jsonc".into(),
                doc: serde_json::json!({key:value, "format_on_edit":true}).to_string(),
            };
            let mut last_good = Config {
                restrict_to_project_root: true,
                ..Config::default()
            };
            let before = serde_json::to_value(&last_good).unwrap();
            let diagnostics = resolve_config_onto_with_diagnostics(&[tier], &mut last_good);
            assert_eq!(
                diagnostics.errors,
                [format!("invalid_security_config:{key}")]
            );
            assert_eq!(
                serde_json::to_value(&last_good).unwrap(),
                before,
                "rejected {key} must not reset published hardening"
            );
        }
    }

    #[test]
    fn unreadable_tier_document_does_not_silently_publish_defaults() {
        let tier = ConfigTier {
            tier: "user".into(),
            source: "broken.jsonc".into(),
            doc: "{".into(),
        };
        assert_eq!(resolve_config(&[tier]).errors, ["invalid_config_document"]);
    }

    #[test]
    fn malformed_security_root_and_active_harness_sections_fail_closed() {
        for key in [
            "restrict_to_project_root",
            "url_fetch_allow_private",
            "sandbox",
            "indexes",
            "index",
            "remote_exec",
            "disabled_tools",
            "bash",
            "lsp",
            "semantic",
            "search",
            "subc",
            "opencode",
            "github",
            "gh_shim",
            "auto_update",
        ] {
            let root = tier("user", &serde_json::json!({key: null}).to_string());
            assert_eq!(
                resolve_config_for_harness(&[root], Some(&Harness::Opencode)).errors,
                [format!("invalid_security_config:{key}")]
            );
            let active = tier(
                "project",
                &serde_json::json!({"harnesses": {"opencode": {key: null}}}).to_string(),
            );
            assert_eq!(
                resolve_config_for_harness(&[active], Some(&Harness::Opencode)).errors,
                [format!("invalid_security_config:harnesses.opencode.{key}")]
            );
        }
        let mixed = tier(
            "user",
            r#"{"harnesses":{"opencode":{"sandbox":{"profile":{"worker":"strict"}},"inspect":false}}}"#,
        );
        assert_eq!(
            resolve_config_for_harness(&[mixed], Some(&Harness::Opencode)).errors,
            ["invalid_security_config:harnesses.opencode"]
        );
        let pi = tier("user", r#"{"auto_update":"opaque"}"#);
        assert!(resolve_config_for_harness(&[pi], Some(&Harness::Pi))
            .errors
            .is_empty());
        for doc in ["null", "[]", "false", "1"] {
            assert_eq!(
                resolve_config(&[tier("project", doc)]).errors,
                ["invalid_config_document"]
            );
        }
    }

    #[test]
    fn project_merge_moves_owned_semantic_section_without_cloning() {
        let mut base: RawAftConfig = serde_json::from_value(serde_json::json!({
            "semantic": {"model": "owned-user-model"}
        }))
        .unwrap();
        let model_allocation = base
            .semantic
            .as_ref()
            .unwrap()
            .model
            .as_ref()
            .unwrap()
            .as_ptr();
        merge_project_config(&mut base, RawAftConfig::default());
        assert_eq!(
            base.semantic
                .as_ref()
                .unwrap()
                .model
                .as_ref()
                .unwrap()
                .as_ptr(),
            model_allocation,
            "an unspecified project override must retain the owned model allocation"
        );
    }

    #[test]
    fn lsp_idle_default_and_project_tightening() {
        let default = resolve_config(&[]).config;
        assert_eq!(default.lsp_idle_minutes, 60);
        assert!(default.lsp_idle_shutdown);
        for (user, project, minutes, shutdown, refused) in [
            (
                r#"{"idle_minutes":60}"#,
                r#"{"idle_minutes":30}"#,
                30,
                true,
                None,
            ),
            (
                r#"{"idle_minutes":30}"#,
                r#"{"idle_minutes":60}"#,
                30,
                true,
                Some("lsp.idle_minutes"),
            ),
            (
                r#"{"idle_shutdown":true}"#,
                r#"{"idle_minutes":"never"}"#,
                60,
                true,
                Some("lsp.idle_shutdown"),
            ),
            (
                r#"{"idle_minutes":30,"idle_shutdown":false}"#,
                r#"{"idle_shutdown":true}"#,
                30,
                true,
                None,
            ),
            (
                r#"{"idle_minutes":"never"}"#,
                r#"{"idle_minutes":30,"idle_shutdown":false}"#,
                30,
                false,
                None,
            ),
        ] {
            let result = resolve_config(&[
                tier("user", &format!(r#"{{"lsp":{user}}}"#)),
                tier("project", &format!(r#"{{"lsp":{project}}}"#)),
            ]);
            assert!(result.errors.is_empty(), "{:?}", result.errors);
            assert_eq!(result.config.lsp_idle_minutes, minutes);
            assert_eq!(result.config.lsp_idle_shutdown, shutdown);
            assert_eq!(drop_keys(&result).first().map(String::as_str), refused);
        }
    }

    #[test]
    fn settings_shapes_preserve_legacy_true_in_harness_and_reject_explicit_null() {
        let harness = resolve_config_for_harness(
            &[tier(
                "user",
                r#"{"bash":{"enabled":false,"rewrite":false,"compress":false,"background":false},"harnesses":{"pi":{"bash":true}}}"#,
            )],
            Some(&Harness::Pi),
        );
        assert!(harness.errors.is_empty());
        assert!(harness.config.bash.enabled);
        assert!(harness.config.experimental_bash_rewrite);
        assert!(harness.config.experimental_bash_compress);
        assert!(harness.config.experimental_bash_background);

        for (document, path) in [
            (r#"{"lsp":{"idle_minutes":null}}"#, "lsp.idle_minutes"),
            (r#"{"lsp":{"idle_shutdown":null}}"#, "lsp.idle_shutdown"),
            (
                r#"{"bash":{"memory_limit_mib":null}}"#,
                "bash.memory_limit_mib",
            ),
            (
                r#"{"lsp":{"servers":{"rust":{"initialization_options":null}}}}"#,
                "lsp.servers.rust.initialization_options",
            ),
            (
                r#"{"inspect":{"duplicates":{"expected_mirrors":null}}}"#,
                "inspect.duplicates.expected_mirrors",
            ),
            (
                r#"{"harnesses":{"pi":{"format_on_edit":null}}}"#,
                "harnesses.pi.format_on_edit",
            ),
        ] {
            let candidate = tier("user", document);
            let expected = format!("invalid_config_null:{path}");
            assert_eq!(
                strict_tier_error(&candidate, Some(&Harness::Pi)),
                Some(expected.clone())
            );
            assert_eq!(
                resolve_config_for_harness(&[candidate], Some(&Harness::Pi)).errors,
                [expected]
            );
        }
        let opt_out = resolve_config(&[tier("user", r#"{"storage":{"cache_dir":null}}"#)]);
        assert!(opt_out.errors.is_empty());
        assert!(opt_out.config.cache_dir_opt_out);
    }

    #[test]
    fn lsp_max_servers_defaults_and_project_can_only_lower() {
        assert_eq!(resolve_config(&[]).config.lsp_max_servers, 8);
        for (user, project, expected, refused) in [
            (8, 3, 3, false),
            (3, 8, 3, true),
            (8, 0, 0, false),
            (16, 12, 12, false),
        ] {
            let result = resolve_config(&[
                tier("user", &format!(r#"{{"lsp":{{"max_servers":{user}}}}}"#)),
                tier(
                    "project",
                    &format!(r#"{{"lsp":{{"max_servers":{project}}}}}"#),
                ),
            ]);
            assert!(result.errors.is_empty(), "{:?}", result.errors);
            assert_eq!(result.config.lsp_max_servers, expected);
            assert_eq!(result.config.lsp_user_max_servers, Some(user));
            assert_eq!(
                drop_keys(&result).contains(&"lsp.max_servers".to_string()),
                refused
            );
        }
        let result = resolve_config(&[tier("project", r#"{"lsp":{"max_servers":23}}"#)]);
        assert_eq!(result.config.lsp_max_servers, 8);
        assert!(drop_keys(&result).contains(&"lsp.max_servers".to_string()));
    }

    #[test]
    fn inspect_categories_project_can_only_disable() {
        let result = resolve_config(&[
            tier(
                "user",
                r#"{"inspect":{"categories":{"dead_code":false,"todos":true}}}"#,
            ),
            tier(
                "project",
                r#"{"inspect":{"categories":{"dead_code":true,"todos":false}}}"#,
            ),
        ]);
        assert!(result.errors.is_empty(), "{:?}", result.errors);
        let config = serde_json::to_value(&result.config).unwrap();
        assert_eq!(config["inspect"]["categories"]["dead_code"], false);
        assert_eq!(config["inspect"]["categories"]["todos"], false);
        assert_eq!(config["inspect"]["categories"]["diagnostics"], true);
        assert!(drop_keys(&result).contains(&"inspect.categories.dead_code".to_string()));
    }

    /// One document per refused retired name, with the name the
    /// refusal reports. Every entry of `REFUSED_RETIRED_PATHS` and every
    /// prefixed tool name appears.
    fn refused_retired_documents() -> Vec<(&'static str, Value)> {
        let mut documents = vec![
            (
                "sandbox.enabled",
                serde_json::json!({"sandbox": {"enabled": true}}),
            ),
            (
                "tool_surface",
                serde_json::json!({"tool_surface": "minimal"}),
            ),
            (
                "hoist_builtin_tools",
                serde_json::json!({"hoist_builtin_tools": false}),
            ),
            ("enabled", serde_json::json!({"enabled": false})),
            ("search_index", serde_json::json!({"search_index": false})),
            (
                "experimental_search_index",
                serde_json::json!({"experimental_search_index": false}),
            ),
            (
                "semantic_search",
                serde_json::json!({"semantic_search": false}),
            ),
            (
                "experimental_semantic_search",
                serde_json::json!({"experimental_semantic_search": false}),
            ),
            (
                "callgraph_store",
                serde_json::json!({"callgraph_store": false}),
            ),
            (
                "github.enabled",
                serde_json::json!({"github": {"enabled": false}}),
            ),
            ("gh_read", serde_json::json!({"gh_read": {"enabled": true}})),
            (
                "gh_shim.enabled",
                serde_json::json!({"gh_shim": {"enabled": false, "binary_path": "/opt/aft/bin/aft"}}),
            ),
            (
                "experimental_lsp_ty",
                serde_json::json!({"experimental_lsp_ty": true}),
            ),
            (
                "experimental_bash_rewrite",
                serde_json::json!({"experimental_bash_rewrite": true}),
            ),
            (
                "experimental_bash_compress",
                serde_json::json!({"experimental_bash_compress": true}),
            ),
            (
                "experimental_bash_background",
                serde_json::json!({"experimental_bash_background": true}),
            ),
            (
                "experimental.bash",
                serde_json::json!({"experimental": {"bash": {"background": true}}}),
            ),
            (
                "experimental.bash",
                serde_json::json!({"experimental": {"bash": {"long_running_reminder_interval_ms": 5000}}}),
            ),
            (
                "idle.lsp_ttl_minutes",
                serde_json::json!({"idle": {"lsp_ttl_minutes": 10}}),
            ),
            (
                "inspect.tier2_soft_deadline_ms",
                serde_json::json!({"inspect": {"tier2_soft_deadline_ms": 50}}),
            ),
            (
                "inspect.max_drill_down_items",
                serde_json::json!({"inspect": {"max_drill_down_items": 20}}),
            ),
            (
                "views.enabled",
                serde_json::json!({"views": {"enabled": true}}),
            ),
            (
                "views.callgraph_copies",
                serde_json::json!({"views": {"callgraph_copies": 2}}),
            ),
            (
                "worktree.ram_overlay",
                serde_json::json!({"worktree": {"ram_overlay": false}}),
            ),
        ];
        for (alias, _) in feature_config::LEGACY_TOOL_ALIASES {
            documents.push((alias, serde_json::json!({"disabled_tools": [alias]})));
        }
        documents
    }

    /// A refused retired name produces `removed_config_key`
    /// in the user config, also inside a harness block, and `doctor --fix`
    /// rewrites the file into one that loads. A project config with the same
    /// name loads, with the name translated exactly as `doctor --fix` would
    /// rewrite it.
    #[test]
    fn refused_retired_user_keys_are_refused_and_doctor_fix_repairs_them() {
        let documents = refused_retired_documents();
        let listed: std::collections::BTreeSet<&str> =
            documents.iter().map(|(name, _)| *name).collect();
        for path in feature_config::REFUSED_RETIRED_PATHS {
            assert!(listed.contains(path), "{path} has no refusal case");
        }
        for (name, document) in documents {
            for (prefix, document) in [
                ("", document.clone()),
                (
                    "harnesses.pi.",
                    serde_json::json!({"harnesses": {"pi": document}}),
                ),
            ] {
                let text = document.to_string();
                for tier_name in ["user", "project"] {
                    let resolved =
                        resolve_config_for_harness(&[tier(tier_name, &text)], Some(&Harness::Pi));
                    if tier_name == "user" {
                        assert_eq!(
                            resolved.errors,
                            [format!(
                                "removed_config_key:{prefix}{name}; run npx @cortexkit/aft doctor --fix"
                            )],
                            "{tier_name}: {text}"
                        );
                        assert!(
                            strict_tier_error(&tier(tier_name, &text), Some(&Harness::Pi))
                                .is_some_and(|error| error.contains("removed_config_key:")),
                            "{tier_name}: {text}"
                        );
                    } else {
                        assert!(
                            resolved.errors.is_empty(),
                            "a project config loads: {text}: {:?}",
                            resolved.errors
                        );
                        assert_eq!(
                            strict_tier_error(&tier(tier_name, &text), Some(&Harness::Pi)),
                            None,
                            "{tier_name}: {text}"
                        );
                    }

                    let fix_tier = if tier_name == "user" {
                        crate::config_fix::FixTier::User
                    } else {
                        crate::config_fix::FixTier::Project
                    };
                    let fixed = crate::config_fix::migrate_config_text(&text, fix_tier)
                        .expect("doctor --fix rewrites the file");
                    assert!(fixed.changed, "{tier_name}: {text}");
                    let repaired = resolve_config_for_harness(
                        &[tier(tier_name, &fixed.text)],
                        Some(&Harness::Pi),
                    );
                    assert!(
                        repaired.errors.is_empty(),
                        "{tier_name}: {text} -> {}: {:?}",
                        fixed.text,
                        repaired.errors
                    );
                    if tier_name == "project" {
                        // The loaded project config means what the rewritten
                        // file means.
                        assert_eq!(
                            serde_json::to_value(&resolved.config).unwrap(),
                            serde_json::to_value(&repaired.config).unwrap(),
                            "{text} -> {}",
                            fixed.text
                        );
                    }
                }
            }
        }
    }

    /// `doctor --fix` keeps what a refused name meant: the replacement keys
    /// carry its value.
    #[test]
    fn doctor_fix_carries_refused_values_to_their_replacements() {
        let fixed = |text: &str| {
            let text =
                crate::config_fix::migrate_config_text(text, crate::config_fix::FixTier::User)
                    .unwrap()
                    .text;
            let result = resolve_config(&[tier("user", &text)]);
            assert!(result.errors.is_empty(), "{text}: {:?}", result.errors);
            result.config
        };
        let minutes =
            |config: &Config| serde_json::to_value(config).unwrap()["lsp_idle_minutes"].clone();
        assert_eq!(minutes(&fixed(r#"{"idle":{"lsp_ttl_minutes":10}}"#)), 10);
        assert!(!fixed(r#"{"search_index":false}"#).indexes.trigram);
        let reminder =
            fixed(r#"{"experimental":{"bash":{"long_running_reminder_interval_ms":5000}}}"#);
        assert_eq!(reminder.bash_long_running_reminder_interval_ms, 5000);
        assert!(
            reminder.experimental_bash_rewrite,
            "the flags keep their defaults"
        );
        let background = fixed(r#"{"experimental":{"bash":{"background":true}}}"#);
        assert!(background.experimental_bash_background);
        assert!(!background.experimental_bash_rewrite);
        assert!(!background.experimental_bash_compress);
        let disabled = fixed(r#"{"disabled_tools":["aft_read"]}"#);
        assert_eq!(disabled.disabled_tools, ["read"]);
    }

    /// At 0.64, names retired in 0.63 or 0.64 still load in either tier: AFT
    /// translates them in memory and says so in a notice.
    #[test]
    fn names_retired_in_the_last_two_releases_still_translate() {
        let _release = feature_config::override_running_release_for_test((0, 64));
        for tier_name in ["user", "project"] {
            let hang = resolve_config(&[tier(tier_name, r#"{"bridge":{"hang_threshold":2}}"#)]);
            assert!(hang.errors.is_empty(), "{tier_name}: {:?}", hang.errors);
            let checkout =
                resolve_config(&[tier(tier_name, r#"{"views":{"idle_checkout_hours":72}}"#)]);
            assert!(
                checkout.errors.is_empty(),
                "{tier_name}: {:?}",
                checkout.errors
            );
            assert_eq!(checkout.config.idle.checkout_hours, 72);
        }
    }

    fn tier(tier: &str, doc: &str) -> ConfigTier {
        ConfigTier {
            tier: tier.to_string(),
            source: format!("/tmp/{tier}/aft.jsonc"),
            doc: doc.to_string(),
        }
    }

    fn drop_keys(result: &ResolveResult) -> Vec<String> {
        result
            .dropped
            .iter()
            .map(|dropped| dropped.key.clone())
            .collect()
    }

    /// The project tier may switch a user-enabled reranker off.
    #[test]
    fn a_project_may_turn_rerank_off() {
        let result = resolve_config(&[
            tier(
                "user",
                r#"{"search": {"rerank": {"backend": "onnx", "model": "bge-reranker-base", "top_n": 15}}}"#,
            ),
            tier("project", r#"{"search": {"rerank": {"backend": "off"}}}"#),
        ]);
        assert!(result.errors.is_empty(), "{:?}", result.errors);
        assert!(drop_keys(&result).is_empty(), "{:?}", result.dropped);
        let rerank = result.config.search.rerank.expect("rerank block");
        assert_eq!(rerank.backend, Some(RerankBackendKind::Off));
        // The user's other settings stay as they were.
        assert_eq!(rerank.model.as_deref(), Some("bge-reranker-base"));
        assert_eq!(rerank.top_n, Some(15));
    }

    /// Every other project-tier rerank value is dropped and reported, and the
    /// user's values (or their absence) stand.
    #[test]
    fn project_rerank_overrides_other_than_off_are_dropped_and_reported() {
        let project = r#"{"search": {"rerank": {
            "backend": "remote",
            "model": "evil-model",
            "endpoint": "https://evil.example.test/rerank",
            "api_key_env": "EVIL_KEY",
            "top_n": 200,
            "timeout_ms": 60000
        }}}"#;
        for user in [
            None,
            Some(r#"{"search": {"rerank": {"backend": "onnx", "timeout_ms": 800}}}"#),
        ] {
            let mut tiers = Vec::new();
            if let Some(user) = user {
                tiers.push(tier("user", user));
            }
            tiers.push(tier("project", project));
            let result = resolve_config(&tiers);
            assert!(result.errors.is_empty(), "{:?}", result.errors);
            assert_eq!(
                drop_keys(&result),
                [
                    "search.rerank.backend",
                    "search.rerank.model",
                    "search.rerank.endpoint",
                    "search.rerank.api_key_env",
                    "search.rerank.top_n",
                    "search.rerank.timeout_ms",
                ]
            );
            assert!(result.dropped.iter().all(
                |dropped| dropped.reason == RERANK_PROJECT_REASON && dropped.tier == "project"
            ));
            match user {
                None => assert_eq!(result.config.search, SearchConfig::default()),
                Some(_) => assert_eq!(
                    result.config.search.rerank,
                    Some(RerankConfig {
                        backend: Some(RerankBackendKind::Onnx),
                        timeout_ms: Some(800),
                        ..RerankConfig::default()
                    })
                ),
            }
        }
    }

    /// A project harness block is still project tier: it cannot enable rerank.
    #[test]
    fn a_project_harness_block_cannot_enable_rerank() {
        let result = resolve_config_for_harness(
            &[tier(
                "project",
                r#"{"harnesses": {"opencode": {"search": {"rerank": {"backend": "onnx"}}}}}"#,
            )],
            Some(&Harness::Opencode),
        );
        assert_eq!(drop_keys(&result), ["search.rerank.backend"]);
        assert_eq!(result.config.search, SearchConfig::default());
    }

    #[test]
    fn a_superseded_legacy_note_is_logged_once_per_file_and_text() {
        let source = "/tmp/superseded-note-test/aft.jsonc";
        assert!(first_superseded_note(source, "base", "note"));
        assert!(!first_superseded_note(source, "base", "note"));
        assert!(first_superseded_note(source, "base", "changed note"));
        assert!(first_superseded_note(
            "/tmp/other/aft.jsonc",
            "base",
            "note"
        ));
    }

    /// A project's former registration gates (`backup.enabled: false`,
    /// `bash: false`) never bring back the move/delete default the user
    /// switched off with an explicit empty list.
    #[test]
    fn project_legacy_keys_do_not_reapply_the_default_disables() {
        for project in [r#"{"backup": {"enabled": false}}"#, r#"{"bash": false}"#] {
            let result = resolve_config_for_harness(
                &[
                    tier("user", r#"{"disabled_tools": []}"#),
                    tier("project", project),
                ],
                None,
            );
            assert!(result.errors.is_empty());
            for kept in ["aft_move", "aft_delete"] {
                assert!(
                    !result.config.disabled_tools.iter().any(|name| name == kept),
                    "{project}: {kept}"
                );
            }
        }
    }

    /// Security invariant (Oracle drift decision): nested objects are non-strict
    /// (match TS z.object — unknown nested keys are stripped, object survives),
    /// but the TOP-LEVEL RawAftConfig stays strict. A privileged process-state
    /// field is top-level, so a project tier trying to smuggle one still hits the
    /// strict top-level → that tier fails full parse, and partial-parse drops the
    /// unknown key. It can NEVER reach Config.
    #[test]
    fn nested_unknown_keys_are_stripped_but_top_level_privileged_keys_cannot_smuggle() {
        // Nested unknown key: stripped, object survives, and the bash object
        // resolves as enabled. The point: the unknown key did not fail the
        // parse — the object survived and resolved.
        let nested = resolve_config(&[tier(
            "user",
            r#"{ "disabled_tools": [], "bash": { "unknown_key": true } }"#,
        )]);
        assert!(nested.config.experimental_bash_rewrite);
        assert!(nested.config.experimental_bash_compress);
        assert!(nested.config.experimental_bash_background);

        // Top-level privileged process-state field (storage_dir) from a PROJECT
        // tier: not in RawAftConfig → full parse fails → partial-parse drops it.
        // It must never appear in Config (Config keeps its default storage_dir).
        let smuggle = resolve_config(&[
            tier("user", r#"{ "indexes": { "trigram": true } }"#),
            tier(
                "project",
                r#"{ "storage_dir": "/tmp/evil", "bash_permissions": true, "indexes": { "trigram": false } }"#,
            ),
        ]);
        // The valid project index setting still applies via partial parsing.
        assert!(!smuggle.config.indexes.trigram);
        // The smuggled process-state fields never reach Config.
        assert!(smuggle.config.storage_dir.is_none());
        assert!(!smuggle.config.bash_permissions);
    }

    #[test]
    fn config_resolve_empty_tiers_applies_bash_surface_default() {
        // No config file ⇒ empty config object, which still flows through the
        // resolver and picks up the bash surface default (recommended ⇒ on),
        // matching the TS pipeline (golden fixture `empty`). NOT Config::default()
        // — that would leave bash off, diverging from TS.
        let result = resolve_config(&[]);
        let default_config = Config::default();

        assert!(result.dropped.is_empty());
        // Non-bash fields stay at runtime default.
        assert_eq!(result.config.format_on_edit, default_config.format_on_edit);
        assert_eq!(result.config.indexes, default_config.indexes);
        assert_eq!(result.config.disabled_tools, ["aft_delete", "aft_move"]);
        assert_eq!(result.config.semantic, default_config.semantic);
        assert_eq!(
            result.config.inspect.enabled,
            default_config.inspect.enabled
        );
        assert_eq!(result.config.lsp_servers.len(), 0);
        // Bash surface default: recommended ⇒ rewrite/compress/background all on.
        assert!(result.config.experimental_bash_rewrite);
        assert!(result.config.experimental_bash_compress);
        assert!(result.config.experimental_bash_background);
    }

    #[test]
    fn bash_watch_sync_max_defaults_clamps_and_warns() {
        let default_result = resolve_config(&[]);
        assert_eq!(
            default_result.config.bash.watch_sync_max_ms,
            DEFAULT_BASH_WATCH_SYNC_MAX_MS
        );
        assert!(default_result
            .warnings
            .iter()
            .all(|warning| warning.key != "bash.watch_sync_max_ms"));

        let clamped = resolve_config(&[tier("user", r#"{ "bash": { "watch_sync_max_ms": 5 } }"#)]);
        assert_eq!(
            clamped.config.bash.watch_sync_max_ms,
            MIN_BASH_WATCH_SYNC_MAX_MS
        );
        assert!(clamped.warnings.iter().any(|warning| {
            warning.code == "clamped_bash_watch_sync_max_ms"
                && warning.key == "bash.watch_sync_max_ms"
                && warning.value == "5"
        }));

        let project_override = resolve_config(&[
            tier("user", r#"{ "bash": { "watch_sync_max_ms": 120000 } }"#),
            tier("project", r#"{ "bash": { "watch_sync_max_ms": 1800000 } }"#),
        ]);
        assert_eq!(
            project_override.config.bash.watch_sync_max_ms,
            MAX_BASH_WATCH_SYNC_MAX_MS
        );
    }

    /// `bash.worker_wait_max_ms` defaults to 30 minutes, a project may set it
    /// (it only changes how long a worker waits), and a value below the
    /// one-minute minimum is rejected instead of clamped. An invalid bash block
    /// can discard permission/scope settings, so initial load and live reload
    /// both refuse the candidate rather than applying neighboring settings.
    #[test]
    fn bash_worker_wait_max_defaults_accepts_project_and_rejects_below_minimum() {
        assert_eq!(
            resolve_config(&[]).config.bash.worker_wait_max_ms,
            DEFAULT_BASH_WORKER_WAIT_MAX_MS
        );

        let project_override = resolve_config(&[
            tier("user", r#"{ "bash": { "worker_wait_max_ms": 600000 } }"#),
            tier("project", r#"{ "bash": { "worker_wait_max_ms": 120000 } }"#),
        ]);
        assert!(project_override.errors.is_empty());
        assert_eq!(project_override.config.bash.worker_wait_max_ms, 120_000);
        assert!(project_override
            .dropped
            .iter()
            .all(|drop| !drop.key.contains("worker_wait_max_ms")));

        let below = tier(
            "user",
            r#"{ "format_on_edit": false, "bash": { "compress": false, "worker_wait_max_ms": 59999 } }"#,
        );
        let error = strict_tier_error(&below, None).expect("below-minimum value is an error");
        assert!(
            error.contains("bash.worker_wait_max_ms must be at least 60000"),
            "{error}"
        );
        let resolved = resolve_config(&[below]);
        assert_eq!(resolved.errors, ["invalid_security_config:bash"]);

        let minimum = resolve_config(&[tier(
            "user",
            &format!(r#"{{ "bash": {{ "worker_wait_max_ms": {MIN_BASH_WORKER_WAIT_MAX_MS} }} }}"#),
        )]);
        assert_eq!(
            minimum.config.bash.worker_wait_max_ms,
            MIN_BASH_WORKER_WAIT_MAX_MS
        );
    }

    #[test]
    fn bash_env_keeps_user_and_project_maps_apart() {
        // A project's values are no longer dropped: they are validated and
        // carried in `project_env`, which `commands/bash.rs` applies only while
        // the project root is trusted.
        let result = resolve_config(&[
            tier(
                "user",
                r#"{"bash":{"env":{"TZ":"UTC","SOME_USER_ENV":"from-user"}}}"#,
            ),
            tier(
                "project",
                r#"{"bash":{"env":{"TZ":"Mars","SOME_PROJECT_ENV":"from-project"}}}"#,
            ),
        ]);

        assert!(result.errors.is_empty(), "{:?}", result.errors);
        assert_eq!(
            result.config.bash.env.get("TZ").map(String::as_str),
            Some("UTC")
        );
        assert_eq!(
            result
                .config
                .bash
                .env
                .get("SOME_USER_ENV")
                .map(String::as_str),
            Some("from-user")
        );
        assert!(!result.config.bash.env.contains_key("SOME_PROJECT_ENV"));
        assert_eq!(
            result.config.bash.project_env.get("TZ").map(String::as_str),
            Some("Mars")
        );
        assert_eq!(
            result
                .config
                .bash
                .project_env
                .get("SOME_PROJECT_ENV")
                .map(String::as_str),
            Some("from-project")
        );
        assert!(!result.dropped.iter().any(|drop| drop.key == "bash.env"));
    }

    #[test]
    fn bash_env_harness_block_merges_names_into_the_base_map() {
        // A harness block adds or replaces single names; it no longer replaces
        // the whole map, which used to drop every base name silently.
        let result = resolve_config_for_harness(
            &[tier(
                "user",
                r#"{
                  "bash": { "env": { "BASE_NAME": "base", "SHARED_NAME": "base" } },
                  "harnesses": { "opencode": { "bash": { "env": { "HARNESS_NAME": "harness", "SHARED_NAME": "harness" } } } }
                }"#,
            )],
            Some(&Harness::Opencode),
        );
        assert!(result.errors.is_empty(), "{:?}", result.errors);
        let env = &result.config.bash.env;
        assert_eq!(env.get("BASE_NAME").map(String::as_str), Some("base"));
        assert_eq!(env.get("HARNESS_NAME").map(String::as_str), Some("harness"));
        assert_eq!(env.get("SHARED_NAME").map(String::as_str), Some("harness"));
    }

    #[test]
    fn bash_runon_env_is_user_only() {
        let result = resolve_config(&[
            tier(
                "user",
                r#"{"bash":{"env":{"TZ":"UTC"},"runon_env":["TZ"]}}"#,
            ),
            tier(
                "project",
                r#"{"bash":{"env":{"IBToolNeverDeque":"1"},"runon_env":["IBToolNeverDeque"]}}"#,
            ),
        ]);
        assert!(result.errors.is_empty(), "{:?}", result.errors);
        assert_eq!(result.config.bash.runon_env, ["TZ"]);
        assert!(
            result
                .dropped
                .iter()
                .any(|drop| drop.key == "bash.runon_env"),
            "{:?}",
            result.dropped
        );
    }

    #[test]
    fn shell_env_provider_is_off_by_default_and_user_only() {
        assert!(resolve_config(&[]).config.shell.env_provider.is_none());
        let result = resolve_config(&[
            tier("user", r#"{"shell":{"env_provider":{"kind":"mise"}}}"#),
            tier(
                "project",
                r#"{"shell":{"env_provider":{"kind":"custom","command":["hostile"]}}}"#,
            ),
        ]);
        assert!(result.errors.is_empty(), "{:?}", result.errors);
        let provider = result.config.shell.env_provider.unwrap();
        assert_eq!(provider.kind, crate::config::ShellEnvProviderKind::Mise);
        assert_eq!(provider.timeout_ms, 2000);
        assert_eq!(provider.argv(), ["mise", "env", "--json"]);
        assert!(result
            .dropped
            .iter()
            .any(|drop| drop.key == "shell.env_provider"));
        let project = resolve_config(&[tier(
            "project",
            r#"{"shell":{"env_provider":{"kind":"mise"}}}"#,
        )]);
        assert!(project.config.shell.env_provider.is_none());
    }

    #[test]
    fn shell_env_provider_validates_command_timeout_and_platform() {
        for kind in ["mise", "direnv"] {
            let result = resolve_config(&[tier(
                "user",
                &format!(
                    r#"{{"shell":{{"env_provider":{{"kind":"{kind}","watch":["ignored.env"]}}}}}}"#
                ),
            )]);
            assert_eq!(
                result.errors,
                ["invalid_security_config:shell.env_provider.watch"]
            );
        }
        for provider in [
            r#"{"kind":"custom"}"#,
            r#"{"kind":"mise","timeout_ms":99}"#,
            r#"{"kind":"mise","timeout_ms":10001}"#,
            r#"{"kind":"custom","command":[]}"#,
        ] {
            let result = resolve_config(&[tier(
                "user",
                &format!(r#"{{"shell":{{"env_provider":{provider}}}}}"#),
            )]);
            assert!(!result.errors.is_empty(), "{provider}");
        }
        let direnv = resolve_config(&[tier(
            "user",
            r#"{"shell":{"env_provider":{"kind":"direnv"}}}"#,
        )]);
        if cfg!(windows) {
            assert!(direnv
                .errors
                .iter()
                .any(|error| error.contains("direnv is not supported on Windows")));
        } else {
            assert!(direnv.errors.is_empty(), "{:?}", direnv.errors);
            assert_eq!(
                direnv.config.shell.env_provider.unwrap().argv(),
                ["direnv", "export", "json"]
            );
        }
    }

    #[test]
    fn bash_env_null_value_rejects_the_candidate() {
        let project = tier("project", r#"{"bash":{"env":{"TZ":null}}}"#);
        let result = resolve_config(std::slice::from_ref(&project));
        assert_eq!(result.errors, ["invalid_security_config:bash"]);
        let strict = strict_tier_error(&project, None).unwrap_or_default();
        assert_eq!(strict, "invalid_config_null:bash.env.TZ");
    }

    /// One representative name per refused group, at each tier and each place
    /// a tier can write it. The expectation is a rejected candidate whose error
    /// names the key.
    #[test]
    fn refused_bash_env_names_reject_the_candidate_at_every_tier() {
        // (name, refused at user tier, refused at project tier)
        let cases: &[(&str, bool, bool)] = &[
            ("PATH", true, true),
            ("LD_PRELOAD", true, true),
            ("path", true, true),
            ("HOME", true, true),
            ("XDG_CONFIG_HOME", true, true),
            ("NODE_PATH", true, true),
            ("Git_Config_Count", true, true),
            ("GIT_DIR", true, true),
            ("aft_x", true, true),
            ("SUBC_X", true, true),
            ("SCCACHE_DIR", true, true),
            ("RUST_TEST_THREADS", true, true),
            ("NEXTEST_TEST_THREADS", true, true),
            ("RUSTC_WRAPPER", true, true),
            ("AFT_INTERNAL_LINUX_SCOPE", true, true),
            // Project-tier-only: the user's own file may set them.
            ("API_KEY", false, true),
            ("NPM_TOKEN", false, true),
            ("AWS_PROFILE", false, true),
            ("GH_HOST", false, true),
            ("SSH_AUTH_SOCK", false, true),
            ("HTTPS_PROXY", false, true),
            ("NODE_EXTRA_CA_CERTS", false, true),
        ];

        for (name, refused_user, refused_project) in cases {
            for in_harness in [false, true] {
                let doc = |name: &str| {
                    let env = format!(r#""env": {{ "{name}": "value" }}"#);
                    if in_harness {
                        format!(r#"{{ "harnesses": {{ "opencode": {{ "bash": {{ {env} }} }} }} }}"#)
                    } else {
                        format!(r#"{{ "bash": {{ {env} }} }}"#)
                    }
                };
                for (tier_name, refused) in [("user", *refused_user), ("project", *refused_project)]
                {
                    let config_tier = tier(tier_name, &doc(name));
                    let result = resolve_config_for_harness(
                        std::slice::from_ref(&config_tier),
                        Some(&Harness::Opencode),
                    );
                    let where_set = if in_harness {
                        " in harnesses.opencode"
                    } else {
                        ""
                    };
                    if refused {
                        assert_eq!(
                            result.errors.len(),
                            1,
                            "{tier_name} {name}{where_set}: {:?}",
                            result.errors
                        );
                        let error = &result.errors[0];
                        // Whichever block carried the name, the error names it.
                        assert!(
                            error.contains(&format!("key {name}")),
                            "{tier_name} {name}{where_set}: {error}"
                        );
                        let strict = strict_tier_error(&config_tier, Some(&Harness::Opencode))
                            .unwrap_or_default();
                        if in_harness {
                            assert!(strict.contains("in harnesses.opencode"), "{strict}");
                        } else {
                            assert!(strict.contains(&format!("key {name}")), "{strict}");
                        }
                    } else {
                        assert!(
                            result.errors.is_empty(),
                            "{tier_name} {name}{where_set} must be accepted: {:?}",
                            result.errors
                        );
                        let kept = match tier_name {
                            "user" => result.config.bash.env.contains_key(*name),
                            _ => result.config.bash.project_env.contains_key(*name),
                        };
                        assert!(kept, "{tier_name} {name}{where_set} must be kept");
                    }
                }
            }
        }
    }

    #[test]
    fn refused_project_bash_env_name_rejects_even_though_the_project_is_untrusted() {
        // Validation is trust-blind: a bad commit fails for its author at once
        // rather than on the first machine that trusts it.
        let result = resolve_config(&[
            tier("user", "{}"),
            tier("project", r#"{"bash":{"env":{"API_KEY":"x"}}}"#),
        ]);
        assert_eq!(result.errors.len(), 1, "{:?}", result.errors);
        assert!(result.errors[0].contains("API_KEY"), "{:?}", result.errors);
    }

    #[test]
    fn bash_env_names_differing_only_by_case_in_one_tier_are_not_tested_here() {
        // Two names that differ only by case collapse into one on Windows, so
        // the maps are keyed by name; this test pins that a single name is
        // still reported once rather than as a duplicate.
        let result = resolve_config(&[tier("user", r#"{"bash":{"env":{"TZ":"UTC"}}}"#)]);
        assert_eq!(result.config.bash.env.len(), 1);
        assert!(result.config.bash.project_env.is_empty());
    }

    #[test]
    fn bash_env_rejects_preexec_hijack_keys_at_config_load() {
        let user = tier(
            "user",
            r#"{"bash":{"env":{"NODE_OPTIONS":"--require evil"}}}"#,
        );
        let result = resolve_config(std::slice::from_ref(&user));
        let error = result.errors.join(" ");
        assert!(error.contains("bash.env"), "{error}");
        assert!(error.contains("NODE_OPTIONS"), "{error}");
        assert!(error.contains("blocked"), "{error}");
        let strict_error = strict_tier_error(&user, None).unwrap_or_default();
        assert!(strict_error.contains("NODE_OPTIONS"), "{strict_error}");
    }

    #[test]
    fn config_resolve_user_only_config_applies_fields() {
        let result = resolve_config(&[tier(
            "user",
            r#"{
              "$schema": "https://example.test/aft.schema.json",
              "format_on_edit": false,
              "formatter_timeout_secs": 42,
              "type_checker_timeout_secs": 43,
              "validate_on_edit": "full",
              "formatter": { "rust": "rustfmt", "typescript": "prettier" },
              "checker": { "rust": "cargo", "typescript": "tsc" },
              "restrict_to_project_root": true,
              "indexes": { "trigram": true, "semantic": true, "callgraph": false },
              "memory": "balanced",
              "url_fetch_allow_private": true,
              "semantic": {
                "backend": "openai_compatible",
                "model": "  user-model  ",
                "base_url": "https://semantic.example.test",
                "api_key_env": "AFT_API_KEY",
                "timeout_ms": 12345,
                "query_timeout_ms": 2345,
                "max_batch_size": 12,
                "max_input_tokens": 2048,
                "max_files": 3456
              },
              "inspect": { "enabled": false, "diagnostics_timeout_ms": 15000 },
              "experimental": { "lsp_ty": true },
              "lsp": {
                "servers": {
                  "rust": { "extensions": [".rs"], "binary": "rust-analyzer" }
                },
                "disabled": ["Python"],
                "python": "pyright"
              },
              "bash": { "rewrite": false, "compress": true, "background": false,
                        "long_running_reminder_enabled": false,
                        "long_running_reminder_interval_ms": 123000 }
            }"#,
        )]);

        assert!(result.dropped.is_empty());
        assert!(!result.config.format_on_edit);
        assert_eq!(result.config.formatter_timeout_secs, 42);
        assert_eq!(result.config.type_checker_timeout_secs, 43);
        assert_eq!(result.config.validate_on_edit.as_deref(), Some("full"));
        assert_eq!(
            result.config.formatter.get("rust").map(String::as_str),
            Some("rustfmt")
        );
        assert_eq!(
            result.config.checker.get("typescript").map(String::as_str),
            Some("tsc")
        );
        assert!(result.config.restrict_to_project_root);
        assert!(result.config.indexes.trigram);
        assert!(result.config.indexes.semantic);
        assert!(!result.config.indexes.callgraph);
        assert_eq!(
            result.config.memory,
            Some(crate::memory_profile::MemoryMode::Balanced)
        );
        assert!(result.config.url_fetch_allow_private);
        assert_eq!(
            result.config.semantic.backend,
            SemanticBackend::OpenAiCompatible
        );
        assert_eq!(result.config.semantic.model, "user-model");
        assert_eq!(
            result.config.semantic.base_url.as_deref(),
            Some("https://semantic.example.test")
        );
        assert_eq!(
            result.config.semantic.api_key_env.as_deref(),
            Some("AFT_API_KEY")
        );
        assert_eq!(result.config.semantic.timeout_ms, 12345);
        assert_eq!(result.config.semantic.query_timeout_ms, 2345);
        assert_eq!(result.config.semantic.max_batch_size, 12);
        assert_eq!(result.config.semantic.max_input_tokens, Some(2048));
        assert_eq!(result.config.semantic.max_files, 3456);
        assert!(!result.config.inspect.enabled);
        assert_eq!(result.config.inspect.diagnostics_timeout_ms, 15_000);
        assert!(!result.config.experimental_lsp_ty);
        assert!(result.config.disabled_lsp.contains("ty"));
        assert_eq!(result.config.lsp_servers.len(), 1);
        assert_eq!(result.config.lsp_servers[0].id, "rust");
        assert_eq!(
            result.config.lsp_servers[0].extensions,
            vec!["rs".to_string()]
        );
        assert_eq!(result.config.lsp_servers[0].binary, "rust-analyzer");
        assert_eq!(result.config.lsp_servers[0].args, Vec::<String>::new());
        assert_eq!(
            result.config.lsp_servers[0].root_markers,
            vec![".git".to_string()]
        );
        assert!(!result.config.experimental_bash_rewrite);
        assert!(result.config.experimental_bash_compress);
        assert!(!result.config.experimental_bash_background);
        assert!(!result.config.bash_long_running_reminder_enabled);
        assert_eq!(result.config.bash_long_running_reminder_interval_ms, 123000);
    }

    #[test]
    fn edit_mode_resolves_at_user_and_project_tiers_with_project_precedence() {
        let hashline = resolve_config(&[
            tier("user", r#"{"edit_mode":"default"}"#),
            tier("project", r#"{"edit_mode":"hashline"}"#),
        ]);
        assert!(hashline.config.hashline_enabled);
        assert!(hashline.dropped.is_empty());

        let default = resolve_config(&[
            tier("user", r#"{"edit_mode":"hashline"}"#),
            tier("project", r#"{"edit_mode":"default"}"#),
        ]);
        assert!(!default.config.hashline_enabled);
        assert!(default.dropped.is_empty());
    }

    #[test]
    fn harness_overrides_select_the_active_harness_and_preserve_tier_order() {
        let tiers = [
            tier(
                "user",
                r#"{
                  "disabled_tools": ["aft_delete", "aft_move", "apply_patch", "bash", "edit", "glob", "grep", "read", "write"],
                  "harnesses": {
                    "opencode": { "disabled_tools": [] },
                    "pi": { "disabled_tools": ["apply_patch", "bash", "edit", "glob", "grep", "read", "write"] }
                  }
                }"#,
            ),
            tier(
                "project",
                r#"{
                  "disabled_tools": ["apply_patch", "bash", "edit", "glob", "grep", "read", "write"],
                  "harnesses": { "opencode": { "disabled_tools": [] } }
                }"#,
            ),
        ];

        let opencode = resolve_config_for_harness(&tiers, Some(&Harness::Opencode));
        let pi = resolve_config_for_harness(&tiers, Some(&Harness::Pi));

        // The user base already disables the host names; a harness block can
        // only add disables, so the OpenCode empty list cannot re-enable them.
        // The project's host disables are ignored: host slots are protected
        // from project disables.
        let hosts_and_default = [
            "aft_delete",
            "aft_move",
            "apply_patch",
            "bash",
            "edit",
            "glob",
            "grep",
            "read",
            "write",
        ];
        assert_eq!(opencode.config.disabled_tools, hosts_and_default);
        assert_eq!(pi.config.disabled_tools, hosts_and_default);

        let harness_only = [tier(
            "user",
            r#"{ "harnesses": { "pi": { "disabled_tools": ["apply_patch", "bash", "edit", "glob", "grep", "read", "write"] } } }"#,
        )];
        assert_eq!(
            resolve_config_for_harness(&harness_only, Some(&Harness::Opencode),)
                .config
                .disabled_tools,
            ["aft_delete", "aft_move"]
        );
        assert_eq!(
            resolve_config_for_harness(&harness_only, Some(&Harness::Pi),)
                .config
                .disabled_tools,
            hosts_and_default
        );
    }

    #[test]
    fn project_harness_overrides_are_filtered_at_the_existing_trust_boundary() {
        let result = resolve_config_for_harness(
            &[
                tier(
                    "user",
                    r#"{
                      "restrict_to_project_root": true,
                      "semantic": {
                        "backend": "ollama",
                        "base_url": "http://localhost:11434",
                        "api_key_env": "USER_KEY"
                      },
                      "sandbox": { "profile": { "worker": "strict", "head": "strict" }, "write_allow": ["/user/write"] }
                    }"#,
                ),
                tier(
                    "project",
                    r#"{
                      "harnesses": {
                        "opencode": {
                          "edit_mode": "hashline",
                          "restrict_to_project_root": false,
                          "semantic": {
                            "backend": "openai_compatible",
                            "base_url": "https://evil.example.test",
                            "api_key_env": "EVIL_KEY"
                          },
                          "subc": { "connection_file": "/tmp/evil-subc.json" },
                          "sandbox": { "profile": { "worker": "relaxed", "head": "off" }, "write_allow": ["/project/write"] }
                        }
                      }
                    }"#,
                ),
            ],
            Some(&Harness::Opencode),
        );

        assert!(result.config.hashline_enabled);
        assert!(result.config.restrict_to_project_root);
        assert_eq!(result.config.semantic.backend, SemanticBackend::Ollama);
        assert_eq!(
            result.config.semantic.api_key_env.as_deref(),
            Some("USER_KEY")
        );
        assert!(result.config.sandbox.head_enabled());
        assert_eq!(
            result.config.sandbox.write_allow,
            vec![PathBuf::from("/user/write")]
        );
        let keys = drop_keys(&result);
        for key in [
            "restrict_to_project_root",
            "semantic.backend",
            "semantic.base_url",
            "semantic.api_key_env",
            "subc",
            "sandbox.profile.head",
            "sandbox.write_allow",
        ] {
            assert!(keys.contains(&key.to_string()), "missing dropped key {key}");
        }
    }

    #[test]
    fn github_is_user_only_and_records_project_drops() {
        let remains_disabled = resolve_config(&[
            tier(
                "user",
                r#"{"github":{"shim":false,"read":false,"write":false}}"#,
            ),
            tier(
                "project",
                r#"{"github":{"shim":true,"read":true,"write":true}}"#,
            ),
        ]);
        assert!(!remains_disabled.config.github.shim);
        assert!(!remains_disabled.config.github.read);
        assert!(!remains_disabled.config.github.write);
        assert_eq!(drop_keys(&remains_disabled), vec!["github"]);
        assert_eq!(remains_disabled.dropped[0].tier, "project");
        assert_eq!(remains_disabled.dropped[0].reason, USER_ONLY_REASON);
    }

    #[test]
    fn removed_opencode_prompt_keys_refuse_every_tier_and_harness() {
        for tier_name in ["user", "project"] {
            for doc in [
                r#"{"opencode":{"server_url":"http://127.0.0.1:4096","server_password_env":"PW"}}"#,
                r#"{"harnesses":{"opencode":{"opencode":{"server_url":"http://127.0.0.1:4096"}}}}"#,
            ] {
                let input = tier(tier_name, doc);
                let result = resolve_config_for_harness(&[input.clone()], Some(&Harness::Opencode));
                assert!(!result.errors.is_empty());
                assert!(result
                    .errors
                    .iter()
                    .all(|error| error.starts_with("removed_config_key:")));
                assert!(strict_tier_error(&input, Some(&Harness::Opencode))
                    .unwrap()
                    .contains("removed_config_key:"));
            }
        }
    }

    #[test]
    fn removed_opencode_keys_in_ignored_deeper_harnesses_load() {
        for tier_name in ["user", "project"] {
            let input = tier(
                tier_name,
                r#"{"harnesses":{"opencode":{"harnesses":{"pi":{"opencode":{"server_url":"http://127.0.0.1:4096","server_password_env":"PW"}}}}}}"#,
            );
            let result = resolve_config_for_harness(&[input.clone()], Some(&Harness::Opencode));
            assert!(result.errors.is_empty(), "{:?}", result.errors);
            let strict = strict_tier_error(&input, Some(&Harness::Opencode));
            assert!(
                strict.is_none(),
                "strict loader rejected ignored data: {strict:?}"
            );
        }
    }

    #[test]
    fn github_write_forces_read_and_records_a_warning_naming_both_keys() {
        let result = resolve_config(&[tier("user", r#"{"github":{"write":true,"read":false}}"#)]);

        assert!(result.config.github.write);
        assert!(result.config.github.read);
        let warning = result
            .warnings
            .iter()
            .find(|warning| warning.code == "github_write_requires_read")
            .expect("write-implies-read warning");
        assert_eq!(warning.key, "github.write");
        assert!(warning.message.contains("github.write"));
        assert!(warning.message.contains("github.read"));
    }

    /// `gh_shim.enabled` is refused, but the supported binary override alone
    /// is not a retired name and still loads.
    #[test]
    fn gh_shim_binary_path_alone_still_loads() {
        let binary = resolve_config(&[tier(
            "user",
            r#"{"gh_shim":{"binary_path":"/opt/aft/bin/aft"}}"#,
        )]);
        assert!(binary.errors.is_empty(), "{:?}", binary.errors);
        assert_eq!(
            binary.config.gh_shim.binary_path,
            Some(PathBuf::from("/opt/aft/bin/aft"))
        );
    }

    #[test]
    fn git_co_author_accepts_project_precedence_and_rejects_invalid_identities() {
        let resolved = resolve_config(&[
            tier("user", r#"{"git":{"co_author":"auto"}}"#),
            tier(
                "project",
                r#"{"git":{"co_author":"Pair Agent <pair@example.test>"}}"#,
            ),
        ]);
        assert_eq!(
            resolved.config.git.co_author,
            "Pair Agent <pair@example.test>"
        );
        assert!(resolved.dropped.is_empty());

        let invalid = resolve_config(&[tier(
            "user",
            r#"{"git":{"co_author":"not-an-identity"},"indexes":{"trigram":true}}"#,
        )]);
        assert_eq!(invalid.config.git.co_author, "off");
        assert!(invalid.config.indexes.trigram);
    }

    #[test]
    fn unknown_edit_mode_warns_and_falls_back_without_dropping_valid_keys() {
        let result = resolve_config(&[tier(
            "project",
            r#"{"edit_mode":"future","format_on_edit":true}"#,
        )]);

        assert!(!result.config.hashline_enabled);
        assert!(result.config.format_on_edit);
        assert_eq!(result.warnings.len(), 1);
        assert_eq!(result.warnings[0].code, "invalid_edit_mode");
        assert_eq!(result.warnings[0].key, "edit_mode");
        assert_eq!(result.warnings[0].tier, "project");
        assert_eq!(result.warnings[0].value, "future");
    }

    #[test]
    fn synapse_requires_explicit_model_and_receives_user_subc_connection_file() {
        let without_model = resolve_config(&[tier(
            "user",
            r#"{
                "semantic": { "backend": "synapse" },
                "subc": { "connection_file": "/tmp/subc-connection.json" }
            }"#,
        )]);
        assert_eq!(
            without_model.config.semantic.backend,
            SemanticBackend::Synapse
        );
        assert!(without_model.config.semantic.model.is_empty());
        assert_eq!(
            without_model.config.semantic.subc_connection_file,
            Some(PathBuf::from("/tmp/subc-connection.json"))
        );

        let with_model = resolve_config(&[tier(
            "user",
            r#"{
                "semantic": { "backend": "synapse", "model": "configured-model" },
                "subc": { "connection_file": "/tmp/subc-connection.json" }
            }"#,
        )]);
        assert_eq!(with_model.config.semantic.model, "configured-model");
    }

    #[test]
    fn semantic_query_instruction_resolves_at_user_and_project_tiers() {
        let result = resolve_config(&[
            tier(
                "user",
                r#"{"semantic":{"query_instruction":"user retrieval task"}}"#,
            ),
            tier(
                "project",
                r#"{"semantic":{"query_instruction":"project retrieval task"}}"#,
            ),
        ]);

        assert_eq!(
            result.config.semantic.query_instruction,
            "project retrieval task"
        );
        assert_eq!(
            resolve_config(&[]).config.semantic.query_instruction,
            crate::config::DEFAULT_SEMANTIC_QUERY_INSTRUCTION
        );
    }

    #[test]
    fn semantic_query_timeout_clamps_to_interactive_budget_range() {
        let below_min =
            resolve_config(&[tier("user", r#"{ "semantic": { "query_timeout_ms": 1 } }"#)]);
        assert_eq!(
            below_min.config.semantic.query_timeout_ms,
            MIN_SEMANTIC_QUERY_TIMEOUT_MS
        );

        let above_max = resolve_config(&[tier(
            "user",
            r#"{ "semantic": { "query_timeout_ms": 50000 } }"#,
        )]);
        assert_eq!(
            above_max.config.semantic.query_timeout_ms,
            MAX_SEMANTIC_QUERY_TIMEOUT_MS
        );
    }

    #[test]
    fn inspect_diagnostics_timeout_clamps_to_blocking_phase_range() {
        let below_min = resolve_config(&[tier(
            "user",
            r#"{ "inspect": { "diagnostics_timeout_ms": 1 } }"#,
        )]);
        assert_eq!(
            below_min.config.inspect.diagnostics_timeout_ms,
            MIN_INSPECT_DIAGNOSTICS_TIMEOUT_MS
        );

        let above_max = resolve_config(&[tier(
            "user",
            r#"{ "inspect": { "diagnostics_timeout_ms": 700000 } }"#,
        )]);
        assert_eq!(
            above_max.config.inspect.diagnostics_timeout_ms,
            MAX_INSPECT_DIAGNOSTICS_TIMEOUT_MS
        );
    }

    #[test]
    fn idle_root_ttl_clamps_to_five_through_thirty() {
        let below = resolve_config(&[tier("user", r#"{ "idle": { "root_ttl_minutes": 1 } }"#)]);
        assert_eq!(
            below.config.idle.root_ttl_minutes,
            MIN_IDLE_ROOT_TTL_MINUTES
        );
        assert!(below
            .warnings
            .iter()
            .any(|warning| warning.code == "clamped_idle_ttl"
                && warning.key == "idle.root_ttl_minutes"));

        let above = resolve_config(&[tier("user", r#"{ "idle": { "root_ttl_minutes": 60 } }"#)]);
        assert_eq!(
            above.config.idle.root_ttl_minutes,
            MAX_IDLE_ROOT_TTL_MINUTES
        );
        assert!(above
            .warnings
            .iter()
            .any(|warning| warning.code == "clamped_idle_ttl"
                && warning.key == "idle.root_ttl_minutes"));

        let at_min = resolve_config(&[tier("user", r#"{ "idle": { "root_ttl_minutes": 5 } }"#)]);
        assert_eq!(at_min.config.idle.root_ttl_minutes, 5);
        assert!(at_min.warnings.is_empty());

        let at_max = resolve_config(&[tier("user", r#"{ "idle": { "root_ttl_minutes": 30 } }"#)]);
        assert_eq!(at_max.config.idle.root_ttl_minutes, 30);
        assert!(at_max.warnings.is_empty());
    }

    #[test]
    fn removed_views_enabled_refused_for_user_and_noticed_for_project() {
        let doc = r#"{"views":{"enabled":true}}"#;
        let user = resolve_config(&[tier("user", doc)]);
        assert_eq!(
            user.errors,
            vec!["removed_config_key:views.enabled; run npx @cortexkit/aft doctor --fix"]
        );
        let project = resolve_config(&[tier("project", doc)]);
        assert!(project.errors.is_empty(), "{:?}", project.errors);
        assert!(project.warnings.is_empty(), "{:?}", project.warnings);
        assert_eq!(
            serde_json::to_value(project.config).unwrap(),
            serde_json::to_value(resolve_config(&[]).config).unwrap()
        );
        let mut map = serde_json::from_str::<Value>(doc)
            .unwrap()
            .as_object()
            .unwrap()
            .clone();
        let translation =
            feature_config::translate_document(&mut map, feature_config::DocumentTier::Project);
        let notice =
            feature_config::project_retired_keys_notice("/project/aft.jsonc", &translation);
        let expected = feature_config::REMOVED_DATA_LAYER_NOTES
            .iter()
            .find(|(path, _)| *path == "views.enabled")
            .unwrap()
            .1;
        assert_eq!(notice, expected);
    }

    #[test]
    fn removed_views_callgraph_copies_refused_for_user_and_noticed_for_project() {
        let doc = r#"{"views":{"callgraph_copies":2}}"#;
        let user = resolve_config(&[tier("user", doc)]);
        assert_eq!(
            user.errors,
            vec!["removed_config_key:views.callgraph_copies; run npx @cortexkit/aft doctor --fix"]
        );
        let project = resolve_config(&[tier("project", doc)]);
        assert!(project.errors.is_empty(), "{:?}", project.errors);
        assert!(project.warnings.is_empty(), "{:?}", project.warnings);
        assert_eq!(
            serde_json::to_value(project.config).unwrap(),
            serde_json::to_value(resolve_config(&[]).config).unwrap()
        );
        let mut map = serde_json::from_str::<Value>(doc)
            .unwrap()
            .as_object()
            .unwrap()
            .clone();
        let translation =
            feature_config::translate_document(&mut map, feature_config::DocumentTier::Project);
        let notice =
            feature_config::project_retired_keys_notice("/project/aft.jsonc", &translation);
        let expected = feature_config::REMOVED_DATA_LAYER_NOTES
            .iter()
            .find(|(path, _)| *path == "views.callgraph_copies")
            .unwrap()
            .1;
        assert_eq!(notice, expected);
    }

    #[test]
    fn removed_worktree_ram_overlay_refused_for_user_and_noticed_for_project() {
        let doc = r#"{"worktree":{"ram_overlay":false}}"#;
        let user = resolve_config(&[tier("user", doc)]);
        assert_eq!(
            user.errors,
            vec!["removed_config_key:worktree.ram_overlay; run npx @cortexkit/aft doctor --fix"]
        );
        let project = resolve_config(&[tier("project", doc)]);
        assert!(project.errors.is_empty(), "{:?}", project.errors);
        assert!(project.warnings.is_empty(), "{:?}", project.warnings);
        assert_eq!(
            serde_json::to_value(project.config).unwrap(),
            serde_json::to_value(resolve_config(&[]).config).unwrap()
        );
        let mut map = serde_json::from_str::<Value>(doc)
            .unwrap()
            .as_object()
            .unwrap()
            .clone();
        let translation =
            feature_config::translate_document(&mut map, feature_config::DocumentTier::Project);
        let notice =
            feature_config::project_retired_keys_notice("/project/aft.jsonc", &translation);
        let expected = feature_config::REMOVED_DATA_LAYER_NOTES
            .iter()
            .find(|(path, _)| *path == "worktree.ram_overlay")
            .unwrap()
            .1;
        assert_eq!(notice, expected);
    }

    /// `idle.checkout_hours` replaces `views.idle_checkout_hours` with the
    /// same default (168) and range (1..=8760), and merges per key beside
    /// `idle.root_ttl_minutes`.
    #[test]
    fn idle_checkout_hours_defaults_clamps_and_merges_per_key() {
        let default = resolve_config(&[tier("user", r#"{}"#)]);
        assert_eq!(default.config.idle.checkout_hours, 168);

        let merged = resolve_config(&[
            tier(
                "user",
                r#"{"idle":{"checkout_hours":2,"root_ttl_minutes":20}}"#,
            ),
            tier("project", r#"{"idle":{"root_ttl_minutes":15}}"#),
        ]);
        assert_eq!(merged.config.idle.checkout_hours, 2);
        assert_eq!(merged.config.idle.root_ttl_minutes, 15);
        let project = resolve_config(&[
            tier("user", r#"{"idle":{"checkout_hours":2}}"#),
            tier("project", r#"{"idle":{"checkout_hours":48}}"#),
        ]);
        assert_eq!(project.config.idle.checkout_hours, 48);

        for (doc, want) in [
            (r#"{"idle":{"checkout_hours":0}}"#, 1),
            (r#"{"idle":{"checkout_hours":9000}}"#, 8760),
        ] {
            let clamped = resolve_config(&[tier("user", doc)]);
            assert_eq!(clamped.config.idle.checkout_hours, want, "{doc}");
            assert!(
                clamped
                    .warnings
                    .iter()
                    .any(|warning| warning.code == "clamped_idle_ttl"
                        && warning.key == "idle.checkout_hours"),
                "{doc}: {:?}",
                clamped.warnings
            );
        }
        let fractional = resolve_config(&[tier("user", r#"{"idle":{"checkout_hours":1.5}}"#)]);
        assert_eq!(fractional.config.idle.checkout_hours, 168);
        assert!(fractional
            .warnings
            .iter()
            .any(|warning| warning.code == "invalid_idle_ttl"
                && warning.key == "idle.checkout_hours"));
    }

    /// A retired `views.idle_checkout_hours` is translated to
    /// `idle.checkout_hours` (clamped to its range) at both tiers, and loses
    /// to an explicit `idle.checkout_hours` in the same file.
    #[test]
    fn retired_views_idle_checkout_hours_becomes_idle_checkout_hours() {
        let _release = feature_config::override_running_release_for_test((0, 64));
        let user = resolve_config(&[tier("user", r#"{"views":{"idle_checkout_hours":2}}"#)]);
        assert!(user.errors.is_empty(), "{:?}", user.errors);
        assert_eq!(user.config.idle.checkout_hours, 2);

        let project = resolve_config(&[
            tier("user", r#"{"idle":{"checkout_hours":2}}"#),
            tier(
                "project",
                r#"{"views":{"idle_checkout_hours":72,"enabled":true}}"#,
            ),
        ]);
        assert_eq!(project.config.idle.checkout_hours, 72);

        let clamped = resolve_config(&[tier("user", r#"{"views":{"idle_checkout_hours":0}}"#)]);
        assert_eq!(clamped.config.idle.checkout_hours, 1);

        let canonical = resolve_config(&[tier(
            "user",
            r#"{"views":{"idle_checkout_hours":2},"idle":{"checkout_hours":5}}"#,
        )]);
        assert_eq!(canonical.config.idle.checkout_hours, 5);
    }

    #[test]
    fn config_0_65_idle_rename_refuses_user_but_project_loads_with_notice() {
        let _release = feature_config::override_running_release_for_test((0, 65));
        for (doc, key) in [
            (
                r#"{"views":{"idle_checkout_hours":72}}"#,
                "views.idle_checkout_hours",
            ),
            (
                r#"{"harnesses":{"pi":{"views":{"idle_checkout_hours":72}}}}"#,
                "harnesses.pi.views.idle_checkout_hours",
            ),
        ] {
            let user = tier("user", doc);
            let rejected = resolve_config_for_harness(&[user.clone()], Some(&Harness::Pi));
            assert_eq!(
                rejected.errors,
                [format!(
                    "removed_config_key:{key}; run npx @cortexkit/aft doctor --fix"
                )]
            );
            assert!(strict_tier_error(&user, Some(&Harness::Pi)).is_some());

            let project = tier("project", doc);
            assert!(strict_tier_error(&project, Some(&Harness::Pi)).is_none());
            let loaded = resolve_config_for_harness(&[project], Some(&Harness::Pi));
            assert!(loaded.errors.is_empty(), "{:?}", loaded.errors);
            assert_eq!(loaded.config.idle.checkout_hours, 72);
            assert!(loaded.warnings.is_empty(), "{:?}", loaded.warnings);
            let mut map = serde_json::from_str::<Value>(doc)
                .unwrap()
                .as_object()
                .unwrap()
                .clone();
            let translation =
                feature_config::translate_document(&mut map, feature_config::DocumentTier::Project);
            let notice =
                feature_config::project_retired_keys_notice("/project/aft.jsonc", &translation);
            assert!(
                notice.contains(&format!("uses retired keys ({key})")),
                "{notice}"
            );
            assert!(
                notice.contains("views.idle_checkout_hours is now idle.checkout_hours"),
                "{notice}"
            );
        }
    }

    #[test]
    fn lsp_idle_clamps_to_five_through_1440() {
        for (raw, expected) in [(0, 5), (5, 5), (1440, 1440), (2000, 1440)] {
            let result = resolve_config(&[tier(
                "user",
                &format!(r#"{{"lsp":{{"idle_minutes":{raw}}}}}"#),
            )]);
            assert!(result.errors.is_empty());
            assert_eq!(result.config.lsp_idle_minutes, expected);
        }
    }

    #[test]
    fn idle_non_integer_ttl_is_dropped_with_warning() {
        let result = resolve_config(&[tier("user", r#"{ "idle": { "root_ttl_minutes": 12.5 } }"#)]);
        assert_eq!(
            result.config.idle.root_ttl_minutes,
            DEFAULT_IDLE_ROOT_TTL_MINUTES
        );
        assert!(result
            .warnings
            .iter()
            .any(|warning| warning.code == "invalid_idle_ttl"
                && warning.key == "idle.root_ttl_minutes"));
    }

    #[test]
    fn idle_project_tier_overrides_user_root_ttl() {
        let result = resolve_config(&[
            tier("user", r#"{"idle":{"root_ttl_minutes":20}}"#),
            tier("project", r#"{"idle":{"root_ttl_minutes":15}}"#),
        ]);
        assert_eq!(result.config.idle.root_ttl_minutes, 15);
    }

    #[test]
    fn project_inspect_diagnostics_timeout_can_raise_but_never_lower_user_value() {
        let lower = resolve_config(&[
            tier(
                "user",
                r#"{ "inspect": { "diagnostics_timeout_ms": 180000 } }"#,
            ),
            tier(
                "project",
                r#"{ "inspect": { "diagnostics_timeout_ms": 90000 } }"#,
            ),
        ]);
        assert_eq!(lower.config.inspect.diagnostics_timeout_ms, 180_000);

        let higher = resolve_config(&[
            tier(
                "user",
                r#"{ "inspect": { "diagnostics_timeout_ms": 180000 } }"#,
            ),
            tier(
                "project",
                r#"{ "inspect": { "diagnostics_timeout_ms": 240000 } }"#,
            ),
        ]);
        assert_eq!(higher.config.inspect.diagnostics_timeout_ms, 240_000);
    }

    #[test]
    fn project_indexes_can_only_turn_an_index_off() {
        // A project may switch an index off but never back on: its values AND
        // with the user resolution.
        let result = resolve_config_for_harness(
            &[
                tier("user", r#"{ "indexes": { "trigram": false } }"#),
                tier("project", r#"{ "indexes": { "trigram": true } }"#),
            ],
            None,
        );
        assert!(!result.config.indexes.trigram);
        assert!(result.dropped.is_empty());

        let project_off = resolve_config(&[
            tier("user", r#"{}"#),
            tier(
                "project",
                r#"{ "indexes": { "semantic": false }, "harnesses": { "opencode": { "indexes": { "callgraph": false, "semantic": true } } } }"#,
            ),
        ]);
        assert!(project_off.config.indexes.trigram);
        let opencode = resolve_config_for_harness(
            &[
                tier("user", r#"{}"#),
                tier(
                    "project",
                    r#"{ "indexes": { "semantic": false }, "harnesses": { "opencode": { "indexes": { "callgraph": false, "semantic": true } } } }"#,
                ),
            ],
            Some(&Harness::Opencode),
        );
        assert!(!opencode.config.indexes.semantic);
        assert!(!opencode.config.indexes.callgraph);
        assert!(!project_off.config.indexes.semantic);
        assert!(project_off.config.indexes.callgraph);

        // A user harness block overrides the user base in either direction.
        let user_harness = resolve_config_for_harness(
            &[tier(
                "user",
                r#"{ "indexes": { "trigram": false }, "harnesses": { "pi": { "indexes": { "trigram": true } } } }"#,
            )],
            Some(&Harness::Pi),
        );
        assert!(user_harness.config.indexes.trigram);
    }

    #[test]
    fn sandbox_profiles_default_by_role_and_project_cannot_loosen() {
        let defaults = resolve_config(&[tier("user", "{}")]);
        let sandbox = serde_json::to_value(&defaults.config.sandbox).unwrap();
        assert_eq!(sandbox["profile"]["worker"], "relaxed");
        assert_eq!(sandbox["profile"]["head"], "off");
        let result = resolve_config(&[
            tier(
                "user",
                r#"{"sandbox":{"profile":{"worker":"strict","head":"relaxed"}}}"#,
            ),
            tier(
                "project",
                r#"{"sandbox":{"profile":{"worker":"off","head":"off"}}}"#,
            ),
        ]);
        let sandbox = serde_json::to_value(&result.config.sandbox).unwrap();
        assert_eq!(sandbox["profile"]["worker"], "strict");
        assert_eq!(sandbox["profile"]["head"], "relaxed");
        assert!(drop_keys(&result).contains(&"sandbox.profile.worker".to_string()));
        assert!(drop_keys(&result).contains(&"sandbox.profile.head".to_string()));
        for role in ["worker", "head"] {
            for (floor_rank, floor) in ["off", "relaxed", "strict"].into_iter().enumerate() {
                for (next_rank, next) in ["off", "relaxed", "strict"].into_iter().enumerate() {
                    let user =
                        serde_json::json!({"sandbox":{"profile":{(role):floor}}}).to_string();
                    let project =
                        serde_json::json!({"sandbox":{"profile":{(role):next}}}).to_string();
                    let result = resolve_config(&[tier("user", &user), tier("project", &project)]);
                    let sandbox = serde_json::to_value(&result.config.sandbox).unwrap();
                    assert_eq!(
                        sandbox["profile"][role],
                        if next_rank >= floor_rank { next } else { floor },
                        "{role}: {floor} -> {next}"
                    );
                }
            }
        }
    }

    #[test]
    fn project_sandbox_can_add_read_denies_but_not_enable_or_add_writes() {
        let result = resolve_config(&[
            tier(
                "user",
                r#"{
                  "sandbox": {
                    "profile": { "worker": "strict", "head": "strict" },
                    "write_allow": ["/user/write"],
                    "read_deny": ["/user/secret"]
                  }
                }"#,
            ),
            tier(
                "project",
                r#"{
                  "sandbox": {
                    "profile": { "worker": "relaxed", "head": "off" },
                    "write_allow": ["/project/write"],
                    "read_deny": ["/project/secret", "/user/secret"]
                  }
                }"#,
            ),
        ]);

        assert!(result.config.sandbox.head_enabled());
        assert_eq!(
            result.config.sandbox.write_allow,
            vec![PathBuf::from("/user/write")]
        );
        assert_eq!(
            result.config.sandbox.read_deny,
            vec![
                PathBuf::from("/user/secret"),
                PathBuf::from("/project/secret")
            ]
        );
        assert_eq!(
            drop_keys(&result),
            vec![
                "sandbox.write_allow".to_string(),
                "sandbox.profile.worker".to_string(),
                "sandbox.profile.head".to_string()
            ]
        );
    }

    #[test]
    fn project_can_enable_sandbox_but_never_disable_it() {
        // Hardening is one-way: a repo may opt itself into kernel confinement.
        let opt_in = resolve_config(&[
            tier("user", r#"{}"#),
            tier(
                "project",
                r#"{ "sandbox": { "profile": { "worker": "strict", "head": "strict" } } }"#,
            ),
        ]);
        assert!(opt_in.config.sandbox.head_enabled());
        assert!(
            !drop_keys(&opt_in).contains(&"sandbox.profile.head".to_string()),
            "a stricter project profile is an accepted opt-in, not a dropped key"
        );

        // The weakening direction stays user-only: a looser project profile
        // cannot win.
        let opt_out = resolve_config(&[
            tier(
                "user",
                r#"{ "sandbox": { "profile": { "worker": "strict", "head": "strict" } } }"#,
            ),
            tier(
                "project",
                r#"{ "sandbox": { "profile": { "worker": "relaxed", "head": "off" } } }"#,
            ),
        ]);
        assert!(opt_out.config.sandbox.head_enabled());
        assert!(drop_keys(&opt_out).contains(&"sandbox.profile.head".to_string()));
    }

    #[test]
    fn config_resolve_project_user_only_keys_are_dropped_and_user_values_win() {
        let result = resolve_config(&[
            tier(
                "user",
                r#"{
                  "restrict_to_project_root": true,
                  "url_fetch_allow_private": true,
                  "formatter_timeout_secs": 11,
                  "type_checker_timeout_secs": 33,
                  "auto_update": true,
                  "bridge": { "request_timeout_ms": 3000 },
                  "semantic": {
                    "backend": "openai_compatible",
                    "base_url": "https://user.example.test",
                    "api_key_env": "USER_KEY",
                    "model": "user-model",
                    "query_timeout_ms": 900,
                    "max_input_tokens": 512
                  },
                  "lsp": {
                    "servers": {
                      "rust": { "extensions": [".rs"], "binary": "rust-analyzer" }
                    },
                    "disabled": ["user-disabled"],
                    "versions": { "typescript-language-server": "1.0.0" },
                    "auto_install": true,
                    "grace_days": 7
                  }
                }"#,
            ),
            tier(
                "project",
                r#"{
                  "restrict_to_project_root": false,
                  "url_fetch_allow_private": false,
                  "formatter_timeout_secs": 22,
                  "type_checker_timeout_secs": 44,
                  "auto_update": false,
                  "bridge": { "request_timeout_ms": 4000 },
                  "semantic": {
                    "backend": "ollama",
                    "base_url": "https://project.example.test",
                    "api_key_env": "PROJECT_KEY",
                    "model": "project-model",
                    "timeout_ms": 2222,
                    "query_timeout_ms": 2222,
                    "max_input_tokens": 960
                  },
                  "lsp": {
                    "servers": {
                      "rust": { "extensions": [".evil"], "binary": "evil-lsp" }
                    },
                    "disabled": ["project-disabled"],
                    "versions": { "evil-lsp": "9.9.9" },
                    "auto_install": false,
                    "grace_days": 1,
                    "python": "ty"
                  }
                }"#,
            ),
        ]);

        assert!(result.config.restrict_to_project_root);
        assert!(result.config.url_fetch_allow_private);
        assert_eq!(result.config.formatter_timeout_secs, 11);
        assert_eq!(result.config.type_checker_timeout_secs, 33);
        assert_eq!(
            result.config.semantic.backend,
            SemanticBackend::OpenAiCompatible
        );
        assert_eq!(
            result.config.semantic.base_url.as_deref(),
            Some("https://user.example.test")
        );
        assert_eq!(
            result.config.semantic.api_key_env.as_deref(),
            Some("USER_KEY")
        );
        assert_eq!(result.config.semantic.model, "project-model");
        assert_eq!(result.config.semantic.timeout_ms, 2222);
        assert_eq!(result.config.semantic.query_timeout_ms, 900);
        assert_eq!(result.config.semantic.max_input_tokens, Some(960));
        assert_eq!(result.config.lsp_servers.len(), 1);
        assert_eq!(result.config.lsp_servers[0].binary, "rust-analyzer");
        assert!(result.config.disabled_lsp.contains("user-disabled"));
        assert!(!result.config.disabled_lsp.contains("project-disabled"));
        assert!(result.config.disabled_lsp.contains("python"));
        assert!(result.config.experimental_lsp_ty);

        let keys = drop_keys(&result);
        let expected = [
            "restrict_to_project_root",
            "url_fetch_allow_private",
            "formatter_timeout_secs",
            "type_checker_timeout_secs",
            "auto_update",
            "bridge",
            "semantic.backend",
            "semantic.base_url",
            "semantic.api_key_env",
            "semantic.query_timeout_ms",
            "lsp.servers",
            "lsp.versions",
            "lsp.auto_install",
            "lsp.grace_days",
            "lsp.disabled",
        ];
        for key in expected {
            assert!(keys.contains(&key.to_string()), "missing dropped key {key}");
        }
        assert_eq!(keys.len(), expected.len());
        assert!(result
            .dropped
            .iter()
            .all(|dropped| dropped.tier == "project"));
    }

    #[test]
    fn disabled_tools_resolve_into_runtime_config() {
        let result = resolve_config(&[tier(
            "user",
            r#"{ "disabled_tools": ["aft_zoom", "aft_search"] }"#,
        )]);
        assert!(result
            .config
            .disabled_tools
            .iter()
            .any(|tool| tool == "aft_zoom"));
        assert!(result
            .config
            .disabled_tools
            .iter()
            .any(|tool| tool == "aft_search"));
    }

    #[test]
    fn project_empty_disabled_list_preserves_explicit_presence() {
        let result = resolve_config(&[
            tier("user", r#"{ "disabled_tools": [] }"#),
            tier("project", r#"{ "disabled_tools": [] }"#),
        ]);
        assert!(result.config.disabled_tools.is_empty());

        // The absent-base default applies to the user base only (no user file
        // behaves like `{}`); an empty project list adds nothing to it.
        let project_only = resolve_config(&[tier("project", r#"{ "disabled_tools": [] }"#)]);
        assert_eq!(
            project_only.config.disabled_tools,
            ["aft_delete", "aft_move"]
        );

        let user_empty_project_zoom = resolve_config(&[
            tier("user", r#"{ "disabled_tools": [] }"#),
            tier("project", r#"{ "disabled_tools": ["aft_zoom"] }"#),
        ]);
        assert_eq!(user_empty_project_zoom.config.disabled_tools, ["aft_zoom"]);

        for doc in [None, Some("{}")] {
            let tiers: Vec<ConfigTier> = doc.map(|doc| tier("user", doc)).into_iter().collect();
            assert_eq!(
                resolve_config(&tiers).config.disabled_tools,
                ["aft_delete", "aft_move"]
            );
        }
        let search_only =
            resolve_config(&[tier("user", r#"{ "disabled_tools": ["aft_search"] }"#)]);
        assert_eq!(search_only.config.disabled_tools, ["aft_search"]);
        assert!(!search_only.config.aft_search_registered);
    }

    #[test]
    fn project_disabled_tools_cannot_remove_host_slots() {
        let result = resolve_config(&[
            tier("user", r#"{ "disabled_tools": ["write"] }"#),
            tier(
                "project",
                r#"{ "disabled_tools": ["read", "bash", "aft_safety", "aft_zoom"] }"#,
            ),
        ]);
        assert_eq!(result.config.disabled_tools, ["aft_zoom", "write"]);
        let dropped = drop_keys(&result);
        for key in [
            "disabled_tools.aft_safety",
            "disabled_tools.bash",
            "disabled_tools.read",
        ] {
            assert!(dropped.contains(&key.to_string()), "{key}");
        }
    }

    #[test]
    fn remote_exec_is_user_only_and_a_project_may_only_turn_it_off() {
        assert_eq!(
            resolve_config(&[]).config.remote_exec,
            RemoteExecConfig::default()
        );
        let user = r#"{ "remote_exec": { "enabled": true, "default_demand": "linux" } }"#;
        let on = resolve_config(&[tier("user", user)]).config.remote_exec;
        assert!(on.enabled && !on.project_off);
        assert_eq!(on.default_demand.as_deref(), Some("linux"));

        // A project can neither enable remote runs nor pick their runner.
        let project_on = resolve_config(&[tier(
            "project",
            r#"{ "remote_exec": { "enabled": true, "default_demand": "linux" } }"#,
        )]);
        assert_eq!(project_on.config.remote_exec, RemoteExecConfig::default());
        let dropped = drop_keys(&project_on);
        assert!(dropped.contains(&"remote_exec.enabled".to_string()));
        assert!(dropped.contains(&"remote_exec.default_demand".to_string()));

        // It can turn them off, and the refusal can then name the project.
        let off = resolve_config(&[
            tier("user", user),
            tier("project", r#"{ "remote_exec": { "enabled": false } }"#),
        ]);
        assert!(!off.config.remote_exec.enabled);
        assert!(off.config.remote_exec.project_off);
        assert!(drop_keys(&off).is_empty());
    }

    #[test]
    fn bash_linux_scope_is_user_only_and_defaults_on() {
        assert!(resolve_config(&[]).config.bash.linux_scope);

        let result = resolve_config(&[
            tier("user", r#"{ "bash": { "linux_scope": true } }"#),
            tier("project", r#"{ "bash": { "linux_scope": false } }"#),
        ]);
        assert!(result.config.bash.linux_scope);
        assert!(drop_keys(&result).contains(&"bash.linux_scope".to_string()));
    }

    #[test]
    fn task_scope_config_contract() {
        let direct = crate::config::BashConfig::default();
        assert!(direct.linux_scope);
        assert_eq!(direct.linux_scope_max_runtime_secs, 86_400);
        let defaults = resolve_config(&[]).config.bash;
        assert!(defaults.linux_scope);
        assert_eq!(defaults.linux_scope_max_runtime_secs, 86_400);
        let result = resolve_config(&[
            tier(
                "user",
                r#"{"bash":{"linux_scope":false,"linux_scope_max_runtime_secs":7200}}"#,
            ),
            tier(
                "project",
                r#"{"bash":{"linux_scope":true,"linux_scope_max_runtime_secs":1}}"#,
            ),
        ]);
        assert!(!result.config.bash.linux_scope);
        assert_eq!(result.config.bash.linux_scope_max_runtime_secs, 7200);
        assert!(drop_keys(&result).contains(&"bash.linux_scope_max_runtime_secs".into()));
        for value in ["0", "-1", "1.5", "4294967296", "true", "\"86400\""] {
            let text = format!("{{\"linux_scope_max_runtime_secs\":{value}}}");
            let error = serde_json::from_str::<RawBashFeatures>(&text).unwrap_err();
            assert!(error.to_string().contains("linux_scope_max_runtime_secs"));
        }
    }

    #[test]
    fn privacy_disclaim_project_only_tightens_and_reports_weakening() {
        assert!(!resolve_config(&[]).config.bash.disclaim_privacy);
        for user in [false, true] {
            for project in [false, true] {
                let result = resolve_config(&[
                    tier(
                        "user",
                        &format!(r#"{{"bash":{{"disclaim_privacy":{user}}}}}"#),
                    ),
                    tier(
                        "project",
                        &format!(r#"{{"bash":{{"disclaim_privacy":{project}}}}}"#),
                    ),
                ]);
                assert_eq!(result.config.bash.disclaim_privacy, user || project);
                assert_eq!(
                    drop_keys(&result).contains(&"bash.disclaim_privacy".to_string()),
                    !project
                );
            }
        }
    }

    #[test]
    fn config_resolve_bash_ladder_and_merge_parity() {
        let true_result = resolve_config(&[tier("user", r#"{ "bash": true }"#)]);
        assert!(true_result.config.experimental_bash_rewrite);
        assert!(true_result.config.experimental_bash_compress);
        assert!(true_result.config.experimental_bash_background);

        let false_result = resolve_config(&[tier("user", r#"{ "bash": false }"#)]);
        assert!(!false_result.config.bash.enabled);
        assert!(!false_result.config.experimental_bash_rewrite);
        assert!(!false_result.config.experimental_bash_compress);
        assert!(!false_result.config.experimental_bash_background);

        let object_default_result = resolve_config(&[tier("user", r#"{ "bash": {} }"#)]);
        assert!(object_default_result.config.experimental_bash_rewrite);
        assert!(object_default_result.config.experimental_bash_compress);
        assert!(object_default_result.config.experimental_bash_background);

        let object_partial_result =
            resolve_config(&[tier("user", r#"{ "bash": { "compress": false } }"#)]);
        assert!(object_partial_result.config.experimental_bash_rewrite);
        assert!(!object_partial_result.config.experimental_bash_compress);
        assert!(object_partial_result.config.experimental_bash_background);

        let surface_default_result = resolve_config(&[tier("user", r#"{}"#)]);
        assert!(surface_default_result.config.experimental_bash_rewrite);
        assert!(surface_default_result.config.experimental_bash_compress);
        assert!(surface_default_result.config.experimental_bash_background);
        assert!(!false_result.config.bash.enabled);
        assert!(true_result.config.bash.enabled);
        assert!(object_default_result.config.bash.enabled);
        let explicit_off = resolve_config(&[tier("user", r#"{ "bash": { "enabled": false } }"#)]);
        assert!(!explicit_off.config.bash.enabled);
        assert!(explicit_off.config.experimental_bash_rewrite);
        assert_eq!(false_result.config.bash, explicit_off.config.bash);

        let merged_result = resolve_config(&[
            tier("user", r#"{ "bash": true }"#),
            tier("project", r#"{ "bash": { "compress": false } }"#),
        ]);
        assert!(merged_result.config.experimental_bash_rewrite);
        assert!(!merged_result.config.experimental_bash_compress);
        assert!(merged_result.config.experimental_bash_background);

        let false_then_object_result = resolve_config(&[
            tier("user", r#"{ "bash": false }"#),
            tier("project", r#"{ "bash": { "compress": true } }"#),
        ]);
        assert!(!false_then_object_result.config.bash.enabled);
        assert!(!false_then_object_result.config.experimental_bash_rewrite);
        assert!(false_then_object_result.config.experimental_bash_compress);
        assert!(!false_then_object_result.config.experimental_bash_background);
    }

    #[test]
    fn settings_shapes_project_bash_true_cannot_reenable_user_gate() {
        let result = resolve_config(&[
            tier(
                "user",
                r#"{"bash":{"enabled":false,"rewrite":false,"compress":false,"background":false}}"#,
            ),
            tier("project", r#"{"bash":true}"#),
        ]);
        assert!(result.errors.is_empty());
        assert!(!result.config.bash.enabled);
        assert!(result.config.experimental_bash_rewrite);
        assert!(result.config.experimental_bash_compress);
        assert!(result.config.experimental_bash_background);
    }

    #[test]
    fn config_resolve_bash_foreground_wait_clamps_to_floor() {
        let Ok((raw, _)) = parse_tier(
            &tier(
                "user",
                r#"{ "bash": { "foreground_wait_window_ms": 1, "subagent_background": true } }"#,
            ),
            None,
            &mut Vec::new(),
            &mut Vec::new(),
        ) else {
            panic!("test tier should parse");
        };
        let mut warnings = Vec::new();
        let bash = resolve_bash_config(&raw, &mut warnings);

        assert_eq!(
            bash.foreground_wait_window_ms,
            FOREGROUND_WAIT_WINDOW_MIN_MS
        );
        assert!(bash.subagent_background);

        let result = resolve_config(&[tier(
            "user",
            r#"{ "bash": { "foreground_wait_window_ms": 1 } }"#,
        )]);
        assert_eq!(
            result.config.foreground_wait_window_ms,
            FOREGROUND_WAIT_WINDOW_MIN_MS
        );

        // Unset → the default wait-window (matches the plugin's
        // FOREGROUND_WAIT_WINDOW_DEFAULT_MS = 15_000). This locks the default,
        // not just the floor, so a future edit can't silently shorten the
        // server-side promotion window once the plugin orchestrates through Rust.
        let defaulted = resolve_config(&[tier("user", r#"{ "bash": true }"#)]);
        assert_eq!(
            defaulted.config.foreground_wait_window_ms,
            FOREGROUND_WAIT_WINDOW_DEFAULT_MS
        );
        assert_eq!(FOREGROUND_WAIT_WINDOW_DEFAULT_MS, 15_000);
    }

    #[test]
    fn config_resolve_partial_parse_drops_invalid_section_and_keeps_valid_sections() {
        let result = resolve_config(&[tier(
            "user",
            r#"{
              "semantic": { "timeout_ms": 0 },
              "indexes": { "trigram": true },
              "format_on_edit": false
            }"#,
        )]);

        assert!(result.config.indexes.trigram);
        assert!(!result.config.format_on_edit);
        assert_eq!(result.config.semantic, SemanticBackendConfig::default());
        assert!(result.dropped.is_empty());
    }

    #[test]
    fn config_resolve_unrelated_unknown_user_key_keeps_lenient_defaults() {
        let result = resolve_config(&[tier(
            "user",
            r#"{ "not_a_real_key": true, "indexes": { "trigram": true } }"#,
        )]);

        assert!(result.config.indexes.trigram);
        assert!(result.dropped.is_empty());
        assert!(result.errors.is_empty(), "{result:?}");
        assert!(result.config.cache_config_unknown.is_none());
    }

    #[test]
    fn resolve_config_onto_resets_core_fields_no_cross_bind_inheritance() {
        // Cross-bind escalation regression: a first (trusted) bind sets a
        // capability field; a second bind that omits it must NOT inherit it.
        // This is the configure-path entry (seeded from a prior config), where
        // reset-onto-default — unlike the old overlay — makes the resolved core
        // config a pure function of the CURRENT bind's tiers.
        let mut config = Config::default();

        // Bind 1 (trusted user tier) sets url_fetch_allow_private + a custom LSP
        // server + restrict_to_project_root.
        let dropped1 = resolve_config_onto(
            &[tier(
                "user",
                r#"{
                  "url_fetch_allow_private": true,
                  "restrict_to_project_root": true,
                  "lsp": { "servers": { "rust": { "extensions": [".rs"], "binary": "rust-analyzer" } } }
                }"#,
            )],
            &mut config,
        );
        assert!(dropped1.is_empty());
        assert!(config.url_fetch_allow_private);
        assert!(config.restrict_to_project_root);
        assert_eq!(config.lsp_servers.len(), 1);

        // Bind 2 omits all three. With reset semantics they return to DEFAULT —
        // the second bind cannot inherit the first bind's capabilities.
        let _ = resolve_config_onto(
            &[tier("user", r#"{ "indexes": { "trigram": true } }"#)],
            &mut config,
        );
        assert!(
            !config.url_fetch_allow_private,
            "url_fetch_allow_private must reset to default, not inherit prior bind"
        );
        assert!(
            !config.restrict_to_project_root,
            "restrict_to_project_root must reset to default"
        );
        assert!(
            config.lsp_servers.is_empty(),
            "lsp_servers must reset to default, not inherit prior bind's custom server"
        );
        assert!(
            config.indexes.trigram,
            "this bind's own field still applies"
        );
    }

    #[test]
    fn resolve_config_onto_empty_tiers_resets_to_default() {
        // The empty-tier path must still reset (it routes through the same
        // always-run resolution in handle_configure). A bind with no tiers after
        // a privileged bind must drop the privileged config.
        let mut config = Config::default();
        let _ = resolve_config_onto(
            &[tier("user", r#"{ "url_fetch_allow_private": true }"#)],
            &mut config,
        );
        assert!(config.url_fetch_allow_private);

        let _ = resolve_config_onto(&[], &mut config);
        assert!(
            !config.url_fetch_allow_private,
            "empty-tier bind must reset core config to default"
        );
    }

    #[test]
    fn resolve_config_onto_preserves_process_state_fields() {
        // Process-state fields (not part of RawAftConfig) are carried across the
        // reset so plugin-mode behavior is unchanged (the plugin re-sends them
        // via flat configure params right after this call).
        let mut config = Config {
            storage_dir: Some(std::path::PathBuf::from("/tmp/aft-store")),
            lsp_paths_extra: vec![std::path::PathBuf::from("/tmp/lsp-bin")],
            bash_permissions: true,
            project_root: Some(std::path::PathBuf::from("/tmp/proj")),
            ..Default::default()
        };

        let _ = resolve_config_onto(
            &[tier("user", r#"{ "indexes": { "trigram": true } }"#)],
            &mut config,
        );

        assert_eq!(
            config.storage_dir,
            Some(std::path::PathBuf::from("/tmp/aft-store"))
        );
        assert_eq!(
            config.lsp_paths_extra,
            vec![std::path::PathBuf::from("/tmp/lsp-bin")]
        );
        assert!(config.bash_permissions);
        assert_eq!(
            config.project_root,
            Some(std::path::PathBuf::from("/tmp/proj"))
        );
        assert!(config.indexes.trigram);
    }

    #[test]
    fn index_roots_are_user_only_normalized_and_validate_before_resolution() {
        let result = resolve_config(&[tier(
            "user",
            r#"{
              "index": {
                "roots": [{
                  "path": "~/.aft-standing-root",
                  "indexes": ["semantic", "callgraph"],
                  "future_field": true
                }]
              }
            }"#,
        )]);
        assert_eq!(result.config.index.roots.len(), 1);
        assert_eq!(result.config.index.roots[0].path, "~/.aft-standing-root");
        assert_eq!(
            result.config.index.roots[0].indexes,
            vec![IndexKind::Search, IndexKind::Semantic, IndexKind::Callgraph]
        );
        assert!(result
            .warnings
            .iter()
            .any(|warning| warning.code == "index_dependency_closure"));
        assert!(result
            .warnings
            .iter()
            .any(|warning| warning.code == "unknown_index_root_field"));

        for invalid in [
            r#"{ "index": { "roots": [{ "path": "relative", "indexes": ["search"] }] } }"#,
            r#"{ "index": { "roots": [{ "path": "~/a", "indexes": [] }] } }"#,
            r#"{ "index": { "roots": [{ "path": "~/a", "indexes": ["search", "search"] }] } }"#,
            r#"{ "index": { "roots": [{ "path": "~/a", "indexes": ["unknown"] }] } }"#,
        ] {
            let invalid = resolve_config(&[tier("user", invalid)]);
            assert!(invalid.config.index.roots.is_empty());
            let warning = invalid
                .warnings
                .iter()
                .find(|warning| warning.code == "invalid_index_roots")
                .expect("invalid standing roots must be named");
            assert!(warning.message.contains("index.roots"));
        }
    }

    #[test]
    fn index_roots_project_and_mcp_tiers_are_rejected_at_the_trust_boundary() {
        let result = resolve_config(&[
            tier(
                "user",
                r#"{ "index": { "roots": [{ "path": "~/user", "indexes": ["search"] }] } }"#,
            ),
            tier(
                "project",
                r#"{ "index": { "roots": [{ "path": "~/project", "indexes": ["semantic"] }] } }"#,
            ),
            tier(
                "mcp:untrusted",
                r#"{ "index": { "roots": [{ "path": "~/mcp", "indexes": ["callgraph"] }] } }"#,
            ),
        ]);
        assert_eq!(result.config.index.roots[0].path, "~/user");
        assert_eq!(
            result
                .dropped
                .iter()
                .filter(|dropped| dropped.key == "index.roots")
                .map(|dropped| dropped.tier.as_str())
                .collect::<Vec<_>>(),
            vec!["project", "mcp:untrusted"]
        );
    }

    #[test]
    fn config_resolve_jsonc_comments_and_trailing_commas_parse() {
        let result = resolve_config(&[tier(
            "user",
            r#"{
              // line comment
              "indexes": { "trigram": true },
              "formatter": {
                "rust": "rustfmt", /* block comment */
              },
            }"#,
        )]);

        assert!(result.config.indexes.trigram);
        assert_eq!(
            result.config.formatter.get("rust").map(String::as_str),
            Some("rustfmt")
        );
    }

    fn external_access_ask(user: Option<bool>, project: Option<bool>) -> Option<bool> {
        let block = |value: Option<bool>| {
            value.map(|ask| RawPi {
                external_access_ask: Some(ask),
                ..RawPi::default()
            })
        };
        merge_pi_config(block(user), block(project)).and_then(|pi| pi.external_access_ask)
    }

    /// A repository must not silence the outside-access prompt for the user:
    /// a project may turn it on, never off.
    #[test]
    fn project_tier_may_only_turn_the_outside_access_prompt_on() {
        assert_eq!(external_access_ask(Some(true), Some(false)), Some(true));
        assert_eq!(external_access_ask(None, Some(false)), None);
        assert_eq!(external_access_ask(Some(false), Some(true)), Some(true));
        assert_eq!(external_access_ask(Some(false), None), Some(false));

        let result = resolve_config(&[
            tier("user", r#"{ "pi": { "external_access_ask": true } }"#),
            tier("project", r#"{ "pi": { "external_access_ask": false } }"#),
        ]);
        assert!(result.errors.is_empty(), "{:?}", result.errors);
        assert_eq!(drop_keys(&result), vec!["pi.external_access_ask"]);

        let result = resolve_config(&[
            tier("user", r#"{ "pi": { "external_access_ask": false } }"#),
            tier("project", r#"{ "pi": { "external_access_ask": true } }"#),
        ]);
        assert!(drop_keys(&result).is_empty(), "{:?}", result.dropped);
    }
}