ai-session-search 1.0.0-rc.4

Local-first search, inspection, export, recovery, and MCP recall across supported AI coding-agent sessions.
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
// SPDX-FileCopyrightText: 2026 Andrew Hundt
// SPDX-FileCopyrightText: 2026 Adam Zhao
// SPDX-FileCopyrightText: 2026 Nisarg Patel
// SPDX-License-Identifier: Apache-2.0

use std::collections::BTreeMap;
use std::fmt;
use std::fs;
use std::num::{NonZeroU32, NonZeroUsize};
use std::path::PathBuf;
use std::time::{Duration, Instant};

use anyhow::{bail, Context, Result};
use serde::{Deserialize, Deserializer, Serialize, Serializer};

use crate::keymap::KeyBindings;
use crate::terminal_style::CapabilityMode;
use crate::util::expand_tilde;

pub const CONFIG_EXAMPLE_TOML: &str = include_str!("../config.example.toml");

pub const DEFAULT_MCP_SEARCH_SESSIONS_LIMIT: usize = 10;
pub const DEFAULT_MCP_LIST_SESSIONS_LIMIT: usize = 20;
/// Default MCP page size for `search_messages`.
///
/// WHY 15. The result ceiling below is a backstop, not the mechanism: a response that errors is
///   a worse outcome than one that never grew. At the measured marginal cost of about 1,583
///   characters per result, 15 results land near 25,000 characters, roughly 53% of the ceiling,
///   leaving about 2x headroom for a long matched message. At 20 the figure was 69%, which the
///   multiplicative levers consume immediately: `detail=full` measured 4.8x and
///   `include=[...,"parsed_references"]` 2.7x, and they compose.
/// PLATFORM: this repository's MCP surface only. CLI, Rust and Python return all results by
///   design and are untouched.
/// RAISE IT WHEN: `max_tool_result_chars` is raised for this deployment, or the per-result cost
///   drops. Keep an ordinary call under about 55% of the ceiling.
/// LOWER IT WHEN: the ceiling is lowered, or per-result cost grows.
/// NOT A CAP. A caller passes an explicit `limit` for more; `has_more` and `next_offset` are
///   unchanged, so paging stays correct and a caller wanting 20 asks for 20.
pub const DEFAULT_MCP_SEARCH_MESSAGES_LIMIT: usize = 15;

/// Maximum characters in one serialized MCP `CallToolResult`.
///
/// WHY 48,000. It is Codex's model-facing result cap, about 12,000 tokens at four characters
///   each. Codex is the only measured client that truncates a result **silently**, from the
///   middle, with no marker -- which keeps a plausible head and tail and so looks complete. That,
///   not being the smallest number, is why it sets the default: Gemini CLI's 40,000 is smaller
///   and announces the overflow, persists it, and states how many characters it omitted, so it
///   loses nothing.
/// PLATFORMS measured 2026-08-03:
///   Codex          ~12,000 tok = ~48,000 chars   SILENT middle truncation   <- binding
///   Claude Code    25,000 tok, persists >100,000 announces, saves to a file
///   Gemini CLI     40,000 chars                  announces, saves to a file
///   VS Code        50% of the model prompt budget, token-budgeted
///   OpenCode       none; MCP results pass through untouched
///   Cursor, Windsurf, Antigravity, Claude Desktop   unverified, closed source
/// RAISE IT WHEN: the deployment talks only to clients that announce truncation, or Codex raises
///   its own cap. Codex's schema budget already moved 4,000 -> 5,000, so its constants do move.
/// LOWER IT WHEN: a client is found that truncates silently below this. Antigravity is the live
///   risk: it superseded Gemini CLI, holds three of the thirteen registrations here, and its
///   truncation behaviour is unverified.
/// Measured over the serialized `CallToolResult`, not the JSON-RPC envelope around it: the
/// dispatcher owns the former and not the latter, and they differ by 34 characters.
pub const DEFAULT_MCP_MAX_TOOL_RESULT_CHARS: usize = 48_000;
pub const DEFAULT_MCP_RUN_MESSAGE_CLASSIFICATION_LIMIT: usize = 20;
/// Signed whole-transcript presentation window used by MCP `get_session` when omitted.
pub const DEFAULT_MCP_GET_SESSION_TRANSCRIPT_LINE_WINDOW: i64 = -40;
pub const DEFAULT_MCP_PREVIEW_CHARS: usize = crate::inspect::DEFAULT_PREVIEW_CHARS;
pub const DEFAULT_MCP_SUMMARY_ITEMS: i64 = -(crate::inspect::DEFAULT_EVIDENCE_LIMIT as i64);
pub const DEFAULT_MCP_QUERY_MAX_CELL_CHARS: usize = crate::sql_query::DEFAULT_MCP_MAX_CELL_CHARS;
pub const DEFAULT_MCP_INTERNAL_SCHEMA_SUMMARY_TABLES: usize = 4;
pub const DEFAULT_MCP_INTERNAL_SCHEMA_SUMMARY_COLUMNS: usize = 12;
pub const MAX_MCP_CONCURRENT_READS: usize = tokio::sync::Semaphore::MAX_PERMITS;
/// Signed whole-transcript presentation window used by `aise show` when omitted.
pub const DEFAULT_CLI_SHOW_TRANSCRIPT_LINE_WINDOW: i64 = -40;
/// Signed per-message presentation window; zero preserves complete message content.
pub const DEFAULT_MESSAGE_LINE_WINDOW: i64 = 0;
pub const DEFAULT_CLI_EVIDENCE_PREVIEW_CHARS: usize = crate::inspect::DEFAULT_PREVIEW_CHARS;
pub const DEFAULT_CLI_SUMMARY_ITEMS: i64 = -(crate::inspect::DEFAULT_EVIDENCE_LIMIT as i64);
pub const DEFAULT_DB_QUERY_LIMIT: usize = crate::sql_query::DEFAULT_LIMIT;
pub const DEFAULT_DB_QUERY_TIMEOUT_MS: u64 = crate::sql_query::DEFAULT_TIMEOUT_MS;
pub const DEFAULT_MESSAGE_CLASSIFICATION_LIMIT: usize = 50;
pub const DEFAULT_ANALYTICS_PLANNING_LIMIT: usize = 50;
pub const DEFAULT_ANALYTICS_VOCAB_LIMIT: usize = 50;
pub const DEFAULT_ANALYTICS_REPEAT_MAX_GROUPS: usize = 50;
/// Structured repeat output exposes representative examples, not every matching message.
/// Three matches the long-standing table presentation; callers can request 0 for all examples.
pub const DEFAULT_ANALYTICS_REPEAT_MAX_EXAMPLES_PER_GROUP: usize = 3;
pub const DEFAULT_ANALYTICS_REPEAT_MIN_MATCHES: usize = 2;
pub const DEFAULT_ANALYTICS_REPEAT_PHRASE_MIN_WORDS: usize = 2;
pub const DEFAULT_ANALYTICS_REPEAT_PHRASE_MAX_WORDS: usize = 5;

#[derive(Debug, Clone, Serialize)]
#[non_exhaustive]
pub struct Config {
    #[serde(default)]
    pub providers: ProvidersConfig,
    #[serde(default)]
    pub index: IndexConfig,
    #[serde(default)]
    pub ui: UiConfig,
    #[serde(default)]
    pub search: SearchConfig,
    #[serde(default)]
    pub analytics: AnalyticsConfig,
    #[serde(default)]
    pub skills: SkillsConfig,
    #[serde(default)]
    pub capabilities: CapabilitiesConfig,
    #[serde(default)]
    pub performance: PerformanceConfig,
    #[serde(default)]
    pub mcp: McpConfig,
    #[serde(default)]
    pub cli: CliConfig,
    #[serde(default)]
    pub db: DbConfig,
    #[serde(default)]
    pub release_notifications: ReleaseNotificationConfig,
    #[serde(default)]
    pub integrations: IntegrationsConfig,
}

/// Per-invocation configuration overrides. `None` preserves lower-precedence sources.
#[derive(Debug, Clone, Default)]
pub struct ConfigOverrides {
    pub config_path: Option<PathBuf>,
    pub database_path: Option<PathBuf>,
    pub cache_dir: Option<PathBuf>,
    pub threads: Option<usize>,
    pub index_refresh: Option<IndexRefresh>,
}

/// Process environment captured once so precedence can be tested without mutating global state.
#[derive(Debug, Clone, Default)]
pub struct ConfigEnvironment {
    pub config_path: Option<PathBuf>,
    pub database_path: Option<PathBuf>,
    pub cache_dir: Option<PathBuf>,
    pub threads: Option<String>,
    pub index_refresh: Option<String>,
    /// The MCP result ceiling an MCP registration sets in its own `env` block.
    ///
    /// Every MCP client config format carries a per-server `env` table, which is the only place
    /// a deployment can give one harness a different bound without giving every harness the same
    /// one. The over-ceiling error names this variable as a remedy, so it has to reach the
    /// resolver rather than only the prose.
    pub max_tool_result_chars: Option<String>,
    /// Per-row client-limit budgets an MCP registration sets in its own `env` block, keyed by
    /// row name and kept as the raw text each variable carried. Raw because `Config::resolve`
    /// owns rejection: a value that cannot be honoured is reported against the variable that
    /// carried it, never dropped here, which would leave the shipped budget silently in force —
    /// the defect `resolve_max_tool_result_chars` exists to close.
    pub client_limits: BTreeMap<String, String>,
}

impl ConfigEnvironment {
    pub fn capture() -> Self {
        Self {
            config_path: nonempty_env_path("AI_SESSION_SEARCH_CONFIG"),
            database_path: nonempty_env_path("AI_SESSION_SEARCH_DATABASE"),
            cache_dir: nonempty_env_path("AI_SESSION_SEARCH_CACHE_DIR"),
            threads: nonempty_env_string("AI_SESSION_SEARCH_THREADS"),
            index_refresh: nonempty_env_string("AI_SESSION_SEARCH_INDEX_REFRESH"),
            max_tool_result_chars: nonempty_env_string("AI_SESSION_SEARCH_MAX_TOOL_RESULT_CHARS"),
            client_limits: client_limits_from_environment(std::env::vars()),
        }
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct ConfigOrigins {
    pub config: String,
    pub database: String,
    pub cache: String,
    pub threads: String,
    pub index_refresh: String,
    pub search_scope: String,
    /// Where the MCP message page a caller gets when they pass no `limit` came from.
    ///
    /// Reported because the effective number alone cannot distinguish a deliberate deployment
    /// choice from a source default that happens to match it, and these two bounds are the ones
    /// a release decision turns on: the page returned when the caller passes nothing, and the
    /// ceiling that decides whether a result is delivered at all
    /// (`REQ013-resolve-parameters-by-origin`).
    pub search_messages_limit: String,
    /// Where the serialized-`CallToolResult` ceiling came from.
    pub max_tool_result_chars: String,
    /// Which client-limit rows this process is not using its measured default for, and from
    /// where. Reported per row because the rows are independent: a registration may move Codex's
    /// schema budget while every other row keeps the number read from its own client's source.
    pub client_limits: BTreeMap<String, String>,
}

/// Validated effective configuration plus provenance.
#[derive(Debug, Clone)]
pub struct ResolvedConfig {
    pub config: Config,
    pub config_path: PathBuf,
    pub origins: ConfigOrigins,
}

#[derive(Debug, Default, Deserialize)]
#[serde(default, deny_unknown_fields)]
struct ConfigFile {
    providers: Option<ProvidersFile>,
    index: Option<IndexConfig>,
    ui: Option<UiConfig>,
    search: Option<SearchConfig>,
    analytics: Option<AnalyticsConfig>,
    skills: Option<SkillsConfig>,
    capabilities: Option<CapabilitiesConfig>,
    performance: Option<PerformanceConfig>,
    mcp: Option<McpConfig>,
    cli: Option<CliConfig>,
    db: Option<DbConfig>,
    release_notifications: Option<ReleaseNotificationConfig>,
    integrations: Option<IntegrationsConfig>,
}

#[derive(Debug, Default, Deserialize)]
#[serde(default, deny_unknown_fields)]
struct ProvidersFile {
    claude: Option<ProviderFile>,
    #[serde(rename = "claude-desktop")]
    claude_desktop: Option<ProviderFile>,
    codex: Option<ProviderFile>,
    cursor: Option<ProviderFile>,
    antigravity: Option<ProviderFile>,
    pi: Option<ProviderFile>,
    #[serde(rename = "prime-agent")]
    prime_agent: Option<ProviderFile>,
    aistudio: Option<ProviderFile>,
    #[serde(rename = "gemini-cli")]
    gemini_cli: Option<ProviderFile>,
}

#[derive(Debug, Default, Deserialize)]
#[serde(default, deny_unknown_fields)]
struct ProviderFile {
    enabled: Option<bool>,
    paths: Option<Vec<String>>,
}

impl ProviderFile {
    fn apply(self, provider: &mut ProviderConfig) {
        if let Some(enabled) = self.enabled {
            provider.enabled = enabled;
        }
        if let Some(paths) = self.paths {
            provider.paths = paths;
        }
    }
}

impl ConfigFile {
    fn into_config(self) -> Config {
        let mut config = Config::default();
        if let Some(providers) = self.providers {
            if let Some(value) = providers.claude {
                value.apply(&mut config.providers.claude);
            }
            if let Some(value) = providers.claude_desktop {
                value.apply(&mut config.providers.claude_desktop);
            }
            if let Some(value) = providers.codex {
                value.apply(&mut config.providers.codex);
            }
            if let Some(value) = providers.cursor {
                value.apply(&mut config.providers.cursor);
            }
            if let Some(value) = providers.antigravity {
                value.apply(&mut config.providers.antigravity);
            }
            if let Some(value) = providers.pi {
                value.apply(&mut config.providers.pi);
            }
            if let Some(value) = providers.prime_agent {
                value.apply(&mut config.providers.prime_agent);
            }
            if let Some(value) = providers.aistudio {
                value.apply(&mut config.providers.aistudio);
            }
            if let Some(value) = providers.gemini_cli {
                value.apply(&mut config.providers.gemini_cli);
            }
        }
        if let Some(mut value) = self.index {
            let defaults = IndexConfig::default();
            value.db_path = value.db_path.or(defaults.db_path);
            value.cache_dir = value.cache_dir.or(defaults.cache_dir);
            config.index = value;
        }
        if let Some(value) = self.ui {
            config.ui = value;
        }
        if let Some(value) = self.search {
            config.search = value;
        }
        if let Some(value) = self.analytics {
            config.analytics = value;
        }
        if let Some(value) = self.skills {
            config.skills = value;
        }
        if let Some(value) = self.capabilities {
            config.capabilities = value;
        }
        if let Some(value) = self.performance {
            config.performance = value;
        }
        if let Some(value) = self.mcp {
            config.mcp = value;
        }
        if let Some(value) = self.cli {
            config.cli = value;
        }
        if let Some(value) = self.db {
            config.db = value;
        }
        if let Some(value) = self.release_notifications {
            config.release_notifications = value;
        }
        if let Some(value) = self.integrations {
            config.integrations = value;
        }
        config
    }
}

impl<'de> Deserialize<'de> for Config {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        Ok(ConfigFile::deserialize(deserializer)?.into_config())
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
pub struct ProvidersConfig {
    #[serde(default)]
    pub claude: ProviderConfig,
    #[serde(default, rename = "claude-desktop")]
    pub claude_desktop: ProviderConfig,
    #[serde(default)]
    pub codex: ProviderConfig,
    #[serde(default)]
    pub cursor: ProviderConfig,
    #[serde(default)]
    pub antigravity: ProviderConfig,
    #[serde(default)]
    pub pi: ProviderConfig,
    #[serde(default, rename = "prime-agent")]
    pub prime_agent: ProviderConfig,
    #[serde(default)]
    pub aistudio: ProviderConfig,
    #[serde(default, rename = "gemini-cli")]
    pub gemini_cli: ProviderConfig,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
pub struct ProviderConfig {
    #[serde(default = "default_true")]
    pub enabled: bool,
    #[serde(default)]
    pub paths: Vec<String>,
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize, clap::ValueEnum)]
#[serde(rename_all = "kebab-case")]
pub enum IndexRefresh {
    #[default]
    Auto,
    BeforeQuery,
    ExistingOnly,
}

impl std::str::FromStr for IndexRefresh {
    type Err = String;

    fn from_str(value: &str) -> std::result::Result<Self, Self::Err> {
        match value.trim() {
            "auto" => Ok(Self::Auto),
            "before-query" => Ok(Self::BeforeQuery),
            "existing-only" => Ok(Self::ExistingOnly),
            other => Err(format!(
                "expected auto, before-query, or existing-only; got {other:?}"
            )),
        }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
pub struct IndexConfig {
    pub db_path: Option<String>,
    pub cache_dir: Option<String>,
    /// When implicit read paths refresh indexed session sources.
    #[serde(default)]
    pub refresh: IndexRefresh,
    /// SQLite busy timeout in milliseconds. Applies while opening/initializing the DB too, so
    /// normal concurrent CLI/MCP use waits briefly for another writer instead of failing.
    #[serde(default = "default_busy_timeout_ms")]
    pub busy_timeout_ms: u64,
    /// Busy timeout used only by automatic background reindex refreshes. When it expires on writer
    /// contention, read commands have already served the existing readable index.
    #[serde(default = "default_auto_reindex_busy_timeout_ms")]
    pub auto_reindex_busy_timeout_ms: u64,
    /// Cross-process interval after a successful automatic refresh where read commands skip
    /// auto-reindex entirely and stay read-only.
    #[serde(default = "default_auto_reindex_interval_ms")]
    pub auto_reindex_interval_ms: u64,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
pub struct UiConfig {
    /// Lines of transcript body in the preview. 1.0.0rc2 spelled it `preview_lines`, and a
    /// config file that still does keeps loading: an upgrade must not require editing settings
    /// the user wrote for the previous release.
    #[serde(default = "default_preview_body_lines", alias = "preview_lines")]
    pub preview_body_lines: usize,
    /// Idle wake interval for the TUI event loop. Keys redraw immediately, and active worker
    /// output uses a shorter bounded slice, so this paces only settled idle turns.
    #[serde(default = "default_idle_poll_interval_ms")]
    pub idle_poll_interval_ms: u64,
    /// Milliseconds an edited TUI query must stay unchanged before it becomes a search. Typing
    /// never waits on it — only the search does. `0` searches on every keystroke, and Enter
    /// searches the current query immediately at any value.
    #[serde(default = "default_search_debounce_ms")]
    pub search_debounce_ms: u64,
    /// Rows the selection moves for PageDown/PageUp in the session list.
    #[serde(default = "default_list_page_rows")]
    pub list_page_rows: usize,
    /// Rendered rows the preview scrolls for `K`/`J` (and Shift+Up/Shift+Down). Rows, not
    /// transcript lines: the scroll offset indexes the wrapped pane, where one long line occupies
    /// several.
    #[serde(default = "default_preview_scroll_rows")]
    pub preview_scroll_rows: usize,
    /// Rendered rows the preview scrolls for Ctrl-d/Ctrl-u.
    #[serde(default = "default_preview_page_rows")]
    pub preview_page_rows: usize,
    /// Width of the provider label column in the session list. Normal panes clamp upward to the
    /// longest label; exceptionally narrow panes clamp to their interior and may truncate it.
    #[serde(default = "default_provider_label_width")]
    pub provider_label_width: usize,
    /// Percent of the body width given to the session-list pane; the preview pane gets the
    /// remainder — one number, not two that must sum to 100.
    #[serde(default = "default_list_pane_percent")]
    pub list_pane_percent: u16,
    /// Whether the TUI draws characters outside ASCII: box borders, the ellipsis, the preview's
    /// section rules and elision markers. `auto` reads the locale and falls back only when it
    /// names an encoding that cannot carry them. `crate::terminal_style` owns the resolution.
    #[serde(default)]
    pub unicode: CapabilityMode,
    /// Whether the TUI colours anything. `auto` honours `NO_COLOR` and `TERM=dumb`. Emphasis
    /// that does not need colour — bold, the selection symbol — is drawn either way.
    #[serde(default)]
    pub color: CapabilityMode,
    /// What each key press means. A `[ui.keys]` table names only the actions it changes; the
    /// rest keep their defaults. `crate::keymap` owns the vocabulary and the parsing.
    #[serde(default)]
    pub keys: KeyBindings,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
pub struct SearchConfig {
    #[serde(default = "default_limit")]
    pub default_limit: usize,
    #[serde(default = "default_true")]
    pub prefer_current_repo: bool,
    /// Fuzzy-ranker weights. The defaults are tuned; override only to retune relevance.
    #[serde(default)]
    pub scoring: ScoringConfig,
    /// Shared message-search preferences. Omission preserves each surface's current default.
    #[serde(default, rename = "message-search")]
    pub message_search: MessageSearchConfig,
    /// Optional hard ceilings. Every omitted field preserves current runtime behavior.
    #[serde(default)]
    pub budgets: SearchBudgetConfig,
    /// Trusted search authority. `all` preserves current unrestricted behavior.
    #[serde(default)]
    pub scope: SearchScopeConfig,
    /// User-defined, versioned soft preference bundles. No built-in purpose ships by default.
    #[serde(default)]
    pub purposes: BTreeMap<String, PurposeDefinition>,
}

#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
pub struct MessageSearchConfig {
    /// Optional shared positive page size. `None` preserves current CLI, MCP, Python, and Rust
    /// surface defaults; requesting every result remains an explicit per-call decision.
    pub default_limit: Option<NonZeroUsize>,
    /// Maximum Unicode scalar characters in automatic selected-field match evidence.
    /// Omission uses the typed default.
    pub match_evidence_max_chars: Option<NonZeroUsize>,
    #[serde(default)]
    pub context: MessageContextDefaults,
}

#[derive(Debug, Clone, Copy, Default, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
pub struct MessageContextDefaults {
    pub context_before: Option<usize>,
    pub context_after: Option<usize>,
}

#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
pub struct SearchBudgetConfig {
    /// Maximum hits in a finite message-search page.
    ///
    /// This does not cap an explicit all-results request: `all_results` deliberately selects a
    /// different, unpaged extent. The service never silently converts all-results into a page or
    /// truncates either extent.
    pub max_hits_per_page: Option<NonZeroUsize>,
    pub max_context_neighbors_per_hit: Option<NonZeroUsize>,
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize, clap::ValueEnum)]
#[serde(rename_all = "kebab-case")]
pub enum SearchScopeMode {
    #[default]
    All,
    AllowedRoots,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
pub struct SearchScopeConfig {
    pub mode: SearchScopeMode,
    pub roots: Vec<String>,
    pub include_invocation_directory: bool,
}

impl Default for SearchScopeConfig {
    fn default() -> Self {
        Self {
            mode: SearchScopeMode::All,
            roots: Vec::new(),
            include_invocation_directory: false,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum SearchOperation {
    MessageSearch,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct PurposeDefinition {
    pub version: NonZeroU32,
    pub operation: SearchOperation,
    #[serde(default)]
    pub preferences: MessagePurposePreferences,
}

#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
pub struct MessagePurposePreferences {
    pub default_limit: Option<NonZeroUsize>,
    pub context_before: Option<usize>,
    pub context_after: Option<usize>,
    pub receipt_level: Option<crate::message_search::ReceiptLevel>,
    pub include_refs: Option<bool>,
    pub lines_per_message: Option<i64>,
    pub match_evidence_max_chars: Option<NonZeroUsize>,
}

/// Tunable weights for the session search ranker (`[search.scoring]` in config.toml).
/// Every field defaults to the value the ranker shipped with, so an absent or partial
/// `[search.scoring]` table leaves ranking byte-for-byte unchanged — you should rarely
/// need to set any of these. A field contributes its weight when the lowercased query is
/// a substring of that haystack; `token_bonus` is added per query token found in a
/// haystack, `all_tokens_bonus` once when every token matched across fields of one session, recency adds
/// `(recency_max_days - age_days).max(0) * recency_weight`, and `current_repo_bonus` is
/// added when a session's repo matches the current one.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
pub struct ScoringConfig {
    #[serde(default = "default_title_score")]
    pub title_score: i64,
    #[serde(default = "default_summary_score")]
    pub summary_score: i64,
    /// Weight for a cwd or repo-root substring match.
    #[serde(default = "default_path_score")]
    pub path_score: i64,
    #[serde(default = "default_preview_score")]
    pub preview_score: i64,
    /// Weight for any other haystack (e.g. the transcript body).
    #[serde(default = "default_other_score")]
    pub other_score: i64,
    #[serde(default = "default_token_bonus")]
    pub token_bonus: i64,
    #[serde(default = "default_all_tokens_bonus")]
    pub all_tokens_bonus: i64,
    #[serde(default = "default_recency_weight")]
    pub recency_weight: i64,
    #[serde(default = "default_recency_max_days")]
    pub recency_max_days: i64,
    #[serde(default = "default_current_repo_bonus")]
    pub current_repo_bonus: i64,
}

/// Analytics defaults and overrides (`[analytics]` in config.toml).
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
pub struct AnalyticsConfig {
    /// `planning`: when non-empty, restricts the count to slash commands whose token
    /// matches one of these (case-insensitive) regexes. Empty = count every slash command.
    #[serde(default)]
    pub planning_commands: Vec<String>,
    /// Default `aise planning --limit`. `0` means every command.
    #[serde(default = "default_analytics_planning_limit")]
    pub planning_limit: usize,
    /// Default `aise vocab --limit`. `0` means unlimited.
    #[serde(default = "default_analytics_vocab_limit")]
    pub vocab_limit: usize,
    /// Default `aise repeats --max-groups`. `0` means all groups.
    #[serde(default = "default_analytics_repeat_max_groups")]
    pub repeat_max_groups: usize,
    /// Default `aise repeats --max-examples-per-group`. `0` means every matching message.
    #[serde(default = "default_analytics_repeat_max_examples_per_group")]
    pub repeat_max_examples_per_group: usize,
    /// Default `aise repeats --min-matches`. Must be at least 1.
    #[serde(default = "default_analytics_repeat_min_matches")]
    pub repeat_min_matches: usize,
    /// Default `aise repeats --phrase-min-words`. Must be at least 1.
    #[serde(default = "default_analytics_repeat_phrase_min_words")]
    pub repeat_phrase_min_words: usize,
    /// Default `aise repeats --phrase-max-words`. Must be >= `repeat_phrase_min_words`.
    #[serde(default = "default_analytics_repeat_phrase_max_words")]
    pub repeat_phrase_max_words: usize,
}

/// Deterministic skill discovery and authoring (`[skills]` in config.toml).
///
/// A skill is a standard Agent Skills directory. Deterministic capabilities are declared by
/// adjacent, strictly parsed metadata; `aise` does not execute instructions from `SKILL.md`.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
pub struct SkillsConfig {
    /// Directories to scan for skills, each either a skill directory or a directory containing
    /// skill directories. `~` is expanded. Empty = only capabilities embedded in the executable.
    ///
    /// These are DISCOVERY roots and are deliberately not the install destinations from
    /// `aise integrations install`: install writes the same bundled skill to three client roots,
    /// so scanning those would find three copies of one name. Discovery is also not activation --
    /// a file appearing here never changes results until it is selected by name.
    #[serde(default)]
    pub search_paths: Vec<String>,
    /// Parent directory `aise skills create` writes into when `--output-dir` is omitted.
    /// `None` = require the flag rather than guessing a destination for a new directory.
    #[serde(default)]
    pub authoring_root: Option<String>,
}

/// Defaults for typed deterministic capabilities.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
pub struct CapabilitiesConfig {
    pub message_classification: MessageClassificationConfig,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
pub struct MessageClassificationConfig {
    /// Default native CLI and Python result count. `0` means every match.
    #[serde(default = "default_message_classification_limit")]
    pub limit: usize,
}

/// Parallelism overrides (`[performance]` in config.toml). `threads` controls the worker
/// count for data-parallel CPU-bound scans (e.g. message classification). `0` (the default) means
/// auto-detect from the host (`std::thread::available_parallelism`), so it adapts to any
/// machine with no configuration. See [`Config::resolve_threads`] for the override chain.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
pub struct PerformanceConfig {
    /// Worker threads for parallel scans. `0` = auto (all available cores); `1` = sequential.
    #[serde(default)]
    pub threads: usize,
}

/// Simultaneous MCP read-only SQLite calls per server process.
///
/// `Auto` admits half the available host parallelism, rounded up, because admitted fuzzy searches
/// share a separate host-sized Rayon worker pool. `Host` admits one call per available logical CPU.
/// `Fixed` is an explicit positive cap. Neither value changes the separate single-writer election
/// used by index refresh.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum McpReadConcurrency {
    #[default]
    Auto,
    Host,
    Fixed(NonZeroUsize),
}

impl McpReadConcurrency {
    fn resolve(self) -> Result<NonZeroUsize> {
        let host = std::thread::available_parallelism().unwrap_or(NonZeroUsize::MIN);
        let resolved = match self {
            Self::Auto => NonZeroUsize::new(host.get().div_ceil(2))
                .expect("half of nonzero host parallelism remains nonzero"),
            Self::Host => host,
            Self::Fixed(value) => value,
        };
        if resolved.get() > MAX_MCP_CONCURRENT_READS {
            bail!("{}", invalid_mcp_read_concurrency(&resolved.get()));
        }
        Ok(resolved)
    }
}

fn invalid_mcp_read_concurrency(got: &impl fmt::Display) -> String {
    format!(
        "max_concurrent_reads must be \"auto\", \"host\", or an integer from 1 through \
         {MAX_MCP_CONCURRENT_READS}, got {got}; use \"auto\" for the balanced default, \"host\" \
         for one slot per available logical CPU, or an integer in that range to cap simultaneous \
         read-only SQLite calls"
    )
}

impl Serialize for McpReadConcurrency {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match self {
            Self::Auto => serializer.serialize_str("auto"),
            Self::Host => serializer.serialize_str("host"),
            Self::Fixed(value) => serializer.serialize_u64(value.get() as u64),
        }
    }
}

impl<'de> Deserialize<'de> for McpReadConcurrency {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct McpReadConcurrencyVisitor;

        impl serde::de::Visitor<'_> for McpReadConcurrencyVisitor {
            type Value = McpReadConcurrency;

            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
                formatter.write_str("\"auto\", \"host\", or a positive integer")
            }

            fn visit_str<E>(self, value: &str) -> std::result::Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                match value {
                    "auto" => return Ok(McpReadConcurrency::Auto),
                    "host" => return Ok(McpReadConcurrency::Host),
                    _ => {}
                }
                Err(E::custom(invalid_mcp_read_concurrency(&format_args!(
                    "{value:?}"
                ))))
            }

            fn visit_u64<E>(self, value: u64) -> std::result::Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                let value = usize::try_from(value)
                    .ok()
                    .and_then(NonZeroUsize::new)
                    .filter(|value| value.get() <= MAX_MCP_CONCURRENT_READS)
                    .ok_or_else(|| E::custom(invalid_mcp_read_concurrency(&value)))?;
                Ok(McpReadConcurrency::Fixed(value))
            }

            fn visit_i64<E>(self, value: i64) -> std::result::Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                u64::try_from(value)
                    .ok()
                    .and_then(|value| usize::try_from(value).ok())
                    .and_then(NonZeroUsize::new)
                    .filter(|value| value.get() <= MAX_MCP_CONCURRENT_READS)
                    .map(McpReadConcurrency::Fixed)
                    .ok_or_else(|| E::custom(invalid_mcp_read_concurrency(&value)))
            }
        }

        deserializer.deserialize_any(McpReadConcurrencyVisitor)
    }
}

/// Agent-facing MCP defaults (`[mcp]` in config.toml). These affect default tool-call behavior
/// only when the MCP client omits the matching parameter; explicit tool arguments still win. They
/// matter because MCP responses are usually copied straight into an agent's context window.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
pub struct McpConfig {
    /// Maximum tool calls per MCP server process that may hold independent read-only SQLite
    /// connections simultaneously. Additional calls wait without opening a connection. This
    /// bounds page-cache/result working memory while allowing WAL readers to overlap. `"auto"`
    /// is the balanced default; `"host"` admits one reader per available logical CPU.
    #[serde(default)]
    pub max_concurrent_reads: McpReadConcurrency,
    /// Default `search_sessions.limit`: session-level search page size. Does not affect CLI
    /// `aise search`, which uses `[search].default_limit`.
    #[serde(default = "default_mcp_search_sessions_limit")]
    pub search_sessions_limit: usize,
    /// Default `list_sessions.limit`: recent-session page size. Does not affect CLI
    /// `aise list`, which uses `[search].default_limit`.
    #[serde(default = "default_mcp_list_sessions_limit")]
    pub list_sessions_limit: usize,
    /// Default `search_messages.limit`: message-hit page size. Must be at least 1 so pagination
    /// always makes progress. Does not affect CLI `aise messages search`.
    #[serde(default = "default_mcp_search_messages_limit")]
    pub search_messages_limit: usize,
    /// Ceiling on one serialized MCP `CallToolResult`, in characters.
    ///
    /// Typed and named rather than a constant because `REQ008-reject-hidden-cutoffs` requires an
    /// intentional bound to be named, typed, documented and rejected when it conflicts, and
    /// because no single value is right for thirteen registrations whose clients differ by more
    /// than 2x in what they tolerate and differ in kind in how they fail. A registration
    /// overrides it with `AI_SESSION_SEARCH_MAX_TOOL_RESULT_CHARS` in its own `env` block, the
    /// same mechanism `AI_SESSION_SEARCH_INDEX_REFRESH` already uses.
    ///
    /// MCP `tools/call` only. CLI, Rust and Python return every result by design.
    #[serde(default = "default_mcp_max_tool_result_chars")]
    pub max_tool_result_chars: usize,
    /// Default `run_skill_capability` message-classification page size. Must be at least 1 so
    /// pagination always makes progress. Deliberately smaller than the CLI and Python default of
    /// `[capabilities.message_classification].limit`: an MCP result is pasted straight into an
    /// agent context window, where a classification row carries a whole user message. Callers
    /// that want everything pass `all_results`.
    #[serde(default = "default_mcp_run_message_classification_limit")]
    pub run_message_classification_limit: usize,
    /// Default `get_session.transcript_lines`: positive=head, negative=tail,
    /// 0=entire transcript. Does not affect `get_session` calls that pass `message_seq`.
    #[serde(default = "default_mcp_get_session_transcript_line_window")]
    pub get_session_transcript_lines: i64,
    /// Default `preview_chars` for concise MCP hit/context previews and `get_session` summary or
    /// focused-message output. Explicit MCP tool-call `preview_chars` values still win. Does not
    /// affect transcript output. Must be at least 1.
    #[serde(default = "default_mcp_preview_chars")]
    pub preview_chars: usize,
    /// Default aggregate evidence window for get_session summary: positive=first,
    /// negative=last, zero=all.
    #[serde(default = "default_mcp_summary_items")]
    pub summary_items: i64,
    /// Default `lines_per_message` for `search_messages` hits/context and `get_session`
    /// focused `message_seq` output: caps each individual message's content to this many lines
    /// (positive=head, negative=tail, 0=full content). Distinct from
    /// `get_session_transcript_lines`, which windows one whole session transcript.
    #[serde(default = "default_message_line_window")]
    pub lines_per_message: i64,
    /// Default `query_session_index.max_cell_chars`: truncates long string cells in MCP JSON
    /// responses only. It does not change SQL execution or CLI `aise db query` output.
    /// `0` disables MCP string-cell truncation.
    #[serde(default = "default_mcp_query_max_cell_chars")]
    pub query_max_cell_chars: usize,
    /// MCP-only raw-SQL execution timeout in milliseconds. `0` (the default) disables
    /// interruption. This is separate from `[db].query_timeout_ms`; adopt a finite default only
    /// after representative valid-query and concurrency calibration justifies the availability
    /// guard.
    #[serde(default)]
    pub query_timeout_ms: u64,
    /// Internal MCP presentation budgets. These affect only generated tool descriptions, not
    /// search/query results. Leave unchanged unless the schema summary is too large/small for your
    /// MCP client.
    #[serde(default)]
    pub internal: McpInternalConfig,
    /// Per-row client-limit budgets, keyed by the row name `aise mcp schema-budget` reports,
    /// for example `codex-input-schema-bytes` or `claude-code-tool-description-chars`.
    ///
    /// These are client policy rather than protocol, and client policy moves: Codex raised its
    /// schema budget from 4,000 to 5,000 bytes in `b6f9aee16d`, and Gemini CLI's result cap
    /// differs by two orders of magnitude across forks of one codebase. The shipped values are
    /// what was measured from each client's source at a pinned version, recorded in
    /// `docs/development/mcp-client-limits-and-measured-evidence.md`. An operator running a
    /// client that has since moved sets the new number here instead of waiting for a release
    /// built against it.
    ///
    /// An unknown row name is rejected rather than ignored, so a typo cannot silently leave the
    /// shipped budget in force while appearing to change it.
    #[serde(default)]
    pub client_limits: BTreeMap<String, usize>,
}

/// Internal MCP presentation budgets (`[mcp.internal]`). These exist to keep tool descriptions
/// concise while still giving agents enough live schema context to form valid SQL.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
pub struct McpInternalConfig {
    /// Number of schema objects shown in the `query_session_index` tool description.
    #[serde(default = "default_mcp_internal_schema_summary_tables")]
    pub schema_summary_tables: usize,
    /// Number of columns per schema object shown in the `query_session_index` tool description.
    #[serde(default = "default_mcp_internal_schema_summary_columns")]
    pub schema_summary_columns: usize,
}

/// CLI defaults (`[cli]`). These affect command-line behavior only when the flag is omitted.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
pub struct CliConfig {
    /// Default `aise show --transcript-lines`: positive=head, negative=tail, 0=entire transcript.
    /// A bounded default keeps long sessions skimmable; pass `--transcript-lines 0` explicitly
    /// when the full transcript is needed.
    #[serde(default = "default_cli_show_transcript_line_window")]
    pub show_transcript_lines: i64,
    /// Default `aise messages search/get/timeline --lines-per-message`: caps each individual
    /// message's content to this many lines (positive=head, negative=tail, 0=full content).
    /// Distinct from `show_transcript_lines`, which windows one whole session transcript.
    #[serde(default = "default_message_line_window")]
    pub lines_per_message: i64,
    /// Default `aise messages evidence --preview-chars`. This affects only compact
    /// evidence previews; JSON message search/get output still keeps full message content. Must be
    /// at least 1.
    #[serde(default = "default_cli_evidence_preview_chars")]
    pub evidence_preview_chars: usize,
    /// Default aggregate evidence window for compact CLI summaries: positive=first,
    /// negative=last, zero=all.
    #[serde(default = "default_cli_summary_items")]
    pub summary_items: i64,
}

/// Native raw SQLite query defaults (`[db]`).
///
/// These apply to `aise db query` and public Rust callers when an argument is omitted. MCP has a
/// separate `mcp.query_timeout_ms` availability guard because its synchronous tool lifecycle is
/// distinct. Neither configuration affects indexed search APIs such as `search_messages`.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
pub struct DbConfig {
    /// Default maximum rows for read-only SQL. `0` means unlimited and can produce huge output.
    #[serde(default = "default_db_query_limit")]
    pub query_limit: usize,
    /// Native read-only SQL timeout in milliseconds. `0` (the default) disables interruption.
    #[serde(default = "default_db_query_timeout_ms")]
    pub query_timeout_ms: u64,
}

pub const DEFAULT_RELEASE_NOTIFICATION_MINIMUM_CHECK_INTERVAL_HOURS: u64 = 24;
pub const DEFAULT_RELEASE_NOTIFICATION_REQUEST_TIMEOUT_MS: u64 = 1_000;

/// Stable-release notification defaults (`[release_notifications]`).
/// Explicit `aise package check|update` requests remain available when notifications are disabled.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
pub struct ReleaseNotificationConfig {
    /// Check for an applicable release after ordinary interactive CLI output.
    pub enabled: bool,
    /// Minimum interval between completed notification checks.
    pub minimum_check_interval_hours: u64,
    /// End-to-end timeout for the GitHub release request.
    pub request_timeout_ms: u64,
}

impl Default for ReleaseNotificationConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            minimum_check_interval_hours: DEFAULT_RELEASE_NOTIFICATION_MINIMUM_CHECK_INTERVAL_HOURS,
            request_timeout_ms: DEFAULT_RELEASE_NOTIFICATION_REQUEST_TIMEOUT_MS,
        }
    }
}

/// Installed-integration upkeep (`[integrations]`).
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
pub struct IntegrationsConfig {
    /// After aise changes version, rewrite installed skill files and instruction blocks it wrote
    /// that nobody has edited, once, from the first CLI command or MCP server start. Edits are
    /// never rewritten.
    pub refresh_after_upgrade: bool,
}

impl Default for IntegrationsConfig {
    fn default() -> Self {
        Self {
            refresh_after_upgrade: true,
        }
    }
}

fn default_true() -> bool {
    true
}

fn default_limit() -> usize {
    50
}

fn default_preview_body_lines() -> usize {
    // Main's established four section caps are 8 + 4 + 8 + 14 body lines. Keeping their sum as
    // the default makes the now-live setting preserve the pre-worker preview byte-for-byte.
    34
}

fn default_idle_poll_interval_ms() -> u64 {
    150
}

fn default_search_debounce_ms() -> u64 {
    // Longer than the gap between keystrokes at a fast typing speed, so a burst becomes one
    // search rather than one cancelled scan per character, and short enough that the wait after
    // the last key is not the thing a reader notices. Measured on a 36.5 GB index, the search
    // itself takes 2.3 to 3.6 s, so this is a rounding error there; on a small index it is the
    // whole wait, which is why it is not larger.
    150
}

fn default_list_page_rows() -> usize {
    10
}

fn default_preview_scroll_rows() -> usize {
    5
}

fn default_preview_page_rows() -> usize {
    15
}

fn default_provider_label_width() -> usize {
    9
}

fn default_list_pane_percent() -> u16 {
    45
}

fn default_busy_timeout_ms() -> u64 {
    crate::db::DEFAULT_BUSY_TIMEOUT_MS
}

fn default_auto_reindex_busy_timeout_ms() -> u64 {
    crate::db::DEFAULT_AUTO_REINDEX_BUSY_TIMEOUT_MS
}

fn default_auto_reindex_interval_ms() -> u64 {
    crate::db::DEFAULT_AUTO_REINDEX_INTERVAL_MS
}

fn default_mcp_search_sessions_limit() -> usize {
    DEFAULT_MCP_SEARCH_SESSIONS_LIMIT
}
fn default_mcp_list_sessions_limit() -> usize {
    DEFAULT_MCP_LIST_SESSIONS_LIMIT
}
fn default_mcp_search_messages_limit() -> usize {
    DEFAULT_MCP_SEARCH_MESSAGES_LIMIT
}
fn default_mcp_max_tool_result_chars() -> usize {
    DEFAULT_MCP_MAX_TOOL_RESULT_CHARS
}
fn default_mcp_run_message_classification_limit() -> usize {
    DEFAULT_MCP_RUN_MESSAGE_CLASSIFICATION_LIMIT
}

fn default_mcp_get_session_transcript_line_window() -> i64 {
    DEFAULT_MCP_GET_SESSION_TRANSCRIPT_LINE_WINDOW
}
fn default_mcp_preview_chars() -> usize {
    DEFAULT_MCP_PREVIEW_CHARS
}
fn default_mcp_summary_items() -> i64 {
    DEFAULT_MCP_SUMMARY_ITEMS
}
fn default_mcp_query_max_cell_chars() -> usize {
    DEFAULT_MCP_QUERY_MAX_CELL_CHARS
}
fn default_mcp_internal_schema_summary_tables() -> usize {
    DEFAULT_MCP_INTERNAL_SCHEMA_SUMMARY_TABLES
}
fn default_mcp_internal_schema_summary_columns() -> usize {
    DEFAULT_MCP_INTERNAL_SCHEMA_SUMMARY_COLUMNS
}
fn default_cli_show_transcript_line_window() -> i64 {
    DEFAULT_CLI_SHOW_TRANSCRIPT_LINE_WINDOW
}
fn default_message_line_window() -> i64 {
    DEFAULT_MESSAGE_LINE_WINDOW
}
fn default_cli_evidence_preview_chars() -> usize {
    DEFAULT_CLI_EVIDENCE_PREVIEW_CHARS
}
fn default_cli_summary_items() -> i64 {
    DEFAULT_CLI_SUMMARY_ITEMS
}
fn default_db_query_limit() -> usize {
    DEFAULT_DB_QUERY_LIMIT
}
fn default_db_query_timeout_ms() -> u64 {
    DEFAULT_DB_QUERY_TIMEOUT_MS
}
fn default_message_classification_limit() -> usize {
    DEFAULT_MESSAGE_CLASSIFICATION_LIMIT
}
fn default_analytics_planning_limit() -> usize {
    DEFAULT_ANALYTICS_PLANNING_LIMIT
}
fn default_analytics_vocab_limit() -> usize {
    DEFAULT_ANALYTICS_VOCAB_LIMIT
}
fn default_analytics_repeat_max_groups() -> usize {
    DEFAULT_ANALYTICS_REPEAT_MAX_GROUPS
}
fn default_analytics_repeat_max_examples_per_group() -> usize {
    DEFAULT_ANALYTICS_REPEAT_MAX_EXAMPLES_PER_GROUP
}
fn default_analytics_repeat_min_matches() -> usize {
    DEFAULT_ANALYTICS_REPEAT_MIN_MATCHES
}
fn default_analytics_repeat_phrase_min_words() -> usize {
    DEFAULT_ANALYTICS_REPEAT_PHRASE_MIN_WORDS
}
fn default_analytics_repeat_phrase_max_words() -> usize {
    DEFAULT_ANALYTICS_REPEAT_PHRASE_MAX_WORDS
}
fn default_title_score() -> i64 {
    600
}
fn default_summary_score() -> i64 {
    450
}
fn default_path_score() -> i64 {
    350
}
fn default_preview_score() -> i64 {
    250
}
fn default_other_score() -> i64 {
    100
}
fn default_token_bonus() -> i64 {
    40
}
fn default_all_tokens_bonus() -> i64 {
    150
}
fn default_recency_weight() -> i64 {
    2
}
fn default_recency_max_days() -> i64 {
    90
}
fn default_current_repo_bonus() -> i64 {
    200
}
impl Default for ScoringConfig {
    fn default() -> Self {
        Self {
            title_score: default_title_score(),
            summary_score: default_summary_score(),
            path_score: default_path_score(),
            preview_score: default_preview_score(),
            other_score: default_other_score(),
            token_bonus: default_token_bonus(),
            all_tokens_bonus: default_all_tokens_bonus(),
            recency_weight: default_recency_weight(),
            recency_max_days: default_recency_max_days(),
            current_repo_bonus: default_current_repo_bonus(),
        }
    }
}

impl Default for Config {
    fn default() -> Self {
        let home = home_dir_fallback();
        Self {
            providers: ProvidersConfig {
                claude: ProviderConfig {
                    enabled: true,
                    paths: vec![home.join(".claude/projects").to_string_lossy().to_string()],
                },
                claude_desktop: ProviderConfig {
                    enabled: true,
                    paths: default_claude_desktop_paths(),
                },
                codex: ProviderConfig {
                    enabled: true,
                    paths: vec![home.join(".codex/sessions").to_string_lossy().to_string()],
                },
                cursor: ProviderConfig {
                    enabled: true,
                    paths: vec![home.join(".cursor/projects").to_string_lossy().to_string()],
                },
                antigravity: ProviderConfig {
                    enabled: true,
                    paths: default_antigravity_paths(),
                },
                pi: ProviderConfig {
                    enabled: true,
                    paths: vec![home
                        .join(".pi/agent/sessions")
                        .to_string_lossy()
                        .to_string()],
                },
                prime_agent: ProviderConfig {
                    enabled: true,
                    paths: vec![
                        home.join(".prime/agent/sessions")
                            .to_string_lossy()
                            .to_string(),
                        home.join(".prime/agent/session-artifacts")
                            .to_string_lossy()
                            .to_string(),
                    ],
                },
                aistudio: ProviderConfig {
                    enabled: true,
                    paths: Vec::new(),
                },
                gemini_cli: ProviderConfig {
                    enabled: true,
                    paths: vec![home.join(".gemini/tmp").to_string_lossy().to_string()],
                },
            },
            index: IndexConfig {
                db_path: Some(default_db_path().to_string_lossy().into_owned()),
                cache_dir: Some(default_cache_dir().to_string_lossy().into_owned()),
                refresh: IndexRefresh::Auto,
                busy_timeout_ms: default_busy_timeout_ms(),
                auto_reindex_busy_timeout_ms: default_auto_reindex_busy_timeout_ms(),
                auto_reindex_interval_ms: default_auto_reindex_interval_ms(),
            },
            ui: UiConfig {
                preview_body_lines: default_preview_body_lines(),
                idle_poll_interval_ms: default_idle_poll_interval_ms(),
                search_debounce_ms: default_search_debounce_ms(),
                list_page_rows: default_list_page_rows(),
                preview_scroll_rows: default_preview_scroll_rows(),
                preview_page_rows: default_preview_page_rows(),
                provider_label_width: default_provider_label_width(),
                list_pane_percent: default_list_pane_percent(),
                unicode: CapabilityMode::default(),
                color: CapabilityMode::default(),
                keys: KeyBindings::default(),
            },
            search: SearchConfig {
                default_limit: default_limit(),
                prefer_current_repo: default_true(),
                scoring: ScoringConfig::default(),
                message_search: MessageSearchConfig::default(),
                budgets: SearchBudgetConfig::default(),
                scope: SearchScopeConfig::default(),
                purposes: BTreeMap::new(),
            },
            analytics: AnalyticsConfig::default(),
            skills: SkillsConfig::default(),
            capabilities: CapabilitiesConfig::default(),
            performance: PerformanceConfig::default(),
            mcp: McpConfig::default(),
            cli: CliConfig::default(),
            db: DbConfig::default(),
            release_notifications: ReleaseNotificationConfig::default(),
            integrations: IntegrationsConfig::default(),
        }
    }
}

fn default_claude_desktop_paths() -> Vec<String> {
    let mut paths = Vec::new();
    if cfg!(target_os = "macos") {
        if let Some(home) = dirs::home_dir() {
            push_unique_path(
                &mut paths,
                home.join("Library/Application Support/Claude/local-agent-mode-sessions"),
            );
        }
    }
    if let Some(config_dir) = dirs::config_dir() {
        push_unique_path(
            &mut paths,
            config_dir.join("Claude/local-agent-mode-sessions"),
        );
        push_unique_path(
            &mut paths,
            config_dir.join("claude/local-agent-mode-sessions"),
        );
    }
    if let Some(data_dir) = dirs::data_dir() {
        push_unique_path(
            &mut paths,
            data_dir.join("Claude/local-agent-mode-sessions"),
        );
    }
    if let Some(data_local_dir) = dirs::data_local_dir() {
        push_unique_path(
            &mut paths,
            data_local_dir.join("Claude/local-agent-mode-sessions"),
        );
    }
    paths
}

fn default_antigravity_paths() -> Vec<String> {
    let home = home_dir_fallback();
    let mut paths = Vec::new();
    push_unique_path(&mut paths, home.join(".gemini/antigravity-cli/brain"));
    push_unique_path(&mut paths, home.join(".gemini/antigravity/brain"));
    paths
}

fn push_unique_path(paths: &mut Vec<String>, path: PathBuf) {
    let value = path.to_string_lossy().to_string();
    if !paths.iter().any(|existing| existing == &value) {
        paths.push(value);
    }
}

impl Config {
    /// Resolve the already-merged worker-thread setting, falling back to host parallelism.
    /// Always returns `>= 1`. `1` means run sequentially (single worker).
    pub fn resolve_threads(&self) -> usize {
        if self.performance.threads > 0 {
            return self.performance.threads;
        }
        std::thread::available_parallelism()
            .map(|n| n.get())
            .unwrap_or(1)
    }

    /// Resolve the named MCP reader policy to the positive admission bound used by the semaphore.
    pub fn resolve_mcp_max_concurrent_reads(&self) -> Result<NonZeroUsize> {
        self.mcp.max_concurrent_reads.resolve()
    }
}

impl Default for ProvidersConfig {
    fn default() -> Self {
        Config::default().providers
    }
}

impl Default for ProviderConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            paths: Vec::new(),
        }
    }
}

impl Default for IndexConfig {
    fn default() -> Self {
        Config::default().index
    }
}

impl Default for UiConfig {
    fn default() -> Self {
        Config::default().ui
    }
}

impl Default for SearchConfig {
    fn default() -> Self {
        Config::default().search
    }
}

impl Default for AnalyticsConfig {
    fn default() -> Self {
        Self {
            planning_commands: Vec::new(),
            planning_limit: default_analytics_planning_limit(),
            vocab_limit: default_analytics_vocab_limit(),
            repeat_max_groups: default_analytics_repeat_max_groups(),
            repeat_max_examples_per_group: default_analytics_repeat_max_examples_per_group(),
            repeat_min_matches: default_analytics_repeat_min_matches(),
            repeat_phrase_min_words: default_analytics_repeat_phrase_min_words(),
            repeat_phrase_max_words: default_analytics_repeat_phrase_max_words(),
        }
    }
}

impl Default for MessageClassificationConfig {
    fn default() -> Self {
        Self {
            limit: default_message_classification_limit(),
        }
    }
}

impl Default for McpConfig {
    fn default() -> Self {
        Self {
            max_concurrent_reads: McpReadConcurrency::Auto,
            search_sessions_limit: default_mcp_search_sessions_limit(),
            list_sessions_limit: default_mcp_list_sessions_limit(),
            search_messages_limit: default_mcp_search_messages_limit(),
            max_tool_result_chars: default_mcp_max_tool_result_chars(),
            run_message_classification_limit: default_mcp_run_message_classification_limit(),
            get_session_transcript_lines: default_mcp_get_session_transcript_line_window(),
            preview_chars: default_mcp_preview_chars(),
            summary_items: default_mcp_summary_items(),
            lines_per_message: default_message_line_window(),
            query_max_cell_chars: default_mcp_query_max_cell_chars(),
            query_timeout_ms: 0,
            internal: McpInternalConfig::default(),
            client_limits: BTreeMap::new(),
        }
    }
}

impl Default for McpInternalConfig {
    fn default() -> Self {
        Self {
            schema_summary_tables: default_mcp_internal_schema_summary_tables(),
            schema_summary_columns: default_mcp_internal_schema_summary_columns(),
        }
    }
}

impl Default for CliConfig {
    fn default() -> Self {
        Self {
            show_transcript_lines: default_cli_show_transcript_line_window(),
            lines_per_message: default_message_line_window(),
            evidence_preview_chars: default_cli_evidence_preview_chars(),
            summary_items: default_cli_summary_items(),
        }
    }
}

impl Default for DbConfig {
    fn default() -> Self {
        Self {
            query_limit: default_db_query_limit(),
            query_timeout_ms: default_db_query_timeout_ms(),
        }
    }
}

impl Config {
    pub fn selected_config_path(override_path: Option<PathBuf>) -> PathBuf {
        override_path
            .or_else(|| nonempty_env_path("AI_SESSION_SEARCH_CONFIG"))
            .map_or_else(Self::config_path, expand_override_path)
    }

    pub fn load() -> Result<Self> {
        Ok(Self::resolve(ConfigOverrides::default())?.config)
    }

    pub fn resolve(overrides: ConfigOverrides) -> Result<ResolvedConfig> {
        Self::resolve_with_environment(overrides, ConfigEnvironment::capture())
    }

    pub fn resolve_with_environment(
        overrides: ConfigOverrides,
        environment: ConfigEnvironment,
    ) -> Result<ResolvedConfig> {
        let (config_path, config_origin, explicit_config_path) =
            if let Some(path) = overrides.config_path {
                (expand_override_path(path), "cli --config".to_string(), true)
            } else if let Some(path) = environment.config_path {
                (
                    expand_override_path(path),
                    "environment AI_SESSION_SEARCH_CONFIG".to_string(),
                    true,
                )
            } else {
                (
                    Self::config_path(),
                    "platform/legacy discovery".to_string(),
                    false,
                )
            };
        let raw = read_config_text(&config_path, explicit_config_path)?;
        let document: toml::Value = toml::from_str(&raw)
            .with_context(|| format!("failed to parse config file {}", config_path.display()))?;
        let mut config: Config = match without_superseded_names(&document) {
            // Parsed from the table only when a key must be dropped, so every other file keeps
            // error messages that point at its own line and column.
            Some(document) => document.try_into(),
            None => toml::from_str(&raw),
        }
        .with_context(|| format!("failed to parse config file {}", config_path.display()))?;
        let has_database_config = toml_has_key(&document, "index", "db_path");
        let has_cache_config = toml_has_key(&document, "index", "cache_dir");
        let has_index_refresh_config = toml_has_key(&document, "index", "refresh");
        let has_threads_config =
            toml_has_key(&document, "performance", "threads") && config.performance.threads > 0;
        let has_search_scope_config = document
            .get("search")
            .and_then(|search| search.get("scope"))
            .is_some();
        let has_search_messages_limit_config =
            toml_has_key(&document, "mcp", "search_messages_limit");
        let has_max_tool_result_chars_config =
            toml_has_key(&document, "mcp", "max_tool_result_chars");
        anchor_toml_paths(
            &mut config,
            &document,
            &absolute_config_parent(&config_path)?,
            has_database_config,
            has_cache_config,
        );

        let (database, database_origin) = if let Some(path) = overrides.database_path {
            (path, "cli --database".to_string())
        } else if let Some(path) = environment.database_path {
            (path, "environment AI_SESSION_SEARCH_DATABASE".to_string())
        } else {
            (
                config.db_path(),
                if has_database_config {
                    "config file"
                } else {
                    "typed/platform default"
                }
                .to_string(),
            )
        };
        config.index.db_path = Some(database.to_string_lossy().into_owned());

        let (cache, cache_origin) = if let Some(path) = overrides.cache_dir {
            (path, "cli --cache-dir".to_string())
        } else if let Some(path) = environment.cache_dir {
            (path, "environment AI_SESSION_SEARCH_CACHE_DIR".to_string())
        } else {
            (
                config.cache_dir(),
                if has_cache_config {
                    "config file"
                } else {
                    "typed/platform default"
                }
                .to_string(),
            )
        };
        config.index.cache_dir = Some(cache.to_string_lossy().into_owned());

        let (index_refresh, index_refresh_origin) = resolve_index_refresh_setting(
            overrides.index_refresh,
            environment.index_refresh.as_deref(),
            config.index.refresh,
            has_index_refresh_config,
        )?;
        config.index.refresh = index_refresh;

        let (threads, threads_origin) = resolve_threads_setting(
            overrides.threads,
            environment.threads.as_deref(),
            config.performance.threads,
            has_threads_config,
        )?;
        config.performance.threads = threads;

        let (max_tool_result_chars, max_tool_result_chars_origin) = resolve_max_tool_result_chars(
            environment.max_tool_result_chars.as_deref(),
            config.mcp.max_tool_result_chars,
            has_max_tool_result_chars_config,
        )?;
        config.mcp.max_tool_result_chars = max_tool_result_chars;

        // Registration over config file, so one harness can differ from the machine default. The
        // merge is per row rather than wholesale: a registration that overrides Codex's schema
        // budget should not silently discard a `[mcp.client_limits]` entry for another client.
        let client_limits_from_registration: Vec<String> =
            environment.client_limits.keys().cloned().collect();
        // Named here rather than left to `validate`, so a registration mistake reports the
        // variable the operator actually wrote instead of the row name it was translated into.
        for (row, raw) in &environment.client_limits {
            if !crate::mcp_schema_budget::declared_limit_names().contains(&row.as_str()) {
                bail!(
                    "{} names no client limit. Run `aise mcp schema-budget` to list the rows it \
                     reports, then correct or remove the variable in this MCP registration's \
                     `env` block.",
                    client_limit_env_var(row)
                );
            }
            if !crate::mcp_schema_budget::limit_overridable(row).unwrap_or(false) {
                bail!(
                    "{} names {row}, a structural rule rather than a client budget: overriding \
                     the number silences the checker while the client still rejects the schema. \
                     Remove the variable and fix the emitted schema instead.",
                    client_limit_env_var(row)
                );
            }
            let parsed: usize = raw.trim().parse().map_err(|_| {
                anyhow::anyhow!(
                    "{} is {raw:?}, which does not parse as a whole number. It overrides the \
                     {row} budget; correct or remove the variable in this MCP registration's \
                     `env` block.",
                    client_limit_env_var(row)
                )
            })?;
            config.mcp.client_limits.insert(row.clone(), parsed);
        }

        config
            .validate()
            .with_context(|| format!("invalid config at {}", config_path.display()))?;

        // Computed before `config` moves into the resolved value below.
        let client_limit_origins: BTreeMap<String, String> = config
            .mcp
            .client_limits
            .keys()
            .map(|row| {
                let origin = if client_limits_from_registration.contains(row) {
                    format!("environment {}", client_limit_env_var(row))
                } else {
                    "config file".to_string()
                };
                (row.clone(), origin)
            })
            .collect();
        Ok(ResolvedConfig {
            config,
            config_path,
            origins: ConfigOrigins {
                config: config_origin,
                database: database_origin,
                cache: cache_origin,
                threads: threads_origin,
                index_refresh: index_refresh_origin,
                search_scope: if has_search_scope_config {
                    "config file"
                } else {
                    "typed default"
                }
                .to_string(),
                // No environment variable resolves the page size, and none is added here. A
                // caller who wants a different page passes `limit`, which every message-search
                // surface already accepts and which the response echoes in `effective_request`;
                // a deployment that wants a different default sets it in the config file. A
                // third spelling would be a fourth place to look when the number surprises
                // someone.
                search_messages_limit: if has_search_messages_limit_config {
                    "config file"
                } else {
                    "typed default"
                }
                .to_string(),
                max_tool_result_chars: max_tool_result_chars_origin,
                client_limits: client_limit_origins,
            },
        })
    }

    pub fn config_path() -> PathBuf {
        let home = home_dir_fallback();
        let app = home.join(".ai-session-search/config.toml");
        let platform_legacy = dirs::config_dir()
            .unwrap_or_else(|| home.join(".config"))
            .join("ai-session-search/config.toml");
        let xdg_legacy = home.join(".config/ai-session-search/config.toml");
        choose_config_path(
            nonempty_env_path("AI_SESSION_SEARCH_CONFIG"),
            app,
            &[platform_legacy, xdg_legacy],
        )
    }

    pub fn db_path(&self) -> PathBuf {
        self.index
            .db_path
            .as_deref()
            .map(expand_tilde)
            .unwrap_or_else(default_db_path)
    }

    pub fn cache_dir(&self) -> PathBuf {
        self.index
            .cache_dir
            .as_deref()
            .map(expand_tilde)
            .unwrap_or_else(default_cache_dir)
    }

    pub fn claude_paths(&self) -> Vec<PathBuf> {
        self.providers
            .claude
            .paths
            .iter()
            .map(|path| expand_tilde(path))
            .collect()
    }

    pub fn claude_desktop_paths(&self) -> Vec<PathBuf> {
        self.providers
            .claude_desktop
            .paths
            .iter()
            .map(|path| expand_tilde(path))
            .collect()
    }

    pub fn codex_paths(&self) -> Vec<PathBuf> {
        self.providers
            .codex
            .paths
            .iter()
            .map(|path| expand_tilde(path))
            .collect()
    }

    pub fn cursor_paths(&self) -> Vec<PathBuf> {
        self.providers
            .cursor
            .paths
            .iter()
            .map(|path| expand_tilde(path))
            .collect()
    }

    pub fn antigravity_paths(&self) -> Vec<PathBuf> {
        self.providers
            .antigravity
            .paths
            .iter()
            .map(|path| expand_tilde(path))
            .collect()
    }

    pub fn pi_paths(&self) -> Vec<PathBuf> {
        self.providers
            .pi
            .paths
            .iter()
            .map(|path| expand_tilde(path))
            .collect()
    }

    pub fn prime_agent_paths(&self) -> Vec<PathBuf> {
        self.providers
            .prime_agent
            .paths
            .iter()
            .map(|path| expand_tilde(path))
            .collect()
    }

    pub fn aistudio_paths(&self) -> Vec<PathBuf> {
        self.providers
            .aistudio
            .paths
            .iter()
            .map(|path| expand_tilde(path))
            .collect()
    }

    pub fn gemini_cli_paths(&self) -> Vec<PathBuf> {
        self.providers
            .gemini_cli
            .paths
            .iter()
            .map(|path| expand_tilde(path))
            .collect()
    }

    pub fn validate(&self) -> Result<()> {
        const FIX: &str = "edit the invalid value in the config file; run `aise config example` \
                           to view the defaults (`aise config init --force` replaces the entire file)";
        if self.search.default_limit == 0 {
            bail!("search.default_limit must be greater than zero; {FIX}");
        }
        if self.ui.preview_body_lines == 0 {
            bail!("ui.preview_body_lines must be greater than zero; {FIX}");
        }
        if self.ui.idle_poll_interval_ms == 0 {
            bail!("ui.idle_poll_interval_ms must be greater than zero; {FIX}");
        }
        if self.ui.list_page_rows == 0 {
            bail!("ui.list_page_rows must be greater than zero; {FIX}");
        }
        if self.ui.preview_scroll_rows == 0 {
            bail!("ui.preview_scroll_rows must be greater than zero; {FIX}");
        }
        if self.ui.preview_page_rows == 0 {
            bail!("ui.preview_page_rows must be greater than zero; {FIX}");
        }
        if self.ui.provider_label_width == 0 {
            bail!("ui.provider_label_width must be greater than zero; {FIX}");
        }
        // The vocabulary's own rules: one chord meaning two things in a mode, and a table
        // with no way out. Parsing already refused an unknown spelling.
        self.ui.keys.validate()?;
        if !(10..=90).contains(&self.ui.list_pane_percent) {
            bail!("ui.list_pane_percent must be between 10 and 90 inclusive; {FIX}");
        }
        if Instant::now()
            .checked_add(Duration::from_millis(self.ui.idle_poll_interval_ms))
            .is_none()
        {
            bail!(
                "ui.idle_poll_interval_ms is too large for this platform's monotonic clock; \
                 choose a smaller millisecond interval; {FIX}"
            );
        }
        // No lower bound: unlike the pacing and step settings, 0 names a behavior here rather
        // than an impossible one — search on every keystroke, which is what this did before the
        // setting existed.
        if Instant::now()
            .checked_add(Duration::from_millis(self.ui.search_debounce_ms))
            .is_none()
        {
            bail!(
                "ui.search_debounce_ms is too large for this platform's monotonic clock; \
                 choose a smaller millisecond delay, or 0 to search on every keystroke; {FIX}"
            );
        }
        if self.release_notifications.minimum_check_interval_hours == 0 {
            bail!(
                "release_notifications.minimum_check_interval_hours must be 1 or greater, got 0; \
                 pass the minimum whole hours between completed release-notification checks; {FIX}"
            );
        }
        if self.release_notifications.request_timeout_ms == 0 {
            bail!(
                "release_notifications.request_timeout_ms must be 1 or greater, got 0; \
                 pass the end-to-end release-notification request timeout in milliseconds; {FIX}"
            );
        }
        if self.mcp.search_messages_limit == 0 {
            bail!("mcp.search_messages_limit must be greater than zero; {FIX}");
        }
        self.resolve_mcp_max_concurrent_reads()?;
        if self.mcp.run_message_classification_limit == 0 {
            bail!(
                "mcp.run_message_classification_limit must be 1 or greater, got 0; \
                 pass the default number of classification matches in one MCP page; {FIX}"
            );
        }
        if self.search.scoring.recency_max_days < 0 {
            bail!(
                "search.scoring.recency_max_days must be 0 or greater, got {}; {FIX}",
                self.search.scoring.recency_max_days
            );
        }
        if let Some(maximum) = self.search.budgets.max_hits_per_page {
            if self
                .search
                .message_search
                .default_limit
                .is_some_and(|limit| limit > maximum)
            {
                bail!(
                    "search.message-search.default_limit exceeds search.budgets.max_hits_per_page {}; {FIX}",
                    maximum
                );
            }
            if self.mcp.search_messages_limit > maximum.get() {
                bail!(
                    "mcp.search_messages_limit {} exceeds search.budgets.max_hits_per_page {}; {FIX}",
                    self.mcp.search_messages_limit,
                    maximum
                );
            }
        }
        let context_total = self
            .search
            .message_search
            .context
            .context_before
            .unwrap_or(0)
            .checked_add(
                self.search
                    .message_search
                    .context
                    .context_after
                    .unwrap_or(0),
            )
            .ok_or_else(|| {
                anyhow::anyhow!("search.message-search.context total overflows usize; {FIX}")
            })?;
        if self
            .search
            .budgets
            .max_context_neighbors_per_hit
            .is_some_and(|maximum| context_total > maximum.get())
        {
            bail!(
                "search.message-search.context exceeds search.budgets.max_context_neighbors_per_hit; {FIX}"
            );
        }
        if self.search.scope.mode == SearchScopeMode::All
            && (!self.search.scope.roots.is_empty()
                || self.search.scope.include_invocation_directory)
        {
            bail!(
                "search.scope roots and include_invocation_directory require mode = \"allowed-roots\"; {FIX}"
            );
        }
        if self
            .search
            .scope
            .roots
            .iter()
            .any(|root| root.trim().is_empty())
        {
            bail!("search.scope.roots must not contain an empty path; {FIX}");
        }
        for root in &self.search.scope.roots {
            crate::search_scope::validate_configured_root(std::path::Path::new(root)).map_err(
                |error| anyhow::anyhow!("search.scope.roots entry {root:?}: {error}; {FIX}"),
            )?;
        }
        // A key naming no row would otherwise sit in config.toml looking like it raised a budget
        // while the shipped one stayed in force, which is the failure this whole surface exists
        // to prevent: a limit that appears configured and is not.
        for name in self.mcp.client_limits.keys() {
            if !crate::mcp_schema_budget::declared_limit_names().contains(&name.as_str()) {
                bail!(
                    "mcp.client_limits.{name:?} names no client limit. Run \
                     `aise mcp schema-budget` to list the rows it reports; {FIX}"
                );
            }
            // A structural row's number is not a moving client cap: accepting an override for
            // it would silence the checker while the client still rejects the schema outright.
            if !crate::mcp_schema_budget::limit_overridable(name).unwrap_or(false) {
                bail!(
                    "mcp.client_limits.{name:?} is a structural rule rather than a client \
                     budget: overriding the number silences the checker while the client still \
                     rejects the schema. Remove the entry and fix the emitted schema; {FIX}"
                );
            }
        }
        for (name, purpose) in &self.search.purposes {
            if !crate::message_search::is_dash_separated_phrase(name) {
                bail!(
                    "search.purposes name {name:?} must be a short lowercase dash-separated phrase; {FIX}"
                );
            }
            if purpose.operation != SearchOperation::MessageSearch {
                bail!("search.purposes.{name}.operation is not supported; {FIX}");
            }
            if let Some(lines) = purpose.preferences.lines_per_message {
                crate::message_search::LineWindow::from_signed(lines).map_err(|error| {
                    anyhow::anyhow!("search.purposes.{name}.lines_per_message: {error}; {FIX}")
                })?;
            }
            if let (Some(limit), Some(maximum)) = (
                purpose.preferences.default_limit,
                self.search.budgets.max_hits_per_page,
            ) {
                if limit > maximum {
                    bail!(
                        "search.purposes.{name}.default_limit {} exceeds search.budgets.max_hits_per_page {}; {FIX}",
                        limit,
                        maximum
                    );
                }
            }
            if let Some(maximum) = self.search.budgets.max_context_neighbors_per_hit {
                let total = purpose
                    .preferences
                    .context_before
                    .unwrap_or(0)
                    .checked_add(purpose.preferences.context_after.unwrap_or(0))
                    .ok_or_else(|| {
                        anyhow::anyhow!(
                            "search.purposes.{name} context total overflows usize; {FIX}"
                        )
                    })?;
                if total > maximum.get() {
                    bail!(
                        "search.purposes.{name} context total {total} exceeds search.budgets.max_context_neighbors_per_hit {}; {FIX}",
                        maximum
                    );
                }
            }
        }
        if self.mcp.preview_chars == 0 {
            bail!("mcp.preview_chars must be greater than zero; {FIX}");
        }
        // The same floor the environment path enforces: unlike the sibling knobs where 0 means
        // disabled, a delivery ceiling of 0 would reject every result including the smallest.
        if self.mcp.max_tool_result_chars == 0 {
            bail!(
                "mcp.max_tool_result_chars must be 1 or greater: it bounds the serialized MCP \
                 tool result in characters, and a ceiling of 0 would reject every result \
                 including the smallest. Remove the key to keep the default; {FIX}"
            );
        }
        if self.cli.evidence_preview_chars == 0 {
            bail!("cli.evidence_preview_chars must be greater than zero; {FIX}");
        }
        if self.analytics.repeat_min_matches == 0 {
            bail!("analytics.repeat_min_matches must be greater than zero; {FIX}");
        }
        if self.analytics.repeat_phrase_min_words == 0 {
            bail!("analytics.repeat_phrase_min_words must be greater than zero; {FIX}");
        }
        if self.analytics.repeat_phrase_max_words < self.analytics.repeat_phrase_min_words {
            bail!("analytics.repeat_phrase_max_words must be >= repeat_phrase_min_words; {FIX}");
        }
        Ok(())
    }
}

fn home_dir_fallback() -> PathBuf {
    dirs::home_dir()
        .unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")))
}

fn nonempty_env_path(name: &str) -> Option<PathBuf> {
    std::env::var_os(name)
        .filter(|value| !value.is_empty())
        .map(PathBuf::from)
}

/// Prefix for the per-row client-limit variables a registration sets in its own `env` block.
pub const CLIENT_LIMIT_ENV_PREFIX: &str = "AI_SESSION_SEARCH_CLIENT_LIMIT_";

/// The variable that overrides one client-limit row for one harness.
///
/// `[mcp.client_limits]` is one setting for every harness a machine serves, and these numbers are
/// per client: Codex bounds a schema at 5,000 bytes and Claude Code does not bound it at all. A
/// registration's `env` block is the only place a deployment can give one harness a different
/// budget without giving every harness the same one, which is why the result ceiling already
/// reads `AI_SESSION_SEARCH_MAX_TOOL_RESULT_CHARS` from there.
pub fn client_limit_env_var(row: &str) -> String {
    format!(
        "{CLIENT_LIMIT_ENV_PREFIX}{}",
        row.to_ascii_uppercase().replace('-', "_")
    )
}

/// Read every client-limit override out of an environment, keyed back to its row name.
///
/// Every variable carrying the prefix is returned raw, including one whose suffix names no row
/// and one whose value does not parse. Dropping either here would leave the shipped budget in
/// force while the registration looked like it had moved one; `Config::resolve` rejects both
/// against the variable's own name.
pub fn client_limits_from_environment<I>(vars: I) -> BTreeMap<String, String>
where
    I: Iterator<Item = (String, String)>,
{
    vars.filter_map(|(key, value)| {
        let row = key.strip_prefix(CLIENT_LIMIT_ENV_PREFIX)?;
        Some((row.to_ascii_lowercase().replace('_', "-"), value))
    })
    .collect()
}

fn nonempty_env_string(name: &str) -> Option<String> {
    std::env::var(name)
        .ok()
        .map(|value| value.trim().to_string())
        .filter(|value| !value.is_empty())
}

fn parse_positive_threads(name: &str, raw: &str) -> Result<usize> {
    match raw.trim().parse::<usize>() {
        Ok(value) if value > 0 => Ok(value),
        _ => bail!("{name} must be a positive integer, got {raw:?}"),
    }
}

fn resolve_index_refresh_setting(
    cli: Option<IndexRefresh>,
    environment: Option<&str>,
    configured: IndexRefresh,
    configured_explicitly: bool,
) -> Result<(IndexRefresh, String)> {
    if let Some(value) = cli {
        return Ok((value, "cli --index-refresh".to_string()));
    }
    if let Some(raw) = environment {
        return Ok((
            raw.parse().map_err(|error: String| {
                anyhow::anyhow!("AI_SESSION_SEARCH_INDEX_REFRESH {error}")
            })?,
            "environment AI_SESSION_SEARCH_INDEX_REFRESH".to_string(),
        ));
    }
    Ok((
        configured,
        if configured_explicitly {
            "config file"
        } else {
            "typed default"
        }
        .to_string(),
    ))
}

fn resolve_threads_setting(
    cli: Option<usize>,
    canonical_env: Option<&str>,
    configured: usize,
    configured_explicitly: bool,
) -> Result<(usize, String)> {
    if let Some(value) = cli {
        if value == 0 {
            bail!("--threads must be a positive integer");
        }
        return Ok((value, "cli --threads".to_string()));
    }
    if let Some(raw) = canonical_env {
        return Ok((
            parse_positive_threads("AI_SESSION_SEARCH_THREADS", raw)?,
            "environment AI_SESSION_SEARCH_THREADS".to_string(),
        ));
    }
    Ok((
        configured,
        if configured_explicitly {
            "config file"
        } else {
            "typed/host default"
        }
        .to_string(),
    ))
}

/// Resolve the serialized-`CallToolResult` ceiling: registration environment, then config file,
/// then the typed default.
///
/// There is no CLI override on purpose. The ceiling belongs to a long-lived server process that
/// a client launches from a config entry, so the flag would have to be threaded through every
/// registration this project writes; the `env` block those registrations already carry is the
/// one place a deployment can set it per harness. That is also why the environment wins over the
/// config file rather than the other way round: the config file is shared by every harness on
/// the machine, and the registration block is the narrower, more deliberate statement.
///
/// An unusable value is rejected rather than ignored. A registration that sets a bound and does
/// not get it is the defect this function exists to close, and silently falling back to the
/// default would reproduce it one layer down.
fn resolve_max_tool_result_chars(
    environment: Option<&str>,
    configured: usize,
    configured_explicitly: bool,
) -> Result<(usize, String)> {
    if let Some(raw) = environment {
        return Ok((
            parse_positive_result_ceiling("AI_SESSION_SEARCH_MAX_TOOL_RESULT_CHARS", raw)?,
            "environment AI_SESSION_SEARCH_MAX_TOOL_RESULT_CHARS".to_string(),
        ));
    }
    Ok((
        configured,
        if configured_explicitly {
            "config file"
        } else {
            "typed default"
        }
        .to_string(),
    ))
}

/// A ceiling of zero would reject every result including the smallest, so 1 is the floor.
fn parse_positive_result_ceiling(name: &str, raw: &str) -> Result<usize> {
    match raw.trim().parse::<usize>() {
        Ok(value) if value > 0 => Ok(value),
        _ => bail!(
            "{name} must be an integer of 1 or greater, got {raw:?}. It bounds the serialized \
             MCP tool result in characters; a ceiling of 0 would reject every result."
        ),
    }
}

/// `document` without an old key name when the file also sets the current one, or `None`.
///
/// A serde alias accepts the old name alone, but a file that sets both fails with "duplicate
/// field", which names only the new key and stops every command, including the MCP server. No
/// release loaded such a file (1.0.0rc2 knew only `preview_lines`, 1.0.0rc3 only
/// `preview_body_lines`), so no earlier behavior depends on it, and the current name wins.
fn without_superseded_names(document: &toml::Value) -> Option<toml::Value> {
    if !(toml_has_key(document, "ui", "preview_lines")
        && toml_has_key(document, "ui", "preview_body_lines"))
    {
        return None;
    }
    let mut document = document.clone();
    if let Some(ui) = document.get_mut("ui").and_then(toml::Value::as_table_mut) {
        ui.remove("preview_lines");
    }
    Some(document)
}

fn toml_has_key(document: &toml::Value, table: &str, key: &str) -> bool {
    document
        .get(table)
        .cloned()
        .and_then(|value| value.get(key).cloned())
        .is_some()
}

fn read_config_text(path: &std::path::Path, explicit: bool) -> Result<String> {
    match fs::read_to_string(path) {
        Ok(raw) => Ok(raw),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound && !explicit => {
            Ok(String::new())
        }
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
            bail!("explicit config file does not exist: {}", path.display())
        }
        Err(error) => {
            Err(error).with_context(|| format!("failed to read config file {}", path.display()))
        }
    }
}

fn absolute_config_parent(path: &std::path::Path) -> Result<PathBuf> {
    let parent = path
        .parent()
        .filter(|parent| !parent.as_os_str().is_empty())
        .unwrap_or_else(|| std::path::Path::new("."));
    if parent.is_absolute() {
        Ok(parent.to_path_buf())
    } else {
        Ok(std::env::current_dir()
            .context("failed to resolve current directory for relative config path")?
            .join(parent))
    }
}

fn anchor_toml_paths(
    config: &mut Config,
    document: &toml::Value,
    config_parent: &std::path::Path,
    has_database_config: bool,
    has_cache_config: bool,
) {
    if has_database_config {
        anchor_optional_path(&mut config.index.db_path, config_parent);
    }
    if has_cache_config {
        anchor_optional_path(&mut config.index.cache_dir, config_parent);
    }
    for (provider_name, provider) in [
        ("claude", &mut config.providers.claude),
        ("claude-desktop", &mut config.providers.claude_desktop),
        ("codex", &mut config.providers.codex),
        ("cursor", &mut config.providers.cursor),
        ("antigravity", &mut config.providers.antigravity),
        ("pi", &mut config.providers.pi),
        ("prime-agent", &mut config.providers.prime_agent),
        ("aistudio", &mut config.providers.aistudio),
        ("gemini-cli", &mut config.providers.gemini_cli),
    ] {
        if toml_has_nested_key(document, "providers", provider_name, "paths") {
            for path in &mut provider.paths {
                *path = anchored_path(path, config_parent);
            }
        }
    }
}

fn anchor_optional_path(value: &mut Option<String>, config_parent: &std::path::Path) {
    if let Some(path) = value {
        *path = anchored_path(path, config_parent);
    }
}

fn anchored_path(value: &str, config_parent: &std::path::Path) -> String {
    let path = std::path::Path::new(value);
    if value.is_empty() || value == "~" || value.starts_with("~/") || path.is_absolute() {
        value.to_string()
    } else {
        config_parent.join(path).to_string_lossy().into_owned()
    }
}

fn toml_has_nested_key(document: &toml::Value, table: &str, nested: &str, key: &str) -> bool {
    document
        .get(table)
        .cloned()
        .and_then(|value| value.get(nested).cloned())
        .and_then(|value| value.get(key).cloned())
        .is_some()
}

fn choose_config_path(
    override_path: Option<PathBuf>,
    app_path: PathBuf,
    legacy_paths: &[PathBuf],
) -> PathBuf {
    if let Some(path) = override_path {
        return expand_override_path(path);
    }
    // The app-owned configuration is deliberately a sibling of harness directories such as
    // ~/.claude and ~/.codex. Older platform/XDG paths remain readable until the user creates the
    // new file, so an upgrade cannot silently discard working configuration.
    if app_path.exists() {
        return app_path;
    }
    legacy_paths
        .iter()
        .find(|path| path.exists())
        .cloned()
        .unwrap_or(app_path)
}

fn default_db_path() -> PathBuf {
    let home = home_dir_fallback();
    let platform = dirs::data_local_dir()
        .unwrap_or_else(|| home.join(".local/share"))
        .join("ai-session-search/index.db");
    let legacy = home.join(".local/share/ai-session-search/index.db");
    choose_default_state_path(platform, legacy)
}

fn default_cache_dir() -> PathBuf {
    let home = home_dir_fallback();
    let platform = dirs::cache_dir()
        .unwrap_or_else(|| home.join(".cache"))
        .join("ai-session-search");
    let legacy = home.join(".cache/ai-session-search");
    choose_default_state_path(platform, legacy)
}

fn choose_default_state_path(platform_path: PathBuf, legacy_path: PathBuf) -> PathBuf {
    // A legacy path wins whenever it exists. In particular, do not let an empty or partial
    // platform destination created by a failed cutover hide the user's working legacy index.
    // A completed migration writes an explicit index.db_path, which bypasses this default.
    if legacy_path.exists() {
        legacy_path
    } else {
        platform_path
    }
}

fn expand_override_path(path: PathBuf) -> PathBuf {
    path.to_str().map_or_else(
        || path.clone(),
        |value| {
            if value == "~" || value.starts_with("~/") {
                expand_tilde(value)
            } else {
                path.clone()
            }
        },
    )
}

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

    const TEST_BUSY_TIMEOUT_MS: u64 = 250;
    const TEST_AUTO_REINDEX_BUSY_TIMEOUT_MS: u64 = 10;
    const TEST_AUTO_REINDEX_INTERVAL_MS: u64 = 11;

    #[test]
    fn validate_rejects_every_zero_or_inverted_field_with_a_concrete_fix() {
        // Each condition, in isolation, must reject and name a concrete recovery action —
        // not just restate the constraint. Regression-lock for validate()'s bail! messages.
        type BreakField = fn(&mut Config);
        let cases: &[(BreakField, &str)] = &[
            (
                |c| c.release_notifications.minimum_check_interval_hours = 0,
                "release_notifications.minimum_check_interval_hours must be 1 or greater, got 0",
            ),
            (
                |c| c.release_notifications.request_timeout_ms = 0,
                "release_notifications.request_timeout_ms must be 1 or greater, got 0",
            ),
            (
                |c| c.search.default_limit = 0,
                "search.default_limit must be greater than zero",
            ),
            (
                |c| c.ui.preview_body_lines = 0,
                "ui.preview_body_lines must be greater than zero",
            ),
            (
                |c| c.ui.idle_poll_interval_ms = 0,
                "ui.idle_poll_interval_ms must be greater than zero",
            ),
            (
                |c| c.ui.list_page_rows = 0,
                "ui.list_page_rows must be greater than zero",
            ),
            (
                |c| c.ui.preview_scroll_rows = 0,
                "ui.preview_scroll_rows must be greater than zero",
            ),
            (
                |c| c.ui.preview_page_rows = 0,
                "ui.preview_page_rows must be greater than zero",
            ),
            (
                |c| c.ui.provider_label_width = 0,
                "ui.provider_label_width must be greater than zero",
            ),
            (
                |c| c.ui.list_pane_percent = 100,
                "ui.list_pane_percent must be between 10 and 90 inclusive",
            ),
            (
                |c| c.mcp.search_messages_limit = 0,
                "mcp.search_messages_limit must be greater than zero",
            ),
            (
                |c| c.mcp.preview_chars = 0,
                "mcp.preview_chars must be greater than zero",
            ),
            (
                |c| c.cli.evidence_preview_chars = 0,
                "cli.evidence_preview_chars must be greater than zero",
            ),
            (
                |c| c.analytics.repeat_min_matches = 0,
                "analytics.repeat_min_matches must be greater than zero",
            ),
            (
                |c| c.analytics.repeat_phrase_min_words = 0,
                "analytics.repeat_phrase_min_words must be greater than zero",
            ),
            (
                |c| c.analytics.repeat_phrase_max_words = c.analytics.repeat_phrase_min_words - 1,
                "analytics.repeat_phrase_max_words must be >= repeat_phrase_min_words",
            ),
        ];
        for (break_field, expected_prefix) in cases {
            let mut config = Config::default();
            break_field(&mut config);
            let error = config.validate().unwrap_err().to_string();
            assert!(error.starts_with(expected_prefix), "{error}");
            assert!(
                error.contains("aise config example") && error.contains("replaces the entire file"),
                "missing non-destructive recovery guidance: {error}"
            );
        }
        assert!(Config::default().validate().is_ok());
    }

    #[test]
    fn scoring_defaults_match_shipped_weights() {
        // The defaults must equal the ranker's original hard-coded weights so a config
        // without a [search.scoring] table leaves ranking unchanged.
        let s = ScoringConfig::default();
        assert_eq!(s.title_score, 600);
        assert_eq!(s.summary_score, 450);
        assert_eq!(s.path_score, 350);
        assert_eq!(s.preview_score, 250);
        assert_eq!(s.other_score, 100);
        assert_eq!(s.token_bonus, 40);
        assert_eq!(s.all_tokens_bonus, 150);
        assert_eq!(s.recency_weight, 2);
        assert_eq!(s.recency_max_days, 90);
        assert_eq!(s.current_repo_bonus, 200);
    }

    #[test]
    fn partial_scoring_toml_overrides_one_field_and_keeps_other_defaults() {
        // Overriding a single weight must not reset the rest — minimal-config friendliness.
        let toml = "[search.scoring]\ntitle_score = 999\n";
        let cfg: Config = toml::from_str(toml).unwrap();
        assert_eq!(cfg.search.scoring.title_score, 999);
        assert_eq!(
            cfg.search.scoring.summary_score, 450,
            "untouched weight keeps its default"
        );
        // Sibling settings still take their defaults.
        assert!(cfg.search.prefer_current_repo);
        assert_eq!(cfg.search.default_limit, 50);
    }

    #[test]
    fn message_search_panels_preserve_current_behavior_when_omitted() {
        let cfg: Config = toml::from_str("").unwrap();
        assert_eq!(cfg.search.message_search.default_limit, None);
        assert_eq!(cfg.search.message_search.context.context_before, None);
        assert_eq!(cfg.search.message_search.context.context_after, None);
        assert!(cfg.search.budgets.max_hits_per_page.is_none());
        assert!(cfg.search.budgets.max_context_neighbors_per_hit.is_none());
        assert_eq!(cfg.search.scope.mode, SearchScopeMode::All);
        assert!(cfg.search.scope.roots.is_empty());
        assert!(!cfg.search.scope.include_invocation_directory);
        assert!(cfg.search.purposes.is_empty());
    }

    #[test]
    fn message_search_panels_parse_typed_values_and_purpose_preferences() {
        let roots = tempfile::tempdir().unwrap();
        let root_a = roots.path().join("a");
        let root_b = roots.path().join("b");
        let source = format!(
            r#"
            [search.message-search]
            default_limit = 25
            match_evidence_max_chars = 120

            [search.message-search.context]
            context_before = 2
            context_after = 3

            [search.budgets]
            max_hits_per_page = 100
            max_context_neighbors_per_hit = 8

            [search.scope]
            mode = "allowed-roots"
            roots = [{root_a:?}, {root_b:?}]
            include_invocation_directory = true

            [search.purposes.historical-audit]
            version = 1
            operation = "message-search"

            [search.purposes.historical-audit.preferences]
            default_limit = 40
            context_before = 1
            context_after = 4
            receipt_level = "summary"
            include_refs = true
            lines_per_message = -8
            match_evidence_max_chars = 90
            "#
        );
        let cfg: Config = toml::from_str(&source).unwrap();
        cfg.validate().unwrap();
        assert_eq!(
            cfg.search
                .message_search
                .default_limit
                .map(NonZeroUsize::get),
            Some(25)
        );
        assert_eq!(cfg.search.message_search.context.context_before, Some(2));
        assert_eq!(cfg.search.message_search.context.context_after, Some(3));
        assert_eq!(
            cfg.search
                .message_search
                .match_evidence_max_chars
                .map(NonZeroUsize::get),
            Some(120)
        );
        assert_eq!(cfg.search.scope.mode, SearchScopeMode::AllowedRoots);
        assert_eq!(cfg.search.scope.roots.len(), 2);
        let purpose = &cfg.search.purposes["historical-audit"];
        assert_eq!(purpose.version.get(), 1);
        assert_eq!(purpose.operation, SearchOperation::MessageSearch);
        assert_eq!(
            purpose.preferences.receipt_level,
            Some(crate::message_search::ReceiptLevel::Summary)
        );
        assert_eq!(purpose.preferences.lines_per_message, Some(-8));
        assert_eq!(
            purpose
                .preferences
                .match_evidence_max_chars
                .map(NonZeroUsize::get),
            Some(90)
        );
    }

    #[test]
    fn message_search_panels_reject_zero_unknown_and_conflicting_values() {
        for toml in [
            "[search.message-search]\ndefault_limit = 0\n",
            "[search.message-search]\nmatch_evidence_max_chars = 0\n",
            "[search.budgets]\nmax_context_neighbors_per_hit = 0\n",
            "[search.message-search.context]\nmessages_before = 2\n",
            "[search.message-search.context]\nmessages_after = 2\n",
            "[search.budgets]\nmax_results_per_page = 10\n",
            "[search.budgets]\nmax_context_messages = 10\n",
            "[search.budgets]\ntimeout_ms = 5000\n",
            "[search.purposes.audit]\nversion = 0\noperation = \"message-search\"\n",
        ] {
            assert!(toml::from_str::<Config>(toml).is_err(), "{toml}");
        }
        let unknown = toml::from_str::<Config>(
            "[search.purposes.audit]\nversion = 1\noperation = \"message-search\"\n\
             [search.purposes.audit.preferences]\nquery_mode = \"regex\"\n",
        )
        .unwrap_err()
        .to_string();
        assert!(unknown.contains("unknown field"), "{unknown}");

        let mut cfg: Config =
            toml::from_str("[search.scope]\nmode = \"all\"\nroots = [\"/workspace\"]\n").unwrap();
        assert!(cfg
            .validate()
            .unwrap_err()
            .to_string()
            .contains("allowed-roots"));

        cfg.search.scope = SearchScopeConfig::default();
        cfg.search.message_search.context.context_before = Some(3);
        cfg.search.message_search.context.context_after = Some(4);
        cfg.search.budgets.max_context_neighbors_per_hit = NonZeroUsize::new(6);
        assert!(cfg
            .validate()
            .unwrap_err()
            .to_string()
            .contains("max_context_neighbors_per_hit"));

        cfg.search.message_search.context = MessageContextDefaults::default();
        cfg.search.budgets.max_context_neighbors_per_hit = None;
        cfg.search.purposes.insert(
            "hard2parse".into(),
            PurposeDefinition {
                version: NonZeroU32::new(1).unwrap(),
                operation: SearchOperation::MessageSearch,
                preferences: MessagePurposePreferences::default(),
            },
        );
        assert!(cfg
            .validate()
            .unwrap_err()
            .to_string()
            .contains("dash-separated phrase"));
    }

    #[test]
    fn scoring_config_rejects_negative_recency_range() {
        let config = toml::from_str::<Config>("[search.scoring]\nrecency_max_days = -1\n").unwrap();
        let error = config.validate().unwrap_err().to_string();
        assert!(error.contains("search.scoring.recency_max_days"), "{error}");
        assert!(error.contains("0 or greater"), "{error}");
    }

    #[test]
    fn configured_message_defaults_must_fit_their_explicit_policy_budget() {
        let maximum = NonZeroUsize::new(10).unwrap();

        let mut operation = Config::default();
        operation.search.budgets.max_hits_per_page = Some(maximum);
        operation.search.message_search.default_limit = NonZeroUsize::new(11);
        let error = operation.validate().unwrap_err().to_string();
        assert!(
            error.contains("search.message-search.default_limit"),
            "{error}"
        );

        let mut surface = Config::default();
        surface.search.budgets.max_hits_per_page = Some(maximum);
        surface.mcp.search_messages_limit = 11;
        let error = surface.validate().unwrap_err().to_string();
        assert!(error.contains("mcp.search_messages_limit"), "{error}");

        let mut purpose = Config::default();
        purpose.search.budgets.max_hits_per_page = Some(maximum);
        purpose.mcp.search_messages_limit = maximum.get();
        purpose.search.purposes.insert(
            "focused-review".into(),
            PurposeDefinition {
                version: NonZeroU32::new(1).unwrap(),
                operation: SearchOperation::MessageSearch,
                preferences: MessagePurposePreferences {
                    default_limit: NonZeroUsize::new(11),
                    ..Default::default()
                },
            },
        );
        let error = purpose.validate().unwrap_err().to_string();
        assert!(
            error.contains("search.purposes.focused-review.default_limit"),
            "{error}"
        );
    }

    #[test]
    fn allowed_roots_configuration_rejects_relative_root_and_file_paths() {
        for root in ["relative/project", "/"] {
            let mut cfg = Config::default();
            cfg.search.scope = SearchScopeConfig {
                mode: SearchScopeMode::AllowedRoots,
                roots: vec![root.into()],
                include_invocation_directory: false,
            };
            let error = cfg.validate().unwrap_err().to_string();
            assert!(error.contains("search.scope.roots entry"), "{error}");
        }

        let directory = tempfile::tempdir().unwrap();
        let file = directory.path().join("not-a-directory");
        std::fs::write(&file, b"fixture").unwrap();
        let mut cfg = Config::default();
        cfg.search.scope = SearchScopeConfig {
            mode: SearchScopeMode::AllowedRoots,
            roots: vec![file.to_string_lossy().into_owned()],
            include_invocation_directory: false,
        };
        let error = cfg.validate().unwrap_err().to_string();
        assert!(error.contains("not a directory"), "{error}");
    }

    #[test]
    fn claude_desktop_provider_has_separate_hyphenated_config_table() {
        let cfg: Config = toml::from_str(
            r#"
            [providers.claude]
            paths = ["/tmp/claude-code"]

            [providers.claude-desktop]
            paths = ["/tmp/claude-desktop"]
            "#,
        )
        .unwrap();
        assert_eq!(cfg.providers.claude.paths, vec!["/tmp/claude-code"]);
        assert_eq!(
            cfg.providers.claude_desktop.paths,
            vec!["/tmp/claude-desktop"]
        );
    }

    #[test]
    fn claude_desktop_default_paths_are_deduplicated_candidates() {
        let paths = default_claude_desktop_paths();
        let unique: std::collections::HashSet<_> = paths.iter().collect();
        assert_eq!(
            unique.len(),
            paths.len(),
            "defaults should not duplicate roots"
        );
        assert!(
            paths
                .iter()
                .all(|path| path.ends_with("Claude/local-agent-mode-sessions")
                    || path.ends_with("claude/local-agent-mode-sessions")),
            "all candidates point at Claude Desktop local agent session roots: {paths:?}"
        );
    }

    #[test]
    fn antigravity_default_paths_include_cli_and_legacy_brain_roots() {
        let cfg = Config::default();
        let paths = &cfg.providers.antigravity.paths;
        let unique: std::collections::HashSet<_> = paths.iter().collect();
        assert_eq!(
            unique.len(),
            paths.len(),
            "defaults should not duplicate roots"
        );
        assert!(
            paths
                .iter()
                .any(|path| path.ends_with(".gemini/antigravity-cli/brain")),
            "Antigravity CLI writes transcripts under ~/.gemini/antigravity-cli/brain: {paths:?}"
        );
        assert!(
            paths
                .iter()
                .any(|path| path.ends_with(".gemini/antigravity/brain")),
            "keep legacy Antigravity brain root for existing users: {paths:?}"
        );
    }

    #[test]
    fn performance_threads_parses_and_defaults_to_auto() {
        // Absent [performance] → threads = 0 (auto-detect).
        let cfg: Config = toml::from_str("").unwrap();
        assert_eq!(cfg.performance.threads, 0);
        // Explicit override parses.
        let cfg: Config = toml::from_str("[performance]\nthreads = 4\n").unwrap();
        assert_eq!(cfg.performance.threads, 4);
    }

    #[test]
    fn performance_rejects_removed_custom_trigram_tuning() {
        for key in ["regex_prefilter_min_corpus", "trigram_rebuild_delta"] {
            let error = toml::from_str::<Config>(&format!("[performance]\n{key} = 10000\n"))
                .unwrap_err()
                .to_string();
            assert!(error.contains("unknown field"), "{key}: {error}");
        }
    }

    #[test]
    fn index_busy_timeout_parses_and_defaults() {
        let cfg: Config = toml::from_str("").unwrap();
        assert_eq!(
            cfg.index.busy_timeout_ms,
            crate::db::DEFAULT_BUSY_TIMEOUT_MS
        );
        assert_eq!(
            cfg.index.auto_reindex_busy_timeout_ms,
            crate::db::DEFAULT_AUTO_REINDEX_BUSY_TIMEOUT_MS
        );
        assert_eq!(
            cfg.index.auto_reindex_interval_ms,
            crate::db::DEFAULT_AUTO_REINDEX_INTERVAL_MS
        );

        let cfg: Config = toml::from_str(&format!(
            "[index]\nbusy_timeout_ms = {TEST_BUSY_TIMEOUT_MS}\nauto_reindex_busy_timeout_ms = {TEST_AUTO_REINDEX_BUSY_TIMEOUT_MS}\nauto_reindex_interval_ms = {TEST_AUTO_REINDEX_INTERVAL_MS}\n"
        ))
        .unwrap();
        assert_eq!(cfg.index.busy_timeout_ms, TEST_BUSY_TIMEOUT_MS);
        assert_eq!(
            cfg.index.auto_reindex_busy_timeout_ms,
            TEST_AUTO_REINDEX_BUSY_TIMEOUT_MS
        );
        assert_eq!(
            cfg.index.auto_reindex_interval_ms,
            TEST_AUTO_REINDEX_INTERVAL_MS
        );
    }

    #[test]
    fn mcp_defaults_parse_bounded_agent_pages_and_unbounded_sql_time() {
        let cfg: Config = toml::from_str("").unwrap();
        assert_eq!(cfg.mcp.max_concurrent_reads, McpReadConcurrency::Auto);
        assert_eq!(
            cfg.resolve_mcp_max_concurrent_reads().unwrap().get(),
            std::thread::available_parallelism()
                .unwrap_or(NonZeroUsize::MIN)
                .get()
                .div_ceil(2)
        );
        assert_eq!(
            cfg.mcp.search_sessions_limit,
            DEFAULT_MCP_SEARCH_SESSIONS_LIMIT
        );
        assert_eq!(cfg.mcp.list_sessions_limit, DEFAULT_MCP_LIST_SESSIONS_LIMIT);
        assert_eq!(
            cfg.mcp.search_messages_limit,
            DEFAULT_MCP_SEARCH_MESSAGES_LIMIT
        );
        assert_eq!(
            cfg.mcp.get_session_transcript_lines,
            DEFAULT_MCP_GET_SESSION_TRANSCRIPT_LINE_WINDOW
        );
        assert_eq!(cfg.mcp.preview_chars, DEFAULT_MCP_PREVIEW_CHARS);
        assert_eq!(
            cfg.mcp.max_tool_result_chars,
            DEFAULT_MCP_MAX_TOOL_RESULT_CHARS
        );
        assert_eq!(cfg.mcp.summary_items, DEFAULT_MCP_SUMMARY_ITEMS);
        assert_eq!(
            cfg.mcp.query_max_cell_chars,
            DEFAULT_MCP_QUERY_MAX_CELL_CHARS
        );
        assert_eq!(cfg.mcp.query_timeout_ms, 0);
        assert_eq!(
            cfg.mcp.internal.schema_summary_tables,
            DEFAULT_MCP_INTERNAL_SCHEMA_SUMMARY_TABLES
        );
        assert_eq!(
            cfg.mcp.internal.schema_summary_columns,
            DEFAULT_MCP_INTERNAL_SCHEMA_SUMMARY_COLUMNS
        );

        let cfg: Config = toml::from_str(
            r#"
            [mcp]
            max_concurrent_reads = "auto"
            search_sessions_limit = 7
            list_sessions_limit = 8
            search_messages_limit = 9
            get_session_transcript_lines = -12
            preview_chars = 77
            query_max_cell_chars = 13
            query_timeout_ms = 2500

            [mcp.internal]
            schema_summary_tables = 2
            schema_summary_columns = 3
            "#,
        )
        .unwrap();
        assert_eq!(cfg.mcp.max_concurrent_reads, McpReadConcurrency::Auto);
        assert_eq!(
            cfg.resolve_mcp_max_concurrent_reads().unwrap().get(),
            std::thread::available_parallelism()
                .unwrap_or(NonZeroUsize::MIN)
                .get()
                .div_ceil(2)
        );
        let host: Config = toml::from_str("[mcp]\nmax_concurrent_reads = \"host\"\n").unwrap();
        assert_eq!(host.mcp.max_concurrent_reads, McpReadConcurrency::Host);
        assert_eq!(
            host.resolve_mcp_max_concurrent_reads().unwrap(),
            std::thread::available_parallelism().unwrap_or(NonZeroUsize::MIN)
        );
        assert_eq!(cfg.mcp.search_sessions_limit, 7);
        assert_eq!(cfg.mcp.list_sessions_limit, 8);
        assert_eq!(cfg.mcp.search_messages_limit, 9);
        assert_eq!(cfg.mcp.get_session_transcript_lines, -12);
        assert_eq!(cfg.mcp.preview_chars, 77);
        assert_eq!(cfg.mcp.query_max_cell_chars, 13);
        assert_eq!(cfg.mcp.query_timeout_ms, 2500);
        assert_eq!(cfg.mcp.internal.schema_summary_tables, 2);
        assert_eq!(cfg.mcp.internal.schema_summary_columns, 3);

        let cfg: Config = toml::from_str("[mcp]\nmax_concurrent_reads = 2\n").unwrap();
        assert_eq!(
            cfg.mcp.max_concurrent_reads,
            McpReadConcurrency::Fixed(NonZeroUsize::new(2).unwrap())
        );
        assert_eq!(cfg.resolve_mcp_max_concurrent_reads().unwrap().get(), 2);
        let maximum = tokio::sync::Semaphore::MAX_PERMITS;
        let cfg: Config =
            toml::from_str(&format!("[mcp]\nmax_concurrent_reads = {maximum}\n")).unwrap();
        assert_eq!(
            cfg.resolve_mcp_max_concurrent_reads().unwrap().get(),
            maximum
        );

        for (invalid, expected) in [("0", "got 0"), ("-2", "got -2"), ("\"all\"", "got \"all\"")] {
            let error =
                toml::from_str::<Config>(&format!("[mcp]\nmax_concurrent_reads = {invalid}\n"))
                    .unwrap_err()
                    .to_string();
            assert!(
                error.contains(&format!(
                    "must be \"auto\", \"host\", or an integer from 1 through {}",
                    tokio::sync::Semaphore::MAX_PERMITS
                )),
                "{error}"
            );
            assert!(error.contains(expected), "{error}");
            assert!(
                error.contains("use \"auto\" for the balanced default"),
                "{error}"
            );
        }

        if let Some(too_many) = maximum.checked_add(1) {
            let error =
                toml::from_str::<Config>(&format!("[mcp]\nmax_concurrent_reads = {too_many}\n"))
                    .unwrap_err()
                    .to_string();
            assert!(
                error.contains(&format!(
                    "must be \"auto\", \"host\", or an integer from 1 through {maximum}"
                )),
                "{error}"
            );
            assert!(error.contains(&format!("got {too_many}")), "{error}");
        }
    }

    #[test]
    fn cli_defaults_parse_and_default_to_bounded_show() {
        let cfg: Config = toml::from_str("").unwrap();
        assert_eq!(
            cfg.cli.show_transcript_lines,
            DEFAULT_CLI_SHOW_TRANSCRIPT_LINE_WINDOW
        );
        assert_eq!(cfg.cli.lines_per_message, DEFAULT_MESSAGE_LINE_WINDOW);
        assert_eq!(cfg.mcp.lines_per_message, DEFAULT_MESSAGE_LINE_WINDOW);
        assert_eq!(
            cfg.cli.evidence_preview_chars,
            DEFAULT_CLI_EVIDENCE_PREVIEW_CHARS
        );
        assert_eq!(cfg.cli.summary_items, DEFAULT_CLI_SUMMARY_ITEMS);

        let cfg: Config = toml::from_str(
            r#"
            [mcp]
            lines_per_message = -6

            [cli]
            show_transcript_lines = -12
            lines_per_message = 8
            evidence_preview_chars = 88
            "#,
        )
        .unwrap();
        assert_eq!(cfg.cli.show_transcript_lines, -12);
        assert_eq!(cfg.cli.lines_per_message, 8);
        assert_eq!(cfg.mcp.lines_per_message, -6);
        assert_eq!(cfg.cli.evidence_preview_chars, 88);
    }

    #[test]
    fn analytics_defaults_parse_for_user_facing_scan_controls() {
        let cfg: Config = toml::from_str("").unwrap();
        assert_eq!(cfg.analytics.vocab_limit, DEFAULT_ANALYTICS_VOCAB_LIMIT);
        assert_eq!(
            cfg.analytics.repeat_max_groups,
            DEFAULT_ANALYTICS_REPEAT_MAX_GROUPS
        );
        assert_eq!(
            cfg.analytics.repeat_max_examples_per_group,
            DEFAULT_ANALYTICS_REPEAT_MAX_EXAMPLES_PER_GROUP
        );
        assert_eq!(
            cfg.analytics.repeat_min_matches,
            DEFAULT_ANALYTICS_REPEAT_MIN_MATCHES
        );
        assert_eq!(
            cfg.analytics.repeat_phrase_min_words,
            DEFAULT_ANALYTICS_REPEAT_PHRASE_MIN_WORDS
        );
        assert_eq!(
            cfg.analytics.repeat_phrase_max_words,
            DEFAULT_ANALYTICS_REPEAT_PHRASE_MAX_WORDS
        );

        let cfg: Config = toml::from_str(
            r#"
            [analytics]
            vocab_limit = 17
            repeat_max_groups = 18
            repeat_max_examples_per_group = 7
            repeat_min_matches = 3
            repeat_phrase_min_words = 4
            repeat_phrase_max_words = 9
            "#,
        )
        .unwrap();
        assert_eq!(cfg.analytics.vocab_limit, 17);
        assert_eq!(cfg.analytics.repeat_max_groups, 18);
        assert_eq!(cfg.analytics.repeat_max_examples_per_group, 7);
        assert_eq!(cfg.analytics.repeat_min_matches, 3);
        assert_eq!(cfg.analytics.repeat_phrase_min_words, 4);
        assert_eq!(cfg.analytics.repeat_phrase_max_words, 9);
    }

    #[test]
    fn mcp_config_rejects_noncanonical_field_names() {
        for config in [
            "[mcp]\nmessage_search_limit = 11\n",
            "[mcp]\nschema_summary_tables = 12\n",
            "[mcp]\nschema_summary_columns = 13\n",
            "[search.budgets]\nmax_response_bytes = 1024\n",
            "[mcp]\nmax_response_bytes = 1024\n",
        ] {
            assert!(toml::from_str::<Config>(config).is_err());
        }
    }

    #[test]
    fn native_db_query_defaults_parse_and_default_to_unbounded_execution_time() {
        let cfg: Config = toml::from_str("").unwrap();
        assert_eq!(cfg.db.query_limit, DEFAULT_DB_QUERY_LIMIT);
        assert_eq!(cfg.db.query_timeout_ms, 0);
        assert!(cfg.release_notifications.enabled);
        assert_eq!(
            cfg.release_notifications.minimum_check_interval_hours,
            DEFAULT_RELEASE_NOTIFICATION_MINIMUM_CHECK_INTERVAL_HOURS
        );
        assert_eq!(
            cfg.release_notifications.request_timeout_ms,
            DEFAULT_RELEASE_NOTIFICATION_REQUEST_TIMEOUT_MS
        );

        let cfg: Config = toml::from_str(
            r#"
            [db]
            query_limit = 17
            query_timeout_ms = 2500
            "#,
        )
        .unwrap();
        assert_eq!(cfg.db.query_limit, 17);
        assert_eq!(cfg.db.query_timeout_ms, 2500);
    }

    #[test]
    fn release_notification_names_are_exact_and_old_update_names_are_rejected() {
        let cfg: Config = toml::from_str(
            r#"
            [release_notifications]
            enabled = false
            minimum_check_interval_hours = 12
            request_timeout_ms = 750
            "#,
        )
        .unwrap();
        assert!(!cfg.release_notifications.enabled);
        assert_eq!(cfg.release_notifications.minimum_check_interval_hours, 12);
        assert_eq!(cfg.release_notifications.request_timeout_ms, 750);

        for stale_config in [
            "[release_updates]\npassive_check = false\n",
            "[release_notifications]\npassive_check = false\n",
            "[release_notifications]\npassive_check_interval_hours = 12\n",
            "[release_notifications]\npassive_request_timeout_ms = 750\n",
        ] {
            assert!(
                toml::from_str::<Config>(stale_config).is_err(),
                "stale release-notification name unexpectedly parsed: {stale_config}"
            );
        }
    }

    #[test]
    fn planning_keeps_its_bounded_analytics_default() {
        let cfg = Config::default();
        assert_eq!(cfg.analytics.planning_limit, DEFAULT_ANALYTICS_VOCAB_LIMIT);
        let overridden: Config = toml::from_str("[analytics]\nplanning_limit = 9\n").unwrap();
        assert_eq!(overridden.analytics.planning_limit, 9);
    }

    #[test]
    fn skills_section_rejects_unknown_keys() {
        // deny_unknown_fields: a typo must be named, not silently ignored, or a user who wrote
        // `search_path` would get the embedded default and no indication why.
        let err = toml::from_str::<Config>("[skills]\nsearch_path = []\n")
            .expect_err("a misspelled key must be rejected")
            .to_string();
        assert!(err.contains("search_path"), "{err}");
    }

    #[test]
    fn message_classification_defaults_have_capability_and_mcp_specific_names() {
        let configured: Config = toml::from_str(
            "[capabilities.message_classification]\nlimit = 7\n\
             [mcp]\nrun_message_classification_limit = 11\n",
        )
        .unwrap();
        assert_eq!(configured.capabilities.message_classification.limit, 7);
        assert_eq!(configured.mcp.run_message_classification_limit, 11);

        let zero: Config = toml::from_str("[mcp]\nrun_message_classification_limit = 0\n").unwrap();
        let error = zero
            .validate()
            .expect_err("a zero MCP page cannot make pagination progress")
            .to_string();
        assert!(
            error.contains("mcp.run_message_classification_limit")
                && error.contains("1 or greater")
                && error.contains("got 0"),
            "{error}"
        );

        for removed in [
            "[analytics]\ncorrections_limit = 7\n",
            "[mcp]\nfind_corrections_limit = 11\n",
            "[skills]\nenabled = [\"mine\"]\n",
        ] {
            assert!(
                toml::from_str::<Config>(removed).is_err(),
                "removed prerelease correction settings must fail instead of being ignored"
            );
        }
    }

    #[test]
    fn typed_defaults_and_serde_defaults_agree_for_every_section() {
        // Every default has two authorities: the value `Config::default()` writes, and the
        // `default_*` function serde calls when a present section omits the key. A file that
        // names each section and sets nothing must therefore reproduce `Config::default()`
        // exactly. Without this, `ui.idle_poll_interval_ms = 150` in one place and
        // `default_idle_poll_interval_ms() = 200` in the other would give a user with an empty
        // `[ui]` table different pacing than a user with no config file, and no test would fail.
        let every_section_present = "\
[providers]
[index]
[ui]
[search]
[analytics]
[skills]
[capabilities]
[performance]
[mcp]
[cli]
[db]
[release_notifications]
";
        let parsed: Config = toml::from_str(every_section_present)
            .expect("a file naming every section with no keys must parse");
        let from_file = serde_json::to_value(&parsed).unwrap();
        let typed = serde_json::to_value(Config::default()).unwrap();
        // Compare section by section so a drift names the one table that disagrees instead of
        // printing the whole resolved configuration twice.
        for (section, typed_value) in typed.as_object().expect("Config serializes as an object") {
            assert_eq!(
                from_file.get(section),
                Some(typed_value),
                "[{section}] present with no keys must resolve to the same values as no config file"
            );
        }
        assert_eq!(
            from_file.as_object().map(|table| table.len()),
            typed.as_object().map(|table| table.len()),
            "every serialized section must be covered by this file"
        );
    }

    #[test]
    fn the_shipped_example_sets_every_value_to_the_shipped_default() {
        // `aise config init` writes this file, so what it names is what a reader believes the
        // program does before they change anything. Every value in it is a literal duplicate of
        // a `default_*` function, and nothing had been comparing the two: the seven spot-checks
        // in `embedded_example_config_stays_parseable` below pass on a file whose other keys
        // have drifted, which is how ten new `[ui]` keys could arrive with their defaults
        // written out twice and no test looking at either copy.
        let from_example = serde_json::to_value(
            toml::from_str::<Config>(CONFIG_EXAMPLE_TOML).expect("the shipped example parses"),
        )
        .unwrap();
        let typed = serde_json::to_value(Config::default()).unwrap();
        // Section by section, so a drift names the one table that disagrees rather than
        // printing the whole resolved configuration twice.
        for (section, typed_value) in typed.as_object().expect("Config serializes as an object") {
            assert_eq!(
                from_example.get(section),
                Some(typed_value),
                "[{section}] in config.example.toml no longer matches its typed default"
            );
        }
    }

    #[test]
    fn the_shipped_example_names_every_configuration_key() {
        // Comparing values cannot see a key the example never mentions: it parses to its typed
        // default and compares equal. Deleting `list_pane_percent = 45` leaves
        // `the_shipped_example_sets_every_value_to_the_shipped_default` green, so that test alone
        // would let a new setting ship with nothing documenting that it exists.
        fn leaf_keys(value: &serde_json::Value, into: &mut Vec<String>) {
            if let Some(table) = value.as_object() {
                for (key, nested) in table {
                    match nested.as_object() {
                        // An empty table has no leaves of its own, so the table name is what the
                        // example has to carry; `[search.purposes]` is the case that matters.
                        Some(inner) if !inner.is_empty() => leaf_keys(nested, into),
                        _ => into.push(key.clone()),
                    }
                }
            }
        }
        let mut keys = Vec::new();
        leaf_keys(&serde_json::to_value(Config::default()).unwrap(), &mut keys);
        assert!(keys.len() > 40, "the walk found only {} keys", keys.len());

        let missing: Vec<&String> = keys
            .iter()
            .filter(|key| {
                !CONFIG_EXAMPLE_TOML.lines().any(|line| {
                    let body = line.trim_start().trim_start_matches('#').trim_start();
                    // A table whose own contents are a user's choice of names, such as
                    // `[search.purposes.<name>]`, is documented by its header rather than by an
                    // assignment.
                    if let Some(header) = body.strip_prefix('[').and_then(|r| r.split(']').next()) {
                        return header.split('.').any(|segment| segment == key.as_str());
                    }
                    // Live or commented: many optional keys are documented as `# key = <type>`.
                    body.strip_prefix(key.as_str())
                        .is_some_and(|rest| rest.trim_start().starts_with('='))
                })
            })
            .collect();
        assert!(
            missing.is_empty(),
            "config.example.toml never names these settings, so `aise config example` does not \
             tell a reader they exist: {missing:?}"
        );
    }

    #[test]
    fn the_example_key_table_lists_every_action_with_its_shipped_chords() {
        // The `[ui.keys]` block is commented out, so `toml::from_str` above never reads it and
        // the test that does read the example cannot see it drift. It is also the block a reader
        // copies to rebind a key, so a stale line there is a wrong instruction rather than an
        // unused one. Uncomment it here and compare against the shipped bindings.
        let mut listed: BTreeMap<crate::keymap::TuiAction, Vec<crate::keymap::KeyChord>> =
            BTreeMap::new();
        let mut lines = CONFIG_EXAMPLE_TOML
            .lines()
            .skip_while(|line| line.trim() != "# [ui.keys]");
        assert!(
            lines.next().is_some(),
            "config.example.toml lost # [ui.keys]"
        );
        for line in lines {
            // Every line of the block is commented, the bare `#` separating its two halves
            // included, so the first uncommented line is the end of it. Reading past that point
            // reaches the provider prose, where "explicit `paths = []` means search no roots"
            // parses as an assignment if the scan is any looser than this.
            let Some(body) = line.strip_prefix('#') else {
                break;
            };
            let body = body.trim_start();
            // The next commented table header would also end it.
            if body.starts_with('[') {
                break;
            }
            let Some((name, chords)) = body.split_once(" = ") else {
                continue;
            };
            // An action name, not prose that happens to contain ` = `.
            if !name
                .chars()
                .all(|character| character.is_ascii_lowercase() || character == '_')
                || !chords.starts_with('[')
            {
                continue;
            }
            let entry: BTreeMap<crate::keymap::TuiAction, Vec<crate::keymap::KeyChord>> =
                toml::from_str(&format!("{name} = {chords}")).unwrap_or_else(|error| {
                    panic!("config.example.toml documents an unusable binding {body:?}: {error}")
                });
            listed.extend(entry);
        }

        let shipped = KeyBindings::default();
        let expected: BTreeMap<crate::keymap::TuiAction, Vec<crate::keymap::KeyChord>> =
            crate::keymap::TuiAction::ALL
                .into_iter()
                .map(|action| (action, shipped.chords(action).to_vec()))
                .collect();
        assert_eq!(
            listed, expected,
            "the commented [ui.keys] block must name every action with the keys it actually ships"
        );
    }

    #[test]
    fn embedded_example_config_stays_parseable() {
        let cfg: Config = toml::from_str(CONFIG_EXAMPLE_TOML).unwrap();
        assert_eq!(
            cfg.mcp.search_messages_limit,
            DEFAULT_MCP_SEARCH_MESSAGES_LIMIT
        );
        assert_eq!(cfg.mcp.preview_chars, DEFAULT_MCP_PREVIEW_CHARS);
        assert_eq!(
            cfg.cli.evidence_preview_chars,
            DEFAULT_CLI_EVIDENCE_PREVIEW_CHARS
        );
        assert_eq!(cfg.analytics.vocab_limit, DEFAULT_ANALYTICS_VOCAB_LIMIT);
        assert_eq!(
            cfg.analytics.repeat_max_groups,
            DEFAULT_ANALYTICS_REPEAT_MAX_GROUPS
        );
        assert_eq!(cfg.db.query_timeout_ms, DEFAULT_DB_QUERY_TIMEOUT_MS);
        assert_eq!(
            cfg.mcp.internal.schema_summary_tables,
            DEFAULT_MCP_INTERNAL_SCHEMA_SUMMARY_TABLES
        );
        assert!(
            CONFIG_EXAMPLE_TOML.contains("An explicit `--limit 0` requests every matching session"),
            "the shipped example must not claim explicit zero uses search.default_limit"
        );
        assert!(!CONFIG_EXAMPLE_TOML.contains("omitted or set to 0"));
    }

    #[test]
    fn config_path_selection_prefers_sibling_app_root_and_preserves_legacy_fallbacks() {
        let dir = tempfile::tempdir().unwrap();
        let app = dir.path().join("home/.ai-session-search/config.toml");
        let platform_legacy = dir.path().join("platform/ai-session-search/config.toml");
        let xdg_legacy = dir
            .path()
            .join("home/.config/ai-session-search/config.toml");

        assert_eq!(
            choose_config_path(
                None,
                app.clone(),
                &[platform_legacy.clone(), xdg_legacy.clone()]
            ),
            app,
            "new installs use the app-owned sibling directory"
        );

        fs::create_dir_all(xdg_legacy.parent().unwrap()).unwrap();
        fs::write(&xdg_legacy, "").unwrap();
        assert_eq!(
            choose_config_path(
                None,
                app.clone(),
                &[platform_legacy.clone(), xdg_legacy.clone()]
            ),
            xdg_legacy,
            "an existing XDG config remains active until the app config exists"
        );

        fs::create_dir_all(platform_legacy.parent().unwrap()).unwrap();
        fs::write(&platform_legacy, "").unwrap();
        assert_eq!(
            choose_config_path(None, app.clone(), &[platform_legacy.clone(), xdg_legacy]),
            platform_legacy,
            "the first existing legacy location has deterministic precedence"
        );

        fs::create_dir_all(app.parent().unwrap()).unwrap();
        fs::write(&app, "").unwrap();
        assert_eq!(
            choose_config_path(None, app.clone(), &[platform_legacy]),
            app,
            "the sibling app config wins once explicitly created"
        );
    }

    #[test]
    fn explicit_config_path_override_has_highest_precedence() {
        let override_path = PathBuf::from("/portable/config.toml");
        assert_eq!(
            choose_config_path(
                Some(override_path.clone()),
                PathBuf::from("/home/.ai-session-search/config.toml"),
                &[PathBuf::from("/legacy/config.toml")],
            ),
            override_path
        );
    }

    #[test]
    fn resolve_wraps_a_validation_failure_with_the_offending_config_file_path() {
        let dir = tempfile::tempdir().unwrap();
        let config_path = dir.path().join("config.toml");
        fs::write(&config_path, "[search]\ndefault_limit = 0\n").unwrap();
        let error = Config::resolve_with_environment(
            ConfigOverrides {
                config_path: Some(config_path.clone()),
                ..Default::default()
            },
            ConfigEnvironment::default(),
        )
        .unwrap_err();
        let chain = format!("{error:#}");
        assert!(
            chain.contains(&config_path.display().to_string()),
            "{chain}"
        );
        assert!(
            chain.contains("search.default_limit must be greater than zero"),
            "{chain}"
        );
    }

    #[test]
    fn cache_override_precedes_configured_and_default_paths() {
        let dir = tempfile::tempdir().unwrap();
        let config_path = dir.path().join("config.toml");
        fs::write(&config_path, "[index]\ncache_dir = '/configured/cache'\n").unwrap();
        let resolved = Config::resolve_with_environment(
            ConfigOverrides {
                config_path: Some(config_path),
                cache_dir: Some(PathBuf::from("/portable/cache")),
                ..Default::default()
            },
            ConfigEnvironment {
                cache_dir: Some(PathBuf::from("/environment/cache")),
                ..Default::default()
            },
        )
        .unwrap();
        assert_eq!(
            resolved.config.cache_dir(),
            PathBuf::from("/portable/cache")
        );
        assert_eq!(resolved.origins.cache, "cli --cache-dir");
    }

    /// The result ceiling resolves registration environment, then config file, then typed
    /// default, and reports which one it used at every step.
    ///
    /// The precedence is the point rather than the values: a shared config file states the
    /// deployment's policy and one harness's registration narrows it, so the narrower statement
    /// has to win or a per-harness override cannot exist. Each case asserts the origin as well
    /// as the number, because a value that is right by coincidence and a value that is right by
    /// resolution are indistinguishable from the number alone.
    #[test]
    fn the_result_ceiling_resolves_environment_then_config_then_typed_default() {
        let dir = tempfile::tempdir().unwrap();

        let bare = dir.path().join("bare.toml");
        fs::write(&bare, "").unwrap();
        let resolved = Config::resolve_with_environment(
            ConfigOverrides {
                config_path: Some(bare.clone()),
                ..Default::default()
            },
            ConfigEnvironment::default(),
        )
        .unwrap();
        assert_eq!(
            resolved.config.mcp.max_tool_result_chars,
            DEFAULT_MCP_MAX_TOOL_RESULT_CHARS
        );
        assert_eq!(resolved.origins.max_tool_result_chars, "typed default");
        assert_eq!(
            resolved.config.mcp.search_messages_limit,
            DEFAULT_MCP_SEARCH_MESSAGES_LIMIT
        );
        assert_eq!(resolved.origins.search_messages_limit, "typed default");

        let configured = dir.path().join("configured.toml");
        fs::write(
            &configured,
            "[mcp]\nmax_tool_result_chars = 24000\nsearch_messages_limit = 20\n",
        )
        .unwrap();
        let resolved = Config::resolve_with_environment(
            ConfigOverrides {
                config_path: Some(configured.clone()),
                ..Default::default()
            },
            ConfigEnvironment::default(),
        )
        .unwrap();
        assert_eq!(resolved.config.mcp.max_tool_result_chars, 24_000);
        assert_eq!(resolved.origins.max_tool_result_chars, "config file");
        assert_eq!(
            resolved.config.mcp.search_messages_limit, 20,
            "a page size the user wrote down stays what they wrote, whatever the typed default \
             later becomes"
        );
        assert_eq!(resolved.origins.search_messages_limit, "config file");

        let resolved = Config::resolve_with_environment(
            ConfigOverrides {
                config_path: Some(configured),
                ..Default::default()
            },
            ConfigEnvironment {
                max_tool_result_chars: Some("31000".to_string()),
                ..Default::default()
            },
        )
        .unwrap();
        assert_eq!(
            resolved.config.mcp.max_tool_result_chars, 31_000,
            "one harness's registration must be able to narrow a machine-wide config file"
        );
        assert_eq!(
            resolved.origins.max_tool_result_chars,
            "environment AI_SESSION_SEARCH_MAX_TOOL_RESULT_CHARS"
        );
    }

    /// An unusable ceiling is rejected, and the complaint names the variable and its range.
    #[test]
    fn an_unusable_result_ceiling_is_rejected_rather_than_ignored() {
        let dir = tempfile::tempdir().unwrap();
        let bare = dir.path().join("bare.toml");
        fs::write(&bare, "").unwrap();

        for unusable in ["0", "-1", "12.5", "lots", " ", "99999999999999999999999999"] {
            let error = Config::resolve_with_environment(
                ConfigOverrides {
                    config_path: Some(bare.clone()),
                    ..Default::default()
                },
                ConfigEnvironment {
                    max_tool_result_chars: Some(unusable.to_string()),
                    ..Default::default()
                },
            )
            .expect_err(&format!("{unusable:?} is not a usable result ceiling"));
            let complaint = format!("{error:#}");
            assert!(
                complaint.contains("AI_SESSION_SEARCH_MAX_TOOL_RESULT_CHARS"),
                "name the variable the deployment set: {complaint}"
            );
            assert!(
                complaint.contains("1 or greater"),
                "state the accepted range: {complaint}"
            );
        }
    }

    /// The floor stated for the environment path holds for the config file too: a ceiling of
    /// zero would reject every result including the smallest, and `validate` has to say so
    /// rather than let every tool call fail at runtime.
    #[test]
    fn a_zero_result_ceiling_in_the_config_file_is_rejected() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.toml");
        fs::write(&path, "[mcp]\nmax_tool_result_chars = 0\n").unwrap();
        let error = Config::resolve_with_environment(
            ConfigOverrides {
                config_path: Some(path),
                ..Default::default()
            },
            ConfigEnvironment::default(),
        )
        .unwrap_err();
        let chain = format!("{error:#}");
        assert!(chain.contains("mcp.max_tool_result_chars"), "{chain}");
        assert!(chain.contains("reject every result"), "{chain}");
    }

    /// A value that does not parse is rejected against the variable that carried it, never
    /// silently dropped while the shipped budget stays in force. That drop is exactly the
    /// defect `resolve_max_tool_result_chars` names: a registration that sets a bound and does
    /// not get it.
    #[test]
    fn a_malformed_client_limit_value_is_rejected_rather_than_dropped() {
        let dir = tempfile::tempdir().unwrap();
        let bare = dir.path().join("bare.toml");
        fs::write(&bare, "").unwrap();
        let mut client_limits = BTreeMap::new();
        client_limits.insert("codex-input-schema-bytes".to_owned(), "6ooo".to_owned());
        let error = Config::resolve_with_environment(
            ConfigOverrides {
                config_path: Some(bare),
                ..Default::default()
            },
            ConfigEnvironment {
                client_limits,
                ..Default::default()
            },
        )
        .unwrap_err();
        let chain = format!("{error:#}");
        assert!(
            chain.contains("AI_SESSION_SEARCH_CLIENT_LIMIT_CODEX_INPUT_SCHEMA_BYTES"),
            "name the variable the deployment set: {chain}"
        );
        assert!(
            chain.contains("6ooo"),
            "quote the value that failed: {chain}"
        );
    }

    /// A structural row is not a client budget: accepting an override for it silences the
    /// checker while the client still rejects the schema outright.
    #[test]
    fn a_structural_rule_cannot_be_configured_as_a_client_budget() {
        let mut config = Config::default();
        config
            .mcp
            .client_limits
            .insert("vscode-no-root-combinator".to_owned(), 1);
        let error = config
            .validate()
            .expect_err("a structural rule must not take a budget override");
        let chain = format!("{error:#}");
        assert!(chain.contains("vscode-no-root-combinator"), "{chain}");
        assert!(chain.contains("structural"), "{chain}");
    }

    #[test]
    fn state_path_selection_uses_platform_for_new_installs_and_preserves_legacy_data() {
        let dir = tempfile::tempdir().unwrap();
        let platform = dir.path().join("platform/ai-session-search/index.db");
        let legacy = dir.path().join("legacy/ai-session-search/index.db");

        assert_eq!(
            choose_default_state_path(platform.clone(), legacy.clone()),
            platform,
            "new installs use the platform-standard state path"
        );

        fs::create_dir_all(legacy.parent().unwrap()).unwrap();
        fs::write(&legacy, "legacy index").unwrap();
        assert_eq!(
            choose_default_state_path(platform.clone(), legacy.clone()),
            legacy,
            "an existing legacy index remains active"
        );

        fs::create_dir_all(platform.parent().unwrap()).unwrap();
        fs::write(&platform, "partial destination").unwrap();
        assert_eq!(
            choose_default_state_path(platform, legacy.clone()),
            legacy,
            "an ambiguous destination must not silently hide legacy data"
        );
    }

    #[test]
    fn effective_config_serializes_for_config_show() {
        let cfg = Config::default();

        let toml = toml::to_string(&cfg).unwrap();
        assert!(toml.contains("auto_reindex_busy_timeout_ms"));
        assert!(toml.contains("auto_reindex_interval_ms"));
        assert!(toml.contains("search_messages_limit"));
        assert!(toml.contains("get_session_transcript_lines"));
        assert!(toml.contains("preview_chars"));
        assert!(toml.contains("show_transcript_lines"));
        assert!(toml.contains("lines_per_message"));
        assert!(toml.contains("evidence_preview_chars"));
        assert!(toml.contains("[capabilities.message_classification]"));
        assert!(toml.contains("run_message_classification_limit"));
        assert!(!toml.contains("corrections_limit"));
        assert!(toml.contains("planning_limit"));
        assert!(toml.contains("vocab_limit"));
        assert!(toml.contains("repeat_max_groups"));
        assert!(toml.contains("repeat_max_examples_per_group"));
        assert!(toml.contains("query_timeout_ms"));
        assert!(toml.contains("schema_summary_tables"));

        let json = serde_json::to_string(&cfg).unwrap();
        assert!(json.contains("auto_reindex_busy_timeout_ms"));
        assert!(json.contains("auto_reindex_interval_ms"));
        assert!(json.contains("search_messages_limit"));
        assert!(json.contains("get_session_transcript_lines"));
        assert!(json.contains("preview_chars"));
        assert!(json.contains("show_transcript_lines"));
        assert!(json.contains("lines_per_message"));
        assert!(json.contains("evidence_preview_chars"));
        assert!(json.contains("\"capabilities\""));
        assert!(json.contains("run_message_classification_limit"));
        assert!(!json.contains("corrections_limit"));
        assert!(json.contains("planning_limit"));
        assert!(json.contains("vocab_limit"));
        assert!(json.contains("repeat_max_groups"));
        assert!(json.contains("repeat_max_examples_per_group"));
        assert!(json.contains("query_timeout_ms"));
        assert!(json.contains("schema_summary_tables"));
    }

    #[test]
    fn resolve_threads_precedence_uses_pure_inputs() {
        let (threads, origin) = resolve_threads_setting(Some(11), Some("7"), 3, true).unwrap();
        assert_eq!((threads, origin.as_str()), (11, "cli --threads"));

        let (threads, origin) = resolve_threads_setting(None, Some("7"), 3, true).unwrap();
        assert_eq!(
            (threads, origin.as_str()),
            (7, "environment AI_SESSION_SEARCH_THREADS")
        );
        assert!(resolve_threads_setting(None, Some("0"), 3, true).is_err());
    }

    #[test]
    fn every_provider_preserves_omitted_empty_and_two_root_path_semantics() {
        fn provider_config(config: &Config, provider: crate::models::Provider) -> &ProviderConfig {
            match provider {
                crate::models::Provider::Claude => &config.providers.claude,
                crate::models::Provider::ClaudeDesktop => &config.providers.claude_desktop,
                crate::models::Provider::Codex => &config.providers.codex,
                crate::models::Provider::Cursor => &config.providers.cursor,
                crate::models::Provider::Antigravity => &config.providers.antigravity,
                crate::models::Provider::Pi => &config.providers.pi,
                crate::models::Provider::PrimeAgent => &config.providers.prime_agent,
                crate::models::Provider::AiStudio => &config.providers.aistudio,
                crate::models::Provider::GeminiCli => &config.providers.gemini_cli,
            }
        }
        let defaults = Config::default();

        for provider in crate::source::PROVIDERS {
            let name = provider.as_str();
            let omitted: Config =
                toml::from_str(&format!("[providers.{name}]\nenabled = false\n")).unwrap();
            assert_eq!(
                provider_config(&omitted, provider).paths,
                provider_config(&defaults, provider).paths,
                "{name}: omitting paths must preserve platform defaults"
            );

            let empty: Config =
                toml::from_str(&format!("[providers.{name}]\nenabled = true\npaths = []\n"))
                    .unwrap();
            assert!(
                provider_config(&empty, provider).paths.is_empty(),
                "{name}: explicit [] must select no roots"
            );

            let two: Config = toml::from_str(&format!(
                "[providers.{name}]\nenabled = true\npaths = ['/one', '/two']\n"
            ))
            .unwrap();
            assert_eq!(
                provider_config(&two, provider).paths,
                ["/one", "/two"],
                "{name}: an explicit list must replace defaults without losing order"
            );
        }
    }

    #[test]
    fn the_rc2_preview_setting_name_still_sets_the_preview_body() {
        // 1.0.0rc3 renamed this key and every config that set it stopped loading.
        let config = toml::from_str::<Config>("[ui]\npreview_lines = 20\n").unwrap();
        assert_eq!(config.ui.preview_body_lines, 20);
    }

    #[test]
    fn a_config_setting_both_preview_names_loads_and_the_current_name_wins() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.toml");
        std::fs::write(&path, "[ui]\npreview_lines = 20\npreview_body_lines = 12\n").unwrap();
        let resolved = Config::resolve_with_environment(
            ConfigOverrides {
                config_path: Some(path),
                ..ConfigOverrides::default()
            },
            ConfigEnvironment::default(),
        )
        .unwrap();
        assert_eq!(resolved.config.ui.preview_body_lines, 12);
    }

    #[test]
    fn unknown_config_keys_are_rejected_instead_of_silently_ignored() {
        let error =
            toml::from_str::<Config>("[providers.gemini_cli]\nenabled = false\n").unwrap_err();
        assert!(error.to_string().contains("gemini_cli"));
    }

    #[test]
    fn provider_config_uses_the_public_aistudio_identifier() {
        let serialized = toml::to_string(&Config::default()).unwrap();
        assert!(serialized.contains("[providers.aistudio]"));
        assert!(!serialized.contains("[providers.ai-studio]"));
        assert!(toml::from_str::<Config>("[providers.aistudio]\nenabled = false\n").is_ok());
        assert!(toml::from_str::<Config>("[providers.ai-studio]\nenabled = false\n").is_err());
    }

    #[test]
    fn resolver_applies_cli_then_canonical_env_then_config_then_default() {
        let dir = tempfile::tempdir().unwrap();
        let config_path = dir.path().join("config.toml");
        fs::write(
            &config_path,
            "[index]\ndb_path = '/config/index.db'\ncache_dir = '/config/cache'\n[performance]\nthreads = 3\n",
        )
        .unwrap();
        let resolved = Config::resolve_with_environment(
            ConfigOverrides {
                config_path: Some(config_path),
                database_path: Some(PathBuf::from("/cli/index.db")),
                threads: Some(11),
                ..Default::default()
            },
            ConfigEnvironment {
                database_path: Some(PathBuf::from("/env/index.db")),
                cache_dir: Some(PathBuf::from("/env/cache")),
                threads: Some("7".to_string()),
                ..Default::default()
            },
        )
        .unwrap();
        assert_eq!(resolved.config.db_path(), PathBuf::from("/cli/index.db"));
        assert_eq!(resolved.config.cache_dir(), PathBuf::from("/env/cache"));
        assert_eq!(resolved.config.performance.threads, 11);
        assert_eq!(resolved.origins.database, "cli --database");
        assert_eq!(
            resolved.origins.cache,
            "environment AI_SESSION_SEARCH_CACHE_DIR"
        );
        assert_eq!(resolved.origins.threads, "cli --threads");
    }

    #[test]
    fn index_refresh_resolver_applies_cli_environment_config_default_precedence() {
        let configured = IndexRefresh::ExistingOnly;
        assert_eq!(
            resolve_index_refresh_setting(
                Some(IndexRefresh::BeforeQuery),
                Some("auto"),
                configured,
                true,
            )
            .unwrap(),
            (IndexRefresh::BeforeQuery, "cli --index-refresh".to_string())
        );
        assert_eq!(
            resolve_index_refresh_setting(None, Some("auto"), configured, true).unwrap(),
            (
                IndexRefresh::Auto,
                "environment AI_SESSION_SEARCH_INDEX_REFRESH".to_string(),
            )
        );
        assert_eq!(
            resolve_index_refresh_setting(None, None, configured, true).unwrap(),
            (IndexRefresh::ExistingOnly, "config file".to_string())
        );
        assert_eq!(
            resolve_index_refresh_setting(None, None, IndexRefresh::Auto, false).unwrap(),
            (IndexRefresh::Auto, "typed default".to_string())
        );
        assert!(
            resolve_index_refresh_setting(None, Some("later"), configured, true)
                .unwrap_err()
                .to_string()
                .contains(
                    "AI_SESSION_SEARCH_INDEX_REFRESH expected auto, before-query, or existing-only"
                )
        );
    }

    #[test]
    fn resolver_anchors_toml_relative_paths_to_config_parent() {
        let dir = tempfile::tempdir().unwrap();
        let config_dir = dir.path().join("portable");
        fs::create_dir_all(&config_dir).unwrap();
        let config_path = config_dir.join("config.toml");
        fs::write(
            &config_path,
            r#"
[index]
db_path = "state/index.db"
cache_dir = "cache"
[providers.claude]
paths = ["sessions/claude"]
[providers.claude-desktop]
paths = ["sessions/claude-desktop"]
[providers.codex]
paths = ["sessions/codex"]
[providers.cursor]
paths = ["sessions/cursor"]
[providers.antigravity]
paths = ["sessions/antigravity"]
[providers.pi]
paths = ["sessions/pi"]
[providers.prime-agent]
paths = ["sessions/prime-agent"]
[providers.aistudio]
paths = ["sessions/ai-studio"]
[providers.gemini-cli]
paths = ["sessions/gemini-cli"]
"#,
        )
        .unwrap();

        let resolved = Config::resolve_with_environment(
            ConfigOverrides {
                config_path: Some(config_path),
                ..Default::default()
            },
            ConfigEnvironment::default(),
        )
        .unwrap();

        assert_eq!(resolved.config.db_path(), config_dir.join("state/index.db"));
        assert_eq!(resolved.config.cache_dir(), config_dir.join("cache"));
        for (actual, relative) in [
            (resolved.config.claude_paths(), "sessions/claude"),
            (
                resolved.config.claude_desktop_paths(),
                "sessions/claude-desktop",
            ),
            (resolved.config.codex_paths(), "sessions/codex"),
            (resolved.config.cursor_paths(), "sessions/cursor"),
            (resolved.config.antigravity_paths(), "sessions/antigravity"),
            (resolved.config.pi_paths(), "sessions/pi"),
            (resolved.config.prime_agent_paths(), "sessions/prime-agent"),
            (resolved.config.aistudio_paths(), "sessions/ai-studio"),
            (resolved.config.gemini_cli_paths(), "sessions/gemini-cli"),
        ] {
            assert_eq!(actual, vec![config_dir.join(relative)]);
        }
    }

    #[test]
    fn resolver_leaves_cli_and_environment_relative_overrides_cwd_relative() {
        let dir = tempfile::tempdir().unwrap();
        let config_path = dir.path().join("config.toml");
        fs::write(&config_path, "").unwrap();

        let resolved = Config::resolve_with_environment(
            ConfigOverrides {
                config_path: Some(config_path),
                database_path: Some(PathBuf::from("cli/index.db")),
                ..Default::default()
            },
            ConfigEnvironment {
                cache_dir: Some(PathBuf::from("environment/cache")),
                ..Default::default()
            },
        )
        .unwrap();

        assert_eq!(resolved.config.db_path(), PathBuf::from("cli/index.db"));
        assert_eq!(
            resolved.config.cache_dir(),
            PathBuf::from("environment/cache")
        );
    }

    #[test]
    fn explicit_missing_config_errors_but_implicit_missing_config_is_empty() {
        let dir = tempfile::tempdir().unwrap();
        let missing = dir.path().join("missing.toml");

        let override_error = Config::resolve_with_environment(
            ConfigOverrides {
                config_path: Some(missing.clone()),
                ..Default::default()
            },
            ConfigEnvironment::default(),
        )
        .unwrap_err();
        assert_eq!(
            override_error.to_string(),
            format!("explicit config file does not exist: {}", missing.display())
        );

        let environment_error = Config::resolve_with_environment(
            ConfigOverrides::default(),
            ConfigEnvironment {
                config_path: Some(missing.clone()),
                ..Default::default()
            },
        )
        .unwrap_err();
        assert_eq!(
            environment_error.to_string(),
            format!("explicit config file does not exist: {}", missing.display())
        );

        assert_eq!(read_config_text(&missing, false).unwrap(), "");
    }
}