synaps-core 0.10.1

Foundation types, config, session, auth, protocol — leaf crate for agent-runtime
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
use crate::core::shell_config::ShellConfig;
use std::collections::BTreeMap;
use std::path::PathBuf;
use std::sync::OnceLock;

static PROFILE_NAME: OnceLock<Option<String>> = OnceLock::new();
static PROVIDER_KEYS: OnceLock<BTreeMap<String, String>> = OnceLock::new();
static IDENTITY: OnceLock<String> = OnceLock::new();

pub const DEFAULT_IDENTITY: &str =
    "You are an AI assistant running in SynapsCLI, an open-source agent runtime.";

/// Returns the configured identity string for the system prompt preamble.
/// Falls back to `DEFAULT_IDENTITY` (the SynapsCLI identity above) if not set
/// in config. Initialized by `load_config()` — safe to call anytime after boot.
pub fn get_identity() -> String {
    IDENTITY
        .get()
        .cloned()
        .unwrap_or_else(|| DEFAULT_IDENTITY.to_string())
}

/// Provider API keys parsed from `provider.<name> = ...` lines in config.
/// Empty if `load_config()` hasn't been called. The registry falls back to
/// env vars, so e.g. `GROQ_API_KEY` works even with an empty map.
pub fn get_provider_keys() -> BTreeMap<String, String> {
    PROVIDER_KEYS.get().cloned().unwrap_or_default()
}

/// Returns the active profile name, if any.
/// Reads from `SYNAPS_PROFILE` environment variable if not already set programmatically.
pub fn get_profile() -> Option<String> {
    PROFILE_NAME
        .get_or_init(|| std::env::var("SYNAPS_PROFILE").ok())
        .clone()
}

/// Sets the active profile name. Must be called before any `get_profile()` call
/// (i.e., before config resolution begins). Uses OnceLock — first write wins,
/// subsequent calls are no-ops. No env var mutation (unsafe under tokio).
pub fn set_profile(name: Option<String>) {
    let _ = PROFILE_NAME.set(name);
}

pub fn base_dir() -> PathBuf {
    if let Ok(path) = std::env::var("SYNAPS_BASE_DIR") {
        return PathBuf::from(path);
    }
    let home = std::env::var("HOME")
        .or_else(|_| std::env::var("USERPROFILE"))
        .unwrap_or_else(|_| ".".to_string());
    PathBuf::from(home).join(".synaps-cli")
}

/// Overrides the Synaps base directory. Intended for tests and embedded harnesses.
#[doc(hidden)]
pub fn set_base_dir_for_tests(path: PathBuf) {
    std::env::set_var("SYNAPS_BASE_DIR", path);
}

/// Resolves a path for reading. Checks the profile folder first, then falls back to the default folder.
pub fn resolve_read_path(filename: &str) -> PathBuf {
    let base = base_dir();

    if let Some(profile) = get_profile() {
        let profile_path = base.join(&profile).join(filename);
        if profile_path.exists() {
            return profile_path;
        }
    }

    base.join(filename)
}

/// Resolves a path for reading with an extended arbitrary path tree.
pub fn resolve_read_path_extended(path: &str) -> PathBuf {
    let base = base_dir();

    if let Some(profile) = get_profile() {
        let profile_path = base.join(&profile).join(path);
        if profile_path.exists() {
            return profile_path;
        }
    }

    base.join(path)
}

/// Resolves a path for writing. Unconditionally writes to the profile folder if a profile is active.
pub fn resolve_write_path(filename: &str) -> PathBuf {
    let mut base = base_dir();

    if let Some(profile) = get_profile() {
        base.push(profile);
    }

    let _ = std::fs::create_dir_all(&base);
    base.join(filename)
}

/// Gets the absolute directory for the current profile (or root if default).
pub fn get_active_config_dir() -> PathBuf {
    let mut base = base_dir();
    if let Some(profile) = get_profile() {
        base.push(profile);
    }
    base
}

/// Automatic context management is opt-in; independent of compaction disclosure.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ContextManagementMode {
    #[default]
    Off,
    Auto,
}

impl ContextManagementMode {
    pub fn parse(value: &str) -> Option<Self> {
        match value.trim().to_ascii_lowercase().as_str() {
            "off" => Some(Self::Off),
            "auto" => Some(Self::Auto),
            _ => None,
        }
    }

    pub fn as_str(self) -> &'static str {
        match self {
            Self::Off => "off",
            Self::Auto => "auto",
        }
    }
}

/// Task-aware soft context bands, parsed from `context_management.*` keys.
///
/// Missing thresholds use window-aware defaults (200k: 140k/180k;
/// 1m: 250k/400k). A single override adjusts the other default as necessary
/// to keep pressure below rollover. These settings never override the host's
/// hard capacity or authorize tools, disclosure, or a session transition.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ContextManagementConfig {
    pub mode: ContextManagementMode,
    /// Optional absolute token threshold; `auto` in config clears the override.
    pub pressure_tokens: Option<u64>,
    /// Optional absolute token threshold; `auto` in config clears the override.
    pub rollover_tokens: Option<u64>,
    /// Minimum remaining headroom before any model round. Default: 16,000.
    pub reserve_tokens: u64,
    /// Maximum extra Plan/WrapUp rounds after rollover becomes due. Default: 2.
    /// Zero disables extensions; phase reports cannot renew this allowance.
    pub finish_rounds: u32,
}

impl Default for ContextManagementConfig {
    fn default() -> Self {
        Self {
            mode: ContextManagementMode::Off,
            pressure_tokens: None,
            rollover_tokens: None,
            reserve_tokens: 16_000,
            finish_rounds: 2,
        }
    }
}

impl ContextManagementConfig {
    pub const MAX_FINISH_ROUNDS: u32 = 8;
    pub const MAX_RESERVE_TOKENS: u64 = 1_000_000;

    /// Validate independently of a model selection. Also call
    /// `validate_for_window` when the effective context window is known.
    pub fn validate(&self) -> Result<(), &'static str> {
        if self.pressure_tokens == Some(0) {
            return Err("pressure_tokens must be positive");
        }
        if self.rollover_tokens.is_some_and(|v| v < 2) {
            return Err("rollover_tokens must be at least 2");
        }
        if let (Some(pressure), Some(rollover)) = (self.pressure_tokens, self.rollover_tokens) {
            if pressure >= rollover {
                return Err("pressure_tokens must be below rollover_tokens");
            }
        }
        if !(1..=Self::MAX_RESERVE_TOKENS).contains(&self.reserve_tokens) {
            return Err("reserve_tokens must be between 1 and 1000000");
        }
        if self.finish_rounds > Self::MAX_FINISH_ROUNDS {
            return Err("finish_rounds must be between 0 and 8");
        }
        Ok(())
    }

    /// Threshold overrides must fit the effective window. The hard budget
    /// remains authoritative even when an override fits this validation.
    pub fn validate_for_window(&self, context_window_tokens: u64) -> Result<(), &'static str> {
        self.validate()?;
        if context_window_tokens < 2 {
            return Err("context window must contain at least two tokens");
        }
        if self
            .pressure_tokens
            .is_some_and(|v| v >= context_window_tokens)
        {
            return Err("pressure_tokens must be below the context window");
        }
        if self
            .rollover_tokens
            .is_some_and(|v| v > context_window_tokens)
        {
            return Err("rollover_tokens must not exceed the context window");
        }
        Ok(())
    }
}

/// Parse fields first; validate the complete policy after all lines so threshold
/// ordering and an explicit context window do not depend on config key order.
fn parse_context_management_config_key(
    config: &mut ContextManagementConfig,
    key: &str,
    value: &str,
) -> Result<(), &'static str> {
    match key {
        "context_management.mode" => {
            config.mode = ContextManagementMode::parse(value).ok_or("expected off or auto")?;
        }
        "context_management.pressure_tokens" | "context_management.rollover_tokens" => {
            let tokens = if value.eq_ignore_ascii_case("auto") {
                None
            } else {
                Some(
                    value
                        .parse::<u64>()
                        .map_err(|_| "expected auto or an unsigned token count")?,
                )
            };
            if key == "context_management.pressure_tokens" {
                config.pressure_tokens = tokens;
            } else {
                config.rollover_tokens = tokens;
            }
        }
        "context_management.reserve_tokens" => {
            config.reserve_tokens = value
                .parse()
                .map_err(|_| "expected an unsigned token count")?;
        }
        "context_management.finish_rounds" => {
            config.finish_rounds = value
                .parse()
                .map_err(|_| "expected an unsigned round count")?;
        }
        _ => return Err("unknown context management key"),
    }
    Ok(())
}

/// Startup / first-turn behaviour (`startup.*` keys). Boot-time only — these
/// take effect at the next launch, never mid-session.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StartupConfig {
    /// Skip blocking on extension discovery before the first turn. When true
    /// the attach path sets `await_extensions=false` (fast cold start; a tool
    /// from a slow extension may be unavailable on turn 1). Default: true.
    pub quick_start: bool,
    /// Max seconds to wait for extensions when Quick Start is off. Default: 30.
    pub extensions_ready_timeout_secs: u64,
}

impl Default for StartupConfig {
    fn default() -> Self {
        Self {
            quick_start: true,
            extensions_ready_timeout_secs: 30,
        }
    }
}

/// Daemon lifetime knobs (`daemon.*` keys). Config-file fallbacks; the matching
/// `SYNAPS_DAEMON_*` env vars still WIN over these when set.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DaemonConfig {
    /// Seconds an auto-spawned daemon stays alive after the last client
    /// disconnects. `0` = never idle-exit. Env `SYNAPS_DAEMON_IDLE_EXIT_SECS`
    /// overrides. Default: 10.
    pub idle_exit_secs: u64,
    /// Seconds a pending host confirmation on a detached session survives
    /// before it is fail-closed answered `None`. `0` = disabled (survives
    /// forever). Env `SYNAPS_DAEMON_PROMPT_ABANDON_SECS` overrides. Default: 3600.
    pub prompt_abandon_secs: u64,
    /// Seconds a PARKED session row lingers before eviction. `0` = keep
    /// forever. Env `SYNAPS_DAEMON_PARKED_EVICT_SECS` overrides. Default: 3600.
    pub parked_evict_secs: u64,
}

impl Default for DaemonConfig {
    fn default() -> Self {
        Self {
            idle_exit_secs: 10,
            prompt_abandon_secs: 3600,
            parked_evict_secs: 3600,
        }
    }
}

/// Parse `startup.*` keys. Unknown keys return an error (caller warns).
fn parse_startup_config_key(
    config: &mut StartupConfig,
    key: &str,
    value: &str,
) -> Result<(), &'static str> {
    match key {
        "startup.quick_start" => {
            config.quick_start = match value.trim() {
                "true" | "1" | "on" | "yes" => true,
                "false" | "0" | "off" | "no" => false,
                _ => return Err("expected on or off"),
            };
        }
        "startup.extensions_ready_timeout_secs" => {
            config.extensions_ready_timeout_secs =
                value.trim().parse().map_err(|_| "expected an unsigned second count")?;
        }
        _ => return Err("unknown startup key"),
    }
    Ok(())
}

/// Parse `daemon.*` keys. Unknown keys return an error (caller warns).
fn parse_daemon_config_key(
    config: &mut DaemonConfig,
    key: &str,
    value: &str,
) -> Result<(), &'static str> {
    let secs = || value.trim().parse::<u64>().map_err(|_| "expected an unsigned second count");
    match key {
        "daemon.idle_exit_secs" => config.idle_exit_secs = secs()?,
        "daemon.prompt_abandon_secs" => config.prompt_abandon_secs = secs()?,
        "daemon.parked_evict_secs" => config.parked_evict_secs = secs()?,
        _ => return Err("unknown daemon key"),
    }
    Ok(())
}

/// Server security configuration parsed from `server.*` keys.
#[derive(Debug, Clone, Default)]
pub struct ServerConfig {
    /// Comma-separated list of allowed Origin headers. Empty = allow all (localhost-only protection).
    pub allowed_origins: Vec<String>,
    /// Pre-shared authentication token. If set, clients must provide it on WebSocket upgrade
    /// via `?token=X` query param or `Authorization: Bearer X` header. If None, auto-generated on boot.
    pub token: Option<String>,
    /// When true, `HookResult::Confirm` is auto-approved without prompting (useful for headless/agent mode).
    pub auto_approve_confirms: bool,
    /// Maximum inbound message size in bytes. Defaults to context_window * 4 (rough token→byte estimate).
    /// None means no artificial cap.
    pub max_message_size: Option<usize>,
}

/// Bridge daemon configuration parsed from `bridge.*` keys.
///
/// Controls best-effort mirroring of watcher heartbeats over the bridge
/// daemon's UDS `ControlSocket` (`heartbeat_emit` op). All keys are optional
/// and the feature is OFF by default.
#[derive(Debug, Clone)]
pub struct BridgeConfig {
    /// Path to the bridge daemon's UDS control socket.
    /// When `None`, defaults to `base_dir().join("bridge/control.sock")`.
    pub uds_path: Option<PathBuf>,
    /// When true, every watcher heartbeat tick mirrors a `heartbeat_emit`
    /// JSON-RPC call over the UDS socket. Errors are logged at debug only.
    pub heartbeat_mirror: bool,
    /// Per-call timeout in milliseconds (covers connect + write + read).
    pub heartbeat_timeout_ms: u64,
}

impl Default for BridgeConfig {
    fn default() -> Self {
        Self {
            uds_path: None,
            heartbeat_mirror: false,
            heartbeat_timeout_ms: 250,
        }
    }
}

impl BridgeConfig {
    /// Resolve the UDS path, falling back to the default under `base_dir()`.
    pub fn resolved_uds_path(&self) -> PathBuf {
        self.uds_path
            .clone()
            .unwrap_or_else(|| base_dir().join("bridge/control.sock"))
    }
}

/// Auth configuration parsed from `auth.*` keys. Controls whether this client
/// resolves provider tokens from the local `auth.json` (default) or from a
/// remote credential broker. See task #157 / `auth::credential_source`.
#[derive(Debug, Clone, Default)]
pub struct AuthConfig {
    /// Broker base URL. When set (here, or via `SYNAPS_AUTH_ENDPOINT`), the
    /// client fetches short-lived access tokens from the broker instead of
    /// reading/refreshing the local `auth.json`.
    pub remote_endpoint: Option<String>,
    /// Per-machine bearer presented to the broker (or `SYNAPS_MACHINE_TOKEN`).
    /// This is the machine's own identity, never the provider credential.
    pub machine_token: Option<String>,
}

impl AuthConfig {
    /// Resolve the credential source. Environment variables take precedence over
    /// config-file values: `SYNAPS_AUTH_ENDPOINT` / `SYNAPS_MACHINE_TOKEN`.
    /// Returns `Remote` iff an endpoint is set (env or config), else `Local`.
    pub fn credential_source(&self) -> crate::core::auth::CredentialSource {
        let endpoint = std::env::var("SYNAPS_AUTH_ENDPOINT")
            .ok()
            .filter(|s| !s.trim().is_empty())
            .or_else(|| self.remote_endpoint.clone());
        let machine_token = std::env::var("SYNAPS_MACHINE_TOKEN")
            .ok()
            .filter(|s| !s.trim().is_empty())
            .or_else(|| self.machine_token.clone());
        crate::core::auth::CredentialSource::from_parts(endpoint, machine_token)
    }
}

/// Prompt-cache TTL strategy for Anthropic requests.
///
/// Controls the `cache_control` value emitted at every cache marker site:
/// - `FiveMinutes` (default): bare `{"type": "ephemeral"}` — byte-identical
///   to historical payloads; the default path can never invalidate existing
///   cached prefixes.
/// - `OneHour`: `{"type": "ephemeral", "ttl": "1h"}` on all markers.
/// - `Hybrid`: 1h on the stable prefix (tools + system, written rarely),
///   bare 5m on the message-tail marker (written every turn).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum CacheTtl {
    #[default]
    FiveMinutes,
    OneHour,
    Hybrid,
}

impl CacheTtl {
    /// Parse a config value (case-insensitive). Returns `None` for unknown
    /// values so the caller can warn and fall back to the default.
    pub fn parse(val: &str) -> Option<CacheTtl> {
        match val.to_ascii_lowercase().as_str() {
            "5m" | "5min" | "default" => Some(CacheTtl::FiveMinutes),
            "1h" | "60m" | "1hr" => Some(CacheTtl::OneHour),
            "hybrid" => Some(CacheTtl::Hybrid),
            _ => None,
        }
    }
}

/// `tools.activation_confirm` — host policy for model-initiated
/// `activate_tools` (progressive tool disclosure).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ActivationConfirm {
    /// Authorize model-initiated activation without prompting (default).
    #[default]
    Auto,
    /// Ask the host: the y/n "Confirm tool activation" dialog; only an
    /// explicit y/yes authorizes (fail-closed).
    Prompt,
    /// Never authorize model-initiated activation; no prompt is raised.
    Deny,
}

impl ActivationConfirm {
    pub fn parse(val: &str) -> Option<Self> {
        match val.trim().to_ascii_lowercase().as_str() {
            "auto" => Some(Self::Auto),
            "prompt" => Some(Self::Prompt),
            "deny" => Some(Self::Deny),
            _ => None,
        }
    }

    pub fn as_str(self) -> &'static str {
        match self {
            Self::Auto => "auto",
            Self::Prompt => "prompt",
            Self::Deny => "deny",
        }
    }
}

/// Animated theme-transition mode, parsed from `theme_transition`:
/// - `"on"` (default): cross-fade theme changes over the default 350 ms.
/// - `"off"`: instant snap — accessibility, and mercy on tmux-over-ssh.
/// - integer milliseconds: cross-fade over that duration (clamped to
///   0–2000 ms; `0` behaves like `off`).
///
/// Purely a TUI presentation knob: it changes *how* a new palette is
/// applied, never *which* palette wins.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ThemeTransitionMode {
    #[default]
    On,
    Off,
    Ms(u64),
}

impl ThemeTransitionMode {
    /// Default cross-fade duration for `On` (and the fallback when a live
    /// palette update carries no advisory duration of its own).
    pub const DEFAULT_MS: u64 = 350;
    /// Duration ceiling — both this knob and MXC wire `fade_ms` clamp here.
    pub const MAX_MS: u64 = 2000;

    /// Parse a config value (case-insensitive). Returns `None` for unknown
    /// values so the caller can warn and fall back to the default.
    pub fn parse(val: &str) -> Option<ThemeTransitionMode> {
        match val.to_ascii_lowercase().as_str() {
            "on" | "true" | "yes" => Some(ThemeTransitionMode::On),
            "off" | "false" | "no" => Some(ThemeTransitionMode::Off),
            other => other
                .parse::<u64>()
                .ok()
                .map(|ms| ThemeTransitionMode::Ms(ms.min(Self::MAX_MS))),
        }
    }

    /// Effective default duration in milliseconds; `0` means "snap".
    pub fn duration_ms(self) -> u64 {
        match self {
            ThemeTransitionMode::On => Self::DEFAULT_MS,
            ThemeTransitionMode::Off => 0,
            ThemeTransitionMode::Ms(ms) => ms.min(Self::MAX_MS),
        }
    }
}

/// Runtime event routing configuration parsed from `events.*` keys.
///
/// Controls how runtime events (from the `EventQueue`) are delivered in
/// server and RPC modes.
#[derive(Debug, Clone)]
pub struct EventsConfig {
    /// When `true` (default), the server/RPC/daemon session automatically
    /// triggers a model turn when runtime events arrive while idle.  Set
    /// `events.auto_turn = false` (or `0` / `no` / `off`) to opt out.
    /// Unrecognised values fail safe to `false` with a warning.
    /// The consecutive-turn cap (`auto_turn_cap`) still applies regardless.
    pub auto_turn: bool,
    /// Maximum number of consecutive auto-triggered model turns before the
    /// engine parks and waits for real user input.  Set via
    /// `events.auto_turn_cap = N`.  Default **5**.
    ///
    /// `0` (or `unlimited` / `inf` / `infinite`) disables the cap entirely —
    /// "to infinity and beyond".  Unparseable values warn and keep the default.
    pub auto_turn_cap: u32,
}

/// Default for `events.auto_turn_cap` — mirrors `engine::reactor::AUTO_TURN_CAP`.
pub const DEFAULT_AUTO_TURN_CAP: u32 = 5;

impl Default for EventsConfig {
    fn default() -> Self {
        Self {
            auto_turn: true,
            auto_turn_cap: DEFAULT_AUTO_TURN_CAP,
        }
    }
}

/// Parse a `events.auto_turn_cap` value.  Returns `None` on garbage.
///
/// Accepts a non-negative integer (`0` = unlimited) or one of the aliases
/// `unlimited` / `inf` / `infinite` / `infinity` / `none` (all → `0`).
pub fn parse_auto_turn_cap(val: &str) -> Option<u32> {
    let normalised = val.trim().to_lowercase();
    match normalised.as_str() {
        "unlimited" | "inf" | "infinite" | "infinity" | "none" => Some(0),
        n => n.parse::<u32>().ok(),
    }
}

/// Parse `events.*` configuration keys.
fn parse_events_config_key(cfg: &mut EventsConfig, key: &str, val: &str) {
    if key == "events.auto_turn" {
        let normalised = val.trim().to_lowercase();
        cfg.auto_turn = match normalised.as_str() {
            // Explicit true values.
            "true" | "1" | "yes" | "on" => true,
            // Explicit false values.
            "false" | "0" | "no" | "off" => false,
            // Unrecognised: fail safe to false and warn so the user knows.
            other => {
                eprintln!(
                    "warning: config: unrecognised value for events.auto_turn = {:?}; \
                     expected true/false/yes/no/on/off/1/0 — defaulting to false",
                    other
                );
                false
            }
        };
    } else if key == "events.auto_turn_cap" {
        match parse_auto_turn_cap(val) {
            Some(cap) => cfg.auto_turn_cap = cap,
            None => {
                eprintln!(
                    "warning: config: unrecognised value for events.auto_turn_cap = {:?}; \
                     expected a non-negative integer or unlimited/inf/infinite (0 = unlimited) \
                     — keeping default {}",
                    val.trim(),
                    DEFAULT_AUTO_TURN_CAP
                );
            }
        }
    } // unknown events.* keys ignored
}

/// Typed per-role turn-budget overrides (Task 23, spec §8.1). Every field
/// is optional: unset fields keep the role's compiled default. Values are
/// parsed from `turn_budget.<role>.<field>` config keys.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct TurnBudgetOverrides {
    pub max_provider_rounds: Option<u32>,
    pub max_tool_calls: Option<u32>,
    pub max_elapsed_secs: Option<u64>,
    pub max_accumulated_tool_result_bytes: Option<usize>,
    pub max_context_tokens: Option<u64>,
    pub max_cost_usd: Option<f64>,
    /// Bounded auto-renewals of the provider-round allowance after it is
    /// exhausted mid-turn (spec §8.1). Each renewal resets the round counter;
    /// round renewals never reset wall-clock (durable context successors do). `0`
    /// disables graceful continuation (hard stop at the first exhaustion).
    pub max_round_renewals: Option<u32>,
}

/// Per-role turn budgets (foreground, autonomous/watcher, worker).
#[derive(Debug, Clone, Default, PartialEq)]
pub struct TurnBudgetsConfig {
    pub foreground: TurnBudgetOverrides,
    pub autonomous: TurnBudgetOverrides,
    pub worker: TurnBudgetOverrides,
}

/// Parse `turn_budget.<role>.<field>` keys. Invalid values warn and keep
/// the default (parity with shell.* parsing).
fn parse_turn_budget_config_key(budgets: &mut TurnBudgetsConfig, key: &str, val: &str) {
    let Some(rest) = key.strip_prefix("turn_budget.") else {
        return;
    };
    let Some((role, field)) = rest.split_once('.') else {
        eprintln!("Warning: invalid turn_budget key '{key}' (expected turn_budget.<role>.<field>)");
        return;
    };
    let overrides = match role {
        "foreground" => &mut budgets.foreground,
        "autonomous" => &mut budgets.autonomous,
        "worker" => &mut budgets.worker,
        other => {
            eprintln!("Warning: unknown turn_budget role '{other}' (expected foreground|autonomous|worker)");
            return;
        }
    };
    macro_rules! set {
        ($slot:expr, $ty:ty) => {
            match val.parse::<$ty>() {
                Ok(parsed) => $slot = Some(parsed),
                Err(_) => eprintln!("Warning: invalid value for {key}: '{val}', using default"),
            }
        };
    }
    match field {
        "max_provider_rounds" => set!(overrides.max_provider_rounds, u32),
        "max_tool_calls" => set!(overrides.max_tool_calls, u32),
        "max_elapsed_secs" => set!(overrides.max_elapsed_secs, u64),
        "max_accumulated_tool_result_bytes" => {
            set!(overrides.max_accumulated_tool_result_bytes, usize)
        }
        "max_context_tokens" => set!(overrides.max_context_tokens, u64),
        "max_cost_usd" => set!(overrides.max_cost_usd, f64),
        "max_round_renewals" => set!(overrides.max_round_renewals, u32),
        other => eprintln!("Warning: unknown turn_budget field '{other}'"),
    }
}

/// Continuous-memory settings surface (Task A2, spec §12). Every field is
/// fail-closed: unknown or invalid values warn and keep the compiled default.
///
/// This struct contains continuous-memory policy; backend selection lives in
/// the separate `MemoryBackendConfig`.
/// Secret handling, retention, and project-scope rules are deliberately NOT
/// fields here — they are not configurable at all (spec §12: "Secret,
/// retention, and project rules are not configurable to fail open").
#[derive(Debug, Clone, PartialEq)]
pub struct MemoryConfig {
    /// Durable default memory mode. "off" unless the operator explicitly
    /// consents via `memory.default_mode_confirmed = true` in the same
    /// config parse pass (spec §12 operator-consent rule). Known values:
    /// off | recall_once | recall_each_prompt | capture_only |
    /// capture_and_recall (spec §6.1).
    pub default_mode: String,
    /// Operator-consent latch for `default_mode` (spec §12). Must be set to
    /// `true` in the same parse pass for a non-"off" `default_mode` to take
    /// effect; otherwise `default_mode` reverts to "off" with a warning.
    pub default_mode_confirmed: bool,
    /// Max records surfaced per recall (spec §10.3 budget).
    pub recall_max_records: u32,
    /// Max tokens surfaced per recall (spec §10.3 budget).
    pub recall_max_tokens: u32,
    /// Recall time budget in milliseconds (spec §16).
    pub recall_timeout_ms: u64,
    /// Tool-result capture policy: off | summary_only (spec §11).
    pub capture_tools: String,
    /// Capture assistant turns (spec §8.2).
    pub capture_assistant: bool,
    /// Capture user turns (spec §8.2).
    pub capture_user: bool,
    /// Background consolidation: off | on (spec §11.3, explicit opt-in).
    pub auto_consolidate: String,
    /// Local embedding models: off | on (spec §11.2, never implicit).
    pub local_embeddings: String,
    /// GLiNER entity extraction: off | on (spec §11.2, never implicit).
    pub gliner: String,
}

impl Default for MemoryConfig {
    fn default() -> Self {
        Self {
            default_mode: "off".to_string(),
            default_mode_confirmed: false,
            recall_max_records: 8,
            recall_max_tokens: 4096,
            recall_timeout_ms: 150,
            capture_tools: "summary_only".to_string(),
            capture_assistant: true,
            capture_user: true,
            auto_consolidate: "off".to_string(),
            local_embeddings: "off".to_string(),
            gliner: "off".to_string(),
        }
    }
}

/// Memory mode strings accepted by `memory.default_mode` (spec §6.1,
/// snake_case of `MemoryContextMode`). Anything else fails closed to the
/// current value — `default_mode` can never silently become a non-off mode
/// through an unrecognised string.
const KNOWN_MEMORY_MODES: &[&str] = &[
    "off",
    "recall_once",
    "recall_each_prompt",
    "capture_only",
    "capture_and_recall",
];

/// Parse `memory.<field>` keys (Task A2, spec §12). Invalid values warn and
/// keep the default (parity with turn_budget.* parsing) — never fail open.
fn parse_memory_config_key(memory: &mut MemoryConfig, key: &str, val: &str) {
    let Some(field) = key.strip_prefix("memory.") else {
        return;
    };
    /// Strict boolean: recognised forms parse; anything else warns and
    /// keeps the current (default) value.
    fn parse_bool(slot: &mut bool, key: &str, val: &str) {
        match val {
            "true" | "1" | "yes" | "on" => *slot = true,
            "false" | "0" | "no" | "off" => *slot = false,
            other => eprintln!(
                "Warning: invalid value for {key}: '{other}', expected true/false — using default"
            ),
        }
    }
    /// Closed string-enum: value must be in `allowed`, else warn and keep
    /// the current (default) value.
    fn parse_enum(slot: &mut String, key: &str, val: &str, allowed: &[&str]) {
        if allowed.contains(&val) {
            *slot = val.to_string();
        } else {
            eprintln!(
                "Warning: invalid value for {key}: '{val}', expected one of {} — using default",
                allowed.join("|")
            );
        }
    }
    macro_rules! set_num {
        ($slot:expr, $ty:ty) => {
            match val.parse::<$ty>() {
                Ok(parsed) => $slot = parsed,
                Err(_) => eprintln!("Warning: invalid value for {key}: '{val}', using default"),
            }
        };
    }
    match field {
        "default_mode" => parse_enum(&mut memory.default_mode, key, val, KNOWN_MEMORY_MODES),
        "default_mode_confirmed" => parse_bool(&mut memory.default_mode_confirmed, key, val),
        "recall_max_records" => set_num!(memory.recall_max_records, u32),
        "recall_max_tokens" => set_num!(memory.recall_max_tokens, u32),
        "recall_timeout_ms" => set_num!(memory.recall_timeout_ms, u64),
        "capture_tools" => parse_enum(
            &mut memory.capture_tools,
            key,
            val,
            &["off", "summary_only"],
        ),
        "capture_assistant" => parse_bool(&mut memory.capture_assistant, key, val),
        "capture_user" => parse_bool(&mut memory.capture_user, key, val),
        "auto_consolidate" => parse_enum(&mut memory.auto_consolidate, key, val, &["off", "on"]),
        "local_embeddings" => parse_enum(&mut memory.local_embeddings, key, val, &["off", "on"]),
        "gliner" => parse_enum(&mut memory.gliner, key, val, &["off", "on"]),
        other => eprintln!("Warning: unknown memory field '{other}'"),
    }
}

/// Host-owned note storage selection, independent of continuous-memory consent.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum MemoryBackendKind {
    #[default]
    Legacy,
    Axel,
    /// Invalid configuration must never select legacy storage implicitly.
    Unavailable,
}

#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct MemoryBackendConfig {
    pub kind: MemoryBackendKind,
    /// Explicit absolute executable path; never resolved through PATH.
    pub executable: Option<PathBuf>,
    /// Optional absolute shared Axel brain path; absent uses the private user default.
    pub brain: Option<PathBuf>,
    /// Explicit host opt-in to user-wide notes. Never grants capture/history consent.
    pub user_scope: bool,
}

/// Parsed configuration from the config file.
#[derive(Debug, Clone)]
pub struct SynapsConfig {
    pub model: Option<String>,
    pub thinking_budget: Option<u32>,
    /// Named reasoning level, parsed from the same `thinking = …` key.
    /// When `Some`, this is the authoritative level. When `None`, fall back
    /// to `thinking_budget` for legacy numeric-only values.
    pub thinking_level: Option<crate::core::reasoning::ReasoningLevel>,
    pub context_window: Option<u64>, // override auto-detected context window (tokens)
    pub context_management: ContextManagementConfig,
    /// First-turn / cold-start behaviour (`startup.*`).
    pub startup: StartupConfig,
    /// Daemon lifetime knobs (`daemon.*`); env vars still win.
    pub daemon: DaemonConfig,
    pub compaction_model: Option<String>, // model used for /compact (default: claude-sonnet-4-6)
    /// Where compaction summarization runs (spec §9.4): remote provider or
    /// local-only (zero network construction).
    pub compaction_mode: crate::core::compaction::CompactionMode,
    /// Content classes excluded from remote compaction disclosure.
    pub compaction_exclude: Vec<crate::core::compaction::ContentClass>,
    pub max_tool_output: usize,  // default 30000
    pub bash_timeout: u64,       // default 30
    pub bash_max_timeout: u64,   // default 300
    pub subagent_timeout: u64,   // default 300
    pub api_retries: u32,        // default 3
    pub refusal_retries: u32,    // default 2 — retries on stop_reason=refusal
    pub telemetry: String,       // off | basic | full (default off)
    pub cache_diagnostics: bool, // opt into cache-diagnosis beta (default false)
    /// Prompt-cache TTL strategy: "5m" (default) | "1h" | "hybrid".
    pub cache_ttl: CacheTtl,
    /// Max TUI redraw rate in frames/sec — caps streaming redraws (e.g. 60,
    /// 144, 240). User input always redraws immediately regardless. Default
    /// 60. Range 1–1000. The frame budget is `1000 / max_fps` ms.
    pub max_fps: u32,
    /// Lines to scroll per mouse-wheel event. Different terminal emulators
    /// emit 1–9+ scroll events per physical notch; set this to compensate.
    /// Default: 3. Range 1–20.
    pub scroll_lines: Option<u16>,
    pub theme: Option<String>,
    /// Animated theme transitions: `"on"` (350 ms cross-fade, default),
    /// `"off"` (instant snap), or integer milliseconds (0–2000).
    pub theme_transition: ThemeTransitionMode,
    /// Whether the TUI paints its own opaque background. `false` preserves the terminal background.
    pub tui_background_opaque: bool,
    /// Whether the prompt shows a glow sweeping across it while a turn streams. Default off.
    pub tui_streaming_glow: bool,
    pub agent_name: Option<String>,
    pub identity: Option<String>,
    pub disabled_plugins: Vec<String>,
    pub favorite_models: Vec<String>,
    pub disabled_skills: Vec<String>,
    /// Opt-in progressive tool disclosure (Task 18). When false, providers
    /// receive the existing full tool schema byte-for-byte. When true, each
    /// stream starts with the small essential local core plus discovery and
    /// authorization gateways; exact activations are added per session.
    pub progressive_tool_disclosure: bool,
    /// Host confirmation policy for MODEL-INITIATED `activate_tools`
    /// (`tools.activation_confirm`). `Auto` (default) authorizes without
    /// prompting; `Prompt` asks the host (y/n confirm dialog); `Deny` never
    /// authorizes (locked-down hosts). `server.auto_approve_confirms = true`
    /// still authorizes regardless of this key.
    pub tools_activation_confirm: ActivationConfirm,
    /// Opt-in session persistence strategy (Task 35, spec §9.8). `Json`
    /// (default) is the unchanged legacy full-rewrite path; `Journal` adds
    /// an append-only delta journal with periodic atomic snapshots. See
    /// docs/decisions/T35-session-journal-opt-in.md.
    pub session_persistence: crate::core::session_journal::SessionPersistence,
    /// Built-in tools to disable by runtime name (e.g. "bash", "ls"). Removed
    /// from the registry at boot so they're never offered to the model.
    pub disabled_tools: Vec<String>,
    pub shell: ShellConfig,
    pub server: ServerConfig,
    pub bridge: BridgeConfig,
    pub auth: AuthConfig,
    pub events: EventsConfig,
    pub provider_keys: BTreeMap<String, String>,
    pub keybinds: std::collections::HashMap<String, String>,
    /// Typed per-role turn budgets (Task 23, spec §8.1).
    pub turn_budgets: TurnBudgetsConfig,
    /// Continuous-memory settings surface (Task A2, spec §12).
    pub memory: MemoryConfig,
    /// Host-owned backend; selecting it does not enable recall or capture.
    pub memory_backend: MemoryBackendConfig,
    /// Non-fatal problems found while parsing the config file (unknown keys,
    /// unparseable values). Surfaced once at startup — never block boot.
    pub warnings: Vec<String>,
}

impl Default for SynapsConfig {
    fn default() -> Self {
        Self {
            model: None,
            thinking_budget: None,
            thinking_level: None,
            context_window: None,
            context_management: ContextManagementConfig::default(),
            startup: StartupConfig::default(),
            daemon: DaemonConfig::default(),
            compaction_model: None,
            compaction_mode: crate::core::compaction::CompactionMode::default(),
            compaction_exclude: Vec::new(),
            max_tool_output: 30000,
            bash_timeout: 30,
            bash_max_timeout: 300,
            subagent_timeout: 300,
            api_retries: 3,
            refusal_retries: 2,
            telemetry: "off".to_string(),
            cache_diagnostics: false,
            cache_ttl: CacheTtl::default(),
            max_fps: 60,
            scroll_lines: None,
            theme: None,
            theme_transition: ThemeTransitionMode::default(),
            tui_background_opaque: true,
            tui_streaming_glow: false,
            agent_name: None,
            identity: None,
            disabled_plugins: Vec::new(),
            favorite_models: Vec::new(),
            disabled_skills: Vec::new(),
            progressive_tool_disclosure: false,
            tools_activation_confirm: ActivationConfirm::default(),
            session_persistence: crate::core::session_journal::SessionPersistence::default(),
            disabled_tools: Vec::new(),
            shell: ShellConfig::default(),
            server: ServerConfig::default(),
            bridge: BridgeConfig::default(),
            auth: AuthConfig::default(),
            events: EventsConfig::default(),
            provider_keys: BTreeMap::new(),
            keybinds: std::collections::HashMap::new(),
            turn_budgets: TurnBudgetsConfig::default(),
            memory: MemoryConfig::default(),
            memory_backend: MemoryBackendConfig::default(),
            warnings: Vec::new(),
        }
    }
}

/// Known top-level config keys — used for unknown-key warnings + did-you-mean.
const KNOWN_CONFIG_KEYS: &[&str] = &[
    "model",
    "thinking",
    "compaction_model",
    "context_window",
    "context_management.mode",
    "context_management.pressure_tokens",
    "context_management.rollover_tokens",
    "context_management.reserve_tokens",
    "context_management.finish_rounds",
    "startup.quick_start",
    "startup.extensions_ready_timeout_secs",
    "daemon.idle_exit_secs",
    "daemon.prompt_abandon_secs",
    "daemon.parked_evict_secs",
    "max_tool_output",
    "bash_timeout",
    "bash_max_timeout",
    "subagent_timeout",
    "api_retries",
    "refusal_retries",
    "telemetry",
    "cache_diagnostics",
    "cache_ttl",
    "max_fps",
    "scroll_lines",
    "theme",
    "theme_transition",
    "tui_background_opaque",
    "tui_streaming_glow",
    "agent_name",
    "identity",
    "disabled_plugins",
    "favorite_models",
    "disabled_skills",
    "disabled_tools",
    "progressive_tool_disclosure",
    "tools.activation_confirm",
    "session_persistence",
];

/// Simple Levenshtein distance for did-you-mean suggestions.
fn levenshtein(a: &str, b: &str) -> usize {
    let a: Vec<char> = a.chars().collect();
    let b: Vec<char> = b.chars().collect();
    let mut prev: Vec<usize> = (0..=b.len()).collect();
    let mut cur = vec![0; b.len() + 1];
    for (i, ca) in a.iter().enumerate() {
        cur[0] = i + 1;
        for (j, cb) in b.iter().enumerate() {
            let cost = if ca == cb { 0 } else { 1 };
            cur[j + 1] = (prev[j + 1] + 1).min(cur[j] + 1).min(prev[j] + cost);
        }
        std::mem::swap(&mut prev, &mut cur);
    }
    prev[b.len()]
}

/// Closest known key within edit distance 2, for typo suggestions.
fn did_you_mean(key: &str) -> Option<&'static str> {
    KNOWN_CONFIG_KEYS
        .iter()
        .map(|k| (*k, levenshtein(key, k)))
        .filter(|(_, d)| *d <= 2)
        .min_by_key(|(_, d)| *d)
        .map(|(k, _)| k)
}

// parse_thinking_budget replaced by ThinkingSpec::parse in apply_config_content.

fn parse_comma_list(val: &str) -> Vec<String> {
    val.split(',')
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
        .collect()
}

fn write_comma_list_locked(key: &str, values: &[String]) -> std::io::Result<()> {
    write_config_value_locked(key, &values.join(", "))
}

/// Parse shell.* configuration keys and update the ShellConfig.
fn parse_shell_config_key(shell_config: &mut ShellConfig, key: &str, val: &str) {
    match key {
        "shell.max_sessions" => {
            if let Ok(sessions) = val.parse::<usize>() {
                shell_config.max_sessions = sessions;
            } else {
                eprintln!(
                    "Warning: invalid value for shell.max_sessions: '{}', using default",
                    val
                );
            }
        }
        "shell.idle_timeout" => {
            if let Ok(timeout) = val.parse::<u64>() {
                shell_config.idle_timeout = std::time::Duration::from_secs(timeout);
            } else {
                eprintln!(
                    "Warning: invalid value for shell.idle_timeout: '{}', using default",
                    val
                );
            }
        }
        "shell.readiness_timeout_ms" => {
            if let Ok(timeout) = val.parse::<u64>() {
                shell_config.readiness_timeout_ms = timeout;
            } else {
                eprintln!(
                    "Warning: invalid value for shell.readiness_timeout_ms: '{}', using default",
                    val
                );
            }
        }
        "shell.max_readiness_timeout_ms" => {
            if let Ok(timeout) = val.parse::<u64>() {
                shell_config.max_readiness_timeout_ms = timeout;
            } else {
                eprintln!("Warning: invalid value for shell.max_readiness_timeout_ms: '{}', using default", val);
            }
        }
        "shell.default_rows" => {
            if let Ok(rows) = val.parse::<u16>() {
                shell_config.default_rows = rows;
            } else {
                eprintln!(
                    "Warning: invalid value for shell.default_rows: '{}', using default",
                    val
                );
            }
        }
        "shell.default_cols" => {
            if let Ok(cols) = val.parse::<u16>() {
                shell_config.default_cols = cols;
            } else {
                eprintln!(
                    "Warning: invalid value for shell.default_cols: '{}', using default",
                    val
                );
            }
        }
        "shell.readiness_strategy" => {
            let val_lower = val.to_lowercase();
            match val_lower.as_str() {
                "timeout" | "prompt" | "hybrid" => {
                    shell_config.readiness_strategy = val.to_string();
                }
                _ => {
                    eprintln!(
                        "Warning: invalid value for shell.readiness_strategy: '{}', using default",
                        val
                    );
                }
            }
        }
        "shell.max_output" => {
            if let Ok(max_output) = val.parse::<usize>() {
                shell_config.max_output = max_output;
            } else {
                eprintln!(
                    "Warning: invalid value for shell.max_output: '{}', using default",
                    val
                );
            }
        }
        _ => {
            // Unknown shell.* keys are preserved (not rejected)
        }
    }
}

/// Parse server.* configuration keys and update the ServerConfig.
#[allow(clippy::collapsible_match)]
fn parse_server_config_key(server_config: &mut ServerConfig, key: &str, val: &str) {
    match key {
        "server.allowed_origins" => {
            server_config.allowed_origins = parse_comma_list(val);
        }
        "server.token" => {
            if !val.is_empty() {
                server_config.token = Some(val.to_string());
            }
        }
        "server.auto_approve_confirms" => {
            server_config.auto_approve_confirms = matches!(val, "true" | "1" | "yes");
        }
        "server.max_message_size" => {
            if let Ok(size) = val.parse::<usize>() {
                server_config.max_message_size = Some(size);
            } else {
                eprintln!(
                    "Warning: invalid value for server.max_message_size: '{}', ignored",
                    val
                );
            }
        }
        _ => {
            // Unknown server.* keys preserved (not rejected)
        }
    }
}

/// Parse bridge.* configuration keys and update the BridgeConfig.
fn parse_bridge_config_key(bridge_config: &mut BridgeConfig, key: &str, val: &str) {
    match key {
        "bridge.uds_path" => {
            if val.is_empty() {
                bridge_config.uds_path = None;
            } else {
                bridge_config.uds_path = Some(PathBuf::from(val));
            }
        }
        "bridge.heartbeat_mirror" => {
            bridge_config.heartbeat_mirror = matches!(val, "true" | "1" | "yes");
        }
        "bridge.heartbeat_timeout_ms" => {
            if let Ok(ms) = val.parse::<u64>() {
                bridge_config.heartbeat_timeout_ms = ms;
            } else {
                eprintln!(
                    "Warning: invalid value for bridge.heartbeat_timeout_ms: '{}', using default",
                    val
                );
            }
        }
        _ => {
            // Unknown bridge.* keys preserved (not rejected)
        }
    }
}

/// Parse auth.* configuration keys and update the AuthConfig.
fn parse_auth_config_key(auth_config: &mut AuthConfig, key: &str, val: &str) {
    let v = val.trim();
    match key {
        "auth.remote_endpoint" => {
            auth_config.remote_endpoint = if v.is_empty() {
                None
            } else {
                Some(v.to_string())
            };
        }
        "auth.machine_token" => {
            auth_config.machine_token = if v.is_empty() {
                None
            } else {
                Some(v.to_string())
            };
        }
        _ => {
            // Unknown auth.* keys preserved (not rejected)
        }
    }
}

/// Parse config from a raw string — useful for tests and embedded harnesses.
/// Does NOT write to `PROVIDER_KEYS` or `IDENTITY` OnceLocks.
pub fn load_config_from_str(content: &str) -> SynapsConfig {
    let mut config = SynapsConfig::default();
    apply_config_content(&mut config, content);
    config
}

/// Parse the config file at ~/.synaps-cli/config (or profile variant).
/// Returns default config if file doesn't exist or can't be read.
pub fn load_config() -> SynapsConfig {
    let path = resolve_read_path("config");
    let mut config = SynapsConfig::default();

    let Ok(content) = std::fs::read_to_string(&path) else {
        return config;
    };

    apply_config_content(&mut config, &content);

    // Publish provider keys to the process-wide cache for the API router.
    // First writer wins (OnceLock) — subsequent load_config calls are no-ops.
    let _ = PROVIDER_KEYS.set(config.provider_keys.clone());

    // Publish identity to the process-wide cache for API system prompt preamble.
    let identity_val = config
        .identity
        .clone()
        .unwrap_or_else(|| DEFAULT_IDENTITY.to_string());
    let _ = IDENTITY.set(identity_val);

    config
}

/// Apply key=value config lines from `content` into `config`.
/// Shared by `load_config` (file path) and `load_config_from_str` (test helper).
fn apply_config_content(config: &mut SynapsConfig, content: &str) {
    let mut invalid_context_management = false;
    let mut invalid_memory_backend = false;
    for line in content.lines() {
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        let Some((key, val)) = line.split_once('=') else {
            continue;
        };
        let key = key.trim();
        let val = val.trim();
        match key {
            "model" => config.model = Some(val.to_string()),
            "thinking" => {
                use crate::core::reasoning::ThinkingSpec;
                match ThinkingSpec::parse(val) {
                    Some(ThinkingSpec::Named(level)) => {
                        config.thinking_level = Some(level);
                        config.thinking_budget = level.to_legacy_budget();
                    }
                    Some(ThinkingSpec::Budget(budget)) => {
                        // Preserve exact legacy budgets; do not make the derived
                        // bucket authoritative over the user's token count.
                        config.thinking_level = None;
                        config.thinking_budget = Some(budget);
                    }
                    None => {
                        config.warnings.push(format!("thinking = {val} — expected off|adaptive|low|medium|high|xhigh|max|ultra|ultracode or a token count; thinking disabled"));
                    }
                }
            }
            "compaction_model" => config.compaction_model = Some(val.to_string()),
            "compaction_mode" => match val {
                "remote" => {
                    config.compaction_mode = crate::core::compaction::CompactionMode::Remote
                }
                "local" | "local_only" | "local-only" => {
                    config.compaction_mode = crate::core::compaction::CompactionMode::LocalOnly
                }
                _ => {
                    config.warnings.push(format!(
                        "compaction_mode = {val} — expected remote or local; ignored"
                    ));
                }
            },
            "compaction_exclude" => {
                let mut classes = Vec::new();
                for part in val.split(',').map(str::trim).filter(|p| !p.is_empty()) {
                    match crate::core::compaction::ContentClass::parse(part) {
                        Some(class) => {
                            if !classes.contains(&class) {
                                classes.push(class);
                            }
                        }
                        None => config.warnings.push(format!(
                            "compaction_exclude — unknown content class '{part}'; \
                             expected one of: user_text, assistant_text, thinking, \
                             tool_calls, tool_results, file_paths, event_data"
                        )),
                    }
                }
                config.compaction_exclude = classes;
            }
            "context_window" => {
                let parsed = match val {
                    "200k" | "200K" => Some(200_000),
                    "1m" | "1M" => Some(1_000_000),
                    _ => val.parse::<u64>().ok(),
                };
                if parsed.is_none() {
                    config.warnings.push(format!(
                        "context_window = {val} — expected 200k, 1m, or a token count; ignored"
                    ));
                }
                config.context_window = parsed;
            }
            "max_tool_output" => match val.parse::<usize>() {
                Ok(size) => config.max_tool_output = size,
                Err(_) => config.warnings.push(format!(
                    "max_tool_output = {val} — not a number; using {}",
                    config.max_tool_output
                )),
            },
            "bash_timeout" => match val.parse::<u64>() {
                Ok(t) if t >= 1 => config.bash_timeout = t,
                Ok(_) => config.warnings.push(format!(
                    "bash_timeout = {val} — below minimum (1s); using {}",
                    config.bash_timeout
                )),
                Err(_) => config.warnings.push(format!(
                    "bash_timeout = {val} — not a number; using {}",
                    config.bash_timeout
                )),
            },
            "bash_max_timeout" => {
                if let Ok(timeout) = val.parse::<u64>() {
                    config.bash_max_timeout = timeout;
                }
            }
            "subagent_timeout" => {
                if let Ok(timeout) = val.parse::<u64>() {
                    config.subagent_timeout = timeout;
                }
            }
            "api_retries" => {
                if let Ok(retries) = val.parse::<u32>() {
                    config.api_retries = retries;
                }
            }
            "refusal_retries" => {
                if let Ok(retries) = val.parse::<u32>() {
                    config.refusal_retries = retries;
                }
            }
            "telemetry" => config.telemetry = val.to_string(),
            "cache_diagnostics" => {
                config.cache_diagnostics = matches!(val, "true" | "1" | "on" | "yes");
            }
            "cache_ttl" => match CacheTtl::parse(val) {
                Some(ttl) => config.cache_ttl = ttl,
                None => config.warnings.push(format!(
                    "cache_ttl = {val} — expected 5m, 1h, or hybrid; using 5m"
                )),
            },
            "max_fps" => match val.parse::<u32>() {
                Ok(fps) if (1..=1000).contains(&fps) => config.max_fps = fps,
                Ok(_) => config.warnings.push(format!(
                    "max_fps = {val} — expected 1–1000; using {}",
                    config.max_fps
                )),
                Err(_) => config.warnings.push(format!(
                    "max_fps = {val} — not a number; using {}",
                    config.max_fps
                )),
            },
            "scroll_lines" => match val.parse::<u16>() {
                Ok(n) if (1..=20).contains(&n) => config.scroll_lines = Some(n),
                Ok(_) => config
                    .warnings
                    .push(format!("scroll_lines = {val} — expected 1–20; ignoring")),
                Err(_) => config
                    .warnings
                    .push(format!("scroll_lines = {val} — not a number; ignoring")),
            },
            "theme" => config.theme = Some(val.to_string()),
            "theme_transition" => match ThemeTransitionMode::parse(val) {
                Some(mode) => config.theme_transition = mode,
                None => config.warnings.push(format!(
                    "theme_transition = {val} — expected on, off, or milliseconds (0–2000); using on"
                )),
            },
            "tui_background_opaque" => match val {
                "true" | "1" | "on" | "yes" | "opaque" => config.tui_background_opaque = true,
                "false" | "0" | "off" | "no" | "invisible" => config.tui_background_opaque = false,
                _ => config.warnings.push(format!(
                    "tui_background_opaque = {val} — expected opaque or invisible; using {}",
                    if config.tui_background_opaque {
                        "opaque"
                    } else {
                        "invisible"
                    }
                )),
            },
            "tui_streaming_glow" => match val {
                "true" | "1" | "on" | "yes" => config.tui_streaming_glow = true,
                "false" | "0" | "off" | "no" => config.tui_streaming_glow = false,
                _ => config.warnings.push(format!(
                    "tui_streaming_glow = {val} — expected on or off; using off"
                )),
            },
            "agent_name" => config.agent_name = Some(val.to_string()),
            "identity" => config.identity = Some(val.to_string()),
            "disabled_plugins" => {
                config.disabled_plugins = parse_comma_list(val);
            }
            "favorite_models" => {
                config.favorite_models = parse_comma_list(val);
            }
            "disabled_skills" => {
                config.disabled_skills = parse_comma_list(val);
            }
            "progressive_tool_disclosure" => {
                config.progressive_tool_disclosure = matches!(val, "true" | "1" | "on" | "yes");
            }
            "tools.activation_confirm" => match ActivationConfirm::parse(val) {
                Some(mode) => config.tools_activation_confirm = mode,
                None => config.warnings.push(format!(
                    "tools.activation_confirm = {val} — expected auto, prompt or deny; \
                     keeping the default (auto)"
                )),
            },
            "session_persistence" => {
                match crate::core::session_journal::SessionPersistence::parse(val) {
                    Some(mode) => config.session_persistence = mode,
                    None => config.warnings.push(format!(
                        "session_persistence = {val} — expected json or journal; \
                         keeping the default (json)"
                    )),
                }
            }
            "disabled_tools" => {
                config.disabled_tools = parse_comma_list(val);
            }
            "memory.backend" => {
                config.memory_backend.kind = match val {
                    "legacy" => MemoryBackendKind::Legacy,
                    "axel" => MemoryBackendKind::Axel,
                    _ => {
                        invalid_memory_backend = true;
                        config.warnings.push(format!(
                            "memory.backend = {val} — expected legacy or axel; memory backend unavailable"
                        ));
                        MemoryBackendKind::Unavailable
                    }
                };
            }
            "memory.user_scope" => match val {
                "true" => config.memory_backend.user_scope = true,
                "false" => config.memory_backend.user_scope = false,
                _ => {
                    invalid_memory_backend = true;
                    config.warnings.push("memory.user_scope — expected true or false; memory backend unavailable".into());
                }
            },
            "memory.axel.executable" | "memory.axel.brain" => {
                let path = PathBuf::from(val);
                if !path.is_absolute() {
                    invalid_memory_backend = true;
                    config.warnings.push(format!(
                        "{key} — expected an absolute path; memory backend unavailable"
                    ));
                }
                // Retain invalid paths too: direct config consumers must not
                // mistake an invalid explicit path for an absent default.
                if key == "memory.axel.executable" {
                    config.memory_backend.executable = Some(path);
                } else {
                    config.memory_backend.brain = Some(path);
                }
            }
            _ => {
                // Handle namespaced keys
                if key.starts_with("shell.") {
                    parse_shell_config_key(&mut config.shell, key, val);
                } else if key.starts_with("server.") {
                    parse_server_config_key(&mut config.server, key, val);
                } else if key.starts_with("bridge.") {
                    parse_bridge_config_key(&mut config.bridge, key, val);
                } else if key.starts_with("auth.") {
                    parse_auth_config_key(&mut config.auth, key, val);
                } else if key.starts_with("events.") {
                    parse_events_config_key(&mut config.events, key, val);
                } else if key.starts_with("turn_budget.") {
                    parse_turn_budget_config_key(&mut config.turn_budgets, key, val);
                } else if key.starts_with("memory.") {
                    parse_memory_config_key(&mut config.memory, key, val);
                } else if key.starts_with("startup.") {
                    if let Err(reason) =
                        parse_startup_config_key(&mut config.startup, key, val)
                    {
                        config.warnings.push(format!("{key} — {reason}"));
                    }
                } else if key.starts_with("daemon.") {
                    if let Err(reason) =
                        parse_daemon_config_key(&mut config.daemon, key, val)
                    {
                        config.warnings.push(format!("{key} — {reason}"));
                    }
                } else if key.starts_with("context_management.") {
                    if let Err(reason) = parse_context_management_config_key(
                        &mut config.context_management, key, val,
                    ) {
                        invalid_context_management = true;
                        config.warnings.push(format!("{key} — {reason}"));
                    }
                } else if let Some(provider_key) = key.strip_prefix("provider.") {
                    config
                        .provider_keys
                        .insert(provider_key.to_string(), val.to_string());
                } else if let Some(keybind_key) = key.strip_prefix("keybind.") {
                    config
                        .keybinds
                        .insert(keybind_key.to_string(), val.to_string());
                } else if key.contains('.') {
                    // Dotted keys are namespaced (plugin/extension config, e.g.
                    // `knowledge.jawz_notes`). Plugins define their own keys —
                    // not ours to police. Silently preserved.
                } else {
                    // Unknown top-level key — warn with a did-you-mean if close.
                    match did_you_mean(key) {
                        Some(suggestion) => config.warnings.push(format!(
                            "unknown key '{key}' (did you mean '{suggestion}'?)"
                        )),
                        None => config
                            .warnings
                            .push(format!("unknown key '{key}' — ignored")),
                    }
                }
            }
        }
    }

    // Never leave a partially parsed automatic policy enabled. Syntax errors
    // invalidate this whole parse pass, even if a later duplicate is valid.
    let context_validation = match config.context_window {
        Some(window) => config.context_management.validate_for_window(window),
        None => config.context_management.validate(),
    };
    if let Err(reason) = context_validation {
        invalid_context_management = true;
        config
            .warnings
            .push(format!("context_management — {reason}"));
    }
    if invalid_context_management {
        config.context_management = ContextManagementConfig::default();
        config.warnings.push(
            "invalid context_management configuration — using defaults (mode off)".to_string(),
        );
    }

    // Any invalid backend setting poisons this parse pass, regardless of key
    // order or later duplicate selectors. Never silently route to legacy.
    if invalid_memory_backend {
        config.memory_backend.kind = MemoryBackendKind::Unavailable;
    }

    // Fail-closed operator-consent rule (Task A2, spec §12): a non-"off"
    // `memory.default_mode` takes effect only when the operator also set
    // `memory.default_mode_confirmed = true` in this same parse pass.
    // Checked after the loop so key order never matters.
    if config.memory.default_mode != "off" && !config.memory.default_mode_confirmed {
        config.warnings.push(format!(
            "memory.default_mode = {} requires memory.default_mode_confirmed = true \
             in the same config; reverting to off",
            config.memory.default_mode
        ));
        config.memory.default_mode = "off".to_string();
    }

    // Derive max_message_size from context_window if not explicitly set.
    // Rough estimate: 1 token ≈ 4 bytes. Context window in tokens → bytes.
    if config.server.max_message_size.is_none() {
        if let Some(ctx_tokens) = config.context_window {
            config.server.max_message_size = Some((ctx_tokens as usize) * 4);
        }
    }
}

/// Read a single config value by exact key from the active config file.
pub fn read_config_value(key: &str) -> Option<String> {
    let path = resolve_read_path("config");
    let content = std::fs::read_to_string(&path).ok()?;
    for line in content.lines() {
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        let Some((k, v)) = line.split_once('=') else {
            continue;
        };
        if k.trim() == key.trim() {
            return Some(v.trim().to_string());
        }
    }
    None
}

/// Exclusive advisory lock on `<config>.lock`, held around every
/// read-modify-write of the config file (same pattern as `auth.json`).
/// Two writers (`/settings` in two processes, a `/model` favorite toggle
/// racing a settings edit) no longer lose each other's updates.
///
/// Held for the RMW only (< 1 ms); readers (`load_config`) never take it —
/// they already tolerate the atomic rename. `SYNAPS_CONFIG_LOCK=0` bypasses.
///
/// NOT reentrant: flock on a fresh fd of the same file from the same process
/// conflicts on Linux. Callers that already hold the guard must use the
/// `_locked` inner fns.
struct ConfigLock {
    _file: Option<std::fs::File>,
}

impl ConfigLock {
    fn acquire() -> std::io::Result<Self> {
        if std::env::var("SYNAPS_CONFIG_LOCK").as_deref() == Ok("0") {
            return Ok(Self { _file: None });
        }
        use fs4::fs_std::FileExt;
        let lock_path = resolve_write_path("config").with_extension("lock");
        if let Some(parent) = lock_path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        let mut open = std::fs::OpenOptions::new();
        open.create(true).write(true).truncate(false);
        #[cfg(unix)]
        {
            use std::os::unix::fs::OpenOptionsExt;
            open.mode(0o600);
        }
        let file = open.open(&lock_path)?;
        FileExt::lock_exclusive(&file)?;
        Ok(Self { _file: Some(file) })
    }
}

/// Write a single `key = value` pair to `~/.synaps-cli/config` (or profile config).
/// Replaces the first existing line that matches the key, or appends if absent.
/// Preserves comments and unknown keys. Writes atomically via temp file + rename.
pub fn write_config_value(key: &str, value: &str) -> std::io::Result<()> {
    let _guard = ConfigLock::acquire()?;
    write_config_value_locked(key, value)
}

/// The RMW body; caller holds [`ConfigLock`].
fn write_config_value_locked(key: &str, value: &str) -> std::io::Result<()> {
    let path = resolve_write_path("config");
    let existing = std::fs::read_to_string(&path).unwrap_or_default();

    let key_trimmed = key.trim();
    let replacement = format!("{} = {}", key_trimmed, value);

    let mut found = false;
    let mut new_lines: Vec<String> = existing
        .lines()
        .map(|line| {
            if found {
                return line.to_string();
            }
            let t = line.trim_start();
            if t.starts_with('#') || t.is_empty() {
                return line.to_string();
            }
            if let Some((k, _)) = t.split_once('=') {
                if k.trim() == key_trimmed {
                    found = true;
                    return replacement.clone();
                }
            }
            line.to_string()
        })
        .collect();

    if !found {
        new_lines.push(replacement);
    }

    let mut out = new_lines.join("\n");
    if !out.ends_with('\n') {
        out.push('\n');
    }

    let tmp = path.with_extension("tmp");
    std::fs::write(&tmp, out)?;
    // Config may contain API keys — restrict to owner-only
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o600))?;
    }
    std::fs::rename(&tmp, &path)?;
    Ok(())
}

/// Add a favorite model id (`provider/model`) to config, preserving sort/dedup.
pub fn add_favorite_model(id: &str) -> std::io::Result<()> {
    let trimmed = id.trim();
    if trimmed.is_empty() {
        return Ok(());
    }
    let _guard = ConfigLock::acquire()?;
    let mut values = load_config().favorite_models;
    if !values.iter().any(|v| v == trimmed) {
        values.push(trimmed.to_string());
        values.sort();
    }
    write_comma_list_locked("favorite_models", &values)
}

/// Remove a favorite model id (`provider/model`) from config.
pub fn remove_favorite_model(id: &str) -> std::io::Result<()> {
    let _guard = ConfigLock::acquire()?;
    let mut values = load_config().favorite_models;
    values.retain(|v| v != id.trim());
    write_comma_list_locked("favorite_models", &values)
}

/// Return whether a model id is marked as favorite.
pub fn is_favorite_model(id: &str) -> bool {
    load_config().favorite_models.iter().any(|v| v == id.trim())
}

/// Whether a key matches the secret denylist (case-insensitive).
/// Used by the journal save path to ensure secret values never reach disk,
/// and by the client env capture to strip secrets before `Hello`.
pub fn is_secret_key(key: &str) -> bool {
    let upper = key.to_ascii_uppercase();
    upper.ends_with("_KEY")
        || upper.ends_with("_TOKEN")
        || upper.ends_with("_CREDENTIALS")
        || upper.ends_with("_API_KEY")
        || upper.contains("SECRET")
        || upper.contains("PASSWORD")
        || upper.contains("PASSWD")
        || upper.ends_with("_PAT")
        || upper.ends_with("_DSN")
}

/// Whether an env VALUE carries a credential regardless of its key name:
/// any URL with userinfo (`scheme://user:pass@host`, `scheme://key@host`),
/// anywhere in the value — `DATABASE_URL`, `HTTPS_PROXY`, a Sentry DSN or a
/// JDBC option string all qualify. The key-name denylist alone missed these,
/// so their credentials reached the daemon and the session files on disk.
/// A username-only URL (`ssh://git@host/…`) is treated as a secret too:
/// rare in an environment, and failing safe beats a guess.
pub fn is_secret_env_value(value: &str) -> bool {
    let mut rest = value;
    while let Some(i) = rest.find("://") {
        let scheme_ok = rest[..i]
            .chars()
            .next_back()
            .is_some_and(|c| c.is_ascii_alphanumeric());
        let after = &rest[i + 3..];
        // The authority ends at the path, query or fragment, or at a list /
        // option separator when several URLs share one value.
        let end = after
            .find(|c: char| {
                matches!(c, '/' | '?' | '#' | ',' | ';' | '"' | '\'') || c.is_whitespace()
            })
            .unwrap_or(after.len());
        if scheme_ok && after[..end].rfind('@').is_some_and(|at| at > 0) {
            return true;
        }
        rest = after;
    }
    false
}

/// Whether an env pair must never reach the daemon or disk: a secret key
/// name OR a value carrying credentials (see [`is_secret_env_value`]).
pub fn is_secret_env(key: &str, value: &str) -> bool {
    is_secret_key(key) || is_secret_env_value(value)
}

/// Resolve the system prompt from CLI flag, config file, or default.
/// Priority: explicit value > ~/.synaps-cli/system.md > built-in default.
pub fn resolve_system_prompt(explicit: Option<&str>) -> String {
    #[cfg(windows)]
    const DEFAULT_PROMPT: &str = "You are a helpful AI agent running in a terminal on Windows. \
        You have access to powershell, bash, read, and write tools. \
        Prefer the powershell tool for system commands and filesystem operations — it is native \
        to Windows and avoids quoting/path translation issues. \
        Use bash only when the task specifically requires WSL or a Unix environment. \
        Be concise and direct. Use tools when the user asks you to interact with the filesystem or run commands.";
    #[cfg(not(windows))]
    const DEFAULT_PROMPT: &str = "You are a helpful AI agent running in a terminal. \
        You have access to bash, read, and write tools. \
        Be concise and direct. Use tools when the user asks you to interact with the filesystem or run commands.";

    if let Some(val) = explicit {
        let path = std::path::Path::new(val);
        if path.exists() && path.is_file() {
            return std::fs::read_to_string(path).unwrap_or_else(|_| val.to_string());
        }
        return val.to_string();
    }

    let system_path = resolve_read_path("system.md");
    if system_path.exists() {
        return std::fs::read_to_string(&system_path).unwrap_or_default();
    }

    DEFAULT_PROMPT.to_string()
}

#[cfg(test)]
mod tests {
    #[test]
    fn secret_env_value_detects_credential_urls() {
        use super::is_secret_env_value as v;
        // user:password in the authority
        assert!(v("postgres://app:hunter2@db.internal:5432/prod"));
        assert!(v("redis://:pw@cache:6379/0"));
        assert!(v("http://user:pass@proxy.corp:3128"));
        assert!(v(
            "mongodb+srv://u:p@cluster0.example.net/db?retryWrites=true"
        ));
        // a key as the username, no password (Sentry DSN)
        assert!(v("https://abc123def456@o1.ingest.sentry.io/42"));
        // anywhere in the value, not only at the start; lists
        assert!(v("-Dspring.datasource.url=jdbc:postgresql://u:p@h/db"));
        assert!(v("redis://h1:6379,redis://u:p@h2:6379"));
        // no userinfo → not a secret
        assert!(!v("https://api.example.com/v1/items?q=a@b"));
        assert!(!v("http://host/path/with@sign"));
        assert!(!v("https://@host/empty-userinfo"));
        assert!(!v("git@github.com:org/repo.git"));
        assert!(!v("mailto:someone@example.com"));
        assert!(!v("someone@example.com"));
        assert!(!v("/usr/local/bin:/usr/bin"));
        assert!(!v(""));
    }

    #[test]
    fn secret_key_covers_pat_and_dsn() {
        assert!(super::is_secret_key("GITHUB_PAT"));
        assert!(super::is_secret_key("gh_pat"));
        assert!(super::is_secret_key("SENTRY_DSN"));
        assert!(!super::is_secret_key("PATH"));
        assert!(!super::is_secret_key("PATTERN_DIR"));
    }

    #[test]
    fn secret_env_is_key_or_value() {
        assert!(super::is_secret_env(
            "DATABASE_URL",
            "postgres://app:hunter2@db/prod"
        ));
        assert!(super::is_secret_env("GH_TOKEN", "anything"));
        assert!(!super::is_secret_env("DATABASE_URL", "postgres://db/prod"));
        assert!(!super::is_secret_env("HOME", "/home/u"));
    }
    #[test]
    fn startup_and_daemon_defaults() {
        let c = super::load_config_from_str("");
        assert!(c.startup.quick_start, "quick_start defaults ON");
        assert_eq!(c.startup.extensions_ready_timeout_secs, 30);
        assert_eq!(c.daemon.idle_exit_secs, 10);
        assert_eq!(c.daemon.prompt_abandon_secs, 3600);
        assert_eq!(c.daemon.parked_evict_secs, 3600);
        // No warnings for the absent keys.
        assert!(c.warnings.is_empty(), "warnings: {:?}", c.warnings);
    }

    #[test]
    fn startup_and_daemon_parse_all_keys() {
        let c = super::load_config_from_str(concat!(
            "startup.quick_start = off\n",
            "startup.extensions_ready_timeout_secs = 45\n",
            "daemon.idle_exit_secs = 20\n",
            "daemon.prompt_abandon_secs = 0\n",
            "daemon.parked_evict_secs = 120\n",
        ));
        assert!(!c.startup.quick_start);
        assert_eq!(c.startup.extensions_ready_timeout_secs, 45);
        assert_eq!(c.daemon.idle_exit_secs, 20);
        assert_eq!(c.daemon.prompt_abandon_secs, 0);
        assert_eq!(c.daemon.parked_evict_secs, 120);
        assert!(
            !c.warnings.iter().any(|w| w.contains("unknown")),
            "no unknown-key warning: {:?}",
            c.warnings
        );
    }

    #[test]
    fn startup_quick_start_accepts_on() {
        let c = super::load_config_from_str("startup.quick_start = on\n");
        assert!(c.startup.quick_start);
    }

    #[test]
    fn startup_and_daemon_keys_are_known() {
        for k in [
            "startup.quick_start",
            "startup.extensions_ready_timeout_secs",
            "daemon.idle_exit_secs",
            "daemon.prompt_abandon_secs",
            "daemon.parked_evict_secs",
        ] {
            assert!(super::KNOWN_CONFIG_KEYS.contains(&k), "{k} not in KNOWN_CONFIG_KEYS");
        }
    }

    #[test]
    fn startup_daemon_bad_values_warn_and_keep_defaults() {
        let c = super::load_config_from_str(concat!(
            "startup.quick_start = maybe\n",
            "daemon.idle_exit_secs = soon\n",
        ));
        assert!(c.startup.quick_start, "invalid bool keeps default");
        assert_eq!(c.daemon.idle_exit_secs, 10, "invalid u64 keeps default");
        assert!(c.warnings.iter().any(|w| w.contains("startup.quick_start")));
        assert!(c.warnings.iter().any(|w| w.contains("daemon.idle_exit_secs")));
    }

    #[test]
    fn context_management_defaults_off_and_parses_all_keys() {
        use super::{ContextManagementConfig, ContextManagementMode};
        assert_eq!(
            super::load_config_from_str("").context_management,
            ContextManagementConfig::default()
        );
        let parsed = super::load_config_from_str(
            "context_management.mode = AUTO\n\
             context_management.pressure_tokens = 250000\n\
             context_management.rollover_tokens = 400000\n\
             context_management.reserve_tokens = 24000\n\
             context_management.finish_rounds = 3\n\
             context_window = 1m\n",
        );
        assert_eq!(
            parsed.context_management,
            ContextManagementConfig {
                mode: ContextManagementMode::Auto,
                pressure_tokens: Some(250_000),
                rollover_tokens: Some(400_000),
                reserve_tokens: 24_000,
                finish_rounds: 3,
            }
        );
        assert!(parsed.warnings.is_empty(), "{:?}", parsed.warnings);
        assert!(parsed.provider_keys.is_empty());
        assert!(super::load_config_from_str("context_management.mode = off")
            .warnings
            .is_empty());
    }

    #[test]
    fn context_management_auto_clears_overrides_and_allows_bounded_extremes() {
        for rounds in [0, super::ContextManagementConfig::MAX_FINISH_ROUNDS] {
            let parsed = super::load_config_from_str(&format!(
                "context_management.mode = auto\n\
                 context_management.pressure_tokens = 300000\n\
                 context_management.rollover_tokens = 450000\n\
                 context_management.pressure_tokens = auto\n\
                 context_management.rollover_tokens = AUTO\n\
                 context_management.finish_rounds = {rounds}\n"
            ));
            assert_eq!(parsed.context_management.pressure_tokens, None);
            assert_eq!(parsed.context_management.rollover_tokens, None);
            assert_eq!(parsed.context_management.finish_rounds, rounds);
            assert!(parsed.warnings.is_empty());
        }
    }

    #[test]
    fn context_management_invalid_values_reset_entire_policy() {
        for (key, value) in [
            ("mode", "on"),
            ("pressure_tokens", "0"),
            ("pressure_tokens", "-1"),
            ("pressure_tokens", "250k"),
            ("pressure_tokens", "18446744073709551616"),
            ("rollover_tokens", "1"),
            ("rollover_tokens", "nope"),
            ("reserve_tokens", "0"),
            ("reserve_tokens", "1000001"),
            ("reserve_tokens", "auto"),
            ("finish_rounds", "9"),
            ("finish_rounds", "-1"),
            ("finish_rounds", "4294967296"),
            ("finish_rounds", ""),
            ("mod", "auto"),
        ] {
            let parsed = super::load_config_from_str(&format!(
                "context_management.mode = auto\ncontext_management.{key} = {value}\n"
            ));
            assert_eq!(
                parsed.context_management,
                super::ContextManagementConfig::default(),
                "{key}={value}"
            );
            assert!(!parsed.warnings.is_empty(), "{key}={value}");
            assert!(parsed.provider_keys.is_empty());
        }
        let duplicate = super::load_config_from_str(
            "context_management.mode = auto\ncontext_management.finish_rounds = bad\ncontext_management.finish_rounds = 2"
        );
        assert_eq!(
            duplicate.context_management,
            super::ContextManagementConfig::default()
        );
    }

    #[test]
    fn context_management_validates_final_threshold_order_and_window() {
        for fields in [
            "pressure_tokens = 400000\ncontext_management.rollover_tokens = 400000",
            "pressure_tokens = 500000\ncontext_management.rollover_tokens = 400000",
            "pressure_tokens = 1000000",
            "rollover_tokens = 1000001",
        ] {
            for window_first in [false, true] {
                let policy =
                    format!("context_management.mode = auto\ncontext_management.{fields}\n");
                let content = if window_first {
                    format!("context_window = 1m\n{policy}")
                } else {
                    format!("{policy}context_window = 1m\n")
                };
                let parsed = super::load_config_from_str(&content);
                assert_eq!(
                    parsed.context_management,
                    super::ContextManagementConfig::default()
                );
                assert!(!parsed.warnings.is_empty());
            }
        }
        // Temporarily reversed overrides are valid once the whole file is parsed.
        let parsed = super::load_config_from_str(
            "context_management.mode = auto\n\
             context_management.rollover_tokens = 100000\n\
             context_management.pressure_tokens = 300000\n\
             context_management.rollover_tokens = 450000\ncontext_window = 1m",
        );
        assert!(parsed.warnings.is_empty());
        assert_eq!(parsed.context_management.rollover_tokens, Some(450_000));
    }

    #[test]
    fn context_management_parsed_finish_override_bounds_rollover_extension() {
        use crate::core::context_policy::{
            assess_context, ContextAction, ContextBudget, ContextState, WorkPhase,
        };
        let config = super::load_config_from_str(
            "context_management.mode = auto\n\
             context_management.finish_rounds = 1\ncontext_window = 1m",
        );
        let budget = ContextBudget {
            context_window_tokens: 1_000_000,
            used_tokens: 400_000,
            hard_remaining_tokens: 600_000,
            required_next_round_tokens: 8_000,
        };
        let mut state = ContextState::default();
        state.report_phase(WorkPhase::Plan);
        let first = assess_context(&config.context_management, &state, budget);
        assert_eq!(
            first.action,
            ContextAction::FinishBounded {
                rounds_remaining: 0
            }
        );
        state = first.next_state;
        state.report_phase(WorkPhase::WrapUp);
        assert_eq!(
            assess_context(&config.context_management, &state, budget).action,
            ContextAction::Rollover
        );
    }

    #[test]
    fn context_management_keys_are_known_for_suggestions() {
        for key in [
            "mode",
            "pressure_tokens",
            "rollover_tokens",
            "reserve_tokens",
            "finish_rounds",
        ] {
            let full = format!("context_management.{key}");
            assert!(super::KNOWN_CONFIG_KEYS.contains(&full.as_str()));
            assert_eq!(
                super::did_you_mean(&format!("{full}x")),
                Some(full.as_str())
            );
        }
    }

    #[test]
    fn context_management_parsed_policy_rolls_over_before_executing_350k_plan() {
        use crate::core::context_policy::{
            assess_context, ContextAction, ContextBudget, ContextState, WorkPhase,
        };
        let config =
            super::load_config_from_str("context_management.mode = auto\ncontext_window = 1m");
        let budget = ContextBudget {
            context_window_tokens: config.context_window.unwrap(),
            used_tokens: 350_000,
            hard_remaining_tokens: 650_000,
            required_next_round_tokens: 8_000,
        };
        let mut state = ContextState::default();
        state.report_phase(WorkPhase::Plan);
        let plan = assess_context(&config.context_management, &state, budget);
        assert_eq!(plan.action, ContextAction::Advisory);
        state = plan.next_state;
        state.report_phase(WorkPhase::Execute);
        assert_eq!(
            assess_context(&config.context_management, &state, budget).action,
            ContextAction::Rollover
        );
    }

    #[test]
    fn tui_streaming_glow_defaults_off_and_parses() {
        assert!(!super::load_config_from_str("").tui_streaming_glow);
        assert!(super::load_config_from_str("tui_streaming_glow = on\n").tui_streaming_glow);
        assert!(!super::load_config_from_str("tui_streaming_glow = off\n").tui_streaming_glow);
        let invalid = super::load_config_from_str("tui_streaming_glow = sparkly\n");
        assert!(
            !invalid.tui_streaming_glow,
            "invalid keeps the default (off)"
        );
        assert!(invalid
            .warnings
            .iter()
            .any(|w| w.contains("tui_streaming_glow")));
    }

    #[test]
    fn tui_background_opaque_defaults_and_parses_supported_values() {
        assert!(super::load_config_from_str("").tui_background_opaque);
        assert!(
            super::load_config_from_str("tui_background_opaque = opaque\n").tui_background_opaque
        );
        assert!(
            !super::load_config_from_str("tui_background_opaque = invisible\n")
                .tui_background_opaque
        );
        let invalid = super::load_config_from_str("tui_background_opaque = translucent\n");
        assert!(invalid.tui_background_opaque);
        assert!(invalid
            .warnings
            .iter()
            .any(|w| w.contains("tui_background_opaque")));
    }

    #[test]
    fn turn_budget_keys_parse_typed_per_role() {
        let config = super::load_config_from_str(
            "turn_budget.worker.max_provider_rounds = 3\n\
             turn_budget.worker.max_cost_usd = 0.25\n\
             turn_budget.autonomous.max_elapsed_secs = 90\n\
             turn_budget.foreground.max_tool_calls = 7\n\
             turn_budget.foreground.max_round_renewals = 12\n\
             turn_budget.worker.max_provider_rounds_bogus = 1\n\
             turn_budget.nosuchrole.max_tool_calls = 1\n",
        );
        assert_eq!(config.turn_budgets.worker.max_provider_rounds, Some(3));
        assert_eq!(config.turn_budgets.worker.max_cost_usd, Some(0.25));
        assert_eq!(config.turn_budgets.autonomous.max_elapsed_secs, Some(90));
        assert_eq!(config.turn_budgets.foreground.max_tool_calls, Some(7));
        assert_eq!(config.turn_budgets.foreground.max_round_renewals, Some(12));
        // Unknown fields/roles warn and change nothing.
        assert_eq!(config.turn_budgets.worker.max_tool_calls, None);
        // Invalid values keep the default (None).
        let bad = super::load_config_from_str("turn_budget.worker.max_provider_rounds = nope\n");
        assert_eq!(bad.turn_budgets.worker.max_provider_rounds, None);
    }

    #[test]
    fn memory_keys_all_parse_with_consent() {
        let config = super::load_config_from_str(
            "memory.default_mode = capture_and_recall\n\
             memory.default_mode_confirmed = true\n\
             memory.recall_max_records = 12\n\
             memory.recall_max_tokens = 2048\n\
             memory.recall_timeout_ms = 250\n\
             memory.capture_tools = off\n\
             memory.capture_assistant = false\n\
             memory.capture_user = false\n\
             memory.auto_consolidate = on\n\
             memory.local_embeddings = on\n\
             memory.gliner = on\n",
        );
        assert_eq!(config.memory.default_mode, "capture_and_recall");
        assert!(config.memory.default_mode_confirmed);
        assert_eq!(config.memory.recall_max_records, 12);
        assert_eq!(config.memory.recall_max_tokens, 2048);
        assert_eq!(config.memory.recall_timeout_ms, 250);
        assert_eq!(config.memory.capture_tools, "off");
        assert!(!config.memory.capture_assistant);
        assert!(!config.memory.capture_user);
        assert_eq!(config.memory.auto_consolidate, "on");
        assert_eq!(config.memory.local_embeddings, "on");
        assert_eq!(config.memory.gliner, "on");
    }

    #[test]
    fn memory_defaults_match_spec_12() {
        let config = super::load_config_from_str("");
        assert_eq!(config.memory, super::MemoryConfig::default());
        assert_eq!(config.memory.default_mode, "off");
        assert!(!config.memory.default_mode_confirmed);
        assert_eq!(config.memory.recall_max_records, 8);
        assert_eq!(config.memory.recall_max_tokens, 4096);
        assert_eq!(config.memory.recall_timeout_ms, 150);
        assert_eq!(config.memory.capture_tools, "summary_only");
        assert!(config.memory.capture_assistant);
        assert!(config.memory.capture_user);
        assert_eq!(config.memory.auto_consolidate, "off");
        assert_eq!(config.memory.local_embeddings, "off");
        assert_eq!(config.memory.gliner, "off");
    }

    #[test]
    fn memory_unknown_values_fail_closed_to_defaults() {
        let config = super::load_config_from_str(
            "memory.default_mode = recall_everything_forever\n\
             memory.default_mode_confirmed = true\n\
             memory.recall_max_records = lots\n\
             memory.recall_max_tokens = -5\n\
             memory.recall_timeout_ms = fast\n\
             memory.capture_tools = full\n\
             memory.capture_assistant = maybe\n\
             memory.capture_user = sometimes\n\
             memory.auto_consolidate = aggressive\n\
             memory.local_embeddings = auto\n\
             memory.gliner = download\n\
             memory.nosuchfield = 1\n",
        );
        // Unrecognised mode string must stay "off" — never a non-off mode.
        assert_eq!(config.memory.default_mode, "off");
        assert_eq!(config.memory.recall_max_records, 8);
        assert_eq!(config.memory.recall_max_tokens, 4096);
        assert_eq!(config.memory.recall_timeout_ms, 150);
        assert_eq!(config.memory.capture_tools, "summary_only");
        assert!(config.memory.capture_assistant);
        assert!(config.memory.capture_user);
        assert_eq!(config.memory.auto_consolidate, "off");
        assert_eq!(config.memory.local_embeddings, "off");
        assert_eq!(config.memory.gliner, "off");
    }

    #[test]
    fn memory_default_mode_without_consent_reverts_to_off() {
        let config = super::load_config_from_str("memory.default_mode = recall_each_prompt\n");
        assert_eq!(config.memory.default_mode, "off");
        assert!(
            config
                .warnings
                .iter()
                .any(|w| w.contains("memory.default_mode_confirmed")),
            "reversion must surface a warning; got: {:?}",
            config.warnings
        );

        // Explicit false consent is not consent.
        let denied = super::load_config_from_str(
            "memory.default_mode = capture_only\n\
             memory.default_mode_confirmed = false\n",
        );
        assert_eq!(denied.memory.default_mode, "off");

        // Garbage consent value fails closed — not consent.
        let garbage = super::load_config_from_str(
            "memory.default_mode = capture_only\n\
             memory.default_mode_confirmed = definitely\n",
        );
        assert_eq!(garbage.memory.default_mode, "off");
    }

    #[test]
    fn memory_consent_is_order_independent() {
        // Consent key before the mode key.
        let before = super::load_config_from_str(
            "memory.default_mode_confirmed = true\n\
             memory.default_mode = recall_once\n",
        );
        assert_eq!(before.memory.default_mode, "recall_once");
        // Consent key after the mode key.
        let after = super::load_config_from_str(
            "memory.default_mode = recall_once\n\
             memory.default_mode_confirmed = true\n",
        );
        assert_eq!(after.memory.default_mode, "recall_once");
    }

    #[test]
    fn memory_backend_defaults_are_independent_of_consent() {
        let config = super::load_config_from_str("");
        assert_eq!(config.memory_backend, super::MemoryBackendConfig::default());
        assert_eq!(config.memory_backend.kind, super::MemoryBackendKind::Legacy);
        let axel = super::load_config_from_str("memory.backend = axel\n");
        assert_eq!(axel.memory_backend.kind, super::MemoryBackendKind::Axel);
        assert_eq!(axel.memory, config.memory);
        assert!(axel.warnings.is_empty());
    }

    #[test]
    fn user_wide_notes_require_explicit_valid_opt_in() {
        let default = super::load_config_from_str("memory.backend = axel\n");
        assert!(!default.memory_backend.user_scope);
        let enabled =
            super::load_config_from_str("memory.backend = axel\nmemory.user_scope = true\n");
        assert!(enabled.memory_backend.user_scope);
        assert_eq!(enabled.memory, default.memory);
        for bad in ["yes", "", "1", "TRUE"] {
            let config = super::load_config_from_str(&format!(
                "memory.user_scope = {bad}\nmemory.backend = axel\n"
            ));
            assert_eq!(
                config.memory_backend.kind,
                super::MemoryBackendKind::Unavailable
            );
        }
    }

    #[test]
    fn memory_backend_invalid_selector_fails_closed() {
        for content in [
            "memory.backend = typo\n",
            "memory.backend = \n",
            "memory.backend = unavailable\n",
            "memory.backend = axel\nmemory.backend = typo\n",
            "memory.backend = typo\nmemory.backend = legacy\n",
        ] {
            let config = super::load_config_from_str(content);
            assert_eq!(
                config.memory_backend.kind,
                super::MemoryBackendKind::Unavailable
            );
            assert!(config
                .warnings
                .iter()
                .any(|w| w.contains("memory backend unavailable")));
        }
    }

    #[test]
    fn memory_backend_absolute_paths_are_preserved() {
        let root = std::env::current_dir().unwrap();
        let executable = root.join("fixture bin/axel");
        let brain = root.join("fixture brain");
        let config = super::load_config_from_str(&format!(
            "memory.axel.brain = {}\nmemory.backend = axel\nmemory.axel.executable = {}\n",
            brain.display(),
            executable.display()
        ));
        assert_eq!(config.memory_backend.kind, super::MemoryBackendKind::Axel);
        assert_eq!(config.memory_backend.executable, Some(executable));
        assert_eq!(config.memory_backend.brain, Some(brain));
        assert!(config.warnings.is_empty());
    }

    #[test]
    fn memory_backend_relative_or_empty_paths_fail_closed_in_any_order() {
        for key in ["memory.axel.executable", "memory.axel.brain"] {
            for path in ["relative/path", "~/brain", ""] {
                for content in [
                    format!("memory.backend = axel\n{key} = {path}\n"),
                    format!("{key} = {path}\nmemory.backend = legacy\n"),
                ] {
                    let config = super::load_config_from_str(&content);
                    assert_eq!(
                        config.memory_backend.kind,
                        super::MemoryBackendKind::Unavailable
                    );
                    assert!(config.warnings.iter().any(|w| w.contains("absolute path")));
                }
            }
        }
    }

    #[test]
    fn memory_config_surface_is_closed_by_construction() {
        // Exhaustive struct literal — no `..Default::default()` spread. This
        // fails to COMPILE if any field is added to or removed from
        // MemoryConfig, pinning the exact memory.* config surface. Secret,
        // retention, and project-scope semantics have no field here, so no
        // `memory.secret*` / `memory.retention*` / `memory.project*` config
        // key can exist (spec §12: those rules are not configurable to fail
        // open). Asserted by construction, not by test disproof.
        let _closed_surface = super::MemoryConfig {
            default_mode: "off".to_string(),
            default_mode_confirmed: false,
            recall_max_records: 8,
            recall_max_tokens: 4096,
            recall_timeout_ms: 150,
            capture_tools: "summary_only".to_string(),
            capture_assistant: true,
            capture_user: true,
            auto_consolidate: "off".to_string(),
            local_embeddings: "off".to_string(),
            gliner: "off".to_string(),
        };
    }

    use super::*;
    use serial_test::serial;

    #[test]
    fn test_levenshtein_basics() {
        assert_eq!(levenshtein("model", "model"), 0);
        assert_eq!(levenshtein("modle", "model"), 2);
        assert_eq!(levenshtein("them", "theme"), 1);
    }

    #[test]
    fn test_did_you_mean_close_typos() {
        assert_eq!(did_you_mean("modle"), Some("model"));
        assert_eq!(did_you_mean("them"), Some("theme"));
        assert_eq!(did_you_mean("thinkng"), Some("thinking"));
        assert_eq!(did_you_mean("completely_unrelated_key"), None);
    }

    #[test]
    #[serial]
    fn test_config_warnings_unknown_key_and_bad_values() {
        let home = std::env::temp_dir().join(format!("synaps-warn-test-{}", std::process::id()));
        let dir = home.join(".synaps-cli");
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("config"), "modle = claude-opus-4-6\nthinking = hgih\nbash_timeout = 0\nknowledge.jawz_notes = ~/Jawz/notes\ncustom.plugin.key = 42\n").unwrap();

        with_home(&home, || {
            let config = load_config();
            // Dotted (namespaced) keys must NOT warn — plugins own those.
            assert_eq!(config.warnings.len(), 3, "warnings: {:?}", config.warnings);
            assert!(
                !config.warnings.iter().any(|w| w.contains("knowledge")),
                "{:?}",
                config.warnings
            );
            assert!(
                config
                    .warnings
                    .iter()
                    .any(|w| w.contains("did you mean 'model'")),
                "{:?}",
                config.warnings
            );
            assert!(
                config.warnings.iter().any(|w| w.contains("thinking")),
                "{:?}",
                config.warnings
            );
            assert!(
                config.warnings.iter().any(|w| w.contains("below minimum")),
                "{:?}",
                config.warnings
            );
            // Bad values fall back to defaults
            assert_eq!(config.bash_timeout, 30);
            assert_eq!(config.thinking_budget, None);
        });
        let _ = std::fs::remove_dir_all(&home);
    }

    // ── cache_ttl parse table (spec §3.1) ──

    #[test]
    fn test_cache_ttl_parse_table() {
        // 5m aliases
        assert_eq!(CacheTtl::parse("5m"), Some(CacheTtl::FiveMinutes));
        assert_eq!(CacheTtl::parse("5min"), Some(CacheTtl::FiveMinutes));
        assert_eq!(CacheTtl::parse("default"), Some(CacheTtl::FiveMinutes));
        // 1h aliases
        assert_eq!(CacheTtl::parse("1h"), Some(CacheTtl::OneHour));
        assert_eq!(CacheTtl::parse("60m"), Some(CacheTtl::OneHour));
        assert_eq!(CacheTtl::parse("1hr"), Some(CacheTtl::OneHour));
        // hybrid
        assert_eq!(CacheTtl::parse("hybrid"), Some(CacheTtl::Hybrid));
        // case-insensitive
        assert_eq!(CacheTtl::parse("1H"), Some(CacheTtl::OneHour));
        assert_eq!(CacheTtl::parse("HYBRID"), Some(CacheTtl::Hybrid));
        assert_eq!(CacheTtl::parse("Default"), Some(CacheTtl::FiveMinutes));
        // garbage → None (caller warns + defaults)
        assert_eq!(CacheTtl::parse("2h"), None);
        assert_eq!(CacheTtl::parse(""), None);
        assert_eq!(CacheTtl::parse("forever"), None);
    }

    #[test]
    fn test_cache_ttl_default_is_five_minutes() {
        assert_eq!(CacheTtl::default(), CacheTtl::FiveMinutes);
        assert_eq!(SynapsConfig::default().cache_ttl, CacheTtl::FiveMinutes);
    }

    #[test]
    fn test_max_fps_default_is_60() {
        assert_eq!(SynapsConfig::default().max_fps, 60);
    }

    // ── theme_transition parse table (animated theme transitions) ──

    #[test]
    fn test_theme_transition_parse_table() {
        use ThemeTransitionMode as M;
        assert_eq!(M::parse("on"), Some(M::On));
        assert_eq!(M::parse("ON"), Some(M::On));
        assert_eq!(M::parse("off"), Some(M::Off));
        assert_eq!(M::parse("Off"), Some(M::Off));
        // integer ms, clamped to 0..=2000
        assert_eq!(M::parse("500"), Some(M::Ms(500)));
        assert_eq!(M::parse("0"), Some(M::Ms(0)));
        assert_eq!(M::parse("2000"), Some(M::Ms(2000)));
        assert_eq!(M::parse("99999"), Some(M::Ms(2000)), "clamped to MAX_MS");
        // garbage → None (caller warns + keeps default)
        assert_eq!(M::parse("fast"), None);
        assert_eq!(M::parse(""), None);
        assert_eq!(M::parse("-5"), None);
        assert_eq!(M::parse("1.5"), None);
    }

    #[test]
    fn test_theme_transition_duration_ms() {
        use ThemeTransitionMode as M;
        assert_eq!(M::On.duration_ms(), M::DEFAULT_MS);
        assert_eq!(M::DEFAULT_MS, 350);
        assert_eq!(M::Off.duration_ms(), 0);
        assert_eq!(M::Ms(120).duration_ms(), 120);
        assert_eq!(M::Ms(0).duration_ms(), 0, "0 ms behaves like off");
        assert_eq!(M::Ms(u64::MAX).duration_ms(), M::MAX_MS);
    }

    #[test]
    fn test_theme_transition_config_key_parses_and_defaults() {
        use ThemeTransitionMode as M;
        assert_eq!(SynapsConfig::default().theme_transition, M::On);
        assert_eq!(
            super::load_config_from_str("theme_transition = off\n").theme_transition,
            M::Off
        );
        assert_eq!(
            super::load_config_from_str("theme_transition = 750\n").theme_transition,
            M::Ms(750)
        );
        let bad = super::load_config_from_str("theme_transition = warp\n");
        assert_eq!(bad.theme_transition, M::On, "bad value keeps default");
        assert!(
            bad.warnings.iter().any(|w| w.contains("theme_transition")),
            "{:?}",
            bad.warnings
        );
    }

    #[test]
    #[serial]
    fn test_max_fps_config_parse_and_validation() {
        let home = std::env::temp_dir().join(format!("synaps-maxfps-test-{}", std::process::id()));
        let dir = home.join(".synaps-cli");
        std::fs::create_dir_all(&dir).unwrap();

        // Valid high-refresh value parses, no warning.
        std::fs::write(dir.join("config"), "max_fps = 144\n").unwrap();
        with_home(&home, || {
            let config = load_config();
            assert_eq!(config.max_fps, 144);
            assert!(
                config.warnings.is_empty(),
                "warnings: {:?}",
                config.warnings
            );
        });

        // Out-of-range (0) → default 60 + boot warning (never blocks boot).
        std::fs::write(dir.join("config"), "max_fps = 0\n").unwrap();
        with_home(&home, || {
            let config = load_config();
            assert_eq!(config.max_fps, 60);
            assert!(
                config.warnings.iter().any(|w| w.contains("max_fps")),
                "warnings: {:?}",
                config.warnings
            );
        });

        // Non-numeric → default 60 + warning.
        std::fs::write(dir.join("config"), "max_fps = fast\n").unwrap();
        with_home(&home, || {
            let config = load_config();
            assert_eq!(config.max_fps, 60);
            assert!(
                config.warnings.iter().any(|w| w.contains("max_fps")),
                "warnings: {:?}",
                config.warnings
            );
        });

        let _ = std::fs::remove_dir_all(&home);
    }

    #[test]
    #[serial]
    fn test_cache_ttl_config_parse_and_garbage_warning() {
        let home =
            std::env::temp_dir().join(format!("synaps-cachettl-test-{}", std::process::id()));
        let dir = home.join(".synaps-cli");
        std::fs::create_dir_all(&dir).unwrap();

        // Valid value parses, no warning.
        std::fs::write(dir.join("config"), "cache_ttl = hybrid\n").unwrap();
        with_home(&home, || {
            let config = load_config();
            assert_eq!(config.cache_ttl, CacheTtl::Hybrid);
            assert!(
                config.warnings.is_empty(),
                "warnings: {:?}",
                config.warnings
            );
        });

        // Garbage value → 5m default + boot warning (never blocks boot).
        std::fs::write(dir.join("config"), "cache_ttl = 2h\n").unwrap();
        with_home(&home, || {
            let config = load_config();
            assert_eq!(config.cache_ttl, CacheTtl::FiveMinutes);
            assert!(
                config.warnings.iter().any(|w| w.contains("cache_ttl")),
                "warnings: {:?}",
                config.warnings
            );
        });

        let _ = std::fs::remove_dir_all(&home);
    }

    #[test]
    fn test_parse_thinking_budget() {
        use crate::core::reasoning::ThinkingSpec;
        // ThinkingSpec::parse replaced parse_thinking_budget; verify budget values.
        assert_eq!(ThinkingSpec::parse("low").unwrap().to_budget(), Some(2048));
        assert_eq!(
            ThinkingSpec::parse("medium").unwrap().to_budget(),
            Some(4096)
        );
        assert_eq!(
            ThinkingSpec::parse("high").unwrap().to_budget(),
            Some(16384)
        );
        assert_eq!(
            ThinkingSpec::parse("xhigh").unwrap().to_budget(),
            Some(32768)
        );
        assert_eq!(ThinkingSpec::parse("8192").unwrap().to_budget(), Some(8192));
        let config = load_config_from_str("thinking = 8192\n");
        assert_eq!(config.thinking_level, None);
        assert_eq!(config.thinking_budget, Some(8192));
        assert_eq!(ThinkingSpec::parse("invalid"), None);
    }

    #[test]
    fn test_base_dir() {
        let path = base_dir();
        assert!(path.to_string_lossy().ends_with(".synaps-cli"));
    }

    #[test]
    fn test_resolve_system_prompt_explicit() {
        let result = resolve_system_prompt(Some("test prompt"));
        assert_eq!(result, "test prompt");
    }

    #[test]
    fn test_resolve_system_prompt_none() {
        let result = resolve_system_prompt(None);
        assert!(result.contains("helpful AI agent"));
    }

    // Note: test_load_config_nonexistent_file removed — HOME env var mutation
    // is not thread-safe and races with shell config tests. Coverage provided
    // by shell::config::tests::test_shell_config_from_file.

    #[test]
    fn test_synaps_config_default() {
        let config = SynapsConfig::default();
        assert_eq!(config.model, None);
        assert_eq!(config.thinking_budget, None);
        assert_eq!(config.max_tool_output, 30000);
        assert_eq!(config.bash_timeout, 30);
        assert_eq!(config.bash_max_timeout, 300);
        assert_eq!(config.subagent_timeout, 300);
        assert_eq!(config.api_retries, 3);
        assert_eq!(config.theme, None);
        assert!(config.disabled_plugins.is_empty());
        assert!(config.favorite_models.is_empty());
        assert!(config.disabled_skills.is_empty());
        assert!(!config.progressive_tool_disclosure);
        assert_eq!(config.tools_activation_confirm, ActivationConfirm::Auto);
        assert_eq!(config.shell.max_sessions, 5);
        assert_eq!(config.shell.idle_timeout.as_secs(), 600);
        // Server config defaults
        assert!(config.server.allowed_origins.is_empty());
        assert_eq!(config.server.token, None);
        assert!(!config.server.auto_approve_confirms);
        assert_eq!(config.server.max_message_size, None);
        // Bridge config defaults
        assert!(config.bridge.uds_path.is_none());
        assert!(!config.bridge.heartbeat_mirror);
        assert_eq!(config.bridge.heartbeat_timeout_ms, 250);
    }

    #[test]
    #[serial]
    fn test_load_config_tools_activation_confirm_modes() {
        for (raw, expected, warns) in [
            ("prompt", ActivationConfirm::Prompt, false),
            ("deny", ActivationConfirm::Deny, false),
            ("AUTO", ActivationConfirm::Auto, false),
            ("garbage", ActivationConfirm::Auto, true),
        ] {
            let home = make_test_home(&format!("activation-confirm-{raw}"));
            let cfg = home.join(".synaps-cli/config");
            std::fs::write(&cfg, format!("tools.activation_confirm = {raw}\n")).unwrap();
            with_home(&home, || {
                let config = load_config();
                assert_eq!(config.tools_activation_confirm, expected, "{raw}");
                assert_eq!(
                    config.warnings.iter().any(|w| w.contains("tools.activation_confirm")),
                    warns,
                    "{raw}: {:?}",
                    config.warnings
                );
            });
            let _ = std::fs::remove_dir_all(&home);
        }
    }

    #[test]
    #[serial]
    fn test_load_config_progressive_tool_disclosure_is_opt_in() {
        let home = make_test_home("progressive-tool-disclosure");
        let cfg = home.join(".synaps-cli/config");
        std::fs::write(&cfg, "progressive_tool_disclosure = true\n").unwrap();

        with_home(&home, || {
            let config = load_config();
            assert!(config.progressive_tool_disclosure);
            assert!(config.warnings.is_empty());
        });

        let _ = std::fs::remove_dir_all(&home);
    }

    #[test]
    #[serial]
    fn test_load_config_bridge_keys() {
        let home = make_test_home("bridge-keys");
        let cfg = home.join(".synaps-cli/config");
        std::fs::write(
            &cfg,
            "\
bridge.uds_path = /tmp/some/control.sock\n\
bridge.heartbeat_mirror = true\n\
bridge.heartbeat_timeout_ms = 750\n\
",
        )
        .unwrap();

        with_home(&home, || {
            let config = load_config();
            assert_eq!(
                config.bridge.uds_path,
                Some(std::path::PathBuf::from("/tmp/some/control.sock")),
            );
            assert!(config.bridge.heartbeat_mirror);
            assert_eq!(config.bridge.heartbeat_timeout_ms, 750);
            assert_eq!(
                config.bridge.resolved_uds_path(),
                std::path::PathBuf::from("/tmp/some/control.sock"),
            );
        });

        let _ = std::fs::remove_dir_all(&home);
    }

    #[test]
    fn test_bridge_config_defaults() {
        let cfg = BridgeConfig::default();
        assert!(cfg.uds_path.is_none());
        assert!(!cfg.heartbeat_mirror);
        assert_eq!(cfg.heartbeat_timeout_ms, 250);
        // resolved path falls under base_dir()/bridge/control.sock
        let resolved = cfg.resolved_uds_path();
        assert!(resolved.ends_with("bridge/control.sock"));
    }

    #[test]
    #[serial]
    fn test_bridge_heartbeat_mirror_defaults_off_when_unset() {
        let home = make_test_home("bridge-default-off");
        let cfg = home.join(".synaps-cli/config");
        std::fs::write(&cfg, "model = claude-sonnet-4-6\n").unwrap();

        with_home(&home, || {
            let config = load_config();
            assert!(!config.bridge.heartbeat_mirror);
            assert!(config.bridge.uds_path.is_none());
            assert_eq!(config.bridge.heartbeat_timeout_ms, 250);
        });

        let _ = std::fs::remove_dir_all(&home);
    }

    #[test]
    fn compaction_disclosure_keys_parse_with_typed_warnings() {
        let config = load_config_from_str(
            "compaction_mode = local\ncompaction_exclude = thinking, tool_results, bogus\n",
        );
        assert_eq!(
            config.compaction_mode,
            crate::core::compaction::CompactionMode::LocalOnly
        );
        assert_eq!(
            config.compaction_exclude,
            vec![
                crate::core::compaction::ContentClass::Thinking,
                crate::core::compaction::ContentClass::ToolResults,
            ]
        );
        assert!(
            config.warnings.iter().any(|w| w.contains("bogus")),
            "unknown class must warn: {:?}",
            config.warnings
        );

        let defaults = load_config_from_str("");
        assert_eq!(
            defaults.compaction_mode,
            crate::core::compaction::CompactionMode::Remote
        );
        assert!(defaults.compaction_exclude.is_empty());

        let bad_mode = load_config_from_str("compaction_mode = cloud\n");
        assert_eq!(
            bad_mode.compaction_mode,
            crate::core::compaction::CompactionMode::Remote
        );
        assert!(bad_mode
            .warnings
            .iter()
            .any(|w| w.contains("compaction_mode")));
    }

    #[test]
    #[serial]
    fn test_load_config_server_keys() {
        let home = make_test_home("server-keys");
        let cfg = home.join(".synaps-cli/config");
        std::fs::write(
            &cfg,
            "\
server.allowed_origins = http://localhost:3000, http://localhost:5193\n\
server.token = my-secret-token\n\
server.auto_approve_confirms = true\n\
server.max_message_size = 65536\n\
context_window = 200k\n\
",
        )
        .unwrap();

        with_home(&home, || {
            let config = load_config();
            assert_eq!(
                config.server.allowed_origins,
                vec![
                    "http://localhost:3000".to_string(),
                    "http://localhost:5193".to_string(),
                ]
            );
            assert_eq!(config.server.token, Some("my-secret-token".to_string()));
            assert!(config.server.auto_approve_confirms);
            // Explicit max_message_size takes precedence over context_window derivation
            assert_eq!(config.server.max_message_size, Some(65536));
        });

        let _ = std::fs::remove_dir_all(&home);
    }

    #[test]
    #[serial]
    fn test_server_max_message_size_derived_from_context_window() {
        let home = make_test_home("server-derive");
        let cfg = home.join(".synaps-cli/config");
        std::fs::write(&cfg, "context_window = 200k\n").unwrap();

        with_home(&home, || {
            let config = load_config();
            // 200_000 tokens * 4 bytes/token = 800_000 bytes
            assert_eq!(config.server.max_message_size, Some(800_000));
        });

        let _ = std::fs::remove_dir_all(&home);
    }

    fn make_test_home(subdir: &str) -> std::path::PathBuf {
        let dir = std::path::PathBuf::from(format!("/tmp/synaps-write-test-{}", subdir));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(dir.join(".synaps-cli")).unwrap();
        dir
    }

    fn with_home<F: FnOnce()>(home: &std::path::Path, f: F) {
        // `base_dir()` reads SYNAPS_BASE_DIR before HOME: pin it too, or a value
        // another test left set redirects the write away from `home`.
        let original = std::env::var("HOME").ok();
        let original_base = std::env::var("SYNAPS_BASE_DIR").ok();
        std::env::set_var("HOME", home);
        std::env::set_var("SYNAPS_BASE_DIR", home.join(".synaps-cli"));
        f();
        if let Some(h) = original {
            std::env::set_var("HOME", h);
        } else {
            std::env::remove_var("HOME");
        }
        if let Some(b) = original_base {
            std::env::set_var("SYNAPS_BASE_DIR", b);
        } else {
            std::env::remove_var("SYNAPS_BASE_DIR");
        }
    }

    #[test]
    #[serial]
    fn write_config_value_replaces_existing_key() {
        let home = make_test_home("replace");
        let cfg = home.join(".synaps-cli/config");
        std::fs::write(&cfg, "model = claude-opus-4-6\nthinking = low\n").unwrap();

        with_home(&home, || {
            write_config_value("model", "claude-sonnet-4-6").unwrap();
        });

        let contents = std::fs::read_to_string(&cfg).unwrap();
        assert!(contents.contains("model = claude-sonnet-4-6"));
        assert!(contents.contains("thinking = low"));
        let _ = std::fs::remove_dir_all(&home);
    }

    #[test]
    #[serial]
    fn write_config_value_appends_when_missing() {
        let home = make_test_home("append");
        let cfg = home.join(".synaps-cli/config");
        std::fs::write(&cfg, "model = claude-opus-4-6\n").unwrap();

        with_home(&home, || {
            write_config_value("theme", "dracula").unwrap();
        });

        let contents = std::fs::read_to_string(&cfg).unwrap();
        assert!(contents.contains("model = claude-opus-4-6"));
        assert!(contents.contains("theme = dracula"));
        let _ = std::fs::remove_dir_all(&home);
    }

    #[test]
    #[serial]
    fn write_config_value_concurrent_writers_lose_nothing() {
        let home = make_test_home("concurrent");
        let cfg = home.join(".synaps-cli/config");
        std::fs::write(&cfg, "# keep\n").unwrap();

        // HOME is process-global; set it for the whole test, not per thread.
        with_home(&home, || {
            let a = std::thread::spawn(|| {
                for i in 0..200 {
                    write_config_value("a_key", &i.to_string()).unwrap();
                }
            });
            let b = std::thread::spawn(|| {
                for i in 0..200 {
                    write_config_value("b_key", &i.to_string()).unwrap();
                }
            });
            a.join().unwrap();
            b.join().unwrap();
        });

        let contents = std::fs::read_to_string(&cfg).unwrap();
        assert!(contents.contains("# keep"), "{contents}");
        assert!(contents.contains("a_key = 199"), "{contents}");
        assert!(contents.contains("b_key = 199"), "{contents}");
        assert_eq!(contents.matches("a_key").count(), 1);
        assert_eq!(contents.matches("b_key").count(), 1);

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let lock = home.join(".synaps-cli/config.lock");
            let mode = std::fs::metadata(&lock).unwrap().permissions().mode() & 0o777;
            assert_eq!(mode, 0o600);
        }
        let _ = std::fs::remove_dir_all(&home);
    }

    #[test]
    #[serial]
    fn config_lock_kill_switch_still_writes() {
        let home = make_test_home("lock-off");
        let cfg = home.join(".synaps-cli/config");
        std::env::set_var("SYNAPS_CONFIG_LOCK", "0");
        with_home(&home, || {
            write_config_value("model", "claude-sonnet-4-6").unwrap();
        });
        std::env::remove_var("SYNAPS_CONFIG_LOCK");
        let contents = std::fs::read_to_string(&cfg).unwrap();
        assert!(contents.contains("model = claude-sonnet-4-6"));
        assert!(!home.join(".synaps-cli/config.lock").exists());
        let _ = std::fs::remove_dir_all(&home);
    }

    #[test]
    #[serial]
    fn add_favorite_model_end_to_end_does_not_deadlock() {
        let home = make_test_home("favorite-lock");
        let cfg = home.join(".synaps-cli/config");
        with_home(&home, || {
            add_favorite_model("anthropic/claude-sonnet-4-6").unwrap();
            add_favorite_model("openai/gpt-5").unwrap();
            remove_favorite_model("anthropic/claude-sonnet-4-6").unwrap();
        });
        let contents = std::fs::read_to_string(&cfg).unwrap();
        assert!(contents.contains("favorite_models = openai/gpt-5"), "{contents}");
        let _ = std::fs::remove_dir_all(&home);
    }

    #[test]
    #[serial]
    fn write_config_value_preserves_comments() {
        let home = make_test_home("comments");
        let cfg = home.join(".synaps-cli/config");
        std::fs::write(&cfg, "# user comment\nmodel = claude-opus-4-6\n# another\n").unwrap();

        with_home(&home, || {
            write_config_value("model", "claude-sonnet-4-6").unwrap();
        });

        let contents = std::fs::read_to_string(&cfg).unwrap();
        assert!(contents.contains("# user comment"));
        assert!(contents.contains("# another"));
        assert!(contents.contains("model = claude-sonnet-4-6"));
        let _ = std::fs::remove_dir_all(&home);
    }

    #[test]
    #[serial]
    fn write_config_value_preserves_unknown_keys() {
        let home = make_test_home("unknown");
        let cfg = home.join(".synaps-cli/config");
        std::fs::write(&cfg, "custom_thing = 42\nmodel = claude-opus-4-6\n").unwrap();

        with_home(&home, || {
            write_config_value("model", "claude-sonnet-4-6").unwrap();
        });

        let contents = std::fs::read_to_string(&cfg).unwrap();
        assert!(contents.contains("custom_thing = 42"));
        let _ = std::fs::remove_dir_all(&home);
    }

    #[test]
    #[serial]
    fn write_config_value_creates_file_if_absent() {
        let home = make_test_home("create");
        let cfg = home.join(".synaps-cli/config");
        assert!(!cfg.exists());

        with_home(&home, || {
            write_config_value("model", "claude-sonnet-4-6").unwrap();
        });

        let contents = std::fs::read_to_string(&cfg).unwrap();
        assert!(contents.contains("model = claude-sonnet-4-6"));
        let _ = std::fs::remove_dir_all(&home);
    }

    #[test]
    #[serial]
    fn load_config_parses_theme_key() {
        let dir = std::path::PathBuf::from("/tmp/synaps-config-test-theme/.synaps-cli");
        let _ = std::fs::create_dir_all(&dir);
        std::fs::write(dir.join("config"), "theme = dracula\n").unwrap();

        let original_home = std::env::var("HOME").ok();
        std::env::set_var("HOME", "/tmp/synaps-config-test-theme");

        let config = load_config();

        if let Some(home) = original_home {
            std::env::set_var("HOME", home);
        } else {
            std::env::remove_var("HOME");
        }
        let _ = std::fs::remove_dir_all("/tmp/synaps-config-test-theme");

        assert_eq!(config.theme.as_deref(), Some("dracula"));
    }

    #[test]
    #[serial]
    fn test_load_config_disable_lists() {
        let test_dir =
            std::path::PathBuf::from("/tmp/synaps-config-test-disable-lists/.synaps-cli");
        let _ = std::fs::create_dir_all(&test_dir);
        let config_path = test_dir.join("config");

        let config_content = r#"
# Test config with disable lists
favorite_models = claude/claude-opus-4-7, groq/llama-3.3-70b-versatile

disabled_plugins = foo, bar
disabled_skills = baz, plug:qual
"#;
        std::fs::write(&config_path, config_content).unwrap();

        let original_home = std::env::var("HOME").ok();
        std::env::set_var("HOME", "/tmp/synaps-config-test-disable-lists");

        let config = load_config();

        if let Some(home) = original_home {
            std::env::set_var("HOME", home);
        } else {
            std::env::remove_var("HOME");
        }

        let _ = std::fs::remove_dir_all("/tmp/synaps-config-test-disable-lists");

        assert_eq!(
            config.disabled_plugins,
            vec!["foo".to_string(), "bar".to_string()]
        );
        assert_eq!(
            config.favorite_models,
            vec![
                "claude/claude-opus-4-7".to_string(),
                "groq/llama-3.3-70b-versatile".to_string(),
            ]
        );
        assert_eq!(
            config.disabled_skills,
            vec!["baz".to_string(), "plug:qual".to_string()]
        );
    }

    #[test]
    #[serial]
    fn favorite_model_helpers_round_trip_through_config_file() {
        let home = make_test_home("favorite-models");
        let cfg = home.join(".synaps-cli/config");
        std::fs::write(&cfg, "model = claude-opus-4-7\n").unwrap();

        with_home(&home, || {
            add_favorite_model("groq/llama-3.3-70b-versatile").unwrap();
            add_favorite_model("claude/claude-opus-4-7").unwrap();
            add_favorite_model("groq/llama-3.3-70b-versatile").unwrap();
            assert!(is_favorite_model("groq/llama-3.3-70b-versatile"));
            remove_favorite_model("groq/llama-3.3-70b-versatile").unwrap();
            assert!(!is_favorite_model("groq/llama-3.3-70b-versatile"));
            assert!(is_favorite_model("claude/claude-opus-4-7"));
        });

        let contents = std::fs::read_to_string(&cfg).unwrap();
        assert!(contents.contains("model = claude-opus-4-7"));
        assert!(contents.contains("favorite_models = claude/claude-opus-4-7"));
        let _ = std::fs::remove_dir_all(&home);
    }

    #[test]
    #[serial]
    fn test_load_config_new_keys() {
        // Create a temporary config directory with the new keys
        let test_dir = std::path::PathBuf::from("/tmp/synaps-config-test-new-keys/.synaps-cli");
        let _ = std::fs::create_dir_all(&test_dir);
        let config_path = test_dir.join("config");

        let config_content = r#"
# Test config with new keys
model = claude-haiku
thinking = medium
max_tool_output = 50000
bash_timeout = 45
bash_max_timeout = 600
subagent_timeout = 120
api_retries = 5
"#;
        std::fs::write(&config_path, config_content).unwrap();

        // Temporarily override the config path for this test
        let original_home = std::env::var("HOME").ok();
        std::env::set_var("HOME", "/tmp/synaps-config-test-new-keys");

        let config = load_config();

        // Restore original HOME
        if let Some(home) = original_home {
            std::env::set_var("HOME", home);
        } else {
            std::env::remove_var("HOME");
        }

        // Cleanup
        let _ = std::fs::remove_dir_all("/tmp/synaps-config-test-new-keys");

        assert_eq!(config.model, Some("claude-haiku".to_string()));
        assert_eq!(config.thinking_budget, Some(4096)); // medium = 4096
        assert_eq!(config.max_tool_output, 50000);
        assert_eq!(config.bash_timeout, 45);
        assert_eq!(config.bash_max_timeout, 600);
        assert_eq!(config.subagent_timeout, 120);
        assert_eq!(config.api_retries, 5);
    }

    // ── auth.* config + credential source (#157) ──

    // ── events.auto_turn parser ──────────────────────────────────────────────

    #[test]
    fn events_auto_turn_explicit_true_values() {
        for val in &["true", "TRUE", "1", "yes", "YES", "on", "ON"] {
            let cfg = load_config_from_str(&format!("events.auto_turn = {val}"));
            assert!(
                cfg.events.auto_turn,
                "expected true for events.auto_turn = {val}"
            );
        }
    }

    #[test]
    fn events_auto_turn_explicit_false_values() {
        for val in &["false", "FALSE", "0", "no", "NO", "off", "OFF"] {
            let cfg = load_config_from_str(&format!("events.auto_turn = {val}"));
            assert!(
                !cfg.events.auto_turn,
                "expected false for events.auto_turn = {val}"
            );
        }
    }

    #[test]
    fn events_auto_turn_typo_fails_safe_false() {
        // Unrecognised value should fail safe to false (with a warning on stderr).
        let cfg = load_config_from_str("events.auto_turn = fales");
        assert!(
            !cfg.events.auto_turn,
            "typo 'fales' must fail safe to false"
        );
    }

    // ── events.auto_turn_cap parser ──────────────────────────────────────────

    #[test]
    fn events_auto_turn_cap_default_is_five() {
        let cfg = load_config_from_str("");
        assert_eq!(cfg.events.auto_turn_cap, 5);
        assert_eq!(DEFAULT_AUTO_TURN_CAP, 5);
    }

    #[test]
    fn events_auto_turn_cap_zero_is_unlimited() {
        let cfg = load_config_from_str("events.auto_turn_cap = 0");
        assert_eq!(cfg.events.auto_turn_cap, 0);
    }

    #[test]
    fn events_auto_turn_cap_unlimited_aliases() {
        for val in ["unlimited", "inf", "infinite", "Infinity", "UNLIMITED", " inf "] {
            let cfg = load_config_from_str(&format!("events.auto_turn_cap = {val}"));
            assert_eq!(
                cfg.events.auto_turn_cap, 0,
                "expected 0 for events.auto_turn_cap = {val:?}"
            );
        }
    }

    #[test]
    fn events_auto_turn_cap_explicit_number() {
        let cfg = load_config_from_str("events.auto_turn_cap = 12");
        assert_eq!(cfg.events.auto_turn_cap, 12);
    }

    #[test]
    fn events_auto_turn_cap_garbage_keeps_default() {
        for val in ["banana", "-3", "5.5", "", "true"] {
            let cfg = load_config_from_str(&format!("events.auto_turn_cap = {val}"));
            assert_eq!(
                cfg.events.auto_turn_cap, 5,
                "garbage {val:?} must keep default 5"
            );
        }
    }

    #[test]
    fn events_auto_turn_cap_independent_of_auto_turn() {
        let cfg = load_config_from_str("events.auto_turn = false\nevents.auto_turn_cap = 0");
        assert!(!cfg.events.auto_turn);
        assert_eq!(cfg.events.auto_turn_cap, 0);
    }

    #[test]
    fn events_auto_turn_default_is_true() {
        let cfg = load_config_from_str("model = claude-haiku");
        assert!(cfg.events.auto_turn, "default must be true when key absent");
    }

    #[test]
    #[serial]
    fn test_auth_config_parses_endpoint_and_token() {
        let home = std::env::temp_dir().join(format!("synaps-auth-test-{}", std::process::id()));
        let dir = home.join(".synaps-cli");
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(
            dir.join("config"),
            "auth.remote_endpoint = https://jade.jade:8181\nauth.machine_token = machine-abc\n",
        )
        .unwrap();
        with_home(&home, || {
            let config = load_config();
            assert_eq!(
                config.auth.remote_endpoint.as_deref(),
                Some("https://jade.jade:8181")
            );
            assert_eq!(config.auth.machine_token.as_deref(), Some("machine-abc"));
            // auth.* are namespaced -> must NOT warn as unknown keys
            assert!(
                !config.warnings.iter().any(|w| w.contains("auth.")),
                "{:?}",
                config.warnings
            );
        });
        let _ = std::fs::remove_dir_all(&home);
    }

    #[test]
    #[serial]
    fn test_credential_source_local_by_default() {
        std::env::remove_var("SYNAPS_AUTH_ENDPOINT");
        std::env::remove_var("SYNAPS_MACHINE_TOKEN");
        assert!(!AuthConfig::default().credential_source().is_remote());
    }

    #[test]
    #[serial]
    fn test_credential_source_remote_from_config() {
        std::env::remove_var("SYNAPS_AUTH_ENDPOINT");
        std::env::remove_var("SYNAPS_MACHINE_TOKEN");
        let auth = AuthConfig {
            remote_endpoint: Some("https://b".into()),
            machine_token: Some("m".into()),
        };
        assert_eq!(
            auth.credential_source(),
            crate::core::auth::CredentialSource::Remote {
                endpoint: "https://b".into(),
                machine_token: "m".into()
            }
        );
    }

    #[test]
    #[serial]
    fn test_credential_source_env_overrides_config() {
        let auth = AuthConfig {
            remote_endpoint: Some("https://config-host".into()),
            machine_token: Some("config-tok".into()),
        };
        std::env::set_var("SYNAPS_AUTH_ENDPOINT", "https://env-host");
        std::env::set_var("SYNAPS_MACHINE_TOKEN", "env-tok");
        let src = auth.credential_source();
        std::env::remove_var("SYNAPS_AUTH_ENDPOINT");
        std::env::remove_var("SYNAPS_MACHINE_TOKEN");
        assert_eq!(
            src,
            crate::core::auth::CredentialSource::Remote {
                endpoint: "https://env-host".into(),
                machine_token: "env-tok".into()
            }
        );
    }
    #[test]
    fn config_parses_ultracode_as_distinct_canonical_level() {
        let cfg = load_config_from_str("thinking = ultracode\n");
        assert_eq!(
            cfg.thinking_level,
            Some(crate::reasoning::ReasoningLevel::UltraCode)
        );
        assert_eq!(cfg.thinking_budget, None);
        for other in [
            crate::reasoning::ReasoningLevel::Ultra,
            crate::reasoning::ReasoningLevel::Max,
            crate::reasoning::ReasoningLevel::XHigh,
        ] {
            assert_ne!(cfg.thinking_level, Some(other));
        }
    }
}